Giter Site home page Giter Site logo

policies's Introduction

Contributors

Made with contributors-img.

Policies

This repository contains Kyverno policies for a wide array of usage on various Kubernetes and ecosystem resources and subjects. For the optimal searching and browsing experience, please see Usage and Documentation. For guidance on how you can contribute your own, please see Contribution. To request a Kyverno policy be created which doesn't exist, please see Policy Requests.

Usage and Documentation

See https://kyverno.io/policies/ for a list of all the policies represented here in a simplified list with easy filtering abilities.

Contribution

Anyone and everyone is welcome to write and contribute Kyverno policies! We have standardized on several practices to ensure these policies are effective, descriptive, and assist in easy location on the website. Please follow these guidelines when contributing or modifying a policy.

  • As a CNCF project, Kyverno requires all contributors to abide by the DCO guidelines published here. This entails signing off on all git commits.

  • Use the Kyverno annotations to mark your policy with descriptive metadata. This is not only important to explain your policy, but to allow the filtering logic on the policies page to work effectively.

  • Name your policy something descriptive which matches its function. Either dashes or underscores are permitted.

  • Provide test resources (where possible) which allow your policy to be validated using the Kyverno CLI. See an example of a complete policy, resource, and test here. If unfamiliar with the Kyverno CLI and its test ability, please see the documentation here.

  • For validate rules, please set validationFailureAction: Audit so that should a user download and apply the policy without having a yet full understanding of Kyverno, it will not cause unintended harm to their environment by blocking resources.

  • String values do not need to be quoted nor do values which contain JMESPath expressions such as {{request.operation}}. The exception is if a field's value is only such an expression. In those cases, the JMESPath expression needs to be double quoted.

  • Since Kyverno policies are made available on Artifact Hub, each new policy requires a separate metadata file. Create the artifacthub-pkg.yml file in the same directory as your policy. See the Artifact Hub section below for more details on its contents.

  • A dedicated folder must be created for each policy.

  • The folder must be named the same as the policy.

  • Use dashes for folder name and policy name instead of underscores.

  • When updating a policy already in the library, calculate the new sha256 sum of the changed policy and update the artifacthub-pkg.yml file's digest field with this value. This is to ensure Artifact Hub picks up the changes once merged.

Once your policy is written within these guidelines and tested, please open a standard PR against the main branch of kyverno/policies. In order for a policy to make it to the website's policies page, it must first be committed to the main branch in this repo. Following that, an administrator will render these policies to produce Markdown files in a second PR. You do not need to worry about this process, however.

In order to streamline the process, the beginning "stub" of a ClusterPolicy resource is provided below with an example of how especially the annotations should be completed. Be sure to check the documentation and other sample policies as there is no guarantee this below stub is up to date.

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: disallow-capabilities
  annotations:
    policies.kyverno.io/title: Disallow Capabilities
    policies.kyverno.io/category: Pod Security Standards (Baseline)
    policies.kyverno.io/severity: medium
    kyverno.io/kyverno-version: 1.6.0
    policies.kyverno.io/minversion: 1.6.0
    kyverno.io/kubernetes-version: "1.22-1.23"
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      Adding capabilities beyond those listed in the policy must be disallowed.
spec:
  validationFailureAction: audit
  background: true
  rules:
  - name: my-rule-name
    match:
      any:
      - resources:
          kinds:
            - Resource

Artifact Hub

Add an artifacthub-pkg.yml metadata file to the folder. See an example metadata file for Kyverno policies below and customize per the comments.

---
name: backup-all-volumes # The name of the package (only alphanum, no spaces, dashes allowed)
version: 1.0.0 # Version of the policy
displayName: Backup All Volumes  # Display name of the policy
createdAt: "2023-03-29T00:00:00.000Z" # The date this package was created (RFC3339 layout)
description: >-
# The description value should be taken from the relevant annotation policies.kyverno.io/description
      In order for Velero to backup volumes in a Pod using an opt-in approach, it
      requires an annotation on the Pod called `backup.velero.io/backup-volumes` with the
      value being a comma-separated list of the volumes mounted to that Pod. This policy
      automatically annotates Pods (and Pod controllers) which refer to a PVC so that
      all volumes are listed in the aforementioned annotation if a Namespace with the label
      `velero-backup-pvc=true`.
