SecureShell.cpp 84 KB

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