Hunter0x7c7
2022-08-11 b8230139fb40edea387617b6accd8371e37eda58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package internet
 
import (
    "encoding/binary"
    "net"
    "os"
    "syscall"
    "unsafe"
 
    "golang.org/x/sys/unix"
)
 
const (
    sysPFINOUT     = 0x0
    sysPFIN        = 0x1
    sysPFOUT       = 0x2
    sysPFFWD       = 0x3
    sysDIOCNATLOOK = 0xc04c4417
)
 
type pfiocNatlook struct {
    Saddr     [16]byte /* pf_addr */
    Daddr     [16]byte /* pf_addr */
    Rsaddr    [16]byte /* pf_addr */
    Rdaddr    [16]byte /* pf_addr */
    Sport     uint16
    Dport     uint16
    Rsport    uint16
    Rdport    uint16
    Af        uint8
    Proto     uint8
    Direction uint8
    Pad       [1]byte
}
 
const (
    sizeofPfiocNatlook = 0x4c
    soReUsePort        = 0x00000200
    soReUsePortLB      = 0x00010000
)
 
func ioctl(s uintptr, ioc int, b []byte) error {
    if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, s, uintptr(ioc), uintptr(unsafe.Pointer(&b[0]))); errno != 0 {
        return error(errno)
    }
    return nil
}
 
func (nl *pfiocNatlook) rdPort() int {
    return int(binary.BigEndian.Uint16((*[2]byte)(unsafe.Pointer(&nl.Rdport))[:]))
}
 
func (nl *pfiocNatlook) setPort(remote, local int) {
    binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&nl.Sport))[:], uint16(remote))
    binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&nl.Dport))[:], uint16(local))
}
 
// OriginalDst uses ioctl to read original destination from /dev/pf
func OriginalDst(la, ra net.Addr) (net.IP, int, error) {
    f, err := os.Open("/dev/pf")
    if err != nil {
        return net.IP{}, -1, newError("failed to open device /dev/pf").Base(err)
    }
    defer f.Close()
    fd := f.Fd()
    b := make([]byte, sizeofPfiocNatlook)
    nl := (*pfiocNatlook)(unsafe.Pointer(&b[0]))
    var raIP, laIP net.IP
    var raPort, laPort int
    switch la.(type) {
    case *net.TCPAddr:
        raIP = ra.(*net.TCPAddr).IP
        laIP = la.(*net.TCPAddr).IP
        raPort = ra.(*net.TCPAddr).Port
        laPort = la.(*net.TCPAddr).Port
        nl.Proto = syscall.IPPROTO_TCP
    case *net.UDPAddr:
        raIP = ra.(*net.UDPAddr).IP
        laIP = la.(*net.UDPAddr).IP
        raPort = ra.(*net.UDPAddr).Port
        laPort = la.(*net.UDPAddr).Port
        nl.Proto = syscall.IPPROTO_UDP
    }
    if raIP.To4() != nil {
        if laIP.IsUnspecified() {
            laIP = net.ParseIP("127.0.0.1")
        }
        copy(nl.Saddr[:net.IPv4len], raIP.To4())
        copy(nl.Daddr[:net.IPv4len], laIP.To4())
        nl.Af = syscall.AF_INET
    }
    if raIP.To16() != nil && raIP.To4() == nil {
        if laIP.IsUnspecified() {
            laIP = net.ParseIP("::1")
        }
        copy(nl.Saddr[:], raIP)
        copy(nl.Daddr[:], laIP)
        nl.Af = syscall.AF_INET6
    }
    nl.setPort(raPort, laPort)
    ioc := uintptr(sysDIOCNATLOOK)
    for _, dir := range []byte{sysPFOUT, sysPFIN} {
        nl.Direction = dir
        err = ioctl(fd, int(ioc), b)
        if err == nil || err != syscall.ENOENT {
            break
        }
    }
    if err != nil {
        return net.IP{}, -1, os.NewSyscallError("ioctl", err)
    }
 
    odPort := nl.rdPort()
    var odIP net.IP
    switch nl.Af {
    case syscall.AF_INET:
        odIP = make(net.IP, net.IPv4len)
        copy(odIP, nl.Rdaddr[:net.IPv4len])
    case syscall.AF_INET6:
        odIP = make(net.IP, net.IPv6len)
        copy(odIP, nl.Rdaddr[:])
    }
    return odIP, odPort, nil
}
 
