Convert Figma logo to code with AI

shadowsocks logoshadowsocks-libev

Bug-fix-only libev port of shadowsocks. Future development moved to shadowsocks-rust

15,787
5,693
15,787
121

Top Related Projects

A C# port of shadowsocks

A platform for building proxies to bypass network restrictions.

18,819

An unidentifiable mechanism that helps you bypass GFW.

13,863

A Quantum-Safe Secure Tunnel based on QPP, KCP, FEC, and N:M multiplexing.

16,292

A simple proxy client

Quick Overview

Shadowsocks-libev is a lightweight and high-performance implementation of the Shadowsocks proxy protocol. It's designed to be a secure socks5 proxy, optimized for high-throughput and low-latency network connections. This project is particularly useful for circumventing internet censorship and enhancing online privacy.

Pros

  • High performance and low resource consumption
  • Cross-platform support (Linux, macOS, Windows, and more)
  • Robust encryption and security features
  • Active development and community support

Cons

  • Requires some technical knowledge to set up and configure
  • May be blocked or restricted in some regions
  • Limited built-in features compared to some alternative VPN solutions
  • Potential legal concerns in certain jurisdictions

Code Examples

  1. Starting a Shadowsocks server:
#include <shadowsocks.h>

int main(int argc, char **argv)
{
    ss_server_t server;
    ss_server_config_t config;

    // Initialize config with default values
    ss_server_config_init(&config);

    // Set custom config options
    config.server_port = 8388;
    config.password = "your_password";
    config.method = "aes-256-gcm";

    // Start the server
    if (ss_server_new(&server, &config) == 0) {
        ss_server_run(&server);
    }

    return 0;
}
  1. Creating a Shadowsocks client connection:
#include <shadowsocks.h>

int main(int argc, char **argv)
{
    ss_client_t client;
    ss_client_config_t config;

    // Initialize config with default values
    ss_client_config_init(&config);

    // Set custom config options
    config.server = "server_address";
    config.server_port = 8388;
    config.password = "your_password";
    config.method = "aes-256-gcm";

    // Create and run the client
    if (ss_client_new(&client, &config) == 0) {
        ss_client_connect(&client);
    }

    return 0;
}
  1. Handling encryption methods:
#include <shadowsocks.h>

void set_encryption_method(ss_crypto_t *crypto, const char *method)
{
    if (ss_crypto_init(crypto, method, "password") == 0) {
        printf("Encryption method set: %s\n", method);
    } else {
        fprintf(stderr, "Failed to set encryption method\n");
    }
}

Getting Started

To get started with shadowsocks-libev:

  1. Install dependencies:

    sudo apt-get install --no-install-recommends gettext build-essential autoconf libtool libpcre3-dev asciidoc xmlto libev-dev libc-ares-dev automake libmbedtls-dev libsodium-dev
    
  2. Clone the repository:

    git clone https://github.com/shadowsocks/shadowsocks-libev.git
    cd shadowsocks-libev
    
  3. Build and install:

    ./autogen.sh
    ./configure
    make
    sudo make install
    
  4. Run the server:

    ss-server -s server_address -p 8388 -k password -m aes-256-gcm
    

Remember to configure your client accordingly to connect to the server.

Competitor Comparisons

A C# port of shadowsocks

Pros of shadowsocks-windows

  • User-friendly GUI for easy configuration and management
  • Designed specifically for Windows, offering better integration with the OS
  • Supports PAC mode for automatic proxy configuration

Cons of shadowsocks-windows

  • Limited to Windows platform, reducing cross-platform compatibility
  • May have slower performance compared to the libev version
  • Less suitable for server-side deployment

Code Comparison

