diff --git a/README.md b/README.md index cd6f0718..6058cf1c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ of wireproxy by [@artem-russkikh](https://github.com/artem-russkikh). # Feature - TCP static routing for client and server -- SOCKS5/HTTP proxy (currently only CONNECT is supported) +- SOCKS5/HTTP proxy (SOCKS5 supports CONNECT only; the HTTP proxy supports CONNECT and plain HTTP requests of any method, each on its own connection to the origin, and tunnels protocol upgrades such as WebSocket) - Transparent TLS ([SNI](https://en.wikipedia.org/wiki/Server_Name_Indication)) proxy # TODO diff --git a/http.go b/http.go index 110bf9ef..8576a588 100644 --- a/http.go +++ b/http.go @@ -11,10 +11,15 @@ import ( "net" "net/http" "strings" + "time" ) const proxyAuthHeaderKey = "Proxy-Authorization" +// httpReadRequestTimeout bounds how long a client may take to send its request +// line and headers. +var httpReadRequestTimeout = 30 * time.Second + type HTTPServer struct { config *HTTPConfig @@ -50,6 +55,37 @@ func (s *HTTPServer) authenticate(req *http.Request) (int, error) { return http.StatusUnauthorized, fmt.Errorf("username and password not matching") } +// hopByHopHeaders are the headers that apply to a single transport-level +// connection (RFC 7230 section 6.1) plus the proxy-specific ones, and must not +// be forwarded to the origin. +var hopByHopHeaders = []string{ + "Connection", + "Proxy-Connection", + "Keep-Alive", + "Proxy-Authenticate", + proxyAuthHeaderKey, + "Te", + "Trailer", + "Transfer-Encoding", + "Upgrade", +} + +// removeHopByHopHeaders deletes the hop-by-hop headers, including any header +// named in a Connection header, so that proxy credentials and connection +// management do not leak to the origin. +func removeHopByHopHeaders(h http.Header) { + for _, v := range h.Values("Connection") { + for _, name := range strings.Split(v, ",") { + if name = strings.TrimSpace(name); name != "" { + h.Del(name) + } + } + } + for _, name := range hopByHopHeaders { + h.Del(name) + } +} + func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn, err error) { addr := req.Host if !strings.Contains(addr, ":") { @@ -71,26 +107,125 @@ func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn return } -func (s *HTTPServer) handle(req *http.Request) (peer net.Conn, err error) { +// isUpgrade returns the requested protocol if the client asked for a protocol +// upgrade (e.g. WebSocket) with both Connection: upgrade and an Upgrade header. +func isUpgrade(h http.Header) string { + for _, v := range h.Values("Connection") { + for _, token := range strings.Split(v, ",") { + if strings.EqualFold(strings.TrimSpace(token), "upgrade") { + return h.Get("Upgrade") + } + } + } + return "" +} + +// writeInterim writes a 1xx response (100 Continue, 101 Switching Protocols) +// to the client. +func writeInterim(w io.Writer, resp *http.Response) error { + if _, err := fmt.Fprintf(w, "HTTP/1.1 %s\r\n", resp.Status); err != nil { + return err + } + if err := resp.Header.Write(w); err != nil { + return err + } + _, err := io.WriteString(w, "\r\n") + return err +} + +// handle forwards one plain-HTTP request to the origin on its own connection +// and relays the response. rd holds any bytes of the client connection that +// were read ahead of the request. +func (s *HTTPServer) handle(req *http.Request, conn net.Conn, rd io.Reader) error { addr := req.Host if !strings.Contains(addr, ":") { port := "80" addr = net.JoinHostPort(addr, port) } - peer, err = s.dial("tcp", addr) + peer, err := s.dial("tcp", addr) if err != nil { - return peer, fmt.Errorf("tun tcp dial failed: %w", err) + return fmt.Errorf("tun tcp dial failed: %w", err) } + defer func() { _ = peer.Close() }() - err = req.Write(peer) - if err != nil { - _ = peer.Close() - peer = nil - return peer, fmt.Errorf("conn write failed: %w", err) + upgrade := isUpgrade(req.Header) + removeHopByHopHeaders(req.Header) + if upgrade != "" { + // Keep the upgrade handshake (e.g. WebSocket) so it can be tunnelled. + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", upgrade) + } else { + // One origin connection per request: ask the origin to close after + // the response. + req.Close = true } - return + // An origin that goes silent must not hold the connection forever. + d := proxyIdleTimeout + idle := time.AfterFunc(d, func() { _ = peer.Close() }) + defer idle.Stop() + oc := idleConn{Conn: peer, reset: func() { idle.Reset(d) }} + + // Write the request while relaying the response, so that an interim + // response (100 Continue) reaches a client that is waiting for it before it + // sends the body. + written := make(chan error, 1) + go func() { + err := req.Write(oc) + if err != nil { + _ = peer.Close() + } + written <- err + }() + + br := bufio.NewReader(oc) + for { + resp, err := http.ReadResponse(br, req) + if err != nil { + // Do not wait for the writer: it may be blocked reading a + // request body the client has not sent. serve closes the client + // connection, which unblocks it. + select { + case werr := <-written: + if werr != nil { + return fmt.Errorf("conn write failed: %w", werr) + } + default: + } + return fmt.Errorf("read response failed: %w", err) + } + + if resp.StatusCode == http.StatusSwitchingProtocols && upgrade != "" { + if err := writeInterim(conn, resp); err != nil { + return err + } + if err := <-written; err != nil { + return fmt.Errorf("conn write failed: %w", err) + } + idle.Stop() + // Tunnel from here on. The origin's reads are no longer + // idle-tracked, and br may hold bytes sent right after the 101. + buffered, _ := br.Peek(br.Buffered()) + ahead := append([]byte(nil), buffered...) + proxyCopy(readerConn{Conn: conn, r: rd}, readerConn{Conn: peer, r: io.MultiReader(bytes.NewReader(ahead), peer)}) + return nil + } + if resp.StatusCode >= 100 && resp.StatusCode < 200 && resp.StatusCode != http.StatusSwitchingProtocols { + if err := writeInterim(conn, resp); err != nil { + return err + } + continue + } + + // The origin's connection management does not apply to the client + // connection, which is closed after this response. + removeHopByHopHeaders(resp.Header) + resp.Close = true + err = resp.Write(conn) + _ = resp.Body.Close() + return err + } } func (s *HTTPServer) serve(conn net.Conn) { @@ -100,10 +235,23 @@ func (s *HTTPServer) serve(conn net.Conn) { _ = conn.Close() } }() + if err := conn.SetReadDeadline(time.Now().Add(httpReadRequestTimeout)); err != nil { + log.Printf("set read deadline failed: %s\n", err) + return + } var rd = bufio.NewReader(conn) req, err := http.ReadRequest(rd) if err != nil { - log.Printf("read request failed: %s\n", err) + // io.EOF means the client closed before sending any byte (a port + // probe or health check), which is not worth a log line. A request + // cut short is io.ErrUnexpectedEOF and is still logged. + if err != io.EOF { + log.Printf("read request failed: %s\n", err) + } + return + } + if err := conn.SetReadDeadline(time.Time{}); err != nil { + log.Printf("clear read deadline failed: %s\n", err) return } @@ -118,17 +266,14 @@ func (s *HTTPServer) serve(conn net.Conn) { return } - var peer net.Conn - switch req.Method { - case http.MethodConnect: - peer, err = s.handleConn(req, conn) - case http.MethodGet: - peer, err = s.handle(req) - default: - _ = responseWith(req, http.StatusMethodNotAllowed).Write(conn) - log.Printf("unsupported protocol: %s\n", req.Method) + if req.Method != http.MethodConnect { + if err := s.handle(req, conn, rd); err != nil { + log.Printf("proxy request failed: %s\n", err) + } return } + + peer, err := s.handleConn(req, conn) if err != nil { if peer != nil { _ = peer.Close() @@ -143,19 +288,8 @@ func (s *HTTPServer) serve(conn net.Conn) { handled = true - go func() { - defer func() { _ = conn.Close() }() - defer func() { _ = peer.Close() }() - - _, _ = io.Copy(conn, peer) - }() - - go func() { - defer func() { _ = conn.Close() }() - defer func() { _ = peer.Close() }() - - _, _ = io.Copy(peer, conn) - }() + // rd may already hold bytes the client sent after the request. + proxyCopy(readerConn{Conn: conn, r: rd}, peer) } func (s *HTTPServer) listen(network, addr string) (net.Listener, error) { diff --git a/http_test.go b/http_test.go index 97ccc02d..cbf18d92 100644 --- a/http_test.go +++ b/http_test.go @@ -2,11 +2,18 @@ package wireproxy import ( "bufio" + "bytes" + "errors" "io" + "log" "net" "net/http" "net/http/httptest" + "os" + "strings" + "sync/atomic" "testing" + "time" ) func TestHTTPServerServeGet(t *testing.T) { @@ -99,3 +106,691 @@ func TestHTTPServerServeFailureClosesConn(t *testing.T) { t.Fatalf("expected EOF when server closes connection, got %v", err) } } + +// startTestProxy serves server on a loopback listener and returns its address. +func startTestProxy(t *testing.T, server *HTTPServer) string { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go server.serve(conn) + } + }() + return listener.Addr().String() +} + +func TestHTTPServerStripsHopByHopHeaders(t *testing.T) { + got := make(chan http.Header, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got <- r.Header.Clone() + _, _ = w.Write([]byte("ok")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + auth: CredentialValidator{"u", "p"}, + authRequired: true, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + raw := "GET http://" + ts.Listener.Addr().String() + "/ HTTP/1.1\r\n" + + "Host: " + ts.Listener.Addr().String() + "\r\n" + + "Proxy-Authorization: Basic dTpw\r\n" + + "Proxy-Connection: keep-alive\r\n" + + "Connection: keep-alive, X-Secret-Hop\r\n" + + "Keep-Alive: timeout=5\r\n" + + "X-Secret-Hop: 1\r\n" + + "X-Keep-Me: yes\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + + select { + case h := <-got: + for _, name := range []string{"Proxy-Authorization", "Proxy-Connection", "Keep-Alive", "X-Secret-Hop"} { + if v := h.Get(name); v != "" { + t.Errorf("origin saw %s=%q", name, v) + } + } + if h.Get("X-Keep-Me") != "yes" { + t.Errorf("end-to-end header dropped: %v", h) + } + case <-time.After(5 * time.Second): + t.Fatal("origin did not receive the request") + } +} + +// startEchoServer accepts connections and echoes everything back. +func startEchoServer(t *testing.T) string { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = conn.Close() }() + _, _ = io.Copy(conn, conn) + }() + } + }() + return listener.Addr().String() +} + +func TestHTTPServerConnectForwardsEarlyBytes(t *testing.T) { + echo := startEchoServer(t) + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, echo) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + // The payload arrives in the same segment as the CONNECT request, so it + // sits in the proxy's bufio.Reader. + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\nEARLY")); err != nil { + t.Fatal(err) + } + + rd := bufio.NewReader(clientConn) + status, err := rd.ReadString('\n') + if err != nil || status != "HTTP/1.1 200 Connection established\r\n" { + t.Fatalf("unexpected status %q (err %v)", status, err) + } + if line, err := rd.ReadString('\n'); err != nil || line != "\r\n" { + t.Fatalf("unexpected header terminator %q (err %v)", line, err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)) + buf := make([]byte, len("EARLY")) + if _, err := io.ReadFull(rd, buf); err != nil { + t.Fatalf("early bytes were not forwarded: %v", err) + } + if string(buf) != "EARLY" { + t.Fatalf("unexpected echo %q", buf) + } +} + +func TestHTTPServerConnectHalfClose(t *testing.T) { + // The origin replies only after the client has half-closed. + originLn, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = originLn.Close() }() + go func() { + conn, err := originLn.Accept() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + req, _ := io.ReadAll(conn) + _, _ = conn.Write(append([]byte("reply to "), req...)) + }() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, originLn.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n")); err != nil { + t.Fatal(err) + } + rd := bufio.NewReader(clientConn) + for { + line, err := rd.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" { + break + } + } + + if _, err := clientConn.Write([]byte("request")); err != nil { + t.Fatal(err) + } + if err := clientConn.(*net.TCPConn).CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(rd) + if err != nil { + t.Fatal(err) + } + if string(got) != "reply to request" { + t.Fatalf("got %q after half-close", got) + } +} + +func setReadRequestTimeout(t *testing.T, d time.Duration) { + t.Helper() + old := httpReadRequestTimeout + httpReadRequestTimeout = d + t.Cleanup(func() { httpReadRequestTimeout = old }) +} + +func TestHTTPServerReadRequestTimeout(t *testing.T) { + setReadRequestTimeout(t, 100*time.Millisecond) + addr := startTestProxy(t, &HTTPServer{}) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + + // An incomplete request line, then silence. + if _, err := clientConn.Write([]byte("GET http://example.test/ HT")); err != nil { + t.Fatal(err) + } + + _ = clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := clientConn.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("expected the proxy to close the idle connection, got %v", err) + } +} + +// A client that connects and closes without sending anything (a port probe or +// load balancer health check) is not an error, but a truncated request is. +func TestHTTPServerReadRequestLogging(t *testing.T) { + var logs bytes.Buffer + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(os.Stderr) }) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = listener.Close() }) + + // serveAfter has a client write write (if not empty) and close, then + // returns what serve logged for that connection. + serveAfter := func(write string) string { + logs.Reset() + client, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + if write != "" { + if _, err := client.Write([]byte(write)); err != nil { + t.Fatal(err) + } + } + _ = client.Close() + server, err := listener.Accept() + if err != nil { + t.Fatal(err) + } + (&HTTPServer{}).serve(server) + return logs.String() + } + + if got := serveAfter(""); got != "" { + t.Errorf("empty connection logged %q, want nothing", got) + } + if got := serveAfter("GET http://example.test/ HT"); !strings.Contains(got, "read request failed") { + t.Errorf("truncated request logged %q, want a read request failure", got) + } +} + +func TestHTTPServerReadDeadlineClearedForTunnel(t *testing.T) { + setReadRequestTimeout(t, 100*time.Millisecond) + echo := startEchoServer(t) + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, echo) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("CONNECT example.test:443 HTTP/1.1\r\nHost: example.test:443\r\n\r\n")); err != nil { + t.Fatal(err) + } + rd := bufio.NewReader(clientConn) + for { + line, err := rd.ReadString('\n') + if err != nil { + t.Fatal(err) + } + if line == "\r\n" { + break + } + } + + // Stay idle for longer than the request timeout, then use the tunnel. + time.Sleep(300 * time.Millisecond) + if _, err := clientConn.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + buf := make([]byte, 4) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "ping" { + t.Fatalf("tunnel closed by the request read deadline: %q, %v", buf, err) + } +} + +func TestHTTPServerForwardsNonGetMethods(t *testing.T) { + type seen struct { + method, body string + close bool + } + got := make(chan seen, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + got <- seen{r.Method, string(body), r.Close} + _, _ = w.Write([]byte("done")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodHead} { + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + req, err := http.NewRequest(method, "http://"+ts.Listener.Addr().String()+"/x", strings.NewReader("payload")) + if err != nil { + t.Fatal(err) + } + if err := req.Write(clientConn); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), req) + if err != nil { + t.Fatalf("%s: %v", method, err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("%s: status %d", method, resp.StatusCode) + } + _ = resp.Body.Close() + _ = clientConn.Close() + + select { + case s := <-got: + if s.method != method || s.body != "payload" || !s.close { + t.Fatalf("%s: origin saw %+v", method, s) + } + case <-time.After(5 * time.Second): + t.Fatalf("%s: origin did not receive the request", method) + } + } +} + +// A keep-alive follow-up for another host must not be piped to the first origin. +func TestHTTPServerPlainRequestUsesOneOriginConnection(t *testing.T) { + var requests atomic.Int32 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = w.Write([]byte("first")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + two := "GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n" + + "GET http://b.test/ HTTP/1.1\r\nHost: b.test\r\n\r\n" + if _, err := clientConn.Write([]byte(two)); err != nil { + t.Fatal(err) + } + + all, err := io.ReadAll(clientConn) + if err != nil { + t.Fatalf("expected the proxy to close the client connection after the response: %v", err) + } + if n := strings.Count(string(all), "HTTP/1.1 200"); n != 1 { + t.Fatalf("got %d responses, want 1: %q", n, all) + } + if n := requests.Load(); n != 1 { + t.Fatalf("origin saw %d requests, want 1", n) + } +} + +// startRawOrigin accepts connections and hands each to handle. +func startRawOrigin(t *testing.T, handle func(conn net.Conn)) *HTTPServer { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func() { + defer func() { _ = conn.Close() }() + handle(conn) + }() + } + }() + return &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ln.Addr().String()) + }, + } +} + +func TestHTTPServerPlainRequestChunkedBody(t *testing.T) { + type seen struct { + body string + te []string + } + got := make(chan seen, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + got <- seen{string(body), r.TransferEncoding} + _, _ = w.Write([]byte("ok")) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + raw := "POST http://a.test/upload HTTP/1.1\r\nHost: a.test\r\nTransfer-Encoding: chunked\r\n\r\n" + + "5\r\nhello\r\n6\r\n world\r\n0\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), nil) + if err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("response: %v, %v", resp, err) + } + + select { + case s := <-got: + if s.body != "hello world" || len(s.te) != 1 || s.te[0] != "chunked" { + t.Fatalf("origin saw %+v", s) + } + case <-time.After(5 * time.Second): + t.Fatal("origin did not receive the request") + } +} + +func TestHTTPServerExpectContinue(t *testing.T) { + // net/http answers "100 Continue" when the handler reads the body. + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + _, _ = w.Write([]byte("got " + string(body))) + })) + defer ts.Close() + + server := &HTTPServer{ + dial: func(network, address string) (net.Conn, error) { + return net.Dial(network, ts.Listener.Addr().String()) + }, + } + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + headers := "POST http://a.test/ HTTP/1.1\r\nHost: a.test\r\nContent-Length: 5\r\nExpect: 100-continue\r\n\r\n" + if _, err := clientConn.Write([]byte(headers)); err != nil { + t.Fatal(err) + } + + // Like curl, send the body only after the 100 Continue. + rd := bufio.NewReader(clientConn) + interim, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatalf("no interim response before the body was sent: %v", err) + } + if interim.StatusCode != http.StatusContinue { + t.Fatalf("interim status %d", interim.StatusCode) + } + if _, err := clientConn.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusOK || string(body) != "got hello" { + t.Fatalf("final response %d %q", resp.StatusCode, body) + } +} + +func TestHTTPServerUpgrade(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + br := bufio.NewReader(conn) + req, err := http.ReadRequest(br) + if err != nil { + return + } + if req.Header.Get("Upgrade") != "websocket" || !strings.EqualFold(req.Header.Get("Connection"), "Upgrade") || + req.Header.Get("Proxy-Authorization") != "" { + _, _ = conn.Write([]byte("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n")) + return + } + // "frame" is sent in the same write as the 101. + _, _ = conn.Write([]byte("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\nframe")) + _, _ = io.Copy(conn, br) + }) + server.auth = CredentialValidator{"u", "p"} + server.authRequired = true + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + raw := "GET http://a.test/ws HTTP/1.1\r\nHost: a.test\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n" + + "Proxy-Authorization: Basic dTpw\r\nProxy-Connection: keep-alive\r\n\r\n" + if _, err := clientConn.Write([]byte(raw)); err != nil { + t.Fatal(err) + } + + rd := bufio.NewReader(clientConn) + resp, err := http.ReadResponse(rd, nil) + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusSwitchingProtocols || resp.Header.Get("Upgrade") != "websocket" { + t.Fatalf("response %d %v", resp.StatusCode, resp.Header) + } + + buf := make([]byte, len("frame")) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "frame" { + t.Fatalf("bytes after the 101 were lost: %q, %v", buf, err) + } + if _, err := clientConn.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + buf = make([]byte, 4) + if _, err := io.ReadFull(rd, buf); err != nil || string(buf) != "ping" { + t.Fatalf("tunnel did not echo: %q, %v", buf, err) + } +} + +// An origin that ignores "Connection: close" and keeps the connection open +// must not keep the client waiting after a complete response. +func TestHTTPServerPlainResponseEndsAtFraming(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")) + _, _ = io.Copy(io.Discard, conn) // never closes by itself + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + all, err := io.ReadAll(clientConn) + if err != nil { + t.Fatalf("client connection was not closed after the response: %v", err) + } + if !strings.HasSuffix(string(all), "\r\n\r\nok") { + t.Fatalf("unexpected response %q", all) + } +} + +// An origin that stalls mid-response is cut off after the idle timeout. +func TestHTTPServerPlainResponseIdleTimeout(t *testing.T) { + setProxyIdleTimeout(t, 100*time.Millisecond) + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\npart")) + _, _ = io.Copy(io.Discard, conn) + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + // The truncated response ends in an error or EOF, not a deadline timeout. + _, err = io.ReadAll(clientConn) + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + t.Fatalf("proxy did not cut off the stalled origin: %v", err) + } +} + +func TestHTTPServerPlainResponseHeadersAndTrailers(t *testing.T) { + server := startRawOrigin(t, func(conn net.Conn) { + _, _ = http.ReadRequest(bufio.NewReader(conn)) + _, _ = conn.Write([]byte("HTTP/1.1 200 OK\r\n" + + "Transfer-Encoding: chunked\r\n" + + "Trailer: X-Sum\r\n" + + "Connection: keep-alive, X-Custom-Hop\r\n" + + "Keep-Alive: timeout=5\r\n" + + "Proxy-Authenticate: Basic\r\n" + + "X-Custom-Hop: 1\r\n" + + "X-Keep-Me: yes\r\n\r\n" + + "5\r\nhello\r\n0\r\nX-Sum: abc\r\n\r\n")) + _, _ = io.Copy(io.Discard, conn) + }) + addr := startTestProxy(t, server) + + clientConn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer func() { _ = clientConn.Close() }() + _ = clientConn.SetDeadline(time.Now().Add(5 * time.Second)) + + if _, err := clientConn.Write([]byte("GET http://a.test/ HTTP/1.1\r\nHost: a.test\r\n\r\n")); err != nil { + t.Fatal(err) + } + resp, err := http.ReadResponse(bufio.NewReader(clientConn), nil) + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(resp.Body) + if err != nil || string(body) != "hello" { + t.Fatalf("body %q, %v", body, err) + } + + for _, name := range []string{"Keep-Alive", "Proxy-Authenticate", "X-Custom-Hop"} { + if v := resp.Header.Get(name); v != "" { + t.Errorf("client saw %s=%q", name, v) + } + } + if resp.Header.Get("X-Keep-Me") != "yes" { + t.Errorf("end-to-end header dropped: %v", resp.Header) + } + if !resp.Close { + t.Errorf("expected Connection: close, headers %v", resp.Header) + } + if got := resp.Trailer.Get("X-Sum"); got != "abc" { + t.Errorf("trailer X-Sum = %q, want abc (trailer %v)", got, resp.Trailer) + } +} diff --git a/proxy.go b/proxy.go new file mode 100644 index 00000000..28b0b46d --- /dev/null +++ b/proxy.go @@ -0,0 +1,170 @@ +package wireproxy + +import ( + "errors" + "io" + "net" + "os" + "sync" + "sync/atomic" + "time" +) + +const copyBufferSize = 32 * 1024 + +// copyBufferPool holds the buffers used by proxyCopy, so that each connection +// does not allocate a new buffer per direction. +var copyBufferPool = sync.Pool{ + New: func() any { + b := make([]byte, copyBufferSize) + return &b + }, +} + +// closeWriter is implemented by connections that can shut down only their +// write side (*net.TCPConn, *tls.Conn, gonet.TCPConn). +type closeWriter interface { + CloseWrite() error +} + +// readerOnly and writerOnly hide the WriterTo and ReaderFrom methods of the +// wrapped value so that io.CopyBuffer always uses the supplied buffer. +type readerOnly struct{ io.Reader } +type writerOnly struct{ io.Writer } + +func copyPooled(dst io.Writer, src io.Reader) (int64, error) { + bp := copyBufferPool.Get().(*[]byte) + defer copyBufferPool.Put(bp) + return io.CopyBuffer(writerOnly{dst}, readerOnly{src}, *bp) +} + +// proxyIdleTimeout bounds how long a half-closed proxyCopy, or a plain-HTTP +// response relay, waits for more data from the other side. +var proxyIdleTimeout = 2 * time.Minute + +// activityReader calls onRead after every read that returned data. +type activityReader struct { + io.Reader + onRead func() +} + +func (r activityReader) Read(p []byte) (int, error) { + n, err := r.Reader.Read(p) + if n > 0 { + r.onRead() + } + return n, err +} + +// idleConn calls reset after every read or write that moved data. +type idleConn struct { + net.Conn + reset func() +} + +func (c idleConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + if n > 0 { + c.reset() + } + return n, err +} + +func (c idleConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + if n > 0 { + c.reset() + } + return n, err +} + +type proxyState struct { + a, b io.ReadWriteCloser + idle *time.Timer + d time.Duration + // closing is set before we close the connections ourselves, so errors that + // our own Close causes in the other direction are not logged. + closing atomic.Bool + halfClosed atomic.Bool +} + +func (s *proxyState) closeBoth() { + s.closing.Store(true) + _ = s.a.Close() + _ = s.b.Close() +} + +// copyHalf copies src to dst. When src reaches EOF it shuts down the write side +// of dst so the other end sees EOF while the reverse direction keeps going, +// bounded by the idle timeout. If that is not possible, or the copy failed, +// both connections are closed. +func (s *proxyState) copyHalf(dst, src io.ReadWriteCloser) { + _, err := copyPooled(dst, activityReader{src, func() { + if s.halfClosed.Load() { + s.idle.Reset(s.d) + } + }}) + if err != nil && !s.closing.Load() && !errors.Is(err, net.ErrClosed) { + errorLogger.Printf("Cannot forward traffic: %s\n", err.Error()) + } + if err == nil { + if cw, ok := dst.(closeWriter); ok && cw.CloseWrite() == nil { + s.halfClosed.Store(true) + s.idle.Reset(s.d) + return + } + } + s.closeBoth() +} + +// proxyCopy copies data in both directions between a and b, honouring +// half-close, and closes both once both directions are finished (or one fails, +// or the remaining direction is idle for proxyIdleTimeout after the other +// finished). It blocks until then. +func proxyCopy(a, b io.ReadWriteCloser) { + s := &proxyState{a: a, b: b, d: proxyIdleTimeout} + s.idle = time.AfterFunc(s.d, s.closeBoth) + s.idle.Stop() + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + s.copyHalf(a, b) + }() + go func() { + defer wg.Done() + s.copyHalf(b, a) + }() + wg.Wait() + s.idle.Stop() + _ = a.Close() + _ = b.Close() +} + +// readerConn reads from r instead of the embedded connection, for a connection +// that was partly consumed through a buffer. Writes and closes go to the +// connection. +type readerConn struct { + net.Conn + r io.Reader +} + +func (c readerConn) Read(p []byte) (int, error) { return c.r.Read(p) } + +func (c readerConn) CloseWrite() error { + if cw, ok := c.Conn.(closeWriter); ok { + return cw.CloseWrite() + } + return errors.ErrUnsupported +} + +// stdioConn presents a stdin/stdout pair as a single connection. +type stdioConn struct { + in *os.File + out *os.File +} + +func (c stdioConn) Read(p []byte) (int, error) { return c.in.Read(p) } +func (c stdioConn) Write(p []byte) (int, error) { return c.out.Write(p) } +func (c stdioConn) Close() error { return errors.Join(c.in.Close(), c.out.Close()) } diff --git a/proxy_test.go b/proxy_test.go new file mode 100644 index 00000000..f5785932 --- /dev/null +++ b/proxy_test.go @@ -0,0 +1,285 @@ +package wireproxy + +import ( + "bytes" + "errors" + "io" + "log" + "net" + "strings" + "testing" + "time" +) + +// tcpPair returns the two ends of a loopback TCP connection. +func tcpPair(t *testing.T) (*net.TCPConn, *net.TCPConn) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer func() { _ = listener.Close() }() + + accepted := make(chan *net.TCPConn, 1) + go func() { + conn, err := listener.Accept() + if err != nil { + accepted <- nil + return + } + accepted <- conn.(*net.TCPConn) + }() + + client, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + server := <-accepted + if server == nil { + t.Fatal("accept failed") + } + t.Cleanup(func() { + _ = client.Close() + _ = server.Close() + }) + return client.(*net.TCPConn), server +} + +func TestProxyCopyHalfClose(t *testing.T) { + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, proxyB) + close(done) + }() + + // The origin only answers after it has seen the end of the request. + go func() { + req, _ := io.ReadAll(origin) + _, _ = origin.Write(append([]byte("reply to "), req...)) + _ = origin.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := client.Write([]byte("request")); err != nil { + t.Fatal(err) + } + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(client) + if err != nil { + t.Fatal(err) + } + if string(got) != "reply to request" { + t.Fatalf("got %q after half-close", got) + } + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return after both directions finished") + } +} + +func TestProxyCopyLargeBidirectional(t *testing.T) { + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + go proxyCopy(proxyA, proxyB) + + payload := bytes.Repeat([]byte("0123456789abcdef"), 1<<16) // 1 MiB + _ = client.SetDeadline(time.Now().Add(10 * time.Second)) + _ = origin.SetDeadline(time.Now().Add(10 * time.Second)) + + send := func(c *net.TCPConn) { + _, _ = c.Write(payload) + _ = c.CloseWrite() + } + go send(client) + go send(origin) + + for name, c := range map[string]*net.TCPConn{"client": client, "origin": origin} { + got, err := io.ReadAll(c) + if err != nil { + t.Fatalf("%s read: %v", name, err) + } + if !bytes.Equal(got, payload) { + t.Fatalf("%s received %d bytes, want %d", name, len(got), len(payload)) + } + } +} + +// A connection without CloseWrite cannot signal EOF, so both sides are closed. +func TestProxyCopyClosesBothWithoutCloseWrite(t *testing.T) { + pipeClient, pipeProxy := net.Pipe() + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(pipeProxy, proxyB) + close(done) + }() + + _ = origin.Close() + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return") + } + _ = pipeClient.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := pipeClient.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("expected EOF on the other side, got %v", err) + } +} + +type failingWriterTo struct{ io.Reader } + +func (failingWriterTo) WriteTo(io.Writer) (int64, error) { panic("WriteTo used") } + +type failingReaderFrom struct{ bytes.Buffer } + +func (*failingReaderFrom) ReadFrom(io.Reader) (int64, error) { panic("ReadFrom used") } + +func TestCopyPooledUsesBuffer(t *testing.T) { + var dst failingReaderFrom + n, err := copyPooled(&dst, failingWriterTo{bytes.NewReader([]byte("data"))}) + if err != nil || n != 4 || dst.String() != "data" { + t.Fatalf("copyPooled = %d, %v, %q", n, err, dst.String()) + } +} + +func setProxyIdleTimeout(t *testing.T, d time.Duration) { + t.Helper() + old := proxyIdleTimeout + proxyIdleTimeout = d + t.Cleanup(func() { proxyIdleTimeout = old }) +} + +// After one side half-closes, a silent other side must not linger forever. +func TestProxyCopyIdleAfterHalfClose(t *testing.T) { + setProxyIdleTimeout(t, 100*time.Millisecond) + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, proxyB) + close(done) + }() + + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + // The origin sees EOF but never replies or closes. + _ = origin.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := origin.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("origin read: %v", err) + } + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not give up on the idle half-closed connection") + } +} + +// The idle timeout is not an absolute deadline: it restarts on every read. +func TestProxyCopyIdleTimeoutResetsOnActivity(t *testing.T) { + setProxyIdleTimeout(t, 200*time.Millisecond) + client, proxyA := tcpPair(t) + proxyB, origin := tcpPair(t) + + go proxyCopy(proxyA, proxyB) + + go func() { + for i := 0; i < 6; i++ { + time.Sleep(80 * time.Millisecond) + _, _ = origin.Write([]byte("x")) + } + _ = origin.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + got, err := io.ReadAll(client) + if err != nil || string(got) != "xxxxxx" { + t.Fatalf("got %q, %v", got, err) + } +} + +// opaqueErrConn blocks in Read until it is closed, then fails with an error +// that is not net.ErrClosed (like gonet after a local Close). +type opaqueErrConn struct { + closed chan struct{} + err error +} + +func (c *opaqueErrConn) Read([]byte) (int, error) { + <-c.closed + return 0, c.err +} +func (c *opaqueErrConn) Write(p []byte) (int, error) { return len(p), nil } +func (c *opaqueErrConn) Close() error { + select { + case <-c.closed: + default: + close(c.closed) + } + return nil +} + +func captureErrorLog(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + old := errorLogger + errorLogger = log.New(&buf, "", 0) + t.Cleanup(func() { errorLogger = old }) + return &buf +} + +func TestProxyCopyDoesNotLogOwnClose(t *testing.T) { + buf := captureErrorLog(t) + client, proxyA := tcpPair(t) + fake := &opaqueErrConn{closed: make(chan struct{}), err: errors.New("endpoint is closed for receive")} + + done := make(chan struct{}) + go func() { + proxyCopy(proxyA, fake) + close(done) + }() + + // EOF from the client: fake has no CloseWrite, so both sides get closed, + // which makes fake's Read fail with an opaque error. + _ = client.Close() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("proxyCopy did not return") + } + if buf.Len() != 0 { + t.Fatalf("logged an error caused by our own close: %q", buf.String()) + } +} + +func TestProxyCopyLogsRealError(t *testing.T) { + buf := captureErrorLog(t) + _, proxyA := tcpPair(t) + fake := &failingReadConn{err: errors.New("boom")} + + proxyCopy(proxyA, fake) + if !strings.Contains(buf.String(), "boom") { + t.Fatalf("real error not logged: %q", buf.String()) + } +} + +type failingReadConn struct{ err error } + +func (c *failingReadConn) Read([]byte) (int, error) { return 0, c.err } +func (c *failingReadConn) Write(p []byte) (int, error) { return len(p), nil } +func (c *failingReadConn) Close() error { return nil } diff --git a/routine.go b/routine.go index 731d0175..3f4b0b0a 100644 --- a/routine.go +++ b/routine.go @@ -8,7 +8,6 @@ import ( "encoding/binary" "encoding/json" "errors" - "io" "log" "math/rand" "net" @@ -170,11 +169,25 @@ func (passthroughResolver) Resolve(ctx context.Context, name string) (context.Co // and dials everything else directly. Used by the HTTP and SNI proxies, whose // dial callbacks receive the destination hostname intact. func (d VirtualTun) RoutedDial(router *DomainRouter) func(network, address string) (net.Conn, error) { + var direct net.Dialer + return routedDial(router, routedDialTimeout, d.Tnet.DialContext, direct.DialContext) +} + +// routedDialTimeout bounds a dial made by RoutedDial. Without it a dead tunnel +// or target makes the caller wait for the TCP SYN retries (about two minutes in +// netstack). +const routedDialTimeout = 30 * time.Second + +type dialContextFunc func(ctx context.Context, network, address string) (net.Conn, error) + +func routedDial(router *DomainRouter, timeout time.Duration, tunnel, direct dialContextFunc) func(network, address string) (net.Conn, error) { return func(network, address string) (net.Conn, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() if router.route(hostFromAddr(address)) { - return d.Tnet.Dial(network, address) + return tunnel(ctx, network, address) } - return net.Dial(network, address) + return direct(ctx, network, address) } } @@ -262,17 +275,6 @@ func (c CredentialValidator) Valid(username, password string) bool { return u&p == 1 } -// connForward copy data from `from` to `to` -func connForward(from io.ReadWriteCloser, to io.ReadWriteCloser) { - defer func() { _ = from.Close() }() - defer func() { _ = to.Close() }() - - _, err := io.Copy(to, from) - if err != nil && !errors.Is(err, net.ErrClosed) { - errorLogger.Printf("Cannot forward traffic: %s\n", err.Error()) - } -} - // tcpClientForward starts a new connection via wireguard and forward traffic from `conn` func tcpClientForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { target, err := vt.resolveToAddrPort(raddr) @@ -291,8 +293,7 @@ func tcpClientForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { return } - go connForward(sconn, conn) - go connForward(conn, sconn) + proxyCopy(sconn, conn) } // STDIOTcpForward starts a new connection via wireguard and forward traffic from `conn` @@ -310,8 +311,7 @@ func STDIOTcpForward(vt *VirtualTun, raddr *addressPort, input *os.File, output return } - go connForward(input, sconn) - go connForward(sconn, output) + proxyCopy(sconn, stdioConn{in: input, out: output}) } // SpawnRoutine spawns a local TCP server which acts as a proxy to the specified target @@ -363,9 +363,7 @@ func tcpServerForward(vt *VirtualTun, raddr *addressPort, conn net.Conn) { return } - go connForward(sconn, conn) - go connForward(conn, sconn) - + proxyCopy(sconn, conn) } // SpawnRoutine spawns a TCP server on wireguard which acts as a proxy to the specified target diff --git a/routine_test.go b/routine_test.go new file mode 100644 index 00000000..31c4db5e --- /dev/null +++ b/routine_test.go @@ -0,0 +1,41 @@ +package wireproxy + +import ( + "context" + "net" + "regexp" + "testing" + "time" +) + +func TestRoutedDialTimesOut(t *testing.T) { + router := NewDomainRouter([]*regexp.Regexp{regexp.MustCompile(`^tunnel\.test$`)}, false) + + // A dial that only returns when its context ends, like an unreachable host. + var tunnelCalls, directCalls int + blocking := func(calls *int) dialContextFunc { + return func(ctx context.Context, network, address string) (net.Conn, error) { + *calls++ + if _, ok := ctx.Deadline(); !ok { + t.Error("dial context has no deadline") + } + <-ctx.Done() + return nil, ctx.Err() + } + } + dial := routedDial(router, 50*time.Millisecond, blocking(&tunnelCalls), blocking(&directCalls)) + + for _, address := range []string{"tunnel.test:443", "direct.test:443"} { + start := time.Now() + _, err := dial("tcp", address) + if err == nil { + t.Fatalf("%s: expected an error", address) + } + if elapsed := time.Since(start); elapsed > 5*time.Second { + t.Fatalf("%s: dial took %s", address, elapsed) + } + } + if tunnelCalls != 1 || directCalls != 1 { + t.Fatalf("tunnel dialled %d times, direct %d times; want 1 each", tunnelCalls, directCalls) + } +} diff --git a/sni.go b/sni.go index ea2ac197..5bf85322 100644 --- a/sni.go +++ b/sni.go @@ -38,15 +38,7 @@ func peekClientHello(conn net.Conn) (string, io.ReadWriteCloser, error) { }, }).Handshake() - wrappedConn := struct { - io.Reader - io.Writer - io.Closer - }{ - Reader: io.MultiReader(peekedBytes, conn), - Writer: conn, - Closer: conn, - } + wrappedConn := readerConn{Conn: conn, r: io.MultiReader(peekedBytes, conn)} var serverName string if hello != nil { @@ -57,7 +49,8 @@ func peekClientHello(conn net.Conn) (string, io.ReadWriteCloser, error) { return serverName, wrappedConn, err } -// Get SNI hostname, dial out through tunnel, then proxy data +// Get SNI hostname, dial out through tunnel, then proxy data until both +// directions are done func sniProxyForward(dial func(string, string) (net.Conn, error), conn net.Conn) error { if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { return fmt.Errorf("set read deadline failed: %w", err) @@ -82,8 +75,7 @@ func sniProxyForward(dial func(string, string) (net.Conn, error), conn net.Conn) return fmt.Errorf("tun tcp dial failed: %w", err) } - go connForward(clientConn, backendConn) - go connForward(backendConn, clientConn) + proxyCopy(clientConn, backendConn) return nil } diff --git a/sni_test.go b/sni_test.go new file mode 100644 index 00000000..d9f1ef09 --- /dev/null +++ b/sni_test.go @@ -0,0 +1,83 @@ +package wireproxy + +import ( + "crypto/tls" + "errors" + "io" + "net" + "testing" + "time" +) + +// captureConn records what a TLS client writes and then fails the handshake. +type captureConn struct { + net.Conn + written []byte +} + +func (c *captureConn) Write(p []byte) (int, error) { + c.written = append(c.written, p...) + return len(p), nil +} +func (c *captureConn) Read([]byte) (int, error) { return 0, errors.New("capture only") } + +func clientHelloFor(t *testing.T, serverName string) []byte { + t.Helper() + cc := &captureConn{} + _ = tls.Client(cc, &tls.Config{ServerName: serverName}).Handshake() + if len(cc.written) == 0 { + t.Fatal("no ClientHello captured") + } + return cc.written +} + +func TestSNIProxyHalfClose(t *testing.T) { + hello := clientHelloFor(t, "example.test") + + client, proxyConn := tcpPair(t) + proxyBackend, backend := tcpPair(t) + + var dialed string + dial := func(network, address string) (net.Conn, error) { + dialed = address + return proxyBackend, nil + } + + done := make(chan error, 1) + go func() { done <- sniProxyForward(dial, proxyConn) }() + + // The backend answers only once the client has finished sending. + go func() { + req, _ := io.ReadAll(backend) + _, _ = backend.Write([]byte("got ")) + _, _ = backend.Write([]byte{byte(len(req) % 256)}) + _ = backend.Close() + }() + + _ = client.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := client.Write(hello); err != nil { + t.Fatal(err) + } + if err := client.CloseWrite(); err != nil { + t.Fatal(err) + } + reply, err := io.ReadAll(client) + if err != nil { + t.Fatal(err) + } + if want := append([]byte("got "), byte(len(hello)%256)); string(reply) != string(want) { + t.Fatalf("reply %q, want %q", reply, want) + } + + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("sniProxyForward did not return") + } + if dialed != "example.test:443" { + t.Fatalf("dialed %q", dialed) + } +}