1
0

SecureShell.cpp 81 KB

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