PuttyIntf.cpp 18 KB

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