SecureShell.cpp 86 KB

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