SecureShell.cpp 88 KB

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