SecureShell.cpp 77 KB

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