1
0

SecureShell.cpp 87 KB

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