Skip to content

直接绑定模式 + 防火墙本地端口转发示例 #135

Description

@wyzhou-com

适用场景:natmap 和业务服务器同时运行在路由器上,且 natmap 无法复用业务源端口,如内核态 WireGuard,比 natmap 纯软件转发性能高得多。
原理:通过使用 natmap 的-f选项为出站的 STUN/HTTP 流量添加防火墙标记,同时在 output 链为所有带标记的流量打上相应的 conntrack 标记,在入站 prerouting 链将所有不带 conntrack 标记的流量(即外部主动发起的连接)重定向到实际业务端口。

这种模式都是固定端口,可以直接使用单独的防火墙 table 加上相应通知脚本即可,根据实际业务情况增减和修改相关变量,我只运行了一个 SSH 和 WireGuard,下面是示例:

natmap.nft

#!/usr/sbin/nft -f

define TCP_MARK = 256
define UDP_MARK = 257

define TCP_DNAT_PORT = 50023
define TCP_REDIRECT_PORT = 22

define UDP_DNAT_PORT = 51821
define UDP_REDIRECT_PORT = 51820

table ip natmap { }
delete table ip natmap

table ip natmap {
    chain output {
        type filter hook output priority mangle; policy accept;
        ct mark set meta mark map { $TCP_MARK : $TCP_MARK, $UDP_MARK : $UDP_MARK } counter
    }

    chain prerouting {
        type nat hook prerouting priority dstnat; policy accept;
        tcp dport $TCP_DNAT_PORT ct mark != $TCP_MARK counter redirect to :$TCP_REDIRECT_PORT
        udp dport $UDP_DNAT_PORT ct mark != $UDP_MARK counter redirect to :$UDP_REDIRECT_PORT
    }
}

PS:fw4 表需要添加相应的防火墙规则放行实际业务端口。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions