SecureShell.cpp 83 KB

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