OPA-Gatekeeper实验:对特定用户的更新时间窗口做限制
实验目的
OPA-Gatekeeper可以在Kubernetes 中,通过策略来实现一些额外的管理、安全方面的限制,例如:限制特定用户在 Namespace 中的行为权限
本次实验将在test命名空间内对开发人员的更新操作提供时间窗口限制。
说明:
在自建的k8s集群实验成功。
在rancher2.4.4中创建失败,原因是rego语法解析错误,已经提交到官方论坛,尚未解决。
实现思路
为了方便管理,开发人员将使用统一用户deploy,
然后在k8s中添加基于角色的访问控制(RBAC),即使用role和rolebinding,限制deploy在test命名空间内的资源权限。
最后使用gatekeeper做时间窗口限制。
| Namespace | role | user |
|---|---|---|
| test | manager | deploy |
实现步骤
1 创建用户
- 创建私钥
openssl genrsa -out deploy.key 2048
- 创建csr(证书签名请求)文件
openssl req -new -key deploy.key -out deploy.csr -subj "/CN=deploy/O=MGM"
- 通过集群的CA证书和deploy的csr文件,来为deploy颁发证书
我的CA证书是在/etc/kubernetes/pki/目录下
openssl x509 -req -in deploy.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out deploy.crt -days 3650
- 为用户配置credentials认证环境和context上下文环境
kubectl config set-credentials deploy --client-certificate=deploy.crt --client-key=deploy.key
kubectl config get-users
kubectl config set-context deploy --cluster=kubernetes --namespace=test --user=deploy
kubectl config get-contexts
- 测试切换用户环境
kubectl config use-context deploy
kubectl config use-context kubernetes-admin@kubernetes
2 创建角色
在RBAC中,角色有两种——普通角色(Role)和集群角色(ClusterRole),ClusterRole是特殊的Role:
- Role属于某个命名空间,而ClusterRole属于整个集群,其中包括所有的命名空间
- ClusterRole能够授予集群范围的权限,比如node资源的管理,比如非资源类型的接口请求(如"/health"),比如可以请求全命名空间的资源(通过指定 --all-namespaces)
这里要在test命名空间内创建一个权限小的普通角色
kind: Role
metadata:
namespace: test
name: manager
rules:
- apiGroups: ["apps"]
resources: ["*"]
verbs: ["*"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["*"]
kubectl apply -f role.yaml
kubectl get role -n test
以上涉及的api资源查看方式:
kubectl api-resources|grep "apps/v1"
kubectl api-resources|grep " v1"
3 将前面的角色和用户绑定
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: manager-binding
namespace: test
subjects:
- kind: User
name: deploy
roleRef:
kind: Role
name: manager
apiGroup: "rbac.authorization.k8s.io"
kubectl apply -f Rolebinding.yaml
kubectl get rolebinding -n test
测试deploy用户创建pod
kubectl get pods -n test --context=deploy
kubectl run nginx --image=nginx:latest -n default --context=deploy
kubectl run nginx --image=nginx:latest -n test --context=deploy
5 安装gatekeeper
wget https://raw.githubusercontent.com/open-policy-agent/gatekeeper/master/deploy/gatekeeper.yaml
kubectl apply -f gatekeeper.yaml
检查
kubectl get ConstraintTemplate #等待出现 No resources found 才表示成功
kubectl get crd #CustomResourceDefinitions #只有当AGE不为<Invalid>而是一个时间时,才表示这个资源对象可用
ConstraintTemplate 约束模板
在定义约束之前,必须先定义一个 ConstraintTemplate (相当于创造了自定义的api-resources类型)
它主要内容描述的是 执行约束的Rego语句 和 约束的模式。
约束的模式允许admin对约束行为进行微调,就像对一个函数传参。
spec由两部分组成:
- crd:CustomResourceDefinition 自定义资源
- targets:一组target,是以 rego 代码块为主体
实验
以下模板提供了时间窗口限制(每周一、三,晚23:30至次日06:00)
apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
name: updatelimits
spec:
crd:
spec:
names:
kind: UpdateLimits
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package updatelimit
###TIME check
nanosec := time.now_ns()
wday := time.weekday(nanosec)
dhour :=time.clock(nanosec)[0]
dmin :=time.clock(nanosec)[1]
###userAuth Check
#ns := input.review.object.metadata.namespace
uname := input.review.userInfo.username
# 23:30至次日06:00,要考虑 k8s 的8h时差
timeOK {
dhour==15
dmin>=30
}
timeOK {
dhour>15
dhour<22
}
weekdayOK{
wday == "Wednesday"
}
weekdayOK{
wday == "Monday"
}
#三种不同情况下的限制提示
violation[{"msg": msgX}] {
uname != "deploy"
msgX = "\n>>>>>>>>>>>>>>>>>>>>>>>>>> Changes are only allowed for USER [deploy].\n"
}
violation[{"msg": msgX}] {
uname == "deploy"
not weekdayOK
msgX = "\n%%%%%%%%%%%%%%%%%%%%%%%%%% Changes are only allowed on [Monday] or [Wednesday].\n"
}
violation[{"msg": msgX}] {
uname == "deploy"
weekdayOK
not timeOK
msgX = "\n************************** Changes are only allowed in [23:30-06:00].\n"
}
# kubectl apply -f constrainttemplateV1Beta1.yaml
# kubectl get ConstraintTemplate
# kubectl api-resources |grep gatekeeper
NAME SHORTNAMES APIVERSION NAMESPACED KIND
updatelimits constraints.gatekeeper.sh/v1beta1 false UpdateLimits
注意项
- spec.crd.spec.names.kind 小写后必须和 metadata.name 一致
- violation返回值是一个结构体切片:[{"msg": STRING}]
violation[{"msg": message}] {
message := ""
}
Constraint 约束条件
知识介绍(可以略过)
Constraint负责通知Gatekeeper,admin想要一个什么样的template
Constraint使用 K8sRequiredLabels 来约束上文中的模版,以便于确保 gatekeeper 标签被定义到所有namespace上
可认为是对某一个 ConstraintTemplate 的实例化,其中对 ConstraintTemplate 的未指定参数进行了具体的配置。
注意spec.match字段,它定义了 一个指定的约束 将要被应用到的 目标的范围
Note the match field, which defines the scope of objects to which a given constraint will be applied.
支持的匹配项目:
- kinds:接受一个对象列表,包含 apiGroups和 kinds,用来指定 约束将应用到的 对象组/种类的字段。如果指定了多个对象,只要满足其中一个就会被匹配
only one match is needed for the resource to be in scope. - 目标范围:允许 * ,Cluster 或者 Namespaced
此外还有:
- namespaces:指定ns列表
- excludedNamespaces:指定ns排除列表
- labelSelector
- namespaceSelector
注意:
如果定义了多个matcher,则匹配资源必须满足所有顶级matcher
空matcher匹配所有
namespaces, excludedNamespaces, 和 namespaceSelector 将会匹配上没有ns所属的资源,为了避免这种情况,注意指定Namespace范围。
实验
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: UpdateLimits
metadata:
name: updatelimit-for-test
spec:
match:
namespaces: ["test"]
kinds:
- apiGroups: ["apps"]
kinds:
- "Deployment"
- "DaemonSet"
- "StatefulSet"
部署
kubectl apply -f ConstraintV1Beta1.yaml
kubectl get constraint
测试deployment
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
name: nginx
namespace: depl
spec:
replicas: 0
selector:
matchLabels:
io/os: linux
template:
metadata:
labels:
io/os: linux
spec:
containers:
- image: nginx:latest
name: nginx
shell脚本:
#!/bin/sh
deployFile=nginx-deployment.yaml
echo
echo
echo
kubectl config use-context deploy
kubectl apply -f ${deployFile} -n depl && kubectl delete -f ${deployFile} -n depl
echo -e "\n\n\n"
kubectl config use-context kubernetes-admin@kubernetes
实验结果:
root@master:~/OPAtest/MyTest# ./test.sh
Switched to context "deploy".
Error from server ([updatelimit-for-depl]
%%%%%%%%%%%%%%%%%%%%%%%%%% Changes are only allowed on [Monday] or [Wednesday].
): error when creating "nginx-deployment.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [updatelimit-for-depl]
%%%%%%%%%%%%%%%%%%%%%%%%%% Changes are only allowed on [Monday] or [Wednesday].
参考资料:
- 用户与角色绑定:https://zhuanlan.zhihu.com/p/43237959
- Input对象:https://www.openpolicyagent.org/docs/latest/kubernetes-primer/#input-document
- 时间函数:https://www.openpolicyagent.org/docs/latest/policy-reference/#time
- rego实验室:https://play.openpolicyagent.org/
OPA-Gatekeeper实验:对特定用户的更新时间窗口做限制的更多相关文章
- 关于iOS特定设别推送(特定用户推送)【原】
在这里,我就不哆嗦如何制作推送证书之类的了,网上一搜一大堆. 我们现在很多开发者的推送,就是集成第三方的推送SDK,然后通过第三方的推送平台帮我们进行推送.其实,这种推送(如JPush),一般只能广播 ...
- PHP处理大数据量老用户头像更新的操作--解决数据量大超时的问题
/** * @title 老用户头像更新--每3秒调用一次接口,每次更新10条数据 * @example user/createHeadPicForOldUser? * @method GET * @ ...
- day108:MoFang:首页检测用户是否登录&在项目中使用MongoDB&用户页面更新用户信息&交易密码界面实现
目录 1.首页页面也要检测用户是否登录 2.在flask中使用MongoDB 3.用户页面更新用户信息 4.交易密码界面/密码修改界面/昵称修改界面初始化 5.交易密码实现 1.首页页面也要检测用户是 ...
- 【】二次通告--Apache log4j-2.15.0-rc1版本存在绕过风险,请广大用户尽快更新版本
[转载自360众测] Apache Log4j2是一个基于Java的日志记录工具.该工具重写了Log4j框架,并且引入了大量丰富的特性.我们可以控制日志信息输送的目的地为控制台.文件.GUI组件等,通 ...
- 通过自定义特性,使用EF6拦截器完成创建人、创建时间、更新人、更新时间的统一赋值(使用数据库服务器时间赋值,接上一篇)
目录: 前言 设计(完成扩展) 实现效果 扩展设计方案 扩展后代码结构 集思广益(问题) 前言: 在上一篇文章我写了如何重建IDbCommandTreeInterceptor来实现创建人.创建时间.更 ...
- 自动化部署与统一安装升级 - 类ansible工具 udeploy0.3版本发布 (更新时间2014-12-24)
下载地址: unifyDeploy0.1版本 unifyDeploy0.2版本 unifyDeploy0.3版本 (更新时间2014-07-25) 自动化部署与统一安装升级,适用于多资 ...
- MYSQL 更新时间自动同步与创建时间默认值共存问题
本文作者:苏生米沿 本文地址:http://blog.csdn.net/sushengmiyan/article/details/50326259 在使用SQL的时候,希望在更新数据的时候自动填充更新 ...
- Dynamics CRM 插件Plugin中获取和更新时间字段值的准确转换
前面两篇介绍了后台代码通过组织服务获取更新时间字段.窗体javascript通过Odata获取更新时间字段,最后篇来实验下在插件中的获取和更新时间字段是否需要时制的转化,为何说是最后篇呢,因为在CRM ...
- mysql自动更新时间
ALTER TABLE sys_user MODIFY COLUMN update_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDAT ...
随机推荐
- MyCat的快速搭建
1. 概述 老话说的好:一个好汉三个帮,一个人再聪明.再有本事,也要借助他人的力量,才能成功. 言归正传,今天我们来聊聊 MyCat的快速搭建. 2. 场景介绍 服务器A IP:192.168.1.2 ...
- 2021-06-27 & 2021-06-28 集训题解
西克 题目传送门 Description Solution 跟 2021年省选A卷D2T1 一模一样,懒得讲了 不过这个题似乎有点卡空间,所以卡不过去 Code #include <bits/s ...
- JVM详解(五)——运行时数据区-方法区
一.概述 1.介绍 <Java虚拟机规范>中明确说明:尽管所有的方法区在逻辑上属于堆的一部分,但一些简单的实现可能不会选择去进行垃圾收集或者进行压缩.但对于HotSpot JVM而言,方法 ...
- Visual Studio 安装 C++
Visual Studio 安装 C++
- CQL和SQL的CRUD操作比较
数据进行CRUD操作时,CQL语句和SQL语句的异同之处. 1.建表 2.CRUD语句比较 3.总结 1.建表 在此之前先分别创建两张表,插入数据,用来测试然后进行比较 在SQL数据库里面创建表 在C ...
- 搬运2:早期写的探究printf
目录: 1. 关于printf格式化输出 2. printf的一般形式 3. 转换说明 4. 格式化输出的意义 5. 转换说明修饰符 6. 修饰符中的标记 7. printf的返回值 ps:共3250 ...
- Machine learning (8-Neural Networks: Representation)
1.Non-linear Hypotheses 2.Neurons and the Brain 从某种意义上来说,如果我们能找出大脑的学习算法,然后在计算机上执行大脑学习算法或与之相似的算法,也许这将 ...
- 深入理解 Linux的进程,线程,PID,LWP,TID,TGID
转载:https://www.linuxidc.com/Linux/2019-03/157819.htm 在Linux的top和ps命令中,默认看到最多的是pid (process ID),也许你也能 ...
- Python import Queue ImportError: No module named 'Queue'
python3 中引入Queue 会报出这个问题 python3 中这样引入 import queue python2 中这样引入 import Queue 为了兼容 可以这样 import sys ...
- word-break leetcoder C++
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separa ...