Safe K8s Deployment with Open Policy Agent

Introduction

This demo shows how to enforce security policies for K8s deployments using Open Policy Agentarrow-up-right, and the corresponding Gatekeeperarrow-up-right project.

For details on the demo application see hello spring boot application.

Open Policy Agent

Before diving into the Kubernetes part with Gatekeeperarrow-up-right let's look into Open Policy Agentarrow-up-right how open policies work in general.

OPA decouples policy decision-making from policy enforcement. When your software needs to make policy decisions it queries OPA and supplies structured data (e.g., JSON) as input. OPA works similar to a BPM engine, or a state machine by decoupling processes from input and output data.

opa

(Source: https://www.openpolicyagent.org)

Policies in OPA are written using OPA's own language called Regoarrow-up-right.

This example checks if the container image to be deployed on a K8s cluster origins from a trusted container registry called (myreg.com).

To evaluate and play with Regoarrow-up-right you can use The Rego Playgroundarrow-up-right

Gatekeeper

Gatekeeperarrow-up-right installs an admission controllerarrow-up-right on K8s that contains the Open Policy Agentarrow-up-right to enforce policies for deployments on the Kubernetes cluster.

opa

(Source: https://www.openpolicyagent.org)

Lab

To install Gatekeeperarrow-up-right just follow the installation instructionsarrow-up-right or use the script deploy-gatekeeper.sh in this folder.

Rego policies cannot be deployed directly into a K8s cluster, instead Gatekeeperarrow-up-right uses the OPA Constraint Frameworkarrow-up-right.

Here you first deploy a constraint template and then a corresponding constraint using the template. In this step we will enforce that all Pod specifications require to include a security context disallowing privilege escalation by setting allowPrivilegeEscalation to false.

To enforce this, please execute the script deploy-constraint.sh in this folder.

Deploy the application (will be denied)

First we want to see the Gatekeeperarrow-up-right in action so that our deployment is denied because of allowing privilege escalation. The corresponding container image is pulled from andifalk/hello-rootless-jibarrow-up-right docker hub repository.

The application is deployed using the following deployment yaml file k8s/deploy_denied.yaml:

You will get an error message from the Gatekeeperarrow-up-right denying the deployment.

Deploy the application (will be deployed successfully)

Now we want to see that Gatekeeperarrow-up-right accepts our deployment because of disallowing privilege escalation now. The corresponding container image is pulled from andifalk/hello-rootless-jibarrow-up-right docker hub repository.

The application is deployed using the following deployment yaml file k8s/deploy.yaml:

This should now be deployed without any error.

Last updated