Shadowsocks primitives for .NET: Shadowsocks.Crypto for ciphers and key derivation, Shadowsocks.Protocol for Shadowsocks over TCP and UDP.
2022-blake3-aes-128-gcm,2022-blake3-aes-256-gcm,2022-blake3-chacha20-poly1305aes-128-gcm,aes-192-gcm,aes-256-gcm,chacha20-ietf-poly1305,xchacha20-ietf-poly1305none
using System.Net.Sockets;
using Shadowsocks.Crypto;
using Shadowsocks.Protocol;
// One key and one client serve all connections to a server.
using ShadowsocksKey key = ShadowsocksKey.FromPsk(ShadowsocksMethod.Aead2022Aes256Gcm, "YctPZ6U7xPPcU+gp3u+0tx/tRizJN9K8y+uKlW2qjlI=");
ShadowsocksClient client = new(key);
using TcpClient tcp = new();
await tcp.ConnectAsync("proxy.example", 8388, cancellationToken);
// Sending the first data with the request saves a packet and hides the length of the request.
byte[] firstData = "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n"u8.ToArray();
await using ShadowsocksStream stream = await client.ConnectAsync(tcp.GetStream(), new ShadowsocksAddress("example.com", 80), firstData, cancellationToken);
await stream.CopyToAsync(output, cancellationToken);// One server for all listeners of the key: it remembers the requests of the 2022 edition against replays.
ShadowsocksServer server = new(key);
// For each connection:
using Socket client = await listener.AcceptAsync(cancellationToken);
await using NetworkStream network = new(client);
using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(30));
ShadowsocksStream accepted;
try
{
accepted = await server.AcceptAsync(network, timeout.Token);
}
catch (ShadowsocksException)
{
// Whatever was wrong, a probe sees the same: nothing, until it gives up or the time is over.
await network.CopyToAsync(Stream.Null, timeout.Token);
return;
}
await using ShadowsocksStream stream = accepted;
using Socket target = new(SocketType.Stream, ProtocolType.Tcp);
await target.ConnectAsync(stream.Destination.ToEndPoint(), cancellationToken);
await using NetworkStream upstream = new(target);
await Task.WhenAll(RelayAsync(stream, upstream, target), RelayAsync(upstream, stream, client));
async Task RelayAsync(Stream from, Stream to, Socket receiver)
{
try
{
await from.CopyToAsync(to, cancellationToken);
receiver.Shutdown(SocketShutdown.Send);
}
catch
{
// Resets both sides, so that neither takes what it got for complete.
client.Close(0);
target.Close(0);
throw;
}
}using Socket udp = new(SocketType.Dgram, ProtocolType.Udp);
await udp.ConnectAsync("proxy.example", 8388, cancellationToken);
// One encoder for each source address and port that the client serves.
using ShadowsocksUdpEncoder requests = new(client);
byte[] buffer = new byte[ushort.MaxValue];
int length = requests.Encode(new ShadowsocksAddress("192.0.2.53", 53), query.Span, buffer);
await udp.SendAsync(buffer.AsMemory(0, length), cancellationToken);
// One decoder for each session of the server, which opens another one after a restart. Methods without sessions use the ID 0.
Dictionary<UInt128, ShadowsocksUdpDecoder> sessions = [];
while (true)
{
int received = await udp.ReceiveAsync(buffer, cancellationToken);
Memory<byte> packet = buffer.AsMemory(0, received);
_ = client.TryReadSessionId(packet.Span, out UInt128 id);
ShadowsocksUdpDecoder responses = sessions.GetValueOrDefault(id) ?? requests.CreateResponseDecoder();
if (responses.Decode(packet, out ShadowsocksAddress source, out Memory<byte> payload) is ShadowsocksError.None)
{
sessions.TryAdd(id, responses); // until it CanForget
Console.WriteLine($"{source}: {payload.Length} bytes");
}
}// By session ID, or for the methods without sessions by the address of the client.
ConcurrentDictionary<(UInt128, EndPoint?), Session> sessions = [];
TimeSpan natTimeout = TimeSpan.FromMinutes(5);
byte[] buffer = new byte[ushort.MaxValue];
while (true)
{
try
{
SocketReceiveFromResult received = await socket.ReceiveFromAsync(buffer, AnyOf(socket), cancellationToken);
Memory<byte> packet = buffer.AsMemory(0, received.ReceivedBytes);
(UInt128, EndPoint?) route = server.TryReadSessionId(packet.Span, out UInt128 id) ? (id, null) : (0, received.RemoteEndPoint);
Session? session = sessions.GetValueOrDefault(route);
ShadowsocksUdpDecoder requests = session?.Requests ?? new ShadowsocksUdpDecoder(server);
if (requests.Decode(packet, out ShadowsocksAddress destination, out Memory<byte> payload) is not ShadowsocksError.None)
{
continue;
}
if (session is null)
{
session = new Session(requests, requests.CreateResponseEncoder(), new Socket(SocketType.Dgram, ProtocolType.Udp));
session.Outside.Bind(AnyOf(session.Outside));
sessions[route] = session;
_ = RespondAsync(route, session);
}
// Only now, as the packet is valid.
session.Client = received.RemoteEndPoint;
session.LastSeen = Environment.TickCount64;
EndPoint target = destination.ToEndPoint();
if (target is DnsEndPoint name)
{
// Here, a slow lookup delays every client.
target = new IPEndPoint((await Dns.GetHostAddressesAsync(name.Host, cancellationToken))[0], name.Port);
}
try
{
await session.Outside.SendToAsync(payload, target, cancellationToken);
}
catch (ObjectDisposedException)
{
// The session was just forgotten.
}
}
catch (Exception e) when (e is SocketException or ArgumentException)
{
// A bad destination, or on Windows a peer that is gone, must not end the loop.
}
}
// Responds until the session is idle for the NAT timeout and its requests can be forgotten.
async Task RespondAsync((UInt128, EndPoint?) route, Session session)
{
using Socket outside = session.Outside;
byte[] payload = new byte[ushort.MaxValue];
byte[] packet = new byte[ushort.MaxValue + 1024]; // the payload and what the encoding adds
while (true)
{
using CancellationTokenSource idle = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
idle.CancelAfter(natTimeout);
try
{
SocketReceiveFromResult received = await outside.ReceiveFromAsync(payload, AnyOf(outside), idle.Token);
session.LastSeen = Environment.TickCount64;
int length = session.Responses.Encode(new ShadowsocksAddress(received.RemoteEndPoint), payload.AsSpan(0, received.ReceivedBytes), packet);
await socket.SendToAsync(packet.AsMemory(0, length), session.Client, cancellationToken);
}
catch (SocketException)
{
// As above, or the response became too long for a packet.
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
if (Environment.TickCount64 - session.LastSeen >= natTimeout.TotalMilliseconds && session.Requests.CanForget)
{
sessions.TryRemove(KeyValuePair.Create(route, session));
return;
}
}
}
}
// The socket takes endpoints of its own address family, which is IPv6 for a dual-mode one.
static IPEndPoint AnyOf(Socket socket)
{
return new IPEndPoint(socket.AddressFamily is AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
}
sealed record Session(ShadowsocksUdpDecoder Requests, ShadowsocksUdpEncoder Responses, Socket Outside)
{
public EndPoint Client { get; set; } = new IPEndPoint(0, 0);
public long LastSeen { get; set; }
}Several users share one port behind an identity key (SIP023), with the AES methods of the 2022 edition.
// Client: the identity key, then the key of the user.
using ShadowsocksKey key = ShadowsocksKey.FromPsk(ShadowsocksMethod.Aead2022Aes128Gcm, $"{identityPsk}:{alicePsk}");
// Server: the User of a connection or UDP decoder is "alice". UpdateUsers replaces the users while the server runs.
using ShadowsocksKey identityKey = ShadowsocksKey.FromPsk(ShadowsocksMethod.Aead2022Aes128Gcm, identityPsk);
using ShadowsocksKey alice = ShadowsocksKey.FromPsk(ShadowsocksMethod.Aead2022Aes128Gcm, alicePsk);
ShadowsocksServer server = new(identityKey, new Dictionary<string, ShadowsocksKey> { ["alice"] = alice });ShadowsocksUri uri = ShadowsocksUri.Parse("ss://YWVzLTEyOC1nY206dGVzdA@192.168.100.1:8888#Example1");
using ShadowsocksKey key = ShadowsocksKey.Create(uri.Method, uri.Password);
// ss://YWVzLTEyOC1nY206dGVzdA@[2001:db8::1]:8388#home
string text = new ShadowsocksUri("aes-128-gcm", "test", "2001:db8::1", 8388) { Name = "home" }.ToString();ShadowsocksTcpEncoder and ShadowsocksTcpDecoder are the connections without the I/O: each handles one direction, from the salt and header to the last chunk. ShadowsocksAddress converts from IPAddress, and to and from EndPoint and SocketAddress.