#!/bin/bash
function deploy_k8s(){
  export KKZONE=cn

  # /root/kk 已经通过terrraform provisioner拷贝主机
  chmod 755 /root/kk

  apt-get update -y
  apt-get install -y conntrack ebtables socat

  /root/kk create cluster --with-kubernetes v1.21.5 -y
}

#
function deploy_vulnerable_env(){

  kubectl_bin_path=/usr/local/bin/kubectl
  kubelet_arg_path=/var/lib/kubelet/kubeadm-flags.env
  yaml_path=/root/pod.yaml

  # 使用docker网络
  sed -i 's/--network-plugin=cni//' $kubelet_arg_path
  service kubelet restart
  sleep 60
  echo '[done] "kubelet" restart'

  # 模拟漏洞
  sysctl -w net.ipv4.conf.all.route_localnet=1
  sysctl -w net.ipv4.conf.default.route_localnet=1
  sysctl -w net.ipv4.conf.docker0.route_localnet=1

  sysctl -w net.ipv4.conf.all.accept_local=1
  sysctl -w net.ipv4.conf.default.accept_local=1
  sysctl -w net.ipv4.conf.docker0.accept_local=1

  nsenter -n -t 1 iptables -D KUBE-FIREWALL 2 # -A KUBE-FIREWALL ! -s 127.0.0.0/8 -d 127.0.0.0/8 -m comment --comment "block incoming localnet connections" -m conntrack ! --ctstate RELATED,ESTABLISHED,DNAT -j DROP

  # 宿主机上有部分服务在 127.0.0.1 监听
  # root@iZj6ce4bmwc11otulk7i3rZ:~# netstat -antp|grep 127.0.0.1
  # tcp        0      0 127.0.0.1:37953         0.0.0.0:*               LISTEN      2551/containerd
  # tcp        0      0 127.0.0.1:41351         0.0.0.0:*               LISTEN      15900/kubelet
  # tcp        0      0 127.0.0.1:10248         0.0.0.0:*               LISTEN      15900/kubelet

  # 部署恶意pod
  $kubectl_bin_path apply -f $yaml_path
  sleep 60
  echo '[done] "test-pod" create'
}

deploy_k8s
echo "[done] 'k8s cluster' deploy" && sleep 60
deploy_vulnerable_env
