1
0

SecureShell.cpp 73 KB

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