SecureShell.cpp 83 KB

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