How to Block an IP Address From Your Website

28 December 2022 | by Xavier Bellekens

Blocking malicious IP addresses can help protect a website from various types of cyberattacks such as Denial of Service (DoS) attacks, Brute force attacks, SSH bruteforce and many more. By blocking malicious IP addresses, a website owner can help prevent these types of attacks and protect the site and its users from harm, ahead of a breach.

What is an IP address

An IP address is the unique identifier that allows one device connected to a network (like the internet) to communicate with another. It stands for “Internet Protocol” and closely resembles a street address – it tells other devices exactly where, in relation to its own space, traffic is supposed to go. It’s important to understand what an IP address is because almost all communication that passes over the global internet does so by using them.

IP Reputation

What does an IP address look like?

The two most common types of IP addresses are IPv4 and IPv6. IPv4 is a 32-bit address type that has been in use since the early days of the internet. IPv6, on the other hand, is a 128-bit address type released as an improvement over its predecessor, providing more flexibility for larger networks and devices.

For this article we will concentrate only on IPv4 as this is still the most common type these days. IP addresses are composed of a set of numbers.

These numbers make it possible for data packets to be routed between computers on the internet. An IP address typically looks like a series of numbers separated by dots, such as 123.456.78.90, and can be further divided into two parts: the network number and the host number.

The network address identifies the network the device is connected to, while the host address identifies each individual device or node on that network.

Why and when do you need to block IP addresses?

Blocking IP addresses can be a useful tool for protecting a network or website from malicious activity. This technique makes it possible to restrict access to those who have been identified as engaging in malicious behavior that could cause harm, such as hackers, or accessing content that is only meant for certain users.

There are several reasons why you might need to block IP addresses:

  1. To protect against cyberattacks: As mentioned above, blocking malicious IP addresses can help protect a website from various types of cyberattacks, including DoS attacks, brute force attacks, and malware attacks.
  2. To prevent spam: Blocking IP addresses can help prevent spam from reaching your website or email inbox. Spammers often use botnets (networks of compromised computers) to send spam, and blocking these IP addresses can help reduce the amount of spam you receive.
  3. To enforce site policies: If you have policies in place that prohibit certain types of behavior on your website (e.g., posting inappropriate content), you may need to block IP addresses belonging to users who violate these policies.

It’s important to note that blocking IP addresses should be done carefully, as it can prevent legitimate users from accessing your website. However, blocking malicious IP addresses can play an important role in achieving better cyber-resilience and secure business operations.

How to Block an IP Address?

Before blocking an IP address, we must determine if the IP address is malicious or not.

There are several ways to determine if an IP address is malicious:

  1. Check online reputation databases: such as Lupovis Prowl. This databases can provide information on whether an IP address has been associated with spam, malware, or other types of malicious activity.
  2. Use security tools: There are several security tools available that can scan IP addresses for signs of malicious activity. These tools can include antivirus software, firewalls, and intrusion detection/prevention systems or cyber deception for contextual threat intelligence.
  3. Monitor website logs: Monitoring your website’s logs (records of activity on your site) can help you identify unusual or suspicious activity that may be coming from a particular IP address. For example, if you see a large number of failed login attempts coming from a single IP address, it may be a sign of a brute force attack.
  4. Monitor traffic patterns: Monitoring traffic patterns on your website can help you identify unusual or suspicious activity that may be coming from a particular IP address. For example, if you see a sudden increase in traffic from a single IP address, it may be a sign of a DoS attack.

It’s important to note that not all malicious activity will be detectable using these methods. In some cases, an IP address may not have a known reputation, or the activity may be disguised in some way. It’s always a good idea to take a cautious approach when it comes to security, and to use a combination of these and other measures to protect your website and its users.

Blocking an IP Address on WordPress

As an example, we will monitor and identify malicious IP addresses accessing a sample WordPress website. This can also be replicated for other type of applications such as web apps, APIs or even on Azure Sentinel, or any other SIEM and SOAR.

In this example, we installed a sample WordPress website

When a user (legitimate or not) accesses the website, a log is created on the web server. In our case the web server is Nginx, however the same concept applies for Apache.

For Nginx, the logs are located in

/var/log/nginx/wordpress_http_access.log

For Apache, the logs are located in

/var/log/apache2/access.log

The access log file contains raw logs of all requests made to your website.

83.31.00.00 - - [27/Dec/2022:23:24:13 +0000] "GET /wp-content/plugins/wordfence/images/logos/shield-free.svg HTTP/1.1" 304 0 "http://100.00.00.178/wp-content/plugins/wordfence/css/license/free-global.1600000000.css?ver=0.0.0" "Mozilla/5.0 (Macintosh; Intel Mac OS X 00_00_00) AppleWebKit/00.00 (KHTML, like Gecko) Chrome/00.0.0.0 Safari/000.00"

Each line begins with the IP address making that request to the web server.

To ensure that you don’t wind up preventing legitimate users, search engines, or yourself from visiting your website you can manually look the IP of the user, on Lupovis Prowl.

This, however, would be tedious, hence we can use the Prowl API to do it automatically for every single visitor (legitimate or not).

Acquire an API Key

To do so, you can visit the Amazon AWS Marketplace and subscribe to the service.

Using the API, you can essentially query every IP and obtain information on the reputation of the visitor. In turn, you can block any IP addresses deemed malicious.

