MacOS配置NAT转发规则
首先启用IP转发
Section titled “首先启用IP转发”# 启用IPv4转发sudo sysctl -w net.inet.ip.forwarding=1为了重启后依然有效,比较好的方式是创建启动项:
# 创建一个plist文件sudo vim /Library/LaunchDaemons/com.lc.ipforwarding.plistcom.lc.ipforwarding.plist文件内容如下
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>Label</key> <string>com.custom.ipforwarding</string> <key>ProgramArguments</key> <array> <string>/usr/sbin/sysctl</string> <string>-w</string> <string>net.inet.ip.forwarding=1</string> </array> <key>RunAtLoad</key> <true/></dict></plist>设置权限并加载:
# 设置正确的权限sudo chown root:wheel /Library/LaunchDaemons/com.lc.ipforwarding.plistsudo chmod 644 /Library/LaunchDaemons/com.lc.ipforwarding.plist
# 立即加载sudo launchctl load -w /Library/LaunchDaemons/com.lc.ipforwarding.plist验证设置:
# 检查当前状态sysctl net.inet.ip.forwarding
# 检查启动项状态sudo launchctl list | grep ipforwarding编辑pf配置文件
Section titled “编辑pf配置文件”# 编辑配置文件sudo vim /etc/pf.conf
# 基本NAT配置示例,表示转发IP段192.168.1.0/24nat on en0 from 192.168.1.0/24 to any -> (en0)直接添加转发配置到pf.conf文件的最下面会有问题,应用配置文件时会报错
pfctl: Use of -f option, could result in flushing of rulespresent in the main ruleset added by the system at startup.See /etc/pf.conf for further details.
No ALTQ support in kernelALTQ related functions disabled/etc/pf.conf:31: Rules must be in order: options, normalization, queueing, translation, filteringpfctl: Syntax error in config file: pf rules not loaded解决办法是重新组织整个文件里内容的顺序
# 1. 定义变量ext_if = "en0"internal_net = "192.168.1.0/24"
# 2. 选项 (options)set skip on lo0set block-policy return
# 3. 规范化 (normalization)scrub-anchor "com.apple/*"
# 4. 队列 (queueing)dummynet-anchor "com.apple/*"
# 5. 转换 (translation)nat-anchor "com.apple/*"rdr-anchor "com.apple/*"# 添加自定义NAT规则nat on $ext_if from $internal_net to any -> ($ext_if)
# 6. 过滤 (filtering)anchor "com.apple/*"load anchor "com.apple" from "/etc/pf.anchors/com.apple"# 检查语法sudo pfctl -nf /etc/pf.conf
# 应用规则(使用-F清除旧规则)sudo pfctl -F all -f /etc/pf.conf
# 启用pfsudo pfctl -e