PuttyIntf.cpp 31 KB

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