Wednesday, May 23, 2018

pfSense: Enabling or disabling firewall rules from a script.

Thought I'd post a quick and dirty script I put together to allow me to enable/disable firewall groups from any network connected device, including my phone.



#!/usr/bin/expect -f
# exp_internal 1    ;# uncomment to turn on expect debugging
set timeout 10
spawn ssh username@firewall.hostname -p 22
expect "Password for username@firewall.host.name:"
send "password\n"
expect ":"
send "sudo /etc/rc.initial\n"
expect "Password:"
send "password\n"
expect ":"
send "12\n"
send "global \$config;\n"
send "parse_config(true);\n"
send "\$config\['filter'\]\['rule'\]\['26'\]\['disabled'\] = true;\n"
send "\$config\['filter'\]\['rule'\]\['27'\]\['disabled'\] = true;\n"
send "write_config();\n"
send "exec\n"
send "filter_configure_sync();\n"
send "exit\n"
expect ":"
send "8\n"
expect ":"
send "sudo su\n"
expect ":"
send "pfctl -k 192.168.10.129/32; pfctl -k 0.0.0.0/0 -k 192.168.10.129/32 \n"
send "pfctl -k 192.168.10.26/32; pfctl -k 0.0.0.0/0 -k 192.168.10.26/32 \n"
send "pfctl -k 192.168.10.28/32; pfctl -k 0.0.0.0/0 -k 192.168.10.28/32 \n"
send "pfctl -k 2600:8807:4c80:22::1912/128; pfctl -k 0.0.0.0/0 -k
2600:8807:4c80:22::1912/128\n"
send "pfctl -k 2600:8807:4c80:22::2000/128; pfctl -k 0.0.0.0/0 -k
2600:8807:4c80:22::2000/128\n"
send "/etc/rc.filter_configure\n"
expect ":"
send "exit\n"
expect ":"
send "exit\n"
expect eof
exit 0

Replace firewall.host.name with your pfSense install address, sent "password" with your password and "username" with an admin user on the firewall.

Then, you'll need to change the rule numbers to correspond with the rules on your firewall.

The way I tell is this:  Hover over the rule you want and look at the link in the lower left corner.


The "27" in this example corresponds to rule 27 on the firewall.  Keep in mind that adding or removing rules on the firewall will change the number, so you'll need to keep track.


After changing the status on the rule, filter_configure_sync writes the rule and makes it active.

Then the pfctl -k lines reset the firewall states on some selected IPs.  In this case, they correspond to the devices in the rule.  This kills the connections now whereas a rule change just disallows any new connections to transpire, but existing open connections are unaffected.

Another filter reconfigure and you're done!

Then, just make a corresponding script to enable the rules and execute them from your favorite shell.



No comments: