Refactor...

pull/41/head
xSmurf 8 years ago
parent 4b632fb6f2
commit 5d4b38c5b4

@ -2,38 +2,9 @@ package main
import ( import (
"github.com/gotk3/gotk3/gtk" "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 { "github.com/subgraph/fw-daemon/sgfw"
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
}()
func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) { func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) {
var levelCombo *gtk.ComboBoxText 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 lvl, ok := conf["log_level"].(int32); ok {
if id, ok := levelToId[lvl]; ok { if id, ok := sgfw.LevelToId[lvl]; ok {
levelCombo.SetActiveID(id) levelCombo.SetActiveID(id)
} }
} }
@ -69,14 +40,12 @@ func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) {
if v, ok := conf["prompt_expert"].(bool); ok { if v, ok := conf["prompt_expert"].(bool); ok {
expertCheck.SetActive(v) expertCheck.SetActive(v)
} }
if av, ok := conf["default_action"].(int32); ok { if av, ok := conf["default_action"].(uint16); ok {
if id, ok := actionToId[av]; ok { actionCombo.SetActiveID(sgfw.GetFilterScopeString(sgfw.FilterScope(av)))
actionCombo.SetActiveID(id)
}
} }
b.ConnectSignals(map[string]interface{}{ b.ConnectSignals(map[string]interface{}{
"on_level_combo_changed": func() { "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) dbus.setConfig("log_level", lvl)
} }
}, },
@ -90,9 +59,7 @@ func loadConfig(win *gtk.Window, b *builder, dbus *dbusObject) {
dbus.setConfig("prompt_expert", expertCheck.GetActive()) dbus.setConfig("prompt_expert", expertCheck.GetActive())
}, },
"on_action_combo_changed": func() { "on_action_combo_changed": func() {
if al, ok := idToAction[actionCombo.GetActiveID()]; ok { dbus.setConfig("default_action", sgfw.GetFilterScopeValue(actionCombo.GetActiveID()))
dbus.setConfig("default_action", al)
}
}, },
}) })

