1
0
Fork 0
bypass/request.go

494 lines
12 KiB
Go
Raw Permalink Normal View History

2014-01-24 03:29:13 +08:00
package socks5
import (
2018-02-14 21:42:26 +08:00
"bytes"
2014-01-24 04:04:20 +08:00
"fmt"
"io"
2018-02-14 21:42:26 +08:00
"log"
"math/big"
2014-01-24 03:29:13 +08:00
"net"
"strconv"
2014-01-24 05:42:35 +08:00
"strings"
"golang.org/x/net/context"
2014-01-24 03:29:13 +08:00
)
2014-01-24 04:04:20 +08:00
const (
ConnectCommand = uint8(1)
BindCommand = uint8(2)
AssociateCommand = uint8(3)
2014-01-24 04:04:20 +08:00
ipv4Address = uint8(1)
fqdnAddress = uint8(3)
ipv6Address = uint8(4)
)
const (
2014-02-14 02:49:35 +08:00
successReply uint8 = iota
2014-01-24 04:04:20 +08:00
serverFailure
ruleFailure
networkUnreachable
hostUnreachable
connectionRefused
ttlExpired
commandNotSupported
addrTypeNotSupported
)
var (
unrecognizedAddrType = fmt.Errorf("Unrecognized address type")
)
2014-01-24 08:55:08 +08:00
// AddressRewriter is used to rewrite a destination transparently
type AddressRewriter interface {
Rewrite(ctx context.Context, request *Request) (context.Context, *AddrSpec)
2014-01-24 08:55:08 +08:00
}
2014-01-24 08:46:32 +08:00
// AddrSpec is used to return the target AddrSpec
2014-01-24 04:04:20 +08:00
// which may be specified as IPv4, IPv6, or a FQDN
2014-01-24 08:46:32 +08:00
type AddrSpec struct {
FQDN string
IP net.IP
Port int
2014-01-24 04:04:20 +08:00
}
func (a *AddrSpec) String() string {
if a.FQDN != "" {
return fmt.Sprintf("%s (%s):%d", a.FQDN, a.IP, a.Port)
}
return fmt.Sprintf("%s:%d", a.IP, a.Port)
}
// Address returns a string suitable to dial; prefer returning IP-based
// address, fallback to FQDN
func (a AddrSpec) Address() string {
if 0 != len(a.IP) {
return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port))
}
return net.JoinHostPort(a.FQDN, strconv.Itoa(a.Port))
}
// A Request represents request received by a server
type Request struct {
// Protocol version
Version uint8
// Requested command
Command uint8
// AuthContext provided during negotiation
AuthContext *AuthContext
// AddrSpec of the the network that sent the request
RemoteAddr *AddrSpec
// AddrSpec of the desired destination
DestAddr *AddrSpec
// AddrSpec of the actual destination (might be affected by rewrite)
realDestAddr *AddrSpec
bufConn io.Reader
}
2014-01-24 06:07:39 +08:00
type conn interface {
Write([]byte) (int, error)
RemoteAddr() net.Addr
}
// NewRequest creates a new Request from the tcp connection
func NewRequest(bufConn io.Reader) (*Request, error) {
2014-01-24 04:04:20 +08:00
// Read the version byte
header := []byte{0, 0, 0}
if _, err := io.ReadAtLeast(bufConn, header, 3); err != nil {
return nil, fmt.Errorf("Failed to get command version: %v", err)
2014-01-24 04:04:20 +08:00
}
// Ensure we are compatible
if header[0] != socks5Version {
return nil, fmt.Errorf("Unsupported command version: %v", header[0])
2014-01-24 04:04:20 +08:00
}
// Read in the destination address
dest, err := readAddrSpec(bufConn)
if err != nil {
return nil, err
}
request := &Request{
Version: socks5Version,
Command: header[1],
DestAddr: dest,
bufConn: bufConn,
2014-01-24 04:04:20 +08:00
}
return request, nil
}
// handleRequest is used for request processing after authentication
func (s *Server) handleRequest(req *Request, conn conn) error {
ctx := context.Background()
2014-01-24 05:11:58 +08:00
// Resolve the address if we have a FQDN
dest := req.DestAddr
2014-01-24 08:46:32 +08:00
if dest.FQDN != "" {
ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
2014-01-24 05:11:58 +08:00
if err != nil {
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, hostUnreachable, nil); err != nil {
2014-01-24 05:11:58 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-24 08:46:32 +08:00
return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err)
2014-01-24 05:11:58 +08:00
}
ctx = ctx_
2014-01-24 08:46:32 +08:00
dest.IP = addr
2014-01-24 05:11:58 +08:00
}
2014-01-24 08:55:08 +08:00
// Apply any address rewrites
req.realDestAddr = req.DestAddr
2014-01-24 08:55:08 +08:00
if s.config.Rewriter != nil {
ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
2014-01-24 08:55:08 +08:00
}
2014-01-24 08:46:32 +08:00
2014-01-24 04:04:20 +08:00
// Switch on the command
switch req.Command {
case ConnectCommand:
return s.handleConnect(ctx, conn, req)
case BindCommand:
return s.handleBind(ctx, conn, req)
case AssociateCommand:
return s.handleAssociate(ctx, conn, req)
2014-01-24 04:04:20 +08:00
default:
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-24 05:42:35 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Unsupported command: %v", req.Command)
2014-01-24 04:04:20 +08:00
}
}
// handleConnect is used to handle a connect command
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error {
2014-01-24 05:11:58 +08:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-24 05:11:58 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-24 05:11:58 +08:00
}
2014-01-24 05:42:35 +08:00
// Attempt to connect
2016-02-05 03:25:27 +08:00
dial := s.config.Dial
if dial == nil {
dial = func(ctx context.Context, net_, addr string) (net.Conn, error) {
return net.Dial(net_, addr)
}
2016-02-05 03:25:27 +08:00
}
target, err := dial(ctx, "tcp", req.realDestAddr.Address())
2014-01-24 05:42:35 +08:00
if err != nil {
msg := err.Error()
resp := hostUnreachable
if strings.Contains(msg, "refused") {
resp = connectionRefused
} else if strings.Contains(msg, "network is unreachable") {
resp = networkUnreachable
}
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, resp, nil); err != nil {
2014-01-24 05:42:35 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err)
2014-01-24 05:42:35 +08:00
}
defer target.Close()
// Send success
2014-01-25 06:31:58 +08:00
local := target.LocalAddr().(*net.TCPAddr)
bind := AddrSpec{IP: local.IP, Port: local.Port}
if err := sendReply(conn, successReply, &bind); err != nil {
2014-01-24 05:42:35 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
// Start proxying
errCh := make(chan error, 2)
go proxy(target, req.bufConn, errCh)
go proxy(conn, target, errCh)
2014-01-24 05:42:35 +08:00
// Wait
for i := 0; i < 2; i++ {
e := <-errCh
if e != nil {
// return from this function closes target (and conn).
return e
}
2014-01-24 05:42:35 +08:00
}
return nil
2014-01-24 04:04:20 +08:00
}
// handleBind is used to handle a connect command
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error {
2014-01-24 05:11:58 +08:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-24 05:11:58 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Bind to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-24 05:11:58 +08:00
}
2014-01-24 05:42:35 +08:00
// TODO: Support bind
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-24 05:42:35 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-24 04:04:20 +08:00
return nil
}
// handleAssociate is used to handle a connect command
func (s *Server) handleAssociate(ctx context.Context, conn conn, req *Request) error {
2014-01-24 05:11:58 +08:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-24 05:11:58 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Associate to %v blocked by rules", req.DestAddr)
} else {
ctx = ctx_
2014-01-24 05:11:58 +08:00
}
2014-01-24 05:42:35 +08:00
// TODO: Support associate
2014-01-25 06:31:58 +08:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-24 05:42:35 +08:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-24 03:29:13 +08:00
return nil
}
2014-01-24 04:04:20 +08:00
2014-01-24 08:46:32 +08:00
// readAddrSpec is used to read AddrSpec.
2014-01-24 04:04:20 +08:00
// Expects an address type byte, follwed by the address and port
2014-01-24 08:46:32 +08:00
func readAddrSpec(r io.Reader) (*AddrSpec, error) {
d := &AddrSpec{}
2014-01-24 04:04:20 +08:00
// Get the address type
addrType := []byte{0}
if _, err := r.Read(addrType); err != nil {
return nil, err
}
// Handle on a per type basis
switch addrType[0] {
case ipv4Address:
addr := make([]byte, 4)
if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
return nil, err
}
2014-01-24 08:46:32 +08:00
d.IP = net.IP(addr)
2014-01-24 04:04:20 +08:00
case ipv6Address:
addr := make([]byte, 16)
if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
return nil, err
}
2014-01-24 08:46:32 +08:00
d.IP = net.IP(addr)
2014-01-24 04:04:20 +08:00
case fqdnAddress:
if _, err := r.Read(addrType); err != nil {
return nil, err
}
addrLen := int(addrType[0])
fqdn := make([]byte, addrLen)
if _, err := io.ReadAtLeast(r, fqdn, addrLen); err != nil {
return nil, err
}
2014-01-24 08:46:32 +08:00
d.FQDN = string(fqdn)
2014-01-24 04:04:20 +08:00
default:
return nil, unrecognizedAddrType
}
// Read the port
port := []byte{0, 0}
if _, err := io.ReadAtLeast(r, port, 2); err != nil {
return nil, err
}
2014-01-25 06:31:58 +08:00
d.Port = (int(port[0]) << 8) | int(port[1])
2014-01-24 04:04:20 +08:00
return d, nil
}
// sendReply is used to send a reply message
2014-01-24 08:46:32 +08:00
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error {
2014-01-24 04:04:20 +08:00
// Format the address
var addrType uint8
var addrBody []byte
2014-01-24 08:23:59 +08:00
var addrPort uint16
2014-01-24 04:04:20 +08:00
switch {
case addr == nil:
addrType = ipv4Address
addrBody = []byte{0, 0, 0, 0}
addrPort = 0
2014-01-24 04:04:20 +08:00
2014-01-24 08:46:32 +08:00
case addr.FQDN != "":
2014-01-24 04:04:20 +08:00
addrType = fqdnAddress
2014-01-24 08:46:32 +08:00
addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...)
addrPort = uint16(addr.Port)
2014-01-24 04:04:20 +08:00
2014-01-24 08:46:32 +08:00
case addr.IP.To4() != nil:
2014-01-24 04:04:20 +08:00
addrType = ipv4Address
2014-01-24 08:46:32 +08:00
addrBody = []byte(addr.IP.To4())
addrPort = uint16(addr.Port)
2014-01-24 04:04:20 +08:00
2014-01-24 08:46:32 +08:00
case addr.IP.To16() != nil:
2014-01-24 04:04:20 +08:00
addrType = ipv6Address
2014-01-24 08:46:32 +08:00
addrBody = []byte(addr.IP.To16())
addrPort = uint16(addr.Port)
2014-01-24 04:04:20 +08:00
default:
return fmt.Errorf("Failed to format address: %v", addr)
}
// Format the message
msg := make([]byte, 6+len(addrBody))
msg[0] = socks5Version
msg[1] = resp
msg[2] = 0 // Reserved
msg[3] = addrType
copy(msg[4:], addrBody)
2014-01-25 06:31:58 +08:00
msg[4+len(addrBody)] = byte(addrPort >> 8)
msg[4+len(addrBody)+1] = byte(addrPort & 0xff)
2014-01-24 04:04:20 +08:00
// Send the message
_, err := w.Write(msg)
return err
}
2014-01-24 05:42:35 +08:00
type closeWriter interface {
CloseWrite() error
}
2014-01-24 05:42:35 +08:00
// proxy is used to suffle data from src to destination, and sends errors
// down a dedicated channel
func proxy(dst io.Writer, src io.Reader, errCh chan error) {
2017-09-18 19:16:52 +08:00
//_, err := io.Copy(dst, src)
_, err := copyAndModify(dst, src)
if tcpConn, ok := dst.(closeWriter); ok {
tcpConn.CloseWrite()
}
2014-01-24 06:07:39 +08:00
errCh <- err
2014-01-24 05:42:35 +08:00
}
2017-09-18 19:16:52 +08:00
func copyAndModify(dst io.Writer, src io.Reader) (written int64, err error) {
// based on copyBuffer in io.go
buf := make([]byte, 32*1024)
for {
nr, er := src.Read(buf)
if written == 0 && nr > 0 {
2018-02-14 21:42:26 +08:00
if buf[0] == 0x16 && buf[5] == 0x01 { // && buf[1] == 0x03 && buf[2] == 0x01) {
modifyHello(buf)
2017-09-18 19:16:52 +08:00
}
}
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
}
func modifyHello(buf []byte) {
// 1 byte content type
// 2 byte tls version
// 2 byte tls frame length
frameLength := big.NewInt(0)
frameLength.SetBytes(buf[3:5])
// 1 byte handshake type
// 3 byte handshake length
handshakeLength := big.NewInt(0)
handshakeLength.SetBytes(buf[6:9])
// 2 byte version
// 32 byte random
// 1 byte session id length
sessionLength := big.NewInt(0)
sessionLength.SetBytes(buf[43:44])
// session id
// 2 byte cipher suites length (in bytes)
suitesLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
suitesLength.SetBytes(buf[44+sessionLength.Uint64() : 44+sessionLength.Uint64()+2])
2017-09-18 19:16:52 +08:00
// cipher suites
// 1 byte compression methods length
// 1 byte compression method
// 2 byte extensions length
extensionsLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
extensionsLength.SetBytes(buf[48+sessionLength.Uint64()+suitesLength.Uint64() : 48+sessionLength.Uint64()+suitesLength.Uint64()+2])
2017-09-18 19:16:52 +08:00
// extensions:
extensionsStart := 50 + sessionLength.Uint64() + suitesLength.Uint64()
extensionsEnd := extensionsStart + extensionsLength.Uint64()
cur := extensionsStart
2018-02-14 21:42:26 +08:00
for cur+4 < extensionsEnd {
if buf[cur] != 0x00 || buf[cur+1] != 0x00 {
2017-09-18 19:16:52 +08:00
extensionLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
extensionLength.SetBytes(buf[cur+2 : cur+4])
2017-09-18 19:16:52 +08:00
cur += 4 + extensionLength.Uint64()
continue
}
// yay is sni header!
extensionLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
extensionLength.SetBytes(buf[cur+2 : cur+4])
2017-09-18 19:16:52 +08:00
// 2 byte sni list length
listLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
listLength.SetBytes(buf[cur+4 : cur+6])
2017-09-18 19:16:52 +08:00
var list []string
listStart := cur + 6
listEnd := cur + 6 + listLength.Uint64()
lcur := listStart
2018-02-14 21:42:26 +08:00
for lcur+3 < listEnd {
2017-09-18 19:16:52 +08:00
// 1 byte type
// 2 byte length
nameLength := big.NewInt(0)
2018-02-14 21:42:26 +08:00
nameLength.SetBytes(buf[lcur+1 : lcur+3])
2017-09-18 19:16:52 +08:00
//buf[lcur+3] = 'x'
// name
var name bytes.Buffer
2018-02-14 21:42:26 +08:00
name.Write(buf[lcur+3 : lcur+3+nameLength.Uint64()])
2017-09-18 19:16:52 +08:00
name.WriteByte(0)
// append to list
list = append(list, name.String())
lcur += 3 + nameLength.Uint64()
}
2018-02-14 21:42:26 +08:00
log.Println(list)
2017-09-18 19:16:52 +08:00
break
}
// 2 byte extension type
// 2 byte extension length
// extension data
2018-02-14 21:42:26 +08:00
2017-09-18 19:16:52 +08:00
}