SecureShell.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "PuttyIntf.h"
  5. #include "Exceptions.h"
  6. #include "Interface.h"
  7. #include "SecureShell.h"
  8. #include "TextsCore.h"
  9. #include "HelpCore.h"
  10. #include "Common.h"
  11. #include "CoreMain.h"
  12. #ifndef AUTO_WINSOCK
  13. #include <winsock2.h>
  14. #endif
  15. //---------------------------------------------------------------------------
  16. #pragma package(smart_init)
  17. //---------------------------------------------------------------------------
  18. #define MAX_BUFSIZE 32768
  19. //---------------------------------------------------------------------------
  20. struct TPuttyTranslation
  21. {
  22. const char * Original;
  23. int Translation;
  24. };
  25. //---------------------------------------------------------------------------
  26. __fastcall TSecureShell::TSecureShell(TSessionUI* UI,
  27. TSessionData * SessionData, TSessionLog * Log, TConfiguration * Configuration)
  28. {
  29. FUI = UI;
  30. FSessionData = SessionData;
  31. FLog = Log;
  32. FConfiguration = Configuration;
  33. FActive = false;
  34. FWaiting = 0;
  35. FOpened = false;
  36. OutPtr = NULL;
  37. Pending = NULL;
  38. FBackendHandle = NULL;
  39. ResetConnection();
  40. FOnCaptureOutput = NULL;
  41. FOnReceive = NULL;
  42. FConfig = new Config();
  43. memset(FConfig, 0, sizeof(*FConfig));
  44. FSocket = INVALID_SOCKET;
  45. FSocketEvent = CreateEvent(NULL, false, false, NULL);
  46. FFrozen = false;
  47. FSimple = false;
  48. }
  49. //---------------------------------------------------------------------------
  50. __fastcall TSecureShell::~TSecureShell()
  51. {
  52. assert(FWaiting == 0);
  53. Active = false;
  54. ResetConnection();
  55. CloseHandle(FSocketEvent);
  56. ClearConfig(FConfig);
  57. delete FConfig;
  58. FConfig = NULL;
  59. }
  60. //---------------------------------------------------------------------------
  61. void __fastcall TSecureShell::ResetConnection()
  62. {
  63. FreeBackend();
  64. ClearStdError();
  65. PendLen = 0;
  66. PendSize = 0;
  67. sfree(Pending);
  68. Pending = NULL;
  69. FCWriteTemp = "";
  70. ResetSessionInfo();
  71. FAuthenticating = false;
  72. FAuthenticated = false;
  73. FStoredPasswordTried = false;
  74. FStoredPasswordTriedForKI = false;
  75. }
  76. //---------------------------------------------------------------------------
  77. void __fastcall TSecureShell::ResetSessionInfo()
  78. {
  79. FSessionInfoValid = false;
  80. FMaxPacketSize = NULL;
  81. }
  82. //---------------------------------------------------------------------------
  83. inline void __fastcall TSecureShell::UpdateSessionInfo()
  84. {
  85. if (!FSessionInfoValid)
  86. {
  87. FSshVersion = get_ssh_version(FBackendHandle);
  88. FSessionInfo.ProtocolBaseName = "SSH";
  89. FSessionInfo.ProtocolName =
  90. FORMAT("%s-%d", (FSessionInfo.ProtocolBaseName, get_ssh_version(FBackendHandle)));
  91. FSessionInfo.SecurityProtocolName = FSessionInfo.ProtocolName;
  92. FSessionInfo.CSCompression =
  93. FuncToCompression(FSshVersion, get_cscomp(FBackendHandle));
  94. FSessionInfo.SCCompression =
  95. FuncToCompression(FSshVersion, get_sccomp(FBackendHandle));
  96. if (FSshVersion == 1)
  97. {
  98. FSessionInfo.CSCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  99. FSessionInfo.SCCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  100. }
  101. else
  102. {
  103. FSessionInfo.CSCipher = CipherNames[FuncToSsh2Cipher(get_cscipher(FBackendHandle))];
  104. FSessionInfo.SCCipher = CipherNames[FuncToSsh2Cipher(get_sccipher(FBackendHandle))];
  105. }
  106. FSessionInfoValid = true;
  107. }
  108. }
  109. //---------------------------------------------------------------------------
  110. const TSessionInfo & __fastcall TSecureShell::GetSessionInfo()
  111. {
  112. if (!FSessionInfoValid)
  113. {
  114. UpdateSessionInfo();
  115. }
  116. return FSessionInfo;
  117. }
  118. //---------------------------------------------------------------------
  119. void __fastcall TSecureShell::ClearConfig(Config * cfg)
  120. {
  121. StrDispose(cfg->remote_cmd_ptr);
  122. StrDispose(cfg->remote_cmd_ptr2);
  123. // clear all
  124. memset(cfg, 0, sizeof(*cfg));
  125. }
  126. //---------------------------------------------------------------------
  127. void __fastcall TSecureShell::StoreToConfig(TSessionData * Data, Config * cfg, bool Simple)
  128. {
  129. ClearConfig(cfg);
  130. // user-configurable settings
  131. ASCOPY(cfg->host, Data->HostName);
  132. ASCOPY(cfg->username, Data->UserName);
  133. cfg->port = Data->PortNumber;
  134. cfg->protocol = PROT_SSH;
  135. // always set 0, as we will handle keepalives ourselves to avoid
  136. // multi-threaded issues in putty timer list
  137. cfg->ping_interval = 0;
  138. cfg->compression = Data->Compression;
  139. cfg->tryagent = Data->TryAgent;
  140. cfg->agentfwd = Data->AgentFwd;
  141. cfg->addressfamily = Data->AddressFamily;
  142. ASCOPY(cfg->ssh_rekey_data, Data->RekeyData);
  143. cfg->ssh_rekey_time = Data->RekeyTime;
  144. for (int c = 0; c < CIPHER_COUNT; c++)
  145. {
  146. int pcipher;
  147. switch (Data->Cipher[c]) {
  148. case cipWarn: pcipher = CIPHER_WARN; break;
  149. case cip3DES: pcipher = CIPHER_3DES; break;
  150. case cipBlowfish: pcipher = CIPHER_BLOWFISH; break;
  151. case cipAES: pcipher = CIPHER_AES; break;
  152. case cipDES: pcipher = CIPHER_DES; break;
  153. case cipArcfour: pcipher = CIPHER_ARCFOUR; break;
  154. default: assert(false);
  155. }
  156. cfg->ssh_cipherlist[c] = pcipher;
  157. }
  158. for (int k = 0; k < KEX_COUNT; k++)
  159. {
  160. int pkex;
  161. switch (Data->Kex[k]) {
  162. case kexWarn: pkex = KEX_WARN; break;
  163. case kexDHGroup1: pkex = KEX_DHGROUP1; break;
  164. case kexDHGroup14: pkex = KEX_DHGROUP14; break;
  165. case kexDHGEx: pkex = KEX_DHGEX; break;
  166. case kexRSA: pkex = KEX_RSA; break;
  167. default: assert(false);
  168. }
  169. cfg->ssh_kexlist[k] = pkex;
  170. }
  171. AnsiString SPublicKeyFile = Data->PublicKeyFile;
  172. if (SPublicKeyFile.IsEmpty()) SPublicKeyFile = Configuration->DefaultKeyFile;
  173. SPublicKeyFile = StripPathQuotes(ExpandEnvironmentVariables(SPublicKeyFile));
  174. ASCOPY(cfg->keyfile.path, SPublicKeyFile);
  175. cfg->sshprot = Data->SshProt;
  176. cfg->ssh2_des_cbc = Data->Ssh2DES;
  177. cfg->ssh_no_userauth = Data->SshNoUserAuth;
  178. cfg->try_tis_auth = Data->AuthTIS;
  179. cfg->try_ki_auth = Data->AuthKI;
  180. cfg->try_gssapi_auth = Data->AuthGSSAPI;
  181. cfg->gssapifwd = Data->GSSAPIFwdTGT;
  182. cfg->change_username = Data->ChangeUsername;
  183. cfg->proxy_type = Data->ProxyMethod;
  184. ASCOPY(cfg->proxy_host, Data->ProxyHost);
  185. cfg->proxy_port = Data->ProxyPort;
  186. ASCOPY(cfg->proxy_username, Data->ProxyUsername);
  187. ASCOPY(cfg->proxy_password, Data->ProxyPassword);
  188. if (Data->ProxyMethod == pmCmd)
  189. {
  190. ASCOPY(cfg->proxy_telnet_command, Data->ProxyLocalCommand);
  191. }
  192. else
  193. {
  194. ASCOPY(cfg->proxy_telnet_command, Data->ProxyTelnetCommand);
  195. }
  196. cfg->proxy_dns = Data->ProxyDNS;
  197. cfg->even_proxy_localhost = Data->ProxyLocalhost;
  198. #pragma option push -w-eas
  199. // after 0.53b values were reversed, however putty still stores
  200. // settings to registry in save way as before
  201. cfg->sshbug_ignore1 = Data->Bug[sbIgnore1];
  202. cfg->sshbug_plainpw1 = Data->Bug[sbPlainPW1];
  203. cfg->sshbug_rsa1 = Data->Bug[sbRSA1];
  204. cfg->sshbug_hmac2 = Data->Bug[sbHMAC2];
  205. cfg->sshbug_derivekey2 = Data->Bug[sbDeriveKey2];
  206. cfg->sshbug_rsapad2 = Data->Bug[sbRSAPad2];
  207. cfg->sshbug_rekey2 = Data->Bug[sbRekey2];
  208. // new after 0.53b
  209. cfg->sshbug_pksessid2 = Data->Bug[sbPKSessID2];
  210. cfg->sshbug_maxpkt2 = Data->Bug[sbMaxPkt2];
  211. #pragma option pop
  212. if (!Data->TunnelPortFwd.IsEmpty())
  213. {
  214. assert(!Simple);
  215. ASCOPY(cfg->portfwd, Data->TunnelPortFwd);
  216. // when setting up a tunnel, do not open shell/sftp
  217. cfg->ssh_no_shell = TRUE;
  218. }
  219. else
  220. {
  221. assert(Simple);
  222. cfg->ssh_simple = Simple;
  223. if (Data->FSProtocol == fsSCPonly)
  224. {
  225. cfg->ssh_subsys = FALSE;
  226. if (Data->Shell.IsEmpty())
  227. {
  228. // Following forces Putty to open default shell
  229. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  230. cfg->remote_cmd[0] = '\0';
  231. }
  232. else
  233. {
  234. cfg->remote_cmd_ptr = StrNew(Data->Shell.c_str());
  235. }
  236. }
  237. else
  238. {
  239. if (Data->SftpServer.IsEmpty())
  240. {
  241. cfg->ssh_subsys = TRUE;
  242. strcpy(cfg->remote_cmd, "sftp");
  243. }
  244. else
  245. {
  246. cfg->ssh_subsys = FALSE;
  247. cfg->remote_cmd_ptr = StrNew(Data->SftpServer.c_str());
  248. }
  249. if (Data->FSProtocol != fsSFTPonly)
  250. {
  251. cfg->ssh_subsys2 = FALSE;
  252. if (Data->Shell.IsEmpty())
  253. {
  254. // Following forces Putty to open default shell
  255. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  256. cfg->remote_cmd_ptr2 = StrNew("\0");
  257. }
  258. else
  259. {
  260. cfg->remote_cmd_ptr2 = StrNew(Data->Shell.c_str());
  261. }
  262. }
  263. if ((Data->FSProtocol == fsSFTPonly) && Data->SftpServer.IsEmpty())
  264. {
  265. // see psftp_connect() from psftp.c
  266. cfg->ssh_subsys2 = FALSE;
  267. cfg->remote_cmd_ptr2 = StrNew(
  268. "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
  269. "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
  270. "exec sftp-server");
  271. }
  272. }
  273. }
  274. // permanent settings
  275. cfg->nopty = TRUE;
  276. cfg->tcp_keepalives = 0;
  277. for (int Index = 0; Index < n_ssh_gss_libraries; Index++)
  278. {
  279. cfg->ssh_gsslist[Index] = ssh_gss_libraries[Index].id;
  280. }
  281. }
  282. //---------------------------------------------------------------------------
  283. void __fastcall TSecureShell::Open()
  284. {
  285. FBackend = &ssh_backend;
  286. ResetConnection();
  287. FAuthenticating = false;
  288. FAuthenticated = false;
  289. Active = false;
  290. FAuthenticationLog = "";
  291. FUI->Information(LoadStr(STATUS_LOOKUPHOST), true);
  292. StoreToConfig(FSessionData, FConfig, Simple);
  293. char * RealHost;
  294. FreeBackend(); // in case we are reconnecting
  295. const char * InitError = FBackend->init(this, &FBackendHandle, FConfig,
  296. FSessionData->HostName.c_str(), FSessionData->PortNumber, &RealHost, 0,
  297. FConfig->tcp_keepalives);
  298. sfree(RealHost);
  299. if (InitError)
  300. {
  301. PuttyFatalError(InitError);
  302. }
  303. FUI->Information(LoadStr(STATUS_CONNECT), true);
  304. Init();
  305. CheckConnection(CONNECTION_FAILED);
  306. FLastDataSent = Now();
  307. FSessionInfo.LoginTime = Now();
  308. FAuthenticating = false;
  309. FAuthenticated = true;
  310. FUI->Information(LoadStr(STATUS_AUTHENTICATED), true);
  311. ResetSessionInfo();
  312. assert(!FSessionInfo.SshImplementation.IsEmpty());
  313. FOpened = true;
  314. }
  315. //---------------------------------------------------------------------------
  316. void __fastcall TSecureShell::Init()
  317. {
  318. try
  319. {
  320. try
  321. {
  322. // Recent pscp checks FBackend->exitcode(FBackendHandle) in the loop
  323. // (see comment in putty revision 8110)
  324. // It seems that we do not need to do it.
  325. while (!get_ssh_state_session(FBackendHandle))
  326. {
  327. if (Configuration->ActualLogProtocol >= 1)
  328. {
  329. LogEvent("Waiting for the server to continue with the initialisation");
  330. }
  331. WaitForData();
  332. }
  333. // unless this is tunnel session, it must be safe to send now
  334. assert(FBackend->sendok(FBackendHandle) || !FSessionData->TunnelPortFwd.IsEmpty());
  335. }
  336. catch(Exception & E)
  337. {
  338. if (FAuthenticating && !FAuthenticationLog.IsEmpty())
  339. {
  340. FUI->FatalError(&E, FMTLOAD(AUTHENTICATION_LOG, (FAuthenticationLog)));
  341. }
  342. else
  343. {
  344. throw;
  345. }
  346. }
  347. }
  348. catch(Exception & E)
  349. {
  350. if (FAuthenticating)
  351. {
  352. FUI->FatalError(&E, LoadStr(AUTHENTICATION_FAILED));
  353. }
  354. else
  355. {
  356. throw;
  357. }
  358. }
  359. }
  360. //---------------------------------------------------------------------------
  361. void __fastcall TSecureShell::PuttyLogEvent(const AnsiString & Str)
  362. {
  363. #define SERVER_VERSION_MSG "Server version: "
  364. // Gross hack
  365. if (Str.Pos(SERVER_VERSION_MSG) == 1)
  366. {
  367. FSessionInfo.SshVersionString = Str.SubString(strlen(SERVER_VERSION_MSG) + 1,
  368. Str.Length() - strlen(SERVER_VERSION_MSG));
  369. const char * Ptr = strchr(FSessionInfo.SshVersionString.c_str(), '-');
  370. if (Ptr != NULL)
  371. {
  372. Ptr = strchr(Ptr + 1, '-');
  373. }
  374. FSessionInfo.SshImplementation = (Ptr != NULL) ? Ptr + 1 : "";
  375. }
  376. #define FORWARDING_FAILURE_MSG "Forwarded connection refused by server: "
  377. else if (Str.Pos(FORWARDING_FAILURE_MSG) == 1)
  378. {
  379. FLastTunnelError = Str.SubString(strlen(FORWARDING_FAILURE_MSG) + 1,
  380. Str.Length() - strlen(FORWARDING_FAILURE_MSG));
  381. static const TPuttyTranslation Translation[] = {
  382. { "Administratively prohibited [%]", PFWD_TRANSL_ADMIN },
  383. { "Connect failed [%]", PFWD_TRANSL_CONNECT },
  384. };
  385. TranslatePuttyMessage(Translation, LENOF(Translation), FLastTunnelError);
  386. }
  387. LogEvent(Str);
  388. }
  389. //---------------------------------------------------------------------------
  390. bool __fastcall TSecureShell::PromptUser(bool /*ToServer*/,
  391. AnsiString AName, bool /*NameRequired*/,
  392. AnsiString Instructions, bool InstructionsRequired,
  393. TStrings * Prompts, TStrings * Results)
  394. {
  395. // there can be zero prompts!
  396. assert(Results->Count == Prompts->Count);
  397. TPromptKind PromptKind;
  398. // beware of changing order
  399. static const TPuttyTranslation NameTranslation[] = {
  400. { "SSH login name", USERNAME_TITLE },
  401. { "SSH key passphrase", PASSPHRASE_TITLE },
  402. { "SSH TIS authentication", SERVER_PROMPT_TITLE },
  403. { "SSH CryptoCard authentication", SERVER_PROMPT_TITLE },
  404. { "SSH server: %", SERVER_PROMPT_TITLE2 },
  405. { "SSH server authentication", SERVER_PROMPT_TITLE },
  406. { "SSH password", PASSWORD_TITLE },
  407. { "New SSH password", NEW_PASSWORD_TITLE },
  408. };
  409. AnsiString Name = AName;
  410. int Index = TranslatePuttyMessage(NameTranslation, LENOF(NameTranslation), Name);
  411. const TPuttyTranslation * InstructionTranslation = NULL;
  412. const TPuttyTranslation * PromptTranslation = NULL;
  413. size_t PromptTranslationCount = 1;
  414. if (Index == 0) // username
  415. {
  416. static const TPuttyTranslation UsernamePromptTranslation[] = {
  417. { "login as: ", USERNAME_PROMPT2 },
  418. };
  419. PromptTranslation = UsernamePromptTranslation;
  420. PromptKind = pkUserName;
  421. }
  422. else if (Index == 1) // passhrase
  423. {
  424. static const TPuttyTranslation PassphrasePromptTranslation[] = {
  425. { "Passphrase for key \"%\": ", PROMPT_KEY_PASSPHRASE },
  426. };
  427. PromptTranslation = PassphrasePromptTranslation;
  428. PromptKind = pkPassphrase;
  429. }
  430. else if (Index == 2) // TIS
  431. {
  432. static const TPuttyTranslation TISInstructionTranslation[] = {
  433. { "Using TIS authentication.%", TIS_INSTRUCTION },
  434. };
  435. static const TPuttyTranslation TISPromptTranslation[] = {
  436. { "Response: ", PROMPT_PROMPT },
  437. };
  438. InstructionTranslation = TISInstructionTranslation;
  439. PromptTranslation = TISPromptTranslation;
  440. PromptKind = pkTIS;
  441. }
  442. else if (Index == 3) // CryptoCard
  443. {
  444. static const TPuttyTranslation CryptoCardInstructionTranslation[] = {
  445. { "Using CryptoCard authentication.%", CRYPTOCARD_INSTRUCTION },
  446. };
  447. static const TPuttyTranslation CryptoCardPromptTranslation[] = {
  448. { "Response: ", PROMPT_PROMPT },
  449. };
  450. InstructionTranslation = CryptoCardInstructionTranslation;
  451. PromptTranslation = CryptoCardPromptTranslation;
  452. PromptKind = pkCryptoCard;
  453. }
  454. else if ((Index == 4) || (Index == 5))
  455. {
  456. static const TPuttyTranslation KeybInteractiveInstructionTranslation[] = {
  457. { "Using keyboard-interactive authentication.%", KEYBINTER_INSTRUCTION },
  458. };
  459. InstructionTranslation = KeybInteractiveInstructionTranslation;
  460. PromptKind = pkKeybInteractive;
  461. }
  462. else if (Index == 6)
  463. {
  464. assert(Prompts->Count == 1);
  465. Prompts->Strings[0] = LoadStr(PASSWORD_PROMPT);
  466. PromptKind = pkPassword;
  467. }
  468. else if (Index == 7)
  469. {
  470. static const TPuttyTranslation NewPasswordPromptTranslation[] = {
  471. { "Current password (blank for previously entered password): ", NEW_PASSWORD_CURRENT_PROMPT },
  472. { "Enter new password: ", NEW_PASSWORD_NEW_PROMPT },
  473. { "Confirm new password: ", NEW_PASSWORD_CONFIRM_PROMPT },
  474. };
  475. PromptTranslation = NewPasswordPromptTranslation;
  476. PromptTranslationCount = LENOF(NewPasswordPromptTranslation);
  477. PromptKind = pkNewPassword;
  478. }
  479. else
  480. {
  481. PromptKind = pkPrompt;
  482. assert(false);
  483. }
  484. LogEvent(FORMAT("Prompt (%d, %s, %s, %s)", (PromptKind, AName, Instructions, (Prompts->Count > 0 ? Prompts->Strings[0] : AnsiString("<no prompt>")))));
  485. Name = Name.Trim();
  486. if (InstructionTranslation != NULL)
  487. {
  488. TranslatePuttyMessage(InstructionTranslation, 1, Instructions);
  489. }
  490. // some servers add leading blank line to make the prompt look prettier
  491. // on terminal console
  492. Instructions = Instructions.Trim();
  493. for (int Index = 0; Index < Prompts->Count; Index++)
  494. {
  495. AnsiString Prompt = Prompts->Strings[Index];
  496. if (PromptTranslation != NULL)
  497. {
  498. TranslatePuttyMessage(PromptTranslation, PromptTranslationCount, Prompt);
  499. }
  500. // some servers add leading blank line to make the prompt look prettier
  501. // on terminal console
  502. Prompts->Strings[Index] = Prompt.Trim();
  503. }
  504. bool Result = false;
  505. if (PromptKind == pkUserName)
  506. {
  507. if (FSessionData->AuthGSSAPI)
  508. {
  509. // use empty username if no username was filled on login dialog
  510. // and GSSAPI auth is enabled, hence there's chance that the server can
  511. // deduce the username otherwise
  512. Results->Strings[0] = "";
  513. Result = true;
  514. }
  515. }
  516. else if ((PromptKind == pkTIS) || (PromptKind == pkCryptoCard) ||
  517. (PromptKind == pkKeybInteractive))
  518. {
  519. if (FSessionData->AuthKIPassword && !FSessionData->Password.IsEmpty() &&
  520. !FStoredPasswordTriedForKI && (Prompts->Count == 1) &&
  521. !bool(Prompts->Objects[0]))
  522. {
  523. LogEvent("Using stored password.");
  524. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  525. Result = true;
  526. Results->Strings[0] = FSessionData->Password;
  527. FStoredPasswordTriedForKI = true;
  528. }
  529. else if (Instructions.IsEmpty() && !InstructionsRequired && (Prompts->Count == 0))
  530. {
  531. LogEvent("Ignoring empty SSH server authentication request");
  532. Result = true;
  533. }
  534. }
  535. else if (PromptKind == pkPassword)
  536. {
  537. if (!FSessionData->Password.IsEmpty() && !FStoredPasswordTried)
  538. {
  539. LogEvent("Using stored password.");
  540. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  541. Result = true;
  542. Results->Strings[0] = FSessionData->Password;
  543. FStoredPasswordTried = true;
  544. }
  545. }
  546. if (!Result)
  547. {
  548. Result = FUI->PromptUser(FSessionData,
  549. PromptKind, Name, Instructions, Prompts, Results);
  550. if (Result)
  551. {
  552. if ((PromptKind == pkUserName) && (Prompts->Count == 1))
  553. {
  554. FUserName = Results->Strings[0];
  555. }
  556. }
  557. }
  558. return Result;
  559. }
  560. //---------------------------------------------------------------------------
  561. void __fastcall TSecureShell::GotHostKey()
  562. {
  563. // due to re-key GotHostKey() may be called again later during session
  564. if (!FAuthenticating && !FAuthenticated)
  565. {
  566. FAuthenticating = true;
  567. FUI->Information(LoadStr(STATUS_AUTHENTICATE), true);
  568. }
  569. }
  570. //---------------------------------------------------------------------------
  571. void __fastcall TSecureShell::CWrite(const char * Data, int Length)
  572. {
  573. // some messages to stderr may indicate that something has changed with the
  574. // session, so reset the session info
  575. ResetSessionInfo();
  576. // We send only whole line at once, so we have to cache incoming data
  577. FCWriteTemp += DeleteChar(AnsiString(Data, Length), '\r');
  578. AnsiString Line;
  579. // Do we have at least one complete line in std error cache?
  580. while (FCWriteTemp.Pos("\n") > 0)
  581. {
  582. AnsiString Line = CutToChar(FCWriteTemp, '\n', false);
  583. FLog->Add(llStdError, Line);
  584. if (FAuthenticating)
  585. {
  586. TranslateAuthenticationMessage(Line);
  587. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Line;
  588. }
  589. FUI->Information(Line, false);
  590. }
  591. }
  592. //---------------------------------------------------------------------------
  593. void __fastcall TSecureShell::RegisterReceiveHandler(TNotifyEvent Handler)
  594. {
  595. assert(FOnReceive == NULL);
  596. FOnReceive = Handler;
  597. }
  598. //---------------------------------------------------------------------------
  599. void __fastcall TSecureShell::UnregisterReceiveHandler(TNotifyEvent Handler)
  600. {
  601. assert(FOnReceive == Handler);
  602. USEDPARAM(Handler);
  603. FOnReceive = NULL;
  604. }
  605. //---------------------------------------------------------------------------
  606. void __fastcall TSecureShell::FromBackend(bool IsStdErr, const char * Data, int Length)
  607. {
  608. CheckConnection();
  609. if (Configuration->ActualLogProtocol >= 1)
  610. {
  611. LogEvent(FORMAT("Received %u bytes (%d)", (Length, int(IsStdErr))));
  612. }
  613. // Following is taken from scp.c from_backend() and modified
  614. if (IsStdErr)
  615. {
  616. AddStdError(AnsiString(Data, Length));
  617. }
  618. else
  619. {
  620. unsigned char *p = (unsigned char *)Data;
  621. unsigned Len = (unsigned)Length;
  622. // with event-select mechanism we can now receive data even before we
  623. // actually expect them (OutPtr can be NULL)
  624. if ((OutPtr != NULL) && (OutLen > 0) && (Len > 0))
  625. {
  626. unsigned Used = OutLen;
  627. if (Used > Len) Used = Len;
  628. memcpy(OutPtr, p, Used);
  629. OutPtr += Used; OutLen -= Used;
  630. p += Used; Len -= Used;
  631. }
  632. if (Len > 0)
  633. {
  634. if (PendSize < PendLen + Len)
  635. {
  636. PendSize = PendLen + Len + 4096;
  637. Pending = (char *)
  638. (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize));
  639. if (!Pending) FatalError("Out of memory");
  640. }
  641. memcpy(Pending + PendLen, p, Len);
  642. PendLen += Len;
  643. }
  644. if (FOnReceive != NULL)
  645. {
  646. if (!FFrozen)
  647. {
  648. FFrozen = true;
  649. try
  650. {
  651. do
  652. {
  653. FDataWhileFrozen = false;
  654. FOnReceive(NULL);
  655. }
  656. while (FDataWhileFrozen);
  657. }
  658. __finally
  659. {
  660. FFrozen = false;
  661. }
  662. }
  663. else
  664. {
  665. FDataWhileFrozen = true;
  666. }
  667. }
  668. }
  669. }
  670. //---------------------------------------------------------------------------
  671. bool __fastcall TSecureShell::Peek(char *& Buf, int Len)
  672. {
  673. bool Result = (int(PendLen) >= Len);
  674. if (Result)
  675. {
  676. Buf = Pending;
  677. }
  678. return Result;
  679. }
  680. //---------------------------------------------------------------------------
  681. Integer __fastcall TSecureShell::Receive(char * Buf, Integer Len)
  682. {
  683. CheckConnection();
  684. if (Len > 0)
  685. {
  686. // Following is taken from scp.c ssh_scp_recv() and modified
  687. OutPtr = Buf;
  688. OutLen = Len;
  689. try
  690. {
  691. /*
  692. * See if the pending-input block contains some of what we
  693. * need.
  694. */
  695. if (PendLen > 0)
  696. {
  697. unsigned PendUsed = PendLen;
  698. if (PendUsed > OutLen)
  699. {
  700. PendUsed = OutLen;
  701. }
  702. memcpy(OutPtr, Pending, PendUsed);
  703. memmove(Pending, Pending + PendUsed, PendLen - PendUsed);
  704. OutPtr += PendUsed;
  705. OutLen -= PendUsed;
  706. PendLen -= PendUsed;
  707. if (PendLen == 0)
  708. {
  709. PendSize = 0;
  710. sfree(Pending);
  711. Pending = NULL;
  712. }
  713. }
  714. while (OutLen > 0)
  715. {
  716. if (Configuration->ActualLogProtocol >= 1)
  717. {
  718. LogEvent(FORMAT("Waiting for another %u bytes", (static_cast<int>(OutLen))));
  719. }
  720. WaitForData();
  721. }
  722. // This seems ambiguous
  723. if (Len <= 0) FatalError(LoadStr(LOST_CONNECTION));
  724. }
  725. __finally
  726. {
  727. OutPtr = NULL;
  728. }
  729. };
  730. if (Configuration->ActualLogProtocol >= 1)
  731. {
  732. LogEvent(FORMAT("Read %u bytes (%d pending)",
  733. (static_cast<int>(Len), static_cast<int>(PendLen))));
  734. }
  735. return Len;
  736. }
  737. //---------------------------------------------------------------------------
  738. AnsiString __fastcall TSecureShell::ReceiveLine()
  739. {
  740. unsigned Index;
  741. Char Ch;
  742. AnsiString Line;
  743. Boolean EOL = False;
  744. do
  745. {
  746. // If there is any buffer of received chars
  747. if (PendLen > 0)
  748. {
  749. Index = 0;
  750. // Repeat until we walk thru whole buffer or reach end-of-line
  751. while ((Index < PendLen) && (!Index || (Pending[Index-1] != '\n')))
  752. {
  753. Index++;
  754. }
  755. EOL = (Boolean)(Index && (Pending[Index-1] == '\n'));
  756. Integer PrevLen = Line.Length();
  757. Line.SetLength(PrevLen + Index);
  758. Receive(Line.c_str() + PrevLen, Index);
  759. }
  760. // If buffer don't contain end-of-line character
  761. // we read one more which causes receiving new buffer of chars
  762. if (!EOL)
  763. {
  764. Receive(&Ch, 1);
  765. Line += Ch;
  766. EOL = (Ch == '\n');
  767. }
  768. }
  769. while (!EOL);
  770. // We don't want end-of-line character
  771. Line.SetLength(Line.Length()-1);
  772. CaptureOutput(llOutput, Line);
  773. return Line;
  774. }
  775. //---------------------------------------------------------------------------
  776. void __fastcall TSecureShell::SendSpecial(int Code)
  777. {
  778. LogEvent(FORMAT("Sending special code: %d", (Code)));
  779. CheckConnection();
  780. FBackend->special(FBackendHandle, (Telnet_Special)Code);
  781. CheckConnection();
  782. FLastDataSent = Now();
  783. }
  784. //---------------------------------------------------------------------------
  785. void __fastcall TSecureShell::SendEOF()
  786. {
  787. SendSpecial(TS_EOF);
  788. }
  789. //---------------------------------------------------------------------------
  790. int __fastcall TSecureShell::TimeoutPrompt(TQueryParamsTimerEvent PoolEvent)
  791. {
  792. FWaiting++;
  793. int Answer;
  794. try
  795. {
  796. TQueryParams Params(qpFatalAbort | qpAllowContinueOnError);
  797. Params.Timer = 500;
  798. Params.TimerEvent = PoolEvent;
  799. Params.TimerMessage = FMTLOAD(TIMEOUT_STILL_WAITING2, (FSessionData->Timeout));
  800. Params.TimerAnswers = qaAbort;
  801. Answer = FUI->QueryUser(FMTLOAD(CONFIRM_PROLONG_TIMEOUT3, (FSessionData->Timeout)),
  802. NULL, qaRetry | qaAbort, &Params);
  803. }
  804. __finally
  805. {
  806. FWaiting--;
  807. }
  808. return Answer;
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall TSecureShell::SendBuffer(unsigned int & Result)
  812. {
  813. // for comments see PoolForData
  814. if (!Active)
  815. {
  816. Result = qaRetry;
  817. }
  818. else
  819. {
  820. try
  821. {
  822. if (FBackend->sendbuffer(FBackendHandle) <= MAX_BUFSIZE)
  823. {
  824. Result = qaOK;
  825. }
  826. }
  827. catch(...)
  828. {
  829. Result = qaRetry;
  830. }
  831. }
  832. }
  833. //---------------------------------------------------------------------------
  834. void __fastcall TSecureShell::DispatchSendBuffer(int BufSize)
  835. {
  836. TDateTime Start = Now();
  837. do
  838. {
  839. CheckConnection();
  840. if (Configuration->ActualLogProtocol >= 1)
  841. {
  842. LogEvent(FORMAT("There are %u bytes remaining in the send buffer, "
  843. "need to send at least another %u bytes",
  844. (BufSize, BufSize - MAX_BUFSIZE)));
  845. }
  846. EventSelectLoop(100, false, NULL);
  847. BufSize = FBackend->sendbuffer(FBackendHandle);
  848. if (Configuration->ActualLogProtocol >= 1)
  849. {
  850. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  851. }
  852. if (Now() - Start > FSessionData->TimeoutDT)
  853. {
  854. LogEvent("Waiting for dispatching send buffer timed out, asking user what to do.");
  855. int Answer = TimeoutPrompt(SendBuffer);
  856. switch (Answer)
  857. {
  858. case qaRetry:
  859. Start = Now();
  860. break;
  861. case qaOK:
  862. BufSize = 0;
  863. break;
  864. default:
  865. assert(false);
  866. // fallthru
  867. case qaAbort:
  868. FatalError(LoadStr(USER_TERMINATED));
  869. break;
  870. }
  871. }
  872. }
  873. while (BufSize > MAX_BUFSIZE);
  874. }
  875. //---------------------------------------------------------------------------
  876. void __fastcall TSecureShell::Send(const char * Buf, Integer Len)
  877. {
  878. CheckConnection();
  879. int BufSize = FBackend->send(FBackendHandle, (char *)Buf, Len);
  880. if (Configuration->ActualLogProtocol >= 1)
  881. {
  882. LogEvent(FORMAT("Sent %u bytes", (static_cast<int>(Len))));
  883. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  884. }
  885. FLastDataSent = Now();
  886. // among other forces receive of pending data to free the servers's send buffer
  887. EventSelectLoop(0, false, NULL);
  888. if (BufSize > MAX_BUFSIZE)
  889. {
  890. DispatchSendBuffer(BufSize);
  891. }
  892. CheckConnection();
  893. }
  894. //---------------------------------------------------------------------------
  895. void __fastcall TSecureShell::SendNull()
  896. {
  897. LogEvent("Sending NULL.");
  898. Send("", 1);
  899. }
  900. //---------------------------------------------------------------------------
  901. void __fastcall TSecureShell::SendStr(AnsiString Str)
  902. {
  903. CheckConnection();
  904. Send(Str.c_str(), Str.Length());
  905. }
  906. //---------------------------------------------------------------------------
  907. void __fastcall TSecureShell::SendLine(AnsiString Line)
  908. {
  909. SendStr(Line);
  910. Send("\n", 1);
  911. FLog->Add(llInput, Line);
  912. }
  913. //---------------------------------------------------------------------------
  914. int __fastcall TSecureShell::TranslatePuttyMessage(
  915. const TPuttyTranslation * Translation, size_t Count, AnsiString & Message)
  916. {
  917. int Result = -1;
  918. for (unsigned int Index = 0; Index < Count; Index++)
  919. {
  920. const char * Original = Translation[Index].Original;
  921. const char * Div = strchr(Original, '%');
  922. if (Div == NULL)
  923. {
  924. if (strcmp(Message.c_str(), Original) == 0)
  925. {
  926. Message = LoadStr(Translation[Index].Translation);
  927. Result = int(Index);
  928. break;
  929. }
  930. }
  931. else
  932. {
  933. size_t OriginalLen = strlen(Original);
  934. size_t PrefixLen = Div - Original;
  935. size_t SuffixLen = OriginalLen - PrefixLen - 1;
  936. if (((size_t)Message.Length() >= OriginalLen - 1) &&
  937. (strncmp(Message.c_str(), Original, PrefixLen) == 0) &&
  938. (strncmp(Message.c_str() + Message.Length() - SuffixLen, Div + 1, SuffixLen) == 0))
  939. {
  940. Message = FMTLOAD(Translation[Index].Translation,
  941. (Message.SubString(PrefixLen + 1, Message.Length() - PrefixLen - SuffixLen).TrimRight()));
  942. Result = int(Index);
  943. break;
  944. }
  945. }
  946. }
  947. return Result;
  948. }
  949. //---------------------------------------------------------------------------
  950. int __fastcall TSecureShell::TranslateAuthenticationMessage(AnsiString & Message)
  951. {
  952. static const TPuttyTranslation Translation[] = {
  953. { "Using username \"%\".", AUTH_TRANSL_USERNAME },
  954. { "Using keyboard-interactive authentication.", AUTH_TRANSL_KEYB_INTER }, // not used anymore
  955. { "Authenticating with public key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  956. { "Authenticating with public key \"%\"", AUTH_TRANSL_PUBLIC_KEY },
  957. { "Authenticated using RSA key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  958. { "Wrong passphrase", AUTH_TRANSL_WRONG_PASSPHRASE },
  959. { "Wrong passphrase.", AUTH_TRANSL_WRONG_PASSPHRASE },
  960. { "Access denied", AUTH_TRANSL_ACCESS_DENIED },
  961. { "Trying public key authentication.", AUTH_TRANSL_TRY_PUBLIC_KEY },
  962. { "Server refused our public key.", AUTH_TRANSL_KEY_REFUSED },
  963. { "Server refused our key", AUTH_TRANSL_KEY_REFUSED }
  964. };
  965. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  966. }
  967. //---------------------------------------------------------------------------
  968. void __fastcall TSecureShell::AddStdError(AnsiString Str)
  969. {
  970. FStdError += Str;
  971. Integer P;
  972. Str = DeleteChar(Str, '\r');
  973. // We send only whole line at once to log, so we have to cache
  974. // incoming std error data
  975. FStdErrorTemp += Str;
  976. AnsiString Line;
  977. // Do we have at least one complete line in std error cache?
  978. while ((P = FStdErrorTemp.Pos("\n")) > 0)
  979. {
  980. Line = FStdErrorTemp.SubString(1, P-1);
  981. FStdErrorTemp.Delete(1, P);
  982. AddStdErrorLine(Line);
  983. }
  984. }
  985. //---------------------------------------------------------------------------
  986. void __fastcall TSecureShell::AddStdErrorLine(const AnsiString & Str)
  987. {
  988. if (FAuthenticating)
  989. {
  990. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Str;
  991. }
  992. CaptureOutput(llStdError, Str);
  993. }
  994. //---------------------------------------------------------------------------
  995. const AnsiString & __fastcall TSecureShell::GetStdError()
  996. {
  997. return FStdError;
  998. }
  999. //---------------------------------------------------------------------------
  1000. void __fastcall TSecureShell::ClearStdError()
  1001. {
  1002. // Flush std error cache
  1003. if (!FStdErrorTemp.IsEmpty())
  1004. {
  1005. if (FAuthenticating)
  1006. {
  1007. FAuthenticationLog +=
  1008. (FAuthenticationLog.IsEmpty() ? "" : "\n") + FStdErrorTemp;
  1009. }
  1010. CaptureOutput(llStdError, FStdErrorTemp);
  1011. FStdErrorTemp = "";
  1012. }
  1013. FStdError = "";
  1014. }
  1015. //---------------------------------------------------------------------------
  1016. void __fastcall TSecureShell::CaptureOutput(TLogLineType Type,
  1017. const AnsiString & Line)
  1018. {
  1019. if (FOnCaptureOutput != NULL)
  1020. {
  1021. FOnCaptureOutput(Line, (Type == llStdError));
  1022. }
  1023. FLog->Add(Type, Line);
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. int __fastcall TSecureShell::TranslateErrorMessage(AnsiString & Message)
  1027. {
  1028. static const TPuttyTranslation Translation[] = {
  1029. { "Server unexpectedly closed network connection", UNEXPECTED_CLOSE_ERROR },
  1030. { "Network error: Connection refused", NET_TRANSL_REFUSED },
  1031. { "Network error: Connection reset by peer", NET_TRANSL_RESET },
  1032. { "Network error: Connection timed out", NET_TRANSL_TIMEOUT },
  1033. };
  1034. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  1035. }
  1036. //---------------------------------------------------------------------------
  1037. void __fastcall TSecureShell::PuttyFatalError(AnsiString Error)
  1038. {
  1039. TranslateErrorMessage(Error);
  1040. FatalError(Error);
  1041. }
  1042. //---------------------------------------------------------------------------
  1043. void __fastcall TSecureShell::FatalError(AnsiString Error)
  1044. {
  1045. FUI->FatalError(NULL, Error);
  1046. }
  1047. //---------------------------------------------------------------------------
  1048. void __fastcall inline TSecureShell::LogEvent(const AnsiString & Str)
  1049. {
  1050. if (FLog->Logging)
  1051. {
  1052. FLog->Add(llMessage, Str);
  1053. }
  1054. }
  1055. //---------------------------------------------------------------------------
  1056. void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, bool Startup)
  1057. {
  1058. int Events;
  1059. if (Startup)
  1060. {
  1061. Events = (FD_CONNECT | FD_READ | FD_WRITE | FD_OOB | FD_CLOSE | FD_ACCEPT);
  1062. }
  1063. else
  1064. {
  1065. Events = 0;
  1066. }
  1067. if (Configuration->ActualLogProtocol >= 2)
  1068. {
  1069. LogEvent(FORMAT("Selecting events %d for socket %d", (int(Events), int(Socket))));
  1070. }
  1071. if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR)
  1072. {
  1073. if (Configuration->ActualLogProtocol >= 2)
  1074. {
  1075. LogEvent(FORMAT("Error selecting events %d for socket %d", (int(Events), int(Socket))));
  1076. }
  1077. if (Startup)
  1078. {
  1079. FatalError(FMTLOAD(EVENT_SELECT_ERROR, (WSAGetLastError())));
  1080. }
  1081. }
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TSecureShell::UpdateSocket(SOCKET value, bool Startup)
  1085. {
  1086. if (!FActive && !Startup)
  1087. {
  1088. // no-op
  1089. // Remove the branch eventualy:
  1090. // When TCP connection fails, PuTTY does not release the memory allocate for
  1091. // socket. As a simple hack we call sk_tcp_close() in ssh.c to release the memory,
  1092. // until they fix it better. Unfortunately sk_tcp_close calls do_select,
  1093. // so we must filter that out.
  1094. }
  1095. else
  1096. {
  1097. assert(value);
  1098. assert((FActive && (FSocket == value)) || (!FActive && Startup));
  1099. // filter our "local proxy" connection, which have no socket
  1100. if (value != INVALID_SOCKET)
  1101. {
  1102. SocketEventSelect(value, FSocketEvent, Startup);
  1103. }
  1104. else
  1105. {
  1106. assert(FSessionData->ProxyMethod == pmCmd);
  1107. }
  1108. if (Startup)
  1109. {
  1110. FSocket = value;
  1111. FActive = true;
  1112. }
  1113. else
  1114. {
  1115. FSocket = INVALID_SOCKET;
  1116. Discard();
  1117. }
  1118. }
  1119. }
  1120. //---------------------------------------------------------------------------
  1121. void __fastcall TSecureShell::UpdatePortFwdSocket(SOCKET value, bool Startup)
  1122. {
  1123. if (Configuration->ActualLogProtocol >= 2)
  1124. {
  1125. LogEvent(FORMAT("Updating forwarding socket %d (%d)", (int(value), int(Startup))));
  1126. }
  1127. SocketEventSelect(value, FSocketEvent, Startup);
  1128. if (Startup)
  1129. {
  1130. FPortFwdSockets.insert(value);
  1131. }
  1132. else
  1133. {
  1134. FPortFwdSockets.erase(value);
  1135. }
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. void __fastcall TSecureShell::SetActive(bool value)
  1139. {
  1140. if (FActive != value)
  1141. {
  1142. if (value)
  1143. {
  1144. Open();
  1145. }
  1146. else
  1147. {
  1148. Close();
  1149. }
  1150. }
  1151. }
  1152. //---------------------------------------------------------------------------
  1153. void __fastcall TSecureShell::FreeBackend()
  1154. {
  1155. if (FBackendHandle != NULL)
  1156. {
  1157. FBackend->free(FBackendHandle);
  1158. FBackendHandle = NULL;
  1159. }
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TSecureShell::Discard()
  1163. {
  1164. bool WasActive = FActive;
  1165. FActive = false;
  1166. FOpened = false;
  1167. if (WasActive)
  1168. {
  1169. FUI->Closed();
  1170. }
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. void __fastcall TSecureShell::Close()
  1174. {
  1175. LogEvent("Closing connection.");
  1176. assert(FActive);
  1177. // this is particularly necessary when using local proxy command
  1178. // (e.g. plink), otherwise it hangs in sk_localproxy_close
  1179. SendEOF();
  1180. FreeBackend();
  1181. Discard();
  1182. }
  1183. //---------------------------------------------------------------------------
  1184. void inline __fastcall TSecureShell::CheckConnection(int Message)
  1185. {
  1186. if (!FActive || get_ssh_state_closed(FBackendHandle))
  1187. {
  1188. AnsiString Str = LoadStr(Message >= 0 ? Message : NOT_CONNECTED);
  1189. int ExitCode = get_ssh_exitcode(FBackendHandle);
  1190. if (ExitCode >= 0)
  1191. {
  1192. Str += " " + FMTLOAD(SSH_EXITCODE, (ExitCode));
  1193. }
  1194. FatalError(Str);
  1195. }
  1196. }
  1197. //---------------------------------------------------------------------------
  1198. void __fastcall TSecureShell::PoolForData(WSANETWORKEVENTS & Events, unsigned int & Result)
  1199. {
  1200. if (!Active)
  1201. {
  1202. // see comment below
  1203. Result = qaRetry;
  1204. }
  1205. else
  1206. {
  1207. try
  1208. {
  1209. if (Configuration->ActualLogProtocol >= 2)
  1210. {
  1211. LogEvent("Pooling for data in case they finally arrives");
  1212. }
  1213. // in extreme condition it may happen that send buffer is full, but there
  1214. // will be no data comming and we may not empty the send buffer because we
  1215. // do not process FD_WRITE until we receive any FD_READ
  1216. if (EventSelectLoop(0, false, &Events))
  1217. {
  1218. LogEvent("Data has arrived, closing query to user.");
  1219. Result = qaOK;
  1220. }
  1221. }
  1222. catch(...)
  1223. {
  1224. // if we let the exception out, it may popup another message dialog
  1225. // in whole event loop, another call to PoolForData from original dialog
  1226. // would be invoked, leading to an infinite loop.
  1227. // by retrying we hope (that probably fatal) error would repeat in WaitForData.
  1228. // anyway now once no actual work is done in EventSelectLoop,
  1229. // hardly any exception can occur actually
  1230. Result = qaRetry;
  1231. }
  1232. }
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. class TPoolForDataEvent
  1236. {
  1237. public:
  1238. __fastcall TPoolForDataEvent(TSecureShell * SecureShell, WSANETWORKEVENTS & Events) :
  1239. FSecureShell(SecureShell),
  1240. FEvents(Events)
  1241. {
  1242. }
  1243. void __fastcall PoolForData(unsigned int & Result)
  1244. {
  1245. FSecureShell->PoolForData(FEvents, Result);
  1246. }
  1247. private:
  1248. TSecureShell * FSecureShell;
  1249. WSANETWORKEVENTS & FEvents;
  1250. };
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TSecureShell::WaitForData()
  1253. {
  1254. // see winsftp.c
  1255. bool IncomingData;
  1256. do
  1257. {
  1258. if (Configuration->ActualLogProtocol >= 2)
  1259. {
  1260. LogEvent("Looking for incoming data");
  1261. }
  1262. IncomingData = EventSelectLoop(FSessionData->Timeout * 1000, true, NULL);
  1263. if (!IncomingData)
  1264. {
  1265. WSANETWORKEVENTS Events;
  1266. memset(&Events, 0, sizeof(Events));
  1267. TPoolForDataEvent Event(this, Events);
  1268. LogEvent("Waiting for data timed out, asking user what to do.");
  1269. int Answer = TimeoutPrompt(Event.PoolForData);
  1270. switch (Answer)
  1271. {
  1272. case qaRetry:
  1273. // noop
  1274. break;
  1275. case qaOK:
  1276. // read event was already captured in PoolForData(),
  1277. // make sure we do not try to select it again as it would timeout
  1278. // unless another read event occurs
  1279. IncomingData = true;
  1280. HandleNetworkEvents(FSocket, Events);
  1281. break;
  1282. default:
  1283. assert(false);
  1284. // fallthru
  1285. case qaAbort:
  1286. FatalError(LoadStr(USER_TERMINATED));
  1287. break;
  1288. }
  1289. }
  1290. }
  1291. while (!IncomingData);
  1292. }
  1293. //---------------------------------------------------------------------------
  1294. bool __fastcall TSecureShell::SshFallbackCmd() const
  1295. {
  1296. return ssh_fallback_cmd(FBackendHandle);
  1297. }
  1298. //---------------------------------------------------------------------------
  1299. bool __fastcall TSecureShell::EnumNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1300. {
  1301. if (Configuration->ActualLogProtocol >= 2)
  1302. {
  1303. LogEvent(FORMAT("Enumerating network events for socket %d", (int(Socket))));
  1304. }
  1305. // see winplink.c
  1306. WSANETWORKEVENTS AEvents;
  1307. if (WSAEnumNetworkEvents(Socket, NULL, &AEvents) == 0)
  1308. {
  1309. noise_ultralight(Socket);
  1310. noise_ultralight(AEvents.lNetworkEvents);
  1311. Events.lNetworkEvents |= AEvents.lNetworkEvents;
  1312. for (int Index = 0; Index < FD_MAX_EVENTS; Index++)
  1313. {
  1314. if (AEvents.iErrorCode[Index] != 0)
  1315. {
  1316. Events.iErrorCode[Index] = AEvents.iErrorCode[Index];
  1317. }
  1318. }
  1319. if (Configuration->ActualLogProtocol >= 2)
  1320. {
  1321. LogEvent(FORMAT("Enumerated %d network events making %d cumulative events for socket %d",
  1322. (int(AEvents.lNetworkEvents), int(Events.lNetworkEvents), int(Socket))));
  1323. }
  1324. }
  1325. else
  1326. {
  1327. if (Configuration->ActualLogProtocol >= 2)
  1328. {
  1329. LogEvent(FORMAT("Error enumerating network events for socket %d", (int(Socket))));
  1330. }
  1331. }
  1332. return
  1333. FLAGSET(Events.lNetworkEvents, FD_READ) ||
  1334. FLAGSET(Events.lNetworkEvents, FD_CLOSE);
  1335. }
  1336. //---------------------------------------------------------------------------
  1337. void __fastcall TSecureShell::HandleNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1338. {
  1339. static const struct { int Bit, Mask; const char * Desc; } EventTypes[] =
  1340. {
  1341. { FD_READ_BIT, FD_READ, "read" },
  1342. { FD_WRITE_BIT, FD_WRITE, "write" },
  1343. { FD_OOB_BIT, FD_OOB, "oob" },
  1344. { FD_ACCEPT_BIT, FD_ACCEPT, "accept" },
  1345. { FD_CONNECT_BIT, FD_CONNECT, "connect" },
  1346. { FD_CLOSE_BIT, FD_CLOSE, "close" },
  1347. };
  1348. for (int Event = 0; Event < LENOF(EventTypes); Event++)
  1349. {
  1350. if (FLAGSET(Events.lNetworkEvents, EventTypes[Event].Mask))
  1351. {
  1352. int Err = Events.iErrorCode[EventTypes[Event].Bit];
  1353. if (Configuration->ActualLogProtocol >= 2)
  1354. {
  1355. LogEvent(FORMAT("Handling network %s event on socket %d with error %d",
  1356. (EventTypes[Event].Desc, int(Socket), Err)));
  1357. }
  1358. #pragma option push -w-prc
  1359. LPARAM SelectEvent = WSAMAKESELECTREPLY(EventTypes[Event].Mask, Err);
  1360. #pragma option pop
  1361. if (!select_result((WPARAM)Socket, SelectEvent))
  1362. {
  1363. // note that connection was closed definitely,
  1364. // so "check" is actually not required
  1365. CheckConnection();
  1366. }
  1367. }
  1368. }
  1369. }
  1370. //---------------------------------------------------------------------------
  1371. bool __fastcall TSecureShell::ProcessNetworkEvents(SOCKET Socket)
  1372. {
  1373. WSANETWORKEVENTS Events;
  1374. memset(&Events, 0, sizeof(Events));
  1375. bool Result = EnumNetworkEvents(Socket, Events);
  1376. HandleNetworkEvents(Socket, Events);
  1377. return Result;
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. bool __fastcall TSecureShell::EventSelectLoop(unsigned int MSec, bool ReadEventRequired,
  1381. WSANETWORKEVENTS * Events)
  1382. {
  1383. CheckConnection();
  1384. bool Result = false;
  1385. do
  1386. {
  1387. if (Configuration->ActualLogProtocol >= 2)
  1388. {
  1389. LogEvent("Looking for network events");
  1390. }
  1391. unsigned int TicksBefore = GetTickCount();
  1392. int HandleCount;
  1393. // note that this returns all handles, not only the session-related handles
  1394. HANDLE * Handles = handle_get_events(&HandleCount);
  1395. try
  1396. {
  1397. Handles = sresize(Handles, HandleCount + 1, HANDLE);
  1398. Handles[HandleCount] = FSocketEvent;
  1399. unsigned int WaitResult = WaitForMultipleObjects(HandleCount + 1, Handles, FALSE, MSec);
  1400. if (WaitResult < WAIT_OBJECT_0 + HandleCount)
  1401. {
  1402. if (handle_got_event(Handles[WaitResult - WAIT_OBJECT_0]))
  1403. {
  1404. Result = true;
  1405. }
  1406. }
  1407. else if (WaitResult == WAIT_OBJECT_0 + HandleCount)
  1408. {
  1409. if (Configuration->ActualLogProtocol >= 1)
  1410. {
  1411. LogEvent("Detected network event");
  1412. }
  1413. if (Events == NULL)
  1414. {
  1415. if (ProcessNetworkEvents(FSocket))
  1416. {
  1417. Result = true;
  1418. }
  1419. }
  1420. else
  1421. {
  1422. if (EnumNetworkEvents(FSocket, *Events))
  1423. {
  1424. Result = true;
  1425. }
  1426. }
  1427. {
  1428. TSockets::iterator i = FPortFwdSockets.begin();
  1429. while (i != FPortFwdSockets.end())
  1430. {
  1431. ProcessNetworkEvents(*i);
  1432. i++;
  1433. }
  1434. }
  1435. }
  1436. else if (WaitResult == WAIT_TIMEOUT)
  1437. {
  1438. if (Configuration->ActualLogProtocol >= 2)
  1439. {
  1440. LogEvent("Timeout waiting for network events");
  1441. }
  1442. MSec = 0;
  1443. }
  1444. else
  1445. {
  1446. if (Configuration->ActualLogProtocol >= 2)
  1447. {
  1448. LogEvent(FORMAT("Unknown waiting result %d", (int(WaitResult))));
  1449. }
  1450. MSec = 0;
  1451. }
  1452. }
  1453. __finally
  1454. {
  1455. sfree(Handles);
  1456. }
  1457. unsigned int TicksAfter = GetTickCount();
  1458. // ticks wraps once in 49.7 days
  1459. if (TicksBefore < TicksAfter)
  1460. {
  1461. unsigned int Ticks = TicksAfter - TicksBefore;
  1462. if (Ticks > MSec)
  1463. {
  1464. MSec = 0;
  1465. }
  1466. else
  1467. {
  1468. MSec -= Ticks;
  1469. }
  1470. }
  1471. }
  1472. while (ReadEventRequired && (MSec > 0) && !Result);
  1473. return Result;
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. void __fastcall TSecureShell::Idle(unsigned int MSec)
  1477. {
  1478. noise_regular();
  1479. call_ssh_timer(FBackendHandle);
  1480. EventSelectLoop(MSec, false, NULL);
  1481. }
  1482. //---------------------------------------------------------------------------
  1483. void __fastcall TSecureShell::KeepAlive()
  1484. {
  1485. if (FActive && (FWaiting == 0))
  1486. {
  1487. LogEvent("Sending null packet to keep session alive.");
  1488. SendSpecial(TS_PING);
  1489. }
  1490. else
  1491. {
  1492. // defer next keepalive attempt
  1493. FLastDataSent = Now();
  1494. }
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. unsigned long __fastcall TSecureShell::MaxPacketSize()
  1498. {
  1499. if (!FSessionInfoValid)
  1500. {
  1501. UpdateSessionInfo();
  1502. }
  1503. if (FSshVersion == 1)
  1504. {
  1505. return 0;
  1506. }
  1507. else
  1508. {
  1509. if (FMaxPacketSize == NULL)
  1510. {
  1511. FMaxPacketSize = ssh2_remmaxpkt(FBackendHandle);
  1512. }
  1513. return *FMaxPacketSize;
  1514. }
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. AnsiString __fastcall TSecureShell::FuncToCompression(
  1518. int SshVersion, const void * Compress) const
  1519. {
  1520. enum TCompressionType { ctNone, ctZLib };
  1521. if (SshVersion == 1)
  1522. {
  1523. return get_ssh1_compressing(FBackendHandle) ? "ZLib" : "";
  1524. }
  1525. else
  1526. {
  1527. return (ssh_compress *)Compress == &ssh_zlib ? "ZLib" : "";
  1528. }
  1529. }
  1530. //---------------------------------------------------------------------------
  1531. TCipher __fastcall TSecureShell::FuncToSsh1Cipher(const void * Cipher)
  1532. {
  1533. const ssh_cipher *CipherFuncs[] =
  1534. {&ssh_3des, &ssh_des, &ssh_blowfish_ssh1};
  1535. const TCipher TCiphers[] = {cip3DES, cipDES, cipBlowfish};
  1536. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1537. TCipher Result = cipWarn;
  1538. for (int Index = 0; Index < LENOF(TCiphers); Index++)
  1539. {
  1540. if ((ssh_cipher *)Cipher == CipherFuncs[Index])
  1541. {
  1542. Result = TCiphers[Index];
  1543. }
  1544. }
  1545. assert(Result != cipWarn);
  1546. return Result;
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. TCipher __fastcall TSecureShell::FuncToSsh2Cipher(const void * Cipher)
  1550. {
  1551. const ssh2_ciphers *CipherFuncs[] =
  1552. {&ssh2_3des, &ssh2_des, &ssh2_aes, &ssh2_blowfish, &ssh2_arcfour};
  1553. const TCipher TCiphers[] = {cip3DES, cipDES, cipAES, cipBlowfish, cipArcfour};
  1554. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1555. TCipher Result = cipWarn;
  1556. for (int C = 0; C < LENOF(TCiphers); C++)
  1557. {
  1558. for (int F = 0; F < CipherFuncs[C]->nciphers; F++)
  1559. {
  1560. if ((ssh2_cipher *)Cipher == CipherFuncs[C]->list[F])
  1561. {
  1562. Result = TCiphers[C];
  1563. }
  1564. }
  1565. }
  1566. assert(Result != cipWarn);
  1567. return Result;
  1568. }
  1569. //---------------------------------------------------------------------------
  1570. struct TClipboardHandler
  1571. {
  1572. AnsiString Text;
  1573. void __fastcall Copy(TObject * /*Sender*/)
  1574. {
  1575. CopyToClipboard(Text);
  1576. }
  1577. };
  1578. //---------------------------------------------------------------------------
  1579. void __fastcall TSecureShell::VerifyHostKey(AnsiString Host, int Port,
  1580. const AnsiString KeyType, AnsiString KeyStr, const AnsiString Fingerprint)
  1581. {
  1582. GotHostKey();
  1583. char Delimiter = ';';
  1584. assert(KeyStr.Pos(Delimiter) == 0);
  1585. if (FSessionData->Tunnel)
  1586. {
  1587. Host = FSessionData->OrigHostName;
  1588. Port = FSessionData->OrigPortNumber;
  1589. }
  1590. FSessionInfo.HostKeyFingerprint = Fingerprint;
  1591. bool Result = false;
  1592. AnsiString Buf = FSessionData->HostKey;
  1593. while (!Result && !Buf.IsEmpty())
  1594. {
  1595. AnsiString ExpectedKey = CutToChar(Buf, Delimiter, false);
  1596. if (ExpectedKey == Fingerprint)
  1597. {
  1598. Result = true;
  1599. }
  1600. }
  1601. AnsiString StoredKeys;
  1602. if (!Result)
  1603. {
  1604. StoredKeys.SetLength(10240);
  1605. if (retrieve_host_key(Host.c_str(), Port, KeyType.c_str(),
  1606. StoredKeys.c_str(), StoredKeys.Length()) == 0)
  1607. {
  1608. PackStr(StoredKeys);
  1609. AnsiString Buf = StoredKeys;
  1610. while (!Result && !Buf.IsEmpty())
  1611. {
  1612. AnsiString StoredKey = CutToChar(Buf, Delimiter, false);
  1613. if (StoredKey == KeyStr)
  1614. {
  1615. Result = true;
  1616. }
  1617. }
  1618. }
  1619. else
  1620. {
  1621. StoredKeys = "";
  1622. }
  1623. }
  1624. if (!Result)
  1625. {
  1626. if (Configuration->DisableAcceptingHostKeys)
  1627. {
  1628. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1629. }
  1630. else
  1631. {
  1632. TClipboardHandler ClipboardHandler;
  1633. ClipboardHandler.Text = Fingerprint;
  1634. bool Unknown = StoredKeys.IsEmpty();
  1635. int Answers;
  1636. int AliasesCount;
  1637. TQueryButtonAlias Aliases[3];
  1638. Aliases[0].Button = qaRetry;
  1639. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  1640. Aliases[0].OnClick = &ClipboardHandler.Copy;
  1641. Answers = qaYes | qaCancel | qaRetry;
  1642. AliasesCount = 1;
  1643. if (!Unknown)
  1644. {
  1645. Aliases[1].Button = qaYes;
  1646. Aliases[1].Alias = LoadStr(UPDATE_KEY_BUTTON);
  1647. Aliases[2].Button = qaOK;
  1648. Aliases[2].Alias = LoadStr(ADD_KEY_BUTTON);
  1649. AliasesCount += 2;
  1650. Answers |= qaSkip | qaOK;
  1651. }
  1652. else
  1653. {
  1654. Answers |= qaNo;
  1655. }
  1656. TQueryParams Params;
  1657. Params.NoBatchAnswers = qaYes | qaRetry | qaSkip | qaOK;
  1658. Params.HelpKeyword = (Unknown ? HELP_UNKNOWN_KEY : HELP_DIFFERENT_KEY);
  1659. Params.Aliases = Aliases;
  1660. Params.AliasesCount = AliasesCount;
  1661. int R = FUI->QueryUser(
  1662. FMTLOAD((Unknown ? UNKNOWN_KEY2 : DIFFERENT_KEY3), (KeyType, Fingerprint)),
  1663. NULL, Answers, &Params, qtWarning);
  1664. switch (R) {
  1665. case qaOK:
  1666. assert(!Unknown);
  1667. KeyStr = (StoredKeys + Delimiter + KeyStr);
  1668. // fall thru
  1669. case qaYes:
  1670. store_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1671. break;
  1672. case qaCancel:
  1673. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1674. }
  1675. }
  1676. }
  1677. }
  1678. //---------------------------------------------------------------------------
  1679. void __fastcall TSecureShell::AskAlg(const AnsiString AlgType,
  1680. const AnsiString AlgName)
  1681. {
  1682. AnsiString Msg;
  1683. if (AlgType == "key-exchange algorithm")
  1684. {
  1685. Msg = FMTLOAD(KEX_BELOW_TRESHOLD, (AlgName));
  1686. }
  1687. else
  1688. {
  1689. int CipherType;
  1690. if (AlgType == "cipher")
  1691. {
  1692. CipherType = CIPHER_TYPE_BOTH;
  1693. }
  1694. else if (AlgType == "client-to-server cipher")
  1695. {
  1696. CipherType = CIPHER_TYPE_CS;
  1697. }
  1698. else if (AlgType == "server-to-client cipher")
  1699. {
  1700. CipherType = CIPHER_TYPE_SC;
  1701. }
  1702. else
  1703. {
  1704. assert(false);
  1705. }
  1706. Msg = FMTLOAD(CIPHER_BELOW_TRESHOLD, (LoadStr(CipherType), AlgName));
  1707. }
  1708. if (FUI->QueryUser(Msg, NULL, qaYes | qaNo, NULL, qtWarning) == qaNo)
  1709. {
  1710. Abort();
  1711. }
  1712. }
  1713. //---------------------------------------------------------------------------
  1714. void __fastcall TSecureShell::DisplayBanner(const AnsiString & Banner)
  1715. {
  1716. FUI->DisplayBanner(Banner);
  1717. }
  1718. //---------------------------------------------------------------------------
  1719. void __fastcall TSecureShell::OldKeyfileWarning()
  1720. {
  1721. // actually never called, see Net.cpp
  1722. FUI->QueryUser(LoadStr(OLD_KEY), NULL, qaOK, NULL, qtWarning);
  1723. }
  1724. //---------------------------------------------------------------------------
  1725. bool __fastcall TSecureShell::GetStoredCredentialsTried()
  1726. {
  1727. return FStoredPasswordTried || FStoredPasswordTriedForKI;
  1728. }
  1729. //---------------------------------------------------------------------------
  1730. bool __fastcall TSecureShell::GetReady()
  1731. {
  1732. return FOpened && (FWaiting == 0);
  1733. }