SecureShell.cpp 88 KB

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