From fa70c06af2b14eb6c116b524804ed89549596114 Mon Sep 17 00:00:00 2001 From: shw Date: Thu, 11 May 2017 15:35:58 +0000 Subject: [PATCH] CIDR subnet/mask matching support for firewall rules. --- sgfw/const.go | 1 + sgfw/dbus.go | 6 ++++++ sgfw/rules.go | 15 ++++++++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/sgfw/const.go b/sgfw/const.go index 10d6cf5..b6ed474 100644 --- a/sgfw/const.go +++ b/sgfw/const.go @@ -105,6 +105,7 @@ var FilterResultValue = map[string]FilterResult{ // DbusRule struct of the rule passed to the dbus interface type DbusRule struct { ID uint32 +// Net string App string Path string Verb uint16 diff --git a/sgfw/dbus.go b/sgfw/dbus.go index d43e8ce..3797a23 100644 --- a/sgfw/dbus.go +++ b/sgfw/dbus.go @@ -93,8 +93,14 @@ func (ds *dbusServer) IsEnabled() (bool, *dbus.Error) { } func createDbusRule(r *Rule) DbusRule { +// XXX: Uncommenting will require fw-settings upgrade. +/* netstr := "" + if r.network != nil { + netstr = r.network.String() + } */ return DbusRule{ ID: uint32(r.id), +// Net: netstr, App: path.Base(r.policy.path), Path: r.policy.path, Verb: uint16(r.rtype), diff --git a/sgfw/rules.go b/sgfw/rules.go index 7417dca..c41fd27 100644 --- a/sgfw/rules.go +++ b/sgfw/rules.go @@ -26,6 +26,7 @@ type Rule struct { mode RuleMode rtype RuleAction hostname string + network *net.IPNet addr uint32 saddr net.IP port uint16 @@ -53,6 +54,8 @@ func (r *Rule) AddrString(redact bool) string { port := "*" if r.hostname != "" { addr = r.hostname + } else if r.network != nil { + addr = r.network.String() } else if r.addr != matchAny && r.addr != noAddress { bs := make([]byte, 4) binary.BigEndian.PutUint32(bs, r.addr) @@ -96,6 +99,9 @@ log.Notice("comparison: ", hostname, " / ", dst, " : ", dstPort, " -> ", xip, " } return r.hostname == hostname } + if r.network != nil && r.network.Contains(dst) { + return true + } return r.addr == binary.BigEndian.Uint32(dst.To4()) } @@ -179,7 +185,7 @@ func (r *Rule) parse(s string) bool { } else if len(parts) > 2 { r.saddr = net.ParseIP(parts[2]) } - fmt.Println("----- rule parser: srcip = ", r.saddr) + return r.parseVerb(parts[0]) && r.parseTarget(parts[1]) } @@ -200,6 +206,7 @@ func (r *Rule) parseTarget(t string) bool { if len(addrPort) != 2 { return false } + return r.parseAddr(addrPort[0]) && r.parsePort(addrPort[1]) } @@ -213,10 +220,12 @@ func (r *Rule) parseAddr(a string) bool { r.hostname = a return true } - ip := net.ParseIP(a) - if ip == nil { +// ip := net.ParseIP(a) + ip, ipnet, err := net.ParseCIDR(a) + if err != nil || ip == nil { return false } + r.network = ipnet r.addr = binary.BigEndian.Uint32(ip.To4()) return true }