Reading guide

Pod The container wants to get the resource information of the cluster , You need to configure roles and ServiceAccount To authorize . For better control of Pod How resources are used ,Kubernetes from 1.4 Version started to be introduced PodSecurityPolicy Resource object pair Pod Security policy management .

Pod Privilege mode

Processes inside the container get almost the same privileges as processes outside the container . Use privilege mode , It's easier to write network and volume plug-ins as separate pod, No need to compile to kubelet in .

PodSecurityPolicy

Official website definition

Pod The security policy (Pod Security Policy) It's a cluster level resource , It can control Pod Statute Security related aspects of .PodSecurityPolicy Object defines a set of Pod The conditions that must be followed at runtime and the default values of the related fields , Only Pod Only when these conditions are met can the system accept it .

Pod Security policy allows administrators to control the following aspects :

Pod The security policy It consists of settings and policies , They can control Pod Security features of access . These settings fall into three categories :

(1) Based on Boolean control : This type of field defaults to the most restrictive value .

(2) Control based on the set of allowed values : This type of field is compared to this set of values , Allowed with confirmation value .

(3) Based on policy control : The setting item generates the value through a policy provided mechanism , This mechanism ensures that the specified values fall within the allowed set of values .

Turn on

If it needs to be turned on PodSecurityPolicy, Need to be in kube-apiserver Set the following parameters in the startup parameters of

--enable-admission-plugins=PodSecurityPolicy

In the open PodSecurityPolicy After entering the controller ,k8s It is not allowed to create any by default Pod, Need to create PodSecurityPolicy and RBAC The authorization policy ,Pod To create a successful .

notes : modify kube-apiserver The configuration file /etc/kubernetes/manifests/kube-apiserver.yaml, Because it is static pod, So the changes will take effect .

By default, this parameter is :

--enable-admission-plugins=NodeRestriction

Open and create Pod The following error occurs :

establish PodSecurityPolicy

The following PodSecurityPolicy Indicates that privilege mode creation is not allowed Pod

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: psp-non-privileged
spec:
privileged: false # Privilege mode is not allowed Pod
seLinux:
rule: RunAsAny
supplementalGroups:
rule: RunAsAny
runAsUser:
rule: RunAsAny
fsGroup:
rule: RunAsAny
volumes:
- '*'

View after creation :

kubectl get psp
perhaps
kubectl get podSecurityPolicy

And then create it again Pod You can create it

above PodSecurytiPolicy The privilege mode is not allowed to be created Pod, for example , In the following YAML The configuration file pod-privileged.yaml In Chinese, it means Pod Set privilege mode :

apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- name: nginx
image: nginx:latest
imagePullPolicy: IfNotPresent
ports:
- containerPort: 80
securityContext:
privileged: true

The following error will be reported when creating :

unable to validate against any pod security policy

PodSecurityPolicy Configuration details

stay PodSecurityPolicy The following fields can be set in the object to control Pod Various security policies at runtime

(1) Privilege mode related configuration

privileged: Whether to allow Pod Run in privileged mode

(2) Host resource related configuration

1、hostPID: Whether to allow Pod Shared host process space

2、hostIPC: Whether to allow Pod Sharing host IPC Namespace

3、hostNetwork: Whether to allow Pod Shared host network namespace

4、hostPorts: Whether to allow Pod Use the host port number , Can pass hostPortRange Field to set the allowed port number range , With [min, max] Set the minimum port number and the maximum port number

5、Volumes: allow Pod Used storage volume Volume type , Set to “*” Indicates that you are allowed to use any Volume type , It is suggested that at least Pod Use the following Volume type .configMap,emptyDir、downwardAPI、persistentVolumeClaim、secret、projected

6、AllowedHostPaths: allow Pod Using the host hostPath Path name , It can be done by pathPrefix Field to set the prefix of the path , And you can set whether the property is read-only or not , for example : Only Pod Visit the host to “/foo” Path for prefix , package enclosed “/foo”“/foo/”“/foo/bar” etc. ,

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: all-hostpath-volumes
spec:
volumes:
- hostPath
allowedHostPaths:
- pathPrefix: "/foo"
readOnly: true

