From 1371b4849cfe937f7de50bf861a388c77a3524f0 Mon Sep 17 00:00:00 2001 From: Simone Margaritelli Date: Wed, 31 Mar 2021 16:10:57 +0200 Subject: [PATCH] fix: do not reset firewall and apply rules if there were no changes --- cmd/agent/main.go | 43 ++++++++++++++++++++++++++++++++----------- version/version.go | 2 +- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index 1478d3a..fc3d689 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -1,6 +1,8 @@ package main import ( + "crypto/sha256" + "encoding/json" "flag" "fmt" "github.com/evilsocket/islazy/log" @@ -8,6 +10,7 @@ import ( "github.com/evilsocket/shieldwall/version" "os" "os/signal" + "sort" "syscall" "time" ) @@ -38,6 +41,26 @@ func addAllowRules(s *State) { } } +func hashObject(v interface{}) (string, error) { + if raw, err := json.Marshal(v); err != nil { + return "", err + } else { + return fmt.Sprintf("%x", sha256.Sum256(raw)), nil + } +} + +func rulesHash(rules []firewall.Rule) string { + // make sure the order is always the same + sort.Slice(rules, func(i, j int) bool { + return rules[i].CreatedAt.Before(rules[j].CreatedAt) + }) + hash, err := hashObject(rules) + if err != nil { + log.Warning("can't hash rules: %v", err) + } + return hash +} + func main() { flag.Parse() @@ -83,24 +106,22 @@ func main() { api := NewAPI(conf.API) // main loop for { - prev := len(state.Rules) - + prevHash := rulesHash(state.Rules) if rules, err := api.FetchRules(); err != nil { log.Error("error polling api: %v", err) } else { state.Rules = rules - if len(conf.Allow) > 0 { addAllowRules(state) } - - num := len(state.Rules) - if num != prev { - log.Info("applying %d rules", num) - } - - if err = firewall.Apply(state.Rules, conf.Drops); err != nil { - log.Fatal("%v", err) + newHash := rulesHash(state.Rules) + if prevHash != newHash { + log.Info("applying %d rules", len(state.Rules)) + if err = firewall.Apply(state.Rules, conf.Drops); err != nil { + log.Fatal("%v", err) + } + } else { + log.Debug("no changes") } } diff --git a/version/version.go b/version/version.go index a892ec0..c3e7598 100644 --- a/version/version.go +++ b/version/version.go @@ -1,3 +1,3 @@ package version -const Version = "1.2.1" \ No newline at end of file +const Version = "1.2.0" \ No newline at end of file