Last active
December 21, 2023 14:04
-
-
Save pedrom34/187c896fa3ad3e6aebf212b9597ed0f1 to your computer and use it in GitHub Desktop.
Whitelist public IP in Authelia and Crowdsec, notify, log and restart containers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Set the path to the .last_ip file | |
LAST_IP_FILE=/opt/scripts/.last_ip | |
# Get the current IP address | |
CURRENT_IP=$(curl -s ifconfig.co) | |
VALID_IP=$( [[ $CURRENT_IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] && echo true || echo false ) | |
# set telegram infos | |
TOKEN="XX:XX-XX" | |
CHAT_ID="XX" | |
URL="https://api.telegram.org/bot$TOKEN/sendMessage" | |
function whitelist() { | |
## - authelia | |
authelia="/opt/containers/nginx/authelia/configuration.yml" | |
sed -i "s/^.*#WAN_IP$/ - '$CURRENT_IP\/32' #WAN_IP/" "$authelia" | |
nohup /usr/bin/docker restart authelia >/dev/null 2>&1 & | |
## - crowdsec | |
crowdsec="/opt/containers/nginx/crowdsec/hub/parsers/s02-enrich/crowdsecurity/whitelists.yaml" | |
sed -i "s/^.*# WAN_IP.*/ - \"$CURRENT_IP\" # WAN_IP/" "$crowdsec" | |
nohup /usr/bin/docker restart crowdsec >/dev/null 2>&1 & | |
} | |
#if invalid ip, i.e. lookup error, log and exit | |
if [[ $VALID_IP == false ]]; then | |
echo "$(date '+%Y-%m-%d %H:%M:%S') - Unable to get IP, value: $CURRENT_IP" >> /opt/scripts/ip_change.log | |
exit 1 | |
fi | |
# Check if the .last_ip file exists | |
if [ -f "$LAST_IP_FILE" ]; then | |
# Read the last IP address from the file | |
read -ru 0 last_ip < "$LAST_IP_FILE" | |
# Compare the current IP address to the last IP address | |
if [ "$CURRENT_IP" != "$last_ip" ]; then | |
# Log a message indicating that the IP address has changed | |
echo "$(date '+%Y-%m-%d %H:%M:%S') - IP address has changed from $last_ip to $CURRENT_IP" >> /opt/scripts/ip_change.log | |
# Update the last IP address in the file | |
echo "$CURRENT_IP" > "$LAST_IP_FILE" | |
whitelist "$CURRENT_IP" | |
# send pushover alert | |
curl -s -X POST $URL -d chat_id=$CHAT_ID -d text="New IP !%0APublic IP has changed. New IP: $CURRENT_IP.%0AReminder, last IP: $last_ip" | |
fi | |
else | |
# The .last_ip file doesn't exist, so create it and store the current IP address in it | |
echo "$CURRENT_IP" > "$LAST_IP_FILE" | |
# Set permissions for the .last_ip file so it can be read by other users | |
chmod 644 "$LAST_IP_FILE" | |
# Set ownership for the .last_ip file to root and the group to root | |
chown root:root "$LAST_IP_FILE" | |
# log IP to file | |
echo "$(date '+%Y-%m-%d %H:%M:%S') - IP address has been set to $CURRENT_IP" >> /root/scripts/ip_change.log | |
whitelist "$CURRENT_IP" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment