go-socks5/request.go

326 lines
8.1 KiB
Go
Raw Normal View History

2014-01-23 19:29:13 +00:00
package socks5
import (
2020-04-19 09:08:22 +00:00
"context"
2014-01-23 20:04:20 +00:00
"fmt"
"io"
2014-01-23 19:29:13 +00:00
"net"
2014-01-23 21:42:35 +00:00
"strings"
2014-01-23 19:29:13 +00:00
)
2014-01-23 20:04:20 +00:00
var (
unrecognizedAddrType = fmt.Errorf("Unrecognized address type")
)
// A Request represents request received by a server
type Request struct {
2020-04-19 13:37:05 +00:00
Header
// 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-23 22:07:39 +00: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-23 20:04:20 +00: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-23 20:04:20 +00:00
}
// Ensure we are compatible
if header[0] != socks5Version {
return nil, fmt.Errorf("Unsupported command version: %v", header[0])
2014-01-23 20:04:20 +00:00
}
// Read in the destination address
dest, err := readAddrSpec(bufConn)
if err != nil {
return nil, err
}
2020-04-19 13:37:05 +00:00
return &Request{
Version: socks5Version,
Command: header[1],
DestAddr: dest,
bufConn: bufConn,
2020-04-19 13:37:05 +00:00
}, nil
//hd, err := Parse(bufConn)
//if err != nil {
// return nil, err
//}
//return &Request{
// Version: hd.Version,
// Command: hd.Command,
// DestAddr: &hd.Address,
// bufConn: bufConn,
//}, nil
}
// handleRequest is used for request processing after authentication
func (s *Server) handleRequest(req *Request, conn conn) error {
ctx := context.Background()
2014-01-23 21:11:58 +00:00
// Resolve the address if we have a FQDN
dest := req.DestAddr
2014-01-24 00:46:32 +00:00
if dest.FQDN != "" {
ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
2014-01-23 21:11:58 +00:00
if err != nil {
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, hostUnreachable, nil); err != nil {
2014-01-23 21:11:58 +00:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-24 00:46:32 +00:00
return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err)
2014-01-23 21:11:58 +00:00
}
ctx = ctx_
2014-01-24 00:46:32 +00:00
dest.IP = addr
2014-01-23 21:11:58 +00:00
}
2014-01-24 00:55:08 +00:00
// Apply any address rewrites
req.realDestAddr = req.DestAddr
2014-01-24 00:55:08 +00:00
if s.config.Rewriter != nil {
ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
2014-01-24 00:55:08 +00:00
}
2014-01-24 00:46:32 +00:00
2014-01-23 20:04:20 +00: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-23 20:04:20 +00:00
default:
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-23 21:42:35 +00:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Unsupported command: %v", req.Command)
2014-01-23 20:04:20 +00:00
}
}
// handleConnect is used to handle a connect command
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error {
2014-01-23 21:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-23 21:11:58 +00: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-23 21:11:58 +00:00
}
2014-01-23 21:42:35 +00:00
// Attempt to connect
2016-02-04 19:25:27 +00: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-04 19:25:27 +00:00
}
target, err := dial(ctx, "tcp", req.realDestAddr.Address())
2014-01-23 21:42:35 +00: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-24 22:31:58 +00:00
if err := sendReply(conn, resp, nil); err != nil {
2014-01-23 21:42:35 +00:00
return fmt.Errorf("Failed to send reply: %v", err)
}
return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err)
2014-01-23 21:42:35 +00:00
}
defer target.Close()
// Send success
if err := sendReply(conn, successReply, addrSpecFromNetAddr(target.LocalAddr())); err != nil {
2014-01-23 21:42:35 +00: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-23 21:42:35 +00: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-23 21:42:35 +00:00
}
return nil
2014-01-23 20:04:20 +00:00
}
// handleBind is used to handle a connect command
func (s *Server) handleBind(ctx context.Context, conn conn, req *Request) error {
2014-01-23 21:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-23 21:11:58 +00: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-23 21:11:58 +00:00
}
2014-01-23 21:42:35 +00:00
// TODO: Support bind
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-23 21:42:35 +00:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-23 20:04:20 +00: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-23 21:11:58 +00:00
// Check if this is allowed
if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, ruleFailure, nil); err != nil {
2014-01-23 21:11:58 +00: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-23 21:11:58 +00:00
}
2014-01-23 21:42:35 +00:00
// TODO: Support associate
2014-01-24 22:31:58 +00:00
if err := sendReply(conn, commandNotSupported, nil); err != nil {
2014-01-23 21:42:35 +00:00
return fmt.Errorf("Failed to send reply: %v", err)
}
2014-01-23 19:29:13 +00:00
return nil
}
2014-01-23 20:04:20 +00:00
2014-01-24 00:46:32 +00:00
// readAddrSpec is used to read AddrSpec.
2014-01-23 20:04:20 +00:00
// Expects an address type byte, follwed by the address and port
2014-01-24 00:46:32 +00:00
func readAddrSpec(r io.Reader) (*AddrSpec, error) {
d := &AddrSpec{}
2014-01-23 20:04:20 +00: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 00:46:32 +00:00
d.IP = net.IP(addr)
2014-01-23 20:04:20 +00:00
case ipv6Address:
addr := make([]byte, 16)
if _, err := io.ReadAtLeast(r, addr, len(addr)); err != nil {
return nil, err
}
2014-01-24 00:46:32 +00:00
d.IP = net.IP(addr)
2014-01-23 20:04:20 +00: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 00:46:32 +00:00
d.FQDN = string(fqdn)
2014-01-23 20:04:20 +00: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-24 22:31:58 +00:00
d.Port = (int(port[0]) << 8) | int(port[1])
2014-01-23 20:04:20 +00:00
return d, nil
}
func addrSpecFromNetAddr(addr net.Addr) *AddrSpec {
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
return &AddrSpec{IP: tcpAddr.IP, Port: tcpAddr.Port}
}
return nil
}
2014-01-23 20:04:20 +00:00
// sendReply is used to send a reply message
2014-01-24 00:46:32 +00:00
func sendReply(w io.Writer, resp uint8, addr *AddrSpec) error {
2020-04-19 13:37:05 +00:00
var head Header
2014-01-23 20:04:20 +00:00
// Format the address
var addrBody []byte
2014-01-24 00:23:59 +00:00
var addrPort uint16
2020-04-19 13:37:05 +00:00
head.Version = socks5Version
head.Command = resp
head.Reserved = 0
2014-01-23 20:04:20 +00:00
switch {
case addr == nil:
2020-04-19 13:37:05 +00:00
head.addrType = ipv4Address
addrBody = []byte{0, 0, 0, 0}
addrPort = 0
2014-01-23 20:04:20 +00:00
2014-01-24 00:46:32 +00:00
case addr.FQDN != "":
2020-04-19 13:37:05 +00:00
head.addrType = fqdnAddress
2014-01-24 00:46:32 +00:00
addrBody = append([]byte{byte(len(addr.FQDN))}, addr.FQDN...)
addrPort = uint16(addr.Port)
2014-01-23 20:04:20 +00:00
2014-01-24 00:46:32 +00:00
case addr.IP.To4() != nil:
2020-04-19 13:37:05 +00:00
head.addrType = ipv4Address
addrBody = addr.IP.To4()
2014-01-24 00:46:32 +00:00
addrPort = uint16(addr.Port)
2014-01-23 20:04:20 +00:00
2014-01-24 00:46:32 +00:00
case addr.IP.To16() != nil:
2020-04-19 13:37:05 +00:00
head.addrType = ipv6Address
addrBody = addr.IP.To16()
2014-01-24 00:46:32 +00:00
addrPort = uint16(addr.Port)
2014-01-23 20:04:20 +00:00
default:
return fmt.Errorf("Failed to format address: %v", addr)
}
// Format the message
2020-04-19 13:37:05 +00:00
msg := make([]byte, 0, 6+len(addrBody))
msg = append(msg, head.Version, head.Command, head.Reserved, head.addrType)
msg = append(msg, addrBody...)
msg = append(msg, byte(addrPort>>8), byte(addrPort&0xff))
2014-01-23 20:04:20 +00:00
// Send the message
_, err := w.Write(msg)
return err
}
2014-01-23 21:42:35 +00:00
type closeWriter interface {
CloseWrite() error
}
2014-01-23 21:42:35 +00: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) {
_, err := io.Copy(dst, src)
if tcpConn, ok := dst.(closeWriter); ok {
tcpConn.CloseWrite()
}
2014-01-23 22:07:39 +00:00
errCh <- err
2014-01-23 21:42:35 +00:00
}