SecureShell.cpp 71 KB

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