Documentation
¶
Overview ¶
Package transparent accepts TCP connections and UDP datagrams that a transparent proxy setup redirects to a local socket, and recovers the destination they were addressed to.
Platform Control OriginalDestination Linux, Android IP_TRANSPARENT/IPV6_TRANSPARENT SO_ORIGINAL_DST, else the local address FreeBSD IP_BINDANY/IPV6_BINDANY pf DIOCNATLOOK, else the local address macOS, iOS nothing (pf rdr needs no option) pf DIOCNATLOOK (root only) others ErrListenUnsupported ErrOriginalDestinationUnsupported
Listen is a net.ListenConfig with Control; to combine the transparent options with others, such as SO_REUSEPORT or SO_MARK, call Control from a Control function of one's own.
For UDP, ListenPacket, ReadFromUDP and DialUDP implement Linux TPROXY: datagrams carry their original destination, and replies are sent from it. ControlPacket sets the options of ListenPacket. FlowListener, from ListenUDPFlows, builds on them a connection per flow. Elsewhere they return errors matching errors.ErrUnsupported.
Index ¶
- Constants
- Variables
- func Control(network, address string, c syscall.RawConn) error
- func ControlPacket(network, address string, c syscall.RawConn) error
- func DialUDP(ctx context.Context, local, remote netip.AddrPort) (*net.UDPConn, error)
- func Listen(ctx context.Context, network, address string) (net.Listener, error)
- func ListenPacket(ctx context.Context, network, address string) (*net.UDPConn, error)
- func OriginalDestination(conn net.Conn) (dst netip.AddrPort, redirected bool, err error)
- type FlowConn
- func (f *FlowConn) Close() error
- func (f *FlowConn) LocalAddr() net.Addr
- func (f *FlowConn) Read(b []byte) (int, error)
- func (f *FlowConn) Redirected() bool
- func (f *FlowConn) RemoteAddr() net.Addr
- func (f *FlowConn) SetDeadline(t time.Time) error
- func (f *FlowConn) SetReadDeadline(t time.Time) error
- func (f *FlowConn) SetWriteDeadline(t time.Time) error
- func (f *FlowConn) Write(b []byte) (int, error)
- type FlowListener
- type FlowOption
- type PacketInfo
Examples ¶
Constants ¶
const ( // DefaultFlowQueue is how many datagrams a connection holds until they // are read; see WithFlowQueue. DefaultFlowQueue = 128 // DefaultFlowAcceptBacklog is how many new connections wait for Accept; // see WithFlowAcceptBacklog. DefaultFlowAcceptBacklog = 128 )
Defaults of NewFlowListener.
Variables ¶
var ErrControlTruncated = errors.New("transparent: control messages truncated before the original destination")
ErrControlTruncated is returned by ReadFromUDP, with the datagram, when the datagram's control messages were cut short before its original destination. It concerns that datagram only.
var ErrListenUnsupported = fmt.Errorf("transparent: listening is not supported on this platform: %w", errors.ErrUnsupported)
ErrListenUnsupported is returned by Listen, Control and their UDP counterparts on platforms without transparent sockets. It matches errors.ErrUnsupported.
var ErrOriginalDestinationUnsupported = fmt.Errorf("transparent: original destination lookup is not supported on this platform: %w", errors.ErrUnsupported)
ErrOriginalDestinationUnsupported is returned by OriginalDestination on platforms without a lookup. It matches errors.ErrUnsupported.
Functions ¶
func Control ¶
Control prepares a socket to take transparently redirected connections, or, on a dialer, to bind an address that is not local. It has the signature of net.ListenConfig.Control and net.Dialer.Control.
On Linux it sets IP_TRANSPARENT and IPV6_TRANSPARENT, and on FreeBSD IP_BINDANY and IPV6_BINDANY, where the socket's family has them; it fails when neither could be set. Both usually require elevated privileges, such as CAP_NET_ADMIN on Linux. On macOS and iOS it does nothing: pf rdr rules need no socket option, and OriginalDestination asks pf for the target. Elsewhere, including Windows, it returns ErrListenUnsupported.
Example ¶
Combine the transparent socket options with others of one's own.
package main
import (
"context"
"log"
"net"
"syscall"
"time"
"github.com/djylb/netx/transparent"
)
func main() {
lc := net.ListenConfig{
KeepAliveConfig: net.KeepAliveConfig{Enable: true, Idle: 30 * time.Second},
Control: func(network, address string, c syscall.RawConn) error {
if err := transparent.Control(network, address, c); err != nil {
return err
}
// Set further options here, such as SO_REUSEPORT or SO_MARK.
return nil
},
}
ln, err := lc.Listen(context.Background(), "tcp", "0.0.0.0:8080")
if err != nil {
log.Fatal(err)
}
_ = ln.Close()
}
Output:
func ControlPacket ¶
ControlPacket prepares a UDP socket for ListenPacket: it does what Control does and also sets IP_RECVORIGDSTADDR and IPV6_RECVORIGDSTADDR, so that ReadFromUDP can report each datagram's original destination. It has the signature of net.ListenConfig.Control. It is available on Linux and Android; elsewhere it returns ErrListenUnsupported.
func DialUDP ¶
DialUDP returns a UDP socket bound to local, the original destination of a redirected datagram, and connected to remote, the datagram's source, so that replies reach the client from the address it sent to. Several such sockets may share one local address. It needs CAP_NET_ADMIN and is available where ListenPacket is.
The listening socket does not share its address, since that would let other sockets bind its port, so DialUDP fails with EADDRINUSE for an original destination the listener holds: with a listener on a wildcard address, any destination on the listener's port. Listen on a port that redirected traffic does not use.
func Listen ¶
Listen listens on a TCP address for transparently redirected connections. network must be "tcp", "tcp4" or "tcp6". It is net.ListenConfig.Listen with Control as the Control function.
Example ¶
Accept redirected connections and forward each to its original destination.
package main
import (
"context"
"log"
"net"
"github.com/djylb/netx"
"github.com/djylb/netx/transparent"
)
func main() {
ctx := context.Background()
ln, err := transparent.Listen(ctx, "tcp", "0.0.0.0:8080")
if err != nil {
log.Fatal(err)
}
for {
c, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go func() {
dst, redirected, err := transparent.OriginalDestination(c)
// A connection made to the listener directly would connect the
// proxy to itself, again and again.
if err != nil || !redirected {
_ = c.Close()
return
}
var d net.Dialer
upstream, err := d.DialContext(ctx, "tcp", dst.String())
if err != nil {
_ = c.Close()
return
}
_, _, _ = netx.Relay(ctx, c, upstream)
}()
}
}
Output:
func ListenPacket ¶
ListenPacket listens on a UDP address for datagrams that a TPROXY rule redirects to it, and asks the kernel to report each datagram's original destination, which ReadFromUDP returns. network must be "udp", "udp4" or "udp6". It is net.ListenConfig.ListenPacket with ControlPacket as the Control function, and needs CAP_NET_ADMIN. It is available on Linux and Android; elsewhere it returns ErrListenUnsupported.
Example ¶
Answer UDP datagrams redirected by a TPROXY rule from the address they were sent to.
package main
import (
"context"
"errors"
"log"
"github.com/djylb/netx/transparent"
)
func main() {
ctx := context.Background()
ln, err := transparent.ListenPacket(ctx, "udp", "0.0.0.0:5353")
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 65535)
for {
n, info, err := transparent.ReadFromUDP(ln, buf)
if errors.Is(err, transparent.ErrControlTruncated) {
continue // this datagram's destination is unknown
}
if err != nil {
log.Fatal(err)
}
if !info.Redirected {
continue // sent to the listener itself
}
reply, err := transparent.DialUDP(ctx, info.Dst, info.Src)
if err != nil {
continue
}
_, _ = reply.Write(buf[:n])
_ = reply.Close()
}
}
Output:
func OriginalDestination ¶
OriginalDestination returns the destination that an accepted TCP connection was addressed to, and whether a redirect brought it to this socket. A connection made to the socket directly reports its own local address and false: forwarding it would connect the proxy to itself.
On Linux it reads SO_ORIGINAL_DST, or IP6T_SO_ORIGINAL_DST for a native IPv6 local address (REDIRECT/DNAT), and on FreeBSD and macOS it queries pf with DIOCNATLOOK, which XNU only allows for root. Without a translation the connection reached the address it was sent to, its local address, as TPROXY and IP_BINDANY sockets receive it. A destination on another port than the local one was redirected. One on the same port was redirected unless it is an address of this host: forwarding it would come back. Linux asks the routing table, through the device that the socket is bound to, such as a VRF, and counts local and IPv6 anycast routes; FreeBSD and macOS bind the address. So a NAT that maps another address of this host to the listener's port, or TPROXY delivering a connection for an address of this host, is reported as direct. Lookup failures, such as for a closed connection or without permission to read /dev/pf, are returned. On other platforms it returns ErrOriginalDestinationUnsupported.
Wrappers, such as a *tls.Conn or the connection types of the netx package, are looked through along their NetConn methods, so the lookup and the local address are the accepted socket's rather than an address that a wrapper reports, such as the destination of a PROXY header, which conn.LocalAddr returns. A connection beneath which no socket can be reached is an error. IPv4-mapped addresses are unmapped, and a link-local IPv6 address keeps its zone, such as [fe80::1%eth0]:80, which a dialer needs to reach it. A nil conn returns net.ErrClosed.
Types ¶
type FlowConn ¶
type FlowConn struct {
// contains filtered or unexported fields
}
FlowConn is a flow that a FlowListener accepted: the datagrams from one source to one original destination. Its RemoteAddr is the source and its LocalAddr the original destination, both *net.UDPAddr.
Writes are sent to the source from the original destination, through a socket that DialUDP binds to it on the first Write and that is closed with the connection; the source's later datagrams arrive on that socket, and are read from the connection like the others. A flow sent to the listening socket directly, accepted with WithFlowDirect, is answered from the listening socket, from the address the source sent to.
func (*FlowConn) Close ¶
Close closes the flow and its answering socket. Its pending and later Reads and Writes return net.ErrClosed, and the next datagram of the flow starts a new connection.
func (*FlowConn) Read ¶
Read reads the next datagram of the flow into b, truncated to b. As on a socket, an expired read deadline fails it even while datagrams are queued. It returns io.EOF once an idle timeout closed f, and net.ErrClosed once f or the listener is closed.
func (*FlowConn) Redirected ¶
Redirected reports whether the flow was redirected to the listener rather than sent to it directly, which only WithFlowDirect accepts.
func (*FlowConn) RemoteAddr ¶
RemoteAddr returns the flow's source.
func (*FlowConn) SetDeadline ¶
SetDeadline sets the read and write deadlines.
func (*FlowConn) SetReadDeadline ¶
SetReadDeadline sets the deadline of pending and later Reads.
func (*FlowConn) SetWriteDeadline ¶
SetWriteDeadline sets the deadline of pending and later Writes.
type FlowListener ¶
type FlowListener struct {
// contains filtered or unexported fields
}
FlowListener accepts one connection per flow of the datagrams that TPROXY redirects to a UDP socket: per source and original destination. The first datagram of a flow starts a *FlowConn that Accept returns; later datagrams of the flow are read from it, and its writes answer the source from the original destination. It is available on Linux and Android.
Each Read of a connection returns one datagram, truncated to the buffer like a UDP socket. Datagrams that arrive while a connection's queue is full, or while too many connections wait for Accept, are dropped. Datagrams sent to the socket directly, which ReadFromUDP reports as not redirected, are dropped too unless WithFlowDirect is given: answering them as a proxy would send them to the socket again. After a connection is closed, the next datagram of its flow starts a new one. A connection lasts until it is closed, so a listener facing untrusted or spoofed sources should set WithFlowIdleTimeout or read deadlines. The zero FlowListener owns no socket and its Accept waits until Close.
func ListenUDPFlows ¶
func ListenUDPFlows(ctx context.Context, network, address string, opts ...FlowOption) (*FlowListener, error)
ListenUDPFlows listens on a UDP address with ListenPacket and returns a FlowListener for the datagrams redirected to it. network must be "udp", "udp4" or "udp6". It needs CAP_NET_ADMIN. It is available on Linux and Android; elsewhere it returns ErrListenUnsupported.
Example ¶
Forward each redirected UDP flow to its original destination.
package main
import (
"context"
"log"
"net"
"time"
"github.com/djylb/netx"
"github.com/djylb/netx/transparent"
)
func main() {
ctx := context.Background()
l, err := transparent.ListenUDPFlows(ctx, "udp", "0.0.0.0:5353", transparent.WithFlowIdleTimeout(time.Minute))
if err != nil {
log.Fatal(err)
}
for {
c, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func() {
var d net.Dialer
upstream, err := d.DialContext(ctx, "udp", c.LocalAddr().String())
if err != nil {
_ = c.Close()
return
}
_, _, _ = netx.Relay(ctx, c, upstream)
}()
}
}
Output:
func NewFlowListener ¶
func NewFlowListener(c *net.UDPConn, opts ...FlowOption) (*FlowListener, error)
NewFlowListener starts reading c, a socket set up with ControlPacket, such as one from ListenPacket, and returns a FlowListener for its flows. The listener owns c and closes it on Close; c must not be read otherwise. A read error meaning that c is closed closes the listener; other read errors are retried, with a growing delay while they persist, and an expired read deadline on c is cleared. It is available on Linux and Android; elsewhere it returns ErrListenUnsupported.
func (*FlowListener) Accept ¶
func (l *FlowListener) Accept() (net.Conn, error)
Accept waits for the next flow and returns its *FlowConn. It returns net.ErrClosed once the listener is closed. The idle timeout of a connection starts when it is accepted.
func (*FlowListener) Addr ¶
func (l *FlowListener) Addr() net.Addr
Addr returns the listening socket's address.
func (*FlowListener) Close ¶
func (l *FlowListener) Close() error
Close closes the socket and every connection of the listener, and waits for the listener's goroutines to stop.
type FlowOption ¶
type FlowOption func(*flowOptions)
FlowOption configures ListenUDPFlows and NewFlowListener.
func WithFlowAcceptBacklog ¶
func WithFlowAcceptBacklog(n int) FlowOption
WithFlowAcceptBacklog sets how many new connections wait for Accept, DefaultFlowAcceptBacklog by default.
func WithFlowClock ¶
func WithFlowClock(c timeshim.Clock) FlowOption
WithFlowClock makes the listener tell the time of the idle timeout by c instead of the system clock, such as a timeshim.Fake in tests.
func WithFlowDirect ¶
func WithFlowDirect() FlowOption
WithFlowDirect also accepts flows of datagrams sent to the socket directly, not redirected, which are dropped by default. FlowConn.Redirected tells them apart, and their connections answer from the listening socket, from the address the source sent to.
func WithFlowIdleTimeout ¶
func WithFlowIdleTimeout(d time.Duration) FlowOption
WithFlowIdleTimeout closes a connection that has neither received nor sent a datagram for d since Accept returned it. Its pending and later Reads return io.EOF. Connections waiting for Accept are kept with their datagrams. A non-positive d, the default, keeps idle connections.
func WithFlowMaxConns ¶
func WithFlowMaxConns(n int) FlowOption
WithFlowMaxConns sets how many connections the listener holds at once, accepted or waiting for Accept; a non-positive n, the default, sets no limit. While it holds n, a datagram of a new flow is dropped before anything is allocated for it. Each connection holds its queued datagrams and, once it has written, a socket, so the limit bounds the listener's memory and descriptors with WithFlowQueue. Sources that spoof their address can take every place, and keep it while they send, until an idle timeout or the application closes their connections: pair the limit with WithFlowIdleTimeout.
func WithFlowQueue ¶
func WithFlowQueue(n int) FlowOption
WithFlowQueue sets how many datagrams a connection holds until they are read, DefaultFlowQueue by default. A datagram larger than 2 KiB takes the room of several in proportion to its size, so a connection holds at most n × 2 KiB of queued datagrams, or a single larger one.
type PacketInfo ¶
type PacketInfo struct {
// Src is the datagram's source.
Src netip.AddrPort
// Dst is the destination the datagram was originally sent to.
Dst netip.AddrPort
// Redirected reports whether a redirect brought the datagram to the
// socket. A datagram sent to the socket directly reports false:
// forwarding it would send it to the socket again.
Redirected bool
}
PacketInfo describes a datagram that ReadFromUDP read.
func ReadFromUDP ¶
ReadFromUDP reads one datagram from c, a socket from ListenPacket, into b and returns its length and what is known of it.
A datagram for a port other than c's, or, when c is bound to one address, for another address, was redirected. One for c's port on a wildcard socket was redirected unless its destination is an address of this host, which is looked up as for OriginalDestination; addresses found local are remembered for a minute, so a datagram to an address removed meanwhile may be reported as direct. Listening on a port that redirected traffic does not use, as DialUDP needs anyway, avoids the lookup.
A datagram without the original destination, as on a socket not from ListenPacket, reports c's own address as Dst. If the datagram's control messages were cut short before the original destination, it returns the datagram and its source with ErrControlTruncated.