SshTests.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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 void 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. var asyncResult = command.BeginExecute();
  277. using (var reader = new StreamReader(command.OutputStream, new UTF8Encoding(false), false, 10))
  278. {
  279. var lines = new List<string>();
  280. string line = null;
  281. while ((line = reader.ReadLine()) != null)
  282. {
  283. lines.Add(line);
  284. }
  285. Assert.AreEqual(6, lines.Count, string.Join("\n", lines));
  286. Assert.AreEqual(expectedResult, string.Join("\n", lines));
  287. Assert.AreEqual(13, command.ExitStatus);
  288. }
  289. var actualResult = command.EndExecute(asyncResult);
  290. // command.Result (also returned from EndExecute) consumes OutputStream,
  291. // which we've already read from, so Result will be empty.
  292. // TODO consider the suggested changes in https://github.com/sshnet/SSH.NET/issues/650
  293. //Assert.AreEqual(expectedResult, actualResult);
  294. //Assert.AreEqual(expectedResult, command.Result);
  295. // For now just assert the current behaviour.
  296. Assert.AreEqual(0, actualResult.Length);
  297. Assert.AreEqual(0, command.Result.Length);
  298. }
  299. }
  300. finally
  301. {
  302. RemoveFileOrDirectory(sshClient, remoteFile);
  303. }
  304. }
  305. }
  306. [TestMethod]
  307. public void Ssh_DynamicPortForwarding_DisposeSshClientWithoutStoppingPort()
  308. {
  309. const string searchText = "HTTP/1.1 301 Moved Permanently";
  310. const string hostName = "github.com";
  311. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  312. Socket socksSocket;
  313. using (var client = new SshClient(_connectionInfoFactory.Create()))
  314. {
  315. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  316. client.Connect();
  317. var forwardedPort = new ForwardedPortDynamic(1080);
  318. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  319. client.AddForwardedPort(forwardedPort);
  320. forwardedPort.Start();
  321. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  322. string.Empty,
  323. string.Empty);
  324. socksSocket = socksClient.Connect(hostName, 80);
  325. socksSocket.Send(httpGetRequest);
  326. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  327. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  328. }
  329. Assert.IsTrue(socksSocket.Connected);
  330. // check if client socket was properly closed
  331. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  332. }
  333. [TestMethod]
  334. public void Ssh_DynamicPortForwarding_DomainName()
  335. {
  336. const string searchText = "HTTP/1.1 301 Moved Permanently";
  337. const string hostName = "github.com";
  338. // Set-up a host alias for google.be on the remote server that is not known locally; this allows us to
  339. // verify whether the host name is resolved remotely.
  340. const string hostNameAlias = "dynamicportforwarding-test.for.sshnet";
  341. // Construct a HTTP request for which we expected the response to contain the search text.
  342. var httpGetRequest = Encoding.ASCII.GetBytes($"GET / HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  343. var ipAddresses = Dns.GetHostAddresses(hostName);
  344. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  345. try
  346. {
  347. using (var client = new SshClient(_connectionInfoFactory.Create()))
  348. {
  349. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  350. client.Connect();
  351. var forwardedPort = new ForwardedPortDynamic(1080);
  352. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  353. client.AddForwardedPort(forwardedPort);
  354. forwardedPort.Start();
  355. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  356. string.Empty,
  357. string.Empty);
  358. var socksSocket = socksClient.Connect(hostNameAlias, 80);
  359. socksSocket.Send(httpGetRequest);
  360. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  361. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  362. // Verify if port is still open
  363. socksSocket.Send(httpGetRequest);
  364. GetHttpResponse(socksSocket, Encoding.ASCII);
  365. forwardedPort.Stop();
  366. Assert.IsTrue(socksSocket.Connected);
  367. // check if client socket was properly closed
  368. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  369. forwardedPort.Start();
  370. // create new SOCKS connection and very whether the forwarded port is functional again
  371. socksSocket = socksClient.Connect(hostNameAlias, 80);
  372. socksSocket.Send(httpGetRequest);
  373. httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  374. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  375. forwardedPort.Dispose();
  376. Assert.IsTrue(socksSocket.Connected);
  377. // check if client socket was properly closed
  378. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  379. forwardedPort.Dispose();
  380. }
  381. }
  382. finally
  383. {
  384. if (hostsFileUpdated)
  385. {
  386. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddresses[0], hostNameAlias);
  387. }
  388. }
  389. }
  390. [TestMethod]
  391. public void Ssh_DynamicPortForwarding_IPv4()
  392. {
  393. const string searchText = "HTTP/1.1 301 Moved Permanently";
  394. const string hostName = "github.com";
  395. var httpGetRequest = Encoding.ASCII.GetBytes($"GET /null HTTP/1.1\r\nHost: {hostName}\r\n\r\n");
  396. var ipv4 = Dns.GetHostAddresses(hostName).FirstOrDefault(p => p.AddressFamily == AddressFamily.InterNetwork);
  397. Assert.IsNotNull(ipv4, $@"No IPv4 address found for '{hostName}'.");
  398. using (var client = new SshClient(_connectionInfoFactory.Create()))
  399. {
  400. client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(200);
  401. client.Connect();
  402. var forwardedPort = new ForwardedPortDynamic(1080);
  403. forwardedPort.Exception += (sender, args) => Console.WriteLine(args.Exception.ToString());
  404. client.AddForwardedPort(forwardedPort);
  405. forwardedPort.Start();
  406. var socksClient = new Socks5Handler(new IPEndPoint(IPAddress.Loopback, 1080),
  407. string.Empty,
  408. string.Empty);
  409. var socksSocket = socksClient.Connect(new IPEndPoint(ipv4, 80));
  410. socksSocket.Send(httpGetRequest);
  411. var httpResponse = GetHttpResponse(socksSocket, Encoding.ASCII);
  412. Assert.IsTrue(httpResponse.Contains(searchText), httpResponse);
  413. forwardedPort.Dispose();
  414. // check if client socket was properly closed
  415. Assert.AreEqual(0, socksSocket.Receive(new byte[1], 0, 1, SocketFlags.None));
  416. }
  417. }
  418. /// <summary>
  419. /// Verifies whether channels are effectively closed.
  420. /// </summary>
  421. [TestMethod]
  422. public void Ssh_LocalPortForwardingCloseChannels()
  423. {
  424. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  425. const string hostName = "github.com";
  426. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  427. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  428. try
  429. {
  430. var connectionInfo = _connectionInfoFactory.Create();
  431. connectionInfo.MaxSessions = 1;
  432. using (var client = new SshClient(connectionInfo))
  433. {
  434. client.Connect();
  435. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  436. for (var i = 0; i < (connectionInfo.MaxSessions + 1); i++)
  437. {
  438. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  439. (uint)localEndPoint.Port,
  440. hostNameAlias,
  441. 80);
  442. client.AddForwardedPort(forwardedPort);
  443. forwardedPort.Start();
  444. try
  445. {
  446. var httpRequest = (HttpWebRequest)WebRequest.Create("http://" + localEndPoint);
  447. httpRequest.Host = hostName;
  448. httpRequest.Method = "GET";
  449. httpRequest.AllowAutoRedirect = false;
  450. try
  451. {
  452. using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
  453. {
  454. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  455. }
  456. }
  457. catch (WebException ex)
  458. {
  459. Assert.AreEqual(WebExceptionStatus.ProtocolError, ex.Status);
  460. Assert.IsNotNull(ex.Response);
  461. using (var httpResponse = ex.Response as HttpWebResponse)
  462. {
  463. Assert.IsNotNull(httpResponse);
  464. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  465. }
  466. }
  467. }
  468. finally
  469. {
  470. client.RemoveForwardedPort(forwardedPort);
  471. }
  472. }
  473. }
  474. }
  475. finally
  476. {
  477. if (hostsFileUpdated)
  478. {
  479. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  480. }
  481. }
  482. }
  483. [TestMethod]
  484. public void Ssh_LocalPortForwarding()
  485. {
  486. const string hostNameAlias = "localportforwarding-test.for.sshnet";
  487. const string hostName = "github.com";
  488. var ipAddress = Dns.GetHostAddresses(hostName)[0];
  489. var hostsFileUpdated = AddOrUpdateHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  490. try
  491. {
  492. using (var client = new SshClient(_connectionInfoFactory.Create()))
  493. {
  494. client.Connect();
  495. var localEndPoint = new IPEndPoint(IPAddress.Loopback, 1225);
  496. var forwardedPort = new ForwardedPortLocal(localEndPoint.Address.ToString(),
  497. (uint)localEndPoint.Port,
  498. hostNameAlias,
  499. 80);
  500. forwardedPort.Exception +=
  501. (sender, args) => Console.WriteLine(@"ForwardedPort exception: " + args.Exception);
  502. client.AddForwardedPort(forwardedPort);
  503. forwardedPort.Start();
  504. try
  505. {
  506. var httpRequest = (HttpWebRequest)WebRequest.Create("http://" + localEndPoint);
  507. httpRequest.Host = hostName;
  508. httpRequest.Method = "GET";
  509. httpRequest.Accept = "text/html";
  510. httpRequest.AllowAutoRedirect = false;
  511. try
  512. {
  513. using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
  514. {
  515. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  516. }
  517. }
  518. catch (WebException ex)
  519. {
  520. Assert.AreEqual(WebExceptionStatus.ProtocolError, ex.Status);
  521. Assert.IsNotNull(ex.Response);
  522. using (var httpResponse = ex.Response as HttpWebResponse)
  523. {
  524. Assert.IsNotNull(httpResponse);
  525. Assert.AreEqual(HttpStatusCode.MovedPermanently, httpResponse.StatusCode);
  526. }
  527. }
  528. }
  529. finally
  530. {
  531. client.RemoveForwardedPort(forwardedPort);
  532. }
  533. }
  534. }
  535. finally
  536. {
  537. if (hostsFileUpdated)
  538. {
  539. RemoveHostsEntry(_adminConnectionInfoFactory, ipAddress, hostNameAlias);
  540. }
  541. }
  542. }
  543. [TestMethod]
  544. public void Ssh_RemotePortForwarding()
  545. {
  546. var hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
  547. var ipv4HostAddress = hostAddresses.First(p => p.AddressFamily == AddressFamily.InterNetwork);
  548. var endpoint1 = new IPEndPoint(ipv4HostAddress, 10000);
  549. var endpoint2 = new IPEndPoint(ipv4HostAddress, 10001);
  550. var bytesReceivedOnListener1 = new List<byte>();
  551. var bytesReceivedOnListener2 = new List<byte>();
  552. using (var socketListener1 = new AsyncSocketListener(endpoint1))
  553. using (var socketListener2 = new AsyncSocketListener(endpoint2))
  554. using (var client = new SshClient(_connectionInfoFactory.Create()))
  555. {
  556. socketListener1.BytesReceived += (received, socket) => bytesReceivedOnListener1.AddRange(received);
  557. socketListener1.Start();
  558. socketListener2.BytesReceived += (received, socket) => bytesReceivedOnListener2.AddRange(received);
  559. socketListener2.Start();
  560. client.Connect();
  561. var forwardedPort1 = new ForwardedPortRemote(IPAddress.Loopback,
  562. 10002,
  563. endpoint1.Address,
  564. (uint)endpoint1.Port);
  565. forwardedPort1.Exception += (sender, args) => Console.WriteLine(@"forwardedPort1 exception: " + args.Exception);
  566. client.AddForwardedPort(forwardedPort1);
  567. forwardedPort1.Start();
  568. var forwardedPort2 = new ForwardedPortRemote(IPAddress.Loopback,
  569. 10003,
  570. endpoint2.Address,
  571. (uint)endpoint2.Port);
  572. forwardedPort2.Exception += (sender, args) => Console.WriteLine(@"forwardedPort2 exception: " + args.Exception);
  573. client.AddForwardedPort(forwardedPort2);
  574. forwardedPort2.Start();
  575. using (var s = client.CreateShellStream("a", 80, 25, 800, 600, 200))
  576. {
  577. s.WriteLine($"telnet {forwardedPort1.BoundHost} {forwardedPort1.BoundPort}");
  578. s.Expect($"Connected to {forwardedPort1.BoundHost}\r\n");
  579. s.WriteLine("ABC");
  580. s.Flush();
  581. s.Expect("ABC");
  582. s.Close();
  583. }
  584. using (var s = client.CreateShellStream("b", 80, 25, 800, 600, 200))
  585. {
  586. s.WriteLine($"telnet {forwardedPort2.BoundHost} {forwardedPort2.BoundPort}");
  587. s.Expect($"Connected to {forwardedPort2.BoundHost}\r\n");
  588. s.WriteLine("DEF");
  589. s.Flush();
  590. s.Expect("DEF");
  591. s.Close();
  592. }
  593. forwardedPort1.Stop();
  594. forwardedPort2.Stop();
  595. }
  596. var textReceivedOnListener1 = Encoding.ASCII.GetString(bytesReceivedOnListener1.ToArray());
  597. Assert.AreEqual("ABC\r\n", textReceivedOnListener1);
  598. var textReceivedOnListener2 = Encoding.ASCII.GetString(bytesReceivedOnListener2.ToArray());
  599. Assert.AreEqual("DEF\r\n", textReceivedOnListener2);
  600. }
  601. /// <summary>
  602. /// Issue 1591
  603. /// </summary>
  604. [TestMethod]
  605. public void Ssh_ExecuteShellScript()
  606. {
  607. const string remoteFile = "/home/sshnet/run.sh";
  608. const string content = "#\bin\bash\necho Hello World!";
  609. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  610. {
  611. client.Connect();
  612. if (client.Exists(remoteFile))
  613. {
  614. client.DeleteFile(remoteFile);
  615. }
  616. using (var memoryStream = new MemoryStream())
  617. using (var sw = new StreamWriter(memoryStream, Encoding.ASCII))
  618. {
  619. sw.Write(content);
  620. sw.Flush();
  621. memoryStream.Position = 0;
  622. client.UploadFile(memoryStream, remoteFile);
  623. }
  624. }
  625. using (var client = new SshClient(_connectionInfoFactory.Create()))
  626. {
  627. client.Connect();
  628. try
  629. {
  630. var runChmod = client.RunCommand("chmod u+x " + remoteFile);
  631. runChmod.Execute();
  632. Assert.AreEqual(0, runChmod.ExitStatus, runChmod.Error);
  633. var runLs = client.RunCommand("ls " + remoteFile);
  634. var asyncResultLs = runLs.BeginExecute();
  635. var runScript = client.RunCommand(remoteFile);
  636. var asyncResultScript = runScript.BeginExecute();
  637. Assert.IsTrue(asyncResultScript.AsyncWaitHandle.WaitOne(10000));
  638. var resultScript = runScript.EndExecute(asyncResultScript);
  639. Assert.AreEqual("Hello World!\n", resultScript);
  640. Assert.IsTrue(asyncResultLs.AsyncWaitHandle.WaitOne(10000));
  641. var resultLs = runLs.EndExecute(asyncResultLs);
  642. Assert.AreEqual(remoteFile + "\n", resultLs);
  643. }
  644. finally
  645. {
  646. RemoveFileOrDirectory(client, remoteFile);
  647. }
  648. }
  649. }
  650. /// <summary>
  651. /// Verifies if a hosts file contains an entry for a given combination of IP address and hostname,
  652. /// and if necessary add either the host entry or an alias to an exist entry for the specified IP
  653. /// address.
  654. /// </summary>
  655. /// <param name="linuxAdminConnectionFactory"></param>
  656. /// <param name="ipAddress"></param>
  657. /// <param name="hostName"></param>
  658. /// <returns>
  659. /// <see langword="true"/> if an entry was added or updated in the specified hosts file; otherwise,
  660. /// <see langword="false"/>.
  661. /// </returns>
  662. private static bool AddOrUpdateHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  663. IPAddress ipAddress,
  664. string hostName)
  665. {
  666. const string hostsFile = "/etc/hosts";
  667. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  668. {
  669. client.Connect();
  670. var hostConfig = HostConfig.Read(client, hostsFile);
  671. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  672. if (hostEntry != null)
  673. {
  674. if (hostEntry.HostName == hostName)
  675. {
  676. return false;
  677. }
  678. foreach (var alias in hostEntry.Aliases)
  679. {
  680. if (alias == hostName)
  681. {
  682. return false;
  683. }
  684. }
  685. hostEntry.Aliases.Add(hostName);
  686. }
  687. else
  688. {
  689. bool mappingFound = false;
  690. for (var i = (hostConfig.Entries.Count - 1); i >= 0; i--)
  691. {
  692. hostEntry = hostConfig.Entries[i];
  693. if (hostEntry.HostName == hostName)
  694. {
  695. if (hostEntry.IPAddress.Equals(ipAddress))
  696. {
  697. mappingFound = true;
  698. continue;
  699. }
  700. // If hostname is currently mapped to another IP address, then remove the
  701. // current mapping
  702. hostConfig.Entries.RemoveAt(i);
  703. }
  704. else
  705. {
  706. for (var j = (hostEntry.Aliases.Count - 1); j >= 0; j--)
  707. {
  708. var alias = hostEntry.Aliases[j];
  709. if (alias == hostName)
  710. {
  711. hostEntry.Aliases.RemoveAt(j);
  712. }
  713. }
  714. }
  715. }
  716. if (!mappingFound)
  717. {
  718. hostEntry = new HostEntry(ipAddress, hostName);
  719. hostConfig.Entries.Add(hostEntry);
  720. }
  721. }
  722. hostConfig.Write(client, hostsFile);
  723. return true;
  724. }
  725. }
  726. /// <summary>
  727. /// Remove the mapping between a given IP address and host name from the remote hosts file either by
  728. /// removing a host entry entirely (if no other aliases are defined for the IP address) or removing
  729. /// the aliases that match the host name for the IP address.
  730. /// </summary>
  731. /// <param name="linuxAdminConnectionFactory"></param>
  732. /// <param name="ipAddress"></param>
  733. /// <param name="hostName"></param>
  734. /// <returns>
  735. /// <see langword="true"/> if the hosts file was updated; otherwise, <see langword="false"/>.
  736. /// </returns>
  737. private static bool RemoveHostsEntry(IConnectionInfoFactory linuxAdminConnectionFactory,
  738. IPAddress ipAddress,
  739. string hostName)
  740. {
  741. const string hostsFile = "/etc/hosts";
  742. using (var client = new ScpClient(linuxAdminConnectionFactory.Create()))
  743. {
  744. client.Connect();
  745. var hostConfig = HostConfig.Read(client, hostsFile);
  746. var hostEntry = hostConfig.Entries.SingleOrDefault(h => h.IPAddress.Equals(ipAddress));
  747. if (hostEntry == null)
  748. {
  749. return false;
  750. }
  751. if (hostEntry.HostName == hostName)
  752. {
  753. if (hostEntry.Aliases.Count == 0)
  754. {
  755. hostConfig.Entries.Remove(hostEntry);
  756. }
  757. else
  758. {
  759. // Use one of the aliases (that are different from the specified host name) as host name
  760. // of the host entry.
  761. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  762. {
  763. var alias = hostEntry.Aliases[i];
  764. if (alias == hostName)
  765. {
  766. hostEntry.Aliases.RemoveAt(i);
  767. }
  768. else if (hostEntry.HostName == hostName)
  769. {
  770. // If we haven't already used one of the aliases as host name of the host entry
  771. // then do this now and remove the alias.
  772. hostEntry.HostName = alias;
  773. hostEntry.Aliases.RemoveAt(i);
  774. }
  775. }
  776. // If for some reason the host name of the host entry matched the specified host name
  777. // and it only had aliases that match the host name, then remove the host entry altogether.
  778. if (hostEntry.Aliases.Count == 0 && hostEntry.HostName == hostName)
  779. {
  780. hostConfig.Entries.Remove(hostEntry);
  781. }
  782. }
  783. }
  784. else
  785. {
  786. var aliasRemoved = false;
  787. for (var i = hostEntry.Aliases.Count - 1; i >= 0; i--)
  788. {
  789. if (hostEntry.Aliases[i] == hostName)
  790. {
  791. hostEntry.Aliases.RemoveAt(i);
  792. aliasRemoved = true;
  793. }
  794. }
  795. if (!aliasRemoved)
  796. {
  797. return false;
  798. }
  799. }
  800. hostConfig.Write(client, hostsFile);
  801. return true;
  802. }
  803. }
  804. private static string GetHttpResponse(Socket socket, Encoding encoding)
  805. {
  806. var httpResponseBuffer = new byte[2048];
  807. // We expect:
  808. // * The response to contain the searchText in the first receive.
  809. // * The full response to be returned in the first receive.
  810. var bytesReceived = socket.Receive(httpResponseBuffer,
  811. 0,
  812. httpResponseBuffer.Length,
  813. SocketFlags.None);
  814. if (bytesReceived == 0)
  815. {
  816. return null;
  817. }
  818. if (bytesReceived == httpResponseBuffer.Length)
  819. {
  820. throw new Exception("We expect the HTTP response to be less than the buffer size. If not, we won't consume the full response.");
  821. }
  822. using (var sr = new StringReader(encoding.GetString(httpResponseBuffer, 0, bytesReceived)))
  823. {
  824. return sr.ReadToEnd();
  825. }
  826. }
  827. private static void CreateShellScript(IConnectionInfoFactory connectionInfoFactory, string remoteFile, string script)
  828. {
  829. using (var sftpClient = new SftpClient(connectionInfoFactory.Create()))
  830. {
  831. sftpClient.Connect();
  832. using (var sw = sftpClient.CreateText(remoteFile, new UTF8Encoding(false)))
  833. {
  834. sw.Write(script);
  835. }
  836. sftpClient.ChangePermissions(remoteFile, 0x1FF);
  837. }
  838. }
  839. private static void RemoveFileOrDirectory(SshClient client, string remoteFile)
  840. {
  841. using (var cmd = client.CreateCommand("rm -Rf " + remoteFile))
  842. {
  843. cmd.Execute();
  844. Assert.AreEqual(0, cmd.ExitStatus, cmd.Error);
  845. }
  846. }
  847. }
  848. }