1
0

SecureShell.cpp 89 KB

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