PuttyIntf.cpp 50 KB

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