ACL, RBAC, ABAC authorization middleware for KubeSphere

casbin-kubesphere-auth

Casbin-kubesphere-auth is a plugin which apply several security authentication check on kubesphere via casbin. This plugin support the following function:

  • check whether it is legal to apply an operation on a k8s resource (e.g. perform a 'DELETE' operation on a certain deployment). Illegal request will be intercepted and rejected.
  • check whether the docker image you use on any pod/deployment is trusted. If not, request will be intercepted and rejected.

Functions above are implemented via admission webhook of k8s. Webhook service can be built as a docker file, and to support kubesphere better, this webhook service is also packed as a helm application, which can be uploaded to local kubesphere market and easily deployed.

You can use this plugin in kubesphere and a raw k8s.

Overview

Structure for this project:

  • casbin-kubesphere/ this folder is used for create a helm package.
  • k8sconfig/ this folder contains necessary yaml configuration files to deploy this webhook.
  • webhook/ this folder contains real code for webhook service. This folder also include a Dockerfile, which means the docker image of the service should be buit base on this folder.
    • webhook/casbinconfig contains casbin model and policies.
    • webhook/certificate contains certificates, private keys and public keys ONLY FOR EXAMPLE! You MUST NOT use this keys in any environment except test environment because EVERYONE CAN GET THE PRIVATE KEY IN THIS FOLDER. You should generate a set of your own keys via the method metioned by the tutorial below.
    • the others are go codes implementing this service.

Get Started: How to make this plugin work.

step 1: have k8s and kubesphere installed.

Install k8s: https://kubernetes.io/docs/setup/

Install kubesphere: https://kubesphere.com.cn/en/docs/quick-start/minimal-kubesphere-on-k8s/

(When install kubesphere, please choose 'minimal install on kubernets' instead of 'all in one for linux')

step 2 Enable the ValidatingWebhookConfiguration of your k8s

Briefly, you should add configuration '--enable-admission-plugins=NodeRestriction,MutatingAdmissionWebhook,ValidatingAdmissionWebhook' to k8s apiserver. Specific method to add this configuration varies depending on how you installed your k8s.

For example, if you use minikube, you are supposed to stop the minikube and restart it via the following command

minikube start --extra-config=apiserver.enable-admission-plugins=NodeRestriction,MutatingAdmissionWebhook,ValidatingAdmissionWebhook

Or if you used kubeadm to install the k8s, perhaps you need to add '--enable-admission-plugins=NodeRestriction,MutatingAdmissionWebhook,ValidatingAdmissionWebhook' line to the proper position of your api-server configuration file, which is usually under /etc/kubernetes/manifests.

Or perhaps you may be able to use 'kube-apiserver' directly ......

You may find more information from k8s doc. See https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/

Generate a set of certificate and private keys.

K8s requires that any webhook for k8s must use https, not http.

In this step, we shall generate a self-made CA, and use this CA to sign a self-signed certificate for your webhook. If you already have a certificate signed by a real CA, you can skip this step.

AN EXAMPLE of the output of this step now exists in webhook/certificate. BUT YOU MUST NOT USE IT directly because private key is also exposed in this folder, and a leaked private key makes your connection insecure.

Generate the private key for the fake CA

openssl genrsa -des3 -out ca.key 2048

Remove the password protection of the private key.

openssl rsa -in ca.key -out ca.key

Generate a private key for the webhook server and remove the password.

openssl genrsa -des3 -out server.key 2048
openssl rsa -in server.key  -out server.key 

Copy your system's openssl config file for temporary use. You can use openssl version -a to find out the location of the config file.

Find the [req] paragraph and add the following line: req_extensions = v3_req

Find the [v3_req] paragraph and add the following line: subjectAltName = @alt_names

Append following lines to the file:

[alt_names]
DNS.2=casbin-webhook-svc.default.svc

The 'casbin-webhook-svc.default.svc' should be replaced with the real service name of your own service (if you decide to modify the service name)

Use the modified config file to generate a certificate request file

openssl req -new -nodes -keyout server.key -out server.csr -config openssl.cnf 

Use the self-made CA to respond the request and sign the certificate