7、FSGroup: Set to allow access to some Volume Of Group ID Range , Can be rule Field set to ManyRunAs、MayRunAs、RunAsAny

MustRunAs: Need to set up Group ID The scope of the , for example 1~65535, requirement Pod Of securityContext.fsGroup The set value must belong to the Group ID The scope of the .

MayRunAs: Need to set up Group ID The scope of the , for example 1~65535, It's not mandatory Pod Set up securityContext.fsGroup.

RunAsAny: Don't limit Group ID The scope of the , whatever Group All accessible Volume.

8、ReadOnlyRootFilesystem: The root file system that the container is required to run (root filesystem) It has to be read-only

9、allowedFlexVolumes: For types of flexVolume The storage volume of , Set the type of driver allowed , for example :

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: allowedflexvolumes
spec:
volumes:
- flexVolume
allowedFlexVolumes:
- driver: example/lvm
- driver: example/cifs

(3) User and group related configuration

1、RunAsUser: Set up the user running the container ID Range ,rule Can be set to MustRunAs、MustRunAsNonRoot or RunAsAny

MustRunAs: Need to set up User ID The scope of the , requirement Pod Of securityContext.runAsUser The set value must belong to the User ID The scope of the .

MustRunAsNonRoot: It has to be non root User run container , requirement Pod Of securityContext.runAsUser Set a non 0 Users of ID, Or in the mirror image USER Field sets the user ID, It is recommended to set it at the same time allowPrivilegeEscalation=false To avoid not Raise the necessary permissions .

RunAsAny: Don't limit User ID The scope of the , whatever User Can run .

2、RunAsGroup: Set the running container's Group ID Range , Can be set to MustRunAs、MustRunAsNonRoot、RunAsAny

MustRunAs: Need to set up Group ID The scope of the , requirement Pod Of securityContext.runAsGroup The set value must belong to the Group ID The scope of the .

MustRunAsNonRoot: It has to be non root Group run container , requirement Pod Of securityContext.runAsUser Set a non 0 Users of ID, Or in the mirror image USER Field sets the user ID, It is recommended to set it at the same time allowPrivilegeEscalation=false In order to avoid unnecessary privilege operation .

RunAsAny: Don't limit Group ID The scope of the , whatever Group All users can run .

3、SupplementalGroups: Set the container to add additional Group ID Range , You can put the rules (rule Field ) Set to MustRunAs、MayRunAs or RunAsAny

MustRunAs: Need to set up Group ID The scope of the , requirement Pod Of securityContext.supplementalGroups The set value must belong to the Group ID Range .

MayRunAs: Need to set up Group ID The scope of the , It's not mandatory Pod Set up securityContext.supplementalGroups.

RunAsAny: Don't limit Group ID The scope of the , whatever supplementalGroups All users can run .

(4) Enhance the configuration of privilege

1、AllowPrivilegeEscalation: It is used to set whether the child process in the container can be promoted , It's usually set to not Root user (MustRunAsNonRoot) Set when .

2、DefaultAllowPrivilegeEscalation: Set up AllowPrivilegeEscalation The default value of , Set to disallow when , Administrators can also explicitly set AllowPrivilegeEscalation To specify whether permission elevation is allowed .

(5)Linux Capability related configuration

1、AllowedCapabilities: Set the container to use linux Ability list , Set to “*” Indicates permission to use Linux All abilities ( Such as NET_ADMIN、SYS_TIME etc. ).

2、RequiredDropCapabilities: Set the container is not allowed to use linux Ability list

3、DefaultAddCapabilities: Set default to container added Linux Ability list , for example SYS_TIME etc.

(6)SELinux Related configuration

seLinux: Set up SELinux Parameters , You can put the rule field (rule) Is set to MustRunAs or RunAsAny.

MustRunAs: It is required to set seLinuxOptions, The system will Pod Of securityContext.seLinuxOptions Set the value for verification .

RunAsAny: Don't limit seLinuxOptions Set up

