Leif160519的blog Leif160519的blog

——————

目录
Kubernetes安全框架(下)-网络策略
/    

Kubernetes安全框架(下)-网络策略

1.网络策略概述

网络策略(Network Policy),用于限制Pod出入流量,提供Pod级别和Namespace级别网络访问控制。

一些应用场景:

  • 应用程序间的访问控制。例如微服务A允许访问微服务B,微服务C不能访问微服务A
  • 开发环境命名空间不能访问测试环境命名空间Pod
  • 当Pod暴露到外部时,需要做Pod白名单
  • 多租户网络环境隔离

1.1 Pod网络入口方向隔离:

  • 基于Pod级网络隔离:只允许特定对象访问Pod(使用标签定义),允许白名单上的IP地址或者IP段访问Pod
  • 基于Namespace级网络隔离:多个命名空间,A和B命名空间Pod完全隔离。

1.2 Pod网络出口方向隔离:

  • 拒绝某个Namespace上所有Pod访问外部
  • 基于目的IP的网络隔离:只允许Pod访问白名单上的IP地址或者IP段
  • 基于目标端口的网络隔离:只允许Pod访问白名单上的端口

网络策略依赖cni插件,常用cni插件为flannel和calico,而flannel不支持网略策略,cni支持

image.png

podSelector:策略应用的pod
ingress:进流量,控制谁来访问我
egress:出流量,控制我能访问谁

2.示例

  • 将default命名空间携带app=web标签的Pod隔离,只允许default命名空间携带run=client1标签的Pod访问80端口。
    ·test-network-policy.yaml·
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: web
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          project: default
    - podSelector:
        matchLabels:
          run: client1
    ports:
    - protocol: TCP
      port: 80

准备app=web的一个pod
image.png

再准备两个pod:

kubectl run -it --rm client1 --image=busybox:1.28.4 sh
kubectl run -it --rm client2 --image=busybox:1.28.4 sh

[root@k8s-master network-policy]# kubectl get pod --show-labels 
NAME                   READY   STATUS    RESTARTS   AGE   LABELS
client1                1/1     Running   0          12m   run=client1
client2                1/1     Running   0          11m   run=client2
web-5dcb957ccc-kb4vz   1/1     Running   0          22m   app=web,pod-template-hash=5dcb957ccc

应用网略策略:

kubectl apply -f test-networkpolicy.yaml

[root@k8s-master network-policy]# kubectl get networkpolicy
NAME                  POD-SELECTOR   AGE
test-network-policy   app=web        41m

测试两个busybox的pod发现,run=client1的可以访问web pod,而client2不能

  • default命名空间下所有pod可以互相访问,也可以访问其他命名空间Pod,但其他命名空间不能访问default命名空间Pod。

deny-from-other-namespace.yaml

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: deny-from-other-namespaces
  namespace: default
spec:
  podSelector: {} # 不配置,默认是该命名空间下所有pod
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector: {} #不配置,默认是不允许

准备两个pod

kubectl run -it --rm client1 --image=busybox:1.28.4 sh
kubectl run -it --rm client2 --image=busybox:1.28.4 sh -n kube-system

应用策略后,发现,client1可以访问client2,但client2却不能访问client1,client1也能访问同命名空间下的web pod。


“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill

标  题Kubernetes安全框架(下)-网络策略
作  者Leif160519
出  处https://github.icu/articles/2020/08/08/1596876685752.html
关于博主:坐标六朝古都南京,服务器运维工程师+桌面运维工程师,如有问题探讨可以直接下方留言。
声援博主:如果您觉得文章对您有帮助,可以评论、订阅、收藏。您的鼓励是博主的最大动力!