1
0

SecureShell.cpp 75 KB

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