PuttyIntf.cpp 16 KB

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