PuttyIntf.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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. bool HadRandomSeed;
  20. char appname_[50];
  21. const char *const appname = appname_;
  22. extern const bool share_can_be_downstream = false;
  23. extern const bool share_can_be_upstream = false;
  24. //---------------------------------------------------------------------------
  25. extern "C"
  26. {
  27. #include <winstuff.h>
  28. }
  29. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  30. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  31. const UnicodeString OriginalPuttyExecutable("putty.exe");
  32. const UnicodeString KittyExecutable("kitty.exe");
  33. const UnicodeString PuttyKeyExt(L"ppk");
  34. //---------------------------------------------------------------------------
  35. void __fastcall PuttyInitialize()
  36. {
  37. SaveRandomSeed = true;
  38. InitializeCriticalSection(&putty_section);
  39. HadRandomSeed = FileExists(ApiPath(Configuration->RandomSeedFileName));
  40. // make sure random generator is initialised, so random_save_seed()
  41. // in destructor can proceed
  42. random_ref();
  43. flags = FLAG_VERBOSE | FLAG_SYNCAGENT; // verbose log
  44. sk_init();
  45. AnsiString VersionString = AnsiString(SshVersionString());
  46. DebugAssert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  47. strcpy(sshver, VersionString.c_str());
  48. AnsiString AppName = AnsiString(AppNameString());
  49. DebugAssert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  50. strcpy(appname_, AppName.c_str());
  51. }
  52. //---------------------------------------------------------------------------
  53. static bool DeleteRandomSeedOnExit()
  54. {
  55. return !HadRandomSeed && !SaveRandomSeed;
  56. }
  57. //---------------------------------------------------------------------------
  58. void __fastcall PuttyFinalize()
  59. {
  60. if (SaveRandomSeed)
  61. {
  62. random_save_seed();
  63. }
  64. random_unref();
  65. // random_ref in PuttyInitialize creates the seed file. Delete it, if we didn't want to create it.
  66. if (DeleteRandomSeedOnExit())
  67. {
  68. DeleteFile(ApiPath(Configuration->RandomSeedFileName));
  69. }
  70. sk_cleanup();
  71. win_misc_cleanup();
  72. win_secur_cleanup();
  73. ec_cleanup();
  74. DeleteCriticalSection(&putty_section);
  75. }
  76. //---------------------------------------------------------------------------
  77. void __fastcall DontSaveRandomSeed()
  78. {
  79. SaveRandomSeed = false;
  80. }
  81. //---------------------------------------------------------------------------
  82. bool RandomSeedExists()
  83. {
  84. return
  85. !DeleteRandomSeedOnExit() &&
  86. FileExists(ApiPath(Configuration->RandomSeedFileName));
  87. }
  88. //---------------------------------------------------------------------------
  89. TSecureShell * GetSecureShell(Plug * plug, bool & pfwd)
  90. {
  91. if (!is_ssh(plug) && !is_pfwd(plug))
  92. {
  93. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  94. // Get SSH/PFwd plug which it wraps.
  95. ProxySocket * AProxySocket = get_proxy_plug_socket(plug);
  96. plug = AProxySocket->plug;
  97. }
  98. pfwd = is_pfwd(plug);
  99. Seat * seat;
  100. if (pfwd)
  101. {
  102. seat = get_pfwd_seat(plug);
  103. }
  104. else
  105. {
  106. seat = get_ssh_seat(plug);
  107. }
  108. DebugAssert(seat != NULL);
  109. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  110. return SecureShell;
  111. }
  112. //---------------------------------------------------------------------------
  113. struct callback_set * get_callback_set(Plug * plug)
  114. {
  115. bool pfwd;
  116. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  117. return SecureShell->GetCallbackSet();
  118. }
  119. //---------------------------------------------------------------------------
  120. struct callback_set * get_seat_callback_set(Seat * seat)
  121. {
  122. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  123. return SecureShell->GetCallbackSet();
  124. }
  125. //---------------------------------------------------------------------------
  126. extern "C" char * do_select(Plug * plug, SOCKET skt, bool startup)
  127. {
  128. bool pfwd;
  129. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  130. if (!pfwd)
  131. {
  132. SecureShell->UpdateSocket(skt, startup);
  133. }
  134. else
  135. {
  136. SecureShell->UpdatePortFwdSocket(skt, startup);
  137. }
  138. return NULL;
  139. }
  140. //---------------------------------------------------------------------------
  141. static size_t output(Seat * seat, bool is_stderr, const void * data, size_t len)
  142. {
  143. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  144. if (static_cast<int>(static_cast<char>(is_stderr)) == -1)
  145. {
  146. SecureShell->CWrite(reinterpret_cast<const char *>(data), len);
  147. }
  148. else if (!is_stderr)
  149. {
  150. SecureShell->FromBackend(reinterpret_cast<const unsigned char *>(data), len);
  151. }
  152. else
  153. {
  154. SecureShell->AddStdError(reinterpret_cast<const char *>(data), len);
  155. }
  156. return 0;
  157. }
  158. //---------------------------------------------------------------------------
  159. static bool eof(Seat *)
  160. {
  161. return false;
  162. }
  163. //---------------------------------------------------------------------------
  164. static int get_userpass_input(Seat * seat, prompts_t * p, bufchain * DebugUsedArg(input))
  165. {
  166. DebugAssert(p != NULL);
  167. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  168. DebugAssert(SecureShell != NULL);
  169. int Result;
  170. TStrings * Prompts = new TStringList();
  171. TStrings * Results = new TStringList();
  172. try
  173. {
  174. UnicodeString Name = UTF8ToString(p->name);
  175. UnicodeString AName = Name;
  176. TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
  177. bool UTF8Prompt = (PromptKind != pkPassphrase);
  178. for (int Index = 0; Index < int(p->n_prompts); Index++)
  179. {
  180. prompt_t * Prompt = p->prompts[Index];
  181. UnicodeString S;
  182. if (UTF8Prompt)
  183. {
  184. S = UTF8ToString(Prompt->prompt);
  185. }
  186. else
  187. {
  188. S = UnicodeString(AnsiString(Prompt->prompt));
  189. }
  190. Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  191. // this fails, when new passwords do not match on change password prompt,
  192. // and putty retries the prompt
  193. DebugAssert(Prompt->resultsize == 0);
  194. Results->Add(L"");
  195. }
  196. UnicodeString Instructions = UTF8ToString(p->instruction);
  197. if (SecureShell->PromptUser(p->to_server, Name, p->name_reqd,
  198. Instructions, p->instr_reqd, Prompts, Results))
  199. {
  200. for (int Index = 0; Index < int(p->n_prompts); Index++)
  201. {
  202. prompt_t * Prompt = p->prompts[Index];
  203. RawByteString S;
  204. if (UTF8Prompt)
  205. {
  206. S = RawByteString(UTF8String(Results->Strings[Index]));
  207. }
  208. else
  209. {
  210. S = RawByteString(AnsiString(Results->Strings[Index]));
  211. }
  212. prompt_set_result(Prompt, S.c_str());
  213. }
  214. Result = 1;
  215. }
  216. else
  217. {
  218. Result = 0;
  219. }
  220. }
  221. __finally
  222. {
  223. delete Prompts;
  224. delete Results;
  225. }
  226. return Result;
  227. }
  228. //---------------------------------------------------------------------------
  229. static void connection_fatal(Seat * seat, const char * message)
  230. {
  231. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  232. SecureShell->PuttyFatalError(UnicodeString(AnsiString(message)));
  233. }
  234. //---------------------------------------------------------------------------
  235. int verify_ssh_host_key(Seat * seat, const char * host, int port, const char * keytype,
  236. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  237. void * /*ctx*/)
  238. {
  239. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  240. SecureShell->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  241. // We should return 0 when key was not confirmed, we throw exception instead.
  242. return 1;
  243. }
  244. //---------------------------------------------------------------------------
  245. bool have_ssh_host_key(Seat * seat, const char * hostname, int port,
  246. const char * keytype)
  247. {
  248. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  249. return SecureShell->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  250. }
  251. //---------------------------------------------------------------------------
  252. int confirm_weak_crypto_primitive(Seat * seat, const char * algtype, const char * algname,
  253. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  254. {
  255. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  256. SecureShell->AskAlg(algtype, algname);
  257. // We should return 0 when alg was not confirmed, we throw exception instead.
  258. return 1;
  259. }
  260. //---------------------------------------------------------------------------
  261. int confirm_weak_cached_hostkey(Seat *, const char * /*algname*/, const char * /*betteralgs*/,
  262. void (*/*callback*/)(void *ctx, int result), void * /*ctx*/)
  263. {
  264. return 1;
  265. }
  266. //---------------------------------------------------------------------------
  267. void old_keyfile_warning(void)
  268. {
  269. // no reference to TSecureShell instance available
  270. }
  271. //---------------------------------------------------------------------------
  272. void display_banner(Seat * seat, const char * banner, int size)
  273. {
  274. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  275. UnicodeString Banner(UTF8String(banner, size));
  276. SecureShell->DisplayBanner(Banner);
  277. }
  278. //---------------------------------------------------------------------------
  279. static void SSHFatalError(const char * Format, va_list Param)
  280. {
  281. char Buf[200];
  282. vsnprintf(Buf, LENOF(Buf), Format, Param);
  283. Buf[LENOF(Buf) - 1] = '\0';
  284. // Only few calls from putty\winnet.c might be connected with specific
  285. // TSecureShell. Otherwise called only for really fatal errors
  286. // like 'out of memory' from putty\ssh.c.
  287. throw ESshFatal(NULL, Buf);
  288. }
  289. //---------------------------------------------------------------------------
  290. void modalfatalbox(const char * fmt, ...)
  291. {
  292. va_list Param;
  293. va_start(Param, fmt);
  294. SSHFatalError(fmt, Param);
  295. va_end(Param);
  296. }
  297. //---------------------------------------------------------------------------
  298. void nonfatal(const char * fmt, ...)
  299. {
  300. va_list Param;
  301. va_start(Param, fmt);
  302. SSHFatalError(fmt, Param);
  303. va_end(Param);
  304. }
  305. //---------------------------------------------------------------------------
  306. void ldisc_echoedit_update(Ldisc * /*handle*/)
  307. {
  308. DebugFail();
  309. }
  310. //---------------------------------------------------------------------------
  311. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  312. {
  313. return ticks + GetTickCount();
  314. }
  315. //---------------------------------------------------------------------------
  316. void expire_timer_context(void * /*ctx*/)
  317. {
  318. // nothing
  319. }
  320. //---------------------------------------------------------------------------
  321. Pinger * pinger_new(Conf * /*conf*/, Backend * /*back*/)
  322. {
  323. return NULL;
  324. }
  325. //---------------------------------------------------------------------------
  326. void pinger_reconfig(Pinger * /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  327. {
  328. // nothing
  329. }
  330. //---------------------------------------------------------------------------
  331. void pinger_free(Pinger * /*pinger*/)
  332. {
  333. // nothing
  334. }
  335. //---------------------------------------------------------------------------
  336. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  337. {
  338. // nothing, therefore no auth.
  339. }
  340. //---------------------------------------------------------------------------
  341. // Based on PuTTY's settings.c
  342. char * get_remote_username(Conf * conf)
  343. {
  344. char * username = conf_get_str(conf, CONF_username);
  345. char * result;
  346. if (*username)
  347. {
  348. result = dupstr(username);
  349. }
  350. else
  351. {
  352. result = NULL;
  353. }
  354. return result;
  355. }
  356. //---------------------------------------------------------------------------
  357. static const SeatVtable ScpSeatVtable =
  358. {
  359. output,
  360. eof,
  361. get_userpass_input,
  362. nullseat_notify_remote_exit,
  363. connection_fatal,
  364. nullseat_update_specials_menu,
  365. nullseat_get_ttymode,
  366. nullseat_set_busy_status,
  367. verify_ssh_host_key,
  368. confirm_weak_crypto_primitive,
  369. confirm_weak_cached_hostkey,
  370. nullseat_is_always_utf8,
  371. nullseat_echoedit_update,
  372. nullseat_get_x_display,
  373. nullseat_get_windowid,
  374. nullseat_get_window_pixel_size,
  375. nullseat_stripctrl_new,
  376. nullseat_set_trust_status_vacuously
  377. };
  378. //---------------------------------------------------------------------------
  379. ScpSeat::ScpSeat(TSecureShell * ASecureShell)
  380. {
  381. SecureShell = ASecureShell;
  382. vt = &ScpSeatVtable;
  383. }
  384. //---------------------------------------------------------------------------
  385. static std::unique_ptr<TCriticalSection> PuttyRegistrySection(TraceInitPtr(new TCriticalSection()));
  386. enum TPuttyRegistryMode { prmPass, prmRedirect, prmCollect, prmFail };
  387. static TPuttyRegistryMode PuttyRegistryMode = prmRedirect;
  388. typedef std::map<UnicodeString, unsigned long> TPuttyRegistryTypes;
  389. TPuttyRegistryTypes PuttyRegistryTypes;
  390. //---------------------------------------------------------------------------
  391. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  392. {
  393. long R;
  394. DebugAssert(Configuration != NULL);
  395. DebugAssert(Key == HKEY_CURRENT_USER);
  396. DebugUsedParam(Key);
  397. UnicodeString RegKey = SubKey;
  398. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  399. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  400. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  401. if (!RegKey.IsEmpty())
  402. {
  403. DebugAssert(RegKey[1] == L'\\');
  404. RegKey.Delete(1, 1);
  405. }
  406. if (RegKey.IsEmpty())
  407. {
  408. *Result = static_cast<HKEY>(NULL);
  409. R = ERROR_SUCCESS;
  410. }
  411. else
  412. {
  413. // we expect this to be called only from verify_host_key() or store_host_key()
  414. DebugAssert(RegKey == L"SshHostKeys");
  415. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  416. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  417. if (Storage->OpenSubKey(RegKey, CanCreate))
  418. {
  419. *Result = reinterpret_cast<HKEY>(Storage);
  420. R = ERROR_SUCCESS;
  421. }
  422. else
  423. {
  424. delete Storage;
  425. R = ERROR_CANTOPEN;
  426. }
  427. }
  428. return R;
  429. }
  430. //---------------------------------------------------------------------------
  431. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  432. {
  433. if (PuttyRegistryMode == prmPass)
  434. {
  435. return RegOpenKeyA(Key, SubKey, Result);
  436. }
  437. else if (PuttyRegistryMode == prmCollect)
  438. {
  439. *Result = reinterpret_cast<HKEY>(1);
  440. return ERROR_SUCCESS;
  441. }
  442. else if (PuttyRegistryMode == prmFail)
  443. {
  444. return ERROR_CANTOPEN;
  445. }
  446. DebugAssert(PuttyRegistryMode == prmRedirect);
  447. return OpenWinSCPKey(Key, SubKey, Result, false);
  448. }
  449. //---------------------------------------------------------------------------
  450. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  451. {
  452. if (PuttyRegistryMode == prmPass)
  453. {
  454. return RegCreateKeyA(Key, SubKey, Result);
  455. }
  456. else if (PuttyRegistryMode == prmCollect)
  457. {
  458. *Result = reinterpret_cast<HKEY>(1);
  459. return ERROR_SUCCESS;
  460. }
  461. DebugAssert(PuttyRegistryMode == prmRedirect);
  462. return OpenWinSCPKey(Key, SubKey, Result, true);
  463. }
  464. //---------------------------------------------------------------------------
  465. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * Reserved,
  466. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  467. {
  468. if (PuttyRegistryMode == prmPass)
  469. {
  470. return RegQueryValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  471. }
  472. else if (PuttyRegistryMode == prmCollect)
  473. {
  474. return ERROR_READ_FAULT;
  475. }
  476. DebugAssert(PuttyRegistryMode == prmRedirect);
  477. long R;
  478. DebugAssert(Configuration != NULL);
  479. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  480. AnsiString Value;
  481. if (Storage == NULL)
  482. {
  483. if (UnicodeString(ValueName) == L"RandSeedFile")
  484. {
  485. Value = AnsiString(Configuration->RandomSeedFileName);
  486. R = ERROR_SUCCESS;
  487. }
  488. else
  489. {
  490. DebugFail();
  491. R = ERROR_READ_FAULT;
  492. }
  493. }
  494. else
  495. {
  496. if (Storage->ValueExists(ValueName))
  497. {
  498. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  499. R = ERROR_SUCCESS;
  500. }
  501. else
  502. {
  503. R = ERROR_READ_FAULT;
  504. }
  505. }
  506. if (R == ERROR_SUCCESS)
  507. {
  508. DebugAssert(Type != NULL);
  509. *Type = REG_SZ;
  510. char * DataStr = reinterpret_cast<char *>(Data);
  511. strncpy(DataStr, Value.c_str(), *DataSize);
  512. DataStr[*DataSize - 1] = '\0';
  513. *DataSize = strlen(DataStr);
  514. }
  515. return R;
  516. }
  517. //---------------------------------------------------------------------------
  518. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long Reserved,
  519. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  520. {
  521. if (PuttyRegistryMode == prmPass)
  522. {
  523. return RegSetValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  524. }
  525. else if (PuttyRegistryMode == prmCollect)
  526. {
  527. PuttyRegistryTypes[ValueName] = Type;
  528. return ERROR_SUCCESS;
  529. }
  530. DebugAssert(PuttyRegistryMode == prmRedirect);
  531. DebugAssert(Configuration != NULL);
  532. DebugAssert(Type == REG_SZ);
  533. DebugUsedParam(Type);
  534. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  535. DebugAssert(Storage != NULL);
  536. if (Storage != NULL)
  537. {
  538. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  539. Storage->WriteStringRaw(ValueName, Value);
  540. }
  541. return ERROR_SUCCESS;
  542. }
  543. //---------------------------------------------------------------------------
  544. long reg_close_winscp_key(HKEY Key)
  545. {
  546. if (PuttyRegistryMode == prmPass)
  547. {
  548. return RegCloseKey(Key);
  549. }
  550. else if (PuttyRegistryMode == prmCollect)
  551. {
  552. return ERROR_SUCCESS;
  553. }
  554. DebugAssert(PuttyRegistryMode == prmRedirect);
  555. DebugAssert(Configuration != NULL);
  556. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  557. if (Storage != NULL)
  558. {
  559. delete Storage;
  560. }
  561. return ERROR_SUCCESS;
  562. }
  563. //---------------------------------------------------------------------------
  564. TKeyType KeyType(UnicodeString FileName)
  565. {
  566. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  567. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  568. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  569. UTF8String UtfFileName = UTF8String(FileName);
  570. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  571. TKeyType Result = (TKeyType)key_type(KeyFile);
  572. filename_free(KeyFile);
  573. return Result;
  574. }
  575. //---------------------------------------------------------------------------
  576. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  577. {
  578. UTF8String UtfFileName = UTF8String(FileName);
  579. bool Result;
  580. char * CommentStr = NULL;
  581. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  582. try
  583. {
  584. switch (KeyType)
  585. {
  586. case ktSSH2:
  587. Result = (ssh2_userkey_encrypted(KeyFile, &CommentStr) != 0);
  588. break;
  589. case ktOpenSSHPEM:
  590. case ktOpenSSHNew:
  591. case ktSSHCom:
  592. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  593. break;
  594. default:
  595. DebugFail();
  596. Result = false;
  597. break;
  598. }
  599. }
  600. __finally
  601. {
  602. filename_free(KeyFile);
  603. }
  604. if (CommentStr != NULL)
  605. {
  606. Comment = UnicodeString(AnsiString(CommentStr));
  607. // ktOpenSSH has no comment, PuTTY defaults to file path
  608. if (Comment == FileName)
  609. {
  610. Comment = ExtractFileName(FileName);
  611. }
  612. sfree(CommentStr);
  613. }
  614. return Result;
  615. }
  616. //---------------------------------------------------------------------------
  617. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  618. {
  619. UTF8String UtfFileName = UTF8String(FileName);
  620. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  621. struct ssh2_userkey * Ssh2Key = NULL;
  622. const char * ErrorStr = NULL;
  623. AnsiString AnsiPassphrase = Passphrase;
  624. try
  625. {
  626. switch (KeyType)
  627. {
  628. case ktSSH2:
  629. Ssh2Key = ssh2_load_userkey(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  630. break;
  631. case ktOpenSSHPEM:
  632. case ktOpenSSHNew:
  633. case ktSSHCom:
  634. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  635. break;
  636. default:
  637. DebugFail();
  638. break;
  639. }
  640. }
  641. __finally
  642. {
  643. Shred(AnsiPassphrase);
  644. filename_free(KeyFile);
  645. }
  646. if (Ssh2Key == NULL)
  647. {
  648. UnicodeString Error = AnsiString(ErrorStr);
  649. // While theoretically we may get "unable to open key file" and
  650. // so we should check system error code,
  651. // we actully never get here unless we call KeyType previously
  652. // and handle ktUnopenable accordingly.
  653. throw Exception(Error);
  654. }
  655. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  656. {
  657. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  658. }
  659. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  660. }
  661. //---------------------------------------------------------------------------
  662. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  663. {
  664. AnsiString AnsiComment(Comment);
  665. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  666. sfree(Ssh2Key->comment);
  667. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  668. }
  669. //---------------------------------------------------------------------------
  670. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  671. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  672. {
  673. UTF8String UtfFileName = UTF8String(FileName);
  674. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  675. try
  676. {
  677. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  678. AnsiString AnsiPassphrase = Passphrase;
  679. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  680. switch (KeyType)
  681. {
  682. case ktSSH2:
  683. if (!ssh2_save_userkey(KeyFile, Ssh2Key, PassphrasePtr))
  684. {
  685. int Error = errno;
  686. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  687. }
  688. break;
  689. default:
  690. DebugFail();
  691. break;
  692. }
  693. }
  694. __finally
  695. {
  696. filename_free(KeyFile);
  697. }
  698. }
  699. //---------------------------------------------------------------------------
  700. void FreeKey(TPrivateKey * PrivateKey)
  701. {
  702. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  703. ssh_key_free(Ssh2Key->key);
  704. sfree(Ssh2Key);
  705. }
  706. //---------------------------------------------------------------------------
  707. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  708. {
  709. RawByteString Result;
  710. UTF8String UtfFileName = UTF8String(FileName);
  711. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  712. try
  713. {
  714. char * AlgorithmStr = NULL;
  715. char * CommentStr = NULL;
  716. const char * ErrorStr = NULL;
  717. strbuf * PublicKeyBuf = strbuf_new();
  718. if (!ssh2_userkey_loadpub(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  719. {
  720. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  721. throw Exception(Error);
  722. }
  723. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  724. sfree(AlgorithmStr);
  725. Comment = UnicodeString(AnsiString(CommentStr));
  726. sfree(CommentStr);
  727. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  728. strbuf_free(PublicKeyBuf);
  729. }
  730. __finally
  731. {
  732. filename_free(KeyFile);
  733. }
  734. return Result;
  735. }
  736. //---------------------------------------------------------------------------
  737. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  738. {
  739. UnicodeString Algorithm;
  740. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  741. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  742. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  743. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  744. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  745. return Result;
  746. }
  747. //---------------------------------------------------------------------------
  748. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  749. {
  750. static int has = -1;
  751. if (has < 0)
  752. {
  753. Conf * conf = conf_new();
  754. ssh_gss_liblist * List = NULL;
  755. try
  756. {
  757. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  758. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  759. filename_free(filename);
  760. List = ssh_gss_setup(conf, NULL);
  761. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  762. {
  763. ssh_gss_library * library = &List->libraries[Index];
  764. Ssh_gss_ctx ctx;
  765. memset(&ctx, 0, sizeof(ctx));
  766. has =
  767. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  768. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  769. }
  770. }
  771. __finally
  772. {
  773. ssh_gss_cleanup(List);
  774. conf_free(conf);
  775. }
  776. if (has < 0)
  777. {
  778. has = 0;
  779. }
  780. }
  781. return (has > 0);
  782. }
  783. //---------------------------------------------------------------------------
  784. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName, UnicodeString & KeyType)
  785. {
  786. const int MaxCount = 10;
  787. const ssh_keyalg * SignKeys[MaxCount];
  788. int Count = LENOF(SignKeys);
  789. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  790. // as the names have different number of dashes
  791. get_hostkey_algs(&Count, SignKeys);
  792. for (int Index = 0; Index < Count; Index++)
  793. {
  794. const ssh_keyalg * SignKey = SignKeys[Index];
  795. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  796. if (StartsStr(Name + L" ", Fingerprint))
  797. {
  798. UnicodeString Rest = Fingerprint.SubString(Name.Length() + 2, Fingerprint.Length() - Name.Length() - 1);
  799. int Space = Rest.Pos(L" ");
  800. // If not a number, it's an invalid input,
  801. // either something completelly wrong, or it can be OpenSSH base64 public key,
  802. // that got here from TPasteKeyHandler::Paste
  803. if (IsNumber(Rest.SubString(1, Space - 1)))
  804. {
  805. KeyName = Name;
  806. Fingerprint = Rest.SubString(Space + 1, Fingerprint.Length() - Space);
  807. Fingerprint = Base64ToUrlSafe(Fingerprint);
  808. Fingerprint = MD5ToUrlSafe(Fingerprint);
  809. KeyType = UnicodeString(SignKey->cache_id);
  810. return;
  811. }
  812. }
  813. else if (StartsStr(Name + NormalizedFingerprintSeparator, Fingerprint))
  814. {
  815. KeyType = UnicodeString(SignKey->cache_id);
  816. KeyName = Name;
  817. Fingerprint.Delete(1, Name.Length() + 1);
  818. return;
  819. }
  820. }
  821. }
  822. //---------------------------------------------------------------------------
  823. void __fastcall NormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName)
  824. {
  825. UnicodeString KeyType;
  826. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  827. }
  828. //---------------------------------------------------------------------------
  829. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  830. {
  831. UnicodeString KeyType;
  832. UnicodeString KeyName; // unused
  833. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  834. return KeyType;
  835. }
  836. //---------------------------------------------------------------------------
  837. UnicodeString __fastcall GetPuTTYVersion()
  838. {
  839. // "Release 0.64"
  840. // "Pre-release 0.65:2015-07-20.95501a1"
  841. // "Development snapshot 2015-12-22.51465fa"
  842. UnicodeString Result = get_putty_version();
  843. // Skip "Release", "Pre-release", "Development snapshot"
  844. int P = Result.LastDelimiter(L" ");
  845. Result.Delete(1, P);
  846. return Result;
  847. }
  848. //---------------------------------------------------------------------------
  849. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  850. {
  851. unsigned char Digest[32];
  852. hash_simple(&ssh_sha256, make_ptrlen(Data, Size), Digest);
  853. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  854. return Result;
  855. }
  856. //---------------------------------------------------------------------------
  857. void __fastcall DllHijackingProtection()
  858. {
  859. dll_hijacking_protection();
  860. }
  861. //---------------------------------------------------------------------------
  862. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  863. {
  864. UTF8String UtfLine = UTF8String(Line);
  865. char * AlgorithmName = NULL;
  866. char * CommentPtr = NULL;
  867. const char * ErrorStr = NULL;
  868. strbuf * PubBlobBuf = strbuf_new();
  869. UnicodeString Result;
  870. if (!openssh_loadpub_line(UtfLine.c_str(), &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  871. {
  872. throw Exception(UnicodeString(ErrorStr));
  873. }
  874. else
  875. {
  876. try
  877. {
  878. Algorithm = find_pubkey_alg(AlgorithmName);
  879. if (Algorithm == NULL)
  880. {
  881. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  882. }
  883. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  884. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  885. if (Key == NULL)
  886. {
  887. throw Exception(L"Invalid public key.");
  888. }
  889. char * FmtKey = Algorithm->cache_str(Key);
  890. Result = UnicodeString(FmtKey);
  891. sfree(FmtKey);
  892. Algorithm->freekey(Key);
  893. }
  894. __finally
  895. {
  896. strbuf_free(PubBlobBuf);
  897. sfree(AlgorithmName);
  898. sfree(CommentPtr);
  899. }
  900. }
  901. return Result;
  902. }
  903. //---------------------------------------------------------------------------
  904. UnicodeString __fastcall GetSsh1KeyType()
  905. {
  906. return UnicodeString(ssh_rsa.cache_id);
  907. }
  908. //---------------------------------------------------------------------------
  909. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  910. {
  911. UnicodeString Result;
  912. if (KeyType == ssh_dss.cache_id)
  913. {
  914. Result = L"DSA";
  915. }
  916. else if ((KeyType == ssh_rsa.cache_id) ||
  917. (KeyType == L"rsa")) // SSH1
  918. {
  919. Result = L"RSA";
  920. }
  921. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  922. {
  923. Result = L"Ed25519";
  924. }
  925. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  926. {
  927. Result = L"ECDSA/nistp256";
  928. }
  929. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  930. {
  931. Result = L"ECDSA/nistp384";
  932. }
  933. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  934. {
  935. Result = L"ECDSA/nistp521";
  936. }
  937. else
  938. {
  939. DebugFail();
  940. Result = KeyType;
  941. }
  942. return Result;
  943. }
  944. //---------------------------------------------------------------------------
  945. bool IsOpenSSH(const UnicodeString & SshImplementation)
  946. {
  947. return
  948. // e.g. "OpenSSH_5.3"
  949. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  950. // Sun SSH is based on OpenSSH (suffers the same bugs)
  951. (SshImplementation.Pos(L"Sun_SSH") == 1);
  952. }
  953. //---------------------------------------------------------------------------
  954. TStrings * SshCipherList()
  955. {
  956. std::unique_ptr<TStrings> Result(new TStringList());
  957. // Same order as DefaultCipherList
  958. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  959. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  960. {
  961. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  962. {
  963. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->ssh2_id);
  964. Result->Add(Name);
  965. }
  966. }
  967. return Result.release();
  968. }
  969. //---------------------------------------------------------------------------
  970. TStrings * SshKexList()
  971. {
  972. std::unique_ptr<TStrings> Result(new TStringList());
  973. // Same order as DefaultKexList
  974. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  975. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  976. {
  977. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  978. {
  979. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  980. Result->Add(Name);
  981. }
  982. }
  983. return Result.release();
  984. }
  985. //---------------------------------------------------------------------------
  986. TStrings * SshHostKeyList()
  987. {
  988. std::unique_ptr<TStrings> Result(new TStringList());
  989. const int MaxCount = 10;
  990. const ssh_keyalg * SignKeys[MaxCount];
  991. int Count = LENOF(SignKeys);
  992. get_hostkey_algs(&Count, SignKeys);
  993. for (int Index = 0; Index < Count; Index++)
  994. {
  995. const ssh_keyalg * SignKey = SignKeys[Index];
  996. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  997. Result->Add(Name);
  998. }
  999. return Result.release();
  1000. }
  1001. //---------------------------------------------------------------------------
  1002. TStrings * SshMacList()
  1003. {
  1004. std::unique_ptr<TStrings> Result(new TStringList());
  1005. const struct ssh2_macalg ** Macs = NULL;
  1006. int Count = 0;
  1007. get_macs(&Count, &Macs);
  1008. for (int Index = 0; Index < Count; Index++)
  1009. {
  1010. UnicodeString Name = UnicodeString(Macs[Index]->name);
  1011. Result->Add(Name);
  1012. }
  1013. return Result.release();
  1014. }
  1015. //---------------------------------------------------------------------------
  1016. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  1017. {
  1018. return UnicodeString(UTF8String(Cipher->vt->text_name));
  1019. }
  1020. //---------------------------------------------------------------------------
  1021. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  1022. {
  1023. UnicodeString Result;
  1024. if (Compressor != NULL)
  1025. {
  1026. Result = UnicodeString(UTF8String(Compressor->vt->name));
  1027. }
  1028. return Result;
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  1032. {
  1033. UnicodeString Result;
  1034. if (Decompressor != NULL)
  1035. {
  1036. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  1037. }
  1038. return Result;
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void WritePuttySettings(THierarchicalStorage * Storage, const UnicodeString & ASettings)
  1042. {
  1043. if (PuttyRegistryTypes.empty())
  1044. {
  1045. TGuard Guard(PuttyRegistrySection.get());
  1046. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1047. PuttyRegistryMode = prmCollect;
  1048. Conf * conf = conf_new();
  1049. try
  1050. {
  1051. do_defaults(NULL, conf);
  1052. save_settings(NULL, conf);
  1053. }
  1054. __finally
  1055. {
  1056. conf_free(conf);
  1057. }
  1058. }
  1059. std::unique_ptr<TStrings> Settings(new TStringList());
  1060. UnicodeString Buf = ASettings;
  1061. UnicodeString Setting;
  1062. while (CutToken(Buf, Setting))
  1063. {
  1064. Settings->Add(Setting);
  1065. }
  1066. for (int Index = 0; Index < Settings->Count; Index++)
  1067. {
  1068. UnicodeString Name = Settings->Names[Index];
  1069. TPuttyRegistryTypes::const_iterator IType = PuttyRegistryTypes.find(Name);
  1070. if (IType != PuttyRegistryTypes.end())
  1071. {
  1072. UnicodeString Value = Settings->ValueFromIndex[Index];
  1073. int I;
  1074. if (IType->second == REG_SZ)
  1075. {
  1076. Storage->WriteStringRaw(Name, Value);
  1077. }
  1078. else if (DebugAlwaysTrue(IType->second == REG_DWORD) &&
  1079. TryStrToInt(Value, I))
  1080. {
  1081. Storage->WriteInteger(Name, I);
  1082. }
  1083. }
  1084. }
  1085. }
  1086. //---------------------------------------------------------------------------
  1087. void PuttyDefaults(Conf * conf)
  1088. {
  1089. TGuard Guard(PuttyRegistrySection.get());
  1090. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1091. PuttyRegistryMode = prmFail;
  1092. do_defaults(NULL, conf);
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. void SavePuttyDefaults(const UnicodeString & Name)
  1096. {
  1097. TGuard Guard(PuttyRegistrySection.get());
  1098. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1099. PuttyRegistryMode = prmPass;
  1100. Conf * conf = conf_new();
  1101. try
  1102. {
  1103. PuttyDefaults(conf);
  1104. AnsiString PuttyName = PuttyStr(Name);
  1105. save_settings(PuttyName.c_str(), conf);
  1106. }
  1107. __finally
  1108. {
  1109. conf_free(conf);
  1110. }
  1111. }
  1112. //---------------------------------------------------------------------------
  1113. //---------------------------------------------------------------------------