Iptables

過濾 docker 流量

  • November 28, 2019

我的系統上有許多帶有自己埠的 docker 容器。Docker 使用 IPTables 做了一些魔術,因此很難為它定義一些自定義規則。

僅對於 http 連接,反向代理沒有問題 - 所以我可以使用在主機上執行的 nginx 定義我自己的規則(如 SYN 洪水保護)。

但現在我想將名稱伺服器作為 docker-container 執行。為了保護放大攻擊,我寫了一條規則,但是 docker-iptables-magic 繞過了這條規則。

所以我試圖欺騙。我將名稱伺服器的已發布埠更改為其他埠(5353)。我的計劃是製定這樣的規則

# rules defined via ferm

table filter {
  chain INPUT {
     POLICY DROP;

     # drop any-query for nameserver
     proto udp dport (53) {
        mod string from 40 algo bm hex-string "|0000ff0001|" DROP;

        # my old rule would jump to ACCEPT now
        ACCEPT;

        # but I think would be nice, when can route the packet now
        # routing isn't allowed here
        REDIRECT to-ports 5353;
     }
  }
}


table nat {
  chain PREROUTING {
     # I also tried to preroute the packet
     # but then will match the docker-rule again 
     # and I cant protect the port
     proto udp dport 53 REDIRECT to-ports 5353;
  }
}

有人有想法嗎?我也完全接受其他解決方案 - 是否可以選擇 UDP 中繼?

我做到了!@preserve是關鍵字。這告訴 ferm 保持這些鏈條不受影響。在這裡找到它https://www.lullabot.com/articles/convincing-docker-and-iptables-play-nicely

這是我的新配置

#vars
@def $WG_PORT = XXX;
@def $TCP_PORTS = (80 443 22);


table filter {

   # keep docker-chains
   chain (DOCKER DOCKER-INGRESS DOCKER-ISOLATION-STAGE-1 DOCKER-ISOLATION-STAGE-2 FORWARD KUBE-FIREWALL DOCKER-USER) @preserve;    

   chain mainRules {
       #allow local and wireguard
       interface (lo wg0 docker0 br+) ACCEPT;
       source 127.0.0.1 ACCEPT;

       #keep connected
       mod conntrack ctstate (ESTABLISHED RELATED) jump ACCEPT;

       #icmp
       proto icmp {
           mod limit limit  10/minute limit-burst 10 ACCEPT;
           DROP;
       }

       # allow wireguard-traffic instant
       proto udp dport ($WG_PORT) ACCEPT;


       # drop any-query for nameserver when udp
       proto udp dport (53) {
           mod string from 40 algo bm hex-string "|0000ff0001|" DROP;
           ACCEPT;
       }

       #tcp
       proto tcp dport ($TCP_PORTS) {

           #prevent syn-flood, but accept other
           syn {
               mod limit limit 10/sec limit-burst 10 jump PREACCEPT;
               DROP;
           }

           jump ACCEPT;
       }
   }


   chain INPUT {
       policy DROP;
       jump mainRules;
   }

   chain OUTPUT {
       policy ACCEPT;
   }

   chain FORWARD {
       policy ACCEPT;
   }
}

table nat {

   chain (DOCKER DOCKER-INGRESS PREROUTING POSTROUTING OUTPUT DOCKER-USER KUBE-POSTROUTING) @preserve;
}

現在 ferm 和 docker 一起玩得很好。

引用自:https://unix.stackexchange.com/questions/552685