PuttyIntf.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  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, const char * DebugUsedArg(keydisp), char ** key_fingerprints, bool DebugUsedArg(mismatch),
  247. void (*DebugUsedArg(callback))(void *ctx, SeatPromptResult result), void * DebugUsedArg(ctx))
  248. {
  249. UnicodeString FingerprintSHA256, FingerprintMD5;
  250. if (key_fingerprints[SSH_FPTYPE_SHA256] != NULL)
  251. {
  252. FingerprintSHA256 = key_fingerprints[SSH_FPTYPE_SHA256];
  253. }
  254. if (DebugAlwaysTrue(key_fingerprints[SSH_FPTYPE_MD5] != NULL))
  255. {
  256. FingerprintMD5 = key_fingerprints[SSH_FPTYPE_MD5];
  257. }
  258. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  259. SecureShell->VerifyHostKey(host, port, keytype, keystr, FingerprintSHA256, FingerprintMD5);
  260. // We should return 0 when key was not confirmed, we throw exception instead.
  261. return SPR_OK;
  262. }
  263. //---------------------------------------------------------------------------
  264. bool have_ssh_host_key(Seat * seat, const char * hostname, int port,
  265. const char * keytype)
  266. {
  267. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  268. return SecureShell->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  269. }
  270. //---------------------------------------------------------------------------
  271. SeatPromptResult confirm_weak_crypto_primitive(Seat * seat, const char * algtype, const char * algname,
  272. void (*/*callback*/)(void * ctx, SeatPromptResult result), void * /*ctx*/)
  273. {
  274. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  275. SecureShell->AskAlg(algtype, algname);
  276. // We should return 0 when alg was not confirmed, we throw exception instead.
  277. return SPR_OK;
  278. }
  279. //---------------------------------------------------------------------------
  280. SeatPromptResult confirm_weak_cached_hostkey(Seat *, const char * /*algname*/, const char * /*betteralgs*/,
  281. void (*/*callback*/)(void *ctx, SeatPromptResult result), void * /*ctx*/)
  282. {
  283. return SPR_OK;
  284. }
  285. //---------------------------------------------------------------------------
  286. void old_keyfile_warning(void)
  287. {
  288. // no reference to TSecureShell instance available
  289. }
  290. //---------------------------------------------------------------------------
  291. size_t banner(Seat * seat, const void * data, size_t len)
  292. {
  293. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  294. UnicodeString Banner(UTF8String(static_cast<const char *>(data), len));
  295. SecureShell->DisplayBanner(Banner);
  296. return 0; // PuTTY never uses the value
  297. }
  298. //---------------------------------------------------------------------------
  299. uintmax_t strtoumax(const char *nptr, char **endptr, int base)
  300. {
  301. if (DebugAlwaysFalse(endptr != NULL) ||
  302. DebugAlwaysFalse(base != 10))
  303. {
  304. Abort();
  305. }
  306. return StrToInt64(UnicodeString(AnsiString(nptr)));
  307. }
  308. //---------------------------------------------------------------------------
  309. static void SSHFatalError(const char * Format, va_list Param)
  310. {
  311. char Buf[200];
  312. vsnprintf(Buf, LENOF(Buf), Format, Param);
  313. Buf[LENOF(Buf) - 1] = '\0';
  314. // Only few calls from putty\winnet.c might be connected with specific
  315. // TSecureShell. Otherwise called only for really fatal errors
  316. // like 'out of memory' from putty\ssh.c.
  317. throw ESshFatal(NULL, Buf);
  318. }
  319. //---------------------------------------------------------------------------
  320. void modalfatalbox(const char * fmt, ...)
  321. {
  322. va_list Param;
  323. va_start(Param, fmt);
  324. SSHFatalError(fmt, Param);
  325. va_end(Param);
  326. }
  327. //---------------------------------------------------------------------------
  328. void nonfatal(const char * fmt, ...)
  329. {
  330. va_list Param;
  331. va_start(Param, fmt);
  332. SSHFatalError(fmt, Param);
  333. va_end(Param);
  334. }
  335. //---------------------------------------------------------------------------
  336. void ldisc_echoedit_update(Ldisc * /*handle*/)
  337. {
  338. DebugFail();
  339. }
  340. //---------------------------------------------------------------------------
  341. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  342. {
  343. return ticks + GetTickCount();
  344. }
  345. //---------------------------------------------------------------------------
  346. void expire_timer_context(void * /*ctx*/)
  347. {
  348. // nothing
  349. }
  350. //---------------------------------------------------------------------------
  351. Pinger * pinger_new(Conf * /*conf*/, Backend * /*back*/)
  352. {
  353. return NULL;
  354. }
  355. //---------------------------------------------------------------------------
  356. void pinger_reconfig(Pinger * /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  357. {
  358. // nothing
  359. }
  360. //---------------------------------------------------------------------------
  361. void pinger_free(Pinger * /*pinger*/)
  362. {
  363. // nothing
  364. }
  365. //---------------------------------------------------------------------------
  366. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  367. {
  368. // nothing, therefore no auth.
  369. }
  370. //---------------------------------------------------------------------------
  371. // Based on PuTTY's settings.c
  372. char * get_remote_username(Conf * conf)
  373. {
  374. char * username = conf_get_str(conf, CONF_username);
  375. char * result;
  376. if (*username)
  377. {
  378. result = dupstr(username);
  379. }
  380. else
  381. {
  382. result = NULL;
  383. }
  384. return result;
  385. }
  386. //---------------------------------------------------------------------------
  387. static const SeatVtable ScpSeatVtable =
  388. {
  389. output,
  390. eof,
  391. nullseat_sent,
  392. banner,
  393. get_userpass_input,
  394. nullseat_notify_session_started,
  395. nullseat_notify_remote_exit,
  396. nullseat_notify_remote_disconnect,
  397. connection_fatal,
  398. nullseat_update_specials_menu,
  399. nullseat_get_ttymode,
  400. nullseat_set_busy_status,
  401. confirm_ssh_host_key,
  402. confirm_weak_crypto_primitive,
  403. confirm_weak_cached_hostkey,
  404. nullseat_is_always_utf8,
  405. nullseat_echoedit_update,
  406. nullseat_get_x_display,
  407. nullseat_get_windowid,
  408. nullseat_get_window_pixel_size,
  409. nullseat_stripctrl_new,
  410. nullseat_set_trust_status,
  411. nullseat_can_set_trust_status_yes,
  412. nullseat_has_mixed_input_stream_yes,
  413. nullseat_verbose_yes,
  414. nullseat_interactive_no,
  415. nullseat_get_cursor_position,
  416. };
  417. //---------------------------------------------------------------------------
  418. ScpSeat::ScpSeat(TSecureShell * ASecureShell)
  419. {
  420. SecureShell = ASecureShell;
  421. vt = &ScpSeatVtable;
  422. }
  423. //---------------------------------------------------------------------------
  424. static std::unique_ptr<TCriticalSection> PuttyRegistrySection(TraceInitPtr(new TCriticalSection()));
  425. enum TPuttyRegistryMode { prmPass, prmRedirect, prmCollect, prmFail };
  426. static TPuttyRegistryMode PuttyRegistryMode = prmRedirect;
  427. typedef std::map<UnicodeString, unsigned long> TPuttyRegistryTypes;
  428. TPuttyRegistryTypes PuttyRegistryTypes;
  429. //---------------------------------------------------------------------------
  430. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  431. {
  432. long R;
  433. DebugAssert(Key == HKEY_CURRENT_USER);
  434. DebugUsedParam(Key);
  435. UnicodeString RegKey = SubKey;
  436. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  437. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  438. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  439. if (!RegKey.IsEmpty())
  440. {
  441. DebugAssert(RegKey[1] == L'\\');
  442. RegKey.Delete(1, 1);
  443. }
  444. if (RegKey.IsEmpty())
  445. {
  446. *Result = static_cast<HKEY>(NULL);
  447. R = ERROR_SUCCESS;
  448. }
  449. else
  450. {
  451. // we expect this to be called only from retrieve_host_key() or store_host_key()
  452. DebugAssert(RegKey == L"SshHostKeys");
  453. DebugAssert(PuttyStorage != NULL);
  454. DebugAssert(PuttyStorage->AccessMode == (CanCreate ? smReadWrite : smRead));
  455. if (PuttyStorage->OpenSubKey(RegKey, CanCreate))
  456. {
  457. *Result = reinterpret_cast<HKEY>(PuttyStorage);
  458. R = ERROR_SUCCESS;
  459. }
  460. else
  461. {
  462. R = ERROR_CANTOPEN;
  463. }
  464. }
  465. return R;
  466. }
  467. //---------------------------------------------------------------------------
  468. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  469. {
  470. if (PuttyRegistryMode == prmPass)
  471. {
  472. return RegOpenKeyA(Key, SubKey, Result);
  473. }
  474. else if (PuttyRegistryMode == prmCollect)
  475. {
  476. *Result = reinterpret_cast<HKEY>(1);
  477. return ERROR_SUCCESS;
  478. }
  479. else if (PuttyRegistryMode == prmFail)
  480. {
  481. return ERROR_CANTOPEN;
  482. }
  483. DebugAssert(PuttyRegistryMode == prmRedirect);
  484. return OpenWinSCPKey(Key, SubKey, Result, false);
  485. }
  486. //---------------------------------------------------------------------------
  487. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  488. {
  489. if (PuttyRegistryMode == prmPass)
  490. {
  491. return RegCreateKeyA(Key, SubKey, Result);
  492. }
  493. else if (PuttyRegistryMode == prmCollect)
  494. {
  495. *Result = reinterpret_cast<HKEY>(1);
  496. return ERROR_SUCCESS;
  497. }
  498. DebugAssert(PuttyRegistryMode == prmRedirect);
  499. return OpenWinSCPKey(Key, SubKey, Result, true);
  500. }
  501. //---------------------------------------------------------------------------
  502. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * Reserved,
  503. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  504. {
  505. if (PuttyRegistryMode == prmPass)
  506. {
  507. return RegQueryValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  508. }
  509. else if (PuttyRegistryMode == prmCollect)
  510. {
  511. return ERROR_READ_FAULT;
  512. }
  513. DebugAssert(PuttyRegistryMode == prmRedirect);
  514. long R;
  515. DebugAssert(Configuration != NULL);
  516. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  517. AnsiString Value;
  518. if (Storage == NULL)
  519. {
  520. if (UnicodeString(ValueName) == L"RandSeedFile")
  521. {
  522. Value = AnsiString(Configuration->RandomSeedFileName);
  523. R = ERROR_SUCCESS;
  524. }
  525. else
  526. {
  527. DebugFail();
  528. R = ERROR_READ_FAULT;
  529. }
  530. }
  531. else
  532. {
  533. if (Storage->ValueExists(ValueName))
  534. {
  535. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  536. R = ERROR_SUCCESS;
  537. }
  538. else
  539. {
  540. R = ERROR_READ_FAULT;
  541. }
  542. }
  543. if (R == ERROR_SUCCESS)
  544. {
  545. DebugAssert(Type != NULL);
  546. *Type = REG_SZ;
  547. char * DataStr = reinterpret_cast<char *>(Data);
  548. strncpy(DataStr, Value.c_str(), *DataSize);
  549. DataStr[*DataSize - 1] = '\0';
  550. *DataSize = strlen(DataStr);
  551. }
  552. return R;
  553. }
  554. //---------------------------------------------------------------------------
  555. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long Reserved,
  556. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  557. {
  558. if (PuttyRegistryMode == prmPass)
  559. {
  560. return RegSetValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  561. }
  562. else if (PuttyRegistryMode == prmCollect)
  563. {
  564. PuttyRegistryTypes[ValueName] = Type;
  565. return ERROR_SUCCESS;
  566. }
  567. DebugAssert(PuttyRegistryMode == prmRedirect);
  568. DebugAssert(Type == REG_SZ);
  569. DebugUsedParam(Type);
  570. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  571. DebugAssert(Storage != NULL);
  572. if (Storage != NULL)
  573. {
  574. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  575. Storage->WriteStringRaw(ValueName, Value);
  576. }
  577. return ERROR_SUCCESS;
  578. }
  579. //---------------------------------------------------------------------------
  580. long reg_close_winscp_key(HKEY Key)
  581. {
  582. if (PuttyRegistryMode == prmPass)
  583. {
  584. return RegCloseKey(Key);
  585. }
  586. else if (PuttyRegistryMode == prmCollect)
  587. {
  588. return ERROR_SUCCESS;
  589. }
  590. DebugAssert(PuttyRegistryMode == prmRedirect);
  591. return ERROR_SUCCESS;
  592. }
  593. //---------------------------------------------------------------------------
  594. TKeyType KeyType(UnicodeString FileName)
  595. {
  596. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  597. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  598. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  599. UTF8String UtfFileName = UTF8String(FileName);
  600. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  601. TKeyType Result = (TKeyType)key_type(KeyFile);
  602. filename_free(KeyFile);
  603. return Result;
  604. }
  605. //---------------------------------------------------------------------------
  606. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  607. {
  608. UTF8String UtfFileName = UTF8String(FileName);
  609. bool Result;
  610. char * CommentStr = NULL;
  611. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  612. try
  613. {
  614. switch (KeyType)
  615. {
  616. case ktSSH2:
  617. Result = (ppk_encrypted_f(KeyFile, &CommentStr) != 0);
  618. break;
  619. case ktOpenSSHPEM:
  620. case ktOpenSSHNew:
  621. case ktSSHCom:
  622. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  623. break;
  624. default:
  625. DebugFail();
  626. Result = false;
  627. break;
  628. }
  629. }
  630. __finally
  631. {
  632. filename_free(KeyFile);
  633. }
  634. if (CommentStr != NULL)
  635. {
  636. Comment = UnicodeString(AnsiString(CommentStr));
  637. // ktOpenSSH has no comment, PuTTY defaults to file path
  638. if (Comment == FileName)
  639. {
  640. Comment = ExtractFileName(FileName);
  641. }
  642. sfree(CommentStr);
  643. }
  644. return Result;
  645. }
  646. //---------------------------------------------------------------------------
  647. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase, UnicodeString & Error)
  648. {
  649. UTF8String UtfFileName = UTF8String(FileName);
  650. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  651. struct ssh2_userkey * Ssh2Key = NULL;
  652. const char * ErrorStr = NULL;
  653. AnsiString AnsiPassphrase = Passphrase;
  654. try
  655. {
  656. switch (KeyType)
  657. {
  658. case ktSSH2:
  659. Ssh2Key = ppk_load_f(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  660. break;
  661. case ktOpenSSHPEM:
  662. case ktOpenSSHNew:
  663. case ktSSHCom:
  664. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  665. break;
  666. default:
  667. DebugFail();
  668. break;
  669. }
  670. }
  671. __finally
  672. {
  673. Shred(AnsiPassphrase);
  674. filename_free(KeyFile);
  675. }
  676. if (Ssh2Key == NULL)
  677. {
  678. // While theoretically we may get "unable to open key file" and
  679. // so we should check system error code,
  680. // we actully never get here unless we call KeyType previously
  681. // and handle ktUnopenable accordingly.
  682. Error = AnsiString(ErrorStr);
  683. }
  684. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  685. {
  686. Error = EmptyStr;
  687. Ssh2Key = NULL;
  688. }
  689. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  690. }
  691. //---------------------------------------------------------------------------
  692. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  693. {
  694. UnicodeString Error;
  695. TPrivateKey * Result = LoadKey(KeyType, FileName, Passphrase, Error);
  696. if (Result == NULL)
  697. {
  698. if (!Error.IsEmpty())
  699. {
  700. throw Exception(Error);
  701. }
  702. else
  703. {
  704. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  705. }
  706. }
  707. return Result;
  708. }
  709. //---------------------------------------------------------------------------
  710. UnicodeString TestKey(TKeyType KeyType, const UnicodeString & FileName)
  711. {
  712. UnicodeString Result;
  713. TPrivateKey * Key = LoadKey(KeyType, FileName, EmptyStr, Result);
  714. if (Key != NULL)
  715. {
  716. FreeKey(Key);
  717. }
  718. return Result;
  719. }
  720. //---------------------------------------------------------------------------
  721. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  722. {
  723. AnsiString AnsiComment(Comment);
  724. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  725. sfree(Ssh2Key->comment);
  726. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  727. }
  728. //---------------------------------------------------------------------------
  729. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  730. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  731. {
  732. UTF8String UtfFileName = UTF8String(FileName);
  733. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  734. try
  735. {
  736. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  737. AnsiString AnsiPassphrase = Passphrase;
  738. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  739. switch (KeyType)
  740. {
  741. case ktSSH2:
  742. {
  743. ppk_save_parameters Params = ppk_save_default_parameters;
  744. if (Configuration->KeyVersion != 0)
  745. {
  746. Params.fmt_version = Configuration->KeyVersion;
  747. }
  748. if (!ppk_save_f(KeyFile, Ssh2Key, PassphrasePtr, &Params))
  749. {
  750. int Error = errno;
  751. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  752. }
  753. }
  754. break;
  755. default:
  756. DebugFail();
  757. break;
  758. }
  759. }
  760. __finally
  761. {
  762. filename_free(KeyFile);
  763. }
  764. }
  765. //---------------------------------------------------------------------------
  766. void FreeKey(TPrivateKey * PrivateKey)
  767. {
  768. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  769. ssh_key_free(Ssh2Key->key);
  770. sfree(Ssh2Key->comment);
  771. sfree(Ssh2Key);
  772. }
  773. //---------------------------------------------------------------------------
  774. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  775. {
  776. RawByteString Result;
  777. UTF8String UtfFileName = UTF8String(FileName);
  778. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  779. try
  780. {
  781. char * AlgorithmStr = NULL;
  782. char * CommentStr = NULL;
  783. const char * ErrorStr = NULL;
  784. strbuf * PublicKeyBuf = strbuf_new();
  785. if (!ppk_loadpub_f(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  786. {
  787. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  788. throw Exception(Error);
  789. }
  790. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  791. sfree(AlgorithmStr);
  792. Comment = UnicodeString(AnsiString(CommentStr));
  793. sfree(CommentStr);
  794. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  795. strbuf_free(PublicKeyBuf);
  796. }
  797. __finally
  798. {
  799. filename_free(KeyFile);
  800. }
  801. return Result;
  802. }
  803. //---------------------------------------------------------------------------
  804. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  805. {
  806. UnicodeString Algorithm;
  807. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  808. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  809. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  810. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  811. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  812. return Result;
  813. }
  814. //---------------------------------------------------------------------------
  815. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  816. {
  817. static int has = -1;
  818. if (has < 0)
  819. {
  820. Conf * conf = conf_new();
  821. ssh_gss_liblist * List = NULL;
  822. try
  823. {
  824. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  825. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  826. filename_free(filename);
  827. List = ssh_gss_setup(conf, NULL);
  828. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  829. {
  830. ssh_gss_library * library = &List->libraries[Index];
  831. Ssh_gss_ctx ctx;
  832. memset(&ctx, 0, sizeof(ctx));
  833. has =
  834. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  835. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  836. }
  837. }
  838. __finally
  839. {
  840. ssh_gss_cleanup(List);
  841. conf_free(conf);
  842. }
  843. if (has < 0)
  844. {
  845. has = 0;
  846. }
  847. }
  848. return (has > 0);
  849. }
  850. //---------------------------------------------------------------------------
  851. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName, UnicodeString & KeyType)
  852. {
  853. const int MaxCount = 10;
  854. const ssh_keyalg * SignKeys[MaxCount];
  855. int Count = LENOF(SignKeys);
  856. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  857. // as the names have different number of dashes
  858. get_hostkey_algs(&Count, SignKeys);
  859. for (int Index = 0; Index < Count; Index++)
  860. {
  861. const ssh_keyalg * SignKey = SignKeys[Index];
  862. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  863. if (StartsStr(Name + L" ", Fingerprint))
  864. {
  865. UnicodeString Rest = Fingerprint.SubString(Name.Length() + 2, Fingerprint.Length() - Name.Length() - 1);
  866. int Space = Rest.Pos(L" ");
  867. // If not a number, it's an invalid input,
  868. // either something completelly wrong, or it can be OpenSSH base64 public key,
  869. // that got here from TPasteKeyHandler::Paste
  870. if (IsNumber(Rest.SubString(1, Space - 1)))
  871. {
  872. KeyName = Name;
  873. Fingerprint = Rest.SubString(Space + 1, Fingerprint.Length() - Space);
  874. Fingerprint = Base64ToUrlSafe(Fingerprint);
  875. Fingerprint = MD5ToUrlSafe(Fingerprint);
  876. KeyType = UnicodeString(SignKey->cache_id);
  877. return;
  878. }
  879. }
  880. else if (StartsStr(Name + NormalizedFingerprintSeparator, Fingerprint))
  881. {
  882. KeyType = UnicodeString(SignKey->cache_id);
  883. KeyName = Name;
  884. Fingerprint.Delete(1, Name.Length() + 1);
  885. return;
  886. }
  887. }
  888. }
  889. //---------------------------------------------------------------------------
  890. void __fastcall NormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName)
  891. {
  892. UnicodeString KeyType;
  893. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  894. }
  895. //---------------------------------------------------------------------------
  896. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  897. {
  898. UnicodeString KeyType;
  899. UnicodeString KeyName; // unused
  900. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  901. return KeyType;
  902. }
  903. //---------------------------------------------------------------------------
  904. UnicodeString __fastcall GetPuTTYVersion()
  905. {
  906. // "Release 0.64"
  907. // "Pre-release 0.65:2015-07-20.95501a1"
  908. // "Development snapshot 2015-12-22.51465fa"
  909. UnicodeString Result = get_putty_version();
  910. // Skip "Release", "Pre-release", "Development snapshot"
  911. int P = Result.LastDelimiter(L" ");
  912. Result.Delete(1, P);
  913. return Result;
  914. }
  915. //---------------------------------------------------------------------------
  916. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  917. {
  918. unsigned char Digest[32];
  919. hash_simple(&ssh_sha256, make_ptrlen(Data, Size), Digest);
  920. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  921. return Result;
  922. }
  923. //---------------------------------------------------------------------------
  924. void __fastcall DllHijackingProtection()
  925. {
  926. dll_hijacking_protection();
  927. }
  928. //---------------------------------------------------------------------------
  929. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  930. {
  931. UTF8String UtfLine = UTF8String(Line);
  932. char * AlgorithmName = NULL;
  933. char * CommentPtr = NULL;
  934. const char * ErrorStr = NULL;
  935. strbuf * PubBlobBuf = strbuf_new();
  936. BinarySource Source[1];
  937. BinarySource_BARE_INIT(Source, UtfLine.c_str(), UtfLine.Length());
  938. UnicodeString Result;
  939. if (!openssh_loadpub(Source, &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  940. {
  941. throw Exception(UnicodeString(ErrorStr));
  942. }
  943. else
  944. {
  945. try
  946. {
  947. Algorithm = find_pubkey_alg(AlgorithmName);
  948. if (Algorithm == NULL)
  949. {
  950. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  951. }
  952. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  953. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  954. if (Key == NULL)
  955. {
  956. throw Exception(L"Invalid public key.");
  957. }
  958. char * FmtKey = Algorithm->cache_str(Key);
  959. Result = UnicodeString(FmtKey);
  960. sfree(FmtKey);
  961. Algorithm->freekey(Key);
  962. }
  963. __finally
  964. {
  965. strbuf_free(PubBlobBuf);
  966. sfree(AlgorithmName);
  967. sfree(CommentPtr);
  968. }
  969. }
  970. return Result;
  971. }
  972. //---------------------------------------------------------------------------
  973. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  974. {
  975. UnicodeString Result;
  976. if (KeyType == ssh_dsa.cache_id)
  977. {
  978. Result = L"DSA";
  979. }
  980. else if ((KeyType == ssh_rsa.cache_id) ||
  981. (KeyType == L"rsa")) // SSH1
  982. {
  983. Result = L"RSA";
  984. }
  985. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  986. {
  987. Result = L"Ed25519";
  988. }
  989. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  990. {
  991. Result = L"ECDSA/nistp256";
  992. }
  993. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  994. {
  995. Result = L"ECDSA/nistp384";
  996. }
  997. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  998. {
  999. Result = L"ECDSA/nistp521";
  1000. }
  1001. else
  1002. {
  1003. DebugFail();
  1004. Result = KeyType;
  1005. }
  1006. return Result;
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. bool IsOpenSSH(const UnicodeString & SshImplementation)
  1010. {
  1011. return
  1012. // e.g. "OpenSSH_5.3"
  1013. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  1014. // Sun SSH is based on OpenSSH (suffers the same bugs)
  1015. (SshImplementation.Pos(L"Sun_SSH") == 1);
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. TStrings * SshCipherList()
  1019. {
  1020. std::unique_ptr<TStrings> Result(new TStringList());
  1021. // Same order as DefaultCipherList
  1022. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  1023. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  1024. {
  1025. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  1026. {
  1027. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->ssh2_id);
  1028. Result->Add(Name);
  1029. }
  1030. }
  1031. return Result.release();
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. TStrings * SshKexList()
  1035. {
  1036. std::unique_ptr<TStrings> Result(new TStringList());
  1037. // Same order as DefaultKexList
  1038. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  1039. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  1040. {
  1041. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  1042. {
  1043. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  1044. Result->Add(Name);
  1045. }
  1046. }
  1047. return Result.release();
  1048. }
  1049. //---------------------------------------------------------------------------
  1050. TStrings * SshHostKeyList()
  1051. {
  1052. std::unique_ptr<TStrings> Result(new TStringList());
  1053. const int MaxCount = 10;
  1054. const ssh_keyalg * SignKeys[MaxCount];
  1055. int Count = LENOF(SignKeys);
  1056. get_hostkey_algs(&Count, SignKeys);
  1057. for (int Index = 0; Index < Count; Index++)
  1058. {
  1059. const ssh_keyalg * SignKey = SignKeys[Index];
  1060. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  1061. Result->Add(Name);
  1062. }
  1063. return Result.release();
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. TStrings * SshMacList()
  1067. {
  1068. std::unique_ptr<TStrings> Result(new TStringList());
  1069. const struct ssh2_macalg ** Macs = NULL;
  1070. int Count = 0;
  1071. get_macs(&Count, &Macs);
  1072. for (int Index = 0; Index < Count; Index++)
  1073. {
  1074. UnicodeString Name = UnicodeString(Macs[Index]->name);
  1075. UnicodeString S = Name;
  1076. UnicodeString ETMName = UnicodeString(Macs[Index]->etm_name);
  1077. if (!ETMName.IsEmpty())
  1078. {
  1079. S = FORMAT(L"%s (%s)", (S, ETMName));
  1080. }
  1081. Result->Add(S);
  1082. }
  1083. return Result.release();
  1084. }
  1085. //---------------------------------------------------------------------------
  1086. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  1087. {
  1088. return UnicodeString(UTF8String(Cipher->vt->text_name));
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  1092. {
  1093. UnicodeString Result;
  1094. if (Compressor != NULL)
  1095. {
  1096. Result = UnicodeString(UTF8String(Compressor->vt->name));
  1097. }
  1098. return Result;
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  1102. {
  1103. UnicodeString Result;
  1104. if (Decompressor != NULL)
  1105. {
  1106. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  1107. }
  1108. return Result;
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. void WritePuttySettings(THierarchicalStorage * Storage, const UnicodeString & ASettings)
  1112. {
  1113. if (PuttyRegistryTypes.empty())
  1114. {
  1115. TGuard Guard(PuttyRegistrySection.get());
  1116. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1117. PuttyRegistryMode = prmCollect;
  1118. Conf * conf = conf_new();
  1119. try
  1120. {
  1121. do_defaults(NULL, conf);
  1122. save_settings(NULL, conf);
  1123. }
  1124. __finally
  1125. {
  1126. conf_free(conf);
  1127. }
  1128. }
  1129. std::unique_ptr<TStrings> Settings(new TStringList());
  1130. UnicodeString Buf = ASettings;
  1131. UnicodeString Setting;
  1132. while (CutToken(Buf, Setting))
  1133. {
  1134. Settings->Add(Setting);
  1135. }
  1136. for (int Index = 0; Index < Settings->Count; Index++)
  1137. {
  1138. UnicodeString Name = Settings->Names[Index];
  1139. TPuttyRegistryTypes::const_iterator IType = PuttyRegistryTypes.find(Name);
  1140. if (IType != PuttyRegistryTypes.end())
  1141. {
  1142. UnicodeString Value = Settings->ValueFromIndex[Index];
  1143. int I;
  1144. if (IType->second == REG_SZ)
  1145. {
  1146. Storage->WriteStringRaw(Name, Value);
  1147. }
  1148. else if (DebugAlwaysTrue(IType->second == REG_DWORD) &&
  1149. TryStrToInt(Value, I))
  1150. {
  1151. Storage->WriteInteger(Name, I);
  1152. }
  1153. }
  1154. }
  1155. }
  1156. //---------------------------------------------------------------------------
  1157. void PuttyDefaults(Conf * conf)
  1158. {
  1159. TGuard Guard(PuttyRegistrySection.get());
  1160. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1161. PuttyRegistryMode = prmFail;
  1162. do_defaults(NULL, conf);
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. void SavePuttyDefaults(const UnicodeString & Name)
  1166. {
  1167. TGuard Guard(PuttyRegistrySection.get());
  1168. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1169. PuttyRegistryMode = prmPass;
  1170. Conf * conf = conf_new();
  1171. try
  1172. {
  1173. PuttyDefaults(conf);
  1174. AnsiString PuttyName = PuttyStr(Name);
  1175. save_settings(PuttyName.c_str(), conf);
  1176. }
  1177. __finally
  1178. {
  1179. conf_free(conf);
  1180. }
  1181. }
  1182. //---------------------------------------------------------------------------
  1183. //---------------------------------------------------------------------------