PuttyIntf.cpp 18 KB

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