SecureShell.cpp 75 KB

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