PuttyIntf.cpp 50 KB

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