openssl x509 -req -days 3650 -in server.csr -out server.crt -CA ca.crt  -CAkey ca.key -CAcreateserial -extensions v3_req  -extfile openssl.cnf 

Reexamine yaml configs

To make the webhook into effort, we need to apply some yaml configs to k8s.

There are two yaml files in k8sconfig folder: webhook2.yaml and webhook3.yaml.

Applying webhook3.yaml will make you create a Deployment using the image of this plugin, and a Service which expose the plugin's ip and port.

Applying webhook2.yaml will make you tell k8s that which service admission webhooks services are, and when operation on specified resources are being applied, request should be sent to these services.

In webhook2.yaml you can see 'caBundle' attribute. This is the base64 encoded string of the certificate of the CA which signed the certificate for your webhook service, because k8s need to know the CA so that they can ensure the certificate your webhook provides is valid. For example, in this project, you can use 'base64 ca.crt' to get the string. It should be noted that anything like '\n', '\r' must be removed.

In webhook3.yaml, you can find that we used local docker image and set the image policy to 'never pull images from remote'. for the convenience of running this tiny project. If your corporation has a private docker repo, you should modify this part.

Reexamine casbin configs

casbin model and policies are stored in webhook/casbinconfig. There are 2 sets of model&policy. image_model.conf and image_policy controls whether a image is trusted, and permission_model.conf and permission_policy.csv control whether an operation on a resource can be applied

Reexamine webhook configs

In webhook/webhookconfig you can see config.json. Through this file, you can turn on or turn off a check rule, or modify the parmeter of casbin Enforcer. For example, you can modify them so that casbin's enforcer can use something like redis or mysql adapters so that ploicies can be modified dynamically. In this project we use files as policy to make an exapmle, which is not recommeded because if so, you have to shut down ther service and rebuild the docker image every time you make some changes to policy.

Pack this service into helm app

If you want to make this service became a infrastructure of your organization, you should ack this service into helm app, which is the only format the kubesphere app store supports.

If you haven't installed helm yet, see https://helm.sh/docs/ and have it installed.

Run

helm create casbin-kubesphere

You can see a folder 'casbin-kubesphere' is created. In this project, we have already runned this command and you can see there's already a folder casbin-kubesphere there.

Remove everything under casbin-kubesphere/templates except deployment.yaml. Combine the contents of k8sconfig/webhook2.yaml and k8sconfig/webhook3.yaml ans copy it into deployment.yaml

Wipe out everything in values.yaml

Run

helm package casbin-kubesphere

and you will see a file called 'casbin-kubesphere-0.1.0.tgz' created. This is the helm package for this plugin.

To install this plugin in k8s directly, run helm install casbin-kubesphere-0.1.0.tgz.

To upload this app to kubesphere so that everyone can use it, see https://kubesphere.com.cn/en/docs/workspace-administration/upload-helm-based-application/

