最新消息:

威胁样本下载器 (Threat Sample Downloader)

威胁样本下载器 (Threat Sample Downloader)

一个高性能、安全的威胁样本下载器,专为网络安全研究和恶意软件分析而设计。主要应用场景为对接狩猎平台(NTA/蜜罐/WAF/EDR等)提取到的: Malware-Url 提交自动下载获取到恶意样本。

功能特性

🚀 高性能下载

  • 并发下载: 支持多线程并发下载,可配置最大并发数
  • 断点续传: 支持网络中断后的断点续传功能
  • 智能重试: 自动重试失败的下载,支持指数退避策略
  • 连接池: 复用HTTP连接,提高下载效率
  • 限流控制: 支持下载速度限制和突发流量控制

🔒 安全防护

  • 文件验证: 支持MD5、SHA1、SHA256哈希值验证
  • 类型检查: 可配置允许/禁止的文件类型白黑名单
  • URL安全: 检查URL安全性,防止访问私有IP地址
  • SSL验证: 支持SSL证书验证和自签名证书处理

📊 监控统计

  • 实时统计: 提供下载进度、成功率、速度等实时统计
  • 进度回调: 支持自定义进度回调函数
  • 日志记录: 详细的下载日志和错误记录
  • 指标收集: 支持Prometheus指标导出
  • 告警通知: 支持Webhook告警通知

⚙️ 灵活配置

  • 存储配置: 可配置存储路径、文件命名规则、压缩等
  • 网络配置: 支持代理、超时、重试、用户代理等配置
  • 并发配置: 可调整并发数、队列大小、批处理等参数
  • 安全配置: 灵活的安全策略配置

快速开始

基本使用

<code>package main

import (
    "log"
    "github.com/your-org/truth/pkg/downloader"
)

func main() {
    // 创建默认配置
    config := downloader.DefaultConfig()
    
    // 自定义配置
    config.Storage.BasePath = "./downloads"
    config.Concurrency.MaxConcurrentDownloads = 5
    config.Security.EnableHashVerify = true
    
    // 创建下载器
    dl, err := downloader.NewThreatDownloader(config)
    if err != nil {
        log.Fatal(err)
    }
    
    // 启动下载器
    if err := dl.Start(); err != nil {
        log.Fatal(err)
    }
    defer dl.Stop()
    
    // 创建威胁样本
    sample := &amp;downloader.ThreatSample{
        ID:         "sample_001",
        URL:        "https://example.com/malware.exe",
        Filename:   "malware.exe",
        SHA256:     "expected_sha256_hash",
        ThreatType: "trojan",
        Source:     "honeypot",
        Priority:   8,
    }
    
    // 提交下载任务
    task, err := dl.SubmitTask(sample)
    if err != nil {
        log.Fatal(err)
    }
    
    log.Printf("任务已提交: %s", task.Sample.ID)
}
</code>

批量下载

<code>// 创建多个威胁样本
samples := []*downloader.ThreatSample{
    {
        ID:         "sample_001",
        URL:        "https://example.com/malware1.exe",
        SHA256:     "hash1",
        ThreatType: "trojan",
    },
    {
        ID:         "sample_002", 
        URL:        "https://example.com/malware2.dll",
        MD5:        "hash2",
        ThreatType: "backdoor",
    },
}

// 批量提交
tasks, err := dl.SubmitBatch(samples)
if err != nil {
    log.Printf("批量提交失败: %v", err)
}

log.Printf("已提交 %d 个任务", len(tasks))
</code>

进度监控

<code>// 注册进度回调
dl.RegisterCallback("progress", func(task *downloader.DownloadTask, downloaded, total int64) {
    if total &gt; 0 {
        progress := float64(downloaded) / float64(total) * 100
        fmt.Printf("任务 %s: %.1f%% (%s/%s)\n", 
            task.Sample.ID, progress, 
            downloader.FormatBytes(downloaded), 
            downloader.FormatBytes(total))
    }
})

// 获取统计信息
stats := dl.GetStats()
fmt.Printf("完成: %d, 失败: %d, 成功率: %.1f%%\n",
    stats.CompletedTasks, stats.FailedTasks, stats.SuccessRate)
</code>

配置说明

存储配置 (StorageConfig)

<code>Storage: StorageConfig{
    BasePath:          "./downloads",     // 下载基础路径
    TempPath:          "./temp",          // 临时文件路径
    MaxFileSize:       100 * 1024 * 1024, // 最大文件大小 (100MB)
    MinFileSize:       1024,              // 最小文件大小 (1KB)
    AutoCreateDir:     true,              // 自动创建目录
    FileNamingPattern: "hash",            // 文件命名模式: hash/timestamp/original
    EnableCompression: false,             // 启用压缩存储
    CleanupTemp:       true,              // 清理临时文件
}
</code>

网络配置 (NetworkConfig)

