Blocking Brute Force Hacking attacks on your FreePBX machine

Hi All,

I just thought I’d post a list of IP Addresses that are consistently being used by hackers for brute force VoIP attacks. This occurs with EVERYONE that uses FreePBX, all you have to do is monitor the asterisk log file (/var/log/asterisk/full) and you’ll see plenty of the following examples:

a) [2023-05-16 00:00:00] NOTICE[13821] res_pjsip/pjsip_distributor.c: Request '**REGISTER**' from '<sip:[email protected]>' failed for '5.62.60.117:1439' (callid: e5f4a819415934e4f7a502) - Failed to authenticate

b) [2023-05-16 00:00:00] NOTICE[21789] res_pjsip/pjsip_distributor.c: Request '**INVITE**' from '"8014" <sip:[email protected]>' failed for '95.216.21.57:5066' (callid: 2002550741) - No matching endpoint found after 159 tries in 1.234 ms

c) [2023-05-14 00:00:00] ERROR[1283] pjproject: 	sip_transport. **Error processing** 732 bytes packet from UDP 51.178.64.240:62222 : PJSIP syntax error exception when parsing 'Request Line' header on line 1 col 12:

Sure, some of you will think that most of these are dynamic addresses however the vast majority are NOT. The small minority that are dynamic, are consistently being used by hackers because through my continuous monitoring of these IP Addresses, I keep receiving packets/attacks. I check this from my FreePBX machine using the command: iptables -L -v

By sharing the offending IP Addresses here, the intention is to help others to add these IP Addresses to their IPTABLES block rules using: iptables -A INPUT -s {ip} -j DROP
Where {ip} = the offending IP Address.

I have made a couple of scripts that do the detecting and blocking automatically, run as a service in the background which I want to share on this forum, it is a simple python script and extremely effective.

See the next post below for the download link

Here are the offending IP Addresses that you can add to your iptables rules:

142.44.218.83
165.22.177.218
209.38.228.211
144.126.192.78
43.156.237.162
23.175.48.210
67.229.26.82
149.202.67.181
185.224.128.31
185.210.157.116
74.50.90.134
78.47.231.138
169.150.204.34
94.102.61.29
185.210.219.100
94.137.92.3
185.51.134.199
5.253.207.4
185.244.212.19
51.142.141.47
94.198.41.99
43.134.73.205
188.215.235.94
188.215.235.88
178.218.167.216
172.107.246.188
172.107.246.60
172.107.246.138
172.107.246.134
172.107.246.58
116.90.74.185
172.107.246.59
172.107.246.139
172.107.246.118
20.91.188.27
106.144.25.91
178.249.214.75
35.230.130.11
37.120.217.165
92.223.89.146
103.157.139.4
20.164.39.239
212.129.7.65
51.15.149.5
172.173.178.202
103.230.142.233
5.8.16.163
87.249.133.115
217.138.220.199
188.241.177.228
151.106.38.75
4.236.186.218
5.157.13.3
190.136.50.33
38.147.168.233
95.174.65.147
85.132.252.37
20.0.0.189
185.212.169.195
81.169.226.88
66.90.67.44
196.244.192.230
102.38.204.5
20.62.1.102
84.252.113.5
195.154.36.107
163.172.112.188
159.242.228.116
51.158.21.218
154.47.24.203
185.224.128.31
149.202.67.181
23.175.48.210
23.175.48.210
147.182.180.42
57.128.33.103
51.89.157.82
51.158.46.129
51.178.64.240
184.168.28.215
192.99.161.59
45.155.91.121
46.101.195.167
159.89.101.18
164.92.129.196
178.62.14.68
45.155.91.124
5.62.62.205
92.38.180.47
185.54.229.42
5.62.34.17
64.112.72.254
185.224.128.117
185.224.128.118
45.155.91.63
95.216.21.57
5.62.56.29
5.62.62.149
5.62.62.37
5.62.60.197
185.185.133.179
5.62.60.17
5.62.60.145
5.62.62.153
5.62.61.61
185.185.132.51
5.62.62.17
5.62.58.29
5.62.62.141
212.129.39.217
5.62.60.153
5.62.63.53
5.62.60.157
159.242.228.1
185.185.133.67
5.62.60.37
5.62.62.189
195.154.61.12
195.154.54.32
5.62.62.9
5.62.62.161
5.62.60.13
159.242.234.169
5.62.61.249
5.62.63.17
5.62.56.25
5.62.62.41
5.62.58.193
5.62.60.129
5.62.60.9
5.62.62.13
84.17.46.159
5.62.61.237
159.242.234.127
5.62.56.229
5.62.63.245
5.62.63.233
5.62.56.141
5.62.58.197
5.62.20.35
5.62.60.97
5.62.63.49
5.62.61.25
84.17.46.229
5.62.56.213
159.242.234.2
5.62.58.25
37.120.232.116
5.62.56.217
5.62.62.25
5.62.60.41
5.62.61.57
5.62.62.93
5.62.56.121
5.62.56.205
5.62.20.25
5.62.58.133
185.212.169.211
5.62.62.125
5.62.60.25
5.62.58.113
5.62.58.185
5.62.60.169
5.62.58.209
5.62.20.45
159.242.234.85
5.62.62.237
20.49.48.203
185.212.169.163
5.62.60.105
92.38.172.12
5.62.60.249
5.62.62.225
5.62.63.1
5.62.62.221
5.62.63.5
103.76.164.20
5.62.63.37
5.62.60.61
5.62.58.101
5.62.62.77
5.62.62.73
5.62.62.165
5.62.61.229
5.62.56.109
5.62.56.101
5.62.63.169
5.62.56.89
92.38.172.26
5.62.60.233
5.62.60.165
5.62.61.13
5.62.58.97
5.62.61.45
5.62.56.105
5.62.60.73
5.62.61.189
5.62.58.85
5.62.60.229
5.62.62.241
5.62.60.77
5.62.61.9
5.62.63.225
5.62.62.61
5.62.60.173
103.108.94.244
92.38.162.145
5.62.62.101
103.76.164.4
103.231.91.132
20.39.210.91
20.46.48.197
5.62.61.145
5.62.58.17
20.110.15.145
5.62.61.245
5.62.60.49
5.62.63.213
5.62.62.113
5.62.56.41
5.62.61.109
5.62.63.33
5.62.61.37
5.62.49.30
128.127.105.193
5.62.58.21
37.120.142.83
5.62.62.209
5.62.60.117
5.62.56.17
5.62.63.29
5.62.61.225
5.62.63.241
5.62.58.41
5.62.61.41
5.62.63.85

