PuttyIntf.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. Proxy_Socket ProxySocket = ((Proxy_Plug)plug)->proxy_socket;
  78. plug = ProxySocket->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 char * 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(data, datalen);
  111. }
  112. return 0;
  113. }
  114. //---------------------------------------------------------------------------
  115. int from_backend_untrusted(void * /*frontend*/, const char * /*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, const unsigned char * /*in*/, int /*inlen*/)
  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. Ssh2Key->alg->freekey(Ssh2Key->data);
  645. sfree(Ssh2Key->comment);
  646. sfree(Ssh2Key);
  647. }
  648. //---------------------------------------------------------------------------
  649. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  650. {
  651. RawByteString Result;
  652. UTF8String UtfFileName = UTF8String(FileName);
  653. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  654. try
  655. {
  656. char * AlgorithmStr = NULL;
  657. int PublicKeyLen = 0;
  658. char * CommentStr = NULL;
  659. const char * ErrorStr = NULL;
  660. unsigned char * PublicKeyPtr =
  661. ssh2_userkey_loadpub(KeyFile, &AlgorithmStr, &PublicKeyLen, &CommentStr, &ErrorStr);
  662. if (PublicKeyPtr == NULL)
  663. {
  664. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  665. throw Exception(Error);
  666. }
  667. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  668. sfree(AlgorithmStr);
  669. Comment = UnicodeString(AnsiString(CommentStr));
  670. sfree(CommentStr);
  671. Result = RawByteString(reinterpret_cast<char *>(PublicKeyPtr), PublicKeyLen);
  672. free(PublicKeyPtr);
  673. }
  674. __finally
  675. {
  676. filename_free(KeyFile);
  677. }
  678. return Result;
  679. }
  680. //---------------------------------------------------------------------------
  681. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  682. {
  683. UnicodeString Algorithm;
  684. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  685. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  686. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  687. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  688. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  689. return Result;
  690. }
  691. //---------------------------------------------------------------------------
  692. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  693. {
  694. static int has = -1;
  695. if (has < 0)
  696. {
  697. Conf * conf = conf_new();
  698. ssh_gss_liblist * List = NULL;
  699. try
  700. {
  701. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  702. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  703. filename_free(filename);
  704. List = ssh_gss_setup(conf, NULL);
  705. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  706. {
  707. ssh_gss_library * library = &List->libraries[Index];
  708. Ssh_gss_ctx ctx;
  709. memset(&ctx, 0, sizeof(ctx));
  710. has =
  711. ((library->acquire_cred(library, &ctx) == SSH_GSS_OK) &&
  712. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  713. }
  714. }
  715. __finally
  716. {
  717. ssh_gss_cleanup(List);
  718. conf_free(conf);
  719. }
  720. if (has < 0)
  721. {
  722. has = 0;
  723. }
  724. }
  725. return (has > 0);
  726. }
  727. //---------------------------------------------------------------------------
  728. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyType)
  729. {
  730. const wchar_t NormalizedSeparator = L'-';
  731. const int MaxCount = 10;
  732. const ssh_signkey * SignKeys[MaxCount];
  733. int Count = LENOF(SignKeys);
  734. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  735. // as the names have different number of dashes
  736. get_hostkey_algs(&Count, SignKeys);
  737. for (int Index = 0; Index < Count; Index++)
  738. {
  739. const ssh_signkey * SignKey = SignKeys[Index];
  740. UnicodeString Name = UnicodeString(SignKey->name);
  741. if (StartsStr(Name + L" ", Fingerprint))
  742. {
  743. int LenStart = Name.Length() + 1;
  744. Fingerprint[LenStart] = NormalizedSeparator;
  745. int Space = Fingerprint.Pos(L" ");
  746. // If not a number, it's an invalid input,
  747. // either something completelly wrong, or it can be OpenSSH base64 public key,
  748. // that got here from TPasteKeyHandler::Paste
  749. if (IsNumber(Fingerprint.SubString(LenStart + 1, Space - LenStart - 1)))
  750. {
  751. Fingerprint.Delete(LenStart + 1, Space - LenStart);
  752. // noop for SHA256 fingerprints
  753. Fingerprint = ReplaceChar(Fingerprint, L':', NormalizedSeparator);
  754. KeyType = UnicodeString(SignKey->keytype);
  755. return;
  756. }
  757. }
  758. else if (StartsStr(Name + NormalizedSeparator, Fingerprint))
  759. {
  760. KeyType = UnicodeString(SignKey->keytype);
  761. return;
  762. }
  763. }
  764. }
  765. //---------------------------------------------------------------------------
  766. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  767. {
  768. UnicodeString KeyType; // unused
  769. DoNormalizeFingerprint(Fingerprint, KeyType);
  770. return Fingerprint;
  771. }
  772. //---------------------------------------------------------------------------
  773. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  774. {
  775. UnicodeString KeyType;
  776. DoNormalizeFingerprint(Fingerprint, KeyType);
  777. return KeyType;
  778. }
  779. //---------------------------------------------------------------------------
  780. UnicodeString __fastcall GetPuTTYVersion()
  781. {
  782. // "Release 0.64"
  783. // "Pre-release 0.65:2015-07-20.95501a1"
  784. // "Development snapshot 2015-12-22.51465fa"
  785. UnicodeString Result = get_putty_version();
  786. // Skip "Release", "Pre-release", "Development snapshot"
  787. int P = Result.LastDelimiter(L" ");
  788. Result.Delete(1, P);
  789. return Result;
  790. }
  791. //---------------------------------------------------------------------------
  792. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  793. {
  794. unsigned char Digest[32];
  795. SHA256_Simple(Data, Size, Digest);
  796. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  797. return Result;
  798. }
  799. //---------------------------------------------------------------------------
  800. void __fastcall DllHijackingProtection()
  801. {
  802. dll_hijacking_protection();
  803. }
  804. //---------------------------------------------------------------------------
  805. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_signkey *& Algorithm)
  806. {
  807. UTF8String UtfLine = UTF8String(Line);
  808. char * AlgorithmName = NULL;
  809. int PubBlobLen = 0;
  810. char * CommentPtr = NULL;
  811. const char * ErrorStr = NULL;
  812. unsigned char * PubBlob = openssh_loadpub_line(UtfLine.c_str(), &AlgorithmName, &PubBlobLen, &CommentPtr, &ErrorStr);
  813. UnicodeString Result;
  814. if (PubBlob == NULL)
  815. {
  816. throw Exception(UnicodeString(ErrorStr));
  817. }
  818. else
  819. {
  820. try
  821. {
  822. Algorithm = find_pubkey_alg(AlgorithmName);
  823. if (Algorithm == NULL)
  824. {
  825. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  826. }
  827. void * Key = Algorithm->newkey(Algorithm, reinterpret_cast<const char*>(PubBlob), PubBlobLen);
  828. if (Key == NULL)
  829. {
  830. throw Exception(L"Invalid public key.");
  831. }
  832. char * FmtKey = Algorithm->fmtkey(Key);
  833. Result = UnicodeString(FmtKey);
  834. sfree(FmtKey);
  835. Algorithm->freekey(Key);
  836. }
  837. __finally
  838. {
  839. sfree(PubBlob);
  840. sfree(AlgorithmName);
  841. sfree(CommentPtr);
  842. }
  843. }
  844. return Result;
  845. }
  846. //---------------------------------------------------------------------------
  847. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  848. {
  849. UnicodeString Result;
  850. if (KeyType == ssh_dss.keytype)
  851. {
  852. Result = L"DSA";
  853. }
  854. else if (KeyType == ssh_rsa.keytype)
  855. {
  856. Result = L"RSA";
  857. }
  858. else if (KeyType == ssh_ecdsa_ed25519.keytype)
  859. {
  860. Result = L"Ed25519";
  861. }
  862. else if (KeyType == ssh_ecdsa_nistp256.keytype)
  863. {
  864. Result = L"ECDSA/nistp256";
  865. }
  866. else if (KeyType == ssh_ecdsa_nistp384.keytype)
  867. {
  868. Result = L"ECDSA/nistp384";
  869. }
  870. else if (KeyType == ssh_ecdsa_nistp521.keytype)
  871. {
  872. Result = L"ECDSA/nistp521";
  873. }
  874. else
  875. {
  876. DebugFail();
  877. Result = KeyType;
  878. }
  879. return Result;
  880. }
  881. //---------------------------------------------------------------------------
  882. bool IsOpenSSH(const UnicodeString & SshImplementation)
  883. {
  884. return
  885. // e.g. "OpenSSH_5.3"
  886. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  887. // Sun SSH is based on OpenSSH (suffers the same bugs)
  888. (SshImplementation.Pos(L"Sun_SSH") == 1);
  889. }
  890. //---------------------------------------------------------------------------
  891. TStrings * SshCipherList()
  892. {
  893. std::unique_ptr<TStrings> Result(new TStringList());
  894. // Same order as DefaultCipherList
  895. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  896. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  897. {
  898. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  899. {
  900. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->name);
  901. Result->Add(Name);
  902. }
  903. }
  904. return Result.release();
  905. }
  906. //---------------------------------------------------------------------------
  907. TStrings * SshKexList()
  908. {
  909. std::unique_ptr<TStrings> Result(new TStringList());
  910. // Same order as DefaultKexList
  911. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  912. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  913. {
  914. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  915. {
  916. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  917. Result->Add(Name);
  918. }
  919. }
  920. return Result.release();
  921. }
  922. //---------------------------------------------------------------------------
  923. TStrings * SshHostKeyList()
  924. {
  925. std::unique_ptr<TStrings> Result(new TStringList());
  926. const int MaxCount = 10;
  927. const ssh_signkey * SignKeys[MaxCount];
  928. int Count = LENOF(SignKeys);
  929. get_hostkey_algs(&Count, SignKeys);
  930. for (int Index = 0; Index < Count; Index++)
  931. {
  932. const ssh_signkey * SignKey = SignKeys[Index];
  933. UnicodeString Name = UnicodeString(SignKey->name);
  934. Result->Add(Name);
  935. }
  936. return Result.release();
  937. }
  938. //---------------------------------------------------------------------------
  939. TStrings * SshMacList()
  940. {
  941. std::unique_ptr<TStrings> Result(new TStringList());
  942. const struct ssh_mac ** Macs = NULL;
  943. int Count = 0;
  944. get_macs(&Count, &Macs);
  945. for (int Index = 0; Index < Count; Index++)
  946. {
  947. UnicodeString Name = UnicodeString(Macs[Index]->name);
  948. Result->Add(Name);
  949. }
  950. return Result.release();
  951. }
  952. //---------------------------------------------------------------------------
  953. //---------------------------------------------------------------------------