diff --git a/cmd/probe.go b/cmd/probe.go index 31457cb7..803d8257 100644 --- a/cmd/probe.go +++ b/cmd/probe.go @@ -22,10 +22,8 @@ and what KubeArmor features will be supported e.g: observability, enforcement, e If KubeArmor is running, It probes which environment KubeArmor is running on (e.g: systemd mode, kubernetes etc.), the supported KubeArmor features in the environment, the pods being handled by KubeArmor and the policies running on each of these pods`, RunE: func(cmd *cobra.Command, args []string) error { - err := probe.PrintProbeResult(client, probeInstallOptions) return err - }, } diff --git a/cmd/recommend.go b/cmd/recommend.go index d9949c3f..191de888 100644 --- a/cmd/recommend.go +++ b/cmd/recommend.go @@ -23,12 +23,12 @@ var recommendCmd = &cobra.Command{ return err }, } + var updateCmd = &cobra.Command{ Use: "update", Short: "Updates policy-template cache", Long: "Updates the local cache of policy-templates ($HOME/.cache/karmor)", RunE: func(cmd *cobra.Command, args []string) error { - if _, err := genericpolicies.DownloadAndUnzipRelease(); err != nil { return err } diff --git a/cmd/root.go b/cmd/root.go index a1cfdb97..12213948 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -17,7 +17,7 @@ var rootCmd = &cobra.Command{ PersistentPreRunE: func(cmd *cobra.Command, args []string) error { var err error - //Initialise k8sClient for all child commands to inherit + // Initialise k8sClient for all child commands to inherit client, err = k8s.ConnectK8sClient() // fmt.Printf("%v", client.K8sClientset) if err != nil { diff --git a/cmd/rotate-tls.go b/cmd/rotate-tls.go index 5d77e6ef..cf97e6d7 100644 --- a/cmd/rotate-tls.go +++ b/cmd/rotate-tls.go @@ -5,18 +5,20 @@ import ( "github.com/spf13/cobra" ) -var namespace string -var rotateCmd = &cobra.Command{ - Use: "rotate-tls", - Short: "Rotate webhook controller tls certificates", - Long: `Rotate webhook controller tls certificates`, - RunE: func(cmd *cobra.Command, args []string) error { - if err := rotatetls.RotateTLS(client, namespace); err != nil { - return err - } - return nil - }, -} +var ( + namespace string + rotateCmd = &cobra.Command{ + Use: "rotate-tls", + Short: "Rotate webhook controller tls certificates", + Long: `Rotate webhook controller tls certificates`, + RunE: func(cmd *cobra.Command, args []string) error { + if err := rotatetls.RotateTLS(client, namespace); err != nil { + return err + } + return nil + }, + } +) func init() { rootCmd.AddCommand(rotateCmd) diff --git a/cmd/vm.go b/cmd/vm.go index 50e217de..4cb991eb 100644 --- a/cmd/vm.go +++ b/cmd/vm.go @@ -16,7 +16,7 @@ var ( HTTPIP string // HTTPPort : Port of the http request HTTPPort string - //IsKvmsEnv : Is kubearmor virtual machine env? + // IsKvmsEnv : Is kubearmor virtual machine env? IsKvmsEnv bool ) diff --git a/cmd/vmlabel.go b/cmd/vmlabel.go index 90a16096..78aa1210 100644 --- a/cmd/vmlabel.go +++ b/cmd/vmlabel.go @@ -10,9 +10,7 @@ import ( "github.com/spf13/cobra" ) -var ( - labelOptions vm.LabelOptions -) +var labelOptions vm.LabelOptions // vmLabelCmd represents the vm command for label management var vmLabelCmd = &cobra.Command{ diff --git a/deployment/probedeployment.go b/deployment/probedeployment.go index 971fa771..67ac0085 100644 --- a/deployment/probedeployment.go +++ b/deployment/probedeployment.go @@ -16,25 +16,24 @@ var Karmorprobe = "karmor-probe" // GenerateDaemonSet Function func GenerateDaemonSet(namespace string, krnhdr bool) *appsv1.DaemonSet { - - var label = map[string]string{ + label := map[string]string{ "kubearmor-app": Karmorprobe, } - var privileged = bool(true) - var terminationGracePeriodSeconds = int64(30) - var args = []string{ + privileged := bool(true) + terminationGracePeriodSeconds := int64(30) + args := []string{ "while true; do sleep 30; done;", } - var volumeMounts = []corev1.VolumeMount{ + volumeMounts := []corev1.VolumeMount{ { - Name: "lsm-path", //lsm (read-only) + Name: "lsm-path", // lsm (read-only) MountPath: "/sys/kernel/security", ReadOnly: true, }, } - var volumes = []corev1.Volume{ + volumes := []corev1.Volume{ { Name: "lsm-path", VolumeSource: corev1.VolumeSource{ @@ -48,12 +47,12 @@ func GenerateDaemonSet(namespace string, krnhdr bool) *appsv1.DaemonSet { if krnhdr { volumeMounts = append(volumeMounts, []corev1.VolumeMount{ { - Name: "lib-modules", //lib modules (read-only) + Name: "lib-modules", // lib modules (read-only) MountPath: "/lib/modules", ReadOnly: true, }, { - Name: "kernel-header", //kernel header (read-only) + Name: "kernel-header", // kernel header (read-only) MountPath: "/usr/src", ReadOnly: true, }, diff --git a/go.mod b/go.mod index 3601eaeb..9c860f90 100644 --- a/go.mod +++ b/go.mod @@ -32,7 +32,7 @@ require ( github.com/accuknox/auto-policy-discovery/src v0.0.0-20230912162532-0b5b73425c5a github.com/charmbracelet/bubbles v0.17.1 github.com/charmbracelet/bubbletea v0.25.0 - github.com/charmbracelet/lipgloss v0.9.1 + github.com/charmbracelet/lipgloss v0.10.0 github.com/deckarep/golang-set/v2 v2.6.0 github.com/evertras/bubble-table v0.15.6 github.com/google/go-cmp v0.6.0 @@ -52,6 +52,8 @@ require ( k8s.io/client-go v0.29.2 ) +require github.com/go-logfmt/logfmt v0.6.0 // indirect + require ( cloud.google.com/go/compute v1.23.3 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect @@ -124,6 +126,7 @@ require ( github.com/buildkite/interpolate v0.0.0-20200526001904-07f35b4ae251 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chai2010/gettext-go v1.0.2 // indirect + github.com/charmbracelet/log v0.4.0 github.com/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589 // indirect github.com/cilium/ebpf v0.13.2 // indirect github.com/cilium/proxy v0.0.0-20231218064853-ea8cba5b690b // indirect @@ -285,7 +288,7 @@ require ( github.com/protocolbuffers/txtpbfmt v0.0.0-20231025115547-084445ff1adf // indirect github.com/r3labs/diff v1.1.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect - github.com/rivo/uniseg v0.4.4 // indirect + github.com/rivo/uniseg v0.4.7 // indirect github.com/robfig/cron v1.2.0 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/rubenv/sql-migrate v1.6.0 // indirect diff --git a/go.sum b/go.sum index a719ba14..576538ea 100644 --- a/go.sum +++ b/go.sum @@ -334,6 +334,10 @@ github.com/charmbracelet/bubbletea v0.25.0 h1:bAfwk7jRz7FKFl9RzlIULPkStffg5k6pNt github.com/charmbracelet/bubbletea v0.25.0/go.mod h1:EN3QDR1T5ZdWmdfDzYcqOCAps45+QIJbLOBxmVNWNNg= github.com/charmbracelet/lipgloss v0.9.1 h1:PNyd3jvaJbg4jRHKWXnCj1akQm4rh8dbEzN1p/u1KWg= github.com/charmbracelet/lipgloss v0.9.1/go.mod h1:1mPmG4cxScwUQALAAnacHaigiiHB9Pmr+v1VEawJl6I= +github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s= +github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE= +github.com/charmbracelet/log v0.4.0 h1:G9bQAcx8rWA2T3pWvx7YtPTPwgqpk7D68BX21IRW8ZM= +github.com/charmbracelet/log v0.4.0/go.mod h1:63bXt/djrizTec0l11H20t8FDSvA4CRZJ1KH22MdptM= github.com/chavacava/garif v0.0.0-20210405163807-87a70f3d418b/go.mod h1:Qjyv4H3//PWVzTeCezG2b9IRn6myJxJSr4TD/xo6ojU= github.com/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589 h1:krfRl01rzPzxSxyLyrChD+U+MzsBXbm0OwYYB67uF+4= github.com/chrismellard/docker-credential-acr-env v0.0.0-20230304212654-82a0ddb27589/go.mod h1:OuDyvmLnMCwa2ep4Jkm6nyA0ocJuZlGyk2gGseVzERM= @@ -554,6 +558,8 @@ github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vb github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-logr/logr v0.3.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= @@ -1354,6 +1360,8 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= diff --git a/install/customResource.go b/install/customResource.go index da464e74..3e33b8f9 100644 --- a/install/customResource.go +++ b/install/customResource.go @@ -8,8 +8,10 @@ import ( apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" ) -var kspName = "kubearmorpolicies.security.kubearmor.com" -var hspName = "kubearmorhostpolicies.security.kubearmor.com" +var ( + kspName = "kubearmorpolicies.security.kubearmor.com" + hspName = "kubearmorhostpolicies.security.kubearmor.com" +) // CreateCustomResourceDefinition creates the CRD and add it into Kubernetes. func CreateCustomResourceDefinition(crdName string) apiextensions.CustomResourceDefinition { diff --git a/install/defaults.go b/install/defaults.go index 70bd8992..e7607baa 100644 --- a/install/defaults.go +++ b/install/defaults.go @@ -5,29 +5,35 @@ package install var kubearmor = "kubearmor" -var serviceAccountName = kubearmor -var operatorServiceAccountName = "kubearmor-operator" -var KubeArmorOperatorClusterRoleName = "kubearmor-operator-clusterrole" -var KubeArmorOperatorManageClusterRoleName = "kubearmor-operator-manage-kubearmor-clusterrole" -var KubeArmorOperatorManageControllerClusterRoleName = "kubearmor-operator-manage-controller-clusterrole" -var KubeArmorClusterRoleName = "kubearmor-clusterrole" -var RelayClusterRoleName = "kubearmor-relay-clusterrole" -var KubeArmorControllerClusterRoleName = "kubearmor-controller-clusterrole" -var KubeArmorSnitchClusterRoleName = "kubearmor-snitch" -var KubeArmorControllerProxyClusterRoleName = "kubearmor-controller-proxy-role" +var ( + serviceAccountName = kubearmor + operatorServiceAccountName = "kubearmor-operator" + KubeArmorOperatorClusterRoleName = "kubearmor-operator-clusterrole" + KubeArmorOperatorManageClusterRoleName = "kubearmor-operator-manage-kubearmor-clusterrole" + KubeArmorOperatorManageControllerClusterRoleName = "kubearmor-operator-manage-controller-clusterrole" + KubeArmorClusterRoleName = "kubearmor-clusterrole" + RelayClusterRoleName = "kubearmor-relay-clusterrole" + KubeArmorControllerClusterRoleName = "kubearmor-controller-clusterrole" + KubeArmorSnitchClusterRoleName = "kubearmor-snitch" + KubeArmorControllerProxyClusterRoleName = "kubearmor-controller-proxy-role" +) -var KubeArmorSnitchClusterroleBindingName = "kubearmor-snitch-binding" -var RelayClusterRoleBindingName = "kubearmor-relay-clusterrolebinding" -var KubeArmorControllerProxyClusterRoleBindingName = "kubearmor-controller-proxy-rolebinding" -var KubeArmorControllerClusterRoleBindingName = "kubearmor-controller-clusterrolebinding" -var KubeArmorClusterRoleBindingName = "kubearmor-clusterrolebinding" -var KubeArmorOperatorManageControllerClusterRoleBindingName = "kubearmor-operator-manage-controller-clusterrole-binding" -var KubeArmorOperatorManageClusterRoleBindingName = "kubearmor-operator-manage-kubearmor-clusterrole-binding" -var KubeArmorOperatorClusterRoleBindingName = "kubearmor-operator-clusterrole-binding" +var ( + KubeArmorSnitchClusterroleBindingName = "kubearmor-snitch-binding" + RelayClusterRoleBindingName = "kubearmor-relay-clusterrolebinding" + KubeArmorControllerProxyClusterRoleBindingName = "kubearmor-controller-proxy-rolebinding" + KubeArmorControllerClusterRoleBindingName = "kubearmor-controller-clusterrolebinding" + KubeArmorClusterRoleBindingName = "kubearmor-clusterrolebinding" + KubeArmorOperatorManageControllerClusterRoleBindingName = "kubearmor-operator-manage-controller-clusterrole-binding" + KubeArmorOperatorManageClusterRoleBindingName = "kubearmor-operator-manage-kubearmor-clusterrole-binding" + KubeArmorOperatorClusterRoleBindingName = "kubearmor-operator-clusterrole-binding" +) -var relayServiceName = kubearmor -var relayDeploymentName = "kubearmor-relay" -var policyManagerServiceName = "kubearmor-policy-manager-metrics-service" -var policyManagerDeploymentName = "kubearmor-policy-manager" -var hostPolicyManagerServiceName = "kubearmor-host-policy-manager-metrics-service" -var hostPolicyManagerDeploymentName = "kubearmor-host-policy-manager" +var ( + relayServiceName = kubearmor + relayDeploymentName = "kubearmor-relay" + policyManagerServiceName = "kubearmor-policy-manager-metrics-service" + policyManagerDeploymentName = "kubearmor-policy-manager" + hostPolicyManagerServiceName = "kubearmor-host-policy-manager-metrics-service" + hostPolicyManagerDeploymentName = "kubearmor-host-policy-manager" +) diff --git a/install/install.go b/install/install.go index 5bb51f10..d1e1e6ec 100644 --- a/install/install.go +++ b/install/install.go @@ -6,14 +6,13 @@ package install import ( "context" - "io" - "path/filepath" - "errors" "fmt" + "io" "log" "os" "path" + "path/filepath" "slices" "strings" "time" @@ -75,10 +74,12 @@ type envOption struct { Environment string } -var verify bool -var progress int -var cursorcount int -var validEnvironments = []string{"k0s", "k3s", "microK8s", "minikube", "gke", "bottlerocket", "eks", "docker", "oke", "generic"} +var ( + verify bool + progress int + cursorcount int + validEnvironments = []string{"k0s", "k3s", "microK8s", "minikube", "gke", "bottlerocket", "eks", "docker", "oke", "generic"} +) // Checks if passed string is a valid environment func (env *envOption) CheckAndSetValidEnvironmentOption(envOption string) error { @@ -377,7 +378,6 @@ func checkPodsLegacy(c *k8s.Client, o Options) { } break } - } func checkTerminatingPods(c *k8s.Client, ns string) int { @@ -903,7 +903,7 @@ func writeHelmManifests(manifests string, filename string, printYAML []interface } } - file, _ := os.OpenFile("kubearmor.yaml", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + file, _ := os.OpenFile("kubearmor.yaml", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) // Write the string to the file _, err = file.WriteString(manifests + "\n") if err != nil { @@ -972,7 +972,7 @@ func K8sInstaller(c *k8s.Client, o Options) error { var repoFile repo.File repoFile.Update(entry) - if err := repoFile.WriteFile(settings.RepositoryConfig, 0644); err != nil { + if err := repoFile.WriteFile(settings.RepositoryConfig, 0o644); err != nil { return fmt.Errorf("failed to write repository file: %w", err) } diff --git a/log/log.go b/log/log.go index b6167a0a..952f7473 100644 --- a/log/log.go +++ b/log/log.go @@ -62,13 +62,17 @@ type Options struct { } // StopChan Channel -var StopChan chan struct{} -var sigChan chan os.Signal +var ( + StopChan chan struct{} + sigChan chan os.Signal +) // UnblockSignal is a flag to check whether the Watch* APIs have exited or signal has rcvd -var UnblockSignal error -var matchLabels = map[string]string{"kubearmor-app": "kubearmor-relay"} -var port int64 = 32767 +var ( + UnblockSignal error + matchLabels = map[string]string{"kubearmor-app": "kubearmor-relay"} + port int64 = 32767 +) // GetOSSigChannel Function func GetOSSigChannel() chan os.Signal { diff --git a/log/logClient.go b/log/logClient.go index a6d54dc2..fc487226 100644 --- a/log/logClient.go +++ b/log/logClient.go @@ -32,8 +32,10 @@ type EventInfo struct { } // Limitchan handles telemetry event output limit -var Limitchan chan bool -var i uint32 +var ( + Limitchan chan bool + i uint32 +) // ============ // // == Common == // @@ -53,7 +55,7 @@ func StrToFile(str, destFile string) { } // #nosec - file, err := os.OpenFile(destFile, os.O_WRONLY|os.O_APPEND, 0644) + file, err := os.OpenFile(destFile, os.O_WRONLY|os.O_APPEND, 0o644) if err != nil { fmt.Fprintf(os.Stderr, "Failed to open a file (%s, %s)\n", destFile, err.Error()) } @@ -81,7 +83,7 @@ type Feeder struct { // server server string - //limit + // limit limit uint32 // connection @@ -228,7 +230,6 @@ func (fd *Feeder) WatchMessages(msgPath string, jsonFormat bool) error { } func regexMatcher(filter *regexp.Regexp, res string) bool { - match := filter.MatchString(res) if !match { return false @@ -413,7 +414,6 @@ func WatchTelemetryHelper(arr []byte, t string, o Options) { var prettyJSON bytes.Buffer err = json.Indent(&prettyJSON, arr, "", " ") - if err != nil { fmt.Fprintf(os.Stderr, "Failed to prettify JSON (%s)\n", err.Error()) } @@ -479,7 +479,6 @@ func WatchTelemetryHelper(arr []byte, t string, o Options) { } else if o.LogPath != "" { StrToFile(str, o.LogPath) } - } // DestroyClient Function @@ -498,7 +497,6 @@ func selectLabels(o Options, labels []string) error { return nil } } - } return errors.New("Not found any flag") } diff --git a/log/logClient_test.go b/log/logClient_test.go index 23da4a1a..8c2c8238 100644 --- a/log/logClient_test.go +++ b/log/logClient_test.go @@ -9,10 +9,12 @@ import ( pb "github.com/kubearmor/KubeArmor/protobuf" ) -var eventChan chan EventInfo -var done chan bool -var gotAlerts = 0 -var gotLogs = 0 +var ( + eventChan chan EventInfo + done chan bool + gotAlerts = 0 + gotLogs = 0 +) const maxEvents = 5 @@ -36,7 +38,7 @@ func genericWaitOnEvent(cnt int) { } func TestLogClient(t *testing.T) { - var res = &pb.Alert{ + res := &pb.Alert{ ClusterName: "breaking-bad", HostName: "saymyname", NamespaceName: "heisenberg", @@ -48,7 +50,7 @@ func TestLogClient(t *testing.T) { Type: "MatchedPolicy", } eventChan = make(chan EventInfo, maxEvents) - var o = Options{ + o := Options{ EventChan: eventChan, Selector: []string{"substance=meth"}, } diff --git a/log/tls.go b/log/tls.go index 84c26bed..418b1aa5 100644 --- a/log/tls.go +++ b/log/tls.go @@ -27,7 +27,7 @@ func loadTLSCredentials(client kubernetes.Interface, o Options) (credentials.Tra if o.TlsCertProvider == SelfCertProvider { // create certificate configurations clientCertCfg = cert.DefaultKubeArmorClientConfig - clientCertCfg.NotAfter = time.Now().AddDate(1, 0, 0) //valid for 1 year + clientCertCfg.NotAfter = time.Now().AddDate(1, 0, 0) // valid for 1 year } tlsConfig := cert.TlsConfig{ CertCfg: clientCertCfg, diff --git a/probe/print.go b/probe/print.go index 2af07009..00419dfc 100644 --- a/probe/print.go +++ b/probe/print.go @@ -102,7 +102,6 @@ func (o *Options) printKubeArmorContainers(containerData map[string]*KubeArmorPo o.printToOutput(boldWhite, "Containers : \n") for name, spec := range containerData { - data = append(data, []string{" ", name, "Running: " + spec.Running, "Image Version: " + spec.Image_Version}) } o.renderOutputInTableWithNoBorders(data) @@ -110,12 +109,10 @@ func (o *Options) printKubeArmorContainers(containerData map[string]*KubeArmorPo // printKubeArmorprobe function func (o *Options) printKubeArmorprobe(probeData []KubeArmorProbeData) { - for i, pd := range probeData { o.printToOutput(boldWhite, "Node "+fmt.Sprint(i+1)+" : \n") o.printKubeArmorProbeOutput(pd) } - } // printKubeArmorProbeOutput function @@ -136,7 +133,6 @@ func (o *Options) printKubeArmorProbeOutput(kd KubeArmorProbeData) { // printAnnotatedPods function func (o *Options) printAnnotatedPods(podData [][]string) { - o.printToOutput(boldWhite, "Armored Up pods : \n") table := tablewriter.NewWriter(o.getWriter()) table.SetHeader([]string{"NAMESPACE", "DEFAULT POSTURE", "VISIBILITY", "NAME", "POLICY"}) @@ -147,6 +143,7 @@ func (o *Options) printAnnotatedPods(podData [][]string) { table.SetAutoMergeCellsByColumnIndex([]int{0, 1, 2}) table.Render() } + func (o *Options) printContainersSystemd(podData [][]string) { o.printToOutput(boldWhite, "Armored Up Containers : \n") @@ -158,8 +155,8 @@ func (o *Options) printContainersSystemd(podData [][]string) { table.SetRowLine(true) table.SetAutoMergeCellsByColumnIndex([]int{0, 1}) table.Render() - } + func (o *Options) printHostPolicy(hostPolicy [][]string) { o.printToOutput(boldWhite, "Host Policies : \n") diff --git a/probe/probe.go b/probe/probe.go index 1d003fb2..9e65c54f 100644 --- a/probe/probe.go +++ b/probe/probe.go @@ -8,6 +8,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "log" @@ -35,19 +36,19 @@ import ( "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/remotecommand" - "errors" - pb "github.com/kubearmor/KubeArmor/protobuf" "golang.org/x/sys/unix" ) -var white = color.New(color.FgWhite) -var boldWhite = white.Add(color.Bold) -var green = color.New(color.FgGreen) -var itwhite = color.New(color.Italic).Add(color.Italic) -var red = color.New(color.FgRed) -var yellow = color.New(color.FgYellow) -var blue = color.New(color.FgBlue) +var ( + white = color.New(color.FgWhite) + boldWhite = white.Add(color.Bold) + green = color.New(color.FgGreen) + itwhite = color.New(color.Italic).Add(color.Italic) + red = color.New(color.FgRed) + yellow = color.New(color.FgYellow) + blue = color.New(color.FgBlue) +) // K8sInstaller for karmor install func probeDaemonInstaller(c *k8s.Client, o Options, krnhdr bool) error { @@ -92,11 +93,12 @@ func PrintProbeResult(c *k8s.Client, o Options) error { armoredContainers, containerMap := getArmoredContainerData(policyData.ContainerList, policyData.ContainerMap) hostPolicyData := getHostPolicyData(policyData) if o.Output == "json" { - probeData := map[string]interface{}{"Probe Data": map[string]interface{}{ - "Host": kd, - "HostPolicies": policyData.HostMap, - "ArmoredContainers": containerMap, - }, + probeData := map[string]interface{}{ + "Probe Data": map[string]interface{}{ + "Host": kd, + "HostPolicies": policyData.HostMap, + "ArmoredContainers": containerMap, + }, } out, err := json.Marshal(probeData) if err != nil { @@ -133,13 +135,14 @@ func PrintProbeResult(c *k8s.Client, o Options) error { log.Println("error occured when getting annotated pods", err) } if o.Output == "json" { - ProbeData := map[string]interface{}{"Probe Data": map[string]interface{}{ - "DaemonsetStatus": daemonsetStatus, - "Deployments": deploymentData, - "Containers": containerData, - "Nodes": nodeData, - "ArmoredPods": armoredPodData, - }, + ProbeData := map[string]interface{}{ + "Probe Data": map[string]interface{}{ + "DaemonsetStatus": daemonsetStatus, + "Deployments": deploymentData, + "Containers": containerData, + "Nodes": nodeData, + "ArmoredPods": armoredPodData, + }, } out, err := json.Marshal(ProbeData) if err != nil { @@ -260,10 +263,10 @@ func checkBTFSupport() bool { } func checkKernelHeaderPresent() bool { - //check if there's any directory /usr/src/$(uname -r) + // check if there's any directory /usr/src/$(uname -r) var uname unix.Utsname if err := unix.Uname(&uname); err == nil { - var path = "" + path := "" if _, err := os.Stat("/etc/redhat-release"); !os.IsNotExist(err) { path = "/usr/src/" + string(uname.Release[:]) } else if _, err := os.Stat("/lib/modules/" + string(uname.Release[:]) + "/build/Kconfig"); !os.IsNotExist(err) { @@ -306,7 +309,6 @@ func execIntoPod(c *k8s.Client, podname, namespace, cmd string) (string, error) Stdout: buf, Stderr: errBuf, }) - if err != nil { return "none", err } @@ -402,7 +404,6 @@ func probeNode(c *k8s.Client, o Options) { func isKubeArmorRunning(c *k8s.Client) (bool, *Status) { isRunning, DaemonsetStatus := getKubeArmorDaemonset(c) return isRunning, DaemonsetStatus - } func getKubeArmorDaemonset(c *k8s.Client) (bool, *Status) { @@ -457,11 +458,9 @@ func getKubeArmorDeployments(c *k8s.Client) map[string]*Status { } func getKubeArmorContainers(c *k8s.Client) map[string]*KubeArmorPodSpec { - kubearmorPods, err := c.K8sClientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{ LabelSelector: "kubearmor-app", }) - if err != nil { log.Println("error occured when getting kubearmor pods", err) return nil @@ -469,7 +468,6 @@ func getKubeArmorContainers(c *k8s.Client) map[string]*KubeArmorPodSpec { KAContainerData := make(map[string]*KubeArmorPodSpec) if len(kubearmorPods.Items) > 0 { for _, kubearmorPodItem := range kubearmorPods.Items { - KAContainerData[kubearmorPodItem.Name] = &KubeArmorPodSpec{ Running: strconv.Itoa(len(kubearmorPodItem.Spec.Containers)), Image_Version: kubearmorPodItem.Spec.Containers[0].Image, @@ -547,13 +545,14 @@ func readDataFromKubeArmor(c *k8s.Client, pod corev1.Pod) (KubeArmorProbeData, e return KubeArmorProbeData{}, fmt.Errorf("read empty data from kubearmor pod") } var kd KubeArmorProbeData - var json = jsoniter.ConfigCompatibleWithStandardLibrary + json := jsoniter.ConfigCompatibleWithStandardLibrary err = json.Unmarshal(buf, &kd) if err != nil { return KubeArmorProbeData{}, fmt.Errorf("error occured while parsing data from kubeArmor pod %s", err.Error()) } return kd, nil } + func getPostureData(probeData []KubeArmorProbeData) map[string]string { postureData := make(map[string]string) if len(probeData) > 0 { @@ -587,7 +586,7 @@ func probeSystemdMode() (KubeArmorProbeData, error) { } var kd KubeArmorProbeData - var json = jsoniter.ConfigCompatibleWithStandardLibrary + json := jsoniter.ConfigCompatibleWithStandardLibrary err = json.Unmarshal(buf, &kd) if err != nil { return KubeArmorProbeData{}, err @@ -620,13 +619,11 @@ func getPolicyData(o Options) (*pb.ProbeResponse, error) { } return resp, nil - } -func getArmoredContainerData(containerList []string, containerMap map[string]*pb.ContainerData) ([][]string, map[string][]string) { +func getArmoredContainerData(containerList []string, containerMap map[string]*pb.ContainerData) ([][]string, map[string][]string) { var data [][]string for _, containerName := range containerList { - if _, ok := containerMap[containerName]; ok { if containerMap[containerName].PolicyEnabled == 1 { for _, policyName := range containerMap[containerName].PolicyList { @@ -636,12 +633,10 @@ func getArmoredContainerData(containerList []string, containerMap map[string]*pb } else { data = append(data, []string{containerName, ""}) } - } mp := make(map[string][]string) for _, v := range data { - if val, exists := mp[v[0]]; exists { val = append(val, v[1]) @@ -650,24 +645,19 @@ func getArmoredContainerData(containerList []string, containerMap map[string]*pb } else { mp[v[0]] = []string{v[1]} } - } return data, mp - } -func getHostPolicyData(policyData *pb.ProbeResponse) [][]string { +func getHostPolicyData(policyData *pb.ProbeResponse) [][]string { var data [][]string for k, v := range policyData.HostMap { - for _, policy := range v.PolicyList { data = append(data, []string{k, policy}) } - } return data - } func getAnnotatedPodLabels(m map[string]string) mapset.Set[string] { @@ -684,7 +674,6 @@ func getNsSecurityPostureAndVisibility(c *k8s.Client, postureData map[string]str mp := make(map[string]*NamespaceData) namespaces, err := c.K8sClientset.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{}) - if err != nil { return mp, err } @@ -727,7 +716,6 @@ func getNsSecurityPostureAndVisibility(c *k8s.Client, postureData map[string]str } func getAnnotatedPods(c *k8s.Client, o Options, postureData map[string]string) (map[string]interface{}, [][]string, error) { - // Annotated Pods Description var data [][]string pods, err := c.K8sClientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{}) @@ -747,7 +735,6 @@ func getAnnotatedPods(c *k8s.Client, o Options, postureData map[string]string) ( } for _, p := range pods.Items { - if p.Annotations["kubearmor-policy"] == "enabled" { armoredPod, err := c.K8sClientset.CoreV1().Pods(p.Namespace).Get(context.Background(), p.Name, metav1.GetOptions{}) if err != nil { @@ -760,18 +747,25 @@ func getAnnotatedPods(c *k8s.Client, o Options, postureData map[string]string) ( } labels := getAnnotatedPodLabels(armoredPod.Labels) - for policyKey, policyValue := range policyMap { - s2 := sliceToSet(policyValue) - if s2.IsSubset(labels) { - if !checkIfDataAlreadyContainsPodName(data, armoredPod.Name, policyKey) { - - data = append(data, []string{armoredPod.Namespace, mp[armoredPod.Namespace].NsPostureString, mp[armoredPod.Namespace].NsVisibilityString, armoredPod.Name, policyKey}) - + for _, policy := range policyMap { + s2 := sliceToSet(policy["labels"].([]string)) + namespaces := policy["namespaces"].([]string) + found := false + for _, namespace := range namespaces { + if namespace == armoredPod.Namespace { + found = true + break + } + } + if found && s2.IsSubset(labels) { + if !checkIfDataAlreadyContainsPodName(data, armoredPod.Name, policy["name"].(string)) { + data = append(data, []string{armoredPod.Namespace, mp[armoredPod.Namespace].NsPostureString, mp[armoredPod.Namespace].NsVisibilityString, armoredPod.Name, policy["name"].(string)}) } } } } } + // sorting according to namespaces, for merging of cells with same namespaces sort.SliceStable(data, func(i, j int) bool { return data[i][0] < data[j][0] @@ -791,8 +785,8 @@ func getAnnotatedPods(c *k8s.Client, o Options, postureData map[string]string) ( return map[string]interface{}{"Namespaces": armoredPodData}, data, nil } -func getPoliciesOnAnnotatedPods(c *k8s.Client) (map[string][]string, error) { - maps := make(map[string][]string) +func getPoliciesOnAnnotatedPods(c *k8s.Client) ([]map[string]interface{}, error) { + var maps []map[string]interface{} kspInterface := c.KSPClientset.KubeArmorPolicies("") policies, err := kspInterface.List(context.Background(), metav1.ListOptions{}) if err != nil { @@ -800,17 +794,31 @@ func getPoliciesOnAnnotatedPods(c *k8s.Client) (map[string][]string, error) { } if len(policies.Items) > 0 { for _, policy := range policies.Items { + p := make(map[string]interface{}) selectLabels := policy.Spec.Selector.MatchLabels + labels := []string{} + namespaces := []string{} for key, value := range selectLabels { - maps[policy.Name] = append(maps[policy.Name], key+":"+value) + labels = append(labels, key+":"+value) + namespaces = append(namespaces, policy.Namespace) } + p["name"] = policy.Name + p["labels"] = labels + p["namespaces"] = namespaces + maps = append(maps, p) } } return maps, nil } + +/* + { + "policy_name": map[string][]string + } +*/ func checkIfDataAlreadyContainsPodName(input [][]string, name string, policy string) bool { for _, slice := range input { - //if slice contains podname, then append the policy to the existing policies + // if slice contains podname, then append the policy to the existing policies if slices.Contains(slice, name) { if slice[4] == "" { slice[4] = policy @@ -819,7 +827,6 @@ func checkIfDataAlreadyContainsPodName(input [][]string, name string, policy str } return true } - } return false } @@ -827,6 +834,9 @@ func checkIfDataAlreadyContainsPodName(input [][]string, name string, policy str func sliceToSet(mySlice []string) mapset.Set[string] { mySet := mapset.NewSet[string]() for _, ele := range mySlice { + if len(ele) >= 10 && ele[0:9] == "namespace" { + continue + } mySet.Add(ele) } return mySet diff --git a/profile/Client/profileClient.go b/profile/Client/profileClient.go index a0395249..989b7fb7 100644 --- a/profile/Client/profileClient.go +++ b/profile/Client/profileClient.go @@ -52,7 +52,7 @@ var ( styleBase = lipgloss.NewStyle(). BorderForeground(lipgloss.Color("12")). Align(lipgloss.Right) - //ColumnStyle for column color + // ColumnStyle for column color ColumnStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#00af00")).Align(lipgloss.Center).Bold(true) @@ -177,7 +177,6 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case key.Matches(msg, m.keys.Quit): m.quitting = true return m, tea.Quit - } switch msg.String() { @@ -298,7 +297,6 @@ func (m Model) View() string { )) } return total - } // Profile Row Data to display @@ -380,14 +378,14 @@ func AggregateSummary(inputMap map[Profile]*Frequency, Operation string) map[Pro func convertToJSON(Operation string, data []Profile) { var jsonArray []string jsonByte, _ := json.MarshalIndent(data, " ", " ") - //unmarshalling here because it is marshalled two times for some reason + // unmarshalling here because it is marshalled two times for some reason if err := json.Unmarshal(jsonByte, &jsonArray); err != nil { fmt.Println("Error parsing JSON array:", err) } if len(jsonArray) > 0 { filepath := "Profile_Summary/" - err := os.MkdirAll(filepath, 0600) - err = os.WriteFile(filepath+Operation+".json", []byte(jsonArray[0]), 0600) + err := os.MkdirAll(filepath, 0o600) + err = os.WriteFile(filepath+Operation+".json", []byte(jsonArray[0]), 0o600) if err != nil { panic(err) } @@ -405,7 +403,6 @@ func generateRowsFromData(data []pb.Log, Operation string) []table.Row { m := make(map[Profile]int) w := make(map[Profile]*Frequency) for _, entry := range data { - if entry.Operation == Operation { if (entry.NamespaceName == o1.Namespace) || (entry.PodName == o1.Pod) || @@ -508,5 +505,4 @@ func Start(o Options) { default: break } - } diff --git a/profile/Client/tabs.go b/profile/Client/tabs.go index f83e6bf1..cf66e6d0 100644 --- a/profile/Client/tabs.go +++ b/profile/Client/tabs.go @@ -79,7 +79,6 @@ func (m tabs) View() string { out := []string{} cursor := " " for i, item := range m.items { - if m.cursor == i { cursor = activeTab.Render(item) m.active = item diff --git a/profile/profile.go b/profile/profile.go index d287bc65..304dc1bc 100644 --- a/profile/profile.go +++ b/profile/profile.go @@ -6,12 +6,13 @@ package profile import ( "errors" + "sync" + pb "github.com/kubearmor/KubeArmor/protobuf" "github.com/kubearmor/kubearmor-client/k8s" klog "github.com/kubearmor/kubearmor-client/log" log "github.com/sirupsen/logrus" "google.golang.org/protobuf/encoding/protojson" - "sync" ) var eventChan chan klog.EventInfo @@ -69,7 +70,7 @@ func KarmorProfileStart(logFilter string, grpc string) <-chan error { } go func() { - //defer close(ErrChan) + // defer close(ErrChan) err = klog.StartObserver(client, klog.Options{ LogFilter: logFilter, MsgPath: "none", diff --git a/recommend/engines/generic_policies/generic_policies.go b/recommend/engines/generic_policies/generic_policies.go index 03e5f8fd..ad0df575 100644 --- a/recommend/engines/generic_policies/generic_policies.go +++ b/recommend/engines/generic_policies/generic_policies.go @@ -8,7 +8,6 @@ import ( _ "embed" // need for embedding "fmt" "path/filepath" - "regexp" "strings" @@ -27,8 +26,7 @@ const ( ) // GenericPolicy defines Policy Generators -type GenericPolicy struct { -} +type GenericPolicy struct{} // Init initializing Policy Generator func (P GenericPolicy) Init() error { diff --git a/recommend/engines/generic_policies/policy-templates.go b/recommend/engines/generic_policies/policy-templates.go index 39ea6492..4d98ccf5 100644 --- a/recommend/engines/generic_policies/policy-templates.go +++ b/recommend/engines/generic_policies/policy-templates.go @@ -59,7 +59,6 @@ func CurrentRelease() string { if err != nil { CurrentVersion = strings.Trim(updateRulesYAML([]byte{}), "\"") } else { - CurrentVersion = strings.Trim(updateRulesYAML(path), "\"") } return CurrentVersion @@ -68,7 +67,6 @@ func CurrentRelease() string { func getCachePath() string { cache := fmt.Sprintf("%s/%s", common.UserHome(), cache) return cache - } //go:embed yaml/rules.yaml @@ -152,7 +150,7 @@ func DownloadAndUnzipRelease() (string, error) { if err != nil { log.WithError(err).Error("failed to remove cache files") } - err = os.MkdirAll(filepath.Dir(getCachePath()), 0750) + err = os.MkdirAll(filepath.Dir(getCachePath()), 0o750) if err != nil { return "", err } @@ -160,7 +158,6 @@ func DownloadAndUnzipRelease() (string, error) { downloadURL := fmt.Sprintf("%s%s.zip", url, latestVersion) zipPath := getCachePath() + ".zip" err = downloadZip(downloadURL, zipPath) - if err != nil { err = removeData(getCachePath()) if err != nil { @@ -212,7 +209,7 @@ func unZip(source, dest string) error { if err != nil { return err } - err = os.MkdirAll(path.Dir(name), 0750) + err = os.MkdirAll(path.Dir(name), 0o750) if err != nil { log.WithError(err).Error("failed to create directory") } diff --git a/recommend/image/image.go b/recommend/image/image.go index 81746f91..8e592929 100644 --- a/recommend/image/image.go +++ b/recommend/image/image.go @@ -253,7 +253,6 @@ func (img *Info) getPolicyFile(spec string, outDir string) string { } func addPolicyRule(policy *pol.KubeArmorPolicy, r pol.KubeArmorPolicySpec) { - if len(r.File.MatchDirectories) != 0 || len(r.File.MatchPaths) != 0 { policy.Spec.File = r.File } @@ -270,7 +269,8 @@ func (img *Info) createPolicy(ms common.MatchSpec) (pol.KubeArmorPolicy, error) Spec: pol.KubeArmorPolicySpec{ Severity: 1, // by default Selector: pol.SelectorType{ - MatchLabels: map[string]string{}}, + MatchLabels: map[string]string{}, + }, }, } policy.APIVersion = "security.kubearmor.com/v1" @@ -313,7 +313,7 @@ func (img *Info) GetPolicy(ms common.MatchSpec, options common.Options) ([]byte, arr, _ := json.Marshal(policy) outFile := img.getPolicyFile(ms.Name, options.OutDir) - err = os.MkdirAll(filepath.Dir(outFile), 0750) + err = os.MkdirAll(filepath.Dir(outFile), 0o750) if err != nil { log.WithError(err).Error("failed to create directory") } diff --git a/recommend/recommend.go b/recommend/recommend.go index 9ab1ed66..4c46a053 100644 --- a/recommend/recommend.go +++ b/recommend/recommend.go @@ -84,7 +84,7 @@ func createOutDir(dir string) error { } _, err := os.Stat(dir) if errors.Is(err, os.ErrNotExist) { - err = os.Mkdir(dir, 0750) + err = os.Mkdir(dir, 0o750) if err != nil { return err } diff --git a/recommend/registry/registry.go b/recommend/registry/registry.go index c65cb935..261671d4 100644 --- a/recommend/registry/registry.go +++ b/recommend/registry/registry.go @@ -154,7 +154,7 @@ func (r *Scanner) Analyze(img *image.Info) { // The randomizer used in this function is not used for any cryptographic // operation and hence safe to use. func randString(n int) string { - var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] // #nosec @@ -245,7 +245,7 @@ func extractTar(tarname string, tempDir string) ([]string, []string) { switch hdr.Typeflag { case tar.TypeDir: if _, err := os.Stat(tgt); err != nil { - if err := os.MkdirAll(tgt, 0750); err != nil { + if err := os.MkdirAll(tgt, 0o750); err != nil { log.WithError(err).WithFields(log.Fields{ "target": tgt, }).Fatal("tar mkdirall") @@ -259,7 +259,6 @@ func extractTar(tarname string, tempDir string) ([]string, []string) { "target": tgt, }).Error("tar open file") } else { - // copy over contents if _, err := io.CopyN(f, tr, 2e+9 /*2GB*/); err != io.EOF { log.WithError(err).WithFields(log.Fields{ diff --git a/recommend/report/report_html.go b/recommend/report/report_html.go index 74dfa488..4688921e 100644 --- a/recommend/report/report_html.go +++ b/recommend/report/report_html.go @@ -198,21 +198,21 @@ func (r HTMLReport) Render(out string) error { outPath = outPath + "/.static/" - err = os.MkdirAll(outPath, 0740) + err = os.MkdirAll(outPath, 0o740) if err != nil { log.WithError(err) } - if err := os.WriteFile(outPath+"main.css", []byte(mainCSS), 0600); err != nil { + if err := os.WriteFile(outPath+"main.css", []byte(mainCSS), 0o600); err != nil { log.WithError(err).Error("failed to write file") } - if err := os.WriteFile(outPath+"v38_6837.png", []byte(imageV38_6837), 0600); err != nil { + if err := os.WriteFile(outPath+"v38_6837.png", []byte(imageV38_6837), 0o600); err != nil { log.WithError(err).Error("failed to write file") } - if err := os.WriteFile(outPath+"v38_7029.png", []byte(imageV38_7029), 0600); err != nil { + if err := os.WriteFile(outPath+"v38_7029.png", []byte(imageV38_7029), 0o600); err != nil { log.WithError(err).Error("failed to write file") } - if err := os.WriteFile(out, []byte(r.outString.String()), 0600); err != nil { + if err := os.WriteFile(out, []byte(r.outString.String()), 0o600); err != nil { log.WithError(err).Error("failed to write file") } return nil diff --git a/recommend/report/report_text.go b/recommend/report/report_text.go index a5b981a9..3e68b2e9 100644 --- a/recommend/report/report_text.go +++ b/recommend/report/report_text.go @@ -106,8 +106,7 @@ func wrapPolicyName(name string, limit int) string { // Render output the table func (r TextReport) Render(out string) error { - - if err := os.WriteFile(out, []byte(r.outString.String()), 0600); err != nil { + if err := os.WriteFile(out, []byte(r.outString.String()), 0o600); err != nil { log.WithError(err).Error("failed to write file") } return nil diff --git a/selfupdate/selfupdate.go b/selfupdate/selfupdate.go index 6c95671f..c9b29a66 100644 --- a/selfupdate/selfupdate.go +++ b/selfupdate/selfupdate.go @@ -108,7 +108,7 @@ func doSelfUpdate(curver string) error { // SelfUpdate handler for karmor cli tool func SelfUpdate(c *k8s.Client) error { - var ver = GitSummary + ver := GitSummary fmt.Printf("current karmor version %s\n", ver) if !isValidVersion(ver) { fmt.Println("version does not match the pattern. Maybe using a locally built karmor!") diff --git a/sysdump/sysdump.go b/sysdump/sysdump.go index 7b9bf3e9..d5115f67 100644 --- a/sysdump/sysdump.go +++ b/sysdump/sysdump.go @@ -100,7 +100,6 @@ func Collect(c *k8s.Client, o Options) error { pods, err := c.K8sClientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{ LabelSelector: "kubearmor-app", }) - if err != nil { fmt.Printf("kubearmor pod not found. (possible if kubearmor is running in process mode)\n") return nil @@ -250,7 +249,7 @@ func Collect(c *k8s.Client, o Options) error { } func writeToFile(p, v string) error { - return os.WriteFile(p, []byte(v), 0600) + return os.WriteFile(p, []byte(v), 0o600) } func writeYaml(p string, o runtime.Object) error { @@ -309,7 +308,7 @@ func copyFromPod(srcPath string, d string, c *k8s.Client) error { if err != nil { return err } - if err := os.WriteFile(destPath, buf, 0600); err != nil { + if err := os.WriteFile(destPath, buf, 0o600); err != nil { return err } } @@ -319,7 +318,6 @@ func copyFromPod(srcPath string, d string, c *k8s.Client) error { // IsDirEmpty Function func IsDirEmpty(name string) (bool, error) { files, err := os.ReadDir(name) - if err != nil { return false, err } diff --git a/tests/recommend/recommend_test.go b/tests/recommend/recommend_test.go index d5828ecc..48dce075 100644 --- a/tests/recommend/recommend_test.go +++ b/tests/recommend/recommend_test.go @@ -21,13 +21,14 @@ import ( . "github.com/onsi/gomega" ) -var testOptions common.Options -var err error +var ( + testOptions common.Options + err error +) var client *k8s.Client func compareData(file1, file2 string) bool { - var pol1, pol2 common.MatchSpec data1, err := os.ReadFile(filepath.Clean(file1)) if err != nil { @@ -65,12 +66,11 @@ func compareData(file1, file2 string) bool { } var _ = Describe("karmor", func() { - BeforeEach(func() { testOptions.OutDir = "out" testOptions.ReportFile = "report.txt" testOptions.Policy = []string{"KubeArmorPolicy"} - //Initialise k8sClient for all child commands to inherit + // Initialise k8sClient for all child commands to inherit client, err = k8s.ConnectK8sClient() Expect(err).To(BeNil()) }) @@ -80,17 +80,15 @@ var _ = Describe("karmor", func() { }) Describe("recommend", func() { - Context("when called with `update` command", func() { - It("should fetch the latest policy-template release and modify the rule under ~/.cache/karmor/", func() { - //os.MkdirAll(testOptions.OutDir, 0777) + // os.MkdirAll(testOptions.OutDir, 0777) _, err := genericpolicies.DownloadAndUnzipRelease() Expect(err).To(BeNil()) files, err := os.ReadDir(fmt.Sprintf("%s/.cache/karmor", os.Getenv("HOME"))) Expect(err).To(BeNil()) Expect(len(files)).To(BeNumerically(">=", 1)) - //os.RemoveAll(testOptions.OutDir) + // os.RemoveAll(testOptions.OutDir) }) }) @@ -111,10 +109,8 @@ var _ = Describe("karmor", func() { filesRes, err := os.ReadDir("res/out/ubuntu-18-04") Expect(err).To(BeNil()) for _, fileRes := range filesRes { - if compareData(testOptions.OutDir+"/ubuntu-18-04/"+file.Name(), "res/out/ubuntu-18-04/"+fileRes.Name()) { count++ - } } } @@ -145,7 +141,6 @@ var _ = Describe("karmor", func() { if compareData(testOptions.OutDir+"/ubuntu-18-04/"+file.Name(), "res/out/ubuntu-18-04/"+fileRes.Name()) { count++ } - } } fmt.Printf("Matched files count: %v\n", count) @@ -172,10 +167,8 @@ var _ = Describe("karmor", func() { filesRes, err := os.ReadDir("res/out/wordpress-mysql-wordpress") Expect(err).To(BeNil()) for _, fileRes := range filesRes { - if compareData(testOptions.OutDir+"/wordpress-mysql-wordpress/"+file.Name(), "res/out/wordpress-mysql-wordpress/"+fileRes.Name()) { count++ - } } } diff --git a/utils/portforward.go b/utils/portforward.go index 2709f2f6..f565157f 100644 --- a/utils/portforward.go +++ b/utils/portforward.go @@ -66,7 +66,6 @@ func (pf *PortForwardOpt) handlePortForward(c *k8s.Client) error { return fmt.Errorf("\ncould not do kubearmor portforward, error=%s", err.Error()) } return nil - } // k8s port forward @@ -117,7 +116,6 @@ func (pf *PortForwardOpt) getPodName(c *k8s.Client) error { podList, err := c.K8sClientset.CoreV1().Pods(pf.Namespace).List(context.Background(), metav1.ListOptions{ LabelSelector: metav1.FormatLabelSelector(&labelSelector), }) - if err != nil { return err } @@ -131,7 +129,6 @@ func (pf *PortForwardOpt) getPodName(c *k8s.Client) error { // Returns the local port for the port forwarder func (pf *PortForwardOpt) getLocalPort() (int64, error) { - for { port, err := getRandomPort() if err != nil { @@ -146,7 +143,6 @@ func (pf *PortForwardOpt) getLocalPort() (int64, error) { return port, nil } } - } // Return a port number > 32767 @@ -156,6 +152,6 @@ func getRandomPort() (int64, error) { return -1, errors.New("unable to generate random integer for port") } - var portNo = n.Int64() + 32768 + portNo := n.Int64() + 32768 return portNo, nil } diff --git a/vm/getscript.go b/vm/getscript.go index a84edbcb..1526e0bc 100644 --- a/vm/getscript.go +++ b/vm/getscript.go @@ -87,7 +87,6 @@ func getClusterIP(c *k8s.Client, options ScriptOptions) (string, error) { // GetScript - Function to handle script download for vm option func GetScript(c *k8s.Client, options ScriptOptions, httpIP string, isNonK8sEnv bool) error { - var ( clusterIP string err error diff --git a/vm/label.go b/vm/label.go index f6250efa..51360520 100644 --- a/vm/label.go +++ b/vm/label.go @@ -30,7 +30,6 @@ type KubeArmorVirtualMachineLabel struct { // LabelHandling Function recives path to YAML file with the type of event and HTTP Server func LabelHandling(t string, o LabelOptions, address string, isKvmsEnv bool) error { - var respBody []byte if isKvmsEnv { diff --git a/vm/onboarding.go b/vm/onboarding.go index 23e1895e..0841eaa7 100644 --- a/vm/onboarding.go +++ b/vm/onboarding.go @@ -21,7 +21,6 @@ import ( ) func postHTTPRequest(eventData []byte, vmAction string, address string) (string, error) { - timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, diff --git a/vm/policy.go b/vm/policy.go index 1f350ca6..bf71accd 100644 --- a/vm/policy.go +++ b/vm/policy.go @@ -79,11 +79,9 @@ func sendPolicyOverGRPC(o PolicyOptions, policyEventData []byte, kind string) er } fmt.Printf("Policy %s \n", resp.Status) return nil - } func sendPolicyOverHTTP(address string, kind string, policyEventData []byte) error { - timeout := time.Duration(5 * time.Second) client := http.Client{ Timeout: timeout, @@ -203,7 +201,6 @@ func PolicyHandling(t string, path string, o PolicyOptions, httpAddress string, // Systemd mode, hence send policy over gRPC if err = sendPolicyOverGRPC(o, policyEventData, k.Kind); err != nil { return err - } } }