Hope this helps someone.
Pete.

1 Like

An Easy Way To Stop Continuous Brute Force Hacking Attacks on FreePBX

Hi guys,

I thought I would make a post to help people deal with the continuous brute force hacking attacks that keep occurring once a FreePBX is live on any network.

Basically, I got tired of trying to block IP Address ranges from clever hacker bots that keep trying to brute force attack (guess extension & password - or search for guest extensions) to then use bandwidth and ultimately VoIP Accounts which usually result in thousands of dollars lost thanks to these scumbag hackers.

Therefore I have written a Python script (with lots of help from Chat GPT-4) that utilizes ‘iptables’ and a few other neat little tricks such as peering into the asterisk log file, to identify and ultimately immediately block brute force hacking attacks which often take over your network if it’s not protected which is the case for most people. If you are a super duper I.T. professional or genius then you probably won’t care about this script, but if you are the average user with some knowledge in Linux terminal, then this could be useful to you.

Anyone can use this script free, I’ve made a readme file that explains all the steps you need to do to get it up and running as a service. Alternatively, you can also run it manually, even with --debug option, which is also described in the readme. I called this script ‘KobraKai’ (after the famous Karate series) because the script has a ‘No Mercy’ policy to block brute force hacker attempts immediately, without giving them any chance to continue. The moment a hacking attempt is detected through the asterisk log and a hacker-ips-list log, the script blocks the originating IP Address through iptables.

I wanted to gift this to the FreePBX community after enjoying the software for many years and now it was time to give back something to the community.

The file provided is a zip file through the following link: https :// www. udrop. com/ 89SL /KobraKai-v1-2023 .zip

Don’t worry there are no viruses in it. Anyone can open all files with a simple notepad and inspect if you have doubts.
Here is the structure of the files contained in the .zip file.

1/ 1x folder that contains 3x files (a) hacker-ips-list.txt, (b) ignore-list.txt (c) kobrakai-v1.py
Install this in the “/home” directory when logged into root.
2/ 1x kobrakai.service file (to be installed in the /etc/systemd/system/ directory).
3/ 1x README file which contains description and instructions on how to install everything.

Yes sure, I know people will say don’t install anything in root, however this needs root access to be able to issue commands through to iptables and a few other applications. If you don’t trust the code, then either don’t use it or open the kobrakai-v1.py file with notepad and read through the code. It is there to help people stop these damn brute force hacking attacks, permanently.

Note: Sure, anyone can setup IPTABLES and BLOCK ALL traffic then allow only the required IP Addresses of those devices you use for your network, however many times this becomes troublesome if you are a noob or you don’t know what you are doing or if you use Dynamic external IP Addresses. This software will ONLY identify and block hackers that make brute force hacking attempts through iptables, nothing else.

I hope this helps someone.
Cheers
Pete…

To help understand the python script file, I have output the contents below:

########################################################################################################################################################
########################################################################################################################################################
################## KobraKai - No Mercy Hacker Blocker for FreePBX Machines - By Pietro Casoar with help from Chat GPT-4 ################################
########################################################################################################################################################
# This software is a no nonsense blocker against hackers that attempt brute force attacks on your FreePBX(c) (Or Asterisk(c) / Sangoma(cc)) devices.   #
# Note that this software is NOT meant for noobs/novices, you need to know what you are doing around a linux system and have at least basic knowledge  #
# of iptables.  When in doubt, how to work with IP Tables, you can always consult Chat GPT for assistance.                                             #
########################################################################################################################################################
########################################################################################################################################################
# You are Free to distribute and edit/add to this script anywhere, with the caveat that you keep my name as the original author of this script         #
# KobraKai - VoIP Hacker Blocker Script                                                                                                                #
# Copyright (c) 2023 Pietro Casoar                                                                                                                     #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER   #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #
# IN THE SOFTWARE. USE AT YOUR OWN RISK.                                                                                                               #
########################################################################################################################################################
#                                                                                                                                                      #
# NOTE: DEBUG Feature should be with the following usage: [python3 kobrakai-v1.py --debug]                                                             #
#                                                                                                                                                      #
# This software has been tested & designed to run continuously on a FreePBX image with great success, blocking all scumbag hackers that were detected  #
# The software has been tested on a Raspberry Pi 4 Hardware / FreePBX image as of May 15 2023.                                                         #
#                                                                                                                                                      #
# In Summary: when a VoIP hacker tries to brute force attack your machine which can ultimately result in having your bandwidth or even account minutes #
# stolen, this software will immediately identify and mercilessly block all IP Addresses of these low life hackers, by applying it to iptables rules   #
# and immediately saving iptables rules.  Even if your machine reboots or has a power failure, when it boots up again, it will automatically be        #
# running in the background and continue to block all hackers from brute force attacking your FreePBX machine.                                         #
#                                                                                                                                                      #
# Just be aware to make sure you add your own IP Address and or Dyns Domain Name, BEFORE you activate the service, so that you don't block yourself    #
# incase you make an error with the SIP / IAX extension or password, otherwise this software will immediately and permanently lock you out of your     #
# system, without mercy.                                                                                                                               #
#                                                                                                                                                      #
# If however, that does happen, you must log in locally to the server and perform the following 2 actions:                                             #
# 1/ Edit the "hacker-ips-list.txt" file and remove your IP Address.                                                                                   #
# and                                                                                                                                                  #
# 2/ Use the "iptables -D INPUT -s {ip} -j DROP" command to remove your ip address from IPTABLES.                                                      #
# and                                                                                                                                                  #
# 3/ Add your IP Address / range to the "ignore-list.txt" file and save.                                                                               #
# Note: {ip} = your IP Address (either local or external or both), depending on what result you get after issuing the "iptables -L -v" command.        #
#                                                                                                                                                      #
# To avoid the above mentioned, make sure you add your IP Address (Local & External / DynDns) to the "ignore-list.txt" file BEFORE executing the code  #
########################################################################################################################################################

