SecureShell.cpp 65 KB

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