install: |- # The installation instructions for the package
    ```shell
    kubectl apply -f https://raw.githubusercontent.com/kyverno/policies/main/velero/backup-all-volumes/backup-all-volumes.yaml
    ```   
keywords: # Keywords should always have "kyverno" and whatever the value of the policies.kyverno.io/category annotation. 
  - velero
  - kyverno
readme: | # readme should be same as policies.kyverno.io/description annotation plus the last sentence as a static value.
  In order for Velero to backup volumes in a Pod using an opt-in approach, it
  requires an annotation on the Pod called `backup.velero.io/backup-volumes` with the
  value being a comma-separated list of the volumes mounted to that Pod. This policy
  automatically annotates Pods (and Pod controllers) which refer to a PVC so that
  all volumes are listed in the aforementioned annotation if a Namespace with the label
  `velero-backup-pvc=true`.

  Refer to the documentation for more details on Kyverno annotations: https://artifacthub.io/docs/topics/annotations/kyverno/
annotations: # See the annotations guide on Artifact Hub here: https://artifacthub.io/docs/topics/annotations/kyverno/
  kyverno/category: "Velero"
  kyverno/kubernetesVersion: "1.25"
  kyverno/subject: "Pod, Annotation"
digest: 795012387c2755c61fa802fea900011c45520c2cffb27238210933ebb9a7f2c0 # The SHA256 hash String that uniquely identifies this package version

Policy Requests

If you're not yet comfortable with Kyverno and would like to see a policy that may not presently exist, or if you're having trouble crafting that perfect policy, a couple resources exist. The most expedient way to get help may be to post on Kyverno Slack. Kyverno has a rich and active community with its members and maintainers ready to assist. You may also open an issue to request a certain policy be created to satisfy your needs. If going this route, do keep a few things in mind.

  • Clearly explain in detail your use case for why you need a policy which isn't present on the policies page.

  • Explain what you want this policy to do and on what resources.

  • If applicable, explain what other policies and/or steps you have taken yourself that have been unsuccessful.

  • Be responsive to the GitHub issue if further follow-up is required by the contributors or maintainers.

Having this information up front will assist others in crafting a policy to meet your needs.

policies's People

Contributors

abhinav-nirmata avatar anita-ihuman avatar aslafy-z avatar chandan-dk avatar chipzoller avatar dependabot[bot] avatar developer-guy avatar eddycharly avatar guohaoyu110 avatar jimbugwadia avatar leizerbeam avatar mariamfahmy98 avatar mattbator avatar mintbomb27 avatar mohamedasifs123 avatar monotek avatar oshi36 avatar patelrit avatar realshuting avatar ron1 avatar shubham4443 avatar siddharthlal25 avatar smnmtzgr avatar sotoiwa avatar swastik959 avatar treydock avatar ugur99 avatar viveksahu26 avatar vyankd avatar vyankygh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

policies's Issues

drop-all-capabilities policy reports violation on initContainer even initContainer not exist

Kyverno version

  • Kubernetes version: v1.18.6
  • Kyverno version: v1.3.3

Describe the issue
Policy drop-all-capabilities would report violation on initContainer even initContainer not exist in the yaml

  - category: Best Practices
    message: 'validation error: All capabilities should be dropped with only those
      required added back. Rule autogen-check-init-containers failed at path /spec/template/spec/initContainers/'
    policy: drop-all-capabilities
    resources:
    - apiVersion: apps/v1
      kind: Deployment
      name: velero
      namespace: velero
      uid: 674e0e3c-a087-406b-a90c-12c45ffcd248
    rule: autogen-check-init-containers
    scored: true
    status: fail

Expected behavior
If initContainer is not configured, then no policy violation should be reported on that.

Additional context
Here's the velero deployment resource yaml. Only container but no initContainer in the resource.
Policy violation of same policy has reported on container as well, which is expected.

apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2020-12-23T03:06:24Z"
  generation: 1
  labels:
    app.kubernetes.io/component: deployment.velero
    app.kubernetes.io/instance: velero-aws
    app.kubernetes.io/name: velero-aws
  name: velero
  namespace: velero
  resourceVersion: "922407"
  selfLink: /apis/apps/v1/namespaces/velero/deployments/velero
  uid: 674e0e3c-a087-406b-a90c-12c45ffcd248
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app.kubernetes.io/component: deployment.velero
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      annotations:
        prometheus.io/path: /metrics
        prometheus.io/port: "8085"
        prometheus.io/scrape: "true"
      creationTimestamp: null
      labels:
        app.kubernetes.io/component: deployment.velero
        app.kubernetes.io/instance: velero-aws
        app.kubernetes.io/name: velero-aws
        component: velero
        nirmata.io/application.addon.type: Other
        nirmata.io/application.type: cluster-addon
    spec:
      containers:
      - args:
        - server
        command:
        - /velero
        env:
        - name: AWS_SHARED_CREDENTIALS_FILE
          value: /credentials/cloud
        - name: VELERO_SCRATCH_DIR
          value: /scratch
        image: gcr.io/heptio-images/velero:v1.0.0
        imagePullPolicy: IfNotPresent
        name: velero
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /credentials
          name: cloud-credentials
        - mountPath: /plugins
          name: plugins
        - mountPath: /scratch
          name: scratch
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      serviceAccount: velero
      serviceAccountName: velero
      terminationGracePeriodSeconds: 30
      volumes:
      - name: cloud-credentials
        secret:
          defaultMode: 420
          secretName: cloud-credentials
      - emptyDir: {}
        name: plugins
      - emptyDir: {}
        name: scratch

Add safe-to-evict

The policy is not working as it suppose to work.
It's due to absence of conditional anchors in fields spec and volumes.

Add sample to check imagePullSecrets based on the registry

See: https://kubernetes.slack.com/archives/CLGR9BJU9/p1622749892231800?thread_ts=1622729028.223700&cid=CLGR9BJU9

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: require-secrets
spec:
  validationFailureAction: enforce
  rules:
  - name: check-for-image-pull-secrets
    match:
      resources:
        kinds:
        - Pod
    preconditions:
    - key: "{{ images.containers.*.registry }}"
      operator: NotIn
      value:
      - ghcr.io
      - quay.io
    validate:
      message: "The array `imagePullSecret` is required."
      pattern:
        spec:
          imagePullSecrets:
          - name: "?*"

Better descriptions for policies

Policies are hit or miss with respect to explaining why it's useful. They explain what it does, but descriptions could do both to help users better.

GitHub action to rebuild website MD files upon pushes

Need a GitHub action for this repo which:

  1. Detects commits to kyverno/policies
  2. Runs the render program on kyverno/website
  3. Generates the new Markdown files
  4. Pushes those to kyverno/website in /content/en/policies (should wipe contents first!)

Need to handle other files in /content/en/policies to account for tests and kustomize manifests.

Require Limits and Requests

I'd like to have a policy that checks for a match between resource requests and limits. Since there doesn't appear to be any kind of == operator, I tried making use of variables like so:

            containers:
              - resources:
                  requests:
                    memory: "?*"
                  limits:
                    memory: "$(./../../requests/memory)"

To my surprise though, my newly created pod (with non-matching memory requests/limits) passed validation. I suspect the variable is not interpolating what was set for requests.memory and is just using "?*". Am I thinking about this correctly? Is there another method I can use to evaluate?

Set read-only = true on VolumeMounts that are connected to hostPath volumes with a certain path

We want to create a Kyverno policy that whitelists certain hostPath volume paths.

Therefore, we use:

    validate:
      pattern:
         =(spec):
            =(volumes):
              - (hostPath):
                =(path): "/test/path"

But, we also want to validate with this policy that all VolumeMounts that are mounted to the volumes with the /test/path path to be read-only. Is this possible in Kyverno?

Based on the documentation, it looks like this is not possible with the logic that is supported.

Simplify samples policies

Need to standardize on how to write policies in the most simple and efficient manner possible. This is not only to reduce complexity but to be effective teaching aids for new users. The following are examples of how to do this:

  • Remove double quotes from strings
  • Remove name: "*" items from rules when not needed
  • Minimize indentation of dictionary keys

Require Pod Probes

After upgrading from 1.3.6 to 1.4.2, this policy starts again firing alert for CronJobs / Jobs (pods created by them). Applied last CRDs, undeployed Kyverno, cleaned up all crds and policies, installed cleanly, still same issue.
Kubernetes EKS 1.21.

