SecureShell.cpp 75 KB

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