PuttyIntf.cpp 48 KB

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