Use -C flag to detect if iptables rules already exist.

Additionally add rule to reject marked packets and clean up logging
noise
pull/16/head
brl 9 years ago
parent 57c1d9af5d
commit 27391175f7

@ -7,42 +7,38 @@ import (
"strings" "strings"
) )
const iptablesRule = "-t mangle -%c OUTPUT -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0 --queue-bypass" const iptablesRule = "OUTPUT -t mangle -m conntrack --ctstate NEW -j NFQUEUE --queue-num 0 --queue-bypass"
const dnsRule = "-%c INPUT --protocol udp -m multiport --source-ports 53 -j NFQUEUE --queue-num 0 --queue-bypass" const dnsRule = "INPUT --protocol udp --sport 53 -j NFQUEUE --queue-num 0 --queue-bypass"
const blockRule = "OUTPUT --protocol tcp -m mark --mark 1 -j REJECT"
func setupIPTables() { func setupIPTables() {
removeIPTRules(dnsRule, iptablesRule) addIPTRules(iptablesRule, dnsRule, blockRule)
addIPTRules(iptablesRule, dnsRule)
}
func removeIPTRules(rules ...string) {
for _, r := range rules {
iptables('D', r)
}
} }
func addIPTRules(rules ...string) { func addIPTRules(rules ...string) {
for _, r := range rules { for _, r := range rules {
if(iptables('C', r)) {
log.Info("IPTables rule already present: %s", r)
} else {
log.Info("Installing IPTables rule: %s", r)
iptables('I', r) iptables('I', r)
} }
} }
}
func iptables(verb rune, rule string) { func iptables(verb rune, rule string) bool {
iptablesPath, err := exec.LookPath("iptables") iptablesPath, err := exec.LookPath("iptables")
if err != nil { if err != nil {
log.Warning("Could not find iptables binary in path") log.Warning("Could not find iptables binary in path")
os.Exit(1) os.Exit(1)
} }
argLine := fmt.Sprintf("-%c %s", verb, rule)
argLine := fmt.Sprintf(rule, verb)
args := strings.Fields(argLine) args := strings.Fields(argLine)
fmt.Println(iptablesPath, argLine)
cmd := exec.Command(iptablesPath, args...) cmd := exec.Command(iptablesPath, args...)
out, err := cmd.CombinedOutput() _, err = cmd.CombinedOutput()
fmt.Fprintf(os.Stderr, string(out))
_, exitErr := err.(*exec.ExitError) _, exitErr := err.(*exec.ExitError)
if err != nil && !exitErr { if err != nil && !exitErr {
log.Warning("Error reading output: %v", err) log.Warning("Error running iptables: %v", err)
} }
return !exitErr
} }

Loading…
Cancel
Save