SecureShell.cpp 90 KB

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