SecureShell.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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. #define SSH_ERROR(x) throw ESsh(NULL, x)
  17. #define SSH_FATAL_ERROR_EXT(E, x) throw ESshFatal(E, x)
  18. #define SSH_FATAL_ERROR(x) SSH_FATAL_ERROR_EXT(NULL, x)
  19. //---------------------------------------------------------------------------
  20. #pragma package(smart_init)
  21. //---------------------------------------------------------------------------
  22. #define MAX_BUFSIZE 32768
  23. //---------------------------------------------------------------------------
  24. struct TPuttyTranslation
  25. {
  26. const char * Original;
  27. int Translation;
  28. };
  29. //---------------------------------------------------------------------------
  30. __fastcall TSecureShell::TSecureShell(TSessionUI* UI,
  31. TSessionData * SessionData, TSessionLog * Log, TConfiguration * Configuration)
  32. {
  33. FUI = UI;
  34. FSessionData = SessionData;
  35. FLog = Log;
  36. FConfiguration = Configuration;
  37. FActive = false;
  38. OutPtr = NULL;
  39. Pending = NULL;
  40. FBackendHandle = NULL;
  41. ResetConnection();
  42. FOnCaptureOutput = NULL;
  43. FOnReceive = NULL;
  44. FConfig = new Config();
  45. FSocket = INVALID_SOCKET;
  46. FSocketEvent = CreateEvent(NULL, false, false, NULL);
  47. FFrozen = false;
  48. }
  49. //---------------------------------------------------------------------------
  50. __fastcall TSecureShell::~TSecureShell()
  51. {
  52. Active = false;
  53. ResetConnection();
  54. CloseHandle(FSocketEvent);
  55. delete FConfig;
  56. FConfig = NULL;
  57. }
  58. //---------------------------------------------------------------------------
  59. void __fastcall TSecureShell::ResetConnection()
  60. {
  61. FreeBackend();
  62. ClearStdError();
  63. PendLen = 0;
  64. PendSize = 0;
  65. sfree(Pending);
  66. Pending = NULL;
  67. FCWriteTemp = "";
  68. ResetSessionInfo();
  69. FAuthenticating = false;
  70. FAuthenticated = false;
  71. FStoredPasswordTried = false;
  72. FStoredPasswordTriedForKI = false;
  73. }
  74. //---------------------------------------------------------------------------
  75. void __fastcall TSecureShell::ResetSessionInfo()
  76. {
  77. FSessionInfoValid = false;
  78. FMaxPacketSize = NULL;
  79. }
  80. //---------------------------------------------------------------------------
  81. inline void __fastcall TSecureShell::UpdateSessionInfo()
  82. {
  83. if (!FSessionInfoValid)
  84. {
  85. FSshVersion = get_ssh_version(FBackendHandle);
  86. FSessionInfo.ProtocolBaseName = "SSH";
  87. FSessionInfo.ProtocolName =
  88. FORMAT("%s-%d", (FSessionInfo.ProtocolBaseName, get_ssh_version(FBackendHandle)));
  89. FSessionInfo.SecurityProtocolName = FSessionInfo.ProtocolName;
  90. FSessionInfo.CSCompression =
  91. FuncToCompression(FSshVersion, get_cscomp(FBackendHandle));
  92. FSessionInfo.SCCompression =
  93. FuncToCompression(FSshVersion, get_sccomp(FBackendHandle));
  94. if (FSshVersion == 1)
  95. {
  96. FSessionInfo.CSCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  97. FSessionInfo.SCCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  98. }
  99. else
  100. {
  101. FSessionInfo.CSCipher = CipherNames[FuncToSsh2Cipher(get_cscipher(FBackendHandle))];
  102. FSessionInfo.SCCipher = CipherNames[FuncToSsh2Cipher(get_sccipher(FBackendHandle))];
  103. }
  104. FSessionInfoValid = true;
  105. }
  106. }
  107. //---------------------------------------------------------------------------
  108. const TSessionInfo & __fastcall TSecureShell::GetSessionInfo()
  109. {
  110. if (!FSessionInfoValid)
  111. {
  112. UpdateSessionInfo();
  113. }
  114. return FSessionInfo;
  115. }
  116. //---------------------------------------------------------------------
  117. void __fastcall TSecureShell::StoreToConfig(TSessionData * Data, Config * cfg)
  118. {
  119. // clear all (parameters not set below)
  120. memset(cfg, 0, sizeof(*cfg));
  121. // user-configurable settings
  122. ASCOPY(cfg->host, Data->HostName);
  123. ASCOPY(cfg->username, Data->UserName);
  124. cfg->port = Data->PortNumber;
  125. cfg->protocol = PROT_SSH;
  126. // always set 0, as we will handle keepalives ourselves to avoid
  127. // multi-threaded issues in putty timer list
  128. cfg->ping_interval = 0;
  129. cfg->compression = Data->Compression;
  130. cfg->agentfwd = Data->AgentFwd;
  131. cfg->addressfamily = Data->AddressFamily;
  132. ASCOPY(cfg->ssh_rekey_data, Data->RekeyData);
  133. cfg->ssh_rekey_time = Data->RekeyTime;
  134. for (int c = 0; c < CIPHER_COUNT; c++)
  135. {
  136. int pcipher;
  137. switch (Data->Cipher[c]) {
  138. case cipWarn: pcipher = CIPHER_WARN; break;
  139. case cip3DES: pcipher = CIPHER_3DES; break;
  140. case cipBlowfish: pcipher = CIPHER_BLOWFISH; break;
  141. case cipAES: pcipher = CIPHER_AES; break;
  142. case cipDES: pcipher = CIPHER_DES; break;
  143. default: assert(false);
  144. }
  145. cfg->ssh_cipherlist[c] = pcipher;
  146. }
  147. for (int k = 0; k < KEX_COUNT; k++)
  148. {
  149. int pkex;
  150. switch (Data->Kex[k]) {
  151. case kexWarn: pkex = KEX_WARN; break;
  152. case kexDHGroup1: pkex = KEX_DHGROUP1; break;
  153. case kexDHGroup14: pkex = KEX_DHGROUP14; break;
  154. case kexDHGEx: pkex = KEX_DHGEX; break;
  155. default: assert(false);
  156. }
  157. cfg->ssh_kexlist[k] = pkex;
  158. }
  159. AnsiString SPublicKeyFile = Data->PublicKeyFile;
  160. if (SPublicKeyFile.IsEmpty()) SPublicKeyFile = Configuration->DefaultKeyFile;
  161. SPublicKeyFile = StripPathQuotes(ExpandEnvironmentVariables(SPublicKeyFile));
  162. ASCOPY(cfg->keyfile.path, SPublicKeyFile);
  163. cfg->sshprot = Data->SshProt;
  164. cfg->ssh2_des_cbc = Data->Ssh2DES;
  165. cfg->try_tis_auth = Data->AuthTIS;
  166. cfg->try_ki_auth = Data->AuthKI;
  167. cfg->try_gssapi_auth = Data->AuthGSSAPI;
  168. cfg->gssapi_fwd_tgt = Data->GSSAPIFwdTGT;
  169. ASCOPY(cfg->gssapi_server_realm, Data->GSSAPIServerRealm);
  170. cfg->change_username = Data->ChangeUsername;
  171. cfg->proxy_type = Data->ProxyMethod;
  172. ASCOPY(cfg->proxy_host, Data->ProxyHost);
  173. cfg->proxy_port = Data->ProxyPort;
  174. ASCOPY(cfg->proxy_username, Data->ProxyUsername);
  175. ASCOPY(cfg->proxy_password, Data->ProxyPassword);
  176. ASCOPY(cfg->proxy_telnet_command, Data->ProxyTelnetCommand);
  177. cfg->proxy_dns = Data->ProxyDNS;
  178. cfg->even_proxy_localhost = Data->ProxyLocalhost;
  179. #pragma option push -w-eas
  180. // after 0.53b values were reversed, however putty still stores
  181. // settings to registry in save way as before
  182. cfg->sshbug_ignore1 = Data->Bug[sbIgnore1];
  183. cfg->sshbug_plainpw1 = Data->Bug[sbPlainPW1];
  184. cfg->sshbug_rsa1 = Data->Bug[sbRSA1];
  185. cfg->sshbug_hmac2 = Data->Bug[sbHMAC2];
  186. cfg->sshbug_derivekey2 = Data->Bug[sbDeriveKey2];
  187. cfg->sshbug_rsapad2 = Data->Bug[sbRSAPad2];
  188. cfg->sshbug_rekey2 = Data->Bug[sbRekey2];
  189. // new after 0.53b
  190. cfg->sshbug_pksessid2 = Data->Bug[sbPKSessID2];
  191. #pragma option pop
  192. if (!Data->TunnelPortFwd.IsEmpty())
  193. {
  194. ASCOPY(cfg->portfwd, Data->TunnelPortFwd);
  195. // when setting up a tunnel, do not open shell/sftp
  196. cfg->ssh_no_shell = TRUE;
  197. }
  198. else
  199. {
  200. if (Data->FSProtocol == fsSCPonly)
  201. {
  202. cfg->ssh_subsys = FALSE;
  203. if (Data->Shell.IsEmpty())
  204. {
  205. // Following forces Putty to open default shell
  206. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  207. cfg->remote_cmd[0] = '\0';
  208. }
  209. else
  210. {
  211. ASCOPY(cfg->remote_cmd, Data->Shell);
  212. }
  213. }
  214. else
  215. {
  216. cfg->ssh_subsys = TRUE;
  217. strcpy(cfg->remote_cmd, "sftp");
  218. if (Data->FSProtocol != fsSFTPonly)
  219. {
  220. cfg->ssh_subsys2 = FALSE;
  221. if (Data->Shell.IsEmpty())
  222. {
  223. // Following forces Putty to open default shell
  224. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  225. cfg->remote_cmd2[0] = '\0';
  226. }
  227. else
  228. {
  229. ASCOPY(cfg->remote_cmd2, Data->Shell);
  230. }
  231. // Putty reads only "ptr" member for fallback
  232. cfg->remote_cmd_ptr2 = cfg->remote_cmd2;
  233. }
  234. else
  235. {
  236. // see psftp_connect() from psftp.c
  237. cfg->ssh_subsys2 = FALSE;
  238. cfg->remote_cmd_ptr2 =
  239. "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
  240. "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
  241. "exec sftp-server";
  242. }
  243. }
  244. }
  245. // permanent settings
  246. cfg->nopty = TRUE;
  247. cfg->tcp_keepalives = 0;
  248. }
  249. //---------------------------------------------------------------------------
  250. void __fastcall TSecureShell::Open()
  251. {
  252. ResetConnection();
  253. FAuthenticating = false;
  254. FAuthenticated = false;
  255. Active = false;
  256. FBackend = &ssh_backend;
  257. FAuthenticationLog = "";
  258. FUI->Information(LoadStr(STATUS_LOOKUPHOST), true);
  259. StoreToConfig(FSessionData, FConfig);
  260. char * RealHost;
  261. FreeBackend(); // in case we are reconnecting
  262. const char * InitError = FBackend->init(this, &FBackendHandle, FConfig,
  263. FSessionData->HostName.c_str(), FSessionData->PortNumber, &RealHost, 0,
  264. FConfig->tcp_keepalives);
  265. sfree(RealHost);
  266. if (InitError)
  267. {
  268. PuttyFatalError(InitError);
  269. }
  270. FUI->Information(LoadStr(STATUS_CONNECT), true);
  271. /*FLoggingContext = log_init(this, (void *)FConfig);
  272. FBackend->provide_logctx(FBackendHandle, FLoggingContext);*/
  273. Init();
  274. CheckConnection(CONNECTION_FAILED);
  275. FLastDataSent = Now();
  276. FSessionInfo.LoginTime = Now();
  277. FAuthenticating = false;
  278. FAuthenticated = true;
  279. FUI->Information(LoadStr(STATUS_AUTHENTICATED), true);
  280. ResetSessionInfo();
  281. assert(!FSessionInfo.SshImplementation.IsEmpty());
  282. }
  283. //---------------------------------------------------------------------------
  284. void __fastcall TSecureShell::Init()
  285. {
  286. try
  287. {
  288. try
  289. {
  290. while (!get_ssh_state_session(FBackendHandle))
  291. {
  292. if (Configuration->LogProtocol >= 1)
  293. {
  294. LogEvent("Waiting for the server to continue with the initialisation");
  295. }
  296. WaitForData();
  297. }
  298. // unless this is tunnel session, it must be safe to send now
  299. assert(FBackend->sendok(FBackendHandle) || !FSessionData->TunnelPortFwd.IsEmpty());
  300. }
  301. catch(Exception & E)
  302. {
  303. if (FAuthenticating && !FAuthenticationLog.IsEmpty())
  304. {
  305. FatalError(&E, FMTLOAD(AUTHENTICATION_LOG, (FAuthenticationLog)));
  306. }
  307. else
  308. {
  309. throw;
  310. }
  311. }
  312. }
  313. catch(Exception & E)
  314. {
  315. if (FAuthenticating)
  316. {
  317. FatalError(&E, LoadStr(AUTHENTICATION_FAILED));
  318. }
  319. else
  320. {
  321. throw;
  322. }
  323. }
  324. }
  325. //---------------------------------------------------------------------------
  326. void __fastcall TSecureShell::PuttyLogEvent(const AnsiString & Str)
  327. {
  328. #define SERVER_VERSION_MSG "Server version: "
  329. // Gross hack
  330. if (Str.Pos(SERVER_VERSION_MSG) == 1)
  331. {
  332. FSessionInfo.SshVersionString = Str.SubString(strlen(SERVER_VERSION_MSG) + 1,
  333. Str.Length() - strlen(SERVER_VERSION_MSG));
  334. const char * Ptr = strchr(FSessionInfo.SshVersionString.c_str(), '-');
  335. if (Ptr != NULL)
  336. {
  337. Ptr = strchr(Ptr + 1, '-');
  338. }
  339. FSessionInfo.SshImplementation = (Ptr != NULL) ? Ptr + 1 : "";
  340. }
  341. #define FORWARDING_FAILURE_MSG "Forwarded connection refused by server: "
  342. else if (Str.Pos(FORWARDING_FAILURE_MSG) == 1)
  343. {
  344. FLastTunnelError = Str.SubString(strlen(FORWARDING_FAILURE_MSG) + 1,
  345. Str.Length() - strlen(FORWARDING_FAILURE_MSG));
  346. static const TPuttyTranslation Translation[] = {
  347. { "Administratively prohibited [%]", PFWD_TRANSL_ADMIN },
  348. { "Connect failed [%]", PFWD_TRANSL_CONNECT },
  349. };
  350. TranslatePuttyMessage(Translation, LENOF(Translation), FLastTunnelError);
  351. }
  352. LogEvent(Str);
  353. }
  354. //---------------------------------------------------------------------------
  355. bool __fastcall TSecureShell::PromptUser(const AnsiString Prompt,
  356. AnsiString & Response, bool IsPassword)
  357. {
  358. bool Result;
  359. if (!IsPassword)
  360. {
  361. assert(Prompt == "login as: ");
  362. LogEvent(FORMAT("Username prompt (%s)", (Prompt)));
  363. if (FSessionData->AuthGSSAPI)
  364. {
  365. // use empty username if no username was filled on login dialog
  366. // and GSSAPI auth is enabled, hence there's chance that the server can
  367. // deduce the username otherwise
  368. Response = "";
  369. Result = true;
  370. }
  371. else
  372. {
  373. Result = FUI->PromptUser(FSessionData,
  374. FMTLOAD(USERNAME_PROMPT, (FSessionData->SessionName)),
  375. pkPrompt, Response);
  376. if (Result)
  377. {
  378. FUserName = Response;
  379. }
  380. }
  381. }
  382. else
  383. {
  384. if (Prompt.Pos("Passphrase for key ") == 1)
  385. {
  386. AnsiString Key(Prompt);
  387. int P = Prompt.Pos("\"");
  388. if (P > 0)
  389. {
  390. Key.Delete(1, P);
  391. P = Key.LastDelimiter("\"");
  392. if (P > 0)
  393. {
  394. Key.SetLength(P - 1);
  395. }
  396. }
  397. LogEvent(FORMAT("Passphrase prompt (%s)", (Prompt)));
  398. Result = FUI->PromptUser(FSessionData, FMTLOAD(PROMPT_KEY_PASSPHRASE, (Key)),
  399. pkPassphrase, Response);
  400. }
  401. else if (Prompt.Pos("'s password: "))
  402. {
  403. LogEvent(FORMAT("Session password prompt (%s)", (Prompt)));
  404. if (!FSessionData->Password.IsEmpty() && !FStoredPasswordTried)
  405. {
  406. LogEvent("Using stored password.");
  407. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  408. Result = true;
  409. Response = FSessionData->Password;
  410. FStoredPasswordTried = true;
  411. }
  412. else
  413. {
  414. Result = FUI->PromptUser(FSessionData,
  415. FMTLOAD(PROMPT_SESSION_PASSWORD, (FSessionData->SessionName)),
  416. pkPassword, Response);
  417. }
  418. }
  419. else
  420. {
  421. // in other cases we assume TIS/Cryptocard/keyboard-interactive authentification prompt
  422. LogEvent(FORMAT("%s prompt from server", (Prompt)));
  423. if (FSessionData->AuthKIPassword && !FSessionData->Password.IsEmpty() &&
  424. !FStoredPasswordTriedForKI)
  425. {
  426. LogEvent("Using stored password.");
  427. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  428. Result = true;
  429. Response = FSessionData->Password;
  430. FStoredPasswordTriedForKI = true;
  431. }
  432. else
  433. {
  434. static const AnsiString ResponseSuffix("\r\nResponse: ");
  435. // Strip Cryptocard/TIS "Response" suffix
  436. AnsiString UserPrompt = Prompt;
  437. if (UserPrompt.SubString(UserPrompt.Length() - ResponseSuffix.Length() + 1,
  438. ResponseSuffix.Length()) == ResponseSuffix)
  439. {
  440. UserPrompt.SetLength(UserPrompt.Length() - ResponseSuffix.Length());
  441. }
  442. // some servers add leading blank line to make the prompt look prettier
  443. // on terminal console
  444. UserPrompt = UserPrompt.Trim();
  445. Result = FUI->PromptUser(FSessionData, UserPrompt, pkServerPrompt, Response);
  446. }
  447. };
  448. }
  449. return Result;
  450. }
  451. //---------------------------------------------------------------------------
  452. void __fastcall TSecureShell::GotHostKey()
  453. {
  454. // due to re-key GotHostKey() may be called again later during session
  455. if (!FAuthenticating && !FAuthenticated)
  456. {
  457. FAuthenticating = true;
  458. FUI->Information(LoadStr(STATUS_AUTHENTICATE), true);
  459. }
  460. }
  461. //---------------------------------------------------------------------------
  462. void __fastcall TSecureShell::CWrite(const char * Data, int Length, bool Untrusted)
  463. {
  464. // some messages to stderr may indicate that something has changed with the
  465. // session, so reset the session info
  466. ResetSessionInfo();
  467. // We send only whole line at once, so we have to cache incoming data
  468. FCWriteTemp += DeleteChar(AnsiString(Data, Length), '\r');
  469. AnsiString Line;
  470. // Do we have at least one complete line in std error cache?
  471. while (FCWriteTemp.Pos("\n") > 0)
  472. {
  473. AnsiString Line = CutToChar(FCWriteTemp, '\n', false);
  474. FLog->Add(llStdError, Line);
  475. if (FAuthenticating)
  476. {
  477. // No point trying to translate message coming from server
  478. if (!Untrusted)
  479. {
  480. TranslateAuthenticationMessage(Line);
  481. }
  482. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Line;
  483. }
  484. // Untrusted means generally that it comes from the server,
  485. // do not use such a output as "information" for end user
  486. if (!Untrusted)
  487. {
  488. FUI->Information(Line, false);
  489. }
  490. }
  491. }
  492. //---------------------------------------------------------------------------
  493. void __fastcall TSecureShell::RegisterReceiveHandler(TNotifyEvent Handler)
  494. {
  495. assert(FOnReceive == NULL);
  496. FOnReceive = Handler;
  497. }
  498. //---------------------------------------------------------------------------
  499. void __fastcall TSecureShell::UnregisterReceiveHandler(TNotifyEvent Handler)
  500. {
  501. assert(FOnReceive == Handler);
  502. USEDPARAM(Handler);
  503. FOnReceive = NULL;
  504. }
  505. //---------------------------------------------------------------------------
  506. void __fastcall TSecureShell::FromBackend(bool IsStdErr, const char * Data, int Length)
  507. {
  508. CheckConnection();
  509. if (Configuration->LogProtocol >= 1)
  510. {
  511. LogEvent(FORMAT("Received %u bytes (%d)", (Length, int(IsStdErr))));
  512. }
  513. // Following is taken from scp.c from_backend() and modified
  514. if (IsStdErr)
  515. {
  516. AddStdError(AnsiString(Data, Length));
  517. }
  518. else
  519. {
  520. unsigned char *p = (unsigned char *)Data;
  521. unsigned Len = (unsigned)Length;
  522. // with event-select mechanism we can now receive data even before we
  523. // actually expect them (OutPtr can be NULL)
  524. if ((OutPtr != NULL) && (OutLen > 0) && (Len > 0))
  525. {
  526. unsigned Used = OutLen;
  527. if (Used > Len) Used = Len;
  528. memcpy(OutPtr, p, Used);
  529. OutPtr += Used; OutLen -= Used;
  530. p += Used; Len -= Used;
  531. }
  532. if (Len > 0)
  533. {
  534. if (PendSize < PendLen + Len)
  535. {
  536. PendSize = PendLen + Len + 4096;
  537. Pending = (char *)
  538. (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize));
  539. if (!Pending) FatalError("Out of memory");
  540. }
  541. memcpy(Pending + PendLen, p, Len);
  542. PendLen += Len;
  543. }
  544. if (FOnReceive != NULL)
  545. {
  546. if (!FFrozen)
  547. {
  548. FFrozen = true;
  549. try
  550. {
  551. do
  552. {
  553. FDataWhileFrozen = false;
  554. FOnReceive(NULL);
  555. }
  556. while (FDataWhileFrozen);
  557. }
  558. __finally
  559. {
  560. FFrozen = false;
  561. }
  562. }
  563. else
  564. {
  565. FDataWhileFrozen = true;
  566. }
  567. }
  568. }
  569. }
  570. //---------------------------------------------------------------------------
  571. bool __fastcall TSecureShell::Peek(char *& Buf, int Len)
  572. {
  573. bool Result = (int(PendLen) >= Len);
  574. if (Result)
  575. {
  576. Buf = Pending;
  577. }
  578. return Result;
  579. }
  580. //---------------------------------------------------------------------------
  581. Integer __fastcall TSecureShell::Receive(char * Buf, Integer Len)
  582. {
  583. CheckConnection();
  584. if (Len > 0)
  585. {
  586. // Following is taken from scp.c ssh_scp_recv() and modified
  587. OutPtr = Buf;
  588. OutLen = Len;
  589. try
  590. {
  591. /*
  592. * See if the pending-input block contains some of what we
  593. * need.
  594. */
  595. if (PendLen > 0)
  596. {
  597. unsigned PendUsed = PendLen;
  598. if (PendUsed > OutLen)
  599. {
  600. PendUsed = OutLen;
  601. }
  602. memcpy(OutPtr, Pending, PendUsed);
  603. memmove(Pending, Pending + PendUsed, PendLen - PendUsed);
  604. OutPtr += PendUsed;
  605. OutLen -= PendUsed;
  606. PendLen -= PendUsed;
  607. if (PendLen == 0)
  608. {
  609. PendSize = 0;
  610. sfree(Pending);
  611. Pending = NULL;
  612. }
  613. }
  614. while (OutLen > 0)
  615. {
  616. if (Configuration->LogProtocol >= 1)
  617. {
  618. LogEvent(FORMAT("Waiting for another %u bytes", (static_cast<int>(OutLen))));
  619. }
  620. WaitForData();
  621. }
  622. // This seems ambiguous
  623. if (Len <= 0) FatalError(LoadStr(LOST_CONNECTION));
  624. }
  625. __finally
  626. {
  627. OutPtr = NULL;
  628. }
  629. };
  630. if (Configuration->LogProtocol >= 1)
  631. {
  632. LogEvent(FORMAT("Read %u bytes (%d pending)",
  633. (static_cast<int>(Len), static_cast<int>(PendLen))));
  634. }
  635. return Len;
  636. }
  637. //---------------------------------------------------------------------------
  638. AnsiString __fastcall TSecureShell::ReceiveLine()
  639. {
  640. unsigned Index;
  641. Char Ch;
  642. AnsiString Line;
  643. Boolean EOL = False;
  644. do
  645. {
  646. // If there is any buffer of received chars
  647. if (PendLen > 0)
  648. {
  649. Index = 0;
  650. // Repeat until we walk thru whole buffer or reach end-of-line
  651. while ((Index < PendLen) && (!Index || (Pending[Index-1] != '\n')))
  652. {
  653. Index++;
  654. }
  655. EOL = (Boolean)(Index && (Pending[Index-1] == '\n'));
  656. Integer PrevLen = Line.Length();
  657. Line.SetLength(PrevLen + Index);
  658. Receive(Line.c_str() + PrevLen, Index);
  659. }
  660. // If buffer don't contain end-of-line character
  661. // we read one more which causes receiving new buffer of chars
  662. if (!EOL)
  663. {
  664. Receive(&Ch, 1);
  665. Line += Ch;
  666. EOL = (Ch == '\n');
  667. }
  668. }
  669. while (!EOL);
  670. // We don't want end-of-line character
  671. Line.SetLength(Line.Length()-1);
  672. CaptureOutput(llOutput, Line);
  673. return Line;
  674. }
  675. //---------------------------------------------------------------------------
  676. void __fastcall TSecureShell::SendSpecial(int Code)
  677. {
  678. LogEvent(FORMAT("Sending special code: %d", (Code)));
  679. CheckConnection();
  680. FBackend->special(FBackendHandle, (Telnet_Special)Code);
  681. CheckConnection();
  682. FLastDataSent = Now();
  683. }
  684. //---------------------------------------------------------------------------
  685. void __fastcall TSecureShell::SendEOF()
  686. {
  687. SendSpecial(TS_EOF);
  688. }
  689. //---------------------------------------------------------------------------
  690. void __fastcall TSecureShell::Send(const char * Buf, Integer Len)
  691. {
  692. CheckConnection();
  693. int BufSize = FBackend->send(FBackendHandle, (char *)Buf, Len);
  694. if (Configuration->LogProtocol >= 1)
  695. {
  696. LogEvent(FORMAT("Sent %u bytes", (static_cast<int>(Len))));
  697. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  698. }
  699. FLastDataSent = Now();
  700. // among other forces receive of pending data to free the servers's send buffer
  701. EventSelectLoop(0, false);
  702. while (BufSize > MAX_BUFSIZE)
  703. {
  704. if (Configuration->LogProtocol >= 1)
  705. {
  706. LogEvent(FORMAT("There are %u bytes remaining in the send buffer, "
  707. "need to send at least another %u bytes",
  708. (BufSize, BufSize - MAX_BUFSIZE)));
  709. }
  710. EventSelectLoop(100, false);
  711. BufSize = FBackend->sendbuffer(FBackendHandle);
  712. if (Configuration->LogProtocol >= 1)
  713. {
  714. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  715. }
  716. }
  717. CheckConnection();
  718. }
  719. //---------------------------------------------------------------------------
  720. void __fastcall TSecureShell::SendNull()
  721. {
  722. LogEvent("Sending NULL.");
  723. Send("", 1);
  724. }
  725. //---------------------------------------------------------------------------
  726. void __fastcall TSecureShell::SendStr(AnsiString Str)
  727. {
  728. CheckConnection();
  729. Send(Str.c_str(), Str.Length());
  730. }
  731. //---------------------------------------------------------------------------
  732. void __fastcall TSecureShell::SendLine(AnsiString Line)
  733. {
  734. SendStr(Line);
  735. Send("\n", 1);
  736. FLog->Add(llInput, Line);
  737. }
  738. //---------------------------------------------------------------------------
  739. bool __fastcall TSecureShell::TranslatePuttyMessage(
  740. const TPuttyTranslation * Translation, size_t Count, AnsiString & Message)
  741. {
  742. bool Result = false;
  743. for (unsigned int Index = 0; Index < Count; Index++)
  744. {
  745. const char * Original = Translation[Index].Original;
  746. const char * Div = strchr(Original, '%');
  747. if (Div == NULL)
  748. {
  749. if (strcmp(Message.c_str(), Original) == 0)
  750. {
  751. Message = LoadStr(Translation[Index].Translation);
  752. Result = true;
  753. break;
  754. }
  755. }
  756. else
  757. {
  758. size_t OriginalLen = strlen(Original);
  759. size_t PrefixLen = Div - Original;
  760. size_t SuffixLen = OriginalLen - PrefixLen - 1;
  761. if (((size_t)Message.Length() >= OriginalLen - 1) &&
  762. (strncmp(Message.c_str(), Original, PrefixLen) == 0) &&
  763. (strncmp(Message.c_str() + Message.Length() - SuffixLen, Div + 1, SuffixLen) == 0))
  764. {
  765. Message = FMTLOAD(Translation[Index].Translation,
  766. (Message.SubString(PrefixLen + 1, Message.Length() - PrefixLen - SuffixLen).TrimRight()));
  767. Result = true;
  768. break;
  769. }
  770. }
  771. }
  772. return Result;
  773. }
  774. //---------------------------------------------------------------------------
  775. bool __fastcall TSecureShell::TranslateAuthenticationMessage(AnsiString & Message)
  776. {
  777. static const TPuttyTranslation Translation[] = {
  778. { "Using username \"%\".", AUTH_TRANSL_USERNAME },
  779. { "Using keyboard-interactive authentication.", AUTH_TRANSL_KEYB_INTER },
  780. { "Authenticating with public key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  781. { "Authenticating with public key \"%\"", AUTH_TRANSL_PUBLIC_KEY },
  782. { "Authenticated using RSA key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  783. { "Wrong passphrase", AUTH_TRANSL_WRONG_PASSPHRASE },
  784. { "Wrong passphrase.", AUTH_TRANSL_WRONG_PASSPHRASE },
  785. { "Access denied", AUTH_TRANSL_ACCESS_DENIED },
  786. { "Trying public key authentication.", AUTH_TRANSL_TRY_PUBLIC_KEY },
  787. { "Server refused our public key.", AUTH_TRANSL_KEY_REFUSED },
  788. { "Server refused our key", AUTH_TRANSL_KEY_REFUSED }
  789. };
  790. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  791. }
  792. //---------------------------------------------------------------------------
  793. void __fastcall TSecureShell::AddStdError(AnsiString Str)
  794. {
  795. FStdError += Str;
  796. Integer P;
  797. Str = DeleteChar(Str, '\r');
  798. // We send only whole line at once to log, so we have to cache
  799. // incoming std error data
  800. FStdErrorTemp += Str;
  801. AnsiString Line;
  802. // Do we have at least one complete line in std error cache?
  803. while ((P = FStdErrorTemp.Pos("\n")) > 0)
  804. {
  805. Line = FStdErrorTemp.SubString(1, P-1);
  806. FStdErrorTemp.Delete(1, P);
  807. AddStdErrorLine(Line);
  808. }
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall TSecureShell::AddStdErrorLine(const AnsiString & Str)
  812. {
  813. if (FAuthenticating)
  814. {
  815. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Str;
  816. }
  817. CaptureOutput(llStdError, Str);
  818. }
  819. //---------------------------------------------------------------------------
  820. const AnsiString & __fastcall TSecureShell::GetStdError()
  821. {
  822. return FStdError;
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall TSecureShell::ClearStdError()
  826. {
  827. // Flush std error cache
  828. if (!FStdErrorTemp.IsEmpty())
  829. {
  830. if (FAuthenticating)
  831. {
  832. FAuthenticationLog +=
  833. (FAuthenticationLog.IsEmpty() ? "" : "\n") + FStdErrorTemp;
  834. }
  835. CaptureOutput(llStdError, FStdErrorTemp);
  836. FStdErrorTemp = "";
  837. }
  838. FStdError = "";
  839. }
  840. //---------------------------------------------------------------------------
  841. void __fastcall TSecureShell::CaptureOutput(TLogLineType Type,
  842. const AnsiString & Line)
  843. {
  844. if (FOnCaptureOutput != NULL)
  845. {
  846. FOnCaptureOutput(Line, (Type == llStdError));
  847. }
  848. FLog->Add(Type, Line);
  849. }
  850. //---------------------------------------------------------------------------
  851. void __fastcall TSecureShell::FatalError(Exception * E, AnsiString Msg)
  852. {
  853. // the same code is in TTerminal
  854. if (FActive)
  855. {
  856. // We log this instead of exception handler, because Close() would
  857. // probably cause exception handler to loose pointer to TShellLog()
  858. LogEvent("Attempt to close connection due to fatal exception:");
  859. FLog->Add(llException, Msg);
  860. FLog->AddException(E);
  861. Close();
  862. }
  863. SSH_FATAL_ERROR_EXT(E, Msg);
  864. }
  865. //---------------------------------------------------------------------------
  866. bool __fastcall TSecureShell::TranslateErrorMessage(AnsiString & Message)
  867. {
  868. static const TPuttyTranslation Translation[] = {
  869. { "Server unexpectedly closed network connection", UNEXPECTED_CLOSE_ERROR },
  870. { "Network error: Connection refused", NET_TRANSL_REFUSED },
  871. { "Network error: Connection reset by peer", NET_TRANSL_RESET },
  872. { "Network error: Connection timed out", NET_TRANSL_TIMEOUT },
  873. };
  874. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall TSecureShell::PuttyFatalError(AnsiString Error)
  878. {
  879. TranslateErrorMessage(Error);
  880. FatalError(Error);
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TSecureShell::FatalError(AnsiString Error)
  884. {
  885. FatalError(NULL, Error);
  886. }
  887. //---------------------------------------------------------------------------
  888. void __fastcall inline TSecureShell::LogEvent(const AnsiString & Str)
  889. {
  890. if (FLog->Logging)
  891. {
  892. FLog->Add(llMessage, Str);
  893. }
  894. }
  895. //---------------------------------------------------------------------------
  896. void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, bool Startup)
  897. {
  898. int Events;
  899. if (Startup)
  900. {
  901. Events = (FD_CONNECT | FD_READ | FD_WRITE | FD_OOB | FD_CLOSE | FD_ACCEPT);
  902. }
  903. else
  904. {
  905. Events = 0;
  906. }
  907. if (Configuration->LogProtocol >= 2)
  908. {
  909. LogEvent(FORMAT("Selecting events %d for socket %d", (int(Events), int(Socket))));
  910. }
  911. if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR)
  912. {
  913. if (Configuration->LogProtocol >= 2)
  914. {
  915. LogEvent(FORMAT("Error selecting events %d for socket %d", (int(Events), int(Socket))));
  916. }
  917. if (Startup)
  918. {
  919. FatalError(FMTLOAD(EVENT_SELECT_ERROR, (WSAGetLastError())));
  920. }
  921. }
  922. }
  923. //---------------------------------------------------------------------------
  924. void __fastcall TSecureShell::UpdateSocket(SOCKET value, bool Startup)
  925. {
  926. assert(value);
  927. assert((FActive && (FSocket == value)) || (!FActive && Startup));
  928. SocketEventSelect(value, FSocketEvent, Startup);
  929. if (Startup)
  930. {
  931. FSocket = value;
  932. FActive = true;
  933. }
  934. else
  935. {
  936. FSocket = INVALID_SOCKET;
  937. Discard();
  938. }
  939. }
  940. //---------------------------------------------------------------------------
  941. void __fastcall TSecureShell::UpdatePortFwdSocket(SOCKET value, bool Startup)
  942. {
  943. if (Configuration->LogProtocol >= 2)
  944. {
  945. LogEvent(FORMAT("Updating forwarding socket %d (%d)", (int(value), int(Startup))));
  946. }
  947. SocketEventSelect(value, FSocketEvent, Startup);
  948. if (Startup)
  949. {
  950. FPortFwdSockets.insert(value);
  951. }
  952. else
  953. {
  954. FPortFwdSockets.erase(value);
  955. }
  956. }
  957. //---------------------------------------------------------------------------
  958. void __fastcall TSecureShell::SetActive(bool value)
  959. {
  960. if (FActive != value)
  961. {
  962. if (value)
  963. {
  964. Open();
  965. }
  966. else
  967. {
  968. Close();
  969. }
  970. }
  971. }
  972. //---------------------------------------------------------------------------
  973. void __fastcall TSecureShell::FreeBackend()
  974. {
  975. if (FBackendHandle != NULL)
  976. {
  977. FBackend->free(FBackendHandle);
  978. FBackendHandle = NULL;
  979. }
  980. }
  981. //---------------------------------------------------------------------------
  982. void __fastcall TSecureShell::Discard()
  983. {
  984. bool WasActive = FActive;
  985. FActive = false;
  986. if (WasActive)
  987. {
  988. FUI->Closed();
  989. }
  990. }
  991. //---------------------------------------------------------------------------
  992. void __fastcall TSecureShell::Close()
  993. {
  994. LogEvent("Closing connection.");
  995. assert(FActive);
  996. FreeBackend();
  997. Discard();
  998. }
  999. //---------------------------------------------------------------------------
  1000. void inline __fastcall TSecureShell::CheckConnection(int Message)
  1001. {
  1002. if (!FActive || get_ssh_state_closed(FBackendHandle))
  1003. {
  1004. AnsiString Str = LoadStr(Message >= 0 ? Message : NOT_CONNECTED);
  1005. int ExitCode = get_ssh_exitcode(FBackendHandle);
  1006. if (ExitCode >= 0)
  1007. {
  1008. Str += " " + FMTLOAD(SSH_EXITCODE, (ExitCode));
  1009. }
  1010. FatalError(Str);
  1011. }
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. void __fastcall TSecureShell::PoolForData(unsigned int & Result)
  1015. {
  1016. try
  1017. {
  1018. if (Configuration->LogProtocol >= 2)
  1019. {
  1020. LogEvent("Pooling for data in case they finally arrives");
  1021. }
  1022. if (EventSelectLoop(0, false))
  1023. {
  1024. LogEvent("Data has arrived, closing query to user.");
  1025. Result = qaOK;
  1026. }
  1027. }
  1028. catch(...)
  1029. {
  1030. // if we let the exception out, it may popup another message dialog
  1031. // in whole event loop, another call to PoolForData from original dialog
  1032. // would be invoked, leading to an infinite loop.
  1033. // by retrying we hope (that probably fatal) error would repeat in WaitForData
  1034. Result = qaRetry;
  1035. }
  1036. }
  1037. //---------------------------------------------------------------------------
  1038. void __fastcall TSecureShell::WaitForData()
  1039. {
  1040. // see winsftp.c
  1041. bool IncomingData;
  1042. do
  1043. {
  1044. if (Configuration->LogProtocol >= 2)
  1045. {
  1046. LogEvent("Looking for incoming data");
  1047. }
  1048. IncomingData = EventSelectLoop(FSessionData->Timeout * 1000, true);
  1049. if (!IncomingData)
  1050. {
  1051. LogEvent("Waiting for data timed out, asking user what to do.");
  1052. TQueryParams Params(qpFatalAbort | qpAllowContinueOnError);
  1053. Params.Timer = 500;
  1054. Params.TimerEvent = PoolForData;
  1055. Params.TimerMessage = FMTLOAD(TIMEOUT_STILL_WAITING, (FSessionData->Timeout));
  1056. Params.TimerAnswers = qaAbort;
  1057. int Answer = FUI->QueryUser(FMTLOAD(CONFIRM_PROLONG_TIMEOUT2, (FSessionData->Timeout)),
  1058. NULL, qaRetry | qaAbort, &Params);
  1059. switch (Answer)
  1060. {
  1061. case qaRetry:
  1062. // noop
  1063. break;
  1064. case qaOK:
  1065. // read event was already captured in PoolForData(),
  1066. // make sure we do not try to select it again as it would timeout
  1067. // unless another read event occurs
  1068. IncomingData = true;
  1069. break;
  1070. default:
  1071. assert(false);
  1072. // fallthru
  1073. case qaAbort:
  1074. FatalError(LoadStr(USER_TERMINATED));
  1075. break;
  1076. }
  1077. }
  1078. }
  1079. while (!IncomingData);
  1080. }
  1081. //---------------------------------------------------------------------------
  1082. bool __fastcall TSecureShell::SshFallbackCmd() const
  1083. {
  1084. return ssh_fallback_cmd(FBackendHandle);
  1085. }
  1086. //---------------------------------------------------------------------------
  1087. bool __fastcall TSecureShell::ProcessNetworkEvents(SOCKET Socket)
  1088. {
  1089. bool Result = false;
  1090. if (Configuration->LogProtocol >= 2)
  1091. {
  1092. LogEvent(FORMAT("Enumerating network events for socket %d", (int(Socket))));
  1093. }
  1094. // see winplink.c
  1095. WSANETWORKEVENTS Events;
  1096. if (WSAEnumNetworkEvents(Socket, NULL, &Events) == 0)
  1097. {
  1098. static const struct { int Bit, Mask; const char * Desc; } EventTypes[] =
  1099. {
  1100. { FD_READ_BIT, FD_READ, "read" },
  1101. { FD_WRITE_BIT, FD_WRITE, "write" },
  1102. { FD_OOB_BIT, FD_OOB, "oob" },
  1103. { FD_ACCEPT_BIT, FD_ACCEPT, "accept" },
  1104. { FD_CONNECT_BIT, FD_CONNECT, "connect" },
  1105. { FD_CLOSE_BIT, FD_CLOSE, "close" },
  1106. };
  1107. noise_ultralight(Socket);
  1108. noise_ultralight(Events.lNetworkEvents);
  1109. if (Configuration->LogProtocol >= 2)
  1110. {
  1111. LogEvent(FORMAT("Enumerated %d network events for socket %d",
  1112. (int(Events.lNetworkEvents), int(Socket))));
  1113. }
  1114. for (int Event = 0; Event < LENOF(EventTypes); Event++)
  1115. {
  1116. if (Events.lNetworkEvents & EventTypes[Event].Mask)
  1117. {
  1118. if (EventTypes[Event].Mask & FD_READ)
  1119. {
  1120. Result = true;
  1121. }
  1122. int Err = Events.iErrorCode[EventTypes[Event].Bit];
  1123. if (Configuration->LogProtocol >= 2)
  1124. {
  1125. LogEvent(FORMAT("Detected network %s event on socket %d with error %d",
  1126. (EventTypes[Event].Desc, int(Socket), Err)));
  1127. }
  1128. #pragma option push -w-prc
  1129. LPARAM SelectEvent = WSAMAKESELECTREPLY(EventTypes[Event].Mask, Err);
  1130. #pragma option pop
  1131. if (!select_result((WPARAM)Socket, SelectEvent))
  1132. {
  1133. // note that connection was closed definitely,
  1134. // so "check" is actually not required
  1135. CheckConnection();
  1136. }
  1137. }
  1138. }
  1139. }
  1140. else
  1141. {
  1142. if (Configuration->LogProtocol >= 2)
  1143. {
  1144. LogEvent(FORMAT("Error enumerating network events for socket %d", (int(Socket))));
  1145. }
  1146. }
  1147. return Result;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. bool __fastcall TSecureShell::EventSelectLoop(unsigned int MSec, bool ReadEventRequired)
  1151. {
  1152. CheckConnection();
  1153. bool Result = false;
  1154. do
  1155. {
  1156. if (Configuration->LogProtocol >= 2)
  1157. {
  1158. LogEvent("Looking for network events");
  1159. }
  1160. unsigned int TicksBefore = GetTickCount();
  1161. int WaitResult = WaitForSingleObject(FSocketEvent, MSec);
  1162. switch (WaitResult)
  1163. {
  1164. case WAIT_OBJECT_0:
  1165. if (Configuration->LogProtocol >= 1)
  1166. {
  1167. LogEvent("Detected network event");
  1168. }
  1169. if (ProcessNetworkEvents(FSocket))
  1170. {
  1171. Result = true;
  1172. }
  1173. {
  1174. TSockets::iterator i = FPortFwdSockets.begin();
  1175. while (i != FPortFwdSockets.end())
  1176. {
  1177. ProcessNetworkEvents(*i);
  1178. i++;
  1179. }
  1180. }
  1181. break;
  1182. case WAIT_TIMEOUT:
  1183. if (Configuration->LogProtocol >= 2)
  1184. {
  1185. LogEvent("Timeout waiting for network events");
  1186. }
  1187. MSec = 0;
  1188. break;
  1189. default:
  1190. if (Configuration->LogProtocol >= 2)
  1191. {
  1192. LogEvent(FORMAT("Unknown waiting result %d", (WaitResult)));
  1193. }
  1194. MSec = 0;
  1195. break;
  1196. }
  1197. unsigned int TicksAfter = GetTickCount();
  1198. // ticks wraps once in 49.7 days
  1199. if (TicksBefore < TicksAfter)
  1200. {
  1201. unsigned int Ticks = TicksAfter - TicksBefore;
  1202. if (Ticks > MSec)
  1203. {
  1204. MSec = 0;
  1205. }
  1206. else
  1207. {
  1208. MSec -= Ticks;
  1209. }
  1210. }
  1211. }
  1212. while (ReadEventRequired && (MSec > 0) && !Result);
  1213. return Result;
  1214. }
  1215. //---------------------------------------------------------------------------
  1216. void __fastcall TSecureShell::Idle(unsigned int MSec)
  1217. {
  1218. noise_regular();
  1219. call_ssh_timer(FBackendHandle);
  1220. EventSelectLoop(MSec, false);
  1221. }
  1222. //---------------------------------------------------------------------------
  1223. void __fastcall TSecureShell::KeepAlive()
  1224. {
  1225. LogEvent("Sending null packet to keep session alive.");
  1226. SendSpecial(TS_PING);
  1227. }
  1228. //---------------------------------------------------------------------------
  1229. unsigned long __fastcall TSecureShell::MaxPacketSize()
  1230. {
  1231. if (!FSessionInfoValid)
  1232. {
  1233. UpdateSessionInfo();
  1234. }
  1235. if (FSshVersion == 1)
  1236. {
  1237. return 0;
  1238. }
  1239. else
  1240. {
  1241. if (FMaxPacketSize == NULL)
  1242. {
  1243. FMaxPacketSize = ssh2_remmaxpkt(FBackendHandle);
  1244. }
  1245. return *FMaxPacketSize;
  1246. }
  1247. }
  1248. //---------------------------------------------------------------------------
  1249. AnsiString __fastcall TSecureShell::FuncToCompression(
  1250. int SshVersion, const void * Compress) const
  1251. {
  1252. enum TCompressionType { ctNone, ctZLib };
  1253. if (SshVersion == 1)
  1254. {
  1255. return get_ssh1_compressing(FBackendHandle) ? "ZLib" : "";
  1256. }
  1257. else
  1258. {
  1259. return (ssh_compress *)Compress == &ssh_zlib ? "ZLib" : "";
  1260. }
  1261. }
  1262. //---------------------------------------------------------------------------
  1263. TCipher __fastcall TSecureShell::FuncToSsh1Cipher(const void * Cipher)
  1264. {
  1265. const ssh_cipher *CipherFuncs[] =
  1266. {&ssh_3des, &ssh_des, &ssh_blowfish_ssh1};
  1267. const TCipher TCiphers[] = {cip3DES, cipDES, cipBlowfish};
  1268. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1269. TCipher Result = cipWarn;
  1270. for (int Index = 0; Index < LENOF(TCiphers); Index++)
  1271. {
  1272. if ((ssh_cipher *)Cipher == CipherFuncs[Index])
  1273. {
  1274. Result = TCiphers[Index];
  1275. }
  1276. }
  1277. assert(Result != cipWarn);
  1278. return Result;
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. TCipher __fastcall TSecureShell::FuncToSsh2Cipher(const void * Cipher)
  1282. {
  1283. const ssh2_ciphers *CipherFuncs[] =
  1284. {&ssh2_3des, &ssh2_des, &ssh2_aes, &ssh2_blowfish};
  1285. const TCipher TCiphers[] = {cip3DES, cipDES, cipAES, cipBlowfish};
  1286. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1287. TCipher Result = cipWarn;
  1288. for (int C = 0; C < LENOF(TCiphers); C++)
  1289. {
  1290. for (int F = 0; F < CipherFuncs[C]->nciphers; F++)
  1291. {
  1292. if ((ssh2_cipher *)Cipher == CipherFuncs[C]->list[F])
  1293. {
  1294. Result = TCiphers[C];
  1295. }
  1296. }
  1297. }
  1298. assert(Result != cipWarn);
  1299. return Result;
  1300. }
  1301. //---------------------------------------------------------------------------
  1302. void __fastcall TSecureShell::VerifyHostKey(const AnsiString Host, int Port,
  1303. const AnsiString KeyType, const AnsiString KeyStr, const AnsiString Fingerprint)
  1304. {
  1305. GotHostKey();
  1306. int Result;
  1307. FSessionInfo.HostKeyFingerprint = Fingerprint;
  1308. // Verify the key against the registry.
  1309. Result = verify_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1310. if (Result != 0)
  1311. {
  1312. if (Configuration->DisableAcceptingHostKeys)
  1313. {
  1314. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1315. }
  1316. else
  1317. {
  1318. TQueryParams Params;
  1319. Params.HelpKeyword = (Result == 1 ? HELP_UNKNOWN_KEY : HELP_DIFFERENT_KEY);
  1320. int R = FUI->QueryUser(
  1321. FMTLOAD((Result == 1 ? UNKNOWN_KEY2 : DIFFERENT_KEY2), (KeyType, Fingerprint)),
  1322. NULL, qaYes | qaNo | qaCancel, &Params, qtWarning);
  1323. switch (R) {
  1324. case qaYes:
  1325. store_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1326. break;
  1327. case qaCancel:
  1328. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1329. }
  1330. }
  1331. }
  1332. }
  1333. //---------------------------------------------------------------------------
  1334. void __fastcall TSecureShell::AskAlg(const AnsiString AlgType,
  1335. const AnsiString AlgName)
  1336. {
  1337. AnsiString Msg;
  1338. if (AlgType == "key-exchange algorithm")
  1339. {
  1340. Msg = FMTLOAD(KEX_BELOW_TRESHOLD, (AlgName));
  1341. }
  1342. else
  1343. {
  1344. int CipherType;
  1345. if (AlgType == "cipher")
  1346. {
  1347. CipherType = CIPHER_TYPE_BOTH;
  1348. }
  1349. else if (AlgType == "client-to-server cipher")
  1350. {
  1351. CipherType = CIPHER_TYPE_CS;
  1352. }
  1353. else if (AlgType == "server-to-client cipher")
  1354. {
  1355. CipherType = CIPHER_TYPE_SC;
  1356. }
  1357. else
  1358. {
  1359. assert(false);
  1360. }
  1361. Msg = FMTLOAD(CIPHER_BELOW_TRESHOLD, (LoadStr(CipherType), AlgName));
  1362. }
  1363. if (FUI->QueryUser(Msg, NULL, qaYes | qaNo, NULL, qtWarning) == qaNo)
  1364. {
  1365. Abort();
  1366. }
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. void __fastcall TSecureShell::DisplayBanner(const AnsiString & Banner)
  1370. {
  1371. FUI->DisplayBanner(Banner);
  1372. }
  1373. //---------------------------------------------------------------------------
  1374. void __fastcall TSecureShell::OldKeyfileWarning()
  1375. {
  1376. // actually never called, see Net.cpp
  1377. FUI->QueryUser(LoadStr(OLD_KEY), NULL, qaOK, NULL, qtWarning);
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. bool __fastcall TSecureShell::GetStoredCredentialsTried()
  1381. {
  1382. return FStoredPasswordTried || FStoredPasswordTriedForKI;
  1383. }