PuttyIntf.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #define PUTTY_DO_GLOBALS
  5. #include "PuttyIntf.h"
  6. #include "Interface.h"
  7. #include "SecureShell.h"
  8. #include "Exceptions.h"
  9. #include "CoreMain.h"
  10. #include "TextsCore.h"
  11. #include <StrUtils.hpp>
  12. #include <Soap.EncdDecd.hpp>
  13. //---------------------------------------------------------------------------
  14. char sshver[50];
  15. extern const char commitid[] = "";
  16. const int platform_uses_x11_unix_by_default = TRUE;
  17. CRITICAL_SECTION putty_section;
  18. bool SaveRandomSeed;
  19. char appname_[50];
  20. const char *const appname = appname_;
  21. extern const int share_can_be_downstream = FALSE;
  22. extern const int share_can_be_upstream = FALSE;
  23. //---------------------------------------------------------------------------
  24. extern "C"
  25. {
  26. #include <winstuff.h>
  27. }
  28. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  29. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  30. const UnicodeString OriginalPuttyExecutable("putty.exe");
  31. const UnicodeString KittyExecutable("kitty.exe");
  32. const UnicodeString PuttyKeyExt(L"ppk");
  33. //---------------------------------------------------------------------------
  34. void __fastcall PuttyInitialize()
  35. {
  36. SaveRandomSeed = true;
  37. InitializeCriticalSection(&putty_section);
  38. // make sure random generator is initialised, so random_save_seed()
  39. // in destructor can proceed
  40. random_ref();
  41. flags = FLAG_VERBOSE | FLAG_SYNCAGENT; // verbose log
  42. sk_init();
  43. AnsiString VersionString = AnsiString(SshVersionString());
  44. DebugAssert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  45. strcpy(sshver, VersionString.c_str());
  46. AnsiString AppName = AnsiString(AppNameString());
  47. DebugAssert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  48. strcpy(appname_, AppName.c_str());
  49. }
  50. //---------------------------------------------------------------------------
  51. void __fastcall PuttyFinalize()
  52. {
  53. if (SaveRandomSeed)
  54. {
  55. random_save_seed();
  56. }
  57. random_unref();
  58. sk_cleanup();
  59. win_misc_cleanup();
  60. win_secur_cleanup();
  61. ec_cleanup();
  62. DeleteCriticalSection(&putty_section);
  63. }
  64. //---------------------------------------------------------------------------
  65. void __fastcall DontSaveRandomSeed()
  66. {
  67. SaveRandomSeed = false;
  68. }
  69. //---------------------------------------------------------------------------
  70. TSecureShell * GetSecureShell(Plug plug, bool & pfwd)
  71. {
  72. if (!is_ssh(plug) && !is_pfwd(plug))
  73. {
  74. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  75. // Get SSH/PFwd plug which it wraps.
  76. ProxySocket * AProxySocket = get_proxy_plug_socket(plug);
  77. plug = AProxySocket->plug;
  78. }
  79. pfwd = is_pfwd(plug);
  80. void * frontend;
  81. if (pfwd)
  82. {
  83. frontend = get_pfwd_frontend(plug);
  84. }
  85. else
  86. {
  87. frontend = get_ssh_frontend(plug);
  88. }
  89. DebugAssert(frontend != NULL);
  90. return reinterpret_cast<TSecureShell*>(frontend);
  91. }
  92. //---------------------------------------------------------------------------
  93. struct callback_set * get_callback_set(Plug plug)
  94. {
  95. bool pfwd;
  96. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  97. return SecureShell->GetCallbackSet();
  98. }
  99. //---------------------------------------------------------------------------
  100. extern "C" char * do_select(Plug plug, SOCKET skt, int startup)
  101. {
  102. bool pfwd;
  103. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  104. if (!pfwd)
  105. {
  106. SecureShell->UpdateSocket(skt, startup);
  107. }
  108. else
  109. {
  110. SecureShell->UpdatePortFwdSocket(skt, startup);
  111. }
  112. return NULL;
  113. }
  114. //---------------------------------------------------------------------------
  115. int from_backend(Frontend * frontend, int is_stderr, const void * data, int datalen)
  116. {
  117. DebugAssert(frontend);
  118. if (is_stderr >= 0)
  119. {
  120. DebugAssert((is_stderr == 0) || (is_stderr == 1));
  121. ((TSecureShell *)frontend)->FromBackend((is_stderr == 1), reinterpret_cast<const unsigned char *>(data), datalen);
  122. }
  123. else
  124. {
  125. DebugAssert(is_stderr == -1);
  126. ((TSecureShell *)frontend)->CWrite(reinterpret_cast<const char *>(data), datalen);
  127. }
  128. return 0;
  129. }
  130. //---------------------------------------------------------------------------
  131. int from_backend_untrusted(Frontend * /*frontend*/, const void * /*data*/, int /*len*/)
  132. {
  133. // currently used with authentication banner only,
  134. // for which we have own interface display_banner
  135. return 0;
  136. }
  137. //---------------------------------------------------------------------------
  138. int from_backend_eof(Frontend * /*frontend*/)
  139. {
  140. return FALSE;
  141. }
  142. //---------------------------------------------------------------------------
  143. int get_userpass_input(prompts_t * p, bufchain * DebugUsedArg(input))
  144. {
  145. DebugAssert(p != NULL);
  146. TSecureShell * SecureShell = reinterpret_cast<TSecureShell *>(p->frontend);
  147. DebugAssert(SecureShell != NULL);
  148. int Result;
  149. TStrings * Prompts = new TStringList();
  150. TStrings * Results = new TStringList();
  151. try
  152. {
  153. UnicodeString Name = UTF8ToString(p->name);
  154. UnicodeString AName = Name;
  155. TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
  156. bool UTF8Prompt = (PromptKind != pkPassphrase);
  157. for (int Index = 0; Index < int(p->n_prompts); Index++)
  158. {
  159. prompt_t * Prompt = p->prompts[Index];
  160. UnicodeString S;
  161. if (UTF8Prompt)
  162. {
  163. S = UTF8ToString(Prompt->prompt);
  164. }
  165. else
  166. {
  167. S = UnicodeString(AnsiString(Prompt->prompt));
  168. }
  169. Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  170. // this fails, when new passwords do not match on change password prompt,
  171. // and putty retries the prompt
  172. DebugAssert(Prompt->resultsize == 0);
  173. Results->Add(L"");
  174. }
  175. UnicodeString Instructions = UTF8ToString(p->instruction);
  176. if (SecureShell->PromptUser(p->to_server, Name, p->name_reqd,
  177. Instructions, p->instr_reqd, Prompts, Results))
  178. {
  179. for (int Index = 0; Index < int(p->n_prompts); Index++)
  180. {
  181. prompt_t * Prompt = p->prompts[Index];
  182. RawByteString S;
  183. if (UTF8Prompt)
  184. {
  185. S = RawByteString(UTF8String(Results->Strings[Index]));
  186. }
  187. else
  188. {
  189. S = RawByteString(AnsiString(Results->Strings[Index]));
  190. }
  191. prompt_set_result(Prompt, S.c_str());
  192. }
  193. Result = 1;
  194. }
  195. else
  196. {
  197. Result = 0;
  198. }
  199. }
  200. __finally
  201. {
  202. delete Prompts;
  203. delete Results;
  204. }
  205. return Result;
  206. }
  207. //---------------------------------------------------------------------------
  208. char * get_ttymode(Frontend * /*frontend*/, const char * /*mode*/)
  209. {
  210. // should never happen when Config.nopty == TRUE
  211. DebugFail();
  212. return NULL;
  213. }
  214. //---------------------------------------------------------------------------
  215. void logevent(Frontend * frontend, const char * string)
  216. {
  217. // Frontend maybe NULL here
  218. if (frontend != NULL)
  219. {
  220. ((TSecureShell *)frontend)->PuttyLogEvent(string);
  221. }
  222. }
  223. //---------------------------------------------------------------------------
  224. void connection_fatal(Frontend * frontend, const char * fmt, ...)
  225. {
  226. va_list Param;
  227. char Buf[200];
  228. va_start(Param, fmt);
  229. vsnprintf(Buf, LENOF(Buf), fmt, Param); \
  230. Buf[LENOF(Buf) - 1] = '\0'; \
  231. va_end(Param);
  232. DebugAssert(frontend != NULL);
  233. ((TSecureShell *)frontend)->PuttyFatalError(Buf);
  234. }
  235. //---------------------------------------------------------------------------
  236. int verify_ssh_host_key(Frontend * frontend, char * host, int port, const char * keytype,
  237. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  238. void * /*ctx*/)
  239. {
  240. DebugAssert(frontend != NULL);
  241. reinterpret_cast<TSecureShell *>(frontend)->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  242. // We should return 0 when key was not confirmed, we throw exception instead.
  243. return 1;
  244. }
  245. //---------------------------------------------------------------------------
  246. int have_ssh_host_key(void * frontend, const char * hostname, int port,
  247. const char * keytype)
  248. {
  249. DebugAssert(frontend != NULL);
  250. return static_cast<TSecureShell *>(frontend)->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  251. }
  252. //---------------------------------------------------------------------------
  253. int askalg(Frontend * frontend, const char * algtype, const char * algname,
  254. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  255. {
  256. DebugAssert(frontend != NULL);
  257. ((TSecureShell *)frontend)->AskAlg(algtype, algname);
  258. // We should return 0 when alg was not confirmed, we throw exception instead.
  259. return 1;
  260. }
  261. //---------------------------------------------------------------------------
  262. int askhk(Frontend * /*frontend*/, const char * /*algname*/, const char * /*betteralgs*/,
  263. void (*/*callback*/)(void *ctx, int result), void * /*ctx*/)
  264. {
  265. return 1;
  266. }
  267. //---------------------------------------------------------------------------
  268. void old_keyfile_warning(void)
  269. {
  270. // no reference to TSecureShell instance available
  271. }
  272. //---------------------------------------------------------------------------
  273. void display_banner(void * frontend, const char * banner, int size)
  274. {
  275. DebugAssert(frontend);
  276. UnicodeString Banner(UTF8String(banner, size));
  277. ((TSecureShell *)frontend)->DisplayBanner(Banner);
  278. }
  279. //---------------------------------------------------------------------------
  280. static void SSHFatalError(const char * Format, va_list Param)
  281. {
  282. char Buf[200];
  283. vsnprintf(Buf, LENOF(Buf), Format, Param);
  284. Buf[LENOF(Buf) - 1] = '\0';
  285. // Only few calls from putty\winnet.c might be connected with specific
  286. // TSecureShell. Otherwise called only for really fatal errors
  287. // like 'out of memory' from putty\ssh.c.
  288. throw ESshFatal(NULL, Buf);
  289. }
  290. //---------------------------------------------------------------------------
  291. void fatalbox(const char * fmt, ...)
  292. {
  293. va_list Param;
  294. va_start(Param, fmt);
  295. SSHFatalError(fmt, Param);
  296. va_end(Param);
  297. }
  298. //---------------------------------------------------------------------------
  299. void modalfatalbox(const char * fmt, ...)
  300. {
  301. va_list Param;
  302. va_start(Param, fmt);
  303. SSHFatalError(fmt, Param);
  304. va_end(Param);
  305. }
  306. //---------------------------------------------------------------------------
  307. void nonfatal(const char * fmt, ...)
  308. {
  309. va_list Param;
  310. va_start(Param, fmt);
  311. SSHFatalError(fmt, Param);
  312. va_end(Param);
  313. }
  314. //---------------------------------------------------------------------------
  315. void cleanup_exit(int /*code*/)
  316. {
  317. throw ESshFatal(NULL, "");
  318. }
  319. //---------------------------------------------------------------------------
  320. int askappend(Frontend * /*frontend*/, Filename * /*filename*/,
  321. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  322. {
  323. // this is called from logging.c of putty, which is never used with WinSCP
  324. DebugFail();
  325. return 0;
  326. }
  327. //---------------------------------------------------------------------------
  328. void ldisc_echoedit_update(Ldisc * /*handle*/)
  329. {
  330. DebugFail();
  331. }
  332. //---------------------------------------------------------------------------
  333. void agent_schedule_callback(void (* /*callback*/)(void *, void *, int),
  334. void * /*callback_ctx*/, void * /*data*/, int /*len*/)
  335. {
  336. DebugFail();
  337. }
  338. //---------------------------------------------------------------------------
  339. void notify_remote_exit(Frontend * /*frontend*/)
  340. {
  341. // nothing
  342. }
  343. //---------------------------------------------------------------------------
  344. void update_specials_menu(Frontend * /*frontend*/)
  345. {
  346. // nothing
  347. }
  348. //---------------------------------------------------------------------------
  349. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  350. {
  351. return ticks + GetTickCount();
  352. }
  353. //---------------------------------------------------------------------------
  354. void expire_timer_context(void * /*ctx*/)
  355. {
  356. // nothing
  357. }
  358. //---------------------------------------------------------------------------
  359. Pinger pinger_new(Conf * /*conf*/, Backend * /*back*/)
  360. {
  361. return NULL;
  362. }
  363. //---------------------------------------------------------------------------
  364. void pinger_reconfig(Pinger /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  365. {
  366. // nothing
  367. }
  368. //---------------------------------------------------------------------------
  369. void pinger_free(Pinger /*pinger*/)
  370. {
  371. // nothing
  372. }
  373. //---------------------------------------------------------------------------
  374. void set_busy_status(Frontend * /*frontend*/, int /*status*/)
  375. {
  376. // nothing
  377. }
  378. //---------------------------------------------------------------------------
  379. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  380. {
  381. // nothing, therefore no auth.
  382. }
  383. //---------------------------------------------------------------------------
  384. // Based on PuTTY's settings.c
  385. char * get_remote_username(Conf * conf)
  386. {
  387. char * username = conf_get_str(conf, CONF_username);
  388. char * result;
  389. if (*username)
  390. {
  391. result = dupstr(username);
  392. }
  393. else
  394. {
  395. result = NULL;
  396. }
  397. return result;
  398. }
  399. //---------------------------------------------------------------------------
  400. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  401. {
  402. long R;
  403. DebugAssert(Configuration != NULL);
  404. DebugAssert(Key == HKEY_CURRENT_USER);
  405. DebugUsedParam(Key);
  406. UnicodeString RegKey = SubKey;
  407. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  408. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  409. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  410. if (!RegKey.IsEmpty())
  411. {
  412. DebugAssert(RegKey[1] == L'\\');
  413. RegKey.Delete(1, 1);
  414. }
  415. if (RegKey.IsEmpty())
  416. {
  417. *Result = static_cast<HKEY>(NULL);
  418. R = ERROR_SUCCESS;
  419. }
  420. else
  421. {
  422. // we expect this to be called only from verify_host_key() or store_host_key()
  423. DebugAssert(RegKey == L"SshHostKeys");
  424. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  425. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  426. if (Storage->OpenSubKey(RegKey, CanCreate))
  427. {
  428. *Result = reinterpret_cast<HKEY>(Storage);
  429. R = ERROR_SUCCESS;
  430. }
  431. else
  432. {
  433. delete Storage;
  434. R = ERROR_CANTOPEN;
  435. }
  436. }
  437. return R;
  438. }
  439. //---------------------------------------------------------------------------
  440. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  441. {
  442. return OpenWinSCPKey(Key, SubKey, Result, false);
  443. }
  444. //---------------------------------------------------------------------------
  445. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  446. {
  447. return OpenWinSCPKey(Key, SubKey, Result, true);
  448. }
  449. //---------------------------------------------------------------------------
  450. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  451. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  452. {
  453. long R;
  454. DebugAssert(Configuration != NULL);
  455. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  456. AnsiString Value;
  457. if (Storage == NULL)
  458. {
  459. if (UnicodeString(ValueName) == L"RandSeedFile")
  460. {
  461. Value = AnsiString(Configuration->RandomSeedFileName);
  462. R = ERROR_SUCCESS;
  463. }
  464. else
  465. {
  466. DebugFail();
  467. R = ERROR_READ_FAULT;
  468. }
  469. }
  470. else
  471. {
  472. if (Storage->ValueExists(ValueName))
  473. {
  474. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  475. R = ERROR_SUCCESS;
  476. }
  477. else
  478. {
  479. R = ERROR_READ_FAULT;
  480. }
  481. }
  482. if (R == ERROR_SUCCESS)
  483. {
  484. DebugAssert(Type != NULL);
  485. *Type = REG_SZ;
  486. char * DataStr = reinterpret_cast<char *>(Data);
  487. strncpy(DataStr, Value.c_str(), *DataSize);
  488. DataStr[*DataSize - 1] = '\0';
  489. *DataSize = strlen(DataStr);
  490. }
  491. return R;
  492. }
  493. //---------------------------------------------------------------------------
  494. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  495. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  496. {
  497. DebugAssert(Configuration != NULL);
  498. DebugAssert(Type == REG_SZ);
  499. DebugUsedParam(Type);
  500. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  501. DebugAssert(Storage != NULL);
  502. if (Storage != NULL)
  503. {
  504. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  505. Storage->WriteStringRaw(ValueName, Value);
  506. }
  507. return ERROR_SUCCESS;
  508. }
  509. //---------------------------------------------------------------------------
  510. long reg_close_winscp_key(HKEY Key)
  511. {
  512. DebugAssert(Configuration != NULL);
  513. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  514. if (Storage != NULL)
  515. {
  516. delete Storage;
  517. }
  518. return ERROR_SUCCESS;
  519. }
  520. //---------------------------------------------------------------------------
  521. TKeyType KeyType(UnicodeString FileName)
  522. {
  523. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  524. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  525. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  526. UTF8String UtfFileName = UTF8String(FileName);
  527. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  528. TKeyType Result = (TKeyType)key_type(KeyFile);
  529. filename_free(KeyFile);
  530. return Result;
  531. }
  532. //---------------------------------------------------------------------------
  533. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  534. {
  535. UTF8String UtfFileName = UTF8String(FileName);
  536. bool Result;
  537. char * CommentStr = NULL;
  538. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  539. try
  540. {
  541. switch (KeyType)
  542. {
  543. case ktSSH2:
  544. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  545. break;
  546. case ktOpenSSHPEM:
  547. case ktOpenSSHNew:
  548. case ktSSHCom:
  549. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  550. break;
  551. default:
  552. DebugFail();
  553. Result = false;
  554. break;
  555. }
  556. }
  557. __finally
  558. {
  559. filename_free(KeyFile);
  560. }
  561. if (CommentStr != NULL)
  562. {
  563. Comment = UnicodeString(AnsiString(CommentStr));
  564. // ktOpenSSH has no comment, PuTTY defaults to file path
  565. if (Comment == FileName)
  566. {
  567. Comment = ExtractFileName(FileName);
  568. }
  569. sfree(CommentStr);
  570. }
  571. return Result;
  572. }
  573. //---------------------------------------------------------------------------
  574. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  575. {
  576. UTF8String UtfFileName = UTF8String(FileName);
  577. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  578. struct ssh2_userkey * Ssh2Key = NULL;
  579. const char * ErrorStr = NULL;
  580. AnsiString AnsiPassphrase = Passphrase;
  581. try
  582. {
  583. switch (KeyType)
  584. {
  585. case ktSSH2:
  586. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  587. break;
  588. case ktOpenSSHPEM:
  589. case ktOpenSSHNew:
  590. case ktSSHCom:
  591. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  592. break;
  593. default:
  594. DebugFail();
  595. break;
  596. }
  597. }
  598. __finally
  599. {
  600. Shred(AnsiPassphrase);
  601. filename_free(KeyFile);
  602. }
  603. if (Ssh2Key == NULL)
  604. {
  605. UnicodeString Error = AnsiString(ErrorStr);
  606. // While theoretically we may get "unable to open key file" and
  607. // so we should check system error code,
  608. // we actully never get here unless we call KeyType previously
  609. // and handle ktUnopenable accordingly.
  610. throw Exception(Error);
  611. }
  612. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  613. {
  614. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  615. }
  616. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  617. }
  618. //---------------------------------------------------------------------------
  619. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  620. {
  621. AnsiString AnsiComment(Comment);
  622. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  623. sfree(Ssh2Key->comment);
  624. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  625. }
  626. //---------------------------------------------------------------------------
  627. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  628. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  629. {
  630. UTF8String UtfFileName = UTF8String(FileName);
  631. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  632. try
  633. {
  634. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  635. AnsiString AnsiPassphrase = Passphrase;
  636. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  637. switch (KeyType)
  638. {
  639. case ktSSH2:
  640. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  641. {
  642. int Error = errno;
  643. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  644. }
  645. break;
  646. default:
  647. DebugFail();
  648. break;
  649. }
  650. }
  651. __finally
  652. {
  653. filename_free(KeyFile);
  654. }
  655. }
  656. //---------------------------------------------------------------------------
  657. void FreeKey(TPrivateKey * PrivateKey)
  658. {
  659. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  660. ssh_key_free(Ssh2Key->key);
  661. sfree(Ssh2Key);
  662. }
  663. //---------------------------------------------------------------------------
  664. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  665. {
  666. RawByteString Result;
  667. UTF8String UtfFileName = UTF8String(FileName);
  668. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  669. try
  670. {
  671. char * AlgorithmStr = NULL;
  672. char * CommentStr = NULL;
  673. const char * ErrorStr = NULL;
  674. strbuf * PublicKeyBuf = strbuf_new();
  675. if (!ssh2_userkey_loadpub(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  676. {
  677. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  678. throw Exception(Error);
  679. }
  680. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  681. sfree(AlgorithmStr);
  682. Comment = UnicodeString(AnsiString(CommentStr));
  683. sfree(CommentStr);
  684. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  685. strbuf_free(PublicKeyBuf);
  686. }
  687. __finally
  688. {
  689. filename_free(KeyFile);
  690. }
  691. return Result;
  692. }
  693. //---------------------------------------------------------------------------
  694. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  695. {
  696. UnicodeString Algorithm;
  697. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  698. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  699. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  700. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  701. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  702. return Result;
  703. }
  704. //---------------------------------------------------------------------------
  705. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  706. {
  707. static int has = -1;
  708. if (has < 0)
  709. {
  710. Conf * conf = conf_new();
  711. ssh_gss_liblist * List = NULL;
  712. try
  713. {
  714. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  715. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  716. filename_free(filename);
  717. List = ssh_gss_setup(conf, NULL);
  718. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  719. {
  720. ssh_gss_library * library = &List->libraries[Index];
  721. Ssh_gss_ctx ctx;
  722. memset(&ctx, 0, sizeof(ctx));
  723. has =
  724. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  725. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  726. }
  727. }
  728. __finally
  729. {
  730. ssh_gss_cleanup(List);
  731. conf_free(conf);
  732. }
  733. if (has < 0)
  734. {
  735. has = 0;
  736. }
  737. }
  738. return (has > 0);
  739. }
  740. //---------------------------------------------------------------------------
  741. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyType)
  742. {
  743. const wchar_t NormalizedSeparator = L'-';
  744. const int MaxCount = 10;
  745. const ssh_keyalg * SignKeys[MaxCount];
  746. int Count = LENOF(SignKeys);
  747. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  748. // as the names have different number of dashes
  749. get_hostkey_algs(&Count, SignKeys);
  750. for (int Index = 0; Index < Count; Index++)
  751. {
  752. const ssh_keyalg * SignKey = SignKeys[Index];
  753. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  754. if (StartsStr(Name + L" ", Fingerprint))
  755. {
  756. int LenStart = Name.Length() + 1;
  757. Fingerprint[LenStart] = NormalizedSeparator;
  758. int Space = Fingerprint.Pos(L" ");
  759. // If not a number, it's an invalid input,
  760. // either something completelly wrong, or it can be OpenSSH base64 public key,
  761. // that got here from TPasteKeyHandler::Paste
  762. if (IsNumber(Fingerprint.SubString(LenStart + 1, Space - LenStart - 1)))
  763. {
  764. Fingerprint.Delete(LenStart + 1, Space - LenStart);
  765. // noop for SHA256 fingerprints
  766. Fingerprint = ReplaceChar(Fingerprint, L':', NormalizedSeparator);
  767. KeyType = UnicodeString(SignKey->cache_id);
  768. return;
  769. }
  770. }
  771. else if (StartsStr(Name + NormalizedSeparator, Fingerprint))
  772. {
  773. KeyType = UnicodeString(SignKey->cache_id);
  774. return;
  775. }
  776. }
  777. }
  778. //---------------------------------------------------------------------------
  779. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  780. {
  781. UnicodeString KeyType; // unused
  782. DoNormalizeFingerprint(Fingerprint, KeyType);
  783. return Fingerprint;
  784. }
  785. //---------------------------------------------------------------------------
  786. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  787. {
  788. UnicodeString KeyType;
  789. DoNormalizeFingerprint(Fingerprint, KeyType);
  790. return KeyType;
  791. }
  792. //---------------------------------------------------------------------------
  793. UnicodeString __fastcall GetPuTTYVersion()
  794. {
  795. // "Release 0.64"
  796. // "Pre-release 0.65:2015-07-20.95501a1"
  797. // "Development snapshot 2015-12-22.51465fa"
  798. UnicodeString Result = get_putty_version();
  799. // Skip "Release", "Pre-release", "Development snapshot"
  800. int P = Result.LastDelimiter(L" ");
  801. Result.Delete(1, P);
  802. return Result;
  803. }
  804. //---------------------------------------------------------------------------
  805. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  806. {
  807. unsigned char Digest[32];
  808. SHA256_Simple(Data, Size, Digest);
  809. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  810. return Result;
  811. }
  812. //---------------------------------------------------------------------------
  813. void __fastcall DllHijackingProtection()
  814. {
  815. dll_hijacking_protection();
  816. }
  817. //---------------------------------------------------------------------------
  818. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  819. {
  820. UTF8String UtfLine = UTF8String(Line);
  821. char * AlgorithmName = NULL;
  822. char * CommentPtr = NULL;
  823. const char * ErrorStr = NULL;
  824. strbuf * PubBlobBuf = strbuf_new();
  825. UnicodeString Result;
  826. if (!openssh_loadpub_line(UtfLine.c_str(), &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  827. {
  828. throw Exception(UnicodeString(ErrorStr));
  829. }
  830. else
  831. {
  832. try
  833. {
  834. Algorithm = find_pubkey_alg(AlgorithmName);
  835. if (Algorithm == NULL)
  836. {
  837. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  838. }
  839. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  840. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  841. if (Key == NULL)
  842. {
  843. throw Exception(L"Invalid public key.");
  844. }
  845. char * FmtKey = Algorithm->cache_str(Key);
  846. Result = UnicodeString(FmtKey);
  847. sfree(FmtKey);
  848. Algorithm->freekey(Key);
  849. }
  850. __finally
  851. {
  852. strbuf_free(PubBlobBuf);
  853. sfree(AlgorithmName);
  854. sfree(CommentPtr);
  855. }
  856. }
  857. return Result;
  858. }
  859. //---------------------------------------------------------------------------
  860. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  861. {
  862. UnicodeString Result;
  863. if (KeyType == ssh_dss.cache_id)
  864. {
  865. Result = L"DSA";
  866. }
  867. else if (KeyType == ssh_rsa.cache_id)
  868. {
  869. Result = L"RSA";
  870. }
  871. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  872. {
  873. Result = L"Ed25519";
  874. }
  875. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  876. {
  877. Result = L"ECDSA/nistp256";
  878. }
  879. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  880. {
  881. Result = L"ECDSA/nistp384";
  882. }
  883. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  884. {
  885. Result = L"ECDSA/nistp521";
  886. }
  887. else
  888. {
  889. DebugFail();
  890. Result = KeyType;
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. bool IsOpenSSH(const UnicodeString & SshImplementation)
  896. {
  897. return
  898. // e.g. "OpenSSH_5.3"
  899. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  900. // Sun SSH is based on OpenSSH (suffers the same bugs)
  901. (SshImplementation.Pos(L"Sun_SSH") == 1);
  902. }
  903. //---------------------------------------------------------------------------
  904. TStrings * SshCipherList()
  905. {
  906. std::unique_ptr<TStrings> Result(new TStringList());
  907. // Same order as DefaultCipherList
  908. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  909. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  910. {
  911. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  912. {
  913. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->name);
  914. Result->Add(Name);
  915. }
  916. }
  917. return Result.release();
  918. }
  919. //---------------------------------------------------------------------------
  920. TStrings * SshKexList()
  921. {
  922. std::unique_ptr<TStrings> Result(new TStringList());
  923. // Same order as DefaultKexList
  924. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  925. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  926. {
  927. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  928. {
  929. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  930. Result->Add(Name);
  931. }
  932. }
  933. return Result.release();
  934. }
  935. //---------------------------------------------------------------------------
  936. TStrings * SshHostKeyList()
  937. {
  938. std::unique_ptr<TStrings> Result(new TStringList());
  939. const int MaxCount = 10;
  940. const ssh_keyalg * SignKeys[MaxCount];
  941. int Count = LENOF(SignKeys);
  942. get_hostkey_algs(&Count, SignKeys);
  943. for (int Index = 0; Index < Count; Index++)
  944. {
  945. const ssh_keyalg * SignKey = SignKeys[Index];
  946. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  947. Result->Add(Name);
  948. }
  949. return Result.release();
  950. }
  951. //---------------------------------------------------------------------------
  952. TStrings * SshMacList()
  953. {
  954. std::unique_ptr<TStrings> Result(new TStringList());
  955. const struct ssh2_macalg ** Macs = NULL;
  956. int Count = 0;
  957. get_macs(&Count, &Macs);
  958. for (int Index = 0; Index < Count; Index++)
  959. {
  960. UnicodeString Name = UnicodeString(Macs[Index]->name);
  961. Result->Add(Name);
  962. }
  963. return Result.release();
  964. }
  965. //---------------------------------------------------------------------------
  966. UnicodeString GetCipher1Name(const ssh1_cipher * Cipher)
  967. {
  968. return UnicodeString(UTF8String((*Cipher)->text_name));
  969. }
  970. //---------------------------------------------------------------------------
  971. UnicodeString GetCipher2Name(const ssh2_cipher * Cipher)
  972. {
  973. return UnicodeString(UTF8String((*Cipher)->text_name));
  974. }
  975. //---------------------------------------------------------------------------
  976. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  977. {
  978. UnicodeString Result;
  979. if (Compressor != NULL)
  980. {
  981. Result = UnicodeString(UTF8String(Compressor->vt->name));
  982. }
  983. return Result;
  984. }
  985. //---------------------------------------------------------------------------
  986. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  987. {
  988. UnicodeString Result;
  989. if (Decompressor != NULL)
  990. {
  991. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  992. }
  993. return Result;
  994. }
  995. //---------------------------------------------------------------------------
  996. //---------------------------------------------------------------------------