mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-22 03:10:42 +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]>
768 lines
19 KiB
Go
768 lines
19 KiB
Go
package core
|
||
|
||
import (
|
||
"crypto/tls"
|
||
"fmt"
|
||
"net"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"strconv"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/shadow1ng/fscan/common"
|
||
)
|
||
|
||
/*
|
||
web_scanner_test.go - WebScanner核心逻辑测试
|
||
|
||
注意:web_scanner.go 包含网络IO和缓存管理。
|
||
本测试文件专注于可测试的纯逻辑和算法正确性:
|
||
1. IsWebServiceByFingerprint - Web服务识别逻辑
|
||
2. createTargetFromURL - URL解析和HostInfo构建
|
||
3. 缓存操作 - MarkAsWebService, GetWebServiceInfo, IsMarkedWebService
|
||
4. 指纹缓存 - SetFingerprints, GetFingerprints
|
||
|
||
不测试的部分(需要集成测试):
|
||
- createHTTPClient - 依赖全局配置
|
||
- tryHTTP, DetectHTTPServiceOnly - 网络IO
|
||
- Execute - 完整流程
|
||
|
||
"服务识别和URL解析是纯逻辑,应该测试。
|
||
缓存操作需要验证并发安全性。"
|
||
*/
|
||
|
||
// =============================================================================
|
||
// 核心逻辑测试:Web服务识别
|
||
// =============================================================================
|
||
|
||
// TestIsWebServiceByFingerprint 测试Web服务识别逻辑
|
||
func TestIsWebServiceByFingerprint(t *testing.T) {
|
||
tests := []struct {
|
||
name string
|
||
serviceInfo *ServiceInfo
|
||
expected bool
|
||
}{
|
||
{
|
||
name: "nil服务信息",
|
||
serviceInfo: nil,
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "空服务名",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "HTTP服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "http",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "HTTPS服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "https",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Nginx服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "nginx",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Apache服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "apache",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "IIS服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "iis",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Tomcat服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "tomcat",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "MySQL服务-非Web",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "mysql",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "Redis服务-非Web",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "redis",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "SSH服务-非Web",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "ssh",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "FTP服务-非Web",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "ftp",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "大小写混合-HTTP",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "HTTP/1.1",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "包含Web关键字-http-server",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "custom-http-server",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Banner包含Server头",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "unknown",
|
||
Banner: "Server: Apache/2.4.41",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Banner包含HTTP协议",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "unknown",
|
||
Banner: "HTTP/1.1 200 OK",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Banner包含Content-Type",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "unknown",
|
||
Banner: "Content-Type: text/html",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "Banner大写-SERVER",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "unknown",
|
||
Banner: "SERVER: NGINX/1.18.0",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "非Web服务名+非Web Banner",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "telnet",
|
||
Banner: "Telnet Server Ready",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "未知服务+无Banner",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "unknown",
|
||
Banner: "",
|
||
},
|
||
expected: false,
|
||
},
|
||
{
|
||
name: "PHP服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "php",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "JSP服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "jsp",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "ASP服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "asp",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "SSL/TLS服务",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "ssl",
|
||
},
|
||
expected: true,
|
||
},
|
||
{
|
||
name: "包含非Web关键字-postgresql",
|
||
serviceInfo: &ServiceInfo{
|
||
Name: "postgresql-server",
|
||
},
|
||
expected: false,
|
||
},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
result := IsWebServiceByFingerprint(tt.serviceInfo)
|
||
if result != tt.expected {
|
||
t.Errorf("IsWebServiceByFingerprint() = %v, 期望 %v (Name=%q, Banner=%q)",
|
||
result, tt.expected, tt.serviceInfo.Name, tt.serviceInfo.Banner)
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// URL解析测试
|
||
// =============================================================================
|
||
|
||
// TestCreateTargetFromURL 测试URL解析和HostInfo构建
|
||
func TestCreateTargetFromURL(t *testing.T) {
|
||
strategy := NewWebScanStrategy()
|
||
|
||
tests := []struct {
|
||
name string
|
||
baseInfo common.HostInfo
|
||
urlStr string
|
||
expectNil bool
|
||
expectedHost string
|
||
expectedPort int
|
||
expectedURL string
|
||
}{
|
||
{
|
||
name: "完整HTTP URL",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://example.com",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 80,
|
||
expectedURL: "http://example.com",
|
||
},
|
||
{
|
||
name: "完整HTTPS URL",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "https://example.com",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 443,
|
||
expectedURL: "https://example.com",
|
||
},
|
||
{
|
||
name: "HTTP+自定义端口",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://example.com:8080",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 8080,
|
||
expectedURL: "http://example.com:8080",
|
||
},
|
||
{
|
||
name: "HTTPS+自定义端口",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "https://example.com:8443",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 8443,
|
||
expectedURL: "https://example.com:8443",
|
||
},
|
||
{
|
||
name: "无协议头-自动添加http",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "example.com",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 80,
|
||
expectedURL: "http://example.com",
|
||
},
|
||
{
|
||
name: "无协议头+端口",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "example.com:8080",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 8080,
|
||
expectedURL: "http://example.com:8080",
|
||
},
|
||
{
|
||
name: "IP地址",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://192.168.1.1",
|
||
expectNil: false,
|
||
expectedHost: "192.168.1.1",
|
||
expectedPort: 80,
|
||
expectedURL: "http://192.168.1.1",
|
||
},
|
||
{
|
||
name: "IP地址+端口",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://192.168.1.1:8080",
|
||
expectNil: false,
|
||
expectedHost: "192.168.1.1",
|
||
expectedPort: 8080,
|
||
expectedURL: "http://192.168.1.1:8080",
|
||
},
|
||
{
|
||
name: "带路径的URL",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://example.com/path/to/page",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 80,
|
||
expectedURL: "http://example.com/path/to/page",
|
||
},
|
||
{
|
||
name: "带查询参数的URL",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://example.com/?key=value",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 80,
|
||
expectedURL: "http://example.com/?key=value",
|
||
},
|
||
{
|
||
name: "继承baseInfo属性",
|
||
baseInfo: common.HostInfo{
|
||
Info: []string{"info1", "info2"},
|
||
},
|
||
urlStr: "http://example.com",
|
||
expectNil: false,
|
||
expectedHost: "example.com",
|
||
expectedPort: 80,
|
||
expectedURL: "http://example.com",
|
||
},
|
||
{
|
||
name: "非法URL-无效字符",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://example.com:abc",
|
||
expectNil: true, // 端口非法,解析失败
|
||
},
|
||
{
|
||
name: "localhost",
|
||
baseInfo: common.HostInfo{},
|
||
urlStr: "http://localhost:8080",
|
||
expectNil: false,
|
||
expectedHost: "localhost",
|
||
expectedPort: 8080,
|
||
expectedURL: "http://localhost:8080",
|
||
},
|
||
}
|
||
|
||
for _, tt := range tests {
|
||
t.Run(tt.name, func(t *testing.T) {
|
||
result := strategy.createTargetFromURL(tt.baseInfo, tt.urlStr)
|
||
|
||
// 验证是否为nil
|
||
if tt.expectNil {
|
||
if result != nil {
|
||
t.Errorf("期望返回nil, 实际返回 %+v", result)
|
||
}
|
||
return
|
||
}
|
||
|
||
if result == nil {
|
||
t.Fatal("不应返回nil")
|
||
}
|
||
|
||
// 验证Host
|
||
if result.Host != tt.expectedHost {
|
||
t.Errorf("Host = %q, 期望 %q", result.Host, tt.expectedHost)
|
||
}
|
||
|
||
// 验证Ports
|
||
if result.Port != tt.expectedPort {
|
||
t.Errorf("Port = %d, 期望 %d", result.Port, tt.expectedPort)
|
||
}
|
||
|
||
// 验证Url
|
||
if result.URL != tt.expectedURL {
|
||
t.Errorf("URL = %q, 期望 %q", result.URL, tt.expectedURL)
|
||
}
|
||
|
||
// 验证baseInfo属性继承
|
||
if len(tt.baseInfo.Info) > 0 {
|
||
if len(result.Info) != len(tt.baseInfo.Info) {
|
||
t.Errorf("Infostr未继承, 长度 = %d, 期望 %d",
|
||
len(result.Info), len(tt.baseInfo.Info))
|
||
}
|
||
}
|
||
})
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// 缓存管理测试
|
||
// =============================================================================
|
||
|
||
// TestWebServiceCache 测试Web服务缓存操作
|
||
func TestWebServiceCache(t *testing.T) {
|
||
// 清空缓存
|
||
webCacheMutex.Lock()
|
||
webServiceCache = make(map[string]*ServiceInfo)
|
||
webCacheMutex.Unlock()
|
||
|
||
t.Run("存储和读取", func(t *testing.T) {
|
||
serviceInfo := &ServiceInfo{
|
||
Name: "http",
|
||
Banner: "Apache/2.4.41",
|
||
}
|
||
|
||
// 标记Web服务
|
||
MarkAsWebService("192.168.1.1", 80, serviceInfo)
|
||
|
||
// 验证IsMarkedWebService
|
||
if !IsMarkedWebService("192.168.1.1", 80) {
|
||
t.Error("IsMarkedWebService应返回true")
|
||
}
|
||
|
||
// 验证GetWebServiceInfo
|
||
info, exists := GetWebServiceInfo("192.168.1.1", 80)
|
||
if !exists {
|
||
t.Error("GetWebServiceInfo应返回exists=true")
|
||
}
|
||
if info.Name != "http" {
|
||
t.Errorf("Name = %q, 期望 'http'", info.Name)
|
||
}
|
||
})
|
||
|
||
t.Run("不存在的服务", func(t *testing.T) {
|
||
if IsMarkedWebService("192.168.1.2", 80) {
|
||
t.Error("不存在的服务应返回false")
|
||
}
|
||
|
||
info, exists := GetWebServiceInfo("192.168.1.2", 80)
|
||
if exists {
|
||
t.Error("不存在的服务应返回exists=false")
|
||
}
|
||
if info != nil {
|
||
t.Error("不存在的服务应返回nil info")
|
||
}
|
||
})
|
||
|
||
t.Run("覆盖写入", func(t *testing.T) {
|
||
serviceInfo1 := &ServiceInfo{Name: "http"}
|
||
serviceInfo2 := &ServiceInfo{Name: "https"}
|
||
|
||
MarkAsWebService("192.168.1.3", 80, serviceInfo1)
|
||
MarkAsWebService("192.168.1.3", 80, serviceInfo2)
|
||
|
||
info, _ := GetWebServiceInfo("192.168.1.3", 80)
|
||
if info.Name != "https" {
|
||
t.Errorf("覆盖后Name = %q, 期望 'https'", info.Name)
|
||
}
|
||
})
|
||
|
||
t.Run("不同端口独立存储", func(t *testing.T) {
|
||
serviceInfo80 := &ServiceInfo{Name: "http"}
|
||
serviceInfo443 := &ServiceInfo{Name: "https"}
|
||
|
||
MarkAsWebService("192.168.1.4", 80, serviceInfo80)
|
||
MarkAsWebService("192.168.1.4", 443, serviceInfo443)
|
||
|
||
info80, _ := GetWebServiceInfo("192.168.1.4", 80)
|
||
info443, _ := GetWebServiceInfo("192.168.1.4", 443)
|
||
|
||
if info80.Name != "http" {
|
||
t.Errorf("端口80的Name = %q, 期望 'http'", info80.Name)
|
||
}
|
||
if info443.Name != "https" {
|
||
t.Errorf("端口443的Name = %q, 期望 'https'", info443.Name)
|
||
}
|
||
})
|
||
}
|
||
|
||
// TestWebServiceCache_Concurrent 测试并发安全性
|
||
func TestWebServiceCache_Concurrent(t *testing.T) {
|
||
// 清空缓存
|
||
webCacheMutex.Lock()
|
||
webServiceCache = make(map[string]*ServiceInfo)
|
||
webCacheMutex.Unlock()
|
||
|
||
t.Run("不同key并发写入", func(t *testing.T) {
|
||
var wg sync.WaitGroup
|
||
numGoroutines := 100
|
||
|
||
// 并发写入不同端口
|
||
for i := 0; i < numGoroutines; i++ {
|
||
wg.Add(1)
|
||
go func(id int) {
|
||
defer wg.Done()
|
||
serviceInfo := &ServiceInfo{
|
||
Name: "http",
|
||
}
|
||
MarkAsWebService("192.168.1.1", id, serviceInfo)
|
||
}(i)
|
||
}
|
||
|
||
wg.Wait()
|
||
|
||
// 验证数据完整性
|
||
for i := 0; i < numGoroutines; i++ {
|
||
if !IsMarkedWebService("192.168.1.1", i) {
|
||
t.Errorf("端口 %d 应被标记", i)
|
||
}
|
||
}
|
||
})
|
||
|
||
t.Run("同一key并发读写", func(t *testing.T) {
|
||
// 这才是真正的race condition测试
|
||
var wg sync.WaitGroup
|
||
numGoroutines := 100
|
||
const testHost = "192.168.1.100"
|
||
const testPort = 80
|
||
|
||
// 同时读写同一个key
|
||
for i := 0; i < numGoroutines; i++ {
|
||
wg.Add(2)
|
||
|
||
// 写goroutine
|
||
go func(id int) {
|
||
defer wg.Done()
|
||
serviceInfo := &ServiceInfo{
|
||
Name: "http",
|
||
Banner: fmt.Sprintf("writer-%d", id),
|
||
}
|
||
MarkAsWebService(testHost, testPort, serviceInfo)
|
||
}(i)
|
||
|
||
// 读goroutine
|
||
go func() {
|
||
defer wg.Done()
|
||
info, exists := GetWebServiceInfo(testHost, testPort)
|
||
// 不验证具体内容(因为写入顺序不确定)
|
||
// 只验证不会panic或返回不一致的exists/info
|
||
if exists && info == nil {
|
||
t.Error("exists=true但info=nil,数据不一致")
|
||
}
|
||
}()
|
||
}
|
||
|
||
wg.Wait()
|
||
|
||
// 验证最终状态一致
|
||
info, exists := GetWebServiceInfo(testHost, testPort)
|
||
if !exists {
|
||
t.Error("应该至少有一次写入成功")
|
||
}
|
||
if info == nil {
|
||
t.Error("exists=true但info=nil")
|
||
}
|
||
})
|
||
}
|
||
|
||
// =============================================================================
|
||
// 指纹缓存测试
|
||
// =============================================================================
|
||
|
||
// =============================================================================
|
||
// 边界情况测试
|
||
// =============================================================================
|
||
|
||
// TestCreateTargetFromURL_EdgeCases 测试URL解析边界情况
|
||
func TestCreateTargetFromURL_EdgeCases(t *testing.T) {
|
||
strategy := NewWebScanStrategy()
|
||
|
||
t.Run("空URL", func(t *testing.T) {
|
||
result := strategy.createTargetFromURL(common.HostInfo{}, "")
|
||
// url.Parse("")会成功,但Hostname()返回空
|
||
if result == nil {
|
||
t.Skip("空URL解析行为依赖于url.Parse实现")
|
||
}
|
||
})
|
||
|
||
t.Run("只有协议", func(t *testing.T) {
|
||
result := strategy.createTargetFromURL(common.HostInfo{}, "http://")
|
||
// url.Parse("http://")会成功,但Host为空
|
||
if result != nil && result.Host == "" {
|
||
t.Log("Empty host check passed as expected")
|
||
}
|
||
})
|
||
|
||
t.Run("特殊字符URL", func(t *testing.T) {
|
||
result := strategy.createTargetFromURL(common.HostInfo{}, "http://例子.com")
|
||
// 中文域名可能成功解析(IDN)
|
||
if result == nil {
|
||
t.Log("中文域名解析失败(预期行为)")
|
||
}
|
||
})
|
||
|
||
t.Run("IPv6地址", func(t *testing.T) {
|
||
result := strategy.createTargetFromURL(common.HostInfo{}, "http://[::1]:8080")
|
||
if result == nil {
|
||
t.Error("IPv6地址应能正确解析")
|
||
} else {
|
||
if result.Host != "::1" {
|
||
t.Errorf("IPv6 Host = %q, 期望 '::1'", result.Host)
|
||
}
|
||
if result.Port != 8080 {
|
||
t.Errorf("IPv6 Ports = %q, 期望 '8080'", result.Port)
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
// TestIsWebServiceByFingerprint_Priority 测试识别优先级
|
||
func TestIsWebServiceByFingerprint_Priority(t *testing.T) {
|
||
t.Run("非Web服务名优先级高于Web Banner", func(t *testing.T) {
|
||
// 服务名是mysql,但Banner包含Web特征
|
||
serviceInfo := &ServiceInfo{
|
||
Name: "mysql",
|
||
Banner: "Server: Apache",
|
||
}
|
||
result := IsWebServiceByFingerprint(serviceInfo)
|
||
if result {
|
||
t.Error("非Web服务名应优先,即使Banner包含Web特征")
|
||
}
|
||
})
|
||
|
||
t.Run("Web服务名优先级高于非Web Banner", func(t *testing.T) {
|
||
serviceInfo := &ServiceInfo{
|
||
Name: "http",
|
||
Banner: "MySQL Server Ready",
|
||
}
|
||
result := IsWebServiceByFingerprint(serviceInfo)
|
||
if !result {
|
||
t.Error("Web服务名应优先,即使Banner包含非Web特征")
|
||
}
|
||
})
|
||
}
|
||
|
||
// =============================================================================
|
||
// 协议检测测试
|
||
// =============================================================================
|
||
|
||
// TestDetectHTTPScheme 测试HTTP/HTTPS协议智能检测
|
||
func TestDetectHTTPScheme(t *testing.T) {
|
||
// 设置WebTimeout避免测试超时
|
||
cfg := common.GetGlobalConfig()
|
||
oldTimeout := cfg.Network.WebTimeout
|
||
cfg.Network.WebTimeout = 2 * time.Second
|
||
defer func() { cfg.Network.WebTimeout = oldTimeout }()
|
||
|
||
session := common.NewScanSession(cfg, common.NewState(), common.GetFlagVars())
|
||
|
||
t.Run("HTTPS服务器检测", func(t *testing.T) {
|
||
// 创建HTTPS测试服务器
|
||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(http.StatusOK)
|
||
}))
|
||
defer server.Close()
|
||
|
||
// 解析服务器地址
|
||
host, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
|
||
if err != nil {
|
||
t.Fatalf("解析服务器地址失败: %v", err)
|
||
}
|
||
port, _ := strconv.Atoi(portStr)
|
||
|
||
// 测试检测
|
||
result := DetectHTTPScheme(host, port, cfg, session)
|
||
if result != "https" {
|
||
t.Errorf("DetectHTTPScheme() = %q, 期望 'https'", result)
|
||
}
|
||
})
|
||
|
||
t.Run("HTTP服务器检测", func(t *testing.T) {
|
||
// 创建HTTP测试服务器
|
||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(http.StatusOK)
|
||
}))
|
||
defer server.Close()
|
||
|
||
// 解析服务器地址
|
||
host, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
|
||
if err != nil {
|
||
t.Fatalf("解析服务器地址失败: %v", err)
|
||
}
|
||
port, _ := strconv.Atoi(portStr)
|
||
|
||
// 测试检测
|
||
result := DetectHTTPScheme(host, port, cfg, session)
|
||
if result != "http" {
|
||
t.Errorf("DetectHTTPScheme() = %q, 期望 'http'", result)
|
||
}
|
||
})
|
||
|
||
t.Run("不存在的服务", func(t *testing.T) {
|
||
// 使用127.0.0.1的一个未使用端口
|
||
result := DetectHTTPScheme("127.0.0.1", 65534, cfg, session)
|
||
if result != "" {
|
||
t.Errorf("不存在的服务应返回空字符串, 实际 %q", result)
|
||
}
|
||
})
|
||
|
||
t.Run("非Web服务端口", func(t *testing.T) {
|
||
// 创建一个TCP监听器但不响应HTTP
|
||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||
if err != nil {
|
||
t.Skipf("无法创建监听器: %v", err)
|
||
}
|
||
defer func() { _ = listener.Close() }()
|
||
|
||
// 启动一个接受连接但立即关闭的goroutine
|
||
go func() {
|
||
for {
|
||
conn, err := listener.Accept()
|
||
if err != nil {
|
||
return
|
||
}
|
||
conn.Close()
|
||
}
|
||
}()
|
||
|
||
// 解析端口
|
||
_, portStr, _ := net.SplitHostPort(listener.Addr().String())
|
||
port, _ := strconv.Atoi(portStr)
|
||
|
||
// 测试检测
|
||
result := DetectHTTPScheme("127.0.0.1", port, cfg, session)
|
||
if result != "" {
|
||
t.Logf("非Web服务检测返回: %q (预期空字符串,但立即关闭连接可能被误判)", result)
|
||
}
|
||
})
|
||
|
||
t.Run("TLS版本兼容性", func(t *testing.T) {
|
||
// 测试TLS 1.0兼容性(DetectHTTPScheme设置MinVersion为TLS 1.0)
|
||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(http.StatusOK)
|
||
}))
|
||
server.TLS = &tls.Config{
|
||
MinVersion: tls.VersionTLS10,
|
||
MaxVersion: tls.VersionTLS10,
|
||
}
|
||
server.StartTLS()
|
||
defer server.Close()
|
||
|
||
host, portStr, _ := net.SplitHostPort(server.Listener.Addr().String())
|
||
port, _ := strconv.Atoi(portStr)
|
||
|
||
result := DetectHTTPScheme(host, port, cfg, session)
|
||
if result != "https" {
|
||
t.Errorf("TLS 1.0服务器应被检测为https, 实际 %q", result)
|
||
}
|
||
})
|
||
}
|