func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error {
    if config.Mark != 0 {
        if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_USER_COOKIE, int(config.Mark)); err != nil {
            return newError("failed to set SO_USER_COOKIE").Base(err)
        }
    }
 
    if isTCPSocket(network) {
        switch config.Tfo {
        case SocketConfig_Enable:
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, 1); err != nil {
                return newError("failed to set TCP_FASTOPEN_CONNECT=1").Base(err)
            }
        case SocketConfig_Disable:
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, 0); err != nil {
                return newError("failed to set TCP_FASTOPEN_CONNECT=0").Base(err)
            }
        }
 
        if config.TcpKeepAliveIdle > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil {
                return newError("failed to set TCP_KEEPIDLE").Base(err)
            }
        }
        if config.TcpKeepAliveInterval > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil {
                return newError("failed to set TCP_KEEPINTVL").Base(err)
            }
        }
        if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil {
                return newError("failed to set SO_KEEPALIVE").Base(err)
            }
        }
    }
 
    if config.Tproxy.IsEnabled() {
        ip, _, _ := net.SplitHostPort(address)
        if net.ParseIP(ip).To4() != nil {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BINDANY, 1); err != nil {
                return newError("failed to set outbound IP_BINDANY").Base(err)
            }
        } else {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_BINDANY, 1); err != nil {
                return newError("failed to set outbound IPV6_BINDANY").Base(err)
            }
        }
    }
 
    if config.TxBufSize != 0 {
        if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_SNDBUF, int(config.TxBufSize)); err != nil {
            return newError("failed to set SO_SNDBUF").Base(err)
        }
    }
 
    if config.RxBufSize != 0 {
        if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, int(config.RxBufSize)); err != nil {
            return newError("failed to set SO_RCVBUF").Base(err)
        }
    }
 
    return nil
}
 
func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error {
    if config.Mark != 0 {
        if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_USER_COOKIE, int(config.Mark)); err != nil {
            return newError("failed to set SO_USER_COOKIE").Base(err)
        }
    }
    if isTCPSocket(network) {
        switch config.Tfo {
        case SocketConfig_Enable:
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, 1); err != nil {
                return newError("failed to set TCP_FASTOPEN=1").Base(err)
            }
        case SocketConfig_Disable:
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_FASTOPEN, 0); err != nil {
                return newError("failed to set TCP_FASTOPEN=0").Base(err)
            }
        }
        if config.TcpKeepAliveIdle > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPIDLE, int(config.TcpKeepAliveIdle)); err != nil {
                return newError("failed to set TCP_KEEPIDLE").Base(err)
            }
        }
        if config.TcpKeepAliveInterval > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, syscall.TCP_KEEPINTVL, int(config.TcpKeepAliveInterval)); err != nil {
                return newError("failed to set TCP_KEEPINTVL").Base(err)
            }
        }
        if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 {
            if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_KEEPALIVE, 1); err != nil {
                return newError("failed to set SO_KEEPALIVE").Base(err)
            }
        }
    }
 
    if config.Tproxy.IsEnabled() {
        if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IPV6, syscall.IPV6_BINDANY, 1); err != nil {
            if err := syscall.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BINDANY, 1); err != nil {
                return newError("failed to set inbound IP_BINDANY").Base(err)
            }
        }
    }
 
    if config.TxBufSize != 0 {
        if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_SNDBUF, int(config.TxBufSize)); err != nil {
            return newError("failed to set SO_SNDBUF").Base(err)
        }
    }
 
    if config.RxBufSize != 0 {
        if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, int(config.RxBufSize)); err != nil {
            return newError("failed to set SO_RCVBUF").Base(err)
        }
    }
 
    return nil
}
 
func bindAddr(fd uintptr, ip []byte, port uint32) error {
    setReuseAddr(fd)
    setReusePort(fd)
 
    var sockaddr syscall.Sockaddr
 
    switch len(ip) {
    case net.IPv4len:
        a4 := &syscall.SockaddrInet4{
            Port: int(port),
        }
        copy(a4.Addr[:], ip)
        sockaddr = a4
    case net.IPv6len:
        a6 := &syscall.SockaddrInet6{
            Port: int(port),
        }
        copy(a6.Addr[:], ip)
        sockaddr = a6
    default:
        return newError("unexpected length of ip")
    }
 
    return syscall.Bind(int(fd), sockaddr)
}
 
func setReuseAddr(fd uintptr) error {
    if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
        return newError("failed to set SO_REUSEADDR").Base(err).AtWarning()
    }
    return nil
}
 
func setReusePort(fd uintptr) error {
    if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, soReUsePortLB, 1); err != nil {
        if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, soReUsePort, 1); err != nil {
            return newError("failed to set SO_REUSEPORT").Base(err).AtWarning()
        }
    }
    return nil
}