SecureShell.cpp 65 KB

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