-
Notifications
You must be signed in to change notification settings - Fork 37
/
transparent_bsd.go
66 lines (59 loc) · 1.76 KB
/
transparent_bsd.go
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
// +build darwin freebsd
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"os/exec"
)
// realServerAddress returns an intercepted connection's original destination.
func realServerAddress(conn net.Conn) (net.Addr, error) {
// If the connection was intercepted with an IPFW fwd rule,
// its LocalAddr will be the original destination.
addr := conn.LocalAddr()
if !isLocalAddress(addr) {
return addr, nil
}
// If the connection was intercepted with a PF rdr rule,
// we need to examine the state table to find the original address.
pfctl := exec.Command("pfctl", "-ss")
stdout, err := pfctl.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("error getting output of pfctl -ss: %v", err)
}
if err := pfctl.Start(); err != nil {
return nil, fmt.Errorf("error running pfctl -ss: %v", err)
}
defer pfctl.Wait()
// Search for redirected connections matching the remote host and port.
// The lines look like this:
// all tcp 10.1.10.1:6502 (199.27.79.143:80) <- 10.1.10.203:62586 ESTABLISHED:ESTABLISHED
// dest. of rdr real server addr remote address
remote := append([]byte(") <- "), conn.RemoteAddr().String()...)
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
line := scanner.Bytes()
if !bytes.HasPrefix(line, []byte("all tcp ")) {
continue
}
loc := bytes.Index(line, remote)
if loc == -1 {
continue
}
openParen := bytes.LastIndex(line[:loc], []byte{'('})
if openParen == -1 {
continue
}
as := string(line[openParen+1 : loc])
a, err := net.ResolveTCPAddr("tcp", as)
if err != nil {
return nil, fmt.Errorf("error parsing address %q: %v", as, err)
}
return a, nil
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading output of pfctl -ss: %v", err)
}
return addr, nil
}