PuttyIntf.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. // this fails, when new passwords do not match on change password prompt,
  135. // and putty retries the prompt
  136. assert(Prompt->resultsize == 0);
  137. Results->Add(L"");
  138. }
  139. if (SecureShell->PromptUser(p->to_server, p->name, p->name_reqd,
  140. p->instruction, p->instr_reqd, Prompts, Results))
  141. {
  142. for (int Index = 0; Index < int(p->n_prompts); Index++)
  143. {
  144. prompt_t * Prompt = p->prompts[Index];
  145. prompt_set_result(Prompt, AnsiString(Results->Strings[Index]).c_str());
  146. }
  147. Result = 1;
  148. }
  149. else
  150. {
  151. Result = 0;
  152. }
  153. }
  154. __finally
  155. {
  156. delete Prompts;
  157. delete Results;
  158. }
  159. return Result;
  160. }
  161. //---------------------------------------------------------------------------
  162. char * get_ttymode(void * /*frontend*/, const char * /*mode*/)
  163. {
  164. // should never happen when Config.nopty == TRUE
  165. FAIL;
  166. return NULL;
  167. }
  168. //---------------------------------------------------------------------------
  169. void logevent(void * frontend, const char * string)
  170. {
  171. // Frontend maybe NULL here
  172. if (frontend != NULL)
  173. {
  174. ((TSecureShell *)frontend)->PuttyLogEvent(string);
  175. }
  176. }
  177. //---------------------------------------------------------------------------
  178. void connection_fatal(void * frontend, char * fmt, ...)
  179. {
  180. va_list Param;
  181. char Buf[200];
  182. va_start(Param, fmt);
  183. vsnprintf(Buf, LENOF(Buf), fmt, Param); \
  184. Buf[LENOF(Buf) - 1] = '\0'; \
  185. va_end(Param);
  186. assert(frontend != NULL);
  187. ((TSecureShell *)frontend)->PuttyFatalError(Buf);
  188. }
  189. //---------------------------------------------------------------------------
  190. int verify_ssh_host_key(void * frontend, char * host, int port, char * keytype,
  191. char * keystr, char * fingerprint, void (*/*callback*/)(void * ctx, int result),
  192. void * /*ctx*/)
  193. {
  194. assert(frontend != NULL);
  195. ((TSecureShell *)frontend)->VerifyHostKey(host, port, keytype, keystr, fingerprint);
  196. // We should return 0 when key was not confirmed, we throw exception instead.
  197. return 1;
  198. }
  199. //---------------------------------------------------------------------------
  200. int askalg(void * frontend, const char * algtype, const char * algname,
  201. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  202. {
  203. assert(frontend != NULL);
  204. ((TSecureShell *)frontend)->AskAlg(algtype, algname);
  205. // We should return 0 when alg was not confirmed, we throw exception instead.
  206. return 1;
  207. }
  208. //---------------------------------------------------------------------------
  209. void old_keyfile_warning(void)
  210. {
  211. // no reference to TSecureShell instace available
  212. }
  213. //---------------------------------------------------------------------------
  214. void display_banner(void * frontend, const char * banner, int size)
  215. {
  216. assert(frontend);
  217. UnicodeString Banner(banner, size);
  218. ((TSecureShell *)frontend)->DisplayBanner(Banner);
  219. }
  220. //---------------------------------------------------------------------------
  221. static void SSHFatalError(const char * Format, va_list Param)
  222. {
  223. char Buf[200];
  224. vsnprintf(Buf, LENOF(Buf), Format, Param);
  225. Buf[LENOF(Buf) - 1] = '\0';
  226. // Only few calls from putty\winnet.c might be connected with specific
  227. // TSecureShell. Otherwise called only for really fatal errors
  228. // like 'out of memory' from putty\ssh.c.
  229. throw ESshFatal(NULL, Buf);
  230. }
  231. //---------------------------------------------------------------------------
  232. void fatalbox(char * fmt, ...)
  233. {
  234. va_list Param;
  235. va_start(Param, fmt);
  236. SSHFatalError(fmt, Param);
  237. va_end(Param);
  238. }
  239. //---------------------------------------------------------------------------
  240. void modalfatalbox(char * fmt, ...)
  241. {
  242. va_list Param;
  243. va_start(Param, fmt);
  244. SSHFatalError(fmt, Param);
  245. va_end(Param);
  246. }
  247. //---------------------------------------------------------------------------
  248. void nonfatal(char * fmt, ...)
  249. {
  250. va_list Param;
  251. va_start(Param, fmt);
  252. SSHFatalError(fmt, Param);
  253. va_end(Param);
  254. }
  255. //---------------------------------------------------------------------------
  256. void cleanup_exit(int /*code*/)
  257. {
  258. throw ESshFatal(NULL, "");
  259. }
  260. //---------------------------------------------------------------------------
  261. int askappend(void * /*frontend*/, Filename * /*filename*/,
  262. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  263. {
  264. // this is called from logging.c of putty, which is never used with WinSCP
  265. FAIL;
  266. return 0;
  267. }
  268. //---------------------------------------------------------------------------
  269. void ldisc_send(void * /*handle*/, char * /*buf*/, int len, int /*interactive*/)
  270. {
  271. // This is only here because of the calls to ldisc_send(NULL,
  272. // 0) in ssh.c. Nothing in PSCP actually needs to use the ldisc
  273. // as an ldisc. So if we get called with any real data, I want
  274. // to know about it.
  275. assert(len == 0);
  276. USEDPARAM(len);
  277. }
  278. //---------------------------------------------------------------------------
  279. void agent_schedule_callback(void (* /*callback*/)(void *, void *, int),
  280. void * /*callback_ctx*/, void * /*data*/, int /*len*/)
  281. {
  282. FAIL;
  283. }
  284. //---------------------------------------------------------------------------
  285. void notify_remote_exit(void * /*frontend*/)
  286. {
  287. // nothing
  288. }
  289. //---------------------------------------------------------------------------
  290. void update_specials_menu(void * /*frontend*/)
  291. {
  292. // nothing
  293. }
  294. //---------------------------------------------------------------------------
  295. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  296. {
  297. return ticks + GetTickCount();
  298. }
  299. //---------------------------------------------------------------------------
  300. void expire_timer_context(void * /*ctx*/)
  301. {
  302. // nothing
  303. }
  304. //---------------------------------------------------------------------------
  305. Pinger pinger_new(Conf * /*conf*/, Backend * /*back*/, void * /*backhandle*/)
  306. {
  307. return NULL;
  308. }
  309. //---------------------------------------------------------------------------
  310. void pinger_reconfig(Pinger /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  311. {
  312. // nothing
  313. }
  314. //---------------------------------------------------------------------------
  315. void pinger_free(Pinger /*pinger*/)
  316. {
  317. // nothing
  318. }
  319. //---------------------------------------------------------------------------
  320. void set_busy_status(void * /*frontend*/, int /*status*/)
  321. {
  322. // nothing
  323. }
  324. //---------------------------------------------------------------------------
  325. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  326. {
  327. // nothing, therefore no auth.
  328. }
  329. //---------------------------------------------------------------------------
  330. // Based on PuTTY's settings.c
  331. char * get_remote_username(Conf * conf)
  332. {
  333. char * username = conf_get_str(conf, CONF_username);
  334. char * result;
  335. if (*username)
  336. {
  337. result = dupstr(username);
  338. }
  339. else
  340. {
  341. result = NULL;
  342. }
  343. return result;
  344. }
  345. //---------------------------------------------------------------------------
  346. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  347. {
  348. long R;
  349. assert(Configuration != NULL);
  350. assert(Key == HKEY_CURRENT_USER);
  351. USEDPARAM(Key);
  352. UnicodeString RegKey = SubKey;
  353. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  354. assert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  355. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  356. if (!RegKey.IsEmpty())
  357. {
  358. assert(RegKey[1] == L'\\');
  359. RegKey.Delete(1, 1);
  360. }
  361. if (RegKey.IsEmpty())
  362. {
  363. *Result = static_cast<HKEY>(NULL);
  364. R = ERROR_SUCCESS;
  365. }
  366. else
  367. {
  368. // we expect this to be called only from verify_host_key() or store_host_key()
  369. assert(RegKey == L"SshHostKeys");
  370. THierarchicalStorage * Storage = Configuration->CreateConfigStorage();
  371. Storage->AccessMode = (CanCreate ? smReadWrite : smRead);
  372. if (Storage->OpenSubKey(RegKey, CanCreate))
  373. {
  374. *Result = reinterpret_cast<HKEY>(Storage);
  375. R = ERROR_SUCCESS;
  376. }
  377. else
  378. {
  379. delete Storage;
  380. R = ERROR_CANTOPEN;
  381. }
  382. }
  383. return R;
  384. }
  385. //---------------------------------------------------------------------------
  386. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  387. {
  388. return OpenWinSCPKey(Key, SubKey, Result, false);
  389. }
  390. //---------------------------------------------------------------------------
  391. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  392. {
  393. return OpenWinSCPKey(Key, SubKey, Result, true);
  394. }
  395. //---------------------------------------------------------------------------
  396. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * /*Reserved*/,
  397. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  398. {
  399. long R;
  400. assert(Configuration != NULL);
  401. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  402. AnsiString Value;
  403. if (Storage == NULL)
  404. {
  405. if (UnicodeString(ValueName) == L"RandSeedFile")
  406. {
  407. Value = Configuration->RandomSeedFileName;
  408. R = ERROR_SUCCESS;
  409. }
  410. else
  411. {
  412. FAIL;
  413. R = ERROR_READ_FAULT;
  414. }
  415. }
  416. else
  417. {
  418. if (Storage->ValueExists(ValueName))
  419. {
  420. Value = Storage->ReadStringRaw(ValueName, L"");
  421. R = ERROR_SUCCESS;
  422. }
  423. else
  424. {
  425. R = ERROR_READ_FAULT;
  426. }
  427. }
  428. if (R == ERROR_SUCCESS)
  429. {
  430. assert(Type != NULL);
  431. *Type = REG_SZ;
  432. char * DataStr = reinterpret_cast<char *>(Data);
  433. strncpy(DataStr, Value.c_str(), *DataSize);
  434. DataStr[*DataSize - 1] = '\0';
  435. *DataSize = strlen(DataStr);
  436. }
  437. return R;
  438. }
  439. //---------------------------------------------------------------------------
  440. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long /*Reserved*/,
  441. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  442. {
  443. assert(Configuration != NULL);
  444. assert(Type == REG_SZ);
  445. USEDPARAM(Type);
  446. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  447. assert(Storage != NULL);
  448. if (Storage != NULL)
  449. {
  450. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  451. Storage->WriteStringRaw(ValueName, Value);
  452. }
  453. return ERROR_SUCCESS;
  454. }
  455. //---------------------------------------------------------------------------
  456. long reg_close_winscp_key(HKEY Key)
  457. {
  458. assert(Configuration != NULL);
  459. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  460. if (Storage != NULL)
  461. {
  462. delete Storage;
  463. }
  464. return ERROR_SUCCESS;
  465. }
  466. //---------------------------------------------------------------------------
  467. TKeyType KeyType(UnicodeString FileName)
  468. {
  469. assert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  470. assert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  471. UTF8String UtfFileName = UTF8String(FileName);
  472. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  473. TKeyType Result = (TKeyType)key_type(KeyFile);
  474. filename_free(KeyFile);
  475. return Result;
  476. }
  477. //---------------------------------------------------------------------------
  478. UnicodeString KeyTypeName(TKeyType KeyType)
  479. {
  480. return key_type_to_str(KeyType);
  481. }
  482. //---------------------------------------------------------------------------
  483. __int64 __fastcall ParseSize(UnicodeString SizeStr)
  484. {
  485. AnsiString AnsiSizeStr = SizeStr;
  486. return parse_blocksize(AnsiSizeStr.c_str());
  487. }
  488. //---------------------------------------------------------------------------
  489. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  490. {
  491. static int has = -1;
  492. if (has < 0)
  493. {
  494. Conf * conf = conf_new();
  495. ssh_gss_liblist * List = NULL;
  496. try
  497. {
  498. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  499. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  500. filename_free(filename);
  501. List = ssh_gss_setup(conf);
  502. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  503. {
  504. ssh_gss_library * library = &List->libraries[Index];
  505. Ssh_gss_ctx ctx;
  506. memset(&ctx, 0, sizeof(ctx));
  507. has =
  508. ((library->acquire_cred(library, &ctx) == SSH_GSS_OK) &&
  509. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  510. }
  511. }
  512. __finally
  513. {
  514. ssh_gss_cleanup(List);
  515. conf_free(conf);
  516. }
  517. if (has < 0)
  518. {
  519. has = 0;
  520. }
  521. }
  522. return (has > 0);
  523. }
  524. //---------------------------------------------------------------------------
  525. UnicodeString __fastcall NormalizeFingerprint(UnicodeString Fingerprint)
  526. {
  527. UnicodeString DssName = UnicodeString(ssh_dss.name) + L" ";
  528. UnicodeString RsaName = UnicodeString(ssh_rsa.name) + L" ";
  529. bool IsFingerprint = false;
  530. int LenStart;
  531. if (StartsStr(DssName, Fingerprint))
  532. {
  533. LenStart = DssName.Length() + 1;
  534. IsFingerprint = true;
  535. }
  536. else if (StartsStr(RsaName, Fingerprint))
  537. {
  538. LenStart = RsaName.Length() + 1;
  539. IsFingerprint = true;
  540. }
  541. if (IsFingerprint)
  542. {
  543. Fingerprint[LenStart - 1] = L'-';
  544. int Space = Fingerprint.Pos(L" ");
  545. assert(IsNumber(Fingerprint.SubString(LenStart, Space - LenStart)));
  546. Fingerprint.Delete(LenStart, Space - LenStart + 1);
  547. Fingerprint = ReplaceChar(Fingerprint, L':', L'-');
  548. }
  549. return Fingerprint;
  550. }
  551. //---------------------------------------------------------------------------
  552. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  553. {
  554. Fingerprint = NormalizeFingerprint(Fingerprint);
  555. UnicodeString Type;
  556. if (StartsStr(UnicodeString(ssh_dss.name) + L"-", Fingerprint))
  557. {
  558. Type = ssh_dss.keytype;
  559. }
  560. else if (StartsStr(UnicodeString(ssh_rsa.name) + L"-", Fingerprint))
  561. {
  562. Type = ssh_rsa.keytype;
  563. }
  564. return Type;
  565. }
  566. //---------------------------------------------------------------------------