概述

安全监控与检测是网络安全运营的核心能力,通过持续监控系统和网络活动,及时发现潜在的安全威胁。本教程将深入介绍各种监控技术和检测方法。

安全监控基础

监控层次

┌─────────────────────────────────────────────┐
│              安全监控层次                  │
├─────────────────────────────────────────────┤
│                                             │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  │
│  │ 网络层  │  │ 主机层  │  │ 应用层  │  │
│  └─────────┘  └─────────┘  └─────────┘  │
│       │            │            │          │
│       ▼            ▼            ▼          │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  │
│  │ 流量监控 │  │ 日志监控 │  │ 行为监控 │  │
│  └─────────┘  └─────────┘  └─────────┘  │
│                                             │
└─────────────────────────────────────────────┘

监控数据源

  1. 网络数据

    • 网络流量
    • 数据包捕获
    • 流日志(NetFlow/IPFIX)
  2. 系统日志

    • 操作系统日志
    • 应用程序日志
    • 安全设备日志
  3. 端点数据

    • 进程活动
    • 文件系统变化
    • 注册表修改
  4. 用户行为

    • 登录活动
    • 权限变更
    • 数据访问

网络监控技术

流量监控

流量监控配置:
  监控点:
    - 网络边界
    - 关键网段
    - 服务器区域
  
  监控指标:
    - 带宽使用率
    - 连接数
    - 协议分布
    - 异常流量
  
  告警阈值:
    带宽: > 80%
    连接数: > 10000
    异常流量: > 基线 3 倍

数据包捕获

# 使用 tcpdump 捕获数据包
tcpdump -i eth0 -w capture.pcap

# 捕获特定端口
tcpdump -i eth0 port 80 -w http.pcap

# 捕获特定主机
tcpdump -i eth0 host 192.168.1.100 -w host.pcap

# 使用 Wireshark 分析
wireshark capture.pcap

流日志分析

# NetFlow 分析示例
import pyshark

def analyze_netflow(flow_file):
    """分析 NetFlow 数据"""
    flows = pyshark.FileCapture(flow_file)
    
    for flow in flows:
        src_ip = flow.ip.src
        dst_ip = flow.ip.dst
        bytes = int(flow.tcp.len)
        
        # 检测异常流量
        if bytes > 1000000:  # 超过 1MB
            print(f"异常大流量: {src_ip} -> {dst_ip}")

日志监控

日志收集架构

┌──────────┐    ┌──────────┐    ┌──────────┐
│ 服务器 1 │    │ 服务器 2 │    │ 服务器 3 │
└─────┬────┘    └─────┬────┘    └─────┬────┘
      │                │                │
      └────────┬───────┴────────┬───────┘
               │                │
               ▼                ▼
         ┌──────────────┐
         │  日志收集器   │
         │  (Filebeat)  │
         └──────┬───────┘
                │
                ▼
         ┌──────────────┐
         │  日志聚合器   │
         │  (Logstash)  │
         └──────┬───────┘
                │
                ▼
         ┌──────────────┐
         │  日志存储     │
         │  (Elasticsearch)│
         └──────┬───────┘
                │
                ▼
         ┌──────────────┐
         │  可视化平台   │
         │  (Kibana)    │
         └──────────────┘

关键日志类型

  1. 系统日志

    • /var/log/syslog (Linux)
    • Windows Event Log
    • 系统启动/关闭
    • 用户登录/登出
  2. 应用日志

    • Web 服务器日志
    • 应用程序错误日志
    • 事务日志
  3. 安全日志

    • 防火墙日志
    • IDS/IPS 日志
    • VPN 日志

日志分析示例

# 日志分析脚本
import re
from collections import Counter

def analyze_security_logs(log_file):
    """分析安全日志"""
    failed_logins = []
    suspicious_ips = Counter()
    
    with open(log_file, 'r') as f:
        for line in f:
            # 检测失败登录
            if 'Failed password' in line:
                ip_match = re.search(r'from (\d+\.\d+\.\d+\.\d+)', line)
                if ip_match:
                    ip = ip_match.group(1)
                    failed_logins.append(ip)
                    suspicious_ips[ip] += 1
    
    # 报告可疑 IP
    for ip, count in suspicious_ips.most_common(10):
        if count > 5:
            print(f"可疑 IP: {ip}, 失败次数: {count}")

入侵检测系统

