SecureShell.cpp 71 KB

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