Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name: Test
on:
push: {}
pull_request: {}
workflow_dispatch: {}
concurrency:
group: test-${{ github.event_name }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
permissions:
contents: read
defaults:
run:
shell: bash
jobs:
test:
name: go-test
# A pull request from a branch of this repository is already tested by its push.
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.repository
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
# Each failure is repeated as an annotation: job logs need admin rights, annotations are public.
- name: gofmt
run: |
if ! test -z "$(gofmt -l .)"; then
gofmt -l .
gofmt -d . > gofmt.diff || true
cat gofmt.diff
echo "::error title=gofmt::$(head -n 150 gofmt.diff | sed 's/%/%25/g' | awk 'BEGIN { ORS = "%0A" } { print }')"
exit 1
fi
- name: go vet
run: |
if ! go vet ./... > vet.log 2>&1; then
cat vet.log
echo "::error title=go vet::$(head -n 150 vet.log | sed 's/%/%25/g' | awk 'BEGIN { ORS = "%0A" } { print }')"
exit 1
fi
- name: go test
run: |
if ! go test -race -count=1 ./... > test.log 2>&1; then
cat test.log
echo "::error title=go test::$(head -n 150 test.log | sed 's/%/%25/g' | awk 'BEGIN { ORS = "%0A" } { print }')"
exit 1
fi

cat test.log
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,8 @@ If the flag is empty, no ingress listener is started.
- `CONNECT` requests are accepted on that listener.
- `X-Dst-Addr` must contain the full destination as `IP:port`.
- If the destination port is closed, the listener returns `400`.
- `X-Dst-Protocol: udp` opens one UDP flow to `X-Dst-Addr` instead of a TCP connection. See "UDP ingress".
Without the header the connection is TCP; any other value returns `400`.
- `GET /ca` returns the PEM-encoded CA certificate (`/ca/ca.crt`). Only useful when `-tls-intercept` is enabled. Returns `404` if the certificate doesn't exist.
- `PUT /egress` updates shared runtime configuration. Supported fields are:
- `port` -- updates `http-egress-port`
Expand All @@ -178,9 +180,35 @@ curl -v -x http://127.0.0.1:49122 https://ignored.example \
-H 'X-Dst-Addr: 172.17.0.1:8443'
```

# UDP ingress

The ingress listener relays one UDP flow per connection. Request:

```
CONNECT 127.0.0.1:<port> HTTP/1.1
Host: 127.0.0.1:<port>
X-Dst-Addr: 127.0.0.1:<port>
X-Dst-Protocol: udp
```

`X-Dst-Addr` is validated as for TCP and must be an IPv4 `IP:port`; otherwise the listener returns `400`.
On success it answers `200` exactly as for TCP. UDP has no handshake, so a port with nothing listening
still gets `200`.

After the request head (bytes may follow it without waiting for `200`), both directions carry frames:
a 2-byte big-endian length `L` from 0 to 1500, then `L` bytes of one datagram.

- Datagrams over 1500 bytes from the container are dropped. Empty datagrams are valid.
- Frames toward the container with a length from 1501 to `0xFFFE` are skipped and the flow stays open, so
the limit can be raised later without negotiation. A length of `0xFFFF` is a protocol error that closes the flow.
- ICMP port unreachable does not end the flow; the application may bind the port later.
- Half-close is not used: EOF or an error in either direction ends the flow, and the listener closes the
connection and the UDP socket. There is no idle timeout.
- Under backpressure datagrams are dropped at the UDP socket, not buffered.

# DNS interception

UDP interception is currently limited to DNS on port `53` and is optional.
UDP egress interception is currently limited to DNS on port `53` and is optional.

- Pass `-dns-enabled` to enable DNS interception.
- `-dns-address` controls the IPv4 transparent DNS listener address. Default: `127.0.0.9:5000`.
Expand All @@ -199,7 +227,7 @@ Behavior:
3. HTTP CONNECT everything.

# Current limitations
1. UDP support is currently limited to DNS on port `53`.
1. UDP egress is currently limited to DNS on port `53`. UDP ingress is IPv4 only.
2. Proxying to unix sockets is not implemented yet due to lack of support on MacOS.

# TLDR: How?
Expand Down
15 changes: 15 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,21 @@ func (s *ingressServer) handleConnect(ctx context.Context, clientConn net.Conn,
return
}

switch protocol := req.Header.Get("X-Dst-Protocol"); protocol {
case "":
// absent means TCP
case "udp":
s.handleConnectUDP(ctx, clientConn, reader, targetAddr)
return
default:
if writeErr := (&http.Response{ProtoMajor: 1, ProtoMinor: 1, StatusCode: http.StatusBadRequest}).Write(clientConn); writeErr != nil {
log.Println("error writing unknown protocol response:", writeErr)
}

log.Println("error: unknown ingress protocol", protocol)
return
}

originConn, err := (&net.Dialer{}).DialContext(ctx, "tcp", targetAddr)
response := http.Response{ProtoMajor: 1, ProtoMinor: 1}
if err != nil {
Expand Down
173 changes: 173 additions & 0 deletions udp_ingress.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
package main

import (
"bufio"
"context"
"encoding/binary"
"errors"
"io"
"log"
"net"
"net/http"
"sync"
"syscall"
)

// UDP ingress: a CONNECT with X-Dst-Protocol: udp opens one UDP flow to X-Dst-Addr and gets the same
// 200 as TCP. Then each direction carries frames: a 2-byte big-endian length L, then L bytes of one
// datagram. Frames with L above 1500 are skipped and the flow stays open, so the limit can grow later.
// L = 0xFFFF is FLOW_END, which only cc-oxy-router sends; one from workerd is a protocol error that
// ends the flow. EOF or an error on either side also ends it.

const maxUDPPayloadSize = 1500

const udpFrameHeaderSize = 2

const maxUDPFrameSize = udpFrameHeaderSize + maxUDPPayloadSize

// A FLOW_END frame only travels away from the container.
const udpFlowEndLength = 0xffff

var errUDPFlowEndTowardContainer = errors.New("udp FLOW_END frame sent toward the container")

func (s *ingressServer) handleConnectUDP(ctx context.Context, clientConn net.Conn, reader *bufio.Reader, targetAddr string) {
originConn, err := (&net.Dialer{}).DialContext(ctx, "udp4", targetAddr)
response := http.Response{ProtoMajor: 1, ProtoMinor: 1}
if err != nil {
response.StatusCode = http.StatusBadRequest
if writeErr := response.Write(clientConn); writeErr != nil {
log.Println("error writing ingress udp dial failure response:", writeErr)
}

log.Println("error dialing ingress udp target", targetAddr, err)
return
}

udpConn := originConn.(*net.UDPConn)
defer udpConn.Close()

response.StatusCode = http.StatusOK
if err := response.Write(clientConn); err != nil {
log.Println("error writing ingress udp connect response:", err)
return
}

relayUDPFlow(ctx, clientConn, reader, udpConn)
}

// relayUDPFlow returns once both directions have stopped. Half-close is never used on a UDP tunnel:
// EOF or an error in either direction closes the tunnel and the UDP socket.
func relayUDPFlow(ctx context.Context, clientConn net.Conn, reader *bufio.Reader, udpConn *net.UDPConn) {
closeFlow := func() {
clientConn.Close()
udpConn.Close()
}

stopAfterFunc := context.AfterFunc(ctx, closeFlow)
defer stopAfterFunc()

var flowWG sync.WaitGroup

flowWG.Go(func() {
defer closeFlow()

err := relayTunnelToUDP(reader, udpConn)
if err != io.EOF && !errors.Is(err, net.ErrClosed) {
log.Println("ingress udp tunnel to udp relay ended:", err)
}
})

flowWG.Go(func() {
defer closeFlow()

err := relayUDPToTunnel(udpConn, clientConn)
if !errors.Is(err, net.ErrClosed) {
log.Println("ingress udp udp to tunnel relay ended:", err)
}
})

flowWG.Wait()
}

// relayTunnelToUDP returns io.EOF only when the tunnel ends on a frame boundary.
func relayTunnelToUDP(reader io.Reader, udpConn *net.UDPConn) error {
buffer := make([]byte, maxUDPFrameSize)

for {
payload, err := readUDPFrame(reader, buffer)
if err != nil {
return err
}

// ICMP port unreachable from an earlier datagram; the application may bind the port later.
if _, err := udpConn.Write(payload); err != nil && !errors.Is(err, syscall.ECONNREFUSED) {
return err
}
}
}

// relayUDPToTunnel blocks on tunnel writes, so under backpressure the kernel drops at the UDP socket.
func relayUDPToTunnel(udpConn *net.UDPConn, tunnel io.Writer) error {
frame := make([]byte, maxUDPFrameSize+1)

for {
// A datagram over maxUDPPayloadSize fills the extra byte of the buffer.
n, err := udpConn.Read(frame[udpFrameHeaderSize:])
if errors.Is(err, syscall.ECONNREFUSED) {
continue
}

if err != nil {
return err
}

if n > maxUDPPayloadSize {
continue
}

binary.BigEndian.PutUint16(frame, uint16(n))
if _, err := tunnel.Write(frame[:udpFrameHeaderSize+n]); err != nil {
return err
}
}
}

// readUDPFrame reads frames into buffer, which holds at least maxUDPFrameSize bytes, until one carries
// a datagram within maxUDPPayloadSize, and returns its payload. Larger frames are skipped without
// buffering, so a peer can raise its limit without negotiation. io.EOF means the stream ended between
// frames.
func readUDPFrame(reader io.Reader, buffer []byte) ([]byte, error) {
header := buffer[:udpFrameHeaderSize]

for {
if _, err := io.ReadFull(reader, header); err != nil {
return nil, err
}

length := int(binary.BigEndian.Uint16(header))
if length == udpFlowEndLength {
return nil, errUDPFlowEndTowardContainer
}

if length <= maxUDPPayloadSize {
payload := buffer[udpFrameHeaderSize : udpFrameHeaderSize+length]
if _, err := io.ReadFull(reader, payload); err != nil {
return nil, unexpectedEOF(err)
}

return payload, nil
}

if _, err := io.CopyN(io.Discard, reader, int64(length)); err != nil {
return nil, unexpectedEOF(err)
}
}
}

func unexpectedEOF(err error) error {
if err == io.EOF {
return io.ErrUnexpectedEOF
}

return err
}
Loading
Loading