PuttyIntf.cpp 32 KB

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