PuttyIntf.cpp 36 KB

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