前言

银狐木马,又名Winos 或 ValleyRAT。流传范围最广的是Winos4.0版本,本文对其在受害主机留下的文件相关痕迹进行分析总结,提取出关键信息以便后续的溯源分析,并给出一键dump脚本,便捷提取出所有留下的蛛丝马迹。

文件痕迹

银狐的上线流程为shellcode加载器->上线模块->登录模块的多阶段模式,其中登录模块是处理命令的核心模块。

内存加载dll

登录模块中,会初始化保存在注册表中的dll,这些dll由主控端发送,目的是保存在注册表中内存加载,同时减少流量的传输。

32位的被控端保存在HKEY_CURRENT_USER\Console\0

64位的被控端保存在HKEY_CURRENT_USER\Console\1

​

保存的键为dll的md5哈希值,数据为一个固定大小的dll信息结构体和dll的二进制数据。

备注分组

登录模块中,可通过修改指定的注册表值,实现了分组和备注功能

备注和分组都以utf-16-le编码后保存

备注保存在HKEY_CURRENT_USER\Network GROUP

分组保存在HKEY_CURRENT_USER\Network REMARK

上线信息

登录模块中,可通过修改指定注册表值,实现永久更改连接的主控端ip 端口 协议

信息保存在HKEY_CURRENT_USER\Console IpDate 中

键盘记录

使用DirectInput api自动进行键盘记录

自动离线记录保存在HKEY_CURRENT_USER\key open

离线记录的键盘数据保存在目录CSIDL_COMMON_APPDATA(通常为C:\ProgramData) 中,文件名为DisplaySessionContainers.log

​

Rootkit

驱动模块中,创建系统驱动服务,开启自动运行,可隐藏指定进程 文件 目录 注册表项,并开机自动注入shellcode到DWM.exe进程,实现隐匿持久化

将驱动文件保存到目录 CSIDL_COMMON_APPDATA,文件名为23423.txt,注册驱动服务kernelquick

添加注册表项,用来设置要隐藏和保护的对象,该驱动代码实际由开源项目hidden修改而来

​

写入上线shellcode到HKEY_LOCAL_MACHINE\SOFTWARE IpDates中,驱动启动时,会自动注入到DWM.exe进程中。

dump 代码

使用python进行dump,效果图和代码如下

import winreg
import os
import ctypes
import re

class PayloadConfigStruct(ctypes.Structure):
    _fields_ = [
        ("unknown_int_1", ctypes.c_int),
        ("module_name", ctypes.c_wchar * 255),
        ("is_platform_x64", ctypes.c_int),
        ("payload_size", ctypes.c_int),
        ("unknown_buffer_1", ctypes.c_wchar * 50),
        ("unknown_buffer_2", ctypes.c_wchar * 1000),
        ("unknown_int_2", ctypes.c_int)
    ]

def sanitize_filename(filename):
    clean_name = re.sub(r'[\\/*?:"<>|]', "_", filename)
    clean_name = clean_name.strip('\x00').strip()
    if not clean_name:
        return "unknown_filename"
    return clean_name

def ensure_dump_dir():
    output_dir = "dump"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    return output_dir

def clean_rat_config(text):
    match = re.search(r'(.*\|t3:\d+\|)', text)
    if match:
        return match.group(1)
    return text

