SecureShell.cpp 88 KB

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