#!/bin/bash
##########
#
# Modsecurity 
#
#########

#Variable Assign
mod_sec="/etc/modsecurity/modsecurity.conf"
FILE=/etc/modsecurity/modsecurity.conf

function mod_conf ()
{
grep -r "SecRule REQUEST_URI \"@beginsWith /BluKryptBuilder/\" \"allow,id:1\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/SecRuleEngine On/a SecRule REQUEST_URI \"@beginsWith /BluKryptBuilder/\" \"allow,id:1\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /paracloud/\" \"allow,id:2\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:1/a SecRule REQUEST_URI \"@beginsWith /paracloud/\" \"allow,id:2\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /support/\" \"allow,id:3\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:2/a SecRule REQUEST_URI \"@beginsWith /support/\" \"allow,id:3\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /paramail/\" \"allow,id:4\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:3/a SecRule REQUEST_URI \"@beginsWith /paramail/\" \"allow,id:4\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /ParacloudSearch/\" \"allow,id:5\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:4/a SecRule REQUEST_URI \"@beginsWith /ParacloudSearch/\" \"allow,id:5\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /BluKryptJob/\" \"allow,id:6\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:5/a SecRule REQUEST_URI \"@beginsWith /BluKryptJob/\" \"allow,id:6\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /paracloudjob/\" \"allow,id:7\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:6/a SecRule REQUEST_URI \"@beginsWith /paracloudjob/\" \"allow,id:7\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /portal/\" \"allow,id:8\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:7/a SecRule REQUEST_URI \"@beginsWith /portal/\" \"allow,id:8\"" $mod_sec
fi

grep -r "SecRule REQUEST_URI \"@beginsWith /msjob/\" \"allow,id:9\"" $mod_sec
if [ $? -ne 0 ]; then
        sed -i "/id:8/a SecRule REQUEST_URI \"@beginsWith /msjob/\" \"allow,id:9\"" $mod_sec
fi
###### changing values
sed -Ei 's/SecRequestBodyAccess On/SecRequestBodyAccess Off/g' $FILE
sed -Ei 's/SecRequestBodyLimitAction Reject/SecRequestBodyLimitAction ProcessPartial/g'  $FILE
sed -Ei 's/SecResponseBodyAccess On/SecResponseBodyAccess Off/g'  $FILE

sleep 1

service apache2 restart

}

#if modsecurity.conf is present then do below changes:
if [ -f "$FILE" ]; then
sudo sed -i "s/SecRuleEngine Off/SecRuleEngine On/" /etc/modsecurity/modsecurity.conf
sleep 2
mod_conf

else
    apt-get -y install libapache2-mod-security2

sleep 2
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

sudo sed -i "s/SecRuleEngine DetectionOnly/SecRuleEngine On/" /etc/modsecurity/modsecurity.conf

mod_conf
fi
