If you're experiencing the same issues as I had, you might find that your server is constantly bombarded with unwanted traffic and requests coming from Amazon Compute resources.
To tackle this problem, I developed a PHP script that automatically retrieves the latest AWS IP ranges from Amazon's public JSON file. The script then updates the iptables
rules to block these IP addresses.
(The image above is a screenshot of the iftop
command in linux in action. iftop is a tool used for monitoring network bandwidth in real-time)
- PHP CLI
- cURL support in PHP
- Tor (optional)
iptables
/ip6tables
-
Install Tor (Optional):
- Using Tor is optional and it's used for anonymously fetching the JSON data. If you prefer not to use Tor, simply skip this step and modify the script to not use the Tor proxy.
- If opting to use Tor:
- Debian/Ubuntu:
sudo apt-get install tor
- CentOS/RedHat:
sudo yum install tor
- macOS (using Homebrew):
brew install tor
- Debian/Ubuntu:
- Start the Tor service on Linux:
sudo service tor start
- Ensure Tor is configured to listen on port 9050 (SOCKS proxy).
-
Clone the Repository:
- Clone this repository or download the script to your server.
-
Make the Script Executable:
- Run
chmod +x aws-blocker.php
to make the script executable.
- Run
-
Run the Script in CLI mode:
- Execute the script with
sudo ./aws-blocker.php
.
- Execute the script with
-
Optional: Set Up a Cron Job:
- For automatic daily execution, set up a cron job.
- Edit the crontab for the root user with
sudo crontab -e
. - Add the following line to run the script every day at a specific time (e.g., 3:00 AM):
0 3 * * * /path/to/aws-blocker.php
- The script fetches the latest IP ranges used by AWS services.
- It uses Tor, if installed and configured, to anonymously retrieve the JSON data.
- It then parses the JSON file to extract both IPv4 and IPv6 ranges.
- The script checks if each IP range already has a corresponding rule in
iptables
. - New rules are added only for IP ranges not already blocked.
- This script modifies
iptables
rules and may block a significant number of IP addresses. - Understand the implications, as this might block legitimate traffic.
- Testing in a controlled environment before using it in production is highly recommended.
Nejib BEN AHMED
This project is licensed under the MIT License - see the LICENSE file for details.