提升蜜罐与安全检测代码功能

table {
border-collapse: collapse;
width: 100%;
margin-bottom: 1rem;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
pre {
background-color: #f8f8f8;
padding: 15px;
border-radius: 4px;
overflow-x: auto;
}

1、目前,HoneyResolver.py 很容易区分真实和虚假结果,因为所有虚假结果都解析到同一个 IP 地址。修改代码,仅将某些虚假子域名解析为为每个子域名分配的唯一 IP 地址。

可按以下步骤修改代码以实现仅将某些虚假子域名解析为唯一 IP 地址:

定义一个字典,用于存储某些虚假子域名及其对应的唯一 IP 地址。


resolve

函数中,检查请求的子域名是否在该字典中。若在,使用该字典中的 IP 地址进行响应;若不在,使用原来的蜜罐 IP 地址响应。

以下是修改后的代码示例:


from dnslib import *
from dnslib.server import DNSServer

host = "localhost"
port = 8053
subdomains = {
    "www.": "10.0.0.1",
    "smtp.": "10.0.0.2"
}
domain = "example.com"
honeyip = "10.0.0.0"

# 定义某些虚假子域名及其唯一 IP 地址
special_fake_subdomains = {
    "fake1.": "10.0.0.3",
    "fake2.": "10.0.0.4"
}
blocked = {}

class HoneyResolver:
    def resolve(self, request, handler):
        subdomain = str(request.q.qname.stripSuffix(domain + "."))
        if subdomain in subdomains:
            reply = request.reply()
            ip = subdomains[subdomain]
            reply.add_answer(RR(
                rname=request.q.qname,
                rtype=QTYPE.A,
                rclass=1,
                ttl=300,
                rdata=A(ip)
            ))
        elif subdomain in special_fake_subdomains:
            reply = request.reply()
            ip = special_fake_subdomains[subdomain]
            reply.add_answer(RR(
                rname=request.q.qname,
                rtype=QTYPE.A,
                rclass=1,
                ttl=300,
                rdata=A(ip)
            ))
        else:
            reply = request.reply()
            reply.add_answer(RR(
                rname=request.q.qname,
                rtype=QTYPE.A,
                rclass=1,
                ttl=300,
                rdata=A(honeyip)
            ))
        return reply

resolver = HoneyResolver()
server = DNSServer(resolver, port=port, address=host)
server.start_thread()

import time
while True:
    time.sleep(5)
server.stop()

2、AutorunDetection 使用 psutil 库确定进程的 PID。修改代码以提供有关可疑进程的更多信息,例如它们的创建时间或父 PID。

要修改

AutorunDetection.py

代码以提供有关可疑进程的更多信息,如创建时间和父 PID,可以在

DetectAutorunProcess

函数中添加相应逻辑。以下是修改后的代码:


import win32con
from win32api import GetLogicalDriveStrings
from win32file import GetDriveType
import os.path
import psutil


def GetRemovableDrives():
    driveStrings = GetLogicalDriveStrings()
    drives = [item for item in driveStrings.split("x00") if item]
    return [drive for drive in drives if GetDriveType(drive) is win32con.DRIVE_REMOVABLE]


def CheckAutorun(drive):
    filename = drive + "Autorun.inf"
    if os.path.isfile(filename):
        print("Autorun file at %s" % filename)
        with open(filename, "r") as f:
            for line in f:
                if line.startswith("Open"):
                    ind = line.index("=")
                    return line[ind + 1:].rstrip()
    else:
        return None


def DetectAutorunProcess(executable):
    for proc in psutil.process_iter():
        if executable == proc.name():
            try:
                create_time = proc.create_time()
                parent_pid = proc.ppid()
                print(f"Autorun file running with PID {proc.pid}, created at {create_time}, parent PID: {parent_pid}")
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass


for drive in GetRemovableDrives():
    executable = CheckAutorun(drive)
    if executable:
        DetectAutorunProcess(executable)

在上述代码中,

DetectAutorunProcess

函数在找到匹配的进程后,通过

proc.create_time()

获取进程的创建时间,通过

proc.ppid()

获取父进程的 PID,并将这些信息打印出来。同时,使用

try-except

块捕获可能的异常,如进程不存在、访问被拒绝或僵尸进程等情况。

3、修改DetectAntivirusService.py,通过将检测到的服务的Start值设置为0x04来禁用该服务。

要实现此修改,需在

DetectAntivirusService.py

中找到检测到的服务对应的键,以写权限打开该键,然后使用

SetValueEx

函数将

Start

值设置为

0x04

。示例代码如下:


import winreg

reghive = winreg.HKEY_LOCAL_MACHINE
regpath = "SYSTEMCurrentControlSetServices"
av_list = ['MBAM']  # 可根据需要扩展

try:
    key = winreg.OpenKey(reghive, regpath, 0, access=winreg.KEY_READ)
    numKeys = winreg.QueryInfoKey(key)[0]
    for i in range(numKeys):
        subkey = winreg.EnumKey(key, i)
        for name in av_list:
            if name in subkey:
                subPath = "%s\%s" % (regpath, subkey)
                # 以写权限打开子键
                k = winreg.OpenKey(reghive, subPath, 0, winreg.KEY_ALL_ACCESS)
                numVals = winreg.QueryInfoKey(k)[1]
                for j in range(numVals):
                    val = winreg.EnumValue(k, j)
                    if val[0] == "Start" and val[1] == 2:
                        print("Service %s set to run automatically, disabling it." % subkey)
                        # 设置Start值为0x04
                        winreg.SetValueEx(k, "Start", 0, winreg.REG_DWORD, 0x04)
                winreg.CloseKey(k)
    winreg.CloseKey(key)
except Exception as e:
    print(e)

此代码在原检测代码基础上,当找到

Start

值为

0x02

的服务时,以写权限打开该服务的键,并将

Start

值设置为

0x04

以禁用服务。注意,运行此代码需要管理员权限。

4、编辑 MonitorClipboard 代码,当剪贴板被可疑进程修改时,提取并打印剪贴板的当前内容。

要实现这个需求,需要对

MonitorClipboard.py

代码进行修改,在检测到剪贴板被可疑进程修改时,提取并打印剪贴板的当前内容。以下是修改后的代码:


import win32gui, win32api, ctypes
from win32clipboard import GetClipboardOwner, OpenClipboard, GetClipboardData, CloseClipboard
from win32process import GetWindowThreadProcessId
from psutil import Process

allowlist = []

def processEvent(hwnd, msg, wparam, lparam):
    if msg == 0x031D:
        try:
            win = GetClipboardOwner()
            pid = GetWindowThreadProcessId(win)[1]
            p = Process(pid)
            name = p.name()
            if name not in allowlist:
                print(f"Clipboard modified by {name}")
                # 打开剪贴板
                OpenClipboard()
                # 获取剪贴板内容
                clipboard_data = GetClipboardData()
                # 关闭剪贴板
                CloseClipboard()
                print(f"Current clipboard contents: {clipboard_data}")
        except:
            print("Clipboard modified by unknown process")

def createWindow():
    wc = win32gui.WNDCLASS()
    wc.lpfnWndProc = processEvent
    wc.lpszClassName = 'clipboardListener'
    wc.hInstance = win32api.GetModuleHandle(None)
    class_atom = win32gui.RegisterClass(wc)
    return win32gui.CreateWindow(class_atom, 'clipboardListener', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, wc.hInstance, None)

def setupListener():
    hwnd = createWindow()
    ctypes.windll.user32.AddClipboardFormatListener(hwnd)
    win32gui.PumpMessages()

setupListener()

在上述代码中,当检测到剪贴板被可疑进程修改时,会调用

OpenClipboard

打开剪贴板,使用

GetClipboardData

获取剪贴板内容,然后使用

CloseClipboard

关闭剪贴板,最后打印出剪贴板的当前内容。

© 版权声明

相关文章

暂无评论

none
暂无评论...