Skip to content

Commit 3d19492

Browse files
committed
Set IP_TRANSPARENT when binding a non-local address
1 parent 5b4b2c2 commit 3d19492

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
@@ -64,12 +64,13 @@ func (l *ldapTarget) HandleConn(netConn net.Conn) {
6464
}
6565
raddr := netConn.RemoteAddr().(*net.TCPAddr)
6666
if l.localPoolRange.Contains(destAddr.IP) {
67-
sourceAddr := &net.TCPAddr{
68-
IP: raddr.IP,
69-
}
70-
dp.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
71-
return net.DialTCP(network, sourceAddr, destAddr)
67+
td := &TransparentDialer{
68+
SourceAddr: &net.TCPAddr{
69+
IP: raddr.IP,
70+
},
71+
DestAddr: destAddr,
7272
}
73+
dp.DialContext = td.DialContext
7374
}
7475
dp.HandleConn(netConn)
7576
}
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)