def dump_console_payloads():
    target_sub_keys = [r"Console\0", r"Console\1"]
    
    base_dump_dir = ensure_dump_dir()
    
    for arch in ["x86", "x64"]:
        arch_dir = os.path.join(base_dump_dir, arch)
        if not os.path.exists(arch_dir):
            os.makedirs(arch_dir)

    current_struct_size = ctypes.sizeof(PayloadConfigStruct)
    print(f"[*] Header Structure Size: {current_struct_size} bytes")
    
    for sub_key in target_sub_keys:
        print("-" * 50)
        print(f"[*] Target Registry: HKCU\\{sub_key}")

        try:
            h_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
        except FileNotFoundError:
            print(f"[!] Registry path HKCU\\{sub_key} not found.")
            continue

        index = 0
        
        while True:
            try:
                name, value, type_ = winreg.EnumValue(h_key, index)
                
                if type_ == winreg.REG_BINARY:
                    total_len = len(value)
                    
                    if total_len < current_struct_size:
                        print(f"[!] Skipping '{name}': Data too short to parse header.")
                    else:
                        header = PayloadConfigStruct.from_buffer_copy(value[:current_struct_size])
                        
                        extracted_name = header.module_name
                        is_x64 = header.is_platform_x64
                        data_len = header.payload_size
                        
                        arch_str = "x64" if is_x64 else "x86"
                        
                        print(f"[+] Payload Found in {sub_key}: {name}")
                        print(f"    |-- Module Name : {extracted_name}")
                        print(f"    |-- Architecture: {arch_str}")
                        print(f"    |-- Payload Size: {data_len} bytes")
                        print(f"    |-- Total RegSz : {total_len} bytes")
                        
                        real_header_len = total_len - data_len
                        
                        if real_header_len < 0:
                             print(f"    [!] Critical Error: Payload size ({data_len}) > Registry data ({total_len})!")
                             index += 1
                             continue
                             
                        dll_data = value[-data_len:]
                        
                        safe_name = sanitize_filename(extracted_name)
                        if safe_name == "unknown_filename":
                            safe_name = f"Unknown_{name}"
                        
                        save_subdir = os.path.join(base_dump_dir, arch_str)
                        save_path = os.path.join(save_subdir, f"{safe_name}.dll")
                        
                        try:
                            with open(save_path, "wb") as f:
                                f.write(dll_data)
                            print(f"    |-- [OK] Saved successfully: {save_path}")
                        except Exception as e:
                            print(f"    |-- [ERR] Save failed: {e}")
                        
                        print("." * 30)

                index += 1
            except OSError:
                break
            except Exception as e:
                print(f"[!] Error: {e}")
                index += 1

        winreg.CloseKey(h_key)
    print("-" * 50)

