## File: README.md

# shadowsocks-libev

[](https://travis-ci.com/shadowsocks/shadowsocks-libev) [](https://snapcraft.io/shadowsocks-libev)

## Intro

[Shadowsocks-libev](https://shadowsocks.org) is a lightweight secured SOCKS5
proxy for embedded devices and low-end boxes.

It is a port of [Shadowsocks](https://github.com/shadowsocks/shadowsocks)
created by [@clowwindy](https://github.com/clowwindy), and maintained by
[@madeye](https://github.com/madeye) and [@linusyang](https://github.com/linusyang).

Current version: 3.3.6 | [Changelog](debian/changelog)

## Features

Shadowsocks-libev is written in pure C and depends on [libev](http://software.schmorp.de/pkg/libev.html). 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](https://github.com/shadowsocks/shadowsocks/wiki/Feature-Comparison-across-Different-Versions).

## 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:

```bash
sudo snap install shadowsocks-libev
```

Edge channel:

```bash
sudo snap install shadowsocks-libev --edge
```

## Installation

### Distribution-specific guide

- [Debian & Ubuntu](#debian--ubuntu)
    + [Install from repository](#install-from-repository-not-recommended)
    + [Build deb package from source](#build-deb-package-from-source)
    + [Configure and start the service](#configure-and-start-the-service)
- [Fedora & RHEL](#fedora--rhel)
    + [Build from source with centos](#build-from-source-with-centos)
- [Archlinux & Manjaro](#archlinux--manjaro)
- [NixOS](#nixos)
- [Nix](#nix)
- [Directly build and install on UNIX-like system](#linux)
- [FreeBSD](#freebsd)
    + [Install](#install)
    + [Configuration](#configuration)
    + [Run](#run)
    + [Run as client](#run-as-client)
- [OpenWRT](#openwrt)
- [OS X](#os-x)
- [Windows (MinGW)](#windows-mingw)
- [Docker](#docker)

* * *

### Build from source (CMake)

shadowsocks-libev uses CMake as its sole build system. Start by pulling submodules:

```bash
git submodule update --init --recursive
```

Then build:

```bash
mkdir -p build && cd build
cmake ..
make
sudo make install
```

To run unit tests:

```bash
cd build
ctest --output-on-failure
```

#### CMake options

For a complete list of available options, run `cmake -LH` from a build directory.
Commonly used options:

| Option | Default | Description |
|---|---|---|
| `-DWITH_EMBEDDED_SRC=OFF` | `ON` | Use system libcork/libipset/libbloom instead of bundled submodules |
| `-DWITH_DOC_MAN=OFF` | `ON` | Skip man page generation (removes asciidoc/xmlto dependency) |
| `-DBUILD_TESTING=OFF` | `ON` | Disable unit tests |
| `-DENABLE_CONNMARKTOS=ON` | `OFF` | Linux netfilter conntrack QoS support |
| `-DENABLE_NFTABLES=ON` | `OFF` | nftables firewall integration |

On macOS, if libraries are installed via Homebrew, specify paths:

```bash
cmake .. -DCMAKE_PREFIX_PATH="/usr/local/opt/mbedtls;/usr/local/opt/libsodium"
```

### 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

```bash
sudo apt update
sudo apt install shadowsocks-libev
```

#### Build deb package from source

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

```bash
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](#linux) section below.

#### 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:

```bash
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

```bash
sudo pacman -S shadowsocks-libev
```

Please refer to downstream [PKGBUILD](https://github.com/archlinux/svntogit-community/blob/packages/shadowsocks-libev/trunk/PKGBUILD)
script for extra modifications and distribution-specific bugs.

### NixOS

```bash
nix-env -iA nixos.shadowsocks-libev
```

### Nix

```bash
nix-env -iA nixpkgs.shadowsocks-libev
```

### Linux

In general, you need the following build dependencies:

* cmake (>= 3.2)
* a C compiler (gcc or clang)
* pkg-config
* libmbedtls
* libsodium (>= 1.0.4)
* libpcre2
* libev
* libc-ares
* asciidoc (for documentation only)
* xmlto (for documentation only)

If your system is too old to provide libmbedtls and libsodium (>= 1.0.4), you will need to either install those libraries manually or upgrade your system.

Install build dependencies for your distribution:

```bash
# Debian / Ubuntu
sudo apt-get install --no-install-recommends build-essential cmake pkg-config \
    libpcre2-dev libev-dev libc-ares-dev libmbedtls-dev libsodium-dev \
    asciidoc xmlto

# CentOS / Fedora / RHEL
sudo yum install gcc cmake make pkg-config pcre2-devel c-ares-devel \
    libev-devel libsodium-devel mbedtls-devel asciidoc xmlto

# Arch
sudo pacman -S gcc cmake make pkg-config pcre2 c-ares libev libsodium mbedtls \
    asciidoc xmlto
```

Then build and install:

```bash
git submodule update --init --recursive
mkdir -p build && cd build
cmake ..
make
sudo make install
```

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

**pkg (recommended)**

```bash
pkg install shadowsocks-libev
```

**ports**

```bash
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:

```bash
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](https://github.com/shadowsocks/openwrt-shadowsocks).

### OS X
For OS X, use [Homebrew](http://brew.sh) to install or build.

Install Homebrew:

```bash
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
Install shadowsocks-libev:

```bash
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:

* https://github.com/shadowsocks/libev/archive/mingw.zip

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= -p<server-port>:8388 -p<server-port>:8388/udp -d shadowsocks/shadowsocks-libev
```

More information about the image can be found [here](docker/alpine/README.md).

## 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 of your remote server.

       -m <encrypt_method>        Encrypt method:
                                  2022-blake3-aes-128-gcm,
                                  2022-blake3-aes-256-gcm,
                                  2022-blake3-chacha20-poly1305,
                                  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.

                                  The 2022-blake3-* ciphers implement
                                  Shadowsocks 2022 (SIP022) and are the
                                  recommended choice. They take a
                                  base64-encoded pre-shared key of exactly
                                  the cipher's key size via -k, not a
                                  password: generate one with
                                  `openssl rand -base64 32` (or 16 for
                                  2022-blake3-aes-128-gcm).

       [--server-url <ss_url>]    Take the server address, port, cipher,
                                  password and SIP003 plugin from a single
                                  ss:// URL (SIP002 or the legacy form).
                                  ss-local only. Options given later on the
                                  command line override the URL's values.

       [-a ]                Run as another user.

       [-f ]            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 ]           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>:]         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 to the executable of ss-server.
                                  (only available in manager mode)

       [-D ]                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.

## Helper Scripts

### ss-setup

`ss-setup` is an interactive TUI (text user interface) tool for setting up shadowsocks-libev server and client configurations. It uses `whiptail` or `dialog` for the menu interface.

It is installed automatically by `make install` and can also be run directly from `scripts/ss-setup.sh`.

**Prerequisites:** `whiptail` or `dialog`, `openssl` (optional, for password generation)

#### Server setup (with systemd service)

Run as root for full functionality (config + systemd service installation):

```bash
sudo ss-setup
```

This launches an interactive menu that walks you through:
1. Choosing a config instance name
2. Setting the listen address and port (manual or random high port)
3. Selecting an AEAD cipher (chacha20-ietf-poly1305, aes-256-gcm, etc.)
4. Generating or entering a password
5. Configuring timeout, network mode (TCP/UDP), and TCP Fast Open
6. Optionally selecting a SIP003 plugin
7. Installing and starting a systemd service

The config is saved to `/etc/shadowsocks-libev/<name>.json` and a systemd template service `shadowsocks-libev-server@<name>.service` is created.

At the end, it displays a `ss://` URI you can import into clients.

#### Client config generation

Select "Generate ss-local client config" from the main menu. The wizard prompts for the remote server address, port, cipher, password, and local SOCKS5 port, then writes a JSON config:

```bash
# Run without root to generate config in the current directory
ss-setup
# Select: client -> fill in server details -> save

# Then start the client
ss-local -c ~/ss-client.json
```

#### Config-only mode (non-root)

When run without root, `ss-setup` skips service installation and plugin management, but still generates config files in the current directory:

```bash
ss-setup
# Config saved to ./config.json (in current directory)
# Start manually:
ss-server -c ./config.json
```

#### Service management

From the main menu, select "Manage running services" to start, stop, restart, enable/disable, or view logs for any configured instance:

```
sudo ss-setup
# Select: service -> pick instance -> start/stop/restart/logs
```

#### Plugin installation

Select "Install a SIP003 plugin" from the main menu (requires root). Supports automatic download of:
- simple-obfs (build from source or package manager)
- v2ray-plugin (GitHub release)
- xray-plugin (GitHub release)
- kcptun (GitHub release)
- Custom plugin binary

### ss-nat

`ss-nat` is a helper script that sets up iptables NAT rules for `ss-redir` to provide transparent TCP/UDP redirection. It is installed on Linux systems by `make install`.

**Prerequisites:** Linux with `iptables`, `ipset`, and optionally TPROXY kernel module for UDP

#### Basic usage (TCP redirect)

```bash
# Start ss-redir first
ss-redir -s YOUR_SERVER_IP -p 8388 -l 1080 -k PASSWORD -m chacha20-ietf-poly1305 -u

# Set up NAT rules to redirect TCP traffic through ss-redir
sudo ss-nat -s YOUR_SERVER_IP -l 1080
```

#### Enable UDP relay with TPROXY

```bash
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -u
```

#### Apply rules to OUTPUT chain (proxy the local machine itself)

```bash
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -u -o
```

#### Use separate TCP/UDP servers

```bash
sudo ss-nat -s TCP_SERVER_IP -l 1080 -S UDP_SERVER_IP -L 1080 -U
```

#### Bypass specific WAN IPs

```bash
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -b "1.2.3.4 5.6.7.8"
```

#### Use a bypass IP list file

```bash
# Create a file with one IP/CIDR per line
echo "1.2.3.0/24" > /etc/ss-bypass.list
echo "5.6.7.0/24" >> /etc/ss-bypass.list

sudo ss-nat -s YOUR_SERVER_IP -l 1080 -i /etc/ss-bypass.list
```

#### LAN access control

```bash
# Whitelist mode: only proxy traffic from these LAN IPs
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -a "w192.168.1.10 192.168.1.20"

# Blacklist mode: proxy all LAN traffic except these IPs
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -a "b192.168.1.100"
```

#### Flush all rules

```bash
sudo ss-nat -f
```

#### Complete example: transparent proxy gateway

Set up a Linux box as a transparent proxy gateway for the entire LAN:

```bash
# 1. Start ss-redir with UDP relay
ss-redir -s YOUR_SERVER_IP -p 8388 -l 1080 -k PASSWORD \
    -m chacha20-ietf-poly1305 -u -f /var/run/ss-redir.pid

# 2. Set up NAT rules (TCP + UDP, apply to local OUTPUT too)
sudo ss-nat -s YOUR_SERVER_IP -l 1080 -u -o -I eth0

# 3. Point other devices' default gateway to this machine's LAN IP
#    and set their DNS to a public resolver (e.g., 1.1.1.1 or 8.8.8.8)

# To tear down:
sudo ss-nat -f
```

## Transparent proxy (manual iptables)

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.

Note: For most use cases, [`ss-nat`](#ss-nat) above is simpler than writing iptables rules manually.

    # 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.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## 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/>.
```

---

## File: docker/alpine/README.md

# Shadowsocks-libev Docker Image

[shadowsocks-libev][1] is a lightweight secured socks5 proxy for embedded
devices and low end boxes.  It is a port of [shadowsocks][2] created by
@clowwindy maintained by @madeye and @linusyang.

Docker images are built for quick deployment in various computing cloud providers. For more information on docker and containerization technologies, refer to [official document][9].

## Prepare the host

Many cloud providers offer docker-ready environments, for instance the [CoreOS Droplet in DigitalOcean][10] or the [Container-Optimized OS in Google Cloud][11].

If you need to install docker yourself, follow the [official installation guide][12].

## Pull the image

```bash
$ docker pull shadowsocks/shadowsocks-libev
```
This pulls the latest release of shadowsocks-libev.

You can also choose to pull a previous release or to try the bleeding edge build:
```bash
$ docker pull shadowsocks/shadowsocks-libev:<tag>
$ docker pull shadowsocks/shadowsocks-libev:edge
```
> A list of supported tags can be found at [Docker Hub][13].

## Start a container

```bash
$ docker run -p 8388:8388 -p 8388:8388/udp -d --restart always shadowsocks/shadowsocks-libev:latest
```
This starts a container of the latest release with all the default settings, which is equivalent to
```bash
$ ss-server -s 0.0.0.0 -p 8388 -k "$(hostname)" -m aes-256-gcm -t 300 -d "8.8.8.8,8.8.4.4" -u
```
> **Note**: It's the hostname in the container that is used as the password, not that of the host.

### With custom port

In most cases you'll want to change a thing or two, for instance the port which the server listens on. This is done by changing the `-p` arguments.

Here's an example to start a container that listens on `28388` (both TCP and UDP):
```bash
$ docker run -p 28388:8388 -p 28388:8388/udp -d --restart always shadowsocks/shadowsocks-libev
```

### With custom password

Another thing you may want to change is the password. To change that, you can pass your own password as an environment variable when starting the container.

Here's an example to start a container with `9MLSpPmNt` as the password:
```bash
$ docker run -e PASSWORD=9MLSpPmNt -p 8388:8388 -p 8388:8388/udp -d --restart always shadowsocks/shadowsocks-libev
```
> :warning: Click [here][6] to generate a strong password to protect your server.

### With password as a mounted file or a Docker secret (swarm only)

Instead of hardcoding a password to the docker-compose file or `docker run` command, you can mount in a file that contains the password. To do so, pass the path that you mounted to the container as the `PASSWORD_FILE` environment variable.

If you are running Docker Swarm, you can also utilize Docker secrets. To do so, pass the name of the secret as the `PASSWORD_SECRET` environment variable. If you specify both `PASSWORD_FILE` and `PASSWORD_SECRET`, the latter will take effect.

This is a sample `docker-compose.yml` file that uses the external Docker secret named `shadowsocks` as the password.

```yaml
shadowsocks:
  image: shadowsocks/shadowsocks-libev
  ports:
    - "8388:8388"
  environment:
    - METHOD=aes-256-gcm
    - PASSWORD_SECRET=shadowsocks
  secrets:
    - shadowsocks
```

This is a sample `docker service create` command that uses the external Docker secret named `shadowsocks` as the password.

```bash
docker service create -e PASSWORD_SECRET=shadowsocks -p 8388:8388 -p 8388:8388/udp --secret shadowsocks shadowsocks/shadowsocks-libev
```

### With other customizations
Besides `PASSWORD`, the image also defines the following environment variables that you can customize:
* `SERVER_ADDR`: the IP/domain to bind to, defaults to `0.0.0.0`
* `SERVER_ADDR_IPV6`: the IPv6 address to bind to, defaults to `::0`
* `METHOD`: encryption method to use, defaults to `aes-256-gcm`
* `TIMEOUT`: defaults to `300`
* `DNS_ADDRS`: DNS servers to redirect NS lookup requests to, defaults to `8.8.8.8,8.8.4.4`
* `TZ`: Timezone, defaults to `UTC`

Additional arguments supported by `ss-server` can be passed with the environment variable `ARGS`, for instance to start in verbose mode:
```bash
$ docker run -e ARGS=-v -p 8388:8388 -p 8388:8388/udp -d --restart always shadowsocks/shadowsocks-libev:latest
```

## Use docker-compose to manage (optional)

It is very handy to use [docker-compose][7] to manage docker containers.
You can download the binary at <https://github.com/docker/compose/releases>.

This is a sample `docker-compose.yml` file.

```yaml
shadowsocks:
  image: shadowsocks/shadowsocks-libev
  ports:
    - "8388:8388"
  environment:
    - METHOD=aes-256-gcm
    - PASSWORD=9MLSpPmNt
  restart: always
```

It is highly recommended that you setup a directory tree to make things easy to manage.

```bash
$ mkdir -p ~/fig/shadowsocks/
$ cd ~/fig/shadowsocks/
$ curl -sSLO https://github.com/shadowsocks/shadowsocks-libev/raw/master/docker/alpine/docker-compose.yml
$ docker-compose up -d
$ docker-compose ps
```

## Finish

At last, download shadowsocks client [here][8].
Don't forget to share internet with your friends.

```yaml
{
    "server": "your-vps-ip",
    "server_port": 8388,
    "local_address": "0.0.0.0",
    "local_port": 1080,
    "password": "9MLSpPmNt",
    "timeout": 600,
    "method": "aes-256-gcm"
}
```

[1]: https://github.com/shadowsocks/shadowsocks-libev
[2]: https://shadowsocks.org/en/index.html
[6]: https://duckduckgo.com/?q=password+12&t=ffsb&ia=answer
[7]: https://github.com/docker/compose
[8]: https://shadowsocks.org/en/download/clients.html
[9]: https://docs.docker.com/
[10]: https://www.digitalocean.com/products/linux-distribution/coreos/
[11]: https://cloud.google.com/container-optimized-os/
[12]: https://docs.docker.com/install/
[13]: https://hub.docker.com/r/shadowsocks/shadowsocks-libev/tags/

---

## File: README_pt_BR.md

# shadowsocks-libev

[](https://travis-ci.com/shadowsocks/shadowsocks-libev) [](https://build.snapcraft.io/user/shadowsocks/shadowsocks-libev)

## Introdução

[Shadowsocks-libev](https://shadowsocks.org) é um SOCKS5 leve e seguro
proxy para dispositivos embutidos e caixas de baixo custo.

É uma porta de [Shadowsocks](https://github.com/shadowsocks/shadowsocks)
criado por [@clowwindy](https://github.com/clowwindy) e mantido por
[@madeye](https://github.com/madeye) e [@linusyang](https://github.com/linusyang).

Versão atual: 3.3.6 | [Changelog](debian/changelog)

## Características

Shadowsocks-libev é escrito em C puro e depende de [libev](http://software.schmorp.de/pkg/libev.html). Ele foi projetado para ser uma implementação leve do protocolo shadowsocks, a fim de manter o uso de recursos o mais baixo possível.

Para obter uma lista completa de comparação de recursos entre diferentes versões de shadowsocks, consulte a [página da Wiki (https://github.com/shadowsocks/shadowsocks/wiki/Feature-Comparison-across-Different-Versions).

## Começo rápido

Snap é a maneira recomendada de instalar os binários mais recentes.

### Instale o snap core

https://snapcraft.io/core

### Instalar a partir do snapcraft.io

Stable channel:

```bash
sudo snap install shadowsocks-libev
```

Edge channel:

```bash
sudo snap install shadowsocks-libev --edge
```

## Instalação

### Guia específico de distribuição

- [Debian & Ubuntu](#debian--ubuntu)
    + [Instalar do repositório](#instale-a-partir-do-repositório-não-recomendado)
    + [Construa o pacote deb a partir da fonte](#compile-o-pacote-deb-a-partir-da-fonte)
    + [Configurar e iniciar o serviço](#configurar-e-iniciar-o-serviço)
- [Fedora & RHEL](#fedora--rhel)
     + [Construir a partir da fonte com centos](#construa-a-partir-da-fonte-com-centos)
- [Archlinux & Manjaro](#archlinux--manjaro)
- [NixOS](#nixos)
- [Nix](#nix)
- [Compile e instale diretamente no sistema semelhante ao UNIX](#linux)
- [FreeBSD](#freebsd)
     + [Instalar](#instalar)
     + [Configuração](#configuração)
     + [Executar](#executar)
     + [Executar como cliente](#executar-como-cliente)
- [OpenWRT](#openwrt)
- [OS X](#os-x)
- [Windows (MinGW)](#windows-mingw)
- [Docker](#docker)

* * *

### Inicialize o ambiente de compilação

Este repositório usa submódulos, então você deve puxá-los antes de começar, usando:

```bash
git submodule update --init --recursive
```

### Guia de configuração de pré-compilação

Para obter uma lista completa das opções de tempo de configuração disponíveis,
tentar `configure --help`.

### Debian & Ubuntu

#### Instale a partir do repositório (não recomendado)

Shadowsocks-libev está disponível no repositório oficial para as seguintes distribuições:

* Debian 8 ou superior, incluindo oldoldstable (jessie), old stable (stretch), stable (buster), testing (bullseye) e unstable (sid)
* Ubuntu 16.10 ou superior

```bash
sudo apt update
sudo apt install shadowsocks-libev
```

#### Compile o pacote deb a partir da fonte.

Distribuições suportadas:

* Debian 8, 9 ou superior
* Ubuntu 14.04 LTS, 16.04 LTS, 16.10 ou superior

Você pode construir shadowsocks-libev e todas as suas dependências por script:

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

Para sistemas mais antigos, a construção de pacotes `.deb` não é suportada.
Por favor, tente construir e instalar diretamente da fonte. Veja a seção [Linux](#linux) abaixo.

**Nota para usuários do Debian 8 (Jessie) para construir seus próprios pacotes deb**:

Nós encorajamos você a instalar shadowsocks-libev de `jessie-backports-sloppy`. Se você insistir em compilar a partir da fonte, você precisará instalar manualmente o libsodium de `jessie-backports-sloppy`, **NÃO** libsodium no repositório principal.

Para mais informações sobre backports, você pode consultar [Debian Backports](https://backports.debian.org).

``` bash
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
```

**Nota para usuários do Debian 9 (Stretch) para construir seus próprios pacotes deb**:

Nós encorajamos você a instalar shadowsocks-libev de `stretch-backports`. Se você insistir em compilar a partir do código-fonte, precisará instalar manualmente o libsodium de `stretch-backports`, **NÃO** libsodium no repositório principal.

Para mais informações sobre backports, você pode consultar [Debian Backports](https://backports.debian.org).

``` bash
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
```

#### Configurar e iniciar o serviço

```
# Edite o arquivo de configuração
sudo vim /etc/shadowsocks-libev/config.json

# Edite a configuração padrão do debian
sudo vim /etc/default/shadowsocks-libev

# Inicia o serviço
sudo /etc/init.d/shadowsocks-libev start    # para sysvinit, ou
sudo systemctl start shadowsocks-libev      # para systemd
```

### Fedora & RHEL

Distribuições suportadas:

* Versões recentes do Fedora (até EOL)
* RHEL 6, 7 e derivados (incluindo CentOS, Scientific Linux)

#### Construa a partir da fonte com centos

Se você estiver usando o CentOS 7, precisará instalar estes pré-requisitos para compilar a partir do código-fonte:

```bash
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

```bash
sudo pacman -S shadowsocks-libev
```

Consulte o script downstream [PKGBUILD](https://github.com/archlinux/svntogit-community/blob/packages/shadowsocks-libev/trunk/PKGBUILD) para modificações extras e bugs específicos da distribuição.

### NixOS

```bash
nix-env -iA nixos.shadowsocks-libev
```

### Nix

```bash
nix-env -iA nixpkgs.shadowsocks-libev
```

### Linux

Em geral, você precisa das seguintes dependências de compilação:

* autotools (autoconf, automake, libtool)
* gettext
* pkg-config
* libmbedtls
* libsodium
* libpcre3 (antiga biblioteca pcre)
* libev
* libc-ares
* asciidoc (somente para documentação)
* xmlto (apenas para documentação)

Notas: Fedora 26 libsodium versão >= 1.0.12, então você pode instalar via dnf install libsodium em vez de compilar a partir da fonte.

Se seu sistema for muito antigo para fornecer libmbedtls e libsodium (posterior a **v1.0.8**), você precisará instalar essas bibliotecas manualmente ou atualizar seu sistema.

Se o seu sistema fornece essas bibliotecas, você **não deve** instalá-las a partir do código-fonte. Você deve ir para esta seção e instalá-las a partir do repositório de distribuição.

Para algumas das distribuições, você pode instalar dependências de compilação como esta:

```bash
# Instalação de dependências básicas de compilação
## 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

# Instalação do 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

# Instalação do 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

# Comece a construir
./autogen.sh && ./configure && make
sudo make install
```

Pode ser necessário instalar manualmente os softwares ausentes.

### FreeBSD
#### Instalar
Shadowsocks-libev está disponível na Coleção de Ports do FreeBSD. Você pode instalá-lo de qualquer maneira, `pkg` ou `ports`.

**pkg (recomendado)**

```bash
pkg install shadowsocks-libev
```

**portas**

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

#### Configuração
Edite seu arquivo `config.json`. Por padrão, está localizado em `/usr/local/etc/shadowsocks-libev`.

Para habilitar shadowsocks-libev, adicione a seguinte variável rc ao seu arquivo `/etc/rc.conf`:

```
shadowsocks_libev_enable="YES"
```

#### Executar

Inicie o servidor Shadowsocks:

```bash
service shadowsocks_libev start
```

#### Executar como cliente
Por padrão, shadowsocks-libev está rodando como um servidor no FreeBSD. Se você quiser iniciar o shadowsocks-libev no modo cliente, você pode modificar o script rc (`/usr/local/etc/rc.d/shadowsocks_libev`) manualmente.

```
# modifique a seguinte linha de "ss-server" para "ss-local"
command="/usr/local/bin/ss-local"
```

Observe que é simplesmente uma solução alternativa, cada vez que você atualizar a porta, suas alterações serão substituídas pela nova versão.

### OpenWRT

O projeto OpenWRT é mantido aqui:
[openwrt-shadowsocks](https://github.com/shadowsocks/openwrt-shadowsocks).

### OS X
Para OS X, use [Homebrew](http://brew.sh) para instalar ou compilar.

Instale o Homebrew:

```bash
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
Instale shadowsocks-libev:

```bash
brew install shadowsocks-libev
```

### Windows (MinGW)
Para compilar binários nativos do Windows, o método recomendado é usar o Docker:

* No Windows: clique duas vezes em `make.bat` em `docker\mingw`
* No sistema do tipo Unix:

        cd shadowsocks-libev/docker/mingw
        make

Um tarball com binários de 32 bits e 64 bits será gerado no mesmo diretório.

Você também pode usar compiladores MinGW-w64 manualmente para compilar em shell do tipo Unix (MSYS2/Cygwin) ou compilar em sistemas semelhantes ao Unix (Linux/MacOS). Por favor, consulte os scripts de compilação em `docker/mingw`.

Atualmente você precisa usar uma biblioteca libev corrigida para MinGW:

* https://github.com/shadowsocks/libev/archive/mingw.zip

Observe que o TCP Fast Open (TFO) está disponível apenas no **Windows 10**, **1607** ou versão posterior (precisamente, build >= 14393). Se você estiver usando **1709** (compilação 16299) ou versão posterior, também precisará executar o seguinte comando no PowerShell/Prompt de comando **como administrador** e **reinicializar** para usar o TFO corretamente:

        netsh int tcp set global fastopenfallback=disabled

### Docker

Como você espera, basta puxar a imagem e executar.
```
docker pull shadowsocks/shadowsocks-libev
docker run -e PASSWORD= -p<server-port>:8388 -p<server-port>:8388/udp -d shadowsocks/shadowsocks-libev
```

Mais informações sobre a imagem podem ser encontradas [aqui](docker/alpine/README.md).

## Utilização

Para obter uma lista detalhada e completa de todos os argumentos suportados,
você pode consultar as páginas de manual dos aplicativos, respectivamente.

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

       -s <server_host>            Nome do host ou endereço IP de seu servidor remoto.

       -p <server_port>            Número da porta do seu servidor remoto.

       -l <local_port>             Número da porta do seu servidor local.

       -k                Senha do seu servidor remoto.

       -m <encrypt_method>         Método de criptografia: 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 e chacha20-ietf.
                                   A cifra padrão é chacha20-ietf-poly1305.

       [-a ]                 Executar como outro usuário.

       [-f ]             O caminho do arquivo para armazenar pid.

       [-t <timeout>]              Tempo limite do soquete em segundos.

       [-c <config_file>]          O caminho para o arquivo de configuração.

       [-n <number>]               Número máximo de arquivos abertos.

       [-i ]            Interface de rede a ser vinculada.
                                   (não disponível no modo redir)

       [-b <local_address>]        Endereço local para ligar.
                                   Para servidores: Especifique o endereço local a ser usado
                                   enquanto este servidor está fazendo saída
                                   conexões a servidores remotos em nome do
                                   clientes.
                                   Para clientes: Especifique o endereço local a ser usado
                                   enquanto este cliente está fazendo saída
                                   conexões com o servidor.

       [-u]                        Habilita retransmissão UDP.
                                   (TPROXY é necessário no modo redir)

       [-U]                        Ativa a retransmissão UDP e desativa a retransmissão TCP.
                                   (não disponível no modo local)

       [-T]                        Use tproxy em vez de redirecionar. (para tcp)
                                   (disponível apenas no modo redir)

       [-L <addr>:]          Endereço e porta do servidor de destino
                                   para encaminhamento de porta local.
                                   (disponível apenas no modo túnel)

       [-6]                        Primeiro, resolva o nome do host para o endereço IPv6.

       [-d <addr>]                 Servidores de nome para resolvedor de DNS interno.
                                   (disponível apenas no modo servidor)

       [--reuse-port]              Habilita a reutilização de porta.

       [--fast-open]               Habilita a abertura rápida do TCP.
                                   com kernel do Linux > 3.7.0.
                                   (disponível apenas no modo local e servidor)

       [--acl <acl_file>]          Caminho para ACL (lista de controle de acesso).
                                   (disponível apenas no modo local e servidor)

       [--manager-address <addr>]  endereço de soquete do domínio UNIX.
                                   (disponível apenas no modo servidor e gerenciador)

       [--mtu <MTU>]               MTU de sua interface de rede.

       [--mptcp]                   Habilita o Multipath TCP no Kernel MPTCP.
 
       [--no-delay]                Habilita TCP_NODELAY.

       [--executable ]       Caminho para o executável do ss-server.
                                   (disponível apenas no modo gerenciador)
 
       [-D ]                 Caminho para o diretório de trabalho do ss-manager.
                                   (disponível apenas no modo gerenciador)

       [--key <key_in_base64>]     Chave do seu servidor remoto.

## proxy transparente

O mais recente shadowsocks-libev forneceu um modo *redir*. Você pode configurar sua caixa ou roteador baseado em Linux para fazer proxy de todo o tráfego TCP de forma transparente, o que é útil se você usar um roteador com OpenWRT.

    # Criar nova cadeia
    iptables -t nat -N SHADOWSOCKS
    iptables -t mangle -N SHADOWSOCKS

    # Ignore os endereços do seu servidor shadowsocks
    # É muito IMPORTANTE, apenas tome cuidado.
    iptables -t nat -A SHADOWSOCKS -d 123.123.123.123 -j RETURN

    # Ignore LANs e quaisquer outros endereços que você gostaria de ignorar o proxy
    # Veja Wikipedia e RFC5735 para lista completa de redes reservadas.
    # Consulte ashi009/bestroutetb para obter uma lista de rotas CHN altamente otimizada.
    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

    # Qualquer outra coisa deve ser redirecionada para a porta local do shadowsocks
    iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 12345

    # Adicione quaisquer regras UDP
    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

    # Aplicar as regras
    iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS
    iptables -t mangle -A PREROUTING -j SHADOWSOCKS

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

## Proxy transparente (tproxy puro)

A execução deste script no host linux pode fazer proxy de todo o tráfego de saída desta máquina (exceto o tráfego enviado para o endereço reservado). Outros hosts na mesma LAN também podem alterar seu gateway padrão para o ip deste host linux (ao mesmo tempo, alterar o servidor dns para 1.1.1.1 ou 8.8.8.8, etc.) para fazer proxy de seu tráfego de saída.

> Claro, o proxy ipv6 é semelhante, basta alterar `iptables` para `ip6tables`, `ip` para `ip -6`, `127.0.0.1` para `::1`, e outros detalhes.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Dicas de segurança

Para qualquer servidor público, para evitar que os usuários acessem o localhost do seu servidor, adicione `--acl acl/server_block_local.acl` à linha de comando.

Embora shadowsocks-libev possa lidar bem com milhares de conexões simultâneas, ainda recomendamos
configurando as regras de firewall do seu servidor para limitar as conexões de cada usuário:

    # Até 32 conexões são suficientes para uso normal
    iptables -A INPUT -p tcp --syn --dport ${SHADOWSOCKS_PORT} -m connlimit --connlimit-above 32 -j REJECT --reject-with tcp-reset

## Licença

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

Este programa é um software livre: você pode redistribuí-lo 
e/ou modificá-lo sob os termos da GNU General Public License 
conforme publicada pela Free Software Foundation, a versão 3
da Licença ou (a seu critério) qualquer versão posterior.

Este programa é distribuído na esperança de que seja útil,
 mas SEM QUALQUER GARANTIA; sem mesmo a garantia implícita 
de COMERCIALIZAÇÃO ou ADEQUAÇÃO A UM DETERMINADO FIM.Veja
a Licença Pública Geral GNU para mais detalhes.

Você deve ter recebido uma cópia da GNU General Public License 
juntamente com este programa. Caso contrário, 
consulte <http://www.gnu.org/licenses/>.
```