SecureShell.cpp 87 KB

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