-
Notifications
You must be signed in to change notification settings - Fork 4
/
nat.go
105 lines (88 loc) · 2.26 KB
/
nat.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
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
package main
import (
"context"
"fmt"
"net"
"time"
nfqueue "github.com/florianl/go-nfqueue"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
func nat(c *cli.Context) error {
log.Info("Starting")
config := nfqueue.Config{
NfQueue: 42,
MaxPacketLen: 65535,
MaxQueueLen: 255,
Copymode: nfqueue.NfQnlCopyPacket,
ReadTimeout: 10 * time.Millisecond,
WriteTimeout: 15 * time.Millisecond,
}
queue, err := nfqueue.Open(&config)
if err != nil {
log.Fatalf("Connecting to NFQUEUE: %s", err)
}
defer queue.Close()
wanIPs, err := getWANIPs(*wanIf)
if err != nil {
log.Fatalf("Getting WAN IPs: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
translator := NewAddressAndPortDependentNAT(wanIPs)
process := func(a nfqueue.Attribute) int {
pkt := NewPacket(*a.Payload)
if pkt == nil {
// We don't know how to handle this kind of packet
queue.SetVerdict(*a.PacketID, nfqueue.NfDrop)
return 0
}
intf, err := net.InterfaceByIndex(int(*a.InDev))
if err != nil {
panic(err)
}
verdict := TranslatorVerdictDrop
switch intf.Name {
case *lanIf:
verdict = translator.TranslateOutUDP(*a.Payload)
case *wanIf:
verdict = translator.TranslateInUDP(*a.Payload)
}
switch verdict {
case TranslatorVerdictAccept:
queue.SetVerdict(*a.PacketID, nfqueue.NfAccept)
case TranslatorVerdictDrop:
queue.SetVerdict(*a.PacketID, nfqueue.NfDrop)
case TranslatorVerdictMangle:
queue.SetVerdictModPacket(*a.PacketID, nfqueue.NfAccept, *a.Payload)
}
return 0
}
err = queue.Register(ctx, process)
if err != nil {
log.Fatalf("Couldn't register packet processor: %s", err)
}
log.Info("Created tuns")
<-ctx.Done()
log.Info("Exiting")
return nil
}
func getWANIPs(ifName string) ([]net.IP, error) {
iface, err := net.InterfaceByName(ifName)
if err != nil {
return nil, fmt.Errorf("Getting %s interface info: %s", ifName, err)
}
ret := []net.IP{}
addrs, err := iface.Addrs()
if err != nil {
return nil, fmt.Errorf("Getting %s interface addrs: %s", ifName, err)
}
for _, addr := range addrs {
ipaddr := addr.(*net.IPAddr)
if ipaddr == nil || ipaddr.IP.To4() == nil || !ipaddr.IP.IsGlobalUnicast() {
continue
}
ret = append(ret, ipaddr.IP)
}
return ret, nil
}