PuttyIntf.cpp 18 KB

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