#!/bin/bash
# only root can run this script
if [[ $EUID -ne 0 ]]; then
   echo "This script $0 must be run as root." 1>&2
   exit 1
fi
rpm -q mod_security &> /dev/null
if [ $? -ne 0 ]; then
  echo "Installing mod_security package for auth failure throttling..."
  yum install -y mod_security
fi
if [ -e /etc/httpd/conf.d/mod_security.conf ]; then
  grep /phoenix /etc/httpd/conf.d/mod_security.conf &> /dev/null
  if [ $? -ne 0 ]; then
    echo "Changing default mod_security configuration to skip rule engine for /phoenix URLs..."
    sed -i '/^\s*SecRuleEngine On/a\    SecRule REQUEST_URI "^/phoenix" "id:12345,phase:1,t:none,pass,nolog,ctl:ruleEngine=Off"' /etc/httpd/conf.d/mod_security.conf 
  fi
fi
echo "Setting mod_security config http request body limit to the max 1GB to avoid event upload issues..."
sed -i -e 's/SecRequestBodyLimit 13107200$/SecRequestBodyLimit 1000000000/' /etc/httpd/conf.d/mod_security.conf
echo "Adding auth failure throttling rule to mod_security configuration..."
cat > /etc/httpd/modsecurity.d/local_rules/auth_throttle.conf << EOF
        # Retrieve the Username and URI
        SecRule REQUEST_HEADERS:authorization "Basic ([a-zA-Z0-9]+=*)$" "phase:1,nolog,pass,id:1001,chain,capture"
                SecRule TX:1 "^([-a-zA-Z0-9_]+):" "t:base64Decode,chain,capture"
                SecAction initcol:user=%{TX.1},initcol:resource=%{REQUEST_URI}

        SecRule user:bf_block "@gt 0" "id:'1002',status:401,log,deny,msg:'Username \"%{REMOTE_USER}\" blocked because of suspected brute-force attack'"

        SecRule REQUEST_URI "^/(svnupload|svnupload2|winupload|winupload_direct|fwdupload|evthandler|evthandler2|linuxupload|rawupload)" "id:'1003',phase:5,chain,t:none,nolog,pass"
                SecRule RESPONSE_STATUS "@eq 200" "setvar:resource.bf_counter=0,setvar:user.bf_counter=0"

        SecRule REQUEST_URI "^/(svnupload|svnupload2|winupload|winupload_direct|fwdupload||evthandler|evthandler2|linuxupload|rawupload)" "id:'1004',phase:5,chain,t:none,nolog,pass"
                SecRule RESPONSE_STATUS "^401" "setvar:resource.bf_counter=+1,setvar:user.bf_counter=+1"

        # Check for too many failures for a single username
        SecRule user:bf_counter "@ge 3" "id:1005,phase:5,t:none,pass,chain,setvar:user.bf_block,setvar:!user.bf_counter,expirevar:user.bf_block=60"
EOF
echo -n "Restarting httpd to enable mod_security auth failure throttling..."
systemctl restart httpd.service
echo "Done."