The output provided by the API looks like this

{'ip': '51.195.190.00', 'ttps': ['dir-busting', 'web-traversal', 'scanning']}%  

With this information, you know that this IP address is attempting one or more of these attacks against your website or application and is, henceforth, malicious.

How to automate it?

One way is to use a python script that will query all IP addresses against the API and add firewall rules to your web server.

The script can then be run in the background and continuously block malicious IPs.

import requests
import os
import json
import subprocess
logfile = "/var/log/apache2/access.log"
#logfile = "access.log"
processed_ips = []
ips = []
with open(logfile) as f:
    for line in f:
        ips.append(line.split()[0])
ips = list(set(ips))
response_types = [
    "known-apache-attack"
    "known-bot",
    "known-brute-force-attack",
    "known-email-attack",
    "known-imap-attack",
    "known-ssh-attack",
    "known-voip-attack",
    "web-brute-force"
]
def process_ip(ip, flags):
    global processed_ips
    for flag in flags:
        if flag == "known-bot" or flag == "known-brute-force-attack" or flag == "web-brute-force" or flag not in response_types:
            # Block from accessing the entire network
            ip_tables_cmd = f"sudo iptables -A INPUT -s {ip} -j DROP"
            os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing the network")
        elif flag == "known-apache-attack":
            # Change firewall settings to block this IP from accessing port 80 and 443
            ip_tables_cmds = [
                f"sudo iptables -A INPUT -p tcp --dport 80 -s {ip} -j DROP",
                f"sudo iptables -A INPUT -p tcp --dport 443 -s {ip} -j DROP"
            ]
            #ip_tables_cmd_to_unblock = f"sudo iptables -D INPUT -p tcp --dport 80 -s {ip} -j DROP"
            #os.system("sudo iptables -F")
            for ip_tables_cmd in ip_tables_cmds: 
                os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing port 80 and 443")
        elif flag == "known-email-attack":
            # Block from accessing email default ports (25, 465, 587)
            ip_tables_cmds = [
                f"sudo iptables -A INPUT -p tcp --dport 25 -s {ip} -j DROP",
                f"sudo iptables -A INPUT -p tcp --dport 465 -s {ip} -j DROP",
                f"sudo iptables -A INPUT -p tcp --dport 587 -s {ip} -j DROP"
            ] 
            for ip_tables_cmd in ip_tables_cmds:
                os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing email default ports (25, 465, 587)")
        elif flag == "known-imap-attack":
            # Block from accessing imap default ports (143, 993)
            ip_tables_cmds = [
                f"sudo iptables -A INPUT -p tcp --dport 143 -s {ip} -j DROP",
                f"sudo iptables -A INPUT -p tcp --dport 993 -s {ip} -j DROP"
            ]
            for ip_tables_cmd in ip_tables_cmds:
                os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing imap default ports (143, 993)")
        elif flag == "known-ssh-attack":
            # Block from accessing ssh default port (22)
            ip_tables_cmd = f"sudo iptables -A INPUT -p tcp --dport 22 -s {ip} -j DROP"
            os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing ssh default port (22)")
        elif flag == "known-voip-attack":
            # Block from accessing voip default ports (5060, 5061)
            ip_tables_cmds = [
                f"sudo iptables -A INPUT -p tcp --dport 5060 -s {ip} -j DROP",
                f"sudo iptables -A INPUT -p tcp --dport 5061 -s {ip} -j DROP"
            ]
            for ip_tables_cmd in ip_tables_cmds:
                os.system(ip_tables_cmd)
            print(f"Blocked {ip} from accessing voip default ports (5060, 5061)")
if __name__ == "__main__":
    with open("processed_ips.txt", "r") as f:
        processed_ips = f.read().splitlines()
    while True:
        ips = []
        with open(logfile) as f:
            for line in f:
                ips.append(line.split()[0])
        ips = list(set(ips))
        for ip in ips:
            #ip = '23.129.64.227'
            if ip not in processed_ips:
                response = requests.get(
                    "https://84h9dq7p3c.execute-api.eu-west-1.amazonaws.com/live/GetIPReputation",
                    params={"ip": ip},
                    headers={"x-api-key": "_REPLACE_WITH_PROWL_API_KEY"},
                ).text
               
                flags = eval(response)["ttps"]
                process_ip(ip, flags)
                processed_ips.append(ip)
                with open("processed_ips.txt", "a") as f:
                    f.write(ip + "\n")

You can also download the script from our GitHub.

To run the script, you can use the following command

sudo python3 prowl_IPreputation.py

This will give you the following output

block IP addresses wordpress

To run it in the background, you can add the execution line

sudo python3 prowl_IPreputation.py

To the following file

/etc/rc.local

The rc.local script is a superuser startup script. Note that you may want to use systemd and create a new unit to avoid compatibility with newer systems.

Conclusion

Blocking malicious IP addresses is one of the most important steps you can take to prevent cyberattacks. By acting quickly and decisively, you can help protect your business from the ever-present threat of hackers. If you suspect that an IP address is up to no good, don’t hesitate to block it. It could be the difference between a minor inconvenience and a major disaster.

28 December 2022 | by Xavier Bellekens

Speak to an Expert

Whether you have a specific security issue or are looking for more information on our Deception as a Service platform, simply request a call back with one of our security experts, at a time that suits you.