SecureShell.cpp 77 KB

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