Owner
Casbin
Casbin authorization library and the official middlewares
Casbin
Comments
  • feat: migrate policies from csv files into k8s crd resource

    feat: migrate policies from csv files into k8s crd resource

    1. convert all traditional csv-format policies into k8s crd format.
    2. modified all e2e test cases to use crd resources instead of csv policy
    3. implement some simple command-line script to automatically convert a csv policy file into k8s yaml configuration files
  • feat: migrate project into kubebuilder &  implement controller for model CRD

    feat: migrate project into kubebuilder & implement controller for model CRD

    This pr contains the following thing:

    1. migrate project into kubebuilder, which is recommended by kubesphere community
    2. implemented a controller for model CRD. It can automatically generate and apply the corresponding CRD definition of associated policy, when a model (which represent a rule) is applied.
  • feat: implement  crd adapter for casbin

    feat: implement crd adapter for casbin

    PR information

    feat: implement crd adapter for casbin Signed-off-by: Товарищ программист [email protected]

    Overview of This CRD Adapter

    This adapter saves policys into k8s cluster as CRD resource. More specifically, this adapter saves policies of one model into one kind of CRD resource, and saves one line of policy into one CRD object.

    Example of using CRD resource to save policy

    In this example , we will see how to convert a external_ip.csv into crd resource , which is able to be read and modified with this adapter. The external_ip.csv is given as follow.

    p,default,10.10.10.10,allow
    p,default,10.10.10.11, allow
    

    1. create a special namespace for saving policies.

    (It's because that in the definition of out CustomResourceDefinition for saving the policy, we declare the "scope: Namespaced")

    kubectl create policy
    

    The name"policy" can be modified as you wish.

    2. create the CustomResourceDefinition for saving the policy

    save the following content into a file named "crd_example.yaml"

    apiVersion: apiextensions.k8s.io/v1
    kind: CustomResourceDefinition
    metadata:
      ##EDIT HERE
      # name must match the spec fields below, and be in the form: <plural>.<group>
      name: type1policies.stable.example.com
      namespace: policy
    spec:
      # group name to use for REST API: /apis/<group>/<version>
      group: stable.example.com
      # list of versions supported by this CustomResourceDefinition
      versions:
        - name: v1
          # Each version can be enabled/disabled by Served flag.
          served: true
          # One and only one version must be marked as the storage version.
          storage: true
          schema:
            openAPIV3Schema:
              type: object
              properties:
                spec:
                  type: object
                  properties:
                    policyItem:
                      ##EDIT HERE
                      #this policyItem contains a line of policy. multiple lines of policy is forbiddened
                      type: string
                    
      # either Namespaced or Cluster
      scope: Namespaced
      names:
        ## EDIT HERE: change the plural,singular and kind of the name to your own policy name.
        # plural name to be used in the URL: /apis/<group>/<version>/<plural>
        plural: type1policies
        # singular name to be used as an alias on the CLI and for display
        singular: type1policy
        # kind is normally the CamelCased singular type. Your resource manifests use this.
        kind: Type1Policy
    

    change the names(type1policies...) as you wish.

    and execute the following command: kubectl --namespace=policy apply -f crd_example.yaml

    3. create several policy

    save the following content into a file named "type1policy_1.yaml"

    apiVersion: "stable.example.com/v1"
    kind: Type1Policy
    metadata:
      name: policy2
    spec:
      policyItem: |
        p,default,10.10.10.10, allow
    

    NOTE: this policyItem contains a single line of policy. multiple lines of policy is forbiddened!

    imitate the example above and create some objects according to the external_ip.csv, then execute kubectl --namespace=policy get type1policies, you will see

    NAME                               AGE
    policy1                            10m
    policy2                            10m
    

    each crd object is a line of policy.

    To be more precise, execute kubectl --namespace=policy get type1policies -o yaml you will see

    apiVersion: v1
    items:
    - apiVersion: stable.example.com/v1
      kind: Type1Policy
      metadata:
        creationTimestamp: "2021-09-13T06:04:08Z"
        generation: 2
        name: 50870b6a200ab49bd79be54cf7c685a1
        namespace: policy
        resourceVersion: "1735"
        uid: 34ab1d3a-1568-481a-9bd4-65025c70cd2e
      spec:
        policyItem: p,default,1.1.1.4,allow
    - apiVersion: stable.example.com/v1
      kind: Type1Policy
      metadata:
        annotations:
          kubectl.kubernetes.io/last-applied-configuration: |
            {"apiVersion":"stable.example.com/v1","kind":"Type1Policy","metadata":{"annotations":{},"name":"policy1","namespace":"policy"},"spec":{"policyItem":"p,default,10.10.10.10, allow\n"}}
        creationTimestamp: "2021-09-13T06:46:08Z"
        generation: 1
        name: policy1
        namespace: policy
        resourceVersion: "3496"
        uid: 8de5483e-8deb-4dfb-bfa8-39565c7bcacc
      spec:
        policyItem: |
          p,default,10.10.10.10, allow
    - apiVersion: stable.example.com/v1
      kind: Type1Policy
      metadata:
        annotations:
          kubectl.kubernetes.io/last-applied-configuration: |
            {"apiVersion":"stable.example.com/v1","kind":"Type1Policy","metadata":{"annotations":{},"name":"policy2","namespace":"policy"},"spec":{"policyItem":"p,default,10.10.10.11, allow\n"}}
        creationTimestamp: "2021-09-13T06:46:17Z"
        generation: 1
        name: policy2
        namespace: policy
        resourceVersion: "3503"
        uid: b2c55235-aa36-4967-9150-823f66b34c71
      spec:
        policyItem: |
          p,default,10.10.10.11, allow
    kind: List
    metadata:
      resourceVersion: ""
      selfLink: ""
    

    a crd object contains one line of policy, corresponding one line of external_ip.csv
    the whole crd resource contains all policy, corresponding to the external_ip.csv

  • feat: implement rule replica-limits&required_annotations&required-labels&required_probes

    feat: implement rule replica-limits&required_annotations&required-labels&required_probes

    feat: implement rule replica-limits&required_annotations&required-labels&required_probes

    Signed-off-by: Товарищ программист [email protected]

  • feat: implement rules 10&11&12

    feat: implement rules 10&11&12

    feat: implement rules 10&11&12

    This pr contains following contents:

    • ks-admission-general-external-ip
    • ks-admission-general-https-only
    • ks-admission-general-image-digests Signed-off-by: Товарищ программист [email protected]
  • feat: implement rules ks-admission-general-container-resource-ratios&k8s-admission-general-disallowed-tags

    feat: implement rules ks-admission-general-container-resource-ratios&k8s-admission-general-disallowed-tags

    feat: implement rules ks-admission-general-container-resource-ratios&k8s-admission-general-disallowed-tags

    This pr includes the following content:

    • implementation of rule ks-admission-general-container-resource-ratios
    • implemention of rule &k8s-admission-general-disallowed-tags
    • fix for a tiny bug in ks-admission-general-container-allowed-repos
    • formating some files, which was forgotten in previous pr
    • renaming some functions, for the convenience of further development

    Signed-off-by: Товарищ программист [email protected]

  • Update README.MD

    Update README.MD

    After starting to integrate this casbinkubesphere-authz, this plugin has been massively modified, and the readme.md is severely outdated. It's time to rewrite the README.MD to fulfill the document.

  • Integrate Casbin into KubeSphere

    Integrate Casbin into KubeSphere

    Proposal: https://github.com/kubesphere/kubesphere/issues/4139

    Roadmap:

    1. Add model and policy for ks-admission rules

    2. Support manage the model and policy through CRD

      • [x] Model and Policy CRD definition
      • [x] Policy CRD adaptor
      • [ ] Use Kubebuilder(Controller) to manager model and policy
    3. Other helpful features

      • [ ] Audit the enforce result.
    4. Configure CI and e2e test on Github Actions

      • [x] Configure CI
      • [ ] Push dev/release image on CI
      • [x] Add e2e test on CI
    5. Complete build/install tools, client SDK and docs

      • [ ] Support helm install
      • [ ] Provide Client SDK
      • [ ] Sample and Developer Docs
  • Add this kubesphere-authz middleware to the official list

    Add this kubesphere-authz middleware to the official list

    We have several options to integrate this repo into the kubesphere ecosystem, like code integration, listing in the 3rd-party authorization middleware list, etc. See how we did it for apisix middleware: https://github.com/casbin-lua/apisix-authz/issues/5 . apisix-authz has already integrated its code into apisix's main trunk. I think this is a very good example.

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Jan 4, 2023
Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Authorization and authentication. Learning go by writing a simple authentication and authorization service.

Aug 5, 2022
BK-IAM is a centralized permission management service provided by The Tencent BlueKing; based on ABAC

(English Documents Available) Overview 蓝鲸权限中心(BK-IAM)是蓝鲸智云提供的集中权限管理服务,支持基于蓝鲸开发框架的SaaS和企业第三方系统的权限控制接入,以及支持细粒度的权限管理。 架构设计 代码目录 Features 蓝鲸权限中心是基于 ABAC 强

Nov 16, 2022
goRBAC provides a lightweight role-based access control (RBAC) implementation in Golang.

goRBAC goRBAC provides a lightweight role-based access control implementation in Golang. For the purposes of this package: * an identity has one or mo

Dec 29, 2022
Minimalistic RBAC package for Go applications

RBAC Overview RBAC is a package that makes it easy to implement Role Based Access Control (RBAC) models in Go applications. Download To download this

Oct 25, 2022
Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发
Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发

go-web-mini Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发: http

Dec 25, 2022
YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等

YSHOP-GO 后台管理系统 项目简介 YSHOP-GO基于当前流行技术组合的前后端RBAC管理系统:Go1.15.x+Beego2.x+Jwt+Redis+Mysql8+Vue 的前后端分离系统,权限控制采用 RBAC,支持数据字典与数据权限管理,支持动态路由等 体验地址: https://go

Dec 30, 2022
RBAC scaffolding based on Gin + Gorm+ Casbin + Wire
RBAC scaffolding based on Gin + Gorm+ Casbin + Wire

Gin Admin 基于 GIN + GORM + CASBIN + WIRE 实现的RBAC权限管理脚手架,目的是提供一套轻量的中后台开发框架,方便、快速的完成业务需求的开发。 特性 遵循 RESTful API 设计规范 & 基于接口的编程规范 基于 GIN 框架,提供了丰富的中间件支持(JWT

Dec 28, 2022
基于 Echo + Gorm + Casbin + Uber-FX 实现的 RBAC 权限管理脚手架,致力于提供一套尽可能轻量且优雅的中后台解决方案。
基于 Echo + Gorm + Casbin + Uber-FX 实现的 RBAC 权限管理脚手架,致力于提供一套尽可能轻量且优雅的中后台解决方案。

Echo-Admin 基于 Echo + Gorm + Casbin + Uber-FX 实现的 RBAC 权限管理脚手架,致力于提供一套尽可能轻量且优雅的中后台解决方案。 English | 简体中文 特性 遵循 RESTful API 设计规范 基于 Echo API 框架,提供了丰富的中间件支

Dec 14, 2022
Role Based Access Control (RBAC) with database persistence

Authority Role Based Access Control (RBAC) Go package with database persistence Install First get authority go get github.com/harranali/authority Next

Dec 8, 2022
Generate K8s RBAC policies based on e2e test runs

rbac-audit Have you ever wondered whether your controller actually needs all the permissions it has granted to it? Wonder no more! This repo contains

Aug 2, 2021
Incomplete CRUD/RBAC service meant to be a practice for Go

Incomplete CRUD / RBAC Service in Go The repository name means nothing. But your task is to complete this repository on your own to be a functional CR

Nov 9, 2021
A practical RBAC implementation

RBAC This project contains a practical RBAC implementation by Golang. It's actually a demo now. With in-memory storage, no database or file storage ye

Dec 1, 2021
Open source RBAC library. Associate users with roles and permissions.
Open source RBAC library. Associate users with roles and permissions.

ℹ️ This package is completely open source and works independently from Permify. Associate users with roles and permissions This package allows you to

Jan 2, 2023
⛩️ Go library for protecting HTTP handlers with authorization bearer token.

G8, pronounced Gate, is a simple Go library for protecting HTTP handlers with tokens. Tired of constantly re-implementing a security layer for each

Nov 14, 2022
Go library providing in-memory implementation of an OAuth2 Authorization Server / OpenID Provider

dispans Go library providing in-memory implementation of an OAuth2 Authorization Server / OpenID Provider. The name comes from the Swedish word dispen

Dec 22, 2021
an stateless OpenID Connect authorization server that mints ID Tokens from Webauthn challenges

Webauthn-oidc Webauthn-oidc is a very minimal OIDC authorization server that only supports webauthn for authentication. This can be used to bootstrap

Nov 6, 2022
policy - the CLI for managing authorization policies
 policy - the CLI for managing authorization policies

policy - the CLI for managing authorization policies The policy CLI is a tool for building, versioning and publishing your authorization policies. It

Dec 30, 2022
telegram authorization in telegram without using a widget

TGAH - telegram Authorization Example of authorization in telegram without using a widget Installation go get -d github.com/tioffs/tgah@master Setti

Jun 6, 2022