Skip to content

Commit

Permalink
address review comments
Browse files Browse the repository at this point in the history
use GetDeploymentsFromK8sClient()

Signed-off-by: Ankur Kothiwal <ankur.kothiwal99@gmail.com>
  • Loading branch information
Ankurk99 committed Jun 14, 2023
1 parent 00e59ce commit 45d3606
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 67 deletions.
46 changes: 45 additions & 1 deletion src/cluster/k8sClientHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,9 @@ func GetDeploymentsFromK8sClient() []types.Deployment {
})
}
}

results = append(results, GetReplicaSetsFromK8sClient()...)
results = append(results, GetStatefulSetsFromK8sClient()...)
results = append(results, GetDaemonSetsFromK8sClient()...)

return results
}
Expand Down Expand Up @@ -520,6 +520,50 @@ func GetReplicaSetsFromK8sClient() []types.Deployment {
return results
}

// ================= //
// == Daemonset == //
// ================= //

func GetDaemonSetsFromK8sClient() []types.Deployment {
results := []types.Deployment{}

client := ConnectK8sClient()
if client == nil {
log.Error().Msg("failed to create k8s client")
return results
}

// get namespaces from k8s api client
daemonsets, err := client.AppsV1().DaemonSets("").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Error().Msg(err.Error())
return results
}

for _, ds := range daemonsets.Items {
if ds.OwnerReferences == nil {
if ds.Namespace == "kube-system" {
continue
}

if ds.Spec.Selector.MatchLabels != nil {
var labels []string

for k, v := range ds.Spec.Selector.MatchLabels {
labels = append(labels, k+"="+v)
}

results = append(results, types.Deployment{
Name: ds.Name,
Namespace: ds.Namespace,
Labels: strings.Join(labels, ","),
})
}
}
}
return results
}

// ================= //
// == StatefulSet == //
// ================= //
Expand Down
82 changes: 16 additions & 66 deletions src/crownjewel/crownjewel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ package crownjewel

