SecureShell.cpp 65 KB

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