In policy, kind attribute is missing in resource element

This policy and one of the examples, contains a resource element but not a kind attribute. Whereas it is mention in the documentation that while working with resource elements, the kind attribute is mandatory. So, I think policy needs to be updated with the kind attribute.
For confirmation, I applied this policy but it returns an error.

$ kubectl apply -f block-updates-delete.yaml
Error from server: error when creating "block-updates-delete.yaml": admission webhook "validate-policy.kyverno.svc" denied the request: At least one element must be specified in a kind block. The kind attribute is mandatory when working with the resources element

require_drop_all policy tests are failing

While working on kyverno/kyverno#1866 I noticed the following when Kyverno main repo runs the test subcommand:

Executing drop-all-capabilities...
applying 1 policy to 1 resource... 
│───│───────────────────────────────────────────────────────────────────│────────│
│ # │ TEST                                                              │ RESULT │
│───│───────────────────────────────────────────────────────────────────│────────│
│ 1 │ add-capabilities with drop-all-capabilities/check-init-containers │ Fail   │
│───│───────────────────────────────────────────────────────────────────│────────│

I do not know if this is an issue with the policy, policy test or with Kyverno.

Restrict volume types

Hi!

In this example:
https://github.com/kyverno/policies/blob/main/pod-security/restricted/restrict-volume-types/restrict-volume-types.yaml
a huge list of NOT allowed volume types described.

I'm stuck trying to describe a list of ONLY allowed volume types using available anchors and operators of kyverno.
I need to write a rule that reads like:
"If a volume is defined then the type of it can ONLY be configMap or emptyDir or persistentVolumeClaim or ..."
This makes rule definition shorter and prevents of not wanted allow of newly added types in future.

Can anyone help?

`background: false` is specified even though it is not required.

In some sample policies, background: false is specified even though it is not required. The following are some examples.

This is confusing and I think we should specify background: false only where necessary. Alternatively, we should explicitly specify whether the background attribute is true or false for all policies.

disallow-adding-capabilities interferes with require-drop-all

The policy pod-security/baseline/disallow-adding-capabilities contradicts best-practices/require_drop_all.

When I implement require_drop_all, which seems reasonable too, of course I must add the capabilities, that are still required, for example NET_BIND_SERVICE.

I've installed Kyverno via Helm Chart and actually I'd like to keep at least the baseline policies. However, the policy in this form is too strict. The rule should only trigger, if add does include capabilities, which are not part of the default set.

See also https://kubernetes.io/docs/concepts/security/pod-security-standards/

Adding additional capabilities beyond those listed below must be disallowed.
Allowed Values

Undefined/nil
AUDIT_WRITE
CHOWN
DAC_OVERRIDE
FOWNER
FSETID
KILL
MKNOD
NET_BIND_SERVICE
SETFCAP
SETGID
SETPCAP
SETUID
SYS_CHROOT

Additionally it seems the rule missed ephemeralContainers

drop-cap-net-raw policy does not work as expected

Software version numbers

Kubernetes: v1.20.8
Kyverno version: v1.4.2-rc3

Describe the bug
The resource which has multiple drop capabilities can not pass the drop-cap-net-raw policy.

To Reproduce

  1. Apply drop-cap-net-raw policy
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: drop-cap-net-raw
  annotations:
    policies.kyverno.io/title: Drop CAP_NET_RAW
    policies.kyverno.io/category: Best Practices
    policies.kyverno.io/severity: medium
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/description: >-
      Capabilities permit privileged actions without giving full root access. The
      CAP_NET_RAW capability, enabled by default, allows processes in a container to
      forge packets and bind to any interface potentially leading to MitM attacks.
      This policy ensures that all containers explicitly drop the CAP_NET_RAW
      ability.
spec:
  validationFailureAction: enforce
  rules:
  - name: drop-cap-net-raw
    match:
      resources:
        kinds:
        - Pod
    validate:
      message: "The capability CAP_NET_RAW must be explicitly dropped."
      pattern:
        spec:
          containers:
          - securityContext:
              capabilities:
                drop: ["NET_RAW"]
          =(initContainers):
          - securityContext:
              capabilities:
                drop: ["NET_RAW"]
  1. Apply the following resource
