SecureShell.cpp 80 KB

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