-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauthlog-threats.py
287 lines (242 loc) · 12.8 KB
/
authlog-threats.py
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/local/bin/python3
""" Get attacking IP addresses from authlog
and add them to pf mapped file for uptake for
OpenBSD 7.3, Python 3.10.10
Copyright (C) Quadhelion Engineering
* All Rights Reserved
* Propreitary and Confidential
Unauthorized sharing of this proprietary Software script via any
medium is strictly prohibited. No Warranty or Liability provided.
QHE License Permissions (QHELP-OME-NC-ND-HI)
Grant only to Obtain, Modify, Execute (OME):
* Obtain from https://bitbucket.org/quadhelion-engineering/authlog-threats/
* Execute this script on Non-Commercial Systems via Human Implementation
"""
__author__ = "Elias Christopher Griffin"
__copyright__ = "Copyright 2023, Quadhelion Engineering"
__url__ = "https://www.quadhelion.engineering/qhelp.html"
__license__ = "QHELP-OME-NC-ND-HI"
__version__ = "1.0"
__date__ = "08/28/2023"
__email__ = "[email protected]"
__status__ = "Production"
from pathlib import Path
from datetime import datetime, date
import os, re, time, sys, subprocess, syslog, configparser, ipaddress
if __name__ == "__main__":
config = configparser.ConfigParser()
config.read('settings.ini')
whitelist = Path(config['USER']['whitelist'])
authlog = Path(config['USER']['authlog'])
threats_list = Path(config['USER']['threats_list'])
threats_added = Path(config['USER']['threats_log'])
## script arguments
# test, pf, or backup
## Mode "test"
# Print to stdout without writing to /etc/threats
# authlog_threats.py test
## Mode "pf"
# Add new threats to file and reload pf with them
# authlog_threats.py pf
pf_reload_rules_cmd = "pfctl -t " + threats_list.name + " -T replace -f " + str(threats_list)
pf_stats_cmd = "pfctl -vsi"
## Mode "backup"
# Nothing but backup copies of whitelist, threatlist, and authlog
## Script arguments
sysarg = sys.argv
if "test" in sysarg:
pf_mode, test_mode, backup_mode = False, True, False
print(f"\n*********************\033[38;5;75m Test Mode \033[0;0m***********************")
print(f"\033[38;5;208m No writes \033[0;0m")
print(f"*******************************************************\n")
elif "pf" in sysarg:
pf_mode, test_mode, backup_mode = True, False, False
print(f"\n********************\033[38;5;75m pf Mode \033[0;0m*************************")
print(f"\033[38;5;208m {pf_reload_rules_cmd} \033[0;0m")
print(f"*******************************************************\n")
elif "backup" in sysarg:
test_mode, backup_mode = False, True
print(f"\n********************\033[38;5;75m Backup Mode \033[0;0m**********************")
print(f"Backing up whitelist, threatlist, and authlog")
print(f"*******************************************************\n")
else:
pf_mode, test_mode, backup_mode = False, False, False
print(f"\n********************\033[38;5;75m Base Mode \033[0;0m************************")
print(f"Available modes \033[38;5;208mtest\033[0;0m or \033[38;5;208mbackup\033[0;0m or \033[38;5;208mpf\033[0;0m")
print(f"*******************************************************\n")
## Backup mode ## copies whitelist, threatlist, and authlog
if backup_mode:
backup_date = date.today()
backup_suffix = ".backup" + "-" + backup_date.strftime("%B") + "-" + backup_date.strftime("%d")
whitelist_backup = whitelist.with_suffix(backup_suffix)
threatslist_backup = threats_list.with_suffix(backup_suffix)
authlog_backup = authlog.with_suffix(backup_suffix)
try:
whitelist_backup.write_bytes(whitelist.read_bytes())
threatslist_backup.write_bytes(threats_list.read_bytes())
authlog_backup.write_bytes(authlog.read_bytes())
except FileNotFoundError as e:
error_path = Path(e.filename)
print(f"\n******************\033[38;5;1m File Not Found \033[0;0m*********************")
print(f"Filename: {error_path.name}")
print(f"Directories used: {error_path.parts}\n")
print("*******************************************************\n")
except PermissionError as e:
print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
print(f"Insufficient permissions {e}")
print(f"{os.stat(threats_added)}{os.linesep}")
print(f"*******************************************************\n")
except OSError as e:
print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
print(f"{e}")
print(f"*******************************************************\n")
else:
syslog.syslog(syslog.LOG_INFO, "Backups Complete")
print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
print(f"Backups created:\n")
print(f"{whitelist_backup}")
print(f"{threatslist_backup}")
print(f"{authlog_backup}")
print(f"*******************************************************\n")
syslog.closelog()
sys.exit()
## Check for directory to write script logs to
script_log_directory = threats_added.parent
if not script_log_directory.exists():
print(f"\n****************\033[38;5;1m No directory exists \033[0;0m******************")
print(f"At {threats_added.parent} to create log")
print(f"*******************************************************\n")
sys.exit()
else:
print(f"\n*******************************************************")
print(f"Log directory: \033[38;5;75m{script_log_directory}\033[0;0m ")
print(f"*******************************************************\n")
## Allow user to see log directory as the
## IP Address list to stdout will send this output off-screen
time.sleep(0.7)
## Handle system files
try:
whitelist_content = whitelist.read_text(encoding="utf-8")
authlog_content = authlog.read_text(encoding="utf-8")
threat = open(threats_list, "a")
threat_content = threats_list.read_text(encoding="utf-8")
threats_added.touch()
except FileNotFoundError as e:
error_path = Path(e.filename)
print(f"\n*******************\033[38;5;1m File Not Found \033[0;0m********************")
print(f"Filename: {error_path.name}")
print(f"Directories used: {error_path.parts}\n")
print("*******************************************************\n")
except PermissionError as e:
print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
print(f"Permission to read/append {e}")
print(f"{os.stat(authlog)}{os.linesep}")
print(f"{os.stat(threats_list)}{os.linesep}")
print(f"{os.stat(threats_added)}{os.linesep}")
print(f"*******************************************************\n")
else:
print(
f"{os.linesep}*********************\033[38;5;75m Running \033[0;0m*************************{os.linesep}"
f"{Path.cwd()}/authlog-threats.py{os.linesep}"
f"*******************************************************{os.linesep}"
)
finally:
print(f"\n*******************\033[38;5;75m Files Mapped \033[0;0m*********************")
print(f"Loaded system files for read/append\n")
print(f"{authlog}")
print(f"{threats_list}")
print(f"*******************************************************\n")
## Allow user to see script status as the
## IP Address list to stdout will send this output off-screen
time.sleep(0.7)
## Expand CIDR IP Addresses in whitelist to check against
whitelist_expanded = []
whitelist_networks = whitelist_content.splitlines()
for line in whitelist_networks:
network_expanded = ipaddress.ip_network(line.rstrip('\t\n ')).hosts()
for ip in network_expanded:
ipv4_string = str(ip)
whitelist_expanded.append(ipv4_string)
## Initialize loop elements
## Blackhole IP address 198.51.100.0/24 https://datatracker.ietf.org/doc/html/rfc5737
ip_set = []
ip_pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
# Loop through each line, collecting IP Addresses not already present
for line in authlog_content.splitlines():
logline = re.search(ip_pattern, line)
if logline is not None:
if (logline.group(0) not in threat_content) and (logline.group(0) not in whitelist_expanded) and (logline.group(0) != "0.0.0.0"): # nosec
if test_mode:
ip_set.append(logline.group())
else:
ip_set.append(logline.group())
threat.writelines(logline.group() + "\n")
else:
continue
else:
continue
## Remove duplicates, count new additions, format single column list
ip_set = [*set(ip_set)]
threat_count = len(ip_set)
ip_string = "\n".join([str(elem) for elem in ip_set])
## Count out threats in existing file during test
if test_mode:
try:
threat_count_reader = open(threats_list, "r")
threat_count_original = len(threat_count_reader.readlines())
except OSError as e:
print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
print(f"{e}")
print(f"*******************************************************\n")
else:
print(f"\n*********************\033[38;5;75m Catalog \033[0;0m*************************")
print(f"\033[38;5;208m{threat_count_original}\033[0;0m existing threats counted")
print(f"*******************************************************\n")
## Create log file of discovered IP addresses in separate timestamped file
try:
timestamp = datetime.now().isoformat()
threats_timestamp = threats_added.name + "-" + timestamp
threats_added_timestamped = threats_added.with_name(threats_timestamp)
threats_added.replace(threats_added_timestamped)
threats_added_timestamped.write_text(ip_string)
## Reload packet filter rules with new threats if command given
if pf_mode:
pf_reloaded = subprocess.run([pf_reload_rules_cmd], shell=True, timeout=1.7)
except subprocess.CalledProcessError as e:
syslog.syslog(syslog.LOG_ERR, "Failure: pf not reloaded")
print(f"\n*********************\033[38;5;1m Shell Error \033[0;0m*********************")
print(f"Command {e.args[1]} failed")
print("*******************************************************\n")
except FileNotFoundError as e:
error_path = Path(e.filename)
print(f"\n******************\033[38;5;1m File Not Found \033[0;0m*********************")
print(f"Filename: {error_path.name}")
print(f"Directories used: {error_path.parts}\n")
print("*******************************************************\n")
except PermissionError as e:
print(f"\n******************\033[38;5;1m Permissions \033[0;0m************************\n")
print(f"Insufficient permissions {e}")
print(f"{os.stat(threats_added)}{os.linesep}")
print(f"*******************************************************\n")
except OSError as e:
print(f"\n********************\033[38;5;1m Locked \033[0;0m**************************\n")
print(f"Perhaps file is busy, locked, process blocked, or raced:\n")
print(f"{e}")
print(f"*******************************************************\n")
else:
if not test_mode:
syslog.syslog(syslog.LOG_INFO, "Success")
print(f"\n*********************\033[38;5;76m Success \033[0;0m*************************")
print(f"\033[38;5;208mThreats:\033[0;0m{os.linesep}{os.linesep.join(map(str, ip_set))}\n\n")
print(f"{threat_count} new threats added")
print(f"Log at {threats_added_timestamped.name}")
print(f"*******************************************************\n")
print(f"*******************************************************\n")
if pf_mode and pf_reloaded.returncode == 0:
syslog.syslog(syslog.LOG_INFO, "Success: pf reloaded")
print(f"\n*******************\033[38;5;75m pf reloaded \033[0;0m*********************")
print(f"{subprocess.run([pf_stats_cmd], shell=True, timeout=1.7)}")
print(f"*******************************************************\n")
print(f"*******************************************************\n")