PuttyIntf.cpp 32 KB

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