├── .gitignore ├── prometheus_example.yml ├── README.md ├── metrics └── metrics.go ├── udp.go ├── server.go └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | -------------------------------------------------------------------------------- /prometheus_example.yml: -------------------------------------------------------------------------------- 1 | global: 2 | scrape_interval: 5s 3 | external_labels: 4 | monitor: 'outline-monitor' 5 | 6 | scrape_configs: 7 | - job_name: 'prometheus' 8 | static_configs: 9 | - targets: ['localhost:9090'] 10 | 11 | - job_name: 'ss-server' 12 | static_configs: 13 | - targets: ['localhost:8080'] 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ss-example 2 | 3 | This repository shows how to implement a custom Shadowsocks server using a [modified version](https://github.com/fortuna/go-shadowsocks2/pull/1) of [go-shadowsocks2](https://github.com/shadowsocks/go-shadowsocks2). 4 | 5 | This custom server allows for measuring traffic using [prometheus.io](https://prometheus.io), and supports multiple users on the same port. 6 | 7 | ## Try it! 8 | 9 | Clone the repositories: 10 | ``` 11 | git clone -b ss-lib https://github.com/fortuna/go-shadowsocks2.git $(go env GOPATH)/src/github.com/shadowsocks/go-shadowsocks2 && 12 | git clone https://github.com/fortuna/ss-example.git $(go env GOPATH)/src/github.com/fortuna/ss-example 13 | ``` 14 | 15 | For development, you may want to use SSH: 16 | ``` 17 | git clone -b ss-lib git@github.com:fortuna/go-shadowsocks2.git $(go env GOPATH)/src/github.com/shadowsocks/go-shadowsocks2 && 18 | git clone git@github.com:fortuna/ss-example.git $(go env GOPATH)/src/github.com/fortuna/ss-example 19 | ``` 20 | 21 | Fetch dependencies and build: 22 | ``` 23 | go get github.com/fortuna/ss-example github.com/shadowsocks/go-shadowsocks2 github.com/prometheus/prometheus/cmd/... 24 | ``` 25 | 26 | On Terminal 1, start the SS server: 27 | ``` 28 | ./ss-example -u "chacha20-ietf-poly1305:Secret1" -u "chacha20-ietf-poly1305:Secret2" -s localhost:9999 -metrics localhost:8080 29 | ``` 30 | 31 | On Terminal 2, start prometheus scraper for metrics collection: 32 | ``` 33 | $(go env GOPATH)/bin/prometheus --config.file=prometheus_example.yml 34 | ``` 35 | 36 | On Terminal 3, start the SS client: 37 | ``` 38 | ./go-shadowsocks2 -c ss://chacha20-ietf-poly1305:Secret1@:9999 -verbose -socks :1080 39 | ``` 40 | 41 | On Terminal 4, fetch a page using the SS client: 42 | ``` 43 | curl --proxy socks5h://localhost:1080 example.com 44 | ``` 45 | 46 | Stop and restart the client on Terminal 3 with "Secret2" as the password and try to fetch the page again on Terminal 4. 47 | 48 | Open http://localhost:8080/metrics and see the exported Prometheus variables. 49 | 50 | Open http://localhost:9090/ and see the Prometheus server dashboard. 51 | 52 | 53 | ## Performance Testing 54 | 55 | Start the iperf3 server (runs on port 5201 by default): 56 | ``` 57 | iperf3 -s 58 | ``` 59 | 60 | Start the SS server (listening on port 20001): 61 | ``` 62 | go build github.com/fortuna/ss-example && \ 63 | ./ss-example -u "chacha20-ietf-poly1305:Secret1" -s :20001 64 | ``` 65 | 66 | Start the SS tunnel to redirect port 20002 -> localhost:5201 via the proxy on 20001: 67 | ``` 68 | go build github.com/shadowsocks/go-shadowsocks2 && \ 69 | ./go-shadowsocks2 -c ss://chacha20-ietf-poly1305:Secret1@:20001 -tcptun ":20002=localhost:5201" -udptun ":20002=localhost:5201" -verbose 70 | ``` 71 | 72 | Test TCP upload (client -> server): 73 | ``` 74 | iperf3 -c localhost -p 20002 75 | ``` 76 | 77 | Test TCP download (server -> client): 78 | ``` 79 | iperf3 -c localhost -p 20002 --reverse 80 | ``` 81 | 82 | Test UDP upload: 83 | ``` 84 | iperf3 -c localhost -p 20002 --udp -b 0 85 | ``` 86 | 87 | Test UDP download: 88 | ``` 89 | iperf3 -c localhost -p 20002 --udp -b 0 --reverse 90 | ``` 91 | 92 | ### Compare to go-shadowsocks2 93 | 94 | Run the commands above, but start the SS server with 95 | ``` 96 | go build github.com/shadowsocks/go-shadowsocks2 && \ 97 | ./go-shadowsocks2 -s ss://chacha20-ietf-poly1305:Secret1@:20001 -verbose 98 | ``` 99 | 100 | 101 | ### Compare to shadowsocks-libev 102 | 103 | Start the SS server (listening on port 10001): 104 | ``` 105 | ss-server -s localhost -p 10001 -m chacha20-ietf-poly1305 -k Secret1 -u -v 106 | ``` 107 | 108 | Start the SS tunnel to redirect port 10002 -> localhost:5201 via the proxy on 10001: 109 | ``` 110 | ss-tunnel -s localhost -p 10001 -m chacha20-ietf-poly1305 -k Secret1 -l 10002 -L localhost:5201 -u -v 111 | ``` 112 | 113 | Run the iperf3 client tests listed above on port 10002. 114 | 115 | You can mix and match the libev and go servers and clients. 116 | -------------------------------------------------------------------------------- /metrics/metrics.go: -------------------------------------------------------------------------------- 1 | package metrics 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "sync" 7 | "time" 8 | 9 | "github.com/prometheus/client_golang/prometheus" 10 | 11 | ssnet "github.com/shadowsocks/go-shadowsocks2/net" 12 | ) 13 | 14 | type TCPMetrics interface { 15 | AddTCPConnection() 16 | RemoveTCPConnection(accessKey, status string, duration time.Duration) 17 | } 18 | 19 | type prometheusTCPMetrics struct { 20 | tcpOpenConnections prometheus.Counter 21 | tcpClosedConnections *prometheus.CounterVec 22 | tcpConnectionDurationMs *prometheus.SummaryVec 23 | } 24 | 25 | func (m *prometheusTCPMetrics) AddTCPConnection() { 26 | m.tcpOpenConnections.Inc() 27 | } 28 | func (m *prometheusTCPMetrics) RemoveTCPConnection(accessKey, status string, duration time.Duration) { 29 | m.tcpClosedConnections.WithLabelValues(accessKey, status).Inc() 30 | m.tcpConnectionDurationMs.WithLabelValues(accessKey, status).Observe(duration.Seconds() * 1000) 31 | } 32 | 33 | func NewPrometheusTCPMetrics() TCPMetrics { 34 | m := &prometheusTCPMetrics{ 35 | tcpOpenConnections: prometheus.NewCounter(prometheus.CounterOpts{ 36 | Namespace: "shadowsocks", 37 | Subsystem: "tcp", 38 | Name: "open_connections", 39 | Help: "Count of open TCP connections", 40 | }), 41 | tcpClosedConnections: prometheus.NewCounterVec(prometheus.CounterOpts{ 42 | Namespace: "shadowsocks", 43 | Subsystem: "tcp", 44 | Name: "closed_connections", 45 | Help: "Count of closed TCP connections", 46 | }, []string{"access_key", "status"}), 47 | tcpConnectionDurationMs: prometheus.NewSummaryVec( 48 | prometheus.SummaryOpts{ 49 | Namespace: "shadowsocks", 50 | Subsystem: "tcp", 51 | Name: "connection_duration_ms", 52 | Help: "TCP connection duration distributions.", 53 | Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}, 54 | }, []string{"access_key", "status"}), 55 | } 56 | // TODO: Is it possible to pass where to register the collectors? 57 | prometheus.MustRegister(m.tcpOpenConnections, m.tcpClosedConnections, m.tcpConnectionDurationMs) 58 | return m 59 | } 60 | 61 | type measuredReader struct { 62 | io.Reader 63 | io.WriterTo 64 | count *int64 65 | } 66 | 67 | func MeasureReader(reader io.Reader, count *int64) io.Reader { 68 | return &measuredReader{Reader: reader, count: count} 69 | } 70 | 71 | func (r *measuredReader) Read(b []byte) (int, error) { 72 | n, err := r.Reader.Read(b) 73 | *r.count += int64(n) 74 | return n, err 75 | } 76 | 77 | func (r *measuredReader) WriteTo(w io.Writer) (int64, error) { 78 | n, err := io.Copy(w, r.Reader) 79 | *r.count += n 80 | return n, err 81 | } 82 | 83 | type measuredWriter struct { 84 | io.Writer 85 | io.ReaderFrom 86 | count *int64 87 | } 88 | 89 | func MeasureWriter(writer io.Writer, count *int64) io.Writer { 90 | return &measuredWriter{Writer: writer, count: count} 91 | } 92 | 93 | func (w *measuredWriter) Write(b []byte) (int, error) { 94 | n, err := w.Writer.Write(b) 95 | *w.count += int64(n) 96 | return n, err 97 | } 98 | 99 | func (w *measuredWriter) ReadFrom(r io.Reader) (int64, error) { 100 | n, err := io.Copy(w.Writer, r) 101 | *w.count += n 102 | return n, err 103 | } 104 | 105 | type ProxyMetrics struct { 106 | ClientProxy int64 107 | ProxyTarget int64 108 | TargetProxy int64 109 | ProxyClient int64 110 | } 111 | 112 | func (m *ProxyMetrics) add(other ProxyMetrics) { 113 | m.ClientProxy += other.ClientProxy 114 | m.ProxyTarget += other.ProxyTarget 115 | m.TargetProxy += other.TargetProxy 116 | m.ProxyClient += other.ProxyClient 117 | } 118 | 119 | type MetricsMap struct { 120 | mutex sync.RWMutex 121 | m map[string]*ProxyMetrics 122 | } 123 | 124 | func (this *MetricsMap) Add(key string, toAdd ProxyMetrics) { 125 | this.mutex.Lock() 126 | defer this.mutex.Unlock() 127 | p, ok := this.m[key] 128 | if !ok { 129 | p = &ProxyMetrics{} 130 | this.m[key] = p 131 | } 132 | p.add(toAdd) 133 | } 134 | 135 | func (this *MetricsMap) Get(key string) ProxyMetrics { 136 | this.mutex.RLock() 137 | defer this.mutex.RUnlock() 138 | if p, ok := this.m[key]; ok { 139 | return *p 140 | } 141 | return ProxyMetrics{} 142 | } 143 | 144 | func NewMetricsMap() *MetricsMap { 145 | return &MetricsMap{m: make(map[string]*ProxyMetrics)} 146 | } 147 | 148 | func MeasureConn(conn ssnet.DuplexConn, bytesSent, bytesRceived *int64) ssnet.DuplexConn { 149 | r := MeasureReader(conn, bytesRceived) 150 | w := MeasureWriter(conn, bytesSent) 151 | return ssnet.WrapDuplexConn(conn, r, w) 152 | } 153 | 154 | func SPrintMetrics(m ProxyMetrics) string { 155 | return fmt.Sprintf("C->P: %v, P->T: %v, T->P: %v, P->C: %v", 156 | m.ClientProxy, m.ProxyTarget, m.TargetProxy, m.ProxyClient) 157 | } 158 | -------------------------------------------------------------------------------- /udp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "log" 6 | "net" 7 | "time" 8 | 9 | "sync" 10 | 11 | "github.com/shadowsocks/go-shadowsocks2/shadowaead" 12 | "github.com/shadowsocks/go-shadowsocks2/socks" 13 | ) 14 | 15 | type mode int 16 | 17 | const ( 18 | remoteServer mode = iota 19 | relayClient 20 | socksClient 21 | ) 22 | 23 | const udpBufSize = 64 * 1024 24 | 25 | // upack decripts src into dst. It tries each cipher until it finds one that authenticates 26 | // correctly. dst and src must not overlap. 27 | func unpack(dst, src []byte, ciphers []shadowaead.Cipher) ([]byte, shadowaead.Cipher, error) { 28 | for i, cipher := range ciphers { 29 | log.Printf("Trying cipher %v", i) 30 | buf, err := shadowaead.Unpack(dst, src, cipher) 31 | if err != nil { 32 | log.Printf("Failed cipher %v: %v", i, err) 33 | continue 34 | } 35 | log.Printf("Selected cipher %v", i) 36 | return buf, cipher, nil 37 | } 38 | return nil, nil, errors.New("could not find valid cipher") 39 | } 40 | 41 | // Listen on addr for encrypted packets and basically do UDP NAT. 42 | func udpRemote(addr string, ciphers []shadowaead.Cipher) { 43 | c, err := net.ListenPacket("udp", addr) 44 | if err != nil { 45 | log.Printf("UDP remote listen error: %v", err) 46 | return 47 | } 48 | defer c.Close() 49 | 50 | nm := newNATmap(config.UDPTimeout) 51 | cipherBuf := make([]byte, udpBufSize) 52 | buf := make([]byte, udpBufSize) 53 | 54 | log.Printf("listening UDP on %s", addr) 55 | for { 56 | func() { 57 | n, raddr, err := c.ReadFrom(cipherBuf) 58 | defer log.Printf("Done with %v", raddr.String()) 59 | if err != nil { 60 | log.Printf("UDP remote read error: %v", err) 61 | return 62 | } 63 | log.Printf("Request from %v", raddr) 64 | buf, cipher, err := unpack(buf, cipherBuf[:n], ciphers) 65 | if err != nil { 66 | log.Printf("UDP remote read error: %v", err) 67 | return 68 | } 69 | 70 | tgtAddr := socks.SplitAddr(buf[:n]) 71 | if tgtAddr == nil { 72 | log.Printf("failed to split target address from packet: %q", buf[:n]) 73 | return 74 | } 75 | 76 | tgtUDPAddr, err := net.ResolveUDPAddr("udp", tgtAddr.String()) 77 | if err != nil { 78 | log.Printf("failed to resolve target UDP address: %v", err) 79 | return 80 | } 81 | 82 | payload := buf[len(tgtAddr):n] 83 | 84 | pc := nm.Get(raddr.String()) 85 | if pc == nil { 86 | pc, err = net.ListenPacket("udp", "") 87 | if err != nil { 88 | log.Printf("UDP remote listen error: %v", err) 89 | return 90 | } 91 | 92 | nm.Add(raddr, shadowaead.NewPacketConn(c, cipher), pc, remoteServer) 93 | } 94 | 95 | _, err = pc.WriteTo(payload, tgtUDPAddr) // accept only UDPAddr despite the signature 96 | if err != nil { 97 | log.Printf("UDP remote write error: %v", err) 98 | return 99 | } 100 | }() 101 | } 102 | } 103 | 104 | // Packet NAT table 105 | type natmap struct { 106 | sync.RWMutex 107 | m map[string]net.PacketConn 108 | timeout time.Duration 109 | } 110 | 111 | func newNATmap(timeout time.Duration) *natmap { 112 | m := &natmap{} 113 | m.m = make(map[string]net.PacketConn) 114 | m.timeout = timeout 115 | return m 116 | } 117 | 118 | func (m *natmap) Get(key string) net.PacketConn { 119 | m.RLock() 120 | defer m.RUnlock() 121 | return m.m[key] 122 | } 123 | 124 | func (m *natmap) Set(key string, pc net.PacketConn) { 125 | m.Lock() 126 | defer m.Unlock() 127 | 128 | m.m[key] = pc 129 | } 130 | 131 | func (m *natmap) Del(key string) net.PacketConn { 132 | m.Lock() 133 | defer m.Unlock() 134 | 135 | pc, ok := m.m[key] 136 | if ok { 137 | delete(m.m, key) 138 | return pc 139 | } 140 | return nil 141 | } 142 | 143 | func (m *natmap) Add(peer net.Addr, dst, src net.PacketConn, role mode) { 144 | m.Set(peer.String(), src) 145 | 146 | go func() { 147 | timedCopy(dst, peer, src, m.timeout, role) 148 | if pc := m.Del(peer.String()); pc != nil { 149 | pc.Close() 150 | } 151 | }() 152 | } 153 | 154 | // copy from src to dst at target with read timeout 155 | func timedCopy(dst net.PacketConn, target net.Addr, src net.PacketConn, timeout time.Duration, role mode) error { 156 | buf := make([]byte, udpBufSize) 157 | 158 | for { 159 | src.SetReadDeadline(time.Now().Add(timeout)) 160 | n, raddr, err := src.ReadFrom(buf) 161 | if err != nil { 162 | return err 163 | } 164 | 165 | switch role { 166 | case remoteServer: // server -> client: add original packet source 167 | srcAddr := socks.ParseAddr(raddr.String()) 168 | copy(buf[len(srcAddr):], buf[:n]) 169 | copy(buf, srcAddr) 170 | _, err = dst.WriteTo(buf[:len(srcAddr)+n], target) 171 | case relayClient: // client -> user: strip original packet source 172 | srcAddr := socks.SplitAddr(buf[:n]) 173 | _, err = dst.WriteTo(buf[len(srcAddr):n], target) 174 | case socksClient: // client -> socks5 program: just set RSV and FRAG = 0 175 | _, err = dst.WriteTo(append([]byte{0, 0, 0}, buf[:n]...), target) 176 | } 177 | 178 | if err != nil { 179 | return err 180 | } 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "flag" 7 | "fmt" 8 | "io" 9 | "log" 10 | "net" 11 | "net/http" 12 | "os" 13 | "os/signal" 14 | "strconv" 15 | "strings" 16 | "syscall" 17 | "time" 18 | 19 | "github.com/fortuna/ss-example/metrics" 20 | "github.com/prometheus/client_golang/prometheus/promhttp" 21 | "github.com/shadowsocks/go-shadowsocks2/core" 22 | ssnet "github.com/shadowsocks/go-shadowsocks2/net" 23 | "github.com/shadowsocks/go-shadowsocks2/shadowaead" 24 | "github.com/shadowsocks/go-shadowsocks2/socks" 25 | ) 26 | 27 | var config struct { 28 | UDPTimeout time.Duration 29 | } 30 | 31 | func shadowConn(conn ssnet.DuplexConn, cipherList []shadowaead.Cipher) (ssnet.DuplexConn, int, error) { 32 | cipher, index, shadowReader, err := findCipher(conn, cipherList) 33 | if err != nil { 34 | return nil, -1, err 35 | } 36 | shadowWriter := shadowaead.NewShadowsocksWriter(conn, cipher) 37 | return ssnet.WrapDuplexConn(conn, shadowReader, shadowWriter), index, nil 38 | } 39 | 40 | func findCipher(clientReader io.Reader, cipherList []shadowaead.Cipher) (shadowaead.Cipher, int, io.Reader, error) { 41 | if len(cipherList) == 0 { 42 | return nil, -1, nil, errors.New("Empty cipher list") 43 | } else if len(cipherList) == 1 { 44 | return cipherList[0], 0, shadowaead.NewShadowsocksReader(clientReader, cipherList[0]), nil 45 | } 46 | // buffer saves the bytes read from shadowConn, in order to allow for replays. 47 | var buffer bytes.Buffer 48 | // Try each cipher until we find one that authenticates successfully. 49 | // This assumes that all ciphers are AEAD. 50 | for i, cipher := range cipherList { 51 | log.Printf("Trying cipher %v", i) 52 | // tmpReader reuses the bytes read so far, falling back to shadowConn if it needs more 53 | // bytes. All bytes read from shadowConn are saved in buffer. 54 | tmpReader := io.MultiReader(bytes.NewReader(buffer.Bytes()), io.TeeReader(clientReader, &buffer)) 55 | // Override the Reader of shadowConn so we can reset it for each cipher test. 56 | cipherReader := shadowaead.NewShadowsocksReader(tmpReader, cipher) 57 | // Read should read just enough data to authenticate the payload size. 58 | _, err := cipherReader.Read(make([]byte, 0)) 59 | if err != nil { 60 | log.Printf("Failed cipher %v: %v", i, err) 61 | continue 62 | } 63 | log.Printf("Selected cipher %v", i) 64 | // We don't need to replay the bytes anymore, but we don't want to drop those 65 | // read so far. 66 | return cipher, i, shadowaead.NewShadowsocksReader(io.MultiReader(&buffer, clientReader), cipher), nil 67 | } 68 | return nil, -1, nil, fmt.Errorf("could not find valid cipher") 69 | } 70 | 71 | func getNetKey(addr net.Addr) (string, error) { 72 | host, _, err := net.SplitHostPort(addr.String()) 73 | if err != nil { 74 | return "", err 75 | } 76 | ip := net.ParseIP(host) 77 | if ip == nil { 78 | return "", errors.New("Failed to parse ip") 79 | } 80 | ipNet := net.IPNet{IP: ip} 81 | if ip.To4() != nil { 82 | ipNet.Mask = net.CIDRMask(24, 32) 83 | } else { 84 | ipNet.Mask = net.CIDRMask(32, 128) 85 | } 86 | return ipNet.String(), nil 87 | } 88 | 89 | // Listen on addr for incoming connections. 90 | func tcpRemote(addr string, cipherList []shadowaead.Cipher, m metrics.TCPMetrics) { 91 | accessKeyMetrics := metrics.NewMetricsMap() 92 | netMetrics := metrics.NewMetricsMap() 93 | l, err := net.Listen("tcp", addr) 94 | if err != nil { 95 | log.Printf("failed to listen on %s: %v", addr, err) 96 | return 97 | } 98 | 99 | log.Printf("listening TCP on %s", addr) 100 | for { 101 | var clientConn ssnet.DuplexConn 102 | clientConn, err := l.(*net.TCPListener).AcceptTCP() 103 | m.AddTCPConnection() 104 | if err != nil { 105 | log.Printf("failed to accept: %v", err) 106 | return 107 | } 108 | 109 | go func() { 110 | defer clientConn.Close() 111 | connStart := time.Now() 112 | clientConn.(*net.TCPConn).SetKeepAlive(true) 113 | accessKey := "INVALID" 114 | // TODO: create status enums and move to metrics.go 115 | status := "OK" 116 | netKey, err := getNetKey(clientConn.RemoteAddr()) 117 | if err != nil { 118 | netKey = "INVALID" 119 | } 120 | var proxyMetrics metrics.ProxyMetrics 121 | defer func() { 122 | connEnd := time.Now() 123 | connDuration := connEnd.Sub(connStart) 124 | log.Printf("Done with status %v, duration %v", status, connDuration) 125 | m.RemoveTCPConnection(accessKey, status, connDuration) 126 | accessKeyMetrics.Add(accessKey, proxyMetrics) 127 | log.Printf("Key %v: %s", accessKey, metrics.SPrintMetrics(accessKeyMetrics.Get(accessKey))) 128 | netMetrics.Add(netKey, proxyMetrics) 129 | log.Printf("Net %v: %s", netKey, metrics.SPrintMetrics(netMetrics.Get(netKey))) 130 | }() 131 | 132 | clientConn = metrics.MeasureConn(clientConn, &proxyMetrics.ProxyClient, &proxyMetrics.ClientProxy) 133 | clientConn, index, err := shadowConn(clientConn, cipherList) 134 | if err != nil { 135 | log.Printf("Failed to find a valid cipher: %v", err) 136 | status = "ERR_CIPHER" 137 | return 138 | } 139 | accessKey = strconv.Itoa(index) 140 | 141 | tgt, err := socks.ReadAddr(clientConn) 142 | if err != nil { 143 | log.Printf("failed to get target address: %v", err) 144 | status = "ERR_READ_ADDRESS" 145 | return 146 | } 147 | 148 | c, err := net.Dial("tcp", tgt.String()) 149 | if err != nil { 150 | log.Printf("failed to connect to target: %v", err) 151 | status = "ERR_CONNECT" 152 | return 153 | } 154 | var tgtConn ssnet.DuplexConn = c.(*net.TCPConn) 155 | defer tgtConn.Close() 156 | tgtConn.(*net.TCPConn).SetKeepAlive(true) 157 | tgtConn = metrics.MeasureConn(tgtConn, &proxyMetrics.ProxyTarget, &proxyMetrics.TargetProxy) 158 | 159 | log.Printf("proxy %s <-> %s", clientConn.RemoteAddr(), tgt) 160 | _, _, err = ssnet.Relay(clientConn, tgtConn) 161 | if err != nil { 162 | log.Printf("relay error: %v", err) 163 | status = "ERR_RELAY" 164 | } 165 | }() 166 | } 167 | } 168 | 169 | type cipherList []shadowaead.Cipher 170 | 171 | func main() { 172 | 173 | var flags struct { 174 | Server string 175 | Ciphers cipherList 176 | MetricsAddr string 177 | } 178 | 179 | flag.StringVar(&flags.Server, "s", "", "server listen address") 180 | flag.Var(&flags.Ciphers, "u", "available ciphers: "+strings.Join(core.ListCipher(), " ")) 181 | flag.DurationVar(&config.UDPTimeout, "udptimeout", 5*time.Minute, "UDP tunnel timeout") 182 | flag.StringVar(&flags.MetricsAddr, "metrics", "", "address for the Prometheus metrics") 183 | flag.Parse() 184 | 185 | if flags.Server == "" || len(flags.Ciphers) == 0 { 186 | flag.Usage() 187 | return 188 | } 189 | 190 | if flags.MetricsAddr != "" { 191 | http.Handle("/metrics", promhttp.Handler()) 192 | go func() { 193 | log.Fatal(http.ListenAndServe(flags.MetricsAddr, nil)) 194 | }() 195 | log.Printf("Metrics on http://%v/metrics", flags.MetricsAddr) 196 | } 197 | 198 | go udpRemote(flags.Server, flags.Ciphers) 199 | go tcpRemote(flags.Server, flags.Ciphers, metrics.NewPrometheusTCPMetrics()) 200 | 201 | sigCh := make(chan os.Signal, 1) 202 | signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) 203 | <-sigCh 204 | } 205 | 206 | func (sl *cipherList) Set(flagValue string) error { 207 | e := strings.SplitN(flagValue, ":", 2) 208 | if len(e) != 2 { 209 | return fmt.Errorf("Missing colon") 210 | } 211 | cipher, err := core.PickCipher(e[0], nil, e[1]) 212 | if err != nil { 213 | return err 214 | } 215 | aead, ok := cipher.(shadowaead.Cipher) 216 | if !ok { 217 | log.Fatal("Only AEAD ciphers are supported") 218 | } 219 | *sl = append(*sl, aead) 220 | return nil 221 | } 222 | 223 | func (sl *cipherList) String() string { 224 | return fmt.Sprint(*sl) 225 | } 226 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------