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…