(7) Other Linux Related configuration

1、AllowedProcMountType: Set allowed PropMountTypes Type list , You can set allowedProcMountTypes or DefaultProcMount.

2、AppArmor: Set access control permissions for container executable programs ,

3、Seccomp: Set the system calls that the container is allowed to use (System Calls) Of profile

4、Sysctl: Set the kernel parameters that are allowed to be adjusted ,

(8) List two commonly used PodSecurityPolicy Security policy configuration

1、 Basic unlimited security policy , Allows the creation of arbitrary security settings Pod.

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: privileged
annotations:
seccomp.security.alpha.kubernetes.io/allowedProfileNames: "*"
spec:
privileged: true # It is not allowed to create privilege mode Pod
allowPrivilegeEscalation: true # Set whether the child process can elevate permissions , To configure MustRunAsNonRoot
allowedCapabilities:
- '*'
volumes:
- '*'
hostNetwork: true
hostPorts:
- min: 0
max: 65535
hostIPC: true
hostPID: true
runAsUser:
rule: 'RunAsAny'
seLinux:
rule: 'RunAsAny'
supplementalGroups:
rule: 'RunAsAny'
fsGroup:
rule: 'RunAsAny'

2、 requirement Pod The running user is a non privileged user ; Prohibit elevation of authority ; Host network is not allowed 、 Port number 、IPC And so on ; Limit what can be used Volume type , wait

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: retricted
annotations:
seccomp.security.alpha.kubernetes.io/allowedProfileNames: 'docker/default'
seccomp.security.alpha.kubernetes.io/defaultProfileNames: 'docker/default'
apparmor.security.beta.kubernetes.io/allowedProfileNames: 'runtime/default'
apparmor.security.beta.kubernetes.io/defaultProfileNames: 'runtime/default'
spec:
privileged: false
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
- 'downwardAPI'
- 'persistentVolumeClaim'
hostNetwork: false
hostIPC: false
hostPID: false
runAsUser:
rule: 'MustRunAsNonRoot'
seLinux:
rule: 'RunAsAny'
supplementalGroups:
rule: 'MustRunAsRoot'
ranges:
- min: 1
max: 65535
fsGroup:
rule: 'MustRunAsRoot'
ranges:
- min: 1
max: 65535
readOnlyRootFilesystem: false

Kubernetes It is recommended to use RBAC Authorization mechanism to set up for Pod Authorization of security policy , You should usually be right about Pod Of ServiceAccount To authorize .

for example , You can create the following ClusterRole( You can also create Role) And set it to allow the use of PodSecurityPolicy:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: role-name
rules:
- apiGroups: ['policy']
resources: ['podsecuritypolicies']
verbs: ['use']
resourceNames:
- # permissible PodSecurityPolicy list

And then create a ClusterRoleBinding With users and ServiceAccount Binding

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: bind-name
ruleRef:
kind: ClusterRole
name: role-name
apiGroup: rabc.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: serviceaccount
namespace:
- kind: User
name: username
apiGroup: rbac.authorization.k8s.io

You can also create RoleBinding Yes, it is RoleBinding same Namespace Medium Pod To authorize , Usually it can be associated with some system level Group Association configuration , for example :

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bind-name
namespace: namespace # The RoleBinding Of namespace
roleRef:
kind: Role
name:
apiGroup: rabc.authorization.k8s.io
subjects:
# Authorize the Namespace All of ServiceAccount
- kind: Group
apiGroup: rabc.authorization.k8s.io
name: system:serviceaccounts
# Authorize the Namespace All users of
- kind: User
apiGroup: rabc.authorization.k8s.io
name: system:authenticated

Pod Security settings for

Pod And container security policies can be found in Pod or Container Of securityContext Field , If in Pod and Container Levels have the same security type field set , The container will use Container Level settings .

stay Pod The security measures that can be set at the level are as follows :

◎ runAsUser: The user running the program in the container ID.

◎ runAsGroup: The user group that runs the program in the container ID.

◎ runAsNonRoot: Whether it is necessary to use non root The user runs the program .◎ fsGroup:SELinux Related settings .

