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