macOS配置80端口映射


0x01 背景

mac下想要绑定80端口的话,以前的做法是直接用root权限启动(也可以是sudo),但是这种方式存在一定的安全问题,所以能不用尽量不用。
本文是分享另一种方式

0x02 端口映射

1. 修改/etc/pf.conf文件

通过sudo vi打开/etc/pf.conf文件,在rdr-anchor "com.apple/*"这一句后面添加如下命令:

rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 10080

添加完成后记得保存哦!/etc/pf.conf修改后的样子形如:

#
# Default PF configuration file.
#
# This file contains the main ruleset, which gets automatically loaded
# at startup.  PF will not be automatically enabled, however.  Instead,
# each component which utilizes PF is responsible for enabling and disabling
# PF via -E and -X as documented in pfctl(8).  That will ensure that PF
# is disabled only when the last enable reference is released.
#
# Care must be taken to ensure that the main ruleset does not get flushed,
# as the nested anchors rely on the anchor point defined here. In addition,
# to the anchors loaded by this file, some system services would dynamically 
# insert anchors into the main ruleset. These anchors will be added only when
# the system service is used and would removed on termination of the service.
#
# See pf.conf(5) for syntax.
#

#
# com.apple anchor point
#
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
rdr on lo0 inet proto tcp from any to 127.0.0.1 port 80 -> 127.0.0.1 port 10080
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"

2. 配置文件检查

检查配置文件,以防手抖配错了 [此步骤非必须]

$ sudo pfctl -vnf /etc/pf.conf

3. 转发生效

$ sudo pfctl -f /etc/pf.conf

4. 启动pf防火墙

$ sudo pfctl -e

5. 启动端口对应服务

本文示例应用端口为10080,启动该服务即可

0x03 开机自启动

1. 创建脚本

  • 脚本路径
$ sudo vi /usr/local/bin/enable-pf.sh
  • 脚本内容
#!/bin/bash

sleep 10
/sbin/pfctl -ef /etc/pf.conf
  • 修改脚本权限
$ sudo chmod 755 /usr/local/bin/enable-pf.sh

2. 创建plist

  • plist路径
$ sudo vi /Library/LaunchDaemons/cn.matz.pfctl.plist
  • 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>cn.matz.pfctl</string>
        <key>ProgramArguments</key>
        <array>
            <string>/usr/local/bin/enable-pf.sh</string>
        </array>
        <key>StandardOutPath</key>
        <string>/var/log/pf/access.log</string>
        <key>StandardErrorPath</key>
        <string>/var/log/pf/error.log</string>
        <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>

3. 其他

以后每次开机,macOS会自动执行该端口映射,日志为/var/log/pf/access.log和/var/log/pf/error.log

声明:PowerMatz | 版权所有,违者必究 | 如未注明,均为原创 | 本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - macOS配置80端口映射


Stay hungry. Stay foolish.