IDS 类型

  1. 基于签名的 IDS

    • 匹配已知攻击模式
    • 误报率低
    • 无法检测未知攻击
  2. 基于异常的 IDS

    • 检测偏离正常行为
    • 可检测未知攻击
    • 误报率较高

Snort 配置示例

# 安装 Snort
sudo apt-get install snort

# 配置文件
# /etc/snort/snort.conf

# 定义规则
alert tcp any any -> any 80 (msg:"WEB-MISC /etc/passwd access"; \
    content:"/etc/passwd"; nocase; sid:1000001;)

# 运行 Snort
sudo snort -i eth0 -A console -q -c /etc/snort/snort.conf

Suricata 配置示例

# suricata.yaml
af-packet:
  interface: eth0

logging:
  outputs:
    - fast:
        enabled: yes
        filename: suricata.log

rule-files:
    - suricata.rules

# 自定义规则
alert http any any -> any any (msg:"SQL Injection Attempt"; \
    content:"UNION SELECT"; nocase; sid:1000001;)

异常检测

基于统计的异常检测

import numpy as np
from scipy import stats

def detect_anomalies(data, threshold=3):
    """使用 Z-score 检测异常"""
    mean = np.mean(data)
    std = np.std(data)
    
    z_scores = [(x - mean) / std for x in data]
    anomalies = []
    
    for i, z in enumerate(z_scores):
        if abs(z) > threshold:
            anomalies.append((i, data[i], z))
    
    return anomalies

# 示例使用
traffic_data = [100, 105, 98, 102, 500, 95, 103]
anomalies = detect_anomalies(traffic_data)

for index, value, z_score in anomalies:
    print(f"异常检测: 索引={index}, 值={value}, Z-score={z_score:.2f}")

基于机器学习的异常检测

from sklearn.ensemble import IsolationForest
import numpy as np

def ml_anomaly_detection(data, contamination=0.1):
    """使用 Isolation Forest 检测异常"""
    # 准备数据
    X = np.array(data).reshape(-1, 1)
    
    # 训练模型
    model = IsolationForest(contamination=contamination)
    model.fit(X)
    
    # 预测异常
    predictions = model.predict(X)
    anomalies = []
    
    for i, pred in enumerate(predictions):
        if pred == -1:  # -1 表示异常
            anomalies.append((i, data[i]))
    
    return anomalies

# 示例使用
network_traffic = [100, 105, 98, 102, 500, 95, 103]
anomalies = ml_anomaly_detection(network_traffic)

for index, value in anomalies:
    print(f"异常流量: 时间={index}, 流量={value}")

端点检测

EDR 功能

  1. 进程监控

    • 进程创建/终止
    • 进程树分析
    • 可疑进程检测
  2. 文件监控

    • 文件创建/修改/删除
    • 恶意软件检测
    • 勒索软件检测
  3. 网络监控

    • 网络连接监控
    • DNS 查询监控
    • C2 通信检测

Sysmon 配置

<!-- Sysmon 配置文件 -->
<Sysmon schemaversion="4.82">
  <EventFiltering>
    <!-- 监控进程创建 -->
    <ProcessCreate onmatch="exclude">
      <Image condition="image">C:\Windows\System32\svchost.exe</Image>
    </ProcessCreate>
    
    <!-- 监控网络连接 -->
    <NetworkConnect onmatch="include">
      <DestinationPort condition="is">443</DestinationPort>
    </NetworkConnect>
    
    <!-- 监控文件创建 -->
    <FileCreateStreamHash onmatch="include">
      <TargetFilename condition="contains">.exe</TargetFilename>
    </FileCreateStreamHash>
  </EventFiltering>
</Sysmon>

威胁情报集成

威胁情报类型

  1. 战略情报

    • 威胁趋势
    • 攻击组织分析
    • 长期威胁预测
  2. 战术情报

    • TTP(战术、技术和程序)
    • 攻击工具
    • 漏洞信息
  3. 操作情报

    • IOC(入侵指标)
    • 恶意域名/IP
    • 文件哈希

威胁情报应用

# 威胁情报匹配
import requests

class ThreatIntel:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.threatintel.example.com"
    
    def check_ip(self, ip_address):
        """检查 IP 地址"""
        url = f"{self.base_url}/ip/{ip_address}"
        headers = {"Authorization": f"Bearer {self.api_key}"}
        
        response = requests.get(url, headers=headers)
        return response.json()
    
    def check_domain(self, domain):
        """检查域名"""
        url = f"{self.base_url}/domain/{domain}"
        headers = {"Authorization": f"Bearer {self.api_key}"}
        
        response = requests.get(url, headers=headers)
        return response.json()

