pfctl – Add Rules at Runtime Without Editing /etc/pf.conf

firewallmacospfctl

I have an app that (while it is running and only while it is running) needs to make changes to the packet filter (pf) so that it blocks or allows certain traffic. These rules should be in addition to the user's own rules in /etc/pf.conf – but i do not want to directly edit /etc/pf.conf as this is extremely intrusive.

I can do this trivially in linux using iptables and even in windows using wfp without altering any on-disk files, can i accomplish the same thing in osx with pf ?

Solution only has to work in yosemite (10.10) and above

Best Answer

I solved this myself.

cat /etc/pf.conf my_rules.conf | sudo /sbin/pfctl -Ef -

Where my_rules.conf contains our own rules, these get concatenated to the pf.conf rules but take precedence due to them being appended after pf.conf in the cat command.

Also note we use pfctl -Ef - the - forces pfctl to read from stdin

We can take this solution a step further and load our own rules from stdin by using this:

echo "block out all" | cat /etc/pf.conf - | sudo /sbin/pfctl -Ef -