SecureShell.cpp 81 KB

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