Skip to content

Commit 5c31cf3

Browse files
committed
Set IP_TRANSPARENT when binding a non-local address
1 parent e37d10e commit 5c31cf3

File tree

2 files changed

+41
-5
lines changed

2 files changed

+41
-5
lines changed

server/common/oursrc/scripts-proxy/main.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,12 +67,13 @@ func (l *ldapTarget) HandleConn(netConn net.Conn) {
6767
}
6868
raddr := netConn.RemoteAddr().(*net.TCPAddr)
6969
if l.localPoolRange.Contains(destAddr.IP) {
70-
sourceAddr := &net.TCPAddr{
71-
IP: raddr.IP,
72-
}
73-
dp.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
74-
return net.DialTCP(network, sourceAddr, destAddr)
70+
td := &TransparentDialer{
71+
SourceAddr: &net.TCPAddr{
72+
IP: raddr.IP,
73+
},
74+
DestAddr: destAddr,
7575
}
76+
dp.DialContext = td.DialContext
7677
}
7778
dp.HandleConn(netConn)
7879
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"log"
6+
"net"
7+
"syscall"
8+
)
9+
10+
// TransparentDialer makes a connection to DestAddr using SourceAddr as the non-local source address.
11+
type TransparentDialer struct {
12+
SourceAddr net.Addr
13+
DestAddr net.Addr
14+
}
15+
16+
func (t *TransparentDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
17+
d := &net.Dialer{
18+
LocalAddr: t.SourceAddr,
19+
Control: func(network, address string, c syscall.RawConn) error {
20+
return c.Control(func(fd uintptr) {
21+
for _, opt := range []int{
22+
syscall.IP_TRANSPARENT,
23+
syscall.IP_FREEBIND,
24+
} {
25+
err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, opt, 1)
26+
if err != nil {
27+
log.Printf("control: %s", err)
28+
return
29+
}
30+
}
31+
})
32+
},
33+
}
34+
return d.DialContext(ctx, network, t.DestAddr.String())
35+
}

0 commit comments

Comments
 (0)