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 ...
随机推荐
- Django+Nginx+Uwsgi(全网最全步骤工作原理流程与部署历程)
一.必要前提 1.1 准备知识 django 一个基于python的开源web框架,请确保自己熟悉它的框架目录结构. uWSGI 一个基于自有的uwsgi协议.wsgi协议和http服务协议的web网 ...
- 基于go语言学习工厂模式
工厂模式 简单工厂模式(Simple Factory) 定义 优点 缺点 适用范围 代码实现 工厂方法模式(Factory Method) 定义 优点 缺点 适用范围 代码实现 抽象工厂模式(Abst ...
- 从零入门 Serverless | Serverless 应用如何管理日志 & 持久化数据
作者 | 竞霄 阿里巴巴开发工程师 本文整理自<Serverless 技术公开课>,关注"Serverless"公众号,回复"入门",即可获取 Se ...
- linux启动redis命令
首先进入到/usr/local/bin目录下(因为你redis安装的目录绝大多数都在这里) root@xxxx:/usr/local/bin#:redis-server wangconfig/redi ...
- 洛谷2408不同字串个数/SPOJ 694/705 (后缀数组SA)
真是一个三倍经验好题啊. 我们来观察这个题目,首先如果直接整体计算,怕是不太好计算. 首先,我们可以将每个子串都看成一个后缀的的前缀.那我们就可以考虑一个一个后缀来计算了. 为了方便起见,我们选择按照 ...
- 初探JavaScript PDF blob转换为Word docx方法
PDF转WORD为什么是历史难题 PDF 转Word 是一个非常非常普遍的需求,可谓人人忌危,为什么如此普遍的需求,却如此难行呢,还得看为什么会有这样的一个需求: PDF文档遵循iOS32000的规范 ...
- UML快速概述 - All you need to know about UML
UML 是统一建模语言的缩写,就像使用一组图表来可视化软件建模的蓝图(或设计计划).它不仅可以让您彻底评估整个概念,还可以确保团队中的每个人都在同一页面上. UML 图可以组织成两个不同的组. 结 ...
- 技术博客——微信小程序UI的设计与美化
技术博客--微信小程序UI的设计与美化 在alpha阶段的开发过后,我们的小程序也上线了.看到自己努力之后的成果大家都很开心,但对比已有的表情包小程序,我们的界面还有很大的提升空间,许多的界面都是各个 ...
- 使用Mybatis的TypeHandler加解密数据
使用Mybatis的TypeHandler加解密数据 一.背景 二.解决方案 三.需求 四.实现思路 1.编写一个实体类,凡是此实体类的数据都表示需要加解密的 2.编写一个加解密的`TypeHandl ...
- SpringBoot整合多个RabbitMQ
一.背景 最近项目中需要用到了RabbitMQ来监听消息队列,监听的消息队列的 虚拟主机(virtualHost)和队列名(queueName)是不一致的,但是接收到的消息格式相同的.而且可能还存 ...