PuttyIntf.cpp 31 KB

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