SecureShell.cpp 82 KB

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