◎ seLinuxOptions:SELinux Related settings .

◎ supplementalGroups: Other user groups that the container is allowed to use ID.

◎ sysctls: Set the kernel parameters that are allowed to be adjusted .

stay Container The security policy types that can be set at level are as follows :

◎ runAsUser: The user running the program in the container ID.

◎ runAsGroup: The user group that runs the program in the container ID.

◎ runAsNonRoot: Whether it is necessary to use non root The user runs the program .

◎ privileged: Whether to run in privileged mode .

◎ allowPrivilegeEscalation: Whether to allow elevation of permissions .

◎ readOnlyRootFilesystem: Whether the root file system is read-only .

◎ capabilities:Linux Ability list .

◎ seLinuxOptions:SELinux Related settings .

for example :Pod Level security settings , Act on the Pod All the containers inside

apiVersion: v1
kind: Pod
metadata:
name: security-context-demo
spec:
securityContext:
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
volumes:
- name: sec-ctx-vol
emptyDir: {}
containers:
- name: sec-ctx-demo
image: nginx
volumeMounts:
- name: sec-ctx-demo
mountPath: /data/demo
securityContext:
allowPrivilegeEscalation: false

◎ runAsUser=1000: All containers will be in User ID 1000 Run the program , All newly generated files User ID It's also set to 1000.

◎ runAsGroup=3000: All containers will be in Group ID 3000 Run the program , All newly generated files Group ID It's also set to 3000.

◎ fsGroup=2000: Mounted volume “/data/demo” And the files created in it will belong to Group ID 2000.

Container Level security settings , Acting on a particular container .

apiVersion: v1
kind: Pod
metadata:
name: scd-2
spec:
securityContext:
runAsUser: 1000
containers:
- name: scd-2
image: nginx:latest
imagePullPolicy: IfNotPresent
securityContext:
runAsUser: 2000
allowPrivilegeEscalation: false

by Container Set available Linux Ability , Set the allowed... For the container Linux Abilities include NET_ADMIN and SYS_TIME.

apiVersion: v1
kind: Pod
metadata:
name: scd-3
spec:
containers:
- name: scd-3
image: nginx
securityContext:
capabilities:
add: ["NET_ADMIN","SYS_TIME"]

===============================

I am a Liusy, A programmer who likes to keep fit .

Get more dry goods and the latest news , Please pay attention to the official account. : Ancient false gods

If it helps you , A little attention is my biggest support !!!

