├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── bindep.txt ├── examples └── policy.json ├── glide.lock ├── glide.yaml ├── kube-system ├── Dockerfile └── k8s-keystone-auth.yaml ├── main.go ├── pkg ├── authenticator │ └── token │ │ └── keystone │ │ ├── authenticator.go │ │ ├── authorizer.go │ │ ├── keystone.go │ │ └── policy.go └── identity │ └── webhook │ └── handlers.go └── tools ├── install-distro-packages.sh └── test-setup.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.sublime-project 2 | *.sublime-workspace 3 | *.swp 4 | .idea 5 | .DS_Store 6 | vendor 7 | bin 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | Copyright 2014 Docker, Inc. 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # golang-client Makefile 2 | # Follows the interface defined in the Golang CTI proposed 3 | # in https://review.openstack.org/410355 4 | 5 | #REPO_VERSION?=$(shell git describe --tags) 6 | 7 | GIT_HOST = git.openstack.org 8 | 9 | PWD := $(shell pwd) 10 | BASE_DIR := $(shell basename $(PWD)) 11 | # Keep an existing GOPATH, make a private one if it is undefined 12 | GOPATH_DEFAULT := $(PWD)/.go 13 | export GOPATH ?= $(GOPATH_DEFAULT) 14 | PKG := $(shell awk '/^package: / { print $$2 }' glide.yaml) 15 | DEST := $(GOPATH)/src/$(GIT_HOST)/openstack/$(BASE_DIR) 16 | DEST := $(GOPATH)/src/$(PKG) 17 | 18 | # CTI targets 19 | 20 | depend: work 21 | cd $(DEST) && glide install --strip-vendor 22 | 23 | depend-update: work 24 | cd $(DEST) && glide update 25 | 26 | build: work 27 | cd $(DEST) && mkdir -p $(DEST)/bin && go build -o $(DEST)/bin/k8s-keystone-auth main.go 28 | 29 | test: unit functional 30 | 31 | unit: depend 32 | cd $(DEST) && go test -tags=unit $(shell glide novendor) 33 | 34 | functional: 35 | @echo "$@ not yet implemented" 36 | 37 | fmt: work 38 | cd $(DEST) && CGO_ENABLED=0 go fmt ./... 39 | 40 | lint: 41 | @echo "$@ not yet implemented" 42 | 43 | cover: 44 | @echo "$@ not yet implemented" 45 | 46 | docs: 47 | @echo "$@ not yet implemented" 48 | 49 | godoc: 50 | @echo "$@ not yet implemented" 51 | 52 | releasenotes: 53 | @echo "Reno not yet implemented for this repo" 54 | 55 | translation: 56 | @echo "$@ not yet implemented" 57 | 58 | # Do the work here 59 | 60 | # Set up the development environment 61 | env: 62 | @echo "PWD: $(PWD)" 63 | @echo "BASE_DIR: $(BASE_DIR)" 64 | @echo "GOPATH: $(GOPATH)" 65 | @echo "GOROOT: $(GOROOT)" 66 | @echo "DEST: $(DEST)" 67 | @echo "PKG: $(PKG)" 68 | go version 69 | go env 70 | 71 | # Get our dev/test dependencies in place 72 | bootstrap: 73 | tools/test-setup.sh 74 | 75 | work: $(GOPATH) $(DEST) 76 | 77 | $(GOPATH): 78 | mkdir -p $(GOPATH) 79 | 80 | $(DEST): $(GOPATH) 81 | mkdir -p $(shell dirname $(DEST)) 82 | ln -s $(PWD) $(DEST) 83 | 84 | .bindep: 85 | virtualenv .bindep 86 | .bindep/bin/pip install -i https://pypi.python.org/simple bindep 87 | 88 | bindep: .bindep 89 | @.bindep/bin/bindep -b -f bindep.txt || true 90 | 91 | install-distro-packages: 92 | tools/install-distro-packages.sh 93 | 94 | clean: 95 | rm -rf $(DEST)/bin $(DEST)/.bindep 96 | 97 | realclean: clean 98 | rm -rf vendor 99 | if [ "$(GOPATH)" = "$(GOPATH_DEFAULT)" ]; then \ 100 | rm -rf $(GOPATH); \ 101 | fi 102 | 103 | shell: work 104 | cd $(DEST) && $(SHELL) -i 105 | 106 | .PHONY: bindep build clean cover depend docs fmt functional lint realclean \ 107 | relnotes test translation 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # k8s-keystone-auth 2 | 3 | Proof-Of-Concept : Kubernetes webhook authentication and authorization for OpenStack Keystone 4 | 5 | Steps to use this webook with Kubernetes 6 | 7 | - Save the following into webhook.kubeconfig. 8 | ``` 9 | apiVersion: v1 10 | clusters: 11 | - cluster: 12 | insecure-skip-tls-verify: true 13 | server: https://localhost:8443/webhook 14 | name: webhook 15 | contexts: 16 | - context: 17 | cluster: webhook 18 | user: webhook 19 | name: webhook 20 | current-context: webhook 21 | kind: Config 22 | preferences: {} 23 | users: 24 | - name: webhook 25 | ``` 26 | 27 | ## Configuration on K8s master for authentication 28 | 29 | - Add the following flags to your Kubernetes api server. 30 | * `--authentication-token-webhook-config-file=/path/to/your/webhook.kubeconfig` 31 | * `--authorization-mode=Node,RBAC` 32 | - Start webhook process with the following flags 33 | * `--tls-cert-file /var/run/kubernetes/serving-kube-apiserver.crt` 34 | * `--tls-private-key-file /var/run/kubernetes/serving-kube-apiserver.key` 35 | * `--keystone-policy-file examples/policy.json` 36 | * `--keystone-url https://my.keystone:5000/v3` 37 | 38 | ## Configuration on K8s master for authorization 39 | 40 | - Copy the examples/policy.json and edit it to your needs. 41 | - Add the following flags to your Kubernetes api server. 42 | * `--authorization-mode=Webhook,Node --authorization-webhook-config-file=/path/to/your/webhook.kubeconfig` 43 | - When you start the webhook process make sure you also have the following flags (in addition to the flags in the case of authentication) 44 | * `--keystone-policy-file examples/policy.json` 45 | 46 | ## K8s kubectl Client configuration 47 | 48 | ### Old kubectl clients 49 | 50 | - Run `openstack token issue` to generate a token 51 | - Run `kubectl --token $TOKEN get po` or `curl -k -v -XGET -H "Accept: application/json" -H "Authorization: Bearer $TOKEN" https://localhost:6443/api/v1/namespaces/default/pods` 52 | 53 | ### New kubectl clients v1.8.0 and later 54 | 55 | The client is able to read the `OS_` env variables used also by the openstackclient. You dont have to pass a token with `--token`, but the client will contact Keystone directly, will get a token and will use it. To configure the client to the following: 56 | 57 | - Run `kubectl config set-credentials openstackuser --auth-provider=openstack` 58 | 59 | This command creates the following entry in your ~/.kube/config 60 | ``` 61 | - name: openstackuser 62 | user: 63 | as-user-extra: {} 64 | auth-provider: 65 | name: openstack 66 | ``` 67 | - Run `kubectl config set-context --cluster=kubernetes --user=openstackuser openstackuser@kubernetes` 68 | - Run `kubectl config use-context openstackuser@kubernetes` to activate the context 69 | 70 | Source your env vars. Make sure you include `OS_DOMAIN_NAME` or the client will fallback to Keystone V2 that is not supported by the webhook.This env should be ok: 71 | 72 | ``` 73 | OS_AUTH_URL="https://keystone.example.com:5000/v3" 74 | OS_DOMAIN_NAME="default" 75 | OS_IDENTITY_API_VERSION="3" 76 | OS_PASSWORD="mysecret" 77 | OS_PROJECT_NAME="myproject" 78 | OS_REGION_NAME="myRegion" 79 | OS_USERNAME="username" 80 | ``` 81 | - Try: `kubectl get pods` 82 | 83 | In case you are using this Webhook just for the authentication, you should get an authorization error: 84 | ``` 85 | Error from server (Forbidden): pods is forbidden: User "username" cannot list pods in the namespace "default" 86 | ``` 87 | 88 | You need to configure the RBAC with roles to be authorized to do something, for example: 89 | 90 | ``` kubectl create rolebinding username-view --clusterrole view --user username --namespace default``` 91 | 92 | Try now again to see the pods with `kubectl get pods` 93 | 94 | ## References 95 | 96 | More details about Kubernetes Authentication Webhook using Bearer Tokens is at : 97 | https://kubernetes.io/docs/admin/authentication/#webhook-token-authentication 98 | 99 | and the Authorization Webhook is at: 100 | https://kubernetes.io/docs/admin/authorization/webhook/ 101 | 102 | ## Tips 103 | 104 | - You can directly test the webhook with 105 | ``` 106 | cat << EOF | curl -kvs -XPOST -d @- https://localhost:8443/webhook | python -mjson.tool 107 | { 108 | "apiVersion": "authentication.k8s.io/v1beta1", 109 | "kind": "TokenReview", 110 | "metadata": { 111 | "creationTimestamp": null 112 | }, 113 | "spec": { 114 | "token": "$TOKEN" 115 | } 116 | } 117 | EOF 118 | 119 | cat << EOF | curl -kvs -XPOST -d @- https://localhost:8443/webhook | python -mjson.tool 120 | { 121 | "apiVersion": "authorization.k8s.io/v1beta1", 122 | "kind": "SubjectAccessReview", 123 | "spec": { 124 | "resourceAttributes": { 125 | "namespace": "kittensandponies", 126 | "verb": "get", 127 | "group": "unicorn.example.org", 128 | "resource": "pods" 129 | }, 130 | "user": "jane", 131 | "group": [ 132 | "group1", 133 | "group2" 134 | ] 135 | } 136 | } 137 | EOF 138 | ``` 139 | -------------------------------------------------------------------------------- /bindep.txt: -------------------------------------------------------------------------------- 1 | pkg-config 2 | build-essential 3 | mercurial 4 | golang-go 5 | golint 6 | make 7 | -------------------------------------------------------------------------------- /examples/policy.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "resource": { 4 | "verb": "*", 5 | "resource": "*", 6 | "version": "*", 7 | "namespace": "*" 8 | }, 9 | "match": { 10 | "type": "role", 11 | "value": "*" 12 | } 13 | }, 14 | { 15 | "resource": { 16 | "verb": "*", 17 | "resource": "*", 18 | "version": "*", 19 | "namespace": "*" 20 | }, 21 | "match": { 22 | "type": "group", 23 | "value": "*" 24 | } 25 | }, 26 | { 27 | "nonresource": { 28 | "verb": "*", 29 | "path": "*" 30 | }, 31 | "match": { 32 | "type": "role", 33 | "value": "*" 34 | } 35 | }, 36 | { 37 | "nonresource": { 38 | "verb": "*", 39 | "path": "*" 40 | }, 41 | "match": { 42 | "type": "group", 43 | "value": "*" 44 | } 45 | } 46 | ] -------------------------------------------------------------------------------- /glide.lock: -------------------------------------------------------------------------------- 1 | hash: f7acad6235ae5e13a88ab6b061415918d30ed2cd1771df6b1d6e75d764b12152 2 | updated: 2017-07-26T12:20:52.339562481-04:00 3 | imports: 4 | - name: github.com/golang/glog 5 | version: 23def4e6c14b4da8ac2ed8007337bc5eb5007998 6 | - name: github.com/gophercloud/gophercloud 7 | version: ed590d9afe113c6107cd60717b196155e6579e78 8 | subpackages: 9 | - openstack 10 | - openstack/identity/v2/tenants 11 | - openstack/identity/v2/tokens 12 | - openstack/identity/v3/tokens 13 | - openstack/utils 14 | - pagination 15 | - name: golang.org/x/net 16 | version: f2499483f923065a842d38eb4c7f1927e6fc6e6d 17 | subpackages: 18 | - context 19 | - html 20 | - html/atom 21 | - http2 22 | - http2/hpack 23 | - idna 24 | - internal/timeseries 25 | - lex/httplex 26 | - trace 27 | - websocket 28 | - name: k8s.io/apimachinery 29 | version: 6134cb2da6d90597b0434e349f90f94fafc9ae51 30 | subpackages: 31 | - pkg/util/net 32 | - pkg/util/sets 33 | - name: k8s.io/apiserver 34 | version: d7bba18199202b51f78c048c2a8404772007f0df 35 | subpackages: 36 | - pkg/authentication/authenticator 37 | - pkg/authentication/user 38 | - name: k8s.io/client-go 39 | version: 450baa5d60f8d6a251c7682cb6f86e939b750b2d 40 | subpackages: 41 | - util/cert 42 | testImports: [] 43 | -------------------------------------------------------------------------------- /glide.yaml: -------------------------------------------------------------------------------- 1 | package: github.com/dims/k8s-keystone-auth 2 | import: 3 | - package: github.com/dims/k8s-keystone-auth 4 | subpackages: 5 | - pkg/authenticator/token/keystone 6 | - package: github.com/golang/glog 7 | - package: github.com/gophercloud/gophercloud 8 | subpackages: 9 | - openstack 10 | - openstack/utils 11 | - package: k8s.io/apimachinery 12 | subpackages: 13 | - pkg/util/net 14 | - package: k8s.io/apiserver 15 | subpackages: 16 | - pkg/authentication/authenticator 17 | - pkg/authentication/user 18 | - package: k8s.io/client-go 19 | subpackages: 20 | - util/cert 21 | -------------------------------------------------------------------------------- /kube-system/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:16.04 2 | MAINTAINER Saverio Proto 3 | RUN apt-get update && \ 4 | apt-get install -y software-properties-common 5 | RUN add-apt-repository -y ppa:masterminds/glide 6 | RUN apt-get update && \ 7 | apt-get install -y glide git build-essential golang && \ 8 | apt-get clean && \ 9 | rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* 10 | RUN git clone https://github.com/dims/k8s-keystone-auth 11 | WORKDIR k8s-keystone-auth 12 | RUN make depend && make build 13 | EXPOSE 8443 14 | CMD ./bin/k8s-keystone-auth --tls-cert-file ${API_SERVER_CERT} --tls-private-key-file ${API_SERVER_KEY} --keystone-url ${OPENSTACK_KEYSTONE_URL} 15 | 16 | -------------------------------------------------------------------------------- /kube-system/k8s-keystone-auth.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Pod 4 | metadata: 5 | annotations: 6 | scheduler.alpha.kubernetes.io/critical-pod: "" 7 | creationTimestamp: null 8 | labels: 9 | component: k8s-keystone-auth 10 | tier: control-plane 11 | name: k8s-keystone-auth 12 | namespace: kube-system 13 | spec: 14 | containers: 15 | - command: 16 | - ./bin/k8s-keystone-auth 17 | - --tls-cert-file 18 | - /etc/kubernetes/pki/apiserver.crt 19 | - --tls-private-key-file 20 | - /etc/kubernetes/pki/apiserver.key 21 | - --keystone-url 22 | - https://mykeystone.com:5000/v3 23 | image: k8s-keystone-auth 24 | imagePullPolicy: Always 25 | #livenessProbe: 26 | # failureThreshold: 8 27 | # httpGet: 28 | # host: 127.0.0.1 29 | # path: /healthz 30 | # port: 6443 31 | # scheme: HTTPS 32 | # initialDelaySeconds: 15 33 | # timeoutSeconds: 15 34 | name: k8s-keystone-auth 35 | resources: 36 | requests: 37 | cpu: 250m 38 | volumeMounts: 39 | - mountPath: /etc/kubernetes/pki 40 | name: k8s-certs 41 | readOnly: true 42 | - mountPath: /etc/ssl/certs 43 | name: ca-certs 44 | readOnly: true 45 | hostNetwork: true 46 | volumes: 47 | - hostPath: 48 | path: /etc/kubernetes/pki 49 | type: DirectoryOrCreate 50 | name: k8s-certs 51 | - hostPath: 52 | path: /etc/ssl/certs 53 | type: DirectoryOrCreate 54 | name: ca-certs 55 | status: {} 56 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed under the Apache License, Version 2.0 (the "License"); 3 | you may not use this file except in compliance with the License. 4 | You may obtain a copy of the License at 5 | 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software 9 | distributed under the License is distributed on an "AS IS" BASIS, 10 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | See the License for the specific language governing permissions and 12 | limitations under the License. 13 | */ 14 | 15 | package main 16 | 17 | import ( 18 | "flag" 19 | "log" 20 | "net/http" 21 | 22 | "github.com/dims/k8s-keystone-auth/pkg/authenticator/token/keystone" 23 | "github.com/dims/k8s-keystone-auth/pkg/identity/webhook" 24 | "k8s.io/apiserver/pkg/authentication/authenticator" 25 | "k8s.io/apiserver/pkg/authorization/authorizer" 26 | ) 27 | 28 | func webhookServer(authenticator authenticator.Token, authorizer authorizer.Authorizer) http.Handler { 29 | return &webhook.WebhookHandler{ 30 | Authenticator: authenticator, 31 | Authorizer: authorizer, 32 | } 33 | } 34 | 35 | var ( 36 | listenAddr string 37 | tlsCertFile string 38 | tlsPrivateKey string 39 | keystoneURL string 40 | keystoneCaFile string 41 | policyFile string 42 | ) 43 | 44 | func main() { 45 | flag.StringVar(&listenAddr, "listen", "localhost:8443", "
: to listen on") 46 | flag.StringVar(&tlsCertFile, "tls-cert-file", "", "File containing the default x509 Certificate for HTTPS.") 47 | flag.StringVar(&tlsPrivateKey, "tls-private-key-file", "", "File containing the default x509 private key matching --tls-cert-file.") 48 | flag.StringVar(&keystoneURL, "keystone-url", "http://localhost/identity/v3/", "URL for the OpenStack Keystone API") 49 | flag.StringVar(&keystoneCaFile, "keystone-ca-file", "", "File containing the certificate authority for Keystone Service.") 50 | flag.StringVar(&policyFile, "keystone-policy-file", "", "File containing the policy.") 51 | flag.Parse() 52 | 53 | if tlsCertFile == "" || tlsPrivateKey == "" { 54 | log.Fatal("Please specify --tls-cert-file and --tls-private-key-file arguments.") 55 | } 56 | if policyFile == "" { 57 | log.Printf("Argument --keystone-policy-file missing. Only keystone authentication will work. Use RBAC for authorization.") 58 | } 59 | 60 | authentication_handler, err := keystone.NewKeystoneAuthenticator(keystoneURL, keystoneCaFile) 61 | if err != nil { 62 | log.Fatal(err.Error()) 63 | } 64 | 65 | authorization_handler, err := keystone.NewKeystoneAuthorizer(keystoneURL, keystoneCaFile, policyFile) 66 | if err != nil { 67 | log.Fatal(err.Error()) 68 | } 69 | 70 | http.Handle("/webhook", webhookServer(authentication_handler, authorization_handler)) 71 | log.Println("Starting webhook..") 72 | log.Fatal( 73 | http.ListenAndServeTLS(":8443", 74 | tlsCertFile, 75 | tlsPrivateKey, 76 | nil)) 77 | } 78 | -------------------------------------------------------------------------------- /pkg/authenticator/token/keystone/authenticator.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 The Kubernetes Authors. 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 keystone 18 | 19 | import ( 20 | "encoding/json" 21 | "errors" 22 | "io/ioutil" 23 | 24 | "github.com/golang/glog" 25 | "github.com/gophercloud/gophercloud" 26 | 27 | "k8s.io/apiserver/pkg/authentication/user" 28 | ) 29 | 30 | // KeystoneAuthenticator contacts openstack keystone to validate user's token passed in the request. 31 | // The keystone endpoint is passed during apiserver startup 32 | type KeystoneAuthenticator struct { 33 | authURL string 34 | client *gophercloud.ServiceClient 35 | } 36 | 37 | // AuthenticatePassword checks the token via Keystone call 38 | func (keystoneAuthenticator *KeystoneAuthenticator) AuthenticateToken(token string) (user.Info, bool, error) { 39 | 40 | // We can use the Keystone GET /v3/auth/tokens API to validate the token 41 | // and get information about the user as well 42 | // http://git.openstack.org/cgit/openstack/keystone/tree/api-ref/source/v3/authenticate-v3.inc#n437 43 | // https://developer.openstack.org/api-ref/identity/v3/?expanded=validate-and-show-information-for-token-detail 44 | request_opts := gophercloud.RequestOpts{ 45 | MoreHeaders: map[string]string{ 46 | "X-Auth-Token": token, 47 | "X-Subject-Token": token, 48 | }, 49 | } 50 | url := keystoneAuthenticator.client.ServiceURL("auth", "tokens") 51 | response, err := keystoneAuthenticator.client.Request("GET", url, &request_opts) 52 | if err != nil { 53 | glog.V(4).Info("Failed: bad response from API call: %v", err) 54 | return nil, false, errors.New("Failed to authenticate") 55 | } 56 | 57 | defer response.Body.Close() 58 | bodyBytes, err := ioutil.ReadAll(response.Body) 59 | if err != nil { 60 | glog.V(4).Infof("Cannot get HTTP response body from keystone token validate: %v", err) 61 | return nil, false, errors.New("Failed to authenticate") 62 | } 63 | 64 | obj := struct { 65 | Token struct { 66 | User struct { 67 | Id string `json:"id"` 68 | Name string `json:"name"` 69 | } `json:"user"` 70 | Project struct { 71 | Id string `json:"id"` 72 | Name string `json:"name"` 73 | } `json:"project"` 74 | Roles []struct { 75 | Name string `json:"name"` 76 | } `json:"roles"` 77 | } `json:"token"` 78 | }{} 79 | 80 | err = json.Unmarshal(bodyBytes, &obj) 81 | if err != nil { 82 | glog.V(4).Infof("Cannot unmarshal response: %v", err) 83 | return nil, false, errors.New("Failed to authenticate") 84 | } 85 | 86 | var roles []string 87 | if obj.Token.Roles != nil && len(obj.Token.Roles) > 0 { 88 | roles = make([]string, len(obj.Token.Roles)) 89 | for i := 0; i < len(obj.Token.Roles); i++ { 90 | roles[i] = obj.Token.Roles[i].Name 91 | } 92 | } else { 93 | roles = make([]string, 0) 94 | } 95 | 96 | extra := map[string][]string{ 97 | "alpha.kubernetes.io/identity/roles": roles, 98 | "alpha.kubernetes.io/identity/project/id": []string{obj.Token.Project.Id}, 99 | "alpha.kubernetes.io/identity/project/name": []string{obj.Token.Project.Name}, 100 | } 101 | 102 | authenticated_user := &user.DefaultInfo{ 103 | Name: obj.Token.User.Name, 104 | UID: obj.Token.User.Id, 105 | Groups: []string{obj.Token.Project.Id}, 106 | Extra: extra, 107 | } 108 | 109 | return authenticated_user, true, nil 110 | } 111 | -------------------------------------------------------------------------------- /pkg/authenticator/token/keystone/authorizer.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 The Kubernetes Authors. 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 keystone 18 | 19 | import ( 20 | "log" 21 | "github.com/gophercloud/gophercloud" 22 | 23 | "k8s.io/apiserver/pkg/authorization/authorizer" 24 | "encoding/json" 25 | ) 26 | 27 | type KeystoneAuthorizer struct { 28 | authURL string 29 | client *gophercloud.ServiceClient 30 | pl policyList 31 | } 32 | 33 | func resourceMatches(p Policy, a authorizer.Attributes) bool { 34 | if p.NonResourceSpec != nil && p.ResourceSpec != nil { 35 | log.Printf("Policy has both resource and nonresource sections. skipping : %#v", p) 36 | return false 37 | } 38 | 39 | if p.ResourceSpec.Verb == "" { 40 | log.Printf("verb is empty. skipping : %#v", p) 41 | return false 42 | } 43 | 44 | if p.ResourceSpec.APIGroup == nil || p.ResourceSpec.Namespace == nil || p.ResourceSpec.Resource == nil { 45 | log.Printf("version/namespace/resource should be all set. skipping : %#v", p) 46 | return false 47 | } 48 | 49 | if p.ResourceSpec.Verb == "*" || p.ResourceSpec.Verb == a.GetVerb() { 50 | if *p.ResourceSpec.APIGroup == "*" || *p.ResourceSpec.APIGroup == a.GetAPIGroup() { 51 | if *p.ResourceSpec.Namespace == "*" || *p.ResourceSpec.Namespace == a.GetNamespace() { 52 | if *p.ResourceSpec.Resource == "*" || *p.ResourceSpec.Resource == a.GetResource() { 53 | allowed := match(p.Match, a) 54 | if allowed { 55 | output, err := json.MarshalIndent(p, "", " ") 56 | if err == nil { 57 | log.Printf(">>>> matched rule : %s", string(output)) 58 | } 59 | return true 60 | } 61 | } 62 | } 63 | } 64 | } 65 | return false 66 | } 67 | 68 | func nonResourceMatches(p Policy, a authorizer.Attributes) bool { 69 | if p.NonResourceSpec.Verb == "" { 70 | log.Printf("verb is empty. skipping : %#v", p) 71 | return false 72 | } 73 | 74 | if p.NonResourceSpec.NonResourcePath == nil { 75 | log.Printf("path should be set. skipping : %#v", p) 76 | return false 77 | } 78 | 79 | if p.NonResourceSpec.Verb == "*" || p.NonResourceSpec.Verb == a.GetVerb() { 80 | if *p.NonResourceSpec.NonResourcePath == "*" || *p.NonResourceSpec.NonResourcePath == a.GetPath() { 81 | if *p.ResourceSpec.Resource == "*" || *p.ResourceSpec.Resource == a.GetResource() { 82 | allowed := match(p.Match, a) 83 | if allowed { 84 | output, err := json.MarshalIndent(p, "", " ") 85 | if err == nil { 86 | log.Printf(">>>> matched rule : %s", string(output)) 87 | } 88 | return true 89 | } 90 | } 91 | } 92 | } 93 | return false 94 | } 95 | 96 | func match(match Match, attributes authorizer.Attributes) bool { 97 | user := attributes.GetUser() 98 | if match.Type == "group" { 99 | for _, group := range user.GetGroups() { 100 | if match.Value == "*" || group == match.Value { 101 | return true 102 | } 103 | } 104 | } else if match.Type == "user" { 105 | if match.Value == "*" || user.GetName() == match.Value || user.GetUID() == match.Value { 106 | return true 107 | } 108 | } else if match.Type == "project" { 109 | if val, ok := user.GetExtra()["alpha.kubernetes.io/identity/project/id"]; ok { 110 | if ok { 111 | for _, item := range val { 112 | if match.Value == "*" || item == match.Value { 113 | return true 114 | } 115 | } 116 | 117 | } 118 | } 119 | if val, ok := user.GetExtra()["alpha.kubernetes.io/identity/project/name"]; ok { 120 | if ok { 121 | for _, item := range val { 122 | if match.Value == "*" || item == match.Value { 123 | return true 124 | } 125 | } 126 | 127 | } 128 | } 129 | } else if match.Type == "role" { 130 | if val, ok := user.GetExtra()["alpha.kubernetes.io/identity/roles"]; ok { 131 | if ok { 132 | for _, item := range val { 133 | if match.Value == "*" || item == match.Value { 134 | return true 135 | } 136 | } 137 | 138 | } 139 | } 140 | } else { 141 | log.Printf("unknown type %s. skipping.", match.Type) 142 | } 143 | return false 144 | } 145 | 146 | func (KeystoneAuthorizer *KeystoneAuthorizer) Authorize(a authorizer.Attributes) (authorized bool, reason string, err error) { 147 | log.Printf("Authorizing user : %#v\n", a.GetUser()) 148 | for _, p := range KeystoneAuthorizer.pl { 149 | if p.NonResourceSpec != nil && p.ResourceSpec != nil { 150 | log.Printf("Policy has both resource and nonresource sections. skipping : %#v", p) 151 | continue 152 | } 153 | if p.ResourceSpec != nil { 154 | if resourceMatches(*p, a) { 155 | return true, "", nil 156 | } 157 | } else if p.NonResourceSpec != nil { 158 | if nonResourceMatches(*p, a) { 159 | return true, "", nil 160 | } 161 | } 162 | } 163 | return false, "No policy matched.", nil 164 | } 165 | -------------------------------------------------------------------------------- /pkg/authenticator/token/keystone/keystone.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2017 The Kubernetes Authors. 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 keystone 18 | 19 | import ( 20 | "crypto/tls" 21 | "errors" 22 | "encoding/json" 23 | "fmt" 24 | "net/http" 25 | "log" 26 | //"strings" 27 | 28 | "github.com/golang/glog" 29 | "github.com/gophercloud/gophercloud" 30 | "github.com/gophercloud/gophercloud/openstack" 31 | "github.com/gophercloud/gophercloud/openstack/utils" 32 | 33 | netutil "k8s.io/apimachinery/pkg/util/net" 34 | certutil "k8s.io/client-go/util/cert" 35 | ) 36 | 37 | // Construct a Keystone v3 client, bail out if we cannot find the v3 API endpoint 38 | func createIdentityV3Provider(options gophercloud.AuthOptions, transport http.RoundTripper) (*gophercloud.ProviderClient, error) { 39 | client, err := openstack.NewClient(options.IdentityEndpoint) 40 | if err != nil { 41 | return nil, err 42 | } 43 | 44 | if transport != nil { 45 | client.HTTPClient.Transport = transport 46 | } 47 | 48 | versions := []*utils.Version{ 49 | {ID: "v3.0", Priority: 30, Suffix: "/v3/"}, 50 | } 51 | chosen, _, err := utils.ChooseVersion(client, versions) 52 | if err != nil { 53 | return nil, fmt.Errorf("Unable to find identity API v3 version : %v", err) 54 | } 55 | 56 | switch chosen.ID { 57 | case "v3.0": 58 | return client, nil 59 | default: 60 | // The switch statement must be out of date from the versions list. 61 | return nil, fmt.Errorf("Unsupported identity API version: %s", chosen.ID) 62 | } 63 | } 64 | 65 | func createKeystoneClient(authURL string, caFile string) (*gophercloud.ServiceClient, error) { 66 | // FIXME: Enable this check later 67 | //if !strings.HasPrefix(authURL, "https") { 68 | // return nil, errors.New("Auth URL should be secure and start with https") 69 | //} 70 | var transport http.RoundTripper 71 | if authURL == "" { 72 | return nil, errors.New("Auth URL is empty") 73 | } 74 | if caFile != "" { 75 | roots, err := certutil.NewPool(caFile) 76 | if err != nil { 77 | return nil, err 78 | } 79 | config := &tls.Config{} 80 | config.RootCAs = roots 81 | transport = netutil.SetOldTransportDefaults(&http.Transport{TLSClientConfig: config}) 82 | } 83 | opts := gophercloud.AuthOptions{IdentityEndpoint: authURL} 84 | provider, err := createIdentityV3Provider(opts, transport) 85 | if err != nil { 86 | return nil, err 87 | } 88 | 89 | // We should use the V3 API 90 | client, err := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}) 91 | if err != nil { 92 | glog.V(4).Info("Failed: Unable to use keystone v3 identity service: %v", err) 93 | return nil, errors.New("Failed to authenticate") 94 | } 95 | if err != nil { 96 | glog.V(4).Info("Failed: Starting openstack authenticate client: %v", err) 97 | return nil, errors.New("Failed to authenticate") 98 | } 99 | 100 | // Make sure we look under /v3 for resources 101 | client.IdentityBase = client.IdentityEndpoint 102 | client.Endpoint = client.IdentityEndpoint 103 | return client, nil 104 | } 105 | 106 | // NewKeystoneAuthenticator returns a password authenticator that validates credentials using openstack keystone 107 | func NewKeystoneAuthenticator(authURL string, caFile string) (*KeystoneAuthenticator, error) { 108 | client, err := createKeystoneClient(authURL, caFile) 109 | if err != nil { 110 | return nil, err 111 | } 112 | 113 | return &KeystoneAuthenticator{authURL: authURL, client: client}, nil 114 | } 115 | 116 | func NewKeystoneAuthorizer(authURL string, caFile string, policyFile string) (*KeystoneAuthorizer, error) { 117 | client, err := createKeystoneClient(authURL, caFile) 118 | if err != nil { 119 | return nil, err 120 | } 121 | 122 | policyList, err := NewFromFile(policyFile) 123 | output, err := json.MarshalIndent(policyList, "", " ") 124 | if err == nil { 125 | log.Printf(">>> Policy %s", string(output)) 126 | } else { 127 | log.Fatalf(">>> Error %#v", err) 128 | } 129 | 130 | return &KeystoneAuthorizer{authURL: authURL, client: client, pl:policyList}, nil 131 | } -------------------------------------------------------------------------------- /pkg/authenticator/token/keystone/policy.go: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2015 The Kubernetes Authors. 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 keystone 18 | 19 | import ( 20 | "os" 21 | "bufio" 22 | "encoding/json" 23 | ) 24 | 25 | type Policy struct { 26 | ResourceSpec *ResourcePolicySpec `json:"resource,omitempty"` 27 | 28 | NonResourceSpec *NonResourcePolicySpec `json:"nonresource,omitempty"` 29 | 30 | // One of user:foo, project:bar, role:baz, group:qux 31 | Match Match `json:"match"` 32 | } 33 | 34 | type Match struct { 35 | Type string `json:"type"` 36 | 37 | Value string `json:"value"` 38 | } 39 | 40 | type ResourcePolicySpec struct { 41 | // Kubernetes resource API verb like: get, list, watch, create, update, delete, proxy. 42 | // "*" matches all verbs. 43 | Verb string `json:"verb"` 44 | 45 | // Resource is the name of a resource. 46 | // "*" matches all resources 47 | Resource *string `json:"resource"` 48 | 49 | // APIGroup is the name of an API group. 50 | // "*" matches all API groups 51 | APIGroup *string `json:"version"` 52 | 53 | // Namespace is the name of a namespace. 54 | // "*" matches all namespaces (including unnamespaced requests) 55 | Namespace *string `json:"namespace"` 56 | } 57 | 58 | type NonResourcePolicySpec struct { 59 | // Kubernetes resource API verb like: get, list, watch, create, update, delete, proxy. 60 | // "*" matches all verbs. 61 | Verb string `json:"verb"` 62 | 63 | // NonResourcePath matches non-resource request paths. 64 | // "*" matches all paths 65 | // "/foo/*" matches all subpaths of foo 66 | NonResourcePath *string `json:"path"` 67 | } 68 | 69 | type policyList []*Policy 70 | 71 | func NewFromFile(path string) (policyList, error) { 72 | file, err := os.Open(path) 73 | if err != nil { 74 | return nil, err 75 | } 76 | defer file.Close() 77 | 78 | var data policyList 79 | 80 | reader := bufio.NewReader(file) 81 | decoder := json.NewDecoder(reader) 82 | err = decoder.Decode(&data) 83 | if err != nil { 84 | return nil, err 85 | } 86 | return data, nil 87 | } 88 | -------------------------------------------------------------------------------- /pkg/identity/webhook/handlers.go: -------------------------------------------------------------------------------- 1 | /* 2 | Licensed under the Apache License, Version 2.0 (the "License"); 3 | you may not use this file except in compliance with the License. 4 | You may obtain a copy of the License at 5 | 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software 9 | distributed under the License is distributed on an "AS IS" BASIS, 10 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | See the License for the specific language governing permissions and 12 | limitations under the License. 13 | */ 14 | 15 | package webhook 16 | 17 | import ( 18 | "encoding/json" 19 | "fmt" 20 | "net/http" 21 | 22 | "k8s.io/apiserver/pkg/authentication/authenticator" 23 | "k8s.io/apiserver/pkg/authorization/authorizer" 24 | "k8s.io/apiserver/pkg/authentication/user" 25 | "log" 26 | ) 27 | 28 | type userInfo struct { 29 | Username string `json:"username"` 30 | UID string `json:"uid"` 31 | Groups []string `json:"groups"` 32 | Extra map[string][]string `json:"extra"` 33 | } 34 | type status struct { 35 | Authenticated bool `json:"authenticated"` 36 | User userInfo `json:"user"` 37 | } 38 | 39 | type WebhookHandler struct { 40 | Authenticator authenticator.Token 41 | Authorizer authorizer.Authorizer 42 | } 43 | 44 | func (h *WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 45 | var data map[string]interface{} 46 | decoder := json.NewDecoder(r.Body) 47 | defer r.Body.Close() 48 | err := decoder.Decode(&data) 49 | if err != nil { 50 | http.Error(w, err.Error(), http.StatusInternalServerError) 51 | return 52 | } 53 | 54 | var apiVersion = data["apiVersion"].(string) 55 | var kind = data["kind"].(string) 56 | 57 | if apiVersion != "authentication.k8s.io/v1beta1" && apiVersion != "authorization.k8s.io/v1beta1" { 58 | http.Error(w, fmt.Sprintf("unknown apiVersion %q", apiVersion), 59 | http.StatusBadRequest) 60 | return 61 | } 62 | if kind == "TokenReview" { 63 | var token = data["spec"].(map[string]interface{})["token"].(string) 64 | h.authenticateToken(w, r, token, data) 65 | } else if kind == "SubjectAccessReview" { 66 | h.authorizeToken(w, r, data) 67 | } else { 68 | http.Error(w, fmt.Sprintf("unknown kind/apiVersion %q %q", kind, apiVersion), 69 | http.StatusBadRequest) 70 | } 71 | } 72 | 73 | func (h *WebhookHandler) authenticateToken(w http.ResponseWriter, r *http.Request, token string, data map[string]interface{}) { 74 | //log.Printf(">>>> authenticateToken data : %#v\n", data) 75 | user, authenticated, err := h.Authenticator.AuthenticateToken(token) 76 | log.Printf("<<<< authenticateToken : %v, %v, %v\n", token, user, err) 77 | 78 | if !authenticated { 79 | var response status 80 | response.Authenticated = false 81 | data["status"] = response 82 | 83 | output, err := json.MarshalIndent(data, "", " ") 84 | if err != nil { 85 | http.Error(w, err.Error(), http.StatusBadRequest) 86 | return 87 | } 88 | w.Header().Set("Content-Type", "application/json") 89 | w.WriteHeader(http.StatusUnauthorized) 90 | w.Write(output) 91 | return 92 | } 93 | 94 | var info userInfo 95 | info.Username = user.GetName() 96 | info.UID = user.GetUID() 97 | info.Groups = user.GetGroups() 98 | info.Extra = user.GetExtra() 99 | 100 | var response status 101 | response.Authenticated = true 102 | response.User = info 103 | 104 | data["status"] = response 105 | 106 | output, err := json.MarshalIndent(data, "", " ") 107 | if err != nil { 108 | http.Error(w, err.Error(), http.StatusInternalServerError) 109 | return 110 | } 111 | w.Header().Set("Content-Type", "application/json") 112 | w.WriteHeader(http.StatusOK) 113 | w.Write(output) 114 | } 115 | 116 | func getField(data map[string]interface{}, name string) string { 117 | if v, ok := data[name]; ok { 118 | return v.(string) 119 | } 120 | return "" 121 | } 122 | 123 | func (h *WebhookHandler) authorizeToken(w http.ResponseWriter, r *http.Request, data map[string]interface{}) { 124 | output, err := json.MarshalIndent(data, "", " ") 125 | log.Printf(">>>> authorizeToken data : %s\n", string(output)) 126 | 127 | spec := data["spec"].(map[string]interface{}) 128 | 129 | username := spec["user"] 130 | usr := &user.DefaultInfo{ 131 | Name: username.(string), 132 | } 133 | attrs := authorizer.AttributesRecord{ 134 | User: usr, 135 | } 136 | 137 | groups := spec["group"].([]interface{}) 138 | for _, v := range groups { 139 | usr.Groups = append(usr.Groups, v.(string)) 140 | } 141 | if extras, ok := spec["extra"].(map[string]interface{}); ok { 142 | usr.Extra = make(map[string][]string, len(extras)) 143 | for key, value := range extras { 144 | for _,v := range value.([]interface{}) { 145 | if data, ok := usr.Extra[key] ; ok { 146 | usr.Extra[key] = append(data, v.(string)) 147 | } else { 148 | usr.Extra[key] = []string{v.(string)} 149 | } 150 | } 151 | } 152 | } 153 | 154 | if resourceAttributes, ok := spec["resourceAttributes"]; ok { 155 | v := resourceAttributes.(map[string]interface{}) 156 | attrs.ResourceRequest = true 157 | attrs.Verb = getField(v, "verb") 158 | attrs.Namespace = getField(v, "namespace") 159 | attrs.APIGroup = getField(v, "group") 160 | attrs.APIVersion = getField(v, "version") 161 | attrs.Resource = getField(v, "resource") 162 | attrs.Name = getField(v, "name") 163 | } else if nonResourceAttributes, ok := spec["nonResourceAttributes"]; ok { 164 | v := nonResourceAttributes.(map[string]interface{}) 165 | attrs.ResourceRequest = false 166 | attrs.Verb = getField(v, "verb") 167 | attrs.Path = getField(v, "path") 168 | } else { 169 | err := fmt.Errorf("Unable to find attributes") 170 | http.Error(w, err.Error(), http.StatusInternalServerError) 171 | return 172 | } 173 | 174 | allowed, reason, err := h.Authorizer.Authorize(attrs) 175 | log.Printf("<<<< authorizeToken : %v, %v, %v\n", allowed, reason, err) 176 | if err != nil { 177 | http.Error(w, reason, http.StatusInternalServerError) 178 | return 179 | } 180 | 181 | delete(data, "spec") 182 | data["status"] = map[string]interface{}{ 183 | "allowed": allowed, 184 | } 185 | output, err = json.MarshalIndent(data, "", " ") 186 | if err != nil { 187 | http.Error(w, err.Error(), http.StatusInternalServerError) 188 | return 189 | } 190 | w.Header().Set("Content-Type", "application/json") 191 | w.WriteHeader(http.StatusOK) 192 | w.Write(output) 193 | } 194 | -------------------------------------------------------------------------------- /tools/install-distro-packages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | 3 | BASE_DIR=$(cd $(dirname $BASH_SOURCE)/.. && pwd) 4 | 5 | # Local version to install bindep packages 6 | # Suitable for use for development 7 | 8 | function is_fedora { 9 | [ -f /usr/bin/yum ] && cat /etc/*release | grep -q -e "Fedora" 10 | } 11 | 12 | PACKAGES="" 13 | if ! which virtualenv; then 14 | PACKAGES="$PACKAGES virtualenv" 15 | fi 16 | if ! which make; then 17 | PACKAGES="$PACKAGES make" 18 | fi 19 | if [[ -n $PACKAGES ]]; then 20 | sudo apt-get -q --assume-yes install virtualenv 21 | fi 22 | 23 | # Check for bindep 24 | if ! which bindep; then 25 | pushd $BASE_DIR >/dev/null 26 | make bindep 27 | popd >/dev/null 28 | fi 29 | 30 | PACKAGES=$(make bindep || true) 31 | 32 | # inspired from project-config install-distro-packages.sh 33 | if apt-get -v >/dev/null 2>&1 ; then 34 | sudo apt-get -qq update 35 | sudo PATH=/usr/sbin:/sbin:$PATH DEBIAN_FRONTEND=noninteractive \ 36 | apt-get -q --option "Dpkg::Options::=--force-confold" \ 37 | --assume-yes install $PACKAGES 38 | elif emerge --version >/dev/null 2>&1 ; then 39 | sudo emerge -uDNq --jobs=4 @world 40 | sudo PATH=/usr/sbin:/sbin:$PATH emerge -q --jobs=4 $PACKAGES 41 | else 42 | is_fedora && YUM=dnf || YUM=yum 43 | sudo PATH=/usr/sbin:/sbin:$PATH $YUM install -y $PACKAGES 44 | fi 45 | -------------------------------------------------------------------------------- /tools/test-setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -xe 2 | # test-setup.sh - Install required stuffs 3 | # Used in both CI jobs and locally 4 | # 5 | # Install the following tools: 6 | # * glide 7 | 8 | # Get OS 9 | case $(uname -s) in 10 | Darwin) 11 | OS=darwin 12 | ;; 13 | Linux) 14 | if LSB_RELEASE=$(which lsb_release); then 15 | OS=$($LSB_RELEASE -s -c) 16 | else 17 | # No lsb-release, trya hack or two 18 | if which dpkg 1>/dev/null; then 19 | OS=debian 20 | elif which yum 1>/dev/null || which dnf 1>/dev/null; then 21 | OS=redhat 22 | else 23 | echo "Linux distro not yet supported" 24 | exit 1 25 | fi 26 | fi 27 | ;; 28 | *) 29 | echo "Unsupported OS" 30 | exit 1 31 | ;; 32 | esac 33 | 34 | case $OS in 35 | darwin) 36 | if which brew 1>/dev/null; then 37 | if ! which glide 1>/dev/null; then 38 | brew install glide 39 | fi 40 | else 41 | echo "Homebrew not found, install Glide from source?" 42 | fi 43 | ;; 44 | xenial) 45 | APT_GET="DEBIAN_FRONTEND=noninteractive \ 46 | apt-get -q --option "Dpkg::Options::=--force-confold" \ 47 | --assume-yes" 48 | if ! which add-apt-repository 1>/dev/null; then 49 | sudo $APT_GET install software-properties-common 50 | fi 51 | sudo add-apt-repository --yes ppa:longsleep/golang-backports 52 | sudo add-apt-repository --yes ppa:masterminds/glide 53 | sudo apt-get update && sudo $APT_GET install golang-go glide 54 | ;; 55 | esac 56 | --------------------------------------------------------------------------------