PF Using anchors to insert rules on-the-fly

Hello community,

Using anchors with PF allows us to add rules on-the-fly:
Code:
...
...
...
block all
anchor my_anchor
...
...
...

Now with the anchor in place we can insert rules from the command line. For example the rule below will block outbound traffic from host 192.168.47.4:
Code:
sudo sh -c 'echo "block return out quick on egress from 192.168.47.4" | pfctl -a my_anchor -f -'

Unless I am logged in as the root user, I have to enter a shell session for the above rule to work. For example the rule below will not work because I did not use sh -c :
Code:
sudo 'echo "block return out quick on egress from 192.168.47.4" | pfctl -a my_anchor -f -'

Why do I have to enter into another shell to make this work?
 
This has nothing to do with pf. Your second command can't do anything useful, as sudo just uses execve(2) to execute whatever you give it. From the man page:
The new process is constructed from an ordinary file, whose
name is pointed to by path, called the new process file. The fexecve()
system call is equivalent to execve() except that the file to be executed
is determined by the file descriptor fd instead of a path. This file is
either an executable object file, or a file of data for an interpreter.
So, what happens is that you execute echo and the pipe symbol will be one of its arguments. If you want it to be interpreted by a shell (which then launches two processes and establishes an actual pipe between them), you have to execute a shell.

edit: Without testing, the following could work though:
Code:
echo "block return out quick on egress from 192.168.47.4" | sudo pfctl -a my_anchor -f -
 
Back
Top