| | | 1 | | using System; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Linq; |
| | | 4 | | using System.Net; |
| | | 5 | | using System.Net.Sockets; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | using Renci.SshNet.Abstractions; |
| | | 10 | | using Renci.SshNet.Channels; |
| | | 11 | | using Renci.SshNet.Common; |
| | | 12 | | |
| | | 13 | | namespace Renci.SshNet |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Provides functionality for forwarding connections from the client to destination servers via the SSH server, |
| | | 17 | | /// also known as dynamic port forwarding. |
| | | 18 | | /// </summary> |
| | | 19 | | public class ForwardedPortDynamic : ForwardedPort |
| | | 20 | | { |
| | | 21 | | private ForwardedPortStatus _status; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Holds a value indicating whether the current instance is disposed. |
| | | 25 | | /// </summary> |
| | | 26 | | /// <value> |
| | | 27 | | /// <see langword="true"/> if the current instance is disposed; otherwise, <see langword="false"/>. |
| | | 28 | | /// </value> |
| | | 29 | | private bool _isDisposed; |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Gets the bound host. |
| | | 33 | | /// </summary> |
| | 410 | 34 | | public string BoundHost { get; } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Gets the bound port. |
| | | 38 | | /// </summary> |
| | 228 | 39 | | public uint BoundPort { get; } |
| | | 40 | | |
| | | 41 | | private Socket _listener; |
| | | 42 | | private CountdownEvent _pendingChannelCountdown; |
| | | 43 | | |
| | | 44 | | /// <summary> |
| | | 45 | | /// Gets a value indicating whether port forwarding is started. |
| | | 46 | | /// </summary> |
| | | 47 | | /// <value> |
| | | 48 | | /// <see langword="true"/> if port forwarding is started; otherwise, <see langword="false"/>. |
| | | 49 | | /// </value> |
| | | 50 | | public override bool IsStarted |
| | | 51 | | { |
| | 3075 | 52 | | get { return _status == ForwardedPortStatus.Started; } |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// Initializes a new instance of the <see cref="ForwardedPortDynamic"/> class. |
| | | 57 | | /// </summary> |
| | | 58 | | /// <param name="port">The port.</param> |
| | | 59 | | public ForwardedPortDynamic(uint port) |
| | 42 | 60 | | : this(string.Empty, port) |
| | 42 | 61 | | { |
| | 42 | 62 | | } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Initializes a new instance of the <see cref="ForwardedPortDynamic"/> class. |
| | | 66 | | /// </summary> |
| | | 67 | | /// <param name="host">The host.</param> |
| | | 68 | | /// <param name="port">The port.</param> |
| | 296 | 69 | | public ForwardedPortDynamic(string host, uint port) |
| | 296 | 70 | | { |
| | 296 | 71 | | BoundHost = host; |
| | 296 | 72 | | BoundPort = port; |
| | 296 | 73 | | _status = ForwardedPortStatus.Stopped; |
| | 296 | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary> |
| | | 77 | | /// Starts local port forwarding. |
| | | 78 | | /// </summary> |
| | | 79 | | protected override void StartPort() |
| | 222 | 80 | | { |
| | 222 | 81 | | if (!ForwardedPortStatus.ToStarting(ref _status)) |
| | 0 | 82 | | { |
| | 0 | 83 | | return; |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | try |
| | 222 | 87 | | { |
| | 222 | 88 | | InternalStart(); |
| | 222 | 89 | | } |
| | 0 | 90 | | catch (Exception) |
| | 0 | 91 | | { |
| | 0 | 92 | | _status = ForwardedPortStatus.Stopped; |
| | 0 | 93 | | throw; |
| | | 94 | | } |
| | 222 | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// Stops local port forwarding, and waits for the specified timeout until all pending |
| | | 99 | | /// requests are processed. |
| | | 100 | | /// </summary> |
| | | 101 | | /// <param name="timeout">The maximum amount of time to wait for pending requests to finish processing.</param> |
| | | 102 | | protected override void StopPort(TimeSpan timeout) |
| | 337 | 103 | | { |
| | 337 | 104 | | if (!ForwardedPortStatus.ToStopping(ref _status)) |
| | 115 | 105 | | { |
| | 115 | 106 | | return; |
| | | 107 | | } |
| | | 108 | | |
| | | 109 | | // signal existing channels that the port is closing |
| | 222 | 110 | | base.StopPort(timeout); |
| | | 111 | | |
| | | 112 | | // prevent new requests from getting processed |
| | 222 | 113 | | StopListener(); |
| | | 114 | | |
| | | 115 | | // wait for open channels to close |
| | 222 | 116 | | InternalStop(timeout); |
| | | 117 | | |
| | | 118 | | // mark port stopped |
| | 222 | 119 | | _status = ForwardedPortStatus.Stopped; |
| | 337 | 120 | | } |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Ensures the current instance is not disposed. |
| | | 124 | | /// </summary> |
| | | 125 | | /// <exception cref="ObjectDisposedException">The current instance is disposed.</exception> |
| | | 126 | | protected override void CheckDisposed() |
| | 276 | 127 | | { |
| | | 128 | | #if NET7_0_OR_GREATER |
| | 186 | 129 | | ObjectDisposedException.ThrowIf(_isDisposed, this); |
| | | 130 | | #else |
| | 90 | 131 | | if (_isDisposed) |
| | 3 | 132 | | { |
| | 3 | 133 | | throw new ObjectDisposedException(GetType().FullName); |
| | | 134 | | } |
| | | 135 | | #endif // NET7_0_OR_GREATER |
| | 267 | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 140 | | /// </summary> |
| | | 141 | | /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langwor |
| | | 142 | | protected override void Dispose(bool disposing) |
| | 385 | 143 | | { |
| | 385 | 144 | | if (_isDisposed) |
| | 101 | 145 | | { |
| | 101 | 146 | | return; |
| | | 147 | | } |
| | | 148 | | |
| | 284 | 149 | | base.Dispose(disposing); |
| | | 150 | | |
| | 284 | 151 | | InternalDispose(disposing); |
| | 284 | 152 | | _isDisposed = true; |
| | 385 | 153 | | } |
| | | 154 | | |
| | | 155 | | private void InternalStart() |
| | 222 | 156 | | { |
| | 222 | 157 | | InitializePendingChannelCountdown(); |
| | | 158 | | |
| | 222 | 159 | | var ip = IPAddress.Any; |
| | 222 | 160 | | if (!string.IsNullOrEmpty(BoundHost)) |
| | 182 | 161 | | { |
| | 182 | 162 | | ip = DnsAbstraction.GetHostAddresses(BoundHost)[0]; |
| | 182 | 163 | | } |
| | | 164 | | |
| | 222 | 165 | | var ep = new IPEndPoint(ip, (int) BoundPort); |
| | | 166 | | |
| | 222 | 167 | | _listener = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; |
| | 222 | 168 | | _listener.Bind(ep); |
| | 222 | 169 | | _listener.Listen(5); |
| | | 170 | | |
| | 222 | 171 | | Session.ErrorOccured += Session_ErrorOccured; |
| | 222 | 172 | | Session.Disconnected += Session_Disconnected; |
| | | 173 | | |
| | | 174 | | // consider port started when we're listening for inbound connections |
| | 222 | 175 | | _status = ForwardedPortStatus.Started; |
| | | 176 | | |
| | 222 | 177 | | StartAccept(e: null); |
| | 222 | 178 | | } |
| | | 179 | | |
| | | 180 | | private void StartAccept(SocketAsyncEventArgs e) |
| | 375 | 181 | | { |
| | 375 | 182 | | if (e is null) |
| | 222 | 183 | | { |
| | | 184 | | #pragma warning disable CA2000 // Dispose objects before losing scope |
| | 222 | 185 | | e = new SocketAsyncEventArgs(); |
| | | 186 | | #pragma warning restore CA2000 // Dispose objects before losing scope |
| | 222 | 187 | | e.Completed += AcceptCompleted; |
| | 222 | 188 | | } |
| | | 189 | | else |
| | 153 | 190 | | { |
| | | 191 | | // clear the socket as we're reusing the context object |
| | 153 | 192 | | e.AcceptSocket = null; |
| | 153 | 193 | | } |
| | | 194 | | |
| | | 195 | | // only accept new connections while we are started |
| | 375 | 196 | | if (IsStarted) |
| | 374 | 197 | | { |
| | | 198 | | try |
| | 374 | 199 | | { |
| | 374 | 200 | | if (!_listener.AcceptAsync(e)) |
| | 0 | 201 | | { |
| | 0 | 202 | | AcceptCompleted(sender: null, e); |
| | 0 | 203 | | } |
| | 374 | 204 | | } |
| | 0 | 205 | | catch (ObjectDisposedException) |
| | 0 | 206 | | { |
| | 0 | 207 | | if (_status == ForwardedPortStatus.Stopping || _status == ForwardedPortStatus.Stopped) |
| | 0 | 208 | | { |
| | | 209 | | // ignore ObjectDisposedException while stopping or stopped |
| | 0 | 210 | | return; |
| | | 211 | | } |
| | | 212 | | |
| | 0 | 213 | | throw; |
| | | 214 | | } |
| | 374 | 215 | | } |
| | 375 | 216 | | } |
| | | 217 | | |
| | | 218 | | private void AcceptCompleted(object sender, SocketAsyncEventArgs e) |
| | 374 | 219 | | { |
| | 374 | 220 | | if (e.SocketError is SocketError.OperationAborted or SocketError.NotSocket) |
| | 221 | 221 | | { |
| | | 222 | | // server was stopped |
| | 221 | 223 | | return; |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | // capture client socket |
| | 153 | 227 | | var clientSocket = e.AcceptSocket; |
| | | 228 | | |
| | 153 | 229 | | if (e.SocketError != SocketError.Success) |
| | 0 | 230 | | { |
| | | 231 | | // accept new connection |
| | 0 | 232 | | StartAccept(e); |
| | | 233 | | |
| | | 234 | | // dispose broken client socket |
| | 0 | 235 | | CloseClientSocket(clientSocket); |
| | 0 | 236 | | return; |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | // accept new connection |
| | 153 | 240 | | StartAccept(e); |
| | | 241 | | |
| | | 242 | | // process connection |
| | 153 | 243 | | ProcessAccept(clientSocket); |
| | 374 | 244 | | } |
| | | 245 | | |
| | | 246 | | private void ProcessAccept(Socket clientSocket) |
| | 153 | 247 | | { |
| | | 248 | | // close the client socket if we're no longer accepting new connections |
| | 153 | 249 | | if (!IsStarted) |
| | 2 | 250 | | { |
| | 2 | 251 | | CloseClientSocket(clientSocket); |
| | 2 | 252 | | return; |
| | | 253 | | } |
| | | 254 | | |
| | | 255 | | // capture the countdown event that we're adding a count to, as we need to make sure that we'll be signaling |
| | | 256 | | // that same instance; the instance field for the countdown event is re-initialized when the port is restart |
| | | 257 | | // and at that time there may still be pending requests |
| | 151 | 258 | | var pendingChannelCountdown = _pendingChannelCountdown; |
| | | 259 | | |
| | 151 | 260 | | pendingChannelCountdown.AddCount(); |
| | | 261 | | |
| | | 262 | | try |
| | 151 | 263 | | { |
| | 151 | 264 | | using (var channel = Session.CreateChannelDirectTcpip()) |
| | 151 | 265 | | { |
| | 151 | 266 | | channel.Exception += Channel_Exception; |
| | | 267 | | |
| | 151 | 268 | | if (!HandleSocks(channel, clientSocket, Session.ConnectionInfo.Timeout)) |
| | 54 | 269 | | { |
| | 54 | 270 | | CloseClientSocket(clientSocket); |
| | 54 | 271 | | return; |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | // start receiving from client socket (and sending to server) |
| | 79 | 275 | | channel.Bind(); |
| | 79 | 276 | | } |
| | 79 | 277 | | } |
| | 22 | 278 | | catch (Exception exp) |
| | 22 | 279 | | { |
| | 22 | 280 | | RaiseExceptionEvent(exp); |
| | 22 | 281 | | CloseClientSocket(clientSocket); |
| | 22 | 282 | | } |
| | | 283 | | finally |
| | 151 | 284 | | { |
| | | 285 | | // take into account that CountdownEvent has since been disposed; when stopping the port we |
| | | 286 | | // wait for a given time for the channels to close, but once that timeout period has elapsed |
| | | 287 | | // the CountdownEvent will be disposed |
| | | 288 | | try |
| | 151 | 289 | | { |
| | 151 | 290 | | _ = pendingChannelCountdown.Signal(); |
| | 151 | 291 | | } |
| | 0 | 292 | | catch (ObjectDisposedException) |
| | 0 | 293 | | { |
| | | 294 | | // Ignore any ObjectDisposedException |
| | 0 | 295 | | } |
| | 151 | 296 | | } |
| | 153 | 297 | | } |
| | | 298 | | |
| | | 299 | | /// <summary> |
| | | 300 | | /// Initializes the <see cref="CountdownEvent"/>. |
| | | 301 | | /// </summary> |
| | | 302 | | /// <remarks> |
| | | 303 | | /// <para> |
| | | 304 | | /// When the port is started for the first time, a <see cref="CountdownEvent"/> is created with an initial count |
| | | 305 | | /// of <c>1</c>. |
| | | 306 | | /// </para> |
| | | 307 | | /// <para> |
| | | 308 | | /// On subsequent (re)starts, we'll dispose the current <see cref="CountdownEvent"/> and create a new one with |
| | | 309 | | /// initial count of <c>1</c>. |
| | | 310 | | /// </para> |
| | | 311 | | /// </remarks> |
| | | 312 | | private void InitializePendingChannelCountdown() |
| | 222 | 313 | | { |
| | 222 | 314 | | var original = Interlocked.Exchange(ref _pendingChannelCountdown, new CountdownEvent(1)); |
| | 222 | 315 | | original?.Dispose(); |
| | 222 | 316 | | } |
| | | 317 | | |
| | | 318 | | private bool HandleSocks(IChannelDirectTcpip channel, Socket clientSocket, TimeSpan timeout) |
| | 151 | 319 | | { |
| | 151 | 320 | | Closing += closeClientSocket; |
| | | 321 | | |
| | | 322 | | try |
| | 151 | 323 | | { |
| | 151 | 324 | | var version = SocketAbstraction.ReadByte(clientSocket, timeout); |
| | 119 | 325 | | switch (version) |
| | | 326 | | { |
| | | 327 | | case -1: |
| | | 328 | | // SOCKS client closed connection |
| | 22 | 329 | | return false; |
| | | 330 | | case 4: |
| | 75 | 331 | | return HandleSocks4(clientSocket, channel, timeout); |
| | | 332 | | case 5: |
| | 4 | 333 | | return HandleSocks5(clientSocket, channel, timeout); |
| | | 334 | | default: |
| | 18 | 335 | | throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "SOCKS version {0} i |
| | | 336 | | } |
| | | 337 | | } |
| | 32 | 338 | | catch (SocketException ex) |
| | 32 | 339 | | { |
| | | 340 | | // ignore exception thrown by interrupting the blocking receive as part of closing |
| | | 341 | | // the forwarded port |
| | | 342 | | #if NETFRAMEWORK |
| | 10 | 343 | | if (ex.SocketErrorCode != SocketError.Interrupted) |
| | 0 | 344 | | { |
| | 0 | 345 | | RaiseExceptionEvent(ex); |
| | 0 | 346 | | } |
| | | 347 | | #else |
| | | 348 | | // Since .NET 5 the exception has been changed. |
| | | 349 | | // more info https://github.com/dotnet/runtime/issues/41585 |
| | 22 | 350 | | if (ex.SocketErrorCode != SocketError.ConnectionAborted) |
| | 0 | 351 | | { |
| | 0 | 352 | | RaiseExceptionEvent(ex); |
| | 0 | 353 | | } |
| | | 354 | | #endif |
| | 32 | 355 | | return false; |
| | | 356 | | } |
| | | 357 | | finally |
| | 151 | 358 | | { |
| | | 359 | | // interrupt of blocking receive is now handled by channel (SOCKS4 and SOCKS5) |
| | | 360 | | // or no longer necessary |
| | 151 | 361 | | Closing -= closeClientSocket; |
| | 151 | 362 | | } |
| | | 363 | | |
| | | 364 | | #pragma warning disable SA1300 // Element should begin with upper-case letter |
| | | 365 | | void closeClientSocket(object sender, EventArgs args) |
| | 32 | 366 | | { |
| | 32 | 367 | | CloseClientSocket(clientSocket); |
| | 32 | 368 | | } |
| | | 369 | | #pragma warning restore SA1300 // Element should begin with upper-case letter |
| | 133 | 370 | | } |
| | | 371 | | |
| | | 372 | | private static void CloseClientSocket(Socket clientSocket) |
| | 110 | 373 | | { |
| | 110 | 374 | | if (clientSocket.Connected) |
| | 74 | 375 | | { |
| | | 376 | | try |
| | 74 | 377 | | { |
| | 74 | 378 | | clientSocket.Shutdown(SocketShutdown.Send); |
| | 74 | 379 | | } |
| | 0 | 380 | | catch (Exception) |
| | 0 | 381 | | { |
| | | 382 | | // ignore exception when client socket was already closed |
| | 0 | 383 | | } |
| | 74 | 384 | | } |
| | | 385 | | |
| | 110 | 386 | | clientSocket.Dispose(); |
| | 110 | 387 | | } |
| | | 388 | | |
| | | 389 | | /// <summary> |
| | | 390 | | /// Interrupts the listener, and unsubscribes from <see cref="Session"/> events. |
| | | 391 | | /// </summary> |
| | | 392 | | private void StopListener() |
| | 222 | 393 | | { |
| | | 394 | | // close listener socket |
| | 222 | 395 | | _listener?.Dispose(); |
| | | 396 | | |
| | | 397 | | // unsubscribe from session events |
| | 222 | 398 | | var session = Session; |
| | 222 | 399 | | if (session is not null) |
| | 222 | 400 | | { |
| | 222 | 401 | | session.ErrorOccured -= Session_ErrorOccured; |
| | 222 | 402 | | session.Disconnected -= Session_Disconnected; |
| | 222 | 403 | | } |
| | 222 | 404 | | } |
| | | 405 | | |
| | | 406 | | /// <summary> |
| | | 407 | | /// Waits for pending channels to close. |
| | | 408 | | /// </summary> |
| | | 409 | | /// <param name="timeout">The maximum time to wait for the pending channels to close.</param> |
| | | 410 | | private void InternalStop(TimeSpan timeout) |
| | 222 | 411 | | { |
| | 222 | 412 | | _ = _pendingChannelCountdown.Signal(); |
| | | 413 | | |
| | 222 | 414 | | if (!_pendingChannelCountdown.Wait(timeout)) |
| | 0 | 415 | | { |
| | | 416 | | // TODO: log as warning |
| | 0 | 417 | | DiagnosticAbstraction.Log("Timeout waiting for pending channels in dynamic forwarded port to close."); |
| | 0 | 418 | | } |
| | 222 | 419 | | } |
| | | 420 | | |
| | | 421 | | private void InternalDispose(bool disposing) |
| | 284 | 422 | | { |
| | 284 | 423 | | if (disposing) |
| | 253 | 424 | | { |
| | 253 | 425 | | var listener = _listener; |
| | 253 | 426 | | if (listener is not null) |
| | 172 | 427 | | { |
| | 172 | 428 | | _listener = null; |
| | 172 | 429 | | listener.Dispose(); |
| | 172 | 430 | | } |
| | | 431 | | |
| | 253 | 432 | | var pendingRequestsCountdown = _pendingChannelCountdown; |
| | 253 | 433 | | if (pendingRequestsCountdown is not null) |
| | 172 | 434 | | { |
| | 172 | 435 | | _pendingChannelCountdown = null; |
| | 172 | 436 | | pendingRequestsCountdown.Dispose(); |
| | 172 | 437 | | } |
| | 253 | 438 | | } |
| | 284 | 439 | | } |
| | | 440 | | |
| | | 441 | | private void Session_Disconnected(object sender, EventArgs e) |
| | 0 | 442 | | { |
| | 0 | 443 | | var session = Session; |
| | 0 | 444 | | if (session is not null) |
| | 0 | 445 | | { |
| | 0 | 446 | | StopPort(session.ConnectionInfo.Timeout); |
| | 0 | 447 | | } |
| | 0 | 448 | | } |
| | | 449 | | |
| | | 450 | | private void Session_ErrorOccured(object sender, ExceptionEventArgs e) |
| | 27 | 451 | | { |
| | 27 | 452 | | var session = Session; |
| | 27 | 453 | | if (session is not null) |
| | 27 | 454 | | { |
| | 27 | 455 | | StopPort(session.ConnectionInfo.Timeout); |
| | 27 | 456 | | } |
| | 27 | 457 | | } |
| | | 458 | | |
| | | 459 | | private void Channel_Exception(object sender, ExceptionEventArgs e) |
| | 0 | 460 | | { |
| | 0 | 461 | | RaiseExceptionEvent(e.Exception); |
| | 0 | 462 | | } |
| | | 463 | | |
| | | 464 | | private bool HandleSocks4(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout) |
| | 75 | 465 | | { |
| | 75 | 466 | | var commandCode = SocketAbstraction.ReadByte(socket, timeout); |
| | 75 | 467 | | if (commandCode == -1) |
| | 0 | 468 | | { |
| | | 469 | | // SOCKS client closed connection |
| | 0 | 470 | | return false; |
| | | 471 | | } |
| | | 472 | | |
| | 75 | 473 | | var portBuffer = new byte[2]; |
| | 75 | 474 | | if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0) |
| | 0 | 475 | | { |
| | | 476 | | // SOCKS client closed connection |
| | 0 | 477 | | return false; |
| | | 478 | | } |
| | | 479 | | |
| | 75 | 480 | | var port = Pack.BigEndianToUInt16(portBuffer); |
| | | 481 | | |
| | 75 | 482 | | var ipBuffer = new byte[4]; |
| | 75 | 483 | | if (SocketAbstraction.Read(socket, ipBuffer, 0, ipBuffer.Length, timeout) == 0) |
| | 0 | 484 | | { |
| | | 485 | | // SOCKS client closed connection |
| | 0 | 486 | | return false; |
| | | 487 | | } |
| | | 488 | | |
| | 75 | 489 | | var ipAddress = new IPAddress(ipBuffer); |
| | | 490 | | |
| | 75 | 491 | | var username = ReadString(socket, timeout); |
| | 75 | 492 | | if (username is null) |
| | 0 | 493 | | { |
| | | 494 | | // SOCKS client closed connection |
| | 0 | 495 | | return false; |
| | | 496 | | } |
| | | 497 | | |
| | 75 | 498 | | var host = ipAddress.ToString(); |
| | | 499 | | |
| | 75 | 500 | | RaiseRequestReceived(host, port); |
| | | 501 | | |
| | 75 | 502 | | channel.Open(host, port, this, socket); |
| | | 503 | | |
| | 75 | 504 | | SocketAbstraction.SendByte(socket, 0x00); |
| | | 505 | | |
| | 75 | 506 | | if (channel.IsOpen) |
| | 75 | 507 | | { |
| | 75 | 508 | | SocketAbstraction.SendByte(socket, 0x5a); |
| | 75 | 509 | | SocketAbstraction.Send(socket, portBuffer, 0, portBuffer.Length); |
| | 75 | 510 | | SocketAbstraction.Send(socket, ipBuffer, 0, ipBuffer.Length); |
| | 75 | 511 | | return true; |
| | | 512 | | } |
| | | 513 | | |
| | | 514 | | // signal that request was rejected or failed |
| | 0 | 515 | | SocketAbstraction.SendByte(socket, 0x5b); |
| | 0 | 516 | | return false; |
| | 75 | 517 | | } |
| | | 518 | | |
| | | 519 | | private bool HandleSocks5(Socket socket, IChannelDirectTcpip channel, TimeSpan timeout) |
| | 4 | 520 | | { |
| | 4 | 521 | | var authenticationMethodsCount = SocketAbstraction.ReadByte(socket, timeout); |
| | 4 | 522 | | if (authenticationMethodsCount == -1) |
| | 0 | 523 | | { |
| | | 524 | | // SOCKS client closed connection |
| | 0 | 525 | | return false; |
| | | 526 | | } |
| | | 527 | | |
| | 4 | 528 | | var authenticationMethods = new byte[authenticationMethodsCount]; |
| | 4 | 529 | | if (SocketAbstraction.Read(socket, authenticationMethods, 0, authenticationMethods.Length, timeout) == 0) |
| | 0 | 530 | | { |
| | | 531 | | // SOCKS client closed connection |
| | 0 | 532 | | return false; |
| | | 533 | | } |
| | | 534 | | |
| | 4 | 535 | | if (authenticationMethods.Min() == 0) |
| | 4 | 536 | | { |
| | | 537 | | // no user authentication is one of the authentication methods supported |
| | | 538 | | // by the SOCKS client |
| | 4 | 539 | | SocketAbstraction.Send(socket, new byte[] { 0x05, 0x00 }, 0, 2); |
| | 4 | 540 | | } |
| | | 541 | | else |
| | 0 | 542 | | { |
| | | 543 | | // the SOCKS client requires authentication, which we currently do not support |
| | 0 | 544 | | SocketAbstraction.Send(socket, new byte[] { 0x05, 0xFF }, 0, 2); |
| | | 545 | | |
| | | 546 | | // we continue business as usual but expect the client to close the connection |
| | | 547 | | // so one of the subsequent reads should return -1 signaling that the client |
| | | 548 | | // has effectively closed the connection |
| | 0 | 549 | | } |
| | | 550 | | |
| | 4 | 551 | | var version = SocketAbstraction.ReadByte(socket, timeout); |
| | 4 | 552 | | if (version == -1) |
| | 0 | 553 | | { |
| | | 554 | | // SOCKS client closed connection |
| | 0 | 555 | | return false; |
| | | 556 | | } |
| | | 557 | | |
| | 4 | 558 | | if (version != 5) |
| | 0 | 559 | | { |
| | 0 | 560 | | throw new ProxyException("SOCKS5: Version 5 is expected."); |
| | | 561 | | } |
| | | 562 | | |
| | 4 | 563 | | var commandCode = SocketAbstraction.ReadByte(socket, timeout); |
| | 4 | 564 | | if (commandCode == -1) |
| | 0 | 565 | | { |
| | | 566 | | // SOCKS client closed connection |
| | 0 | 567 | | return false; |
| | | 568 | | } |
| | | 569 | | |
| | 4 | 570 | | var reserved = SocketAbstraction.ReadByte(socket, timeout); |
| | 4 | 571 | | if (reserved == -1) |
| | 0 | 572 | | { |
| | | 573 | | // SOCKS client closed connection |
| | 0 | 574 | | return false; |
| | | 575 | | } |
| | | 576 | | |
| | 4 | 577 | | if (reserved != 0) |
| | 0 | 578 | | { |
| | 0 | 579 | | throw new ProxyException("SOCKS5: 0 is expected for reserved byte."); |
| | | 580 | | } |
| | | 581 | | |
| | 4 | 582 | | var addressType = SocketAbstraction.ReadByte(socket, timeout); |
| | 4 | 583 | | if (addressType == -1) |
| | 0 | 584 | | { |
| | | 585 | | // SOCKS client closed connection |
| | 0 | 586 | | return false; |
| | | 587 | | } |
| | | 588 | | |
| | 4 | 589 | | var host = GetSocks5Host(addressType, socket, timeout); |
| | 4 | 590 | | if (host is null) |
| | 0 | 591 | | { |
| | | 592 | | // SOCKS client closed connection |
| | 0 | 593 | | return false; |
| | | 594 | | } |
| | | 595 | | |
| | 4 | 596 | | var portBuffer = new byte[2]; |
| | 4 | 597 | | if (SocketAbstraction.Read(socket, portBuffer, 0, portBuffer.Length, timeout) == 0) |
| | 0 | 598 | | { |
| | | 599 | | // SOCKS client closed connection |
| | 0 | 600 | | return false; |
| | | 601 | | } |
| | | 602 | | |
| | 4 | 603 | | var port = Pack.BigEndianToUInt16(portBuffer); |
| | | 604 | | |
| | 4 | 605 | | RaiseRequestReceived(host, port); |
| | | 606 | | |
| | 4 | 607 | | channel.Open(host, port, this, socket); |
| | | 608 | | |
| | 4 | 609 | | var socksReply = CreateSocks5Reply(channel.IsOpen); |
| | | 610 | | |
| | 4 | 611 | | SocketAbstraction.Send(socket, socksReply, 0, socksReply.Length); |
| | | 612 | | |
| | 4 | 613 | | return true; |
| | 4 | 614 | | } |
| | | 615 | | |
| | | 616 | | private static string GetSocks5Host(int addressType, Socket socket, TimeSpan timeout) |
| | 4 | 617 | | { |
| | 4 | 618 | | switch (addressType) |
| | | 619 | | { |
| | | 620 | | case 0x01: // IPv4 |
| | 1 | 621 | | { |
| | 1 | 622 | | var addressBuffer = new byte[4]; |
| | 1 | 623 | | if (SocketAbstraction.Read(socket, addressBuffer, 0, 4, timeout) == 0) |
| | 0 | 624 | | { |
| | | 625 | | // SOCKS client closed connection |
| | 0 | 626 | | return null; |
| | | 627 | | } |
| | | 628 | | |
| | 1 | 629 | | var ipv4 = new IPAddress(addressBuffer); |
| | 1 | 630 | | return ipv4.ToString(); |
| | | 631 | | } |
| | | 632 | | |
| | | 633 | | case 0x03: // Domain name |
| | 3 | 634 | | { |
| | 3 | 635 | | var length = SocketAbstraction.ReadByte(socket, timeout); |
| | 3 | 636 | | if (length == -1) |
| | 0 | 637 | | { |
| | | 638 | | // SOCKS client closed connection |
| | 0 | 639 | | return null; |
| | | 640 | | } |
| | | 641 | | |
| | 3 | 642 | | var addressBuffer = new byte[length]; |
| | 3 | 643 | | if (SocketAbstraction.Read(socket, addressBuffer, 0, addressBuffer.Length, timeout) == 0) |
| | 0 | 644 | | { |
| | | 645 | | // SOCKS client closed connection |
| | 0 | 646 | | return null; |
| | | 647 | | } |
| | | 648 | | |
| | 3 | 649 | | var hostName = SshData.Ascii.GetString(addressBuffer, 0, addressBuffer.Length); |
| | 3 | 650 | | return hostName; |
| | | 651 | | } |
| | | 652 | | |
| | | 653 | | case 0x04: // IPv6 |
| | 0 | 654 | | { |
| | 0 | 655 | | var addressBuffer = new byte[16]; |
| | 0 | 656 | | if (SocketAbstraction.Read(socket, addressBuffer, 0, 16, timeout) == 0) |
| | 0 | 657 | | { |
| | | 658 | | // SOCKS client closed connection |
| | 0 | 659 | | return null; |
| | | 660 | | } |
| | | 661 | | |
| | 0 | 662 | | var ipv6 = new IPAddress(addressBuffer); |
| | 0 | 663 | | return ipv6.ToString(); |
| | | 664 | | } |
| | | 665 | | |
| | | 666 | | default: |
| | 0 | 667 | | throw new ProxyException(string.Format(CultureInfo.InvariantCulture, "SOCKS5: Address type '{0}' is |
| | | 668 | | } |
| | 4 | 669 | | } |
| | | 670 | | |
| | | 671 | | private static byte[] CreateSocks5Reply(bool channelOpen) |
| | 4 | 672 | | { |
| | 4 | 673 | | var socksReply = new byte[// SOCKS version |
| | 4 | 674 | | 1 + |
| | 4 | 675 | | |
| | 4 | 676 | | // Reply field |
| | 4 | 677 | | 1 + |
| | 4 | 678 | | |
| | 4 | 679 | | // Reserved; fixed: 0x00 |
| | 4 | 680 | | 1 + |
| | 4 | 681 | | |
| | 4 | 682 | | // Address type; fixed: 0x01 |
| | 4 | 683 | | 1 + |
| | 4 | 684 | | |
| | 4 | 685 | | // IPv4 server bound address; fixed: {0x00, 0x00, 0x00, 0x00} |
| | 4 | 686 | | 4 + |
| | 4 | 687 | | |
| | 4 | 688 | | // server bound port; fixed: {0x00, 0x00} |
| | 4 | 689 | | 2]; |
| | | 690 | | |
| | 4 | 691 | | socksReply[0] = 0x05; |
| | | 692 | | |
| | 4 | 693 | | if (channelOpen) |
| | 4 | 694 | | { |
| | 4 | 695 | | socksReply[1] = 0x00; // succeeded |
| | 4 | 696 | | } |
| | | 697 | | else |
| | 0 | 698 | | { |
| | 0 | 699 | | socksReply[1] = 0x01; // general SOCKS server failure |
| | 0 | 700 | | } |
| | | 701 | | |
| | | 702 | | // reserved |
| | 4 | 703 | | socksReply[2] = 0x00; |
| | | 704 | | |
| | | 705 | | // IPv4 address type |
| | 4 | 706 | | socksReply[3] = 0x01; |
| | | 707 | | |
| | 4 | 708 | | return socksReply; |
| | 4 | 709 | | } |
| | | 710 | | |
| | | 711 | | /// <summary> |
| | | 712 | | /// Reads a null terminated string from a socket. |
| | | 713 | | /// </summary> |
| | | 714 | | /// <param name="socket">The <see cref="Socket"/> to read from.</param> |
| | | 715 | | /// <param name="timeout">The timeout to apply to individual reads.</param> |
| | | 716 | | /// <returns> |
| | | 717 | | /// The <see cref="string"/> read, or <see langword="null"/> when the socket was closed. |
| | | 718 | | /// </returns> |
| | | 719 | | private static string ReadString(Socket socket, TimeSpan timeout) |
| | 75 | 720 | | { |
| | 75 | 721 | | var text = new StringBuilder(); |
| | 75 | 722 | | var buffer = new byte[1]; |
| | | 723 | | |
| | 781 | 724 | | while (true) |
| | 781 | 725 | | { |
| | 781 | 726 | | if (SocketAbstraction.Read(socket, buffer, 0, 1, timeout) == 0) |
| | 0 | 727 | | { |
| | | 728 | | // SOCKS client closed connection |
| | 0 | 729 | | return null; |
| | | 730 | | } |
| | | 731 | | |
| | 781 | 732 | | var byteRead = buffer[0]; |
| | 781 | 733 | | if (byteRead == 0) |
| | 75 | 734 | | { |
| | | 735 | | // end of the string |
| | 75 | 736 | | break; |
| | | 737 | | } |
| | | 738 | | |
| | 706 | 739 | | _ = text.Append((char) byteRead); |
| | 706 | 740 | | } |
| | | 741 | | |
| | 75 | 742 | | return text.ToString(); |
| | 75 | 743 | | } |
| | | 744 | | |
| | | 745 | | /// <summary> |
| | | 746 | | /// Finalizes an instance of the <see cref="ForwardedPortDynamic"/> class. |
| | | 747 | | /// </summary> |
| | | 748 | | ~ForwardedPortDynamic() |
| | 62 | 749 | | { |
| | 31 | 750 | | Dispose(disposing: false); |
| | 62 | 751 | | } |
| | | 752 | | } |
| | | 753 | | } |