PuttyIntf.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562
  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. void __fastcall DllHijackingProtection()
  1097. {
  1098. dll_hijacking_protection();
  1099. }
  1100. //---------------------------------------------------------------------------
  1101. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  1102. {
  1103. UTF8String UtfLine = UTF8String(Line);
  1104. char * AlgorithmName = NULL;
  1105. char * CommentPtr = NULL;
  1106. const char * ErrorStr = NULL;
  1107. strbuf * PubBlobBuf = strbuf_new();
  1108. BinarySource Source[1];
  1109. BinarySource_BARE_INIT(Source, UtfLine.c_str(), UtfLine.Length());
  1110. UnicodeString Result;
  1111. if (!openssh_loadpub(Source, &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  1112. {
  1113. throw Exception(UnicodeString(ErrorStr));
  1114. }
  1115. else
  1116. {
  1117. try
  1118. {
  1119. Algorithm = find_pubkey_alg(AlgorithmName);
  1120. if (Algorithm == NULL)
  1121. {
  1122. throw Exception(FMTLOAD(PUB_KEY_UNKNOWN, (AlgorithmName)));
  1123. }
  1124. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  1125. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  1126. if (Key == NULL)
  1127. {
  1128. throw Exception(L"Invalid public key.");
  1129. }
  1130. char * FmtKey = Algorithm->cache_str(Key);
  1131. Result = UnicodeString(FmtKey);
  1132. sfree(FmtKey);
  1133. Algorithm->freekey(Key);
  1134. }
  1135. __finally
  1136. {
  1137. strbuf_free(PubBlobBuf);
  1138. sfree(AlgorithmName);
  1139. sfree(CommentPtr);
  1140. }
  1141. }
  1142. return Result;
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. // Based on ca_refresh_pubkey_info
  1146. void ParseCertificatePublicKey(const UnicodeString & Str, RawByteString & PublicKey, UnicodeString & Fingerprint)
  1147. {
  1148. AnsiString AnsiStr = AnsiString(Str);
  1149. ptrlen Data = ptrlen_from_asciz(AnsiStr.c_str());
  1150. strbuf * Blob = strbuf_new();
  1151. try
  1152. {
  1153. // See if we have a plain base64-encoded public key blob.
  1154. if (base64_valid(Data))
  1155. {
  1156. base64_decode_bs(BinarySink_UPCAST(Blob), Data);
  1157. }
  1158. else
  1159. {
  1160. // Otherwise, try to decode as if it was a public key _file_.
  1161. BinarySource Src[1];
  1162. BinarySource_BARE_INIT_PL(Src, Data);
  1163. const char * Error;
  1164. if (!ppk_loadpub_s(Src, NULL, BinarySink_UPCAST(Blob), NULL, &Error))
  1165. {
  1166. throw Exception(FMTLOAD(SSH_HOST_CA_DECODE_ERROR, (Error)));
  1167. }
  1168. }
  1169. ptrlen AlgNamePtrLen = pubkey_blob_to_alg_name(ptrlen_from_strbuf(Blob));
  1170. if (!AlgNamePtrLen.len)
  1171. {
  1172. throw Exception(LoadStr(SSH_HOST_CA_NO_KEY_TYPE));
  1173. }
  1174. UnicodeString AlgName = UnicodeString(AnsiString(static_cast<const char *>(AlgNamePtrLen.ptr), AlgNamePtrLen.len));
  1175. const ssh_keyalg * Alg = find_pubkey_alg_len(AlgNamePtrLen);
  1176. if (Alg == NULL)
  1177. {
  1178. throw Exception(FMTLOAD(PUB_KEY_UNKNOWN, (AlgName)));
  1179. }
  1180. if (Alg->is_certificate)
  1181. {
  1182. throw Exception(FMTLOAD(SSH_HOST_CA_CERTIFICATE, (AlgName)));
  1183. }
  1184. ssh_key * Key = ssh_key_new_pub(Alg, ptrlen_from_strbuf(Blob));
  1185. if (Key == NULL)
  1186. {
  1187. throw Exception(FMTLOAD(SSH_HOST_CA_INVALID, (AlgName)));
  1188. }
  1189. char * FingerprintPtr = ssh2_fingerprint(Key, SSH_FPTYPE_DEFAULT);
  1190. Fingerprint = UnicodeString(FingerprintPtr);
  1191. sfree(FingerprintPtr);
  1192. ssh_key_free(Key);
  1193. PublicKey = StrBufToString(Blob);
  1194. }
  1195. __finally
  1196. {
  1197. strbuf_free(Blob);
  1198. }
  1199. }
  1200. //---------------------------------------------------------------------------
  1201. bool IsCertificateValidityExpressionValid(
  1202. const UnicodeString & Str, UnicodeString & Error, int & ErrorStart, int & ErrorLen)
  1203. {
  1204. char * ErrorMsg;
  1205. ptrlen ErrorLoc;
  1206. AnsiString StrAnsi(Str);
  1207. const char * StrPtr = StrAnsi.c_str();
  1208. bool Result = cert_expr_valid(StrPtr, &ErrorMsg, &ErrorLoc);
  1209. if (!Result)
  1210. {
  1211. Error = UnicodeString(ErrorMsg);
  1212. sfree(ErrorMsg);
  1213. ErrorStart = static_cast<const char *>(ErrorLoc.ptr) - StrPtr;
  1214. ErrorLen = ErrorLoc.len;
  1215. }
  1216. return Result;
  1217. }
  1218. //---------------------------------------------------------------------------
  1219. bool IsOpenSSH(const UnicodeString & SshImplementation)
  1220. {
  1221. return
  1222. // e.g. "OpenSSH_5.3"
  1223. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  1224. // Sun SSH is based on OpenSSH (suffers the same bugs)
  1225. (SshImplementation.Pos(L"Sun_SSH") == 1);
  1226. }
  1227. //---------------------------------------------------------------------------
  1228. // Same order as DefaultCipherList
  1229. struct TCipherGroup
  1230. {
  1231. int CipherGroup;
  1232. const ssh2_ciphers * Cipher;
  1233. };
  1234. TCipherGroup Ciphers[] =
  1235. {
  1236. { CIPHER_AES, &ssh2_aes },
  1237. { CIPHER_CHACHA20, &ssh2_ccp },
  1238. { CIPHER_AESGCM, &ssh2_aesgcm },
  1239. { CIPHER_3DES, &ssh2_3des },
  1240. { CIPHER_DES, &ssh2_des },
  1241. { CIPHER_BLOWFISH, &ssh2_blowfish },
  1242. { CIPHER_ARCFOUR, &ssh2_arcfour },
  1243. };
  1244. //---------------------------------------------------------------------------
  1245. TStrings * SshCipherList()
  1246. {
  1247. std::unique_ptr<TStrings> Result(new TStringList());
  1248. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  1249. {
  1250. const ssh2_ciphers * Cipher = Ciphers[Index].Cipher;
  1251. for (int Index2 = 0; Index2 < Cipher->nciphers; Index2++)
  1252. {
  1253. UnicodeString Name = UnicodeString(Cipher->list[Index2]->ssh2_id);
  1254. Result->Add(Name);
  1255. }
  1256. }
  1257. return Result.release();
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. int GetCipherGroup(const ssh_cipher * TheCipher)
  1261. {
  1262. DebugAssert(strlen(TheCipher->vt->ssh2_id) > 0);
  1263. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  1264. {
  1265. TCipherGroup & CipherGroup = Ciphers[Index];
  1266. const ssh2_ciphers * Cipher = CipherGroup.Cipher;
  1267. for (int Index2 = 0; Index2 < Cipher->nciphers; Index2++)
  1268. {
  1269. if (strcmp(TheCipher->vt->ssh2_id, Cipher->list[Index2]->ssh2_id) == 0)
  1270. {
  1271. return CipherGroup.CipherGroup;
  1272. }
  1273. }
  1274. }
  1275. DebugFail();
  1276. return -1;
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. TStrings * SshKexList()
  1280. {
  1281. std::unique_ptr<TStrings> Result(new TStringList());
  1282. // Same order as DefaultKexList
  1283. const ssh_kexes * Kexes[] = {
  1284. &ssh_gssk5_ecdh_kex, &ssh_gssk5_sha2_kex, &ssh_gssk5_sha1_kex,
  1285. &ssh_ntru_hybrid_kex, &ssh_ecdh_kex, &ssh_diffiehellman_gex,
  1286. &ssh_diffiehellman_group18, &ssh_diffiehellman_group17, &ssh_diffiehellman_group16, &ssh_diffiehellman_group15, &ssh_diffiehellman_group14,
  1287. &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  1288. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  1289. {
  1290. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  1291. {
  1292. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  1293. Result->Add(Name);
  1294. }
  1295. }
  1296. return Result.release();
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. int HostKeyToPutty(THostKey HostKey)
  1300. {
  1301. int Result;
  1302. switch (HostKey)
  1303. {
  1304. case hkWarn: Result = HK_WARN; break;
  1305. case hkRSA: Result = HK_RSA; break;
  1306. case hkDSA: Result = hkDSA; break;
  1307. case hkECDSA: Result = HK_ECDSA; break;
  1308. case hkED25519: Result = HK_ED25519; break;
  1309. case hkED448: Result = HK_ED448; break;
  1310. default: Result = -1; DebugFail();
  1311. }
  1312. return Result;
  1313. }
  1314. //---------------------------------------------------------------------------
  1315. TStrings * SshHostKeyList()
  1316. {
  1317. std::unique_ptr<TStrings> Result(new TStringList());
  1318. for (int DefaultIndex = 0; DefaultIndex < HOSTKEY_COUNT; DefaultIndex++)
  1319. {
  1320. int Type = HostKeyToPutty(DefaultHostKeyList[DefaultIndex]);
  1321. cp_ssh_keyalg * SignKeys;
  1322. int Count;
  1323. get_hostkey_algs(Type, &Count, &SignKeys);
  1324. try
  1325. {
  1326. for (int Index = 0; Index < Count; Index++)
  1327. {
  1328. cp_ssh_keyalg SignKey = SignKeys[Index];
  1329. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  1330. Result->Add(Name);
  1331. }
  1332. }
  1333. __finally
  1334. {
  1335. sfree(SignKeys);
  1336. }
  1337. }
  1338. return Result.release();
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. TStrings * SshMacList()
  1342. {
  1343. std::unique_ptr<TStrings> Result(new TStringList());
  1344. const struct ssh2_macalg ** Macs = NULL;
  1345. int Count = 0;
  1346. get_macs(&Count, &Macs);
  1347. for (int Index = 0; Index < Count; Index++)
  1348. {
  1349. UnicodeString Name = UnicodeString(Macs[Index]->name);
  1350. UnicodeString S = Name;
  1351. UnicodeString ETMName = UnicodeString(Macs[Index]->etm_name);
  1352. if (!ETMName.IsEmpty())
  1353. {
  1354. S = FORMAT(L"%s (%s)", (S, ETMName));
  1355. }
  1356. Result->Add(S);
  1357. }
  1358. return Result.release();
  1359. }
  1360. //---------------------------------------------------------------------------
  1361. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  1362. {
  1363. return UnicodeString(UTF8String(Cipher->vt->text_name));
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  1367. {
  1368. UnicodeString Result;
  1369. if (Compressor != NULL)
  1370. {
  1371. Result = UnicodeString(UTF8String(Compressor->vt->name));
  1372. }
  1373. return Result;
  1374. }
  1375. //---------------------------------------------------------------------------
  1376. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  1377. {
  1378. UnicodeString Result;
  1379. if (Decompressor != NULL)
  1380. {
  1381. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  1382. }
  1383. return Result;
  1384. }
  1385. //---------------------------------------------------------------------------
  1386. void WritePuttySettings(THierarchicalStorage * Storage, const UnicodeString & ASettings)
  1387. {
  1388. if (PuttyRegistryTypes.empty())
  1389. {
  1390. TGuard Guard(PuttyRegistrySection.get());
  1391. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1392. PuttyRegistryMode = prmCollect;
  1393. Conf * conf = conf_new();
  1394. try
  1395. {
  1396. do_defaults(NULL, conf);
  1397. save_settings(NULL, conf);
  1398. }
  1399. __finally
  1400. {
  1401. conf_free(conf);
  1402. }
  1403. }
  1404. std::unique_ptr<TStrings> Settings(new TStringList());
  1405. UnicodeString Buf = ASettings;
  1406. UnicodeString Setting;
  1407. while (CutToken(Buf, Setting))
  1408. {
  1409. Settings->Add(Setting);
  1410. }
  1411. for (int Index = 0; Index < Settings->Count; Index++)
  1412. {
  1413. UnicodeString Name = Settings->Names[Index];
  1414. TPuttyRegistryTypes::const_iterator IType = PuttyRegistryTypes.find(Name);
  1415. if (IType != PuttyRegistryTypes.end())
  1416. {
  1417. UnicodeString Value = Settings->ValueFromIndex[Index];
  1418. int I;
  1419. if (IType->second == REG_SZ)
  1420. {
  1421. Storage->WriteStringRaw(Name, Value);
  1422. }
  1423. else if (DebugAlwaysTrue(IType->second == REG_DWORD) &&
  1424. TryStrToInt(Value, I))
  1425. {
  1426. Storage->WriteInteger(Name, I);
  1427. }
  1428. }
  1429. }
  1430. }
  1431. //---------------------------------------------------------------------------
  1432. void PuttyDefaults(Conf * conf)
  1433. {
  1434. TGuard Guard(PuttyRegistrySection.get());
  1435. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1436. PuttyRegistryMode = prmFail;
  1437. do_defaults(NULL, conf);
  1438. }
  1439. //---------------------------------------------------------------------------
  1440. void SavePuttyDefaults(const UnicodeString & Name)
  1441. {
  1442. TGuard Guard(PuttyRegistrySection.get());
  1443. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1444. PuttyRegistryMode = prmPass;
  1445. Conf * conf = conf_new();
  1446. try
  1447. {
  1448. PuttyDefaults(conf);
  1449. AnsiString PuttyName = PuttyStr(Name);
  1450. save_settings(PuttyName.c_str(), conf);
  1451. }
  1452. __finally
  1453. {
  1454. conf_free(conf);
  1455. }
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. struct host_ca_enum
  1459. {
  1460. int Index;
  1461. };
  1462. //---------------------------------------------------------------------------
  1463. host_ca_enum * enum_host_ca_start()
  1464. {
  1465. Configuration->RefreshPuttySshHostCAList();
  1466. host_ca_enum * Result = new host_ca_enum();
  1467. Result->Index = 0;
  1468. return Result;
  1469. }
  1470. //---------------------------------------------------------------------------
  1471. bool enum_host_ca_next(host_ca_enum * Enum, strbuf * StrBuf)
  1472. {
  1473. const TSshHostCAList * SshHostCAList = Configuration->ActiveSshHostCAList;
  1474. bool Result = (Enum->Index < SshHostCAList->GetCount());
  1475. if (Result)
  1476. {
  1477. put_asciz(StrBuf, UTF8String(SshHostCAList->Get(Enum->Index)->Name).c_str());
  1478. Enum->Index++;
  1479. }
  1480. return Result;
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. void enum_host_ca_finish(host_ca_enum * Enum)
  1484. {
  1485. delete Enum;
  1486. }
  1487. //---------------------------------------------------------------------------
  1488. host_ca * host_ca_load(const char * NameStr)
  1489. {
  1490. host_ca * Result = NULL;
  1491. UnicodeString Name = UTF8String(NameStr);
  1492. const TSshHostCA * SshHostCA = Configuration->ActiveSshHostCAList->Find(Name);
  1493. if (DebugAlwaysTrue(SshHostCA != NULL))
  1494. {
  1495. Result = host_ca_new();
  1496. Result->name = dupstr(NameStr);
  1497. Result->ca_public_key = strbuf_dup(make_ptrlen(SshHostCA->PublicKey.c_str(), SshHostCA->PublicKey.Length()));
  1498. Result->validity_expression = dupstr(UTF8String(SshHostCA->ValidityExpression).c_str());
  1499. Result->opts.permit_rsa_sha1 = SshHostCA->PermitRsaSha1;
  1500. Result->opts.permit_rsa_sha256 = SshHostCA->PermitRsaSha256;
  1501. Result->opts.permit_rsa_sha512 = SshHostCA->PermitRsaSha512;
  1502. }
  1503. return Result;
  1504. }
  1505. //---------------------------------------------------------------------------
  1506. //---------------------------------------------------------------------------