SecureShell.cpp 95 KB

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