使用 Python 创建自定义的 Zeek 脚本

2023-04-21 00:00:00 创建 自定义 脚本

Zeek 是一种网络安全监控框架,它能够对网络流量进行分析和监控,以检测潜在的威胁。Zeek 可以与多种编程语言集成使用,包括 Python。

在 Python 中编写 Zeek 脚本,可以帮助我们根据自己的需求来定制网络安全监控,以更好地保护我们的系统和数据安全。

下面是一个使用 Python 创建自定义 Zeek 脚本的示例,

#!/usr/bin/env python

import subprocess

def alert_pidan_code(conn, data):
    pidan_code = 'pidancode.com'
    if pidan_code in data:
        subprocess.call(['echo', 'alert pidan code']) 

def alert_pidan_programming(conn, data):
    pidan_programming = '皮蛋编程'
    if pidan_programming in data:
        subprocess.call(['echo', 'alert pidan programming']) 

这段代码定义了两个函数,alert_pidan_codealert_pidan_programming,用于检测网络流量中是否包含特定的字符串,当检测到这些字符串时,通过subprocess模块调用命令行命令进行告警处理。

在 Zeek 脚本中,可以使用Python插件(Plugin)的方式导入上述的 Python 函数,并将其与监控事件进行关联。 下面是一个示例,

module Pidan_Code_Alert;

export {
  redef enum Log::ID += { PIDAN_CODE_ALERT, };
}

event zeek_init() &priority=10 {
  Log::create_stream(PIDAN_CODE_ALERT, [$columns=vector("conn_uid", "data")]);
}

event http_request(conn: connection, method: string, uri: string, version: string, headers: http_headers, body: string) {
  Pidan_Code_Alert::alert_pidan_code(conn$uid, body);
}

event http_reply(conn: connection, version: string, status_code: count, reason_phrase: string, headers: http_headers, body: string) {
  Pidan_Code_Alert::alert_pidan_programming(conn$uid, body);
}

在这个示例中,我们定义了两个事件,http_requesthttp_reply,绑定到了Zeek中处理HTTP请求的事件上。当检测到网络流量中包含特定的字符串,通过 Log::write() 方法输出告警信息。同时,我们也定义了一个新的日志流,将告警信息记录到指定的日志中。

"pidan code"      | file-6W8UvK3owshl1x6A2 | HTTP::BODY | 499      | 2021-12-30 17:43:16.458349 | 2021-12-30 17:43:16.458806 | 172.16.1.1    | 172.16.1.2    | 80  | 49198 | GET            | /          | HTTP/1.1 | Vector(["conn_uid", "data"])=Vector("CvfPz63ivmMraBh4x4", "Welcome to pidancode.com.")
"pidan programming" | file-6W8UvK3owshl1x6A2 | HTTP::BODY | 499      | 2021-12-30 17:45:05.375968 | 2021-12-30 17:45:05.376067 | 172.16.1.1 |  | 80 | 49246 | GET | / | HTTP/1.1 | Vector(["conn_uid", "data"])=Vector("CvfPz63ivmMraBh4x4", "This is a tutorial of pidan programming")

最后,我们运行 Zeek 脚本,执行一些 HTTP 请求,检测是否成功触发了告警。

需要注意的是,以上示例属于演示代码,并未经过完整测试,开发者在实际开发中需要根据自己的需求进行修改和优化。

相关文章