-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
iptables.go
48 lines (41 loc) · 1.39 KB
/
iptables.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
package glutton
import (
"fmt"
"strings"
"github.com/coreos/go-iptables/iptables"
)
var (
// iptables -t mangle -I PREROUTING -p tcp ! --dport 22 -m state ! --state ESTABLISHED,RELATED -j TPROXY --on-port 5000 --on-ip 127.0.0.1
specTCP = "-p;%s;-m;state;!;--state;ESTABLISHED,RELATED;!;--dport;%d;-j;TPROXY;--on-port;%d;--on-ip;127.0.0.1"
specUDP = "-p;%s;-m;state;!;--state;ESTABLISHED,RELATED;!;--dport;%d;-j;TPROXY;--on-port;%d;--on-ip;127.0.0.1"
)
func genRuleSpec(chain, iface, protocol, _ string, sshPort, dport uint32) []string {
var spec string
switch protocol {
case "udp":
spec = specUDP
case "tcp":
spec = specTCP
}
switch chain {
case "PREROUTING":
spec = "-i;%s;" + spec
case "OUTPUT":
spec = "-o;%s;" + spec
}
return strings.Split(fmt.Sprintf(spec, iface, protocol, sshPort, dport), ";")
}
func setTProxyIPTables(iface, srcIP, protocol string, port, sshPort uint32) error {
ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
if err != nil {
return err
}
return ipt.AppendUnique("mangle", "PREROUTING", genRuleSpec("PREROUTING", iface, protocol, srcIP, sshPort, port)...)
}
func flushTProxyIPTables(iface, srcIP, protocol string, port, sshPort uint32) error {
ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
if err != nil {
return err
}
return ipt.Delete("mangle", "PREROUTING", genRuleSpec("PREROUTING", iface, protocol, srcIP, sshPort, port)...)
}