PuttyIntf.cpp 45 KB

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