PuttyIntf.cpp 50 KB

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