SecureShell.cpp 89 KB

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