PuttyIntf.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. //---------------------------------------------------------------------------
  13. char sshver[50];
  14. const int platform_uses_x11_unix_by_default = TRUE;
  15. CRITICAL_SECTION putty_section;
  16. bool SaveRandomSeed;
  17. char appname_[50];
  18. const char *const appname = appname_;
  19. //---------------------------------------------------------------------------
  20. extern "C"
  21. {
  22. #include <winstuff.h>
  23. }
  24. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  25. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  26. const UnicodeString OriginalPuttyExecutable("putty.exe");
  27. const UnicodeString KittyExecutable("kitty.exe");
  28. //---------------------------------------------------------------------------
  29. void __fastcall PuttyInitialize()
  30. {
  31. SaveRandomSeed = true;
  32. InitializeCriticalSection(&putty_section);
  33. // make sure random generator is initialised, so random_save_seed()
  34. // in destructor can proceed
  35. random_ref();
  36. flags = FLAG_VERBOSE | FLAG_SYNCAGENT; // verbose log
  37. sk_init();
  38. AnsiString VersionString = SshVersionString();
  39. assert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  40. strcpy(sshver, VersionString.c_str());
  41. AnsiString AppName = AppNameString();
  42. assert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  43. strcpy(appname_, AppName.c_str());
  44. }
  45. //---------------------------------------------------------------------------
  46. void __fastcall PuttyFinalize()
  47. {
  48. if (SaveRandomSeed)
  49. {
  50. random_save_seed();
  51. }
  52. random_unref();
  53. sk_cleanup();
  54. win_misc_cleanup();
  55. DeleteCriticalSection(&putty_section);
  56. }
  57. //---------------------------------------------------------------------------
  58. void __fastcall DontSaveRandomSeed()
  59. {
  60. SaveRandomSeed = false;
  61. }
  62. //---------------------------------------------------------------------------
  63. extern "C" char * do_select(Plug plug, SOCKET skt, int startup)
  64. {
  65. void * frontend;
  66. if (!is_ssh(plug) && !is_pfwd(plug))
  67. {
  68. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  69. // Get SSH/PFwd plug which it wraps.
  70. Proxy_Socket ProxySocket = ((Proxy_Plug)plug)->proxy_socket;
  71. plug = ProxySocket->plug;
  72. }
  73. bool pfwd = is_pfwd(plug);
  74. if (pfwd)
  75. {
  76. plug = (Plug)get_pfwd_backend(plug);
  77. }
  78. frontend = get_ssh_frontend(plug);
  79. assert(frontend);
  80. TSecureShell * SecureShell = reinterpret_cast<TSecureShell*>(frontend);
  81. if (!pfwd)
  82. {
  83. SecureShell->UpdateSocket(skt, startup);
  84. }
  85. else
  86. {
  87. SecureShell->UpdatePortFwdSocket(skt, startup);
  88. }
  89. return NULL;
  90. }
  91. //---------------------------------------------------------------------------
  92. int from_backend(void * frontend, int is_stderr, const char * data, int datalen)
  93. {
  94. assert(frontend);
  95. if (is_stderr >= 0)
  96. {
  97. assert((is_stderr == 0) || (is_stderr == 1));
  98. ((TSecureShell *)frontend)->FromBackend((is_stderr == 1), reinterpret_cast<const unsigned char *>(data), datalen);
  99. }
  100. else
  101. {
  102. assert(is_stderr == -1);
  103. ((TSecureShell *)frontend)->CWrite(data, datalen);
  104. }
  105. return 0;
  106. }
  107. //---------------------------------------------------------------------------
  108. int from_backend_untrusted(void * /*frontend*/, const char * /*data*/, int /*len*/)
  109. {
  110. // currently used with authentication banner only,
  111. // for which we have own interface display_banner
  112. return 0;
  113. }
  114. //---------------------------------------------------------------------------
  115. int from_backend_eof(void * /*frontend*/)
  116. {
  117. return FALSE;
  118. }
  119. //---------------------------------------------------------------------------
  120. int get_userpass_input(prompts_t * p, unsigned char * /*in*/, int /*inlen*/)
  121. {
  122. assert(p != NULL);
  123. TSecureShell * SecureShell = reinterpret_cast<TSecureShell *>(p->frontend);
  124. assert(SecureShell != NULL);
  125. int Result;
  126. TStrings * Prompts = new TStringList();
  127. TStrings * Results = new TStringList();
  128. try
  129. {
  130. for (int Index = 0; Index < int(p->n_prompts); Index++)
  131. {
  132. prompt_t * Prompt = p->prompts[Index];
  133. Prompts->AddObject(Prompt->prompt, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  134. assert(Prompt->resultsize == 0);
  135. Results->Add(L"");
  136. }
  137. if (SecureShell->PromptUser(p->to_server, p->name, p->name_reqd,
  138. p->instruction, p->instr_reqd, Prompts, Results))
  139. {
  140. for (int Index = 0; Index < int(p->n_prompts); Index++)
  141. {
  142. prompt_t * Prompt = p->prompts[Index];
  143. prompt_set_result(Prompt, AnsiString(Results->Strings[Index]).c_str());
  144. }
  145. Result = 1;
  146. }
  147. else
  148. {
  149. Result = 0;
  150. }
  151. }
  152. __finally
  153. {
  154. delete Prompts;
  155. delete Results;
  156. }
  157. return Result;
  158. }
  159. //---------------------------------------------------------------------------
  160. char * get_ttymode(void * /*frontend*/, const char * /*mode*/)
  161. {
  162. // should never happen when Config.nopty == TRUE
  163. assert(false);
  164. return NULL;
  165. }
  166. //---------------------------------------------------------------------------
  167. void logevent(void * frontend, const char * string)
  168. {
  169. // Frontend maybe NULL here
  170. if (frontend != NULL)
  171. {
  172. ((TSecureShell *)frontend)->PuttyLogEvent(string);
  173. }
  174. }
  175. //---------------------------------------------------------------------------
  176. void connection_fatal(void * frontend, char * fmt, ...)
  177. {
  178. va_list Param;
  179. char Buf[200];
  180. va_start(Param, fmt);
  181. vsnprintf(Buf, LENOF(Buf), fmt, Param); \
  182. Buf[LENOF(Buf) - 1] = '\0'; \
  183. va_end(Param);
  184. assert(frontend != NULL);
  185. ((TSecureShell *)frontend)->PuttyFatalError(Buf);
  186. }
  187. //---------------------------------------------------------------------------
  188. int verify_ssh_host_key(void * frontend, char * host, int port, char * keytype,
  189. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  190. void * /*ctx*/)
  191. {
  192. assert(frontend != NULL);
  193. ((TSecureShell *)frontend)->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  194. // We should return 0 when key was not confirmed, we throw exception instead.
  195. return 1;
  196. }
  197. //---------------------------------------------------------------------------
  198. int askalg(void * frontend, const char * algtype, const char * algname,
  199. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  200. {
  201. assert(frontend != NULL);
  202. ((TSecureShell *)frontend)->AskAlg(algtype, algname);
  203. // We should return 0 when alg was not confirmed, we throw exception instead.
  204. return 1;
  205. }
  206. //---------------------------------------------------------------------------
  207. void old_keyfile_warning(void)
  208. {
  209. // no reference to TSecureShell instace available
  210. }
  211. //---------------------------------------------------------------------------
  212. void display_banner(void * frontend, const char * banner, int size)
  213. {
  214. assert(frontend);
  215. UnicodeString Banner(banner, size);
  216. ((TSecureShell *)frontend)->DisplayBanner(Banner);
  217. }
  218. //---------------------------------------------------------------------------
  219. static void SSHFatalError(const char * Format, va_list Param)
  220. {
  221. char Buf[200];
  222. vsnprintf(Buf, LENOF(Buf), Format, Param);
  223. Buf[LENOF(Buf) - 1] = '\0';
  224. // Only few calls from putty\winnet.c might be connected with specific
  225. // TSecureShell. Otherwise called only for really fatal errors
  226. // like 'out of memory' from putty\ssh.c.
  227. throw ESshFatal(NULL, Buf);
  228. }
  229. //---------------------------------------------------------------------------
  230. void fatalbox(char * fmt, ...)
  231. {
  232. va_list Param;
  233. va_start(Param, fmt);
  234. SSHFatalError(fmt, Param);
  235. va_end(Param);
  236. }
  237. //---------------------------------------------------------------------------
  238. void modalfatalbox(char * fmt, ...)
  239. {
  240. va_list Param;
  241. va_start(Param, fmt);
  242. SSHFatalError(fmt, Param);
  243. va_end(Param);
  244. }
  245. //---------------------------------------------------------------------------
  246. void nonfatal(char * fmt, ...)
  247. {
  248. va_list Param;
  249. va_start(Param, fmt);
  250. SSHFatalError(fmt, Param);
  251. va_end(Param);
  252. }
  253. //---------------------------------------------------------------------------
  254. void cleanup_exit(int /*code*/)
  255. {
  256. throw ESshFatal(NULL, "");
  257. }
  258. //---------------------------------------------------------------------------
  259. int askappend(void * /*frontend*/, Filename * /*filename*/,
  260. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  261. {
  262. // this is called from logging.c of putty, which is never used with WinSCP
  263. assert(false);
  264. return 0;
  265. }
  266. //---------------------------------------------------------------------------
  267. void ldisc_send(void * /*handle*/, char * /*buf*/, int len, int /*interactive*/)
  268. {
  269. // This is only here because of the calls to ldisc_send(NULL,
  270. // 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
  271. // as an ldisc. So if we get called with any real data, I want
  272. // to know about it.
  273. assert(len == 0);
  274. USEDPARAM(len);
  275. }
  276. //---------------------------------------------------------------------------
  277. void agent_schedule_callback(void (* /*callback*/)(void *, void *, int),
  278. void * /*callback_ctx*/, void * /*data*/, int /*len*/)
  279. {
  280. assert(false);
  281. }
  282. //---------------------------------------------------------------------------
  283. void notify_remote_exit(void * /*frontend*/)
  284. {
  285. // nothing
  286. }
  287. //---------------------------------------------------------------------------
  288. void update_specials_menu(void * /*frontend*/)
  289. {
  290. // nothing
  291. }
  292. //---------------------------------------------------------------------------
  293. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  294. {
  295. return ticks + GetTickCount();
  296. }
  297. //---------------------------------------------------------------------------
  298. void expire_timer_context(void * /*ctx*/)
  299. {
  300. // nothing
  301. }
  302. //---------------------------------------------------------------------------
  303. Pinger pinger_new(Conf * /*conf*/, Backend * /*back*/, void * /*backhandle*/)
  304. {
  305. return NULL;
  306. }
  307. //---------------------------------------------------------------------------
  308. void pinger_reconfig(Pinger /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  309. {
  310. // nothing
  311. }
  312. //---------------------------------------------------------------------------
  313. void pinger_free(Pinger /*pinger*/)
  314. {
  315. // nothing
  316. }
  317. //---------------------------------------------------------------------------
  318. void set_busy_status(void * /*frontend*/, int /*status*/)
  319. {
  320. // nothing
  321. }
  322. //---------------------------------------------------------------------------
  323. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  324. {
  325. // nothing, therefore no auth.
  326. }
  327. //---------------------------------------------------------------------------
  328. // Based on PuTTY's settings.c
  329. char * get_remote_username(Conf * conf)
  330. {
  331. char * username = conf_get_str(conf, CONF_username);
  332. char * result;
  333. if (*username)
  334. {
  335. result = dupstr(username);
  336. }
  337. else
  338. {
  339. result = NULL;
  340. }
  341. return result;
  342. }
  343. //---------------------------------------------------------------------------
  344. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  345. {
  346. long R;
  347. assert(Configuration != NULL);
  348. assert(Key == HKEY_CURRENT_USER);
  349. USEDPARAM(Key);
  350. UnicodeString RegKey = SubKey;
  351. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  352. assert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  353. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  354. if (!RegKey.IsEmpty())
  355. {
  356. assert(RegKey[1] == L'\\');
  357. RegKey.Delete(1, 1);
  358. }
  359. if (RegKey.IsEmpty())
  360. {
  361. *Result = static_cast<HKEY>(NULL);
  362. R = ERROR_SUCCESS;
  363. }
  364. else
  365. {
  366. // we expect this to be called only from verify_host_key() or store_host_key()
  367. assert(RegKey == L"SshHostKeys");
  368. THierarchicalStorage * Storage = Configuration->CreateScpStorage(false);
  369. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  370. if (Storage->OpenSubKey(RegKey, CanCreate))
  371. {
  372. *Result = reinterpret_cast<HKEY>(Storage);
  373. R = ERROR_SUCCESS;
  374. }
  375. else
  376. {
  377. delete Storage;
  378. R = ERROR_CANTOPEN;
  379. }
  380. }
  381. return R;
  382. }
  383. //---------------------------------------------------------------------------
  384. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  385. {
  386. return OpenWinSCPKey(Key, SubKey, Result, false);
  387. }
  388. //---------------------------------------------------------------------------
  389. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  390. {
  391. return OpenWinSCPKey(Key, SubKey, Result, true);
  392. }
  393. //---------------------------------------------------------------------------
  394. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  395. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  396. {
  397. long R;
  398. assert(Configuration != NULL);
  399. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  400. AnsiString Value;
  401. if (Storage == NULL)
  402. {
  403. if (UnicodeString(ValueName) == L"RandSeedFile")
  404. {
  405. Value = Configuration->RandomSeedFileName;
  406. R = ERROR_SUCCESS;
  407. }
  408. else
  409. {
  410. assert(false);
  411. R = ERROR_READ_FAULT;
  412. }
  413. }
  414. else
  415. {
  416. if (Storage->ValueExists(ValueName))
  417. {
  418. Value = Storage->ReadStringRaw(ValueName, L"");
  419. R = ERROR_SUCCESS;
  420. }
  421. else
  422. {
  423. R = ERROR_READ_FAULT;
  424. }
  425. }
  426. if (R == ERROR_SUCCESS)
  427. {
  428. assert(Type != NULL);
  429. *Type = REG_SZ;
  430. char * DataStr = reinterpret_cast<char *>(Data);
  431. strncpy(DataStr, Value.c_str(), *DataSize);
  432. DataStr[*DataSize - 1] = '\0';
  433. *DataSize = strlen(DataStr);
  434. }
  435. return R;
  436. }
  437. //---------------------------------------------------------------------------
  438. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  439. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  440. {
  441. assert(Configuration != NULL);
  442. assert(Type == REG_SZ);
  443. USEDPARAM(Type);
  444. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  445. assert(Storage != NULL);
  446. if (Storage != NULL)
  447. {
  448. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  449. Storage->WriteStringRaw(ValueName, Value);
  450. }
  451. return ERROR_SUCCESS;
  452. }
  453. //---------------------------------------------------------------------------
  454. long reg_close_winscp_key(HKEY Key)
  455. {
  456. assert(Configuration != NULL);
  457. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  458. if (Storage != NULL)
  459. {
  460. delete Storage;
  461. }
  462. return ERROR_SUCCESS;
  463. }
  464. //---------------------------------------------------------------------------
  465. TKeyType KeyType(UnicodeString FileName)
  466. {
  467. assert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  468. assert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  469. Filename * KeyFile = filename_from_str(AnsiString(FileName).c_str());
  470. TKeyType Result = (TKeyType)key_type(KeyFile);
  471. filename_free(KeyFile);
  472. return Result;
  473. }
  474. //---------------------------------------------------------------------------
  475. UnicodeString KeyTypeName(TKeyType KeyType)
  476. {
  477. return key_type_to_str(KeyType);
  478. }
  479. //---------------------------------------------------------------------------
  480. __int64 __fastcall ParseSize(UnicodeString SizeStr)
  481. {
  482. AnsiString AnsiSizeStr = SizeStr;
  483. return parse_blocksize(AnsiSizeStr.c_str());
  484. }
  485. //---------------------------------------------------------------------------
  486. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  487. {
  488. static int has = -1;
  489. if (has < 0)
  490. {
  491. Conf * conf = conf_new();
  492. ssh_gss_liblist * List = NULL;
  493. try
  494. {
  495. Filename * filename = filename_from_str(AnsiString(CustomPath).c_str());
  496. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  497. filename_free(filename);
  498. List = ssh_gss_setup(conf);
  499. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  500. {
  501. ssh_gss_library * library = &List->libraries[Index];
  502. Ssh_gss_ctx ctx;
  503. memset(&ctx, 0, sizeof(ctx));
  504. has =
  505. ((library->acquire_cred(library, &ctx) == SSH_GSS_OK) &&
  506. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  507. }
  508. }
  509. __finally
  510. {
  511. ssh_gss_cleanup(List);
  512. conf_free(conf);
  513. }
  514. if (has < 0)
  515. {
  516. has = 0;
  517. }
  518. }
  519. return (has > 0);
  520. }
  521. //---------------------------------------------------------------------------
  522. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  523. {
  524. UnicodeString DssName = UnicodeString(ssh_dss.name) + L" ";
  525. UnicodeString RsaName = UnicodeString(ssh_rsa.name) + L" ";
  526. bool IsFingerprint = false;
  527. int LenStart;
  528. if (StartsStr(DssName, Fingerprint))
  529. {
  530. LenStart = DssName.Length() + 1;
  531. IsFingerprint = true;
  532. }
  533. else if (StartsStr(RsaName, Fingerprint))
  534. {
  535. LenStart = RsaName.Length() + 1;
  536. IsFingerprint = true;
  537. }
  538. if (IsFingerprint)
  539. {
  540. Fingerprint[LenStart - 1] = L'-';
  541. int Space = Fingerprint.Pos(L" ");
  542. assert(IsNumber(Fingerprint.SubString(LenStart, Space - LenStart)));
  543. Fingerprint.Delete(LenStart, Space - LenStart + 1);
  544. Fingerprint = ReplaceChar(Fingerprint, L':', L'-');
  545. }
  546. return Fingerprint;
  547. }
  548. //---------------------------------------------------------------------------
  549. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  550. {
  551. Fingerprint = NormalizeFingerprint(Fingerprint);
  552. UnicodeString Type;
  553. if (StartsStr(UnicodeString(ssh_dss.name) + L"-", Fingerprint))
  554. {
  555. Type = ssh_dss.keytype;
  556. }
  557. else if (StartsStr(UnicodeString(ssh_rsa.name) + L"-", Fingerprint))
  558. {
  559. Type = ssh_rsa.keytype;
  560. }
  561. return Type;
  562. }
  563. //---------------------------------------------------------------------------