blob: 47a398cce8bfd02c726c575e1154371d1b97c832 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Tim Windelschmidtc2290c22024-08-15 19:56:00 +02004// Package socksproxy implements a limited subset of the SOCKS 5 (RFC1928)
Serge Bazanskife7134b2022-04-01 15:46:29 +02005// protocol in the form of a pluggable Proxy object. However, this
6// implementation is _not_ RFC1928 compliant, as it does not implement GSSAPI
7// (which is mandated by the spec). It currently only implements CONNECT
8// requests to IPv4/IPv6 addresses. It also doesn't implement any
9// timeout/keepalive system for killing inactive connections.
10//
11// The intended use of the library is internally within Metropolis development
12// environments for contacting test clusters. The code is simple and robust, but
13// not really productionized (as noted above - no timeouts and no authentication
14// make it a bad idea to ever expose this proxy server publicly).
15//
16// There are multiple other, existing Go SOCKS4/5 server implementations, but
17// many of them are either not context aware, part of a larger project (and thus
18// difficult to extract) or are brand new/untested/bleeding edge code.
19package socksproxy
20
21import (
22 "context"
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +020023 "errors"
Serge Bazanskife7134b2022-04-01 15:46:29 +020024 "fmt"
25 "io"
26 "log"
27 "net"
28 "strconv"
29)
30
31// Handler should be implemented by socksproxy users to allow SOCKS connections
32// to be proxied in any other way than via the HostHandler.
33type Handler interface {
34 // Connect is called by the server any time a SOCKS client sends a CONNECT
35 // request. The function should return a ConnectResponse describing some
36 // 'backend' connection, ie. the connection that will then be exposed to the
37 // SOCKS client.
38 //
39 // Connect should return with Error set to a non-default value to abort/deny the
40 // connection request.
41 //
42 // The underlying incoming socket is managed by the proxy server and is not
43 // visible to the client. However, any sockets/connections/files opened by the
44 // Handler should be cleaned up by tying them to the given context, which will
45 // be canceled whenever the connection is closed.
46 Connect(context.Context, *ConnectRequest) *ConnectResponse
47}
48
49// ConnectRequest represents a pending CONNECT request from a client.
50type ConnectRequest struct {
51 // Address is an IPv4 or IPv6 address that the client requested to connect to.
52 // This address might be invalid/malformed/internal, and the Connect method
53 // should sanitize it before using it.
54 Address net.IP
55 // Port is the TCP port number that the client requested to connect to.
56 Port uint16
57}
58
59// ConnectResponse indicates a 'backend' connection that the proxy should expose
60// to the client, or an error if the connection cannot be made.
61type ConnectResponse struct {
62 // Error will cause an error to be returned if it is anything else than the
63 // default value (ReplySucceeded).
64 Error Reply
65
Serge Bazanski1ec1fe92023-03-22 18:29:28 +010066 // Backend is the ReadWriteCloser that will be bridged over to the connecting
67 // client if no Error is set.
68 Backend io.ReadWriteCloser
Serge Bazanskife7134b2022-04-01 15:46:29 +020069 // LocalAddress is the IP address that is returned to the client as the local
70 // address of the newly established backend connection.
71 LocalAddress net.IP
72 // LocalPort is the local TCP port number that is returned to the client as the
73 // local port of the newly established backend connection.
74 LocalPort uint16
75}
76
77// ConnectResponseFromConn builds a ConnectResponse from a net.Conn. This can be
78// used by custom Handlers to easily return a ConnectResponse for a newly
79// established net.Conn, eg. from a Dial call.
80//
81// An error is returned if the given net.Conn does not carry a properly formed
82// LocalAddr.
83func ConnectResponseFromConn(c net.Conn) (*ConnectResponse, error) {
84 laddr := c.LocalAddr().String()
85 host, port, err := net.SplitHostPort(laddr)
86 if err != nil {
87 return nil, fmt.Errorf("could not parse LocalAddr %q: %w", laddr, err)
88 }
89 addr := net.ParseIP(host)
90 if addr == nil {
91 return nil, fmt.Errorf("could not parse LocalAddr host %q as IP", host)
92 }
93 portNum, err := strconv.ParseUint(port, 10, 16)
94 if err != nil {
95 return nil, fmt.Errorf("could not parse LocalAddr port %q", port)
96 }
97 return &ConnectResponse{
98 Backend: c,
99 LocalAddress: addr,
100 LocalPort: uint16(portNum),
101 }, nil
102}
103
104type hostHandler struct{}
105
106func (h *hostHandler) Connect(ctx context.Context, req *ConnectRequest) *ConnectResponse {
107 port := fmt.Sprintf("%d", req.Port)
108 addr := net.JoinHostPort(req.Address.String(), port)
109 s, err := net.Dial("tcp", addr)
110 if err != nil {
111 log.Printf("HostHandler could not dial %q: %v", addr, err)
112 return &ConnectResponse{Error: ReplyConnectionRefused}
113 }
114 go func() {
115 <-ctx.Done()
116 s.Close()
117 }()
118 res, err := ConnectResponseFromConn(s)
119 if err != nil {
120 log.Printf("HostHandler could not build response: %v", err)
121 return &ConnectResponse{Error: ReplyGeneralFailure}
122 }
123 return res
124}
125
126var (
127 // HostHandler is an unsafe SOCKS5 proxy Handler which passes all incoming
128 // connections into the local network stack. The incoming addresses/ports are
129 // not sanitized, and as the proxy does not perform authentication, this handler
130 // is an open proxy. This handler should never be used in cases where the proxy
131 // server is publicly available.
132 HostHandler = &hostHandler{}
133)
134
135// Serve runs a SOCKS5 proxy server for a given Handler at a given listener.
136//
137// When the given context is canceled, the server will stop and the listener
138// will be closed. All pending connections will also be canceled and their
139// sockets closed.
140func Serve(ctx context.Context, handler Handler, lis net.Listener) error {
141 go func() {
142 <-ctx.Done()
143 lis.Close()
144 }()
145
146 for {
147 con, err := lis.Accept()
148 if err != nil {
149 // Context cancellation will close listener socket with a generic 'use of closed
150 // network connection' error, translate that back to context error.
151 if ctx.Err() != nil {
152 return ctx.Err()
153 }
154 return err
155 }
156 go handle(ctx, handler, con)
157 }
158}
159
160// handle runs in a goroutine per incoming SOCKS connection. Its lifecycle
161// corresponds to the lifecycle of a running proxy connection.
162func handle(ctx context.Context, handler Handler, con net.Conn) {
163 // ctxR is a per-request context, and will be canceled whenever the handler
164 // exits or the server is stopped.
165 ctxR, ctxRC := context.WithCancel(ctx)
166 defer ctxRC()
167
168 go func() {
169 <-ctxR.Done()
170 con.Close()
171 }()
172
173 // Perform method negotiation with the client.
174 if err := negotiateMethod(con); err != nil {
175 return
176 }
177
178 // Read request from the client and translate problems into early error replies.
179 req, err := readRequest(con)
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +0200180 switch {
181 case errors.Is(err, errNotConnect):
Serge Bazanskife7134b2022-04-01 15:46:29 +0200182 writeReply(con, ReplyCommandNotSupported, net.IPv4(0, 0, 0, 0), 0)
183 return
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +0200184 case errors.Is(err, errUnsupportedAddressType):
Serge Bazanskife7134b2022-04-01 15:46:29 +0200185 writeReply(con, ReplyAddressTypeNotSupported, net.IPv4(0, 0, 0, 0), 0)
186 return
Tim Windelschmidtd5f851b2024-04-23 14:59:37 +0200187 case err == nil:
Serge Bazanskife7134b2022-04-01 15:46:29 +0200188 default:
189 writeReply(con, ReplyGeneralFailure, net.IPv4(0, 0, 0, 0), 0)
190 return
191 }
192
193 // Ask handler.Connect for a backend.
194 conRes := handler.Connect(ctxR, &ConnectRequest{
195 Address: req.address,
196 Port: req.port,
197 })
198 // Handle programming error when returned value is nil.
199 if conRes == nil {
200 writeReply(con, ReplyGeneralFailure, net.IPv4(0, 0, 0, 0), 0)
201 return
202 }
203 // Handle returned errors.
204 if conRes.Error != ReplySucceeded {
205 writeReply(con, conRes.Error, net.IPv4(0, 0, 0, 0), 0)
206 return
207 }
208
209 // Ensure Bound.* fields are set.
210 if conRes.Backend == nil || conRes.LocalAddress == nil || conRes.LocalPort == 0 {
211 writeReply(con, ReplyGeneralFailure, net.IPv4(0, 0, 0, 0), 0)
212 return
213 }
214 // Send reply.
215 if err := writeReply(con, ReplySucceeded, conRes.LocalAddress, conRes.LocalPort); err != nil {
216 return
217 }
218
219 // Pipe returned backend into connection.
Serge Bazanski1ec1fe92023-03-22 18:29:28 +0100220 go func() {
221 io.Copy(conRes.Backend, con)
222 conRes.Backend.Close()
223 }()
Serge Bazanskife7134b2022-04-01 15:46:29 +0200224 io.Copy(con, conRes.Backend)
Serge Bazanski1ec1fe92023-03-22 18:29:28 +0100225 conRes.Backend.Close()
Serge Bazanskife7134b2022-04-01 15:46:29 +0200226}