| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Net.Sockets; |
| | | 5 | | using System.Text; |
| | | 6 | | using System.Text.RegularExpressions; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | |
| | | 10 | | using Renci.SshNet.Abstractions; |
| | | 11 | | using Renci.SshNet.Common; |
| | | 12 | | using Renci.SshNet.Messages.Transport; |
| | | 13 | | |
| | | 14 | | namespace Renci.SshNet.Connection |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Handles the SSH protocol version exchange. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <remarks> |
| | | 20 | | /// https://tools.ietf.org/html/rfc4253#section-4.2. |
| | | 21 | | /// </remarks> |
| | | 22 | | internal sealed class ProtocolVersionExchange : IProtocolVersionExchange |
| | | 23 | | { |
| | | 24 | | private const byte Null = 0x00; |
| | | 25 | | |
| | 4 | 26 | | private static readonly Regex ServerVersionRe = new Regex("^SSH-(?<protoversion>[^-]+)-(?<softwareversion>.+?)([ |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Performs the SSH protocol version exchange. |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="clientVersion">The identification string of the SSH client.</param> |
| | | 32 | | /// <param name="socket">A <see cref="Socket"/> connected to the server.</param> |
| | | 33 | | /// <param name="timeout">The maximum time to wait for the server to respond.</param> |
| | | 34 | | /// <returns> |
| | | 35 | | /// The SSH identification of the server. |
| | | 36 | | /// </returns> |
| | | 37 | | public SshIdentification Start(string clientVersion, Socket socket, TimeSpan timeout) |
| | 1272 | 38 | | { |
| | | 39 | | // Immediately send the identification string since the spec states both sides MUST send an identification s |
| | | 40 | | // when the connection has been established |
| | 1272 | 41 | | SocketAbstraction.Send(socket, Encoding.UTF8.GetBytes(clientVersion + "\x0D\x0A")); |
| | | 42 | | |
| | 1272 | 43 | | var bytesReceived = new List<byte>(); |
| | | 44 | | |
| | | 45 | | // Get server version from the server, |
| | | 46 | | // ignore text lines which are sent before if any |
| | 1374 | 47 | | while (true) |
| | 1374 | 48 | | { |
| | 1374 | 49 | | var line = SocketReadLine(socket, timeout, bytesReceived); |
| | 1353 | 50 | | if (line is null) |
| | 18 | 51 | | { |
| | 18 | 52 | | if (bytesReceived.Count == 0) |
| | 9 | 53 | | { |
| | 9 | 54 | | throw CreateConnectionLostException(); |
| | | 55 | | } |
| | | 56 | | |
| | 9 | 57 | | throw CreateServerResponseDoesNotContainIdentification(bytesReceived); |
| | | 58 | | } |
| | | 59 | | |
| | 1335 | 60 | | var identificationMatch = ServerVersionRe.Match(line); |
| | 1335 | 61 | | if (identificationMatch.Success) |
| | 1233 | 62 | | { |
| | 1233 | 63 | | return new SshIdentification(GetGroupValue(identificationMatch, "protoversion"), |
| | 1233 | 64 | | GetGroupValue(identificationMatch, "softwareversion"), |
| | 1233 | 65 | | GetGroupValue(identificationMatch, "comments")); |
| | | 66 | | } |
| | 102 | 67 | | } |
| | 1233 | 68 | | } |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Asynchronously performs the SSH protocol version exchange. |
| | | 72 | | /// </summary> |
| | | 73 | | /// <param name="clientVersion">The identification string of the SSH client.</param> |
| | | 74 | | /// <param name="socket">A <see cref="Socket"/> connected to the server.</param> |
| | | 75 | | /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> |
| | | 76 | | /// <returns> |
| | | 77 | | /// A task that represents the SSH protocol version exchange. The value of its |
| | | 78 | | /// <see cref="Task{Task}.Result"/> contains the SSH identification of the server. |
| | | 79 | | /// </returns> |
| | | 80 | | public async Task<SshIdentification> StartAsync(string clientVersion, Socket socket, CancellationToken cancellat |
| | 2 | 81 | | { |
| | | 82 | | // Immediately send the identification string since the spec states both sides MUST send an identification s |
| | | 83 | | // when the connection has been established |
| | 2 | 84 | | SocketAbstraction.Send(socket, Encoding.UTF8.GetBytes(clientVersion + "\x0D\x0A")); |
| | | 85 | | |
| | 2 | 86 | | var bytesReceived = new List<byte>(); |
| | | 87 | | |
| | | 88 | | // Get server version from the server, |
| | | 89 | | // ignore text lines which are sent before if any |
| | 2 | 90 | | while (true) |
| | 2 | 91 | | { |
| | 2 | 92 | | var line = await SocketReadLineAsync(socket, bytesReceived, cancellationToken).ConfigureAwait(false); |
| | 2 | 93 | | if (line is null) |
| | 0 | 94 | | { |
| | 0 | 95 | | if (bytesReceived.Count == 0) |
| | 0 | 96 | | { |
| | 0 | 97 | | throw CreateConnectionLostException(); |
| | | 98 | | } |
| | | 99 | | |
| | 0 | 100 | | throw CreateServerResponseDoesNotContainIdentification(bytesReceived); |
| | | 101 | | } |
| | | 102 | | |
| | 2 | 103 | | var identificationMatch = ServerVersionRe.Match(line); |
| | 2 | 104 | | if (identificationMatch.Success) |
| | 2 | 105 | | { |
| | 2 | 106 | | return new SshIdentification(GetGroupValue(identificationMatch, "protoversion"), |
| | 2 | 107 | | GetGroupValue(identificationMatch, "softwareversion"), |
| | 2 | 108 | | GetGroupValue(identificationMatch, "comments")); |
| | | 109 | | } |
| | 0 | 110 | | } |
| | 2 | 111 | | } |
| | | 112 | | |
| | | 113 | | private static string GetGroupValue(Match match, string groupName) |
| | 3705 | 114 | | { |
| | 3705 | 115 | | var commentsGroup = match.Groups[groupName]; |
| | 3705 | 116 | | if (commentsGroup.Success) |
| | 2482 | 117 | | { |
| | 2482 | 118 | | return commentsGroup.Value; |
| | | 119 | | } |
| | | 120 | | |
| | 1223 | 121 | | return null; |
| | 3705 | 122 | | } |
| | | 123 | | |
| | | 124 | | /// <summary> |
| | | 125 | | /// Performs a blocking read on the socket until a line is read. |
| | | 126 | | /// </summary> |
| | | 127 | | /// <param name="socket">The <see cref="Socket"/> to read from.</param> |
| | | 128 | | /// <param name="timeout">A <see cref="TimeSpan"/> that represents the time to wait until a line is read.</param |
| | | 129 | | /// <param name="buffer">A <see cref="List{Byte}"/> to which read bytes will be added.</param> |
| | | 130 | | /// <exception cref="SshOperationTimeoutException">The read has timed-out.</exception> |
| | | 131 | | /// <exception cref="SocketException">An error occurred when trying to access the socket.</exception> |
| | | 132 | | /// <returns> |
| | | 133 | | /// The line read from the socket, or <see langword="null"/> when the remote server has shutdown and all data ha |
| | | 134 | | /// </returns> |
| | | 135 | | private static string SocketReadLine(Socket socket, TimeSpan timeout, List<byte> buffer) |
| | 1374 | 136 | | { |
| | 1374 | 137 | | var data = new byte[1]; |
| | | 138 | | |
| | 1374 | 139 | | var startPosition = buffer.Count; |
| | | 140 | | |
| | | 141 | | // Read data one byte at a time to find end of line and leave any unhandled information in the buffer |
| | | 142 | | // to be processed by subsequent invocations. |
| | 27411 | 143 | | while (true) |
| | 27411 | 144 | | { |
| | 27411 | 145 | | var bytesRead = SocketAbstraction.Read(socket, data, 0, data.Length, timeout); |
| | 27402 | 146 | | if (bytesRead == 0) |
| | 18 | 147 | | { |
| | | 148 | | // The remote server shut down the socket. |
| | 18 | 149 | | break; |
| | | 150 | | } |
| | | 151 | | |
| | 27384 | 152 | | var byteRead = data[0]; |
| | 27384 | 153 | | buffer.Add(byteRead); |
| | | 154 | | |
| | | 155 | | // The null character MUST NOT be sent |
| | 27384 | 156 | | if (byteRead is Null) |
| | 12 | 157 | | { |
| | 12 | 158 | | throw CreateServerResponseContainsNullCharacterException(buffer); |
| | | 159 | | } |
| | | 160 | | |
| | 27372 | 161 | | if (byteRead == Session.LineFeed) |
| | 1335 | 162 | | { |
| | 1335 | 163 | | if (buffer.Count > startPosition + 1 && buffer[buffer.Count - 2] == Session.CarriageReturn) |
| | 1299 | 164 | | { |
| | | 165 | | // Return current line without CRLF |
| | 1299 | 166 | | return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | // Even though RFC4253 clearly indicates that the identification string should be terminated |
| | | 170 | | // by a CR LF we also support banners and identification strings that are terminated by a LF |
| | | 171 | | |
| | | 172 | | // Return current line without LF |
| | 36 | 173 | | return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1)); |
| | | 174 | | } |
| | 26037 | 175 | | } |
| | | 176 | | |
| | 18 | 177 | | return null; |
| | 1353 | 178 | | } |
| | | 179 | | |
| | | 180 | | private static async Task<string> SocketReadLineAsync(Socket socket, List<byte> buffer, CancellationToken cancel |
| | 2 | 181 | | { |
| | 2 | 182 | | var data = new byte[1]; |
| | | 183 | | |
| | 2 | 184 | | var startPosition = buffer.Count; |
| | | 185 | | |
| | | 186 | | // Read data one byte at a time to find end of line and leave any unhandled information in the buffer |
| | | 187 | | // to be processed by subsequent invocations. |
| | 42 | 188 | | while (true) |
| | 42 | 189 | | { |
| | 42 | 190 | | var bytesRead = await SocketAbstraction.ReadAsync(socket, data, 0, data.Length, cancellationToken).Confi |
| | 42 | 191 | | if (bytesRead == 0) |
| | 0 | 192 | | { |
| | 0 | 193 | | throw new SshConnectionException("The connection was closed by the remote host."); |
| | | 194 | | } |
| | | 195 | | |
| | 42 | 196 | | var byteRead = data[0]; |
| | 42 | 197 | | buffer.Add(byteRead); |
| | | 198 | | |
| | | 199 | | // The null character MUST NOT be sent |
| | 42 | 200 | | if (byteRead is Null) |
| | 0 | 201 | | { |
| | 0 | 202 | | throw CreateServerResponseContainsNullCharacterException(buffer); |
| | | 203 | | } |
| | | 204 | | |
| | 42 | 205 | | if (byteRead == Session.LineFeed) |
| | 2 | 206 | | { |
| | 2 | 207 | | if (buffer.Count > startPosition + 1 && buffer[buffer.Count - 2] == Session.CarriageReturn) |
| | 2 | 208 | | { |
| | | 209 | | // Return current line without CRLF |
| | 2 | 210 | | return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + |
| | | 211 | | } |
| | | 212 | | |
| | | 213 | | // Even though RFC4253 clearly indicates that the identification string should be terminated |
| | | 214 | | // by a CR LF we also support banners and identification strings that are terminated by a LF |
| | | 215 | | |
| | | 216 | | // Return current line without LF |
| | 0 | 217 | | return Encoding.UTF8.GetString(buffer.ToArray(), startPosition, buffer.Count - (startPosition + 1)); |
| | | 218 | | } |
| | 40 | 219 | | } |
| | 2 | 220 | | } |
| | | 221 | | |
| | | 222 | | private static SshConnectionException CreateConnectionLostException() |
| | 9 | 223 | | { |
| | | 224 | | #pragma warning disable SA1118 // Parameter should not span multiple lines |
| | 9 | 225 | | var message = string.Format(CultureInfo.InvariantCulture, |
| | 9 | 226 | | "The server response does not contain an SSH identification string.{0}" + |
| | 9 | 227 | | "The connection to the remote server was closed before any data was received.{0} |
| | 9 | 228 | | "More information on the Protocol Version Exchange is available here:{0}" + |
| | 9 | 229 | | "https://tools.ietf.org/html/rfc4253#section-4.2", |
| | 9 | 230 | | Environment.NewLine); |
| | | 231 | | #pragma warning restore SA1118 // Parameter should not span multiple lines |
| | | 232 | | |
| | 9 | 233 | | return new SshConnectionException(message, DisconnectReason.ConnectionLost); |
| | 9 | 234 | | } |
| | | 235 | | |
| | | 236 | | private static SshConnectionException CreateServerResponseContainsNullCharacterException(List<byte> buffer) |
| | 12 | 237 | | { |
| | | 238 | | #pragma warning disable SA1118 // Parameter should not span multiple lines |
| | 12 | 239 | | var message = string.Format(CultureInfo.InvariantCulture, |
| | 12 | 240 | | "The server response contains a null character at position 0x{0:X8}:{1}{1}{2}{1} |
| | 12 | 241 | | "A server must not send a null character before the Protocol Version Exchange is |
| | 12 | 242 | | "More information is available here:{1}" + |
| | 12 | 243 | | "https://tools.ietf.org/html/rfc4253#section-4.2", |
| | 12 | 244 | | buffer.Count, |
| | 12 | 245 | | Environment.NewLine, |
| | 12 | 246 | | PacketDump.Create(buffer.ToArray(), 2)); |
| | | 247 | | #pragma warning restore SA1118 // Parameter should not span multiple lines |
| | | 248 | | |
| | 12 | 249 | | throw new SshConnectionException(message); |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | private static SshConnectionException CreateServerResponseDoesNotContainIdentification(List<byte> bytesReceived) |
| | 9 | 253 | | { |
| | | 254 | | #pragma warning disable SA1118 // Parameter should not span multiple lines |
| | 9 | 255 | | var message = string.Format(CultureInfo.InvariantCulture, |
| | 9 | 256 | | "The server response does not contain an SSH identification string:{0}{0}{1}{0}{ |
| | 9 | 257 | | "More information on the Protocol Version Exchange is available here:{0}" + |
| | 9 | 258 | | "https://tools.ietf.org/html/rfc4253#section-4.2", |
| | 9 | 259 | | Environment.NewLine, |
| | 9 | 260 | | PacketDump.Create(bytesReceived, 2)); |
| | | 261 | | #pragma warning restore SA1118 // Parameter should not span multiple lines |
| | | 262 | | |
| | 9 | 263 | | throw new SshConnectionException(message, DisconnectReason.ProtocolError); |
| | | 264 | | } |
| | | 265 | | } |
| | | 266 | | } |