PuttyIntf.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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, 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, 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, char * keytype,
  216. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  217. void * /*ctx*/)
  218. {
  219. DebugAssert(frontend != NULL);
  220. ((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 askalg(void * frontend, const char * algtype, const char * algname,
  226. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  227. {
  228. DebugAssert(frontend != NULL);
  229. ((TSecureShell *)frontend)->AskAlg(algtype, algname);
  230. // We should return 0 when alg was not confirmed, we throw exception instead.
  231. return 1;
  232. }
  233. //---------------------------------------------------------------------------
  234. void old_keyfile_warning(void)
  235. {
  236. // no reference to TSecureShell instace available
  237. }
  238. //---------------------------------------------------------------------------
  239. void display_banner(void * frontend, const char * banner, int size)
  240. {
  241. DebugAssert(frontend);
  242. UnicodeString Banner(UTF8String(banner, size));
  243. ((TSecureShell *)frontend)->DisplayBanner(Banner);
  244. }
  245. //---------------------------------------------------------------------------
  246. static void SSHFatalError(const char * Format, va_list Param)
  247. {
  248. char Buf[200];
  249. vsnprintf(Buf, LENOF(Buf), Format, Param);
  250. Buf[LENOF(Buf) - 1] = '\0';
  251. // Only few calls from putty\winnet.c might be connected with specific
  252. // TSecureShell. Otherwise called only for really fatal errors
  253. // like 'out of memory' from putty\ssh.c.
  254. throw ESshFatal(NULL, Buf);
  255. }
  256. //---------------------------------------------------------------------------
  257. void fatalbox(char * fmt, ...)
  258. {
  259. va_list Param;
  260. va_start(Param, fmt);
  261. SSHFatalError(fmt, Param);
  262. va_end(Param);
  263. }
  264. //---------------------------------------------------------------------------
  265. void modalfatalbox(char * fmt, ...)
  266. {
  267. va_list Param;
  268. va_start(Param, fmt);
  269. SSHFatalError(fmt, Param);
  270. va_end(Param);
  271. }
  272. //---------------------------------------------------------------------------
  273. void nonfatal(char * fmt, ...)
  274. {
  275. va_list Param;
  276. va_start(Param, fmt);
  277. SSHFatalError(fmt, Param);
  278. va_end(Param);
  279. }
  280. //---------------------------------------------------------------------------
  281. void cleanup_exit(int /*code*/)
  282. {
  283. throw ESshFatal(NULL, "");
  284. }
  285. //---------------------------------------------------------------------------
  286. int askappend(void * /*frontend*/, Filename * /*filename*/,
  287. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  288. {
  289. // this is called from logging.c of putty, which is never used with WinSCP
  290. DebugFail();
  291. return 0;
  292. }
  293. //---------------------------------------------------------------------------
  294. void ldisc_send(void * /*handle*/, char * /*buf*/, int len, int /*interactive*/)
  295. {
  296. // This is only here because of the calls to ldisc_send(NULL,
  297. // 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
  298. // as an ldisc. So if we get called with any real data, I want
  299. // to know about it.
  300. DebugAssert(len == 0);
  301. DebugUsedParam(len);
  302. }
  303. //---------------------------------------------------------------------------
  304. void agent_schedule_callback(void (* /*callback*/)(void *, void *, int),
  305. void * /*callback_ctx*/, void * /*data*/, int /*len*/)
  306. {
  307. DebugFail();
  308. }
  309. //---------------------------------------------------------------------------
  310. void notify_remote_exit(void * /*frontend*/)
  311. {
  312. // nothing
  313. }
  314. //---------------------------------------------------------------------------
  315. void update_specials_menu(void * /*frontend*/)
  316. {
  317. // nothing
  318. }
  319. //---------------------------------------------------------------------------
  320. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  321. {
  322. return ticks + GetTickCount();
  323. }
  324. //---------------------------------------------------------------------------
  325. void expire_timer_context(void * /*ctx*/)
  326. {
  327. // nothing
  328. }
  329. //---------------------------------------------------------------------------
  330. Pinger pinger_new(Conf * /*conf*/, Backend * /*back*/, void * /*backhandle*/)
  331. {
  332. return NULL;
  333. }
  334. //---------------------------------------------------------------------------
  335. void pinger_reconfig(Pinger /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  336. {
  337. // nothing
  338. }
  339. //---------------------------------------------------------------------------
  340. void pinger_free(Pinger /*pinger*/)
  341. {
  342. // nothing
  343. }
  344. //---------------------------------------------------------------------------
  345. void set_busy_status(void * /*frontend*/, int /*status*/)
  346. {
  347. // nothing
  348. }
  349. //---------------------------------------------------------------------------
  350. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  351. {
  352. // nothing, therefore no auth.
  353. }
  354. //---------------------------------------------------------------------------
  355. // Based on PuTTY's settings.c
  356. char * get_remote_username(Conf * conf)
  357. {
  358. char * username = conf_get_str(conf, CONF_username);
  359. char * result;
  360. if (*username)
  361. {
  362. result = dupstr(username);
  363. }
  364. else
  365. {
  366. result = NULL;
  367. }
  368. return result;
  369. }
  370. //---------------------------------------------------------------------------
  371. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  372. {
  373. long R;
  374. DebugAssert(Configuration != NULL);
  375. DebugAssert(Key == HKEY_CURRENT_USER);
  376. DebugUsedParam(Key);
  377. UnicodeString RegKey = SubKey;
  378. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  379. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  380. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  381. if (!RegKey.IsEmpty())
  382. {
  383. DebugAssert(RegKey[1] == L'\\');
  384. RegKey.Delete(1, 1);
  385. }
  386. if (RegKey.IsEmpty())
  387. {
  388. *Result = static_cast<HKEY>(NULL);
  389. R = ERROR_SUCCESS;
  390. }
  391. else
  392. {
  393. // we expect this to be called only from verify_host_key() or store_host_key()
  394. DebugAssert(RegKey == L"SshHostKeys");
  395. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  396. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  397. if (Storage->OpenSubKey(RegKey, CanCreate))
  398. {
  399. *Result = reinterpret_cast<HKEY>(Storage);
  400. R = ERROR_SUCCESS;
  401. }
  402. else
  403. {
  404. delete Storage;
  405. R = ERROR_CANTOPEN;
  406. }
  407. }
  408. return R;
  409. }
  410. //---------------------------------------------------------------------------
  411. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  412. {
  413. return OpenWinSCPKey(Key, SubKey, Result, false);
  414. }
  415. //---------------------------------------------------------------------------
  416. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  417. {
  418. return OpenWinSCPKey(Key, SubKey, Result, true);
  419. }
  420. //---------------------------------------------------------------------------
  421. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  422. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  423. {
  424. long R;
  425. DebugAssert(Configuration != NULL);
  426. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  427. AnsiString Value;
  428. if (Storage == NULL)
  429. {
  430. if (UnicodeString(ValueName) == L"RandSeedFile")
  431. {
  432. Value = AnsiString(Configuration->RandomSeedFileName);
  433. R = ERROR_SUCCESS;
  434. }
  435. else
  436. {
  437. DebugFail();
  438. R = ERROR_READ_FAULT;
  439. }
  440. }
  441. else
  442. {
  443. if (Storage->ValueExists(ValueName))
  444. {
  445. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  446. R = ERROR_SUCCESS;
  447. }
  448. else
  449. {
  450. R = ERROR_READ_FAULT;
  451. }
  452. }
  453. if (R == ERROR_SUCCESS)
  454. {
  455. DebugAssert(Type != NULL);
  456. *Type = REG_SZ;
  457. char * DataStr = reinterpret_cast<char *>(Data);
  458. strncpy(DataStr, Value.c_str(), *DataSize);
  459. DataStr[*DataSize - 1] = '\0';
  460. *DataSize = strlen(DataStr);
  461. }
  462. return R;
  463. }
  464. //---------------------------------------------------------------------------
  465. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  466. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  467. {
  468. DebugAssert(Configuration != NULL);
  469. DebugAssert(Type == REG_SZ);
  470. DebugUsedParam(Type);
  471. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  472. DebugAssert(Storage != NULL);
  473. if (Storage != NULL)
  474. {
  475. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  476. Storage->WriteStringRaw(ValueName, Value);
  477. }
  478. return ERROR_SUCCESS;
  479. }
  480. //---------------------------------------------------------------------------
  481. long reg_close_winscp_key(HKEY Key)
  482. {
  483. DebugAssert(Configuration != NULL);
  484. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  485. if (Storage != NULL)
  486. {
  487. delete Storage;
  488. }
  489. return ERROR_SUCCESS;
  490. }
  491. //---------------------------------------------------------------------------
  492. TKeyType KeyType(UnicodeString FileName)
  493. {
  494. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  495. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  496. UTF8String UtfFileName = UTF8String(FileName);
  497. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  498. TKeyType Result = (TKeyType)key_type(KeyFile);
  499. filename_free(KeyFile);
  500. return Result;
  501. }
  502. //---------------------------------------------------------------------------
  503. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  504. {
  505. UTF8String UtfFileName = UTF8String(FileName);
  506. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  507. bool Result;
  508. char * CommentStr = NULL;
  509. switch (KeyType)
  510. {
  511. case ktSSH2:
  512. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  513. break;
  514. case ktOpenSSH:
  515. case ktSSHCom:
  516. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  517. break;
  518. default:
  519. DebugFail();
  520. Result = false;
  521. break;
  522. }
  523. if (CommentStr != NULL)
  524. {
  525. Comment = UnicodeString(AnsiString(CommentStr));
  526. // ktOpenSSH has no comment, PuTTY defaults to file path
  527. if (Comment == FileName)
  528. {
  529. Comment = ExtractFileName(FileName);
  530. }
  531. sfree(CommentStr);
  532. }
  533. return Result;
  534. }
  535. //---------------------------------------------------------------------------
  536. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  537. {
  538. UTF8String UtfFileName = UTF8String(FileName);
  539. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  540. AnsiString AnsiPassphrase = Passphrase;
  541. struct ssh2_userkey * Ssh2Key = NULL;
  542. const char * ErrorStr = NULL;
  543. switch (KeyType)
  544. {
  545. case ktSSH2:
  546. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  547. break;
  548. case ktOpenSSH:
  549. case ktSSHCom:
  550. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  551. break;
  552. default:
  553. DebugFail();
  554. break;
  555. }
  556. Shred(AnsiPassphrase);
  557. if (Ssh2Key == NULL)
  558. {
  559. UnicodeString Error = AnsiString(ErrorStr);
  560. // While theoretically we may get "unable to open key file" and
  561. // so we should check system error code,
  562. // we actully never get here unless we call KeyType previously
  563. // and handle ktUnopenable accordingly.
  564. throw Exception(Error);
  565. }
  566. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  567. {
  568. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  569. }
  570. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  571. }
  572. //---------------------------------------------------------------------------
  573. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  574. {
  575. AnsiString AnsiComment(Comment);
  576. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  577. sfree(Ssh2Key->comment);
  578. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  579. }
  580. //---------------------------------------------------------------------------
  581. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  582. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  583. {
  584. UTF8String UtfFileName = UTF8String(FileName);
  585. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  586. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  587. AnsiString AnsiPassphrase = Passphrase;
  588. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  589. switch (KeyType)
  590. {
  591. case ktSSH2:
  592. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  593. {
  594. int Error = errno;
  595. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  596. }
  597. break;
  598. default:
  599. DebugFail();
  600. break;
  601. }
  602. }
  603. //---------------------------------------------------------------------------
  604. void FreeKey(TPrivateKey * PrivateKey)
  605. {
  606. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  607. Ssh2Key->alg->freekey(Ssh2Key->data);
  608. sfree(Ssh2Key);
  609. }
  610. //---------------------------------------------------------------------------
  611. UnicodeString KeyTypeName(TKeyType KeyType)
  612. {
  613. return key_type_to_str(KeyType);
  614. }
  615. //---------------------------------------------------------------------------
  616. __int64 __fastcall ParseSize(UnicodeString SizeStr)
  617. {
  618. AnsiString AnsiSizeStr = AnsiString(SizeStr);
  619. return parse_blocksize64(AnsiSizeStr.c_str());
  620. }
  621. //---------------------------------------------------------------------------
  622. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  623. {
  624. static int has = -1;
  625. if (has < 0)
  626. {
  627. Conf * conf = conf_new();
  628. ssh_gss_liblist * List = NULL;
  629. try
  630. {
  631. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  632. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  633. filename_free(filename);
  634. List = ssh_gss_setup(conf);
  635. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  636. {
  637. ssh_gss_library * library = &List->libraries[Index];
  638. Ssh_gss_ctx ctx;
  639. memset(&ctx, 0, sizeof(ctx));
  640. has =
  641. ((library->acquire_cred(library, &ctx) == SSH_GSS_OK) &&
  642. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  643. }
  644. }
  645. __finally
  646. {
  647. ssh_gss_cleanup(List);
  648. conf_free(conf);
  649. }
  650. if (has < 0)
  651. {
  652. has = 0;
  653. }
  654. }
  655. return (has > 0);
  656. }
  657. //---------------------------------------------------------------------------
  658. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  659. {
  660. UnicodeString DssName = UnicodeString(ssh_dss.name) + L" ";
  661. UnicodeString RsaName = UnicodeString(ssh_rsa.name) + L" ";
  662. bool IsFingerprint = false;
  663. int LenStart;
  664. if (StartsStr(DssName, Fingerprint))
  665. {
  666. LenStart = DssName.Length() + 1;
  667. IsFingerprint = true;
  668. }
  669. else if (StartsStr(RsaName, Fingerprint))
  670. {
  671. LenStart = RsaName.Length() + 1;
  672. IsFingerprint = true;
  673. }
  674. if (IsFingerprint)
  675. {
  676. Fingerprint[LenStart - 1] = L'-';
  677. int Space = Fingerprint.Pos(L" ");
  678. DebugAssert(IsNumber(Fingerprint.SubString(LenStart, Space - LenStart)));
  679. Fingerprint.Delete(LenStart, Space - LenStart + 1);
  680. Fingerprint = ReplaceChar(Fingerprint, L':', L'-');
  681. }
  682. return Fingerprint;
  683. }
  684. //---------------------------------------------------------------------------
  685. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  686. {
  687. Fingerprint = NormalizeFingerprint(Fingerprint);
  688. UnicodeString Type;
  689. if (StartsStr(UnicodeString(ssh_dss.name) + L"-", Fingerprint))
  690. {
  691. Type = ssh_dss.keytype;
  692. }
  693. else if (StartsStr(UnicodeString(ssh_rsa.name) + L"-", Fingerprint))
  694. {
  695. Type = ssh_rsa.keytype;
  696. }
  697. return Type;
  698. }
  699. //---------------------------------------------------------------------------
  700. UnicodeString __fastcall GetPuTTYVersion()
  701. {
  702. // "Release 0.64"
  703. // "Pre-release 0.65:2015-07-20.95501a1"
  704. UnicodeString Result = get_putty_version();
  705. // Skip "Release" (or "Pre-release")
  706. CutToChar(Result, L' ', true);
  707. return Result;
  708. }
  709. //---------------------------------------------------------------------------
  710. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  711. {
  712. unsigned char Digest[32];
  713. SHA256_Simple(Data, Size, Digest);
  714. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  715. return Result;
  716. }
  717. //---------------------------------------------------------------------------
  718. //---------------------------------------------------------------------------