SecureShell.cpp 81 KB

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