SecureShell.cpp 76 KB

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