SecureShell.cpp 96 KB

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