<code>Network: NetworkConfig{
    Timeout:           30 * time.Second,  // 总超时时间
    ConnectTimeout:    10 * time.Second,  // 连接超时
    ReadTimeout:       20 * time.Second,  // 读取超时
    MaxRetries:        3,                 // 最大重试次数
    RetryDelay:        2 * time.Second,   // 重试延迟
    UserAgents:        []string{...},     // 用户代理列表
    ProxyURLs:         []string{...},     // 代理服务器列表
    EnableProxy:       false,             // 启用代理
    FollowRedirects:   true,              // 跟随重定向
    MaxRedirects:      5,                 // 最大重定向次数
    EnableKeepAlive:   true,              // 启用Keep-Alive
    DisableSSLVerify:  false,             // 禁用SSL验证
}
</code>

安全配置 (SecurityConfig)

<code>Security: SecurityConfig{
    AllowedFileTypes:   []string{".exe", ".dll", ".pdf"}, // 允许的文件类型
    BlockedFileTypes:   []string{".txt", ".log"},         // 禁止的文件类型
    EnableHashVerify:   true,                             // 启用哈希验证
    BlockPrivateIPs:    true,                             // 阻止私有IP
    BlockedDomains:     []string{"localhost"},            // 阻止的域名
    AllowedDomains:     []string{"trusted.com"},          // 允许的域名
    EnableAntiHoneypot: true,                             // 启用反蜜罐检测
}
</code>

并发配置 (ConcurrencyConfig)

<code>Concurrency: ConcurrencyConfig{
    MaxConcurrentDownloads: 10,           // 最大并发下载数
    MaxConnectionsPerHost:  5,            // 每个主机最大连接数
    QueueSize:              100,          // 队列大小
    WorkerPoolSize:         10,           // 工作池大小
    BatchSize:              20,           // 批处理大小
    RateLimitRPS:           10,           // 每秒请求数限制
    EnableBurstLimit:       true,         // 启用突发限制
    BurstSize:              20,           // 突发大小
    DownloadChunkSize:      64 * 1024,    // 下载块大小 (64KB)
}
</code>

高级功能

自定义HTTP客户端

<code>// 创建自定义TLS配置
tlsConfig := &amp;tls.Config{
    InsecureSkipVerify: true,
    MinVersion:         tls.VersionTLS12,
}

config.Network.TLSConfig = tlsConfig
</code>

代理配置

<code>config.Network.EnableProxy = true
config.Network.ProxyURLs = []string{
    "http://proxy1:8080",
    "http://proxy2:8080",
    "socks5://proxy3:1080",
}
config.Network.ProxyRotation = true // 启用代理轮换
</code>

文件验证

<code>// 启用哈希验证
config.Security.EnableHashVerify = true

// 创建带哈希的样本
sample := &amp;ThreatSample{
    URL:    "https://example.com/file.exe",
    MD5:    "expected_md5_hash",
    SHA1:   "expected_sha1_hash", 
    SHA256: "expected_sha256_hash",
}
</code>

监控和告警

<code>config.Monitoring = MonitoringConfig{
    EnableMetrics:        true,
    EnableLogging:        true,
    LogLevel:             "info",
    MetricsInterval:      10 * time.Second,
    EnableProgressReport: true,
    ProgressInterval:     5 * time.Second,
    EnableWebhook:        true,
    WebhookURL:           "https://your-webhook.com/alerts",
    AlertThresholds: AlertConfig{
        FailureRateThreshold:  20.0, // 失败率超过20%时告警
        DownloadTimeThreshold: 5 * time.Minute,
        QueueSizeThreshold:    80,   // 队列使用率超过80%时告警
    },
}
</code>

API 参考

主要类型

ThreatSample

威胁样本信息结构体

<code>type ThreatSample struct {
    ID          string            // 样本唯一标识
    URL         string            // 下载URL
    Filename    string            // 文件名
    MD5         string            // 期望的MD5值
    SHA1        string            // 期望的SHA1值
    SHA256      string            // 期望的SHA256值
    Size        int64             // 期望的文件大小
    ThreatType  string            // 威胁类型
    Source      string            // 来源
    Priority    int               // 优先级 (1-10, 10最高)
    Headers     map[string]string// 自定义请求头
    Tags        []string          // 标签
    CreatedTime time.Time         // 创建时间
}
</code>

DownloadTask

下载任务结构体

<code>type DownloadTask struct {
    Sample       *ThreatSample  // 威胁样本信息
    Status       DownloadStatus // 下载状态
    FilePath     string         // 本地保存路径
    ActualMD5    string         // 实际计算的MD5
    ActualSHA1   string         // 实际计算的SHA1
    ActualSHA256 string         // 实际计算的SHA256
    ActualSize   int64          // 实际文件大小
    StartTime    time.Time      // 开始时间
    EndTime      time.Time      // 结束时间
    Duration     time.Duration  // 下载耗时
    ErrorMsg     string         // 错误信息
    RetryCount   int            // 重试次数
    Downloaded   int64          // 已下载字节数
    Progress     float64        // 下载进度 (0-100)
}
</code>

