SecureShell.cpp 82 KB

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