PuttyIntf.cpp 50 KB

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