PuttyIntf.cpp 49 KB

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