SecureShell.cpp 84 KB

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