shadowsocks-windows (C#):

public class Shadowsocks
{
    public static void Main(string[] args)
    {
        Application.Run(new MainForm());
    }
}

shadowsocks-libev (C):

int main(int argc, char **argv)
{
    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;
    ...
}

The shadowsocks-windows code focuses on launching a GUI application, while shadowsocks-libev's main function handles command-line arguments and configuration options, reflecting their different use cases and target platforms.

A platform for building proxies to bypass network restrictions.

Pros of v2ray-core

  • More versatile with support for multiple protocols and transport layers
  • Advanced obfuscation techniques for better censorship resistance
  • Modular design allowing for easier customization and extension

Cons of v2ray-core

  • Higher complexity, potentially steeper learning curve
  • Slightly higher resource usage due to additional features
  • Less widespread adoption compared to Shadowsocks

Code Comparison

v2ray-core (Go):

type ServerConfig struct {
    Address *Address
    Port    uint16
    User    []*User
    Network []net.Network
}

shadowsocks-libev (C):

struct server_config {
    char *server;
    char *password;
    char *method;
    char *timeout;
};

The code snippets demonstrate the difference in configuration structures. v2ray-core's ServerConfig is more complex, reflecting its support for multiple users and network types. shadowsocks-libev's server_config is simpler, focusing on essential parameters for a single server setup.

v2ray-core offers more flexibility and advanced features, making it suitable for complex networking scenarios. However, this comes at the cost of increased complexity and resource usage. shadowsocks-libev, while more limited in features, provides a simpler and more lightweight solution that may be sufficient for many users' needs.

18,819

An unidentifiable mechanism that helps you bypass GFW.

Pros of Trojan

  • Better obfuscation: Mimics HTTPS traffic more effectively
  • Simpler protocol: Easier to implement and maintain
  • Built-in TLS support: Provides stronger encryption out of the box

Cons of Trojan

  • Less flexible: Limited to TLS-based connections
  • Newer project: Less mature and potentially less stable
  • Smaller community: Fewer resources and third-party implementations

Code Comparison

Shadowsocks-libev (server initialization):

static int ss_init(int argc, char **argv)
{
    srand(time(NULL));
    parse_options(argc, argv);
    if (server_num == 0)
        server_num = 1;
    // ...
}

Trojan (server initialization):

int main(int argc, const char *argv[]) {
    try {
        Config config;
        Service service(config);
        return service.run();
    } catch (const exception &e) {
        // ...
    }
}

Both projects use C/C++ for core functionality, but Trojan's codebase is generally more modern and object-oriented. Shadowsocks-libev has a more traditional C-style approach, while Trojan leverages C++ features for better code organization and exception handling.

13,863

A Quantum-Safe Secure Tunnel based on QPP, KCP, FEC, and N:M multiplexing.

Pros of kcptun

  • Utilizes KCP protocol for improved network performance, especially in high-latency or lossy environments
  • Offers more advanced congestion control and flow control mechanisms
  • Provides additional encryption and obfuscation options

Cons of kcptun

  • Higher CPU and bandwidth usage due to the overhead of KCP protocol
  • More complex setup and configuration compared to shadowsocks-libev
  • May not be as widely supported or compatible with various platforms

Code Comparison

shadowsocks-libev:

static int server_recv_cb(EV_P_ ev_io *w, int revents) {
    server_ctx_t *server_recv_ctx = (server_ctx_t *)w;
    server_t *server              = server_recv_ctx->server;
    buffer_t *buf                 = server->buf;
    ssize_t r                     = recv(server->fd, buf->data, BUF_SIZE, 0);
    // ... (handling received data)
}

kcptun:

func (l *Listener) AcceptKCP() (*UDPSession, error) {
    for {
        if sess := l.fetchNewSession(); sess != nil {
            return sess, nil
        }
        l.monitor()
    }
}

The code snippets show different approaches to handling network connections. shadowsocks-libev uses a callback-based approach with libev, while kcptun implements its own session management using Go's concurrency features.

16,292

A simple proxy client

Pros of Netch

  • More versatile, supporting multiple protocols beyond Shadowsocks
  • User-friendly GUI for easier configuration and management
  • Active development with frequent updates and new features

Cons of Netch

  • Larger resource footprint due to additional features
  • Potentially more complex setup for basic Shadowsocks usage
  • Windows-only, limiting cross-platform compatibility

Code Comparison

Shadowsocks-libev (server.c):

static int
create_and_bind(const char *host, const char *port, int mptcp)
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int s, listen_sock;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family   = AF_UNSPEC;   /* Return IPv4 and IPv6 choices */
    hints.ai_socktype = SOCK_STREAM; /* We want a TCP socket */
    hints.ai_flags    = AI_PASSIVE | AI_ADDRCONFIG; /* For wildcard IP address */
    hints.ai_protocol = IPPROTO_TCP;

Netch (Netch/Controllers/SSController.cs):

public class SSController : Guard
{
    public SSController() : base()
    {
        Name = "Shadowsocks";
    }

    public override bool Start(Server server, Mode mode)
    {
        // Implementation details
    }
}

The code snippets highlight the different approaches: Shadowsocks-libev uses C for low-level network operations, while Netch employs C# for higher-level abstractions and easier integration with its GUI.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

shadowsocks-libev

Build Status Snap Status

Intro

Shadowsocks-libev is a lightweight secured SOCKS5 proxy for embedded devices and low-end boxes.

It is a port of Shadowsocks created by @clowwindy, and maintained by @madeye and @linusyang.

Current version: 3.3.5 | Changelog

Features

Shadowsocks-libev is written in pure C and depends on libev. It's designed to be a lightweight implementation of shadowsocks protocol, in order to keep the resource usage as low as possible.

For a full list of feature comparison between different versions of shadowsocks, refer to the Wiki page.

Quick Start

Snap is the recommended way to install the latest binaries.

Install snap core

https://snapcraft.io/core

Install from snapcraft.io

Stable channel:

sudo snap install shadowsocks-libev

Edge channel:

sudo snap install shadowsocks-libev --edge

Installation

Distribution-specific guide


Initialise the build environment

This repository uses submodules, so you should pull them before you start, using:

git submodule update --init --recursive

Pre-build configure guide

For a complete list of available configure-time option, try configure --help.

Debian & Ubuntu

Install from repository (not recommended)

Shadowsocks-libev is available in the official repository for following distributions:

  • Debian 8 or higher, including oldoldstable (jessie), old stable (stretch), stable (buster), testing (bullseye) and unstable (sid)
  • Ubuntu 16.10 or higher
sudo apt update
sudo apt install shadowsocks-libev

Build deb package from source

Supported distributions:

  • Debian 8, 9 or higher
  • Ubuntu 14.04 LTS, 16.04 LTS, 16.10 or higher

You can build shadowsocks-libev and all its dependencies by script:

mkdir -p ~/build-area/
cp ./scripts/build_deb.sh ~/build-area/
cd ~/build-area
./build_deb.sh

For older systems, building .deb packages is not supported. Please try to build and install directly from source. See the Linux section below.

Note for Debian 8 (Jessie) users to build their own deb packages:

We strongly encourage you to install shadowsocks-libev from jessie-backports-sloppy. If you insist on building from source, you will need to manually install libsodium from jessie-backports-sloppy, NOT libsodium in main repository.

For more info about backports, you can refer Debian Backports.

cd shadowsocks-libev
sudo sh -c 'printf "deb http://deb.debian.org/debian jessie-backports main" > /etc/apt/sources.list.d/jessie-backports.list'
sudo sh -c 'printf "deb http://deb.debian.org/debian jessie-backports-sloppy main" >> /etc/apt/sources.list.d/jessie-backports.list'
sudo apt-get install --no-install-recommends devscripts equivs
mk-build-deps --root-cmd sudo --install --tool "apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends -y"
./autogen.sh && dpkg-buildpackage -b -us -uc
cd ..
sudo dpkg -i shadowsocks-libev*.deb

Note for Debian 9 (Stretch) users to build their own deb packages:

We strongly encourage you to install shadowsocks-libev from stretch-backports. If you insist on building from source, you will need to manually install libsodium from stretch-backports, NOT libsodium in main repository.

For more info about backports, you can refer Debian Backports.

cd shadowsocks-libev
sudo sh -c 'printf "deb http://deb.debian.org/debian stretch-backports main" > /etc/apt/sources.list.d/stretch-backports.list'
sudo apt-get install --no-install-recommends devscripts equivs
mk-build-deps --root-cmd sudo --install --tool "apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends -y"
./autogen.sh && dpkg-buildpackage -b -us -uc
cd ..
sudo dpkg -i shadowsocks-libev*.deb

Configure and start the service

# Edit the configuration file
sudo vim /etc/shadowsocks-libev/config.json

# Edit the default configuration for debian
sudo vim /etc/default/shadowsocks-libev

# Start the service
sudo /etc/init.d/shadowsocks-libev start    # for sysvinit, or
sudo systemctl start shadowsocks-libev      # for systemd

Fedora & RHEL

Supported distributions:

  • Recent Fedora versions (until EOL)
  • RHEL 6, 7 and derivatives (including CentOS, Scientific Linux)

Build from source with centos

If you are using CentOS 7, you need to install these prerequirements to build from source code:

yum install epel-release -y
yum install gcc gettext autoconf libtool automake make pcre-devel asciidoc xmlto c-ares-devel libev-devel libsodium-devel mbedtls-devel -y

Archlinux & Manjaro

sudo pacman -S shadowsocks-libev

Please refer to downstream PKGBUILD script for extra modifications and distribution-specific bugs.

NixOS

nix-env -iA nixos.shadowsocks-libev

Nix

nix-env -iA nixpkgs.shadowsocks-libev

Linux

In general, you need the following build dependencies:

  • autotools (autoconf, automake, libtool)
  • gettext
  • pkg-config
  • libmbedtls
  • libsodium
  • libpcre3 (old pcre library)
  • libev
  • libc-ares
  • asciidoc (for documentation only)
  • xmlto (for documentation only)

Notes: Fedora 26 libsodium version >= 1.0.12, so you can install via dnf install libsodium instead build from source.

If your system is too old to provide libmbedtls and libsodium (later than v1.0.8), you will need to either install those libraries manually or upgrade your system.

If your system provides with those libraries, you should not install them from source.You should jump to this section and install them from the distribution repository instead.

For some of the distributions, you might install build dependencies like this:

# Installation of basic build dependencies
## Debian / Ubuntu
sudo apt-get install --no-install-recommends gettext build-essential autoconf libtool libpcre3-dev asciidoc xmlto libev-dev libc-ares-dev automake libmbedtls-dev libsodium-dev pkg-config
## CentOS / Fedora / RHEL
sudo yum install gettext gcc autoconf libtool automake make asciidoc xmlto c-ares-devel libev-devel
## Arch
sudo pacman -S gettext gcc autoconf libtool automake make asciidoc xmlto c-ares libev

# Installation of libsodium
export LIBSODIUM_VER=1.0.16
wget https://download.libsodium.org/libsodium/releases/old/libsodium-$LIBSODIUM_VER.tar.gz
tar xvf libsodium-$LIBSODIUM_VER.tar.gz
pushd libsodium-$LIBSODIUM_VER
./configure --prefix=/usr && make
sudo make install
popd
sudo ldconfig

# Installation of MbedTLS
export MBEDTLS_VER=2.6.0
wget https://github.com/Mbed-TLS/mbedtls/archive/refs/tags/mbedtls-$MBEDTLS_VER.tar.gz
tar xvf mbedtls-$MBEDTLS_VER.tar.gz
pushd mbedtls-$MBEDTLS_VER
make SHARED=1 CFLAGS="-O2 -fPIC"
sudo make DESTDIR=/usr install
popd
sudo ldconfig

# Start building
./autogen.sh && ./configure && make
sudo make install

You may need to manually install missing softwares.

FreeBSD

Install

Shadowsocks-libev is available in FreeBSD Ports Collection. You can install it in either way, pkg or ports.

pkg (recommended)

pkg install shadowsocks-libev

ports

cd /usr/ports/net/shadowsocks-libev
make install

Configuration

Edit your config.json file. By default, it's located in /usr/local/etc/shadowsocks-libev.

To enable shadowsocks-libev, add the following rc variable to your /etc/rc.conf file:

shadowsocks_libev_enable="YES"

Run

Start the Shadowsocks server:

service shadowsocks_libev start

Run as client

By default, shadowsocks-libev is running as a server in FreeBSD. If you would like to start shadowsocks-libev in client mode, you can modify the rc script (/usr/local/etc/rc.d/shadowsocks_libev) manually.

# modify the following line from "ss-server" to "ss-local"
command="/usr/local/bin/ss-local"

Note that is simply a workaround, each time you upgrade the port your changes will be overwritten by the new version.

OpenWRT

The OpenWRT project is maintained here: openwrt-shadowsocks.

OS X

For OS X, use Homebrew to install or build.

Install Homebrew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Install shadowsocks-libev:

brew install shadowsocks-libev

Windows (MinGW)

To build Windows native binaries, the recommended method is to use Docker:

  • On Windows: double-click make.bat in docker\mingw

  • On Unix-like system:

      cd shadowsocks-libev/docker/mingw
      make
    

A tarball with 32-bit and 64-bit binaries will be generated in the same directory.

You could also manually use MinGW-w64 compilers to build in Unix-like shell (MSYS2/Cygwin), or cross-compile on Unix-like systems (Linux/MacOS). Please refer to build scripts in docker/mingw.

Currently you need to use a patched libev library for MinGW:

Notice that TCP Fast Open (TFO) is only available on Windows 10, 1607 or later version (precisely, build >= 14393). If you are using 1709 (build 16299) or later version, you also need to run the following command in PowerShell/Command Prompt as Administrator and reboot to use TFO properly:

    netsh int tcp set global fastopenfallback=disabled

Docker

As you expect, simply pull the image and run.

docker pull shadowsocks/shadowsocks-libev
docker run -e PASSWORD=<password> -p<server-port>:8388 -p<server-port>:8388/udp -d shadowsocks/shadowsocks-libev

More information about the image can be found here.

Usage

For a detailed and complete list of all supported arguments, you may refer to the man pages of the applications, respectively.

ss-[local|redir|server|tunnel|manager]

   -s <server_host>           Host name or IP address of your remote server.

   -p <server_port>           Port number of your remote server.

   -l <local_port>            Port number of your local server.

   -k <password>              Password of your remote server.

   -m <encrypt_method>        Encrypt method: rc4-md5,
                              aes-128-gcm, aes-192-gcm, aes-256-gcm,
                              aes-128-cfb, aes-192-cfb, aes-256-cfb,
                              aes-128-ctr, aes-192-ctr, aes-256-ctr,
                              camellia-128-cfb, camellia-192-cfb,
                              camellia-256-cfb, bf-cfb,
                              chacha20-ietf-poly1305,
                              xchacha20-ietf-poly1305,
                              salsa20, chacha20 and chacha20-ietf.
                              The default cipher is chacha20-ietf-poly1305.

   [-a <user>]                Run as another user.

   [-f <pid_file>]            The file path to store pid.

   [-t <timeout>]             Socket timeout in seconds.

   [-c <config_file>]         The path to config file.

   [-n <number>]              Max number of open files.

   [-i <interface>]           Network interface to bind.
                              (not available in redir mode)

   [-b <local_address>]       Local address to bind.
                              For servers: Specify the local address to use 
                              while this server is making outbound 
                              connections to remote servers on behalf of the
                              clients.
                              For clients: Specify the local address to use 
                              while this client is making outbound 
                              connections to the server.

   [-u]                       Enable UDP relay.
                              (TPROXY is required in redir mode)

   [-U]                       Enable UDP relay and disable TCP relay.
                              (not available in local mode)

   [-T]                       Use tproxy instead of redirect. (for tcp)
                              (only available in redir mode)

   [-L <addr>:<port>]         Destination server address and port
                              for local port forwarding.
                              (only available in tunnel mode)

   [-6]                       Resolve hostname to IPv6 address first.

   [-d <addr>]                Name servers for internal DNS resolver.
                              (only available in server mode)

   [--reuse-port]             Enable port reuse.

   [--fast-open]              Enable TCP fast open.
                              with Linux kernel > 3.7.0.
                              (only available in local and server mode)

   [--acl <acl_file>]         Path to ACL (Access Control List).
                              (only available in local and server mode)

   [--manager-address <addr>] UNIX domain socket address.
                              (only available in server and manager mode)

   [--mtu <MTU>]              MTU of your network interface.

   [--mptcp]                  Enable Multipath TCP on MPTCP Kernel.

   [--no-delay]               Enable TCP_NODELAY.

   [--executable <path>]      Path to the executable of ss-server.
                              (only available in manager mode)

   [-D <path>]                Path to the working directory of ss-manager.
                              (only available in manager mode)

   [--key <key_in_base64>]    Key of your remote server.

   [--plugin <name>]          Enable SIP003 plugin. (Experimental)

   [--plugin-opts <options>]  Set SIP003 plugin options. (Experimental)

   [-v]                       Verbose mode.

Transparent proxy

The latest shadowsocks-libev has provided a redir mode. You can configure your Linux-based box or router to proxy all TCP traffic transparently, which is handy if you use an OpenWRT-powered router.

# Create new chain
iptables -t nat -N SHADOWSOCKS
iptables -t mangle -N SHADOWSOCKS

# Ignore your shadowsocks server's addresses
# It's very IMPORTANT, just be careful.
iptables -t nat -A SHADOWSOCKS -d 123.123.123.123 -j RETURN

# Ignore LANs and any other addresses you'd like to bypass the proxy
# See Wikipedia and RFC5735 for full list of reserved networks.
# See ashi009/bestroutetb for a highly optimized CHN route list.
iptables -t nat -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 224.0.0.0/4 -j RETURN
iptables -t nat -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN

# Anything else should be redirected to shadowsocks's local port
iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 12345

# Add any UDP rules
ip route add local default dev lo table 100
ip rule add fwmark 1 lookup 100
iptables -t mangle -A SHADOWSOCKS -p udp --dport 53 -j TPROXY --on-port 12345 --tproxy-mark 0x01/0x01

# Apply the rules
iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS
iptables -t mangle -A PREROUTING -j SHADOWSOCKS

# Start the shadowsocks-redir
ss-redir -u -c /etc/config/shadowsocks.json -f /var/run/shadowsocks.pid

Transparent proxy (pure tproxy)

Executing this script on the linux host can proxy all outgoing traffic of this machine (except the traffic sent to the reserved address). Other hosts under the same LAN can also change their default gateway to the ip of this linux host (at the same time change the dns server to 1.1.1.1 or 8.8.8.8, etc.) to proxy their outgoing traffic.

Of course, the ipv6 proxy is similar, just change iptables to ip6tables, ip to ip -6, 127.0.0.1 to ::1, and other details.

#!/bin/bash

start_ssredir() {
    # please modify MyIP, MyPort, etc.
    (ss-redir -s MyIP -p MyPort -m MyMethod -k MyPasswd -b 127.0.0.1 -l 60080 --no-delay -u -T -v </dev/null &>>/var/log/ss-redir.log &)
}

stop_ssredir() {
    kill -9 $(pidof ss-redir) &>/dev/null
}

start_iptables() {
    ##################### SSREDIR #####################
    iptables -t mangle -N SSREDIR

    # connection-mark -> packet-mark
    iptables -t mangle -A SSREDIR -j CONNMARK --restore-mark
    iptables -t mangle -A SSREDIR -m mark --mark 0x2333 -j RETURN

    # please modify MyIP, MyPort, etc.
    # ignore traffic sent to ss-server
    iptables -t mangle -A SSREDIR -p tcp -d MyIP --dport MyPort -j RETURN
    iptables -t mangle -A SSREDIR -p udp -d MyIP --dport MyPort -j RETURN

    # ignore traffic sent to reserved addresses
    iptables -t mangle -A SSREDIR -d 0.0.0.0/8          -j RETURN
    iptables -t mangle -A SSREDIR -d 10.0.0.0/8         -j RETURN
    iptables -t mangle -A SSREDIR -d 100.64.0.0/10      -j RETURN
    iptables -t mangle -A SSREDIR -d 127.0.0.0/8        -j RETURN
    iptables -t mangle -A SSREDIR -d 169.254.0.0/16     -j RETURN
    iptables -t mangle -A SSREDIR -d 172.16.0.0/12      -j RETURN
    iptables -t mangle -A SSREDIR -d 192.0.0.0/24       -j RETURN
    iptables -t mangle -A SSREDIR -d 192.0.2.0/24       -j RETURN
    iptables -t mangle -A SSREDIR -d 192.88.99.0/24     -j RETURN
    iptables -t mangle -A SSREDIR -d 192.168.0.0/16     -j RETURN
    iptables -t mangle -A SSREDIR -d 198.18.0.0/15      -j RETURN
    iptables -t mangle -A SSREDIR -d 198.51.100.0/24    -j RETURN
    iptables -t mangle -A SSREDIR -d 203.0.113.0/24     -j RETURN
    iptables -t mangle -A SSREDIR -d 224.0.0.0/4        -j RETURN
    iptables -t mangle -A SSREDIR -d 240.0.0.0/4        -j RETURN
    iptables -t mangle -A SSREDIR -d 255.255.255.255/32 -j RETURN

    # mark the first packet of the connection
    iptables -t mangle -A SSREDIR -p tcp --syn                      -j MARK --set-mark 0x2333
    iptables -t mangle -A SSREDIR -p udp -m conntrack --ctstate NEW -j MARK --set-mark 0x2333

    # packet-mark -> connection-mark
    iptables -t mangle -A SSREDIR -j CONNMARK --save-mark

    ##################### OUTPUT #####################
    # proxy the outgoing traffic from this machine
    iptables -t mangle -A OUTPUT -p tcp -m addrtype --src-type LOCAL ! --dst-type LOCAL -j SSREDIR
    iptables -t mangle -A OUTPUT -p udp -m addrtype --src-type LOCAL ! --dst-type LOCAL -j SSREDIR

    ##################### PREROUTING #####################
    # proxy traffic passing through this machine (other->other)
    iptables -t mangle -A PREROUTING -p tcp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j SSREDIR
    iptables -t mangle -A PREROUTING -p udp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j SSREDIR

    # hand over the marked package to TPROXY for processing
    iptables -t mangle -A PREROUTING -p tcp -m mark --mark 0x2333 -j TPROXY --on-ip 127.0.0.1 --on-port 60080
    iptables -t mangle -A PREROUTING -p udp -m mark --mark 0x2333 -j TPROXY --on-ip 127.0.0.1 --on-port 60080
}

stop_iptables() {
    ##################### PREROUTING #####################
    iptables -t mangle -D PREROUTING -p tcp -m mark --mark 0x2333 -j TPROXY --on-ip 127.0.0.1 --on-port 60080 &>/dev/null
    iptables -t mangle -D PREROUTING -p udp -m mark --mark 0x2333 -j TPROXY --on-ip 127.0.0.1 --on-port 60080 &>/dev/null

    iptables -t mangle -D PREROUTING -p tcp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j SSREDIR &>/dev/null
    iptables -t mangle -D PREROUTING -p udp -m addrtype ! --src-type LOCAL ! --dst-type LOCAL -j SSREDIR &>/dev/null

    ##################### OUTPUT #####################
    iptables -t mangle -D OUTPUT -p tcp -m addrtype --src-type LOCAL ! --dst-type LOCAL -j SSREDIR &>/dev/null
    iptables -t mangle -D OUTPUT -p udp -m addrtype --src-type LOCAL ! --dst-type LOCAL -j SSREDIR &>/dev/null

    ##################### SSREDIR #####################
    iptables -t mangle -F SSREDIR &>/dev/null
    iptables -t mangle -X SSREDIR &>/dev/null
}

start_iproute2() {
    ip route add local default dev lo table 100
    ip rule  add fwmark 0x2333        table 100
}

stop_iproute2() {
    ip rule  del   table 100 &>/dev/null
    ip route flush table 100 &>/dev/null
}

start_resolvconf() {
    # or nameserver 8.8.8.8, etc.
    echo "nameserver 1.1.1.1" >/etc/resolv.conf
}

stop_resolvconf() {
    echo "nameserver 114.114.114.114" >/etc/resolv.conf
}

start() {
    echo "start ..."
    start_ssredir
    start_iptables
    start_iproute2
    start_resolvconf
    echo "start end"
}

stop() {
    echo "stop ..."
    stop_resolvconf
    stop_iproute2
    stop_iptables
    stop_ssredir
    echo "stop end"
}

restart() {
    stop
    sleep 1
    start
}

main() {
    if [ $# -eq 0 ]; then
        echo "usage: $0 start|stop|restart ..."
        return 1
    fi

    for funcname in "$@"; do
        if [ "$(type -t $funcname)" != 'function' ]; then
            echo "'$funcname' not a shell function"
            return 1
        fi
    done

    for funcname in "$@"; do
        $funcname
    done
    return 0
}
main "$@"

Security Tips

For any public server, to avoid users accessing localhost of your server, please add --acl acl/server_block_local.acl to the command line.

Although shadowsocks-libev can handle thousands of concurrent connections nicely, we still recommend setting up your server's firewall rules to limit connections from each user:

# Up to 32 connections are enough for normal usage
iptables -A INPUT -p tcp --syn --dport ${SHADOWSOCKS_PORT} -m connlimit --connlimit-above 32 -j REJECT --reject-with tcp-reset

License

Copyright: 2013-2015, Clow Windy <clowwindy42@gmail.com>
           2013-2018, Max Lv <max.c.lv@gmail.com>
           2014, Linus Yang <linusyang@gmail.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.