PuttyIntf.cpp 45 KB

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