不止于解题:用玄机靶场案例,打造你的自动化安全日志监控脚本
不止于解题用玄机靶场案例打造自动化安全日志监控脚本在网络安全领域日志分析往往是防御的第一道防线。当我们在玄机靶场中完成SSH爆破日志分析的解题后是否想过将这些手动操作转化为自动化工具本文将带你从单次解题跃升到持续防御构建一个能够实时监控auth.log、自动识别异常并采取行动的Python脚本。1. 日志监控的核心原理日志文件是系统活动的忠实记录者尤其是/var/log/auth.logDebian系或/var/log/secureRHEL系它们详细记录了所有认证相关事件。要实现自动化监控我们需要理解几个关键概念实时监控机制不同于一次性读取整个文件我们需要持续跟踪文件新增内容。Linux系统中的tail -f命令正是这种行为的代表它会在文件增长时输出新增内容。事件识别模式SSH爆破通常会在日志中留下特定模式例如Failed password for root from 192.168.1.100 port 22 ssh2 Accepted password for root from 192.168.1.100 port 22 ssh2异常行为定义单次失败登录可能是输入错误但同一IP的多次失败尝试就值得警惕。我们需要设定合理的阈值来判断异常。2. 基础监控脚本构建让我们从最简单的Python实现开始逐步构建功能。首先创建一个能实时读取日志文件的基础框架import time import re def follow_log(file): 模拟tail -f功能持续读取新增日志 with open(file, r) as f: f.seek(0, 2) # 移动到文件末尾 while True: line f.readline() if not line: time.sleep(0.1) # 短暂休眠避免CPU占用过高 continue yield line # 使用示例 for line in follow_log(/var/log/auth.log): print(line, end)这个基础版本已经能持续输出新增日志接下来我们需要添加日志解析功能def parse_ssh_log(line): 解析SSH相关日志条目 patterns { failed: re.compile(rFailed password for (?:invalid user )?(\w) from (\d\.\d\.\d\.\d)), success: re.compile(rAccepted password for (\w) from (\d\.\d\.\d\.\d)), invalid_user: re.compile(rFailed password for invalid user (\w) from (\d\.\d\.\d\.\d)) } for event_type, pattern in patterns.items(): match pattern.search(line) if match: return { event: event_type, user: match.group(1), ip: match.group(2), timestamp: time.strftime(%Y-%m-%d %H:%M:%S) } return None3. 异常检测与响应机制单纯的日志读取和解析还不够我们需要建立一套检测和响应机制。以下是关键组件的实现3.1 IP行为追踪我们需要一个数据结构来记录每个IP的行为模式from collections import defaultdict class IPTracker: def __init__(self, threshold5): self.attempts defaultdict(int) self.threshold threshold self.malicious_ips set() def record_attempt(self, ip): self.attempts[ip] 1 if self.attempts[ip] self.threshold and ip not in self.malicious_ips: self.malicious_ips.add(ip) return True # 表示新发现的恶意IP return False def record_success(self, ip): if ip in self.malicious_ips: return True # 表示成功登录的IP之前被标记为恶意 return False3.2 自动防御措施检测到威胁后我们可以采取多种防御措施。以下是使用iptables自动封锁IP的示例import subprocess def block_ip(ip): 使用iptables封锁指定IP try: subprocess.run([iptables, -A, INPUT, -s, ip, -j, DROP], checkTrue) subprocess.run([iptables-save], checkTrue) return True except subprocess.CalledProcessError: return False注意直接操作iptables需要root权限生产环境中建议通过sudo或专门的权限管理机制运行。4. 系统整合与可视化将各个组件整合成一个完整的监控系统并添加可视化功能import json from datetime import datetime class SSHAnalyzer: def __init__(self, log_file, threshold5): self.log_file log_file self.ip_tracker IPTracker(threshold) self.stats { total_attempts: 0, failed_attempts: 0, success_logins: 0, blocked_ips: [] } def run(self): print(f开始监控 {self.log_file}...) for line in follow_log(self.log_file): event parse_ssh_log(line) if not event: continue self.stats[total_attempts] 1 if event[event] success: self.stats[success_logins] 1 if self.ip_tracker.record_success(event[ip]): self.alert(f成功登录但之前有可疑行为: {event[ip]}) elif event[event] in (failed, invalid_user): self.stats[failed_attempts] 1 if self.ip_tracker.record_attempt(event[ip]): if block_ip(event[ip]): self.stats[blocked_ips].append({ ip: event[ip], timestamp: datetime.now().isoformat() }) self.alert(f已封锁IP: {event[ip]}) # 每小时输出一次统计信息 if datetime.now().minute 0 and datetime.now().second 0: self.report_stats() def alert(self, message): 发送警报的简单实现 print(f[ALERT] {datetime.now()}: {message}) def report_stats(self): 输出统计报告 print(\n 安全统计报告 ) print(f时间: {datetime.now()}) print(f总尝试次数: {self.stats[total_attempts]}) print(f失败尝试: {self.stats[failed_attempts]}) print(f成功登录: {self.stats[success_logins]}) print(f已封锁IP数: {len(self.stats[blocked_ips])}) print(\n)5. 进阶功能与优化基础功能实现后我们可以考虑以下增强功能5.1 多维度威胁检测除了简单的失败次数统计更智能的检测应该考虑时间窗口内的频率短时间内多次失败比长时间分散的失败更可疑用户名尝试多样性尝试多个不同用户名比反复尝试同一用户名更可疑地理位置异常来自不同国家/地区的快速切换登录尝试class EnhancedIPTracker(IPTracker): def __init__(self, time_window300, attempt_threshold5): super().__init__(attempt_threshold) self.time_window time_window # 5分钟 self.attempt_records defaultdict(list) def record_attempt(self, ip, timestamp): now time.time() # 记录本次尝试 self.attempt_records[ip].append(now) # 移除时间窗口外的记录 self.attempt_records[ip] [t for t in self.attempt_records[ip] if now - t self.time_window] if len(self.attempt_records[ip]) self.threshold and ip not in self.malicious_ips: self.malicious_ips.add(ip) return True return False5.2 与现有安全工具集成与其重新发明轮子不如与现有安全工具集成Fail2ban集成通过fail2ban的socket或API报告可疑IPSIEM系统集成将事件发送到SIEM系统如Splunk或ELK通知渠道扩展支持邮件、Slack、Telegram等多种通知方式def notify_slack(message, webhook_url): 发送通知到Slack import requests payload {text: message} try: requests.post(webhook_url, jsonpayload) except requests.RequestException as e: print(fSlack通知失败: {e})5.3 性能优化考虑对于高流量系统我们需要考虑性能优化使用inotify替代轮询Linux的inotify机制比定期检查文件更高效异步处理使用asyncio或线程池处理耗时的操作日志轮转处理正确处理日志文件的轮转和压缩import pyinotify class LogEventHandler(pyinotify.ProcessEvent): def my_init(self, callbackNone): self.callback callback def process_IN_MODIFY(self, event): if event.pathname self.wm.get_watch(event.wd)[path]: with open(event.pathname, r) as f: f.seek(self.last_pos) lines f.readlines() self.last_pos f.tell() if self.callback and lines: self.callback(lines) def monitor_with_inotify(log_file, callback): wm pyinotify.WatchManager() handler LogEventHandler(callbackcallback) notifier pyinotify.Notifier(wm, handler) wm.add_watch(log_file, pyinotify.IN_MODIFY) handler.last_pos 0 notifier.loop()6. 部署与持续改进完成开发后我们需要考虑如何将脚本部署为系统服务6.1 系统服务化创建systemd服务单元文件/etc/systemd/system/ssh_monitor.service:[Unit] DescriptionSSH Security Monitor Afternetwork.target [Service] ExecStart/usr/bin/python3 /opt/ssh_monitor/monitor.py Restartalways Userroot Grouproot EnvironmentPYTHONUNBUFFERED1 [Install] WantedBymulti-user.target然后启用并启动服务sudo systemctl daemon-reload sudo systemctl enable ssh_monitor sudo systemctl start ssh_monitor6.2 日志记录与审计脚本自身的运行也需要记录日志建议使用Python的logging模块import logging from logging.handlers import RotatingFileHandler def setup_logging(): logger logging.getLogger(ssh_monitor) logger.setLevel(logging.INFO) # 文件日志最大10MB保留5个备份 file_handler RotatingFileHandler( /var/log/ssh_monitor.log, maxBytes10*1024*1024, backupCount5 ) file_handler.setFormatter(logging.Formatter( %(asctime)s - %(levelname)s - %(message)s )) logger.addHandler(file_handler) # 控制台日志 console_handler logging.StreamHandler() console_handler.setFormatter(logging.Formatter( %(asctime)s - %(levelname)s - %(message)s )) logger.addHandler(console_handler) return logger6.3 持续改进方向在实际使用中可以根据需求不断改进系统机器学习检测使用简单模型识别更复杂的攻击模式分布式监控在多台服务器上部署并集中报告自动化取证发现攻击时自动收集相关证据白名单管理避免误封合法管理IPclass IPWhitelist: def __init__(self, whitelist_file): self.whitelist set() self.whitelist_file whitelist_file self.load_whitelist() def load_whitelist(self): try: with open(self.whitelist_file, r) as f: for line in f: line line.strip() if line and not line.startswith(#): self.whitelist.add(line) except FileNotFoundError: pass def is_whitelisted(self, ip): return ip in self.whitelist在实际部署中我发现最实用的功能不是自动封锁IP而是实时可视化展示攻击尝试的地图。使用GeoIP库将IP转换为地理位置再用简单的Web界面展示能直观了解攻击来源。另一个经验是阈值设置要足够灵活针对不同服务如SSH、Web管理界面设置不同的敏感度。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2459826.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!