Skip to content

Commit

Permalink
update allow based rule, update status field for policy insertion in db
Browse files Browse the repository at this point in the history
Signed-off-by: Ankur Kothiwal <[email protected]>
  • Loading branch information
Ankurk99 committed Jun 13, 2023
1 parent 17d2f12 commit fb30102
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 27 deletions.
2 changes: 1 addition & 1 deletion src/conf/local-file.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ recommend:
# Recommended policies configuration
crownjewel:
operation-mode: 1 # 1: cronjob | 2: one-time-job
cron-job-time-interval: "1h0m00s" # format: XhYmZs
cron-job-time-interval: "0h0m20s" # format: XhYmZs

# license
license:
Expand Down
50 changes: 30 additions & 20 deletions src/crownjewel/crownjewel.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package crownjewel

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

Expand All @@ -20,6 +22,7 @@ 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 @@ -103,11 +106,6 @@ func CrownjewelPolicyMain() {
log.Error().Msg("Error getting Deployments err=" + err.Error())
return
}
replicaSets, err := client.AppsV1().ReplicaSets("").List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Error().Msg("Error getting replicasets 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())
Expand All @@ -124,12 +122,6 @@ func CrownjewelPolicyMain() {
log.Error().Msg("Error getting mount paths, err=" + err.Error())
}
}
for _, r := range replicaSets.Items {
err := getFilteredPolicy(client, r.Name, r.Namespace, r.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 {
Expand Down Expand Up @@ -247,7 +239,7 @@ func accessedMountPaths(sumResp, mnt []string) ([]string, error) {

for _, sumRespPath := range sumResp {
for _, mntPath := range mnt {
if strings.Contains(sumRespPath, mntPath) && !duplicatePaths[mntPath] {
if strings.HasPrefix(sumRespPath, mntPath) && !duplicatePaths[mntPath] {
matchedMountPaths = append(matchedMountPaths, mntPath)
duplicatePaths[mntPath] = true
}
Expand All @@ -262,30 +254,34 @@ func getFilteredPolicy(client kubernetes.Interface, cname, namespace string, lab
nsFilter := config.CurrentCfg.ConfigSysPolicy.NsFilter
nsNotFilter := config.CurrentCfg.ConfigSysPolicy.NsNotFilter

var policies []types.KnoxSystemPolicy
var err error
if len(nsFilter) > 0 {
for _, ns := range nsFilter {
if strings.Contains(namespace, ns) {
err := getCrownjewelPolicy(client, cname, namespace, labels)
policies, err = getCrownjewelPolicy(client, cname, namespace, labels)
if err != nil {
log.Error().Msg("Error getting Crown jewel policy, err=" + err.Error())
}
}
}
systempolicy.UpdateSysPolicies(policies)
} else if len(nsNotFilter) > 0 {
for _, notns := range nsNotFilter {
if !strings.Contains(namespace, notns) {
err := getCrownjewelPolicy(client, cname, namespace, labels)
policies, err = getCrownjewelPolicy(client, cname, namespace, labels)
if err != nil {
log.Error().Msg("Error getting Crown jewel policy, err=" + err.Error())
}
}
}
systempolicy.UpdateSysPolicies(policies)
}
return nil
}

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

var matchedMountPaths []string
Expand All @@ -308,13 +304,23 @@ func getCrownjewelPolicy(client kubernetes.Interface, cname, namespace string, l
// Check for empty policy
if policy.Spec.File.MatchDirectories == nil && policy.Spec.File.MatchPaths == nil &&
policy.Spec.Process.MatchDirectories == nil && policy.Spec.Process.MatchPaths == nil {
return nil
return nil, nil
}
policies = append(policies, policy)

systempolicy.UpdateSysPolicies(policies)
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 nil
return policies, nil
}

// Build Crown jewel System policy structure
Expand All @@ -327,16 +333,19 @@ func buildSystemPolicy(cname, ns, action string, labels LabelMap, matchDirs []ty
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)
return types.KnoxSystemPolicy{
APIVersion: "v1",
APIVersion: "security.kubearmor.com/v1",
Kind: "KubeArmorPolicy",
Metadata: map[string]string{
"name": "autopol-sensitive-" + name,
"namespace": ns,
"status": "latest",
},
Spec: types.KnoxSystemSpec{
Severity: 7,
Expand Down Expand Up @@ -374,7 +383,7 @@ func createCrownjewelPolicy(ms types.MatchSpec, cname, namespace, action string,

var fromSourceVal []types.KnoxFromSource
for key, value := range fromSrc {
if strings.Contains(key, dirpath) {
if strings.HasPrefix(key, dirpath) {
// Check if the value already exists in fromSourceVal
exists := false
for _, existing := range fromSourceVal {
Expand All @@ -393,6 +402,7 @@ func createCrownjewelPolicy(ms types.MatchSpec, cname, namespace, action string,
Dir: dirpath + "/",
Recursive: true,
FromSource: fromSourceVal,
Action: action,
}

if action == "Allow" {
Expand Down
1 change: 1 addition & 0 deletions src/libs/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,7 @@ func WriteKubeArmorPolicyToYamlFile(fname string, policies []types.KubeArmorPoli
continue
}
writeYamlByte(f, yamlBytes)
f.WriteString("---\n")
}

if err := f.Close(); err != nil {
Expand Down
12 changes: 7 additions & 5 deletions src/plugin/kubearmor.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,14 @@ func ConvertKnoxSystemPolicyToKubeArmorPolicy(knoxPolicies []types.KnoxSystemPol

kubePolicy.Spec = policy.Spec

if kubePolicy.Kind == types.KindKubeArmorPolicy && policy.Spec.Action == "Allow" {
dirRule := types.KnoxMatchDirectories{
Dir: types.PreConfiguredKubearmorRule,
Recursive: true,
if strings.Contains(policy.Metadata["name"], "sensitive") {
if kubePolicy.Kind == types.KindKubeArmorPolicy && policy.Spec.Action == "Allow" {
dirRule := types.KnoxMatchDirectories{
Dir: types.PreConfiguredKubearmorRule,
Recursive: true,
}
kubePolicy.Spec.File.MatchDirectories = append(policy.Spec.File.MatchDirectories, dirRule)
}
kubePolicy.Spec.File.MatchDirectories = append(policy.Spec.File.MatchDirectories, dirRule)
}

for _, procpath := range kubePolicy.Spec.Process.MatchPaths {
Expand Down
3 changes: 3 additions & 0 deletions src/recommendpolicy/helperFunctions.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,9 @@ func generateKyvernoPolicy(name, namespace string, labels LabelMap) ([]kyvernov1
func createRestrictAutomountSATokenPolicy(ms types.MatchSpec, name, namespace string, labels LabelMap) kyvernov1.PolicyInterface {
policyInterface := *(ms.KyvernoPolicy)
policy := (policyInterface.(*kyvernov1.Policy)).DeepCopy()
if policy.Annotations == nil {
policy.Annotations = make(map[string]string)
}
policy.Annotations[types.RecommendedPolicyTagsAnnotation] = strings.Join(ms.KyvernoPolicyTags, ",")
policy.Name = name + "-" + ms.Name
policy.Namespace = namespace
Expand Down
3 changes: 2 additions & 1 deletion src/systempolicy/systemPolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,8 @@ func WriteSystemPoliciesToFile(namespace, clustername, labels, fromsource string
latestPolicies := libs.GetSystemPolicies(CfgDB, namespace, "latest")
if len(latestPolicies) > 0 {
kubeArmorPolicies := plugin.ConvertKnoxSystemPolicyToKubeArmorPolicy(latestPolicies)
libs.WriteKubeArmorPolicyToYamlFile("kubearmor_policies", kubeArmorPolicies)
fname := "kubearmor_policies_sensitive"
libs.WriteKubeArmorPolicyToYamlFile(fname, kubeArmorPolicies)
}
WriteSystemPoliciesToFile_Ext(namespace, clustername, labels, fromsource, includeNetwork)
}
Expand Down

0 comments on commit fb30102

Please sign in to comment.