SecureShell.cpp 96 KB

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