PuttyIntf.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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. //---------------------------------------------------------------------------
  13. char sshver[50];
  14. const int platform_uses_x11_unix_by_default = TRUE;
  15. CRITICAL_SECTION putty_section;
  16. bool SaveRandomSeed;
  17. char appname_[50];
  18. const char *const appname = appname_;
  19. extern const int share_can_be_downstream = FALSE;
  20. extern const int share_can_be_upstream = FALSE;
  21. //---------------------------------------------------------------------------
  22. extern "C"
  23. {
  24. #include <winstuff.h>
  25. }
  26. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  27. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  28. const UnicodeString OriginalPuttyExecutable("putty.exe");
  29. const UnicodeString KittyExecutable("kitty.exe");
  30. //---------------------------------------------------------------------------
  31. void __fastcall PuttyInitialize()
  32. {
  33. SaveRandomSeed = true;
  34. InitializeCriticalSection(&putty_section);
  35. // make sure random generator is initialised, so random_save_seed()
  36. // in destructor can proceed
  37. random_ref();
  38. flags = FLAG_VERBOSE | FLAG_SYNCAGENT; // verbose log
  39. sk_init();
  40. AnsiString VersionString = AnsiString(SshVersionString());
  41. DebugAssert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  42. strcpy(sshver, VersionString.c_str());
  43. AnsiString AppName = AnsiString(AppNameString());
  44. DebugAssert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  45. strcpy(appname_, AppName.c_str());
  46. }
  47. //---------------------------------------------------------------------------
  48. void __fastcall PuttyFinalize()
  49. {
  50. if (SaveRandomSeed)
  51. {
  52. random_save_seed();
  53. }
  54. random_unref();
  55. sk_cleanup();
  56. win_misc_cleanup();
  57. DeleteCriticalSection(&putty_section);
  58. }
  59. //---------------------------------------------------------------------------
  60. void __fastcall DontSaveRandomSeed()
  61. {
  62. SaveRandomSeed = false;
  63. }
  64. //---------------------------------------------------------------------------
  65. extern "C" char * do_select(Plug plug, SOCKET skt, int startup)
  66. {
  67. void * frontend;
  68. if (!is_ssh(plug) && !is_pfwd(plug))
  69. {
  70. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  71. // Get SSH/PFwd plug which it wraps.
  72. Proxy_Socket ProxySocket = ((Proxy_Plug)plug)->proxy_socket;
  73. plug = ProxySocket->plug;
  74. }
  75. bool pfwd = is_pfwd(plug);
  76. if (pfwd)
  77. {
  78. plug = (Plug)get_pfwd_backend(plug);
  79. }
  80. frontend = get_ssh_frontend(plug);
  81. DebugAssert(frontend);
  82. TSecureShell * SecureShell = reinterpret_cast<TSecureShell*>(frontend);
  83. if (!pfwd)
  84. {
  85. SecureShell->UpdateSocket(skt, startup);
  86. }
  87. else
  88. {
  89. SecureShell->UpdatePortFwdSocket(skt, startup);
  90. }
  91. return NULL;
  92. }
  93. //---------------------------------------------------------------------------
  94. int from_backend(void * frontend, int is_stderr, const char * data, int datalen)
  95. {
  96. DebugAssert(frontend);
  97. if (is_stderr >= 0)
  98. {
  99. DebugAssert((is_stderr == 0) || (is_stderr == 1));
  100. ((TSecureShell *)frontend)->FromBackend((is_stderr == 1), reinterpret_cast<const unsigned char *>(data), datalen);
  101. }
  102. else
  103. {
  104. DebugAssert(is_stderr == -1);
  105. ((TSecureShell *)frontend)->CWrite(data, datalen);
  106. }
  107. return 0;
  108. }
  109. //---------------------------------------------------------------------------
  110. int from_backend_untrusted(void * /*frontend*/, const char * /*data*/, int /*len*/)
  111. {
  112. // currently used with authentication banner only,
  113. // for which we have own interface display_banner
  114. return 0;
  115. }
  116. //---------------------------------------------------------------------------
  117. int from_backend_eof(void * /*frontend*/)
  118. {
  119. return FALSE;
  120. }
  121. //---------------------------------------------------------------------------
  122. int get_userpass_input(prompts_t * p, const unsigned char * /*in*/, int /*inlen*/)
  123. {
  124. DebugAssert(p != NULL);
  125. TSecureShell * SecureShell = reinterpret_cast<TSecureShell *>(p->frontend);
  126. DebugAssert(SecureShell != NULL);
  127. int Result;
  128. TStrings * Prompts = new TStringList();
  129. TStrings * Results = new TStringList();
  130. try
  131. {
  132. UnicodeString Name = UTF8ToString(p->name);
  133. UnicodeString AName = Name;
  134. TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
  135. bool UTF8Prompt = (PromptKind != pkPassphrase);
  136. for (int Index = 0; Index < int(p->n_prompts); Index++)
  137. {
  138. prompt_t * Prompt = p->prompts[Index];
  139. UnicodeString S;
  140. if (UTF8Prompt)
  141. {
  142. S = UTF8ToString(Prompt->prompt);
  143. }
  144. else
  145. {
  146. S = UnicodeString(AnsiString(Prompt->prompt));
  147. }
  148. Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  149. // this fails, when new passwords do not match on change password prompt,
  150. // and putty retries the prompt
  151. DebugAssert(Prompt->resultsize == 0);
  152. Results->Add(L"");
  153. }
  154. UnicodeString Instructions = UTF8ToString(p->instruction);
  155. if (SecureShell->PromptUser(p->to_server, Name, p->name_reqd,
  156. Instructions, p->instr_reqd, Prompts, Results))
  157. {
  158. for (int Index = 0; Index < int(p->n_prompts); Index++)
  159. {
  160. prompt_t * Prompt = p->prompts[Index];
  161. RawByteString S;
  162. if (UTF8Prompt)
  163. {
  164. S = RawByteString(UTF8String(Results->Strings[Index]));
  165. }
  166. else
  167. {
  168. S = RawByteString(AnsiString(Results->Strings[Index]));
  169. }
  170. prompt_set_result(Prompt, S.c_str());
  171. }
  172. Result = 1;
  173. }
  174. else
  175. {
  176. Result = 0;
  177. }
  178. }
  179. __finally
  180. {
  181. delete Prompts;
  182. delete Results;
  183. }
  184. return Result;
  185. }
  186. //---------------------------------------------------------------------------
  187. char * get_ttymode(void * /*frontend*/, const char * /*mode*/)
  188. {
  189. // should never happen when Config.nopty == TRUE
  190. DebugFail();
  191. return NULL;
  192. }
  193. //---------------------------------------------------------------------------
  194. void logevent(void * frontend, const char * string)
  195. {
  196. // Frontend maybe NULL here
  197. if (frontend != NULL)
  198. {
  199. ((TSecureShell *)frontend)->PuttyLogEvent(string);
  200. }
  201. }
  202. //---------------------------------------------------------------------------
  203. void connection_fatal(void * frontend, const char * fmt, ...)
  204. {
  205. va_list Param;
  206. char Buf[200];
  207. va_start(Param, fmt);
  208. vsnprintf(Buf, LENOF(Buf), fmt, Param); \
  209. Buf[LENOF(Buf) - 1] = '\0'; \
  210. va_end(Param);
  211. DebugAssert(frontend != NULL);
  212. ((TSecureShell *)frontend)->PuttyFatalError(Buf);
  213. }
  214. //---------------------------------------------------------------------------
  215. int verify_ssh_host_key(void * frontend, char * host, int port, const char * keytype,
  216. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  217. void * /*ctx*/)
  218. {
  219. DebugAssert(frontend != NULL);
  220. static_cast<TSecureShell *>(frontend)->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  221. // We should return 0 when key was not confirmed, we throw exception instead.
  222. return 1;
  223. }
  224. //---------------------------------------------------------------------------
  225. int have_ssh_host_key(void * frontend, const char * hostname, int port,
  226. const char * keytype)
  227. {
  228. DebugAssert(frontend != NULL);
  229. return static_cast<TSecureShell *>(frontend)->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  230. }
  231. //---------------------------------------------------------------------------
  232. int askalg(void * frontend, const char * algtype, const char * algname,
  233. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  234. {
  235. DebugAssert(frontend != NULL);
  236. ((TSecureShell *)frontend)->AskAlg(algtype, algname);
  237. // We should return 0 when alg was not confirmed, we throw exception instead.
  238. return 1;
  239. }
  240. //---------------------------------------------------------------------------
  241. void old_keyfile_warning(void)
  242. {
  243. // no reference to TSecureShell instace available
  244. }
  245. //---------------------------------------------------------------------------
  246. void display_banner(void * frontend, const char * banner, int size)
  247. {
  248. DebugAssert(frontend);
  249. UnicodeString Banner(UTF8String(banner, size));
  250. ((TSecureShell *)frontend)->DisplayBanner(Banner);
  251. }
  252. //---------------------------------------------------------------------------
  253. static void SSHFatalError(const char * Format, va_list Param)
  254. {
  255. char Buf[200];
  256. vsnprintf(Buf, LENOF(Buf), Format, Param);
  257. Buf[LENOF(Buf) - 1] = '\0';
  258. // Only few calls from putty\winnet.c might be connected with specific
  259. // TSecureShell. Otherwise called only for really fatal errors
  260. // like 'out of memory' from putty\ssh.c.
  261. throw ESshFatal(NULL, Buf);
  262. }
  263. //---------------------------------------------------------------------------
  264. void fatalbox(const char * fmt, ...)
  265. {
  266. va_list Param;
  267. va_start(Param, fmt);
  268. SSHFatalError(fmt, Param);
  269. va_end(Param);
  270. }
  271. //---------------------------------------------------------------------------
  272. void modalfatalbox(const char * fmt, ...)
  273. {
  274. va_list Param;
  275. va_start(Param, fmt);
  276. SSHFatalError(fmt, Param);
  277. va_end(Param);
  278. }
  279. //---------------------------------------------------------------------------
  280. void nonfatal(const char * fmt, ...)
  281. {
  282. va_list Param;
  283. va_start(Param, fmt);
  284. SSHFatalError(fmt, Param);
  285. va_end(Param);
  286. }
  287. //---------------------------------------------------------------------------
  288. void cleanup_exit(int /*code*/)
  289. {
  290. throw ESshFatal(NULL, "");
  291. }
  292. //---------------------------------------------------------------------------
  293. int askappend(void * /*frontend*/, Filename * /*filename*/,
  294. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  295. {
  296. // this is called from logging.c of putty, which is never used with WinSCP
  297. DebugFail();
  298. return 0;
  299. }
  300. //---------------------------------------------------------------------------
  301. void ldisc_echoedit_update(void * /*handle*/)
  302. {
  303. DebugFail();
  304. }
  305. //---------------------------------------------------------------------------
  306. void agent_schedule_callback(void (* /*callback*/)(void *, void *, int),
  307. void * /*callback_ctx*/, void * /*data*/, int /*len*/)
  308. {
  309. DebugFail();
  310. }
  311. //---------------------------------------------------------------------------
  312. void notify_remote_exit(void * /*frontend*/)
  313. {
  314. // nothing
  315. }
  316. //---------------------------------------------------------------------------
  317. void update_specials_menu(void * /*frontend*/)
  318. {
  319. // nothing
  320. }
  321. //---------------------------------------------------------------------------
  322. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  323. {
  324. return ticks + GetTickCount();
  325. }
  326. //---------------------------------------------------------------------------
  327. void expire_timer_context(void * /*ctx*/)
  328. {
  329. // nothing
  330. }
  331. //---------------------------------------------------------------------------
  332. Pinger pinger_new(Conf * /*conf*/, Backend * /*back*/, void * /*backhandle*/)
  333. {
  334. return NULL;
  335. }
  336. //---------------------------------------------------------------------------
  337. void pinger_reconfig(Pinger /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  338. {
  339. // nothing
  340. }
  341. //---------------------------------------------------------------------------
  342. void pinger_free(Pinger /*pinger*/)
  343. {
  344. // nothing
  345. }
  346. //---------------------------------------------------------------------------
  347. void set_busy_status(void * /*frontend*/, int /*status*/)
  348. {
  349. // nothing
  350. }
  351. //---------------------------------------------------------------------------
  352. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  353. {
  354. // nothing, therefore no auth.
  355. }
  356. //---------------------------------------------------------------------------
  357. // Based on PuTTY's settings.c
  358. char * get_remote_username(Conf * conf)
  359. {
  360. char * username = conf_get_str(conf, CONF_username);
  361. char * result;
  362. if (*username)
  363. {
  364. result = dupstr(username);
  365. }
  366. else
  367. {
  368. result = NULL;
  369. }
  370. return result;
  371. }
  372. //---------------------------------------------------------------------------
  373. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  374. {
  375. long R;
  376. DebugAssert(Configuration != NULL);
  377. DebugAssert(Key == HKEY_CURRENT_USER);
  378. DebugUsedParam(Key);
  379. UnicodeString RegKey = SubKey;
  380. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  381. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  382. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  383. if (!RegKey.IsEmpty())
  384. {
  385. DebugAssert(RegKey[1] == L'\\');
  386. RegKey.Delete(1, 1);
  387. }
  388. if (RegKey.IsEmpty())
  389. {
  390. *Result = static_cast<HKEY>(NULL);
  391. R = ERROR_SUCCESS;
  392. }
  393. else
  394. {
  395. // we expect this to be called only from verify_host_key() or store_host_key()
  396. DebugAssert(RegKey == L"SshHostKeys");
  397. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  398. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  399. if (Storage->OpenSubKey(RegKey, CanCreate))
  400. {
  401. *Result = reinterpret_cast<HKEY>(Storage);
  402. R = ERROR_SUCCESS;
  403. }
  404. else
  405. {
  406. delete Storage;
  407. R = ERROR_CANTOPEN;
  408. }
  409. }
  410. return R;
  411. }
  412. //---------------------------------------------------------------------------
  413. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  414. {
  415. return OpenWinSCPKey(Key, SubKey, Result, false);
  416. }
  417. //---------------------------------------------------------------------------
  418. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  419. {
  420. return OpenWinSCPKey(Key, SubKey, Result, true);
  421. }
  422. //---------------------------------------------------------------------------
  423. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  424. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  425. {
  426. long R;
  427. DebugAssert(Configuration != NULL);
  428. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  429. AnsiString Value;
  430. if (Storage == NULL)
  431. {
  432. if (UnicodeString(ValueName) == L"RandSeedFile")
  433. {
  434. Value = AnsiString(Configuration->RandomSeedFileName);
  435. R = ERROR_SUCCESS;
  436. }
  437. else
  438. {
  439. DebugFail();
  440. R = ERROR_READ_FAULT;
  441. }
  442. }
  443. else
  444. {
  445. if (Storage->ValueExists(ValueName))
  446. {
  447. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  448. R = ERROR_SUCCESS;
  449. }
  450. else
  451. {
  452. R = ERROR_READ_FAULT;
  453. }
  454. }
  455. if (R == ERROR_SUCCESS)
  456. {
  457. DebugAssert(Type != NULL);
  458. *Type = REG_SZ;
  459. char * DataStr = reinterpret_cast<char *>(Data);
  460. strncpy(DataStr, Value.c_str(), *DataSize);
  461. DataStr[*DataSize - 1] = '\0';
  462. *DataSize = strlen(DataStr);
  463. }
  464. return R;
  465. }
  466. //---------------------------------------------------------------------------
  467. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  468. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  469. {
  470. DebugAssert(Configuration != NULL);
  471. DebugAssert(Type == REG_SZ);
  472. DebugUsedParam(Type);
  473. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  474. DebugAssert(Storage != NULL);
  475. if (Storage != NULL)
  476. {
  477. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  478. Storage->WriteStringRaw(ValueName, Value);
  479. }
  480. return ERROR_SUCCESS;
  481. }
  482. //---------------------------------------------------------------------------
  483. long reg_close_winscp_key(HKEY Key)
  484. {
  485. DebugAssert(Configuration != NULL);
  486. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  487. if (Storage != NULL)
  488. {
  489. delete Storage;
  490. }
  491. return ERROR_SUCCESS;
  492. }
  493. //---------------------------------------------------------------------------
  494. TKeyType KeyType(UnicodeString FileName)
  495. {
  496. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  497. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  498. UTF8String UtfFileName = UTF8String(FileName);
  499. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  500. TKeyType Result = (TKeyType)key_type(KeyFile);
  501. filename_free(KeyFile);
  502. return Result;
  503. }
  504. //---------------------------------------------------------------------------
  505. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  506. {
  507. UTF8String UtfFileName = UTF8String(FileName);
  508. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  509. bool Result;
  510. char * CommentStr = NULL;
  511. switch (KeyType)
  512. {
  513. case ktSSH2:
  514. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  515. break;
  516. case ktOpenSSH:
  517. case ktSSHCom:
  518. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  519. break;
  520. default:
  521. DebugFail();
  522. Result = false;
  523. break;
  524. }
  525. if (CommentStr != NULL)
  526. {
  527. Comment = UnicodeString(AnsiString(CommentStr));
  528. // ktOpenSSH has no comment, PuTTY defaults to file path
  529. if (Comment == FileName)
  530. {
  531. Comment = ExtractFileName(FileName);
  532. }
  533. sfree(CommentStr);
  534. }
  535. return Result;
  536. }
  537. //---------------------------------------------------------------------------
  538. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  539. {
  540. UTF8String UtfFileName = UTF8String(FileName);
  541. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  542. AnsiString AnsiPassphrase = Passphrase;
  543. struct ssh2_userkey * Ssh2Key = NULL;
  544. const char * ErrorStr = NULL;
  545. switch (KeyType)
  546. {
  547. case ktSSH2:
  548. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  549. break;
  550. case ktOpenSSH:
  551. case ktSSHCom:
  552. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  553. break;
  554. default:
  555. DebugFail();
  556. break;
  557. }
  558. Shred(AnsiPassphrase);
  559. if (Ssh2Key == NULL)
  560. {
  561. UnicodeString Error = AnsiString(ErrorStr);
  562. // While theoretically we may get "unable to open key file" and
  563. // so we should check system error code,
  564. // we actully never get here unless we call KeyType previously
  565. // and handle ktUnopenable accordingly.
  566. throw Exception(Error);
  567. }
  568. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  569. {
  570. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  571. }
  572. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  573. }
  574. //---------------------------------------------------------------------------
  575. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  576. {
  577. AnsiString AnsiComment(Comment);
  578. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  579. sfree(Ssh2Key->comment);
  580. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  581. }
  582. //---------------------------------------------------------------------------
  583. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  584. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  585. {
  586. UTF8String UtfFileName = UTF8String(FileName);
  587. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  588. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  589. AnsiString AnsiPassphrase = Passphrase;
  590. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  591. switch (KeyType)
  592. {
  593. case ktSSH2:
  594. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  595. {
  596. int Error = errno;
  597. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  598. }
  599. break;
  600. default:
  601. DebugFail();
  602. break;
  603. }
  604. }
  605. //---------------------------------------------------------------------------
  606. void FreeKey(TPrivateKey * PrivateKey)
  607. {
  608. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  609. Ssh2Key->alg->freekey(Ssh2Key->data);
  610. sfree(Ssh2Key);
  611. }
  612. //---------------------------------------------------------------------------
  613. __int64 __fastcall ParseSize(UnicodeString SizeStr)
  614. {
  615. AnsiString AnsiSizeStr = AnsiString(SizeStr);
  616. return parse_blocksize64(AnsiSizeStr.c_str());
  617. }
  618. //---------------------------------------------------------------------------
  619. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  620. {
  621. static int has = -1;
  622. if (has < 0)
  623. {
  624. Conf * conf = conf_new();
  625. ssh_gss_liblist * List = NULL;
  626. try
  627. {
  628. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  629. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  630. filename_free(filename);
  631. List = ssh_gss_setup(conf);
  632. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  633. {
  634. ssh_gss_library * library = &List->libraries[Index];
  635. Ssh_gss_ctx ctx;
  636. memset(&ctx, 0, sizeof(ctx));
  637. has =
  638. ((library->acquire_cred(library, &ctx) == SSH_GSS_OK) &&
  639. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  640. }
  641. }
  642. __finally
  643. {
  644. ssh_gss_cleanup(List);
  645. conf_free(conf);
  646. }
  647. if (has < 0)
  648. {
  649. has = 0;
  650. }
  651. }
  652. return (has > 0);
  653. }
  654. //---------------------------------------------------------------------------
  655. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyType)
  656. {
  657. int Count = 0;
  658. const wchar_t NormalizedSeparator = L'-';
  659. const ssh_signkey ** SignKeys = get_hostkey_algs(&Count);
  660. for (int Index = 0; Index < Count; Index++)
  661. {
  662. const ssh_signkey * SignKey = SignKeys[Index];
  663. UnicodeString Name = UnicodeString(SignKey->name);
  664. if (StartsStr(Name + L" ", Fingerprint))
  665. {
  666. int LenStart = Name.Length() + 1;
  667. Fingerprint[LenStart] = NormalizedSeparator;
  668. int Space = Fingerprint.Pos(L" ");
  669. DebugAssert(IsNumber(Fingerprint.SubString(LenStart + 1, Space - LenStart - 1)));
  670. Fingerprint.Delete(LenStart + 1, Space - LenStart);
  671. Fingerprint = ReplaceChar(Fingerprint, L':', NormalizedSeparator);
  672. KeyType = UnicodeString(SignKey->keytype);
  673. return;
  674. }
  675. else if (StartsStr(Name + NormalizedSeparator, Fingerprint))
  676. {
  677. KeyType = UnicodeString(SignKey->keytype);
  678. return;
  679. }
  680. }
  681. }
  682. //---------------------------------------------------------------------------
  683. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  684. {
  685. UnicodeString KeyType; // unused
  686. DoNormalizeFingerprint(Fingerprint, KeyType);
  687. return Fingerprint;
  688. }
  689. //---------------------------------------------------------------------------
  690. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  691. {
  692. UnicodeString KeyType;
  693. DoNormalizeFingerprint(Fingerprint, KeyType);
  694. return KeyType;
  695. }
  696. //---------------------------------------------------------------------------
  697. UnicodeString __fastcall GetPuTTYVersion()
  698. {
  699. // "Release 0.64"
  700. // "Pre-release 0.65:2015-07-20.95501a1"
  701. UnicodeString Result = get_putty_version();
  702. // Skip "Release" (or "Pre-release")
  703. CutToChar(Result, L' ', true);
  704. return Result;
  705. }
  706. //---------------------------------------------------------------------------
  707. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  708. {
  709. unsigned char Digest[32];
  710. SHA256_Simple(Data, Size, Digest);
  711. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  712. return Result;
  713. }
  714. //---------------------------------------------------------------------------
  715. //---------------------------------------------------------------------------