Iptables

DNAT 到同一主機上的另一個隱藏埠

  • February 14, 2021

我希望使用 iptables 將到達公共 eth 介面(公共 IPv4 地址)上的特權埠的傳入流量靜默重定向到同一 ubuntu 機器上的隱藏非特權埠。ufw 防火牆處於活動狀態。當然,還有其他選項,例如功能,或將流量複製到非特權埠的特權程序,或在綁定後刪除其 privs 的特權程序等,但至少對我來說,iptables 似乎是最吸引人的。

DNAT 到 127.0.0.1的虛擬介面解決方案帶有 iptables / 透明 SOCKS 代理的目標訪問控制對我來說是完美的(一旦我在 ip add addr… 命令中插入一個額外的“dev”關鍵字)。除了一件事:

  • 我必須為隱藏埠上虛擬介面 IP 的傳入流量打開防火牆

據我所知,這允許其他人將傳入流量直接發送到該 IP:埠,如果他們能夠猜測大約 40 位隱藏資訊(私有 IPv4 地址 + 埠)。

是否有沒有外部流量可以到達該隱藏埠的解決方案,除非原始目標 IP 是盒子的公共 IP,而目標埠是特權埠?


$$ In everyday terms, the dummy interface solution is like having my buddy come to my club, and telling him that here is a VIP pass, take it to the back entrance, and the bouncer will let you in. He will get in, sure, but anyone else may try to fool the bouncer with a fake pass. Can I instead escort my buddy to the back entrance, tell the bouncer he is good, and walk in with him? In other words, can I mark this NATted packet somehow that the firewall rules are bypassed on it? $$

與此同時,我了解到一個 CAN 標記數據包(請參閱,例如,如何在 nat 預路由表中轉發數據包時在數據包上設置標記?),並且還了解了更多關於何時應用哪些 iptables 操作(https://www.digitalocean .com/community/tutorials/a-deep-dive-into-iptables-and-netfilter-architecture)。有了這些,解決方案很簡單:

  1. 在 /etc/ufw/before.rules 中,添加一條 MANGLE 規則:
*mangle
-F
-A PREROUTING -p tcp -i eth0 -d 1.2.3.4 --dport 80 -j MARK --set-mark 0x401
COMMIT
  1. 在同一個文件中,將重定向插入到 NAT 表規則(*nat 部分)中
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
  1. 最後,插入到 FILTER 表(*filter 部分)的 ufw-before-input 鏈中
-A ufw-before-input -m mark --mark 0x401 -j ACCEPT
  1. 重啟ufw
services ufw restart

無需打開任何埠,到 1.2.3.4:80 的傳入數據包會被重定向到 1.2.3.4:8080 並通過防火牆顯式綠燈。iptables對數據包的操作時間順序為:mark、redirect、let through。

您可以跳過虛擬介面並將此類流量重定向到本地主機 IP 地址。

在 nat 表中:

-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

然後你告訴 ufw 允許到那個埠的流量,但只發往 localhost IP 地址。

sudo ufw allow to 127.0.0.1 port 8080 proto tcp

引用自:https://serverfault.com/questions/1053333