PuttyIntf.cpp 39 KB

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