PuttyIntf.cpp 24 KB

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