From 5d4b38c5b43e5c4c4547cf7fe8f3a86075ba2416 Mon Sep 17 00:00:00 2001 From: xSmurf Date: Mon, 28 Nov 2016 23:39:07 +0000 Subject: [PATCH] Refactor... --- fw-settings/config.go | 47 +++------------- fw-settings/dbus.go | 28 +++------- fw-settings/main.go | 10 ++-- fw-settings/rule_edit.go | 10 ++-- fw-settings/rules.go | 36 +++++++------ sgfw/config.go | 6 +-- sgfw/const.go | 112 +++++++++++++++++++++++++++++++++++++++ sgfw/dbus.go | 21 +++----- sgfw/log.go | 54 +++++++++++++++++++ sgfw/policy.go | 6 +-- sgfw/prompt.go | 44 +++------------ sgfw/rules.go | 49 +++++------------ sgfw/sgfw.go | 30 ----------- 13 files changed, 243 insertions(+), 210 deletions(-) create mode 100644 sgfw/const.go create mode 100644 sgfw/log.go diff --git a/fw-settings/config.go b/fw-settings/config.go index 3573ec3..a7c8fe2 100644 --- a/fw-settings/config.go +++ b/fw-settings/config.go @@ -2,38 +2,9 @@ package main import ( "github.com/gotk3/gotk3/gtk" - "github.com/op/go-logging" -) - -var levelToId = map[int32]string{ - int32(logging.ERROR): "error", - int32(logging.WARNING): "warning", - int32(logging.NOTICE): "notice", - int32(logging.INFO): "info", - int32(logging.DEBUG): "debug", -} -var idToLevel = func() map[string]int32 { - m := make(map[string]int32) - for k, v := range levelToId { - m[v] = k - } - return m -}() - -var actionToId = map[int32]string{ - 0: "ONCE", - 1: "SESSION", - 3: "FOREVER", -} - -var idToAction = func() map[string]int32 { - m := make(map[string]int32) - for k, v := range actionToId { - m[v] = k - } - return m -}() + "github.com/subgraph/fw-daemon/sgfw" +) func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) { var levelCombo *gtk.ComboBoxText @@ -56,7 +27,7 @@ func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) { } if lvl, ok := conf["log_level"].(int32); ok { - if id, ok := levelToId[lvl]; ok { + if id, ok := sgfw.LevelToId[lvl]; ok { levelCombo.SetActiveID(id) } } @@ -69,14 +40,12 @@ func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) { if v, ok := conf["prompt_expert"].(bool); ok { expertCheck.SetActive(v) } - if av, ok := conf["default_action"].(int32); ok { - if id, ok := actionToId[av]; ok { - actionCombo.SetActiveID(id) - } + if av, ok := conf["default_action"].(uint16); ok { + actionCombo.SetActiveID(sgfw.GetFilterScopeString(sgfw.FilterScope(av))) } b.ConnectSignals(map[string]interface{}{ "on_level_combo_changed": func() { - if lvl, ok := idToLevel[levelCombo.GetActiveID()]; ok { + if lvl, ok := sgfw.IdToLevel[levelCombo.GetActiveID()]; ok { dbus.setConfig("log_level", lvl) } }, @@ -90,9 +59,7 @@ func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) { dbus.setConfig("prompt_expert", expertCheck.GetActive()) }, "on_action_combo_changed": func() { - if al, ok := idToAction[actionCombo.GetActiveID()]; ok { - dbus.setConfig("default_action", al) - } + dbus.setConfig("default_action", sgfw.GetFilterScopeValue(actionCombo.GetActiveID())) }, }) diff --git a/fw-settings/dbus.go b/fw-settings/dbus.go index 8271495..57d94ae 100644 --- a/fw-settings/dbus.go +++ b/fw-settings/dbus.go @@ -1,6 +1,8 @@ package main import ( + "github.com/subgraph/fw-daemon/sgfw" + "github.com/godbus/dbus" ) @@ -8,23 +10,6 @@ type dbusObject struct { dbus.BusObject } -//type RuleMode uint16 - -const ( - RULE_MODE_SESSION uint16 = iota - RULE_MODE_PERMANENT - RULE_MODE_SYSTEM -) - -type dbusRule struct { - Id uint32 - App string - Path string - Verb uint32 - Target string - Mode uint16 -} - func newDbusObject() (*dbusObject, error) { conn, err := dbus.SystemBus() if err != nil { @@ -41,9 +26,10 @@ func (ob *dbusObject) isEnabled() (bool, error) { return flag, nil } -func (ob *dbusObject) listRules() ([]dbusRule, error) { - rules := []dbusRule{} - if err := ob.Call("com.subgraph.Firewall.ListRules", 0).Store(&rules); err != nil { +func (ob *dbusObject) listRules() ([]sgfw.DbusRule, error) { + rules := []sgfw.DbusRule{} + err := ob.Call("com.subgraph.Firewall.ListRules", 0).Store(&rules); + if err != nil { return nil, err } return rules, nil @@ -53,7 +39,7 @@ func (ob *dbusObject) deleteRule(id uint32) { ob.Call("com.subgraph.Firewall.DeleteRule", 0, id) } -func (ob *dbusObject) updateRule(rule *dbusRule) { +func (ob *dbusObject) updateRule(rule *sgfw.DbusRule) { ob.Call("com.subgraph.Firewall.UpdateRule", 0, rule) } diff --git a/fw-settings/main.go b/fw-settings/main.go index 23d845a..2b4f210 100644 --- a/fw-settings/main.go +++ b/fw-settings/main.go @@ -1,9 +1,11 @@ package main import ( + "fmt" "os" - "fmt" + "github.com/subgraph/fw-daemon/sgfw" + "github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/gtk" ) @@ -54,19 +56,19 @@ func activate(app *gtk.Application) { if _, err := dbus.isEnabled(); err != nil { failDialog(win, "Unable is connect to firewall daemon. Is it running?") } - rlPermanent.loadRules(RULE_MODE_PERMANENT) + rlPermanent.loadRules(sgfw.RULE_MODE_PERMANENT) rlSession := NewRuleList(dbus, win, boxSession) if _, err := dbus.isEnabled(); err != nil { failDialog(win, "Unable is connect to firewall daemon. Is it running?") } - rlSession.loadRules(RULE_MODE_SESSION) + rlSession.loadRules(sgfw.RULE_MODE_SESSION) rlSystem := NewRuleList(dbus, win, boxSystem) if _, err := dbus.isEnabled(); err != nil { failDialog(win, "Unable is connect to firewall daemon. Is it running?") } - rlSystem.loadRules(RULE_MODE_SYSTEM) + rlSystem.loadRules(sgfw.RULE_MODE_SYSTEM) loadConfig(win, b, dbus) app.AddWindow(win) diff --git a/fw-settings/rule_edit.go b/fw-settings/rule_edit.go index 1d484f0..d3c2263 100644 --- a/fw-settings/rule_edit.go +++ b/fw-settings/rule_edit.go @@ -7,6 +7,8 @@ import ( "strings" "unicode" + "github.com/subgraph/fw-daemon/sgfw" + "github.com/gotk3/gotk3/gtk" ) @@ -50,7 +52,7 @@ func newRuleEdit(rr *ruleRow, saveasnew bool) *ruleEdit { func (re *ruleEdit) updateDialogFields() { r := re.row.rule re.pathLabel.SetText(r.Path) - if r.Verb == RULE_ALLOW { + if sgfw.RuleAction(r.Verb) == sgfw.RULE_ACTION_ALLOW { re.verbCombo.SetActiveID("allow") } else { re.verbCombo.SetActiveID("deny") @@ -118,9 +120,9 @@ func (re *ruleEdit) updateRow() { r := re.row.rule switch re.verbCombo.GetActiveID() { case "allow": - r.Verb = RULE_ALLOW + r.Verb = uint16(sgfw.RULE_ACTION_ALLOW) case "deny": - r.Verb = RULE_DENY + r.Verb = uint16(sgfw.RULE_ACTION_DENY) } host, _ := re.hostEntry.GetText() port, _ := re.portEntry.GetText() @@ -132,7 +134,7 @@ func (re *ruleEdit) run(saveasnew bool) { re.dialog.SetTransientFor(re.row.rl.win) if re.dialog.Run() == editDialogOk { if saveasnew { - re.row.rule.Mode = RULE_MODE_PERMANENT + re.row.rule.Mode = uint16(sgfw.RULE_MODE_PERMANENT) } re.updateRow() re.row.rl.dbus.updateRule(re.row.rule) diff --git a/fw-settings/rules.go b/fw-settings/rules.go index b9e1a07..7adad34 100644 --- a/fw-settings/rules.go +++ b/fw-settings/rules.go @@ -2,8 +2,12 @@ package main import ( "fmt" - "github.com/gotk3/gotk3/gtk" + "os" "strings" + + "github.com/subgraph/fw-daemon/sgfw" + + "github.com/gotk3/gotk3/gtk" ) type ruleList struct { @@ -17,7 +21,7 @@ type ruleList struct { type ruleRow struct { rl *ruleList - rule *dbusRule + rule *sgfw.DbusRule widget *gtk.ListBoxRow app_label *gtk.Label verb_label *gtk.Label @@ -36,18 +40,19 @@ func NewRuleList(dbus *dbusObject, win *gtk.Window, list *gtk.ListBox) *ruleList return rl } -func (rl *ruleList) loadRules(mode uint16) error { +func (rl *ruleList) loadRules(mode sgfw.RuleMode) error { rules, err := rl.dbus.listRules() if err != nil { + fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err) return err } rl.addRules(rules, mode) return nil } -func (rl *ruleList) addRules(rules []dbusRule, mode uint16) { +func (rl *ruleList) addRules(rules []sgfw.DbusRule, mode sgfw.RuleMode) { for i := 0; i < len(rules); i++ { - if rules[i].Mode != mode { + if sgfw.RuleMode(rules[i].Mode) != mode { continue } row := createWidget(&rules[i]) @@ -59,10 +64,7 @@ func (rl *ruleList) addRules(rules []dbusRule, mode uint16) { } } -const RULE_DENY = 0 -const RULE_ALLOW = 1 - -func createWidget(rule *dbusRule) *ruleRow { +func createWidget(rule *sgfw.DbusRule) *ruleRow { row := &ruleRow{} row.rule = rule builder := newBuilder("RuleItem") @@ -76,14 +78,14 @@ func createWidget(rule *dbusRule) *ruleRow { "save_button", &row.save_button, "delete_button", &row.delete_button, ) - switch rule.Mode { - case RULE_MODE_SYSTEM: + switch sgfw.RuleMode(rule.Mode) { + case sgfw.RULE_MODE_SYSTEM: row.edit_button.SetVisible(false) row.edit_button.SetNoShowAll(true) row.delete_button.SetSensitive(false) row.delete_button.SetTooltipText("Cannot delete system rules") break - case RULE_MODE_SESSION: + case sgfw.RULE_MODE_SESSION: row.save_button.SetSensitive(true) row.save_button.SetNoShowAll(false) break @@ -107,14 +109,14 @@ func (rr *ruleRow) update() { rr.target_label.SetText(getTargetText(rr.rule)) } -func getVerbText(rule *dbusRule) string { - if rule.Verb == RULE_ALLOW { - return "ALLOW:" +func getVerbText(rule *sgfw.DbusRule) string { + if sgfw.RuleAction(rule.Verb) == sgfw.RULE_ACTION_ALLOW { + return sgfw.RuleActionString[sgfw.RULE_ACTION_ALLOW]+ ":" } - return "DENY:" + return sgfw.RuleActionString[sgfw.RULE_ACTION_DENY]+ ":" } -func getTargetText(rule *dbusRule) string { +func getTargetText(rule *sgfw.DbusRule) string { if rule.Target == "*:*" { return "All connections" } diff --git a/sgfw/config.go b/sgfw/config.go index 1ac9a0d..14b29fc 100644 --- a/sgfw/config.go +++ b/sgfw/config.go @@ -21,7 +21,7 @@ type FirewallConfigs struct { PromptExpanded bool PromptExpert bool DefaultAction string - DefaultActionId int32 `toml:"-"` + DefaultActionId FilterScope `toml:"-"` } var FirewallConfig FirewallConfigs @@ -62,12 +62,12 @@ func readConfig() { } } FirewallConfig.LoggingLevel, _ = logging.LogLevel(FirewallConfig.LogLevel) - FirewallConfig.DefaultActionId = valueScope(FirewallConfig.DefaultAction) + FirewallConfig.DefaultActionId = GetFilterScopeValue(FirewallConfig.DefaultAction) } func writeConfig() { FirewallConfig.LogLevel = FirewallConfig.LoggingLevel.String() - FirewallConfig.DefaultAction = printScope(FirewallConfig.DefaultActionId) + FirewallConfig.DefaultAction = GetFilterScopeString(FirewallConfig.DefaultActionId) if _, err := os.Stat(path.Dir(configDefaultPath)); err != nil && os.IsNotExist(err) { if err := os.MkdirAll(path.Dir(configDefaultPath), 0755); err != nil { diff --git a/sgfw/const.go b/sgfw/const.go new file mode 100644 index 0000000..f0ae3a2 --- /dev/null +++ b/sgfw/const.go @@ -0,0 +1,112 @@ +package sgfw + +import ( + "strings" +) + +const ( + STR_REDACTED = "[redacted]" + STR_UNKNOWN = "[uknown]" +) + +type RuleAction uint16 + +const ( + RULE_ACTION_DENY RuleAction = iota + RULE_ACTION_ALLOW +) + +var RuleActionString = map[RuleAction]string { + RULE_ACTION_DENY: "DENY", + RULE_ACTION_ALLOW: "ALLOW", +} + +var RuleActionValue = map[string]RuleAction { + "DENY": RULE_ACTION_DENY, + "ALLOW": RULE_ACTION_ALLOW, +} + +type RuleMode uint16 + +const ( + RULE_MODE_SESSION RuleMode = iota + RULE_MODE_PERMANENT + RULE_MODE_SYSTEM +) + +var RuleModeString = map[RuleMode]string { + RULE_MODE_SESSION: "SESSION", + RULE_MODE_PERMANENT: "PERMANENT", + RULE_MODE_SYSTEM: "SYSTEM", +} + +var RuleModeValue = map[string]RuleMode { + "SESSION": RULE_MODE_SESSION, + "PERMANENT": RULE_MODE_PERMANENT, + "SYSTEM": RULE_MODE_SYSTEM, +} + + +type FilterScope uint16 +const ( + APPLY_ONCE FilterScope = iota + APPLY_SESSION + APPLY_FOREVER +) + +var FilterScopeString = map[FilterScope]string { + APPLY_ONCE: "ONCE", + APPLY_SESSION: "SESSION", + APPLY_FOREVER: "FOREVER", +} + +var FilterScopeValue = map[string]FilterScope { + "ONCE": APPLY_ONCE, + "SESSION": APPLY_SESSION, + "FOREVER": APPLY_FOREVER, +} + + +func GetFilterScopeString(scope FilterScope) string { + if val, ok := FilterScopeString[scope]; ok { + return val + } + return FilterScopeString[APPLY_SESSION] +} + +func GetFilterScopeValue(scope string) FilterScope { + scope = strings.ToUpper(scope) + if val, ok := FilterScopeValue[scope]; ok { + return val + } + return APPLY_SESSION +} + +type FilterResult uint16 + +const ( + FILTER_DENY FilterResult = iota + FILTER_ALLOW + FILTER_PROMPT +) + +var FilterResultString = map[FilterResult]string{ + FILTER_DENY: "DENY", + FILTER_ALLOW: "ALLOW", + FILTER_PROMPT: "PROMPT", +} + +var FilterResultValue = map[string]FilterResult { + "DENY": FILTER_DENY, + "ALLOW": FILTER_ALLOW, + "PROMPT": FILTER_PROMPT, +} + +type DbusRule struct { + Id uint32 + App string + Path string + Verb uint16 + Target string + Mode uint16 +} diff --git a/sgfw/dbus.go b/sgfw/dbus.go index 33f5002..b7dedcb 100644 --- a/sgfw/dbus.go +++ b/sgfw/dbus.go @@ -54,15 +54,6 @@ type dbusServer struct { prompter *prompter } -type DbusRule struct { - Id uint32 - App string - Path string - Verb uint32 - Target string - Mode uint16 -} - func newDbusServer() (*dbusServer, error) { conn, err := dbus.SystemBus() if err != nil { @@ -106,7 +97,7 @@ func createDbusRule(r *Rule) DbusRule { Id: uint32(r.id), App: path.Base(r.policy.path), Path: r.policy.path, - Verb: uint32(r.rtype), + Verb: uint16(r.rtype), Target: r.AddrString(false), Mode: uint16(r.mode), } @@ -158,8 +149,8 @@ func (ds *dbusServer) UpdateRule(rule DbusRule) *dbus.Error { return nil } r.policy.lock.Lock() - if rule.Verb == RULE_ALLOW || rule.Verb == RULE_DENY { - r.rtype = int(rule.Verb) + if RuleAction(rule.Verb) == RULE_ACTION_ALLOW || RuleAction(rule.Verb) == RULE_ACTION_DENY { + r.rtype = RuleAction(rule.Verb) } r.hostname = tmp.hostname r.addr = tmp.addr @@ -179,7 +170,7 @@ func (ds *dbusServer) GetConfig() (map[string]dbus.Variant, *dbus.Error) { conf["log_redact"] = dbus.MakeVariant(FirewallConfig.LogRedact) conf["prompt_expanded"] = dbus.MakeVariant(FirewallConfig.PromptExpanded) conf["prompt_expert"] = dbus.MakeVariant(FirewallConfig.PromptExpert) - conf["default_action"] = dbus.MakeVariant(int32(FirewallConfig.DefaultActionId)) + conf["default_action"] = dbus.MakeVariant(uint16(FirewallConfig.DefaultActionId)) return conf, nil } @@ -200,8 +191,8 @@ func (ds *dbusServer) SetConfig(key string, val dbus.Variant) *dbus.Error { flag := val.Value().(bool) FirewallConfig.PromptExpert = flag case "default_action": - l := val.Value().(int32) - FirewallConfig.DefaultActionId = l + l := val.Value().(uint16) + FirewallConfig.DefaultActionId = FilterScope(l) } writeConfig() return nil diff --git a/sgfw/log.go b/sgfw/log.go new file mode 100644 index 0000000..a0113e9 --- /dev/null +++ b/sgfw/log.go @@ -0,0 +1,54 @@ +package sgfw + +import ( + "os" + "syscall" + "unsafe" + + "github.com/op/go-logging" +) + +var LevelToId = map[int32]string{ + int32(logging.ERROR): "error", + int32(logging.WARNING): "warning", + int32(logging.NOTICE): "notice", + int32(logging.INFO): "info", + int32(logging.DEBUG): "debug", +} + +var IdToLevel = func() map[string]int32 { + m := make(map[string]int32) + for k, v := range LevelToId { + m[v] = k + } + return m +}() + +var log = logging.MustGetLogger("sgfw") + +var logFormat = logging.MustStringFormatter( + "%{level:.4s} %{id:03x} %{message}", +) +var ttyFormat = logging.MustStringFormatter( + "%{color}%{time:15:04:05} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}", +) + +const ioctlReadTermios = 0x5401 + +func isTerminal(fd int) bool { + var termios syscall.Termios + _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) + return err == 0 +} + +func setupLoggerBackend(lvl logging.Level) logging.LeveledBackend { + format := logFormat + if isTerminal(int(os.Stderr.Fd())) { + format = ttyFormat + } + backend := logging.NewLogBackend(os.Stderr, "", 0) + formatter := logging.NewBackendFormatter(backend, format) + leveler := logging.AddModuleLevel(formatter) + leveler.SetLevel(lvl, "sgfw") + return leveler +} diff --git a/sgfw/policy.go b/sgfw/policy.go index 7ce9e99..85204dc 100644 --- a/sgfw/policy.go +++ b/sgfw/policy.go @@ -154,7 +154,7 @@ func (p *Policy) removePending(pc pendingConnection) { } } -func (p *Policy) processNewRule(r *Rule, scope int32) bool { +func (p *Policy) processNewRule(r *Rule, scope FilterScope) bool { p.lock.Lock() defer p.lock.Unlock() @@ -205,7 +205,7 @@ func (p *Policy) filterPending(rule *Rule) { if rule.match(pc.dst(), pc.dstPort(), pc.hostname()) { log.Infof("Adding rule for: %s", rule.getString(FirewallConfig.LogRedact)) log.Noticef("%s > %s", rule.getString(FirewallConfig.LogRedact), pc.print()) - if rule.rtype == RULE_ALLOW { + if rule.rtype == RULE_ACTION_ALLOW { pc.accept() } else { pc.drop() @@ -241,7 +241,7 @@ func printPacket(pkt *nfqueue.Packet, hostname string, pinfo *procsnitch.Info) s }() if FirewallConfig.LogRedact { - hostname = "[redacted]" + hostname = STR_REDACTED } name := hostname if name == "" { diff --git a/sgfw/prompt.go b/sgfw/prompt.go index 2891b6a..5ba5106 100644 --- a/sgfw/prompt.go +++ b/sgfw/prompt.go @@ -2,17 +2,11 @@ package sgfw import ( "fmt" - "github.com/godbus/dbus" "os/user" "strconv" - "strings" "sync" -) -const ( - APPLY_ONCE = iota - APPLY_SESSION - APPLY_FOREVER + "github.com/godbus/dbus" ) func newPrompter(conn *dbus.Conn) *prompter { @@ -64,33 +58,6 @@ func (p *prompter) processNextPacket() bool { return true } -func printScope(scope int32) string { - switch scope { - case APPLY_SESSION: - return "SESSION" - case APPLY_ONCE: - return "ONCE" - case APPLY_FOREVER: - return "FOREVER" - default: - return "SESSION" - } -} - -func valueScope(scope string) int32 { - scope = strings.ToUpper(scope) - switch scope { - case "SESSION": - return APPLY_SESSION - case "ONCE": - return APPLY_ONCE - case "FOREVER": - return APPLY_FOREVER - default: - return APPLY_SESSION - } -} - func (p *prompter) processConnection(pc pendingConnection) { var scope int32 var rule string @@ -112,7 +79,7 @@ func (p *prompter) processConnection(pc pendingConnection) { int32(pc.procInfo().Pid), FirewallConfig.PromptExpanded, FirewallConfig.PromptExpert, - FirewallConfig.DefaultActionId) + int32(FirewallConfig.DefaultActionId)) err := call.Store(&scope, &rule) if err != nil { log.Warningf("Error sending dbus RequestPrompt message: %v", err) @@ -128,15 +95,16 @@ func (p *prompter) processConnection(pc pendingConnection) { pc.drop() return } - if scope == APPLY_SESSION { + fscope := FilterScope(scope) + if fscope == APPLY_SESSION { r.mode = RULE_MODE_SESSION } - if !policy.processNewRule(r, scope) { + if !policy.processNewRule(r, fscope) { p.lock.Lock() defer p.lock.Unlock() p.removePolicy(pc.policy()) } - if scope == APPLY_FOREVER { + if fscope == APPLY_FOREVER { policy.fw.saveRules() } } diff --git a/sgfw/rules.go b/sgfw/rules.go index 162bde5..72c9db4 100644 --- a/sgfw/rules.go +++ b/sgfw/rules.go @@ -15,27 +15,14 @@ import ( "github.com/subgraph/go-procsnitch" ) -const ( - RULE_DENY = iota - RULE_ALLOW -) - const matchAny = 0 const noAddress = uint32(0xffffffff) -type RuleMode uint16 - -const ( - RULE_MODE_SESSION RuleMode = iota - RULE_MODE_PERMANENT - RULE_MODE_SYSTEM -) - type Rule struct { id uint policy *Policy mode RuleMode - rtype int + rtype RuleAction hostname string addr uint32 port uint16 @@ -46,13 +33,13 @@ func (r *Rule) String() string { } func (r *Rule) getString(redact bool) string { - rtype := "DENY" - if r.rtype == RULE_ALLOW { - rtype = "ALLOW" + rtype := RuleActionString[RULE_ACTION_DENY] + if r.rtype == RULE_ACTION_ALLOW { + rtype = RuleActionString[RULE_ACTION_ALLOW] } rmode := "" if r.mode == RULE_MODE_SYSTEM { - rmode = "|SYSTEM" + rmode = "|" + RuleModeString[RULE_MODE_SYSTEM] } return fmt.Sprintf("%s|%s%s", rtype, r.AddrString(redact), rmode) @@ -74,7 +61,7 @@ func (r *Rule) AddrString(redact bool) string { } if redact && addr != "*" { - addr = "[redacted]" + addr = STR_REDACTED } return fmt.Sprintf("%s:%s", addr, port) @@ -95,14 +82,6 @@ func (r *Rule) match(dst net.IP, dstPort uint16, hostname string) bool { return r.addr == binary.BigEndian.Uint32(dst) } -type FilterResult int - -const ( - FILTER_DENY FilterResult = iota - FILTER_ALLOW - FILTER_PROMPT -) - func (rl *RuleList) filterPacket(p *nfqueue.Packet, pinfo *procsnitch.Info, hostname string) FilterResult { return rl.filter(p, p.Dst, p.DstPort, hostname, pinfo) } @@ -116,9 +95,9 @@ func (rl *RuleList) filter(pkt *nfqueue.Packet, dst net.IP, dstPort uint16, host if r.match(dst, dstPort, hostname) { dstStr := dst.String() if FirewallConfig.LogRedact { - dstStr = "[redacted]" + dstStr = STR_REDACTED } - srcStr := "[uknown]" + srcStr := STR_UNKNOWN if pkt != nil { srcStr = fmt.Sprintf("%s:%d", pkt.Src, pkt.SrcPort) } @@ -127,9 +106,9 @@ func (rl *RuleList) filter(pkt *nfqueue.Packet, dst net.IP, dstPort uint16, host pinfo.ExePath, "TCP", srcStr, dstStr, dstPort) - if r.rtype == RULE_DENY { + if r.rtype == RULE_ACTION_DENY { return FILTER_DENY - } else if r.rtype == RULE_ALLOW { + } else if r.rtype == RULE_ACTION_ALLOW { result = FILTER_ALLOW } } @@ -155,11 +134,11 @@ func (r *Rule) parse(s string) bool { func (r *Rule) parseVerb(v string) bool { switch v { - case "ALLOW": - r.rtype = RULE_ALLOW + case RuleActionString[RULE_ACTION_ALLOW]: + r.rtype = RULE_ACTION_ALLOW return true - case "DENY": - r.rtype = RULE_DENY + case RuleActionString[RULE_ACTION_DENY]: + r.rtype = RULE_ACTION_DENY return true } return false diff --git a/sgfw/sgfw.go b/sgfw/sgfw.go index e204268..f548c90 100644 --- a/sgfw/sgfw.go +++ b/sgfw/sgfw.go @@ -7,7 +7,6 @@ import ( "sync" "syscall" "time" - "unsafe" "github.com/op/go-logging" @@ -15,35 +14,6 @@ import ( "github.com/subgraph/go-procsnitch" ) -var log = logging.MustGetLogger("sgfw") - -var logFormat = logging.MustStringFormatter( - "%{level:.4s} %{id:03x} %{message}", -) -var ttyFormat = logging.MustStringFormatter( - "%{color}%{time:15:04:05} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}", -) - -const ioctlReadTermios = 0x5401 - -func isTerminal(fd int) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} - -func setupLoggerBackend(lvl logging.Level) logging.LeveledBackend { - format := logFormat - if isTerminal(int(os.Stderr.Fd())) { - format = ttyFormat - } - backend := logging.NewLogBackend(os.Stderr, "", 0) - formatter := logging.NewBackendFormatter(backend, format) - leveler := logging.AddModuleLevel(formatter) - leveler.SetLevel(lvl, "sgfw") - return leveler -} - type Firewall struct { dbus *dbusServer dns *dnsCache