Tuesday, July 20, 2010

Static ARP script for OSX

For security reasons, you may wish to set a static ARP entry for your gateway. This script automates this step. Note that this doesn't prevent DHCP or MAC spoofing however.
The script runs whenever a network connection is made or broken by using the launchd feature to check a path for changes. In this case, I used resolv.conf.
The scripts determines the default gateway IP address and then keep trying to find the corresponding MAC address in the ARP table. Then it sets up the static ARP entry.
Two files are needed: one launchd configuration file and a shell script file. You need to give execute rights on the shell script with chmod +x. Copy the files in place and rename/edit the filenames. You need to restart to make the configuration active.

The contents of /Users/darkfader/static-arp.sh:

#!/bin/bash
# if the resolv.conf file was deleted, create an empty one to enable file watch again
touch /var/run/resolv.conf
while true; do
        IP=$(netstat -rn | grep -m 1 default | tr -s ' ' | cut -d' ' -f 2)
        if [ "$IP" == "" ]; then
                exit 0
        fi
        MAC=$(arp -an | grep -m 1 $IP | tr -s ' ' | cut -d' ' -f 4)
        if [ "$MAC" == "" ]; then
                sleep 1
                continue
        fi
        arp -S $IP $MAC
        exit 0
done

The contents of /Library/LaunchDaemons/net.darkfader.static-arp.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>net.darkfader.static-arp</string>
        <key>ProgramArguments</key>
        <array>
                <string>/Users/darkfader/static-arp.sh</string>
        </array>
        <key>QueueDirectories</key>
        <array/>
        <key>WatchPaths</key>
        <array>
                <string>/var/run/resolv.conf</string>
        </array>
</dict>
</plist>

No comments: