A script to automtically enable and disable the firewall

Jul 22, '09 07:30:00AM

Contributed by: dead2sin

This hints allows your firewall to automatically turn on or off based upon which network you are on. A LaunchAgent watches resolv.conf in order to detect when there are changes in the network. Save the following in /Library/LaunchAgents:

<?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>KeepAlive</key>
  <false/>
  <key>Label</key>
  <string>com.yourcompany.autofirewall</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Library/Scripts/yourcompany/autofirewall.sh</string>
  </array>
  <key>RunAtLoad</key>
  <false/>
  <key>WatchPaths</key>
  <array>
    <string>/var/run/resolv.conf</string>
  </array>
</dict>
</plist>
Create and save the following shell script as autofirewall.sh, in the location specified in the LaunchAgent (/Library/Scripts/yourcompany in this example):
#!/bin/bash

#Written by Nate Walck and Clint Armstrong
#Liberty University 2009

#This Script will automatically enable or disable the firewall depending upon which network it is on.

#This function turns the firewall on or off, depending upon which state is desired.
#If the firwall is already in the state desired, the script will leave it in that state.

function firewall {
  #Reads the current state of the firewall and stores it in variable fw
  fw=$(defaults read /Library/Preferences/com.apple.alf globalstate)
  
  #This compares the option passed to function firewall to its current state.
  if [ "$1" != "$fw" ]
    then
      #If the option pased is different from current state, it changes it to the passed value.
      defaults write /Library/Preferences/com.apple.alf globalstate -int $1
      #For troubleshooting purposes, you can put in 'say $1' to see which state is being set.
  fi
}

#Determines if resolv.conf exists.  
if test -e /var/run/resolv.conf
  then  
    #This stores the domain line of resolv.conf into variable NETWORK.
    NETWORK=$(cat /var/run/resolv.conf | grep domain | awk '{print $2}')
    
    #This case looks at $NETWORK for specific domains and runs commands accordingly
    case "$NETWORK" in
    
    #If on VPN, function firewall turns the firewall on.
    vpn.yourcompany.com
    firewall 1
    ;;
    
    #On any other company domain, function firewall turns firewall off.
    *.yourcompany.com)
    firewall 0
    ;;
    
    #On any other domain, function firewall turns firewall on.
    *)
    firewall 1
    ;;

    esac
    
  else
    #If no network connection exists, function firewall turns the firewall on.
    firewall 1    

fi
[robg adds: I haven't tested this one. You'll have to customize both scripts with your company's own information, replacing references to yourcompany.com.]

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20090714140555465