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