Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: (vm) policy management for karmor vm policy command #464

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions cmd/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,29 @@ var vmPolicyDeleteCmd = &cobra.Command{
},
}

var vmPolicyGetCmd = &cobra.Command{
Use: "get",
Short: "get policy for bare-metal vm/kvms control plane vm",
Long: `get policy for bare-metal vm/kvms control plane vm`,
RunE: func(cmd *cobra.Command, args []string) error {
return policyOptions.HandleGet(args)
},
}

// ========== //
// == Init == //
// ========== //

func init() {
vmCmd.AddCommand(vmPolicyCmd)

// Add flags to vmPolicyGetCmd
vmPolicyGetCmd.Flags().StringVarP(&policyOptions.Type, "type", "t", "ksp", "Specify the type of policy to get. (ksp or hsp)")

// Subcommand for policy command
vmPolicyCmd.AddCommand(vmPolicyAddCmd)
vmPolicyCmd.AddCommand(vmPolicyDeleteCmd)
vmPolicyCmd.AddCommand(vmPolicyGetCmd)

// gRPC endpoint flag to communicate with KubeArmor. Available across subcommands.
vmPolicyCmd.PersistentFlags().StringVar(&policyOptions.GRPC, "gRPC", "", "gRPC server information")
Expand Down
37 changes: 37 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package utils

import pb "github.com/kubearmor/KubeArmor/protobuf"

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 {
data = append(data, []string{containerName, policyName})
}
}
} 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])
mp[v[0]] = val
} else {
mp[v[0]] = []string{v[1]}
}
}
return data, mp
}

Check warning on line 28 in utils/utils.go

View workflow job for this annotation

GitHub Actions / go-lint

exported function GetArmoredContainerData should have comment or be unexported
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
}

Check warning on line 37 in utils/utils.go

View workflow job for this annotation

GitHub Actions / go-lint

exported function GetHostPolicyData should have comment or be unexported
131 changes: 131 additions & 0 deletions vm/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ package vm
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/fatih/color"
"github.com/kubearmor/kubearmor-client/utils"
"github.com/olekukonko/tablewriter"
"google.golang.org/protobuf/types/known/emptypb"
"os"
"path/filepath"
"regexp"
Expand All @@ -26,9 +31,14 @@ const (
KubeArmorHostPolicy = "KubeArmorHostPolicy"
)

var (
BoldWhite = color.New(color.FgWhite, color.Bold)
)

// PolicyOptions are optional configuration for kArmor vm policy
type PolicyOptions struct {
GRPC string
Type string
}

func sendPolicyOverGRPC(o PolicyOptions, policyEventData []byte, kind string) error {
Expand Down Expand Up @@ -144,3 +154,124 @@ func PolicyHandling(t string, path string, o PolicyOptions) error {

return nil
}

func (o *PolicyOptions) getPolicyData() (*pb.ProbeResponse, error) {
gRPC := ""
if o.GRPC != "" {
gRPC = o.GRPC
} else {
if val, ok := os.LookupEnv("KUBEARMOR_SERVICE"); ok {
gRPC = val
} else {
gRPC = "localhost:32767"
}
}
conn, err := grpc.Dial(gRPC, grpc.WithInsecure())
if err != nil {
return nil, err
}
client := pb.NewProbeServiceClient(conn)

resp, err := client.GetProbeData(context.Background(), &emptypb.Empty{})
if err != nil {
return nil, err
}
return resp, nil
}

func (o *PolicyOptions) HandleGet(args []string) error {
policyData, err := o.getPolicyData()
if err != nil {
return err
}
switch o.Type {
case "ksp", "Container", "container":
if len(args) == 0 {
armoredContainer, _ := utils.GetArmoredContainerData(policyData.ContainerList, policyData.ContainerMap)
return o.printContainerTable(armoredContainer)
}
targetPolicy := args[0]
for _, container := range policyData.GetContainerMap() {
for i, policy := range container.GetPolicyList() {
if policy == targetPolicy { // access the policyDataList using the index from the policyList
if len(container.GetPolicyDataList()) <= i { // check if the index is valid. fallback for backward compatibility
return errors.New("Cannot retrieve data for policy " + targetPolicy)
}
return prettyPrintPolicy(*container.GetPolicyDataList()[i])
}
}
}
return errors.New("Policy " + targetPolicy + " not found")
case "hsp", "Host", "host":
if len(args) == 0 {
hostPolicyData := utils.GetHostPolicyData(policyData)
if len(hostPolicyData) == 0 {
return errors.New("no host policies found")
}
return o.printHostTable(hostPolicyData)
}
targetPolicy := args[0]
for _, host := range policyData.HostMap {
for i, policy := range host.GetPolicyList() {
if policy == targetPolicy {
if len(host.GetPolicyDataList()) <= i { // check if the index is valid. fallback for backward compatibility
return errors.New("Cannot retrieve data for policy " + targetPolicy)
}
return prettyPrintPolicy(*host.GetPolicyDataList()[i])
}
}
}
return errors.New("Policy " + targetPolicy + " not found")
default:
return errors.New("invalid type: " + o.Type)
}
return nil
}

func (o *PolicyOptions) printContainerTable(podData [][]string) error {
_, err := BoldWhite.Println("Armored Up Containers:")
if err != nil {
return err
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"CONTAINER NAME", "POLICY"})
for _, v := range podData {
table.Append(v)
}
table.SetRowLine(true)
table.SetAutoMergeCellsByColumnIndex([]int{0, 1})
table.Render()
return nil
}

func (o *PolicyOptions) printHostTable(hostPolicy [][]string) error {
_, err := BoldWhite.Println("Host Policy:")
if err != nil {
return err
}

table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"HOST NAME ", "POLICY"})
for _, v := range hostPolicy {
table.Append(v)
}
table.SetRowLine(true)
table.SetAutoMergeCellsByColumnIndex([]int{0, 1})
table.Render()
return nil
}

func prettyPrintPolicy(policy pb.Policy) error {
var policyJSON tp.SecurityPolicy
err := json.Unmarshal(policy.Policy, &policyJSON)
if err != nil {
return err
}
yamlPolicy, err := yaml.Marshal(policyJSON)
if err != nil {
return err
}
fmt.Println(strings.TrimRight(string(yamlPolicy), "\n"))
return nil
}
Loading