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 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 (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. };
  357. //---------------------------------------------------------------------------
  358. ScpSeat::ScpSeat(TSecureShell * ASecureShell)
  359. {
  360. SecureShell = ASecureShell;
  361. vt = &ScpSeatVtable;
  362. }
  363. //---------------------------------------------------------------------------
  364. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  365. {
  366. long R;
  367. DebugAssert(Configuration != NULL);
  368. DebugAssert(Key == HKEY_CURRENT_USER);
  369. DebugUsedParam(Key);
  370. UnicodeString RegKey = SubKey;
  371. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  372. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  373. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  374. if (!RegKey.IsEmpty())
  375. {
  376. DebugAssert(RegKey[1] == L'\\');
  377. RegKey.Delete(1, 1);
  378. }
  379. if (RegKey.IsEmpty())
  380. {
  381. *Result = static_cast<HKEY>(NULL);
  382. R = ERROR_SUCCESS;
  383. }
  384. else
  385. {
  386. // we expect this to be called only from verify_host_key() or store_host_key()
  387. DebugAssert(RegKey == L"SshHostKeys");
  388. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  389. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  390. if (Storage->OpenSubKey(RegKey, CanCreate))
  391. {
  392. *Result = reinterpret_cast<HKEY>(Storage);
  393. R = ERROR_SUCCESS;
  394. }
  395. else
  396. {
  397. delete Storage;
  398. R = ERROR_CANTOPEN;
  399. }
  400. }
  401. return R;
  402. }
  403. //---------------------------------------------------------------------------
  404. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  405. {
  406. return OpenWinSCPKey(Key, SubKey, Result, false);
  407. }
  408. //---------------------------------------------------------------------------
  409. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  410. {
  411. return OpenWinSCPKey(Key, SubKey, Result, true);
  412. }
  413. //---------------------------------------------------------------------------
  414. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  415. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  416. {
  417. long R;
  418. DebugAssert(Configuration != NULL);
  419. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  420. AnsiString Value;
  421. if (Storage == NULL)
  422. {
  423. if (UnicodeString(ValueName) == L"RandSeedFile")
  424. {
  425. Value = AnsiString(Configuration->RandomSeedFileName);
  426. R = ERROR_SUCCESS;
  427. }
  428. else
  429. {
  430. DebugFail();
  431. R = ERROR_READ_FAULT;
  432. }
  433. }
  434. else
  435. {
  436. if (Storage->ValueExists(ValueName))
  437. {
  438. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  439. R = ERROR_SUCCESS;
  440. }
  441. else
  442. {
  443. R = ERROR_READ_FAULT;
  444. }
  445. }
  446. if (R == ERROR_SUCCESS)
  447. {
  448. DebugAssert(Type != NULL);
  449. *Type = REG_SZ;
  450. char * DataStr = reinterpret_cast<char *>(Data);
  451. strncpy(DataStr, Value.c_str(), *DataSize);
  452. DataStr[*DataSize - 1] = '\0';
  453. *DataSize = strlen(DataStr);
  454. }
  455. return R;
  456. }
  457. //---------------------------------------------------------------------------
  458. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  459. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  460. {
  461. DebugAssert(Configuration != NULL);
  462. DebugAssert(Type == REG_SZ);
  463. DebugUsedParam(Type);
  464. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  465. DebugAssert(Storage != NULL);
  466. if (Storage != NULL)
  467. {
  468. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  469. Storage->WriteStringRaw(ValueName, Value);
  470. }
  471. return ERROR_SUCCESS;
  472. }
  473. //---------------------------------------------------------------------------
  474. long reg_close_winscp_key(HKEY Key)
  475. {
  476. DebugAssert(Configuration != NULL);
  477. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  478. if (Storage != NULL)
  479. {
  480. delete Storage;
  481. }
  482. return ERROR_SUCCESS;
  483. }
  484. //---------------------------------------------------------------------------
  485. TKeyType KeyType(UnicodeString FileName)
  486. {
  487. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  488. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  489. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  490. UTF8String UtfFileName = UTF8String(FileName);
  491. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  492. TKeyType Result = (TKeyType)key_type(KeyFile);
  493. filename_free(KeyFile);
  494. return Result;
  495. }
  496. //---------------------------------------------------------------------------
  497. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  498. {
  499. UTF8String UtfFileName = UTF8String(FileName);
  500. bool Result;
  501. char * CommentStr = NULL;
  502. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  503. try
  504. {
  505. switch (KeyType)
  506. {
  507. case ktSSH2:
  508. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  509. break;
  510. case ktOpenSSHPEM:
  511. case ktOpenSSHNew:
  512. case ktSSHCom:
  513. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  514. break;
  515. default:
  516. DebugFail();
  517. Result = false;
  518. break;
  519. }
  520. }
  521. __finally
  522. {
  523. filename_free(KeyFile);
  524. }
  525. if (CommentStr != NULL)
  526. {
  527. Comment = UnicodeString(AnsiString(CommentStr));
  528. // ktOpenSSH has no comment, PuTTY defaults to file path
  529. if (Comment == FileName)
  530. {
  531. Comment = ExtractFileName(FileName);
  532. }
  533. sfree(CommentStr);
  534. }
  535. return Result;
  536. }
  537. //---------------------------------------------------------------------------
  538. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  539. {
  540. UTF8String UtfFileName = UTF8String(FileName);
  541. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  542. struct ssh2_userkey * Ssh2Key = NULL;
  543. const char * ErrorStr = NULL;
  544. AnsiString AnsiPassphrase = Passphrase;
  545. try
  546. {
  547. switch (KeyType)
  548. {
  549. case ktSSH2:
  550. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  551. break;
  552. case ktOpenSSHPEM:
  553. case ktOpenSSHNew:
  554. case ktSSHCom:
  555. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  556. break;
  557. default:
  558. DebugFail();
  559. break;
  560. }
  561. }
  562. __finally
  563. {
  564. Shred(AnsiPassphrase);
  565. filename_free(KeyFile);
  566. }
  567. if (Ssh2Key == NULL)
  568. {
  569. UnicodeString Error = AnsiString(ErrorStr);
  570. // While theoretically we may get "unable to open key file" and
  571. // so we should check system error code,
  572. // we actully never get here unless we call KeyType previously
  573. // and handle ktUnopenable accordingly.
  574. throw Exception(Error);
  575. }
  576. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  577. {
  578. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  579. }
  580. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  581. }
  582. //---------------------------------------------------------------------------
  583. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  584. {
  585. AnsiString AnsiComment(Comment);
  586. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  587. sfree(Ssh2Key->comment);
  588. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  589. }
  590. //---------------------------------------------------------------------------
  591. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  592. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  593. {
  594. UTF8String UtfFileName = UTF8String(FileName);
  595. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  596. try
  597. {
  598. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  599. AnsiString AnsiPassphrase = Passphrase;
  600. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  601. switch (KeyType)
  602. {
  603. case ktSSH2:
  604. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  605. {
  606. int Error = errno;
  607. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  608. }
  609. break;
  610. default:
  611. DebugFail();
  612. break;
  613. }
  614. }
  615. __finally
  616. {
  617. filename_free(KeyFile);
  618. }
  619. }
  620. //---------------------------------------------------------------------------
  621. void FreeKey(TPrivateKey * PrivateKey)
  622. {
  623. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  624. ssh_key_free(Ssh2Key->key);
  625. sfree(Ssh2Key);
  626. }
  627. //---------------------------------------------------------------------------
  628. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  629. {
  630. RawByteString Result;
  631. UTF8String UtfFileName = UTF8String(FileName);
  632. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  633. try
  634. {
  635. char * AlgorithmStr = NULL;
  636. char * CommentStr = NULL;
  637. const char * ErrorStr = NULL;
  638. strbuf * PublicKeyBuf = strbuf_new();
  639. if (!ssh2_userkey_loadpub(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  640. {
  641. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  642. throw Exception(Error);
  643. }
  644. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  645. sfree(AlgorithmStr);
  646. Comment = UnicodeString(AnsiString(CommentStr));
  647. sfree(CommentStr);
  648. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  649. strbuf_free(PublicKeyBuf);
  650. }
  651. __finally
  652. {
  653. filename_free(KeyFile);
  654. }
  655. return Result;
  656. }
  657. //---------------------------------------------------------------------------
  658. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  659. {
  660. UnicodeString Algorithm;
  661. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  662. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  663. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  664. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  665. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  666. return Result;
  667. }
  668. //---------------------------------------------------------------------------
  669. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  670. {
  671. static int has = -1;
  672. if (has < 0)
  673. {
  674. Conf * conf = conf_new();
  675. ssh_gss_liblist * List = NULL;
  676. try
  677. {
  678. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  679. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  680. filename_free(filename);
  681. List = ssh_gss_setup(conf, NULL);
  682. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  683. {
  684. ssh_gss_library * library = &List->libraries[Index];
  685. Ssh_gss_ctx ctx;
  686. memset(&ctx, 0, sizeof(ctx));
  687. has =
  688. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  689. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  690. }
  691. }
  692. __finally
  693. {
  694. ssh_gss_cleanup(List);
  695. conf_free(conf);
  696. }
  697. if (has < 0)
  698. {
  699. has = 0;
  700. }
  701. }
  702. return (has > 0);
  703. }
  704. //---------------------------------------------------------------------------
  705. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyType)
  706. {
  707. const wchar_t NormalizedSeparator = L'-';
  708. const int MaxCount = 10;
  709. const ssh_keyalg * SignKeys[MaxCount];
  710. int Count = LENOF(SignKeys);
  711. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  712. // as the names have different number of dashes
  713. get_hostkey_algs(&Count, SignKeys);
  714. for (int Index = 0; Index < Count; Index++)
  715. {
  716. const ssh_keyalg * SignKey = SignKeys[Index];
  717. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  718. if (StartsStr(Name + L" ", Fingerprint))
  719. {
  720. int LenStart = Name.Length() + 1;
  721. Fingerprint[LenStart] = NormalizedSeparator;
  722. int Space = Fingerprint.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(Fingerprint.SubString(LenStart + 1, Space - LenStart - 1)))
  727. {
  728. Fingerprint.Delete(LenStart + 1, Space - LenStart);
  729. // noop for SHA256 fingerprints
  730. Fingerprint = ReplaceChar(Fingerprint, L':', NormalizedSeparator);
  731. KeyType = UnicodeString(SignKey->cache_id);
  732. return;
  733. }
  734. }
  735. else if (StartsStr(Name + NormalizedSeparator, Fingerprint))
  736. {
  737. KeyType = UnicodeString(SignKey->cache_id);
  738. return;
  739. }
  740. }
  741. }
  742. //---------------------------------------------------------------------------
  743. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  744. {
  745. UnicodeString KeyType; // unused
  746. DoNormalizeFingerprint(Fingerprint, KeyType);
  747. return Fingerprint;
  748. }
  749. //---------------------------------------------------------------------------
  750. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  751. {
  752. UnicodeString KeyType;
  753. DoNormalizeFingerprint(Fingerprint, KeyType);
  754. return KeyType;
  755. }
  756. //---------------------------------------------------------------------------
  757. UnicodeString __fastcall GetPuTTYVersion()
  758. {
  759. // "Release 0.64"
  760. // "Pre-release 0.65:2015-07-20.95501a1"
  761. // "Development snapshot 2015-12-22.51465fa"
  762. UnicodeString Result = get_putty_version();
  763. // Skip "Release", "Pre-release", "Development snapshot"
  764. int P = Result.LastDelimiter(L" ");
  765. Result.Delete(1, P);
  766. return Result;
  767. }
  768. //---------------------------------------------------------------------------
  769. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  770. {
  771. unsigned char Digest[32];
  772. SHA256_Simple(Data, Size, Digest);
  773. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  774. return Result;
  775. }
  776. //---------------------------------------------------------------------------
  777. void __fastcall DllHijackingProtection()
  778. {
  779. dll_hijacking_protection();
  780. }
  781. //---------------------------------------------------------------------------
  782. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  783. {
  784. UTF8String UtfLine = UTF8String(Line);
  785. char * AlgorithmName = NULL;
  786. char * CommentPtr = NULL;
  787. const char * ErrorStr = NULL;
  788. strbuf * PubBlobBuf = strbuf_new();
  789. UnicodeString Result;
  790. if (!openssh_loadpub_line(UtfLine.c_str(), &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  791. {
  792. throw Exception(UnicodeString(ErrorStr));
  793. }
  794. else
  795. {
  796. try
  797. {
  798. Algorithm = find_pubkey_alg(AlgorithmName);
  799. if (Algorithm == NULL)
  800. {
  801. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  802. }
  803. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  804. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  805. if (Key == NULL)
  806. {
  807. throw Exception(L"Invalid public key.");
  808. }
  809. char * FmtKey = Algorithm->cache_str(Key);
  810. Result = UnicodeString(FmtKey);
  811. sfree(FmtKey);
  812. Algorithm->freekey(Key);
  813. }
  814. __finally
  815. {
  816. strbuf_free(PubBlobBuf);
  817. sfree(AlgorithmName);
  818. sfree(CommentPtr);
  819. }
  820. }
  821. return Result;
  822. }
  823. //---------------------------------------------------------------------------
  824. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  825. {
  826. UnicodeString Result;
  827. if (KeyType == ssh_dss.cache_id)
  828. {
  829. Result = L"DSA";
  830. }
  831. else if (KeyType == ssh_rsa.cache_id)
  832. {
  833. Result = L"RSA";
  834. }
  835. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  836. {
  837. Result = L"Ed25519";
  838. }
  839. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  840. {
  841. Result = L"ECDSA/nistp256";
  842. }
  843. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  844. {
  845. Result = L"ECDSA/nistp384";
  846. }
  847. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  848. {
  849. Result = L"ECDSA/nistp521";
  850. }
  851. else
  852. {
  853. DebugFail();
  854. Result = KeyType;
  855. }
  856. return Result;
  857. }
  858. //---------------------------------------------------------------------------
  859. bool IsOpenSSH(const UnicodeString & SshImplementation)
  860. {
  861. return
  862. // e.g. "OpenSSH_5.3"
  863. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  864. // Sun SSH is based on OpenSSH (suffers the same bugs)
  865. (SshImplementation.Pos(L"Sun_SSH") == 1);
  866. }
  867. //---------------------------------------------------------------------------
  868. TStrings * SshCipherList()
  869. {
  870. std::unique_ptr<TStrings> Result(new TStringList());
  871. // Same order as DefaultCipherList
  872. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  873. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  874. {
  875. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  876. {
  877. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->ssh2_id);
  878. Result->Add(Name);
  879. }
  880. }
  881. return Result.release();
  882. }
  883. //---------------------------------------------------------------------------
  884. TStrings * SshKexList()
  885. {
  886. std::unique_ptr<TStrings> Result(new TStringList());
  887. // Same order as DefaultKexList
  888. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  889. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  890. {
  891. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  892. {
  893. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  894. Result->Add(Name);
  895. }
  896. }
  897. return Result.release();
  898. }
  899. //---------------------------------------------------------------------------
  900. TStrings * SshHostKeyList()
  901. {
  902. std::unique_ptr<TStrings> Result(new TStringList());
  903. const int MaxCount = 10;
  904. const ssh_keyalg * SignKeys[MaxCount];
  905. int Count = LENOF(SignKeys);
  906. get_hostkey_algs(&Count, SignKeys);
  907. for (int Index = 0; Index < Count; Index++)
  908. {
  909. const ssh_keyalg * SignKey = SignKeys[Index];
  910. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  911. Result->Add(Name);
  912. }
  913. return Result.release();
  914. }
  915. //---------------------------------------------------------------------------
  916. TStrings * SshMacList()
  917. {
  918. std::unique_ptr<TStrings> Result(new TStringList());
  919. const struct ssh2_macalg ** Macs = NULL;
  920. int Count = 0;
  921. get_macs(&Count, &Macs);
  922. for (int Index = 0; Index < Count; Index++)
  923. {
  924. UnicodeString Name = UnicodeString(Macs[Index]->name);
  925. Result->Add(Name);
  926. }
  927. return Result.release();
  928. }
  929. //---------------------------------------------------------------------------
  930. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  931. {
  932. return UnicodeString(UTF8String(Cipher->vt->text_name));
  933. }
  934. //---------------------------------------------------------------------------
  935. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  936. {
  937. UnicodeString Result;
  938. if (Compressor != NULL)
  939. {
  940. Result = UnicodeString(UTF8String(Compressor->vt->name));
  941. }
  942. return Result;
  943. }
  944. //---------------------------------------------------------------------------
  945. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  946. {
  947. UnicodeString Result;
  948. if (Decompressor != NULL)
  949. {
  950. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  951. }
  952. return Result;
  953. }
  954. //---------------------------------------------------------------------------
  955. //---------------------------------------------------------------------------