2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2021-02-26 21:38:59 +00:00
|
|
|
|
2021-06-28 18:29:25 +00:00
|
|
|
// Package socks5 is a SOCKS5 server implementation.
|
|
|
|
//
|
|
|
|
// This is used for userspace networking in Tailscale. Specifically,
|
|
|
|
// this is used for dialing out of the machine to other nodes, without
|
|
|
|
// the host kernel's involvement, so it doesn't proper routing tables,
|
|
|
|
// TUN, IPv6, etc. This package is meant to only handle the SOCKS5 protocol
|
|
|
|
// details and not any integration with Tailscale internals itself.
|
|
|
|
//
|
|
|
|
// The glue between this package and Tailscale is in net/socks5/tssocks.
|
2021-02-26 21:38:59 +00:00
|
|
|
package socks5
|
|
|
|
|
|
|
|
import (
|
2024-06-25 15:40:42 +00:00
|
|
|
"bytes"
|
2021-02-26 21:38:59 +00:00
|
|
|
"context"
|
|
|
|
"encoding/binary"
|
2024-06-25 15:40:42 +00:00
|
|
|
"errors"
|
2021-02-26 21:38:59 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"log"
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"tailscale.com/types/logger"
|
|
|
|
)
|
|
|
|
|
2023-03-05 20:28:27 +00:00
|
|
|
// Authentication METHODs described in RFC 1928, section 3.
|
2021-02-26 21:38:59 +00:00
|
|
|
const (
|
|
|
|
noAuthRequired byte = 0
|
2023-03-05 20:28:27 +00:00
|
|
|
passwordAuth byte = 2
|
2021-02-26 21:38:59 +00:00
|
|
|
noAcceptableAuth byte = 255
|
|
|
|
)
|
|
|
|
|
2023-03-05 20:28:27 +00:00
|
|
|
// passwordAuthVersion is the auth version byte described in RFC 1929.
|
|
|
|
const passwordAuthVersion = 1
|
|
|
|
|
|
|
|
// socks5Version is the byte that represents the SOCKS version
|
|
|
|
// in requests.
|
|
|
|
const socks5Version byte = 5
|
|
|
|
|
2021-02-26 21:38:59 +00:00
|
|
|
// commandType are the bytes sent in SOCKS5 packets
|
|
|
|
// that represent the kind of connection the client needs.
|
|
|
|
type commandType byte
|
|
|
|
|
2021-06-24 05:08:47 +00:00
|
|
|
// The set of valid SOCKS5 commands as described in RFC 1928.
|
2021-02-26 21:38:59 +00:00
|
|
|
const (
|
|
|
|
connect commandType = 1
|
|
|
|
bind commandType = 2
|
|
|
|
udpAssociate commandType = 3
|
|
|
|
)
|
|
|
|
|
|
|
|
// addrType are the bytes sent in SOCKS5 packets
|
|
|
|
// that represent particular address types.
|
|
|
|
type addrType byte
|
|
|
|
|
|
|
|
// The set of valid SOCKS5 address types as defined in RFC 1928.
|
|
|
|
const (
|
|
|
|
ipv4 addrType = 1
|
|
|
|
domainName addrType = 3
|
|
|
|
ipv6 addrType = 4
|
|
|
|
)
|
|
|
|
|
|
|
|
// replyCode are the bytes sent in SOCKS5 packets
|
|
|
|
// that represent replies from the server to a client
|
|
|
|
// request.
|
|
|
|
type replyCode byte
|
|
|
|
|
|
|
|
// The set of valid SOCKS5 reply types as per the RFC 1928.
|
|
|
|
const (
|
|
|
|
success replyCode = 0
|
|
|
|
generalFailure replyCode = 1
|
|
|
|
connectionNotAllowed replyCode = 2
|
|
|
|
networkUnreachable replyCode = 3
|
|
|
|
hostUnreachable replyCode = 4
|
|
|
|
connectionRefused replyCode = 5
|
|
|
|
ttlExpired replyCode = 6
|
|
|
|
commandNotSupported replyCode = 7
|
|
|
|
addrTypeNotSupported replyCode = 8
|
|
|
|
)
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
// UDP conn default buffer size and read timeout.
|
|
|
|
const (
|
|
|
|
bufferSize = 8 * 1024
|
|
|
|
readTimeout = 5 * time.Second
|
|
|
|
)
|
|
|
|
|
2021-02-26 21:38:59 +00:00
|
|
|
// Server is a SOCKS5 proxy server.
|
|
|
|
type Server struct {
|
|
|
|
// Logf optionally specifies the logger to use.
|
|
|
|
// If nil, the standard logger is used.
|
|
|
|
Logf logger.Logf
|
|
|
|
|
|
|
|
// Dialer optionally specifies the dialer to use for outgoing connections.
|
|
|
|
// If nil, the net package's standard dialer is used.
|
|
|
|
Dialer func(ctx context.Context, network, addr string) (net.Conn, error)
|
2023-03-05 20:28:27 +00:00
|
|
|
|
|
|
|
// Username and Password, if set, are the credential clients must provide.
|
|
|
|
Username string
|
|
|
|
Password string
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) dial(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
|
|
dial := s.Dialer
|
|
|
|
if dial == nil {
|
|
|
|
dialer := &net.Dialer{}
|
|
|
|
dial = dialer.DialContext
|
|
|
|
}
|
|
|
|
return dial(ctx, network, addr)
|
|
|
|
}
|
|
|
|
|
2022-03-16 23:27:57 +00:00
|
|
|
func (s *Server) logf(format string, args ...any) {
|
2021-02-26 21:38:59 +00:00
|
|
|
logf := s.Logf
|
|
|
|
if logf == nil {
|
|
|
|
logf = log.Printf
|
|
|
|
}
|
|
|
|
logf(format, args...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Serve accepts and handles incoming connections on the given listener.
|
|
|
|
func (s *Server) Serve(l net.Listener) error {
|
|
|
|
defer l.Close()
|
|
|
|
for {
|
|
|
|
c, err := l.Accept()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
go func() {
|
2022-03-08 20:44:23 +00:00
|
|
|
defer c.Close()
|
2024-06-25 15:40:42 +00:00
|
|
|
conn := &Conn{logf: s.Logf, clientConn: c, srv: s}
|
2021-02-26 21:38:59 +00:00
|
|
|
err := conn.Run()
|
|
|
|
if err != nil {
|
2021-03-01 18:08:53 +00:00
|
|
|
s.logf("client connection failed: %v", err)
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Conn is a SOCKS5 connection for client to reach
|
|
|
|
// server.
|
|
|
|
type Conn struct {
|
|
|
|
// The struct is filled by each of the internal
|
|
|
|
// methods in turn as the transaction progresses.
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
logf logger.Logf
|
2021-02-26 21:38:59 +00:00
|
|
|
srv *Server
|
|
|
|
clientConn net.Conn
|
|
|
|
request *request
|
2024-06-25 15:40:42 +00:00
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
udpClientAddr net.Addr
|
2024-09-21 06:37:51 +00:00
|
|
|
udpTargetConns map[socksAddr]net.Conn
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Run starts the new connection.
|
|
|
|
func (c *Conn) Run() error {
|
2023-03-05 20:28:27 +00:00
|
|
|
needAuth := c.srv.Username != "" || c.srv.Password != ""
|
|
|
|
authMethod := noAuthRequired
|
|
|
|
if needAuth {
|
|
|
|
authMethod = passwordAuth
|
|
|
|
}
|
|
|
|
|
|
|
|
err := parseClientGreeting(c.clientConn, authMethod)
|
2021-02-26 21:38:59 +00:00
|
|
|
if err != nil {
|
|
|
|
c.clientConn.Write([]byte{socks5Version, noAcceptableAuth})
|
|
|
|
return err
|
|
|
|
}
|
2023-03-05 20:28:27 +00:00
|
|
|
c.clientConn.Write([]byte{socks5Version, authMethod})
|
|
|
|
if !needAuth {
|
|
|
|
return c.handleRequest()
|
|
|
|
}
|
|
|
|
|
|
|
|
user, pwd, err := parseClientAuth(c.clientConn)
|
|
|
|
if err != nil || user != c.srv.Username || pwd != c.srv.Password {
|
|
|
|
c.clientConn.Write([]byte{1, 1}) // auth error
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
c.clientConn.Write([]byte{1, 0}) // auth success
|
|
|
|
|
2021-02-26 21:38:59 +00:00
|
|
|
return c.handleRequest()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) handleRequest() error {
|
|
|
|
req, err := parseClientRequest(c.clientConn)
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
res := errorResponse(generalFailure)
|
2021-02-26 21:38:59 +00:00
|
|
|
buf, _ := res.marshal()
|
|
|
|
c.clientConn.Write(buf)
|
|
|
|
return err
|
|
|
|
}
|
2024-06-25 15:40:42 +00:00
|
|
|
|
|
|
|
c.request = req
|
|
|
|
switch req.command {
|
|
|
|
case connect:
|
|
|
|
return c.handleTCP()
|
|
|
|
case udpAssociate:
|
|
|
|
return c.handleUDP()
|
|
|
|
default:
|
|
|
|
res := errorResponse(commandNotSupported)
|
2021-02-26 21:38:59 +00:00
|
|
|
buf, _ := res.marshal()
|
|
|
|
c.clientConn.Write(buf)
|
|
|
|
return fmt.Errorf("unsupported command %v", req.command)
|
|
|
|
}
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
2021-02-26 21:38:59 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
func (c *Conn) handleTCP() error {
|
2021-02-26 21:38:59 +00:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
srv, err := c.srv.dial(
|
|
|
|
ctx,
|
|
|
|
"tcp",
|
2024-06-25 15:40:42 +00:00
|
|
|
c.request.destination.hostPort(),
|
2021-02-26 21:38:59 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
res := errorResponse(generalFailure)
|
2021-02-26 21:38:59 +00:00
|
|
|
buf, _ := res.marshal()
|
|
|
|
c.clientConn.Write(buf)
|
|
|
|
return err
|
|
|
|
}
|
2021-03-01 18:08:53 +00:00
|
|
|
defer srv.Close()
|
2024-06-25 15:40:42 +00:00
|
|
|
|
|
|
|
localAddr := srv.LocalAddr().String()
|
|
|
|
serverAddr, serverPort, err := splitHostPort(localAddr)
|
2021-02-26 21:38:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
res := &response{
|
2024-06-25 15:40:42 +00:00
|
|
|
reply: success,
|
|
|
|
bindAddr: socksAddr{
|
|
|
|
addrType: getAddrType(serverAddr),
|
|
|
|
addr: serverAddr,
|
|
|
|
port: serverPort,
|
|
|
|
},
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
buf, err := res.marshal()
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
res = errorResponse(generalFailure)
|
2021-02-26 21:38:59 +00:00
|
|
|
buf, _ = res.marshal()
|
|
|
|
}
|
|
|
|
c.clientConn.Write(buf)
|
2021-03-01 18:08:53 +00:00
|
|
|
|
|
|
|
errc := make(chan error, 2)
|
|
|
|
go func() {
|
|
|
|
_, err := io.Copy(c.clientConn, srv)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("from backend to client: %w", err)
|
|
|
|
}
|
|
|
|
errc <- err
|
|
|
|
}()
|
|
|
|
go func() {
|
|
|
|
_, err := io.Copy(srv, c.clientConn)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("from client to backend: %w", err)
|
|
|
|
}
|
|
|
|
errc <- err
|
|
|
|
}()
|
|
|
|
return <-errc
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
func (c *Conn) handleUDP() error {
|
|
|
|
// The DST.ADDR and DST.PORT fields contain the address and port that
|
|
|
|
// the client expects to use to send UDP datagrams on for the
|
|
|
|
// association. The server MAY use this information to limit access
|
|
|
|
// to the association.
|
|
|
|
// @see Page 6, https://datatracker.ietf.org/doc/html/rfc1928.
|
|
|
|
//
|
|
|
|
// We do NOT limit the access from the client currently in this implementation.
|
|
|
|
_ = c.request.destination
|
|
|
|
|
|
|
|
addr := c.clientConn.LocalAddr()
|
|
|
|
host, _, err := net.SplitHostPort(addr.String())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
clientUDPConn, err := net.ListenPacket("udp", net.JoinHostPort(host, "0"))
|
|
|
|
if err != nil {
|
|
|
|
res := errorResponse(generalFailure)
|
|
|
|
buf, _ := res.marshal()
|
|
|
|
c.clientConn.Write(buf)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer clientUDPConn.Close()
|
|
|
|
|
|
|
|
bindAddr, bindPort, err := splitHostPort(clientUDPConn.LocalAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
res := &response{
|
|
|
|
reply: success,
|
|
|
|
bindAddr: socksAddr{
|
|
|
|
addrType: getAddrType(bindAddr),
|
|
|
|
addr: bindAddr,
|
|
|
|
port: bindPort,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
buf, err := res.marshal()
|
|
|
|
if err != nil {
|
|
|
|
res = errorResponse(generalFailure)
|
|
|
|
buf, _ = res.marshal()
|
|
|
|
}
|
|
|
|
c.clientConn.Write(buf)
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
return c.transferUDP(c.clientConn, clientUDPConn)
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
func (c *Conn) transferUDP(associatedTCP net.Conn, clientConn net.PacketConn) error {
|
2024-06-25 15:40:42 +00:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
2024-09-20 15:52:45 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
// client -> target
|
|
|
|
go func() {
|
|
|
|
defer cancel()
|
2024-09-21 06:37:51 +00:00
|
|
|
|
|
|
|
c.udpTargetConns = make(map[socksAddr]net.Conn)
|
|
|
|
// close all target udp connections when the client connection is closed
|
|
|
|
defer func() {
|
|
|
|
for _, conn := range c.udpTargetConns {
|
|
|
|
_ = conn.Close()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
buf := make([]byte, bufferSize)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
2024-09-20 15:52:45 +00:00
|
|
|
err := c.handleUDPRequest(ctx, clientConn, buf)
|
2024-06-25 15:40:42 +00:00
|
|
|
if err != nil {
|
|
|
|
if isTimeout(err) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if errors.Is(err, net.ErrClosed) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
c.logf("udp transfer: handle udp request fail: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
// A UDP association terminates when the TCP connection that the UDP
|
|
|
|
// ASSOCIATE request arrived on terminates. RFC1928
|
|
|
|
_, err := io.Copy(io.Discard, associatedTCP)
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("udp associated tcp conn: %w", err)
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) getOrDialTargetConn(
|
|
|
|
ctx context.Context,
|
|
|
|
clientConn net.PacketConn,
|
2024-09-21 06:37:51 +00:00
|
|
|
targetAddr socksAddr,
|
2024-09-20 15:52:45 +00:00
|
|
|
) (net.Conn, error) {
|
2024-09-21 06:37:51 +00:00
|
|
|
conn, exist := c.udpTargetConns[targetAddr]
|
|
|
|
if exist {
|
2024-09-20 15:52:45 +00:00
|
|
|
return conn, nil
|
|
|
|
}
|
2024-09-21 06:37:51 +00:00
|
|
|
conn, err := c.srv.dial(ctx, "udp", targetAddr.hostPort())
|
2024-09-20 15:52:45 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-09-21 06:37:51 +00:00
|
|
|
c.udpTargetConns[targetAddr] = conn
|
2024-09-20 15:52:45 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
// target -> client
|
|
|
|
go func() {
|
|
|
|
buf := make([]byte, bufferSize)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
2024-09-21 06:37:51 +00:00
|
|
|
err := c.handleUDPResponse(clientConn, targetAddr, conn, buf)
|
2024-06-25 15:40:42 +00:00
|
|
|
if err != nil {
|
|
|
|
if isTimeout(err) {
|
|
|
|
continue
|
|
|
|
}
|
2024-09-20 15:52:45 +00:00
|
|
|
if errors.Is(err, net.ErrClosed) || errors.Is(err, io.EOF) {
|
2024-06-25 15:40:42 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
c.logf("udp transfer: handle udp response fail: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
return conn, nil
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) handleUDPRequest(
|
2024-09-20 15:52:45 +00:00
|
|
|
ctx context.Context,
|
2024-06-25 15:40:42 +00:00
|
|
|
clientConn net.PacketConn,
|
|
|
|
buf []byte,
|
|
|
|
) error {
|
|
|
|
// add a deadline for the read to avoid blocking forever
|
|
|
|
_ = clientConn.SetReadDeadline(time.Now().Add(readTimeout))
|
|
|
|
n, addr, err := clientConn.ReadFrom(buf)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("read from client: %w", err)
|
|
|
|
}
|
|
|
|
c.udpClientAddr = addr
|
|
|
|
req, data, err := parseUDPRequest(buf[:n])
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("parse udp request: %w", err)
|
|
|
|
}
|
2024-09-20 15:52:45 +00:00
|
|
|
|
2024-09-21 06:37:51 +00:00
|
|
|
targetConn, err := c.getOrDialTargetConn(ctx, clientConn, req.addr)
|
2024-06-25 15:40:42 +00:00
|
|
|
if err != nil {
|
2024-09-21 06:37:51 +00:00
|
|
|
return fmt.Errorf("dial target %s fail: %w", req.addr, err)
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
|
|
|
|
2024-09-20 15:52:45 +00:00
|
|
|
nn, err := targetConn.Write(data)
|
2024-06-25 15:40:42 +00:00
|
|
|
if err != nil {
|
2024-09-21 06:37:51 +00:00
|
|
|
return fmt.Errorf("write to target %s fail: %w", req.addr, err)
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
|
|
|
if nn != len(data) {
|
2024-09-21 06:37:51 +00:00
|
|
|
return fmt.Errorf("write to target %s fail: %w", req.addr, io.ErrShortWrite)
|
2024-06-25 15:40:42 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) handleUDPResponse(
|
|
|
|
clientConn net.PacketConn,
|
2024-09-20 15:52:45 +00:00
|
|
|
targetAddr socksAddr,
|
|
|
|
targetConn net.Conn,
|
2024-06-25 15:40:42 +00:00
|
|
|
buf []byte,
|
|
|
|
) error {
|
|
|
|
// add a deadline for the read to avoid blocking forever
|
|
|
|
_ = targetConn.SetReadDeadline(time.Now().Add(readTimeout))
|
2024-09-20 15:52:45 +00:00
|
|
|
n, err := targetConn.Read(buf)
|
2024-06-25 15:40:42 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("read from target: %w", err)
|
|
|
|
}
|
2024-09-20 15:52:45 +00:00
|
|
|
hdr := udpRequest{addr: targetAddr}
|
2024-06-25 15:40:42 +00:00
|
|
|
pkt, err := hdr.marshal()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("marshal udp request: %w", err)
|
|
|
|
}
|
|
|
|
data := append(pkt, buf[:n]...)
|
|
|
|
// use addr from client to send back
|
|
|
|
nn, err := clientConn.WriteTo(data, c.udpClientAddr)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("write to client: %w", err)
|
|
|
|
}
|
|
|
|
if nn != len(data) {
|
|
|
|
return fmt.Errorf("write to client: %w", io.ErrShortWrite)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func isTimeout(err error) bool {
|
|
|
|
terr, ok := errors.Unwrap(err).(interface{ Timeout() bool })
|
|
|
|
return ok && terr.Timeout()
|
|
|
|
}
|
|
|
|
|
|
|
|
func splitHostPort(hostport string) (host string, port uint16, err error) {
|
|
|
|
host, portStr, err := net.SplitHostPort(hostport)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
portInt, err := strconv.Atoi(portStr)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
if portInt < 0 || portInt > 65535 {
|
|
|
|
return "", 0, fmt.Errorf("invalid port number %d", portInt)
|
|
|
|
}
|
|
|
|
return host, uint16(portInt), nil
|
|
|
|
}
|
|
|
|
|
2023-03-05 20:28:27 +00:00
|
|
|
// parseClientGreeting parses a request initiation packet.
|
|
|
|
func parseClientGreeting(r io.Reader, authMethod byte) error {
|
2021-02-26 21:38:59 +00:00
|
|
|
var hdr [2]byte
|
|
|
|
_, err := io.ReadFull(r, hdr[:])
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not read packet header")
|
|
|
|
}
|
|
|
|
if hdr[0] != socks5Version {
|
|
|
|
return fmt.Errorf("incompatible SOCKS version")
|
|
|
|
}
|
|
|
|
count := int(hdr[1])
|
|
|
|
methods := make([]byte, count)
|
|
|
|
_, err = io.ReadFull(r, methods)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not read methods")
|
|
|
|
}
|
|
|
|
for _, m := range methods {
|
2023-03-05 20:28:27 +00:00
|
|
|
if m == authMethod {
|
2021-02-26 21:38:59 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fmt.Errorf("no acceptable auth methods")
|
|
|
|
}
|
|
|
|
|
2023-03-05 20:28:27 +00:00
|
|
|
func parseClientAuth(r io.Reader) (usr, pwd string, err error) {
|
|
|
|
var hdr [2]byte
|
|
|
|
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
|
|
|
return "", "", fmt.Errorf("could not read auth packet header")
|
|
|
|
}
|
|
|
|
if hdr[0] != passwordAuthVersion {
|
|
|
|
return "", "", fmt.Errorf("bad SOCKS auth version")
|
|
|
|
}
|
|
|
|
usrLen := int(hdr[1])
|
|
|
|
usrBytes := make([]byte, usrLen)
|
|
|
|
if _, err := io.ReadFull(r, usrBytes); err != nil {
|
|
|
|
return "", "", fmt.Errorf("could not read auth packet username")
|
|
|
|
}
|
|
|
|
var hdrPwd [1]byte
|
|
|
|
if _, err := io.ReadFull(r, hdrPwd[:]); err != nil {
|
|
|
|
return "", "", fmt.Errorf("could not read auth packet password length")
|
|
|
|
}
|
|
|
|
pwdLen := int(hdrPwd[0])
|
|
|
|
pwdBytes := make([]byte, pwdLen)
|
|
|
|
if _, err := io.ReadFull(r, pwdBytes); err != nil {
|
|
|
|
return "", "", fmt.Errorf("could not read auth packet password")
|
|
|
|
}
|
|
|
|
return string(usrBytes), string(pwdBytes), nil
|
|
|
|
}
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
func getAddrType(addr string) addrType {
|
|
|
|
if ip := net.ParseIP(addr); ip != nil {
|
|
|
|
if ip.To4() != nil {
|
|
|
|
return ipv4
|
|
|
|
}
|
|
|
|
return ipv6
|
|
|
|
}
|
|
|
|
return domainName
|
|
|
|
}
|
|
|
|
|
2021-02-26 21:38:59 +00:00
|
|
|
// request represents data contained within a SOCKS5
|
|
|
|
// connection request packet.
|
|
|
|
type request struct {
|
2024-06-25 15:40:42 +00:00
|
|
|
command commandType
|
|
|
|
destination socksAddr
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// parseClientRequest converts raw packet bytes into a
|
|
|
|
// SOCKS5Request struct.
|
|
|
|
func parseClientRequest(r io.Reader) (*request, error) {
|
2024-06-25 15:40:42 +00:00
|
|
|
var hdr [3]byte
|
2021-02-26 21:38:59 +00:00
|
|
|
_, err := io.ReadFull(r, hdr[:])
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not read packet header")
|
|
|
|
}
|
|
|
|
cmd := hdr[1]
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
destination, err := parseSocksAddr(r)
|
|
|
|
return &request{
|
|
|
|
command: commandType(cmd),
|
|
|
|
destination: destination,
|
|
|
|
}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
type socksAddr struct {
|
|
|
|
addrType addrType
|
|
|
|
addr string
|
|
|
|
port uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
var zeroSocksAddr = socksAddr{addrType: ipv4, addr: "0.0.0.0", port: 0}
|
|
|
|
|
|
|
|
func parseSocksAddr(r io.Reader) (addr socksAddr, err error) {
|
|
|
|
var addrTypeData [1]byte
|
|
|
|
_, err = io.ReadFull(r, addrTypeData[:])
|
|
|
|
if err != nil {
|
|
|
|
return socksAddr{}, fmt.Errorf("could not read address type")
|
|
|
|
}
|
2021-02-26 21:38:59 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
dstAddrType := addrType(addrTypeData[0])
|
|
|
|
var destination string
|
|
|
|
switch dstAddrType {
|
|
|
|
case ipv4:
|
2021-02-26 21:38:59 +00:00
|
|
|
var ip [4]byte
|
|
|
|
_, err = io.ReadFull(r, ip[:])
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
return socksAddr{}, fmt.Errorf("could not read IPv4 address")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
destination = net.IP(ip[:]).String()
|
2024-06-25 15:40:42 +00:00
|
|
|
case domainName:
|
2021-02-26 21:38:59 +00:00
|
|
|
var dstSizeByte [1]byte
|
|
|
|
_, err = io.ReadFull(r, dstSizeByte[:])
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
return socksAddr{}, fmt.Errorf("could not read domain name size")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
dstSize := int(dstSizeByte[0])
|
|
|
|
domainName := make([]byte, dstSize)
|
|
|
|
_, err = io.ReadFull(r, domainName)
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
return socksAddr{}, fmt.Errorf("could not read domain name")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
destination = string(domainName)
|
2024-06-25 15:40:42 +00:00
|
|
|
case ipv6:
|
2021-02-26 21:38:59 +00:00
|
|
|
var ip [16]byte
|
|
|
|
_, err = io.ReadFull(r, ip[:])
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
return socksAddr{}, fmt.Errorf("could not read IPv6 address")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
destination = net.IP(ip[:]).String()
|
2024-06-25 15:40:42 +00:00
|
|
|
default:
|
|
|
|
return socksAddr{}, fmt.Errorf("unsupported address type")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
var portBytes [2]byte
|
|
|
|
_, err = io.ReadFull(r, portBytes[:])
|
|
|
|
if err != nil {
|
2024-06-25 15:40:42 +00:00
|
|
|
return socksAddr{}, fmt.Errorf("could not read port")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
2024-06-25 15:40:42 +00:00
|
|
|
port := binary.BigEndian.Uint16(portBytes[:])
|
|
|
|
return socksAddr{
|
|
|
|
addrType: dstAddrType,
|
|
|
|
addr: destination,
|
|
|
|
port: port,
|
2021-02-26 21:38:59 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
func (s socksAddr) marshal() ([]byte, error) {
|
|
|
|
var addr []byte
|
|
|
|
switch s.addrType {
|
|
|
|
case ipv4:
|
|
|
|
addr = net.ParseIP(s.addr).To4()
|
|
|
|
if addr == nil {
|
|
|
|
return nil, fmt.Errorf("invalid IPv4 address for binding")
|
|
|
|
}
|
|
|
|
case domainName:
|
|
|
|
if len(s.addr) > 255 {
|
|
|
|
return nil, fmt.Errorf("invalid domain name for binding")
|
|
|
|
}
|
|
|
|
addr = make([]byte, 0, len(s.addr)+1)
|
|
|
|
addr = append(addr, byte(len(s.addr)))
|
|
|
|
addr = append(addr, []byte(s.addr)...)
|
|
|
|
case ipv6:
|
|
|
|
addr = net.ParseIP(s.addr).To16()
|
|
|
|
if addr == nil {
|
|
|
|
return nil, fmt.Errorf("invalid IPv6 address for binding")
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
return nil, fmt.Errorf("unsupported address type")
|
|
|
|
}
|
|
|
|
|
|
|
|
pkt := []byte{byte(s.addrType)}
|
|
|
|
pkt = append(pkt, addr...)
|
|
|
|
pkt = binary.BigEndian.AppendUint16(pkt, s.port)
|
|
|
|
return pkt, nil
|
|
|
|
}
|
2024-09-21 06:37:51 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
func (s socksAddr) hostPort() string {
|
|
|
|
return net.JoinHostPort(s.addr, strconv.Itoa(int(s.port)))
|
|
|
|
}
|
|
|
|
|
2024-09-21 06:37:51 +00:00
|
|
|
func (s socksAddr) String() string {
|
|
|
|
return s.hostPort()
|
|
|
|
}
|
|
|
|
|
2021-02-26 21:38:59 +00:00
|
|
|
// response contains the contents of
|
|
|
|
// a response packet sent from the proxy
|
|
|
|
// to the client.
|
|
|
|
type response struct {
|
2024-06-25 15:40:42 +00:00
|
|
|
reply replyCode
|
|
|
|
bindAddr socksAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
func errorResponse(code replyCode) *response {
|
|
|
|
return &response{reply: code, bindAddr: zeroSocksAddr}
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// marshal converts a SOCKS5Response struct into
|
|
|
|
// a packet. If res.reply == Success, it may throw an error on
|
|
|
|
// receiving an invalid bind address. Otherwise, it will not throw.
|
|
|
|
func (res *response) marshal() ([]byte, error) {
|
2024-06-25 15:40:42 +00:00
|
|
|
pkt := make([]byte, 3)
|
2021-02-26 21:38:59 +00:00
|
|
|
pkt[0] = socks5Version
|
|
|
|
pkt[1] = byte(res.reply)
|
|
|
|
pkt[2] = 0 // null reserved byte
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
addrPkt, err := res.bindAddr.marshal()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
return append(pkt, addrPkt...), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type udpRequest struct {
|
|
|
|
frag byte
|
|
|
|
addr socksAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
// +----+------+------+----------+----------+----------+
|
|
|
|
// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
|
|
|
|
// +----+------+------+----------+----------+----------+
|
|
|
|
// | 2 | 1 | 1 | Variable | 2 | Variable |
|
|
|
|
// +----+------+------+----------+----------+----------+
|
|
|
|
func parseUDPRequest(data []byte) (*udpRequest, []byte, error) {
|
|
|
|
if len(data) < 4 {
|
|
|
|
return nil, nil, fmt.Errorf("invalid packet length")
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
// reserved bytes
|
|
|
|
if !(data[0] == 0 && data[1] == 0) {
|
|
|
|
return nil, nil, fmt.Errorf("invalid udp request header")
|
|
|
|
}
|
2021-02-26 21:38:59 +00:00
|
|
|
|
2024-06-25 15:40:42 +00:00
|
|
|
frag := data[2]
|
|
|
|
|
|
|
|
reader := bytes.NewReader(data[3:])
|
|
|
|
addr, err := parseSocksAddr(reader)
|
|
|
|
bodyLen := reader.Len() // (*bytes.Reader).Len() return unread data length
|
|
|
|
body := data[len(data)-bodyLen:]
|
|
|
|
return &udpRequest{
|
|
|
|
frag: frag,
|
|
|
|
addr: addr,
|
|
|
|
}, body, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *udpRequest) marshal() ([]byte, error) {
|
|
|
|
pkt := make([]byte, 3)
|
|
|
|
pkt[0] = 0
|
|
|
|
pkt[1] = 0
|
|
|
|
pkt[2] = u.frag
|
|
|
|
|
|
|
|
addrPkt, err := u.addr.marshal()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return append(pkt, addrPkt...), nil
|
2021-02-26 21:38:59 +00:00
|
|
|
}
|