Skip to content

Commit

Permalink
feat: Connect with discovery-engine to recommend Kyverno policies
Browse files Browse the repository at this point in the history
Signed-off-by: Vyom-Yadav <jackhammervyom@gmail.com>
  • Loading branch information
Vyom-Yadav committed Apr 1, 2023
1 parent 8f3e118 commit 23b3a90
Show file tree
Hide file tree
Showing 12 changed files with 304 additions and 37 deletions.
1 change: 1 addition & 0 deletions cmd/recommend.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func init() {

recommendCmd.Flags().StringSliceVarP(&recommendOptions.Images, "image", "i", []string{}, "Container image list (comma separated)")
recommendCmd.Flags().StringSliceVarP(&recommendOptions.Labels, "labels", "l", []string{}, "User defined labels for policy (comma separated)")
recommendCmd.Flags().StringSliceVarP(&recommendOptions.Policy, "policy", "p", recommend.DefaultPoliciesToBeRecommended, "Types of policy that can be recommended: KubeArmorPolicy|KyvernoPolicy (comma separated)")
recommendCmd.Flags().StringVarP(&recommendOptions.Namespace, "namespace", "n", "", "User defined namespace value for policies")
recommendCmd.Flags().StringVarP(&recommendOptions.OutDir, "outdir", "o", "out", "output folder to write policies")
recommendCmd.Flags().StringVarP(&recommendOptions.ReportFile, "report", "r", "report.txt", "report file")
Expand Down
11 changes: 9 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/kubearmor/kubearmor-client
go 1.18

replace (
github.com/accuknox/auto-policy-discovery/src => ../discovery-engine/src
github.com/optiopay/kafka => github.com/cilium/kafka v0.0.0-20180809090225-01ce283b732b
k8s.io/api => k8s.io/api v0.26.0
k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.26.0
Expand Down Expand Up @@ -50,19 +51,21 @@ require (
github.com/kubearmor/KubeArmor/KubeArmor v0.0.0-20221130063629-a2dd0301b858
github.com/kubearmor/KubeArmor/deployments v0.0.0-20230307164000-b087f0a8bf7f
github.com/kubearmor/KubeArmor/pkg/KubeArmorController v0.0.0-20230307075632-73ce4fa43639
github.com/kyverno/kyverno v1.6.10
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d
github.com/onsi/ginkgo/v2 v2.5.1
github.com/onsi/gomega v1.24.1
k8s.io/api v0.26.0
k8s.io/apiextensions-apiserver v0.26.0
k8s.io/apimachinery v0.26.0
k8s.io/cli-runtime v0.0.0
k8s.io/cli-runtime v0.23.2
k8s.io/client-go v0.26.0
k8s.io/utils v0.0.0-20221128185143-99ec85e7a448
)

require (
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/DATA-DOG/go-sqlmock v1.5.0 // indirect
github.com/Microsoft/go-winio v0.5.2 // indirect
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
Expand Down Expand Up @@ -94,6 +97,7 @@ require (
github.com/go-openapi/strfmt v0.21.3 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/go-openapi/validate v0.22.0 // indirect
github.com/go-sql-driver/mysql v1.5.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.2 // indirect
Expand All @@ -105,7 +109,7 @@ require (
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 // indirect
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/imdario/mergo v0.3.13 // indirect
github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf // indirect
Expand All @@ -124,6 +128,7 @@ require (
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-runewidth v0.0.14 // indirect
github.com/mattn/go-sqlite3 v1.14.12 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/spdystream v0.2.0 // indirect
Expand Down Expand Up @@ -154,6 +159,7 @@ require (
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
github.com/robfig/cron v1.2.0 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/shirou/gopsutil/v3 v3.22.10 // indirect
Expand Down Expand Up @@ -186,6 +192,7 @@ require (
google.golang.org/appengine v1.6.7 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.80.1 // indirect
Expand Down
22 changes: 17 additions & 5 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,16 @@ dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7
github.com/AdaLogics/go-fuzz-headers v0.0.0-20221118232415-3345c89a7c72 h1:kq78byqmxX6R9uk4uN3HD2F5tkZJAZMauuLSkNPS8to=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8=
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
github.com/accuknox/auto-policy-discovery/src v0.0.0-20230307064047-4bb4ca0b527c h1:ZckxW4jRBrDMdYc6O3ayNhJBse7yVv4pVJdvbMhYl3Y=
github.com/accuknox/auto-policy-discovery/src v0.0.0-20230307064047-4bb4ca0b527c/go.mod h1:PvmbhNMbOH27CbhOTbWy3Vd0Od8B65ixNLd9STvBlP0=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
Expand Down Expand Up @@ -212,6 +213,8 @@ github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-openapi/validate v0.22.0 h1:b0QecH6VslW/TxtpKgzpO1SNG7GU2FsaqKdP1E2T50Y=
github.com/go-openapi/validate v0.22.0/go.mod h1:rjnrwK57VJ7A8xqfpAOEKRH8yQSGUriMu5/zuPSQ1hg=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
Expand Down Expand Up @@ -328,8 +331,8 @@ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 h1:pdN6V1QBWetyv/0+wjACpqVH+eVULgEjkurDLq3goeM=
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJrOjhax5N+uePQ0Fh1Z7PheYoUI/0nzkPA=
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
Expand Down Expand Up @@ -394,6 +397,8 @@ github.com/kubearmor/KubeArmor/pkg/KubeArmorController v0.0.0-20230307075632-73c
github.com/kubearmor/KubeArmor/protobuf v0.0.0-20221117040949-d3559c7ffd74 h1:O2NDViNaRckSAtz8+ipjYT2GEZ3EiU/wLoA1JEhH4Xo=
github.com/kubearmor/KubeArmor/protobuf v0.0.0-20221117040949-d3559c7ffd74/go.mod h1:w6uvrqp4v7p3FynjVpYw46RSjfwHOrx5Botgp7nEDBE=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/kyverno/kyverno v1.6.10 h1:3cdSlsOf2cEerQE+RgsauuQCZ+DpiE7jes17IybjNZ0=
github.com/kyverno/kyverno v1.6.10/go.mod h1:l+MY1fRwSl499vJkKFUDW34XzjDx1zv98vu7hpIUJm0=
github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0=
github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
Expand Down Expand Up @@ -425,6 +430,8 @@ github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRC
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/matttproud/golang_protobuf_extensions v1.0.2 h1:hAHbPm5IJGijwng3PWk09JkG9WeqChjprR5s9bBZ+OM=
github.com/matttproud/golang_protobuf_extensions v1.0.2/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
Expand Down Expand Up @@ -541,6 +548,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.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/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 v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
Expand All @@ -555,7 +564,7 @@ github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQD
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/sasha-s/go-deadlock v0.3.1 h1:sqv7fDNShgjcaxkO0JNcOAlr8B9+cV5Ey/OB71efZx0=
github.com/sasha-s/go-deadlock v0.3.1/go.mod h1:F73l+cr82YSh10GxyRI6qZiCgK64VaZjwesgfQ1/iLM=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
github.com/shirou/gopsutil/v3 v3.22.10 h1:4KMHdfBRYXGF9skjDWiL4RA2N+E8dRdodU/bOZpPoVg=
github.com/shirou/gopsutil/v3 v3.22.10/go.mod h1:QNza6r4YQoydyCfo6rH0blGfKahgibh4dQmV5xdFkQk=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
Expand Down Expand Up @@ -1048,6 +1057,8 @@ gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
Expand All @@ -1065,6 +1076,7 @@ gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
84 changes: 84 additions & 0 deletions recommend/admissionControllerPolicy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package recommend

import (
"context"
"errors"
"github.com/accuknox/auto-policy-discovery/src/libs"
"github.com/accuknox/auto-policy-discovery/src/protobuf/v1/worker"
"github.com/clarketm/json"
"github.com/fatih/color"
"github.com/kubearmor/kubearmor-client/k8s"
"github.com/kubearmor/kubearmor-client/utils"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
log "github.com/sirupsen/logrus"
"golang.org/x/exp/slices"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"os"
"strconv"
"strings"
)

func recommendAdmissionControllerPolicies(img ImageInfo, c *k8s.Client) error {
labels := libs.LabelMapToString(img.Labels)
gRPC := ""
targetSvc := "discovery-engine"
var port int64 = 9089
mtchLabels := map[string]string{"app": "discovery-engine"}
if val, ok := os.LookupEnv("DISCOVERY_SERVICE"); ok {
gRPC = val
} else {
pf, err := utils.InitiatePortForward(c, port, port, mtchLabels, targetSvc)
if err != nil {
return err
}
gRPC = "localhost:" + strconv.FormatInt(pf.LocalPort, 10)
}
// create a client
conn, err := grpc.Dial(gRPC, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return errors.New("could not connect to the server. Possible troubleshooting:\n- Check if discovery engine is running\n- Create a portforward to discovery engine service using\n\t\033[1mkubectl port-forward -n explorer service/knoxautopolicy --address 0.0.0.0 --address :: 9089:9089\033[0m\n[0m")
}
defer func(conn *grpc.ClientConn) {
err := conn.Close()
if err != nil {
log.Println("Error while closing connection")
}
}(conn)
client := worker.NewWorkerClient(conn)
resp, err := client.Convert(context.Background(), &worker.WorkerRequest{
Labels: labels,
Namespace: img.Namespace,
Policytype: "AdmissionControllerPolicy",
})
if err != nil {
color.Red(err.Error())
return err
}
if resp.AdmissionControllerPolicy != nil {
for _, policy := range resp.AdmissionControllerPolicy {
var kyvernoPolicy kyvernov1.Policy
err := json.Unmarshal(policy.Data, &kyvernoPolicy)
if err != nil {
return err
}
if matchAdmissionControllerPolicyTags(&kyvernoPolicy) {
img.writeAdmissionControllerPolicy(kyvernoPolicy)
}
}
}
return nil
}

func matchAdmissionControllerPolicyTags(policy *kyvernov1.Policy) bool {
policyTags := strings.Split(policy.Annotations["recommended-policies.kubearmor.io/tags"], ",")
if len(options.Tags) <= 0 {
return true
}
for _, t := range options.Tags {
if slices.Contains(policyTags, t) {
return true
}
}
return false
}
80 changes: 68 additions & 12 deletions recommend/imageHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"math/rand"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"time"
Expand All @@ -26,6 +27,7 @@ import (
"github.com/docker/docker/pkg/jsonmessage"
"github.com/fatih/color"
kg "github.com/kubearmor/KubeArmor/KubeArmor/log"
"github.com/kubearmor/kubearmor-client/k8s"
"github.com/moby/term"
log "github.com/sirupsen/logrus"
)
Expand Down Expand Up @@ -477,37 +479,91 @@ func getImageDetails(img ImageInfo) error {
// step 3: getImageInfo
img.getImageInfo()

if len(img.RepoTags) == 0 {
img.RepoTags = append(img.RepoTags, img.Name)
}
// step 4: get policy from image info
img.getPolicyFromImageInfo()

return nil
}

func imageHandler(namespace, deployment string, labels LabelMap, imageName string, config string) error {
dockerConfigPath = config
log.WithFields(log.Fields{
"image": imageName,
}).Info("pulling image")
func imageHandler(namespace, deployment string, labels LabelMap, imageName string, c *k8s.Client) error {
dockerConfigPath = options.Config
img := ImageInfo{
Name: imageName,
Namespace: namespace,
Deployment: deployment,
Labels: labels,
}
policiesToBeRecommended := options.Policy

if len(policiesToBeRecommended) == 1 {
policyToBeRecommended := policiesToBeRecommended[0]
if policyToBeRecommended == KyvernoPolicy {
if len(img.RepoTags) == 0 {
img.RepoTags = append(img.RepoTags, img.Name)
}
if err := ReportStart(&img); err != nil {
log.WithError(err).Error("report start failed")
return err
}
err := recommendAdmissionControllerPolicies(img, c)
if err != nil {
log.WithError(err).Error("failed to recommend admission controller policies.")
return err
}
} else if policyToBeRecommended == KubeArmorPolicy {
err := recommendKubeArmorPolicies(imageName, img)
if err != nil {
log.WithError(err).Error("failed to recommend kubearmor policies.")
return err
}
} else {
return fmt.Errorf("policy of kind %s cannot be generated", policyToBeRecommended)
}
} else if len(policiesToBeRecommended) == 2 {
if reflect.DeepEqual(policiesToBeRecommended, DefaultPoliciesToBeRecommended) ||
reflect.DeepEqual(policiesToBeRecommended, []string{KubeArmorPolicy, KyvernoPolicy}) {
errKubeArmorPol := recommendKubeArmorPolicies(imageName, img)
if errKubeArmorPol != nil {
log.WithError(errKubeArmorPol).Error("failed to recommend kubearmor policies.")
}
if len(img.RepoTags) == 0 {
img.RepoTags = append(img.RepoTags, img.Name)
}
errAdmissionControllerPol := recommendAdmissionControllerPolicies(img, c)
if errAdmissionControllerPol != nil {
log.WithError(errAdmissionControllerPol).Error("Failed to recommend admission controller policies.")
}
if errKubeArmorPol != nil || errAdmissionControllerPol != nil {
return fmt.Errorf("failed to recommend policies for image %s", imageName)
}
}
} else {
return fmt.Errorf("policies of kind %v can't be generated", policiesToBeRecommended)
}
_ = ReportSectEnd(&img)

return nil
}

func recommendKubeArmorPolicies(imageName string, img ImageInfo) error {
log.WithFields(log.Fields{
"image": imageName,
}).Info("pulling image")
err := pullImage(imageName)
if err != nil {
log.Warn("Failed to pull image. Dumping generic policies.")
img.OS = "linux"
img.RepoTags = append(img.RepoTags, img.Name)
img.getPolicyFromImageInfo()
return nil
}

err = getImageDetails(img)
if err != nil {
return err
} else {
err = getImageDetails(img)
if err != nil {
return err
}
}

return nil
}

Expand Down
Loading

0 comments on commit 23b3a90

Please sign in to comment.