├── .editorconfig
├── .gitignore
├── 2-network-policies
├── Readme.md
├── apply.sh
├── mongodb
│ ├── nosqlclient-basic-auth-secret.yaml
│ ├── nosqlclient-deployment.yaml
│ ├── nosqlclient-ingress.yaml
│ ├── nosqlclient-service.yaml
│ └── values.yaml
├── namespaces
│ ├── monitoring.yaml
│ └── production.yaml
├── network-policies
│ ├── 1-ingress-production-deny-all.yaml
│ ├── 2-ingress-production-allow-traefik-nosqlclient.yaml
│ ├── 3-ingress-production-allow-nosqlclient-mongo.yaml
│ ├── 4-ingress-production-allow-prometheus-mongodb.yaml
│ ├── 5-ingress-kube-system.yaml
│ ├── 6-ingress-monitoring.yaml
│ ├── 7-egress-default-and-production-namespace.yaml
│ ├── 8-egress-other-namespaces.yaml
│ └── 9-egress-specific-ips-example.yaml
├── prometheus
│ ├── prometheus-basic-auth-secret.yaml
│ └── values.yaml
├── traefik
│ ├── traefik-basic-console-basic-auth-secret.yaml
│ └── values.yaml
├── users.json
└── web-console
│ ├── deployment.yaml
│ ├── ingress.yaml
│ ├── secrets.yaml
│ ├── service-account.yaml
│ └── service.yaml
├── 3-security-context
├── Readme.md
├── apply.sh
└── demo
│ ├── 01-deployment-run-as-non-root.yaml
│ ├── 02-deployment-run-as-non-root-unprivileged.yaml
│ ├── 03-deployment-run-as-user-unprivileged.yaml
│ ├── 04-deployment-run-as-user.yaml
│ ├── 05-deployment-allow-no-privilege-escalation.yaml
│ ├── 06-deployment-seccomp.yaml
│ ├── 07-deployment-run-without-caps.yaml
│ ├── 08-deployment-run-with-certain-caps.yaml
│ ├── 09-deployment-run-without-caps-unprivileged.yaml
│ ├── 10-deployment-read-only-fs.yaml
│ ├── 10a-netpol-egress-docker-sudo-allow-internal-only.yaml
│ ├── 11-deployment-nginx-read-only-fs.yaml
│ ├── 12-deployment-nginx-read-only-fs-empty-dirs.yaml
│ ├── 13-deployment-all-at-once.yaml
│ └── interactive-demo.sh
├── 4-pod-security-policies
├── Readme.md
├── apply.sh
└── demo
│ ├── 01-psp-restrictive.yaml
│ ├── 01b-nginx-unprivileged.yaml
│ ├── 02a-psp-whitelist.yaml
│ ├── 02b-patch-nginx-service-account.yaml
│ ├── interactive-demo.sh
│ └── psp-privileged.yaml
├── LICENSE
├── Readme.md
├── cluster-utils.sh
├── config.sh
├── createCluster.sh
├── delete-clusters.sh
├── interactive-utils.sh
└── terraform
├── main.tf
└── vars.tf
/.editorconfig:
--------------------------------------------------------------------------------
1 | # top-most EditorConfig file
2 | root = true
3 |
4 | # Unix-style newlines with a newline ending every file
5 | [*]
6 | end_of_line = lf
7 |
8 | [*.json]
9 | indent_style = space
10 | indent_size = 2
11 |
12 | # 4 space indentation
13 | [*.sh]
14 | indent_style = space
15 | indent_size = 2
16 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 | *.iml
3 | terraform/account.json
4 | terraform/.terraform
--------------------------------------------------------------------------------
/2-network-policies/Readme.md:
--------------------------------------------------------------------------------
1 | # NetworkPolicy Demo
2 |
3 | 
4 |
5 | ## Demo Overview
6 |
7 | * Query users from mongo, traefik dashboard, prometheus
8 | * Enable Block all NW Policies in production namespace
9 | * No longer query users
10 | * But: Ingress not working, mongo not reachable
11 | * Whitelist
12 | * Advanced ingress and egress topics
13 | * See the [network-policies](network-policies) folder for YAML representation of the applied Network Policies.
14 |
15 | ## Demo Listing
16 |
17 | `apply.sh` deploys the applications required for the demos.
18 |
19 | Then you can start the demo:
20 |
21 | ```shell script
22 | # Switch to proper kubectl context - alternatively use kubectx
23 | source ../config.sh
24 | gcloud container clusters get-credentials ${CLUSTER[2]} \
25 | --zone ${ZONE} \
26 | --project ${PROJECT}
27 | ## Reset
28 | kubectl delete netpol --all -n production
29 | kubectl delete netpol --all -n default
30 | kubectl delete netpol --all -n kube-system
31 | kubectl delete netpol --all -n monitoring
32 |
33 |
34 | #### All traffic is allowed
35 | # http://web-console
36 | curl https://fastdl.mongodb.org/linux/mongodb-shell-linux-x86_64-debian92-4.4.1.tgz | tar zxv -C /tmp
37 | mv /tmp/mongo*/bin/mongo /tmp/
38 | /tmp/mongo users --host mongodb.production.svc.cluster.local --eval 'db.users.find().pretty()'
39 | curl traefik-prometheus.kube-system.svc.cluster.local:9100/metrics
40 | curl prometheus-server.monitoring.svc.cluster.local/graph
41 |
42 | #### Deny all Network Policy
43 | # Console Window
44 | cat network-policies/1-ingress-production-deny-all.yaml
45 | kubectl apply -f network-policies/1-ingress-production-deny-all.yaml
46 | # http://web-console ➡️ exception: connect failed
47 | /tmp/mongo users --host mongodb.production.svc.cluster.local --eval 'db.users.find().pretty()'
48 | # http://nosqlclient/ ➡️ Gateway Timeout
49 |
50 | #### Allow ingress traffic from ingress controller
51 | # Console Window
52 | cat network-policies/2-ingress-production-allow-traefik-nosqlclient.yaml
53 | kubectl apply -f network-policies/2-ingress-production-allow-traefik-nosqlclient.yaml
54 | # http://nosqlclient/➡️ Ingress works again➡️ But can't connect to database mongodb://mongodb/users
55 |
56 |
57 | #### Allow ingress traffic on mongo from nosqlclient
58 | # Console Window
59 | cat network-policies/3-ingress-production-allow-nosqlclient-mongo.yaml
60 | kubectl apply -f network-policies/3-ingress-production-allow-nosqlclient-mongo.yaml
61 | # http://nosqlclient/➡️ Connection works again to database mongodb://mongodb/users
62 |
63 | #### Allow scraping metrics on mongo from prometheus (monitoring namespace)
64 | # http://promtheus
65 | # Still can scrape mongodb?➡️ Pitfall: Restart prometheus
66 | # Console Window
67 | kubectl -n monitoring delete pod $(kubectl -n monitoring get pods | awk '/prometheus-server/ {print $1;exit}')
68 | # http://promtheus➡️ No longer possible to scrape
69 | # Console Window
70 | cat network-policies/4-ingress-production-allow-prometheus-mongodb.yaml
71 | kubectl apply -f network-policies/4-ingress-production-allow-prometheus-mongodb.yaml
72 | # http://promtheus ➡ Scraping possible again
73 |
74 | #### Limit ingress to kube-system and monitoring namespaces
75 | # Console Window
76 | kubectl apply -f network-policies/5-ingress-kube-system.yaml
77 | kubectl apply -f network-policies/6-ingress-monitoring.yaml
78 | # http://web-console➡️ no longer possible to query traefik or prometheus from web-console
79 | curl traefik-prometheus.kube-system.svc.cluster.local:9100/metrics
80 | curl prometheus-server.monitoring.svc.cluster.local/graph
81 |
82 | #### Limit egress from default and production namespace
83 | # Console Window
84 | kubectl apply -f network-policies/7-egress-default-and-production-namespace.yaml
85 | # http://web-console
86 | curl https://fastdl.mongodb.org/linux/mongodb-shell-linux-x86_64-debian92-4.4.1.tgz | tar zxv -C /tmp
87 | # ➡️ not possible to download mongodb client
88 |
89 | #### Limit egress from other namespaces
90 |
91 | # Place actual API Server address in YAML before applying it. See comment in 8-egress-other-namespaces.yaml for more details
92 | ACTUAL_API_SERVER_ADDRESS=$(kubectl get endpoints --namespace default kubernetes --template="{{range .subsets}}{{range .addresses}}{{.ip}}{{end}}{{end}}")
93 | cat network-policies/8-egress-other-namespaces.yaml \
94 | | sed "s|APISERVER|${ACTUAL_API_SERVER_ADDRESS}/32|" \
95 | | kubectl apply -f -
96 |
97 | kubectl -n monitoring delete pod $(kubectl -n monitoring get pods | awk '/prometheus-server/ {print $1;exit}')
98 | kubectl rollout restart deployment traefik -n kube-system
99 | # http://promtheus ➡ Scraping possible again
100 | ```
101 |
102 |
--------------------------------------------------------------------------------
/2-network-policies/apply.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 |
4 | BASEDIR=$(dirname $0)
5 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
6 |
7 | source ${ABSOLUTE_BASEDIR}/../config.sh
8 | source ${ABSOLUTE_BASEDIR}/../cluster-utils.sh
9 | source ${ABSOLUTE_BASEDIR}/../interactive-utils.sh
10 |
11 | function main() {
12 |
13 | confirm "Preparing demo in kubernetes cluster '$(kubectl config current-context)'." 'Continue? y/n [n]' \
14 | || exit 0
15 |
16 | kubectl apply -f ${ABSOLUTE_BASEDIR}/namespaces
17 | # Assign label to kube-system namespace so we can match it in network policies
18 | kubectlIdempotent label namespace/kube-system namespace=kube-system --overwrite
19 |
20 | # Note that this requires the applying user to be cluster admin
21 | kubectl apply -f ${ABSOLUTE_BASEDIR}/traefik/traefik-basic-console-basic-auth-secret.yaml
22 |
23 | helm repo add stable https://charts.helm.sh/stable
24 |
25 | helm upgrade --install traefik --namespace kube-system --version 1.87.7 \
26 | --values ${ABSOLUTE_BASEDIR}/traefik/values.yaml \
27 | stable/traefik
28 |
29 | externalIp=$(waitForExternalIp "traefik" "kube-system")
30 | writeEtcHosts "${externalIp}" "$(findIngressHostname "traefik-dashboard" "kube-system")"
31 |
32 | kubectl apply -f ${ABSOLUTE_BASEDIR}/web-console
33 | writeEtcHosts "${externalIp}" "$(findIngressHostname "web-console" "default")"
34 |
35 | kubectl apply -f ${ABSOLUTE_BASEDIR}/prometheus/prometheus-basic-auth-secret.yaml
36 |
37 | helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
38 | helm upgrade --install prometheus --namespace=monitoring --version 11.16.2 \
39 | --values ${ABSOLUTE_BASEDIR}/prometheus/values.yaml \
40 | prometheus-community/prometheus
41 |
42 | writeEtcHosts "${externalIp}" "$(findIngressHostname "prometheus-server" "monitoring")"
43 |
44 | # Make sure mongodb is applied first, otherwise adminmongo seems not to show predefined DB
45 | helm repo add bitnami https://charts.bitnami.com/bitnami
46 | helm upgrade --install mongo --namespace=production --version 9.2.4 \
47 | --values ${ABSOLUTE_BASEDIR}/mongodb/values.yaml \
48 | bitnami/mongodb
49 | waitForPodReady mongodb production
50 |
51 | kubectl -n production cp ${ABSOLUTE_BASEDIR}/users.json mongodb-0:/tmp/users.json
52 | # Data taken from https://swapi.co/api/people/?format=json
53 | kubectl -n production exec mongodb-0 -- mongoimport -d users -c users --jsonArray /tmp/users.json
54 |
55 | find ${ABSOLUTE_BASEDIR}/mongodb -name 'nosqlclient*' -exec kubectl apply -f {} \;
56 | writeEtcHosts "${externalIp}" "$(findIngressHostname "nosqlclient" "production")"
57 | }
58 |
59 | main "$@"
--------------------------------------------------------------------------------
/2-network-policies/mongodb/nosqlclient-basic-auth-secret.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Secret
3 | type: Opaque
4 | metadata:
5 | name: nosqlclient-basic-auth
6 | namespace: production
7 | data:
8 | htpasswd: YWRtaW46JGFwcjEkMkIwOTlYdUIkV1VlZzFESlNscFRGVkdoTlFmWjMuLgo=
--------------------------------------------------------------------------------
/2-network-policies/mongodb/nosqlclient-deployment.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: nosqlclient
6 | name: nosqlclient
7 | namespace: production
8 | spec:
9 | selector:
10 | matchLabels:
11 | run: nosqlclient
12 | strategy:
13 | type: Recreate
14 | template:
15 | metadata:
16 | labels:
17 | run: nosqlclient
18 | spec:
19 | containers:
20 | - image: mongoclient/mongoclient:4.0.1
21 | name: nosqlclient
22 | resources:
23 | requests:
24 | #cpu: 100m
25 | memory: 128Mi
26 | limits:
27 | #cpu: 500m
28 | memory: 512Mi
29 | # Error: failed to connect to server [mongodb:27017]
30 | # Doesn't seem to happen without readiness probe :-/
31 | #readinessProbe:
32 | # httpGet:
33 | # path: /
34 | # port: 3000
35 | livenessProbe:
36 | httpGet:
37 | path: /
38 | port: 3000
39 | ports:
40 | - containerPort: 3000
41 | env:
42 | - name: MONGO_URL
43 | value: mongodb://mongodb
44 | - name: MONGOCLIENT_DEFAULT_CONNECTION_URL
45 | value: mongodb://mongodb/users
46 |
47 |
--------------------------------------------------------------------------------
/2-network-policies/mongodb/nosqlclient-ingress.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: extensions/v1beta1
2 | kind: Ingress
3 | metadata:
4 | name: nosqlclient
5 | namespace: production
6 | annotations:
7 | kubernetes.io/ingress.class: traefik
8 | ingress.kubernetes.io/auth-type: basic
9 | ingress.kubernetes.io/auth-secret: nosqlclient-basic-auth
10 | spec:
11 | rules:
12 | - host: nosqlclient
13 | http:
14 | paths:
15 | - path: /
16 | backend:
17 | serviceName: nosqlclient
18 | servicePort: 80
19 |
--------------------------------------------------------------------------------
/2-network-policies/mongodb/nosqlclient-service.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Service
3 | metadata:
4 | labels:
5 | run: nosqlclient
6 | name: nosqlclient
7 | namespace: production
8 | spec:
9 | ports:
10 | - name: http
11 | port: 80
12 | protocol: TCP
13 | targetPort: 3000
14 | selector:
15 | run: nosqlclient
--------------------------------------------------------------------------------
/2-network-policies/mongodb/values.yaml:
--------------------------------------------------------------------------------
1 | fullnameOverride: mongodb
2 | useStatefulSet: true
3 |
4 | auth:
5 | # This is a deliberate security misconfiguration. When using plain mongo docker image, e.g. this is the default :-o
6 | enabled: false
7 |
8 | metrics:
9 | enabled: true
10 | livenessProbe:
11 | enabled: true
12 | readinessProbe:
13 | enabled: true
--------------------------------------------------------------------------------
/2-network-policies/namespaces/monitoring.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Namespace
3 | metadata:
4 | name: monitoring
5 | labels:
6 | namespace: monitoring
7 |
--------------------------------------------------------------------------------
/2-network-policies/namespaces/production.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Namespace
3 | metadata:
4 | name: production
5 | namespace: production
6 |
--------------------------------------------------------------------------------
/2-network-policies/network-policies/1-ingress-production-deny-all.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-default-deny-all
5 | namespace: production
6 | spec:
7 | podSelector: {}
8 | ingress: []
--------------------------------------------------------------------------------
/2-network-policies/network-policies/2-ingress-production-allow-traefik-nosqlclient.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-allow-traefik-to-access-nosqlclient
5 | namespace: production
6 | spec:
7 | podSelector:
8 | matchLabels:
9 | run: nosqlclient
10 | ingress:
11 | - ports:
12 | - port: 3000
13 | from:
14 | - namespaceSelector:
15 | matchLabels:
16 | namespace: kube-system
17 | podSelector:
18 | matchLabels:
19 | app: traefik
20 | # Note:
21 | # * kube-system does not have a label by default, so we cannot match it.
22 | # If we wanted to achieve that, we could assign it a label like so: kubectl label namespace/kube-system namespace=kube-system
23 | # * Combination of namespaceSelector and podSelector is only available from k8s 1.11+:
24 | # https://github.com/kubernetes/kubernetes/blob/master/CHANGELOG-1.11.md#sig-network-1
25 | # Alternative that works on k8s < 1.11 but is less restrictive: Match all namespaces
26 | #- namespaceSelector: {}
27 |
--------------------------------------------------------------------------------
/2-network-policies/network-policies/3-ingress-production-allow-nosqlclient-mongo.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-allow-nosqlclient-to-access-mongo
5 | namespace: production
6 | spec:
7 | podSelector:
8 | matchLabels:
9 | app.kubernetes.io/name: mongodb
10 | ingress:
11 | - ports:
12 | # Refer to the ports.containerPort.name field in mongo pod
13 | - port: mongodb
14 | from:
15 | - podSelector:
16 | matchLabels:
17 | run: nosqlclient
18 |
--------------------------------------------------------------------------------
/2-network-policies/network-policies/4-ingress-production-allow-prometheus-mongodb.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-allow-prometheus-to-access-mongodb-monitoring
5 | namespace: production
6 | spec:
7 | podSelector:
8 | matchLabels:
9 | app.kubernetes.io/name: mongodb
10 | ingress:
11 | - ports:
12 | # Refer to the ports.containerPort.name field in mongo pod
13 | - port: metrics
14 | from:
15 | - namespaceSelector:
16 | matchLabels:
17 | namespace: monitoring
18 | podSelector:
19 | matchLabels:
20 | app: prometheus
21 | component: server
--------------------------------------------------------------------------------
/2-network-policies/network-policies/5-ingress-kube-system.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-default-deny-all
5 | namespace: kube-system
6 | spec:
7 | podSelector: {}
8 | ingress: []
9 | ---
10 | kind: NetworkPolicy
11 | apiVersion: networking.k8s.io/v1
12 | metadata:
13 | name: ingress-allow-kube-dns-all-namespaces
14 | namespace: kube-system
15 | spec:
16 | podSelector:
17 | matchLabels:
18 | k8s-app: kube-dns
19 | ingress:
20 | - ports:
21 | - protocol: UDP
22 | port: 53
23 | - protocol: TCP
24 | port: 53
25 | from:
26 | - namespaceSelector: {}
27 | ---
28 | kind: NetworkPolicy
29 | apiVersion: networking.k8s.io/v1
30 | metadata:
31 | name: ingress-allow-traefik-external
32 | namespace: kube-system
33 | spec:
34 | podSelector:
35 | matchLabels:
36 | app: traefik
37 | ingress:
38 | - ports:
39 | - port: 80
40 | - port: 443
41 | from: []
42 | ---
43 | kind: NetworkPolicy
44 | apiVersion: networking.k8s.io/v1
45 | metadata:
46 | name: ingress-allow-prometheus-traefik
47 | namespace: kube-system
48 | spec:
49 | podSelector:
50 | matchLabels:
51 | app: traefik
52 | ingress:
53 | - ports:
54 | - port: 9100
55 | from:
56 | - namespaceSelector:
57 | matchLabels:
58 | namespace: monitoring
59 | podSelector:
60 | matchLabels:
61 | app: prometheus
62 | component: server
--------------------------------------------------------------------------------
/2-network-policies/network-policies/6-ingress-monitoring.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: ingress-default-deny-all
5 | namespace: monitoring
6 | spec:
7 | podSelector: {}
8 | ingress: []
9 | ---
10 | kind: NetworkPolicy
11 | apiVersion: networking.k8s.io/v1
12 | metadata:
13 | name: ingress-allow-traefik-to-access-prometheus-server
14 | namespace: monitoring
15 | spec:
16 | podSelector:
17 | matchLabels:
18 | app: prometheus
19 | component: server
20 | ingress:
21 | - ports:
22 | - port: 9090
23 | from:
24 | - namespaceSelector:
25 | matchLabels:
26 | namespace: kube-system
27 | podSelector:
28 | matchLabels:
29 | app: traefik
30 | ---
31 | # Note: The following rules can also be generated by helm chart but seem to cause Problems when there are no Netpols for prometheus server.
32 | # See 2-network-policies/prometheus/values.yaml
33 | kind: NetworkPolicy
34 | apiVersion: networking.k8s.io/v1
35 | metadata:
36 | name: ingress-prometheus-alertmanager
37 | namespace: monitoring
38 | spec:
39 | podSelector:
40 | matchLabels:
41 | app: prometheus
42 | component: alertmanager
43 | ingress:
44 | - ports:
45 | - port: 9093
46 | protocol: TCP
47 | - from:
48 | - podSelector:
49 | matchLabels:
50 | app: prometheus
51 | component: server
52 | ---
53 | kind: NetworkPolicy
54 | apiVersion: networking.k8s.io/v1
55 | metadata:
56 | name: ingress-prometheus-kube-state-metrics
57 | namespace: monitoring
58 | spec:
59 | podSelector:
60 | matchLabels:
61 | app: prometheus
62 | component: kube-state-metrics
63 | ingress:
64 | - ports:
65 | - port: 8080
66 | protocol: TCP
67 | - from:
68 | - podSelector:
69 | matchLabels:
70 | app: prometheus
71 | component: server
72 |
--------------------------------------------------------------------------------
/2-network-policies/network-policies/7-egress-default-and-production-namespace.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: egress-allow-internal-only
5 | namespace: default
6 | spec:
7 | policyTypes:
8 | - Egress
9 | podSelector: {}
10 | egress:
11 | - to:
12 | - namespaceSelector: {}
13 | # Almost same effect, but requires knowledge about IP range of internal networks (nodes, services, pods)
14 | # https://en.wikipedia.org/wiki/IP_address#Private_addresses
15 | #- ipBlock:
16 | # cidr: 10.0.0.0/8
17 | ---
18 | kind: NetworkPolicy
19 | apiVersion: networking.k8s.io/v1
20 | metadata:
21 | name: egress-allow-internal-only
22 | namespace: production
23 | spec:
24 | policyTypes:
25 | - Egress
26 | podSelector: {}
27 | egress:
28 | - to:
29 | - namespaceSelector: {}
--------------------------------------------------------------------------------
/2-network-policies/network-policies/8-egress-other-namespaces.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: egress-allow-cluster-internal-only
5 | namespace: monitoring
6 | spec:
7 | policyTypes:
8 | - Egress
9 | podSelector: {}
10 | egress:
11 | - to:
12 | - namespaceSelector: {}
13 | ---
14 | # Allowing IPs 10.0.0.0/8 might not include API server, even when the "kubernetes" service is within this range.
15 | # It depends on the actual IP address that is resolved behind the service.
16 | # On GKE this is an external IP.
17 | # So find out the IP as follows and replace "APISERVER" by it:
18 | # kubectl get endpoints --namespace default kubernetes
19 | # See https://stackoverflow.com/a/56494510/1845976
20 | # Using "0.0.0.0/0" would be a workaround. It allows all egress. Works everywhere but does not adhere least privilege principle.
21 | kind: NetworkPolicy
22 | apiVersion: networking.k8s.io/v1
23 | metadata:
24 | name: egress-allow-prometheus-server-access-api-server
25 | namespace: monitoring
26 | spec:
27 | policyTypes:
28 | - Egress
29 | podSelector:
30 | matchLabels:
31 | app: prometheus
32 | component: server
33 | egress:
34 | - to:
35 | - ipBlock:
36 | cidr: APISERVER
37 | ---
38 | # Note: The following rules can also be generated by helm chart but seem to cause Problems when there are no Netpols for prometheus server.
39 | kind: NetworkPolicy
40 | apiVersion: networking.k8s.io/v1
41 | metadata:
42 | name: ingress-allow-prometheus-to-access-kube-state-metrics
43 | namespace: monitoring
44 | spec:
45 | podSelector:
46 | matchLabels:
47 | app.kubernetes.io/name: kube-state-metrics
48 | ingress:
49 | - ports:
50 | # No name in ksm pod
51 | - port: 8080
52 | from:
53 | - namespaceSelector:
54 | matchLabels:
55 | namespace: monitoring
56 | podSelector:
57 | matchLabels:
58 | app: prometheus
59 | component: server
60 | ---
61 | kind: NetworkPolicy
62 | apiVersion: networking.k8s.io/v1
63 | metadata:
64 | name: ingress-allow-prometheus-to-access-node-exporter
65 | namespace: monitoring
66 | spec:
67 | podSelector:
68 | matchLabels:
69 | app: prometheus
70 | component: node-exporter
71 | ingress:
72 | - ports:
73 | - port: metrics
74 | from:
75 | - namespaceSelector:
76 | matchLabels:
77 | namespace: monitoring
78 | podSelector:
79 | matchLabels:
80 | app: prometheus
81 | component: server
82 | ---
83 | kind: NetworkPolicy
84 | apiVersion: networking.k8s.io/v1
85 | metadata:
86 | name: egress-allow-cluster-internal-only
87 | namespace: kube-system
88 | spec:
89 | policyTypes:
90 | - Egress
91 | podSelector: {}
92 | egress:
93 | - to:
94 | - namespaceSelector: {}
95 | ---
96 | kind: NetworkPolicy
97 | apiVersion: networking.k8s.io/v1
98 | metadata:
99 | name: egress-allow-traefik-access-api-server
100 | namespace: kube-system
101 | spec:
102 | policyTypes:
103 | - Egress
104 | podSelector:
105 | matchLabels:
106 | app: traefik
107 | egress:
108 | - to:
109 | - ipBlock:
110 | cidr: APISERVER
111 | ---
112 | # If you want DNS resolution outside of the cluster
113 | kind: NetworkPolicy
114 | apiVersion: networking.k8s.io/v1
115 | metadata:
116 | name: egress-allow-kube-dns-access-outside
117 | namespace: kube-system
118 | spec:
119 | policyTypes:
120 | - Egress
121 | podSelector:
122 | matchLabels:
123 | k8s-app: kube-dns
124 | egress:
125 | - ports:
126 | # TODO This port restriction does not seem to be effective, as kube DNS can still talk to API Server on port 443.
127 | # If this should ever work, Kube DNS must be allowed to talk to api server, just like traefik and prometheus.
128 | - protocol: UDP
129 | port: 53
130 | - protocol: TCP
131 | port: 53
132 | - to:
133 | - ipBlock:
134 | cidr: 0.0.0.0/0
--------------------------------------------------------------------------------
/2-network-policies/network-policies/9-egress-specific-ips-example.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: egress-allow-nginx-apt
5 | namespace: production
6 | spec:
7 | policyTypes:
8 | - Egress
9 | podSelector:
10 | matchLabels:
11 | run: nginx
12 | egress:
13 | - to:
14 | - ipBlock:
15 | cidr: 128.61.240.73/32
16 | - ipBlock:
17 | cidr: 128.31.0.0/24
18 | - ipBlock:
19 | cidr: 130.89.148.14/32
20 | - ipBlock:
21 | cidr: 149.20.4.0/24
22 | - ipBlock:
23 | cidr: 128.101.240.215/32
24 | - ipBlock:
25 | cidr: 151.101.184.204/32
26 | - ipBlock:
27 | cidr: 5.153.231.4/32
--------------------------------------------------------------------------------
/2-network-policies/prometheus/prometheus-basic-auth-secret.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Secret
3 | type: Opaque
4 | metadata:
5 | name: prometheus-basic-auth
6 | namespace: monitoring
7 | data:
8 | htpasswd: YWRtaW46JGFwcjEkMkIwOTlYdUIkV1VlZzFESlNscFRGVkdoTlFmWjMuLgo=
--------------------------------------------------------------------------------
/2-network-policies/prometheus/values.yaml:
--------------------------------------------------------------------------------
1 | alertmanager:
2 | enabled: false
3 | alertmanagerFiles:
4 | alertmanager.yml: ""
5 | pushgateway:
6 | enabled: false
7 | # This seems to lead to failures when connecting to kube api server: "failed to list *v1.Pod: Get https://"
8 | #networkPolicy:
9 | #enabled: true
10 |
11 | server:
12 | ingress:
13 | enabled: true
14 | hosts:
15 | - prometheus
16 | annotations:
17 | ingress.kubernetes.io/auth-type: basic
18 | ingress.kubernetes.io/auth-secret: prometheus-basic-auth
19 |
--------------------------------------------------------------------------------
/2-network-policies/traefik/traefik-basic-console-basic-auth-secret.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Secret
3 | type: Opaque
4 | metadata:
5 | name: traefik-basic-auth
6 | namespace: kube-system
7 | data:
8 | htpasswd: YWRtaW46JGFwcjEkMkIwOTlYdUIkV1VlZzFESlNscFRGVkdoTlFmWjMuLgo=
--------------------------------------------------------------------------------
/2-network-policies/traefik/values.yaml:
--------------------------------------------------------------------------------
1 | dashboard:
2 | enabled: true
3 | domain: traefik
4 | ingress:
5 | annotations:
6 | ingress.kubernetes.io/auth-type: basic
7 | ingress.kubernetes.io/auth-secret: traefik-basic-auth
8 |
9 | rbac:
10 | enabled: true
11 | metrics:
12 | prometheus:
13 | enabled: true
14 |
15 | deployment:
16 | podAnnotations:
17 | prometheus.io/scrape: "true"
18 | prometheus.io/port: "9100"
19 |
20 |
21 |
--------------------------------------------------------------------------------
/2-network-policies/users.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "Luke Skywalker",
4 | "height": "172",
5 | "mass": "77",
6 | "hair_color": "blond",
7 | "skin_color": "fair",
8 | "eye_color": "blue",
9 | "birth_year": "19BBY",
10 | "gender": "male",
11 | "homeworld": "https://swapi.co/api/planets/1/",
12 | "films": [
13 | "https://swapi.co/api/films/2/",
14 | "https://swapi.co/api/films/6/",
15 | "https://swapi.co/api/films/3/",
16 | "https://swapi.co/api/films/1/",
17 | "https://swapi.co/api/films/7/"
18 | ],
19 | "species": [
20 | "https://swapi.co/api/species/1/"
21 | ],
22 | "vehicles": [
23 | "https://swapi.co/api/vehicles/14/",
24 | "https://swapi.co/api/vehicles/30/"
25 | ],
26 | "starships": [
27 | "https://swapi.co/api/starships/12/",
28 | "https://swapi.co/api/starships/22/"
29 | ],
30 | "created": "2014-12-09T13:50:51.644000Z",
31 | "edited": "2014-12-20T21:17:56.891000Z",
32 | "url": "https://swapi.co/api/people/1/"
33 | },
34 | {
35 | "name": "C-3PO",
36 | "height": "167",
37 | "mass": "75",
38 | "hair_color": "n/a",
39 | "skin_color": "gold",
40 | "eye_color": "yellow",
41 | "birth_year": "112BBY",
42 | "gender": "n/a",
43 | "homeworld": "https://swapi.co/api/planets/1/",
44 | "films": [
45 | "https://swapi.co/api/films/2/",
46 | "https://swapi.co/api/films/5/",
47 | "https://swapi.co/api/films/4/",
48 | "https://swapi.co/api/films/6/",
49 | "https://swapi.co/api/films/3/",
50 | "https://swapi.co/api/films/1/"
51 | ],
52 | "species": [
53 | "https://swapi.co/api/species/2/"
54 | ],
55 | "vehicles": [],
56 | "starships": [],
57 | "created": "2014-12-10T15:10:51.357000Z",
58 | "edited": "2014-12-20T21:17:50.309000Z",
59 | "url": "https://swapi.co/api/people/2/"
60 | },
61 | {
62 | "name": "R2-D2",
63 | "height": "96",
64 | "mass": "32",
65 | "hair_color": "n/a",
66 | "skin_color": "white, blue",
67 | "eye_color": "red",
68 | "birth_year": "33BBY",
69 | "gender": "n/a",
70 | "homeworld": "https://swapi.co/api/planets/8/",
71 | "films": [
72 | "https://swapi.co/api/films/2/",
73 | "https://swapi.co/api/films/5/",
74 | "https://swapi.co/api/films/4/",
75 | "https://swapi.co/api/films/6/",
76 | "https://swapi.co/api/films/3/",
77 | "https://swapi.co/api/films/1/",
78 | "https://swapi.co/api/films/7/"
79 | ],
80 | "species": [
81 | "https://swapi.co/api/species/2/"
82 | ],
83 | "vehicles": [],
84 | "starships": [],
85 | "created": "2014-12-10T15:11:50.376000Z",
86 | "edited": "2014-12-20T21:17:50.311000Z",
87 | "url": "https://swapi.co/api/people/3/"
88 | },
89 | {
90 | "name": "Darth Vader",
91 | "height": "202",
92 | "mass": "136",
93 | "hair_color": "none",
94 | "skin_color": "white",
95 | "eye_color": "yellow",
96 | "birth_year": "41.9BBY",
97 | "gender": "male",
98 | "homeworld": "https://swapi.co/api/planets/1/",
99 | "films": [
100 | "https://swapi.co/api/films/2/",
101 | "https://swapi.co/api/films/6/",
102 | "https://swapi.co/api/films/3/",
103 | "https://swapi.co/api/films/1/"
104 | ],
105 | "species": [
106 | "https://swapi.co/api/species/1/"
107 | ],
108 | "vehicles": [],
109 | "starships": [
110 | "https://swapi.co/api/starships/13/"
111 | ],
112 | "created": "2014-12-10T15:18:20.704000Z",
113 | "edited": "2014-12-20T21:17:50.313000Z",
114 | "url": "https://swapi.co/api/people/4/"
115 | },
116 | {
117 | "name": "Leia Organa",
118 | "height": "150",
119 | "mass": "49",
120 | "hair_color": "brown",
121 | "skin_color": "light",
122 | "eye_color": "brown",
123 | "birth_year": "19BBY",
124 | "gender": "female",
125 | "homeworld": "https://swapi.co/api/planets/2/",
126 | "films": [
127 | "https://swapi.co/api/films/2/",
128 | "https://swapi.co/api/films/6/",
129 | "https://swapi.co/api/films/3/",
130 | "https://swapi.co/api/films/1/",
131 | "https://swapi.co/api/films/7/"
132 | ],
133 | "species": [
134 | "https://swapi.co/api/species/1/"
135 | ],
136 | "vehicles": [
137 | "https://swapi.co/api/vehicles/30/"
138 | ],
139 | "starships": [],
140 | "created": "2014-12-10T15:20:09.791000Z",
141 | "edited": "2014-12-20T21:17:50.315000Z",
142 | "url": "https://swapi.co/api/people/5/"
143 | },
144 | {
145 | "name": "Owen Lars",
146 | "height": "178",
147 | "mass": "120",
148 | "hair_color": "brown, grey",
149 | "skin_color": "light",
150 | "eye_color": "blue",
151 | "birth_year": "52BBY",
152 | "gender": "male",
153 | "homeworld": "https://swapi.co/api/planets/1/",
154 | "films": [
155 | "https://swapi.co/api/films/5/",
156 | "https://swapi.co/api/films/6/",
157 | "https://swapi.co/api/films/1/"
158 | ],
159 | "species": [
160 | "https://swapi.co/api/species/1/"
161 | ],
162 | "vehicles": [],
163 | "starships": [],
164 | "created": "2014-12-10T15:52:14.024000Z",
165 | "edited": "2014-12-20T21:17:50.317000Z",
166 | "url": "https://swapi.co/api/people/6/"
167 | },
168 | {
169 | "name": "Beru Whitesun lars",
170 | "height": "165",
171 | "mass": "75",
172 | "hair_color": "brown",
173 | "skin_color": "light",
174 | "eye_color": "blue",
175 | "birth_year": "47BBY",
176 | "gender": "female",
177 | "homeworld": "https://swapi.co/api/planets/1/",
178 | "films": [
179 | "https://swapi.co/api/films/5/",
180 | "https://swapi.co/api/films/6/",
181 | "https://swapi.co/api/films/1/"
182 | ],
183 | "species": [
184 | "https://swapi.co/api/species/1/"
185 | ],
186 | "vehicles": [],
187 | "starships": [],
188 | "created": "2014-12-10T15:53:41.121000Z",
189 | "edited": "2014-12-20T21:17:50.319000Z",
190 | "url": "https://swapi.co/api/people/7/"
191 | },
192 | {
193 | "name": "R5-D4",
194 | "height": "97",
195 | "mass": "32",
196 | "hair_color": "n/a",
197 | "skin_color": "white, red",
198 | "eye_color": "red",
199 | "birth_year": "unknown",
200 | "gender": "n/a",
201 | "homeworld": "https://swapi.co/api/planets/1/",
202 | "films": [
203 | "https://swapi.co/api/films/1/"
204 | ],
205 | "species": [
206 | "https://swapi.co/api/species/2/"
207 | ],
208 | "vehicles": [],
209 | "starships": [],
210 | "created": "2014-12-10T15:57:50.959000Z",
211 | "edited": "2014-12-20T21:17:50.321000Z",
212 | "url": "https://swapi.co/api/people/8/"
213 | },
214 | {
215 | "name": "Obi-Wan Kenobi",
216 | "height": "182",
217 | "mass": "77",
218 | "hair_color": "auburn, white",
219 | "skin_color": "fair",
220 | "eye_color": "blue-gray",
221 | "birth_year": "57BBY",
222 | "gender": "male",
223 | "homeworld": "https://swapi.co/api/planets/20/",
224 | "films": [
225 | "https://swapi.co/api/films/2/",
226 | "https://swapi.co/api/films/5/",
227 | "https://swapi.co/api/films/4/",
228 | "https://swapi.co/api/films/6/",
229 | "https://swapi.co/api/films/3/",
230 | "https://swapi.co/api/films/1/"
231 | ],
232 | "species": [
233 | "https://swapi.co/api/species/1/"
234 | ],
235 | "vehicles": [
236 | "https://swapi.co/api/vehicles/38/"
237 | ],
238 | "starships": [
239 | "https://swapi.co/api/starships/48/",
240 | "https://swapi.co/api/starships/59/",
241 | "https://swapi.co/api/starships/64/",
242 | "https://swapi.co/api/starships/65/",
243 | "https://swapi.co/api/starships/74/"
244 | ],
245 | "created": "2014-12-10T16:16:29.192000Z",
246 | "edited": "2014-12-20T21:17:50.325000Z",
247 | "url": "https://swapi.co/api/people/10/"
248 | }
249 | ]
250 |
--------------------------------------------------------------------------------
/2-network-policies/web-console/deployment.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | name: web-console
5 | namespace: default
6 | labels:
7 | app: web-console
8 | spec:
9 | replicas: 1
10 | strategy:
11 | type: Recreate
12 | selector:
13 | matchLabels:
14 | app: web-console
15 | template:
16 | metadata:
17 | labels:
18 | app: web-console
19 | spec:
20 | serviceAccountName: web-console
21 | containers:
22 | - name: web-console
23 | image: schnatterer/web-console:v0.9.7-1
24 | ports:
25 | - containerPort: 80
26 | resources:
27 | limits:
28 | cpu: 250m
29 | memory: 512Mi
30 | requests:
31 | cpu: 100m
32 | memory: 64Mi
33 | readinessProbe:
34 | httpGet:
35 | path: /
36 | port: 80
37 | livenessProbe:
38 | httpGet:
39 | path: /
40 | port: 80
41 | initialDelaySeconds: 15
42 | env:
43 | - name: USER
44 | valueFrom:
45 | secretKeyRef:
46 | name: web-console
47 | key: USERNAME
48 | - name: PASSWORD
49 | valueFrom:
50 | secretKeyRef:
51 | name: web-console
52 | key: PASSWORD
--------------------------------------------------------------------------------
/2-network-policies/web-console/ingress.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: extensions/v1beta1
2 | kind: Ingress
3 | metadata:
4 | name: web-console
5 | namespace: default
6 | annotations:
7 | kubernetes.io/ingress.class: traefik
8 | spec:
9 | rules:
10 | - host: web-console
11 | http:
12 | paths:
13 | - path: /
14 | backend:
15 | serviceName: web-console
16 | servicePort: 80
17 |
--------------------------------------------------------------------------------
/2-network-policies/web-console/secrets.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Secret
3 | metadata:
4 | name: web-console
5 | namespace: default
6 | data:
7 | PASSWORD: MTIzNDU=
8 | USERNAME: YWRtaW4=
9 | type: Opaque
10 |
--------------------------------------------------------------------------------
/2-network-policies/web-console/service-account.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: ServiceAccount
3 | metadata:
4 | name: web-console
5 | namespace: default
--------------------------------------------------------------------------------
/2-network-policies/web-console/service.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: Service
3 | metadata:
4 | name: web-console
5 | namespace: default
6 | labels:
7 | app: web-console
8 | spec:
9 | ports:
10 | - port: 80
11 | targetPort: 80
12 | selector:
13 | app: web-console
14 |
--------------------------------------------------------------------------------
/3-security-context/Readme.md:
--------------------------------------------------------------------------------
1 | # Security Context Demo
2 |
3 | 
4 |
5 | `apply.sh` deploys the applications required for the demos.
6 |
7 | Then, you can can start the interactive demo:
8 |
9 | ```bash
10 | cd demo
11 | ./interactive-demo.sh
12 | ```
13 |
14 | Note if you got [bat](https://github.com/sharkdp/bat) on your `PATH`, the output will prettier.
15 |
16 | Alternatively, you could print a transcript of the demo for doing the demo manually
17 |
18 | ```bash
19 | cd demo
20 | PRINT_ONLY=true ./interactive-demo.sh
21 | ```
--------------------------------------------------------------------------------
/3-security-context/apply.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 |
4 | BASEDIR=$(dirname $0)
5 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
6 |
7 | source ${ABSOLUTE_BASEDIR}/../config.sh
8 | source ${ABSOLUTE_BASEDIR}/../cluster-utils.sh
9 | source ${ABSOLUTE_BASEDIR}/../interactive-utils.sh
10 |
11 | function main() {
12 |
13 | confirm "Preparing demo in kubernetes cluster '$(kubectl config current-context)'." 'Continue? y/n [n]' \
14 | || exit 0
15 |
16 | # Make sure we're in a namespace that does not have any netpols
17 | kubectlIdempotent create namespace sec-ctx
18 | kubectl config set-context $(kubectl config current-context) --namespace=sec-ctx
19 |
20 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/02-deployment-run-as-non-root-unprivileged.yaml
21 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/03-deployment-run-as-user-unprivileged.yaml
22 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/05-deployment-allow-no-privilege-escalation.yaml
23 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/06-deployment-seccomp.yaml
24 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/07-deployment-run-without-caps.yaml
25 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/08-deployment-run-with-certain-caps.yaml
26 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/09-deployment-run-without-caps-unprivileged.yaml
27 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/10-deployment-read-only-fs.yaml
28 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/11-deployment-nginx-read-only-fs.yaml
29 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/12-deployment-nginx-read-only-fs-empty-dirs.yaml
30 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/13-deployment-all-at-once.yaml
31 | }
32 |
33 | main "$@"
34 |
--------------------------------------------------------------------------------
/3-security-context/demo/01-deployment-run-as-non-root.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-as-non-root
6 | name: run-as-non-root
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-as-non-root
11 | template:
12 | metadata:
13 | labels:
14 | run: run-as-non-root
15 | spec:
16 | containers:
17 | - image: nginx:1.19.3
18 | name: run-as-non-root
19 | securityContext:
20 | runAsNonRoot: true
--------------------------------------------------------------------------------
/3-security-context/demo/02-deployment-run-as-non-root-unprivileged.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-as-non-root-unprivileged
6 | name: run-as-non-root-unprivileged
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-as-non-root-unprivileged
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: run-as-non-root-unprivileged
17 | spec:
18 | containers:
19 | - image: nginxinc/nginx-unprivileged:1.19.3
20 | name: run-as-non-root-unprivileged
21 | securityContext:
22 | runAsNonRoot: true
--------------------------------------------------------------------------------
/3-security-context/demo/03-deployment-run-as-user-unprivileged.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-as-user-unprivileged
6 | name: run-as-user-unprivileged
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-as-user-unprivileged
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: run-as-user-unprivileged
17 | spec:
18 | containers:
19 | - image: nginxinc/nginx-unprivileged:1.19.3
20 | name: run-as-user-unprivileged
21 | securityContext:
22 | runAsUser: 100000
23 | runAsGroup: 100000
--------------------------------------------------------------------------------
/3-security-context/demo/04-deployment-run-as-user.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-as-user
6 | name: run-as-user
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-as-user
11 | template:
12 | metadata:
13 | labels:
14 | run: run-as-user
15 | spec:
16 | containers:
17 | - image: nginx:1.19.3
18 | name: run-as-user
19 | securityContext:
20 | runAsUser: 100000
21 | runAsGroup: 100000
--------------------------------------------------------------------------------
/3-security-context/demo/05-deployment-allow-no-privilege-escalation.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: allow-no-privilege-escalation
6 | name: allow-no-privilege-escalation
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: allow-no-privilege-escalation
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: allow-no-privilege-escalation
17 | spec:
18 | containers:
19 | - image: schnatterer/docker-sudo:0.1
20 | name: allow-no-privilege-escalation
21 | securityContext:
22 | allowPrivilegeEscalation: false
23 |
--------------------------------------------------------------------------------
/3-security-context/demo/06-deployment-seccomp.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-with-seccomp
6 | name: run-with-seccomp
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-with-seccomp
11 | template:
12 | metadata:
13 | labels:
14 | run: run-with-seccomp
15 | annotations:
16 | seccomp.security.alpha.kubernetes.io/pod: runtime/default
17 | spec:
18 | containers:
19 | - image: nginx:1.19.3
20 | name: run-with-seccomp
--------------------------------------------------------------------------------
/3-security-context/demo/07-deployment-run-without-caps.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-without-caps
6 | name: run-without-caps
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-without-caps
11 | template:
12 | metadata:
13 | labels:
14 | run: run-without-caps
15 | spec:
16 | containers:
17 | - image: nginx:1.19.3
18 | name: run-without-caps
19 | securityContext:
20 | capabilities:
21 | drop:
22 | - ALL
--------------------------------------------------------------------------------
/3-security-context/demo/08-deployment-run-with-certain-caps.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-with-certain-caps
6 | name: run-with-certain-caps
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-with-certain-caps
11 | template:
12 | metadata:
13 | labels:
14 | run: run-with-certain-caps
15 | spec:
16 | containers:
17 | - image: nginx:1.19.3
18 | name: run-with-certain-caps
19 | securityContext:
20 | capabilities:
21 | drop:
22 | - ALL
23 | add:
24 | - CHOWN
25 | - NET_BIND_SERVICE
26 | - SETGID
27 | - SETUID
--------------------------------------------------------------------------------
/3-security-context/demo/09-deployment-run-without-caps-unprivileged.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: run-without-caps-unprivileged
6 | name: run-without-caps-unprivileged
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: run-without-caps-unprivileged
11 | template:
12 | metadata:
13 | labels:
14 | run: run-without-caps-unprivileged
15 | spec:
16 | containers:
17 | - image: nginxinc/nginx-unprivileged:1.19.3
18 | name: run-without-caps-unprivileged
19 | securityContext:
20 | capabilities:
21 | drop:
22 | - ALL
--------------------------------------------------------------------------------
/3-security-context/demo/10-deployment-read-only-fs.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: read-only-fs
6 | name: read-only-fs
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: read-only-fs
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: read-only-fs
17 | spec:
18 | containers:
19 | - image: schnatterer/docker-sudo:0.1
20 | name: read-only-fs
21 | securityContext:
22 | readOnlyRootFilesystem: true
23 |
24 |
--------------------------------------------------------------------------------
/3-security-context/demo/10a-netpol-egress-docker-sudo-allow-internal-only.yaml:
--------------------------------------------------------------------------------
1 | kind: NetworkPolicy
2 | apiVersion: networking.k8s.io/v1
3 | metadata:
4 | name: egress-nginx-allow-internal-only
5 | spec:
6 | policyTypes:
7 | - Egress
8 | podSelector:
9 | matchLabels:
10 | app: docker-sudo
11 | egress:
12 | - to:
13 | - namespaceSelector: {}
--------------------------------------------------------------------------------
/3-security-context/demo/11-deployment-nginx-read-only-fs.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: failing-nginx-read-only-fs
6 | name: failing-nginx-read-only-fs
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: failing-nginx-read-only-fs
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: failing-nginx-read-only-fs
17 | spec:
18 | containers:
19 | - image: nginx:1.19.3
20 | name: failing-nginx-read-only-fs
21 | securityContext:
22 | readOnlyRootFilesystem: true
23 |
--------------------------------------------------------------------------------
/3-security-context/demo/12-deployment-nginx-read-only-fs-empty-dirs.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: empty-dirs-nginx-read-only-fs
6 | name: empty-dirs-nginx-read-only-fs
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: empty-dirs-nginx-read-only-fs
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: empty-dirs-nginx-read-only-fs
17 | spec:
18 | containers:
19 | - image: nginx:1.19.3
20 | name: empty-dirs-nginx-read-only-fs
21 | securityContext:
22 | readOnlyRootFilesystem: true
23 | volumeMounts:
24 | - name: cache
25 | mountPath: /var/cache/nginx
26 | - name: run
27 | mountPath: /run
28 | volumes:
29 | - name: cache
30 | emptyDir: {}
31 | - name: run
32 | emptyDir: {}
--------------------------------------------------------------------------------
/3-security-context/demo/13-deployment-all-at-once.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: all-at-once
6 | name: all-at-once
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: all-at-once
11 | strategy:
12 | type: Recreate
13 | template:
14 | metadata:
15 | labels:
16 | run: all-at-once
17 | annotations:
18 | seccomp.security.alpha.kubernetes.io/pod: runtime/default
19 | spec:
20 | automountServiceAccountToken: false
21 | enableServiceLinks: false
22 | containers:
23 | # Another suitable example springcommunity/spring-framework-petclinic:5.1.5
24 | - image: nginxinc/nginx-unprivileged:1.19.3
25 | name: all-at-once
26 | securityContext:
27 | readOnlyRootFilesystem: true
28 | allowPrivilegeEscalation: false
29 | runAsNonRoot: true
30 | runAsUser: 100000
31 | runAsGroup: 100000
32 | capabilities:
33 | drop:
34 | - ALL
35 | volumeMounts:
36 | - name: tmp
37 | mountPath: /tmp
38 | volumes:
39 | - name: tmp
40 | emptyDir: {}
--------------------------------------------------------------------------------
/3-security-context/demo/interactive-demo.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 | BASEDIR=$(dirname $0)
4 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
5 |
6 | PRINT_ONLY=${PRINT_ONLY:-false}
7 |
8 | source ${ABSOLUTE_BASEDIR}/../../interactive-utils.sh
9 |
10 | function main() {
11 |
12 | confirm "Preparing demo in kubernetes cluster '$(kubectl config current-context)'." 'Continue? y/n [n]' \
13 | || exit 0
14 |
15 | setup
16 | reset
17 | run "clear"
18 |
19 | runAsRoot
20 |
21 | runAsUser
22 |
23 | allowPrivilegeEscalation
24 |
25 | enableServiceLinks
26 |
27 | activateSeccompProfile
28 |
29 | dropCapabilities
30 |
31 | readOnlyRootFilesystem
32 |
33 | allAtOnce
34 |
35 | echo
36 | message "This concludes the demo, thanks for securing your clusters!"
37 | }
38 |
39 | function setup() {
40 |
41 | run "echo Setting up environment for interactive demo 'security context'"
42 |
43 | source ${ABSOLUTE_BASEDIR}/../../config.sh
44 |
45 | run "echo -n ."
46 |
47 | run "kubectl config set-context \$(kubectl config current-context) --namespace=sec-ctx > /dev/null"
48 | run "echo -n ."
49 | }
50 |
51 | function runAsRoot() {
52 | heading "1. Run as root"
53 |
54 | subHeading "1.1 Pod runs as root"
55 | printAndRun "kubectl create deployment nginx --image nginx:1.19.3"
56 | printAndRun "kubectl exec \$(kubectl get pods | awk '/nginx/ {print \$1;exit}') -- id"
57 |
58 | subHeading "1.2 Same with \"runAsNonRoot: true\""
59 | printFile ${ABSOLUTE_BASEDIR}/01-deployment-run-as-non-root.yaml
60 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 01-deployment-run-as-non-root.yaml")
61 | run "sleep 3"
62 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/^run-as-non-root/ {print \$1;exit}')"
63 | pressKeyToContinue
64 | echo
65 | printAndRun "kubectl describe pod \$(kubectl get pods | awk '/^run-as-non-root/ {print \$1;exit}') | grep Error"
66 |
67 | subHeading "1.3 Image that runs as nginx as non-root ➡️ runs as uid != 0"
68 | printFile ${ABSOLUTE_BASEDIR}/02-deployment-run-as-non-root-unprivileged.yaml
69 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/^run-as-non-root-unprivileged/ {print \$1;exit}')"
70 | pressKeyToContinue
71 | printAndRun "kubectl exec \$(kubectl get pods | awk '/run-as-non-root-unprivileged/ {print \$1;exit}') -- id"
72 |
73 | pressKeyToContinue
74 | }
75 |
76 | function runAsUser() {
77 | heading "2. Run as user/group"
78 |
79 | subHeading "2.1 Runnginx as uid/gid 100000"
80 | printFile ${ABSOLUTE_BASEDIR}/03-deployment-run-as-user-unprivileged.yaml
81 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/run-as-user-unprivileged/ {print \$1;exit}')"
82 | printAndRun "kubectl exec \$(kubectl get pods | awk '/run-as-user-unprivileged/ {print \$1;exit}') -- id"
83 |
84 | subHeading "2.2 Image must be designed to work with \"runAsUser\" and \"runAsGroup\""
85 | printFile ${ABSOLUTE_BASEDIR}/04-deployment-run-as-user.yaml
86 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 04-deployment-run-as-user.yaml")
87 | run "sleep 3"
88 |
89 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/^run-as-user/ {print \$1;exit}')"
90 | echo
91 | printAndRun "kubectl logs \$(kubectl get pods | awk '/^run-as-user/ {print \$1;exit}')"
92 |
93 | pressKeyToContinue
94 | }
95 |
96 | function allowPrivilegeEscalation() {
97 |
98 | heading "3. allowPrivilegeEscalation"
99 |
100 | subHeading "3.1 Escalate privileges"
101 | printAndRun "kubectl create deployment docker-sudo --image schnatterer/docker-sudo:0.1"
102 | run "kubectl rollout status deployment docker-sudo > /dev/null"
103 | printAndRun "kubectl exec \$(kubectl get pods | awk '/docker-sudo/ {print \$1;exit}') -- id"
104 | pressKeyToContinue
105 |
106 | printAndRun "kubectl exec \$(kubectl get pods | awk '/docker-sudo/ {print \$1;exit}') -- sudo id"
107 |
108 | subHeading "3.2 Same with \"allowPrivilegeEscalation: true\" ➡️ escalation fails"
109 | printFile ${ABSOLUTE_BASEDIR}/05-deployment-allow-no-privilege-escalation.yaml
110 | printAndRun "kubectl exec \$(kubectl get pods | awk '/allow-no-privilege-escalation/ {print \$1;exit}') -- sudo id"
111 |
112 | pressKeyToContinue
113 | }
114 |
115 | function enableServiceLinks() {
116 |
117 | heading "4. enableServiceLinks"
118 |
119 | subHeading "4.1 Show service links"
120 | printAndRun "kubectl create service clusterip my-service --tcp=80:8080 || true"
121 | printAndRun "kubectl run tmp-env --image busybox:1.31.1-musl --command sleep 100000"
122 | pressKeyToContinue
123 | printAndRun "kubectl exec tmp-env -- env | sort"
124 |
125 | subHeading "4.2 Disable service links"
126 | printAndRun "kubectl run tmp-env2 --image busybox:1.31.1-musl --overrides='{\"spec\": {\"enableServiceLinks\": false}}' --command sleep 100000"
127 | pressKeyToContinue
128 | printAndRun "kubectl exec tmp-env2 -- env"
129 | pressKeyToContinue
130 | }
131 |
132 | function activateSeccompProfile() {
133 |
134 | heading "5. Enable Seccomp default profile"
135 |
136 | subHeading "5.1 No seccomp profile by default 😲"
137 | kubectlSilent create deployment nginx --image nginx:1.19.3
138 | printAndRun "kubectl exec \$(kubectl get pods | awk '/nginx/ {print \$1;exit}') -- grep Seccomp /proc/1/status"
139 |
140 | subHeading "5.2 Same with default seccomp profile"
141 | printFile ${ABSOLUTE_BASEDIR}/06-deployment-seccomp.yaml
142 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/run-with-seccomp/ {print \$1;exit}')"
143 | printAndRun "kubectl exec \$(kubectl get pods | awk '/run-with-seccomp/ {print \$1;exit}') -- grep Seccomp /proc/1/status"
144 |
145 | pressKeyToContinue
146 | }
147 |
148 | function dropCapabilities() {
149 |
150 | heading "6. Drop Capabilities"
151 |
152 | subHeading "6.1 some images require capabilities"
153 | printFile ${ABSOLUTE_BASEDIR}/07-deployment-run-without-caps.yaml
154 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/^run-without-caps/ {print \$1;exit}')"
155 | echo
156 | printAndRun "kubectl logs \$(kubectl get pods | awk '/^run-without-caps/ {print \$1;exit}') "
157 |
158 | message "How to find out which capabilities we need to add? Reproduce locally."
159 | printAndRun "docker run --rm --cap-drop ALL nginx:1.19.3"
160 | pressKeyToContinue
161 | message "Add first capability: CAP_CHOWN.\nNote: Stop running container with Ctrl + C to continue."
162 | printAndRun "docker run --rm --cap-drop ALL --cap-add CAP_CHOWN nginx:1.19.3"
163 | #printAndRun "docker run --rm --cap-drop ALL --cap-add CAP_CHOWN --cap-add CAP_NET_BIND_SERVICE nginx:1.19.3"
164 | #printAndRun "docker run --rm --cap-drop ALL --cap-add CAP_CHOWN --cap-add CAP_NET_BIND_SERVICE --cap-add SETGID nginx:1.19.3"
165 | #printAndRun "docker run --rm --cap-drop ALL --cap-add CAP_CHOWN --cap-add CAP_NET_BIND_SERVICE --cap-add SETGID --cap-add SETUID nginx:1.19.3"
166 |
167 | message "Continue adding capabilities until the container runs.\nFinally add the necessary caps to kubernetes"
168 | printFile ${ABSOLUTE_BASEDIR}/08-deployment-run-with-certain-caps.yaml
169 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/run-with-certain-caps/ {print \$1;exit}')"
170 |
171 | subHeading "6.2 Image that runs without caps"
172 | printFile ${ABSOLUTE_BASEDIR}/09-deployment-run-without-caps-unprivileged.yaml
173 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/run-without-caps-unprivileged/ {print \$1;exit}')"
174 |
175 | pressKeyToContinue
176 | }
177 |
178 | function readOnlyRootFilesystem() {
179 |
180 | heading "7. readOnlyRootFilesystem"
181 | kubectlSilent create deployment docker-sudo --image schnatterer/docker-sudo:0.1
182 |
183 | subHeading "7.1 Write to container's file system"
184 | printAndRun "kubectl exec \$(kubectl get pods | awk '/docker-sudo/ {print \$1;exit}') -- sudo apt update"
185 |
186 |
187 | subHeading "7.2 Same with \"readOnlyRootFilesystem: true\" ➡️ fails to write to temp dirs"
188 | printFile ${ABSOLUTE_BASEDIR}/10-deployment-read-only-fs.yaml
189 | printAndRun "kubectl exec \$(kubectl get pods | awk '/^read-only-fs/ {print \$1;exit}') -- sudo apt update"
190 |
191 |
192 | subHeading "( 7.2a By the way - this could also be done with a networkPolicy )"
193 | confirm "Want to see? y/n [n]" \
194 | && (
195 | printFile ${ABSOLUTE_BASEDIR}/10a-netpol-egress-docker-sudo-allow-internal-only.yaml
196 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 10a-netpol-egress-docker-sudo-allow-internal-only.yaml")
197 | printAndRun "timeout 10s kubectl exec \$(kubectl get pods | awk '/docker-sudo/ {print \$1;exit}') -- sudo apt update"
198 | )
199 |
200 | subHeading "7.3 readOnlyRootFilesystem causes issues with other images"
201 | printFile ${ABSOLUTE_BASEDIR}/11-deployment-nginx-read-only-fs.yaml
202 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/failing-nginx-read-only-fs/ {print \$1;exit}')"
203 | message "Not running. Let's check the logs"
204 | printAndRun "kubectl logs \$(kubectl get pods | awk '/failing-nginx-read-only-fs/ {print \$1;exit}')"
205 |
206 | message "How to find out which folders we need to mount?"
207 | printAndRun "nginxContainer=\$(docker run -d --rm nginx:1.19.3)"
208 | run "sleep 1"
209 | printAndRun "docker diff \${nginxContainer}"
210 | run "docker rm -f \${nginxContainer} > /dev/null"
211 |
212 | message "Mount those dirs as as emptyDir!"
213 | printFile ${ABSOLUTE_BASEDIR}/12-deployment-nginx-read-only-fs-empty-dirs.yaml
214 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/empty-dirs-nginx-read-only-fs/ {print \$1;exit}')"
215 |
216 | pressKeyToContinue
217 | }
218 |
219 | function allAtOnce() {
220 | heading "8. An example that implements all good practices at once"
221 | pressKeyToContinue
222 |
223 | printFile ${ABSOLUTE_BASEDIR}/13-deployment-all-at-once.yaml
224 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/all-at-once/ {print \$1;exit}')"
225 | pressKeyToContinue
226 | printAndRun "kubectl port-forward \$(kubectl get pods | awk '/all-at-once/ {print \$1;exit}') 8080 > /dev/null& "
227 | run "wget -O- --retry-connrefused --tries=30 -q --wait=1 localhost:8080 > /dev/null"
228 | pressKeyToContinue
229 | printAndRun "curl localhost:8080"
230 | run "jobs > /dev/null && kill %1"
231 |
232 | pressKeyToContinue
233 | }
234 |
235 | function reset() {
236 | # Reset the changes done by this demo
237 | kubectlSilent delete deploy nginx
238 | run "echo -n ."
239 | kubectlSilent delete -f ${ABSOLUTE_BASEDIR}/01-deployment-run-as-non-root.yaml
240 | run "echo -n ."
241 | kubectlSilent delete -f ${ABSOLUTE_BASEDIR}/04-deployment-run-as-user.yaml
242 | run "echo -n ."
243 | kubectlSilent delete deploy docker-sudo
244 | run "echo -n ."
245 | kubectlSilent delete netpol egress-nginx-allow-internal-only
246 | run "echo -n ."
247 | kubectlSilent delete po tmp-env --grace-period=0 --force
248 | run "echo -n ."
249 | kubectlSilent delete po tmp-env2 --grace-period=0 --force
250 | run "echo -n ."
251 | kubectlSilent delete svc my-service
252 | }
253 |
254 | main "$@"
255 |
--------------------------------------------------------------------------------
/4-pod-security-policies/Readme.md:
--------------------------------------------------------------------------------
1 | # Pod Security Policy Demo
2 |
3 | 
4 |
5 | `apply.sh` deploys the applications required for the demos.
6 |
7 | Then, you can can start the interactive demo:
8 |
9 | ```bash
10 | cd demo
11 | ./interactive-demo.sh
12 | ```
13 |
14 | Note if you got [bat](https://github.com/sharkdp/bat) on your `PATH`, the output will prettier.
15 |
16 | Alternatively, you could print a transcript of the demo for doing the demo manually
17 |
18 | ```bash
19 | cd demo
20 | PRINT_ONLY=true ./interactive-demo.sh
21 | ```
--------------------------------------------------------------------------------
/4-pod-security-policies/apply.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 |
4 | BASEDIR=$(dirname $0)
5 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
6 |
7 | source ${ABSOLUTE_BASEDIR}/../config.sh
8 | source ${ABSOLUTE_BASEDIR}/../cluster-utils.sh
9 | source ${ABSOLUTE_BASEDIR}/../interactive-utils.sh
10 |
11 | function main() {
12 |
13 | confirm "Preparing demo in kubernetes cluster '$(kubectl config current-context)'." 'Continue? y/n [n]' \
14 | || exit 0
15 |
16 | # Start with a privileged PSP. Makes sure deployments are allowed to create pods
17 | # Note that this requires the applying user to be cluster admin
18 | kubectl apply -f ${ABSOLUTE_BASEDIR}/demo/psp-privileged.yaml
19 |
20 | # Start in an empty namespace for a smoother intro to the demo
21 | kubectlIdempotent create namespace psp
22 |
23 | kubectl config set-context $(kubectl config current-context) --namespace=psp
24 | }
25 |
26 | main "$@"
27 |
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/01-psp-restrictive.yaml:
--------------------------------------------------------------------------------
1 | # See also https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies
2 | apiVersion: policy/v1beta1
3 | kind: PodSecurityPolicy
4 | metadata:
5 | name: restricted
6 | annotations:
7 | seccomp.security.alpha.kubernetes.io/defaultProfileName: runtime/default
8 | # Not setting this will result in blocking pods that have this profile set explicitly
9 | seccomp.security.alpha.kubernetes.io/allowedProfileNames: runtime/default
10 |
11 | apparmor.security.beta.kubernetes.io/defaultProfileName: runtime/default
12 | apparmor.security.beta.kubernetes.io/allowedProfileNames: runtime/default
13 | spec:
14 | allowedHostPaths: []
15 | hostIPC: false
16 | hostNetwork: false
17 | hostPID: false
18 | hostPorts: []
19 |
20 | requiredDropCapabilities:
21 | - ALL
22 | allowedCapabilities: []
23 |
24 | privileged: false
25 | defaultAllowPrivilegeEscalation: false
26 | allowPrivilegeEscalation: false
27 | # Allow core volume types. But more specifically, don't allow mounting host volumes to include the Docker socket - '/var/run/docker.sock'
28 | # https://kurtmadel.com/posts/native-kubernetes-continuous-delivery/building-container-images-with-kubernetes/
29 | # Without the "volumes" block configmaps, secrets, etc. are not allowed to be used
30 | volumes:
31 | - configMap
32 | - emptyDir
33 | - projected
34 | - secret
35 | - downwardAPI
36 | - persistentVolumeClaim
37 | runAsUser:
38 | rule: MustRunAs
39 | ranges:
40 | - min: 100000
41 | max: 999999
42 | runAsGroup:
43 | rule: MustRunAs
44 | ranges:
45 | - min: 100000
46 | max: 999999
47 | supplementalGroups:
48 | rule: MustRunAs
49 | ranges:
50 | - min: 100000
51 | max: 999999
52 | fsGroup:
53 | rule: MustRunAs
54 | ranges:
55 | - min: 100000
56 | max: 999999
57 | readOnlyRootFilesystem: true
58 |
59 | # Default that must be set
60 | seLinux:
61 | rule: RunAsAny
62 | ---
63 | apiVersion: rbac.authorization.k8s.io/v1
64 | kind: ClusterRole
65 | metadata:
66 | name: podsecuritypolicy:restricted
67 | rules:
68 | - apiGroups:
69 | - extensions
70 | resourceNames:
71 | - restricted
72 | resources:
73 | - podsecuritypolicies
74 | verbs:
75 | - use
76 | ---
77 | # Allows all serviceAccounts to use this restricted PSP.
78 | # If a pod should need more privileges, this could be granted via a PSP, SA, Role and RoleBinding within its namespace.
79 | apiVersion: rbac.authorization.k8s.io/v1
80 | kind: ClusterRoleBinding
81 | metadata:
82 | name: podsecuritypolicy:all-serviceaccounts
83 | roleRef:
84 | apiGroup: rbac.authorization.k8s.io
85 | kind: ClusterRole
86 | name: podsecuritypolicy:restricted
87 | subjects:
88 | - apiGroup: rbac.authorization.k8s.io
89 | kind: Group
90 | name: system:serviceaccounts
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/01b-nginx-unprivileged.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: apps/v1
2 | kind: Deployment
3 | metadata:
4 | labels:
5 | run: nginx-unprivileged
6 | name: nginx-unprivileged
7 | spec:
8 | selector:
9 | matchLabels:
10 | run: nginx-unprivileged
11 | template:
12 | metadata:
13 | labels:
14 | run: nginx-unprivileged
15 | spec:
16 | automountServiceAccountToken: false
17 | enableServiceLinks: false
18 | containers:
19 | - image: nginxinc/nginx-unprivileged:1.19.3
20 | name: nginx-unprivileged
21 | volumeMounts:
22 | - name: tmp
23 | mountPath: /tmp
24 | volumes:
25 | - name: tmp
26 | emptyDir: {}
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/02a-psp-whitelist.yaml:
--------------------------------------------------------------------------------
1 | apiVersion: v1
2 | kind: ServiceAccount
3 | metadata:
4 | name: nginx
5 | namespace: psp
6 | ---
7 | apiVersion: rbac.authorization.k8s.io/v1
8 | kind: Role
9 | metadata:
10 | name: podsecuritypolicy:nginx
11 | namespace: psp
12 | rules:
13 | - apiGroups: ['extensions']
14 | resources: ['podsecuritypolicies']
15 | verbs: ['use']
16 | resourceNames:
17 | - privileged
18 | ---
19 | apiVersion: rbac.authorization.k8s.io/v1
20 | kind: RoleBinding
21 | metadata:
22 | name: podsecuritypolicy:nginx
23 | namespace: psp
24 | roleRef:
25 | apiGroup: rbac.authorization.k8s.io
26 | kind: Role
27 | name: podsecuritypolicy:nginx
28 | subjects:
29 | - kind: ServiceAccount
30 | name: nginx
31 | namespace: psp
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/02b-patch-nginx-service-account.yaml:
--------------------------------------------------------------------------------
1 | spec:
2 | template:
3 | spec:
4 | serviceAccountName: nginx
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/interactive-demo.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 | BASEDIR=$(dirname $0)
4 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
5 |
6 | PRINT_ONLY=${PRINT_ONLY:-false}
7 |
8 | source ${ABSOLUTE_BASEDIR}/../../interactive-utils.sh
9 | source ${ABSOLUTE_BASEDIR}/../../cluster-utils.sh
10 |
11 | function main() {
12 |
13 | confirm "Preparing demo in kubernetes cluster '$(kubectl config current-context)'." 'Continue? y/n [n]' \
14 | || exit 0
15 |
16 | setup
17 | reset
18 | run "clear"
19 | privilegedPsp
20 |
21 | RemoveDefaultPsp
22 |
23 | introduceRestrictedPsp
24 |
25 | adhereToRestrictivePsp
26 |
27 | useLessRestrictivePsp
28 |
29 | echo
30 | message "This concludes the demo, thanks for securing your clusters!"
31 | }
32 |
33 | function setup() {
34 |
35 | run "echo Setting up environment for interactive demo 'pod security policy'"
36 |
37 | source ${ABSOLUTE_BASEDIR}/../../config.sh
38 |
39 | run "echo -n ."
40 |
41 | run "kubectl config set-context \$(kubectl config current-context) --namespace=psp > /dev/null"
42 | run "echo -n ."
43 | }
44 |
45 | function privilegedPsp() {
46 | heading "With privileged PSP"
47 |
48 | subHeading "Start a pod (via a deployment)"
49 | printAndRun "kubectl create deployment nginx --image nginx:1.19.3"
50 |
51 | echo
52 | local podName="$(kubectl get pod | awk '/^nginx/ {print $1;exit}')"
53 | waitForPodReady "${podName}" psp
54 | printAndRun "kubectl get pod \$(kubectl get pod | awk '/^nginx/ {print \$1;exit}')"
55 |
56 | subHeading "It uses a privileged predefined PSP"
57 | printAndRun "kubectl get pod \$(kubectl get pod | awk '/^nginx/ {print \$1;exit}') -o jsonpath='{.metadata.annotations.kubernetes\.io/psp}' "
58 | echo
59 | pressKeyToContinue
60 | printFile ${ABSOLUTE_BASEDIR}/psp-privileged.yaml
61 |
62 | pressKeyToContinue
63 | }
64 |
65 | function RemoveDefaultPsp() {
66 | heading "Remove privileged default PSP"
67 |
68 | # Remove privilege PSP as default
69 | subHeading "Delete privileged PSP"
70 | printAndRun "kubectl delete clusterrolebinding podsecuritypolicy:all-serviceaccounts"
71 |
72 | subHeading "'Restart' all pods"
73 | printAndRun "kubectl delete pod --all"
74 |
75 | subHeading "Are there any pods?"
76 | printAndRun "kubectl get pod"
77 |
78 | subHeading "Why are there no pods? Lets check controllers. Here: Deployment ➡️ ReplicaSets"
79 | printAndRun "kubectl get rs"
80 | pressKeyToContinue
81 | printAndRun "kubectl describe rs \$(kubectl get rs | awk '/nginx/ {print \$1;exit}') | grep Error"
82 |
83 | pressKeyToContinue
84 | }
85 |
86 | function introduceRestrictedPsp() {
87 | heading "Introduce restricted PSP"
88 |
89 | subHeading "Apply PSP"
90 | printFile ${ABSOLUTE_BASEDIR}/01-psp-restrictive.yaml
91 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 01-psp-restrictive.yaml")
92 |
93 | # Delete replica sets -> Deployments create new ones which adhere to new PSP
94 | subHeading "'Restart' all pods"
95 | printAndRun "kubectl delete rs --all"
96 |
97 | subHeading "Lets check ReplicaSets"
98 | printAndRun "kubectl get rs"
99 | pressKeyToContinue
100 | subHeading "Lets check Pod"
101 | printAndRun "kubectl get pod \$(kubectl get pod | awk '/^nginx/ {print \$1;exit}')"
102 | pressKeyToContinue
103 | printAndRun "kubectl logs \$(kubectl get pod | awk '/nginx/ {print \$1;exit}') | grep emerg"
104 |
105 | pressKeyToContinue
106 | }
107 |
108 | function adhereToRestrictivePsp() {
109 | heading "Adhere to restricted PSP"
110 |
111 | subHeading "Best Option: Adapt application to adhere to PSP"
112 | printFile ${ABSOLUTE_BASEDIR}/01b-nginx-unprivileged.yaml
113 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 01b-nginx-unprivileged.yaml")
114 |
115 | echo
116 | local podName="$(kubectl get pod | awk '/unprivileged/ {print $1;exit}')"
117 | waitForPodReady "${podName}" psp
118 | printAndRun "kubectl get pod \$(kubectl get pod | awk '/unprivileged/ {print \$1;exit}')"
119 |
120 | pressKeyToContinue
121 | }
122 |
123 | function useLessRestrictivePsp() {
124 | heading "Alternative (less secure): Use less restrictive PSP for certain pod"
125 |
126 | subHeading "'Whitelist' pod to use less restrictive PSP"
127 | printFile ${ABSOLUTE_BASEDIR}/02a-psp-whitelist.yaml
128 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl apply -f 02a-psp-whitelist.yaml")
129 |
130 | subHeading "Use service account for nginx pod"
131 | printFile ${ABSOLUTE_BASEDIR}/02b-patch-nginx-service-account.yaml
132 | (cd ${ABSOLUTE_BASEDIR} && printAndRun "kubectl patch deployment nginx --patch \"\$(cat 02b-patch-nginx-service-account.yaml)\"")
133 |
134 | printAndRun "kubectl delete pod \$(kubectl get pods | awk '/^nginx/ {print \$1;exit}')"
135 |
136 | subHeading "It's running!"
137 | printAndRun "kubectl get pod \$(kubectl get pods | awk '/^nginx/ {print \$1;exit}')"
138 |
139 | pressKeyToContinue
140 | }
141 |
142 | function reset() {
143 | # Reset the changes done by this demo
144 | kubectlSilent delete deploy nginx
145 | run "echo -n ."
146 | kubectlSilent delete deploy nginx-unprivileged
147 | run "echo -n ."
148 | kubectlSilent delete -f ${ABSOLUTE_BASEDIR}/01-psp-restrictive.yaml
149 | run "echo -n ."
150 | kubectlSilent delete -f ${ABSOLUTE_BASEDIR}/02a-psp-whitelist.yaml
151 | run "echo -n ."
152 | kubectlSilent apply -f ${ABSOLUTE_BASEDIR}/psp-privileged.yaml
153 | run "echo -n ."
154 | }
155 |
156 | main "$@"
--------------------------------------------------------------------------------
/4-pod-security-policies/demo/psp-privileged.yaml:
--------------------------------------------------------------------------------
1 | # This is the least restricted policy you can create, equivalent to not using the pod security policy admission controller:
2 | # https://kubernetes.io/docs/concepts/policy/pod-security-policy/#example-policies
3 | # https://github.com/kubernetes/website/blob/snapshot-initial-v1.17/content/en/examples/policy/privileged-psp.yaml
4 | apiVersion: policy/v1beta1
5 | kind: PodSecurityPolicy
6 | metadata:
7 | name: privileged
8 | annotations:
9 | seccomp.security.alpha.kubernetes.io/allowedProfileNames: '*'
10 | spec:
11 | privileged: true
12 | allowPrivilegeEscalation: true
13 | allowedCapabilities:
14 | - '*'
15 | volumes:
16 | - '*'
17 | hostNetwork: true
18 | hostPorts:
19 | - min: 0
20 | max: 65535
21 | hostIPC: true
22 | hostPID: true
23 | runAsUser:
24 | rule: 'RunAsAny'
25 | seLinux:
26 | rule: 'RunAsAny'
27 | supplementalGroups:
28 | rule: 'RunAsAny'
29 | fsGroup:
30 | rule: 'RunAsAny'
31 | ---
32 | apiVersion: rbac.authorization.k8s.io/v1
33 | kind: ClusterRole
34 | metadata:
35 | name: podsecuritypolicy:privileged
36 | rules:
37 | - apiGroups:
38 | - extensions
39 | resourceNames:
40 | - privileged
41 | resources:
42 | - podsecuritypolicies
43 | verbs:
44 | - use
45 | ---
46 | apiVersion: rbac.authorization.k8s.io/v1
47 | kind: ClusterRoleBinding
48 | metadata:
49 | name: podsecuritypolicy:all-serviceaccounts
50 | roleRef:
51 | apiGroup: rbac.authorization.k8s.io
52 | kind: ClusterRole
53 | name: podsecuritypolicy:privileged
54 | subjects:
55 | - apiGroup: rbac.authorization.k8s.io
56 | kind: Group
57 | name: system:serviceaccounts
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Readme.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Kubernetes Security Demos
4 |
5 | Demos for several kubernetes security features
6 |
7 |
8 |
9 |
10 |
11 |
12 | - [Overview](#overview)
13 | - [Running the demos](#running-the-demos)
14 | - [Credentials](#credentials)
15 | - [Blog Posts](#blog-posts)
16 | - [Setting up the clusters](#setting-up-the-clusters)
17 | - [Deleting clusters](#deleting-clusters)
18 | - [Costs](#costs)
19 |
20 |
21 |
22 | # Overview
23 |
24 | Initially, these demos were developed during the preparation for some talks on [Kubernetes appOps Security](https://github.com/cloudogu/k8s-appops-security-talks) and our [K8s application security training](https://cloudogu.com/en/trainings/?mtm_campaign=k8s-sec-demos&mtm_kwd=trainings&mtm_source=github&mtm_medium=link).
25 |
26 | See also our [series of blog posts](#blog-posts) on the topic.
27 |
28 | Tested to run on Google Kubernetes Engine (GKE) with a local Linux machine.
29 | Should also work on Mac.
30 | Should run on all clusters that support NetworkPolicies and PodSecurityPolicies.
31 |
32 |
33 | 1. ~~Role Based Access Controll (RBAC)~~ - RBAC has now been default for years.
34 | A showcase for the downsides of ABAC seems obsolete.
35 | If you're interested check [git history](https://github.com/cloudogu/k8s-security-demos/tree/b94aa0a94358cc04f3f1beed80f755ac14b994da).
36 | 2. [Network Policies](2-network-policies/Readme.md)
37 | 3. [Security Context](3-security-context/Readme.md)
38 | 4. [Pod Security Policies](4-pod-security-policies/Readme.md)
39 |
40 | # Running the demos
41 |
42 | Each demo is contained in its own sub folder, where each contains a
43 |
44 | * `apply.sh` that deploys the applications required for the demos and
45 | * `README.md` that contains the steps of the demo
46 |
47 | Note that the scripts also create entries to your `/etc/hosts`.
48 |
49 | All Demos run inside the same cluster. Before running make sure to have your `kubeconfig` set to a non-productive cluster.
50 | If you want, you can set one up on your GKE account using the script inside this repo.
51 | See [Setting up the clusters](#setting-up-the-clusters).
52 |
53 | # Credentials
54 |
55 | If not otherwise stated, the login credentials for the webapps are
56 |
57 | * User: `admin`
58 | * Password: `12345`
59 |
60 | It's a demo after all! 😉
61 |
62 | # Demo recordings
63 |
64 | ## Security Context
65 |
66 | [](https://asciinema.org/a/366999)
67 |
68 | Recorded live at [heiseDevSec 2020](https://cloudogu.github.io/k8s-appops-security-talks/2020-10-23-heise-devsec/#/).
69 |
70 | # Blog Posts
71 |
72 | The examples evolved further while working on an article series called "Kubernetes AppOps Security" published in German Magazin JavaSPEKTRUM. Both English translation and German original can be found on the Cloudogu Blog.
73 |
74 | * 05/2019
75 | * [🇬🇧 Network Policies - Part 1 - Good Practices](https://cloudogu.com/en/blog/k8s-app-ops-part-1)
76 | * [🇩🇪 Network Policies - Teil 1 - Good Practices](https://cloudogu.com/de/blog/k8s-app-ops-teil-1)
77 | * 06/2019
78 | * [🇬🇧 Network Policies - Part 2 - Advanced Topics and Tips](https://cloudogu.com/en/blog/k8s-app-ops-part-2)
79 | * [🇩🇪 Network Policies - Teil 2 - Fortgeschrittene Themen und Tipps](https://cloudogu.com/de/blog/k8s-app-ops-teil-2)
80 | * 01/2020
81 | * [🇬🇧 Security Context – Part 1: Good Practices](https://cloudogu.com/en/blog/k8s-app-ops-part-3-security-context-1)
82 | * [🇩🇪 Security Context – Teil 1: Good Practices](https://cloudogu.com/de/blog/k8s-app-ops-teil-3-security-context-1)
83 | * 02/2020
84 | * [🇬🇧 Security Context - Background](https://cloudogu.com/en/blog/k8s-app-ops-part-4-security-context-2)
85 | * [🇩🇪 Security Context - Hintergründe](https://cloudogu.com/de/blog/k8s-app-ops-teil-4-security-context-2)
86 | * 04/2020
87 | * [🇬🇧 Pod Security Policies – Good Practices](https://cloudogu.com/en/blog/k8s-app-ops-part-5-pod-security-policies-1)
88 | * [🇩🇪 Pod Security Policies – Good Practices](https://cloudogu.com/de/blog/k8s-app-ops-teil-5-pod-security-policies-1)
89 | * 05/2020
90 | * [🇬🇧 Pod Security Policies – Good Practices](https://cloudogu.com/en/blog/k8s-app-ops-part-6-pod-security-policies-2)
91 | * [🇩🇪 Pod Security Policies – Good Practices](https://cloudogu.com/de/blog/k8s-app-ops-teil-6-pod-security-policies-2)
92 |
93 | # Setting up the clusters
94 |
95 | This demos should run on most kubernetes clusters that have support for NetworkPolicies and PodSecurityPolicies.
96 |
97 | This repo also features setting up a defined environment Google Kubernetes engine.
98 | You can set it up using [createCluster.sh](createCluster.sh).
99 | It uses terraform to roll out the clusters. If you prefer a bash-only variant, check [git history](https://github.com/cloudogu/k8s-security-demos/tree/b94aa0a94358cc04f3f1beed80f755ac14b994da).
100 |
101 | In order to use the script
102 |
103 | * set your GKE `ZONE` and `PROJECT` in `config.sh`
104 | (alternatively, you can set these properties via env vars).
105 | Note that you can also set `CLUSTER_VERSION` (like `1.11`) and `MACHINE_TYPE` (like `n1-standard-2`).
106 | From time to time GKE drops support for older cluster versions, so you might need to set a newer one, if the one in
107 | `config.sh` is no longer supported at the time of execution.
108 | * set up a service account on GKE that allows terraform to do the setup
109 | ```shell script
110 | source config.sh
111 | SA=terraform-cluster
112 |
113 | # Create SA
114 | gcloud iam service-accounts create ${SA} --display-name ${SA} --project ${PROJECT}
115 |
116 | # Authorize (maybe roles/container.admin is enough?)
117 | gcloud projects add-iam-policy-binding ${PROJECT} \
118 | --member serviceAccount:${SA}@${PROJECT}.iam.gserviceaccount.com --role=roles/editor
119 |
120 | # Export credentials
121 | gcloud iam service-accounts keys create \
122 | --iam-account ${SA}@${PROJECT}.iam.gserviceaccount.com terraform/account.json
123 | ```
124 | * Have terraform installed (should work with 0.12 and 0.13)
125 | * Call `./create Cluster.sh`
126 | * Terraform will ask for confirmation before executing.
127 | If you don't want that, call `./createCluster.sh -auto-approve`
128 |
129 | ## Deleting clusters
130 |
131 | You can delete the cluster and entries to `/etc/hosts` once you're done using the `./delete-clusters.sh` script.
132 |
133 | ## Costs
134 |
135 | For just a quick create, demo, delete action the cost should be < 10$.
136 | The total infra cost for initially creating these demos was about 10$.
137 |
--------------------------------------------------------------------------------
/cluster-utils.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | PSPDIR=4-pod-security-policies/demo
4 |
5 | function waitForExternalIp() {
6 |
7 | local SERVICE_NAME="$1"
8 | local NAMESPACE="$2"
9 |
10 | local ip=""
11 | while [[ -z ${ip} ]]; do
12 | ip=$(findServiceExternalIp "${SERVICE_NAME}" "${NAMESPACE}")
13 | sleep 1
14 | done
15 |
16 | echo "${ip}"
17 | }
18 |
19 | function findServiceExternalIp() {
20 | local NAMESPACE=${2-}
21 |
22 | if [[ ! -z "${NAMESPACE}" ]]; then
23 | NAMESPACE="-n ${NAMESPACE}"
24 | fi
25 |
26 | kubectl get service $1 -o=jsonpath="{.status.loadBalancer.ingress[0].ip}" ${NAMESPACE}
27 | }
28 |
29 | function findIngressHostname() {
30 | local NAMESPACE=${2-}
31 |
32 | if [[ ! -z "${NAMESPACE}" ]]; then
33 | NAMESPACE="-n ${NAMESPACE}"
34 | fi
35 |
36 | kubectl get ingress $1 -o=jsonpath="{.spec.rules[0].host}" ${NAMESPACE}
37 | }
38 |
39 | function writeEtcHosts() {
40 | local IP=$1
41 | local NEW_HOSTNAME=$2
42 |
43 | echo "Writing the following to /etc/hosts: ${IP} ${NEW_HOSTNAME}"
44 | echo "${IP} ${NEW_HOSTNAME}" | sudo tee --append /etc/hosts
45 | }
46 |
47 | function kubectlIdempotent() {
48 | kubectl "$@" --dry-run=client -o yaml | kubectl apply -f -
49 | }
50 |
51 | function waitForPodReady() {
52 |
53 | local POD_NAME="$1"
54 | local NAMESPACE="$2"
55 |
56 | local isReady=""
57 | while [[ -z ${isReady} ]]; do
58 | local isReady=$(kubectl get pod -n "${NAMESPACE}" $(kubectl get pods -n "${NAMESPACE}" | awk -v pod_name="$POD_NAME" '$0 ~ pod_name {print $1;exit}') -o json | jq '.status.conditions[] | select(.type=="Ready" and .status=="True")')
59 | echo "Waiting for pod ${POD_NAME} in namespace ${NAMESPACE} to become ready"
60 | sleep 1
61 | done
62 | # For some reasons pods still refuse after they are ready :-/
63 | sleep 1
64 | }
65 |
--------------------------------------------------------------------------------
/config.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | PROJECT=${PROJECT:-"cloudogu-trainings"}
3 | ZONE=${ZONE:-"us-central1-a"}
4 |
5 | # Docs recommend to not use fuzzy version here:
6 | # https://www.terraform.io/docs/providers/google/r/container_cluster.html
7 | # OTOH google deprecates support for specific version rather fast.
8 | # Resulting in "Error 400: Master version "X" is unsupported., badRequest"
9 | # So we use a version prefix hoping that the stable patch versions won't do unexpected things (which is unlikely!)
10 | CLUSTER_VERSION=${CLUSTER_VERSION:-"1.18."}
11 | MACHINE_TYPE=${MACHINE_TYPE:-"n1-standard-2"}
12 |
13 | CLUSTER="k8s-sec-demo-rbac-nwp-psp"
14 | CLUSTER_NODES=2
15 |
16 | # TODO grep network poilicy hosts from ingress.yamls - grep -r "host: "
17 | HOSTNAMES=( "legacy-authz" "rbac" "traefik" "web-console" "prometheus" "nosqlclient" )
--------------------------------------------------------------------------------
/createCluster.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 |
4 | BASEDIR=$(dirname $0)
5 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
6 |
7 | source ${ABSOLUTE_BASEDIR}/config.sh
8 | source ${ABSOLUTE_BASEDIR}/cluster-utils.sh
9 |
10 | function createCluster() {
11 |
12 | (
13 | cd ${ABSOLUTE_BASEDIR}/terraform && terraform init \
14 | -backend-config "path=.terraform/backend/${CLUSTER}"
15 | )
16 |
17 | (
18 | cd ${ABSOLUTE_BASEDIR}/terraform && terraform apply \
19 | -var "gce_project=${PROJECT}" \
20 | -var "gce_location=${ZONE}" \
21 | -var "cluster_name=${CLUSTER}" \
22 | -var "credentials=account.json" \
23 | -var "node_count=${CLUSTER_NODES}" \
24 | -var "k8s_version_prefix=${CLUSTER_VERSION}" \
25 | -var "machine_type=${MACHINE_TYPE}" $*
26 | )
27 |
28 | # Start with a privileged PSP. Makes sure deployments are allowed to create pods
29 |
30 | local ABSOLUTE_BASEDIR="$(cd $(dirname $0) && pwd)"
31 |
32 | # Become cluster admin, so we are authorized to create role for PSP
33 | becomeClusterAdmin
34 |
35 | kubectl apply -f ${ABSOLUTE_BASEDIR}/${PSPDIR}/psp-privileged.yaml
36 | }
37 |
38 | function becomeClusterAdmin() {
39 | kubectlIdempotent create clusterrolebinding myname-cluster-admin-binding \
40 | --clusterrole=cluster-admin \
41 | --user=$(gcloud info | grep Account | sed -r 's/Account\: \[(.*)\]/\1/')
42 | # TODO replace by kubectl whoami in order to get rid of gcloud dependency?
43 | }
44 |
45 | createCluster "$@"
--------------------------------------------------------------------------------
/delete-clusters.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -o errexit -o nounset -o pipefail
3 |
4 | BASEDIR=$(dirname $0)
5 | ABSOLUTE_BASEDIR="$( cd ${BASEDIR} && pwd )"
6 |
7 | source ${ABSOLUTE_BASEDIR}/config.sh
8 | source ${ABSOLUTE_BASEDIR}/cluster-utils.sh
9 |
10 | function main() {
11 | deleteHostNames
12 |
13 | deleteClusterIfExists "$@"
14 | }
15 |
16 | function deleteClusterIfExists() {
17 |
18 |
19 | (
20 | cd ${ABSOLUTE_BASEDIR}/terraform && terraform init \
21 | -backend-config "path=.terraform/backend/${CLUSTER}"
22 | )
23 |
24 | (
25 | cd ${ABSOLUTE_BASEDIR}/terraform && terraform destroy \
26 | -var "gce_project=${PROJECT}" \
27 | -var "gce_location=${ZONE}" \
28 | -var "cluster_name=${CLUSTER}" \
29 | -var "credentials=account.json" \
30 | -var "node_count=0" \
31 | -var "k8s_version_prefix=dontcare" \
32 | -var "machine_type=dontcare" $*
33 | )
34 | }
35 |
36 | function deleteHostNames() {
37 |
38 | echo "Deleting entries from /etc/hosts: " "${HOSTNAMES[@]}"
39 |
40 | for NAME in "${HOSTNAMES[@]}"
41 | do
42 | sudo sed -i "/${NAME}/d" /etc/hosts
43 | done
44 | }
45 |
46 | main "$@"
--------------------------------------------------------------------------------
/interactive-utils.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | GREEN='\033[0;32m'
4 | RED='\033[0;31m'
5 | GRAY='\033[0;30m'
6 | NO_COLOR='\033[0m'
7 |
8 | CAT=$(if [[ -x "$(command -v bat)" ]]; then echo "bat"; else echo "cat"; fi)
9 |
10 | function heading() {
11 | echo
12 | echo -e "${RED}# ${1}${NO_COLOR}"
13 | echo -e "${RED}========================================${NO_COLOR}"
14 | }
15 |
16 | function subHeading() {
17 | echo
18 | echo -e "${GREEN}# ${1}${NO_COLOR}"
19 | echo
20 | pressKeyToContinue
21 | }
22 |
23 | function message() {
24 | echo
25 | echo -e "${GREEN}${1}${NO_COLOR}"
26 | echo
27 | pressKeyToContinue
28 | }
29 |
30 | function pressKeyToContinue() {
31 | if [[ "${PRINT_ONLY}" != "true" ]]; then
32 | read -n 1 -s -r -p "Press any key to continue"
33 | removeOutputLine
34 | fi
35 | }
36 |
37 | function confirm() {
38 | # shellcheck disable=SC2145
39 | # - the line break between args is intended here!
40 | printf "%s\n" "${@:-Are you sure? [y/N]} "
41 |
42 | read -r response
43 | case "$response" in
44 | [yY][eE][sS] | [yY])
45 | true
46 | ;;
47 | *)
48 | false
49 | ;;
50 | esac
51 | }
52 |
53 | function removeOutputLine() {
54 | echo -en "\r\033[K"
55 | }
56 |
57 | function printAndRun() {
58 | echo "$ ${1}"
59 | run "${1}"
60 | }
61 |
62 | function run() {
63 | if [[ "${PRINT_ONLY}" != "true" ]]; then
64 | eval ${1} || true
65 | fi
66 | }
67 |
68 | function printFile() {
69 | ${CAT} ${1}
70 | pressKeyToContinue
71 | }
72 |
73 | function kubectlSilent() {
74 | if [[ "${PRINT_ONLY}" != "true" ]]; then
75 | kubectl "$@" > /dev/null 2>&1 || true
76 | fi
77 | }
--------------------------------------------------------------------------------
/terraform/main.tf:
--------------------------------------------------------------------------------
1 | terraform {
2 |
3 | backend "local" {}
4 |
5 | required_providers {
6 |
7 | google = {
8 | source = "hashicorp/google"
9 | version = "~> 3.51.0"
10 | }
11 | google-beta = {
12 | source = "hashicorp/google"
13 | version = "~> 3.51.0"
14 | }
15 | }
16 | required_version = ">= 0.14"
17 | }
18 |
19 | provider "google" {
20 | credentials = file(var.credentials)
21 | project = var.gce_project
22 | }
23 |
24 | # Required for pod_security_policy_config
25 | provider google-beta {
26 | credentials = file(var.credentials)
27 | project = var.gce_project
28 | }
29 |
30 | data "google_container_engine_versions" "k8s-security-demo" {
31 | provider = google-beta
32 | location = var.gce_location
33 | version_prefix = var.k8s_version_prefix
34 | }
35 |
36 | resource "google_container_cluster" "k8s-security-demo-cluster" {
37 | # Required for pod_security_policy_config
38 | provider = google-beta
39 | name = var.cluster_name
40 |
41 | min_master_version = data.google_container_engine_versions.k8s-security-demo.latest_master_version
42 | node_version = data.google_container_engine_versions.k8s-security-demo.latest_node_version
43 |
44 | location = var.gce_location
45 |
46 | pod_security_policy_config {
47 | enabled = true
48 | }
49 |
50 | remove_default_node_pool = true
51 | initial_node_count = 1
52 |
53 | network_policy {
54 | # On the nodes
55 | enabled = true
56 | }
57 |
58 | addons_config {
59 | # On the master
60 | network_policy_config {
61 | disabled = false
62 | }
63 | }
64 |
65 | provisioner "local-exec" {
66 | # Create entry for cluster in local kubeconfig
67 | command = "gcloud container clusters get-credentials ${var.cluster_name} --zone ${var.gce_location} --project ${var.gce_project}"
68 | }
69 | provisioner "local-exec" {
70 | when = destroy
71 | command = "kubectl config delete-context gke_${self.project}_${self.location}_${self.name}"
72 | }
73 | }
74 |
75 | resource "google_container_node_pool" "k8s-security-demo-node-pool" {
76 | location = var.gce_location
77 | cluster = google_container_cluster.k8s-security-demo-cluster.name
78 | node_count = var.node_count
79 |
80 | management {
81 | # Avoid unpleasant surprises during live demos
82 | auto_upgrade = false
83 | }
84 |
85 | node_config {
86 | preemptible = false
87 | machine_type = var.machine_type
88 |
89 | metadata = {
90 | disable-legacy-endpoints = "true"
91 | }
92 |
93 | oauth_scopes = [
94 | "https://www.googleapis.com/auth/logging.write",
95 | "https://www.googleapis.com/auth/monitoring",
96 | # Grants Read Access to GCR to clusters
97 | "https://www.googleapis.com/auth/devstorage.read_only",
98 | ]
99 | }
100 | }
--------------------------------------------------------------------------------
/terraform/vars.tf:
--------------------------------------------------------------------------------
1 | variable "gce_project" {
2 | type = string
3 | description = "Determines the Google Cloud project to be used"
4 | }
5 |
6 | variable "gce_location" {
7 | type = string
8 | description = "The GCE location to be used"
9 | }
10 |
11 | variable "cluster_name" {
12 | description = "cluster name inside google cloud project"
13 | }
14 |
15 | variable "credentials" {
16 | description = "Google Service Account JSON used by terraform for authentication"
17 | }
18 |
19 | variable "node_count" {
20 | type = number
21 | description = "Number of nodes in each cluster"
22 | }
23 |
24 | variable "machine_type" {
25 | description = "Type of VM machines used as cluster nodes"
26 | }
27 |
28 | variable "k8s_version_prefix" {
29 | type = string
30 | description = "Master and Node version prefix to setup"
31 | }
32 |
--------------------------------------------------------------------------------