-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsecurebot.py
More file actions
2262 lines (1861 loc) · 85.1 KB
/
securebot.py
File metadata and controls
2262 lines (1861 loc) · 85.1 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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SecureBot - Telegram Security Bot
A Telegram bot for monitoring SSH logins and managing fail2ban
"""
import os
import sys
import argparse
import logging
import signal
import time
import re
import socket
import json
import asyncio
import datetime
import subprocess
from pathlib import Path
from typing import Dict, List, Optional, Any, Union, Tuple, Set
import tomli
import tomli_w
import telegram
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application,
CommandHandler,
CallbackQueryHandler,
ContextTypes,
CallbackContext,
MessageHandler,
filters
)
import paramiko
import pyinotify
__version__ = "1.0.1"
# Set up logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
level=logging.INFO
)
logger = logging.getLogger(__name__)
# Default configuration
DEFAULT_CONFIG = {
"general": {
"local_only": False,
"log_level": "INFO",
"notification_delay": 10
},
"telegram": {
"bot_token": "YOUR_BOT_TOKEN",
"chat_id": "YOUR_CHAT_ID",
"admin_users": [],
"viewer_users": []
},
"permanent_bans": {
},
"local": {
"ssh_log": "/var/log/auth.log",
"fail2ban_log": "/var/log/fail2ban.log",
"audit_log": "/var/log/audit/audit.log"
},
"servers": {
"example_server": {
"hostname": "server.example.com",
"ip": "192.168.1.10",
"ssh_user": "monitor",
"ssh_key_path": "/etc/securebot/keys/server_key",
"ssh_port": 22,
"host_key_path": "/etc/securebot/known_hosts/server",
"logs": {
"ssh": "/var/log/auth.log",
"fail2ban": "/var/log/fail2ban.log"
}
}
},
"notifications": {
"ssh_login": True,
"fail2ban_block": True,
"server_unreachable": True
},
"customization": {
"date_format": "%Y-%m-%d %H:%M:%S",
"resolve_hostnames": True,
"show_ipinfo_link": True
}
}
# Global variables
CONFIG = {}
BOT_INSTANCE = None
NOTIFICATION_MUTED = False
MUTE_UNTIL = 0
SSH_CLIENTS = {}
WATCH_MANAGERS = {}
NOTIFIERS = {}
KNOWN_EVENTS = set()
RUNNING = True
class NetworkUtils:
"""Network-related utility functions"""
@staticmethod
async def get_ip_info(ip: str) -> Dict[str, Any]:
"""Get detailed information about an IP address using ipinfo.io"""
url = f"https://ipinfo.io/{ip}/json"
try:
# Verwende httpx, da es bereits für Telegram verwendet wird
import httpx
async with httpx.AsyncClient() as client:
response = await client.get(url, timeout=5.0)
if response.status_code == 200:
data = response.json()
# Erweitere mit Emoji-Flagge, wenn Land verfügbar
if "country" in data:
country_code = data["country"]
# Konvertiere Ländercode zu Emoji-Flagge (Unicode-Trick)
flag = "".join(chr(ord(c) + 127397) for c in country_code)
data["flag"] = flag
return data
else:
logger.warning(f"Failed to get IP info for {ip}: Status code {response.status_code}")
return {}
except Exception as e:
logger.error(f"Error getting IP info: {e}")
return {}
class DateUtils:
"""Date and time utility functions"""
@staticmethod
def format_timestamp(timestamp: str) -> str:
"""Format a timestamp according to configuration"""
try:
# check if timestamp is in the format YYYY-MM-DD HH:MM:SS,sss
if ',' in timestamp: # 2025-05-18 17:36:28,767
dt_format = "%Y-%m-%d %H:%M:%S,%f"
if timestamp.split(',')[1] and len(timestamp.split(',')[1]) > 3:
timestamp = timestamp.split(',')[0] + ',' + timestamp.split(',')[1][:3]
else: # May 18 17:36:28
dt_format = "%b %d %H:%M:%S"
# convert to datetime object
dt = datetime.datetime.strptime(timestamp, dt_format)
# uee custom date format from config
custom_format = CONFIG.get("customization", {}).get("date_format", "%d. %B %Y, %H:%M:%S")
return dt.strftime(custom_format)
except Exception as e:
logger.warning(f"Failed to format timestamp {timestamp}: {e}")
return timestamp # return original timestamp if formatting fails
class ConfigManager:
"""Handle configuration loading, saving and validation"""
@staticmethod
def load_config(config_path: str) -> dict:
"""Load configuration from a TOML file"""
try:
with open(config_path, "rb") as f:
config = tomli.load(f)
logger.info(f"Configuration loaded from {config_path}")
return config
except FileNotFoundError:
logger.warning(f"Configuration file {config_path} not found")
return {}
except tomli.TOMLDecodeError as e:
logger.error(f"Error parsing configuration file: {e}")
return {}
@staticmethod
def save_config(config: dict, config_path: str) -> bool:
"""Save configuration to a TOML file"""
try:
# Ensure the directory exists
os.makedirs(os.path.dirname(config_path), exist_ok=True)
with open(config_path, "wb") as f:
tomli_w.dump(config, f)
logger.info(f"Configuration saved to {config_path}")
# Set proper permissions for the config file
if config_path.startswith('/etc/'):
subprocess.run(['sudo', 'chmod', '640', config_path], check=True)
subprocess.run(['sudo', 'chown', 'root:securebot', config_path], check=True)
else:
os.chmod(config_path, 0o600) # Only user can read/write
return True
except Exception as e:
logger.error(f"Error saving configuration file: {e}")
return False
@staticmethod
def validate_config(config: dict) -> Tuple[bool, List[str]]:
"""Validate configuration structure and essential values"""
errors = []
# Check for required top-level sections
required_sections = ["general", "telegram", "local"]
for section in required_sections:
if section not in config:
errors.append(f"Missing required section: {section}")
# Validate telegram section
if "telegram" in config:
if not config["telegram"].get("bot_token") or config["telegram"]["bot_token"] == "YOUR_BOT_TOKEN":
errors.append("Telegram bot token is not configured")
if not config["telegram"].get("chat_id") or config["telegram"]["chat_id"] == "YOUR_CHAT_ID":
errors.append("Telegram chat ID is not configured")
# Validate servers section if not local_only
if "general" in config and not config["general"].get("local_only", False):
if "servers" not in config or not config["servers"]:
errors.append("No servers defined while local_only is False")
else:
for server_name, server_config in config["servers"].items():
required_server_keys = ["hostname", "ssh_user", "ssh_key_path"]
for key in required_server_keys:
if key not in server_config:
errors.append(f"Missing required key {key} for server {server_name}")
return len(errors) == 0, errors
@staticmethod
def generate_config() -> dict:
"""Generate a default configuration"""
return DEFAULT_CONFIG.copy()
class SSHManager:
"""Manage SSH connections to remote servers"""
@staticmethod
async def connect_to_server(server_name: str, server_config: dict) -> Optional[paramiko.SSHClient]:
"""Establish SSH connection to a remote server"""
try:
client = paramiko.SSHClient()
# Set up host key policy
if os.path.exists(server_config["host_key_path"]):
client.load_host_keys(server_config["host_key_path"])
else:
# If no host keys found, use system known_hosts or auto-add
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the server
client.connect(
hostname=server_config["hostname"],
port=server_config.get("ssh_port", 22),
username=server_config["ssh_user"],
key_filename=server_config["ssh_key_path"],
timeout=10
)
logger.info(f"Successfully connected to {server_name}")
return client
except paramiko.AuthenticationException:
logger.error(f"Authentication failed for {server_name}")
except paramiko.SSHException as e:
logger.error(f"SSH error for {server_name}: {e}")
except socket.timeout:
logger.error(f"Connection timeout for {server_name}")
except Exception as e:
logger.error(f"Error connecting to {server_name}: {e}")
# Notify about connection failure if configured
if CONFIG["notifications"].get("server_unreachable", True):
await notify_telegram(f"⚠️ Could not connect to server {server_name}")
return None
@staticmethod
async def execute_command(
server_name: str,
command: str,
client: Optional[paramiko.SSHClient] = None
) -> Tuple[bool, str]:
"""Execute command on remote server"""
close_after = False
try:
# Wenn server_name 'localhost' oder None ist, führe lokal aus
if server_name is None or server_name == "localhost":
try:
result = subprocess.check_output(
command,
shell=True,
text=True,
stderr=subprocess.PIPE
).strip()
return True, result
except subprocess.CalledProcessError as e:
error_msg = e.stderr.strip() if hasattr(e, 'stderr') and e.stderr else str(e)
logger.error(f"Error executing local command: {error_msg}")
return False, error_msg
# Für entfernte Server
if client is None:
if server_name not in CONFIG["servers"]:
return False, f"Unknown server: {server_name}"
client = await SSHManager.connect_to_server(
server_name,
CONFIG["servers"][server_name]
)
close_after = True
if client is None:
return False, f"Could not connect to {server_name}"
# Execute the command
stdin, stdout, stderr = client.exec_command(command)
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
result = stdout.read().decode('utf-8').strip()
return True, result
else:
error = stderr.read().decode('utf-8').strip()
logger.error(f"Command failed on {server_name}: {error}")
return False, error
except Exception as e:
logger.error(f"Error executing command on {server_name}: {e}")
return False, str(e)
finally:
if close_after and client:
client.close()
@staticmethod
async def get_file_content(
server_name: str,
file_path: str,
client: Optional[paramiko.SSHClient] = None
) -> Tuple[bool, str]:
"""Get content of a file from remote server"""
close_after = False
try:
# If no client provided, establish a new connection
if client is None:
if server_name not in CONFIG["servers"]:
return False, f"Unknown server: {server_name}"
client = await SSHManager.connect_to_server(
server_name,
CONFIG["servers"][server_name]
)
close_after = True
if client is None:
return False, f"Could not connect to {server_name}"
# Get the file content
sftp = client.open_sftp()
with sftp.open(file_path, 'r') as f:
content = f.read().decode('utf-8')
return True, content
except Exception as e:
logger.error(f"Error getting file content from {server_name}: {e}")
return False, str(e)
finally:
if close_after and client:
client.close()
@staticmethod
async def tail_file(
server_name: str,
file_path: str,
lines: int = 10,
client: Optional[paramiko.SSHClient] = None
) -> Tuple[bool, str]:
"""Get the last n lines of a file from remote server"""
return await SSHManager.execute_command(
server_name,
f"tail -n {lines} {file_path}",
client
)
class Fail2BanManager:
"""Manage fail2ban operations"""
@staticmethod
async def ban_ip_permanently(ip: str, reason: str = "Manual permanent ban", user_id: int = None) -> Tuple[bool, str]:
"""Ban an IP permanently across all servers and jails"""
logger.info(f"Banning IP {ip} permanently")
# Speichere in Konfiguration
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if "permanent_bans" not in CONFIG:
CONFIG["permanent_bans"] = {}
CONFIG["permanent_bans"][ip] = {
"timestamp": timestamp,
"reason": reason,
"banned_by": user_id
}
# Konfiguration speichern
config_path = os.environ.get("SECUREBOT_CONFIG", "/etc/securebot.conf")
ConfigManager.save_config(CONFIG, config_path)
# IP in allen lokalen Jails sperren
success = True
error_messages = []
# 1. Lokale Jails
local_success, jails = await Fail2BanManager.list_jails()
if local_success and jails:
for jail in jails:
ban_success, result = await Fail2BanManager.ban_ip(ip, jail)
if not ban_success:
success = False
error_messages.append(f"Failed to ban in local jail {jail}: {result}")
# 2. Remote Server Jails
if not CONFIG["general"].get("local_only", False) and "servers" in CONFIG:
for server_name, server_config in CONFIG["servers"].items():
server_success, server_jails = await Fail2BanManager.list_jails(server_name)
if server_success and server_jails:
for jail in server_jails:
ban_success, result = await Fail2BanManager.ban_ip(ip, jail, server_name)
if not ban_success:
success = False
error_messages.append(f"Failed to ban in {server_name} jail {jail}: {result}")
# Optional: Zusätzlich iptables-Regel für noch robustere Sperrung hinzufügen
try:
command = f"sudo iptables -A INPUT -s {ip} -j DROP"
subprocess.check_output(command, shell=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
logger.warning(f"Could not add iptables rule for {ip}: {e}")
if success:
return True, f"Successfully banned {ip} permanently across all servers and jails"
else:
return False, f"Partial permanent ban for {ip}. Errors: {', '.join(error_messages)}"
@staticmethod
async def list_permanent_bans() -> Dict[str, Dict[str, Any]]:
"""List all permanent bans"""
return CONFIG.get("permanent_bans", {})
@staticmethod
async def remove_permanent_ban(ip: str) -> Tuple[bool, str]:
"""Remove a permanent ban"""
if "permanent_bans" not in CONFIG or ip not in CONFIG["permanent_bans"]:
return False, f"IP {ip} is not permanently banned"
# Aus Konfiguration entfernen
del CONFIG["permanent_bans"][ip]
# Konfiguration speichern
config_path = os.environ.get("SECUREBOT_CONFIG", "/etc/securebot.conf")
ConfigManager.save_config(CONFIG, config_path)
# Optional: iptables-Regel entfernen
try:
command = f"sudo iptables -D INPUT -s {ip} -j DROP"
subprocess.check_output(command, shell=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError:
pass
return True, f"Removed permanent ban for {ip}"
@staticmethod
async def ensure_permanent_bans() -> Tuple[bool, str]:
"""Ensure all permanent bans are active across all systems"""
logger.info("Verifying permanent bans are active")
if "permanent_bans" not in CONFIG or not CONFIG["permanent_bans"]:
logger.info("No permanent bans configured")
return True, "No permanent bans configured"
success = True
errors = []
# Re-apply all permanent bans
for ip, ban_data in CONFIG["permanent_bans"].items():
logger.info(f"Ensuring IP {ip} is banned (reason: {ban_data.get('reason', 'Permanent ban')})")
# 1. Lokale Jails
local_success, jails = await Fail2BanManager.list_jails()
if local_success and jails:
for jail in jails:
ban_success, result = await Fail2BanManager.ban_ip(ip, jail)
if not ban_success:
success = False
errors.append(f"Failed to ban in local jail {jail}: {result}")
# 2. Remote Server Jails
if not CONFIG["general"].get("local_only", False) and "servers" in CONFIG:
for server_name, server_config in CONFIG["servers"].items():
server_success, server_jails = await Fail2BanManager.list_jails(server_name)
if server_success and server_jails:
for jail in server_jails:
ban_success, result = await Fail2BanManager.ban_ip(ip, jail, server_name)
if not ban_success:
success = False
errors.append(f"Failed to ban in {server_name} jail {jail}: {result}")
# 3. Optional: iptables-Regel hinzufügen
try:
command = f"sudo iptables -A INPUT -s {ip} -j DROP"
subprocess.check_output(command, shell=True, stderr=subprocess.PIPE)
except subprocess.CalledProcessError as e:
logger.warning(f"Could not add iptables rule for {ip}: {e}")
if success:
return True, "Successfully verified all permanent bans"
else:
return False, f"Errors while verifying permanent bans: {', '.join(errors)}"
# command /fail2ban all
@staticmethod
async def get_all_banned_ips(server_name: Optional[str] = None) -> Dict[str, List[str]]:
"""Get all banned IPs from all jails"""
success, jails = await Fail2BanManager.list_jails(server_name)
if not success or not jails:
return {}
results = {}
for jail in jails:
success, ips = await Fail2BanManager.get_banned_ips(jail, server_name)
if success and ips:
results[jail] = ips
return results
# command /fail2ban list
@staticmethod
async def list_jails(server_name: Optional[str] = None) -> Tuple[bool, List[str]]:
"""List all fail2ban jails"""
command = "sudo fail2ban-client status | grep 'Jail list' | sed -E 's/^[^:]+:[ \t]+//g'"
if server_name:
success, result = await SSHManager.execute_command(server_name, command)
else:
# Execute locally
try:
result = subprocess.check_output(
command,
shell=True,
text=True
).strip()
success = True
except subprocess.CalledProcessError as e:
logger.error(f"Error listing fail2ban jails: {e}")
success = False
result = str(e)
if not success:
return False, []
# Parse the comma-separated list of jails
jails = [jail.strip() for jail in result.split(",")]
return True, jails
# command /fail2ban status JAIL
@staticmethod
async def get_banned_ips(jail: str, server_name: Optional[str] = None) -> Tuple[bool, List[str]]:
"""Get list of IPs banned in a specific jail"""
command = f"sudo fail2ban-client status {jail} | grep 'Banned IP list' | sed -E 's/^[^:]+:[ \t]+//g'"
if server_name:
success, result = await SSHManager.execute_command(server_name, command)
else:
# Execute locally
try:
result = subprocess.check_output(
command,
shell=True,
text=True
).strip()
success = True
except subprocess.CalledProcessError as e:
logger.error(f"Error getting banned IPs for jail {jail}: {e}")
success = False
result = str(e)
if not success:
return False, []
# Parse the space-separated list of IPs
if not result:
return True, []
ips = [ip.strip() for ip in result.split()]
return True, ips
# command /fail2ban banip IP JAIL
@staticmethod
async def ban_ip(ip: str, jail: str, server_name: Optional[str] = None) -> Tuple[bool, str]:
"""Ban an IP in a specific jail"""
command = f"sudo fail2ban-client set {jail} banip {ip}"
if server_name:
return await SSHManager.execute_command(server_name, command)
else:
# Execute locally
try:
subprocess.check_output(command, shell=True, text=True)
return True, f"Successfully banned {ip} in {jail}"
except subprocess.CalledProcessError as e:
logger.error(f"Error banning IP {ip} in jail {jail}: {e}")
return False, str(e)
# command /fail2ban unbanip IP JAIL
@staticmethod
async def unban_ip(ip: str, jail: str, server_name: Optional[str] = None) -> Tuple[bool, str]:
"""Unban an IP from a specific jail"""
command = f"sudo fail2ban-client set {jail} unbanip {ip}"
logger.debug(f"Executing command: {command}")
if server_name:
return await SSHManager.execute_command(server_name, command)
else:
# Execute locally (direkt ausführen, nicht über SSH-Manager)
try:
output = subprocess.check_output(command, shell=True, text=True, stderr=subprocess.PIPE)
logger.info(f"Successfully unbanned {ip} from {jail}")
return True, f"Successfully unbanned {ip} from {jail}"
except subprocess.CalledProcessError as e:
error_msg = e.stderr.strip() if e.stderr else str(e)
logger.error(f"Error unbanning IP {ip} from jail {jail}: {error_msg}")
return False, error_msg
class LogParser:
"""Parse various log formats"""
# SSH Login Pattern
SSH_LOGIN_PATTERN = re.compile(
r'(\w{3}\s+\d+\s+\d+:\d+:\d+).*sshd\[\d+\]:\s+Accepted\s+(?:publickey|password|keyboard-interactive/pam)\s+for\s+(\S+)\s+from\s+(\S+)'
)
# fail2ban Patterns old and new
FAIL2BAN_BAN_PATTERN_OLD = re.compile(
r'(\w{3}\s+\d+\s+\d+:\d+:\d+).*fail2ban\.actions\[\d+\]:\s+NOTICE\s+\[([^\]]+)\]\s+Ban\s+(\S+)'
)
FAIL2BAN_BAN_PATTERN_NEW = re.compile(
r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d+)\s+fail2ban\.actions\s+\[\d+\]:\s+NOTICE\s+\[([^\]]+)\]\s+Ban\s+(\S+)'
)
# Unban Patterns old and new
FAIL2BAN_UNBAN_PATTERN_OLD = re.compile(
r'(\w{3}\s+\d+\s+\d+:\d+:\d+).*fail2ban\.actions\[\d+\]:\s+NOTICE\s+\[([^\]]+)\]\s+Unban\s+(\S+)'
)
FAIL2BAN_UNBAN_PATTERN_NEW = re.compile(
r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d+)\s+fail2ban\.actions\s+\[\d+\]:\s+NOTICE\s+\[([^\]]+)\]\s+Unban\s+(\S+)'
)
# Already Banned Patterns old and new
FAIL2BAN_ALREADY_BANNED_PATTERN_OLD = re.compile(
r'(\w{3}\s+\d+\s+\d+:\d+:\d+).*fail2ban\.actions\[\d+\]:\s+(?:NOTICE|WARNING)\s+\[([^\]]+)\]\s+(\S+)\s+already\s+banned'
)
FAIL2BAN_ALREADY_BANNED_PATTERN_NEW = re.compile(
r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d+)\s+fail2ban\.actions\s+\[\d+\]:\s+(?:NOTICE|WARNING)\s+\[([^\]]+)\]\s+(\S+)\s+already\s+banned'
)
# Found IP Patterns old and new
FAIL2BAN_FOUND_IP_PATTERN_OLD = re.compile(
r'(\w{3}\s+\d+\s+\d+:\d+:\d+).*fail2ban\.filter\[\d+\]:\s+INFO\s+\[([^\]]+)\]\s+Found\s+(\S+)\s+-\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}'
)
FAIL2BAN_FOUND_IP_PATTERN_NEW = re.compile(
r'(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d+)\s+fail2ban\.filter\s+\[\d+\]:\s+INFO\s+\[([^\]]+)\]\s+Found\s+(\S+)\s+-\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}'
)
@staticmethod
async def parse_ssh_log_line(line: str, server_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""Parse SSH log line for successful logins"""
match = LogParser.SSH_LOGIN_PATTERN.match(line)
if not match:
return None
timestamp, username, ip = match.groups()
# Create a unique event ID to prevent duplicate notifications
event_id = f"ssh_login_{server_name}_{ip}_{username}_{timestamp}"
if event_id in KNOWN_EVENTS:
return None
KNOWN_EVENTS.add(event_id)
# Resolve hostname if configured
hostname = None
if CONFIG["customization"].get("resolve_hostnames", True):
try:
hostname = socket.gethostbyaddr(ip)[0]
except (socket.herror, socket.gaierror):
hostname = None
event = {
"type": "ssh_login",
"timestamp": timestamp,
"username": username,
"ip": ip,
"hostname": hostname,
"server": server_name or "localhost"
}
return event
@staticmethod
async def parse_fail2ban_log_line(line: str, server_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
"""Parse fail2ban log line for ban/unban events"""
ban_match_old = LogParser.FAIL2BAN_BAN_PATTERN_OLD.match(line)
ban_match_new = LogParser.FAIL2BAN_BAN_PATTERN_NEW.match(line)
unban_match_old = LogParser.FAIL2BAN_UNBAN_PATTERN_OLD.match(line)
unban_match_new = LogParser.FAIL2BAN_UNBAN_PATTERN_NEW.match(line)
already_banned_old = LogParser.FAIL2BAN_ALREADY_BANNED_PATTERN_OLD.match(line)
already_banned_new = LogParser.FAIL2BAN_ALREADY_BANNED_PATTERN_NEW.match(line)
found_ip_old = LogParser.FAIL2BAN_FOUND_IP_PATTERN_OLD.match(line)
found_ip_new = LogParser.FAIL2BAN_FOUND_IP_PATTERN_NEW.match(line)
if ban_match_old:
timestamp, jail, ip = ban_match_old.groups()
event_type = "ban"
elif ban_match_new:
timestamp, jail, ip = ban_match_new.groups()
event_type = "ban"
elif unban_match_old:
timestamp, jail, ip = unban_match_old.groups()
event_type = "unban"
elif unban_match_new:
timestamp, jail, ip = unban_match_new.groups()
event_type = "unban"
elif already_banned_old:
timestamp, jail, ip = already_banned_old.groups()
event_type = "already_banned"
elif already_banned_new:
timestamp, jail, ip = already_banned_new.groups()
event_type = "already_banned"
elif found_ip_old:
timestamp, jail, ip = found_ip_old.groups()
event_type = "found"
elif found_ip_new:
timestamp, jail, ip = found_ip_new.groups()
event_type = "found"
else:
logger.debug(f"No match for fail2ban log line: {line}")
return None
# Create a unique event ID to prevent duplicate notifications
event_id = f"fail2ban_{event_type}_{server_name}_{ip}_{jail}_{timestamp}"
if event_id in KNOWN_EVENTS:
logger.debug(f"Duplicate event skipped: {event_id}")
return None
KNOWN_EVENTS.add(event_id)
logger.debug(f"New event detected: {event_id}")
# Resolve hostname if configured
hostname = None
if CONFIG["customization"].get("resolve_hostnames", True):
try:
hostname = socket.gethostbyaddr(ip)[0]
except (socket.herror, socket.gaierror):
pass
event = {
"type": f"fail2ban_{event_type}",
"timestamp": timestamp,
"jail": jail,
"ip": ip,
"hostname": hostname,
"server": server_name or "localhost"
}
logger.debug(f"Created event: {event}")
return event
class FileWatcher:
"""Watch log files for changes"""
class EventHandler(pyinotify.ProcessEvent):
"""Handle file modification events"""
def __init__(self, file_path: str, callback, server_name: Optional[str] = None):
self.file_path = file_path
self.callback = callback
self.server_name = server_name
self.last_position = 0
# Initialize last_position to current file size
try:
self.last_position = os.path.getsize(file_path)
except OSError:
pass
def process_IN_MODIFY(self, event):
"""Handle file modification event"""
if event.pathname == self.file_path:
try:
with open(self.file_path, 'r') as f:
f.seek(self.last_position)
new_content = f.read()
self.last_position = f.tell()
# Process each new line
for line in new_content.splitlines():
if line.strip():
# Wir verwenden hier einen einfacheren Ansatz mit einem Thread-Pool
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(self.callback(line, self.server_name))
finally:
loop.close()
except Exception as e:
logger.error(f"Error processing file change: {e}")
@staticmethod
def start_watching(file_path: str, callback, server_name: Optional[str] = None) -> Optional[pyinotify.WatchManager]:
"""Start watching a file for changes"""
try:
wm = pyinotify.WatchManager()
handler = FileWatcher.EventHandler(file_path, callback, server_name)
notifier = pyinotify.ThreadedNotifier(wm, handler)
wm.add_watch(file_path, pyinotify.IN_MODIFY)
notifier.start()
# Store references to prevent garbage collection
if server_name not in WATCH_MANAGERS:
WATCH_MANAGERS[server_name] = []
NOTIFIERS[server_name] = []
WATCH_MANAGERS[server_name].append(wm)
NOTIFIERS[server_name].append(notifier)
logger.info(f"Started watching {file_path} on {server_name or 'localhost'}")
return wm
except Exception as e:
logger.error(f"Error setting up file watcher for {file_path}: {e}")
return None
@staticmethod
def stop_watching(server_name: Optional[str] = None):
"""Stop watching files"""
if server_name and server_name in NOTIFIERS:
for notifier in NOTIFIERS[server_name]:
try:
notifier.stop()
except:
pass
NOTIFIERS[server_name] = []
WATCH_MANAGERS[server_name] = []
logger.info(f"Stopped watching files on {server_name}")
elif server_name is None:
# Stop all notifiers
for server, notifiers in NOTIFIERS.items():
for notifier in notifiers:
try:
notifier.stop()
except:
pass
NOTIFIERS.clear()
WATCH_MANAGERS.clear()
logger.info("Stopped all file watchers")
async def setup_remote_watcher(server_name: str, server_config: dict):
"""Set up remote log monitoring via SSH"""
client = await SSHManager.connect_to_server(server_name, server_config)
if client is None:
return
SSH_CLIENTS[server_name] = client
# Start periodic log checking in the background
logs = server_config.get("logs", {})
if "ssh" in logs and logs["ssh"]:
asyncio.create_task(
periodic_check_log(
server_name,
logs["ssh"],
process_ssh_log_line,
interval=10
)
)
if "fail2ban" in logs and logs["fail2ban"]:
asyncio.create_task(
periodic_check_log(
server_name,
logs["fail2ban"],
process_fail2ban_log_line,
interval=10
)
)
async def periodic_check_log(server_name: str, log_path: str, process_func, interval: int = 10):
"""Periodically check a remote log file for new entries"""
last_size = 0
while RUNNING and server_name in SSH_CLIENTS:
try:
client = SSH_CLIENTS[server_name]
if not client or client.get_transport() is None or not client.get_transport().is_active():
# Reconnect if the connection is down
logger.info(f"Reconnecting to {server_name}...")
client = await SSHManager.connect_to_server(
server_name,
CONFIG["servers"][server_name]
)
if client is None:
await asyncio.sleep(interval)
continue
SSH_CLIENTS[server_name] = client
# Get file size
size_cmd = f"stat -c %s {log_path}"
success, size_str = await SSHManager.execute_command(server_name, size_cmd, client)
if not success:
await asyncio.sleep(interval)
continue
current_size = int(size_str.strip())
if current_size > last_size:
# File has grown, get new content
if last_size == 0:
# First run, just get the last few lines
success, content = await SSHManager.tail_file(server_name, log_path, 5, client)
else:
# Get only the new content
cmd = f"tail -c +{last_size + 1} {log_path}"
success, content = await SSHManager.execute_command(server_name, cmd, client)
if success:
# Process each new line
for line in content.splitlines():
if line.strip():
await process_func(line, server_name)
last_size = current_size
# Check for log rotation (file size decreased)
elif current_size < last_size:
# File was rotated, reset
last_size = 0
except Exception as e:
logger.error(f"Error checking log on {server_name}: {e}")
await asyncio.sleep(interval)
async def process_ssh_log_line(line: str, server_name: Optional[str] = None):
"""Process a new SSH log line"""
event = await LogParser.parse_ssh_log_line(line, server_name)
if event and CONFIG["notifications"].get("ssh_login", True):
# Check if notifications are muted
if NOTIFICATION_MUTED and time.time() < MUTE_UNTIL:
return
ip = event["ip"]
username = event["username"]
server = event["server"]
hostname = event["hostname"] or ip
message = (
f"🔐 SSH Login\n"
f"User: {username}\n"
f"From: {hostname} ({ip})\n"
f"Server: {server}\n"
f"Time: {event['timestamp']}"
)
# Add IPinfo link if configured
if CONFIG["customization"].get("show_ipinfo_link", True):
message += f"\nMore Info: https://ipinfo.io/{ip}"