SecureShell.cpp 91 KB

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