1
0

PuttyIntf.cpp 31 KB

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