SecureShell.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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::DumpCWrite()
  463. {
  464. AnsiString Line;
  465. // Do we have at least one complete line in std error cache?
  466. while (FCWriteTemp.Pos("\n") > 0)
  467. {
  468. AnsiString Line = CutToChar(FCWriteTemp, '\n', false);
  469. FLog->Add(llStdError, Line);
  470. if (FAuthenticating)
  471. {
  472. // No point trying to translate message coming from server
  473. if (!FCWriteTempUntrusted)
  474. {
  475. TranslateAuthenticationMessage(Line);
  476. }
  477. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Line;
  478. }
  479. // Untrusted means generally that it comes from the server,
  480. // do not use such a output as "information" for end user
  481. if (!FCWriteTempUntrusted)
  482. {
  483. FUI->Information(Line, false);
  484. }
  485. }
  486. }
  487. //---------------------------------------------------------------------------
  488. void __fastcall TSecureShell::CWrite(const char * Data, int Length, bool Untrusted)
  489. {
  490. // some messages to stderr may indicate that something has changed with the
  491. // session, so reset the session info
  492. ResetSessionInfo();
  493. // if data coming from server were not ended with new line,
  494. // dump rest of the line, once trusted output arrive
  495. if (!FCWriteTemp.IsEmpty() &&
  496. (FCWriteTempUntrusted != Untrusted))
  497. {
  498. FCWriteTemp += '\n';
  499. DumpCWrite();
  500. }
  501. // We send only whole line at once, so we have to cache incoming data
  502. FCWriteTemp += DeleteChar(AnsiString(Data, Length), '\r');
  503. FCWriteTempUntrusted = Untrusted;
  504. DumpCWrite();
  505. }
  506. //---------------------------------------------------------------------------
  507. void __fastcall TSecureShell::RegisterReceiveHandler(TNotifyEvent Handler)
  508. {
  509. assert(FOnReceive == NULL);
  510. FOnReceive = Handler;
  511. }
  512. //---------------------------------------------------------------------------
  513. void __fastcall TSecureShell::UnregisterReceiveHandler(TNotifyEvent Handler)
  514. {
  515. assert(FOnReceive == Handler);
  516. USEDPARAM(Handler);
  517. FOnReceive = NULL;
  518. }
  519. //---------------------------------------------------------------------------
  520. void __fastcall TSecureShell::FromBackend(bool IsStdErr, const char * Data, int Length)
  521. {
  522. CheckConnection();
  523. if (Configuration->LogProtocol >= 1)
  524. {
  525. LogEvent(FORMAT("Received %u bytes (%d)", (Length, int(IsStdErr))));
  526. }
  527. // Following is taken from scp.c from_backend() and modified
  528. if (IsStdErr)
  529. {
  530. AddStdError(AnsiString(Data, Length));
  531. }
  532. else
  533. {
  534. unsigned char *p = (unsigned char *)Data;
  535. unsigned Len = (unsigned)Length;
  536. // with event-select mechanism we can now receive data even before we
  537. // actually expect them (OutPtr can be NULL)
  538. if ((OutPtr != NULL) && (OutLen > 0) && (Len > 0))
  539. {
  540. unsigned Used = OutLen;
  541. if (Used > Len) Used = Len;
  542. memcpy(OutPtr, p, Used);
  543. OutPtr += Used; OutLen -= Used;
  544. p += Used; Len -= Used;
  545. }
  546. if (Len > 0)
  547. {
  548. if (PendSize < PendLen + Len)
  549. {
  550. PendSize = PendLen + Len + 4096;
  551. Pending = (char *)
  552. (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize));
  553. if (!Pending) FatalError("Out of memory");
  554. }
  555. memcpy(Pending + PendLen, p, Len);
  556. PendLen += Len;
  557. }
  558. if (FOnReceive != NULL)
  559. {
  560. if (!FFrozen)
  561. {
  562. FFrozen = true;
  563. try
  564. {
  565. do
  566. {
  567. FDataWhileFrozen = false;
  568. FOnReceive(NULL);
  569. }
  570. while (FDataWhileFrozen);
  571. }
  572. __finally
  573. {
  574. FFrozen = false;
  575. }
  576. }
  577. else
  578. {
  579. FDataWhileFrozen = true;
  580. }
  581. }
  582. }
  583. }
  584. //---------------------------------------------------------------------------
  585. bool __fastcall TSecureShell::Peek(char *& Buf, int Len)
  586. {
  587. bool Result = (int(PendLen) >= Len);
  588. if (Result)
  589. {
  590. Buf = Pending;
  591. }
  592. return Result;
  593. }
  594. //---------------------------------------------------------------------------
  595. Integer __fastcall TSecureShell::Receive(char * Buf, Integer Len)
  596. {
  597. CheckConnection();
  598. if (Len > 0)
  599. {
  600. // Following is taken from scp.c ssh_scp_recv() and modified
  601. OutPtr = Buf;
  602. OutLen = Len;
  603. try
  604. {
  605. /*
  606. * See if the pending-input block contains some of what we
  607. * need.
  608. */
  609. if (PendLen > 0)
  610. {
  611. unsigned PendUsed = PendLen;
  612. if (PendUsed > OutLen)
  613. {
  614. PendUsed = OutLen;
  615. }
  616. memcpy(OutPtr, Pending, PendUsed);
  617. memmove(Pending, Pending + PendUsed, PendLen - PendUsed);
  618. OutPtr += PendUsed;
  619. OutLen -= PendUsed;
  620. PendLen -= PendUsed;
  621. if (PendLen == 0)
  622. {
  623. PendSize = 0;
  624. sfree(Pending);
  625. Pending = NULL;
  626. }
  627. }
  628. while (OutLen > 0)
  629. {
  630. if (Configuration->LogProtocol >= 1)
  631. {
  632. LogEvent(FORMAT("Waiting for another %u bytes", (static_cast<int>(OutLen))));
  633. }
  634. WaitForData();
  635. }
  636. // This seems ambiguous
  637. if (Len <= 0) FatalError(LoadStr(LOST_CONNECTION));
  638. }
  639. __finally
  640. {
  641. OutPtr = NULL;
  642. }
  643. };
  644. if (Configuration->LogProtocol >= 1)
  645. {
  646. LogEvent(FORMAT("Read %u bytes (%d pending)",
  647. (static_cast<int>(Len), static_cast<int>(PendLen))));
  648. }
  649. return Len;
  650. }
  651. //---------------------------------------------------------------------------
  652. AnsiString __fastcall TSecureShell::ReceiveLine()
  653. {
  654. unsigned Index;
  655. Char Ch;
  656. AnsiString Line;
  657. Boolean EOL = False;
  658. do
  659. {
  660. // If there is any buffer of received chars
  661. if (PendLen > 0)
  662. {
  663. Index = 0;
  664. // Repeat until we walk thru whole buffer or reach end-of-line
  665. while ((Index < PendLen) && (!Index || (Pending[Index-1] != '\n')))
  666. {
  667. Index++;
  668. }
  669. EOL = (Boolean)(Index && (Pending[Index-1] == '\n'));
  670. Integer PrevLen = Line.Length();
  671. Line.SetLength(PrevLen + Index);
  672. Receive(Line.c_str() + PrevLen, Index);
  673. }
  674. // If buffer don't contain end-of-line character
  675. // we read one more which causes receiving new buffer of chars
  676. if (!EOL)
  677. {
  678. Receive(&Ch, 1);
  679. Line += Ch;
  680. EOL = (Ch == '\n');
  681. }
  682. }
  683. while (!EOL);
  684. // We don't want end-of-line character
  685. Line.SetLength(Line.Length()-1);
  686. CaptureOutput(llOutput, Line);
  687. return Line;
  688. }
  689. //---------------------------------------------------------------------------
  690. void __fastcall TSecureShell::SendSpecial(int Code)
  691. {
  692. LogEvent(FORMAT("Sending special code: %d", (Code)));
  693. CheckConnection();
  694. FBackend->special(FBackendHandle, (Telnet_Special)Code);
  695. CheckConnection();
  696. FLastDataSent = Now();
  697. }
  698. //---------------------------------------------------------------------------
  699. void __fastcall TSecureShell::SendEOF()
  700. {
  701. SendSpecial(TS_EOF);
  702. }
  703. //---------------------------------------------------------------------------
  704. void __fastcall TSecureShell::Send(const char * Buf, Integer Len)
  705. {
  706. CheckConnection();
  707. int BufSize = FBackend->send(FBackendHandle, (char *)Buf, Len);
  708. if (Configuration->LogProtocol >= 1)
  709. {
  710. LogEvent(FORMAT("Sent %u bytes", (static_cast<int>(Len))));
  711. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  712. }
  713. FLastDataSent = Now();
  714. // among other forces receive of pending data to free the servers's send buffer
  715. EventSelectLoop(0, false, NULL);
  716. while (BufSize > MAX_BUFSIZE)
  717. {
  718. if (Configuration->LogProtocol >= 1)
  719. {
  720. LogEvent(FORMAT("There are %u bytes remaining in the send buffer, "
  721. "need to send at least another %u bytes",
  722. (BufSize, BufSize - MAX_BUFSIZE)));
  723. }
  724. EventSelectLoop(100, false, NULL);
  725. BufSize = FBackend->sendbuffer(FBackendHandle);
  726. if (Configuration->LogProtocol >= 1)
  727. {
  728. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (BufSize)));
  729. }
  730. }
  731. CheckConnection();
  732. }
  733. //---------------------------------------------------------------------------
  734. void __fastcall TSecureShell::SendNull()
  735. {
  736. LogEvent("Sending NULL.");
  737. Send("", 1);
  738. }
  739. //---------------------------------------------------------------------------
  740. void __fastcall TSecureShell::SendStr(AnsiString Str)
  741. {
  742. CheckConnection();
  743. Send(Str.c_str(), Str.Length());
  744. }
  745. //---------------------------------------------------------------------------
  746. void __fastcall TSecureShell::SendLine(AnsiString Line)
  747. {
  748. SendStr(Line);
  749. Send("\n", 1);
  750. FLog->Add(llInput, Line);
  751. }
  752. //---------------------------------------------------------------------------
  753. bool __fastcall TSecureShell::TranslatePuttyMessage(
  754. const TPuttyTranslation * Translation, size_t Count, AnsiString & Message)
  755. {
  756. bool Result = false;
  757. for (unsigned int Index = 0; Index < Count; Index++)
  758. {
  759. const char * Original = Translation[Index].Original;
  760. const char * Div = strchr(Original, '%');
  761. if (Div == NULL)
  762. {
  763. if (strcmp(Message.c_str(), Original) == 0)
  764. {
  765. Message = LoadStr(Translation[Index].Translation);
  766. Result = true;
  767. break;
  768. }
  769. }
  770. else
  771. {
  772. size_t OriginalLen = strlen(Original);
  773. size_t PrefixLen = Div - Original;
  774. size_t SuffixLen = OriginalLen - PrefixLen - 1;
  775. if (((size_t)Message.Length() >= OriginalLen - 1) &&
  776. (strncmp(Message.c_str(), Original, PrefixLen) == 0) &&
  777. (strncmp(Message.c_str() + Message.Length() - SuffixLen, Div + 1, SuffixLen) == 0))
  778. {
  779. Message = FMTLOAD(Translation[Index].Translation,
  780. (Message.SubString(PrefixLen + 1, Message.Length() - PrefixLen - SuffixLen).TrimRight()));
  781. Result = true;
  782. break;
  783. }
  784. }
  785. }
  786. return Result;
  787. }
  788. //---------------------------------------------------------------------------
  789. bool __fastcall TSecureShell::TranslateAuthenticationMessage(AnsiString & Message)
  790. {
  791. static const TPuttyTranslation Translation[] = {
  792. { "Using username \"%\".", AUTH_TRANSL_USERNAME },
  793. { "Using keyboard-interactive authentication.", AUTH_TRANSL_KEYB_INTER },
  794. { "Authenticating with public key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  795. { "Authenticating with public key \"%\"", AUTH_TRANSL_PUBLIC_KEY },
  796. { "Authenticated using RSA key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  797. { "Wrong passphrase", AUTH_TRANSL_WRONG_PASSPHRASE },
  798. { "Wrong passphrase.", AUTH_TRANSL_WRONG_PASSPHRASE },
  799. { "Access denied", AUTH_TRANSL_ACCESS_DENIED },
  800. { "Trying public key authentication.", AUTH_TRANSL_TRY_PUBLIC_KEY },
  801. { "Server refused our public key.", AUTH_TRANSL_KEY_REFUSED },
  802. { "Server refused our key", AUTH_TRANSL_KEY_REFUSED }
  803. };
  804. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  805. }
  806. //---------------------------------------------------------------------------
  807. void __fastcall TSecureShell::AddStdError(AnsiString Str)
  808. {
  809. FStdError += Str;
  810. Integer P;
  811. Str = DeleteChar(Str, '\r');
  812. // We send only whole line at once to log, so we have to cache
  813. // incoming std error data
  814. FStdErrorTemp += Str;
  815. AnsiString Line;
  816. // Do we have at least one complete line in std error cache?
  817. while ((P = FStdErrorTemp.Pos("\n")) > 0)
  818. {
  819. Line = FStdErrorTemp.SubString(1, P-1);
  820. FStdErrorTemp.Delete(1, P);
  821. AddStdErrorLine(Line);
  822. }
  823. }
  824. //---------------------------------------------------------------------------
  825. void __fastcall TSecureShell::AddStdErrorLine(const AnsiString & Str)
  826. {
  827. if (FAuthenticating)
  828. {
  829. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Str;
  830. }
  831. CaptureOutput(llStdError, Str);
  832. }
  833. //---------------------------------------------------------------------------
  834. const AnsiString & __fastcall TSecureShell::GetStdError()
  835. {
  836. return FStdError;
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TSecureShell::ClearStdError()
  840. {
  841. // Flush std error cache
  842. if (!FStdErrorTemp.IsEmpty())
  843. {
  844. if (FAuthenticating)
  845. {
  846. FAuthenticationLog +=
  847. (FAuthenticationLog.IsEmpty() ? "" : "\n") + FStdErrorTemp;
  848. }
  849. CaptureOutput(llStdError, FStdErrorTemp);
  850. FStdErrorTemp = "";
  851. }
  852. FStdError = "";
  853. }
  854. //---------------------------------------------------------------------------
  855. void __fastcall TSecureShell::CaptureOutput(TLogLineType Type,
  856. const AnsiString & Line)
  857. {
  858. if (FOnCaptureOutput != NULL)
  859. {
  860. FOnCaptureOutput(Line, (Type == llStdError));
  861. }
  862. FLog->Add(Type, Line);
  863. }
  864. //---------------------------------------------------------------------------
  865. void __fastcall TSecureShell::FatalError(Exception * E, AnsiString Msg)
  866. {
  867. // the same code is in TTerminal
  868. if (FActive)
  869. {
  870. // We log this instead of exception handler, because Close() would
  871. // probably cause exception handler to loose pointer to TShellLog()
  872. LogEvent("Attempt to close connection due to fatal exception:");
  873. FLog->Add(llException, Msg);
  874. FLog->AddException(E);
  875. Close();
  876. }
  877. SSH_FATAL_ERROR_EXT(E, Msg);
  878. }
  879. //---------------------------------------------------------------------------
  880. bool __fastcall TSecureShell::TranslateErrorMessage(AnsiString & Message)
  881. {
  882. static const TPuttyTranslation Translation[] = {
  883. { "Server unexpectedly closed network connection", UNEXPECTED_CLOSE_ERROR },
  884. { "Network error: Connection refused", NET_TRANSL_REFUSED },
  885. { "Network error: Connection reset by peer", NET_TRANSL_RESET },
  886. { "Network error: Connection timed out", NET_TRANSL_TIMEOUT },
  887. };
  888. return TranslatePuttyMessage(Translation, LENOF(Translation), Message);
  889. }
  890. //---------------------------------------------------------------------------
  891. void __fastcall TSecureShell::PuttyFatalError(AnsiString Error)
  892. {
  893. TranslateErrorMessage(Error);
  894. FatalError(Error);
  895. }
  896. //---------------------------------------------------------------------------
  897. void __fastcall TSecureShell::FatalError(AnsiString Error)
  898. {
  899. FatalError(NULL, Error);
  900. }
  901. //---------------------------------------------------------------------------
  902. void __fastcall inline TSecureShell::LogEvent(const AnsiString & Str)
  903. {
  904. if (FLog->Logging)
  905. {
  906. FLog->Add(llMessage, Str);
  907. }
  908. }
  909. //---------------------------------------------------------------------------
  910. void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, bool Startup)
  911. {
  912. int Events;
  913. if (Startup)
  914. {
  915. Events = (FD_CONNECT | FD_READ | FD_WRITE | FD_OOB | FD_CLOSE | FD_ACCEPT);
  916. }
  917. else
  918. {
  919. Events = 0;
  920. }
  921. if (Configuration->LogProtocol >= 2)
  922. {
  923. LogEvent(FORMAT("Selecting events %d for socket %d", (int(Events), int(Socket))));
  924. }
  925. if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR)
  926. {
  927. if (Configuration->LogProtocol >= 2)
  928. {
  929. LogEvent(FORMAT("Error selecting events %d for socket %d", (int(Events), int(Socket))));
  930. }
  931. if (Startup)
  932. {
  933. FatalError(FMTLOAD(EVENT_SELECT_ERROR, (WSAGetLastError())));
  934. }
  935. }
  936. }
  937. //---------------------------------------------------------------------------
  938. void __fastcall TSecureShell::UpdateSocket(SOCKET value, bool Startup)
  939. {
  940. if (!FActive && !Startup)
  941. {
  942. // no-op
  943. // Remove the branch eventualy:
  944. // When TCP connection fails, PuTTY does not release the memory allocate for
  945. // socket. As a simple hack we call sk_tcp_close() in ssh.c to release the memory,
  946. // until they fix it better. Unfortunately sk_tcp_close calles do_select,
  947. // so we must filter that out.
  948. }
  949. else
  950. {
  951. assert(value);
  952. assert((FActive && (FSocket == value)) || (!FActive && Startup));
  953. SocketEventSelect(value, FSocketEvent, Startup);
  954. if (Startup)
  955. {
  956. FSocket = value;
  957. FActive = true;
  958. }
  959. else
  960. {
  961. FSocket = INVALID_SOCKET;
  962. Discard();
  963. }
  964. }
  965. }
  966. //---------------------------------------------------------------------------
  967. void __fastcall TSecureShell::UpdatePortFwdSocket(SOCKET value, bool Startup)
  968. {
  969. if (Configuration->LogProtocol >= 2)
  970. {
  971. LogEvent(FORMAT("Updating forwarding socket %d (%d)", (int(value), int(Startup))));
  972. }
  973. SocketEventSelect(value, FSocketEvent, Startup);
  974. if (Startup)
  975. {
  976. FPortFwdSockets.insert(value);
  977. }
  978. else
  979. {
  980. FPortFwdSockets.erase(value);
  981. }
  982. }
  983. //---------------------------------------------------------------------------
  984. void __fastcall TSecureShell::SetActive(bool value)
  985. {
  986. if (FActive != value)
  987. {
  988. if (value)
  989. {
  990. Open();
  991. }
  992. else
  993. {
  994. Close();
  995. }
  996. }
  997. }
  998. //---------------------------------------------------------------------------
  999. void __fastcall TSecureShell::FreeBackend()
  1000. {
  1001. if (FBackendHandle != NULL)
  1002. {
  1003. FBackend->free(FBackendHandle);
  1004. FBackendHandle = NULL;
  1005. }
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. void __fastcall TSecureShell::Discard()
  1009. {
  1010. bool WasActive = FActive;
  1011. FActive = false;
  1012. if (WasActive)
  1013. {
  1014. FUI->Closed();
  1015. }
  1016. }
  1017. //---------------------------------------------------------------------------
  1018. void __fastcall TSecureShell::Close()
  1019. {
  1020. LogEvent("Closing connection.");
  1021. assert(FActive);
  1022. FreeBackend();
  1023. Discard();
  1024. }
  1025. //---------------------------------------------------------------------------
  1026. void inline __fastcall TSecureShell::CheckConnection(int Message)
  1027. {
  1028. if (!FActive || get_ssh_state_closed(FBackendHandle))
  1029. {
  1030. AnsiString Str = LoadStr(Message >= 0 ? Message : NOT_CONNECTED);
  1031. int ExitCode = get_ssh_exitcode(FBackendHandle);
  1032. if (ExitCode >= 0)
  1033. {
  1034. Str += " " + FMTLOAD(SSH_EXITCODE, (ExitCode));
  1035. }
  1036. FatalError(Str);
  1037. }
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. void __fastcall TSecureShell::PoolForData(WSANETWORKEVENTS & Events, unsigned int & Result)
  1041. {
  1042. try
  1043. {
  1044. if (Configuration->LogProtocol >= 2)
  1045. {
  1046. LogEvent("Pooling for data in case they finally arrives");
  1047. }
  1048. // in extreme condition it may happen that send buffer is full, but there
  1049. // will be no data comming and we may not empty the send buffer because we
  1050. // do not process FD_WRITE until we receive any FD_READ
  1051. if (EventSelectLoop(0, false, &Events))
  1052. {
  1053. LogEvent("Data has arrived, closing query to user.");
  1054. Result = qaOK;
  1055. }
  1056. }
  1057. catch(...)
  1058. {
  1059. // if we let the exception out, it may popup another message dialog
  1060. // in whole event loop, another call to PoolForData from original dialog
  1061. // would be invoked, leading to an infinite loop.
  1062. // by retrying we hope (that probably fatal) error would repeat in WaitForData.
  1063. // anyway now once no actual work is done in EventSelectLoop,
  1064. // hardly any exception can occur actually
  1065. Result = qaRetry;
  1066. }
  1067. }
  1068. //---------------------------------------------------------------------------
  1069. class TPoolForDataEvent
  1070. {
  1071. public:
  1072. __fastcall TPoolForDataEvent(TSecureShell * SecureShell, WSANETWORKEVENTS & Events) :
  1073. FSecureShell(SecureShell),
  1074. FEvents(Events)
  1075. {
  1076. }
  1077. void __fastcall PoolForData(unsigned int & Result)
  1078. {
  1079. FSecureShell->PoolForData(FEvents, Result);
  1080. }
  1081. private:
  1082. TSecureShell * FSecureShell;
  1083. WSANETWORKEVENTS & FEvents;
  1084. };
  1085. //---------------------------------------------------------------------------
  1086. void __fastcall TSecureShell::WaitForData()
  1087. {
  1088. // see winsftp.c
  1089. bool IncomingData;
  1090. do
  1091. {
  1092. if (Configuration->LogProtocol >= 2)
  1093. {
  1094. LogEvent("Looking for incoming data");
  1095. }
  1096. IncomingData = EventSelectLoop(FSessionData->Timeout * 1000, true, NULL);
  1097. if (!IncomingData)
  1098. {
  1099. WSANETWORKEVENTS Events;
  1100. memset(&Events, 0, sizeof(Events));
  1101. TPoolForDataEvent Event(this, Events);
  1102. LogEvent("Waiting for data timed out, asking user what to do.");
  1103. TQueryParams Params(qpFatalAbort | qpAllowContinueOnError);
  1104. Params.Timer = 500;
  1105. Params.TimerEvent = Event.PoolForData;
  1106. Params.TimerMessage = FMTLOAD(TIMEOUT_STILL_WAITING, (FSessionData->Timeout));
  1107. Params.TimerAnswers = qaAbort;
  1108. int Answer = FUI->QueryUser(FMTLOAD(CONFIRM_PROLONG_TIMEOUT2, (FSessionData->Timeout)),
  1109. NULL, qaRetry | qaAbort, &Params);
  1110. switch (Answer)
  1111. {
  1112. case qaRetry:
  1113. // noop
  1114. break;
  1115. case qaOK:
  1116. // read event was already captured in PoolForData(),
  1117. // make sure we do not try to select it again as it would timeout
  1118. // unless another read event occurs
  1119. IncomingData = true;
  1120. HandleNetworkEvents(FSocket, Events);
  1121. break;
  1122. default:
  1123. assert(false);
  1124. // fallthru
  1125. case qaAbort:
  1126. FatalError(LoadStr(USER_TERMINATED));
  1127. break;
  1128. }
  1129. }
  1130. }
  1131. while (!IncomingData);
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. bool __fastcall TSecureShell::SshFallbackCmd() const
  1135. {
  1136. return ssh_fallback_cmd(FBackendHandle);
  1137. }
  1138. //---------------------------------------------------------------------------
  1139. bool __fastcall TSecureShell::EnumNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1140. {
  1141. if (Configuration->LogProtocol >= 2)
  1142. {
  1143. LogEvent(FORMAT("Enumerating network events for socket %d", (int(Socket))));
  1144. }
  1145. // see winplink.c
  1146. WSANETWORKEVENTS AEvents;
  1147. if (WSAEnumNetworkEvents(Socket, NULL, &AEvents) == 0)
  1148. {
  1149. noise_ultralight(Socket);
  1150. noise_ultralight(AEvents.lNetworkEvents);
  1151. Events.lNetworkEvents |= AEvents.lNetworkEvents;
  1152. for (int Index = 0; Index < FD_MAX_EVENTS; Index++)
  1153. {
  1154. if (AEvents.iErrorCode[Index] != 0)
  1155. {
  1156. Events.iErrorCode[Index] = AEvents.iErrorCode[Index];
  1157. }
  1158. }
  1159. if (Configuration->LogProtocol >= 2)
  1160. {
  1161. LogEvent(FORMAT("Enumerated %d network events making %d cumulative events for socket %d",
  1162. (int(AEvents.lNetworkEvents), int(Events.lNetworkEvents), int(Socket))));
  1163. }
  1164. }
  1165. else
  1166. {
  1167. if (Configuration->LogProtocol >= 2)
  1168. {
  1169. LogEvent(FORMAT("Error enumerating network events for socket %d", (int(Socket))));
  1170. }
  1171. }
  1172. return
  1173. FLAGSET(Events.lNetworkEvents, FD_READ) ||
  1174. FLAGSET(Events.lNetworkEvents, FD_CLOSE);
  1175. }
  1176. //---------------------------------------------------------------------------
  1177. void __fastcall TSecureShell::HandleNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1178. {
  1179. static const struct { int Bit, Mask; const char * Desc; } EventTypes[] =
  1180. {
  1181. { FD_READ_BIT, FD_READ, "read" },
  1182. { FD_WRITE_BIT, FD_WRITE, "write" },
  1183. { FD_OOB_BIT, FD_OOB, "oob" },
  1184. { FD_ACCEPT_BIT, FD_ACCEPT, "accept" },
  1185. { FD_CONNECT_BIT, FD_CONNECT, "connect" },
  1186. { FD_CLOSE_BIT, FD_CLOSE, "close" },
  1187. };
  1188. for (int Event = 0; Event < LENOF(EventTypes); Event++)
  1189. {
  1190. if (FLAGSET(Events.lNetworkEvents, EventTypes[Event].Mask))
  1191. {
  1192. int Err = Events.iErrorCode[EventTypes[Event].Bit];
  1193. if (Configuration->LogProtocol >= 2)
  1194. {
  1195. LogEvent(FORMAT("Handling network %s event on socket %d with error %d",
  1196. (EventTypes[Event].Desc, int(Socket), Err)));
  1197. }
  1198. #pragma option push -w-prc
  1199. LPARAM SelectEvent = WSAMAKESELECTREPLY(EventTypes[Event].Mask, Err);
  1200. #pragma option pop
  1201. if (!select_result((WPARAM)Socket, SelectEvent))
  1202. {
  1203. // note that connection was closed definitely,
  1204. // so "check" is actually not required
  1205. CheckConnection();
  1206. }
  1207. }
  1208. }
  1209. }
  1210. //---------------------------------------------------------------------------
  1211. bool __fastcall TSecureShell::ProcessNetworkEvents(SOCKET Socket)
  1212. {
  1213. WSANETWORKEVENTS Events;
  1214. memset(&Events, 0, sizeof(Events));
  1215. bool Result = EnumNetworkEvents(Socket, Events);
  1216. HandleNetworkEvents(Socket, Events);
  1217. return Result;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. bool __fastcall TSecureShell::EventSelectLoop(unsigned int MSec, bool ReadEventRequired,
  1221. WSANETWORKEVENTS * Events)
  1222. {
  1223. CheckConnection();
  1224. bool Result = false;
  1225. do
  1226. {
  1227. if (Configuration->LogProtocol >= 2)
  1228. {
  1229. LogEvent("Looking for network events");
  1230. }
  1231. unsigned int TicksBefore = GetTickCount();
  1232. int WaitResult = WaitForSingleObject(FSocketEvent, MSec);
  1233. switch (WaitResult)
  1234. {
  1235. case WAIT_OBJECT_0:
  1236. if (Configuration->LogProtocol >= 1)
  1237. {
  1238. LogEvent("Detected network event");
  1239. }
  1240. if (Events == NULL)
  1241. {
  1242. if (ProcessNetworkEvents(FSocket))
  1243. {
  1244. Result = true;
  1245. }
  1246. }
  1247. else
  1248. {
  1249. if (EnumNetworkEvents(FSocket, *Events))
  1250. {
  1251. Result = true;
  1252. }
  1253. }
  1254. {
  1255. TSockets::iterator i = FPortFwdSockets.begin();
  1256. while (i != FPortFwdSockets.end())
  1257. {
  1258. ProcessNetworkEvents(*i);
  1259. i++;
  1260. }
  1261. }
  1262. break;
  1263. case WAIT_TIMEOUT:
  1264. if (Configuration->LogProtocol >= 2)
  1265. {
  1266. LogEvent("Timeout waiting for network events");
  1267. }
  1268. MSec = 0;
  1269. break;
  1270. default:
  1271. if (Configuration->LogProtocol >= 2)
  1272. {
  1273. LogEvent(FORMAT("Unknown waiting result %d", (WaitResult)));
  1274. }
  1275. MSec = 0;
  1276. break;
  1277. }
  1278. unsigned int TicksAfter = GetTickCount();
  1279. // ticks wraps once in 49.7 days
  1280. if (TicksBefore < TicksAfter)
  1281. {
  1282. unsigned int Ticks = TicksAfter - TicksBefore;
  1283. if (Ticks > MSec)
  1284. {
  1285. MSec = 0;
  1286. }
  1287. else
  1288. {
  1289. MSec -= Ticks;
  1290. }
  1291. }
  1292. }
  1293. while (ReadEventRequired && (MSec > 0) && !Result);
  1294. return Result;
  1295. }
  1296. //---------------------------------------------------------------------------
  1297. void __fastcall TSecureShell::Idle(unsigned int MSec)
  1298. {
  1299. noise_regular();
  1300. call_ssh_timer(FBackendHandle);
  1301. EventSelectLoop(MSec, false, NULL);
  1302. }
  1303. //---------------------------------------------------------------------------
  1304. void __fastcall TSecureShell::KeepAlive()
  1305. {
  1306. LogEvent("Sending null packet to keep session alive.");
  1307. SendSpecial(TS_PING);
  1308. }
  1309. //---------------------------------------------------------------------------
  1310. unsigned long __fastcall TSecureShell::MaxPacketSize()
  1311. {
  1312. if (!FSessionInfoValid)
  1313. {
  1314. UpdateSessionInfo();
  1315. }
  1316. if (FSshVersion == 1)
  1317. {
  1318. return 0;
  1319. }
  1320. else
  1321. {
  1322. if (FMaxPacketSize == NULL)
  1323. {
  1324. FMaxPacketSize = ssh2_remmaxpkt(FBackendHandle);
  1325. }
  1326. return *FMaxPacketSize;
  1327. }
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. AnsiString __fastcall TSecureShell::FuncToCompression(
  1331. int SshVersion, const void * Compress) const
  1332. {
  1333. enum TCompressionType { ctNone, ctZLib };
  1334. if (SshVersion == 1)
  1335. {
  1336. return get_ssh1_compressing(FBackendHandle) ? "ZLib" : "";
  1337. }
  1338. else
  1339. {
  1340. return (ssh_compress *)Compress == &ssh_zlib ? "ZLib" : "";
  1341. }
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. TCipher __fastcall TSecureShell::FuncToSsh1Cipher(const void * Cipher)
  1345. {
  1346. const ssh_cipher *CipherFuncs[] =
  1347. {&ssh_3des, &ssh_des, &ssh_blowfish_ssh1};
  1348. const TCipher TCiphers[] = {cip3DES, cipDES, cipBlowfish};
  1349. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1350. TCipher Result = cipWarn;
  1351. for (int Index = 0; Index < LENOF(TCiphers); Index++)
  1352. {
  1353. if ((ssh_cipher *)Cipher == CipherFuncs[Index])
  1354. {
  1355. Result = TCiphers[Index];
  1356. }
  1357. }
  1358. assert(Result != cipWarn);
  1359. return Result;
  1360. }
  1361. //---------------------------------------------------------------------------
  1362. TCipher __fastcall TSecureShell::FuncToSsh2Cipher(const void * Cipher)
  1363. {
  1364. const ssh2_ciphers *CipherFuncs[] =
  1365. {&ssh2_3des, &ssh2_des, &ssh2_aes, &ssh2_blowfish};
  1366. const TCipher TCiphers[] = {cip3DES, cipDES, cipAES, cipBlowfish};
  1367. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1368. TCipher Result = cipWarn;
  1369. for (int C = 0; C < LENOF(TCiphers); C++)
  1370. {
  1371. for (int F = 0; F < CipherFuncs[C]->nciphers; F++)
  1372. {
  1373. if ((ssh2_cipher *)Cipher == CipherFuncs[C]->list[F])
  1374. {
  1375. Result = TCiphers[C];
  1376. }
  1377. }
  1378. }
  1379. assert(Result != cipWarn);
  1380. return Result;
  1381. }
  1382. //---------------------------------------------------------------------------
  1383. void __fastcall TSecureShell::VerifyHostKey(AnsiString Host, int Port,
  1384. const AnsiString KeyType, AnsiString KeyStr, const AnsiString Fingerprint)
  1385. {
  1386. GotHostKey();
  1387. if (FSessionData->Tunnel)
  1388. {
  1389. Host = FSessionData->OrigHostName;
  1390. Port = FSessionData->OrigPortNumber;
  1391. }
  1392. int Result;
  1393. FSessionInfo.HostKeyFingerprint = Fingerprint;
  1394. // Verify the key against the registry.
  1395. Result = verify_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1396. if (Result != 0)
  1397. {
  1398. if (Configuration->DisableAcceptingHostKeys)
  1399. {
  1400. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1401. }
  1402. else
  1403. {
  1404. TQueryParams Params;
  1405. Params.HelpKeyword = (Result == 1 ? HELP_UNKNOWN_KEY : HELP_DIFFERENT_KEY);
  1406. int R = FUI->QueryUser(
  1407. FMTLOAD((Result == 1 ? UNKNOWN_KEY2 : DIFFERENT_KEY2), (KeyType, Fingerprint)),
  1408. NULL, qaYes | qaNo | qaCancel, &Params, qtWarning);
  1409. switch (R) {
  1410. case qaYes:
  1411. store_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1412. break;
  1413. case qaCancel:
  1414. FatalError(LoadStr(KEY_NOT_VERIFIED));
  1415. }
  1416. }
  1417. }
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. void __fastcall TSecureShell::AskAlg(const AnsiString AlgType,
  1421. const AnsiString AlgName)
  1422. {
  1423. AnsiString Msg;
  1424. if (AlgType == "key-exchange algorithm")
  1425. {
  1426. Msg = FMTLOAD(KEX_BELOW_TRESHOLD, (AlgName));
  1427. }
  1428. else
  1429. {
  1430. int CipherType;
  1431. if (AlgType == "cipher")
  1432. {
  1433. CipherType = CIPHER_TYPE_BOTH;
  1434. }
  1435. else if (AlgType == "client-to-server cipher")
  1436. {
  1437. CipherType = CIPHER_TYPE_CS;
  1438. }
  1439. else if (AlgType == "server-to-client cipher")
  1440. {
  1441. CipherType = CIPHER_TYPE_SC;
  1442. }
  1443. else
  1444. {
  1445. assert(false);
  1446. }
  1447. Msg = FMTLOAD(CIPHER_BELOW_TRESHOLD, (LoadStr(CipherType), AlgName));
  1448. }
  1449. if (FUI->QueryUser(Msg, NULL, qaYes | qaNo, NULL, qtWarning) == qaNo)
  1450. {
  1451. Abort();
  1452. }
  1453. }
  1454. //---------------------------------------------------------------------------
  1455. void __fastcall TSecureShell::DisplayBanner(const AnsiString & Banner)
  1456. {
  1457. FUI->DisplayBanner(Banner);
  1458. }
  1459. //---------------------------------------------------------------------------
  1460. void __fastcall TSecureShell::OldKeyfileWarning()
  1461. {
  1462. // actually never called, see Net.cpp
  1463. FUI->QueryUser(LoadStr(OLD_KEY), NULL, qaOK, NULL, qtWarning);
  1464. }
  1465. //---------------------------------------------------------------------------
  1466. bool __fastcall TSecureShell::GetStoredCredentialsTried()
  1467. {
  1468. return FStoredPasswordTried || FStoredPasswordTriedForKI;
  1469. }