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]>
561 lines
17 KiB
Go
561 lines
17 KiB
Go
package lib
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math/rand" //nolint:gosec // G404: math/rand用于生成测试数据,非加密用途
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/google/cel-go/cel"
|
|
"github.com/google/cel-go/checker/decls"
|
|
"github.com/google/cel-go/common/types"
|
|
"github.com/google/cel-go/common/types/ref"
|
|
"github.com/google/cel-go/interpreter/functions"
|
|
"github.com/shadow1ng/fscan/common"
|
|
"github.com/shadow1ng/fscan/common/i18n"
|
|
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
|
|
)
|
|
|
|
// 基础CEL环境缓存(避免重复创建,减少内存分配)
|
|
var (
|
|
baseEnvOnce sync.Once
|
|
baseEnv *cel.Env
|
|
baseProgramOpt []cel.ProgramOption
|
|
)
|
|
|
|
// 包级POC配置(atomic 保证并发安全)
|
|
var pocDNSLog atomic.Bool
|
|
|
|
// InitPOCConfig 初始化POC配置(在扫描开始前调用)
|
|
// 这样CEL回调函数可以使用包级变量而非GetGlobalConfig
|
|
func InitPOCConfig(dnsLog bool) {
|
|
pocDNSLog.Store(dnsLog)
|
|
}
|
|
|
|
// NewEnv 创建一个新的 CEL 环境(使用缓存避免重复注册函数)
|
|
func NewEnv(c *CustomLib) (*cel.Env, error) {
|
|
cachedCELEnvOnce.Do(func() {
|
|
cachedCELEnv, cachedCELEnvErr = cel.NewEnv(cel.Lib(c))
|
|
})
|
|
return cachedCELEnv, cachedCELEnvErr
|
|
}
|
|
|
|
// initBaseEnv 初始化基础CEL环境(只执行一次)
|
|
func initBaseEnv() {
|
|
baseEnvOnce.Do(func() {
|
|
// 收集所有函数声明
|
|
var allDeclarations []*exprpb.Decl
|
|
allDeclarations = append(allDeclarations, registerStringDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerEncodingDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerCryptoDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerRandomDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerMiscDeclarations()...)
|
|
|
|
// 收集所有函数实现
|
|
var allImplementations []*functions.Overload
|
|
allImplementations = append(allImplementations, registerStringImplementations()...)
|
|
allImplementations = append(allImplementations, registerEncodingImplementations()...)
|
|
allImplementations = append(allImplementations, registerCryptoImplementations()...)
|
|
allImplementations = append(allImplementations, registerRandomImplementations()...)
|
|
allImplementations = append(allImplementations, registerMiscImplementations()...)
|
|
|
|
// 保存程序选项供后续使用
|
|
//nolint:staticcheck // SA1019: cel.Functions已废弃但CEL库尚未提供替代方案
|
|
baseProgramOpt = []cel.ProgramOption{cel.Functions(allImplementations...)}
|
|
|
|
// 创建基础环境
|
|
var err error
|
|
baseEnv, err = cel.NewEnv(
|
|
cel.Container("lib"),
|
|
cel.Types(&UrlType{}, &Request{}, &Response{}, &Reverse{}),
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
cel.Declarations(
|
|
decls.NewIdent("request", decls.NewObjectType("lib.Request"), nil),
|
|
decls.NewIdent("response", decls.NewObjectType("lib.Response"), nil),
|
|
decls.NewIdent("reverse", decls.NewObjectType("lib.Reverse"), nil),
|
|
),
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
cel.Declarations(allDeclarations...),
|
|
)
|
|
if err != nil {
|
|
common.LogError(i18n.Tr("webscan_cel_init_failed", err))
|
|
}
|
|
})
|
|
}
|
|
|
|
// GetBaseEnv 获取基础CEL环境
|
|
func GetBaseEnv() *cel.Env {
|
|
initBaseEnv()
|
|
return baseEnv
|
|
}
|
|
|
|
// GetBaseProgramOptions 获取基础程序选项
|
|
func GetBaseProgramOptions() []cel.ProgramOption {
|
|
initBaseEnv()
|
|
return baseProgramOpt
|
|
}
|
|
|
|
// ExtendEnvWithVars 扩展基础环境,添加POC特定的变量声明
|
|
func ExtendEnvWithVars(varDecls []*exprpb.Decl) (*cel.Env, error) {
|
|
base := GetBaseEnv()
|
|
if base == nil {
|
|
return nil, fmt.Errorf("基础CEL环境未初始化")
|
|
}
|
|
if len(varDecls) == 0 {
|
|
return base, nil
|
|
}
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
return base.Extend(cel.Declarations(varDecls...))
|
|
}
|
|
|
|
// MakeVarDecl 根据变量名和表达式创建变量声明
|
|
func MakeVarDecl(key, value string) *exprpb.Decl {
|
|
switch {
|
|
case strings.HasPrefix(value, "randomInt"):
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
return decls.NewIdent(key, decls.Int, nil)
|
|
case strings.HasPrefix(value, "newReverse"):
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
return decls.NewIdent(key, decls.NewObjectType("lib.Reverse"), nil)
|
|
default:
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
return decls.NewIdent(key, decls.String, nil)
|
|
}
|
|
}
|
|
|
|
// Evaluate 评估 CEL 表达式
|
|
func Evaluate(env *cel.Env, expression string, params map[string]interface{}) (ref.Val, error) {
|
|
// 空表达式默认返回 true
|
|
if expression == "" {
|
|
return types.Bool(true), nil
|
|
}
|
|
|
|
// 编译表达式
|
|
ast, issues := env.Compile(expression)
|
|
if issues.Err() != nil {
|
|
return nil, fmt.Errorf("表达式编译错误: %w", issues.Err())
|
|
}
|
|
|
|
// 创建程序(使用缓存的程序选项)
|
|
program, err := env.Program(ast, GetBaseProgramOptions()...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("程序创建错误: %w", err)
|
|
}
|
|
|
|
// 执行评估
|
|
result, _, err := program.Eval(params)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("表达式评估错误: %w", err)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// URLTypeToString 将 TargetURL 结构体转换为字符串
|
|
func URLTypeToString(u *UrlType) string {
|
|
var builder strings.Builder
|
|
|
|
// 处理 scheme 部分
|
|
if u.Scheme != "" {
|
|
builder.WriteString(u.Scheme)
|
|
builder.WriteByte(':')
|
|
}
|
|
|
|
// 处理 host 部分
|
|
if u.Scheme != "" || u.Host != "" {
|
|
if u.Host != "" || u.Path != "" {
|
|
builder.WriteString("//")
|
|
}
|
|
if host := u.Host; host != "" {
|
|
builder.WriteString(host)
|
|
}
|
|
}
|
|
|
|
// 处理 path 部分
|
|
path := u.Path
|
|
if path != "" && path[0] != '/' && u.Host != "" {
|
|
builder.WriteByte('/')
|
|
}
|
|
|
|
// 处理相对路径
|
|
if builder.Len() == 0 {
|
|
if i := strings.IndexByte(path, ':'); i > -1 && strings.IndexByte(path[:i], '/') == -1 {
|
|
builder.WriteString("./")
|
|
}
|
|
}
|
|
builder.WriteString(path)
|
|
|
|
// 处理查询参数
|
|
if u.Query != "" {
|
|
builder.WriteByte('?')
|
|
builder.WriteString(u.Query)
|
|
}
|
|
|
|
// 处理片段标识符
|
|
if u.Fragment != "" {
|
|
builder.WriteByte('#')
|
|
builder.WriteString(u.Fragment)
|
|
}
|
|
|
|
return builder.String()
|
|
}
|
|
|
|
// CustomLib 自定义CEL库配置
|
|
type CustomLib struct {
|
|
envOptions []cel.EnvOption
|
|
programOptions []cel.ProgramOption
|
|
}
|
|
|
|
// 缓存CustomLib实例和CEL环境,避免重复注册CEL函数导致冲突
|
|
var (
|
|
cachedCustomLib CustomLib
|
|
cachedCustomLibOnce sync.Once
|
|
cachedCELEnv *cel.Env
|
|
cachedCELEnvOnce sync.Once
|
|
cachedCELEnvErr error
|
|
)
|
|
|
|
// NewEnvOption 创建新的CEL环境配置(使用缓存避免重复注册)
|
|
func NewEnvOption() CustomLib {
|
|
cachedCustomLibOnce.Do(func() {
|
|
cachedCustomLib = createCustomLib()
|
|
})
|
|
return cachedCustomLib
|
|
}
|
|
|
|
// createCustomLib 实际创建CustomLib(只执行一次)
|
|
func createCustomLib() CustomLib {
|
|
c := CustomLib{}
|
|
|
|
// 收集所有函数声明
|
|
var allDeclarations []*exprpb.Decl
|
|
allDeclarations = append(allDeclarations, registerStringDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerEncodingDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerCryptoDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerRandomDeclarations()...)
|
|
allDeclarations = append(allDeclarations, registerMiscDeclarations()...)
|
|
|
|
c.envOptions = []cel.EnvOption{
|
|
cel.Container("lib"),
|
|
cel.Types(&UrlType{}, &Request{}, &Response{}, &Reverse{}),
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
cel.Declarations(
|
|
decls.NewIdent("request", decls.NewObjectType("lib.Request"), nil),
|
|
decls.NewIdent("response", decls.NewObjectType("lib.Response"), nil),
|
|
decls.NewIdent("reverse", decls.NewObjectType("lib.Reverse"), nil),
|
|
),
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
cel.Declarations(allDeclarations...),
|
|
}
|
|
|
|
// 收集所有函数实现
|
|
var allImplementations []*functions.Overload
|
|
allImplementations = append(allImplementations, registerStringImplementations()...)
|
|
allImplementations = append(allImplementations, registerEncodingImplementations()...)
|
|
allImplementations = append(allImplementations, registerCryptoImplementations()...)
|
|
allImplementations = append(allImplementations, registerRandomImplementations()...)
|
|
allImplementations = append(allImplementations, registerMiscImplementations()...)
|
|
|
|
c.programOptions = []cel.ProgramOption{
|
|
//nolint:staticcheck // SA1019: cel.Functions已废弃但CEL库尚未提供替代方案
|
|
cel.Functions(allImplementations...),
|
|
}
|
|
|
|
return c
|
|
}
|
|
|
|
// CompileOptions 返回环境编译选项
|
|
func (c *CustomLib) CompileOptions() []cel.EnvOption {
|
|
return c.envOptions
|
|
}
|
|
|
|
// ProgramOptions 返回程序运行选项
|
|
// 返回空切片,函数实现通过 GetBaseProgramOptions() 在 Evaluate() 时注入
|
|
// 这避免了多次创建环境时重复注册函数导致的冲突
|
|
func (c *CustomLib) ProgramOptions() []cel.ProgramOption {
|
|
return nil
|
|
}
|
|
|
|
// UpdateCompileOptions 更新编译选项,处理不同类型的变量声明
|
|
func (c *CustomLib) UpdateCompileOptions(args StrMap) {
|
|
for _, item := range args {
|
|
key, value := item.Key, item.Value
|
|
|
|
// 根据函数前缀确定变量类型
|
|
var declaration *exprpb.Decl
|
|
switch {
|
|
case strings.HasPrefix(value, "randomInt"):
|
|
// randomInt 函数返回整型
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
declaration = decls.NewIdent(key, decls.Int, nil)
|
|
case strings.HasPrefix(value, "newReverse"):
|
|
// newReverse 函数返回 Reverse 对象
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
declaration = decls.NewIdent(key, decls.NewObjectType("lib.Reverse"), nil)
|
|
default:
|
|
// 默认声明为字符串类型
|
|
//nolint:staticcheck // SA1019: decls.NewIdent已废弃但CEL库尚未提供替代方案
|
|
declaration = decls.NewIdent(key, decls.String, nil)
|
|
}
|
|
|
|
//nolint:staticcheck // SA1019: cel.Declarations已废弃但CEL库尚未提供替代方案
|
|
c.envOptions = append(c.envOptions, cel.Declarations(declaration))
|
|
}
|
|
}
|
|
|
|
// 随机数生成器(带互斥锁保护,确保并发安全)
|
|
//
|
|
//nolint:gosec // G404: 用于生成测试数据,非加密用途
|
|
var (
|
|
randSource = rand.New(rand.NewSource(time.Now().UnixNano()))
|
|
randMu sync.Mutex
|
|
)
|
|
|
|
// randomLowercase 生成指定长度的小写字母随机字符串
|
|
func randomLowercase(n int) string {
|
|
const lowercase = "abcdefghijklmnopqrstuvwxyz"
|
|
randMu.Lock()
|
|
defer randMu.Unlock()
|
|
return RandomStr(randSource, lowercase, n)
|
|
}
|
|
|
|
// randomUppercase 生成指定长度的大写字母随机字符串
|
|
func randomUppercase(n int) string {
|
|
const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
randMu.Lock()
|
|
defer randMu.Unlock()
|
|
return RandomStr(randSource, uppercase, n)
|
|
}
|
|
|
|
// randomString 生成指定长度的随机字符串(包含大小写字母和数字)
|
|
func randomString(n int) string {
|
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
|
randMu.Lock()
|
|
defer randMu.Unlock()
|
|
return RandomStr(randSource, charset, n)
|
|
}
|
|
|
|
// reverseCheck 检查 DNS 记录是否存在
|
|
// 使用包级pocDNSLog变量,由InitPOCConfig初始化
|
|
func reverseCheck(r *Reverse, timeout int64) bool {
|
|
// 检查必要条件(使用包级配置变量)
|
|
if ceyeAPI == "" || r.Domain == "" || !pocDNSLog.Load() {
|
|
return false
|
|
}
|
|
|
|
// 等待指定时间
|
|
time.Sleep(time.Second * time.Duration(timeout))
|
|
|
|
// 提取子域名
|
|
sub := strings.Split(r.Domain, ".")[0]
|
|
|
|
// 构造 API 请求 TargetURL
|
|
apiURL := fmt.Sprintf("http://api.ceye.io/v1/records?token=%s&type=dns&filter=%s",
|
|
ceyeAPI, sub)
|
|
|
|
// 创建并发送请求
|
|
req, _ := http.NewRequest("GET", apiURL, nil)
|
|
resp, err := DoRequest(req, false)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
// 检查响应内容
|
|
hasData := !bytes.Contains(resp.Body, []byte(`"data": []`))
|
|
isOK := bytes.Contains(resp.Body, []byte(`"message": "OK"`))
|
|
|
|
if hasData && isOK {
|
|
common.LogDebug(apiURL)
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// RandomStr 生成指定长度的随机字符串
|
|
func RandomStr(randSource *rand.Rand, letterBytes string, n int) string {
|
|
const (
|
|
// 用 6 位比特表示一个字母索引
|
|
letterIdxBits = 6
|
|
// 生成掩码:000111111
|
|
letterIdxMask = 1<<letterIdxBits - 1
|
|
// 63 位能存储的字母索引数量
|
|
letterIdxMax = 63 / letterIdxBits
|
|
)
|
|
|
|
// 预分配结果数组
|
|
randBytes := make([]byte, n)
|
|
|
|
// 使用位操作生成随机字符串
|
|
for i, cache, remain := n-1, randSource.Int63(), letterIdxMax; i >= 0; {
|
|
// 当可用的随机位用完时,重新获取随机数
|
|
if remain == 0 {
|
|
cache, remain = randSource.Int63(), letterIdxMax
|
|
}
|
|
|
|
// 获取字符集中的随机索引
|
|
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
|
randBytes[i] = letterBytes[idx]
|
|
i--
|
|
}
|
|
|
|
// 右移已使用的位,更新计数器
|
|
cache >>= letterIdxBits
|
|
remain--
|
|
}
|
|
|
|
return string(randBytes)
|
|
}
|
|
|
|
// DoRequest 执行 HTTP 请求
|
|
func DoRequest(req *http.Request, redirect bool) (*Response, error) {
|
|
// 处理请求头
|
|
if req.Body != nil && req.Body != http.NoBody {
|
|
// 设置 Content-Length
|
|
req.Header.Set("Content-Length", strconv.Itoa(int(req.ContentLength)))
|
|
|
|
// 如果未指定 Content-Type,设置默认值
|
|
if req.Header.Get("Content-Type") == "" {
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
}
|
|
}
|
|
|
|
// 执行请求
|
|
// 检查发包限制
|
|
if canSend, reason := common.CanSendPacket(); !canSend {
|
|
common.LogError(i18n.Tr("webscan_request_restricted", req.URL.String(), reason))
|
|
return nil, fmt.Errorf("发包受限: %s", reason)
|
|
}
|
|
|
|
var (
|
|
oResp *http.Response
|
|
err error
|
|
)
|
|
|
|
if redirect {
|
|
oResp, err = Client.Do(req)
|
|
} else {
|
|
oResp, err = ClientNoRedirect.Do(req)
|
|
}
|
|
|
|
if err != nil {
|
|
// HTTP请求失败,计为TCP失败
|
|
common.GetGlobalState().IncrementTCPFailedPacketCount()
|
|
return nil, fmt.Errorf("请求执行失败: %w", err)
|
|
}
|
|
|
|
// HTTP请求成功,计为TCP成功
|
|
common.GetGlobalState().IncrementTCPSuccessPacketCount()
|
|
defer func() { _ = oResp.Body.Close() }()
|
|
|
|
// 解析响应
|
|
resp, err := ParseResponse(oResp)
|
|
if err != nil {
|
|
common.LogError(i18n.Tr("webscan_response_parse_failed", err))
|
|
}
|
|
|
|
return resp, err
|
|
}
|
|
|
|
// ParseURL 解析 TargetURL 并转换为自定义 TargetURL 类型
|
|
func ParseURL(u *url.URL) *UrlType {
|
|
return &UrlType{
|
|
Scheme: u.Scheme,
|
|
Domain: u.Hostname(),
|
|
Host: u.Host,
|
|
Port: u.Port(),
|
|
Path: u.EscapedPath(),
|
|
Query: u.RawQuery,
|
|
Fragment: u.Fragment,
|
|
}
|
|
}
|
|
|
|
// ParseRequest 将标准 HTTP 请求转换为自定义请求对象
|
|
func ParseRequest(oReq *http.Request) (*Request, error) {
|
|
req := &Request{
|
|
Method: oReq.Method,
|
|
URL: ParseURL(oReq.URL),
|
|
Headers: make(map[string]string),
|
|
ContentType: oReq.Header.Get("Content-Type"),
|
|
}
|
|
|
|
// 复制请求头
|
|
for k := range oReq.Header {
|
|
req.Headers[k] = oReq.Header.Get(k)
|
|
}
|
|
|
|
// 处理请求体
|
|
if oReq.Body != nil && oReq.Body != http.NoBody {
|
|
data, err := io.ReadAll(oReq.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("读取请求体失败: %w", err)
|
|
}
|
|
req.Body = data
|
|
// 重新设置请求体,允许后续重复读取
|
|
oReq.Body = io.NopCloser(bytes.NewBuffer(data))
|
|
}
|
|
|
|
return req, nil
|
|
}
|
|
|
|
// ParseResponse 将标准 HTTP 响应转换为自定义响应对象
|
|
func ParseResponse(oResp *http.Response) (*Response, error) {
|
|
resp := Response{
|
|
Status: int32(oResp.StatusCode),
|
|
URL: ParseURL(oResp.Request.URL),
|
|
Headers: make(map[string]string),
|
|
ContentType: oResp.Header.Get("Content-Type"),
|
|
}
|
|
|
|
// 复制响应头,合并多值头部为分号分隔的字符串
|
|
for k := range oResp.Header {
|
|
resp.Headers[k] = strings.Join(oResp.Header.Values(k), ";")
|
|
}
|
|
|
|
// 读取并解析响应体
|
|
body, err := getRespBody(oResp)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("处理响应体失败: %w", err)
|
|
}
|
|
resp.Body = body
|
|
|
|
return &resp, nil
|
|
}
|
|
|
|
// getRespBody 读取 HTTP 响应体并处理可能的 gzip 压缩
|
|
func getRespBody(oResp *http.Response) ([]byte, error) {
|
|
// 读取原始响应体
|
|
body, err := io.ReadAll(oResp.Body)
|
|
if err != nil && !errors.Is(err, io.EOF) && len(body) == 0 {
|
|
return nil, err
|
|
}
|
|
|
|
// 处理 gzip 压缩
|
|
if strings.Contains(oResp.Header.Get("Content-Encoding"), "gzip") {
|
|
reader, err := gzip.NewReader(bytes.NewReader(body))
|
|
if err != nil {
|
|
return body, nil // 如果解压失败,返回原始数据
|
|
}
|
|
defer func() { _ = reader.Close() }()
|
|
|
|
decompressed, err := io.ReadAll(reader)
|
|
if err != nil && !errors.Is(err, io.EOF) && len(decompressed) == 0 {
|
|
return nil, err
|
|
}
|
|
if len(decompressed) == 0 && len(body) != 0 {
|
|
return body, nil
|
|
}
|
|
return decompressed, nil
|
|
}
|
|
|
|
return body, nil
|
|
}
|