SecureShell.cpp 78 KB

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