SecureShell.cpp 88 KB

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