SecureShell.cpp 72 KB

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