# Initiate Modules
import re
import os
import subprocess
import collections
import argparse
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import logging

# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--debug", help="turn on debug mode", action="store_true")
args = parser.parse_args()

# Configure the watchdog logging module based on command line argument
if args.debug:
    logging.basicConfig(level=logging.DEBUG)
else:
    logging.basicConfig(level=logging.ERROR)

ASTERISK_LOG_FILE = "/var/log/asterisk/full"
IGNORE_LIST_FILE = "/home/KobraKai/ignore-list.txt"
HACKER_IPS_LIST_FILE = "/home/KobraKai/hacker-ips-list.txt"

blocked_ips = set()
# Additional Blocked IPs iptables Save function here #
# Add the new functions here
def save_iptables():
    # Save the iptables rules
    os.system("iptables-save > /etc/iptables.up.rules")

def load_iptables():
    # Load the iptables rules
    os.system("iptables-restore < /etc/iptables.up.rules")

def check_hacker_ips():
    with open(HACKER_IPS_LIST_FILE, 'r') as f:
        hacker_ips = set(f.read().splitlines())
    iptables_list = str(subprocess.check_output("iptables -L INPUT -v -n", shell=True))
    for ip in hacker_ips:
        if ip not in iptables_list:
            update_iptables(ip, 'A')
### Closed Editing of original here ###

def update_iptables(ip, action):
    print(f"Updating iptables for {ip} with action {action}")
    # Update iptables rule
    cmd = f"iptables -{action} INPUT -s {ip} -j DROP"
    try:
        output = subprocess.check_output(cmd, shell=True)
        print(f"Executed command: {cmd}")
        print(f"Output: {output}")
        save_iptables()
    except Exception as e:
        print(f"Failed to execute command: {cmd}")
        print(f"Error: {e}")

def process_log_line(line):
    patterns = [
        r"failed for '(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)",
        r"UDP (\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b):"
    ]
    ip = None

    for pattern in patterns:
        match = re.search(pattern, line)
        if match:
            ip = match.group(1)
            print(f"Suspicious IP Detected: {ip}")
            break

    if ip:
        with open(IGNORE_LIST_FILE, 'r') as f:
            ignore_ips = set(f.read().splitlines())

        with open(HACKER_IPS_LIST_FILE, 'r+') as f:
            hacker_ips = set(f.read().splitlines())

            if ip not in ignore_ips:
                if ip not in blocked_ips:
                    blocked_ips.add(ip)
                    f.write(f"{ip}\n")
                    print(f"Suspicious IP Blocked: {ip}")
                    update_iptables(ip, 'A')  # Append rule
            elif ip in blocked_ips:
                print(f"Removed from IPTABLES: {ip}")
                blocked_ips.remove(ip)
                f.seek(0)
                f.write('\n'.join(hacker_ips))
                f.truncate()
                update_iptables(ip, 'D')  # Delete rule

class AsteriskLogHandler(FileSystemEventHandler):
    def on_modified(self, event):
        if event.src_path == ASTERISK_LOG_FILE:
            with open(event.src_path, 'r', encoding='latin-1') as f:
                lines = collections.deque(f, 100)
                for line in lines:
                    process_log_line(line)

if __name__ == "__main__":
    load_iptables()  # Load iptables config and blocked ip list
    check_hacker_ips()  # Check all ips in the hacker-ips-list.txt against iptables config
    event_handler = AsteriskLogHandler()
    observer = Observer()
    observer.schedule(event_handler, path='/var/log/asterisk/', recursive=False)
    observer.start()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

# END OF CODE

This is the heart of the kobrakai-v1.py file.

In terms of running this file as a service, you need to add the following file/contents (kobrakai.service) to the /etc/systemd/system/ directory of your FreePBX machine.

[Unit]
Description=KobraKai - No Mercy VoIP Hacker Blocker for use with FreePBX(c) (Asterisk(c)/Sangoma(c)) Software

[Service]
ExecStart=/usr/bin/python3 /home/KobraKai/kobrakai-v1.py
Restart=always

[Install]
WantedBy=multi-user.target

There are another 2 files which contain both hacker IP Addresses as well as the ignored IP Addresses.
a) hacker-ips-list.txt
b) ignore-list.txt

Finally, here is the readme contents:

README