Article to read k8s And Pod More articles on Security Policy

  1. kubernetes Basics —— Article to read k8s

    Containers Container vs. virtual machine ( On the left is the container . On the right is the virtual machine ) Container technology is a kind of virtualization technology , With Docker For example ,Docker utilize Linux Of LXC(LinuX Containers) technology .CGroup(Co ...

  2. Article to read HTTP/2 And HTTP/3 characteristic

    Abstract : Study HTTP/2 And HTTP/3. Preface HTTP/2 Compared with HTTP/1, It can be said that the performance of the web page has been greatly improved , Only upgrading to this protocol can reduce a lot of previous performance optimization work , Of course, compatibility issues and how to ...

  3. Article to read AI Brief history : At that time, countries made a wish by burning money , Some of them have not yet been realized

    Article to read AI Brief history : At that time, countries made a wish by burning money , Some of them have not yet been realized Reading guide : In recent days, , Jack ma, . ma . Robin Li and other Internet gangs appeared 2018 World Conference on Artificial Intelligence , And speak on the stage . About the current situation and future of artificial intelligence , They put forward their own views , Also cited ...

  4. Read and understand high performance network programming I/O Model

    1. Preface With the development of the Internet , In the face of massive users and high concurrency business , The traditional blocking server-side architecture model has been powerless . this paper ( And the next part < High performance network programming ( 6、 ... and ): Read the thread model in high performance network programming >) It aims to provide you with useful ...

  5. from HTTP/0.9 To HTTP/2: Article to read HTTP The historical evolution and design ideas of the agreement

    Ruan Yifeng, the original author of this paper , The author blog :ruanyifeng.com. 1. introduction HTTP Protocol is one of the most important basic Internet protocols , It evolved from just browsing the web to now , It's the de facto industry standard for short link communications , The latest version HT ...

  6. Article to read Deep reinforcement learning algorithm A3C (Actor-Critic Algorithm)

    Article to read Deep reinforcement learning algorithm A3C (Actor-Critic Algorithm) 2017-12-25  16:29:19   about A3C Algorithms feel like they always know a little , Now let's sort it out , Record here , also ...

  7. [ Re posting ]MerkleDAG Comprehensive analysis Read what Merkel's directed acyclic graph is

    MerkleDAG Comprehensive analysis Read what Merkel's directed acyclic graph is 2018-08-16 15:58 Blockchain / technology MerkleDAG As IPFS The core data structure of , It is a blend of Merkle Tree and DAG The advantages of , today ...

  8. [ Re posting ] Article to read HTTP/2

    Article to read HTTP/2 http://support.upyun.com/hc/kb/article/1048799/ It's a little shot  •  Published in :2017 year 05 month 18 Japan 15:34:45 •  Updated on :201 ...

  9. [ Re posting ] from HTTP/0.9 To HTTP/2: Article to read HTTP The historical evolution and design ideas of the agreement

    from HTTP/0.9 To HTTP/2: Article to read HTTP The historical evolution and design ideas of the agreement   http://www.52im.net/thread-1709-1-2.html     Ruan Yifeng, the original author of this paper , The author blog :r ...

  10. Article to read HDMI and VGA Interface pin definition

    Article to read HDMI and VGA Interface pin definition Excerpt from :http://www.elecfans.com/yuanqijian/jiekou/20180423666604.html   HDMI summary HDMI It's HD ...

Random recommendation

  1. MySql Miscellany

    1: Make a statement int variable , Set it to... By default 0, Not empty or null. int type , Value range -2,147,483,648 To 2,147,483,647 , The default value is 0 int Value type , Read the specified length in the memory range ...

  2. DELPHI Excellent open source frameworks :QDAC,MORMOT,DIOCP

    DELPHI Excellent open source frameworks :QDAC,MORMOT,DIOCP Programmers do any language program development to a certain level , If you want to improve , You have to get in touch with and learn to use good open source frameworks . MORMOT Encapsulates the WINDOWS Abreast of the times H ...

  3. C# Call the console program , And get the output and write it to the file

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  4. C# Chapter 6 function -2- entrust

    entrust :

  5. Android Status bar transparent ( Immersive effect )

    Android Status bar transparent ( Immersive effect ) Default effect Immersive effect Mode one Source code Download address (Android Studio engineering ):http://download.csdn.net/detail/q487880 ...

  6. be based on Zookeeper Implementation of multi process distributed lock

    One .zookeeper Introduction and basic operation Zookeeper  It's not for storing data , It is mainly used to maintain and monitor the status change of the data you store . When monitoring status of directory node is on , Once the state of the directory node changes ,Watc ...

  7. Open source streaming server SRS Learning notes (4) - Cluster Cluster solution

    Live broadcast on a single server , There's always a single risk , utilize SRS Of Forward Mechanism + Edge Server Design , It's easy to build a large-scale high availability cluster , The schematic diagram is as follows Source server cluster :origin server clus ...

  8. Js Summary of programming problems

    Coding topic : 1. Predict the output of the following code : var Foo = function(a) { function bar() { console.log(a); }; this.baz = func ...

  9. unity3d- The code controls the movement of the game character controller

    On the first one gif Look at the effect . Because of the size limit . So the recording is relatively small . I think the effect is far fetched . Especially the logic code inside . But I still think it's all about achieving , Because I'm new to it . Engineering structure drawing The effect of this implementation is : 1: taken ...

  10. Confluence 6 Create your personal space

    As a novice in a project , You may want to save some work as visible to yourself , Until you're ready to share your work . At the same time, you may receive a message from the mission command center that is only for your mission , You also want these tasks to be stored in a safe place . For tasks like this, we need ...