Last active
April 29, 2025 03:04
-
-
Save NotYusta/f1b90eb5e28c81aa6202e78334ba8ba9 to your computer and use it in GitHub Desktop.
Install cadvisor firewall
This file contains hidden or 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/sh | |
CADVISOR_PORT=9101 | |
IPSET_NAME=cadvisor_whitelist | |
CHAIN_NAME=cadvisor_firewall | |
# Function to install necessary packages | |
install_packages() { | |
if command -v apt-get >/dev/null 2>&1; then | |
apt-get update -y | |
apt-get install -y ipset iptables | |
elif command -v dnf >/dev/null 2>&1; then | |
dnf install -y ipset iptables | |
else | |
echo "Neither apt-get nor dnf found. Install ipset and iptables manually." | |
exit 1 | |
fi | |
} | |
# Function to create and clean up custom chain | |
setup_custom_chain() { | |
iptables -N $CHAIN_NAME 2>/dev/null || true | |
iptables -F $CHAIN_NAME | |
} | |
# Function to create ipset and clean up if it exists | |
setup_ipset() { | |
ipset list $IPSET_NAME >/dev/null 2>&1 && ipset destroy $IPSET_NAME | |
ipset create $IPSET_NAME hash:net | |
} | |
# Function to add IPs to the ipset | |
add_ips_to_ipset() { | |
echo "Enter IPs separated by commas (e.g., 1.2.3.4,5.6.7.0/24):" | |
read IP_LIST | |
for ip in $(echo "$IP_LIST" | tr ',' ' '); do | |
ipset add $IPSET_NAME "$ip" 2>/dev/null || echo "IP $ip already exists or invalid." | |
done | |
} | |
# Function to configure iptables rules | |
setup_iptables_rules() { | |
iptables -A $CHAIN_NAME -p tcp --dport $CADVISOR_PORT -m set ! --match-set $IPSET_NAME src -j LOG --log-prefix "[CADVISOR_BLOCKED] " --log-level 4 | |
iptables -A $CHAIN_NAME -p tcp --dport $CADVISOR_PORT -m set ! --match-set $IPSET_NAME src -j DROP | |
iptables -D INPUT -j $CHAIN_NAME 2>/dev/null || true | |
iptables -I INPUT -j $CHAIN_NAME | |
} | |
# Main function to run all steps | |
main() { | |
install_packages | |
setup_custom_chain | |
setup_ipset | |
add_ips_to_ipset | |
setup_iptables_rules | |
} | |
# Run the main function | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment