SecureShell.cpp 88 KB

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