PuttyIntf.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #define PUTTY_DO_GLOBALS
  5. #include "PuttyIntf.h"
  6. #include "Interface.h"
  7. #include "SecureShell.h"
  8. #include "Exceptions.h"
  9. #include "CoreMain.h"
  10. #include "TextsCore.h"
  11. #include <StrUtils.hpp>
  12. #include <Soap.EncdDecd.hpp>
  13. //---------------------------------------------------------------------------
  14. char sshver[50];
  15. extern const char commitid[] = "";
  16. const bool platform_uses_x11_unix_by_default = true;
  17. CRITICAL_SECTION putty_section;
  18. bool SaveRandomSeed;
  19. char appname_[50];
  20. const char *const appname = appname_;
  21. extern const bool share_can_be_downstream = false;
  22. extern const bool share_can_be_upstream = false;
  23. //---------------------------------------------------------------------------
  24. extern "C"
  25. {
  26. #include <winstuff.h>
  27. }
  28. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  29. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  30. const UnicodeString OriginalPuttyExecutable("putty.exe");
  31. const UnicodeString KittyExecutable("kitty.exe");
  32. const UnicodeString PuttyKeyExt(L"ppk");
  33. //---------------------------------------------------------------------------
  34. void __fastcall PuttyInitialize()
  35. {
  36. SaveRandomSeed = true;
  37. InitializeCriticalSection(&putty_section);
  38. // make sure random generator is initialised, so random_save_seed()
  39. // in destructor can proceed
  40. random_ref();
  41. flags = FLAG_VERBOSE | FLAG_SYNCAGENT; // verbose log
  42. sk_init();
  43. AnsiString VersionString = AnsiString(SshVersionString());
  44. DebugAssert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  45. strcpy(sshver, VersionString.c_str());
  46. AnsiString AppName = AnsiString(AppNameString());
  47. DebugAssert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  48. strcpy(appname_, AppName.c_str());
  49. }
  50. //---------------------------------------------------------------------------
  51. void __fastcall PuttyFinalize()
  52. {
  53. if (SaveRandomSeed)
  54. {
  55. random_save_seed();
  56. }
  57. random_unref();
  58. sk_cleanup();
  59. win_misc_cleanup();
  60. win_secur_cleanup();
  61. ec_cleanup();
  62. DeleteCriticalSection(&putty_section);
  63. }
  64. //---------------------------------------------------------------------------
  65. void __fastcall DontSaveRandomSeed()
  66. {
  67. SaveRandomSeed = false;
  68. }
  69. //---------------------------------------------------------------------------
  70. TSecureShell * GetSecureShell(Plug * plug, bool & pfwd)
  71. {
  72. if (!is_ssh(plug) && !is_pfwd(plug))
  73. {
  74. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  75. // Get SSH/PFwd plug which it wraps.
  76. ProxySocket * AProxySocket = get_proxy_plug_socket(plug);
  77. plug = AProxySocket->plug;
  78. }
  79. pfwd = is_pfwd(plug);
  80. Seat * seat;
  81. if (pfwd)
  82. {
  83. seat = get_pfwd_seat(plug);
  84. }
  85. else
  86. {
  87. seat = get_ssh_seat(plug);
  88. }
  89. DebugAssert(seat != NULL);
  90. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  91. return SecureShell;
  92. }
  93. //---------------------------------------------------------------------------
  94. struct callback_set * get_callback_set(Plug * plug)
  95. {
  96. bool pfwd;
  97. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  98. return SecureShell->GetCallbackSet();
  99. }
  100. //---------------------------------------------------------------------------
  101. struct callback_set * get_seat_callback_set(Seat * seat)
  102. {
  103. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  104. return SecureShell->GetCallbackSet();
  105. }
  106. //---------------------------------------------------------------------------
  107. extern "C" char * do_select(Plug * plug, SOCKET skt, bool startup)
  108. {
  109. bool pfwd;
  110. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  111. if (!pfwd)
  112. {
  113. SecureShell->UpdateSocket(skt, startup);
  114. }
  115. else
  116. {
  117. SecureShell->UpdatePortFwdSocket(skt, startup);
  118. }
  119. return NULL;
  120. }
  121. //---------------------------------------------------------------------------
  122. static size_t output(Seat * seat, bool is_stderr, const void * data, size_t len)
  123. {
  124. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  125. if (static_cast<int>(static_cast<char>(is_stderr)) == -1)
  126. {
  127. SecureShell->CWrite(reinterpret_cast<const char *>(data), len);
  128. }
  129. else if (!is_stderr)
  130. {
  131. SecureShell->FromBackend(reinterpret_cast<const unsigned char *>(data), len);
  132. }
  133. else
  134. {
  135. SecureShell->AddStdError(reinterpret_cast<const char *>(data), len);
  136. }
  137. return 0;
  138. }
  139. //---------------------------------------------------------------------------
  140. static bool eof(Seat *)
  141. {
  142. return false;
  143. }
  144. //---------------------------------------------------------------------------
  145. static int get_userpass_input(Seat * seat, prompts_t * p, bufchain * DebugUsedArg(input))
  146. {
  147. DebugAssert(p != NULL);
  148. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  149. DebugAssert(SecureShell != NULL);
  150. int Result;
  151. TStrings * Prompts = new TStringList();
  152. TStrings * Results = new TStringList();
  153. try
  154. {
  155. UnicodeString Name = UTF8ToString(p->name);
  156. UnicodeString AName = Name;
  157. TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
  158. bool UTF8Prompt = (PromptKind != pkPassphrase);
  159. for (int Index = 0; Index < int(p->n_prompts); Index++)
  160. {
  161. prompt_t * Prompt = p->prompts[Index];
  162. UnicodeString S;
  163. if (UTF8Prompt)
  164. {
  165. S = UTF8ToString(Prompt->prompt);
  166. }
  167. else
  168. {
  169. S = UnicodeString(AnsiString(Prompt->prompt));
  170. }
  171. Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  172. // this fails, when new passwords do not match on change password prompt,
  173. // and putty retries the prompt
  174. DebugAssert(Prompt->resultsize == 0);
  175. Results->Add(L"");
  176. }
  177. UnicodeString Instructions = UTF8ToString(p->instruction);
  178. if (SecureShell->PromptUser(p->to_server, Name, p->name_reqd,
  179. Instructions, p->instr_reqd, Prompts, Results))
  180. {
  181. for (int Index = 0; Index < int(p->n_prompts); Index++)
  182. {
  183. prompt_t * Prompt = p->prompts[Index];
  184. RawByteString S;
  185. if (UTF8Prompt)
  186. {
  187. S = RawByteString(UTF8String(Results->Strings[Index]));
  188. }
  189. else
  190. {
  191. S = RawByteString(AnsiString(Results->Strings[Index]));
  192. }
  193. prompt_set_result(Prompt, S.c_str());
  194. }
  195. Result = 1;
  196. }
  197. else
  198. {
  199. Result = 0;
  200. }
  201. }
  202. __finally
  203. {
  204. delete Prompts;
  205. delete Results;
  206. }
  207. return Result;
  208. }
  209. //---------------------------------------------------------------------------
  210. static void connection_fatal(Seat * seat, const char * message)
  211. {
  212. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  213. SecureShell->PuttyFatalError(UnicodeString(AnsiString(message)));
  214. }
  215. //---------------------------------------------------------------------------
  216. int verify_ssh_host_key(Seat * seat, const char * host, int port, const char * keytype,
  217. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  218. void * /*ctx*/)
  219. {
  220. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  221. SecureShell->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  222. // We should return 0 when key was not confirmed, we throw exception instead.
  223. return 1;
  224. }
  225. //---------------------------------------------------------------------------
  226. bool have_ssh_host_key(Seat * seat, const char * hostname, int port,
  227. const char * keytype)
  228. {
  229. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  230. return SecureShell->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  231. }
  232. //---------------------------------------------------------------------------
  233. int confirm_weak_crypto_primitive(Seat * seat, const char * algtype, const char * algname,
  234. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  235. {
  236. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  237. SecureShell->AskAlg(algtype, algname);
  238. // We should return 0 when alg was not confirmed, we throw exception instead.
  239. return 1;
  240. }
  241. //---------------------------------------------------------------------------
  242. int confirm_weak_cached_hostkey(Seat *, const char * /*algname*/, const char * /*betteralgs*/,
  243. void (*/*callback*/)(void *ctx, int result), void * /*ctx*/)
  244. {
  245. return 1;
  246. }
  247. //---------------------------------------------------------------------------
  248. void old_keyfile_warning(void)
  249. {
  250. // no reference to TSecureShell instance available
  251. }
  252. //---------------------------------------------------------------------------
  253. void display_banner(Seat * seat, const char * banner, int size)
  254. {
  255. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  256. UnicodeString Banner(UTF8String(banner, size));
  257. SecureShell->DisplayBanner(Banner);
  258. }
  259. //---------------------------------------------------------------------------
  260. static void SSHFatalError(const char * Format, va_list Param)
  261. {
  262. char Buf[200];
  263. vsnprintf(Buf, LENOF(Buf), Format, Param);
  264. Buf[LENOF(Buf) - 1] = '\0';
  265. // Only few calls from putty\winnet.c might be connected with specific
  266. // TSecureShell. Otherwise called only for really fatal errors
  267. // like 'out of memory' from putty\ssh.c.
  268. throw ESshFatal(NULL, Buf);
  269. }
  270. //---------------------------------------------------------------------------
  271. void modalfatalbox(const char * fmt, ...)
  272. {
  273. va_list Param;
  274. va_start(Param, fmt);
  275. SSHFatalError(fmt, Param);
  276. va_end(Param);
  277. }
  278. //---------------------------------------------------------------------------
  279. void nonfatal(const char * fmt, ...)
  280. {
  281. va_list Param;
  282. va_start(Param, fmt);
  283. SSHFatalError(fmt, Param);
  284. va_end(Param);
  285. }
  286. //---------------------------------------------------------------------------
  287. void ldisc_echoedit_update(Ldisc * /*handle*/)
  288. {
  289. DebugFail();
  290. }
  291. //---------------------------------------------------------------------------
  292. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  293. {
  294. return ticks + GetTickCount();
  295. }
  296. //---------------------------------------------------------------------------
  297. void expire_timer_context(void * /*ctx*/)
  298. {
  299. // nothing
  300. }
  301. //---------------------------------------------------------------------------
  302. Pinger * pinger_new(Conf * /*conf*/, Backend * /*back*/)
  303. {
  304. return NULL;
  305. }
  306. //---------------------------------------------------------------------------
  307. void pinger_reconfig(Pinger * /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  308. {
  309. // nothing
  310. }
  311. //---------------------------------------------------------------------------
  312. void pinger_free(Pinger * /*pinger*/)
  313. {
  314. // nothing
  315. }
  316. //---------------------------------------------------------------------------
  317. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  318. {
  319. // nothing, therefore no auth.
  320. }
  321. //---------------------------------------------------------------------------
  322. // Based on PuTTY's settings.c
  323. char * get_remote_username(Conf * conf)
  324. {
  325. char * username = conf_get_str(conf, CONF_username);
  326. char * result;
  327. if (*username)
  328. {
  329. result = dupstr(username);
  330. }
  331. else
  332. {
  333. result = NULL;
  334. }
  335. return result;
  336. }
  337. //---------------------------------------------------------------------------
  338. static const SeatVtable ScpSeatVtable =
  339. {
  340. output,
  341. eof,
  342. get_userpass_input,
  343. nullseat_notify_remote_exit,
  344. connection_fatal,
  345. nullseat_update_specials_menu,
  346. nullseat_get_ttymode,
  347. nullseat_set_busy_status,
  348. verify_ssh_host_key,
  349. confirm_weak_crypto_primitive,
  350. confirm_weak_cached_hostkey,
  351. nullseat_is_always_utf8,
  352. nullseat_echoedit_update,
  353. nullseat_get_x_display,
  354. nullseat_get_windowid,
  355. nullseat_get_window_pixel_size,
  356. nullseat_stripctrl_new,
  357. nullseat_set_trust_status_vacuously
  358. };
  359. //---------------------------------------------------------------------------
  360. ScpSeat::ScpSeat(TSecureShell * ASecureShell)
  361. {
  362. SecureShell = ASecureShell;
  363. vt = &ScpSeatVtable;
  364. }
  365. //---------------------------------------------------------------------------
  366. static std::unique_ptr<TCriticalSection> PuttyRegistrySection(TraceInitPtr(new TCriticalSection()));
  367. enum TPuttyRegistryMode { prmPass, prmRedirect, prmCollect, prmFail };
  368. static TPuttyRegistryMode PuttyRegistryMode = prmRedirect;
  369. typedef std::map<UnicodeString, unsigned long> TPuttyRegistryTypes;
  370. TPuttyRegistryTypes PuttyRegistryTypes;
  371. //---------------------------------------------------------------------------
  372. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  373. {
  374. long R;
  375. DebugAssert(Configuration != NULL);
  376. DebugAssert(Key == HKEY_CURRENT_USER);
  377. DebugUsedParam(Key);
  378. UnicodeString RegKey = SubKey;
  379. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  380. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  381. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  382. if (!RegKey.IsEmpty())
  383. {
  384. DebugAssert(RegKey[1] == L'\\');
  385. RegKey.Delete(1, 1);
  386. }
  387. if (RegKey.IsEmpty())
  388. {
  389. *Result = static_cast<HKEY>(NULL);
  390. R = ERROR_SUCCESS;
  391. }
  392. else
  393. {
  394. // we expect this to be called only from verify_host_key() or store_host_key()
  395. DebugAssert(RegKey == L"SshHostKeys");
  396. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  397. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  398. if (Storage->OpenSubKey(RegKey, CanCreate))
  399. {
  400. *Result = reinterpret_cast<HKEY>(Storage);
  401. R = ERROR_SUCCESS;
  402. }
  403. else
  404. {
  405. delete Storage;
  406. R = ERROR_CANTOPEN;
  407. }
  408. }
  409. return R;
  410. }
  411. //---------------------------------------------------------------------------
  412. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  413. {
  414. if (PuttyRegistryMode == prmPass)
  415. {
  416. return RegOpenKeyA(Key, SubKey, Result);
  417. }
  418. else if (PuttyRegistryMode == prmCollect)
  419. {
  420. *Result = reinterpret_cast<HKEY>(1);
  421. return ERROR_SUCCESS;
  422. }
  423. else if (PuttyRegistryMode == prmFail)
  424. {
  425. return ERROR_CANTOPEN;
  426. }
  427. DebugAssert(PuttyRegistryMode == prmRedirect);
  428. return OpenWinSCPKey(Key, SubKey, Result, false);
  429. }
  430. //---------------------------------------------------------------------------
  431. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  432. {
  433. if (PuttyRegistryMode == prmPass)
  434. {
  435. return RegCreateKeyA(Key, SubKey, Result);
  436. }
  437. else if (PuttyRegistryMode == prmCollect)
  438. {
  439. *Result = reinterpret_cast<HKEY>(1);
  440. return ERROR_SUCCESS;
  441. }
  442. DebugAssert(PuttyRegistryMode == prmRedirect);
  443. return OpenWinSCPKey(Key, SubKey, Result, true);
  444. }
  445. //---------------------------------------------------------------------------
  446. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * Reserved,
  447. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  448. {
  449. if (PuttyRegistryMode == prmPass)
  450. {
  451. return RegQueryValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  452. }
  453. else if (PuttyRegistryMode == prmCollect)
  454. {
  455. return ERROR_READ_FAULT;
  456. }
  457. DebugAssert(PuttyRegistryMode == prmRedirect);
  458. long R;
  459. DebugAssert(Configuration != NULL);
  460. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  461. AnsiString Value;
  462. if (Storage == NULL)
  463. {
  464. if (UnicodeString(ValueName) == L"RandSeedFile")
  465. {
  466. Value = AnsiString(Configuration->RandomSeedFileName);
  467. R = ERROR_SUCCESS;
  468. }
  469. else
  470. {
  471. DebugFail();
  472. R = ERROR_READ_FAULT;
  473. }
  474. }
  475. else
  476. {
  477. if (Storage->ValueExists(ValueName))
  478. {
  479. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  480. R = ERROR_SUCCESS;
  481. }
  482. else
  483. {
  484. R = ERROR_READ_FAULT;
  485. }
  486. }
  487. if (R == ERROR_SUCCESS)
  488. {
  489. DebugAssert(Type != NULL);
  490. *Type = REG_SZ;
  491. char * DataStr = reinterpret_cast<char *>(Data);
  492. strncpy(DataStr, Value.c_str(), *DataSize);
  493. DataStr[*DataSize - 1] = '\0';
  494. *DataSize = strlen(DataStr);
  495. }
  496. return R;
  497. }
  498. //---------------------------------------------------------------------------
  499. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long Reserved,
  500. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  501. {
  502. if (PuttyRegistryMode == prmPass)
  503. {
  504. return RegSetValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  505. }
  506. else if (PuttyRegistryMode == prmCollect)
  507. {
  508. PuttyRegistryTypes[ValueName] = Type;
  509. return ERROR_SUCCESS;
  510. }
  511. DebugAssert(PuttyRegistryMode == prmRedirect);
  512. DebugAssert(Configuration != NULL);
  513. DebugAssert(Type == REG_SZ);
  514. DebugUsedParam(Type);
  515. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  516. DebugAssert(Storage != NULL);
  517. if (Storage != NULL)
  518. {
  519. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  520. Storage->WriteStringRaw(ValueName, Value);
  521. }
  522. return ERROR_SUCCESS;
  523. }
  524. //---------------------------------------------------------------------------
  525. long reg_close_winscp_key(HKEY Key)
  526. {
  527. if (PuttyRegistryMode == prmPass)
  528. {
  529. return RegCloseKey(Key);
  530. }
  531. else if (PuttyRegistryMode == prmCollect)
  532. {
  533. return ERROR_SUCCESS;
  534. }
  535. DebugAssert(PuttyRegistryMode == prmRedirect);
  536. DebugAssert(Configuration != NULL);
  537. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  538. if (Storage != NULL)
  539. {
  540. delete Storage;
  541. }
  542. return ERROR_SUCCESS;
  543. }
  544. //---------------------------------------------------------------------------
  545. TKeyType KeyType(UnicodeString FileName)
  546. {
  547. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  548. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  549. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  550. UTF8String UtfFileName = UTF8String(FileName);
  551. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  552. TKeyType Result = (TKeyType)key_type(KeyFile);
  553. filename_free(KeyFile);
  554. return Result;
  555. }
  556. //---------------------------------------------------------------------------
  557. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  558. {
  559. UTF8String UtfFileName = UTF8String(FileName);
  560. bool Result;
  561. char * CommentStr = NULL;
  562. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  563. try
  564. {
  565. switch (KeyType)
  566. {
  567. case ktSSH2:
  568. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  569. break;
  570. case ktOpenSSHPEM:
  571. case ktOpenSSHNew:
  572. case ktSSHCom:
  573. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  574. break;
  575. default:
  576. DebugFail();
  577. Result = false;
  578. break;
  579. }
  580. }
  581. __finally
  582. {
  583. filename_free(KeyFile);
  584. }
  585. if (CommentStr != NULL)
  586. {
  587. Comment = UnicodeString(AnsiString(CommentStr));
  588. // ktOpenSSH has no comment, PuTTY defaults to file path
  589. if (Comment == FileName)
  590. {
  591. Comment = ExtractFileName(FileName);
  592. }
  593. sfree(CommentStr);
  594. }
  595. return Result;
  596. }
  597. //---------------------------------------------------------------------------
  598. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  599. {
  600. UTF8String UtfFileName = UTF8String(FileName);
  601. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  602. struct ssh2_userkey * Ssh2Key = NULL;
  603. const char * ErrorStr = NULL;
  604. AnsiString AnsiPassphrase = Passphrase;
  605. try
  606. {
  607. switch (KeyType)
  608. {
  609. case ktSSH2:
  610. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  611. break;
  612. case ktOpenSSHPEM:
  613. case ktOpenSSHNew:
  614. case ktSSHCom:
  615. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  616. break;
  617. default:
  618. DebugFail();
  619. break;
  620. }
  621. }
  622. __finally
  623. {
  624. Shred(AnsiPassphrase);
  625. filename_free(KeyFile);
  626. }
  627. if (Ssh2Key == NULL)
  628. {
  629. UnicodeString Error = AnsiString(ErrorStr);
  630. // While theoretically we may get "unable to open key file" and
  631. // so we should check system error code,
  632. // we actully never get here unless we call KeyType previously
  633. // and handle ktUnopenable accordingly.
  634. throw Exception(Error);
  635. }
  636. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  637. {
  638. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  639. }
  640. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  641. }
  642. //---------------------------------------------------------------------------
  643. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  644. {
  645. AnsiString AnsiComment(Comment);
  646. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  647. sfree(Ssh2Key->comment);
  648. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  649. }
  650. //---------------------------------------------------------------------------
  651. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  652. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  653. {
  654. UTF8String UtfFileName = UTF8String(FileName);
  655. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  656. try
  657. {
  658. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  659. AnsiString AnsiPassphrase = Passphrase;
  660. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  661. switch (KeyType)
  662. {
  663. case ktSSH2:
  664. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  665. {
  666. int Error = errno;
  667. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  668. }
  669. break;
  670. default:
  671. DebugFail();
  672. break;
  673. }
  674. }
  675. __finally
  676. {
  677. filename_free(KeyFile);
  678. }
  679. }
  680. //---------------------------------------------------------------------------
  681. void FreeKey(TPrivateKey * PrivateKey)
  682. {
  683. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  684. ssh_key_free(Ssh2Key->key);
  685. sfree(Ssh2Key);
  686. }
  687. //---------------------------------------------------------------------------
  688. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  689. {
  690. RawByteString Result;
  691. UTF8String UtfFileName = UTF8String(FileName);
  692. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  693. try
  694. {
  695. char * AlgorithmStr = NULL;
  696. char * CommentStr = NULL;
  697. const char * ErrorStr = NULL;
  698. strbuf * PublicKeyBuf = strbuf_new();
  699. if (!ssh2_userkey_loadpub(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  700. {
  701. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  702. throw Exception(Error);
  703. }
  704. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  705. sfree(AlgorithmStr);
  706. Comment = UnicodeString(AnsiString(CommentStr));
  707. sfree(CommentStr);
  708. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  709. strbuf_free(PublicKeyBuf);
  710. }
  711. __finally
  712. {
  713. filename_free(KeyFile);
  714. }
  715. return Result;
  716. }
  717. //---------------------------------------------------------------------------
  718. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  719. {
  720. UnicodeString Algorithm;
  721. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  722. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  723. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  724. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  725. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  726. return Result;
  727. }
  728. //---------------------------------------------------------------------------
  729. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  730. {
  731. static int has = -1;
  732. if (has < 0)
  733. {
  734. Conf * conf = conf_new();
  735. ssh_gss_liblist * List = NULL;
  736. try
  737. {
  738. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  739. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  740. filename_free(filename);
  741. List = ssh_gss_setup(conf, NULL);
  742. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  743. {
  744. ssh_gss_library * library = &List->libraries[Index];
  745. Ssh_gss_ctx ctx;
  746. memset(&ctx, 0, sizeof(ctx));
  747. has =
  748. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  749. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  750. }
  751. }
  752. __finally
  753. {
  754. ssh_gss_cleanup(List);
  755. conf_free(conf);
  756. }
  757. if (has < 0)
  758. {
  759. has = 0;
  760. }
  761. }
  762. return (has > 0);
  763. }
  764. //---------------------------------------------------------------------------
  765. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName, UnicodeString & KeyType)
  766. {
  767. const int MaxCount = 10;
  768. const ssh_keyalg * SignKeys[MaxCount];
  769. int Count = LENOF(SignKeys);
  770. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  771. // as the names have different number of dashes
  772. get_hostkey_algs(&Count, SignKeys);
  773. for (int Index = 0; Index < Count; Index++)
  774. {
  775. const ssh_keyalg * SignKey = SignKeys[Index];
  776. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  777. if (StartsStr(Name + L" ", Fingerprint))
  778. {
  779. UnicodeString Rest = Fingerprint.SubString(Name.Length() + 2, Fingerprint.Length() - Name.Length() - 1);
  780. int Space = Rest.Pos(L" ");
  781. // If not a number, it's an invalid input,
  782. // either something completelly wrong, or it can be OpenSSH base64 public key,
  783. // that got here from TPasteKeyHandler::Paste
  784. if (IsNumber(Rest.SubString(1, Space - 1)))
  785. {
  786. KeyName = Name;
  787. Fingerprint = Rest.SubString(Space + 1, Fingerprint.Length() - Space);
  788. Fingerprint = Base64ToUrlSafe(Fingerprint);
  789. Fingerprint = MD5ToUrlSafe(Fingerprint);
  790. KeyType = UnicodeString(SignKey->cache_id);
  791. return;
  792. }
  793. }
  794. else if (StartsStr(Name + NormalizedFingerprintSeparator, Fingerprint))
  795. {
  796. KeyType = UnicodeString(SignKey->cache_id);
  797. KeyName = Name;
  798. Fingerprint.Delete(1, Name.Length() + 1);
  799. return;
  800. }
  801. }
  802. }
  803. //---------------------------------------------------------------------------
  804. void __fastcall NormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName)
  805. {
  806. UnicodeString KeyType;
  807. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  808. }
  809. //---------------------------------------------------------------------------
  810. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  811. {
  812. UnicodeString KeyType;
  813. UnicodeString KeyName; // unused
  814. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  815. return KeyType;
  816. }
  817. //---------------------------------------------------------------------------
  818. UnicodeString __fastcall GetPuTTYVersion()
  819. {
  820. // "Release 0.64"
  821. // "Pre-release 0.65:2015-07-20.95501a1"
  822. // "Development snapshot 2015-12-22.51465fa"
  823. UnicodeString Result = get_putty_version();
  824. // Skip "Release", "Pre-release", "Development snapshot"
  825. int P = Result.LastDelimiter(L" ");
  826. Result.Delete(1, P);
  827. return Result;
  828. }
  829. //---------------------------------------------------------------------------
  830. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  831. {
  832. unsigned char Digest[32];
  833. hash_simple(&ssh_sha256, make_ptrlen(Data, Size), Digest);
  834. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  835. return Result;
  836. }
  837. //---------------------------------------------------------------------------
  838. void __fastcall DllHijackingProtection()
  839. {
  840. dll_hijacking_protection();
  841. }
  842. //---------------------------------------------------------------------------
  843. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  844. {
  845. UTF8String UtfLine = UTF8String(Line);
  846. char * AlgorithmName = NULL;
  847. char * CommentPtr = NULL;
  848. const char * ErrorStr = NULL;
  849. strbuf * PubBlobBuf = strbuf_new();
  850. UnicodeString Result;
  851. if (!openssh_loadpub_line(UtfLine.c_str(), &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  852. {
  853. throw Exception(UnicodeString(ErrorStr));
  854. }
  855. else
  856. {
  857. try
  858. {
  859. Algorithm = find_pubkey_alg(AlgorithmName);
  860. if (Algorithm == NULL)
  861. {
  862. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  863. }
  864. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  865. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  866. if (Key == NULL)
  867. {
  868. throw Exception(L"Invalid public key.");
  869. }
  870. char * FmtKey = Algorithm->cache_str(Key);
  871. Result = UnicodeString(FmtKey);
  872. sfree(FmtKey);
  873. Algorithm->freekey(Key);
  874. }
  875. __finally
  876. {
  877. strbuf_free(PubBlobBuf);
  878. sfree(AlgorithmName);
  879. sfree(CommentPtr);
  880. }
  881. }
  882. return Result;
  883. }
  884. //---------------------------------------------------------------------------
  885. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  886. {
  887. UnicodeString Result;
  888. if (KeyType == ssh_dss.cache_id)
  889. {
  890. Result = L"DSA";
  891. }
  892. else if (KeyType == ssh_rsa.cache_id)
  893. {
  894. Result = L"RSA";
  895. }
  896. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  897. {
  898. Result = L"Ed25519";
  899. }
  900. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  901. {
  902. Result = L"ECDSA/nistp256";
  903. }
  904. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  905. {
  906. Result = L"ECDSA/nistp384";
  907. }
  908. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  909. {
  910. Result = L"ECDSA/nistp521";
  911. }
  912. else
  913. {
  914. DebugFail();
  915. Result = KeyType;
  916. }
  917. return Result;
  918. }
  919. //---------------------------------------------------------------------------
  920. bool IsOpenSSH(const UnicodeString & SshImplementation)
  921. {
  922. return
  923. // e.g. "OpenSSH_5.3"
  924. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  925. // Sun SSH is based on OpenSSH (suffers the same bugs)
  926. (SshImplementation.Pos(L"Sun_SSH") == 1);
  927. }
  928. //---------------------------------------------------------------------------
  929. TStrings * SshCipherList()
  930. {
  931. std::unique_ptr<TStrings> Result(new TStringList());
  932. // Same order as DefaultCipherList
  933. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  934. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  935. {
  936. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  937. {
  938. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->ssh2_id);
  939. Result->Add(Name);
  940. }
  941. }
  942. return Result.release();
  943. }
  944. //---------------------------------------------------------------------------
  945. TStrings * SshKexList()
  946. {
  947. std::unique_ptr<TStrings> Result(new TStringList());
  948. // Same order as DefaultKexList
  949. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  950. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  951. {
  952. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  953. {
  954. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  955. Result->Add(Name);
  956. }
  957. }
  958. return Result.release();
  959. }
  960. //---------------------------------------------------------------------------
  961. TStrings * SshHostKeyList()
  962. {
  963. std::unique_ptr<TStrings> Result(new TStringList());
  964. const int MaxCount = 10;
  965. const ssh_keyalg * SignKeys[MaxCount];
  966. int Count = LENOF(SignKeys);
  967. get_hostkey_algs(&Count, SignKeys);
  968. for (int Index = 0; Index < Count; Index++)
  969. {
  970. const ssh_keyalg * SignKey = SignKeys[Index];
  971. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  972. Result->Add(Name);
  973. }
  974. return Result.release();
  975. }
  976. //---------------------------------------------------------------------------
  977. TStrings * SshMacList()
  978. {
  979. std::unique_ptr<TStrings> Result(new TStringList());
  980. const struct ssh2_macalg ** Macs = NULL;
  981. int Count = 0;
  982. get_macs(&Count, &Macs);
  983. for (int Index = 0; Index < Count; Index++)
  984. {
  985. UnicodeString Name = UnicodeString(Macs[Index]->name);
  986. Result->Add(Name);
  987. }
  988. return Result.release();
  989. }
  990. //---------------------------------------------------------------------------
  991. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  992. {
  993. return UnicodeString(UTF8String(Cipher->vt->text_name));
  994. }
  995. //---------------------------------------------------------------------------
  996. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  997. {
  998. UnicodeString Result;
  999. if (Compressor != NULL)
  1000. {
  1001. Result = UnicodeString(UTF8String(Compressor->vt->name));
  1002. }
  1003. return Result;
  1004. }
  1005. //---------------------------------------------------------------------------
  1006. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  1007. {
  1008. UnicodeString Result;
  1009. if (Decompressor != NULL)
  1010. {
  1011. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  1012. }
  1013. return Result;
  1014. }
  1015. //---------------------------------------------------------------------------
  1016. void WritePuttySettings(THierarchicalStorage * Storage, const UnicodeString & ASettings)
  1017. {
  1018. if (PuttyRegistryTypes.empty())
  1019. {
  1020. TGuard Guard(PuttyRegistrySection.get());
  1021. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1022. PuttyRegistryMode = prmCollect;
  1023. Conf * conf = conf_new();
  1024. try
  1025. {
  1026. do_defaults(NULL, conf);
  1027. save_settings(NULL, conf);
  1028. }
  1029. __finally
  1030. {
  1031. conf_free(conf);
  1032. }
  1033. }
  1034. std::unique_ptr<TStrings> Settings(new TStringList());
  1035. UnicodeString Buf = ASettings;
  1036. UnicodeString Setting;
  1037. while (CutToken(Buf, Setting))
  1038. {
  1039. Settings->Add(Setting);
  1040. }
  1041. for (int Index = 0; Index < Settings->Count; Index++)
  1042. {
  1043. UnicodeString Name = Settings->Names[Index];
  1044. TPuttyRegistryTypes::const_iterator IType = PuttyRegistryTypes.find(Name);
  1045. if (IType != PuttyRegistryTypes.end())
  1046. {
  1047. UnicodeString Value = Settings->ValueFromIndex[Index];
  1048. int I;
  1049. if (IType->second == REG_SZ)
  1050. {
  1051. Storage->WriteStringRaw(Name, Value);
  1052. }
  1053. else if (DebugAlwaysTrue(IType->second == REG_DWORD) &&
  1054. TryStrToInt(Value, I))
  1055. {
  1056. Storage->WriteInteger(Name, I);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. //---------------------------------------------------------------------------
  1062. void PuttyDefaults(Conf * conf)
  1063. {
  1064. TGuard Guard(PuttyRegistrySection.get());
  1065. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1066. PuttyRegistryMode = prmFail;
  1067. do_defaults(NULL, conf);
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void SavePuttyDefaults(const UnicodeString & Name)
  1071. {
  1072. TGuard Guard(PuttyRegistrySection.get());
  1073. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1074. PuttyRegistryMode = prmPass;
  1075. Conf * conf = conf_new();
  1076. try
  1077. {
  1078. PuttyDefaults(conf);
  1079. AnsiString PuttyName = PuttyStr(Name);
  1080. save_settings(PuttyName.c_str(), conf);
  1081. }
  1082. __finally
  1083. {
  1084. conf_free(conf);
  1085. }
  1086. }
  1087. //---------------------------------------------------------------------------
  1088. //---------------------------------------------------------------------------