apiVersion: v1
kind: Pod
metadata:
  name: test
spec:
  containers:
  - name: test
    image: debian:9
    command: ["/bin/sh", "-c", "sleep infinity"]
    securityContext:
      capabilities:
        drop:
        - NET_RAW
        - SETUID

Expected behavior
Resource Pod/default/test created successfully.

Actual behavior
Resource Pod/default/test was blocked due to the drop-cap-net-raw policy.

Add simple mutate policy covering adding a label

Create a sample policy covering a simple mutation example for adding a label to incoming objects. Although simple, this is a very common request in the community and is a nice introduction to mutations.

Policies for the EKS CIS Rules

Any idea , where can we find the policies related/similar to the below rules:

  1. Ensure that the cluster-admin role is only used where required
  2. Minimize wildcards use in roles and clusterroles

I wanted to have a policy for 3. Minimize access to create pods , for which I could tweak this:
https://kyverno.io/policies/other/block_updates_deletes/

But could not find policies/related to 1 & 2. Any leads would be helpful.

Thanks in advance.

[BUG] The disallow-adding-capabilities incorrectly specifies null instead of "null"

The disallow-adding-capabilities policy uses null instead of "null". Because of this, it doesn't actually enforce disallowing adding capabilities and instead I was able to add NET_ADMIN like so:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: add-caps
spec:
  selector:
    matchLabels:
      app: add-caps
  template:
    metadata:
      labels:
        app: add-caps
    spec:
      containers:
      - name: add-caps
        image: redis
        securityContext:
          capabilities:
            add:
              - "NET_ADMIN"

Once I fixed the policy to "null" the property was correctly enforced.

When set to null and applied, you can note that the rendered pattern spec is:

spec:
  rules:
  - name: capabilities
    validate:
      ...
      pattern:
        spec:
          =(initContainers):
          - =(securityContext):
              =(capabilities): {}
          containers:
          - =(securityContext):
              =(capabilities): {}

re-organize tests

would be good to allow multiple success and failure cases and automate execution.

Improve Policy "drop-all-capabilities"

I just found out, to fulfill the policy drop-all-capabilities it is important to write ALL in upper case. all in lower case won't satisfy it.

Most documentation/blog posts (about dropping all capabilities) I googled, write:

capabilities:
  drop:
    - all

Therefore, it would be nice if either both all and ALL are valid or the message contains a corresponding hint that ALL in upper case has to be used.

Unique Ingress Host sample policy will always validate/deny

The precondition requires any of two opposite checks which will always be true:

any:
  - key: "{{ request.object.spec.rules[].host }}"
    operator: In
    value: "{{ hosts }}"
  - key: "{{ request.object.spec.rules[].host }}"
    operator: NotIn
    value: "{{ hosts }}"

As we have a deny rule here, the second condition is the one to be removed.

rule 'require-namespace' from policy 'disallow-default-namespace' does not work as expected

Hi,

Do we really need the rule require-namespace in the policy https://github.com/kyverno/policies/blob/main/best-practices/disallow_default_namespace/disallow_default_namespace.yaml?

I expected the below pod to fail the rule but that is not the case.

apiVersion: v1
kind: Pod
metadata:
  name: pod-no-namespace
  labels:
    app: myapp
spec: 
  containers:
  - name: nginx
    image: nginx

Is the rule indeed not working as expected or is my understanding wrong here?

Regards,
Shilpa

not able to apply block_updates_deletes policy

While using https://kyverno.io/policies/other/block_updates_deletes/?policytypes=RBAC policy, getting this error.

error: error validating "kubernetes-infra/kyverno/policies/block-delete.yaml": error validating data: ValidationError(ClusterPolicy.spec.rules[0].match.resources): unknown field "kind" in io.kyverno.v1.ClusterPolicy.spec.rules.match.resources; if you choose to ignore these errors, turn validation off with --validate=false

Kyverno version: 1.4.2

Integrate Github Action

Is your feature request related to a problem? Please describe current state:
The repository does not have a contributor appreciation automation.

Describe the solution you'd like:
Integrate the behaviour bot from Github Apps into the repository.

Describe alternatives you've considered:
No alternative for now.

Screenshots
28289605-1ab81a76-6af8-11e7-8f78-6a1b3948df36

Contributor Resources

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.