1
0

PuttyIntf.cpp 49 KB

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