diff --git a/controllers/clusterwidenetworkpolicy_controller.go b/controllers/clusterwidenetworkpolicy_controller.go index d73e06cb..3132de62 100644 --- a/controllers/clusterwidenetworkpolicy_controller.go +++ b/controllers/clusterwidenetworkpolicy_controller.go @@ -117,7 +117,7 @@ func (r *ClusterwideNetworkPolicyReconciler) Reconcile(ctx context.Context, _ ct return ctrl.Result{}, err } - updated, err := nft.Apply() + updated, err := nft.Apply(ctx) if err != nil { return ctrl.Result{}, err } diff --git a/controllers/droptailer_controller.go b/controllers/droptailer_controller.go index ab02940b..790d72a0 100644 --- a/controllers/droptailer_controller.go +++ b/controllers/droptailer_controller.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "os" - "os/exec" "path" "time" @@ -15,6 +14,7 @@ import ( "github.com/go-logr/logr" firewallv1 "github.com/metal-stack/firewall-controller/v2/api/v1" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" "github.com/txn2/txeh" corev1 "k8s.io/api/core/v1" @@ -37,35 +37,19 @@ type DroptailerReconciler struct { Log logr.Logger - HostsFile string + // Hosts is the hosts file editor, it must be shared with other reconcilers manipulating the same hosts file. + Hosts *txeh.Hosts certificateBase string oldPodIP string - hosts *txeh.Hosts } // SetupWithManager configure this controller with required defaults func (r *DroptailerReconciler) SetupWithManager(mgr ctrl.Manager) error { - hc := &txeh.HostsConfig{ - ReadFilePath: r.HostsFile, - WriteFilePath: r.HostsFile, + if r.Hosts == nil { + return fmt.Errorf("hosts editor must be specified") } - _, err := os.Stat(r.HostsFile) - if os.IsNotExist(err) { - empty, err := os.Create(r.HostsFile) - if err != nil { - return err - } - _ = empty.Close() - } - - hosts, err := txeh.NewHosts(hc) - if err != nil { - return fmt.Errorf("unable to create hosts editor:%w", err) - } - - r.hosts = hosts certificateBase := os.Getenv("DROPTAILER_CLIENT_CERTIFICATE_BASE") if certificateBase != "" { @@ -163,9 +147,9 @@ func (r *DroptailerReconciler) Reconcile(ctx context.Context, req ctrl.Request) podIP := pod.Status.PodIP if podIP != "" && r.oldPodIP != podIP { r.Log.Info("podIP changed, update /etc/hosts", "old", r.oldPodIP, "new", podIP) - r.hosts.RemoveHost("droptailer") - r.hosts.AddHost(podIP, "droptailer") - err := r.hosts.Save() + r.Hosts.RemoveHost("droptailer") + r.Hosts.AddHost(podIP, "droptailer") + err := r.Hosts.Save() if err != nil { r.Log.Error(err, "could not write droptailer hosts entry") return ctrl.Result{}, fmt.Errorf("could not write droptailer hosts entry:%w", err) @@ -173,7 +157,7 @@ func (r *DroptailerReconciler) Reconcile(ctx context.Context, req ctrl.Request) r.oldPodIP = podIP } - err = exec.Command("systemctl", "restart", "droptailer.service").Run() + err = systemd.Restart(ctx, "droptailer.service") if err != nil { return ctrl.Result{}, err } diff --git a/controllers/evebox_controller.go b/controllers/evebox_controller.go new file mode 100644 index 00000000..f3d52c3f --- /dev/null +++ b/controllers/evebox_controller.go @@ -0,0 +1,104 @@ +package controllers + +import ( + "context" + "fmt" + + "github.com/go-logr/logr" + "github.com/txn2/txeh" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/predicate" + + firewallv1 "github.com/metal-stack/firewall-controller/v2/api/v1" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" +) + +const ( + // eveboxHostname is the hostname under which the evebox server in the shoot is reachable from the firewall. + // the evebox server url in the firewall spec is expected to reference this hostname. + eveboxHostname = "evebox" + eveboxAppLabel = "evebox" + eveboxAgentService = "evebox.service" +) + +// EveboxReconciler keeps a hosts entry pointing to the pod ip of the evebox server running in the shoot +// such that the evebox agent on the firewall can reach it under a stable name. +type EveboxReconciler struct { + ShootClient client.Client + Log logr.Logger + Hosts *txeh.Hosts + + oldPodIP string +} + +// SetupWithManager configures this controller with required defaults +func (r *EveboxReconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.Hosts == nil { + return fmt.Errorf("hosts editor must be specified") + } + + eveboxPredicate := predicate.NewPredicateFuncs(func(obj client.Object) bool { + if obj.GetNamespace() != firewallv1.ClusterwideNetworkPolicyNamespace { + return false + } + + return obj.GetLabels()["app"] == eveboxAppLabel + }) + + return ctrl.NewControllerManagedBy(mgr). + Named("evebox"). + For(&corev1.Pod{}, builder.WithPredicates(eveboxPredicate)). + Complete(r) +} + +// Reconcile updates the evebox hosts entry with the evebox server pod ip and restarts the evebox agent on change. +func (r *EveboxReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + pod := &corev1.Pod{} + if err := r.ShootClient.Get(ctx, req.NamespacedName, pod); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + + return ctrl.Result{}, fmt.Errorf("error retrieving evebox pod: %w", err) + } + + if !pod.GetDeletionTimestamp().IsZero() { + r.Log.Info("evebox pod is being deleted") + return ctrl.Result{}, nil + } + + podIP := pod.Status.PodIP + if podIP == "" || podIP == r.oldPodIP { + return ctrl.Result{}, nil + } + + r.Log.Info("evebox pod ip changed, updating hosts file", "old", r.oldPodIP, "new", podIP) + + r.Hosts.RemoveHost(eveboxHostname) + r.Hosts.AddHost(podIP, eveboxHostname) + if err := r.Hosts.Save(); err != nil { + return ctrl.Result{}, fmt.Errorf("could not write evebox hosts entry: %w", err) + } + + r.oldPodIP = podIP + + // only restart the agent when it is enabled, the agent is deployed by the firewall reconciler + enabled, err := systemd.AnyUnitFileEnabled(ctx, eveboxAgentService) + if err != nil { + return ctrl.Result{}, fmt.Errorf("unable to check if evebox agent is enabled: %w", err) + } + + if enabled { + if err := systemd.Restart(ctx, eveboxAgentService); err != nil { + return ctrl.Result{}, fmt.Errorf("unable to restart evebox agent: %w", err) + } + } + + r.Log.Info("evebox hosts entry successfully reconciled") + + return ctrl.Result{}, nil +} diff --git a/controllers/firewall_controller.go b/controllers/firewall_controller.go index 14c9e52b..d2691e5c 100644 --- a/controllers/firewall_controller.go +++ b/controllers/firewall_controller.go @@ -28,7 +28,9 @@ import ( "github.com/metal-stack/firewall-controller-manager/api/v2/helper" firewallv1 "github.com/metal-stack/firewall-controller/v2/api/v1" "github.com/metal-stack/firewall-controller/v2/pkg/network" + "github.com/metal-stack/firewall-controller/v2/pkg/suricata" "github.com/metal-stack/firewall-controller/v2/pkg/updater" + osnet "github.com/metal-stack/os-installer/pkg/network" ) // FirewallReconciler reconciles a Firewall object @@ -63,6 +65,9 @@ const ( nftablesExporterService = "nftables-exporter" nftablesExporterNamedPort = "nftexporter" nftablesExporterPort = 9630 + suricataExporterService = "suricata-exporter" + suricataExporterNamedPort = "suricataexporter" + suricataExporterPort = 9917 exporterLabelKey = "app" ) @@ -94,6 +99,8 @@ func (r *FirewallReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c return ctrl.Result{}, err } + firewallNetwork := osnet.New(allocation) + if r.Updater != nil { r.Log.Info("running binary updater") @@ -110,7 +117,7 @@ func (r *FirewallReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c var errs []error - changed, err := network.ReconcileNetwork(ctx, r.Log, f, allocation, r.FrrVersion) + changed, err := network.ReconcileNetwork(ctx, r.Log, f, firewallNetwork, r.FrrVersion) if changed && err == nil { r.recordFirewallEvent(f, corev1.EventTypeNormal, "Network settings", "reconciliation succeeded (frr.conf)") } else if changed && err != nil { @@ -125,6 +132,11 @@ func (r *FirewallReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c errs = append(errs, err) } + r.Log.Info("reconciling suricata") + if err = suricata.New(r.Log).Reconcile(ctx, r.Log, f, firewallNetwork); err != nil { + errs = append(errs, err) + } + r.Log.Info("reconciling ssh keys") if err := r.reconcileSSHKeys(f); err != nil { errs = append(errs, err) @@ -165,6 +177,11 @@ func (r *FirewallReconciler) reconcileFirewallServices(ctx context.Context, f *f port: nodeExporterPort, namedPort: nodeExporterNamedPort, }, + { + name: suricataExporterNamedPort, + port: suricataExporterPort, + namedPort: suricataExporterNamedPort, + }, } var errs []error diff --git a/controllers/firewall_monitor_annotation_controller.go b/controllers/firewall_monitor_annotation_controller.go index e929501d..42d4545f 100644 --- a/controllers/firewall_monitor_annotation_controller.go +++ b/controllers/firewall_monitor_annotation_controller.go @@ -3,12 +3,13 @@ package controllers import ( "context" "fmt" + "os/exec" "slices" "strings" "github.com/go-logr/logr" firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" - "github.com/metal-stack/firewall-controller/v2/pkg/updater" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/client-go/tools/record" @@ -89,7 +90,7 @@ func (r *FirewallMonitorAnnotationController) Reconcile(ctx context.Context, req services, ok := fwmon.Annotations[firewallv2.FirewallRestartSystemdServicesAnnotation] if !ok { - return reconcile.Result{}, nil + return r.reconcileSuricataUpdateSources(ctx, fwmon) } var ( @@ -126,7 +127,7 @@ func (r *FirewallMonitorAnnotationController) Reconcile(ctx context.Context, req r.Log.Info("restart service", "service-name", serviceName) - if err := updater.Restart(ctx, serviceName); err != nil { + if err := systemd.Restart(ctx, serviceName); err != nil { r.Recorder.Event( fwmon, corev1.EventTypeWarning, @@ -156,7 +157,7 @@ func (r *FirewallMonitorAnnotationController) Reconcile(ctx context.Context, req if restartFirewallController { r.Log.Info("restart firewall-controller") - if err := updater.Restart(ctx, firewallControllerService); err != nil { + if err := systemd.Restart(ctx, firewallControllerService); err != nil { r.Recorder.Event( fwmon, corev1.EventTypeWarning, @@ -175,5 +176,44 @@ func (r *FirewallMonitorAnnotationController) Reconcile(ctx context.Context, req } } + return r.reconcileSuricataUpdateSources(ctx, fwmon) +} + +func (r *FirewallMonitorAnnotationController) reconcileSuricataUpdateSources(ctx context.Context, fwmon *firewallv2.FirewallMonitor) (ctrl.Result, error) { + if !firewallv2.IsAnnotationTrue(fwmon, firewallv2.FirewallSuricataUpdateSourcesAnnotation) { + return ctrl.Result{}, nil + } + + r.Log.Info("updating suricata sources") + + cmd := exec.CommandContext(ctx, "suricata-update", "update-sources") + out, err := cmd.CombinedOutput() + if err != nil { + r.Recorder.Event( + fwmon, + corev1.EventTypeWarning, + "SuricataUpdateSources", + fmt.Sprintf("suricata source update failed: %s: %s", err, strings.TrimSpace(string(out))), + ) + + r.Log.Error(err, "error updating suricata sources", "output", string(out)) + return ctrl.Result{}, fmt.Errorf("unable to update suricata sources: %w", err) + } + + r.Recorder.Event( + fwmon, + corev1.EventTypeNormal, + "SuricataUpdateSources", + "suricata sources were updated through monitor annotation", + ) + + r.Log.Info("Removing annotation from firewall monitor", "annotation", firewallv2.FirewallSuricataUpdateSourcesAnnotation) + + patch := client.MergeFrom(fwmon.DeepCopy()) + delete(fwmon.Annotations, firewallv2.FirewallSuricataUpdateSourcesAnnotation) + if err := r.ShootClient.Patch(ctx, fwmon, patch); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{}, nil } diff --git a/controllers/firewall_monitor_controller.go b/controllers/firewall_monitor_controller.go index 70b6ae5f..bfb0f546 100644 --- a/controllers/firewall_monitor_controller.go +++ b/controllers/firewall_monitor_controller.go @@ -70,14 +70,23 @@ func (r *FirewallMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ return ctrl.Result{}, err } - idsStats := firewallv2.IDSStatsByDevice{} + var ( + idsStats = firewallv2.IDSStatsByDevice{} + s = suricata.New(r.Log) + ) + + suricataStatus, err := s.Status(ctx) + if err != nil { + r.Log.Error(err, "unable to figure out suricata status") + } + if r.IDSEnabled { - s := suricata.New() - ss, err := s.InterfaceStats(ctx) + interfaceStats, err := s.InterfaceStats(ctx) if err != nil { return ctrl.Result{}, err } - for iface, stat := range *ss { + + for iface, stat := range interfaceStats { idsStats[iface] = firewallv2.InterfaceStat{ Drop: stat.Drop, InvalidChecksums: stat.InvalidChecksums, @@ -121,6 +130,10 @@ func (r *FirewallMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ DistanceSupported: false, } + if suricataStatus != nil { + mon.ControllerStatus.Suricata = *suricataStatus + } + if !r.seedUpdated.IsZero() { mon.ControllerStatus.SeedUpdated = r.seedUpdated } diff --git a/controllers/hosts.go b/controllers/hosts.go new file mode 100644 index 00000000..832b322f --- /dev/null +++ b/controllers/hosts.go @@ -0,0 +1,31 @@ +package controllers + +import ( + "fmt" + "os" + + "github.com/txn2/txeh" +) + +// NewHostsFile returns a hosts file editor for the given path, creating the file if it does not exist. +// The returned editor is safe for concurrent use and should be shared between all reconcilers +// that manipulate the same hosts file, otherwise they overwrite each other's entries on save. +func NewHostsFile(path string) (*txeh.Hosts, error) { + if _, err := os.Stat(path); os.IsNotExist(err) { + empty, err := os.Create(path) + if err != nil { + return nil, err + } + _ = empty.Close() + } + + hosts, err := txeh.NewHosts(&txeh.HostsConfig{ + ReadFilePath: path, + WriteFilePath: path, + }) + if err != nil { + return nil, fmt.Errorf("unable to create hosts editor: %w", err) + } + + return hosts, nil +} diff --git a/go.mod b/go.mod index 921ec0b9..89700939 100644 --- a/go.mod +++ b/go.mod @@ -11,9 +11,9 @@ require ( github.com/google/nftables v0.3.0 github.com/ks2211/go-suricata v0.0.0-20200823200910-986ce1470707 github.com/metal-stack/api v0.8.4 - github.com/metal-stack/firewall-controller-manager v0.6.2 + github.com/metal-stack/firewall-controller-manager v0.6.3-0.20261125123020-7a65284b555d github.com/metal-stack/metal-lib v0.26.4 - github.com/metal-stack/os-installer v0.3.4 + github.com/metal-stack/os-installer v0.3.5-0.20261124113501-67fb7a0e3b4c github.com/metal-stack/v v1.0.3 github.com/miekg/dns v1.1.73 github.com/stretchr/testify v1.12.1 diff --git a/go.sum b/go.sum index 114a5f87..eec448d3 100644 --- a/go.sum +++ b/go.sum @@ -139,12 +139,12 @@ github.com/mdlayher/socket v0.8.0 h1:1lIVvHAs3sT623kPkPDa+I0nLVusskwnpWzp6ZUcNyc github.com/mdlayher/socket v0.8.0/go.mod h1:EhNb63aXqexVoTJDblxvDOSuIGIJinC4H5ZktnaJ6Rk= github.com/metal-stack/api v0.8.4 h1:jpArmt1s1NvIsg/ZH1bclTAGiuYjDo2tLGi8PxnxtXU= github.com/metal-stack/api v0.8.4/go.mod h1:U0CJxoo35jpS87HNDbVDrilxR106TnE5rJ/xSmgQkPg= -github.com/metal-stack/firewall-controller-manager v0.6.2 h1:QgL4sFqwZ8PYAOddN0V5o4/N+0zyF1ycWMyp9Yw9hL0= -github.com/metal-stack/firewall-controller-manager v0.6.2/go.mod h1:sYlFUCZDo1l60edNKAGzJ2PmligSwC5942ucY7b7F/Q= +github.com/metal-stack/firewall-controller-manager v0.6.3-0.20261125123020-7a65284b555d h1:fIYRR2G3Ifmo7L0vPOKnKCKZaTTBz2KAjdqu/4yIPg8= +github.com/metal-stack/firewall-controller-manager v0.6.3-0.20261125123020-7a65284b555d/go.mod h1:sYlFUCZDo1l60edNKAGzJ2PmligSwC5942ucY7b7F/Q= github.com/metal-stack/metal-lib v0.26.4 h1:Qg+JorX0AgQCkrCK07wvstGEoRcm/Y97E2UG5ZBAXjo= github.com/metal-stack/metal-lib v0.26.4/go.mod h1:cNXjPBs8SFnjqfBobuSbm5mDk6E/jS8PVeIOrV/7POE= -github.com/metal-stack/os-installer v0.3.4 h1:Ku9NvzxaYaKK4QIPJ7OyNYXiYZqBbNKxzcEfhrhwvDU= -github.com/metal-stack/os-installer v0.3.4/go.mod h1:vMOW7otAMwe8ReQxCPb/VE5KLvA9+q9VauDBhYwInEc= +github.com/metal-stack/os-installer v0.3.5-0.20261124113501-67fb7a0e3b4c h1:dzF19vzllIvkxf9ICK4I70M6Y1dXatdK8t+Olv9Hc6U= +github.com/metal-stack/os-installer v0.3.5-0.20261124113501-67fb7a0e3b4c/go.mod h1:vMOW7otAMwe8ReQxCPb/VE5KLvA9+q9VauDBhYwInEc= github.com/metal-stack/v v1.0.3 h1:Sh2oBlnxrCUD+mVpzfC8HiqL045YWkxs0gpTvkjppqs= github.com/metal-stack/v v1.0.3/go.mod h1:YTahEu7/ishwpYKnp/VaW/7nf8+PInogkfGwLcGPdXg= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= diff --git a/main.go b/main.go index e995b8e0..7073b009 100644 --- a/main.go +++ b/main.go @@ -59,7 +59,6 @@ func main() { logLevel string isVersion bool metricsAddr string - enableIDS bool enableSignatureCheck bool hostsFile string firewallName string @@ -69,8 +68,7 @@ func main() { flag.StringVar(&logLevel, "log-level", "info", "the log level of the controller") flag.BoolVar(&isVersion, "v", false, "Show firewall-controller version") flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.") - flag.BoolVar(&enableIDS, "enable-IDS", true, "Set this to false to exclude IDS.") - flag.StringVar(&hostsFile, "hosts-file", "/etc/hosts", "The hosts file to manipulate for the droptailer.") + flag.StringVar(&hostsFile, "hosts-file", "/etc/hosts", "The hosts file to manipulate for the droptailer and evebox server.") flag.BoolVar(&enableSignatureCheck, "enable-signature-check", true, "Set this to false to ignore signature checking.") flag.StringVar(&firewallName, "firewall-name", "", "the name of the firewall resource in the seed cluster to reconcile (defaults to hostname)") @@ -221,7 +219,6 @@ func main() { ShootClient: shootMgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("FirewallMonitorReconciler"), Recorder: shootMgr.GetEventRecorderFor("FirewallMonitorController"), // nolint:staticcheck - IDSEnabled: enableIDS, FirewallName: firewallName, Namespace: firewallv2.FirewallShootNamespace, } @@ -253,16 +250,32 @@ func main() { panic(err) } + hosts, err := controllers.NewHostsFile(hostsFile) + if err != nil { + l.Error("unable to create hosts file editor", "error", err) + panic(err) + } + // Droptailer Reconciler if err = (&controllers.DroptailerReconciler{ ShootClient: shootMgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("Droptailer"), - HostsFile: hostsFile, + Hosts: hosts, }).SetupWithManager(shootMgr); err != nil { l.Error("unable to create droptailer controller", "error", err) panic(err) } + // Evebox Reconciler + if err = (&controllers.EveboxReconciler{ + ShootClient: shootMgr.GetClient(), + Log: ctrl.Log.WithName("controllers").WithName("Evebox"), + Hosts: hosts, + }).SetupWithManager(shootMgr); err != nil { + l.Error("unable to create evebox controller", "error", err) + panic(err) + } + // ClusterwideNetworkPolicy Reconciler if err = (&controllers.ClusterwideNetworkPolicyReconciler{ SeedClient: seedMgr.GetClient(), diff --git a/pkg/network/network.go b/pkg/network/network.go index 8ec8236b..03bdbc05 100644 --- a/pkg/network/network.go +++ b/pkg/network/network.go @@ -7,7 +7,6 @@ import ( "github.com/Masterminds/semver/v3" "github.com/go-logr/logr" - apiv2 "github.com/metal-stack/api/go/metalstack/api/v2" firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" "github.com/metal-stack/os-installer/pkg/frr" osnet "github.com/metal-stack/os-installer/pkg/network" @@ -20,12 +19,12 @@ const ( // ReconcileNetwork reconciles the network settings for a firewall // Changes both the FRR-Configuration and Nftable rules when network prefixes or FRR template changes -func ReconcileNetwork(ctx context.Context, log logr.Logger, f *firewallv2.Firewall, allocation *apiv2.MachineAllocation, frrVersion *semver.Version) (bool, error) { +func ReconcileNetwork(ctx context.Context, log logr.Logger, f *firewallv2.Firewall, firewallNetwork *osnet.Network, frrVersion *semver.Version) (bool, error) { changed, err := frr.Render(ctx, &frr.Config{ Log: slog.New(logr.ToSlogHandler(log)), Reload: true, Validate: true, - Network: osnet.New(allocation), + Network: firewallNetwork, FRRVersion: frrVersion, }) if err != nil { diff --git a/pkg/nftables/nftables.go b/pkg/nftables/nftables.go index 1a097d45..c51b9440 100644 --- a/pkg/nftables/nftables.go +++ b/pkg/nftables/nftables.go @@ -20,6 +20,7 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/tools/record" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" mn "github.com/metal-stack/metal-lib/pkg/net" osnet "github.com/metal-stack/os-installer/pkg/network" "github.com/metal-stack/os-installer/pkg/nftables" @@ -32,7 +33,6 @@ const ( defaultIpv4RuleFile = "/etc/nftables/firewall-controller.v4" nftablesService = "nftables.service" nftBin = "/usr/sbin/nft" - systemctlBin = "/bin/systemctl" ) //go:embed *.tpl @@ -121,21 +121,21 @@ func (f *Nftables) ipv4RuleFile() string { // Flush flushes the nftables rules that were deduced from a k8s resources // after that the firewall is a "plain metal firewall" with default policy accept in the forward chain. -func (f *Nftables) Flush() error { +func (f *Nftables) Flush(ctx context.Context) error { _, err := os.Stat(f.ipv4RuleFile()) if os.IsNotExist(err) { - return f.reload() + return f.reload(ctx) } // only remove if rule file exists err = os.Remove(f.ipv4RuleFile()) if err != nil { return fmt.Errorf("could not delete ipv4 rule file: %w", err) } - return f.reload() + return f.reload(ctx) } // Apply applies the interface addresses through netlink and writes the /etc/nftables/firewall-controller.v4 rules file. -func (f *Nftables) Apply() (updated bool, err error) { +func (f *Nftables) Apply(ctx context.Context) (updated bool, err error) { tmpFile, err := os.CreateTemp(filepath.Dir(f.ipv4RuleFile()), "."+filepath.Base(f.ipv4RuleFile())) if err != nil { return @@ -169,7 +169,7 @@ func (f *Nftables) Apply() (updated bool, err error) { if f.dryRun { return } - err = f.reload() + err = f.reload(ctx) if err != nil { return } @@ -233,6 +233,10 @@ func (f *Nftables) renderFile(file string) error { } func (f *Nftables) validate(file string) error { + return validateNFTablesFile(file) +} + +func validateNFTablesFile(file string) error { c := exec.Command(nftBin, "-c", "-f", file) out, err := c.CombinedOutput() if err != nil { @@ -335,11 +339,10 @@ func (f *Nftables) reconcileIfaceAddresses() error { return errors.Join(errs...) } -func (f *Nftables) reload() error { - c := exec.Command(systemctlBin, "reload", nftablesService) - err := c.Run() - if err != nil { - return fmt.Errorf("could not reload nftables service, err: %w", err) - } - return nil +func (f *Nftables) reload(ctx context.Context) error { + return reloadNFTablesService(ctx) +} + +func reloadNFTablesService(ctx context.Context) error { + return systemd.Reload(ctx, nftablesService) } diff --git a/pkg/nftables/suricata.go b/pkg/nftables/suricata.go new file mode 100644 index 00000000..903c2bb5 --- /dev/null +++ b/pkg/nftables/suricata.go @@ -0,0 +1,94 @@ +package nftables + +import ( + "context" + "errors" + "fmt" + "log/slog" + "os" + + "github.com/go-logr/logr" + firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" + osnet "github.com/metal-stack/os-installer/pkg/network" + renderer "github.com/metal-stack/os-installer/pkg/template-renderer" +) + +const ( + suricataNFTablesPath = "/etc/nftables/suricata.nft" + // Forwarded traffic which enters through a VRF slave interface carries the + // VRF device as input interface in the forward hook. Match both devices like + // the main ruleset does, otherwise Suricata only sees the outgoing direction + // and drops the replies as midstream packets. + suricataNFTablesTemplate = `table inet suricata { + chain forward { + type filter hook forward priority -10; policy accept; + iifname { "{{ .Interface }}", "{{ .Vrf }}" } queue num 0 bypass comment "suricata nfqueue incoming" + oifname { "{{ .Interface }}", "{{ .Vrf }}" } queue num 0 bypass comment "suricata nfqueue outgoing" + } +} +` +) + +type Suricata struct { + network *osnet.Network + log logr.Logger +} + +func NewSuricata(network *osnet.Network, log logr.Logger) *Suricata { + return &Suricata{ + network: network, + log: log, + } +} + +func (s *Suricata) Reconcile(ctx context.Context, mode *firewallv2.SuricataListenMode) error { + enabled := mode != nil && *mode == firewallv2.SuricataListenModeNfqueue + + if !enabled { + if err := os.Remove(suricataNFTablesPath); err != nil { + if os.IsNotExist(err) { + return nil + } + return fmt.Errorf("unable to remove suricata nftables rules: %w", err) + } + + return reloadNFTablesService(ctx) + } + + if s.network == nil { + return errors.New("network is required for suricata nfqueue mode") + } + + externalInterface, err := s.network.GetDefaultRouteNetworkVlan() + if err != nil { + return fmt.Errorf("unable to determine external interface for suricata nfqueue mode: %w", err) + } + + externalVrf, err := s.network.GetDefaultRouteNetworkVrfName() + if err != nil { + return fmt.Errorf("unable to determine external vrf for suricata nfqueue mode: %w", err) + } + + r, err := renderer.New(&renderer.Config{ + Log: slog.New(logr.ToSlogHandler(s.log)), + TemplateString: suricataNFTablesTemplate, + Data: map[string]string{ + "Interface": externalInterface, + "Vrf": externalVrf, + }, + Validate: validateNFTablesFile, + }) + if err != nil { + return fmt.Errorf("unable to create suricata nftables renderer: %w", err) + } + + changed, err := r.Render(ctx, suricataNFTablesPath) + if err != nil { + return fmt.Errorf("unable to render suricata nftables rules: %w", err) + } + if !changed { + return nil + } + + return reloadNFTablesService(ctx) +} diff --git a/pkg/suricata/reconcile.go b/pkg/suricata/reconcile.go new file mode 100644 index 00000000..97ce96c6 --- /dev/null +++ b/pkg/suricata/reconcile.go @@ -0,0 +1,334 @@ +package suricata + +import ( + "bytes" + "context" + "errors" + "fmt" + "io/fs" + "log/slog" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + + "github.com/go-logr/logr" + firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" + "github.com/metal-stack/firewall-controller/v2/pkg/nftables" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" + osnet "github.com/metal-stack/os-installer/pkg/network" + renderer "github.com/metal-stack/os-installer/pkg/template-renderer" +) + +const eveboxAgentConfigTemplate = `server: + url: {{ .ServerURL | quote }} +{{- if .Key }} + key: {{ .Key | quote }} +{{- end }} +input: + sockets: + - path: {{ .SocketPath | quote }} + type: unix_stream +` + +type eveboxAgentTemplateData struct { + ServerURL string + Key string `json:"-"` + SocketPath string +} + +func (s *Suricata) Reconcile(ctx context.Context, log logr.Logger, f *firewallv2.Firewall, network *osnet.Network) error { + enabled := true + + if f.Spec.Suricata.Enabled != nil { + enabled = *f.Spec.Suricata.Enabled + } + + if !enabled { + log.Info("disabling suricata") + + if err := s.deleteEveboxAgent(ctx); err != nil { + return err + } + + if err := systemd.DisableAndStop(ctx, suricataAfPacketService); err != nil { + return fmt.Errorf("unable to disable suricata service: %w", err) + } + if err := systemd.DisableAndStop(ctx, suricataNFQueueService); err != nil { + return fmt.Errorf("unable to disable suricata nfqueue service: %w", err) + } + if err := nftables.NewSuricata(network, s.log).Reconcile(ctx, nil); err != nil { + return err + } + + return nil + } + + log.Info("enabling suricata", "listen-mode", f.Spec.Suricata.ListenMode, "evebox", f.Spec.Suricata.Evebox.Enabled, "evebox-server-url", f.Spec.Suricata.Evebox.ServerURL) + + if f.Spec.Suricata.Evebox.Enabled { + if err := s.deployEveboxAgent(ctx, &f.Spec.Suricata.Evebox); err != nil { + return err + } + + log.Info("evebox agent deployed") + } else { + if err := s.deleteEveboxAgent(ctx); err != nil { + return err + } + + log.Info("evebox agent deleted") + } + + if err := nftables.NewSuricata(network, s.log).Reconcile(ctx, f.Spec.Suricata.ListenMode); err != nil { + return err + } + + if err := s.reconcileListenMode(ctx, f.Spec.Suricata.ListenMode); err != nil { + return err + } + + suricataService, _, err := suricataUnits(f.Spec.Suricata.ListenMode) + if err != nil { + return err + } + + rulesetsChanged, err := s.reconcileDetectionRulesets(ctx, f.Spec.Suricata.DetectionRulesets) + if err != nil { + return err + } + + dropRulesChanged, err := reconcileDropRules(f.Spec.Suricata.DropRules) + if err != nil { + return err + } + + if !rulesetsChanged && !dropRulesChanged { + return nil + } + + log.Info("suricata rule configuration changed, updating rules", "detection-rulesets-changed", rulesetsChanged, "drop-rules-changed", dropRulesChanged) + + if err := systemd.Start(ctx, suricataUpdateService); err != nil { + return fmt.Errorf("unable to update suricata rules: %w", err) + } + + if err := systemd.Reload(ctx, suricataService); err != nil { + return fmt.Errorf("unable to reload suricata with updated rules: %w", err) + } + + return nil +} + +func (s *Suricata) deployEveboxAgent(ctx context.Context, box *firewallv2.Evebox) error { + if box.ServerURL == "" { + return errors.New("evebox server URL must not be empty") + } + + // TlsEnabled, Certificate and CertificateKey are currently not used because + // the EveBox agent does not support client certificates. TLS is selected by + // the scheme of the server URL. + if err := os.MkdirAll(filepath.Dir(eveboxAgentConfigPath), 0755); err != nil { + return fmt.Errorf("unable to create evebox config directory: %w", err) + } + if err := os.MkdirAll(eveboxSocketDir, 0755); err != nil { + return fmt.Errorf("unable to create evebox socket directory: %w", err) + } + + r, err := renderer.New(&renderer.Config{ + Log: slog.New(logr.ToSlogHandler(s.log)), + TemplateString: eveboxAgentConfigTemplate, + Data: eveboxAgentTemplateData{ + ServerURL: box.ServerURL, + Key: box.Key, + SocketPath: eveboxSocketPath, + }, + }) + if err != nil { + return fmt.Errorf("unable to create evebox agent config renderer: %w", err) + } + + changed, err := r.Render(ctx, eveboxAgentConfigPath) + if err != nil { + return fmt.Errorf("unable to render evebox agent config: %w", err) + } + + if err := os.Chmod(eveboxAgentConfigPath, 0600); err != nil { + return fmt.Errorf("unable to restrict evebox agent config permissions: %w", err) + } + + if changed { + if err := systemd.EnableAndRestart(ctx, eveboxAgentService); err != nil { + return fmt.Errorf("unable to enable and restart evebox agent service: %w", err) + } + } else { + if err := systemd.EnableAndStart(ctx, eveboxAgentService); err != nil { + return fmt.Errorf("unable to enable and start evebox agent service: %w", err) + } + } + + return nil +} + +func (s *Suricata) deleteEveboxAgent(ctx context.Context) error { + if err := systemd.DisableAndStop(ctx, eveboxAgentService); err != nil { + return fmt.Errorf("unable to disable evebox agent service: %w", err) + } + + if err := os.Remove(eveboxAgentConfigPath); err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("unable to remove evebox agent config: %w", err) + } + + return nil +} + +func (s *Suricata) reconcileListenMode(ctx context.Context, mode *firewallv2.SuricataListenMode) error { + desiredService, otherService, err := suricataUnits(mode) + if err != nil { + return err + } + + if err := systemd.DisableAndStop(ctx, otherService); err != nil { + return fmt.Errorf("unable to disable suricata service %s: %w", otherService, err) + } + + if err := systemd.EnableAndStart(ctx, desiredService); err != nil { + return fmt.Errorf("unable to enable suricata service %s: %w", desiredService, err) + } + + return nil +} + +func suricataUnits(mode *firewallv2.SuricataListenMode) (desired string, other string, err error) { + listenMode := firewallv2.SuricataListenModeAfPacket + if mode != nil { + listenMode = *mode + } + + switch listenMode { + case firewallv2.SuricataListenModeAfPacket: + return suricataAfPacketService, suricataNFQueueService, nil + case firewallv2.SuricataListenModeNfqueue: + return suricataNFQueueService, suricataAfPacketService, nil + default: + return "", "", fmt.Errorf("unsupported suricata listen mode %q", listenMode) + } +} + +// reconcileDetectionRulesets enables the desired suricata-update sources and disables all others. +// It returns true if the enabled sources were changed and the rules need to be updated. +func (s *Suricata) reconcileDetectionRulesets(ctx context.Context, rulesets []string) (bool, error) { + desired := []string{defaultDetectionRule} + if len(rulesets) > 0 { + desired = uniqueSorted(rulesets) + } + + enabled, err := enabledDetectionRulesets() + if err != nil { + return false, err + } + + if slices.Equal(desired, enabled) { + return false, nil + } + + for _, ruleset := range desired { + if slices.Contains(enabled, ruleset) { + continue + } + + if _, err := runCommand(ctx, suricataUpdate, "enable-source", ruleset); err != nil { + return false, fmt.Errorf("unable to enable suricata detection ruleset %q: %w", ruleset, err) + } + } + + // Enabling a source can implicitly enable the default source. Re-read the + // enabled sources and disable everything that is not desired. + enabled, err = enabledDetectionRulesets() + if err != nil { + return false, err + } + + for _, ruleset := range enabled { + if slices.Contains(desired, ruleset) { + continue + } + + if _, err := runCommand(ctx, suricataUpdate, "disable-source", ruleset); err != nil { + return false, fmt.Errorf("unable to disable suricata detection ruleset %q: %w", ruleset, err) + } + } + + return true, nil +} + +// reconcileDropRules writes the drop.conf for suricata-update, which converts the matching rules from alert to drop. +// It returns true if the file was changed and the rules need to be updated. +func reconcileDropRules(rules []string) (bool, error) { + return reconcileDropRulesFile(suricataDropConfPath, rules) +} + +func reconcileDropRulesFile(path string, rules []string) (bool, error) { + desired := uniqueSorted(rules) + + for _, rule := range desired { + if strings.ContainsAny(rule, "\r\n") { + return false, fmt.Errorf("suricata drop rule %q must not contain line breaks", rule) + } + if strings.HasPrefix(rule, "#") { + return false, fmt.Errorf("suricata drop rule %q must not start with a comment character", rule) + } + } + + current, err := os.ReadFile(path) + exists := err == nil + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return false, fmt.Errorf("unable to read suricata drop config: %w", err) + } + + if len(desired) == 0 { + if !exists { + return false, nil + } + if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) { + return false, fmt.Errorf("unable to remove suricata drop config: %w", err) + } + return true, nil + } + + content := []byte(dropConfHeader + strings.Join(desired, "\n") + "\n") + + if exists && bytes.Equal(current, content) { + return false, nil + } + + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + return false, fmt.Errorf("unable to create suricata config directory: %w", err) + } + + if err := os.WriteFile(path, content, 0644); err != nil { // nolint:gosec + return false, fmt.Errorf("unable to write suricata drop config: %w", err) + } + + return true, nil +} + +func runCommand(ctx context.Context, name string, args ...string) ([]byte, error) { + cmd := exec.CommandContext(ctx, name, args...) + + var stderr bytes.Buffer + cmd.Stderr = &stderr + + out, err := cmd.Output() + if err != nil { + message := strings.TrimSpace(stderr.String()) + if message == "" { + return nil, fmt.Errorf("%s %s failed: %w", name, strings.Join(args, " "), err) + } + + return nil, fmt.Errorf("%s %s failed: %w: %s", name, strings.Join(args, " "), err, message) + } + + return out, nil +} diff --git a/pkg/suricata/reconcile_test.go b/pkg/suricata/reconcile_test.go new file mode 100644 index 00000000..3f105b64 --- /dev/null +++ b/pkg/suricata/reconcile_test.go @@ -0,0 +1,45 @@ +package suricata + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_reconcileDropRulesFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "suricata", "drop.conf") + + // no rules and no file is a noop + changed, err := reconcileDropRulesFile(path, nil) + require.NoError(t, err) + require.False(t, changed) + require.NoFileExists(t, path) + + // rules get written sorted and deduplicated + changed, err = reconcileDropRulesFile(path, []string{"re:Dshield Block Listed Source", " 2402000 ", "2402000", ""}) + require.NoError(t, err) + require.True(t, changed) + + content, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, dropConfHeader+"2402000\nre:Dshield Block Listed Source\n", string(content)) + + // same rules in a different order do not change anything + changed, err = reconcileDropRulesFile(path, []string{"2402000", "re:Dshield Block Listed Source"}) + require.NoError(t, err) + require.False(t, changed) + + // removing all rules removes the file + changed, err = reconcileDropRulesFile(path, []string{}) + require.NoError(t, err) + require.True(t, changed) + require.NoFileExists(t, path) + + // invalid rules are rejected + _, err = reconcileDropRulesFile(path, []string{"2402000\n# injected"}) + require.Error(t, err) + _, err = reconcileDropRulesFile(path, []string{"# 2402000"}) + require.Error(t, err) +} diff --git a/pkg/suricata/rulesets.go b/pkg/suricata/rulesets.go new file mode 100644 index 00000000..72e9d3e4 --- /dev/null +++ b/pkg/suricata/rulesets.go @@ -0,0 +1,104 @@ +package suricata + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "slices" + "sort" + "strings" + + "sigs.k8s.io/yaml" +) + +const ( + suricataStateDir = "/var/lib/suricata" + suricataSourcesDir = suricataStateDir + "/update/sources" + suricataUpdateIndexPath = suricataStateDir + "/update/cache/index.yaml" + defaultDetectionRule = "et/open" +) + +func availableDetectionRulesets() ([]string, error) { + result := []string{} + + content, err := os.ReadFile(suricataUpdateIndexPath) + switch { + case err == nil: + var index struct { + Sources map[string]map[string]any `json:"sources"` + } + if err := yaml.Unmarshal(content, &index); err != nil { + return nil, fmt.Errorf("unable to parse suricata update source index: %w", err) + } + + for name, source := range index.Sources { + if _, ok := source["deprecated"]; ok { + continue + } + if _, ok := source["obsolete"]; ok { + continue + } + + result = append(result, name) + } + sort.Strings(result) + case errors.Is(err, fs.ErrNotExist): + // noop + default: + return nil, fmt.Errorf("unable to read suricata update source index: %w", err) + } + + return result, nil +} + +func enabledDetectionRulesets() ([]string, error) { + result := []string{} + + err := filepath.WalkDir(suricataSourcesDir, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || !strings.HasSuffix(d.Name(), ".yaml") { + return nil + } + + content, err := os.ReadFile(p) + if err != nil { + return err + } + + var source struct { + Source string `json:"source"` + } + if err := yaml.Unmarshal(content, &source); err != nil { + return fmt.Errorf("unable to parse suricata source config %s: %w", p, err) + } + if source.Source != "" { + result = append(result, source.Source) + } + + return nil + }) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, fmt.Errorf("unable to read enabled suricata sources: %w", err) + } + + sort.Strings(result) + + return result, nil +} + +func uniqueSorted(values []string) []string { + result := make([]string, 0, len(values)) + for _, value := range values { + value = strings.TrimSpace(value) + if value == "" || slices.Contains(result, value) { + continue + } + result = append(result, value) + } + sort.Strings(result) + return result +} diff --git a/pkg/suricata/stats.go b/pkg/suricata/stats.go deleted file mode 100644 index 3d364052..00000000 --- a/pkg/suricata/stats.go +++ /dev/null @@ -1,53 +0,0 @@ -package suricata - -import ( - "context" - - "github.com/ks2211/go-suricata/client" -) - -// defaultSocket to communicate with suricata -const defaultSocket = "/run/suricata-command.socket" - -type Suricata struct { - socket string -} - -type InterfaceStats map[string]InterFaceStat - -type InterFaceStat struct { - Drop int - InvalidChecksums int - Pkts int -} - -func New() Suricata { - return Suricata{socket: defaultSocket} -} - -func (s *Suricata) InterfaceStats(ctx context.Context) (*InterfaceStats, error) { - suricata, err := client.CreateSocket(s.socket) - if err != nil { - return nil, err - } - defer suricata.Close() - - ifaces, err := suricata.IFaceListCommand(ctx) - if err != nil { - return nil, err - } - result := InterfaceStats{} - for _, iface := range ifaces.Ifaces { - stat, err := suricata.IFaceStatCommand(ctx, client.IFaceStatRequest{IFace: iface}) - if err != nil { - return nil, err - } - result[iface] = InterFaceStat{ - Drop: stat.Drop, - InvalidChecksums: stat.InvalidChecksums, - Pkts: stat.Pkts, - } - } - - return &result, nil -} diff --git a/pkg/suricata/suricata.go b/pkg/suricata/suricata.go new file mode 100644 index 00000000..910be426 --- /dev/null +++ b/pkg/suricata/suricata.go @@ -0,0 +1,166 @@ +package suricata + +import ( + "context" + "encoding/json" + "fmt" + "time" + + "github.com/go-logr/logr" + "github.com/ks2211/go-suricata/client" + firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + suricataAfPacketService = "suricata.service" + suricataNFQueueService = "suricata-ips.service" + suricataUpdateService = "suricata-update.service" + eveboxAgentService = "evebox.service" + + eveboxAgentConfigPath = "/etc/evebox/agent.yaml" + + // suricataDropConfPath is read by suricata-update, matching rules are converted to drop rules + suricataDropConfPath = "/etc/suricata/drop.conf" + dropConfHeader = "# This file is managed by the firewall-controller, do not edit.\n" + eveboxSocketDir = "/run/evebox" + eveboxSocketPath = "/run/evebox/eve.sock" + + suricataUpdate = "suricata-update" + suricatasc = "suricatasc" + + // defaultSocket to communicate with suricata + defaultSocket = "/run/suricata-command.socket" +) + +type ( + Suricata struct { + socket string + log logr.Logger + } + + InterfaceStats map[string]InterFaceStat + + InterFaceStat struct { + Drop int + InvalidChecksums int + Pkts int + } +) + +func New(log logr.Logger) *Suricata { + return &Suricata{ + socket: defaultSocket, + log: log, + } +} + +func (s *Suricata) InterfaceStats(ctx context.Context) (InterfaceStats, error) { + suricata, err := client.CreateSocket(s.socket) + if err != nil { + return nil, err + } + defer suricata.Close() + + ifaces, err := suricata.IFaceListCommand(ctx) + if err != nil { + return nil, err + } + result := InterfaceStats{} + for _, iface := range ifaces.Ifaces { + stat, err := suricata.IFaceStatCommand(ctx, client.IFaceStatRequest{IFace: iface}) + if err != nil { + return nil, err + } + result[iface] = InterFaceStat{ + Drop: stat.Drop, + InvalidChecksums: stat.InvalidChecksums, + Pkts: stat.Pkts, + } + } + + return result, nil +} + +func (s *Suricata) Status(ctx context.Context) (*firewallv2.SuricataStatus, error) { + status := &firewallv2.SuricataStatus{ + Running: false, + Uptime: metav1.Duration{}, + Version: "", + AvailableDetectionRulesets: []string{}, + EnabledDetectionRulesets: []string{}, + EveboxAgentRunning: false, + } + + enabled, err := systemd.AnyUnitFileEnabled(ctx, suricataAfPacketService, suricataNFQueueService) + if err != nil { + return nil, fmt.Errorf("unable to figure out if service is running: %w", err) + } + + if !enabled { + return status, nil + } + + querySuricata := func(command string) (json.RawMessage, error) { + out, err := runCommand(ctx, suricatasc, s.socket, "-c", command) + if err != nil { + return nil, fmt.Errorf("unable to query suricata socket: %w", err) + } + + var response struct { + Return string `json:"return"` + Message json.RawMessage `json:"message"` + } + + if err := json.Unmarshal(out, &response); err != nil { + return nil, fmt.Errorf("unable to parse suricata %s response: %w", command, err) + } + + if response.Return != "OK" { + return nil, fmt.Errorf("suricata command %s returned %q", command, response.Return) + } + + return response.Message, nil + } + + uptimeResponse, err := querySuricata("uptime") + if err != nil { + return nil, err + } + + var uptimeSeconds int64 + if err := json.Unmarshal(uptimeResponse, &uptimeSeconds); err != nil { + return nil, fmt.Errorf("unable to parse suricata uptime: %w", err) + } + status.Uptime = metav1.Duration{Duration: time.Duration(uptimeSeconds) * time.Second} + status.Running = true + + versionResponse, err := querySuricata("version") + if err != nil { + return nil, err + } + + if err := json.Unmarshal(versionResponse, &status.Version); err != nil { + return nil, fmt.Errorf("unable to parse suricata version: %w", err) + } + + enabled, err = systemd.AnyUnitFileEnabled(ctx, eveboxAgentService) + if err != nil { + return nil, err + } + + status.EveboxAgentRunning = enabled + + status.AvailableDetectionRulesets, err = availableDetectionRulesets() + if err != nil { + return nil, err + } + + status.EnabledDetectionRulesets, err = enabledDetectionRulesets() + if err != nil { + return nil, err + } + + return status, nil +} diff --git a/pkg/systemd/systemd.go b/pkg/systemd/systemd.go new file mode 100644 index 00000000..e570348d --- /dev/null +++ b/pkg/systemd/systemd.go @@ -0,0 +1,206 @@ +package systemd + +import ( + "context" + "fmt" + "path" + + "github.com/coreos/go-systemd/v22/dbus" +) + +const ( + modeReplace = "replace" + jobDone = "done" + jobSkipped = "skipped" +) + +func Start(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return runJob(ctx, unit, "start", dbc.StartUnitContext) + }) +} + +func Stop(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return runJob(ctx, unit, "stop", dbc.StopUnitContext) + }) +} + +func Restart(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return runJob(ctx, unit, "restart", dbc.RestartUnitContext) + }) +} + +func Reload(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return runJob(ctx, unit, "reload", dbc.ReloadUnitContext) + }) +} + +func DaemonReload(ctx context.Context) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return dbc.ReloadContext(ctx) + }) +} + +func Enable(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return enable(ctx, dbc, unit) + }) +} + +func Disable(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + return disable(ctx, dbc, unit) + }) +} + +func EnableAndStart(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + if err := enable(ctx, dbc, unit); err != nil { + return err + } + + return runJob(ctx, unit, "start", dbc.StartUnitContext) + }) +} + +func EnableAndRestart(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + if err := enable(ctx, dbc, unit); err != nil { + return err + } + + return runJob(ctx, unit, "restart", dbc.RestartUnitContext) + }) +} + +// DisableAndStop disables and stops the unit. Missing units are ignored so +// callers can reconcile against units that are not installed in every image. +func DisableAndStop(ctx context.Context, unit string) error { + return withConnection(ctx, func(dbc *dbus.Conn) error { + exists, err := unitFileExists(ctx, dbc, unit) + if err != nil { + return err + } + if !exists { + return nil + } + + if err := disable(ctx, dbc, unit); err != nil { + return err + } + + return runJob(ctx, unit, "stop", dbc.StopUnitContext) + }) +} + +func UnitFileExists(ctx context.Context, unit string) (bool, error) { + var exists bool + + err := withConnection(ctx, func(dbc *dbus.Conn) error { + var err error + exists, err = unitFileExists(ctx, dbc, unit) + return err + }) + + return exists, err +} + +// AnyUnitFileEnabled returns true when at least one of the given unit files is +// enabled. +func AnyUnitFileEnabled(ctx context.Context, units ...string) (bool, error) { + var enabled bool + + err := withConnection(ctx, func(dbc *dbus.Conn) error { + unitFiles, err := dbc.ListUnitFilesContext(ctx) + if err != nil { + return fmt.Errorf("unable to list unit files: %w", err) + } + + wanted := make(map[string]struct{}, len(units)) + for _, unit := range units { + wanted[unit] = struct{}{} + } + + for _, unit := range unitFiles { + if _, ok := wanted[path.Base(unit.Path)]; !ok { + continue + } + if unit.Type == "enabled" || unit.Type == "enabled-runtime" { + enabled = true + return nil + } + } + + return nil + }) + + return enabled, err +} + +func enable(ctx context.Context, dbc *dbus.Conn, unit string) error { + if _, _, err := dbc.EnableUnitFilesContext(ctx, []string{unit}, false, false); err != nil { + return fmt.Errorf("unable to enable unit %s: %w", unit, err) + } + + return nil +} + +func disable(ctx context.Context, dbc *dbus.Conn, unit string) error { + if _, err := dbc.DisableUnitFilesContext(ctx, []string{unit}, false); err != nil { + return fmt.Errorf("unable to disable unit %s: %w", unit, err) + } + + return nil +} + +func unitFileExists(ctx context.Context, dbc *dbus.Conn, unit string) (bool, error) { + units, err := dbc.ListUnitFilesContext(ctx) + if err != nil { + return false, fmt.Errorf("unable to list unit files: %w", err) + } + + for _, unitFile := range units { + if path.Base(unitFile.Path) == unit { + return true, nil + } + } + + return false, nil +} + +func withConnection(ctx context.Context, fn func(*dbus.Conn) error) error { + dbc, err := dbus.NewWithContext(ctx) + if err != nil { + return fmt.Errorf("unable to connect to dbus: %w", err) + } + defer dbc.Close() + + return fn(dbc) +} + +func runJob( + ctx context.Context, + unit string, + action string, + run func(context.Context, string, string, chan<- string) (int, error), +) error { + resultCh := make(chan string, 1) + + if _, err := run(ctx, unit, modeReplace, resultCh); err != nil { + return fmt.Errorf("unable to %s unit %s: %w", action, unit, err) + } + + select { + case result := <-resultCh: + if result != jobDone && result != jobSkipped { + return fmt.Errorf("unable to %s unit %s: job %s", action, unit, result) + } + + return nil + case <-ctx.Done(): + return fmt.Errorf("unable to %s unit %s: %w", action, unit, ctx.Err()) + } +} diff --git a/pkg/updater/common.go b/pkg/updater/common.go index 90c732c8..178d9d11 100644 --- a/pkg/updater/common.go +++ b/pkg/updater/common.go @@ -1,7 +1,6 @@ package updater import ( - "context" "crypto/sha256" "encoding/hex" "fmt" @@ -10,8 +9,6 @@ import ( "os" "path/filepath" "strings" - - "github.com/coreos/go-systemd/v22/dbus" ) func fetchBinaryAndChecksum(url string) (io.ReadCloser, string, error) { @@ -95,27 +92,3 @@ func slurpFile(url string) (string, error) { } return strings.Split(string(content), " ")[0], nil } - -const done = "done" - -func Restart(ctx context.Context, unitName string) error { - dbc, err := dbus.NewWithContext(ctx) - if err != nil { - return fmt.Errorf("unable to connect to dbus: %w", err) - } - defer dbc.Close() - - c := make(chan string) - _, err = dbc.RestartUnitContext(ctx, unitName, "replace", c) - - if err != nil { - return err - } - - job := <-c - if job != done { - return fmt.Errorf("restart failed %s", job) - } - - return nil -} diff --git a/pkg/updater/nftables-exporter.go b/pkg/updater/nftables-exporter.go index e71c4ff2..39842c80 100644 --- a/pkg/updater/nftables-exporter.go +++ b/pkg/updater/nftables-exporter.go @@ -9,6 +9,7 @@ import ( "os/exec" firewallv2 "github.com/metal-stack/firewall-controller-manager/api/v2" + "github.com/metal-stack/firewall-controller/v2/pkg/systemd" corev1 "k8s.io/api/core/v1" ) @@ -64,7 +65,7 @@ func (u *Updater) updateNFTablesExporter(ctx context.Context, f *firewallv2.Fire return err } - err = Restart(ctx, "nftables-exporter.service") + err = systemd.Restart(ctx, "nftables-exporter.service") if err != nil { u.log.Error(err, "error restarting nftables-exporter") return err