########################################################################################################################################################
############# KobraKai - No Mercy Hacker Blocker for FreePBX Machines - By Pietro Casoar with help from Chat GPT-4 #####################################
########################################################################################################################################################
# This software is a no nonsense blocker for hackers that attempt brute force attacks on your FreePBX (Or Asterisk / Sangoma) devices.                 #
# Note that this software is NOT meant for noobs/novices, you need to know what you are doing around a linux system and have knowledge of iptables.    #
#                                                                                                                                                      #
# You are Free to distribute this script anywhere, with the caveat that you keep my name as the original author of this script                         #
# KobraKai - VoIP Hacker Blocker Script                                                                                                                #
# Copyright (c) 2023 Pietro Casoar                                                                                                                     #
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER   #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS #
# IN THE SOFTWARE. USE AT YOUR OWN RISK.                                                                                                               #
########################################################################################################################################################
#                                                                                                                                                      #
# NOTE: DEBUG Feature should be with the following usage: [python3 kobrakai-v1.py --debug]                                                             #
#                                                                                                                                                      #
# This software has been tested and running continuously on a FreePBX image (Raspberri pi 4) with great success, block all those scumbag hackers       #
#                                                                                                                                                      #
# In Short, when an asshole VoIP hacker tries to brute force attack your machine which can ultimately result in having your bandwidth or even minutes  #
# stolen, this software will immediately identify and mercilessly block the IP Addresses of these low life scumbag hackers, by applying it to iptables #
# rules and saving iptables, within a couple of seconds.                                                                                               #
#                                                                                                                                                      #
# Even if your machine reboots or has a power failure, when it boots up again, it will automatically be running in the background and                  #
# continue to block all hackers from brute force attacking your FreePBX machine.                                                                       #
#                                                                                                                                                      #
# Just be aware to make sure you add your own IP Address and or Dyns Domain Name, BEFORE you activate the service, so that you don't block yourself    #
# incase you make an error with the SIP / IAX extension or password, otherwise this software will immediately and permanently lock you out of your     #
# system, without mercy.                                                                                                                               #
#                                                                                                                                                      #
# If however, that happens to you, you must log in locally to the server and perform 2 actions:                                                        #
# 1/ You must edit the "hacker-ips-list.txt" file and remove your IP Address.                                                                          #
# and                                                                                                                                                  #
# 2/ Use the "iptables -D INPUT -s {ip} -j DROP" command to remove your ip address from IPTABLES.                                                      #
# Note: {ip} = your IP Address (either local or external or both), depending on what result you get after issuing the "iptables -L -v" command.        #
#                                                                                                                                                      #
# To avoid the above mentioned, make sure you add your IP Address (Local & External / DynDns) to the "ignore-list.txt" file before executing the code  #
########################################################################################################################################################

Description:

This script is designed to monitor an Asterisk server's log file for suspicious activities and respond by updating the server's iptables rules to block IP addresses identified as suspicious. The script uses the watchdog module to monitor the log file for changes, and it employs regular expressions to identify suspicious activities by their patterns in the log file.

Here's a high-level breakdown of the functions:

save_iptables(): Saves the current iptables rules to a file. This is used after updating the iptables rules to ensure the changes persist after a system reboot.

load_iptables(): Loads the iptables rules from a file. This is used at the start of the script to ensure any previously saved rules are applied.

check_hacker_ips(): Checks if the IPs in the hacker-ips-list.txt file are blocked in the iptables. If any IP is not blocked, the function calls update_iptables to block it.

update_iptables(ip, action): Updates the iptables rules to either block (action='A') or unblock (action='D') the specified IP address, and then saves the updated rules using save_iptables().

process_log_line(line): Processes each line of the log file, looking for patterns that indicate suspicious activity. If a suspicious IP is found and it's not in the ignore list, the function updates the hacker-ips-list.txt file and the iptables rules to block it. If an IP in the ignore list is currently blocked, the function updates the hacker-ips-list.txt file and the iptables rules to unblock it.

AsteriskLogHandler(FileSystemEventHandler): This class is a custom file system event handler. It overrides the on_modified method to process the last 100 lines of the log file whenever the log file is modified.

The script begins by loading the iptables rules and checking the hacker-ips-list.txt file against the iptables. It then starts the file system observer to monitor the Asterisk log file. The script runs in an infinite loop until it's interrupted by the [systemctl stop kobrakai.service] command, at which point it stops the file system observer.

For debug purposes, before enabling and starting the service, you can run the script by issuing the following command:
python3 /home/KobraKai/kobrakai-v1.py --debug
this will allow you to monitor the software to confirm its functionality.

Note that this file is provided with a list of IP Addresses that are known to be used by scumbag VoIP hackers seeking to steal your bandwidth and use your VoIP accounts which you will ultimately pay for out of your own pocket. "I speak from experience"

Now that thats out of the way, Lets get started:

