-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZoneScanner.py
More file actions
executable file
·184 lines (176 loc) · 7.33 KB
/
ZoneScanner.py
File metadata and controls
executable file
·184 lines (176 loc) · 7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/python3 -O
"""
File: ZoneScanner.py
Author: Leon McClatchey
Date: 2025-11-04
Description: Scans Named (dns) query logs for signs of Bot Scanners
Then blocks those discovered IP addresses
This script is designed to be run on the local host,
but it does pull information from the ansible yaml configuration files
"""
import argparse
import os, sys, subprocess
import socket
import logging
import pathlib
import re
# Initialize Global Strings
Config = {}
VAULT_FILE = "secrets.yml"
LOG_PATH = pathlib.Path("/var/lib/named/log/queries.log")
BLOCK_CMD_TEMPLATE = ["firewall-cmd", "--permanent", "--add-rich-rule=rule family='ipv4' source address='{}' reject"]
RELOAD_CMD = ["firewall-cmd", "--reload"]
# === Suspicious DNS Query Patterns ===
SUSPICIOUS_PATTERNS = [
r"AXFR", # Zone transfer attempts
r"ANY", # Amplification probes
r"\.env", # Misguided bot scans
r"localhost\.localdomain", # Misconfigured clients
]
# Function to check the system Path => Common
def CheckSysPath(target):
npath = os.path.normcase(os.path.abspath(target))
for p in sys.path:
nsys = os.path.normcase(os.path.abspath(p))
if npath == nsys: return True
return False
# Function to obtain host information from ansible data files
def ConfigureHosts(parms):
log = parms['log']['path']
host = parms['host']
key = parms['key']
yml = os.path.join(parms['inventory'],"hosts.yml")
if not os.path.isfile(yml):
msg = f"{yml} does not point to a regular File, Aborting!"
FileTools.WriteLog(msg,log,logging.CRITICAL) if log is not None else print(msg)
sys.exit(5)
Ydata = AnsibleTools.LoadYaml(yml,log)
details = AnsibleTools.find_host_any_distro(Ydata,host)
port = 22 if 'port' not in Ydata['all']['children']['linux'][details['distro']].keys() else Ydata['all']['children']['linux'][details['distro']]['port']
msg = f"{host} services: {details['details']['services']}" if details is not None else f"Failed to obtain info for {host}"
level = logging.INFO if details is not None else logging.WARNING
FileTools.WriteLog(msg,log,level) if log is not None else print(msg)
Security = AnsibleTools.AnsibleCredentials(Config['Args']['inventory'],Config['Args']['password'])
return {'host':host,'key':key,'port':port,'admin':Security['sudo_user'],'password':Security['sudo_pass'],'log':log,'services':details['details']['services']}
# Function to get the Commandline arguments => Uses common initializer
def GetArguments():
script_path = os.path.abspath(sys.argv[0])
script_dir = os.path.dirname(script_path)
script_name = os.path.basename(script_path)
Config["Script"] = {"path":script_path,"folder":script_dir,"name":script_name}
MyScript = f"{os.path.splitext(script_name)[0]}"
parser = MyParser(
prog=f"{MyScript}",
description='Verifies that the specified services for the Specified Host has Started',
epilog='Inventory Files: hosts.yml and vault.yml overrides all defaults\nexcept the ssh keys which can be locally defined',
script=f"{MyScript}",
script_version='1.0.0',
include_python_version=True,
ansible_host=True,
usage = "%(prog)s [-h -v --dry-run --log-level -H -i -p --version -L -s] \
\n(-h displays help, --version displays version)",
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("-k", '--key', dest='key', type=str, help=f"locations of SSH Keys, defaults to vault specs")
try:
known,unknown = parser.parse_known_args()
if '-h' in unknown or '--help' in unknown:
help_text = parser.get_help_text()
parser.print_help()
sys.exit(2)
args = vars(known)
args['log']=Tools.String2Dictionary(args['log'],'=')
args['inventory'] = os.path.join(Config['Script']['folder'],'Data') if args['inventory'] is None else args['inventory']
args['password'] = os.path.expanduser(args['password']) if '~/' in args['password'] else args['password']
args['password'] = AnsibleTools.read_vault_password(args['password'],args['log']['path']) if os.path.isfile(args['password']) else args['password']
msg = None
if args['key'] is None:
tmp = AnsibleTools.AnsibleCredentials(args['inventory'],args['password'])
args['key'] = tmp['key_path'] if tmp is not None and 'key_path' in tmp.keys() else None
if msg is not None:
FileTools.WriteLog(msg,args['log']['path']) if args['log']['path'] is not None else print(msg)
raise argparse.ArgumentError(None,msg)
return args
except argparse.ArgumentError as e:
parser.error(str(e))
# Function to extract suspicious addresses
def ExtractSuspectAddresses(log_path,patterns):
rc = FileTools.CheckFileAccess(log_path,Config['Host']['log'])
FileTools.WriteLog(f"Checking Access to {log_path} returned {rc}",Config['Host']['log'])
if rc == 0:
lines = FileTools.ReadTextFile(log_path)
elif rc == 2:
cmd = ["cat",log_path]
rc = NetTools.Sudo_Run(cmd,Config['Host']['password'])
lines = rc['out'].split() if 'out' in rc.keys() and rc['code'] == 0 else []
ips = set()
FileTools.WriteLog(f"Reading {log_path} returned {len(lines)} lines to be processed",Config['Host']['log'])
for line in lines:
for pattern in patterns:
if re.search(pattern, line, re.IGNORECASE):
print(f"{pattern}: {line}")
match = re.search(r'client ([\d\.]+)', line)
if match:
ips.add(match.group(1))
return ips
def extract_suspicious_ips(log_path, patterns):
if not log_path.exists():
raise FileNotFoundError(f"Log file not found: {log_path}")
with log_path.open("r") as f:
lines = f.readlines()
ips = set()
for line in lines:
for pattern in patterns:
if re.search(pattern, line, re.IGNORECASE):
match = re.search(r'client ([\d\.]+)', line)
if match:
ips.add(match.group(1))
return ips
"""
def is_ip_blocked(ip, password):
output = sudo_run(["firewall-cmd", "--list-rich-rules"], password)
return ip in output
def block_ip(ip, password):
if is_ip_blocked(ip, password):
print(f"🔒 Already blocked: {ip}")
return
cmd = BLOCK_CMD_TEMPLATE.copy()
cmd[3] = cmd[3].format(ip)
sudo_run(cmd, password)
print(f"🚫 Blocked IP: {ip}")
def main():
password = get_sudo_password()
bad_ips = extract_suspicious_ips(LOG_PATH, SUSPICIOUS_PATTERNS)
for ip in bad_ips:
block_ip(ip, password)
if bad_ips:
sudo_run(RELOAD_CMD, password)
"""
# Function to Find the local Common folder and append it to the library path (Common)
def InitializeModules():
ScriptPath = pathlib.Path(__file__).parent.resolve()
LibPath = f"{ScriptPath}/Lib"
if not CheckSysPath(LibPath): sys.path.append(LibPath)
# Main Function
def main():
Config['Args'] = GetArguments()
FileTools.ArchiveLog(Config['Args']['log'])
logging.basicConfig(filename=Config['Args']['log']['path'],filemode='a',level=logging.WARNING)
Config['Host'] = ConfigureHosts(Config['Args'])
print(Config)
bad_ips = ExtractSuspectAddresses(LOG_PATH,SUSPICIOUS_PATTERNS)
#args = {'log_path':LOG_PATH,'pattern':SUSPICIOUS_PATTERNS,'log':Config['Args']['log']['path'],'password':Config['Host']['password']}
#bad_ips = NetTools.GetSuspicousAddresses(**args)
print(bad_ips)
sys.exit(0)
for ip in bad_ips:
block_ip(ip)
if bad_ips:
reload_firewalld()
# Preload with User Libraries -> Common to all scripts
InitializeModules()
import FileTools,NetTools,Tools,DbTools,AnsibleTools
from MyParser import MyParser
# Execute Script
if __name__ =="__main__":
main()