限制条件模板库
借助限制条件模板,您可以定义限制条件的工作原理,但可以将定义限制条件的细节委托给具有主题专业知识的个人或群组。除了分离关注点之外,这还将限制条件的逻辑与其定义分离。
所有限制条件都包含一个 match
部分,该部分定义限制条件应用于的对象。如需详细了解如何配置该部分,请参阅限制条件匹配部分。
并非所有限制条件模板都适用于所有版本的 Policy Controller、Config Sync 和 Config Controller,模板可能会因版本而异。访问以下链接可对受支持的各版本中的限制条件进行比较:
指向本页面受支持版本的链接
为确保您获得完整支持,我们建议您使用受支持的 Policy Controller 版本中的限制条件模板。
为了帮助您了解限制条件模板的工作原理,每个模板都包含了一个示例限制条件和一个违反该限制条件的资源。
AllowedServicePortName
要求服务端口名称具有指定列表中的前缀。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AllowedServicePortName
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# prefixes <array>: Prefixes of allowed service port names.
prefixes:
- <string>
示例
port-name-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AllowedServicePortName metadata: name: port-name-constraint spec: enforcementAction: deny match: kinds: - apiGroups: - "" kinds: - Service parameters: prefixes: - http- - http2- - grpc- - mongo- - redis- - tcp-
允许
apiVersion: v1 kind: Service metadata: labels: app: helloworld name: port-name-http spec: ports: - name: http-helloport port: 5000 selector: app: helloworld
不允许
apiVersion: v1 kind: Service metadata: labels: app: helloworld name: port-name-tcp spec: ports: - name: foo-helloport port: 5000 selector: app: helloworld
apiVersion: v1 kind: Service metadata: labels: app: helloworld name: port-name-bad spec: ports: - name: helloport port: 5000 selector: app: helloworld
AsmAuthzPolicyDefaultDeny
强制执行网格级层的默认拒绝 AuthorizationPolicy。请参阅 https://istio.io/latest/docs/ops/best-practices/security/#use-default-deny-patterns。 注意:此限制条件是参照限制条件。如需了解详情,请参阅启用参照限制条件。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmAuthzPolicyDefaultDeny
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# rootNamespace <string>: Anthos Service Mesh root namespace, default value
# is "istio-system" if not specified.
rootNamespace: <string>
# strictnessLevel <string>: Level of AuthorizationPolicy strictness.
# Allowed Values: Low, High
strictnessLevel: <string>
示例
asm-authz-policy-default-deny-with-input-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: istio-system strictnessLevel: High
允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: istio-system strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: default-deny-no-action namespace: istio-system spec: null
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: istio-system strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: default-deny-with-action namespace: istio-system spec: action: ALLOW
不允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: istio-system strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: not-default-deny namespace: istio-system spec: action: DENY rules: - to: - operation: notMethods: - GET - POST
asm-authz-policy-default-deny-no-input-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High
允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: default-deny-no-action namespace: istio-system spec: null
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: default-deny-with-action namespace: istio-system spec: action: ALLOW
不允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDefaultDeny metadata: name: asm-authz-policy-default-deny-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: not-default-deny namespace: istio-system spec: action: DENY rules: - to: - operation: notMethods: - GET - POST
AsmAuthzPolicyDisallowedPrefix
要求 Istio AuthorizationPolicy
规则中的主账号和命名空间不包含指定列表中的前缀。
https://istio.io/latest/docs/reference/config/security/authorization-policy/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmAuthzPolicyDisallowedPrefix
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# disallowedNamespacePrefixes <array>: Disallowed prefixes for namespaces.
disallowedNamespacePrefixes:
- <string>
# disallowedPrincipalPrefixes <array>: Disallowed prefixes for principals.
disallowedPrincipalPrefixes:
- <string>
示例
asm-authz-policy-disallowed-prefix-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyDisallowedPrefix metadata: name: asm-authz-policy-disallowed-prefix-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy parameters: disallowedNamespacePrefixes: - bad-ns-prefix - worse-ns-prefix disallowedPrincipalPrefixes: - bad-principal-prefix - worse-principal-prefix
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: valid-authz-policy spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - test selector: matchLabels: app: httpbin
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-source-principal spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/worse-principal-prefix-sleep - source: namespaces: - test selector: matchLabels: app: httpbin
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-source-namespace spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - bad-ns-prefix-test selector: matchLabels: app: httpbin
AsmAuthzPolicyEnforceSourcePrincipals
要求 Istio AuthorizationPolicy 的“from”字段(如有定义)必须包含设置为“*”以外内容的来源主账号。 https://istio.io/latest/docs/reference/config/security/authorization-policy/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmAuthzPolicyEnforceSourcePrincipals
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
asm-authz-policy-enforce-source-principals-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyEnforceSourcePrincipals metadata: name: asm-authz-policy-enforce-source-principals-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: valid-authz-policy spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: no-source-principals spec: rules: - from: - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-wildcard spec: rules: - from: - source: principals: - '*' - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-contains-wildcard spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - '*' - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin
AsmAuthzPolicyNormalization
强制执行 AuthorizationPolicy 标准化。请参阅 https://istio.io/latest/docs/reference/config/security/normalization/。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmAuthzPolicyNormalization
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
asm-authz-policy-normalization-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicyNormalization metadata: name: asm-authz-policy-normalization-sample spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: good-authz-policy spec: action: ALLOW rules: - to: - operation: methods: - GET paths: - /test/foo - when: - key: source.ip values: - 10.1.2.3 - 10.2.0.0/16 - key: request.headers[User-Agent] values: - Mozilla/* selector: matchLabels: app: httpbin
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-method-lowercase spec: action: ALLOW rules: - to: - operation: methods: - get selector: matchLabels: app: httpbin
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-request-header-whitespace spec: action: ALLOW rules: - to: - operation: methods: - GET - when: - key: source.ip values: - 10.1.2.3 - 10.2.0.0/16 - key: request.headers[User-Ag ent] values: - Mozilla/* selector: matchLabels: app: httpbin
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: path-unnormalized spec: action: ALLOW rules: - to: - operation: methods: - GET paths: - /test\/foo - when: - key: source.ip values: - 10.1.2.3 - 10.2.0.0/16 - key: request.headers[User-Agent] values: - Mozilla/* selector: matchLabels: app: httpbin
AsmAuthzPolicySafePattern
强制执行 AuthorizationPolicy 安全模式。请参阅 https://istio.io/latest/docs/ops/best-practices/security/#safer-authorization-policy-patterns。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmAuthzPolicySafePattern
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# strictnessLevel <string>: Level of AuthorizationPolicy strictness.
# Allowed Values: Low, High
strictnessLevel: <string>
示例
asm-authz-policy-safe-pattern-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmAuthzPolicySafePattern metadata: name: asm-authz-policy-safe-pattern-sample spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy parameters: strictnessLevel: High
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: good-authz-policy-istio-ingress spec: action: ALLOW rules: - to: - operation: hosts: - test.com - test.com:* methods: - GET selector: matchLabels: istio: ingressgateway
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: good-authz-policy-asm-ingress spec: action: ALLOW rules: - to: - operation: hosts: - test.com - test.com:* methods: - GET selector: matchLabels: asm: ingressgateway
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: hosts-on-noningress spec: action: ALLOW rules: - to: - operation: hosts: - test.com - test.com:* methods: - GET
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: invalid-hosts spec: action: ALLOW rules: - to: - operation: hosts: - test.com methods: - GET selector: matchLabels: istio: ingressgateway
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: allow-negative-match spec: action: ALLOW rules: - to: - operation: hosts: - test.com - test.com:* notMethods: - GET selector: matchLabels: istio: ingressgateway
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: deny-positive-match spec: action: DENY rules: - to: - operation: hosts: - test.com - test.com:* methods: - GET selector: matchLabels: istio: ingressgateway
AsmIngressgatewayLabel
仅在 ingressgateway pod 上强制执行 istio ingressgateway 标签使用。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmIngressgatewayLabel
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
asm-ingressgateway-label-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmIngressgatewayLabel metadata: name: asm-ingressgateway-label-sample spec: enforcementAction: dryrun match: kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: sleep istio: istio name: sleep spec: containers: - image: curlimages/curl name: sleep - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
apiVersion: v1 kind: Pod metadata: labels: app: istio-ingressgateway istio: ingressgateway name: istio-ingressgateway spec: containers: - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
apiVersion: v1 kind: Pod metadata: labels: app: asm-ingressgateway asm: ingressgateway name: asm-ingressgateway spec: containers: - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
不允许
apiVersion: v1 kind: Pod metadata: labels: app: sleep istio: ingressgateway name: sleep spec: containers: - image: curlimages/curl name: sleep
apiVersion: v1 kind: Pod metadata: labels: app: sleep asm: ingressgateway name: sleep spec: containers: - image: curlimages/curl name: sleep
apiVersion: v1 kind: Pod metadata: labels: app: sleep istio: ingressgateway name: sleep spec: containers: - image: curlimages/curl name: sleep - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
AsmPeerAuthnMeshStrictMtls
强制执行网格级层的严格 mtls PeerAuthentication。请参阅 https://istio.io/latest/docs/ops/best-practices/security/#mutual-tls。 注意:此限制条件是参照限制条件。如需了解详情,请参阅启用参照限制条件。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmPeerAuthnMeshStrictMtls
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# rootNamespace <string>: Anthos Service Mesh root namespace, default value
# is "istio-system" if not specified.
rootNamespace: <string>
# strictnessLevel <string>: Level of PeerAuthentication strictness.
# Allowed Values: Low, High
strictnessLevel: <string>
示例
asm-peer-authn-mesh-strict-mtls-with-input-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: asm-root strictnessLevel: High
允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: asm-root strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mesh-strict-mtls namespace: asm-root spec: mtls: mode: STRICT
不允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-with-input-constraint spec: enforcementAction: dryrun parameters: rootNamespace: asm-root strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mesh-permissive-mtls namespace: asm-root spec: mtls: mode: PERMISSIVE
asm-peer-authn-mesh-strict-mtls-no-input-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High
允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mesh-strict-mtls namespace: istio-system spec: mtls: mode: STRICT
不允许
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnMeshStrictMtls metadata: name: asm-peer-authn-mesh-strict-mtls-no-input-constraint spec: enforcementAction: dryrun parameters: strictnessLevel: High --- # Referential Data apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mesh-permissive-mtls namespace: istio-system spec: mtls: mode: PERMISSIVE
AsmPeerAuthnStrictMtls
强制要求所有 PeerAuthentication 均不得覆盖严格 mtls。请参阅 https://istio.io/latest/docs/ops/best-practices/security/#mutual-tls。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmPeerAuthnStrictMtls
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# strictnessLevel <string>: Level of PeerAuthentication strictness.
# Allowed Values: Low, High
strictnessLevel: <string>
示例
asm-peer-authn-strict-mtls-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmPeerAuthnStrictMtls metadata: name: asm-peer-authn-strict-mtls-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - PeerAuthentication parameters: strictnessLevel: High
允许
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: valid-strict-mtls-pa namespace: foo spec: mtls: mode: UNSET portLevelMtls: "80": mode: UNSET "443": mode: STRICT selector: matchLabels: app: bar
不允许
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: invalid-permissive-mtls-pa namespace: foo spec: mtls: mode: PERMISSIVE portLevelMtls: "80": mode: UNSET "443": mode: STRICT selector: matchLabels: app: bar
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: invalid-port-disable-mtls-pa namespace: foo spec: mtls: mode: UNSET portLevelMtls: "80": mode: DISABLE "443": mode: STRICT selector: matchLabels: app: bar
AsmRequestAuthnProhibitedOutputHeaders
在 RequestAuthentication 中,强制执行 jwtRules.outPayloadToHeader
字段,使其不包含常见的 HTTP 请求标头或自定义禁止的标头。请参阅 https://istio.io/latest/docs/reference/config/security/jwt/#JWTRule。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmRequestAuthnProhibitedOutputHeaders
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# prohibitedHeaders <array>: User predefined prohibited headers.
prohibitedHeaders:
- <string>
示例
asm-request-authn-prohibited-output-headers-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmRequestAuthnProhibitedOutputHeaders metadata: name: asm-request-authn-prohibited-output-headers-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - RequestAuthentication parameters: prohibitedHeaders: - Bad-Header - X-Bad-Header
允许
apiVersion: security.istio.io/v1beta1 kind: RequestAuthentication metadata: name: valid-request-authn namespace: istio-system spec: jwtRules: - issuer: example.com outputPayloadToHeader: Good-Header selector: matchLabels: app: istio-ingressgateway
不允许
apiVersion: security.istio.io/v1beta1 kind: RequestAuthentication metadata: name: deny-predefined-output-header namespace: istio-system spec: jwtRules: - issuer: example.com outputPayloadToHeader: Host selector: matchLabels: app: istio-ingressgateway
apiVersion: security.istio.io/v1beta1 kind: RequestAuthentication metadata: name: deny-predefined-output-header namespace: istio-system spec: jwtRules: - issuer: example.com outputPayloadToHeader: X-Bad-Header selector: matchLabels: app: istio-ingressgateway
AsmSidecarInjection
强制要求 istio 代理 Sidecar 始终注入工作负载 pod。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: AsmSidecarInjection
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# strictnessLevel <string>: Level of sidecar injection strictness.
# Allowed Values: Low, High
strictnessLevel: <string>
示例
asm-sidecar-injection-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: AsmSidecarInjection metadata: name: asm-sidecar-injection-sample spec: enforcementAction: dryrun match: kinds: - apiGroups: - "" kinds: - Pod parameters: strictnessLevel: High
允许
apiVersion: v1 kind: Pod metadata: annotations: sidecar.istio.io/inject: "true" name: sleep spec: containers: - image: curlimages/curl name: sleep - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
apiVersion: v1 kind: Pod metadata: annotations: "false": "false" name: sleep spec: containers: - image: curlimages/curl name: sleep - image: gcr.io/gke-release/asm/proxyv2:release name: istio-proxy ports: - containerPort: 15090 name: http-envoy-prom protocol: TCP
不允许
apiVersion: v1 kind: Pod metadata: annotations: sidecar.istio.io/inject: "false" name: sleep spec: containers: - image: curlimages/curl name: sleep
DestinationRuleTLSEnabled
禁止为 Istio DestinationRules 中的所有主机和主机子集停用 TLS。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: DestinationRuleTLSEnabled
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
dr-tls-enabled
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: DestinationRuleTLSEnabled metadata: name: dr-tls-enabled spec: enforcementAction: dryrun match: kinds: - apiGroups: - networking.istio.io kinds: - DestinationRule
不允许
apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: dr-subset-tls-disable namespace: default spec: host: myservice subsets: - name: v1 trafficPolicy: tls: mode: DISABLE - name: v2 trafficPolicy: tls: mode: SIMPLE
apiVersion: networking.istio.io/v1alpha3 kind: DestinationRule metadata: name: dr-traffic-tls-disable namespace: default spec: host: myservice trafficPolicy: tls: mode: DISABLE
DisallowedAuthzPrefix
要求 Istio AuthorizationPolicy
规则中的主账号和命名空间不包含指定列表中的前缀。
https://istio.io/latest/docs/reference/config/security/authorization-policy/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: DisallowedAuthzPrefix
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# disallowedprefixes <array>: Disallowed prefixes of principals and
# namespaces.
disallowedprefixes:
- <string>
示例
disallowed-authz-prefix-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: DisallowedAuthzPrefix metadata: name: disallowed-authz-prefix-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy parameters: disallowedprefixes: - badprefix - reallybadprefix
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: good namespace: foo spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-source-principal namespace: foo spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/badprefix-sleep - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: bad-source-namespace namespace: foo spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - badprefix-test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
GCPStorageLocationConstraintV1
将允许的 StorageBucket Config Connector 资源的 locations
限制在限制条件中提供的位置列表内。exemptions
列表中的存储桶名称例外。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: GCPStorageLocationConstraintV1
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptions <array>: A list of bucket names that are exempt from this
# constraint.
exemptions:
- <string>
# locations <array>: A list of locations that a bucket is permitted to
# have.
locations:
- <string>
示例
singapore-and-jakarta-only
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: GCPStorageLocationConstraintV1 metadata: name: singapore-and-jakarta-only spec: enforcementAction: deny match: kinds: - apiGroups: - storage.cnrm.cloud.google.com kinds: - StorageBucket parameters: exemptions: - my_project_id_cloudbuild locations: - asia-southeast1 - asia-southeast2
允许
apiVersion: storage.cnrm.cloud.google.com/v1beta1 kind: StorageBucket metadata: name: bucket-in-permitted-location spec: location: asia-southeast1
不允许
apiVersion: storage.cnrm.cloud.google.com/v1beta1 kind: StorageBucket metadata: name: bucket-in-disallowed-location spec: location: us-central1
apiVersion: storage.cnrm.cloud.google.com/v1beta1 kind: StorageBucket metadata: name: bucket-without-specific-location spec: null
K8sAllowedRepos
要求容器映像以指定列表中的字符串开头。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# repos <array>: The list of prefixes a container image is allowed to have.
repos:
- <string>
示例
repo-is-openpolicyagent
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sAllowedRepos metadata: name: repo-is-openpolicyagent spec: match: kinds: - apiGroups: - "" kinds: - Pod namespaces: - default parameters: repos: - openpolicyagent/
允许
apiVersion: v1 kind: Pod metadata: name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 30Mi
不允许
apiVersion: v1 kind: Pod metadata: name: nginx-disallowed spec: containers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 30Mi
apiVersion: v1 kind: Pod metadata: name: nginx-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 30Mi initContainers: - image: nginx name: nginxinit resources: limits: cpu: 100m memory: 30Mi
apiVersion: v1 kind: Pod metadata: name: nginx-disallowed spec: containers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 30Mi initContainers: - image: nginx name: nginxinit resources: limits: cpu: 100m memory: 30Mi
apiVersion: v1 kind: Pod metadata: name: nginx-disallowed spec: containers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 30Mi ephemeralContainers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 30Mi initContainers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 30Mi
K8sBlockAllIngress
不允许创建 Ingress 对象(Ingress
、Gateway
和 Service
类型的 NodePort
和 LoadBalancer
)。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockAllIngress
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowList <array>: A list of regular expressions for the Ingress object
# names that are exempt from the constraint.
allowList:
- <string>
示例
block-all-ingress
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockAllIngress metadata: name: block-all-ingress spec: enforcementAction: dryrun parameters: allowList: - name1 - name2 - name3 - my-*
允许
apiVersion: v1 kind: Service metadata: name: my-service spec: ports: - port: 80 protocol: TCP targetPort: 9376 selector: app.kubernetes.io/name: MyApp type: LoadBalancer
apiVersion: v1 kind: Service metadata: name: allowed-clusterip-service-example spec: ports: - port: 80 protocol: TCP targetPort: 9376 selector: app.kubernetes.io/name: MyApp type: ClusterIP
不允许
apiVersion: v1 kind: Service metadata: name: disallowed-service-example spec: ports: - port: 80 protocol: TCP targetPort: 9376 selector: app.kubernetes.io/name: MyApp type: LoadBalancer
K8sBlockCreationWithDefaultServiceAccount
禁止使用默认服务账号创建资源。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockCreationWithDefaultServiceAccount
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-creation-with-default-serviceaccount
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockCreationWithDefaultServiceAccount metadata: name: block-creation-with-default-serviceaccount spec: enforcementAction: dryrun
允许
apiVersion: v1 kind: Namespace metadata: name: example-namespace
K8sBlockEndpointEditDefaultRole
默认情况下,许多 Kubernetes 安装都具有一个 system:aggregate-to-edit ClusterRole,但它并没有正确地限制修改端点的权限。此 ConstraintTemplate 可禁止 system:aggregate-to-edit ClusterRole 授予创建/修补/更新端点的权限。ClusterRole/system:aggregate-to-edit 不应该因 CVE-2021-25740 而允许端点修改权限,Endpoint 和 Endpointslice 权限允许跨命名空间转发,https://github.com/kubernetes/kubernetes/issues/103675
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockEndpointEditDefaultRole
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-endpoint-edit-default-role
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockEndpointEditDefaultRole metadata: name: block-endpoint-edit-default-role spec: match: kinds: - apiGroups: - rbac.authorization.k8s.io kinds: - ClusterRole
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" labels: kubernetes.io/bootstrapping: rbac-defaults rbac.authorization.k8s.io/aggregate-to-edit: "true" name: system:aggregate-to-edit rules: - apiGroups: - "" resources: - pods/attach - pods/exec - pods/portforward - pods/proxy - secrets - services/proxy verbs: - get - list - watch - apiGroups: - "" resources: - serviceaccounts verbs: - impersonate - apiGroups: - "" resources: - pods - pods/attach - pods/exec - pods/portforward - pods/proxy verbs: - create - delete - deletecollection - patch - update - apiGroups: - "" resources: - configmaps - persistentvolumeclaims - replicationcontrollers - replicationcontrollers/scale - secrets - serviceaccounts - services - services/proxy verbs: - create - delete - deletecollection - patch - update - apiGroups: - apps resources: - daemonsets - deployments - deployments/rollback - deployments/scale - replicasets - replicasets/scale - statefulsets - statefulsets/scale verbs: - create - delete - deletecollection - patch - update - apiGroups: - autoscaling resources: - horizontalpodautoscalers verbs: - create - delete - deletecollection - patch - update - apiGroups: - batch resources: - cronjobs - jobs verbs: - create - delete - deletecollection - patch - update - apiGroups: - extensions resources: - daemonsets - deployments - deployments/rollback - deployments/scale - ingresses - networkpolicies - replicasets - replicasets/scale - replicationcontrollers/scale verbs: - create - delete - deletecollection - patch - update - apiGroups: - policy resources: - poddisruptionbudgets verbs: - create - delete - deletecollection - patch - update - apiGroups: - networking.k8s.io resources: - ingresses - networkpolicies verbs: - create - delete - deletecollection - patch - update
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: "true" labels: kubernetes.io/bootstrapping: rbac-defaults rbac.authorization.k8s.io/aggregate-to-edit: "true" name: system:aggregate-to-edit rules: - apiGroups: - "" resources: - pods/attach - pods/exec - pods/portforward - pods/proxy - secrets - services/proxy verbs: - get - list - watch - apiGroups: - "" resources: - serviceaccounts verbs: - impersonate - apiGroups: - "" resources: - pods - pods/attach - pods/exec - pods/portforward - pods/proxy verbs: - create - delete - deletecollection - patch - update - apiGroups: - "" resources: - configmaps - persistentvolumeclaims - replicationcontrollers - replicationcontrollers/scale - secrets - serviceaccounts - services - services/proxy verbs: - create - delete - deletecollection - patch - update - apiGroups: - apps resources: - daemonsets - deployments - deployments/rollback - deployments/scale - endpoints - replicasets - replicasets/scale - statefulsets - statefulsets/scale verbs: - create - delete - deletecollection - patch - update
K8sBlockLoadBalancer
禁止类型为 LoadBalancer 的所有 Service。 https://kubernetes.io/docs/concepts/services-networking/service/#loadbalancer
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockLoadBalancer
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-load-balancer
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockLoadBalancer metadata: name: block-load-balancer spec: match: excludedNamespaces: - ingress-nginx-private - ingress-nginx-public kinds: - apiGroups: - "" kinds: - Service
允许
apiVersion: v1 kind: Service metadata: name: my-service-allowed spec: ports: - port: 80 targetPort: 80 type: ClusterIP
不允许
apiVersion: v1 kind: Service metadata: name: my-service-disallowed spec: ports: - nodePort: 30007 port: 80 targetPort: 80 type: LoadBalancer
K8sBlockNodePort
禁止类型为 NodePort 的所有 Service。 https://kubernetes.io/docs/concepts/services-networking/service/#nodeport
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockNodePort
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-node-port
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockNodePort metadata: name: block-node-port spec: match: kinds: - apiGroups: - "" kinds: - Service
不允许
apiVersion: v1 kind: Service metadata: name: my-service-disallowed spec: ports: - nodePort: 30007 port: 80 targetPort: 80 type: NodePort
K8sBlockObjectsOfType
不允许使用被禁止的类型的对象。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockObjectsOfType
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
forbiddenTypes:
- <string>
示例
block-secrets-of-type-basic-auth
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockObjectsOfType metadata: name: block-secrets-of-type-basic-auth spec: match: kinds: - apiGroups: - "" kinds: - Secret parameters: forbiddenTypes: - kubernetes.io/basic-auth
允许
apiVersion: v1 data: password: ZHVtbXlwYXNz username: ZHVtbXl1c2Vy kind: Secret metadata: name: credentials namespace: default type: Opaque
不允许
apiVersion: v1 data: password: YmFzaWMtcGFzc3dvcmQ= username: YmFzaWMtdXNlcm5hbWU= kind: Secret metadata: name: secret-basic-auth namespace: default type: kubernetes.io/basic-auth
K8sBlockProcessNamespaceSharing
通过将 shareProcessNamespace
设置为 true
来禁止 Pod 规范。这可避免 Pod 中的所有容器共享一个 PID 命名空间和访问彼此文件系统和内存这样的场景。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockProcessNamespaceSharing
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-process-namespace-sharing
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockProcessNamespaceSharing metadata: name: block-process-namespace-sharing
允许
apiVersion: v1 kind: Pod metadata: name: good-pod namespace: default spec: containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: name: bad-pod namespace: default spec: containers: - image: nginx name: nginx shareProcessNamespace: true
K8sBlockWildcardIngress
用户无法使用空白或通配符 (*) 主机名创建 Ingress,因为这会导致没有集群中其他服务的访问权限的用户能够拦截这些服务的流量。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockWildcardIngress
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
block-wildcard-ingress
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sBlockWildcardIngress metadata: name: block-wildcard-ingress spec: match: kinds: - apiGroups: - extensions - networking.k8s.io kinds: - Ingress
允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: non-wildcard-ingress spec: rules: - host: myservice.example.com http: paths: - backend: service: name: example port: number: 80 path: / pathType: Prefix
不允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: wildcard-ingress spec: rules: - host: "" http: paths: - backend: service: name: example port: number: 80 path: / pathType: Prefix
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: wildcard-ingress spec: rules: - http: paths: - backend: service: name: example port: number: 80 path: / pathType: Prefix
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: wildcard-ingress spec: rules: - host: '*.example.com' http: paths: - backend: service: name: example port: number: 80 path: / pathType: Prefix - host: valid.example.com http: paths: - backend: service: name: example port: number: 80 path: / pathType: Prefix
K8sContainerLimits
要求容器设置内存和 CPU 限制,并将该限值限制在指定的最大值范围内。 https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sContainerLimits
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# cpu <string>: The maximum allowed cpu limit on a Pod, exclusive.
cpu: <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# memory <string>: The maximum allowed memory limit on a Pod, exclusive.
memory: <string>
示例
container-must-have-limits
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sContainerLimits metadata: name: container-must-have-limits spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: cpu: 200m memory: 1Gi
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 1Gi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 2Gi
K8sContainerRatios
设置容器资源限制与请求的最大比例。 https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sContainerRatios
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# cpuRatio <string>: The maximum allowed ratio of `resources.limits.cpu` to
# `resources.requests.cpu` on a container. If not specified, equal to
# `ratio`.
cpuRatio: <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# ratio <string>: The maximum allowed ratio of `resources.limits` to
# `resources.requests` on a container.
ratio: <string>
示例
container-must-meet-ratio
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sContainerRatios metadata: name: container-must-meet-ratio spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: ratio: "2"
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 200m memory: 200Mi requests: cpu: 100m memory: 100Mi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 800m memory: 2Gi requests: cpu: 100m memory: 100Mi
container-must-meet-memory-and-cpu-ratio
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sContainerRatios metadata: name: container-must-meet-memory-and-cpu-ratio spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: cpuRatio: "10" ratio: "1"
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: "4" memory: 2Gi requests: cpu: "1" memory: 2Gi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: "4" memory: 2Gi requests: cpu: 100m memory: 2Gi
K8sContainerRequests
要求容器设置内存和 CPU 请求,并将请求限制在指定的最大值范围内。 https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sContainerRequests
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# cpu <string>: The maximum allowed cpu request on a Pod, exclusive.
cpu: <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# memory <string>: The maximum allowed memory request on a Pod, exclusive.
memory: <string>
示例
container-must-have-requests
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sContainerRequests metadata: name: container-must-have-requests spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: cpu: 200m memory: 1Gi
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: requests: cpu: 100m memory: 1Gi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: requests: cpu: 100m memory: 2Gi
K8sDisallowAnonymous
禁止将 ClusterRole 和 Role 资源关联到 system:anonymous user 和 system:unauthenticated group。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowAnonymous
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedRoles <array>: The list of ClusterRoles and Roles that may be
# associated with the `system:unauthenticated` group and `system:anonymous`
# user.
allowedRoles:
- <string>
示例
no-anonymous
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sDisallowAnonymous metadata: name: no-anonymous spec: match: kinds: - apiGroups: - rbac.authorization.k8s.io kinds: - ClusterRoleBinding - apiGroups: - rbac.authorization.k8s.io kinds: - RoleBinding parameters: allowedRoles: - cluster-role-1
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: cluster-role-binding-1 roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-role-1 subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:authenticated - apiGroup: rbac.authorization.k8s.io kind: Group name: system:unauthenticated
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: cluster-role-binding-2 roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-role-2 subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:authenticated - apiGroup: rbac.authorization.k8s.io kind: Group name: system:unauthenticated
K8sDisallowedRoleBindingSubjects
禁止将主题与 disallowedSubjects
匹配的 RoleBinding 或 ClusterRoleBinding 传递为参数。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowedRoleBindingSubjects
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# disallowedSubjects <array>: A list of subjects that cannot appear in a
# RoleBinding.
disallowedSubjects:
- # apiGroup <string>: The Kubernetes API group of the disallowed role
# binding subject. Currently ignored.
apiGroup: <string>
# kind <string>: The kind of the disallowed role binding subject.
kind: <string>
# name <string>: The name of the disallowed role binding subject.
name: <string>
示例
disallowed-rolebinding-subjects
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sDisallowedRoleBindingSubjects metadata: name: disallowed-rolebinding-subjects spec: parameters: disallowedSubjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:unauthenticated
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: good-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: my-role subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:authenticated
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: bad-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: my-role subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:unauthenticated
K8sDisallowedTags
要求容器映像的映像标记与指定列表中的映像标记不同。 https://kubernetes.io/docs/concepts/containers/images/#image-names
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDisallowedTags
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# tags <array>: Disallowed container image tags.
tags:
- <string>
示例
container-image-must-not-have-latest-tag
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sDisallowedTags metadata: name: container-image-must-not-have-latest-tag spec: match: kinds: - apiGroups: - "" kinds: - Pod namespaces: - default parameters: exemptImages: - openpolicyagent/opa-exp:latest - openpolicyagent/opa-exp2:latest tags: - latest
允许
apiVersion: v1 kind: Pod metadata: name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa
apiVersion: v1 kind: Pod metadata: name: opa-exempt-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa-exp:latest name: opa-exp - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/init:v1 name: opa-init - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa-exp2:latest name: opa-exp2
不允许
apiVersion: v1 kind: Pod metadata: name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa name: opa
apiVersion: v1 kind: Pod metadata: name: opa-disallowed-2 spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:latest name: opa
apiVersion: v1 kind: Pod metadata: name: opa-disallowed-ephemeral spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa ephemeralContainers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:latest name: opa
apiVersion: v1 kind: Pod metadata: name: opa-disallowed-3 spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa-exp:latest name: opa - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/init:latest name: opa-init - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa-exp2:latest name: opa-exp2 - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/monitor:latest name: opa-monitor
K8sEmptyDirHasSizeLimit
要求任何 emptyDir
卷都指定 sizeLimit
;您也可以视情况在限制条件中提供 maxSizeLimit
参数来指定许可的大小上限。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sEmptyDirHasSizeLimit
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptVolumesRegex <array>: Exempt Volume names as regex match.
exemptVolumesRegex:
- <string>
# maxSizeLimit <string>: When set, the declared size limit for each volume
# must be less than `maxSizeLimit`.
maxSizeLimit: <string>
示例
empty-dir-has-size-limit
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sEmptyDirHasSizeLimit metadata: name: empty-dir-has-size-limit spec: match: excludedNamespaces: - istio-system - kube-system - gatekeeper-system parameters: exemptVolumesRegex: - ^istio-[a-z]+$ maxSizeLimit: 4Gi
允许
apiVersion: v1 kind: Pod metadata: name: good-pod namespace: default spec: containers: - image: nginx name: nginx volumes: - emptyDir: sizeLimit: 2Gi name: good-pod-volume
apiVersion: v1 kind: Pod metadata: name: exempt-pod namespace: default spec: containers: - image: nginx name: nginx volumes: - emptyDir: {} name: istio-envoy
不允许
apiVersion: v1 kind: Pod metadata: name: bad-pod namespace: default spec: containers: - image: nginx name: nginx volumes: - emptyDir: {} name: bad-pod-volume
K8sEnforceCloudArmorBackendConfig
在 BackendConfig 资源上强制执行 Cloud Armor 配置
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sEnforceCloudArmorBackendConfig
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
enforce-cloudarmor-backendconfig
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sEnforceCloudArmorBackendConfig metadata: name: enforce-cloudarmor-backendconfig spec: enforcementAction: dryrun
允许
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: my-backendconfig namespace: examplenamespace spec: securityPolicy: name: example-security-policy
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: second-backendconfig spec: securityPolicy: name: my-security-policy
不允许
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: my-backendconfig namespace: examplenamespace spec: securityPolicy: name: null
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: my-backendconfig namespace: examplenamespace spec: securityPolicy: name: ""
apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: my-backendconfig spec: logging: enable: true sampleRate: 0.5
K8sEnforceConfigManagement
要求配置管理存在并运行。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sEnforceConfigManagement
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
enforce-config-management
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sEnforceConfigManagement metadata: name: enforce-config-management spec: enforcementAction: dryrun
允许
apiVersion: configmanagement.gke.io/v1 kind: ConfigManagement metadata: annotations: configmanagement.gke.io/managed-by-hub: "true" configmanagement.gke.io/update-time: "1663586155" name: config-management spec: binauthz: enabled: true clusterName: tec6ea817b5b4bb2-cluster enableMultiRepo: true git: proxy: {} syncRepo: git@test-git-server.config-management-system-test:/git-server/repos/sot.git hierarchyController: {} policyController: auditIntervalSeconds: 60 enabled: true monitoring: backends: - prometheus - cloudmonitoring mutation: {} referentialRulesEnabled: true templateLibraryInstalled: true status: configManagementVersion: v1.12.2-rc.2 healthy: true
不允许
apiVersion: configmanagement.gke.io/v1 kind: ConfigManagement metadata: annotations: configmanagement.gke.io/managed-by-hub: "true" configmanagement.gke.io/update-time: "1663586155" name: config-management spec: binauthz: enabled: true clusterName: tec6ea817b5b4bb2-cluster enableMultiRepo: true git: syncRepo: git@test-git-server.config-management-system-test:/git-server/repos/sot.git hierarchyController: {} policyController: auditIntervalSeconds: 60 enabled: true monitoring: backends: - prometheus - cloudmonitoring mutation: {} referentialRulesEnabled: true templateLibraryInstalled: true status: configManagementVersion: v1.12.2-rc.2
K8sExternalIPs
将 Service externalIP 限制为允许的 IP 地址列表。 https://kubernetes.io/docs/concepts/services-networking/service/#external-ips
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sExternalIPs
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedIPs <array>: An allow-list of external IP addresses.
allowedIPs:
- <string>
示例
external-ips
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sExternalIPs metadata: name: external-ips spec: match: kinds: - apiGroups: - "" kinds: - Service parameters: allowedIPs: - 203.0.113.0
允许
apiVersion: v1 kind: Service metadata: name: allowed-external-ip spec: externalIPs: - 203.0.113.0 ports: - name: http port: 80 protocol: TCP targetPort: 8080 selector: app: MyApp
不允许
apiVersion: v1 kind: Service metadata: name: disallowed-external-ip spec: externalIPs: - 1.1.1.1 ports: - name: http port: 80 protocol: TCP targetPort: 8080 selector: app: MyApp
K8sHttpsOnly
要求 Ingress 资源仅限于 HTTPS。 Ingress 资源必须包含 kubernetes.io/ingress.allow-http
注解且设置为 false
。默认情况下,有效的 TLS {} 配置是必需的,通过将 tlsOptional
参数设置为 true
可以将该配置设置为可选配置。https://kubernetes.io/docs/concepts/services-networking/ingress/#tls
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sHttpsOnly
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# tlsOptional <boolean>: When set to `true` the TLS {} is optional,
# defaults to false.
tlsOptional: <boolean>
示例
ingress-https-only
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sHttpsOnly metadata: name: ingress-https-only spec: match: kinds: - apiGroups: - extensions - networking.k8s.io kinds: - Ingress
允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: kubernetes.io/ingress.allow-http: "false" name: ingress-demo-allowed spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix tls: - {}
不允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-demo-disallowed spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix
ingress-https-only-tls-optional
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sHttpsOnly metadata: name: ingress-https-only-tls-optional spec: match: kinds: - apiGroups: - extensions - networking.k8s.io kinds: - Ingress parameters: tlsOptional: true
允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: kubernetes.io/ingress.allow-http: "false" name: ingress-demo-allowed-tls-optional spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix
不允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-demo-disallowed-tls-optional spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix
K8sImageDigests
要求容器映像包含摘要。 https://kubernetes.io/docs/concepts/containers/images/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sImageDigests
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
container-image-must-have-digest
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sImageDigests metadata: name: container-image-must-have-digest spec: match: kinds: - apiGroups: - "" kinds: - Pod namespaces: - default
允许
apiVersion: v1 kind: Pod metadata: name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2@sha256:04ff8fce2afd1a3bc26260348e5b290e8d945b1fad4b4c16d22834c2f3a1814a name: opa
不允许
apiVersion: v1 kind: Pod metadata: name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa initContainers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opainit
apiVersion: v1 kind: Pod metadata: name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa ephemeralContainers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa initContainers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opainit
K8sLocalStorageRequireSafeToEvict
要求使用本地存储空间(emptyDir
或 hostPath
)的 Pod 必须具有 "cluster-autoscaler.kubernetes.io/safe-to-evict": "true"
注释。集群自动扩缩器不会删除没有此注释的 Pod。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sLocalStorageRequireSafeToEvict
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
local-storage-require-safe-to-evict
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sLocalStorageRequireSafeToEvict metadata: name: local-storage-require-safe-to-evict spec: match: excludedNamespaces: - kube-system - istio-system - gatekeeper-system
允许
apiVersion: v1 kind: Pod metadata: annotations: cluster-autoscaler.kubernetes.io/safe-to-evict: "true" name: good-pod namespace: default spec: containers: - image: redis name: redis volumeMounts: - mountPath: /data/redis name: redis-storage volumes: - emptyDir: {} name: redis-storage
不允许
apiVersion: v1 kind: Pod metadata: name: bad-pod namespace: default spec: containers: - image: redis name: redis volumeMounts: - mountPath: /data/redis name: redis-storage volumes: - emptyDir: {} name: redis-storage
K8sMemoryRequestEqualsLimit
通过要求所有容器请求的内存与内存限制完全一致来提升 Pod 稳定性,让 Pod 绝不会处于内存用量超出所请求数量的状态。否则,如果节点上需要内存,Kubernetes 可能会终止请求额外内存的 Pod。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sMemoryRequestEqualsLimit
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptContainersRegex <array>: Exempt Container names as regex match.
exemptContainersRegex:
- <string>
示例
container-must-request-limit
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sMemoryRequestEqualsLimit metadata: name: container-must-request-limit spec: match: excludedNamespaces: - kube-system - resource-group-system - asm-system - istio-system - config-management-system - config-management-monitoring parameters: exemptContainersRegex: - ^istio-[a-z]+$
允许
apiVersion: v1 kind: Pod metadata: name: good-pod namespace: default spec: containers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 4Gi requests: cpu: 50m memory: 4Gi
apiVersion: v1 kind: Pod metadata: name: exempt-pod namespace: default spec: containers: - image: auto name: istio-proxy resources: limits: cpu: 100m memory: 4Gi requests: cpu: 50m memory: 2Gi
不允许
apiVersion: v1 kind: Pod metadata: name: bad-pod namespace: default spec: containers: - image: nginx name: nginx resources: limits: cpu: 100m memory: 4Gi requests: cpu: 50m memory: 2Gi
K8sNoEnvVarSecrets
禁止 Secret 用作 Pod 容器定义中的环境变量;相反,请在数据卷中使用装载的机密文件: https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNoEnvVarSecrets
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
no-secrets-as-env-vars-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sNoEnvVarSecrets metadata: name: no-secrets-as-env-vars-sample spec: enforcementAction: dryrun
允许
apiVersion: v1 kind: Pod metadata: name: allowed-example spec: containers: - image: redis name: test volumeMounts: - mountPath: /etc/test name: test readOnly: true volumes: - name: test secret: secretName: mysecret
不允许
apiVersion: v1 kind: Pod metadata: name: disallowed-example spec: containers: - env: - name: MY_PASSWORD valueFrom: secretKeyRef: key: password name: mysecret image: redis name: test
K8sNoExternalServices
禁止创建将工作负载公开给外部 IP 的已知资源。这包括 Istio 网关资源和 Kubernetes Ingress 资源。除非满足以下条件,否则 Kubernetes 服务也不允许创建:Google Cloud 中 LoadBalancer
类型的任何 Service 都必须具有 "cloud.google.com/load-balancer-type": "Internal"
注释。AWS 中 LoadBalancer
类型的任何 Service 都必须具有 service.beta.kubernetes.io/aws-load-balancer-internal: "true
注释。绑定到 Service 的任何“外部 IP”(即位于集群外部)都必须在提供给限制条件的内部 CIDR 范围内。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sNoExternalServices
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# cloudPlatform <string>: The hosting cloud platform. Only `GCP` and `AWS`
# are supported currently.
cloudPlatform: <string>
# internalCIDRs <array>: A list of CIDRs that are only accessible
# internally, for example: `10.3.27.0/24`. Which IP ranges are
# internal-only is determined by the underlying network infrastructure.
internalCIDRs:
- <string>
示例
no-external
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sNoExternalServices metadata: name: no-external spec: parameters: internalCIDRs: - 10.0.0.1/32
允许
apiVersion: v1 kind: Service metadata: name: good-service namespace: default spec: externalIPs: - 10.0.0.1 ports: - port: 8888 protocol: TCP targetPort: 8888
不允许
apiVersion: v1 kind: Service metadata: name: bad-service namespace: default spec: externalIPs: - 10.0.0.2 ports: - port: 8888 protocol: TCP targetPort: 8888
no-external-aws
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sNoExternalServices metadata: name: no-external-aws spec: parameters: cloudPlatform: AWS
允许
apiVersion: v1 kind: Service metadata: annotations: service.beta.kubernetes.io/aws-load-balancer-internal: "true" name: good-aws-service namespace: default spec: type: LoadBalancer
不允许
apiVersion: v1 kind: Service metadata: annotations: cloud.google.com/load-balancer-type: Internal name: bad-aws-service namespace: default spec: type: LoadBalancer
K8sPSPAllowPrivilegeEscalationContainer
对限制升级至 root 权限这一操作进行控制。 对应于 PodSecurityPolicy 中的 allowPrivilegeEscalation
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#privilege-escalation
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPAllowPrivilegeEscalationContainer
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-allow-privilege-escalation-container-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPAllowPrivilegeEscalationContainer metadata: name: psp-allow-privilege-escalation-container-sample spec: match: kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privilege-escalation name: nginx-privilege-escalation-allowed spec: containers: - image: nginx name: nginx securityContext: allowPrivilegeEscalation: false
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privilege-escalation name: nginx-privilege-escalation-disallowed spec: containers: - image: nginx name: nginx securityContext: allowPrivilegeEscalation: true
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privilege-escalation name: nginx-privilege-escalation-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: allowPrivilegeEscalation: true
K8sPSPAllowedUsers
控制容器和部分卷的用户 ID 和组 ID。对应于 PodSecurityPolicy 中的 runAsUser
、runAsGroup
、supplementalGroups
和 fsGroup
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#users-and-groups
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPAllowedUsers
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# fsGroup <object>: Controls the fsGroup values that are allowed in a Pod
# or container-level SecurityContext.
fsGroup:
# ranges <array>: A list of group ID ranges affected by the rule.
ranges:
# <list item: object>: The range of group IDs affected by the rule.
- # max <integer>: The maximum group ID in the range, inclusive.
max: <integer>
# min <integer>: The minimum group ID in the range, inclusive.
min: <integer>
# rule <string>: A strategy for applying the fsGroup restriction.
# Allowed Values: MustRunAs, MayRunAs, RunAsAny
rule: <string>
# runAsGroup <object>: Controls which group ID values are allowed in a Pod
# or container-level SecurityContext.
runAsGroup:
# ranges <array>: A list of group ID ranges affected by the rule.
ranges:
# <list item: object>: The range of group IDs affected by the rule.
- # max <integer>: The maximum group ID in the range, inclusive.
max: <integer>
# min <integer>: The minimum group ID in the range, inclusive.
min: <integer>
# rule <string>: A strategy for applying the runAsGroup restriction.
# Allowed Values: MustRunAs, MayRunAs, RunAsAny
rule: <string>
# runAsUser <object>: Controls which user ID values are allowed in a Pod or
# container-level SecurityContext.
runAsUser:
# ranges <array>: A list of user ID ranges affected by the rule.
ranges:
# <list item: object>: The range of user IDs affected by the rule.
- # max <integer>: The maximum user ID in the range, inclusive.
max: <integer>
# min <integer>: The minimum user ID in the range, inclusive.
min: <integer>
# rule <string>: A strategy for applying the runAsUser restriction.
# Allowed Values: MustRunAs, MustRunAsNonRoot, RunAsAny
rule: <string>
# supplementalGroups <object>: Controls the supplementalGroups values that
# are allowed in a Pod or container-level SecurityContext.
supplementalGroups:
# ranges <array>: A list of group ID ranges affected by the rule.
ranges:
# <list item: object>: The range of group IDs affected by the rule.
- # max <integer>: The maximum group ID in the range, inclusive.
max: <integer>
# min <integer>: The minimum group ID in the range, inclusive.
min: <integer>
# rule <string>: A strategy for applying the supplementalGroups
# restriction.
# Allowed Values: MustRunAs, MayRunAs, RunAsAny
rule: <string>
示例
psp-pods-allowed-user-ranges
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPAllowedUsers metadata: name: psp-pods-allowed-user-ranges spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: fsGroup: ranges: - max: 200 min: 100 rule: MustRunAs runAsGroup: ranges: - max: 200 min: 100 rule: MustRunAs runAsUser: ranges: - max: 200 min: 100 rule: MustRunAs supplementalGroups: ranges: - max: 200 min: 100 rule: MustRunAs
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-users name: nginx-users-allowed spec: containers: - image: nginx name: nginx securityContext: runAsGroup: 199 runAsUser: 199 securityContext: fsGroup: 199 supplementalGroups: - 199
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-users name: nginx-users-disallowed spec: containers: - image: nginx name: nginx securityContext: runAsGroup: 250 runAsUser: 250 securityContext: fsGroup: 250 supplementalGroups: - 250
apiVersion: v1 kind: Pod metadata: labels: app: nginx-users name: nginx-users-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: runAsGroup: 250 runAsUser: 250 securityContext: fsGroup: 250 supplementalGroups: - 250
K8sPSPAppArmor
配置供容器使用的 AppArmor 配置文件的许可名单。对应于应用于 PodSecurityPolicy 的特定注释。如需详细了解 AppArmor,请参阅 https://kubernetes.io/docs/tutorials/clusters/apparmor/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPAppArmor
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedProfiles <array>: An array of AppArmor profiles. Examples:
# `runtime/default`, `unconfined`.
allowedProfiles:
- <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-apparmor
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPAppArmor metadata: name: psp-apparmor spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedProfiles: - runtime/default
允许
apiVersion: v1 kind: Pod metadata: annotations: container.apparmor.security.beta.kubernetes.io/nginx: runtime/default labels: app: nginx-apparmor name: nginx-apparmor-allowed spec: containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: annotations: container.apparmor.security.beta.kubernetes.io/nginx: unconfined labels: app: nginx-apparmor name: nginx-apparmor-disallowed spec: containers: - image: nginx name: nginx
apiVersion: v1 kind: Pod metadata: annotations: container.apparmor.security.beta.kubernetes.io/nginx: unconfined labels: app: nginx-apparmor name: nginx-apparmor-disallowed spec: ephemeralContainers: - image: nginx name: nginx
K8sPSPAutomountServiceAccountTokenPod
控制任何 pod 启用 automountServiceAccountToken 的能力。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPAutomountServiceAccountTokenPod
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
<object>
示例
psp-automount-serviceaccount-token-pod
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPAutomountServiceAccountTokenPod metadata: name: psp-automount-serviceaccount-token-pod spec: match: excludedNamespaces: - kube-system kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-not-automountserviceaccounttoken name: nginx-automountserviceaccounttoken-allowed spec: automountServiceAccountToken: false containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-automountserviceaccounttoken name: nginx-automountserviceaccounttoken-disallowed spec: automountServiceAccountToken: true containers: - image: nginx name: nginx
K8sPSPCapabilities
控制容器上的 Linux 功能。对应于 PodSecurityPolicy 中的 allowedCapabilities
和 requiredDropCapabilities
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#capabilities
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPCapabilities
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedCapabilities <array>: A list of Linux capabilities that can be
# added to a container.
allowedCapabilities:
- <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# requiredDropCapabilities <array>: A list of Linux capabilities that are
# required to be dropped from a container.
requiredDropCapabilities:
- <string>
示例
capabilities-demo
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPCapabilities metadata: name: capabilities-demo spec: match: kinds: - apiGroups: - "" kinds: - Pod namespaces: - default parameters: allowedCapabilities: - something requiredDropCapabilities: - must_drop
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 30Mi securityContext: capabilities: add: - something drop: - must_drop - another_one
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 30Mi securityContext: capabilities: add: - disallowedcapability
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: ephemeralContainers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 30Mi securityContext: capabilities: add: - disallowedcapability
K8sPSPFSGroup
对分配拥有 Pod 卷的 FSGroup 这一操作进行控制。 对应于 PodSecurityPolicy 中的 fsGroup
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#volumes-and-file-systems
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPFSGroup
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# ranges <array>: GID ranges affected by the rule.
ranges:
- # max <integer>: The maximum GID in the range, inclusive.
max: <integer>
# min <integer>: The minimum GID in the range, inclusive.
min: <integer>
# rule <string>: An FSGroup rule name.
# Allowed Values: MayRunAs, MustRunAs, RunAsAny
rule: <string>
示例
psp-fsgroup
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPFSGroup metadata: name: psp-fsgroup spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: ranges: - max: 1000 min: 1 rule: MayRunAs
允许
apiVersion: v1 kind: Pod metadata: name: fsgroup-disallowed spec: containers: - command: - sh - -c - sleep 1h image: busybox name: fsgroup-demo volumeMounts: - mountPath: /data/demo name: fsgroup-demo-vol securityContext: fsGroup: 500 volumes: - emptyDir: {} name: fsgroup-demo-vol
不允许
apiVersion: v1 kind: Pod metadata: name: fsgroup-disallowed spec: containers: - command: - sh - -c - sleep 1h image: busybox name: fsgroup-demo volumeMounts: - mountPath: /data/demo name: fsgroup-demo-vol securityContext: fsGroup: 2000 volumes: - emptyDir: {} name: fsgroup-demo-vol
K8sPSPFlexVolumes
控制 FlexVolume 驱动程序的许可名单。对应于 PodSecurityPolicy 中的 allowedFlexVolumes
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#flexvolume-drivers
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPFlexVolumes
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedFlexVolumes <array>: An array of AllowedFlexVolume objects.
allowedFlexVolumes:
- # driver <string>: The name of the FlexVolume driver.
driver: <string>
示例
psp-flexvolume-drivers
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPFlexVolumes metadata: name: psp-flexvolume-drivers spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedFlexVolumes: - driver: example/lvm - driver: example/cifs
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-flexvolume-driver name: nginx-flexvolume-driver-allowed spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /test name: test-volume readOnly: true volumes: - flexVolume: driver: example/lvm name: test-volume
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-flexvolume-driver name: nginx-flexvolume-driver-disallowed spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /test name: test-volume readOnly: true volumes: - flexVolume: driver: example/testdriver name: test-volume
K8sPSPForbiddenSysctls
控制容器使用的 sysctl
配置文件。 对应于 PodSecurityPolicy 中的 allowedUnsafeSysctls
和 forbiddenSysctls
字段。如果指定,则任何不在 allowedSysctls
参数中的 sysctl 都会被视为禁止。forbiddenSysctls
参数的优先级高于 allowedSysctls
参数。如需了解详情,请参阅 https://kubernetes.io/docs/tasks/administer-cluster/sysctl-cluster/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPForbiddenSysctls
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedSysctls <array>: An allow-list of sysctls. `*` allows all sysctls
# not listed in the `forbiddenSysctls` parameter.
allowedSysctls:
- <string>
# forbiddenSysctls <array>: A disallow-list of sysctls. `*` forbids all
# sysctls.
forbiddenSysctls:
- <string>
示例
psp-forbidden-sysctls
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPForbiddenSysctls metadata: name: psp-forbidden-sysctls spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedSysctls: - '*' forbiddenSysctls: - kernel.*
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-forbidden-sysctls name: nginx-forbidden-sysctls-disallowed spec: containers: - image: nginx name: nginx securityContext: sysctls: - name: net.core.somaxconn value: "1024"
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-forbidden-sysctls name: nginx-forbidden-sysctls-disallowed spec: containers: - image: nginx name: nginx securityContext: sysctls: - name: kernel.msgmax value: "65536" - name: net.core.somaxconn value: "1024"
K8sPSPHostFilesystem
控制主机文件系统的使用情况。 对应于 PodSecurityPolicy 中的 allowedHostPaths
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#volumes-and-file-systems
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPHostFilesystem
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedHostPaths <array>: An array of hostpath objects, representing
# paths and read/write configuration.
allowedHostPaths:
- # pathPrefix <string>: The path prefix that the host volume must
# match.
pathPrefix: <string>
# readOnly <boolean>: when set to true, any container volumeMounts
# matching the pathPrefix must include `readOnly: true`.
readOnly: <boolean>
示例
psp-host-filesystem
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPHostFilesystem metadata: name: psp-host-filesystem spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedHostPaths: - pathPrefix: /foo readOnly: true
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-filesystem-disallowed name: nginx-host-filesystem spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /cache name: cache-volume readOnly: true volumes: - hostPath: path: /foo/bar name: cache-volume
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-filesystem-disallowed name: nginx-host-filesystem spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /cache name: cache-volume readOnly: true volumes: - hostPath: path: /tmp name: cache-volume
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-filesystem-disallowed name: nginx-host-filesystem spec: ephemeralContainers: - image: nginx name: nginx volumeMounts: - mountPath: /cache name: cache-volume readOnly: true volumes: - hostPath: path: /tmp name: cache-volume
K8sPSPHostNamespace
禁止 pod 容器共享主机 PID 和 IPC 命名空间。对应于 PodSecurityPolicy 中的 hostPID
和 hostIPC
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPHostNamespace
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
<object>
示例
psp-host-namespace-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPHostNamespace metadata: name: psp-host-namespace-sample spec: match: kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-namespace name: nginx-host-namespace-allowed spec: containers: - image: nginx name: nginx hostIPC: false hostPID: false
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-namespace name: nginx-host-namespace-disallowed spec: containers: - image: nginx name: nginx hostIPC: true hostPID: true
K8sPSPHostNetworkingPorts
控制 pod 容器的主机网络命名空间的使用情况。必须指定特定端口。对应于 PodSecurityPolicy 中的 hostNetwork
和 hostPorts
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPHostNetworkingPorts
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# hostNetwork <boolean>: Determines if the policy allows the use of
# HostNetwork in the pod spec.
hostNetwork: <boolean>
# max <integer>: The end of the allowed port range, inclusive.
max: <integer>
# min <integer>: The start of the allowed port range, inclusive.
min: <integer>
示例
psp-host-network-ports-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPHostNetworkingPorts metadata: name: psp-host-network-ports-sample spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: hostNetwork: true max: 9000 min: 80
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-networking-ports name: nginx-host-networking-ports-allowed spec: containers: - image: nginx name: nginx ports: - containerPort: 9000 hostPort: 80 hostNetwork: false
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-networking-ports name: nginx-host-networking-ports-disallowed spec: containers: - image: nginx name: nginx ports: - containerPort: 9001 hostPort: 9001 hostNetwork: true
apiVersion: v1 kind: Pod metadata: labels: app: nginx-host-networking-ports name: nginx-host-networking-ports-disallowed spec: ephemeralContainers: - image: nginx name: nginx ports: - containerPort: 9001 hostPort: 9001 hostNetwork: true
K8sPSPPrivilegedContainer
控制任何容器启用特权模式的能力。对应于 PodSecurityPolicy 中的 privileged
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#privileged
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPPrivilegedContainer
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-privileged-container-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPPrivilegedContainer metadata: name: psp-privileged-container-sample spec: match: excludedNamespaces: - kube-system kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privileged name: nginx-privileged-allowed spec: containers: - image: nginx name: nginx securityContext: privileged: false
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privileged name: nginx-privileged-disallowed spec: containers: - image: nginx name: nginx securityContext: privileged: true
apiVersion: v1 kind: Pod metadata: labels: app: nginx-privileged name: nginx-privileged-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: privileged: true
K8sPSPProcMount
控制容器所允许的 procMount
类型。对应于 PodSecurityPolicy 中的 allowedProcMountTypes
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#allowedprocmounttypes
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPProcMount
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# procMount <string>: Defines the strategy for the security exposure of
# certain paths in `/proc` by the container runtime. Setting to `Default`
# uses the runtime defaults, where `Unmasked` bypasses the default
# behavior.
# Allowed Values: Default, Unmasked
procMount: <string>
示例
psp-proc-mount
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPProcMount metadata: name: psp-proc-mount spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: procMount: Default
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-proc-mount name: nginx-proc-mount-disallowed spec: containers: - image: nginx name: nginx securityContext: procMount: Default
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-proc-mount name: nginx-proc-mount-disallowed spec: containers: - image: nginx name: nginx securityContext: procMount: Unmasked
apiVersion: v1 kind: Pod metadata: labels: app: nginx-proc-mount name: nginx-proc-mount-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: procMount: Unmasked
K8sPSPReadOnlyRootFilesystem
要求 Pod 容器使用只读根文件系统。对应于 PodSecurityPolicy 中的 readOnlyRootFilesystem
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#volumes-and-file-systems
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPReadOnlyRootFilesystem
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-readonlyrootfilesystem
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPReadOnlyRootFilesystem metadata: name: psp-readonlyrootfilesystem spec: match: kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-readonlyrootfilesystem name: nginx-readonlyrootfilesystem-allowed spec: containers: - image: nginx name: nginx securityContext: readOnlyRootFilesystem: true
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-readonlyrootfilesystem name: nginx-readonlyrootfilesystem-disallowed spec: containers: - image: nginx name: nginx securityContext: readOnlyRootFilesystem: false
apiVersion: v1 kind: Pod metadata: labels: app: nginx-readonlyrootfilesystem name: nginx-readonlyrootfilesystem-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: readOnlyRootFilesystem: false
K8sPSPSELinuxV2
定义 pod 容器的 seLinuxOptions 配置的许可名单。对应于要求使用 SELinux 配置的 PodSecurityPolicy。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#selinux
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPSELinuxV2
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedSELinuxOptions <array>: An allow-list of SELinux options
# configurations.
allowedSELinuxOptions:
# <list item: object>: An allowed configuration of SELinux options for a
# pod container.
- # level <string>: An SELinux level.
level: <string>
# role <string>: An SELinux role.
role: <string>
# type <string>: An SELinux type.
type: <string>
# user <string>: An SELinux user.
user: <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-selinux-v2
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPSELinuxV2 metadata: name: psp-selinux-v2 spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedSELinuxOptions: - level: s0:c123,c456 role: object_r type: svirt_sandbox_file_t user: system_u
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-selinux name: nginx-selinux-allowed spec: containers: - image: nginx name: nginx securityContext: seLinuxOptions: level: s0:c123,c456 role: object_r type: svirt_sandbox_file_t user: system_u
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-selinux name: nginx-selinux-disallowed spec: containers: - image: nginx name: nginx securityContext: seLinuxOptions: level: s1:c234,c567 role: sysadm_r type: svirt_lxc_net_t user: sysadm_u
apiVersion: v1 kind: Pod metadata: labels: app: nginx-selinux name: nginx-selinux-disallowed spec: ephemeralContainers: - image: nginx name: nginx securityContext: seLinuxOptions: level: s1:c234,c567 role: sysadm_r type: svirt_lxc_net_t user: sysadm_u
K8sPSPSeccomp
控制容器使用的 seccomp 配置文件。 对应于 PodSecurityPolicy 中的 seccomp.security.alpha.kubernetes.io/allowedProfileNames
注释。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#seccomp
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPSeccomp
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedLocalhostFiles <array>: When using securityContext naming scheme
# for seccomp and including `Localhost` this array holds the allowed
# profile JSON files. Putting a `*` in this array will allows all JSON
# files to be used. This field is required to allow `Localhost` in
# securityContext as with an empty list it will block.
allowedLocalhostFiles:
- <string>
# allowedProfiles <array>: An array of allowed profile values for seccomp
# on Pods/Containers. Can use the annotation naming scheme:
# `runtime/default`, `docker/default`, `unconfined` and/or
# `localhost/some-profile.json`. The item `localhost/*` will allow any
# localhost based profile. Can also use the securityContext naming scheme:
# `RuntimeDefault`, `Unconfined` and/or `Localhost`. For securityContext
# `Localhost`, use the parameter `allowedLocalhostProfiles` to list the
# allowed profile JSON files. The policy code will translate between the
# two schemes so it is not necessary to use both. Putting a `*` in this
# array allows all Profiles to be used. This field is required since with
# an empty list this policy will block all workloads.
allowedProfiles:
- <string>
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
示例
psp-seccomp
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPSeccomp metadata: name: psp-seccomp spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedProfiles: - runtime/default - docker/default
允许
apiVersion: v1 kind: Pod metadata: annotations: container.seccomp.security.alpha.kubernetes.io/nginx: runtime/default labels: app: nginx-seccomp name: nginx-seccomp-allowed spec: containers: - image: nginx name: nginx
apiVersion: v1 kind: Pod metadata: annotations: seccomp.security.alpha.kubernetes.io/pod: runtime/default labels: app: nginx-seccomp name: nginx-seccomp-allowed2 spec: containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: annotations: seccomp.security.alpha.kubernetes.io/pod: unconfined labels: app: nginx-seccomp name: nginx-seccomp-disallowed2 spec: containers: - image: nginx name: nginx
apiVersion: v1 kind: Pod metadata: annotations: container.seccomp.security.alpha.kubernetes.io/nginx: unconfined labels: app: nginx-seccomp name: nginx-seccomp-disallowed spec: containers: - image: nginx name: nginx
apiVersion: v1 kind: Pod metadata: annotations: container.seccomp.security.alpha.kubernetes.io/nginx: unconfined labels: app: nginx-seccomp name: nginx-seccomp-disallowed spec: ephemeralContainers: - image: nginx name: nginx
K8sPSPVolumeTypes
将可装载卷的类型限制为用户指定的类型。对应于 PodSecurityPolicy 中的 volumes
字段。如需了解详情,请参阅 https://kubernetes.io/docs/concepts/policy/pod-security-policy/#volumes-and-file-systems
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPSPVolumeTypes
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# volumes <array>: `volumes` is an array of volume types. All volume types
# can be enabled using `*`.
volumes:
- <string>
示例
psp-volume-types
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPSPVolumeTypes metadata: name: psp-volume-types spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: volumes: - configMap - emptyDir - projected - secret - downwardAPI - persistentVolumeClaim - flexVolume
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-volume-types name: nginx-volume-types-allowed spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /cache name: cache-volume - image: nginx name: nginx2 volumeMounts: - mountPath: /cache2 name: demo-vol volumes: - emptyDir: {} name: cache-volume - emptyDir: {} name: demo-vol
不允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx-volume-types name: nginx-volume-types-disallowed spec: containers: - image: nginx name: nginx volumeMounts: - mountPath: /cache name: cache-volume - image: nginx name: nginx2 volumeMounts: - mountPath: /cache2 name: demo-vol volumes: - hostPath: path: /tmp name: cache-volume - emptyDir: {} name: demo-vol
K8sPodDisruptionBudget
部署 PodDisruptionBudgets 或实现副本子资源的资源(例如 Deployment、ReplicationController、ReplicaSet、StatefulSet)时,禁止以下场景:1. PodDisruptionBudgets 部署,其中 .spec.maxUnavailable == 0 2。PodDisruptionBudgets 部署,其中 .spec.minAvailable == .spec.具有副本子资源的资源的副本数。这会阻止 PodDisruptionBudgets 阻止主动中断(例如节点排空) https://kubernetes.io/docs/concepts/workloads/pods/disruptions/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPodDisruptionBudget
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
pod-distruption-budget
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPodDisruptionBudget metadata: name: pod-distruption-budget spec: match: kinds: - apiGroups: - apps kinds: - Deployment - ReplicaSet - StatefulSet - apiGroups: - policy kinds: - PodDisruptionBudget - apiGroups: - "" kinds: - ReplicationController
允许
apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: nginx-pdb-allowed namespace: default spec: maxUnavailable: 1 selector: matchLabels: foo: bar
apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment-allowed-1 namespace: default spec: replicas: 3 selector: matchLabels: app: nginx example: allowed-deployment-1 template: metadata: labels: app: nginx example: allowed-deployment-1 spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80 --- # Referential Data apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: inventory-nginx-pdb-allowed-1 namespace: default spec: minAvailable: 2 selector: matchLabels: app: nginx example: allowed-deployment-1
apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment-allowed-2 namespace: default spec: replicas: 3 selector: matchLabels: app: nginx example: allowed-deployment-2 template: metadata: labels: app: nginx example: allowed-deployment-2 spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80 --- # Referential Data apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: inventory-nginx-pdb-allowed-2 namespace: default spec: maxUnavailable: 1 selector: matchLabels: app: nginx example: allowed-deployment-2
apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment-allowed-3 namespace: default spec: replicas: 3 selector: matchLabels: app: nginx example: allowed-deployment-3 template: metadata: labels: app: nginx example: allowed-deployment-3 spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80 --- # Referential Data apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: inventory-nginx-pdb-allowed-3 namespace: default spec: minAvailable: 2 selector: matchLabels: app: nginx
apiVersion: apps/v1 kind: Deployment metadata: labels: app: non-matching-nginx name: nginx-deployment-allowed-4 namespace: default spec: replicas: 1 selector: matchLabels: app: non-matching-nginx example: allowed-deployment-4 template: metadata: labels: app: non-matching-nginx example: allowed-deployment-4 spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80 --- # Referential Data apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: inventory-mongo-pdb-allowed-3 namespace: default spec: minAvailable: 2 selector: matchLabels: app: mongo example: non-matching-deployment-3
不允许
apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: nginx-pdb-disallowed namespace: default spec: maxUnavailable: 0 selector: matchLabels: foo: bar
apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: nginx-deployment-disallowed namespace: default spec: replicas: 3 selector: matchLabels: app: nginx example: disallowed-deployment template: metadata: labels: app: nginx example: disallowed-deployment spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80 --- # Referential Data apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: inventory-nginx-pdb-disallowed namespace: default spec: minAvailable: 3 selector: matchLabels: app: nginx example: disallowed-deployment
K8sPodsRequireSecurityContext
要求所有 Pod 都定义 securityContext。要求 Pod 中定义的所有容器都在 Pod 或容器级层定义 SecurityContext。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sPodsRequireSecurityContext
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: A list of exempt Images.
exemptImages:
- <string>
示例
pods-require-security-context-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sPodsRequireSecurityContext metadata: name: pods-require-security-context-sample spec: enforcementAction: dryrun parameters: exemptImages: - nginix-exempt - alpine*
允许
apiVersion: v1 kind: Pod metadata: name: allowed-example spec: containers: - image: nginx name: nginx securityContext: runAsUser: 2000
apiVersion: v1 kind: Pod metadata: name: allowed-example-exemptImage spec: containers: - image: nginix-exempt name: nginx
apiVersion: v1 kind: Pod metadata: name: allowed-example-exemptImage-wildcard spec: containers: - image: alpine17 name: alpine
不允许
apiVersion: v1 kind: Pod metadata: name: disallowed-example spec: containers: - image: nginx name: nginx
K8sProhibitRoleWildcardAccess
要求 Role 和 ClusterRole 不得对通配符(“”)值设置资源访问权限,但作为豁免项提供的豁免 Role 和 ClusterRole 除外。不限制对子资源的通配符访问,例如“/status”。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sProhibitRoleWildcardAccess
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptions <object>: The list of exempted Roles and/or ClusterRoles name
# that are allowed to set resource access to a wildcard.
exemptions:
clusterRoles:
- # name <string>: The name of the ClusterRole to be exempted.
name: <string>
# regexMatch <boolean>: The flag to allow a regular expression
# based match on the name.
regexMatch: <boolean>
roles:
- # name <string>: The name of the Role to be exempted.
name: <string>
# namespace <string>: The namespace of the Role to be exempted.
namespace: <string>
示例
prohibit-role-wildcard-access-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sProhibitRoleWildcardAccess metadata: name: prohibit-role-wildcard-access-sample spec: enforcementAction: dryrun
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cluster-role-example rules: - apiGroups: - "" resources: - pods verbs: - get
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cluster-role-bad-example rules: - apiGroups: - "" resources: - pods verbs: - '*'
prohibit-wildcard-except-exempted-cluster-role
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sProhibitRoleWildcardAccess metadata: name: prohibit-wildcard-except-exempted-cluster-role spec: enforcementAction: dryrun parameters: exemptions: clusterRoles: - name: cluster-role-allowed-example roles: - name: role-allowed-example namespace: role-ns-allowed-example
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cluster-role-allowed-example rules: - apiGroups: - "" resources: - pods verbs: - '*'
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: role-allowed-example namespace: role-ns-allowed-example rules: - apiGroups: - "" resources: - pods verbs: - '*'
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: cluster-role-not-allowed-example rules: - apiGroups: - "" resources: - pods verbs: - '*'
apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: role-not-allowed-example namespace: role-ns-not-allowed-example rules: - apiGroups: - "" resources: - pods verbs: - '*'
K8sReplicaLimits
要求包含 spec.replicas
字段(Deployments、ReplicaSets 等)的对象指定的副本数量在所定义的范围内。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sReplicaLimits
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# ranges <array>: Allowed ranges for numbers of replicas. Values are
# inclusive.
ranges:
# <list item: object>: A range of allowed replicas. Values are
# inclusive.
- # max_replicas <integer>: The maximum number of replicas allowed,
# inclusive.
max_replicas: <integer>
# min_replicas <integer>: The minimum number of replicas allowed,
# inclusive.
min_replicas: <integer>
示例
replica-limits
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sReplicaLimits metadata: name: replica-limits spec: match: kinds: - apiGroups: - apps kinds: - Deployment parameters: ranges: - max_replicas: 50 min_replicas: 3
允许
apiVersion: apps/v1 kind: Deployment metadata: name: allowed-deployment spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80
不允许
apiVersion: apps/v1 kind: Deployment metadata: name: disallowed-deployment spec: replicas: 100 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80
K8sRequireCosNodeImage
强制在节点上使用 Google 的 Container-Optimized OS。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireCosNodeImage
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptOsImages <array>: A list of exempt OS Images.
exemptOsImages:
- <string>
示例
nodes-have-consistent-time
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequireCosNodeImage metadata: name: nodes-have-consistent-time spec: enforcementAction: dryrun parameters: exemptOsImages: - Debian - Ubuntu*
允许
apiVersion: v1 kind: Node metadata: name: allowed-example status: nodeInfo: osImage: Container-Optimized OS from Google
apiVersion: v1 kind: Node metadata: name: example-exempt status: nodeInfo: osImage: Debian
apiVersion: v1 kind: Node metadata: name: example-exempt-regex status: nodeInfo: osImage: Ubuntu 18.04.5 LTS
不允许
apiVersion: v1 kind: Node metadata: name: disallowed-example status: nodeInfo: osImage: Debian GNUv1.0
K8sRequireDaemonsets
要求指定的 daemonset 列表存在。注意:此限制条件是参照限制条件。如需了解详情,请参阅启用参照限制条件。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireDaemonsets
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# requiredDaemonsets <array>: A list of names and namespaces of the
# required daemonsets.
requiredDaemonsets:
- # name <string>: The name of the required daemonset.
name: <string>
# namespace <string>: The namespace for the required daemonset.
namespace: <string>
示例
require-daemonset
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequireDaemonsets metadata: name: require-daemonset spec: enforcementAction: dryrun match: kinds: - apiGroups: - "" kinds: - Namespace parameters: requiredDaemonsets: - name: clamav namespace: pci-dss-av
允许
apiVersion: v1 kind: Namespace metadata: name: pci-dss-av --- # Referential Data apiVersion: apps/v1 kind: DaemonSet metadata: name: other namespace: pci-dss-av spec: selector: matchLabels: name: other template: metadata: labels: name: other spec: containers: - image: us.gcr.io/{your-project-id}/other:latest name: other resources: limits: memory: 3Gi requests: cpu: 500m memory: 2Gi tolerations: - effect: NoSchedule key: node-role.kubernetes.io/master --- # Referential Data apiVersion: apps/v1 kind: DaemonSet metadata: labels: k8s-app: clamav-host-scanner name: clamav namespace: pci-dss-av spec: selector: matchLabels: name: clamav template: metadata: labels: name: clamav spec: containers: - image: us.gcr.io/{your-project-id}/clamav:latest livenessProbe: exec: command: - /health.sh initialDelaySeconds: 60 periodSeconds: 30 name: clamav-scanner resources: limits: memory: 3Gi requests: cpu: 500m memory: 2Gi volumeMounts: - mountPath: /data name: data-vol - mountPath: /host-fs name: host-fs readOnly: true - mountPath: /logs name: logs terminationGracePeriodSeconds: 30 tolerations: - effect: NoSchedule key: node-role.kubernetes.io/master volumes: - emptyDir: {} name: data-vol - hostPath: path: / name: host-fs - hostPath: path: /var/log/clamav name: logs
不允许
apiVersion: v1 kind: Namespace metadata: name: pci-dss-av
apiVersion: v1 kind: Namespace metadata: name: pci-dss-av --- # Referential Data apiVersion: apps/v1 kind: DaemonSet metadata: name: other namespace: pci-dss-av spec: selector: matchLabels: name: other template: metadata: labels: name: other spec: containers: - image: us.gcr.io/{your-project-id}/other:latest name: other resources: limits: memory: 3Gi requests: cpu: 500m memory: 2Gi tolerations: - effect: NoSchedule key: node-role.kubernetes.io/master
K8sRequireDefaultDenyEgressPolicy
要求集群中定义的每个命名空间都具有出站流量的默认拒绝 NetworkPolicy。注意:此限制条件是参照限制条件。如需了解详情,请参阅启用参照限制条件。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireDefaultDenyEgressPolicy
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
require-default-deny-network-policies
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequireDefaultDenyEgressPolicy metadata: name: require-default-deny-network-policies spec: enforcementAction: dryrun
允许
apiVersion: v1 kind: Namespace metadata: name: example-namespace --- # Referential Data apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny-egress namespace: example-namespace spec: podSelector: {} policyTypes: - Egress
不允许
apiVersion: v1 kind: Namespace metadata: name: example-namespace
apiVersion: v1 kind: Namespace metadata: name: example-namespace2 --- # Referential Data apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny-egress namespace: example-namespace spec: podSelector: {} policyTypes: - Egress
K8sRequireNamespaceNetworkPolicies
要求集群中定义的每个命名空间都具有一个 NetworkPolicy。 注意:此限制条件是参照限制条件。如需了解详情,请参阅启用参照限制条件。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireNamespaceNetworkPolicies
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
require-namespace-network-policies-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequireNamespaceNetworkPolicies metadata: name: require-namespace-network-policies-sample spec: enforcementAction: dryrun
允许
apiVersion: v1 kind: Namespace metadata: name: require-namespace-network-policies-example --- # Referential Data apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: test-network-policy namespace: require-namespace-network-policies-example
不允许
apiVersion: v1 kind: Namespace metadata: name: require-namespace-network-policies-example
K8sRequireValidRangesForNetworks
强制执行网络入站流量和出站流量允许的 CIDR 地址块。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequireValidRangesForNetworks
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedEgress <array>: IP ranges in CIDR format (0.0.0.0/32) that are
# allowed for egress.
allowedEgress:
- <string>
# allowedIngress <array>: IP ranges in CIDR format (0.0.0.0/32) that are
# allowed for ingress.
allowedIngress:
- <string>
示例
require-valid-network-ranges
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequireValidRangesForNetworks metadata: name: require-valid-network-ranges spec: enforcementAction: dryrun parameters: allowedEgress: - 1.1.2.0/32 allowedIngress: - 1.1.2.0/24
允许
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: test-network-policy namespace: default spec: egress: - ports: - port: 5978 protocol: TCP to: - ipBlock: cidr: 1.1.2.0/32 ingress: - from: - ipBlock: cidr: 1.1.2.0/29 - ipBlock: cidr: 1.1.2.100/29 - namespaceSelector: matchLabels: project: myproject - podSelector: matchLabels: role: frontend ports: - port: 6379 protocol: TCP podSelector: matchLabels: role: db policyTypes: - Ingress - Egress
不允许
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: test-network-policy-disallowed namespace: default spec: egress: - ports: - port: 5978 protocol: TCP to: - ipBlock: cidr: 1.1.2.0/31 ingress: - from: - ipBlock: cidr: 1.1.2.0/24 - ipBlock: cidr: 2.1.2.0/24 - namespaceSelector: matchLabels: project: myproject - podSelector: matchLabels: role: frontend ports: - port: 6379 protocol: TCP podSelector: matchLabels: role: db policyTypes: - Ingress - Egress
K8sRequiredAnnotations
要求资源包含指定的注解,其值与提供的正则表达式匹配。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredAnnotations
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# annotations <array>: A list of annotations and values the object must
# specify.
annotations:
- # allowedRegex <string>: If specified, a regular expression the
# annotation's value must match. The value must contain at least one
# match for the regular expression.
allowedRegex: <string>
# key <string>: The required annotation.
key: <string>
message: <string>
示例
all-must-have-certain-set-of-annotations
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredAnnotations metadata: name: all-must-have-certain-set-of-annotations spec: match: kinds: - apiGroups: - "" kinds: - Service parameters: annotations: - allowedRegex: ^([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}|[a-z]{1,39})$ key: a8r.io/owner - allowedRegex: ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$ key: a8r.io/runbook message: All services must have a `a8r.io/owner` and `a8r.io/runbook` annotations.
允许
apiVersion: v1 kind: Service metadata: annotations: a8r.io/owner: dev-team-alfa@contoso.com a8r.io/runbook: https://confluence.contoso.com/dev-team-alfa/runbooks name: allowed-service spec: ports: - name: http port: 80 targetPort: 8080 selector: app: foo
不允许
apiVersion: v1 kind: Service metadata: name: disallowed-service spec: ports: - name: http port: 80 targetPort: 8080 selector: app: foo
K8sRequiredLabels
要求资源包含指定的标签,其值与提供的正则表达式匹配。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# labels <array>: A list of labels and values the object must specify.
labels:
- # allowedRegex <string>: If specified, a regular expression the
# annotation's value must match. The value must contain at least one
# match for the regular expression.
allowedRegex: <string>
# key <string>: The required label.
key: <string>
message: <string>
示例
all-must-have-owner
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredLabels metadata: name: all-must-have-owner spec: match: kinds: - apiGroups: - "" kinds: - Namespace parameters: labels: - allowedRegex: ^[a-zA-Z]+.agilebank.demo$ key: owner message: All namespaces must have an `owner` label that points to your company username
允许
apiVersion: v1 kind: Namespace metadata: labels: owner: user.agilebank.demo name: allowed-namespace
不允许
apiVersion: v1 kind: Namespace metadata: name: disallowed-namespace
K8sRequiredProbes
要求 Pod 具有就绪和/或活跃探测。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredProbes
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# probeTypes <array>: The probe must define a field listed in `probeType`
# in order to satisfy the constraint (ex. `tcpSocket` satisfies
# `['tcpSocket', 'exec']`)
probeTypes:
- <string>
# probes <array>: A list of probes that are required (ex: `readinessProbe`)
probes:
- <string>
示例
must-have-probes
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredProbes metadata: name: must-have-probes spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: probeTypes: - tcpSocket - httpGet - exec probes: - readinessProbe - livenessProbe
允许
apiVersion: v1 kind: Pod metadata: name: test-pod1 spec: containers: - image: tomcat livenessProbe: initialDelaySeconds: 5 periodSeconds: 10 tcpSocket: port: 80 name: tomcat ports: - containerPort: 8080 readinessProbe: initialDelaySeconds: 5 periodSeconds: 10 tcpSocket: port: 8080 volumes: - emptyDir: {} name: cache-volume
不允许
apiVersion: v1 kind: Pod metadata: name: test-pod1 spec: containers: - image: nginx:1.7.9 name: nginx-1 ports: - containerPort: 80 volumeMounts: - mountPath: /tmp/cache name: cache-volume - image: tomcat name: tomcat ports: - containerPort: 8080 readinessProbe: initialDelaySeconds: 5 periodSeconds: 10 tcpSocket: port: 8080 volumes: - emptyDir: {} name: cache-volume
apiVersion: v1 kind: Pod metadata: name: test-pod2 spec: containers: - image: nginx:1.7.9 livenessProbe: initialDelaySeconds: 5 periodSeconds: 10 tcpSocket: port: 80 name: nginx-1 ports: - containerPort: 80 volumeMounts: - mountPath: /tmp/cache name: cache-volume - image: tomcat name: tomcat ports: - containerPort: 8080 readinessProbe: initialDelaySeconds: 5 periodSeconds: 10 tcpSocket: port: 8080 volumes: - emptyDir: {} name: cache-volume
K8sRequiredResources
要求容器设置已定义的资源。https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredResources
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exemptImages <array>: Any container that uses an image that matches an
# entry in this list will be excluded from enforcement. Prefix-matching can
# be signified with `*`. For example: `my-image-*`. It is recommended that
# users use the fully-qualified Docker image name (e.g. start with a domain
# name) in order to avoid unexpectedly exempting images from an untrusted
# repository.
exemptImages:
- <string>
# limits <array>: A list of limits that should be enforced (cpu, memory or
# both).
limits:
# Allowed Values: cpu, memory
- <string>
# requests <array>: A list of requests that should be enforced (cpu, memory
# or both).
requests:
# Allowed Values: cpu, memory
- <string>
示例
container-must-have-limits-and-requests
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredResources metadata: name: container-must-have-limits-and-requests spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: limits: - cpu - memory requests: - cpu - memory
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 1Gi requests: cpu: 100m memory: 1Gi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: requests: cpu: 100m memory: 2Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: memory: 2Gi requests: cpu: 100m
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: memory: 2Gi
container-must-have-cpu-requests-memory-limits-and-requests
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredResources metadata: name: container-must-have-cpu-requests-memory-limits-and-requests spec: match: kinds: - apiGroups: - "" kinds: - Pod parameters: limits: - memory requests: - cpu - memory
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 1Gi requests: cpu: 100m memory: 1Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: memory: 2Gi requests: cpu: 100m memory: 2Gi
不允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: requests: cpu: 100m memory: 2Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: memory: 2Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: {}
no-enforcements
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRequiredResources metadata: name: no-enforcements spec: match: kinds: - apiGroups: - "" kinds: - Pod
允许
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-allowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: cpu: 100m memory: 1Gi requests: cpu: 100m memory: 1Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: requests: cpu: 100m memory: 2Gi
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: limits: memory: 2Gi requests: cpu: 100m
apiVersion: v1 kind: Pod metadata: labels: owner: me.agilebank.demo name: opa-disallowed spec: containers: - args: - run - --server - --addr=localhost:8080 image: openpolicyagent/opa:0.9.2 name: opa resources: {}
K8sRestrictLabels
禁止资源包含指定的标签,除非特定资源存在例外。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRestrictLabels
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# exceptions <array>: Objects listed here are exempt from enforcement of
# this constraint. All fields must be provided.
exceptions:
# <list item: object>: A single object's identification, based on group,
# kind, namespace, and name.
- # group <string>: The Kubernetes group of the exempt object.
group: <string>
# kind <string>: The Kubernetes kind of the exempt object.
kind: <string>
# name <string>: The name of the exempt object.
name: <string>
# namespace <string>: The namespace of the exempt object. For
# cluster-scoped resources, use the empty string `""`.
namespace: <string>
# restrictedLabels <array>: A list of label keys strings.
restrictedLabels:
- <string>
示例
restrict-label-example
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRestrictLabels metadata: name: restrict-label-example spec: enforcementAction: dryrun parameters: exceptions: - group: "" kind: Pod name: allowed-example namespace: default restrictedLabels: - label-example
允许
apiVersion: v1 kind: Pod metadata: labels: label-example: example name: allowed-example namespace: default spec: containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: labels: label-example: example name: disallowed-example namespace: default spec: containers: - image: nginx name: nginx
K8sRestrictNamespaces
限制资源使用 restrictedNamespaces 参数下列出的命名空间。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRestrictNamespaces
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# restrictedNamespaces <array>: A list of Namespaces to restrict.
restrictedNamespaces:
- <string>
示例
restrict-default-namespace-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRestrictNamespaces metadata: name: restrict-default-namespace-sample spec: enforcementAction: dryrun parameters: restrictedNamespaces: - default
允许
apiVersion: v1 kind: Pod metadata: name: allowed-example namespace: test-namespace spec: containers: - image: nginx name: nginx
不允许
apiVersion: v1 kind: Pod metadata: name: disallowed-example namespace: default spec: containers: - image: nginx name: nginx
K8sRestrictRbacSubjects
将 RBAC 主体中的名称限制为只能使用指定的值。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRestrictRbacSubjects
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedSubjects <array>: The list of names permitted in RBAC subjects.
allowedSubjects:
- # name <string>: The exact-name or the pattern of the allowed subject
name: <string>
# regexMatch <boolean>: The flag to allow a regular expression based
# match on the name.
regexMatch: <boolean>
示例
restrict-rbac-subjects
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRestrictRbacSubjects metadata: name: restrict-rbac-subjects spec: enforcementAction: dryrun match: kinds: - apiGroups: - rbac.authorization.k8s.io kinds: - RoleBinding - ClusterRoleBinding parameters: allowedSubjects: - name: system:masters - name: ^.+@gcp-sa-mcmetering.iam.gserviceaccount.com$ regexMatch: true - name: ^.+@gcp-sa-gkehub.iam.gserviceaccount.com$ regexMatch: true - name: ^.+@gcp-sa-anthosconfigmanagement.iam.gserviceaccount.com$ regexMatch: true - name: ^.+@gcp-sa-servicemesh.iam.gserviceaccount.com$ regexMatch: true - name: ^.+@system.gserviceaccount.com$ regexMatch: true - name: ^.+@google.com$ regexMatch: true
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: good-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: user@google.com - apiGroup: rbac.authorization.k8s.io kind: Group name: system:masters
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: bad-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: user@example.com
K8sRestrictRoleBindings
将 ClusterRoleBinding 和 RoleBinding 中指定的主题限制为允许的主题列表。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRestrictRoleBindings
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedSubjects <array>: The list of subjects that are allowed to bind to
# the restricted role.
allowedSubjects:
- # apiGroup <string>: The Kubernetes API group of the subject.
apiGroup: <string>
# kind <string>: The Kubernetes kind of the subject.
kind: <string>
# name <string>: The name of the subject which is matched exactly as
# provided as well as based on a regular expression.
name: <string>
# regexMatch <boolean>: The flag to allow a regular expression based
# match on the name.
regexMatch: <boolean>
# restrictedRole <object>: The role that cannot be bound to unless
# expressly allowed.
restrictedRole:
# apiGroup <string>: The Kubernetes API group of the role.
apiGroup: <string>
# kind <string>: The Kubernetes kind of the role.
kind: <string>
# name <string>: The name of the role.
name: <string>
示例
restrict-clusteradmin-rolebindings-sample
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRestrictRoleBindings metadata: name: restrict-clusteradmin-rolebindings-sample spec: enforcementAction: dryrun parameters: allowedSubjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:masters restrictedRole: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: good-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:masters
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: bad-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:unauthenticated
restrict-clusteradmin-rolebindings-regex
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sRestrictRoleBindings metadata: name: restrict-clusteradmin-rolebindings-regex spec: enforcementAction: dryrun parameters: allowedSubjects: - apiGroup: rbac.authorization.k8s.io kind: User name: ^service-[0-9]+@gcp-sa-anthosconfigmanagement.iam.gserviceaccount.com$ regexMatch: true restrictedRole: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin
允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: good-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: service-123456789@gcp-sa-anthosconfigmanagement.iam.gserviceaccount.com
不允许
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: bad-clusterrolebinding roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: cluster-admin subjects: - apiGroup: rbac.authorization.k8s.io kind: User name: someotherservice-123456789@gcp-sa-anthosconfigmanagement.iam.gserviceaccount.com
K8sStorageClass
要求在使用时指定存储类别。仅支持 Gatekeeper 3.9+。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sStorageClass
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
includeStorageClassesInMessage: <boolean>
示例
storageclass
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sStorageClass metadata: name: storageclass spec: match: kinds: - apiGroups: - "" kinds: - PersistentVolumeClaim - apiGroups: - apps kinds: - StatefulSet parameters: includeStorageClassesInMessage: true
允许
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: ok spec: accessModes: - ReadWriteOnce resources: requests: storage: 8Gi storageClassName: somestorageclass volumeMode: Filesystem --- # Referential Data allowVolumeExpansion: true apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: somestorageclass provisioner: foo
apiVersion: apps/v1 kind: StatefulSet metadata: name: volumeclaimstorageclass spec: replicas: 1 selector: matchLabels: app: volumeclaimstorageclass serviceName: volumeclaimstorageclass template: metadata: labels: app: volumeclaimstorageclass spec: containers: - image: registry.k8s.io/nginx-slim:0.8 name: main volumeMounts: - mountPath: /usr/share/nginx/html name: data volumeClaimTemplates: - metadata: name: data spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi storageClassName: somestorageclass --- # Referential Data allowVolumeExpansion: true apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: somestorageclass provisioner: foo
不允许
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: badstorageclass spec: accessModes: - ReadWriteOnce resources: requests: storage: 8Gi storageClassName: badstorageclass volumeMode: Filesystem
apiVersion: apps/v1 kind: StatefulSet metadata: name: badvolumeclaimstorageclass spec: replicas: 1 selector: matchLabels: app: badvolumeclaimstorageclass serviceName: badvolumeclaimstorageclass template: metadata: labels: app: badvolumeclaimstorageclass spec: containers: - image: registry.k8s.io/nginx-slim:0.8 name: main volumeMounts: - mountPath: /usr/share/nginx/html name: data volumeClaimTemplates: - metadata: name: data spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi storageClassName: badstorageclass
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: nostorageclass spec: accessModes: - ReadWriteOnce resources: requests: storage: 8Gi volumeMode: Filesystem
apiVersion: apps/v1 kind: StatefulSet metadata: name: novolumeclaimstorageclass spec: replicas: 1 selector: matchLabels: app: novolumeclaimstorageclass serviceName: novolumeclaimstorageclass template: metadata: labels: app: novolumeclaimstorageclass spec: containers: - image: registry.k8s.io/nginx-slim:0.8 name: main volumeMounts: - mountPath: /usr/share/nginx/html name: data volumeClaimTemplates: - metadata: name: data spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi
K8sUniqueIngressHost
要求所有 Ingress 规则主机都具有唯一性。系统不会处理主机名通配符:https://kubernetes.io/docs/concepts/services-networking/ingress/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sUniqueIngressHost
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
unique-ingress-host
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sUniqueIngressHost metadata: name: unique-ingress-host spec: match: kinds: - apiGroups: - extensions - networking.k8s.io kinds: - Ingress
允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-host-allowed namespace: default spec: rules: - host: example-allowed-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix - host: example-allowed-host1.example.com http: paths: - backend: service: name: nginx2 port: number: 80 path: / pathType: Prefix
不允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-host-disallowed namespace: default spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix --- # Referential Data apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-host-example namespace: default spec: rules: - host: example-host.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-host-disallowed2 namespace: default spec: rules: - host: example-host2.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix - host: example-host3.example.com http: paths: - backend: service: name: nginx2 port: number: 80 path: / pathType: Prefix --- # Referential Data apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-host-example2 namespace: default spec: rules: - host: example-host2.example.com http: paths: - backend: service: name: nginx port: number: 80 path: / pathType: Prefix
K8sUniqueServiceSelector
要求服务在命名空间内具有唯一的选择器。如果选择器具有相同的键和值,则它们会被视为相同的选择器。选择器可以共享键值对,只要它们之间至少有一个不同的键值对即可。 https://kubernetes.io/docs/concepts/services-networking/service/#defining-a-service
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sUniqueServiceSelector
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
unique-service-selector
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: K8sUniqueServiceSelector metadata: labels: owner: admin.agilebank.demo name: unique-service-selector
允许
apiVersion: v1 kind: Service metadata: name: gatekeeper-test-service-disallowed namespace: default spec: ports: - port: 443 selector: key: other-value
不允许
apiVersion: v1 kind: Service metadata: name: gatekeeper-test-service-disallowed namespace: default spec: ports: - port: 443 selector: key: value --- # Referential Data apiVersion: v1 kind: Service metadata: name: gatekeeper-test-service-example namespace: default spec: ports: - port: 443 selector: key: value
NoUpdateServiceAccount
阻止在 Pod 上抽象的资源上更新服务账号。此政策在审核模式下被忽略。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: NoUpdateServiceAccount
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedGroups <array>: Groups that should be allowed to bypass the
# policy.
allowedGroups:
- <string>
# allowedUsers <array>: Users that should be allowed to bypass the policy.
allowedUsers:
- <string>
示例
no-update-kube-system-service-account
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: NoUpdateServiceAccount metadata: name: no-update-kube-system-service-account spec: match: kinds: - apiGroups: - "" kinds: - ReplicationController - apiGroups: - apps kinds: - ReplicaSet - Deployment - StatefulSet - DaemonSet - apiGroups: - batch kinds: - CronJob namespaces: - kube-system parameters: allowedGroups: [] allowedUsers: []
允许
apiVersion: apps/v1 kind: Deployment metadata: labels: app: policy-test name: policy-test namespace: kube-system spec: replicas: 1 selector: matchLabels: app: policy-test-deploy template: metadata: labels: app: policy-test-deploy spec: containers: - command: - /bin/bash - -c - sleep 99999 image: ubuntu name: policy-test serviceAccountName: policy-test-sa-1
PolicyStrictOnly
要求在使用 PeerAuthentication 时始终指定 STRICT
Istio 双向 TLS。此限制条件还可确保已弃用的 Policy 和 MeshPolicy 资源也强制执行 STRICT
双向 TLS。请参阅:https://istio.io/latest/docs/tasks/security/authentication/mtls-migration/#lock-down-mutual-tls-for-the-entire-mesh
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: PolicyStrictOnly
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
peerauthentication-strict-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: PolicyStrictOnly metadata: name: peerauthentication-strict-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - PeerAuthentication namespaces: - default
允许
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-strict namespace: default spec: mtls: mode: STRICT
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-strict-port-level namespace: default spec: mtls: mode: STRICT portLevelMtls: "8080": mode: STRICT
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-strict-port-unset namespace: default spec: mtls: mode: STRICT portLevelMtls: "8080": mode: UNSET
不允许
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: empty-mtls namespace: default spec: mtls: {}
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: unspecified-mtls namespace: default
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-null namespace: default spec: mtls: mode: null
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mtls-null namespace: default spec: mtls: null
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-permissive namespace: default spec: mtls: mode: PERMISSIVE
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-strict-port-permissive namespace: default spec: mtls: mode: STRICT portLevelMtls: "8080": mode: PERMISSIVE
apiVersion: security.istio.io/v1beta1 kind: PeerAuthentication metadata: name: mode-strict-port-permissive namespace: default spec: mtls: mode: STRICT portLevelMtls: "8080": mode: PERMISSIVE "8081": mode: STRICT
deprecated-policy-strict-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: PolicyStrictOnly metadata: name: deprecated-policy-strict-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - authentication.istio.io kinds: - Policy namespaces: - default
允许
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: default-mode-strict namespace: default spec: peers: - mtls: mode: STRICT
不允许
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: default-mtls-empty namespace: default spec: peers: - mtls: {}
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: default-mtls-null namespace: default spec: peers: - mtls: null
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: peers-empty namespace: default spec: peers: []
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: policy-no-peers namespace: default spec: targets: - name: httpbin
apiVersion: authentication.istio.io/v1alpha1 kind: Policy metadata: name: policy-permissive namespace: default spec: peers: - mtls: mode: PERMISSIVE
RestrictNetworkExclusions
控制可以从 Istio 网络捕获中排除的入站端口、出站端口和出站 IP 范围。Istio 代理不会处理绕过 Istio 网络捕获的端口和 IP 范围,它们不受 Istio mTLS 身份验证、授权政策和其他 Istio 功能的约束。此限制条件可用于对以下注解的使用施加限制:
traffic.sidecar.istio.io/excludeInboundPorts
traffic.sidecar.istio.io/excludeOutboundPorts
traffic.sidecar.istio.io/excludeOutboundIPRanges
请参阅 https://istio.io/latest/docs/reference/config/annotations/。
限制出站 IP 范围时,限制条件会计算排除的 IP 范围是匹配还是允许的 IP 范围排除项的子集。
使用此限制条件时,必须始终将所有入站端口、出站端口和出站 IP 范围包含在内,方法是将相应的“include”注解设置为 "*"
或保持未设置。不允许将以下任何注解设置为 "*"
以外的任何值:
traffic.sidecar.istio.io/includeInboundPorts
traffic.sidecar.istio.io/includeOutboundPorts
traffic.sidecar.istio.io/includeOutboundIPRanges
此限制条件始终允许排除端口 15020,因为 Istio Sidecar 注入器会始终将其添加到 traffic.sidecar.istio.io/excludeInboundPorts
注解,以便用于健康检查。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: RestrictNetworkExclusions
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# allowedInboundPortExclusions <array>: A list of ports that this
# constraint will allow in the
# `traffic.sidecar.istio.io/excludeInboundPorts` annotation.
allowedInboundPortExclusions:
- <string>
# allowedOutboundIPRangeExclusions <array>: A list of IP ranges that this
# constraint will allow in the
# `traffic.sidecar.istio.io/excludeOutboundIPRanges` annotation. The
# constraint calculates whether excluded IP ranges match or are a subset of
# the ranges in this list.
allowedOutboundIPRangeExclusions:
- <string>
# allowedOutboundPortExclusions <array>: A list of ports that this
# constraint will allow in the
# `traffic.sidecar.istio.io/excludeOutboundPorts` annotation.
allowedOutboundPortExclusions:
- <string>
示例
restrict-network-exclusions
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: RestrictNetworkExclusions metadata: name: restrict-network-exclusions spec: enforcementAction: deny match: kinds: - apiGroups: - "" kinds: - Pod parameters: allowedInboundPortExclusions: - "80" allowedOutboundIPRangeExclusions: - 169.254.169.254/32 allowedOutboundPortExclusions: - "8888"
允许
apiVersion: v1 kind: Pod metadata: labels: app: nginx name: nothing-excluded spec: containers: - image: nginx name: nginx ports: - containerPort: 80
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/excludeInboundPorts: "80" traffic.sidecar.istio.io/excludeOutboundIPRanges: 169.254.169.254/32 traffic.sidecar.istio.io/excludeOutboundPorts: "8888" labels: app: nginx name: allowed-port-and-ip-exclusions spec: containers: - image: nginx name: nginx ports: - containerPort: 80
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/excludeOutboundIPRanges: 169.254.169.254/32 traffic.sidecar.istio.io/includeOutboundIPRanges: '*' labels: app: nginx name: all-ip-ranges-included-with-one-allowed-ip-excluded spec: containers: - image: nginx name: nginx ports: - containerPort: 80
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/includeInboundPorts: '*' traffic.sidecar.istio.io/includeOutboundIPRanges: '*' traffic.sidecar.istio.io/includeOutboundPorts: '*' labels: app: nginx name: everything-included-with-no-exclusions spec: containers: - image: nginx name: nginx ports: - containerPort: 80
不允许
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/excludeOutboundIPRanges: 1.1.2.0/24 labels: app: nginx name: disallowed-ip-range-exclusion spec: containers: - image: nginx name: nginx ports: - containerPort: 80 - containerPort: 443
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/excludeOutboundIPRanges: 169.254.169.254/32,1.1.2.0/24 labels: app: nginx name: one-disallowed-ip-exclusion-and-one-allowed-exclusion spec: containers: - image: nginx name: nginx ports: - containerPort: 80 - containerPort: 443
apiVersion: v1 kind: Pod metadata: annotations: traffic.sidecar.istio.io/includeInboundPorts: 80,443 traffic.sidecar.istio.io/includeOutboundIPRanges: 169.254.169.254/32 traffic.sidecar.istio.io/includeOutboundPorts: "8888" labels: app: nginx name: disallowed-specific-port-and-ip-inclusions spec: containers: - image: nginx name: nginx ports: - containerPort: 80
SourceNotAllAuthz
要求 Istio AuthorizationPolicy 规则将来源主体设置为“*”以外的内容。 https://istio.io/latest/docs/reference/config/security/authorization-policy/
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: SourceNotAllAuthz
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
示例
sourcenotall-authz-constraint
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: SourceNotAllAuthz metadata: name: sourcenotall-authz-constraint spec: enforcementAction: dryrun match: kinds: - apiGroups: - security.istio.io kinds: - AuthorizationPolicy
允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-good namespace: foo spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
不允许
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-dne namespace: foo spec: rules: - from: - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-all namespace: foo spec: rules: - from: - source: principals: - '*' - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
apiVersion: security.istio.io/v1beta1 kind: AuthorizationPolicy metadata: name: source-principals-someall namespace: foo spec: rules: - from: - source: principals: - cluster.local/ns/default/sa/sleep - '*' - source: namespaces: - test to: - operation: methods: - GET paths: - /info* - operation: methods: - POST paths: - /data when: - key: request.auth.claims[iss] values: - https://accounts.google.com selector: matchLabels: app: httpbin version: v1
VerifyDeprecatedAPI
验证已弃用的 Kubernetes API,确保所有 API 版本均为最新版本。此模板不适用于审核,因为审核会检查集群内已存在且具有未弃用 API 版本的资源。
限制条件架构
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: VerifyDeprecatedAPI
metadata:
name: example
spec:
# match <object>: lets you configure which resources are in scope for this
# constraint. For more information, see the Constraint match section of the
# Anthos Config Management documentation:
# https://cloud.google.com/anthos-config-management/docs/reference/match
match:
[match schema]
parameters:
# k8sVersion <number>: kubernetes version
k8sVersion: <number>
# kvs <array>: Deprecated api versions and corresponding kinds
kvs:
- # deprecatedAPI <string>: deprecated api
deprecatedAPI: <string>
# kinds <array>: impacted list of kinds
kinds:
- <string>
# targetAPI <string>: target api
targetAPI: <string>
示例
verify-1.16
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.16 spec: match: kinds: - apiGroups: - apps kinds: - Deployment - ReplicaSet - StatefulSet - DaemonSet - apiGroups: - extensions kinds: - PodSecurityPolicy - ReplicaSet - Deployment - DaemonSet - NetworkPolicy parameters: k8sVersion: 1.16 kvs: - deprecatedAPI: apps/v1beta1 kinds: - Deployment - ReplicaSet - StatefulSet targetAPI: apps/v1 - deprecatedAPI: extensions/v1beta1 kinds: - ReplicaSet - Deployment - DaemonSet targetAPI: apps/v1 - deprecatedAPI: extensions/v1beta1 kinds: - PodSecurityPolicy targetAPI: policy/v1beta1 - deprecatedAPI: apps/v1beta2 kinds: - ReplicaSet - StatefulSet - Deployment - DaemonSet targetAPI: apps/v1 - deprecatedAPI: extensions/v1beta1 kinds: - NetworkPolicy targetAPI: networking.k8s.io/v1
允许
apiVersion: apps/v1 kind: Deployment metadata: labels: app: nginx name: allowed-deployment spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80
不允许
apiVersion: apps/v1beta1 kind: Deployment metadata: labels: app: nginx name: disallowed-deployment spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - image: nginx:1.14.2 name: nginx ports: - containerPort: 80
verify-1.22
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.22 spec: match: kinds: - apiGroups: - admissionregistration.k8s.io kinds: - MutatingWebhookConfiguration - ValidatingWebhookConfiguration - apiGroups: - apiextensions.k8s.io kinds: - CustomResourceDefinition - apiGroups: - apiregistration.k8s.io kinds: - APIService - apiGroups: - authentication.k8s.io kinds: - TokenReview - apiGroups: - authorization.k8s.io kinds: - SubjectAccessReview - apiGroups: - certificates.k8s.io kinds: - CertificateSigningRequest - apiGroups: - coordination.k8s.io kinds: - Lease - apiGroups: - extensions - networking.k8s.io kinds: - Ingress - apiGroups: - networking.k8s.io kinds: - IngressClass - apiGroups: - rbac.authorization.k8s.io kinds: - ClusterRole - ClusterRoleBinding - Role - RoleBinding - apiGroups: - scheduling.k8s.io/v1beta1 kinds: - PriorityClass - apiGroups: - storage.k8s.io/v1beta1 kinds: - CSIDriver - CSINode - StorageClass - VolumeAttachment parameters: k8sVersion: 1.22 kvs: - deprecatedAPI: admissionregistration.k8s.io/v1beta1 kinds: - MutatingWebhookConfiguration - ValidatingWebhookConfiguration targetAPI: admissionregistration.k8s.io/v1 - deprecatedAPI: apiextensions.k8s.io/v1beta1 kinds: - CustomResourceDefinition targetAPI: apiextensions.k8s.io/v1 - deprecatedAPI: apiregistration.k8s.io/v1beta1 kinds: - APIService targetAPI: apiregistration.k8s.io/v1 - deprecatedAPI: authentication.k8s.io/v1beta1 kinds: - TokenReview targetAPI: authentication.k8s.io/v1 - deprecatedAPI: authorization.k8s.io/v1beta1 kinds: - SubjectAccessReview targetAPI: authorization.k8s.io/v1 - deprecatedAPI: certificates.k8s.io/v1beta1 kinds: - CertificateSigningRequest targetAPI: certificates.k8s.io/v1 - deprecatedAPI: coordination.k8s.io/v1beta1 kinds: - Lease targetAPI: coordination.k8s.io/v1 - deprecatedAPI: extensions/v1beta1 kinds: - Ingress targetAPI: networking.k8s.io/v1 - deprecatedAPI: networking.k8s.io/v1beta1 kinds: - Ingress - IngressClass targetAPI: networking.k8s.io/v1 - deprecatedAPI: rbac.authorization.k8s.io/v1beta1 kinds: - ClusterRole - ClusterRoleBinding - Role - RoleBinding targetAPI: rbac.authorization.k8s.io/v1 - deprecatedAPI: scheduling.k8s.io/v1beta1 kinds: - PriorityClass targetAPI: scheduling.k8s.io/v1 - deprecatedAPI: storage.k8s.io/v1beta1 kinds: - CSIDriver - CSINode - StorageClass - VolumeAttachment targetAPI: storage.k8s.io/v1
允许
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/rewrite-target: / name: allowed-ingress spec: ingressClassName: nginx-example rules: - http: paths: - backend: service: name: test port: number: 80 path: /testpath pathType: Prefix
不允许
apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/rewrite-target: / name: disallowed-ingress spec: ingressClassName: nginx-example rules: - http: paths: - backend: service: name: test port: number: 80 path: /testpath pathType: Prefix
verify-1.25
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.25 spec: match: kinds: - apiGroups: - batch kinds: - CronJob - apiGroups: - discovery.k8s.io kinds: - EndpointSlice - apiGroups: - events.k8s.io kinds: - Event - apiGroups: - autoscaling kinds: - HorizontalPodAutoscaler - apiGroups: - policy kinds: - PodDisruptionBudget - PodSecurityPolicy parameters: k8sVersion: 1.25 kvs: - deprecatedAPI: batch/v1beta1 kinds: - CronJob targetAPI: batch/v1 - deprecatedAPI: discovery.k8s.io/v1beta1 kinds: - EndpointSlice targetAPI: discovery.k8s.io/v1 - deprecatedAPI: events.k8s.io/v1beta1 kinds: - Event targetAPI: events.k8s.io/v1 - deprecatedAPI: autoscaling/v2beta1 kinds: - HorizontalPodAutoscaler targetAPI: autoscaling/v2 - deprecatedAPI: policy/v1beta1 kinds: - PodDisruptionBudget targetAPI: policy/v1 - deprecatedAPI: policy/v1beta1 kinds: - PodSecurityPolicy targetAPI: None - deprecatedAPI: node.k8s.io/v1beta1 kinds: - RuntimeClass targetAPI: node.k8s.io/v1
允许
apiVersion: batch/v1 kind: CronJob metadata: name: allowed-cronjob namespace: default spec: jobTemplate: spec: template: spec: containers: - command: - /bin/sh - -c - date; echo Hello from the Kubernetes cluster image: busybox:1.28 imagePullPolicy: IfNotPresent name: hello restartPolicy: OnFailure schedule: '* * * * *'
不允许
apiVersion: batch/v1beta1 kind: CronJob metadata: name: disallowed-cronjob namespace: default spec: jobTemplate: spec: template: spec: containers: - command: - /bin/sh - -c - date; echo Hello from the Kubernetes cluster image: busybox:1.28 imagePullPolicy: IfNotPresent name: hello restartPolicy: OnFailure schedule: '* * * * *'
verify-1.26
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.26 spec: match: kinds: - apiGroups: - flowcontrol.apiserver.k8s.io kinds: - FlowSchema - PriorityLevelConfiguration - apiGroups: - autoscaling kinds: - HorizontalPodAutoscaler parameters: k8sVersion: 1.26 kvs: - deprecatedAPI: flowcontrol.apiserver.k8s.io/v1beta1 kinds: - FlowSchema - PriorityLevelConfiguration targetAPI: flowcontrol.apiserver.k8s.io/v1beta3 - deprecatedAPI: autoscaling/v2beta2 kinds: - HorizontalPodAutoscaler targetAPI: autoscaling/v2
允许
apiVersion: flowcontrol.apiserver.k8s.io/v1beta3 kind: FlowSchema metadata: name: allowed-flowcontrol namespace: default spec: matchingPrecedence: 1000 priorityLevelConfiguration: name: exempt rules: - nonResourceRules: - nonResourceURLs: - /healthz - /livez - /readyz verbs: - '*' subjects: - group: name: system:unauthenticated kind: Group
不允许
apiVersion: flowcontrol.apiserver.k8s.io/v1beta1 kind: FlowSchema metadata: name: disallowed-flowcontrol namespace: default spec: matchingPrecedence: 1000 priorityLevelConfiguration: name: exempt rules: - nonResourceRules: - nonResourceURLs: - /healthz - /livez - /readyz verbs: - '*' subjects: - group: name: system:unauthenticated kind: Group
verify-1.27
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.27 spec: match: kinds: - apiGroups: - storage.k8s.io kinds: - CSIStorageCapacity parameters: k8sVersion: 1.27 kvs: - deprecatedAPI: storage.k8s.io/v1beta1 kinds: - CSIStorageCapacity targetAPI: storage.k8s.io/v1
允许
apiVersion: storage.k8s.io/v1 kind: CSIStorageCapacity metadata: name: allowed-csistoragecapacity storageClassName: standard
不允许
apiVersion: storage.k8s.io/v1beta1 kind: CSIStorageCapacity metadata: name: allowed-csistoragecapacity namespace: default storageClassName: standard
verify-1.29
限制
apiVersion: constraints.gatekeeper.sh/v1beta1 kind: VerifyDeprecatedAPI metadata: name: verify-1.29 spec: match: kinds: - apiGroups: - flowcontrol.apiserver.k8s.io kinds: - FlowSchema - PriorityLevelConfiguration parameters: k8sVersion: 1.29 kvs: - deprecatedAPI: flowcontrol.apiserver.k8s.io/v1beta2 kinds: - FlowSchema - PriorityLevelConfiguration targetAPI: flowcontrol.apiserver.k8s.io/v1beta3
允许
apiVersion: flowcontrol.apiserver.k8s.io/v1beta3 kind: FlowSchema metadata: name: allowed-flowcontrol namespace: default spec: matchingPrecedence: 1000 priorityLevelConfiguration: name: exempt rules: - nonResourceRules: - nonResourceURLs: - /healthz - /livez - /readyz verbs: - '*' subjects: - group: name: system:unauthenticated kind: Group
不允许
apiVersion: flowcontrol.apiserver.k8s.io/v1beta2 kind: FlowSchema metadata: name: disallowed-flowcontrol namespace: default spec: matchingPrecedence: 1000 priorityLevelConfiguration: name: exempt rules: - nonResourceRules: - nonResourceURLs: - /healthz - /livez - /readyz verbs: - '*' subjects: - group: name: system:unauthenticated kind: Group
后续步骤
- 详细了解政策控制器
- 安装政策控制器
- 了解如何使用限制条件代替 PodSecurityPolicy
- 在 gatekeeper-library 代码库中查看限制条件模板的开源库