SshTests.cs 43 KB

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