SecureShell.cpp 80 KB

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