Skip to content

Instantly share code, notes, and snippets.

@mveytsman
Last active July 14, 2024 04:14
Show Gist options
  • Save mveytsman/7a3366e69401fae6e9a4f9eaf0d3f9b1 to your computer and use it in GitHub Desktop.
Save mveytsman/7a3366e69401fae6e9a4f9eaf0d3f9b1 to your computer and use it in GitHub Desktop.
Check that your firewall is doing what it should be. Post to slack if it's not.
#!/bin/sh
# This is a script that checks to see if the open ports on a host are what you expect them to be.
# If your firewall isn't doing what it's supposed to, it will post a message to Slack to alert you.
# Intended to be run as a cron job.
#
# Requires nmap to be installed
#
# Invoke as
# ./portscanyourself example.com 80 443
# To alert you if any ports other than 80 and 443 are listening on a host
# By default it scans the top 1000 ports. To scan all ports do
#./portscanyourself -all-ports example.com 80 443
SLACK_WEBHOOK= "XXXXXX" # Your slack webhook here!
if [ "$1" = "-all-ports" ]
then
shift
PORTS_PLAG="-p-"
else
PORTS_FLAG="--top_ports 1000"
fi
HOST=$1
shift
DESIRED_PORTS=$(printf '%s\n' "$@" | sort | tr '\n' ' ')
OPEN_PORTS=$(nmap -open-ports $PORTS_FLAG $HOST | grep "^[0-9].*open" | sed 's/^\([0-9][0-9]*\).*$/\1/' | sort | tr '\n' ' ')
if [ "$OPEN_PORTS" = "$DESIRED_PORTS" ]
then
echo "All good"
else
curl -X POST --data-urlencode "payload={'username': 'portscanyourself', 'text': 'Firewall rule mismatch on $HOST. Open Ports (${OPEN_PORTS% }) do not match desired ports (${DESIRED_PORTS% })', 'icon_url': 'https://appcanary.com/assets/appcanary.rect-379a1b2e906a1dd3cd807f2d64b48d4520f17efbb05649deefd0513682208080.png'}" $SLACK_WEBHOOK
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment