1
0

SecureShell.cpp 87 KB

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