ProtocolVersionExchange.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using Renci.SshNet.Abstractions;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.Messages.Transport;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Net.Sockets;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. namespace Renci.SshNet.Connection
  11. {
  12. /// <summary>
  13. /// Handles the SSH protocol version exchange.
  14. /// </summary>
  15. internal class ProtocolVersionExchange : IProtocolVersionExchange
  16. {
  17. private const byte Null = 0x00;
  18. #if FEATURE_REGEX_COMPILE
  19. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+?)([ ](?<comments>.+))?$", RegexOptions.Compiled);
  20. #else
  21. private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+?)([ ](?<comments>.+))?$");
  22. #endif
  23. /// <summary>
  24. /// Performs the SSH protocol version exchange.
  25. /// </summary>
  26. /// <param name="clientVersion">The identification string of the SSH client.</param>
  27. /// <param name="socket">A <see cref="Socket"/> connected to the server.</param>
  28. /// <param name="timeout">The maximum time to wait for the server to respond.</param>
  29. /// <returns>
  30. /// The SSH identification of the server.
  31. /// </returns>
  32. public SshIdentification Start(string clientVersion, Socket socket, TimeSpan timeout)
  33. {
  34. // Immediately send the identification string since the spec states both sides MUST send an identification string
  35. // when the connection has been established
  36. SocketAbstraction.Send(socket, Encoding.UTF8.GetBytes(clientVersion + "\x0D\x0A"));
  37. var bytesReceived = new List<byte>();
  38. // Get server version from the server,
  39. // ignore text lines which are sent before if any
  40. while (true)
  41. {
  42. var line = SocketReadLine(socket, timeout, bytesReceived);
  43. if (line == null)
  44. {
  45. if (bytesReceived.Count == 0)
  46. {
  47. throw new SshConnectionException("Server response does not contain SSH protocol identification. Connection to remote server was closed before any data was received.", DisconnectReason.ConnectionLost);
  48. }
  49. throw new SshConnectionException(string.Format("Server response does not contain SSH protocol identification:{0}{1}", Environment.NewLine, PacketDump.Create(bytesReceived, 2)),
  50. DisconnectReason.ProtocolError);
  51. }
  52. var identificationMatch = ServerVersionRe.Match(line);
  53. if (identificationMatch.Success)
  54. {
  55. return new SshIdentification(GetGroupValue(identificationMatch, "protoversion"),
  56. GetGroupValue(identificationMatch, "softwareversion"),
  57. GetGroupValue(identificationMatch, "comments"));
  58. }
  59. }
  60. }
  61. private static string GetGroupValue(Match match, string groupName)
  62. {
  63. var commentsGroup = match.Groups[groupName];
  64. if (commentsGroup.Success)
  65. {
  66. return commentsGroup.Value;
  67. }
  68. return null;
  69. }
  70. /// <summary>
  71. /// Performs a blocking read on the socket until a line is read.
  72. /// </summary>
  73. /// <param name="socket">The <see cref="Socket"/> to read from.</param>
  74. /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param>
  75. /// <param name="buffer">A <see cref="List{Byte}"/> to which read bytes will be added.</param>
  76. /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception>
  77. /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception>
  78. /// <returns>
  79. /// The line read from the socket, or <c>null</c> when the remote server has shutdown and all data has been received.
  80. /// </returns>
  81. private static string SocketReadLine(Socket socket, TimeSpan timeout, List<byte> buffer)
  82. {
  83. var data = new byte[1];
  84. var startPosition = buffer.Count;
  85. // Read data one byte at a time to find end of line and leave any unhandled information in the buffer
  86. // to be processed by subsequent invocations.
  87. while (true)
  88. {
  89. var bytesRead = SocketAbstraction.Read(socket, data, 0, data.Length, timeout);
  90. if (bytesRead == 0)
  91. {
  92. // The remote server shut down the socket.
  93. break;
  94. }
  95. var byteRead = data[0];
  96. buffer.Add(byteRead);
  97. // The null character MUST NOT be sent
  98. if (byteRead == Null)
  99. {
  100. throw new SshConnectionException(string.Format(CultureInfo.InvariantCulture,
  101. "The identification string contains a null character at position 0x{0:X8}:{1}{2}",
  102. buffer.Count,
  103. Environment.NewLine,
  104. PacketDump.Create(buffer.ToArray(), 2)));
  105. }
  106. if (byteRead == Session.LineFeed && buffer.Count > startPosition + 1 && buffer[buffer.Count - 2] == Session.CarriageReturn)
  107. {
  108. // Return current line without CRLF
  109. return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 2));
  110. }
  111. }
  112. return null;
  113. }
  114. }
  115. }