| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Buffers.Binary; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.IO; |
| | | 8 | | using System.Net.Sockets; |
| | | 9 | | using System.Text; |
| | | 10 | | using System.Threading; |
| | | 11 | | using System.Threading.Tasks; |
| | | 12 | | |
| | | 13 | | namespace System.Net.Http |
| | | 14 | | { |
| | | 15 | | internal static class SocksHelper |
| | | 16 | | { |
| | | 17 | | // Largest possible message size is 513 bytes (Socks5 username & password auth) |
| | | 18 | | private const int BufferSize = 513; |
| | | 19 | | private const int ProtocolVersion4 = 4; |
| | | 20 | | private const int ProtocolVersion5 = 5; |
| | | 21 | | private const int SubnegotiationVersion = 1; // Socks5 username & password auth |
| | | 22 | | private const byte METHOD_NO_AUTH = 0; |
| | | 23 | | private const byte METHOD_USERNAME_PASSWORD = 2; |
| | | 24 | | private const byte CMD_CONNECT = 1; |
| | | 25 | | private const byte ATYP_IPV4 = 1; |
| | | 26 | | private const byte ATYP_DOMAIN_NAME = 3; |
| | | 27 | | private const byte ATYP_IPV6 = 4; |
| | | 28 | | private const byte Socks5_Success = 0; |
| | | 29 | | private const byte Socks4_Success = 90; |
| | | 30 | | private const byte Socks4_AuthFailed = 93; |
| | | 31 | | |
| | | 32 | | public static async ValueTask EstablishSocksTunnelAsync(Stream stream, string host, int port, Uri proxyUri, ICre |
| | 0 | 33 | | { |
| | 0 | 34 | | using (cancellationToken.Register(s => ((Stream)s!).Dispose(), stream)) |
| | 0 | 35 | | { |
| | | 36 | | try |
| | 0 | 37 | | { |
| | 0 | 38 | | NetworkCredential? credentials = proxyCredentials?.GetCredential(proxyUri, proxyUri.Scheme); |
| | | 39 | | |
| | 0 | 40 | | if (string.Equals(proxyUri.Scheme, "socks5", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 41 | | { |
| | 0 | 42 | | await EstablishSocks5TunnelAsync(stream, host, port, credentials, async).ConfigureAwait(false); |
| | 0 | 43 | | } |
| | 0 | 44 | | else if (string.Equals(proxyUri.Scheme, "socks4a", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 45 | | { |
| | 0 | 46 | | await EstablishSocks4TunnelAsync(stream, isVersion4a: true, host, port, credentials, async, canc |
| | 0 | 47 | | } |
| | 0 | 48 | | else if (string.Equals(proxyUri.Scheme, "socks4", StringComparison.OrdinalIgnoreCase)) |
| | 0 | 49 | | { |
| | 0 | 50 | | await EstablishSocks4TunnelAsync(stream, isVersion4a: false, host, port, credentials, async, can |
| | 0 | 51 | | } |
| | | 52 | | else |
| | 0 | 53 | | { |
| | 0 | 54 | | Debug.Fail("Bad socks version."); |
| | | 55 | | } |
| | 0 | 56 | | } |
| | 0 | 57 | | catch |
| | 0 | 58 | | { |
| | 0 | 59 | | stream.Dispose(); |
| | 0 | 60 | | throw; |
| | | 61 | | } |
| | 0 | 62 | | } |
| | 0 | 63 | | } |
| | | 64 | | |
| | | 65 | | private static async ValueTask EstablishSocks5TunnelAsync(Stream stream, string host, int port, NetworkCredentia |
| | 0 | 66 | | { |
| | 0 | 67 | | byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferSize); |
| | | 68 | | try |
| | 0 | 69 | | { |
| | | 70 | | // https://tools.ietf.org/html/rfc1928 |
| | | 71 | | |
| | | 72 | | // +----+----------+----------+ |
| | | 73 | | // |VER | NMETHODS | METHODS | |
| | | 74 | | // +----+----------+----------+ |
| | | 75 | | // | 1 | 1 | 1 to 255 | |
| | | 76 | | // +----+----------+----------+ |
| | 0 | 77 | | buffer[0] = ProtocolVersion5; |
| | 0 | 78 | | if (credentials is null) |
| | 0 | 79 | | { |
| | 0 | 80 | | buffer[1] = 1; |
| | 0 | 81 | | buffer[2] = METHOD_NO_AUTH; |
| | 0 | 82 | | } |
| | | 83 | | else |
| | 0 | 84 | | { |
| | 0 | 85 | | buffer[1] = 2; |
| | 0 | 86 | | buffer[2] = METHOD_NO_AUTH; |
| | 0 | 87 | | buffer[3] = METHOD_USERNAME_PASSWORD; |
| | 0 | 88 | | } |
| | 0 | 89 | | await WriteAsync(stream, buffer.AsMemory(0, buffer[1] + 2), async).ConfigureAwait(false); |
| | | 90 | | |
| | | 91 | | // +----+--------+ |
| | | 92 | | // |VER | METHOD | |
| | | 93 | | // +----+--------+ |
| | | 94 | | // | 1 | 1 | |
| | | 95 | | // +----+--------+ |
| | 0 | 96 | | await ReadToFillAsync(stream, buffer.AsMemory(0, 2), async).ConfigureAwait(false); |
| | 0 | 97 | | VerifyProtocolVersion(ProtocolVersion5, buffer[0]); |
| | | 98 | | |
| | 0 | 99 | | switch (buffer[1]) |
| | | 100 | | { |
| | | 101 | | case METHOD_NO_AUTH: |
| | | 102 | | // continue |
| | 0 | 103 | | break; |
| | | 104 | | |
| | | 105 | | case METHOD_USERNAME_PASSWORD: |
| | 0 | 106 | | { |
| | | 107 | | // https://tools.ietf.org/html/rfc1929 |
| | 0 | 108 | | if (credentials is null) |
| | 0 | 109 | | { |
| | | 110 | | // If the server is behaving well, it shouldn't pick username and password auth |
| | | 111 | | // because we don't claim to support it when we don't have credentials. |
| | | 112 | | // Just being defensive here. |
| | 0 | 113 | | throw new SocksException(SR.net_socks_auth_required); |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | // +----+------+----------+------+----------+ |
| | | 117 | | // |VER | ULEN | UNAME | PLEN | PASSWD | |
| | | 118 | | // +----+------+----------+------+----------+ |
| | | 119 | | // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | |
| | | 120 | | // +----+------+----------+------+----------+ |
| | 0 | 121 | | buffer[0] = SubnegotiationVersion; |
| | 0 | 122 | | byte usernameLength = EncodeString(credentials.UserName, buffer.AsSpan(2), nameof(credential |
| | 0 | 123 | | buffer[1] = usernameLength; |
| | 0 | 124 | | byte passwordLength = EncodeString(credentials.Password, buffer.AsSpan(3 + usernameLength), |
| | 0 | 125 | | buffer[2 + usernameLength] = passwordLength; |
| | 0 | 126 | | await WriteAsync(stream, buffer.AsMemory(0, 3 + usernameLength + passwordLength), async).Con |
| | | 127 | | |
| | | 128 | | // +----+--------+ |
| | | 129 | | // |VER | STATUS | |
| | | 130 | | // +----+--------+ |
| | | 131 | | // | 1 | 1 | |
| | | 132 | | // +----+--------+ |
| | 0 | 133 | | await ReadToFillAsync(stream, buffer.AsMemory(0, 2), async).ConfigureAwait(false); |
| | 0 | 134 | | if (buffer[0] != SubnegotiationVersion || buffer[1] != Socks5_Success) |
| | 0 | 135 | | { |
| | 0 | 136 | | throw new SocksException(SR.net_socks_auth_failed); |
| | | 137 | | } |
| | 0 | 138 | | break; |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | default: |
| | 0 | 142 | | throw new SocksException(SR.net_socks_no_auth_method); |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | |
| | | 146 | | // +----+-----+-------+------+----------+----------+ |
| | | 147 | | // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | |
| | | 148 | | // +----+-----+-------+------+----------+----------+ |
| | | 149 | | // | 1 | 1 | X'00' | 1 | Variable | 2 | |
| | | 150 | | // +----+-----+-------+------+----------+----------+ |
| | 0 | 151 | | buffer[0] = ProtocolVersion5; |
| | 0 | 152 | | buffer[1] = CMD_CONNECT; |
| | 0 | 153 | | buffer[2] = 0; |
| | | 154 | | int addressLength; |
| | | 155 | | |
| | 0 | 156 | | if (IPAddress.TryParse(host, out IPAddress? hostIP)) |
| | 0 | 157 | | { |
| | 0 | 158 | | if (hostIP.AddressFamily == AddressFamily.InterNetwork) |
| | 0 | 159 | | { |
| | 0 | 160 | | buffer[3] = ATYP_IPV4; |
| | 0 | 161 | | hostIP.TryWriteBytes(buffer.AsSpan(4), out int bytesWritten); |
| | 0 | 162 | | Debug.Assert(bytesWritten == 4); |
| | 0 | 163 | | addressLength = 4; |
| | 0 | 164 | | } |
| | | 165 | | else |
| | 0 | 166 | | { |
| | 0 | 167 | | Debug.Assert(hostIP.AddressFamily == AddressFamily.InterNetworkV6); |
| | 0 | 168 | | buffer[3] = ATYP_IPV6; |
| | 0 | 169 | | hostIP.TryWriteBytes(buffer.AsSpan(4), out int bytesWritten); |
| | 0 | 170 | | Debug.Assert(bytesWritten == 16); |
| | 0 | 171 | | addressLength = 16; |
| | 0 | 172 | | } |
| | 0 | 173 | | } |
| | | 174 | | else |
| | 0 | 175 | | { |
| | 0 | 176 | | buffer[3] = ATYP_DOMAIN_NAME; |
| | 0 | 177 | | byte hostLength = EncodeString(host, buffer.AsSpan(5), nameof(host)); |
| | 0 | 178 | | buffer[4] = hostLength; |
| | 0 | 179 | | addressLength = hostLength + 1; |
| | 0 | 180 | | } |
| | | 181 | | |
| | 0 | 182 | | BinaryPrimitives.WriteUInt16BigEndian(buffer.AsSpan(addressLength + 4), (ushort)port); |
| | | 183 | | |
| | 0 | 184 | | await WriteAsync(stream, buffer.AsMemory(0, addressLength + 6), async).ConfigureAwait(false); |
| | | 185 | | |
| | | 186 | | // +----+-----+-------+------+----------+----------+ |
| | | 187 | | // |VER | REP | RSV | ATYP | DST.ADDR | DST.PORT | |
| | | 188 | | // +----+-----+-------+------+----------+----------+ |
| | | 189 | | // | 1 | 1 | X'00' | 1 | Variable | 2 | |
| | | 190 | | // +----+-----+-------+------+----------+----------+ |
| | 0 | 191 | | await ReadToFillAsync(stream, buffer.AsMemory(0, 5), async).ConfigureAwait(false); |
| | 0 | 192 | | VerifyProtocolVersion(ProtocolVersion5, buffer[0]); |
| | 0 | 193 | | if (buffer[1] != Socks5_Success) |
| | 0 | 194 | | { |
| | 0 | 195 | | throw new SocksException(SR.Format(SR.net_socks_connection_failed, buffer[1].ToString("X2"))); |
| | | 196 | | } |
| | 0 | 197 | | int bytesToSkip = buffer[3] switch |
| | 0 | 198 | | { |
| | 0 | 199 | | ATYP_IPV4 => 5, |
| | 0 | 200 | | ATYP_IPV6 => 17, |
| | 0 | 201 | | ATYP_DOMAIN_NAME => buffer[4] + 2, |
| | 0 | 202 | | _ => throw new SocksException(SR.net_socks_bad_address_type) |
| | 0 | 203 | | }; |
| | 0 | 204 | | await ReadToFillAsync(stream, buffer.AsMemory(0, bytesToSkip), async).ConfigureAwait(false); |
| | | 205 | | // response address not used |
| | 0 | 206 | | } |
| | | 207 | | finally |
| | 0 | 208 | | { |
| | 0 | 209 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 0 | 210 | | } |
| | 0 | 211 | | } |
| | | 212 | | |
| | | 213 | | private static async ValueTask EstablishSocks4TunnelAsync(Stream stream, bool isVersion4a, string host, int port |
| | 0 | 214 | | { |
| | 0 | 215 | | byte[] buffer = ArrayPool<byte>.Shared.Rent(BufferSize); |
| | | 216 | | try |
| | 0 | 217 | | { |
| | | 218 | | // https://www.openssh.com/txt/socks4.protocol |
| | | 219 | | |
| | | 220 | | // +----+----+----+----+----+----+----+----+----+----+....+----+ |
| | | 221 | | // | VN | CD | DSTPORT | DSTIP | USERID |NULL| |
| | | 222 | | // +----+----+----+----+----+----+----+----+----+----+....+----+ |
| | | 223 | | // 1 1 2 4 variable 1 |
| | 0 | 224 | | buffer[0] = ProtocolVersion4; |
| | 0 | 225 | | buffer[1] = CMD_CONNECT; |
| | | 226 | | |
| | 0 | 227 | | BinaryPrimitives.WriteUInt16BigEndian(buffer.AsSpan(2), (ushort)port); |
| | | 228 | | |
| | 0 | 229 | | IPAddress? ipv4Address = null; |
| | 0 | 230 | | if (IPAddress.TryParse(host, out IPAddress? hostIP)) |
| | 0 | 231 | | { |
| | 0 | 232 | | if (hostIP.AddressFamily == AddressFamily.InterNetwork) |
| | 0 | 233 | | { |
| | 0 | 234 | | ipv4Address = hostIP; |
| | 0 | 235 | | } |
| | 0 | 236 | | else if (hostIP.IsIPv4MappedToIPv6) |
| | 0 | 237 | | { |
| | 0 | 238 | | ipv4Address = hostIP.MapToIPv4(); |
| | 0 | 239 | | } |
| | | 240 | | else |
| | 0 | 241 | | { |
| | 0 | 242 | | throw new SocksException(SR.net_socks_ipv6_notsupported); |
| | | 243 | | } |
| | 0 | 244 | | } |
| | 0 | 245 | | else if (!isVersion4a) |
| | 0 | 246 | | { |
| | | 247 | | // Socks4 does not support domain names - try to resolve it here |
| | | 248 | | IPAddress[] addresses; |
| | | 249 | | try |
| | 0 | 250 | | { |
| | 0 | 251 | | addresses = async |
| | 0 | 252 | | ? await Dns.GetHostAddressesAsync(host, AddressFamily.InterNetwork, cancellationToken).Confi |
| | 0 | 253 | | : Dns.GetHostAddresses(host, AddressFamily.InterNetwork); |
| | 0 | 254 | | } |
| | 0 | 255 | | catch (Exception ex) |
| | 0 | 256 | | { |
| | 0 | 257 | | throw new SocksException(SR.net_socks_no_ipv4_address, ex); |
| | | 258 | | } |
| | | 259 | | |
| | 0 | 260 | | if (addresses.Length == 0) |
| | 0 | 261 | | { |
| | 0 | 262 | | throw new SocksException(SR.net_socks_no_ipv4_address); |
| | | 263 | | } |
| | | 264 | | |
| | 0 | 265 | | ipv4Address = addresses[0]; |
| | 0 | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | if (ipv4Address is null) |
| | 0 | 269 | | { |
| | 0 | 270 | | Debug.Assert(isVersion4a); |
| | 0 | 271 | | buffer[4] = 0; |
| | 0 | 272 | | buffer[5] = 0; |
| | 0 | 273 | | buffer[6] = 0; |
| | 0 | 274 | | buffer[7] = 255; |
| | 0 | 275 | | } |
| | | 276 | | else |
| | 0 | 277 | | { |
| | 0 | 278 | | ipv4Address.TryWriteBytes(buffer.AsSpan(4), out int bytesWritten); |
| | 0 | 279 | | Debug.Assert(bytesWritten == 4); |
| | 0 | 280 | | } |
| | | 281 | | |
| | 0 | 282 | | byte usernameLength = EncodeString(credentials?.UserName, buffer.AsSpan(8), nameof(credentials.UserName) |
| | 0 | 283 | | buffer[8 + usernameLength] = 0; |
| | 0 | 284 | | int totalLength = 9 + usernameLength; |
| | | 285 | | |
| | 0 | 286 | | if (ipv4Address is null) |
| | 0 | 287 | | { |
| | | 288 | | // https://www.openssh.com/txt/socks4a.protocol |
| | 0 | 289 | | byte hostLength = EncodeString(host, buffer.AsSpan(totalLength), nameof(host)); |
| | 0 | 290 | | buffer[totalLength + hostLength] = 0; |
| | 0 | 291 | | totalLength += hostLength + 1; |
| | 0 | 292 | | } |
| | | 293 | | |
| | 0 | 294 | | await WriteAsync(stream, buffer.AsMemory(0, totalLength), async).ConfigureAwait(false); |
| | | 295 | | |
| | | 296 | | // +----+----+----+----+----+----+----+----+ |
| | | 297 | | // | VN | CD | DSTPORT | DSTIP | |
| | | 298 | | // +----+----+----+----+----+----+----+----+ |
| | | 299 | | // 1 1 2 4 |
| | 0 | 300 | | await ReadToFillAsync(stream, buffer.AsMemory(0, 8), async).ConfigureAwait(false); |
| | | 301 | | |
| | 0 | 302 | | switch (buffer[1]) |
| | | 303 | | { |
| | | 304 | | case Socks4_Success: |
| | | 305 | | // Nothing to do |
| | 0 | 306 | | break; |
| | | 307 | | case Socks4_AuthFailed: |
| | 0 | 308 | | throw new SocksException(SR.net_socks_auth_failed); |
| | | 309 | | default: |
| | 0 | 310 | | throw new SocksException(SR.Format(SR.net_socks_connection_failed, buffer[1].ToString("X2"))); |
| | | 311 | | } |
| | | 312 | | // response address not used |
| | 0 | 313 | | } |
| | | 314 | | finally |
| | 0 | 315 | | { |
| | 0 | 316 | | ArrayPool<byte>.Shared.Return(buffer); |
| | 0 | 317 | | } |
| | 0 | 318 | | } |
| | | 319 | | |
| | | 320 | | private static byte EncodeString(ReadOnlySpan<char> chars, Span<byte> buffer, string parameterName) |
| | 0 | 321 | | { |
| | | 322 | | try |
| | 0 | 323 | | { |
| | 0 | 324 | | return checked((byte)Encoding.UTF8.GetBytes(chars, buffer)); |
| | | 325 | | } |
| | 0 | 326 | | catch |
| | 0 | 327 | | { |
| | 0 | 328 | | Debug.Assert(Encoding.UTF8.GetByteCount(chars) > 255); |
| | 0 | 329 | | throw new SocksException(SR.Format(SR.net_socks_string_too_long, parameterName)); |
| | | 330 | | } |
| | 0 | 331 | | } |
| | | 332 | | |
| | | 333 | | private static void VerifyProtocolVersion(byte expected, byte version) |
| | 0 | 334 | | { |
| | 0 | 335 | | if (expected != version) |
| | 0 | 336 | | { |
| | 0 | 337 | | throw new SocksException(SR.Format(SR.net_socks_unexpected_version, expected, version)); |
| | | 338 | | } |
| | 0 | 339 | | } |
| | | 340 | | |
| | | 341 | | private static ValueTask WriteAsync(Stream stream, Memory<byte> buffer, bool async) |
| | 0 | 342 | | { |
| | 0 | 343 | | if (async) |
| | 0 | 344 | | { |
| | 0 | 345 | | return stream.WriteAsync(buffer); |
| | | 346 | | } |
| | | 347 | | else |
| | 0 | 348 | | { |
| | 0 | 349 | | stream.Write(buffer.Span); |
| | 0 | 350 | | return default; |
| | | 351 | | } |
| | 0 | 352 | | } |
| | | 353 | | |
| | | 354 | | private static async ValueTask ReadToFillAsync(Stream stream, Memory<byte> buffer, bool async) |
| | 0 | 355 | | { |
| | 0 | 356 | | int bytesRead = async |
| | 0 | 357 | | ? await stream.ReadAtLeastAsync(buffer, buffer.Length, throwOnEndOfStream: false).ConfigureAwait(false) |
| | 0 | 358 | | : stream.ReadAtLeast(buffer.Span, buffer.Length, throwOnEndOfStream: false); |
| | | 359 | | |
| | 0 | 360 | | if (bytesRead < buffer.Length) |
| | 0 | 361 | | { |
| | 0 | 362 | | throw new IOException(SR.net_http_invalid_response_premature_eof); |
| | | 363 | | } |
| | 0 | 364 | | } |
| | | 365 | | } |
| | | 366 | | } |