mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-23 03:31:53 +08:00
* feat: v2.1.0 核心重构与功能增强
## 架构重构
- 全局变量消除,迁移至 Config/State 对象
- SMB 插件融合(smb/smb2/smbghost/smbinfo)
- 服务探测重构,实现 Nmap 风格 fallback 机制
- 输出系统重构,TXT 实时刷盘 + 双写机制
- i18n 框架升级至 go-i18n
## 性能优化
- 正则表达式预编译
- 内存优化 map[string]struct{}
- 并发指纹匹配
- SOCKS5 连接复用
- 滑动窗口调度 + 自适应线程池
## 新功能
- Web 管理界面
- 多格式 POC 适配(xray/afrog)
- 增强指纹库(3139条)
- Favicon hash 指纹识别
- 插件选择性编译(Build Tags)
- fscan-lab 靶场环境
- 默认端口扩展(62→133)
## 构建系统
- 添加 no_local tag 支持排除本地插件
- 多版本构建:fscan/fscan-nolocal/fscan-web
- CI 添加 snapshot 模式支持仅测试构建
## Bug 修复
- 修复 120+ 个问题,包括 RDP panic、批量扫描漏报、
JSON 输出格式、Redis 检测、Context 超时等
## 测试增强
- 单元测试覆盖率 74-100%
- 并发安全测试
- 集成测试(Web/端口/服务/SSH/ICMP)
* fix(ci): 移除 PR 对 Project 自动化的触发
* fix: Elasticsearch未授权检测优先于爆破 (#554)
* fix: 修复RDP爆破高误报率问题 (#555)
- 移除 screen.go 中错误的认证结果覆盖逻辑
- 启用 NLA 协议的 ErrorCode 字段检测
- 添加 PubKeyAuth 验证确保认证真正成功
- 修复 io.go 中错误被静默忽略的问题
- 修复 socket.go/io.go 中可能导致 panic 的代码
- 修复 screen.go 中文件句柄泄漏和 log.Panic
* fix: 修复-user/-pwd凭据参数不生效的问题
问题原因:
- Parse()解析凭据后更新globalConfig
- 但BuildConfigFromFlags()创建新Config时使用默认字典
- 导致解析的UserPassPairs等凭据信息被丢弃
修复内容:
1. initialize.go: 将Parse解析的凭据结果应用到新Config
2. credential.go: 单用户密码对时创建UserPassPairs
3. rdp.go: 单凭据测试时跳过指纹识别,减少连接次数
* feat: RDP使用NLA仅验证模式,避免挤掉已登录用户
- 添加ErrNLAAuthSuccess标志用于NLA验证成功信号
- tpkt层支持nlaAuthOnly模式,验证成功后不建立完整会话
- x224层正确传播NLA验证结果
- rdpCrack改用NlaAuth进行凭据验证
* fix: 修复进度条在Windows终端满屏重复输出的问题
- 添加终端宽度检测,动态调整进度条长度
- 使用空格覆盖清除旧内容,避免残留
- 简化进度条格式,确保不超过终端宽度
* feat: 优化日志颜色方案,区分漏洞和普通信息
- 新增 LogVuln 级别(红色),用于漏洞和重要发现
- 密码爆破成功、未授权访问、POC漏洞等改用红色显示
- 普通信息(扫描统计等)改为白色
- Web指纹保持绿色
* refactor: 精简化输出,移除冗余启动信息
- 移除showParseSummary开局配置输出
- 移除LogPluginInfo/LogPluginInfoWithPort插件信息输出
- 移除alive_scanner冗余统计输出
- 移除port_scan_start扫描开始提示
- 移除handleUDPPorts SNMP死代码
- 移除相关i18n条目
* chore: 版本号更新为2.1.1
* fix: 降级依赖版本以保持Go 1.20兼容性
* feat(ldap): 添加NTLM Hash认证支持 (#433)
* chore: 清理无用的 replace 指令
* fix(ping): 修复 TTL expired 导致主机误判为存活的问题
在 ExecCommandPing 中增加错误关键词检测,当 ping 输出包含
TTL expired、Destination unreachable 等错误信息时,不再将
目标主机标记为存活。
Fixes #454
* fix(proxy): 修复透明代理导致输出全端口的问题
在代理初始化时主动探测代理行为,通过连接 RFC 5737 保留的
测试地址来检测是否存在"全回显"问题。如果探测到代理不可靠,
则在端口扫描时跳过所有端口,避免误报。
- 新增 proxyReliable 标志位标记代理可靠性
- 新增 ProbeProxyBehavior 函数探测代理行为
- 端口扫描前检查代理可靠性并输出警告
Fixes #495
* refactor: 移动debug模块到common/debug子包
* fix(web): 修复-u模式下Web插件未执行的问题
* fix: 优化输出格式和颜色显示
- 网段统计格式改为 10.253.0.0/16 网段存活: 26
- WebTitle基础信息改为白色,指纹识别单独绿色输出
- 移除重复的端口数量输出
* fix: URL解析自动补全协议头
-uf 文件中 192.168.1.1:8080 自动转为 http://192.168.1.1:8080
* fix: 修复-u/-uf模式下URLs丢失导致0目标扫描的问题
Parse阶段将URLs设置到全局状态,但Initialize随后创建新状态
并覆盖了全局状态,导致URLs数据丢失。现在在创建新状态前
先保存并迁移Parse阶段设置的URLs和HostPorts数据。
* fix: 智能检测HTTP/HTTPS协议并优化URL显示
- 修复-u/-uf模式URLs丢失导致0目标扫描问题
- detectProtocol改为主动TLS握手检测,不依赖服务名
- WebTitle输出显示完整协议(http/https)
- 隐藏标准端口(80/443)使输出更简洁
* refactor: 精简parsers包,统一配置构建入口
- 删除冗余的中间层(XXXInput、XXXParser类)
- 新增 config_builder.go 统一配置构建
- parsers包从3000+行精简至~540行
- 保留核心函数:ParseIP、ParsePort、文件读取、凭据解析
* test: 扩展parsers单元测试覆盖边缘情况
- 新增内网简写解析测试(192/172/10)
- 新增完整IP范围和无效CIDR测试
- 新增Windows行尾(CRLF)处理测试
- 新增凭据和哈希文件解析测试
- 新增端口解析边缘情况测试
- 测试覆盖率达到94.2%
* refactor: 优化控制台输出格式
- 去掉时间戳,保留[*][+]前缀
- Web输出合并WebTitle和WebFinger为一行
- 有指纹显示绿色[+],无指纹显示白色[*]
- 格式: code:xxx len:xxx title:xxx server:xxx [指纹]
- 服务探测格式: [Product:xxx ||Version:xxx] Banner:(xxx)
- 字段对齐,输出更清爽
* feat: 添加凭据测试未发现弱密码的提示
- credential_tester.go: 失败时设置 Type=ResultTypeCredential
- scanner.go: 根据结果类型在 error 级别输出'未发现弱密码'提示
- 新增 i18n 翻译 brute_no_weak_pass
使用 -log all 或 -log error 可看到此提示
* refactor(logging): 重构日志级别为层级过滤设计
- LogLevel 从 string 改为 int 类型,支持层级比较
- 层级设计:Debug(0) < Base(1) < Info(2) < Success(3) < Vuln(4) < Error(5)
- 设置一个级别后,显示该级别及以上的日志
- Error 级别始终显示,不会被配置过滤掉
- 保留向后兼容别名(LevelAll, LevelInfoSuccess 等)
- 更新测试以匹配新的层级过滤行为
* style(logging): Error级别日志改为黄色显示
* style(findnet): NetInfo输出改为每行一个IP
* refactor(ms17010): 优化错误提示,明确指出SMBv1不支持等情况
* fix(credential): 修复凭据测试结果不一致的问题
问题原因:
1. 未知错误类型不重试,导致服务端限流时跳过正确密码
2. SSH 错误分类不够准确,某些临时错误未被识别
修复内容:
1. 未知错误改为可重试(可能是临时问题)
2. 增加 SSH 特有的网络错误识别(handshake failed, disconnect 等)
* fix(portfinger): 修复SMB2服务指纹识别和NetInfo输出问题
- 添加SMB2ProgNeg探针支持现代Windows的SMB2协议
- 修复Go regexp对高位字节的UTF-8兼容问题,使用Latin-1转换
- 修复探针失败后连接重建逻辑
- 修复vendor_product字段名不匹配问题
- 修复NetInfo多行输出被其他日志打断的问题
* fix(config): 从默认端口移除9100,避免触发打印机打印 (#517)
* feat(proxy): 增强代理端口扫描的深度验证机制
- 新增4阶段深度验证:Banner读取→探测发送→响应等待→最终判定
- 新增SOCKS5错误码和代理错误文本检测
- 优化ProbeProxyBehavior探测逻辑,发送数据验证连接可达性
- 解决透明代理/全回显代理导致的假阳性问题
* fix(proxy): 修复代理深度验证的若干问题
- detector.go: 修复 AutoConfigureProxy 覆盖探测结果的问题
只有未探测过时才设置默认 proxyReliable 值
- port_scan.go: 改进深度验证机制
- 使用带 Host header 的 HTTP GET 请求替代 OPTIONS
- 延长响应等待超时至 2s 以适配慢速服务器
- 正确重置连接 deadline 避免影响后续操作
* refactor: 统一 common 包文件命名风格
Flag.go -> flag.go
* refactor(proxy): 删除自定义 contains() 函数,改用标准库
- 用 strings.Contains() 替代手写的 contains()
- 删除过时的注释
* fix(parsers): 修复带横杠域名被误识别为IP范围的问题
如 111-555.sss.com 这类域名因包含 - 被错误解析为 IP 范围,
添加 looksLikeIPRange() 检查,只有 - 前是有效 IP 才走范围解析
* fix(proxy): 修复代理模式下服务识别错误和端口漏扫问题
- port_scan.go: 验证通过后重建干净连接,避免HTTP GET探测污染服务识别
- port_scan.go: 优化验证策略,用轻量CRLF探测替代HTTP GET,超时从2.2s降至0.6s
- manager.go: 修正ProbeProxyBehavior判断逻辑,超时应视为代理正常转发
* fix(pool): 移除线程池预分配,优化大规模扫描内存占用
WithPreAlloc(true) 会预先创建所有 worker goroutine,
在大规模扫描(如 25域名×65535端口)时可能导致内存问题
* refactor(logging): 统一日志前缀,删除废弃的 LogBase
- 删除 LogBase 函数,所有调用迁移到 LogInfo/LogError
- 新增 PrefixDebug ([.]) 前缀,所有日志级别现在都有前缀
- 修复日志输出缩进不一致的问题
- 删除未使用的 PrefixDefault 常量
* perf(icmp): 实现自适应等待算法优化存活检测性能
- 新增 waitAdaptive 函数,监控响应增量实现智能提前结束
- 算法保守原则:最小等待1s + 连续500ms无新响应才提前结束
- 添加100ms检查间隔避免CPU空转
- 保留原有最大等待时间(3s/6s)作为兜底
- 添加完整单元测试覆盖各种场景
优化效果:
- 全部响应:~100ms (原3s)
- 无响应:~1s (原3s)
- 部分响应后稳定:~1.5s (原3s)
* perf(scan): 实现启发式优化提升扫描体验
1. 端口优先级排序:高价值端口(80,443,22,3389等)优先扫描
- 用户能更快看到有意义的结果
- 不影响端口喷洒策略
2. TCP 补充探测:ICMP 响应率<10%时自动启用
- 对未响应主机用 TCP 80/443/22/445 补充探测
- 解决防火墙过滤 ICMP 导致漏检的问题
* refactor(grdp): 精简RDP库,删除认证检测不需要的代码
- 删除 VNC 协议支持 (protocol/rfb, client/rfb.go)
- 删除完整客户端框架 (client/)
- 删除 RemoteApp 等插件 (plugin/)
- 删除 RLE 图形解压 (core/rle.go)
- 删除绘图指令处理 (pdu/orders.go, pdu/gdi.go)
- 精简 screen.go,移除截图和完整会话功能
- 移除未使用的 RGB 转换函数
grdp 代码从 13,044 行精简至 7,581 行,削减 42%
* refactor(common): 删除死代码,优化代码风格
- 删除未使用的 joinStrings/joinInts 函数
- 删除未使用的 memStats 字段和 getMemoryInfo 方法
- 简化 parsePasswords 中的循环为 append(...) 形式
* refactor(services): 统一数据库插件的DBWrapper
4个数据库插件(MySQL、PostgreSQL、MSSQL、Oracle)都有相同的sql.DB包装代码,
合并为通用的SQLDBWrapper,减少重复。
* refactor(core,grdp): 删除未使用的死代码
- 移除 BaseScanStrategy.LogPluginInfoWithPort 方法(无调用者)
- 移除 mcs.go 中被注释的旧 connect 函数实现
* refactor: 删除 deadcode 检测出的未使用函数
- proxy/detector.go: 删除 IsSOCKS5Standard, IsProxyInitialized
- findnet.go: 删除 NetworkInfo.OneLine, TreeFormat 方法
- port_scan.go: 删除 estimateScanTime 函数
- web_scanner.go: 删除 GetFingerprints 函数
- 清理相关测试代码
* refactor: 删除更多未使用的死代码
- parse.go: 删除 RemoveDuplicate 函数及其测试
- parsers.go: 删除 excludeHosts, removeDuplicates 别名函数
- 更新测试使用真正的函数名
* fix(test): 修复 TestParseIP_InvalidIPRange 测试用例
- 删除不合理的测试用例(无效IP被当作普通主机名处理是设计行为)
- 修复测试逻辑,只在真正通过时输出"正确"
* fix(scan): 移除域名预解析,保留原始域名进行扫描
域名预解析会将域名转换为IP,导致虚拟主机场景下HTTP访问失败
(Host头变成IP而非域名,无法正确路由)
* fix(scan): 修复 -hf 参数无法单独使用的问题
* fix(proxy): 修复透明代理环境下 SOCKS5 代理全端口误报问题
问题:在透明代理(TUN模式)环境下使用 SOCKS5 代理扫描时,
会出现全端口开放的误报,因为代理可靠性检测被透明代理污染。
修复方案(参考 fscanx):
1. 将探针从 CRLF 改为 HTTP GET,更有效检测真实连接状态
2. 删除 "uncertain" 状态,无响应一律判定为端口关闭
3. 调整超时时间以适应代理链路延迟
Fixes #524
* feat(telnet): 新增 telnetd RCE 命令执行验证,修复未授权访问日志级别
* fix: 修复 i18n.Tr vet 报错、Unicode 测试用例,移除过期域名
- 移除 i18n.Tr 中错误的 fmt.Sprintf fallback,消除 go vet 误报
- 修复 match_engine_test Unicode 测试用例与 Latin-1 转换逻辑不匹配
- README 移除过期的 fscan.club 域名
- 添加 .gitattributes 统一换行符为 LF
* refactor: 统一控制台输出风格,使用统一的日志函数
手动合并 PR #558 的改动,适配重构后的代码路径
* fix(ci): 修复版本注入和CI触发配置
- goreleaser ldflags 指向正确的包路径 common.version/commit/date
- version 改为 var 支持 ldflags 注入,banner 显示 commit 和构建日期
- test-build 触发分支增加 dev-* 通配
* fix(ci): 修复 Windows 产物 .exe.exe 双后缀问题
* feat(ci): 扩展构建架构支持 MIPS/ARM/FreeBSD/Solaris
1296 lines
30 KiB
Go
1296 lines
30 KiB
Go
package parsers
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"sort"
|
|
"testing"
|
|
)
|
|
|
|
/*
|
|
parse_test.go - 简化解析器测试
|
|
|
|
测试目标:ParseIP和ParsePort两个核心解析函数
|
|
价值:解析错误会导致:
|
|
- 错误的扫描目标(用户扫描了错误的主机)
|
|
- 错误的端口范围(遗漏关键服务)
|
|
- 性能问题(重复目标导致浪费)
|
|
|
|
"解析器是扫描器的入口。解析错误=整个扫描就是错的。
|
|
端口范围解析bug会让用户遗漏漏洞。这是真实问题。"
|
|
*/
|
|
|
|
// =============================================================================
|
|
// ParsePort - 端口解析测试
|
|
// =============================================================================
|
|
|
|
// TestParsePort_Empty 测试空字符串
|
|
//
|
|
// 验证:空输入返回nil而不是空切片
|
|
//
|
|
// empty slice表示'有数据但是空的'。这个区别很重要。"
|
|
func TestParsePort_Empty(t *testing.T) {
|
|
result := ParsePort("")
|
|
|
|
if result != nil {
|
|
t.Errorf("ParsePort(\"\") = %v, want nil", result)
|
|
}
|
|
|
|
t.Logf("✓ 空字符串正确返回nil")
|
|
}
|
|
|
|
// TestParsePort_SinglePort 测试单个端口
|
|
func TestParsePort_SinglePort(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{"HTTP", "80", []int{80}},
|
|
{"HTTPS", "443", []int{443}},
|
|
{"SSH", "22", []int{22}},
|
|
{"MinPort", "1", []int{1}},
|
|
{"MaxPort", "65535", []int{65535}},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) → %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_MultiplePorts 测试多个端口
|
|
func TestParsePort_MultiplePorts(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"Web端口",
|
|
"80,443,8080",
|
|
[]int{80, 443, 8080},
|
|
},
|
|
{
|
|
"数据库端口",
|
|
"3306,5432,27017",
|
|
[]int{3306, 5432, 27017},
|
|
},
|
|
{
|
|
"带空格",
|
|
" 80 , 443 , 8080 ",
|
|
[]int{80, 443, 8080},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) → %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_PortRange 测试端口范围
|
|
//
|
|
// 验证:范围解析正确,包含起始和结束端口
|
|
//
|
|
// 1-5应该是[1,2,3,4,5]还是[1,2,3,4]?搞错了就是bug。"
|
|
func TestParsePort_PortRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"小范围",
|
|
"1-5",
|
|
[]int{1, 2, 3, 4, 5},
|
|
},
|
|
{
|
|
"HTTP备用端口",
|
|
"8000-8003",
|
|
[]int{8000, 8001, 8002, 8003},
|
|
},
|
|
{
|
|
"单端口范围",
|
|
"80-80",
|
|
[]int{80},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) → %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_MixedFormat 测试混合格式
|
|
func TestParsePort_MixedFormat(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"端口+范围",
|
|
"80,100-102,443",
|
|
[]int{80, 100, 101, 102, 443},
|
|
},
|
|
{
|
|
"多个范围",
|
|
"1-3,10-12",
|
|
[]int{1, 2, 3, 10, 11, 12},
|
|
},
|
|
{
|
|
"复杂混合",
|
|
"22,80-82,443,8000-8001",
|
|
[]int{22, 80, 81, 82, 443, 8000, 8001},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) → %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_InvalidRange 测试无效范围
|
|
//
|
|
// 验证:无效范围被正确过滤
|
|
func TestParsePort_InvalidRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"反向范围",
|
|
"100-50",
|
|
nil,
|
|
},
|
|
{
|
|
"超出上限起始",
|
|
"65536-65540",
|
|
nil,
|
|
},
|
|
{
|
|
"低于下限",
|
|
"0-5",
|
|
nil,
|
|
},
|
|
{
|
|
"无效格式",
|
|
"80-90-100",
|
|
nil,
|
|
},
|
|
{
|
|
"非数字",
|
|
"abc-xyz",
|
|
nil,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确拒绝无效范围", tt.input)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_OutOfRange 测试超出范围的端口
|
|
func TestParsePort_OutOfRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"端口0",
|
|
"0",
|
|
nil,
|
|
},
|
|
{
|
|
"端口65536",
|
|
"65536",
|
|
nil,
|
|
},
|
|
{
|
|
"混合有效和无效",
|
|
"0,80,443,65536",
|
|
[]int{80, 443},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确过滤无效端口", tt.input)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_Deduplicate 测试去重
|
|
//
|
|
// 验证:重复端口被去重,结果已排序
|
|
func TestParsePort_Deduplicate(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"简单重复",
|
|
"80,80,80",
|
|
[]int{80},
|
|
},
|
|
{
|
|
"多个重复",
|
|
"80,443,80,22,443",
|
|
[]int{22, 80, 443},
|
|
},
|
|
{
|
|
"范围重复",
|
|
"1-3,2-4",
|
|
[]int{1, 2, 3, 4},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
// 验证已排序
|
|
if !sort.IntsAreSorted(result) {
|
|
t.Errorf("ParsePort(%q) 结果未排序: %v", tt.input, result)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确去重并排序 → %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_Sorted 测试排序
|
|
func TestParsePort_Sorted(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
}{
|
|
{"乱序端口", "8080,22,443,80"},
|
|
{"乱序范围", "1000-1002,80-82"},
|
|
{"混合乱序", "443,100-102,22,80"},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !sort.IntsAreSorted(result) {
|
|
t.Errorf("ParsePort(%q) 结果未排序: %v", tt.input, result)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 结果已排序: %v", tt.input, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_PortGroups 测试端口组展开
|
|
//
|
|
// 验证:预定义端口组被正确展开
|
|
func TestParsePort_PortGroups(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
shouldContain []int
|
|
shouldNotBeNil bool
|
|
}{
|
|
{
|
|
"web组",
|
|
"web",
|
|
[]int{80, 443, 8080, 8443},
|
|
true,
|
|
},
|
|
{
|
|
"all组",
|
|
"all",
|
|
[]int{1, 100, 1000, 10000, 65535},
|
|
true,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if tt.shouldNotBeNil && result == nil {
|
|
t.Errorf("ParsePort(%q) = nil, want non-nil", tt.input)
|
|
return
|
|
}
|
|
|
|
// 验证包含特定端口
|
|
resultMap := make(map[int]bool)
|
|
for _, port := range result {
|
|
resultMap[port] = true
|
|
}
|
|
|
|
for _, port := range tt.shouldContain {
|
|
if !resultMap[port] {
|
|
t.Errorf("ParsePort(%q) 应该包含端口 %d,但不包含", tt.input, port)
|
|
}
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确展开端口组(%d个端口)", tt.input, len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParsePort_WhitespaceHandling 测试空格处理
|
|
func TestParsePort_WhitespaceHandling(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{
|
|
"端口前后空格",
|
|
" 80 , 443 ",
|
|
[]int{80, 443},
|
|
},
|
|
{
|
|
"范围中的空格",
|
|
" 1 - 3 ",
|
|
[]int{1, 2, 3},
|
|
},
|
|
{
|
|
"混合空格",
|
|
" 80 , 100 - 102 , 443 ",
|
|
[]int{80, 100, 101, 102, 443},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确处理空格", tt.input)
|
|
})
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// ParseIP - IP解析测试
|
|
// =============================================================================
|
|
|
|
// TestParseIP_SingleIP 测试单个IP
|
|
func TestParseIP_SingleIP(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
host string
|
|
expected []string
|
|
}{
|
|
{
|
|
"IPv4",
|
|
"192.168.1.1",
|
|
[]string{"192.168.1.1"},
|
|
},
|
|
{
|
|
"域名",
|
|
"example.com",
|
|
[]string{"example.com"},
|
|
},
|
|
{
|
|
"带横杠的域名",
|
|
"111-555.sss.com",
|
|
[]string{"111-555.sss.com"},
|
|
},
|
|
{
|
|
"多段横杠域名",
|
|
"my-test-server.example.com",
|
|
[]string{"my-test-server.example.com"},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.host, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.host, err)
|
|
}
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParseIP(%q) = %v, want %v", tt.host, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %v", tt.host, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_MultipleIPs 测试多个IP
|
|
func TestParseIP_MultipleIPs(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
host string
|
|
expected []string
|
|
}{
|
|
{
|
|
"两个IP",
|
|
"192.168.1.1,192.168.1.2",
|
|
[]string{"192.168.1.1", "192.168.1.2"},
|
|
},
|
|
{
|
|
"三个IP带空格",
|
|
" 192.168.1.1 , 192.168.1.2 , 192.168.1.3 ",
|
|
[]string{"192.168.1.1", "192.168.1.2", "192.168.1.3"},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.host, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.host, err)
|
|
}
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParseIP(%q) = %v, want %v", tt.host, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %d个IP", tt.host, len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_CIDR 测试CIDR格式
|
|
//
|
|
// 验证:CIDR被正确展开为IP列表
|
|
func TestParseIP_CIDR(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
cidr string
|
|
expectCount int
|
|
}{
|
|
{
|
|
"/30网络",
|
|
"192.168.1.0/30",
|
|
2, // .1, .2 (排除网络地址和广播地址)
|
|
},
|
|
{
|
|
"/29网络",
|
|
"10.0.0.0/29",
|
|
6, // .1-.6
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.cidr, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.cidr, err)
|
|
}
|
|
|
|
if len(result) != tt.expectCount {
|
|
t.Errorf("ParseIP(%q) 返回%d个IP,期望%d个",
|
|
tt.cidr, len(result), tt.expectCount)
|
|
}
|
|
|
|
// 验证已排序
|
|
if !sort.StringsAreSorted(result) {
|
|
t.Errorf("ParseIP(%q) 结果未排序", tt.cidr)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %d个IP", tt.cidr, len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_IPRange 测试IP范围
|
|
func TestParseIP_IPRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
rangeStr string
|
|
expectCount int
|
|
}{
|
|
{
|
|
"小范围",
|
|
"192.168.1.1-3",
|
|
3,
|
|
},
|
|
{
|
|
"单IP范围",
|
|
"192.168.1.1-1",
|
|
1,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.rangeStr, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.rangeStr, err)
|
|
}
|
|
|
|
if len(result) != tt.expectCount {
|
|
t.Errorf("ParseIP(%q) 返回%d个IP,期望%d个",
|
|
tt.rangeStr, len(result), tt.expectCount)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %d个IP", tt.rangeStr, len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_FromFile 测试从文件读取
|
|
//
|
|
// 验证:文件中的IP列表被正确读取
|
|
func TestParseIP_FromFile(t *testing.T) {
|
|
// 创建临时文件
|
|
tmpDir := t.TempDir()
|
|
hostFile := filepath.Join(tmpDir, "hosts.txt")
|
|
|
|
content := `# 这是注释
|
|
192.168.1.1
|
|
192.168.1.2
|
|
|
|
# 空行会被忽略
|
|
192.168.1.3
|
|
`
|
|
|
|
if err := os.WriteFile(hostFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ParseIP("", hostFile, "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(file=%q) error = %v", hostFile, err)
|
|
}
|
|
|
|
expected := []string{"192.168.1.1", "192.168.1.2", "192.168.1.3"}
|
|
if !reflect.DeepEqual(result, expected) {
|
|
t.Errorf("ParseIP(file) = %v, want %v", result, expected)
|
|
}
|
|
|
|
t.Logf("✓ 从文件读取%d个IP(正确过滤注释和空行)", len(result))
|
|
}
|
|
|
|
// TestParseIP_FileNotFound 测试文件不存在
|
|
func TestParseIP_FileNotFound(t *testing.T) {
|
|
_, err := ParseIP("", "nonexistent_file_12345.txt", "")
|
|
|
|
if err == nil {
|
|
t.Error("ParseIP(不存在的文件) 应该返回错误")
|
|
}
|
|
|
|
t.Logf("✓ 文件不存在时正确返回错误: %v", err)
|
|
}
|
|
|
|
// TestParseIP_Exclude 测试排除主机
|
|
//
|
|
// 验证:排除列表中的主机被正确过滤
|
|
func TestParseIP_Exclude(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
hosts string
|
|
exclude string
|
|
expected []string
|
|
}{
|
|
{
|
|
"排除单个",
|
|
"192.168.1.1,192.168.1.2,192.168.1.3",
|
|
"192.168.1.2",
|
|
[]string{"192.168.1.1", "192.168.1.3"},
|
|
},
|
|
{
|
|
"排除多个",
|
|
"192.168.1.1,192.168.1.2,192.168.1.3",
|
|
"192.168.1.1,192.168.1.3",
|
|
[]string{"192.168.1.2"},
|
|
},
|
|
{
|
|
"排除不存在的",
|
|
"192.168.1.1,192.168.1.2",
|
|
"192.168.1.100",
|
|
[]string{"192.168.1.1", "192.168.1.2"},
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.hosts, "", tt.exclude)
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP error = %v", err)
|
|
}
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParseIP(hosts=%q, exclude=%q) = %v, want %v",
|
|
tt.hosts, tt.exclude, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ 正确排除指定主机: %d → %d",
|
|
len(tt.expected)+len(result)-len(tt.expected), len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_Deduplicate 测试去重
|
|
func TestParseIP_Deduplicate(t *testing.T) {
|
|
result, err := ParseIP("192.168.1.1,192.168.1.1,192.168.1.2,192.168.1.2", "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP error = %v", err)
|
|
}
|
|
|
|
expected := []string{"192.168.1.1", "192.168.1.2"}
|
|
if !reflect.DeepEqual(result, expected) {
|
|
t.Errorf("ParseIP(重复IP) = %v, want %v", result, expected)
|
|
}
|
|
|
|
t.Logf("✓ 正确去重: 4个输入 → %d个输出", len(result))
|
|
}
|
|
|
|
// TestParseIP_Sorted 测试排序
|
|
func TestParseIP_Sorted(t *testing.T) {
|
|
result, err := ParseIP("192.168.1.3,192.168.1.1,192.168.1.2", "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP error = %v", err)
|
|
}
|
|
|
|
if !sort.StringsAreSorted(result) {
|
|
t.Errorf("ParseIP 结果未排序: %v", result)
|
|
}
|
|
|
|
t.Logf("✓ 结果已排序: %v", result)
|
|
}
|
|
|
|
// TestParseIP_NoHosts 测试无有效主机
|
|
func TestParseIP_NoHosts(t *testing.T) {
|
|
_, err := ParseIP("", "", "")
|
|
|
|
if err == nil {
|
|
t.Error("ParseIP(空输入) 应该返回错误")
|
|
}
|
|
|
|
if err.Error() != "没有找到有效的主机" {
|
|
t.Errorf("错误信息不匹配: %v", err)
|
|
}
|
|
|
|
t.Logf("✓ 无有效主机时正确返回错误")
|
|
}
|
|
|
|
// TestParseIP_MixedSources 测试混合来源
|
|
func TestParseIP_MixedSources(t *testing.T) {
|
|
// 创建临时文件
|
|
tmpDir := t.TempDir()
|
|
hostFile := filepath.Join(tmpDir, "hosts.txt")
|
|
|
|
if err := os.WriteFile(hostFile, []byte("192.168.1.1\n192.168.1.2\n"), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
// 命令行 + 文件
|
|
result, err := ParseIP("192.168.1.3,192.168.1.4", hostFile, "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP error = %v", err)
|
|
}
|
|
|
|
expected := []string{"192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4"}
|
|
if !reflect.DeepEqual(result, expected) {
|
|
t.Errorf("ParseIP(混合来源) = %v, want %v", result, expected)
|
|
}
|
|
|
|
t.Logf("✓ 正确合并多个来源: %d个IP", len(result))
|
|
}
|
|
|
|
// =============================================================================
|
|
// 辅助函数测试
|
|
// =============================================================================
|
|
|
|
// TestParsePortRange 测试端口范围解析
|
|
func TestParsePortRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{"正常范围", "1-5", []int{1, 2, 3, 4, 5}},
|
|
{"单端口", "80-80", []int{80}},
|
|
{"反向范围", "5-1", nil},
|
|
{"超出范围", "65535-65540", nil},
|
|
{"格式错误", "1-2-3", nil},
|
|
{"非数字", "a-b", nil},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := parsePortRange(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("parsePortRange(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestExcludeHosts 测试排除主机
|
|
func TestExcludeHosts(t *testing.T) {
|
|
hosts := []string{"host1", "host2", "host3", "host4"}
|
|
exclude := []string{"host2", "host4"}
|
|
|
|
result := excludeFromList(hosts, exclude)
|
|
expected := []string{"host1", "host3"}
|
|
|
|
if !reflect.DeepEqual(result, expected) {
|
|
t.Errorf("excludeFromList = %v, want %v", result, expected)
|
|
}
|
|
|
|
t.Logf("✓ excludeFromList: %d → %d", len(hosts), len(result))
|
|
}
|
|
|
|
// TestExcludeHosts_EmptyExclude 测试空排除列表
|
|
func TestExcludeHosts_EmptyExclude(t *testing.T) {
|
|
hosts := []string{"host1", "host2"}
|
|
result := excludeFromList(hosts, []string{})
|
|
|
|
if !reflect.DeepEqual(result, hosts) {
|
|
t.Errorf("excludeFromList(空排除列表) 应该返回原列表")
|
|
}
|
|
}
|
|
|
|
// TestRemoveDuplicates 测试去重
|
|
func TestRemoveDuplicates(t *testing.T) {
|
|
input := []string{"a", "b", "a", "c", "b", "d"}
|
|
result := removeDuplicateStrings(input)
|
|
|
|
// 验证无重复
|
|
seen := make(map[string]bool)
|
|
for _, item := range result {
|
|
if seen[item] {
|
|
t.Errorf("removeDuplicateStrings 结果包含重复项: %s", item)
|
|
}
|
|
seen[item] = true
|
|
}
|
|
|
|
// 验证长度
|
|
if len(result) != 4 {
|
|
t.Errorf("removeDuplicateStrings 返回%d项,期望4项", len(result))
|
|
}
|
|
|
|
t.Logf("✓ removeDuplicateStrings: %d → %d", len(input), len(result))
|
|
}
|
|
|
|
// TestRemoveDuplicatePorts 测试端口去重
|
|
func TestRemoveDuplicatePorts(t *testing.T) {
|
|
input := []int{80, 443, 80, 22, 443, 8080}
|
|
result := removeDuplicatePorts(input)
|
|
|
|
// 验证无重复
|
|
seen := make(map[int]bool)
|
|
for _, port := range result {
|
|
if seen[port] {
|
|
t.Errorf("removeDuplicatePorts 结果包含重复项: %d", port)
|
|
}
|
|
seen[port] = true
|
|
}
|
|
|
|
// 验证长度
|
|
if len(result) != 4 {
|
|
t.Errorf("removeDuplicatePorts 返回%d项,期望4项", len(result))
|
|
}
|
|
|
|
t.Logf("✓ removeDuplicatePorts: %d → %d", len(input), len(result))
|
|
}
|
|
|
|
// =============================================================================
|
|
// 边缘情况测试 - IP解析
|
|
// =============================================================================
|
|
|
|
// TestParseIP_InternalNetworkShortcuts 测试内网简写
|
|
func TestParseIP_InternalNetworkShortcuts(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
shortcut string
|
|
expectMin int // 最少应该有多少IP
|
|
sampleCheck string
|
|
}{
|
|
{
|
|
"192简写",
|
|
"192",
|
|
100, // 192.168.0.0/16 应该很多
|
|
"192.168.",
|
|
},
|
|
{
|
|
"172简写",
|
|
"172",
|
|
100, // 172.16.0.0/12 应该很多
|
|
"172.",
|
|
},
|
|
{
|
|
"10简写",
|
|
"10",
|
|
100, // 10.0.0.0/8 应该很多
|
|
"10.",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.shortcut, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.shortcut, err)
|
|
}
|
|
|
|
if len(result) < tt.expectMin {
|
|
t.Errorf("ParseIP(%q) 返回%d个IP,期望至少%d个",
|
|
tt.shortcut, len(result), tt.expectMin)
|
|
}
|
|
|
|
// 检查样本
|
|
hasMatch := false
|
|
for _, ip := range result[:min(10, len(result))] {
|
|
if len(ip) >= len(tt.sampleCheck) && ip[:len(tt.sampleCheck)] == tt.sampleCheck {
|
|
hasMatch = true
|
|
break
|
|
}
|
|
}
|
|
if !hasMatch {
|
|
t.Errorf("ParseIP(%q) 结果不包含预期前缀 %q", tt.shortcut, tt.sampleCheck)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %d个IP(内网简写展开正确)", tt.shortcut, len(result))
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_FullIPRange 测试完整IP范围格式
|
|
func TestParseIP_FullIPRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
rangeStr string
|
|
expectCount int
|
|
expectFirst string
|
|
expectLast string
|
|
}{
|
|
{
|
|
"完整范围小",
|
|
"192.168.1.1-192.168.1.5",
|
|
5,
|
|
"192.168.1.1",
|
|
"192.168.1.5",
|
|
},
|
|
{
|
|
"跨子网范围",
|
|
"192.168.1.254-192.168.2.2",
|
|
5, // .254, .255, .0, .1, .2
|
|
"192.168.1.254",
|
|
"192.168.2.2",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result, err := ParseIP(tt.rangeStr, "", "")
|
|
|
|
if err != nil {
|
|
t.Fatalf("ParseIP(%q) error = %v", tt.rangeStr, err)
|
|
}
|
|
|
|
if len(result) != tt.expectCount {
|
|
t.Errorf("ParseIP(%q) 返回%d个IP,期望%d个",
|
|
tt.rangeStr, len(result), tt.expectCount)
|
|
}
|
|
|
|
if len(result) > 0 && result[0] != tt.expectFirst {
|
|
t.Errorf("ParseIP(%q) 第一个IP = %q,期望 %q",
|
|
tt.rangeStr, result[0], tt.expectFirst)
|
|
}
|
|
|
|
if len(result) > 0 && result[len(result)-1] != tt.expectLast {
|
|
t.Errorf("ParseIP(%q) 最后一个IP = %q,期望 %q",
|
|
tt.rangeStr, result[len(result)-1], tt.expectLast)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) → %v", tt.rangeStr, result)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_InvalidCIDR 测试无效CIDR
|
|
func TestParseIP_InvalidCIDR(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
cidr string
|
|
expectErr bool
|
|
}{
|
|
{"无效掩码/33", "192.168.1.0/33", true},
|
|
{"无效掩码/0", "192.168.1.0/0", false}, // /0 技术上是有效的
|
|
{"格式错误", "192.168.1.0/abc", true},
|
|
{"缺少掩码", "192.168.1.0/", true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
_, err := ParseIP(tt.cidr, "", "")
|
|
|
|
if tt.expectErr && err == nil {
|
|
t.Errorf("ParseIP(%q) 应该返回错误", tt.cidr)
|
|
}
|
|
if !tt.expectErr && err != nil {
|
|
t.Errorf("ParseIP(%q) 不应该返回错误: %v", tt.cidr, err)
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) 错误处理正确", tt.cidr)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestParseIP_InvalidIPRange 测试无效IP范围
|
|
func TestParseIP_InvalidIPRange(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
rangeStr string
|
|
expectErr bool
|
|
}{
|
|
{"起始大于结束", "192.168.1.100-50", true},
|
|
{"结束值超255", "192.168.1.1-256", true},
|
|
// 注意: "999.999.999.999-192.168.1.100" 不会报错,
|
|
// 因为 looksLikeIPRange 检测到无效IP后会把它当作普通主机名处理
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
_, err := ParseIP(tt.rangeStr, "", "")
|
|
|
|
if tt.expectErr && err == nil {
|
|
t.Errorf("ParseIP(%q) 应该返回错误", tt.rangeStr)
|
|
return
|
|
}
|
|
if !tt.expectErr && err != nil {
|
|
t.Errorf("ParseIP(%q) 不应返回错误: %v", tt.rangeStr, err)
|
|
return
|
|
}
|
|
|
|
t.Logf("✓ ParseIP(%q) 错误处理正确", tt.rangeStr)
|
|
})
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// 边缘情况测试 - 文件读取
|
|
// =============================================================================
|
|
|
|
// TestReadLinesFromFile_WindowsLineEndings 测试Windows行尾
|
|
func TestReadLinesFromFile_WindowsLineEndings(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "crlf.txt")
|
|
|
|
// Windows风格行尾: CRLF
|
|
content := "line1\r\nline2\r\nline3\r\n"
|
|
if err := os.WriteFile(testFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ReadLinesFromFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ReadLinesFromFile error = %v", err)
|
|
}
|
|
|
|
// 应该有3行,且不包含\r
|
|
if len(result) != 3 {
|
|
t.Errorf("ReadLinesFromFile 返回%d行,期望3行", len(result))
|
|
}
|
|
|
|
for i, line := range result {
|
|
if len(line) > 0 && line[len(line)-1] == '\r' {
|
|
t.Errorf("第%d行包含\\r: %q", i+1, line)
|
|
}
|
|
}
|
|
|
|
t.Logf("✓ Windows行尾处理正确: %v", result)
|
|
}
|
|
|
|
// TestReadLinesFromFile_OnlyComments 测试只有注释的文件
|
|
func TestReadLinesFromFile_OnlyComments(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "comments.txt")
|
|
|
|
content := `# comment 1
|
|
# comment 2
|
|
# comment 3
|
|
`
|
|
if err := os.WriteFile(testFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ReadLinesFromFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ReadLinesFromFile error = %v", err)
|
|
}
|
|
|
|
if len(result) != 0 {
|
|
t.Errorf("只有注释的文件应该返回空列表,实际返回: %v", result)
|
|
}
|
|
|
|
t.Logf("✓ 只有注释的文件正确返回空列表")
|
|
}
|
|
|
|
// TestReadLinesFromFile_EmptyFile 测试空文件
|
|
func TestReadLinesFromFile_EmptyFile(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "empty.txt")
|
|
|
|
if err := os.WriteFile(testFile, []byte(""), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ReadLinesFromFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ReadLinesFromFile error = %v", err)
|
|
}
|
|
|
|
if len(result) != 0 {
|
|
t.Errorf("空文件应该返回空列表,实际返回: %v", result)
|
|
}
|
|
|
|
t.Logf("✓ 空文件正确返回空列表")
|
|
}
|
|
|
|
// TestReadLinesFromFile_MixedContent 测试混合内容
|
|
func TestReadLinesFromFile_MixedContent(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "mixed.txt")
|
|
|
|
content := `# Header comment
|
|
192.168.1.1
|
|
# indented comment
|
|
192.168.1.2
|
|
|
|
192.168.1.3
|
|
# trailing comment
|
|
`
|
|
if err := os.WriteFile(testFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ReadLinesFromFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ReadLinesFromFile error = %v", err)
|
|
}
|
|
|
|
expected := []string{"192.168.1.1", "192.168.1.2", "192.168.1.3"}
|
|
if !reflect.DeepEqual(result, expected) {
|
|
t.Errorf("ReadLinesFromFile = %v, want %v", result, expected)
|
|
}
|
|
|
|
t.Logf("✓ 混合内容处理正确: %v", result)
|
|
}
|
|
|
|
// =============================================================================
|
|
// 边缘情况测试 - 凭据解析
|
|
// =============================================================================
|
|
|
|
// TestParseUserPassFile 测试用户密码文件解析
|
|
func TestParseUserPassFile(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "userpass.txt")
|
|
|
|
content := `admin:password123
|
|
root:toor
|
|
# comment line
|
|
user:pass:with:colons
|
|
:emptyuser
|
|
nopassword
|
|
test:
|
|
`
|
|
if err := os.WriteFile(testFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
result, err := ParseUserPassFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ParseUserPassFile error = %v", err)
|
|
}
|
|
|
|
// 验证解析结果
|
|
tests := []struct {
|
|
username string
|
|
password string
|
|
}{
|
|
{"admin", "password123"},
|
|
{"root", "toor"},
|
|
{"user", "pass:with:colons"}, // 密码可以包含冒号
|
|
{"test", ""}, // 空密码
|
|
}
|
|
|
|
if len(result) != len(tests) {
|
|
t.Errorf("ParseUserPassFile 返回%d对,期望%d对", len(result), len(tests))
|
|
}
|
|
|
|
for i, tt := range tests {
|
|
if i >= len(result) {
|
|
break
|
|
}
|
|
if result[i].Username != tt.username || result[i].Password != tt.password {
|
|
t.Errorf("第%d对: got (%q, %q), want (%q, %q)",
|
|
i, result[i].Username, result[i].Password, tt.username, tt.password)
|
|
}
|
|
}
|
|
|
|
t.Logf("✓ 用户密码文件解析正确: %d对", len(result))
|
|
}
|
|
|
|
// TestParseHashFile 测试哈希文件解析
|
|
func TestParseHashFile(t *testing.T) {
|
|
tmpDir := t.TempDir()
|
|
testFile := filepath.Join(tmpDir, "hashes.txt")
|
|
|
|
content := `# MD5 hashes
|
|
5d41402abc4b2a76b9719d911017c592
|
|
098f6bcd4621d373cade4e832627b4f6
|
|
# invalid hash (too short)
|
|
5d41402abc4b2a76
|
|
# invalid hash (non-hex)
|
|
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
|
|
# valid hash
|
|
d41d8cd98f00b204e9800998ecf8427e
|
|
`
|
|
if err := os.WriteFile(testFile, []byte(content), 0600); err != nil {
|
|
t.Fatalf("创建测试文件失败: %v", err)
|
|
}
|
|
|
|
hashValues, hashBytes, err := ParseHashFile(testFile)
|
|
if err != nil {
|
|
t.Fatalf("ParseHashFile error = %v", err)
|
|
}
|
|
|
|
// 应该只有3个有效hash
|
|
if len(hashValues) != 3 {
|
|
t.Errorf("ParseHashFile 返回%d个hash,期望3个", len(hashValues))
|
|
}
|
|
|
|
if len(hashBytes) != 3 {
|
|
t.Errorf("ParseHashFile hashBytes 返回%d个,期望3个", len(hashBytes))
|
|
}
|
|
|
|
// 验证hash bytes长度
|
|
for i, hb := range hashBytes {
|
|
if len(hb) != 16 { // MD5 = 16 bytes
|
|
t.Errorf("hashBytes[%d] 长度=%d,期望16", i, len(hb))
|
|
}
|
|
}
|
|
|
|
t.Logf("✓ 哈希文件解析正确: %d个有效hash", len(hashValues))
|
|
}
|
|
|
|
// =============================================================================
|
|
// 边缘情况测试 - 端口解析
|
|
// =============================================================================
|
|
|
|
// TestParsePort_LargeRange 测试大范围端口
|
|
func TestParsePort_LargeRange(t *testing.T) {
|
|
result := ParsePort("1-1000")
|
|
|
|
if len(result) != 1000 {
|
|
t.Errorf("ParsePort(1-1000) 返回%d个端口,期望1000个", len(result))
|
|
}
|
|
|
|
// 验证第一个和最后一个
|
|
if result[0] != 1 || result[len(result)-1] != 1000 {
|
|
t.Errorf("ParsePort(1-1000) 范围不正确: first=%d, last=%d",
|
|
result[0], result[len(result)-1])
|
|
}
|
|
|
|
t.Logf("✓ 大范围端口解析正确: %d个", len(result))
|
|
}
|
|
|
|
// TestParsePort_EmptyElements 测试空元素
|
|
func TestParsePort_EmptyElements(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
input string
|
|
expected []int
|
|
}{
|
|
{"连续逗号", "80,,443", []int{80, 443}},
|
|
{"开头逗号", ",80,443", []int{80, 443}},
|
|
{"结尾逗号", "80,443,", []int{80, 443}},
|
|
{"多个空", "80,,,443,,,", []int{80, 443}},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
result := ParsePort(tt.input)
|
|
|
|
if !reflect.DeepEqual(result, tt.expected) {
|
|
t.Errorf("ParsePort(%q) = %v, want %v", tt.input, result, tt.expected)
|
|
}
|
|
|
|
t.Logf("✓ ParsePort(%q) 正确处理空元素", tt.input)
|
|
})
|
|
}
|
|
}
|
|
|
|
// =============================================================================
|
|
// 辅助函数
|
|
// =============================================================================
|
|
|
|
func min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|