1
0

SecureShell.cpp 83 KB

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