SecureShell.cpp 96 KB

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