1
0

SecureShell.cpp 80 KB

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