# 使用示例
intel = ThreatIntel("your-api-key")
result = intel.check_ip("192.168.1.100")

if result["malicious"]:
    print(f"恶意 IP: {result['ip']}")
    print(f"威胁类型: {result['threat_type']}")

监控仪表板

关键指标

监控仪表板指标:
  网络安全:
    - 入站流量
    - 出站流量
    - 阻止的连接
    - 异常流量
  
  系统安全:
    - 失败登录次数
    - 权限提升事件
    - 恶意软件检测
    - 异常进程
  
  应用安全:
    - Web 攻击尝试
    - SQL 注入尝试
    - XSS 攻击
    - 异常 API 调用
  
  威胁情报:
    - 匹配的 IOC
    - 新威胁告警
    - 威胁评分

Grafana 仪表板配置

{
  "dashboard": {
    "title": "安全运营仪表板",
    "panels": [
      {
        "title": "网络流量",
        "type": "graph",
        "targets": [
          {
            "expr": "rate(network_bytes_in[5m])",
            "legendFormat": "入站流量"
          },
          {
            "expr": "rate(network_bytes_out[5m])",
            "legendFormat": "出站流量"
          }
        ]
      },
      {
        "title": "安全事件",
        "type": "stat",
        "targets": [
          {
            "expr": "count(security_events)",
            "legendFormat": "总事件数"
          }
        ]
      }
    ]
  }
}

实际应用示例

综合监控流程

import time
from datetime import datetime

class SecurityMonitor:
    def __init__(self):
        self.alerts = []
        self.thresholds = {
            'failed_logins': 5,
            'network_traffic': 1000000,
            'cpu_usage': 80
        }
    
    def monitor_network(self):
        """监控网络流量"""
        traffic = self.get_network_traffic()
        
        if traffic > self.thresholds['network_traffic']:
            alert = {
                'timestamp': datetime.now(),
                'type': 'network',
                'severity': 'high',
                'message': f'异常网络流量: {traffic} bytes'
            }
            self.alerts.append(alert)
    
    def monitor_logins(self):
        """监控登录活动"""
        failed_logins = self.get_failed_logins()
        
        if failed_logins > self.thresholds['failed_logins']:
            alert = {
                'timestamp': datetime.now(),
                'type': 'authentication',
                'severity': 'medium',
                'message': f'多次失败登录: {failed_logins} 次'
            }
            self.alerts.append(alert)
    
    def run(self):
        """运行监控"""
        while True:
            self.monitor_network()
            self.monitor_logins()
            
            # 处理告警
            for alert in self.alerts:
                self.handle_alert(alert)
            
            self.alerts = []
            time.sleep(60)  # 每分钟检查一次
    
    def handle_alert(self, alert):
        """处理告警"""
        print(f"[{alert['timestamp']}] {alert['severity'].upper()}: {alert['message']}")
        # 发送通知
        self.send_notification(alert)
    
    def send_notification(self, alert):
        """发送通知"""
        # 实现通知逻辑
        pass

# 运行监控
monitor = SecurityMonitor()
monitor.run()

总结

本教程详细介绍了网络安全监控与检测:

  1. 安全监控基础

    • 监控层次
    • 监控数据源
    • 监控架构
  2. 网络监控技术

    • 流量监控
    • 数据包捕获
    • 流日志分析
  3. 日志监控

    • 日志收集架构
    • 关键日志类型
    • 日志分析方法
  4. 入侵检测系统

    • IDS 类型
    • Snort 配置
    • Suricata 配置
  5. 异常检测

    • 基于统计的检测
    • 基于机器学习的检测
    • 异常检测实践
  6. 端点检测

    • EDR 功能
    • Sysmon 配置
    • 端点监控实践
  7. 威胁情报集成

    • 威胁情报类型
    • IOC 匹配
    • 情报应用
  8. 监控仪表板

    • 关键指标
    • Grafana 配置
    • 可视化实践

安全监控与检测是网络安全运营的基础能力,建立完善的监控体系对于及时发现和响应安全威胁至关重要。

下一步

在下一教程中,我们将学习安全事件响应,包括:

  • 事件响应流程

  • 事件分类和分级

  • 应急响应技术

  • 事件调查方法

  • 事后分析和改进

继续学习网络安全运营,掌握这门重要领域的更多知识!