Skip to content

Фильтрация трафика внутри кластера

Цель: Проверить работоспособность Network Policy для приложения, произвести настройку согласно NetworkPolicy.

Запуск тестового Deployment

Скачать нужный образ nginx:

console
$ podman pull --tls-verify=false ghcr.io/linuxserver/nginx:latest && \
$ curl http://localhost:5002/v2/_catalog | jq && \
$ curl http://localhost:5002/v2/ghcr.io/linuxserver/nginx/tags/list | jq && \
$ podman pull --tls-verify=false localhost:5002/ghcr.io/linuxserver/nginx:latest

Создать nginx Deployment:

console
$ kubectl create deployment nginx --image=ghcr.io/linuxserver/nginx

Вывод:

text
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
deployment.apps/nginx created

Обеспечить доступ к развертыванию посредством сервиса с именем nginx.

console
$ kubectl expose deployment nginx --port=80

Вывод:

text
service/nginx exposed

Получить информацию о сервисах и подах:

console
$ kubectl get svc,pod

Получен IP-адрес сервиса и состояния пода nginx в статусе Running. Примерный вывод:

text
NAME                        TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
service/kubernetes          ClusterIP   10.96.0.1       <none>        443/TCP    11d
service/nginx               ClusterIP   10.102.3.224    <none>        80/TCP     14m
service/postgres-operator   ClusterIP   10.96.233.151   <none>        8080/TCP   6d15h

NAME                                     READY   STATUS    RESTARTS        AGE
pod/nginx-5557d9f6b4-lbhzd               1/1     Running   0               2m31s
pod/postgres-operator-849bdbdbd8-sqj7n   1/1     Running   1 (3d18h ago)   6d15h

Тестирование доступа с другого пода

Скачать нужный образ busybox:

console
$ podman pull --tls-verify=false ghcr.io/containerd/busybox:latest && \
$ curl http://localhost:5002/v2/_catalog | jq && \
$ curl http://localhost:5002/v2/ghcr.io/containerd/busybox/tags/list | jq && \
$ podman pull --tls-verify=false localhost:5002/ghcr.io/containerd/busybox:latest

Запустить контейнер busybox:

console
$ kubectl run busybox --rm -ti --image=ghcr.io/containerd/busybox:latest -- /bin/sh

Проверить доступ к поду nginx:

console
[busybox]# wget --spider --timeout=1 nginx

Доступ к поду Nginx получен:

text
Connecting to nginx (10.102.3.224:80)
remote file exists

Ограничение доступа к службе nginx

Создать файл NetworkPolicy:

console
$ cat > nginx-policy.yaml <<'EOF'
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: access-nginx
spec:
  podSelector:
    matchLabels:
      app: nginx
  ingress:
  - from:
    - podSelector:
        matchLabels:
          access: "true"
EOF

Применить политику:

console
$ kubectl apply -f nginx-policy.yaml

Политика создана:

text
networkpolicy.networking.k8s.io/access-nginx created

Повторное тестирование доступа с другого пода

Запустить контейнер busybox:

console
$ kubectl run busybox --rm -ti --image=ghcr.io/containerd/busybox:latest -- /bin/sh

Проверить доступ к поду nginx:

console
[busybox]# wget --spider --timeout=1 nginx

Доступ к поду Nginx отсутствует:

text
Connecting to nginx (10.111.250.10:80)
wget: download timed out

Объявить метку и выполнить повторное тестирование с другого пода

Запустить контейнер busybox с меткой access=true:

console
$ kubectl run busybox --rm -ti --labels="access=true" --image=ghcr.io/containerd/busybox:latest -- /bin/sh

Проверить доступ к поду nginx:

console
[busybox]# wget --spider --timeout=1 nginx

Доступ к поду Nginx получен:

text
Connecting to nginx (10.111.250.10:80)
remote file exists

Удалить Deployment Nginx

console
$ kubectl delete deployment nginx

Фильтрация трафика на уровне L7 внутри кластера

Цель: Создать сетевую политику NetworkPolicy, которая ограничивает доступ запросов, проверить доступность.

Создать тестовый Namespace:

console
$ kubectl create namespace network-policy-test

Развернуть тестовый под nginx:

console
$ kubectl run web-server --image=ghcr.io/linuxserver/nginx -n network-policy-test --labels="app=web-server"

Создать сервис web-server:

console
$ kubectl expose pod web-server --port=80 --target-port=80 --namespace=network-policy-test

Развернуть клиент:

console
$ kubectl run client-pod --image=ghcr.io/curl/curl-container/curl:master -n network-policy-test --labels="app=client" -- sh -c 'while true; do sleep 3600; done'

Создание сетевой политики:

console
$ kubectl exec -it client-pod -n network-policy-test -- curl --max-time 3 http://web-server | grep -i welcome
$ kubectl exec -it client-pod -n network-policy-test -- curl --max-time 3 http://web-server/index.html | grep -i welcome

Команда успешно выполняется и возвращает HTML-код стандартной страницы приветствия Nginx. Это подтверждает, что между подами есть сетевая связность. Вывод:

text
            <title>Welcome to our server</title>
                <h1>Welcome to our server</h1>

Создать политику L7:

console
$ cat > l7-nginx-policy.yaml <<'EOF'
apiVersion: "cilium.io/v2"
kind: CiliumNetworkPolicy
metadata:
  name: "allow-get-to-index-html"
  namespace: network-policy-test
spec:
  endpointSelector:
    matchLabels:
      app: web-server
  ingress:
  - fromEndpoints:
    - matchLabels:
        app: client
    toPorts:
    - ports:
      - port: "80"
        protocol: TCP
      rules:
        http:
        - method: "GET"
          path: "/index.html"
EOF

Применить политику L7:

console
$ kubectl apply -f l7-nginx-policy.yaml

Политика применилась:

text
ciliumnetworkpolicy.cilium.io/allow-get-to-index-html created

Проверить доступность разрешенного пути:

console
$ kubectl exec -it client-pod -n network-policy-test -- curl --max-time 3 http://web-server/index.html | grep -i welcome

Путь доступен:

text
            <title>Welcome to our server</title>
                <h1>Welcome to our server</h1>

Проверить доступность запрещенного пути методов GET и POST:

console
$ kubectl exec -it client-pod -n network-policy-test -- curl --max-time 3 http://web-server/
$ kubectl exec -it client-pod -n network-policy-test -- curl -X POST --max-time 3 http://web-server/index.html

Доступ запрещен:

text
Access denied

Удалить тестовое пространство имён, чтобы удалить все созданные ресурсы:

console
$ kubectl delete namespace network-policy-test

Опубликовано под лицензией GPL-3.0+. Содержание доступно по лицензии CC BY-SA 4.0, если не указано иное. Разработано участниками ALT Orchestra.