SshTests.cs 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. using System.ComponentModel;
  2. using System.Net;
  3. #if NETFRAMEWORK
  4. using System.Net.Http;
  5. #endif
  6. using System.Net.Sockets;
  7. using Renci.SshNet.Common;
  8. using Renci.SshNet.IntegrationTests.Common;
  9. using Renci.SshNet.Tests.Common;
  10. namespace Renci.SshNet.IntegrationTests
  11. {
  12. [TestClass]
  13. public class SshTests : TestBase
  14. {
  15. private IConnectionInfoFactory _connectionInfoFactory;
  16. private IConnectionInfoFactory _adminConnectionInfoFactory;
  17. private RemoteSshdConfig _remoteSshdConfig;
  18. [TestInitialize]
  19. public void SetUp()
  20. {
  21. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  22. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  23. _remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  24. _remoteSshdConfig.AllowTcpForwarding()
  25. .PermitTTY(true)
  26. .PrintMotd(false)
  27. .Update()
  28. .Restart();
  29. }
  30. [TestCleanup]
  31. public void TearDown()
  32. {
  33. _remoteSshdConfig?.Reset();
  34. }
  35. /// <summary>
  36. /// Test for a channel that is being closed by the server.
  37. /// </summary>
  38. [TestMethod]
  39. public void Ssh_ShellStream_Exit()
  40. {
  41. using (var client = new SshClient(_connectionInfoFactory.Create()))
  42. {
  43. client.Connect();
  44. var terminalModes = new Dictionary<TerminalModes, uint>
  45. {
  46. { TerminalModes.ECHO, 0 }
  47. };
  48. using (var shellStream = client.CreateShellStream("xterm", 80, 24, 800, 600, 1024, terminalModes))
  49. {
  50. shellStream.WriteLine("echo Hello!");
  51. shellStream.WriteLine("exit");
  52. Thread.Sleep(1000);
  53. try
  54. {
  55. shellStream.Write("ABC");
  56. Assert.Fail();
  57. }
  58. catch (ObjectDisposedException ex)
  59. {
  60. Assert.IsNull(ex.InnerException);
  61. Assert.AreEqual("Renci.SshNet.ShellStream", ex.ObjectName);
  62. Assert.AreEqual($"Cannot access a disposed object.{Environment.NewLine}Object name: '{ex.ObjectName}'.", ex.Message);
  63. }
  64. var line = shellStream.ReadLine();
  65. Assert.IsNotNull(line);
  66. Assert.IsTrue(line.EndsWith("Hello!"), line);
  67. Assert.IsTrue(shellStream.ReadLine() is null || shellStream.ReadLine() is null); // we might first get e.g. "renci-ssh-tests-server:~$"
  68. }
  69. }
  70. }
  71. [TestMethod]
  72. public void Ssh_CreateShellStreamNoTerminal()
  73. {
  74. using (var client = new SshClient(_connectionInfoFactory.Create()))
  75. {
  76. client.Connect();
  77. using (var shellStream = client.CreateShellStreamNoTerminal(bufferSize: 1024))
  78. {
  79. var foo = new string('a', 90);
  80. shellStream.WriteLine($"echo {foo}");
  81. var line = shellStream.ReadLine(TimeSpan.FromSeconds(1));
  82. Assert.IsNotNull(line);
  83. Assert.IsTrue(line.EndsWith(foo), line);
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// https://github.com/sshnet/SSH.NET/issues/63
  89. /// </summary>
  90. [TestMethod]
  91. [Category("Reproduction Tests")]
  92. public void Ssh_ShellStream_IntermittendOutput()
  93. {
  94. const string remoteFile = "/home/sshnet/test.sh";
  95. List<string> expectedLines = ["renci-ssh-tests-server:~$ Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  96. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  97. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  98. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  99. "Line 5 ",
  100. "Line 6",
  101. "renci-ssh-tests-server:~$ "]; // No idea how stable this is.
  102. var scriptBuilder = new StringBuilder();
  103. scriptBuilder.Append("#!/bin/sh\n");
  104. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  105. scriptBuilder.Append("sleep .5\n");
  106. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  107. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  108. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  109. scriptBuilder.Append("sleep 2\n");
  110. scriptBuilder.Append("echo \"Line 5 \"\n");
  111. scriptBuilder.Append("echo Line 6 \n");
  112. scriptBuilder.Append("exit 13\n");
  113. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  114. {
  115. sshClient.Connect();
  116. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  117. try
  118. {
  119. var terminalModes = new Dictionary<TerminalModes, uint>
  120. {
  121. { TerminalModes.ECHO, 0 }
  122. };
  123. using (var shellStream = sshClient.CreateShellStream("xterm", 80, 24, 800, 600, 1024, terminalModes))
  124. {
  125. shellStream.WriteLine(remoteFile);
  126. shellStream.WriteLine("exit");
  127. using (var reader = new StreamReader(shellStream))
  128. {
  129. var lines = new List<string>();
  130. string line = null;
  131. while ((line = reader.ReadLine()) != null)
  132. {
  133. lines.Add(line);
  134. }
  135. CollectionAssert.AreEqual(expectedLines, lines, string.Join("\n", lines));
  136. }
  137. }
  138. }
  139. finally
  140. {
  141. RemoveFileOrDirectory(sshClient, remoteFile);
  142. }
  143. }
  144. }
  145. /// <summary>
  146. /// Issue 1555
  147. /// </summary>
  148. [TestMethod]
  149. public void Ssh_CreateShell()
  150. {
  151. using (var client = new SshClient(_connectionInfoFactory.Create()))
  152. {
  153. client.Connect();
  154. using (var input = new MemoryStream())
  155. using (var output = new MemoryStream())
  156. using (var extOutput = new MemoryStream())
  157. {
  158. var shell = client.CreateShell(input, output, extOutput);
  159. shell.Start();
  160. var inputWriter = new StreamWriter(input, Encoding.ASCII, 1024);
  161. inputWriter.WriteLine("echo $PATH");
  162. var outputReader = new StreamReader(output, Encoding.ASCII, false, 1024);
  163. Console.WriteLine(outputReader.ReadToEnd());
  164. shell.Stop();
  165. }
  166. }
  167. }
  168. [TestMethod]
  169. public void Ssh_CreateShellNoTerminal()
  170. {
  171. using (var client = new SshClient(_connectionInfoFactory.Create()))
  172. {
  173. client.Connect();
  174. using (var input = new MemoryStream())
  175. using (var output = new MemoryStream())
  176. using (var extOutput = new MemoryStream())
  177. {
  178. var shell = client.CreateShellNoTerminal(input, output, extOutput, 1024);
  179. shell.Start();
  180. var inputWriter = new StreamWriter(input, Encoding.ASCII, 1024);
  181. var foo = new string('a', 90);
  182. inputWriter.WriteLine($"echo {foo}");
  183. inputWriter.Flush();
  184. input.Position = 0;
  185. Thread.Sleep(1000);
  186. output.Position = 0;
  187. var outputReader = new StreamReader(output, Encoding.ASCII, false, 1024);
  188. var outputString = outputReader.ReadLine();
  189. Assert.IsNotNull(outputString);
  190. Assert.IsTrue(outputString.EndsWith(foo), outputString);
  191. shell.Stop();
  192. }
  193. }
  194. }
  195. [TestMethod]
  196. public void Ssh_Command_IntermittentOutput_EndExecute()
  197. {
  198. const string remoteFile = "/home/sshnet/test.sh";
  199. var expectedResult = string.Join("\n",
  200. "Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  201. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  202. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  203. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  204. "Line 5 ",
  205. "Line 6",
  206. "");
  207. var scriptBuilder = new StringBuilder();
  208. scriptBuilder.Append("#!/bin/sh\n");
  209. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  210. scriptBuilder.Append("sleep .5\n");
  211. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  212. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  213. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  214. scriptBuilder.Append("sleep 2\n");
  215. scriptBuilder.Append("echo \"Line 5 \"\n");
  216. scriptBuilder.Append("echo Line 6 \n");
  217. scriptBuilder.Append("exit 13\n");
  218. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  219. {
  220. sshClient.Connect();
  221. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  222. try
  223. {
  224. using (var cmd = sshClient.CreateCommand("chmod 777 " + remoteFile))
  225. {
  226. cmd.Execute();
  227. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  228. }
  229. using (var command = sshClient.CreateCommand(remoteFile))
  230. {
  231. var asyncResult = command.BeginExecute();
  232. var actualResult = command.EndExecute(asyncResult);
  233. Assert.AreEqual(expectedResult, actualResult);
  234. Assert.AreEqual(expectedResult, command.Result);
  235. Assert.AreEqual(13, command.ExitStatus);
  236. }
  237. }
  238. finally
  239. {
  240. RemoveFileOrDirectory(sshClient, remoteFile);
  241. }
  242. }
  243. }
  244. [TestMethod]
  245. public async Task Ssh_Command_IntermittentOutput_OutputStream()
  246. {
  247. const string remoteFile = "/home/sshnet/test.sh";
  248. var expectedResult = string.Join("\n",
  249. "Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  250. "Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  251. "Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  252. "Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  253. "Line 5 ",
  254. "Line 6");
  255. var scriptBuilder = new StringBuilder();
  256. scriptBuilder.Append("#!/bin/sh\n");
  257. scriptBuilder.Append("echo Line 1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  258. scriptBuilder.Append("sleep .5\n");
  259. scriptBuilder.Append("echo Line 2 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  260. scriptBuilder.Append("echo Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  261. scriptBuilder.Append("echo Line 4 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
  262. scriptBuilder.Append("sleep 2\n");
  263. scriptBuilder.Append("echo \"Line 5 \"\n");
  264. scriptBuilder.Append("echo Line 6 \n");
  265. scriptBuilder.Append("exit 13\n");
  266. using (var sshClient = new SshClient(_connectionInfoFactory.Create()))
  267. {
  268. sshClient.Connect();
  269. CreateShellScript(_connectionInfoFactory, remoteFile, scriptBuilder.ToString());
  270. try
  271. {
  272. using (var cmd = sshClient.CreateCommand("chmod 777 " + remoteFile))
  273. {
  274. await cmd.ExecuteAsync();
  275. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  276. }
  277. using (var command = sshClient.CreateCommand(remoteFile))
  278. {
  279. await command.ExecuteAsync();
  280. Assert.AreEqual(13, command.ExitStatus);
  281. using (var reader = new StreamReader(command.OutputStream))
  282. {
  283. var lines = new List<string>();
  284. string line = null;
  285. while ((line = await reader.ReadLineAsync()) != null)
  286. {
  287. lines.Add(line);
  288. }
  289. Assert.AreEqual(6, lines.Count, string.Join("\n", lines));
  290. Assert.AreEqual(expectedResult, string.Join("\n", lines));
  291. }
  292. // We have already consumed OutputStream ourselves, so we expect Result to be empty.
  293. Assert.AreEqual("", command.Result);
  294. }
  295. }
  296. finally
  297. {
  298. RemoveFileOrDirectory(sshClient, remoteFile);
  299. }
  300. }
  301. }
  302. [TestMethod]
  303. public void Ssh_DynamicPortForwarding_DisposeSshClientWithoutStoppingPort()
  304. {
  305. const string searchText = "HTTP/1.1 301 Moved Permanently";
  306. const string hostName = "github.com";
  307. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  308. Socket socksSocket;
  309. using (var client = new SshClient(_connectionInfoFactory.Create()))
  310. {
  311. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  312. client.Connect();
  313. var forwardedPort = new ForwardedPortDynamic(1080);
  314. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  315. client.AddForwardedPort(forwardedPort);
  316. forwardedPort.Start();
  317. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  318. string.Empty,
  319. string.Empty);
  320. socksSocket = socksClient.Connect(hostName, 80);
  321. socksSocket.Send(httpGetRequest);
  322. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  323. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  324. }
  325. Assert.IsTrue(socksSocket.Connected);
  326. // check if client socket was properly closed
  327. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  328. }
  329. [TestMethod]
  330. public void Ssh_DynamicPortForwarding_DomainName()
  331. {
  332. const string searchText = "HTTP/1.1 301 Moved Permanently";
  333. const string hostName = "github.com";
  334. // Set-up a host alias for google.be on the remote server that is not known locally; this allows us to
  335. // verify whether the host name is resolved remotely.
  336. const string hostNameAlias = "dynamicportforwarding-test.for.sshnet";
  337. // Construct a HTTP request for which we expected the response to contain the search text.
  338. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  339. var ipAddresses = Dns.GetHostAddresses(hostName);
  340. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  341. try
  342. {
  343. using (var client = new SshClient(_connectionInfoFactory.Create()))
  344. {
  345. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  346. client.Connect();
  347. var forwardedPort = new ForwardedPortDynamic(1080);
  348. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  349. client.AddForwardedPort(forwardedPort);
  350. forwardedPort.Start();
  351. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  352. string.Empty,
  353. string.Empty);
  354. var socksSocket = socksClient.Connect(hostNameAlias, 80);
  355. socksSocket.Send(httpGetRequest);
  356. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  357. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  358. // Verify if port is still open
  359. socksSocket.Send(httpGetRequest);
  360. GetHttpResponse(socksSocket, Encoding.ASCII);
  361. forwardedPort.Stop();
  362. Assert.IsTrue(socksSocket.Connected);
  363. // check if client socket was properly closed
  364. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  365. forwardedPort.Start();
  366. // create new SOCKS connection and very whether the forwarded port is functional again
  367. socksSocket = socksClient.Connect(hostNameAlias, 80);
  368. socksSocket.Send(httpGetRequest);
  369. httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  370. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  371. forwardedPort.Dispose();
  372. Assert.IsTrue(socksSocket.Connected);
  373. // check if client socket was properly closed
  374. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  375. forwardedPort.Dispose();
  376. }
  377. }
  378. finally
  379. {
  380. if (hostsFileUpdated)
  381. {
  382. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  383. }
  384. }
  385. }
  386. [TestMethod]
  387. public void Ssh_DynamicPortForwarding_IPv4()
  388. {
  389. const string searchText = "HTTP/1.1 301 Moved Permanently";
  390. const string hostName = "github.com";
  391. var httpGetRequest = Encoding.ASCII.GetBytes($"GET /null HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  392. var ipv4 = Dns.GetHostAddresses(hostName).FirstOrDefault(p => p.AddressFamily == AddressFamily.InterNetwork);
  393. Assert.IsNotNull(ipv4, $@"No IPv4 address found for '{hostName}'.");
  394. using (var client = new SshClient(_connectionInfoFactory.Create()))
  395. {
  396. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  397. client.Connect();
  398. var forwardedPort = new ForwardedPortDynamic(1080);
  399. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  400. client.AddForwardedPort(forwardedPort);
  401. forwardedPort.Start();
  402. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  403. string.Empty,
  404. string.Empty);
  405. var socksSocket = socksClient.Connect(new IPEndPoint(ipv4, 80));
  406. socksSocket.Send(httpGetRequest);
  407. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  408. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  409. forwardedPort.Dispose();
  410. // check if client socket was properly closed
  411. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  412. }
  413. }
  414. /// <summary>
  415. /// Verifies whether channels are effectively closed.
  416. /// </summary>
  417. [TestMethod]
  418. public void Ssh_LocalPortForwardingCloseChannels()
  419. {
  420. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  421. const string hostName = "github.com";
  422. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  423. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  424. try
  425. {
  426. var connectionInfo = _connectionInfoFactory.Create();
  427. connectionInfo.MaxSessions = 1;
  428. using (var client = new SshClient(connectionInfo))
  429. {
  430. client.Connect();
  431. for (var i = 0; i < (connectionInfo.MaxSessions + 1); i++)
  432. {
  433. var forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(),
  434. hostNameAlias,
  435. 80);
  436. client.AddForwardedPort(forwardedPort);
  437. forwardedPort.Start();
  438. try
  439. {
  440. using HttpClientHandler handler = new()
  441. {
  442. AllowAutoRedirect = false
  443. };
  444. using HttpClient httpClient = new(handler);
  445. using HttpResponseMessage httpResponse = httpClient.GetAsync(
  446. $"http://{forwardedPort.BoundHost}:{forwardedPort.BoundPort}").Result;
  447. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  448. }
  449. finally
  450. {
  451. client.RemoveForwardedPort(forwardedPort);
  452. }
  453. }
  454. }
  455. }
  456. finally
  457. {
  458. if (hostsFileUpdated)
  459. {
  460. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  461. }
  462. }
  463. }
  464. [TestMethod]
  465. public void Ssh_LocalPortForwarding()
  466. {
  467. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  468. const string hostName = "github.com";
  469. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  470. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  471. try
  472. {
  473. using (var client = new SshClient(_connectionInfoFactory.Create()))
  474. {
  475. client.Connect();
  476. var forwardedPort = new ForwardedPortLocal(IPAddress.Loopback.ToString(),
  477. hostNameAlias,
  478. 80);
  479. forwardedPort.Exception +=
  480. (sender, args) => Console.WriteLine(@"ForwardedPort exception: " + args.Exception);
  481. client.AddForwardedPort(forwardedPort);
  482. forwardedPort.Start();
  483. try
  484. {
  485. using HttpClientHandler handler = new()
  486. {
  487. AllowAutoRedirect = false
  488. };
  489. using HttpClient httpClient = new(handler);
  490. using HttpResponseMessage httpResponse = httpClient.GetAsync(
  491. $"http://{forwardedPort.BoundHost}:{forwardedPort.BoundPort}").Result;
  492. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  493. }
  494. finally
  495. {
  496. client.RemoveForwardedPort(forwardedPort);
  497. }
  498. }
  499. }
  500. finally
  501. {
  502. if (hostsFileUpdated)
  503. {
  504. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  505. }
  506. }
  507. }
  508. [TestMethod]
  509. public void Ssh_RemotePortForwarding()
  510. {
  511. var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
  512. var ipv4HostAddress = hostAddresses.First(p => p.AddressFamily == AddressFamily.InterNetwork);
  513. var endpoint1 = new IPEndPoint(ipv4HostAddress, 10000);
  514. var endpoint2 = new IPEndPoint(ipv4HostAddress, 10001);
  515. var areBytesReceivedOnListener1 = false;
  516. var areBytesReceivedOnListener2 = false;
  517. var bytesReceivedOnListener1 = new List<byte>();
  518. var bytesReceivedOnListener2 = new List<byte>();
  519. using (var socketListener1 = new AsyncSocketListener(endpoint1))
  520. using (var socketListener2 = new AsyncSocketListener(endpoint2))
  521. using (var bytesReceivedEventOnListener1 = new AutoResetEvent(false))
  522. using (var bytesReceivedEventOnListener2 = new AutoResetEvent(false))
  523. using (var client = new SshClient(_connectionInfoFactory.Create()))
  524. {
  525. socketListener1.BytesReceived += (received, socket) =>
  526. {
  527. bytesReceivedOnListener1.AddRange(received);
  528. bytesReceivedEventOnListener1.Set();
  529. };
  530. socketListener1.Start();
  531. socketListener2.BytesReceived += (received, socket) =>
  532. {
  533. bytesReceivedOnListener2.AddRange(received);
  534. bytesReceivedEventOnListener2.Set();
  535. };
  536. socketListener2.Start();
  537. client.Connect();
  538. var forwardedPort1 = new ForwardedPortRemote(IPAddress.Loopback,
  539. 10002,
  540. endpoint1.Address,
  541. (uint)endpoint1.Port);
  542. forwardedPort1.Exception += (sender, args) => Console.WriteLine(@"forwardedPort1 exception: " + args.Exception);
  543. client.AddForwardedPort(forwardedPort1);
  544. forwardedPort1.Start();
  545. var forwardedPort2 = new ForwardedPortRemote(IPAddress.Loopback,
  546. 10003,
  547. endpoint2.Address,
  548. (uint)endpoint2.Port);
  549. forwardedPort2.Exception += (sender, args) => Console.WriteLine(@"forwardedPort2 exception: " + args.Exception);
  550. client.AddForwardedPort(forwardedPort2);
  551. forwardedPort2.Start();
  552. using (var s = client.CreateShellStream("a", 80, 25, 800, 600, 200))
  553. {
  554. s.WriteLine($"telnet {forwardedPort1.BoundHost} {forwardedPort1.BoundPort}");
  555. s.Expect($"Connected to {forwardedPort1.BoundHost}\r\n");
  556. s.WriteLine("ABC");
  557. s.Flush();
  558. s.Expect("ABC");
  559. s.Close();
  560. }
  561. using (var s = client.CreateShellStream("b", 80, 25, 800, 600, 200))
  562. {
  563. s.WriteLine($"telnet {forwardedPort2.BoundHost} {forwardedPort2.BoundPort}");
  564. s.Expect($"Connected to {forwardedPort2.BoundHost}\r\n");
  565. s.WriteLine("DEF");
  566. s.Flush();
  567. s.Expect("DEF");
  568. s.Close();
  569. }
  570. areBytesReceivedOnListener1 = bytesReceivedEventOnListener1.WaitOne(1000);
  571. areBytesReceivedOnListener2 = bytesReceivedEventOnListener2.WaitOne(1000);
  572. forwardedPort1.Stop();
  573. forwardedPort2.Stop();
  574. }
  575. Assert.IsTrue(areBytesReceivedOnListener1);
  576. Assert.IsTrue(areBytesReceivedOnListener2);
  577. var textReceivedOnListener1 = Encoding.ASCII.GetString(bytesReceivedOnListener1.ToArray());
  578. Assert.AreEqual("ABC\r\n", textReceivedOnListener1);
  579. var textReceivedOnListener2 = Encoding.ASCII.GetString(bytesReceivedOnListener2.ToArray());
  580. Assert.AreEqual("DEF\r\n", textReceivedOnListener2);
  581. }
  582. /// <summary>
  583. /// Issue 1591
  584. /// </summary>
  585. [TestMethod]
  586. public void Ssh_ExecuteShellScript()
  587. {
  588. const string remoteFile = "/home/sshnet/run.sh";
  589. const string content = "#\bin\bash\necho Hello World!";
  590. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  591. {
  592. client.Connect();
  593. if (client.Exists(remoteFile))
  594. {
  595. client.DeleteFile(remoteFile);
  596. }
  597. using (var memoryStream = new MemoryStream())
  598. using (var sw = new StreamWriter(memoryStream, Encoding.ASCII))
  599. {
  600. sw.Write(content);
  601. sw.Flush();
  602. memoryStream.Position = 0;
  603. client.UploadFile(memoryStream, remoteFile);
  604. }
  605. }
  606. using (var client = new SshClient(_connectionInfoFactory.Create()))
  607. {
  608. client.Connect();
  609. try
  610. {
  611. var runChmod = client.RunCommand("chmod u+x " + remoteFile);
  612. runChmod.Execute();
  613. Assert.AreEqual(0, runChmod.ExitStatus, runChmod.Error);
  614. var runLs = client.RunCommand("ls " + remoteFile);
  615. var asyncResultLs = runLs.BeginExecute();
  616. var runScript = client.RunCommand(remoteFile);
  617. var asyncResultScript = runScript.BeginExecute();
  618. Assert.IsTrue(asyncResultScript.AsyncWaitHandle.WaitOne(10000));
  619. var resultScript = runScript.EndExecute(asyncResultScript);
  620. Assert.AreEqual("Hello World!\n", resultScript);
  621. Assert.IsTrue(asyncResultLs.AsyncWaitHandle.WaitOne(10000));
  622. var resultLs = runLs.EndExecute(asyncResultLs);
  623. Assert.AreEqual(remoteFile + "\n", resultLs);
  624. }
  625. finally
  626. {
  627. RemoveFileOrDirectory(client, remoteFile);
  628. }
  629. }
  630. }
  631. /// <summary>
  632. /// Verifies if a hosts file contains an entry for a given combination of IP address and hostname,
  633. /// and if necessary add either the host entry or an alias to an exist entry for the specified IP
  634. /// address.
  635. /// </summary>
  636. /// <param name="linuxAdminConnectionFactory"></param>
  637. /// <param name="ipAddress"></param>
  638. /// <param name="hostName"></param>
  639. /// <returns>
  640. /// <see langword="true"/> if an entry was added or updated in the specified hosts file; otherwise,
  641. /// <see langword="false"/>.
  642. /// </returns>
  643. private static bool AddOrUpdateHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  644. IPAddress ipAddress,
  645. string hostName)
  646. {
  647. const string hostsFile = "/etc/hosts";
  648. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  649. {
  650. client.Connect();
  651. var hostConfig = HostConfig.Read(client, hostsFile);
  652. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  653. if (hostEntry != null)
  654. {
  655. if (hostEntry.HostName == hostName)
  656. {
  657. return false;
  658. }
  659. foreach (var alias in hostEntry.Aliases)
  660. {
  661. if (alias == hostName)
  662. {
  663. return false;
  664. }
  665. }
  666. hostEntry.Aliases.Add(hostName);
  667. }
  668. else
  669. {
  670. bool mappingFound = false;
  671. for (var i = (hostConfig.Entries.Count - 1); i >= 0; i--)
  672. {
  673. hostEntry = hostConfig.Entries[i];
  674. if (hostEntry.HostName == hostName)
  675. {
  676. if (hostEntry.IPAddress.Equals(ipAddress))
  677. {
  678. mappingFound = true;
  679. continue;
  680. }
  681. // If hostname is currently mapped to another IP address, then remove the
  682. // current mapping
  683. hostConfig.Entries.RemoveAt(i);
  684. }
  685. else
  686. {
  687. for (var j = (hostEntry.Aliases.Count - 1); j >= 0; j--)
  688. {
  689. var alias = hostEntry.Aliases[j];
  690. if (alias == hostName)
  691. {
  692. hostEntry.Aliases.RemoveAt(j);
  693. }
  694. }
  695. }
  696. }
  697. if (!mappingFound)
  698. {
  699. hostEntry = new HostEntry(ipAddress, hostName);
  700. hostConfig.Entries.Add(hostEntry);
  701. }
  702. }
  703. hostConfig.Write(client, hostsFile);
  704. return true;
  705. }
  706. }
  707. /// <summary>
  708. /// Remove the mapping between a given IP address and host name from the remote hosts file either by
  709. /// removing a host entry entirely (if no other aliases are defined for the IP address) or removing
  710. /// the aliases that match the host name for the IP address.
  711. /// </summary>
  712. /// <param name="linuxAdminConnectionFactory"></param>
  713. /// <param name="ipAddress"></param>
  714. /// <param name="hostName"></param>
  715. /// <returns>
  716. /// <see langword="true"/> if the hosts file was updated; otherwise, <see langword="false"/>.
  717. /// </returns>
  718. private static bool RemoveHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  719. IPAddress ipAddress,
  720. string hostName)
  721. {
  722. const string hostsFile = "/etc/hosts";
  723. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  724. {
  725. client.Connect();
  726. var hostConfig = HostConfig.Read(client, hostsFile);
  727. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  728. if (hostEntry == null)
  729. {
  730. return false;
  731. }
  732. if (hostEntry.HostName == hostName)
  733. {
  734. if (hostEntry.Aliases.Count == 0)
  735. {
  736. hostConfig.Entries.Remove(hostEntry);
  737. }
  738. else
  739. {
  740. // Use one of the aliases (that are different from the specified host name) as host name
  741. // of the host entry.
  742. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  743. {
  744. var alias = hostEntry.Aliases[i];
  745. if (alias == hostName)
  746. {
  747. hostEntry.Aliases.RemoveAt(i);
  748. }
  749. else if (hostEntry.HostName == hostName)
  750. {
  751. // If we haven't already used one of the aliases as host name of the host entry
  752. // then do this now and remove the alias.
  753. hostEntry.HostName = alias;
  754. hostEntry.Aliases.RemoveAt(i);
  755. }
  756. }
  757. // If for some reason the host name of the host entry matched the specified host name
  758. // and it only had aliases that match the host name, then remove the host entry altogether.
  759. if (hostEntry.Aliases.Count == 0 && hostEntry.HostName == hostName)
  760. {
  761. hostConfig.Entries.Remove(hostEntry);
  762. }
  763. }
  764. }
  765. else
  766. {
  767. var aliasRemoved = false;
  768. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  769. {
  770. if (hostEntry.Aliases[i] == hostName)
  771. {
  772. hostEntry.Aliases.RemoveAt(i);
  773. aliasRemoved = true;
  774. }
  775. }
  776. if (!aliasRemoved)
  777. {
  778. return false;
  779. }
  780. }
  781. hostConfig.Write(client, hostsFile);
  782. return true;
  783. }
  784. }
  785. private static string GetHttpResponse(Socket socket, Encoding encoding)
  786. {
  787. var httpResponseBuffer = new byte[2048];
  788. // We expect:
  789. // * The response to contain the searchText in the first receive.
  790. // * The full response to be returned in the first receive.
  791. var bytesReceived = socket.Receive(httpResponseBuffer,
  792. 0,
  793. httpResponseBuffer.Length,
  794. SocketFlags.None);
  795. if (bytesReceived == 0)
  796. {
  797. return null;
  798. }
  799. if (bytesReceived == httpResponseBuffer.Length)
  800. {
  801. throw new Exception("We expect the HTTP response to be less than the buffer size. If not, we won't consume the full response.");
  802. }
  803. using (var sr = new StringReader(encoding.GetString(httpResponseBuffer, 0, bytesReceived)))
  804. {
  805. return sr.ReadToEnd();
  806. }
  807. }
  808. private static void CreateShellScript(IConnectionInfoFactory connectionInfoFactory, string remoteFile, string script)
  809. {
  810. using (var sftpClient = new SftpClient(connectionInfoFactory.Create()))
  811. {
  812. sftpClient.Connect();
  813. using (var sw = sftpClient.CreateText(remoteFile, new UTF8Encoding(false)))
  814. {
  815. sw.Write(script);
  816. }
  817. sftpClient.ChangePermissions(remoteFile, 0x1FF);
  818. }
  819. }
  820. private static void RemoveFileOrDirectory(SshClient client, string remoteFile)
  821. {
  822. using (var cmd = client.CreateCommand("rm -Rf " + remoteFile))
  823. {
  824. cmd.Execute();
  825. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  826. }
  827. }
  828. }
  829. }