DownloadStatus

下载状态枚举

<code>const (
    StatusPending     // 等待中
    StatusDownloading // 下载中
    StatusCompleted   // 已完成
    StatusFailed      // 失败
    StatusSkipped     // 跳过
    StatusTimeout     // 超时
)
</code>

主要方法

ThreatDownloader

<code>// 创建下载器
func NewThreatDownloader(config *DownloadConfig) (*ThreatDownloader, error)

// 启动下载器
func (d *ThreatDownloader) Start() error

// 停止下载器
func (d *ThreatDownloader) Stop() error

// 提交单个任务
func (d *ThreatDownloader) SubmitTask(sample *ThreatSample) (*DownloadTask, error)

// 批量提交任务
func (d *ThreatDownloader) SubmitBatch(samples []*ThreatSample) ([]*DownloadTask, error)

// 获取统计信息
func (d *ThreatDownloader) GetStats() *DownloadStats

// 注册进度回调
func (d *ThreatDownloader) RegisterCallback(name string, callback ProgressCallback)

// 取消注册回调
func (d *ThreatDownloader) UnregisterCallback(name string)
</code>

最佳实践

1. 配置优化

<code>// 根据网络环境调整超时时间
config.Network.Timeout = 60 * time.Second        // 慢速网络
config.Network.ConnectTimeout = 15 * time.Second

// 根据服务器性能调整并发数
config.Concurrency.MaxConcurrentDownloads = 20   // 高性能服务器
config.Concurrency.QueueSize = 500

// 启用压缩以节省存储空间
config.Storage.EnableCompression = true
</code>

2. 错误处理

<code>task, err := dl.SubmitTask(sample)
if err != nil {
    log.Printf("提交任务失败: %v", err)
    return
}

// 检查任务状态
if task.Status == downloader.StatusFailed {
    log.Printf("下载失败: %s", task.ErrorMsg)
}
</code>

3. 资源管理

<code>// 确保正确关闭下载器
deferfunc() {
    if err := dl.Stop(); err != nil {
        log.Printf("停止下载器失败: %v", err)
    }
}()

// 定期清理临时文件
gofunc() {
    ticker := time.NewTicker(1 * time.Hour)
    defer ticker.Stop()
    
    forrange ticker.C {
        downloader.CleanupTempFiles("./temp", 24*time.Hour)
    }
}()
</code>

4. 监控和日志

<code>// 定期输出统计信息
go func() {
    ticker := time.NewTicker(30 * time.Second)
    defer ticker.Stop()
    
    for range ticker.C {
        stats := dl.GetStats()
        log.Printf("下载统计: 完成=%d, 失败=%d, 成功率=%.1f%%",
            stats.CompletedTasks, stats.FailedTasks, stats.SuccessRate)
    }
}()
</code>

故障排除

常见问题

  1. 下载速度慢
    • 增加并发数: config.Concurrency.MaxConcurrentDownloads
    • 调整块大小: config.Concurrency.DownloadChunkSize
    • 启用Keep-Alive: config.Network.EnableKeepAlive = true
  2. 连接超时
    • 增加超时时间: config.Network.Timeout
    • 启用代理: config.Network.EnableProxy = true
    • 调整重试策略: config.Network.MaxRetries
  3. 哈希验证失败
    • 检查哈希值是否正确
    • 确认文件完整性
    • 禁用哈希验证进行测试: config.Security.EnableHashVerify = false
  4. 内存使用过高
    • 减少并发数: config.Concurrency.MaxConcurrentDownloads
    • 减小块大小: config.Concurrency.DownloadChunkSize
    • 启用临时文件清理: config.Storage.CleanupTemp = true

调试模式

<code>// 启用详细日志
config.Monitoring.EnableLogging = true
config.Monitoring.LogLevel = "debug"

// 注册调试回调
dl.RegisterCallback("debug", func(task *DownloadTask, downloaded, total int64) {
    log.Printf("[DEBUG] 任务 %s: %d/%d bytes", 
        task.Sample.ID, downloaded, total)
})
</code>

更新日志

v1.0.0

  • 初始版本发布
  • 支持并发下载
  • 实现安全检查
  • 添加进度监控
  • 完善配置系统

转自:https://mp.weixin.qq.com/s/J9PdMGQbtSqZflrCUTKDtg?mpshare=1&scene=1&srcid=1111gbgjBVl1uvT9Wr5LYknx&sharer_shareinfo=09db4797219c34b6cb6609c93bbb8d4b&sharer_shareinfo_first=09db4797219c34b6cb6609c93bbb8d4b&color_scheme=light#rd

转载请注明:jinglingshu的博客 » 威胁样本下载器 (Threat Sample Downloader)

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址