import (
"context"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"

Expand All @@ -22,7 +20,6 @@ import (
"github.com/rs/zerolog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
)

var log *zerolog.Logger
Expand Down Expand Up @@ -100,36 +97,11 @@ func StopCrownjewelCronJob() {

// Create Crown Jewel Policy based on K8s object type
func CrownjewelPolicyMain() {
deployment := cluster.GetDeploymentsFromK8sClient()
client := cluster.ConnectK8sClient()
deployments, err := client.AppsV1().Deployments("").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Error().Msg("Error getting Deployments err=" + err.Error())
return
}
statefulSets, err := client.AppsV1().StatefulSets("").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Error().Msg("Error getting statefulsets err=" + err.Error())
return
}
daemonsets, err := client.AppsV1().DaemonSets("").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Error().Msg("Error getting daemonsets err=" + err.Error())
return
}
for _, d := range deployments.Items {
err := getFilteredPolicy(client, d.Name, d.Namespace, d.Spec.Template.Labels)
if err != nil {
log.Error().Msg("Error getting mount paths, err=" + err.Error())
}
}
for _, s := range statefulSets.Items {
err := getFilteredPolicy(client, s.Name, s.Namespace, s.Spec.Template.Labels)
if err != nil {
log.Error().Msg("Error getting mount paths, err=" + err.Error())
}
}
for _, rs := range daemonsets.Items {
err := getFilteredPolicy(client, rs.Name, rs.Namespace, rs.Spec.Template.Labels)

for _, d := range deployment {
err := getFilteredPolicy(client, d.Name, d.Namespace, d.Labels)
if err != nil {
log.Error().Msg("Error getting mount paths, err=" + err.Error())
}
Expand All @@ -139,12 +111,12 @@ func CrownjewelPolicyMain() {
type LabelMap = map[string]string

// Get list of running processes from observability data
func getProcessList(client kubernetes.Interface, namespace string, labels types.LabelMap) ([]string, error) {
func getProcessList(client kubernetes.Interface, namespace string, labels string) ([]string, error) {
var processList []string
duplicatePaths := make(map[string]bool)

podList, err := client.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
LabelSelector: libs.LabelMapToString(labels),
LabelSelector: labels,
})
if err != nil {
log.Warn().Msg(err.Error())
Expand Down Expand Up @@ -178,9 +150,9 @@ func getProcessList(client kubernetes.Interface, namespace string, labels types.
}

// Get all mounted paths
func getVolumeMountPaths(client kubernetes.Interface, labels LabelMap) ([]string, error) {
func getVolumeMountPaths(client kubernetes.Interface, labels string) ([]string, error) {
podList, err := client.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
LabelSelector: libs.LabelMapToString(labels),
LabelSelector: labels,
})
if err != nil {
return nil, fmt.Errorf("failed to get pod list: %v", err)
Expand All @@ -199,12 +171,12 @@ func getVolumeMountPaths(client kubernetes.Interface, labels LabelMap) ([]string
}

// Get used mount paths from observability data
func usedMountPath(client kubernetes.Interface, namespace string, labels types.LabelMap) ([]string, map[string]string, error) {
func usedMountPath(client kubernetes.Interface, namespace string, labels string) ([]string, map[string]string, error) {
var sumResponses []string
fromSource := make(map[string]string)

podList, err := client.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
LabelSelector: libs.LabelMapToString(labels),
LabelSelector: labels,
})
if err != nil {
log.Warn().Msg(err.Error())
Expand Down Expand Up @@ -249,7 +221,7 @@ func accessedMountPaths(sumResp, mnt []string) ([]string, error) {
}

// Ignore namespaces based on config
func getFilteredPolicy(client kubernetes.Interface, cname, namespace string, labels LabelMap) error {
func getFilteredPolicy(client kubernetes.Interface, cname, namespace string, labels string) error {
// filters to check the namespaces to be ignored
nsFilter := config.CurrentCfg.ConfigSysPolicy.NsFilter
nsNotFilter := config.CurrentCfg.ConfigSysPolicy.NsNotFilter
Expand Down Expand Up @@ -281,7 +253,7 @@ func getFilteredPolicy(client kubernetes.Interface, cname, namespace string, lab
}

// Generate crown jewel policy
func getCrownjewelPolicy(client kubernetes.Interface, cname, namespace string, labels LabelMap) ([]types.KnoxSystemPolicy, error) {
func getCrownjewelPolicy(client kubernetes.Interface, cname, namespace string, labels string) ([]types.KnoxSystemPolicy, error) {
var policies []types.KnoxSystemPolicy

var matchedMountPaths []string
Expand All @@ -308,37 +280,15 @@ func getCrownjewelPolicy(client kubernetes.Interface, cname, namespace string, l
}
policies = append(policies, policy)

jsonData, err := json.Marshal(policies)
if err != nil {
log.Error().Msg("Error marshaling" + err.Error())
return nil, nil
}
yamlData, err := yaml.JSONToYAML(jsonData)
if err != nil {
log.Error().Msg("Error converting JSON to YAML:" + err.Error())
return nil, nil
}
fmt.Println(string(yamlData))

return policies, nil
}

// Build Crown jewel System policy structure
func buildSystemPolicy(cname, ns, action string, labels LabelMap, matchDirs []types.KnoxMatchDirectories, matchPaths []types.KnoxMatchPaths) types.KnoxSystemPolicy {
func buildSystemPolicy(cname, ns, action string, labels string, matchDirs []types.KnoxMatchDirectories, matchPaths []types.KnoxMatchPaths) types.KnoxSystemPolicy {
clustername := config.GetCfgClusterName()

// expand the labels to be in string format
var combinedLabels []string
for key, value := range labels {
label := fmt.Sprintf("%s=%s", key, value)
combinedLabels = append(combinedLabels, label)
}

sort.Strings(combinedLabels)
labelsString := strings.Join(combinedLabels, ",")

// create policy name
name := strconv.FormatUint(uint64(common.HashInt(labelsString+ns+clustername+cname)), 10)
name := strconv.FormatUint(uint64(common.HashInt(labels+ns+clustername+cname)), 10)
return types.KnoxSystemPolicy{
APIVersion: "security.kubearmor.com/v1",
Kind: "KubeArmorPolicy",
Expand All @@ -350,7 +300,7 @@ func buildSystemPolicy(cname, ns, action string, labels LabelMap, matchDirs []ty
Spec: types.KnoxSystemSpec{
Severity: 7,
Selector: types.Selector{
MatchLabels: labels},
MatchLabels: libs.LabelMapFromString(labels)},
Action: "Allow", // global action - default Allow
Message: "Sensitive assets and process control policy",
File: types.KnoxSys{
Expand All @@ -363,7 +313,7 @@ func buildSystemPolicy(cname, ns, action string, labels LabelMap, matchDirs []ty
}
}

func createCrownjewelPolicy(ms types.MatchSpec, cname, namespace, action string, labels LabelMap, matchedDirPts, matchedMountPts, matchedProcessPts []string, fromSrc map[string]string) types.KnoxSystemPolicy {
func createCrownjewelPolicy(ms types.MatchSpec, cname, namespace, action string, labels string, matchedDirPts, matchedMountPts, matchedProcessPts []string, fromSrc map[string]string) types.KnoxSystemPolicy {
var matchDirs []types.KnoxMatchDirectories
i := 1
for _, dirpath := range matchedDirPts {
Expand Down

0 comments on commit 45d3606

Please sign in to comment.