@ -1,6 +1,8 @@
package main package main
import ( import (
"github.com/subgraph/fw-daemon/sgfw"
"github.com/godbus/dbus" "github.com/godbus/dbus"
) )
@ -8,23 +10,6 @@ type dbusObject struct {
dbus.BusObject 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) { func newDbusObject() (*dbusObject, error) {
conn, err := dbus.SystemBus() conn, err := dbus.SystemBus()
if err != nil { if err != nil {
@ -41,9 +26,10 @@ func (ob *dbusObject) isEnabled() (bool, error) {
return flag, nil return flag, nil
} }
func (ob *dbusObject) listRules() ([]dbusRule, error) { func (ob *dbusObject) listRules() ([]sgfw.DbusRule, error) {
rules := []dbusRule{} rules := []sgfw.DbusRule{}
if err := ob.Call("com.subgraph.Firewall.ListRules", 0).Store(&rules); err != nil { err := ob.Call("com.subgraph.Firewall.ListRules", 0).Store(&rules);
if err != nil {
return nil, err return nil, err
} }
return rules, nil return rules, nil
@ -53,7 +39,7 @@ func (ob *dbusObject) deleteRule(id uint32) {
ob.Call("com.subgraph.Firewall.DeleteRule", 0, id) 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) ob.Call("com.subgraph.Firewall.UpdateRule", 0, rule)
} }

@ -1,9 +1,11 @@
package main package main
import ( import (
"fmt"
"os" "os"
"fmt" "github.com/subgraph/fw-daemon/sgfw"
"github.com/gotk3/gotk3/glib" "github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk" "github.com/gotk3/gotk3/gtk"
) )
@ -54,19 +56,19 @@ func activate(app *gtk.Application) {
if _, err := dbus.isEnabled(); err != nil { if _, err := dbus.isEnabled(); err != nil {
failDialog(win, "Unable is connect to firewall daemon. Is it running?") 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) rlSession := NewRuleList(dbus, win, boxSession)
if _, err := dbus.isEnabled(); err != nil { if _, err := dbus.isEnabled(); err != nil {
failDialog(win, "Unable is connect to firewall daemon. Is it running?") 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) rlSystem := NewRuleList(dbus, win, boxSystem)
if _, err := dbus.isEnabled(); err != nil { if _, err := dbus.isEnabled(); err != nil {
failDialog(win, "Unable is connect to firewall daemon. Is it running?") 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) loadConfig(win, b, dbus)
app.AddWindow(win) app.AddWindow(win)

@ -7,6 +7,8 @@ import (
"strings" "strings"
"unicode" "unicode"
"github.com/subgraph/fw-daemon/sgfw"
"github.com/gotk3/gotk3/gtk" "github.com/gotk3/gotk3/gtk"
) )
@ -50,7 +52,7 @@ func newRuleEdit(rr *ruleRow, saveasnew bool) *ruleEdit {
func (re *ruleEdit) updateDialogFields() { func (re *ruleEdit) updateDialogFields() {
r := re.row.rule r := re.row.rule
re.pathLabel.SetText(r.Path) re.pathLabel.SetText(r.Path)
if r.Verb == RULE_ALLOW { if sgfw.RuleAction(r.Verb) == sgfw.RULE_ACTION_ALLOW {
re.verbCombo.SetActiveID("allow") re.verbCombo.SetActiveID("allow")
} else { } else {
re.verbCombo.SetActiveID("deny") re.verbCombo.SetActiveID("deny")
@ -118,9 +120,9 @@ func (re *ruleEdit) updateRow() {
r := re.row.rule r := re.row.rule
switch re.verbCombo.GetActiveID() { switch re.verbCombo.GetActiveID() {
case "allow": case "allow":
r.Verb = RULE_ALLOW r.Verb = uint16(sgfw.RULE_ACTION_ALLOW)
case "deny": case "deny":
r.Verb = RULE_DENY r.Verb = uint16(sgfw.RULE_ACTION_DENY)
} }
host, _ := re.hostEntry.GetText() host, _ := re.hostEntry.GetText()
port, _ := re.portEntry.GetText() port, _ := re.portEntry.GetText()
@ -132,7 +134,7 @@ func (re *ruleEdit) run(saveasnew bool) {
re.dialog.SetTransientFor(re.row.rl.win) re.dialog.SetTransientFor(re.row.rl.win)
if re.dialog.Run() == editDialogOk { if re.dialog.Run() == editDialogOk {
if saveasnew { if saveasnew {
re.row.rule.Mode = RULE_MODE_PERMANENT re.row.rule.Mode = uint16(sgfw.RULE_MODE_PERMANENT)
} }
re.updateRow() re.updateRow()
re.row.rl.dbus.updateRule(re.row.rule) re.row.rl.dbus.updateRule(re.row.rule)

@ -2,8 +2,12 @@ package main
import ( import (
"fmt" "fmt"
"github.com/gotk3/gotk3/gtk" "os"
"strings" "strings"
"github.com/subgraph/fw-daemon/sgfw"
"github.com/gotk3/gotk3/gtk"
) )
type ruleList struct { type ruleList struct {
@ -17,7 +21,7 @@ type ruleList struct {
type ruleRow struct { type ruleRow struct {
rl *ruleList rl *ruleList
rule *dbusRule rule *sgfw.DbusRule
widget *gtk.ListBoxRow widget *gtk.ListBoxRow
app_label *gtk.Label app_label *gtk.Label
verb_label *gtk.Label verb_label *gtk.Label
@ -36,18 +40,19 @@ func NewRuleList(dbus *dbusObject, win *gtk.Window, list *gtk.ListBox) *ruleList
return rl return rl
} }
func (rl *ruleList) loadRules(mode uint16) error { func (rl *ruleList) loadRules(mode sgfw.RuleMode) error {
rules, err := rl.dbus.listRules() rules, err := rl.dbus.listRules()
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err)
return err return err
} }
rl.addRules(rules, mode) rl.addRules(rules, mode)
return nil 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++ { for i := 0; i < len(rules); i++ {
if rules[i].Mode != mode { if sgfw.RuleMode(rules[i].Mode) != mode {
continue continue
} }
row := createWidget(&rules[i]) row := createWidget(&rules[i])
@ -59,10 +64,7 @@ func (rl *ruleList) addRules(rules []dbusRule, mode uint16) {
} }
} }
const RULE_DENY = 0 func createWidget(rule *sgfw.DbusRule) *ruleRow {
const RULE_ALLOW = 1
func createWidget(rule *dbusRule) *ruleRow {
row := &ruleRow{} row := &ruleRow{}
row.rule = rule row.rule = rule
builder := newBuilder("RuleItem") builder := newBuilder("RuleItem")
@ -76,14 +78,14 @@ func createWidget(rule *dbusRule) *ruleRow {
"save_button", &row.save_button, "save_button", &row.save_button,
"delete_button", &row.delete_button, "delete_button", &row.delete_button,
) )
switch rule.Mode { switch sgfw.RuleMode(rule.Mode) {
case RULE_MODE_SYSTEM: case sgfw.RULE_MODE_SYSTEM:
row.edit_button.SetVisible(false) row.edit_button.SetVisible(false)
row.edit_button.SetNoShowAll(true) row.edit_button.SetNoShowAll(true)
row.delete_button.SetSensitive(false) row.delete_button.SetSensitive(false)
row.delete_button.SetTooltipText("Cannot delete system rules") row.delete_button.SetTooltipText("Cannot delete system rules")
break break
case RULE_MODE_SESSION: case sgfw.RULE_MODE_SESSION:
row.save_button.SetSensitive(true) row.save_button.SetSensitive(true)
row.save_button.SetNoShowAll(false) row.save_button.SetNoShowAll(false)
break break
@ -107,14 +109,14 @@ func (rr *ruleRow) update() {
rr.target_label.SetText(getTargetText(rr.rule)) rr.target_label.SetText(getTargetText(rr.rule))
} }
func getVerbText(rule *dbusRule) string { func getVerbText(rule *sgfw.DbusRule) string {
if rule.Verb == RULE_ALLOW { if sgfw.RuleAction(rule.Verb) == sgfw.RULE_ACTION_ALLOW {
return "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 == "*:*" { if rule.Target == "*:*" {
return "All connections" return "All connections"
} }

@ -21,7 +21,7 @@ type FirewallConfigs struct {
PromptExpanded bool PromptExpanded bool
PromptExpert bool PromptExpert bool
DefaultAction string DefaultAction string
DefaultActionId int32 `toml:"-"` DefaultActionId FilterScope `toml:"-"`
} }
var FirewallConfig FirewallConfigs var FirewallConfig FirewallConfigs
@ -62,12 +62,12 @@ func readConfig() {
} }
} }
FirewallConfig.LoggingLevel, _ = logging.LogLevel(FirewallConfig.LogLevel) FirewallConfig.LoggingLevel, _ = logging.LogLevel(FirewallConfig.LogLevel)
FirewallConfig.DefaultActionId = valueScope(FirewallConfig.DefaultAction) FirewallConfig.DefaultActionId = GetFilterScopeValue(FirewallConfig.DefaultAction)
} }
func writeConfig() { func writeConfig() {
FirewallConfig.LogLevel = FirewallConfig.LoggingLevel.String() 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.Stat(path.Dir(configDefaultPath)); err != nil && os.IsNotExist(err) {
if err := os.MkdirAll(path.Dir(configDefaultPath), 0755); err != nil { if err := os.MkdirAll(path.Dir(configDefaultPath), 0755); err != nil {

@ -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
}

@ -54,15 +54,6 @@ type dbusServer struct {
prompter *prompter prompter *prompter
} }
type DbusRule struct {
Id uint32
App string
Path string
Verb uint32
Target string
Mode uint16
}
func newDbusServer() (*dbusServer, error) { func newDbusServer() (*dbusServer, error) {
conn, err := dbus.SystemBus() conn, err := dbus.SystemBus()
if err != nil { if err != nil {
@ -106,7 +97,7 @@ func createDbusRule(r *Rule) DbusRule {
Id: uint32(r.id), Id: uint32(r.id),
App: path.Base(r.policy.path), App: path.Base(r.policy.path),
Path: r.policy.path, Path: r.policy.path,
Verb: uint32(r.rtype), Verb: uint16(r.rtype),
Target: r.AddrString(false), Target: r.AddrString(false),
Mode: uint16(r.mode), Mode: uint16(r.mode),
} }
@ -158,8 +149,8 @@ func (ds *dbusServer) UpdateRule(rule DbusRule) *dbus.Error {
return nil return nil
} }
r.policy.lock.Lock() r.policy.lock.Lock()
if rule.Verb == RULE_ALLOW || rule.Verb == RULE_DENY { if RuleAction(rule.Verb) == RULE_ACTION_ALLOW || RuleAction(rule.Verb) == RULE_ACTION_DENY {
r.rtype = int(rule.Verb) r.rtype = RuleAction(rule.Verb)
} }
r.hostname = tmp.hostname r.hostname = tmp.hostname
r.addr = tmp.addr 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["log_redact"] = dbus.MakeVariant(FirewallConfig.LogRedact)
conf["prompt_expanded"] = dbus.MakeVariant(FirewallConfig.PromptExpanded) conf["prompt_expanded"] = dbus.MakeVariant(FirewallConfig.PromptExpanded)
conf["prompt_expert"] = dbus.MakeVariant(FirewallConfig.PromptExpert) 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 return conf, nil
} }
@ -200,8 +191,8 @@ func (ds *dbusServer) SetConfig(key string, val dbus.Variant) *dbus.Error {
flag := val.Value().(bool) flag := val.Value().(bool)
FirewallConfig.PromptExpert = flag FirewallConfig.PromptExpert = flag
case "default_action": case "default_action":
l := val.Value().(int32) l := val.Value().(uint16)
FirewallConfig.DefaultActionId = l FirewallConfig.DefaultActionId = FilterScope(l)
} }
writeConfig() writeConfig()
return nil return nil

@ -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
}

@ -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() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
@ -205,7 +205,7 @@ func (p *Policy) filterPending(rule *Rule) {
if rule.match(pc.dst(), pc.dstPort(), pc.hostname()) { if rule.match(pc.dst(), pc.dstPort(), pc.hostname()) {
log.Infof("Adding rule for: %s", rule.getString(FirewallConfig.LogRedact)) log.Infof("Adding rule for: %s", rule.getString(FirewallConfig.LogRedact))
log.Noticef("%s > %s", rule.getString(FirewallConfig.LogRedact), pc.print()) log.Noticef("%s > %s", rule.getString(FirewallConfig.LogRedact), pc.print())
if rule.rtype == RULE_ALLOW { if rule.rtype == RULE_ACTION_ALLOW {
pc.accept() pc.accept()
} else { } else {
pc.drop() pc.drop()
@ -241,7 +241,7 @@ func printPacket(pkt *nfqueue.Packet, hostname string, pinfo *procsnitch.Info) s
}() }()
if FirewallConfig.LogRedact { if FirewallConfig.LogRedact {
hostname = "[redacted]" hostname = STR_REDACTED
} }
name := hostname name := hostname
if name == "" { if name == "" {

@ -2,17 +2,11 @@ package sgfw
import ( import (
"fmt" "fmt"
"github.com/godbus/dbus"
"os/user" "os/user"
"strconv" "strconv"
"strings"
"sync" "sync"
)
const ( "github.com/godbus/dbus"
APPLY_ONCE = iota
APPLY_SESSION
APPLY_FOREVER
) )
func newPrompter(conn *dbus.Conn) *prompter { func newPrompter(conn *dbus.Conn) *prompter {
@ -64,33 +58,6 @@ func (p *prompter) processNextPacket() bool {
return true 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) { func (p *prompter) processConnection(pc pendingConnection) {
var scope int32 var scope int32
var rule string var rule string
@ -112,7 +79,7 @@ func (p *prompter) processConnection(pc pendingConnection) {
int32(pc.procInfo().Pid), int32(pc.procInfo().Pid),
FirewallConfig.PromptExpanded, FirewallConfig.PromptExpanded,
FirewallConfig.PromptExpert, FirewallConfig.PromptExpert,
FirewallConfig.DefaultActionId) int32(FirewallConfig.DefaultActionId))
err := call.Store(&scope, &rule) err := call.Store(&scope, &rule)
if err != nil { if err != nil {
log.Warningf("Error sending dbus RequestPrompt message: %v", err) log.Warningf("Error sending dbus RequestPrompt message: %v", err)
@ -128,15 +95,16 @@ func (p *prompter) processConnection(pc pendingConnection) {
pc.drop() pc.drop()
return return
} }
if scope == APPLY_SESSION { fscope := FilterScope(scope)
if fscope == APPLY_SESSION {
r.mode = RULE_MODE_SESSION r.mode = RULE_MODE_SESSION
} }
if !policy.processNewRule(r, scope) { if !policy.processNewRule(r, fscope) {
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock() defer p.lock.Unlock()
p.removePolicy(pc.policy()) p.removePolicy(pc.policy())
} }
if scope == APPLY_FOREVER { if fscope == APPLY_FOREVER {
policy.fw.saveRules() policy.fw.saveRules()
} }
} }

@ -15,27 +15,14 @@ import (
"github.com/subgraph/go-procsnitch" "github.com/subgraph/go-procsnitch"
) )
const (
RULE_DENY = iota
RULE_ALLOW
)
const matchAny = 0 const matchAny = 0
const noAddress = uint32(0xffffffff) const noAddress = uint32(0xffffffff)
type RuleMode uint16
const (
RULE_MODE_SESSION RuleMode = iota
RULE_MODE_PERMANENT
RULE_MODE_SYSTEM
)
type Rule struct { type Rule struct {
id uint id uint
policy *Policy policy *Policy
mode RuleMode mode RuleMode
rtype int rtype RuleAction
hostname string hostname string
addr uint32 addr uint32
port uint16 port uint16
@ -46,13 +33,13 @@ func (r *Rule) String() string {
} }
func (r *Rule) getString(redact bool) string { func (r *Rule) getString(redact bool) string {
rtype := "DENY" rtype := RuleActionString[RULE_ACTION_DENY]
if r.rtype == RULE_ALLOW { if r.rtype == RULE_ACTION_ALLOW {
rtype = "ALLOW" rtype = RuleActionString[RULE_ACTION_ALLOW]
} }
rmode := "" rmode := ""
if r.mode == RULE_MODE_SYSTEM { if r.mode == RULE_MODE_SYSTEM {
rmode = "|SYSTEM" rmode = "|" + RuleModeString[RULE_MODE_SYSTEM]
} }
return fmt.Sprintf("%s|%s%s", rtype, r.AddrString(redact), rmode) 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 != "*" { if redact && addr != "*" {
addr = "[redacted]" addr = STR_REDACTED
} }
return fmt.Sprintf("%s:%s", addr, port) 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) 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 { func (rl *RuleList) filterPacket(p *nfqueue.Packet, pinfo *procsnitch.Info, hostname string) FilterResult {
return rl.filter(p, p.Dst, p.DstPort, hostname, pinfo) 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) { if r.match(dst, dstPort, hostname) {
dstStr := dst.String() dstStr := dst.String()
if FirewallConfig.LogRedact { if FirewallConfig.LogRedact {
dstStr = "[redacted]" dstStr = STR_REDACTED
} }
srcStr := "[uknown]" srcStr := STR_UNKNOWN
if pkt != nil { if pkt != nil {
srcStr = fmt.Sprintf("%s:%d", pkt.Src, pkt.SrcPort) 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", pinfo.ExePath, "TCP",
srcStr, srcStr,
dstStr, dstPort) dstStr, dstPort)
if r.rtype == RULE_DENY { if r.rtype == RULE_ACTION_DENY {
return FILTER_DENY return FILTER_DENY
} else if r.rtype == RULE_ALLOW { } else if r.rtype == RULE_ACTION_ALLOW {
result = FILTER_ALLOW result = FILTER_ALLOW
} }
} }
@ -155,11 +134,11 @@ func (r *Rule) parse(s string) bool {
func (r *Rule) parseVerb(v string) bool { func (r *Rule) parseVerb(v string) bool {
switch v { switch v {
case "ALLOW": case RuleActionString[RULE_ACTION_ALLOW]:
r.rtype = RULE_ALLOW r.rtype = RULE_ACTION_ALLOW
return true return true
case "DENY": case RuleActionString[RULE_ACTION_DENY]:
r.rtype = RULE_DENY r.rtype = RULE_ACTION_DENY
return true return true
} }
return false return false

@ -7,7 +7,6 @@ import (
"sync" "sync"
"syscall" "syscall"
"time" "time"
"unsafe"
"github.com/op/go-logging" "github.com/op/go-logging"
@ -15,35 +14,6 @@ import (
"github.com/subgraph/go-procsnitch" "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 { type Firewall struct {
dbus *dbusServer dbus *dbusServer
dns *dnsCache dns *dnsCache

Loading…
Cancel
Save