├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── cmd └── webhook-server │ ├── admission_controller.go │ └── main.go ├── deploy.sh ├── deployment ├── deployment.yaml.template └── generate-keys.sh ├── examples ├── pod-with-conflict.yaml ├── pod-with-defaults.yaml └── pod-with-override.yaml ├── go.mod ├── go.sum └── image ├── .gitignore └── Dockerfile /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 StackRox Inc. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # Makefile for building the Admission Controller webhook demo server + docker image. 16 | 17 | .DEFAULT_GOAL := docker-image 18 | 19 | IMAGE ?= stackrox/admission-controller-webhook-demo:latest 20 | 21 | image/webhook-server: $(shell find . -name '*.go') 22 | CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o $@ ./cmd/webhook-server 23 | 24 | .PHONY: docker-image 25 | docker-image: image/webhook-server 26 | docker build -t $(IMAGE) image/ 27 | 28 | .PHONY: push-image 29 | push-image: docker-image 30 | docker push $(IMAGE) 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Kubernetes Admission Controller Webhook Demo 2 | 3 | This repository contains a small HTTP server that can be used as a Kubernetes 4 | [MutatingAdmissionWebhook](https://kubernetes.io/docs/admin/admission-controllers/#mutatingadmissionwebhook-beta-in-19). 5 | 6 | The logic of this demo webhook is fairly simple: it enforces more secure defaults for running 7 | containers as non-root user. While it is still possible to run containers as root, the webhook 8 | ensures that this is only possible if the setting `runAsNonRoot` is *explicitly* set to `false` 9 | in the `securityContext` of the Pod. If no value is set for `runAsNonRoot`, a default of `true` 10 | is applied, and the user ID defaults to `1234`. 11 | 12 | ## Prerequisites 13 | 14 | A cluster on which this example can be tested must be running Kubernetes 1.9.0 or above, 15 | with the `admissionregistration.k8s.io/v1beta1` API enabled. You can verify that by observing that the 16 | following command produces a non-empty output: 17 | ``` 18 | kubectl api-versions | grep admissionregistration.k8s.io/v1beta1 19 | ``` 20 | In addition, the `MutatingAdmissionWebhook` admission controller should be added and listed in the admission-control 21 | flag of `kube-apiserver`. 22 | 23 | For building the image, [GNU make](https://www.gnu.org/software/make/) and [Go](https://golang.org) are required. 24 | 25 | ## Deploying the Webhook Server 26 | 27 | 1. Bring up a Kubernetes cluster satisfying the above prerequisites, and make 28 | sure it is active (i.e., either via the configuration in the default location, or by setting 29 | the `KUBECONFIG` environment variable). 30 | 2. Run `./deploy.sh`. This will create a CA, a certificate and private key for the webhook server, 31 | and deploy the resources in the newly created `webhook-demo` namespace in your Kubernetes cluster. 32 | 33 | 34 | ## Verify 35 | 36 | 1. The `webhook-server` pod in the `webhook-demo` namespace should be running: 37 | ``` 38 | $ kubectl -n webhook-demo get pods 39 | NAME READY STATUS RESTARTS AGE 40 | webhook-server-6f976f7bf-hssc9 1/1 Running 0 35m 41 | ``` 42 | 43 | 2. A `MutatingWebhookConfiguration` named `demo-webhook` should exist: 44 | ``` 45 | $ kubectl get mutatingwebhookconfigurations 46 | NAME AGE 47 | demo-webhook 36m 48 | ``` 49 | 50 | 3. Deploy [a pod](examples/pod-with-defaults.yaml) that neither sets `runAsNonRoot` nor `runAsUser`: 51 | ``` 52 | $ kubectl create -f examples/pod-with-defaults.yaml 53 | ``` 54 | Verify that the pod has default values in its security context filled in: 55 | ``` 56 | $ kubectl get pod/pod-with-defaults -o yaml 57 | ... 58 | securityContext: 59 | runAsNonRoot: true 60 | runAsUser: 1234 61 | ... 62 | ``` 63 | Also, check the logs that the pod had in fact been running as a non-root user: 64 | ``` 65 | $ kubectl logs pod-with-defaults 66 | I am running as user 1234 67 | ``` 68 | 69 | 4. Deploy [a pod](examples/pod-with-override.yaml) that explicitly sets `runAsNonRoot` to `false`, allowing it to run as the 70 | `root` user: 71 | ``` 72 | $ kubectl create -f examples/pod-with-override.yaml 73 | $ kubectl get pod/pod-with-override -o yaml 74 | ... 75 | securityContext: 76 | runAsNonRoot: false 77 | ... 78 | $ kubectl logs pod-with-override 79 | I am running as user 0 80 | ``` 81 | 82 | 5. Attempt to deploy [a pod](examples/pod-with-conflict.yaml) that has a conflicting setting: `runAsNonRoot` set to `true`, but `runAsUser` set to 0 (root). 83 | The admission controller should block the creation of that pod. 84 | ``` 85 | $ kubectl create -f examples/pod-with-conflict.yaml 86 | Error from server (InternalError): error when creating "examples/pod-with-conflict.yaml": Internal error 87 | occurred: admission webhook "webhook-server.webhook-demo.svc" denied the request: runAsNonRoot specified, 88 | but runAsUser set to 0 (the root user) 89 | ``` 90 | 91 | ## Build the Image from Sources (optional) 92 | 93 | An image can be built by running `make`. 94 | If you want to modify the webhook server for testing purposes, be sure to set and export 95 | the shell environment variable `IMAGE` to an image tag for which you have push access. You can then 96 | build and push the image by running `make push-image`. Also make sure to change the image tag 97 | in `deployment/deployment.yaml.template`, and if necessary, add image pull secrets. 98 | 99 | -------------------------------------------------------------------------------- /cmd/webhook-server/admission_controller.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 StackRox Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "encoding/json" 21 | "errors" 22 | "fmt" 23 | "io/ioutil" 24 | "log" 25 | "net/http" 26 | 27 | admission "k8s.io/api/admission/v1beta1" 28 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 29 | "k8s.io/apimachinery/pkg/runtime" 30 | "k8s.io/apimachinery/pkg/runtime/serializer" 31 | ) 32 | 33 | const ( 34 | jsonContentType = `application/json` 35 | ) 36 | 37 | var ( 38 | universalDeserializer = serializer.NewCodecFactory(runtime.NewScheme()).UniversalDeserializer() 39 | ) 40 | 41 | // patchOperation is an operation of a JSON patch, see https://tools.ietf.org/html/rfc6902 . 42 | type patchOperation struct { 43 | Op string `json:"op"` 44 | Path string `json:"path"` 45 | Value interface{} `json:"value,omitempty"` 46 | } 47 | 48 | // admitFunc is a callback for admission controller logic. Given an AdmissionRequest, it returns the sequence of patch 49 | // operations to be applied in case of success, or the error that will be shown when the operation is rejected. 50 | type admitFunc func(*admission.AdmissionRequest) ([]patchOperation, error) 51 | 52 | // isKubeNamespace checks if the given namespace is a Kubernetes-owned namespace. 53 | func isKubeNamespace(ns string) bool { 54 | return ns == metav1.NamespacePublic || ns == metav1.NamespaceSystem 55 | } 56 | 57 | // doServeAdmitFunc parses the HTTP request for an admission controller webhook, and -- in case of a well-formed 58 | // request -- delegates the admission control logic to the given admitFunc. The response body is then returned as raw 59 | // bytes. 60 | func doServeAdmitFunc(w http.ResponseWriter, r *http.Request, admit admitFunc) ([]byte, error) { 61 | // Step 1: Request validation. Only handle POST requests with a body and json content type. 62 | 63 | if r.Method != http.MethodPost { 64 | w.WriteHeader(http.StatusMethodNotAllowed) 65 | return nil, fmt.Errorf("invalid method %s, only POST requests are allowed", r.Method) 66 | } 67 | 68 | body, err := ioutil.ReadAll(r.Body) 69 | if err != nil { 70 | w.WriteHeader(http.StatusBadRequest) 71 | return nil, fmt.Errorf("could not read request body: %v", err) 72 | } 73 | 74 | if contentType := r.Header.Get("Content-Type"); contentType != jsonContentType { 75 | w.WriteHeader(http.StatusBadRequest) 76 | return nil, fmt.Errorf("unsupported content type %s, only %s is supported", contentType, jsonContentType) 77 | } 78 | 79 | // Step 2: Parse the AdmissionReview request. 80 | 81 | var admissionReviewReq admission.AdmissionReview 82 | 83 | if _, _, err := universalDeserializer.Decode(body, nil, &admissionReviewReq); err != nil { 84 | w.WriteHeader(http.StatusBadRequest) 85 | return nil, fmt.Errorf("could not deserialize request: %v", err) 86 | } else if admissionReviewReq.Request == nil { 87 | w.WriteHeader(http.StatusBadRequest) 88 | return nil, errors.New("malformed admission review: request is nil") 89 | } 90 | 91 | // Step 3: Construct the AdmissionReview response. 92 | 93 | admissionReviewResponse := admission.AdmissionReview{ 94 | // Since the admission webhook now supports multiple API versions, we need 95 | // to explicitly include the API version in the response. 96 | // This API version needs to match the version from the request exactly, otherwise 97 | // the API server will be unable to process the response. 98 | // Note: a v1beta1 AdmissionReview is JSON-compatible with the v1 version, that's why 99 | // we do not need to differentiate during unmarshaling or in the actual logic. 100 | TypeMeta: admissionReviewReq.TypeMeta, 101 | Response: &admission.AdmissionResponse{ 102 | UID: admissionReviewReq.Request.UID, 103 | }, 104 | } 105 | 106 | var patchOps []patchOperation 107 | // Apply the admit() function only for non-Kubernetes namespaces. For objects in Kubernetes namespaces, return 108 | // an empty set of patch operations. 109 | if !isKubeNamespace(admissionReviewReq.Request.Namespace) { 110 | patchOps, err = admit(admissionReviewReq.Request) 111 | } 112 | 113 | if err != nil { 114 | // If the handler returned an error, incorporate the error message into the response and deny the object 115 | // creation. 116 | admissionReviewResponse.Response.Allowed = false 117 | admissionReviewResponse.Response.Result = &metav1.Status{ 118 | Message: err.Error(), 119 | } 120 | } else { 121 | // Otherwise, encode the patch operations to JSON and return a positive response. 122 | patchBytes, err := json.Marshal(patchOps) 123 | if err != nil { 124 | w.WriteHeader(http.StatusInternalServerError) 125 | return nil, fmt.Errorf("could not marshal JSON patch: %v", err) 126 | } 127 | admissionReviewResponse.Response.Allowed = true 128 | admissionReviewResponse.Response.Patch = patchBytes 129 | 130 | // Announce that we are returning a JSON patch (note: this is the only 131 | // patch type currently supported, but we have to explicitly announce 132 | // it nonetheless). 133 | admissionReviewResponse.Response.PatchType = new(admission.PatchType) 134 | *admissionReviewResponse.Response.PatchType = admission.PatchTypeJSONPatch 135 | } 136 | 137 | // Return the AdmissionReview with a response as JSON. 138 | bytes, err := json.Marshal(&admissionReviewResponse) 139 | if err != nil { 140 | return nil, fmt.Errorf("marshaling response: %v", err) 141 | } 142 | return bytes, nil 143 | } 144 | 145 | // serveAdmitFunc is a wrapper around doServeAdmitFunc that adds error handling and logging. 146 | func serveAdmitFunc(w http.ResponseWriter, r *http.Request, admit admitFunc) { 147 | log.Print("Handling webhook request ...") 148 | 149 | var writeErr error 150 | if bytes, err := doServeAdmitFunc(w, r, admit); err != nil { 151 | log.Printf("Error handling webhook request: %v", err) 152 | w.WriteHeader(http.StatusInternalServerError) 153 | _, writeErr = w.Write([]byte(err.Error())) 154 | } else { 155 | log.Print("Webhook request handled successfully") 156 | _, writeErr = w.Write(bytes) 157 | } 158 | 159 | if writeErr != nil { 160 | log.Printf("Could not write response: %v", writeErr) 161 | } 162 | } 163 | 164 | // admitFuncHandler takes an admitFunc and wraps it into a http.Handler by means of calling serveAdmitFunc. 165 | func admitFuncHandler(admit admitFunc) http.Handler { 166 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 167 | serveAdmitFunc(w, r, admit) 168 | }) 169 | } 170 | -------------------------------------------------------------------------------- /cmd/webhook-server/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2019 StackRox Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "errors" 21 | "fmt" 22 | "log" 23 | "net/http" 24 | "path/filepath" 25 | 26 | admission "k8s.io/api/admission/v1beta1" 27 | corev1 "k8s.io/api/core/v1" 28 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 29 | ) 30 | 31 | const ( 32 | tlsDir = `/run/secrets/tls` 33 | tlsCertFile = `tls.crt` 34 | tlsKeyFile = `tls.key` 35 | ) 36 | 37 | var ( 38 | podResource = metav1.GroupVersionResource{Version: "v1", Resource: "pods"} 39 | ) 40 | 41 | // applySecurityDefaults implements the logic of our example admission controller webhook. For every pod that is created 42 | // (outside of Kubernetes namespaces), it first checks if `runAsNonRoot` is set. If it is not, it is set to a default 43 | // value of `false`. Furthermore, if `runAsUser` is not set (and `runAsNonRoot` was not initially set), it defaults 44 | // `runAsUser` to a value of 1234. 45 | // 46 | // To demonstrate how requests can be rejected, this webhook further validates that the `runAsNonRoot` setting does 47 | // not conflict with the `runAsUser` setting - i.e., if the former is set to `true`, the latter must not be `0`. 48 | // Note that we combine both the setting of defaults and the check for potential conflicts in one webhook; ideally, 49 | // the latter would be performed in a validating webhook admission controller. 50 | func applySecurityDefaults(req *admission.AdmissionRequest) ([]patchOperation, error) { 51 | // This handler should only get called on Pod objects as per the MutatingWebhookConfiguration in the YAML file. 52 | // However, if (for whatever reason) this gets invoked on an object of a different kind, issue a log message but 53 | // let the object request pass through otherwise. 54 | if req.Resource != podResource { 55 | log.Printf("expect resource to be %s", podResource) 56 | return nil, nil 57 | } 58 | 59 | // Parse the Pod object. 60 | raw := req.Object.Raw 61 | pod := corev1.Pod{} 62 | if _, _, err := universalDeserializer.Decode(raw, nil, &pod); err != nil { 63 | return nil, fmt.Errorf("could not deserialize pod object: %v", err) 64 | } 65 | 66 | // Retrieve the `runAsNonRoot` and `runAsUser` values. 67 | var runAsNonRoot *bool 68 | var runAsUser *int64 69 | if pod.Spec.SecurityContext != nil { 70 | runAsNonRoot = pod.Spec.SecurityContext.RunAsNonRoot 71 | runAsUser = pod.Spec.SecurityContext.RunAsUser 72 | } 73 | 74 | // Create patch operations to apply sensible defaults, if those options are not set explicitly. 75 | var patches []patchOperation 76 | if runAsNonRoot == nil { 77 | patches = append(patches, patchOperation{ 78 | Op: "add", 79 | Path: "/spec/securityContext/runAsNonRoot", 80 | // The value must not be true if runAsUser is set to 0, as otherwise we would create a conflicting 81 | // configuration ourselves. 82 | Value: runAsUser == nil || *runAsUser != 0, 83 | }) 84 | 85 | if runAsUser == nil { 86 | patches = append(patches, patchOperation{ 87 | Op: "add", 88 | Path: "/spec/securityContext/runAsUser", 89 | Value: 1234, 90 | }) 91 | } 92 | } else if *runAsNonRoot == true && (runAsUser != nil && *runAsUser == 0) { 93 | // Make sure that the settings are not contradictory, and fail the object creation if they are. 94 | return nil, errors.New("runAsNonRoot specified, but runAsUser set to 0 (the root user)") 95 | } 96 | 97 | return patches, nil 98 | } 99 | 100 | func main() { 101 | certPath := filepath.Join(tlsDir, tlsCertFile) 102 | keyPath := filepath.Join(tlsDir, tlsKeyFile) 103 | 104 | mux := http.NewServeMux() 105 | mux.Handle("/mutate", admitFuncHandler(applySecurityDefaults)) 106 | server := &http.Server{ 107 | // We listen on port 8443 such that we do not need root privileges or extra capabilities for this server. 108 | // The Service object will take care of mapping this port to the HTTPS port 443. 109 | Addr: ":8443", 110 | Handler: mux, 111 | } 112 | log.Fatal(server.ListenAndServeTLS(certPath, keyPath)) 113 | } 114 | -------------------------------------------------------------------------------- /deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Copyright (c) 2019 StackRox Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # deploy.sh 18 | # 19 | # Sets up the environment for the admission controller webhook demo in the active cluster. 20 | 21 | set -euo pipefail 22 | 23 | basedir="$(dirname "$0")/deployment" 24 | keydir="$(mktemp -d)" 25 | 26 | # Generate keys into a temporary directory. 27 | echo "Generating TLS keys ..." 28 | "${basedir}/generate-keys.sh" "$keydir" 29 | 30 | # Create the `webhook-demo` namespace. This cannot be part of the YAML file as we first need to create the TLS secret, 31 | # which would fail otherwise. 32 | echo "Creating Kubernetes objects ..." 33 | kubectl create namespace webhook-demo 34 | 35 | # Create the TLS secret for the generated keys. 36 | kubectl -n webhook-demo create secret tls webhook-server-tls \ 37 | --cert "${keydir}/webhook-server-tls.crt" \ 38 | --key "${keydir}/webhook-server-tls.key" 39 | 40 | # Read the PEM-encoded CA certificate, base64 encode it, and replace the `${CA_PEM_B64}` placeholder in the YAML 41 | # template with it. Then, create the Kubernetes resources. 42 | ca_pem_b64="$(openssl base64 -A <"${keydir}/ca.crt")" 43 | sed -e 's@${CA_PEM_B64}@'"$ca_pem_b64"'@g' <"${basedir}/deployment.yaml.template" \ 44 | | kubectl create -f - 45 | 46 | # Delete the key directory to prevent abuse (DO NOT USE THESE KEYS ANYWHERE ELSE). 47 | rm -rf "$keydir" 48 | 49 | echo "The webhook server has been deployed and configured!" 50 | -------------------------------------------------------------------------------- /deployment/deployment.yaml.template: -------------------------------------------------------------------------------- 1 | apiVersion: apps/v1 2 | kind: Deployment 3 | metadata: 4 | name: webhook-server 5 | namespace: webhook-demo 6 | labels: 7 | app: webhook-server 8 | spec: 9 | replicas: 1 10 | selector: 11 | matchLabels: 12 | app: webhook-server 13 | template: 14 | metadata: 15 | labels: 16 | app: webhook-server 17 | spec: 18 | securityContext: 19 | runAsNonRoot: true 20 | runAsUser: 1234 21 | containers: 22 | - name: server 23 | image: stackrox/admission-controller-webhook-demo:latest 24 | imagePullPolicy: Always 25 | ports: 26 | - containerPort: 8443 27 | name: webhook-api 28 | volumeMounts: 29 | - name: webhook-tls-certs 30 | mountPath: /run/secrets/tls 31 | readOnly: true 32 | volumes: 33 | - name: webhook-tls-certs 34 | secret: 35 | secretName: webhook-server-tls 36 | --- 37 | apiVersion: v1 38 | kind: Service 39 | metadata: 40 | name: webhook-server 41 | namespace: webhook-demo 42 | spec: 43 | selector: 44 | app: webhook-server 45 | ports: 46 | - port: 443 47 | targetPort: webhook-api 48 | --- 49 | apiVersion: admissionregistration.k8s.io/v1beta1 50 | kind: MutatingWebhookConfiguration 51 | metadata: 52 | name: demo-webhook 53 | webhooks: 54 | - name: webhook-server.webhook-demo.svc 55 | sideEffects: None 56 | admissionReviewVersions: ["v1", "v1beta1"] 57 | clientConfig: 58 | service: 59 | name: webhook-server 60 | namespace: webhook-demo 61 | path: "/mutate" 62 | caBundle: ${CA_PEM_B64} 63 | rules: 64 | - operations: [ "CREATE" ] 65 | apiGroups: [""] 66 | apiVersions: ["v1"] 67 | resources: ["pods"] 68 | -------------------------------------------------------------------------------- /deployment/generate-keys.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Copyright (c) 2019 StackRox Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # generate-keys.sh 18 | # 19 | # Generate a (self-signed) CA certificate and a certificate and private key to be used by the webhook demo server. 20 | # The certificate will be issued for the Common Name (CN) of `webhook-server.webhook-demo.svc`, which is the 21 | # cluster-internal DNS name for the service. 22 | # 23 | # NOTE: THIS SCRIPT EXISTS FOR DEMO PURPOSES ONLY. DO NOT USE IT FOR YOUR PRODUCTION WORKLOADS. 24 | 25 | : ${1?'missing key directory'} 26 | 27 | key_dir="$1" 28 | 29 | chmod 0700 "$key_dir" 30 | cd "$key_dir" 31 | 32 | cat >server.conf <