SecureShell.cpp 78 KB

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