[Note that these instructions are based on linux based machines such as the FreePBX Image for the Raspberry Pi found here: http://www.raspberry-asterisk.org/downloads/]

To make this code run, you need to do the following in preparation:

1/ Get yourself a copy of FileZilla or WinSCP.
2/ Make sure you have 1 folder named "KobraKai" (containing 3 files) (a) "hacker-ips-list.txt" (b) "ignore-list.txt"  (c) "kobrakai-v1.py"
3/ Make sure you have 1 file named "kobrakai.service"
4/ Make sure you have ssh ROOT access to the FreePBX machine.

5/ Next, log into your server (the machine you've installed your FreePBX on via your FileZilla or WinSCP.  In this case it is the Raspberry Pi 4) but make sure you log in via ROOT !!!
### IF YOU DO NOT DO THIS IN ROOT, NOTHING WILL WORK !!! ###  You will need to use the following protocol to transfer files [sftp://x.x.x.x]

6/ Transfer the folder [KobraKai] and ALL its contents, to the /home directory of the FreePBX machine, whilst in root access.

7/ Then transfer the [kobrakai.service] file to the "/etc/systemd/system/" directory of the FreePBX machine, whilst in root access.

8/ Next, use your linux terminal from another machine (or locally on the FreePBX machine), to enter via ssh.
Note if you have not changed the ssh port number, the default will be 22.  It is advised you change this port number to something different and very high in number, above 65,000.

[From linux terminal] type(without the hash#): #ssh root@{server-ip} -p 22
and then type the default/your root password for your machine. Default password= raspberry

[From FreePBX terminal] type(without the hash#): #root
and then type the default/your root password for your machine. Default password= raspberry

Once you have logged in, you must type the following to install the required applications.

Type: (without the hash #)
# apt update

then type
# apt install python3-pip

and then type
# pip3 install watchdog

and finally, type
# apt install netfilter-persistent

Wait for these to install correctly with no errors.
Note that without these 3 apps, the script will not work.

9/ Once that is done, we need to perform the final steps in preparation before running the script and that is we need to now prepare IPTABLES to be able to save rules and have then readily available for the script to read.
Using your ssh terminal (or local terminal) from root prompt (because you must have root privileges): (without the hash #)

# touch /etc/iptables.up.rules

Then, you need to ensure that the file is writable:
# chmod u+w /etc/iptables.up.rules

Now, you can manually save the current iptables rules to this file to ensure that everything is working:

# iptables-save > /etc/iptables.up.rules

10/ Now the machine has been prepared and you are ready to activate the script.

Type: (without the hash #)

# systemctl enable kobrakai.service
This will enable the kobrakai service and enable the script to run in the background

# systemctl start kobrakai.service
This starts the kobrakai service

and to check it's operation, you must type:
# systemctl status kobrakai.service

A correct output that doesn't have any errors should look something like this:

root@raspbx:/KobraKai# systemctl status kobrakai.service
------------------------------------------------------------------------------------------------------------------------------------------
● kobrakai.service - KobraKai No Mercy Scumbag VoIP Hacker Blocker for use with FreePBX (Asterisk/Sangoma) Software
   Loaded: loaded (/etc/systemd/system/kobrakai.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2023-05-14 08:20:23 BST; 2s ago
 Main PID: 6551 (python3)
    Tasks: 4 (limit: 4915)
   CGroup: /system.slice/kobrakai.service
           └─6551 /usr/bin/python3 /home/KobraKai/kobrakai-v1.py

May 14 08:20:23 raspbx systemd[1]: Started KobraKai No Mercy Scumbag VoIP Hacker Blocker for use with FreePBX (Asterisk/Sangoma) Software.
------------------------------------------------------------------------------------------------------------------------------------------

To check the service whilst running and any important events, you can use the following:

# journalctl -u kobrakai.service
The output of this will provide a log which looks something like this, if there are no errors (which should be the case if you've done everything described above, correctly)
------------------------------------------------------------------------------------------------------------------------------------------
May 14 07:20:56 raspbx systemd[1]: Stopping KobraKai No Mercy Scumbag VoIP Hacker Blocker for use with FreePBX (Asterisk/Sangoma) Software...
May 14 07:20:56 raspbx systemd[1]: kobrakai.service: Main process exited, code=killed, status=15/TERM
May 14 07:20:56 raspbx systemd[1]: kobrakai.service: Succeeded.
May 14 07:20:56 raspbx systemd[1]: Stopped KobraKai No Mercy Scumbag VoIP Hacker Blocker for use with FreePBX (Asterisk/Sangoma) Software.
May 14 08:20:23 raspbx systemd[1]: Started KobraKai No Mercy Scumbag VoIP Hacker Blocker for use with FreePBX (Asterisk/Sangoma) Software.
------------------------------------------------------------------------------------------------------------------------------------------

In order to exit this log, you just need to press CTRL and C.

If you want to check on the status of the hacker-ips-list.txt file, to see how many or if any new hacker scumbag IP Addresses have been detected and logged, just use the following command:

# cat /home/KobraKai/hacker-ips-list.txt

Now you can rest easy because your FreePBX machine is protected by an additional firewall process which I have working together with the essential Fail2ban (having set guest access to OFF in the advanced settings of asterisk/freepbx).  I hope this helps anyone who is frustrated or who just doesn't have the time to go through FreePBX settings to make sure everything is locked down, or whoever doesn't have the time or knowledge to protect their system.
You are free to distribute this script, just make sure you retain my name in the top header of the script with the description.

The reason for posting the script contents here is for those that don’t trust downloading the .zip file mentioned above.

I hope this helps someone.
Cheers
Pete…

Are you re-inventing the wheel? This thread is describing something very similar to fail2ban, which comes pre-installed as part of the FreePBX Firewall. Fail2ban

If you believe that your software is superior, please explain why. If it runs in important situations where fail2ban is not suitable, explain how.

I’m not saying its superior nor inferior, that’s not the point for posting the script here, nor am I reinventing the wheel. Its a simple script that blocks ALL hacking attacks, more than Fail2Ban does and you can prove it easily. The script relies on messages within asterisk log which is where/how you can know who is trying to brute force your FreePBX.

The point is, I use this script Together With Fail2Ban and in fact in the readme I mention I use it together with Fail2ban. However, the problem is, Fail2ban does NOT block ALL of the hacking attempts as you can check it yourself if you monitor your asterisk log file. You will see hundreds if not thousands of hack attempts from the SAME IP Address which should have been blocked by Fail2Ban but in reality it didn’t block them all.

How to check it yourself? Go to the Asterisk log file: and cat /var/log/asterisk/full
You will see MANY of the 3 examples I showed in the first post and the problem is that fail2ban does NOT block all of them, it will only block some that align with the Fail2Ban blocking parameters.

I was running fail2ban, with the Guest (advanced settings) set to OFF, before I used the script and I still got hacked within 24 hours of installing FreePBX on a network that was behind a firewall. Only specific UDP ports were exposed via appropriate port forwarding, nothing different from anyone else.

This is the reason why I made the script because there was no other way to stop these continuous attacks. If you feel that this Additional script isn’t needed and fail2ban does everything for you, then don’t use it, nobody is forcing you and I’m not gaining anything from posting this here, I even posted the contents of the script, anyone can use it.

The only reason I’ve shared this here is because for ME, Fail2Ban did NOT block ALL of the hacking attempts as I proved myself (and yes, I made all correct settings in the required configurations in both the advanced settings as well as Fail2Ban settings, which did not stop ALL of the attacks). I will reiterate, I use this TOGETHER with Fail2Ban and it has turned out to be a life saver because my script blocks every single attack shown in the asterisk log file. You will never see the same IP Address/attack after the script detects it in the asterisk log file. This is why its useful.

Then you have fail2ban misconfigured.

fail2ban literally does exactly what your script is doing.

Show us your fail2ban settings.

If you want to block known attackers, use APIBAN, it works great.

Then you have fail2ban misconfigured. fail2ban literally does exactly what your script is doing.

Nope, I have configured fail2ban correctly, I’ve been using fail2ban for years…
However, regardless of whether or not its configured correctly, it should have blocked all the hackers and it didn’t. My script does NOT require ANY configuration, it just blocks hackers when they attempt brute force attacks. You don’t have to be Einstein to use or configure it, because it doesn’t need to be configured either. It just works.

The sole function of the script is to log extension number registration/invite request is made, and if it has the wrong password, it will immediately block the originating IP Address.
Fail2Ban didn’t do that for me, it only blocks some of the hackers, not all and that’s why I made this script, so I can block them ALL, without config, without headache.

Show us your fail2ban settings. If you want to block known attackers, use APIBAN, it works great.

I haven’t used APIBAN but I find it funny that instead of considering the script as something that may possibly help someone that is super easy to install and run, instead you’re trying to find holes in it or compare it with someone else’s script, for whatever reason you may have in your mind. Whether the Fail2Ban settings are correct or not, that’s not the point. If the Fail2Ban settings are incorrect, from the default (as well), then the script isn’t worth much to most people because we can’t all be professors like you and if that’s the case, most people usually find out the hard way and costing a huge amount of headache and money.

The script I made is to be installed as is, there is no config, it does everything it is supposed to automatically without any intervention or a professor like you that knows how to configure it.

Additionally and most importantly, as most people do, they forget to turn off Guests in the SIP Advanced settings (or maybe they want to keep Guests enabled/allowed), because Fail2Ban will NOT work if you keep guests enabled, my script WILL work. Thats the difference and I am sure it will help most people.

By the way, I see the attitude hasn’t changed in this forum much, since I can remember, fancy giving heat to people for posting stuff that helps others. Next time I’ll know better to keep any help to myself and let professors like you teach everyone how to configure Fail2Ban and any other software that you know.

By the way, where is YOUR page to show the correct Fail2Ban configuration? have you posted one thread here before? do you have a configuration page that you can reference? Don’t worry about providing a link to the wiki, that’s pointless. Show us YOUR configuration for Fail2Ban so that everyone else interested can know how to configure Fail2Ban correctly as a professor like you.

I didn’t make the script to make money nor did I make it for any other reason other than to block these scumbag hackers (Without ANY Configuration) that make life miserable when you wake up one morning and find your connection overrun and account emptied or costing you thousands, and overrun by scumbag hackers OR to boast about who’s script is better or cooks you breakfast, lunch and dinner or can take the trash out each week…

If you think Fail2Ban is better, then fine, don’t use my script its not for you because you are too good for my crappy script. I wrote this script for people who don’t know how to configure Fail2Ban (even though I configured mine correctly and it only blocked some of the hackers, not all of them were blocked thus my FreePBX WAS compromised and Fail2Ban was not able to stop that from happening).
Even in circumstances where SIP Advanced settings have not been adjusted to turn OFF Guests, my script will work as mentioned above.

The script provided blocks EVERY hacker that tries to register but has a wrong password, thus you will see those logs in your asterisk log. There is no configuration needed at all.

This just isn’t true. First, the FreePBX distro comes with a default firewall that denies all so any distro based systems I have, don’t ever see this kind of thing happening. Even on systems that aren’t distro based, I don’t see what you are seeing. I’m pretty sure there are others that don’t either because again, firewalls already in place.

As well, I also don’t like just blocking a bunch of /32’s from the same IP space. Specially when that IP space is a constant problem, like the 5.62.x.x you have listed. Over 2 dozens IP rules that could be handled in one or two rules. More efficient because the amount of rules a firewall has to process impacts the performance of the firewall. So I’d rather block the same amount of IPs with a handful of rules instead of 1,000’s of /32 entries.

Also, since I know my customer base is only coming from specific types of IP spaces (i.e. US based ISPs) it’s pretty easy to block anything not in the ARIN space. Cuts back on a lot of work and worry.

This just isn’t true. First, the FreePBX distro comes with a default firewall that denies all so any distro based systems I have, don’t ever see this kind of thing happening. Even on systems that aren’t distro based, I don’t see what you are seeing. I’m pretty sure there are others that don’t either because again, firewalls already in place.

Ahhh actually it IS true, and anyone can replicate it any time you like buddy.
I haven’t used any special image or .iso, I’ve used the image provided directly from asterisk/sangoma and anyone can prove the default iptables rules are NOT Deny All.

Why are you stating stuff that isn’t true? You’re being deceptive in telling people that the “FreePBX distro comes with a default firewall that denies all” —> That is Absolute Nonsense! It does NOT deny all because if it did, then no traffic would go through unless you manually allowed it. Secondly, ANYONE can install FreePBX image (in my case I downloaded and installed the Raspberry Pi 4 Image) and the IPTABLES rules were open. So what you are saying is complete nonsense.

As well, I also don’t like just blocking a bunch of /32’s from the same IP space. Specially when that IP space is a constant problem, like the 5.62.x.x you have listed. Over 2 dozens IP rules that could be handled in one or two rules. More efficient because the amount of rules a firewall has to process impacts the performance of the firewall. So I’d rather block the same amount of IPs with a handful of rules instead of 1,000’s of /32 entries.

Thats fine you can block an IP Range by changing the script from iptables -{action} INPUT -s {ip} -j DROP to a range variant such as iptables -{action} INPUT -s {x.x.0.0/16} -j DROP
No problem at all. However Fail2Ban doesn’t block a range either and I’m not sure if you can modify it to drop ranges either, nor do I care.
You could even block all and only allow certain IP addresses through, that’s fine, I even mention that in the readme. However now you’re getting into configuration that is well above the average user’s knowledge. The script is NOT for that kind of setup, its for the average joe blow who doesn’t know or have the time to sit and fiddle with IPTABLES rules all day long.

Also, since I know my customer base is only coming from specific types of IP spaces (i.e. US based ISPs) it’s pretty easy to block anything not in the ARIN space. Cuts back on a lot of work and worry.

Thats fine, you are obviously well versed in networking, but most general users wouldn’t know how to do that or maybe they don’t have time or something. Its not the point. You are talking about specific stuff that would be covered by an IT professional. My script isn’t for professionals, its for basic users who don’t know how to configure. My script does NOT require ANY configuration, other than inputting your IP address/range/domain in the ignore-list.txt file. Thats about it. Outside of that, you just load and run and that’s the way it is intended to be used. If you want more specific stuff, then the script isn’t for you, just like I noted above.

  1. Before claiming nonsense. How do you know your firewall was properly configured?
  2. The RaspberryPi image and FreePBX distro are completely separate things. As a matter of fact, FreePBX on raspberry pi project has its own forums.
  3. You can easily add custom IPtable rules in the GUI within the FreePBX firewall, blocking anything outside of ARIN.
  4. Just tested again, fail2ban, when configured the way you desire --WILL BLOCK an IP on the first attempt with failed credentials. Most people won’t want it acting that way as it can sometimes interfere with the initial 401 challenge.
  5. You keep on saying that you don’t need ANY configuration for your script, but you need to download a zip, run a service etc etc etc… What?

Right, that’s why there is a wizard when you first set it up. It especially has a step in which it asks you to allow IPs for access including the one you’re setting the PBX up from. So yeah, people have to manually allow their own IPs during the wizard, it’s point and click though.

Outside of that there is also the Responsive Firewall portion that allows you to open the SIP Signalling ports and does connection tracking to automatically drop any requests that come in too fast or have too many bad authentications.

I said the FreePBX Distro which is released by Sangoma and is an ISO/image that installs the SagomaOS on the system. You are referring to the RasPBX project which is a third party project not directly related to Sangoma or the FreePBX project. Any non-Distro install doesn’t come with a default firewall, this is well documented in the FreePBX documentation. Doing a manual install requires you to have some sort of knowledge on how networking and Linux works.

The fact that RasPBX doesn’t include a firewall with their version of FreePBX is on that project and not FreePBX. So what I said was, in fact, not complete nonsense but actual facts about how this project works. Something it seems you need to familiarize yourself with.

  1. Before claiming nonsense. How do you know your firewall was properly configured?

I don’t claim nonsense, but thanks for being a smart alec…
Here ya go professor… I do a pen test to check what is open etc…
as well as issuing the relevant commands to see how iptables rules are configured.
An example of a pen test I use is: nmap -sV -Pn --script vulners 192.168.1.200 -v
This is just one, I’m not going to list them all, especially because you are such a professor you know everything anyway… :man_facepalming:

  1. The RaspberryPi image and FreePBX distro are completely separate things. As a matter of fact, FreePBX on raspberry pi project has its own forums.

Do you even know what a raspberry pi is? doesn’t look like it, its just another hardware, the FreePBX image is all the same, they are all linux based, all same config. Probs better to brush up on your knowledge before trying to be a professor to everyone.

  1. You can easily add custom IPtable rules in the GUI within the FreePBX firewall, blocking anything outside of ARIN.

Sure, but you actually have to know the IP Addresses that are from hacker/attacks… Great, so you know off by heart, every single attacker do you? Ridiculous.
The only way you are going to know is if you look through the asterisk log file and find all of the IP addresses from all the failed registration attempts… which means you are going to sit in front of your PC every day, look through the log and manually input them through the GUI… Really? :man_facepalming:

  1. Just tested again, fail2ban, when configured the way you desire --WILL BLOCK an IP on the first attempt with failed credentials. Most people won’t want it acting that way as it can sometimes interfere with the initial 401 challenge.

Really? Okay, give me the IP Address and I’ll show you how your fail2ban will NOT block my attacks.
I’m waiting for you to provide your external IP… then we will see how good your fail2ban config is.
Besides, why don’t you SHOW US ALL your config, so that we can all be professors like you and know how to set up Fail2Ban properly like you… right? We are all waiting for your config.

  1. You keep on saying that you don’t need ANY configuration for your script, but you need to download a zip, run a service etc etc etc… What?

Downloading files and installing them is NOT configuration. Fail2Ban configuration requires you to fiddle with the script. You don’t need to do any of that with my script. You just install it and run it as a service. You can also run it separately if you want to keep a debug running.

Additionally, if you do not disable Guests in SIP Advanced Settings in FreePBX, Fail2Ban will NOT work !!! You don’t have to worry about that with my script, it will work regardless.

I shall now await your Fail2Ban script so that you can show us all how good and perfect you know how to set it up.

Right, that’s why there is a wizard when you first set it up. It especially has a step in which it asks you to allow IPs for access including the one you’re setting the PBX up from. So yeah, people have to manually allow their own IPs during the wizard, it’s point and click though.

No such wizard for IPTABLES rules on the image I used. I haven’t tried ALL the images that FreePBX is distributed with so I can’t comment on other images, I don’t know.

Outside of that there is also the Responsive Firewall portion that allows you to open the SIP Signalling ports and does connection tracking to automatically drop any requests that come in too fast or have too many bad authentications.

Sure, but you have to know WHICH IP Addresses are attacking you. The only way you can find out is either logging from your router/firewall OR through the Asterisk log file. The script reads the asterisk log file and detects and blocks the failed registrations. Thats all the script does, doesn’t require ANY Configuration or settings that you need to fiddle with after you install it. Its just a simple blocker.

The fact that RasPBX doesn’t include a firewall with their version of FreePBX is on that project and not FreePBX. So what I said was, in fact, not complete nonsense but actual facts about how this project works. Something it seems you need to familiarize yourself with.

Thats not true, the Raspberry Pi image DOES come with iptables, ALL linux distros come with iptables. I’m not sure what you are on about there, but anyways…

The fact of the matter is, right from the start I mentioned (as well in the readme and notes within the python script) that this was tested with a raspberry pi 4 and I even give the URL for the image.
I also stated its not for professionals because you wouldn’t need it.
I keep stating its for general use, but nobody seems to understand what I’m writing.
I never said its a replacement for anything, nor am I trying to tell anyone that its better than Fail2Ban.

All I tried to do is SHARE with the public a solution that I found.
If you don’t like the solution or don’t agree with it, that’s fine, but that doesn’t mean you have to try shoot the script down. If you don’t like it, then don’t use it. Simple. Nobody is forcing anyone, its just a solution I found to work for me, blocking hackers that have NOT been blocked by Fail2Ban nor the default iptables settings.

Yet unfortunately things haven’t changed in this forum, its full of people with egos the size of the universe. :man_facepalming: such a pitty.

:man_shrugging:

Again this is not true. They have to make modifications to the software to make their package. They have to package the software themselves. Sangoma has two things, the Distro image and the tarball of the FreePBX OSS source. They don’t make packages for other OS systems like RasPI, RasPBX is its own project that touches things and can remove/add things on their own.

As it was already said, the RasPBX project doesn’t get official support here. If someone with a RasPBX has an issue with installation or some system level issue, that’s something that has to be supported by the RasPBX project, not Sangoma.

Honestly, this has nothing to do with whether or not your firewall is good or bad. It could be great. This is more about the incorrect assumptions you have about how FreePBX and this project work. You’re assuming that your experience of installing RasPBX is somehow the same experience for everyone running FreePBX and we’re simply trying to tell you that’s not true.

1 Like

I don’t think it’s too much to ask that conversations be conducted respectfully. Differences of opinion and correcting misconceptions can be done without name calling.

Pete, thanks for your contribution and for kicking off the conversation. The main source of confusion in this thread is due to the differences between “FreePBX” and the “FreePBX Distro”. These are two different things. There are several distro projects that will give you a system with FreePBX and Asterisk, and they all work differently. The “FreePBX Distro” published by Sangoma includes a FreePBX Firewall module that can do everything discussed in this thread and more. If you’re only familiar with other distros such as RaspPBX, then you may not be aware of this. The FreePBX distro is not supported on the Pi (or any ARM based system).

I do encourage you to investigate APIBAN, you’ll find it does largely what your project does except the ban list is crowdsourced.

3 Likes

I don’t claim nonsense

LoL says he who is full of nonsense… I’m still waiting for YOUR fail2ban config… you are the professor who knows how fail2ban should be setup… I’m waiting… Oh I forgot, you will never provide it, you know why? Because YOU are full of nonsense. Instead of try to write nonsense, how about providing some information to back up your claims… oh I forgot, you can’t because you have no idea.

“FreePBX distro comes with a default firewall that denies all ” —> That is Absolute Nonsense!

Yes correct, it IS nonsense. If your iptables denies all, then how are you able to get traffic through?
Unfortunately, you have no clue what you are talking about, if you did, you’d know that denying all on your iptables literally means you have no traffic allowed through UNTIL you start Allowing traffic. Thats the whole point of ‘denying’…

Again, you have absolutely NO CLUE what you are talking about, you’re just another troll / Fail2Ban tribalist who has nothing better to do with his/her time.

Have a good one, I’m done arguing… I got better things to do with my time than to argue against your nonsensical jibberish.

Thanks for your kind words.

I’m indeed a newbie to FreePBX, Asterisk and fail2ban with zero experience whatsoever. I appreciate you enlightening me with how things work.

1 Like

Thanks for the reply Igaetz, I appreciate it.

I sincerely thought I was doing something good to help those that may be experiencing problems with hackers, but as I’ve quickly found out, there are several tribalists and people that don’t like others to share information other than whats already out there etc…

I’ll know for next time not to share anything anymore, that way I don’t get attacked. Very sad.

In terms of the FreePBX stuff, I only used the image that was on the URL here:
http:// www. raspberry-asterisk .org /downloads/

Anyhow…

No one attacked you, they corrected you. And as I said, this wasn’t about your firewall script being shared, it was about the incorrect things you were saying as to the reasoning behind your firewall script.

It probably didn’t help that the first post of this thread had no mention of RasPBX until the 9th post of the thread. Nor did it help that when someone pointed out that there are things already in place with the Distro that made your script a bit redundant, your reaction was to become rather defensive and lash out.

Mentioning key things like this was for a RasPBX install, at the start, would have probably stopped a lot of this.

2 Likes