Jack Moore

Email: jack(at)jmoore53.com
Project Updates

Syslog-ng more failed Auth Logs

13 Nov 2023 » code, infrastructure, docker

I needed a solution to block unauthorized users attempting to log in to my systems. By using iptables and Python scripts, I’ve developed a method to efficiently block unwanted IPs, ensuring our network remains secure.

To achieve this, I used Python iptables bindings along with custom scripts to automate the process:

  • A script has been added to our production reverse proxy server to manage IP blocking.
  • I’ve updated the ban.sh script for Fail2Ban to log banned IPs and send a request to block them.
  • The uploadbanned.py script was created to automate uploading banned IPs from a file.
  • readnginx.py was created to parse NGINX logs for malicious activity, identifying and banning IPs involved in failed login attempts or other suspicious behavior.

Here are some of the scripts and updates implemented:

Updated ban.sh Script:

#!/bin/bash

echo $1 $2 $3 >> /opt/fail2ban/banned.txt

curl -H "Content-Type: application/json" --request POST --data '{"ip": "$3"}' localhost:5000/block

uploadbanned.py Script:

import requests

def post_ban(ipaddr):
    headers = {"Content-Type": "application/json"}
    r = requests.post("http://192.168.1.2:5000/block", json={"ip": ipaddr}, headers=headers)

with open("banned.txt.copy") as a:
    b = a.readlines()
    for line in b:
        ipaddr = line.split(" ")[2].rstrip()
        post_ban(ipaddr)

readnginx.py Script:

import requests
import re
from datetime import datetime
import shlex
import socket

ips_to_block = []

def post_ban(ipaddr):
    headers = {"Content-Type": "application/json"}
    r = requests.post("http://192.168.1.2:5000/block", json={"ip": ipaddr}, headers=headers)

def valid_ip(address):
    try:
        socket.inet_aton(address)
        return True
    except:
        return False

with open("nginx.log.copy") as nginxlogs:
    lines = nginxlogs.readlines()
    for line in lines:
        a = shlex.split(line, posix=False)
        ip = a[-1].strip('"')
        if valid_ip(ip):
            if a[-5] != "200":
                if "wp" in a[-6] or ".env" in a[-6] or "sftp" in a[-6] or "php" in a[-6]:
                    if ip not in ips_to_block:
                        ips_to_block.append(ip)

for i in ips_to_block:
    # post_ban(i)
    print("IP Banned: " + i)

Our remote server is now actively blocking ports based on WAN IP addresses. A service is running on the WAN server to block these IPs in real-time. A database of blocked IPs has been established, ensuring that our home IP address isn’t blocked accidentally.

© Jack Moore - This site was last built Fri 30 Aug 2024 12:31:24 PM EDT