SecureShell.cpp 51 KB

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