def dump_config(hive, sub_key, target_value_name=None):
    output_dir = ensure_dump_dir()
    output_file = os.path.join(output_dir, "config.txt")
    
    key_map = {
        "REMARK": "note",
        "GROUP": "group",
        "IpDate": "rat_config",
        "open": "keylogger_status"
    }
    
    hive_name = "HKCU" if hive == winreg.HKEY_CURRENT_USER else "HKLM"
    print(f"[*] Target Registry: {hive_name}\\{sub_key}")

    try:
        h_key = winreg.OpenKey(hive, sub_key, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
    except FileNotFoundError:
        print(f"[-] Registry path {hive_name}\\{sub_key} not found.")
        return
    except PermissionError:
        print(f"[!] Permission denied accessing {hive_name}\\{sub_key}. Try running as Administrator.")
        return

    try:
        with open(output_file, "a", encoding="utf-8") as f:
            
            if target_value_name:
                try:
                    value, type_ = winreg.QueryValueEx(h_key, target_value_name)
                    if type_ == winreg.REG_BINARY:
                        text_content = value.decode('utf-16-le', errors='replace').rstrip('\x00')
                        
                        text_content = clean_rat_config(text_content)
                        
                        display_name = key_map.get(target_value_name, target_value_name)
                        line = f"{display_name}: {text_content}"
                        
                        f.write(line + "\n")
                        print(f"[+] Config Found: {line}")
                    else:
                        print(f"[-] '{target_value_name}' exists but is not REG_BINARY.")
                except FileNotFoundError:
                    print(f"[-] Value '{target_value_name}' not found.")
            
            else:
                index = 0
                while True:
                    try:
                        name, value, type_ = winreg.EnumValue(h_key, index)
                        if type_ == winreg.REG_BINARY:
                            try:
                                text_content = value.decode('utf-16-le', errors='replace').rstrip('\x00')
                                
                                text_content = clean_rat_config(text_content)
                                
                                display_name = key_map.get(name, name)
                                line = f"{display_name}: {text_content}"
                                
                                f.write(line + "\n")
                                print(f"[+] Config Found: {line}")
                            except Exception as e:
                                print(f"[!] Error decoding '{name}': {e}")
                        index += 1
                    except OSError:
                        break

        print("-" * 30)

    except Exception as e:
        print(f"[!] Error processing config: {e}")
    finally:
        winreg.CloseKey(h_key)

def dump_rootkit_service():
    sub_key = r"SYSTEM\CurrentControlSet\Services\kernelquick"
    output_dir = ensure_dump_dir()
    output_file = os.path.join(output_dir, "config.txt")
    
    print(f"[*] Target Registry: HKLM\\{sub_key}")

    try:
        h_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
    except FileNotFoundError:
        print(f"[-] Service 'kernelquick' not found.")
        return
    except PermissionError:
        print(f"[!] Permission denied accessing HKLM\\{sub_key}.")
        return

    target_values = {
        "DisplayName": "rootkit_service_name",
        "ImagePath": "rootkit_driver_path",
        
        "KernelQuick_HideFsFiles": "rootkit_hide_files",
        "KernelQuick_HideFsDirs": "rootkit_hide_dirs",
        
        "KernelQuick_HideRegKeys": "rootkit_hide_reg_keys",
        "KernelQuick_HideRegValues": "rootkit_hide_reg_values",
        
        "KernelQuick_ProtectedImages": "rootkit_protected_images",
        "KernelQuick_HideImages": "rootkit_hide_images"
    }

    try:
        with open(output_file, "a", encoding="utf-8") as f:
            for val_name, display_name in target_values.items():
                try:
                    value, type_ = winreg.QueryValueEx(h_key, val_name)
                    
                    content = ""
                    if type_ == winreg.REG_SZ or type_ == winreg.REG_EXPAND_SZ:
                        content = str(value)
                    elif type_ == winreg.REG_MULTI_SZ:
                        content = ", ".join(value)
                    elif type_ == winreg.REG_DWORD:
                        content = str(value)
                    
                    if content:
                        line = f"{display_name}: {content}"
                        f.write(line + "\n")
                        print(f"[+] Config Found: {line}")
                        
                except FileNotFoundError:
                    pass
        print("-" * 30)
    finally:
        winreg.CloseKey(h_key)

def dump_shellcode_from_software():
    sub_key = r"SOFTWARE"
    value_name = "IpDates"
    output_filename = "driver_load_shellcode.bin"
    
    output_dir = ensure_dump_dir()
    output_path = os.path.join(output_dir, output_filename)
    
    print(f"[*] Target Registry: HKLM\\{sub_key} -> {value_name}")

    try:
        h_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, sub_key, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
        try:
            value, type_ = winreg.QueryValueEx(h_key, value_name)
            if type_ == winreg.REG_BINARY:
                with open(output_path, "wb") as f:
                    f.write(value)
                print(f"[+] Dumped: {output_path} (Size: {len(value)} bytes)")
            else:
                print(f"[-] '{value_name}' exists but is not REG_BINARY.")
        except FileNotFoundError:
            print(f"[-] Value '{value_name}' not found.")
        finally:
            winreg.CloseKey(h_key)
    except Exception as e:
        print(f"[!] Error: {e}")
    
    print("-" * 30)

def dump_programdata_files():
    program_data = os.environ.get('ProgramData')
    if not program_data:
        print("[!] Environment variable 'ProgramData' not found.")
        return

    target_files = [
        {"src": "DisplaySessionContainers.log", "dst": "keyboard_logs.txt", "mode": "utf16_to_utf8"},
        {"src": "23423.txt", "dst": "rootkit.sys", "mode": "binary"}
    ]
    
    output_dir = ensure_dump_dir()

    print(f"[*] Target Directory: {program_data}")

    for item in target_files:
        src_filename = item["src"]
        dst_filename = item["dst"]
        mode = item.get("mode", "binary")
        
        src_path = os.path.join(program_data, src_filename)
        dst_path = os.path.join(output_dir, dst_filename)
        
        if not os.path.exists(src_path):
            print(f"[-] File not found: {src_filename}")
            continue

        try:
            if mode == "utf16_to_utf8":
                with open(src_path, 'r', encoding='utf-16-le', errors='replace') as f_in:
                    content = f_in.read()
                with open(dst_path, 'w', encoding='utf-8') as f_out:
                    f_out.write(content)
                print(f"[+] Dumped: {src_filename} -> {dst_path}")
            
            elif mode == "binary":
                with open(src_path, 'rb') as f_in:
                    content = f_in.read()
                with open(dst_path, 'wb') as f_out:
                    f_out.write(content)
                print(f"[+] Dumped: {src_filename} -> {dst_path}")

        except Exception as e:
            print(f"[!] Error processing {src_filename}: {e}")
            
    print("-" * 30)

if __name__ == "__main__":
    config_path = os.path.join("dump", "config.txt")
    if os.path.exists(config_path):
        try:
            os.remove(config_path)
            print("[*] Cleaned up old config.txt")
        except:
            pass

    dump_console_payloads()
    
    dump_config(winreg.HKEY_CURRENT_USER, r"Network")
    
    dump_config(winreg.HKEY_CURRENT_USER, r"Console", target_value_name="IpDate")

    dump_config(winreg.HKEY_CURRENT_USER, r"key", target_value_name="open")

    dump_rootkit_service()

    dump_shellcode_from_software()

    dump_programdata_files()
    
    print("=== All Tasks Completed ===")