SecureShell.cpp 86 KB

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