From 0fb3a5a6ca607589839b2e45889c6aa059d04f4b Mon Sep 17 00:00:00 2001 From: ZacharyZcR Date: Wed, 2 Dec 2026 00:20:43 +0800 Subject: [PATCH 1/3] refactor: isolate session state, fix concurrency races and protocol/POC anti-patterns --- common/logger.go | 40 +++-- common/proxy/manager.go | 27 ++++ common/session.go | 65 +++++++- core/icmp.go | 7 +- core/port_scan.go | 7 +- core/scanner.go | 7 +- core/target_scope_test.go | 2 +- core/web_scanner.go | 77 ++++++--- main_cli.go | 22 ++- pkg/fscan/scanner.go | 16 +- plugins/services/cassandra.go | 22 ++- plugins/services/credential_tester.go | 69 +++----- plugins/services/elasticsearch.go | 38 ++++- plugins/services/kafka.go | 18 +-- plugins/services/mongodb.go | 20 +-- plugins/services/mssql.go | 13 +- plugins/services/mssql_raw.go | 9 +- plugins/services/netbios.go | 11 +- plugins/services/oracle.go | 17 +- plugins/services/oracle_raw.go | 9 +- plugins/services/redis.go | 4 +- plugins/services/types.go | 10 ++ plugins/web/webtitle.go | 60 ++++--- plugins/web/webtitle_test.go | 7 - web/api/project.go | 29 ++-- web/api/result.go | 24 +-- web/api/scan.go | 29 ++-- web/ws/hub.go | 67 ++++++-- webscan/fingerprint/enhanced.go | 81 +++++++--- webscan/fingerprint_scanner.go | 3 +- webscan/lib/Client.go | 203 +++++++++++++++++++++--- webscan/lib/Eval.go | 22 +-- webscan/lib/poc_adapter.go | 57 ++++--- webscan/lib/poc_adapter_example_test.go | 10 +- webscan/lib/poc_adapter_test.go | 15 +- webscan/lib/poc_executor.go | 15 +- 36 files changed, 785 insertions(+), 347 deletions(-) diff --git a/common/logger.go b/common/logger.go index 23f2d5ff..6db6e221 100644 --- a/common/logger.go +++ b/common/logger.go @@ -15,16 +15,21 @@ import ( var ( globalLogger *logging.Logger - loggerOnce sync.Once - loggerMu sync.Mutex + loggerMu sync.RWMutex silentLoggerRefs int ) -func getGlobalLogger() *logging.Logger { +func ensureGlobalLogger() *logging.Logger { + loggerMu.RLock() + l := globalLogger + loggerMu.RUnlock() + if l != nil { + return l + } + loggerMu.Lock() defer loggerMu.Unlock() - - loggerOnce.Do(func() { + if globalLogger == nil { fv := GetFlagVars() level := getLogLevelFromString(fv.LogLevel) config := &logging.LoggerConfig{ @@ -40,10 +45,19 @@ func getGlobalLogger() *logging.Logger { } globalLogger = logging.NewLogger(config) globalLogger.SetCoordinatedOutput(LogWithProgress) - }) + } return globalLogger } +func withGlobalLogger(fn func(*logging.Logger)) { + ensureGlobalLogger() + loggerMu.RLock() + defer loggerMu.RUnlock() + if globalLogger != nil { + fn(globalLogger) + } +} + func getLogLevelFromString(levelStr string) logging.LogLevel { switch strings.ToLower(levelStr) { case "all": @@ -69,23 +83,23 @@ func getLogLevelFromString(levelStr string) logging.LogLevel { // InitLogger 初始化日志系统 func InitLogger() { - getGlobalLogger().Initialize() + withGlobalLogger(func(l *logging.Logger) { l.Initialize() }) } // LogDebug 输出调试日志 -func LogDebug(msg string) { getGlobalLogger().Debug(msg) } +func LogDebug(msg string) { withGlobalLogger(func(l *logging.Logger) { l.Debug(msg) }) } // LogInfo 输出信息日志 -func LogInfo(msg string) { getGlobalLogger().Info(msg) } +func LogInfo(msg string) { withGlobalLogger(func(l *logging.Logger) { l.Info(msg) }) } // LogSuccess 输出成功日志(Web指纹等) -func LogSuccess(result string) { getGlobalLogger().Success(result) } +func LogSuccess(result string) { withGlobalLogger(func(l *logging.Logger) { l.Success(result) }) } // LogVuln 输出漏洞/重要发现日志(密码成功、漏洞等) -func LogVuln(result string) { getGlobalLogger().Vuln(result) } +func LogVuln(result string) { withGlobalLogger(func(l *logging.Logger) { l.Vuln(result) }) } // LogError 输出错误日志 -func LogError(errMsg string) { getGlobalLogger().Error(errMsg) } +func LogError(errMsg string) { withGlobalLogger(func(l *logging.Logger) { l.Error(errMsg) }) } // CloseLogger 关闭日志系统,释放文件资源 func CloseLogger() { @@ -119,11 +133,11 @@ func PushSilentLogger() func() { func resetLoggerLocked() { closeLoggerLocked() globalLogger = nil - loggerOnce = sync.Once{} } func closeLoggerLocked() { if globalLogger != nil { globalLogger.Close() + globalLogger = nil } } diff --git a/common/proxy/manager.go b/common/proxy/manager.go index 720c228f..ee06480f 100644 --- a/common/proxy/manager.go +++ b/common/proxy/manager.go @@ -55,6 +55,33 @@ func NewProxyManager(config *ProxyConfig) ProxyManager { return m } +// NewIsolatedProxyManager 创建与全局代理状态隔离的代理管理器(供 ScanSession 并发使用)。 +// probe 为 true 且为 SOCKS5 时执行一次可靠性探测;返回管理器和该代理是否可靠。 +func NewIsolatedProxyManager(config *ProxyConfig, probe bool) (ProxyManager, bool) { + if config == nil { + config = DefaultProxyConfig() + } + + m := &manager{ + config: config, + stats: &ProxyStats{ + ProxyType: config.Type.String(), + ProxyAddress: config.Address, + }, + dialerCache: make(map[string]Dialer), + cacheExpiry: time.Now().Add(DefaultCacheExpiry), + } + + reliable := true + if probe && config.Type == ProxyTypeSOCKS5 { + if dialer, err := m.createSOCKS5Dialer(); err == nil { + reliable = ProbeProxyBehavior(dialer, config.Timeout) + } + } + + return m, reliable +} + // GetDialer 获取普通拨号器 func (m *manager) GetDialer() (Dialer, error) { m.mu.RLock() diff --git a/common/session.go b/common/session.go index 42bdc96c..f731f4fa 100644 --- a/common/session.go +++ b/common/session.go @@ -27,9 +27,35 @@ type ScanSession struct { PauseGate func(ctx context.Context) error // 每会话 dialer(按 timeout 懒初始化,取决于代理配置) - dialerMu sync.Mutex - dialers map[time.Duration]proxy.Dialer - dialerErrs map[time.Duration]error + dialerMu sync.Mutex + dialers map[time.Duration]proxy.Dialer + dialerErrs map[time.Duration]error + proxyProbed bool + proxyReliable bool + + // 每会话 HTTP 客户端集合(由 webscan/lib.InitSessionHTTP 绑定,避免包循环依赖) + httpClientsMu sync.RWMutex + httpClients interface{} +} + +// SetHTTPClients 绑定会话级 HTTP 客户端集合 +func (s *ScanSession) SetHTTPClients(clients interface{}) { + if s == nil { + return + } + s.httpClientsMu.Lock() + s.httpClients = clients + s.httpClientsMu.Unlock() +} + +// HTTPClients 获取会话级 HTTP 客户端集合 +func (s *ScanSession) HTTPClients() interface{} { + if s == nil { + return nil + } + s.httpClientsMu.RLock() + defer s.httpClientsMu.RUnlock() + return s.httpClients } // NewScanSession 从已构建的 Config、State 和 FlagVars 创建会话 @@ -128,12 +154,18 @@ func (s *ScanSession) DialUDP(ctx context.Context, address string, timeout time. return nil, fmt.Errorf("%s", i18n.Tr("network_rate_limited", err.Error())) } - conn, err := net.DialTimeout("udp", address, timeout) + if ctx == nil { + ctx = context.Background() + } + d := &net.Dialer{Timeout: timeout} + conn, err := d.DialContext(ctx, "udp", address) if err != nil { s.State.IncrementUDPPacketCount() return nil, err } - _ = conn.SetDeadline(time.Now().Add(timeout)) + if timeout > 0 { + _ = conn.SetDeadline(time.Now().Add(timeout)) + } s.State.IncrementUDPPacketCount() return conn, nil } @@ -172,7 +204,21 @@ func (s *ScanSession) ProxyReliable() bool { if !s.ProxyEnabled() || !s.IsSOCKS5Proxy() { return true } - return proxy.IsProxyReliable() + s.dialerMu.Lock() + probed := s.proxyProbed + reliable := s.proxyReliable + s.dialerMu.Unlock() + if probed { + return reliable + } + // 触发一次会话级代理探测 + _, _ = s.getDialer(0) + s.dialerMu.Lock() + defer s.dialerMu.Unlock() + if s.proxyProbed { + return s.proxyReliable + } + return true } func (s *ScanSession) getDialer(timeout time.Duration) (proxy.Dialer, error) { @@ -192,7 +238,12 @@ func (s *ScanSession) getDialer(timeout time.Duration) (proxy.Dialer, error) { } cfg := s.createProxyConfig(timeout) - manager := proxy.NewProxyManager(cfg) + shouldProbe := !s.proxyProbed && cfg.Type == proxy.ProxyTypeSOCKS5 + manager, reliable := proxy.NewIsolatedProxyManager(cfg, shouldProbe) + if shouldProbe { + s.proxyProbed = true + s.proxyReliable = reliable + } dialer, err := manager.GetDialer() s.dialers[timeout] = dialer s.dialerErrs[timeout] = err diff --git a/core/icmp.go b/core/icmp.go index c77339b2..247273f6 100644 --- a/core/icmp.go +++ b/core/icmp.go @@ -738,8 +738,12 @@ func runTcpProbeForHosts(ctx context.Context, hosts []string, session *common.Sc limiter := make(chan struct{}, concurrency) for _, host := range hosts { + select { + case <-ctx.Done(): + goto done + case limiter <- struct{}{}: + } wg.Add(1) - limiter <- struct{}{} go func(h string) { defer func() { @@ -769,6 +773,7 @@ func runTcpProbeForHosts(ctx context.Context, hosts []string, session *common.Sc }(host) } +done: wg.Wait() return aliveHosts } diff --git a/core/port_scan.go b/core/port_scan.go index 3a34b6ac..823e0099 100644 --- a/core/port_scan.go +++ b/core/port_scan.go @@ -883,12 +883,17 @@ func probeSubnets(ctx context.Context, hosts []string, timeout time.Duration, se // ── 阶段 1:网关启发式 ────────────────────────────────── // 对每个子网的 .1 和 .254 打多个端口,命中率高且速度极快 +gatewayLoop: for prefix := range subnets { for _, suffix := range gatewayOffsets { gw := prefix + suffix for _, port := range gatewayProbePorts { + select { + case <-ctx.Done(): + break gatewayLoop + case limiter <- struct{}{}: + } wg.Add(1) - limiter <- struct{}{} go func(pfx, addr string) { defer func() { <-limiter; wg.Done() }() conn, err := session.DialTCP(ctx, "tcp", addr, subnetProbeTimeout) diff --git a/core/scanner.go b/core/scanner.go index dd1bc9a4..5d33ae6c 100644 --- a/core/scanner.go +++ b/core/scanner.go @@ -109,11 +109,13 @@ func RunScan(ctx context.Context, info common.HostInfo, session *common.ScanSess // 设置全局 State(兼容旧代码路径中未传 state 的调用) SetGlobalState(state) - // 初始化HTTP客户端(静默,无需日志) - if err := lib.Inithttp(config); err != nil { + // 初始化会话级 HTTP 客户端(并发扫描互相隔离,结束时释放空闲连接) + httpClients, err := lib.InitSessionHTTP(session) + if err != nil { session.LogError(i18n.Tr("http_client_init_failed", err)) return buildScanReport(state, start), fmt.Errorf("initialize http client: %w", err) } + defer httpClients.Close() // 选择策略 strategy := selectStrategy(config, state, info) @@ -149,6 +151,7 @@ func RunScan(ctx context.Context, info common.HostInfo, session *common.ScanSess session.LogInfo(i18n.GetText("received_exit_signal")) case <-ctx.Done(): } + signal.Stop(sigChan) cancel() time.Sleep(500 * time.Millisecond) } diff --git a/core/target_scope_test.go b/core/target_scope_test.go index 66a6878f..3f8ea3dc 100644 --- a/core/target_scope_test.go +++ b/core/target_scope_test.go @@ -115,7 +115,7 @@ func TestServiceScanUsesSessionCache(t *testing.T) { state := common.NewState() state.SetHostPorts([]string{"127.0.0.1:10003"}) CacheServiceInfoWithState(state, "127.0.0.1", 10003, &ServiceInfo{Name: name}) - previous := globalState + previous := globalState.Load() SetGlobalState(common.NewState()) t.Cleanup(func() { SetGlobalState(previous) }) session := common.NewScanSession(cfg, state, flags) diff --git a/core/web_scanner.go b/core/web_scanner.go index 549a8f70..35c8bdb4 100644 --- a/core/web_scanner.go +++ b/core/web_scanner.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" "sync" + "sync/atomic" + "time" "github.com/shadow1ng/fscan/common" "github.com/shadow1ng/fscan/common/i18n" @@ -40,36 +42,46 @@ func DetectHTTPSchemeContext(ctx context.Context, host string, port int, config timeout := config.Network.WebTimeout addr := net.JoinHostPort(host, strconv.Itoa(port)) - // 第一步:尝试标准TLS握手(优先检测HTTPS) - tlsDialer := &net.Dialer{Timeout: timeout} - tlsConn, err := tls.DialWithDialer( - tlsDialer, - "tcp", addr, - &tls.Config{ - InsecureSkipVerify: true, - MinVersion: tls.VersionTLS10, - }, - ) + dialRaw := func() (net.Conn, error) { + if session != nil { + return session.DialTCP(ctx, "tcp", addr, timeout) + } + return (&net.Dialer{Timeout: timeout}).DialContext(ctx, "tcp", addr) + } + // 第一步:尝试标准TLS握手(优先检测HTTPS,走 session.DialTCP 以支持代理/限速/ctx) + rawConn, err := dialRaw() if err == nil { + if timeout > 0 { + _ = rawConn.SetDeadline(time.Now().Add(timeout)) + } + tlsConn := tls.Client(rawConn, &tls.Config{ + InsecureSkipVerify: true, + MinVersion: tls.VersionTLS10, + }) + err = tlsConn.HandshakeContext(ctx) _ = tlsConn.Close() - return "https" + if err == nil { + return "https" + } } // 第二步:仅在标准 TLS 握手级别失败(cipher/protocol 不兼容)时尝试国密 // 连接级别失败(timeout/refused/非 TLS 端口)不需要尝试 if maybeGMTLS(err) { - gmConn, gmErr := gmtls.DialWithDialer( - tlsDialer, - "tcp", addr, - &gmtls.Config{ + if gmRaw, dialErr := dialRaw(); dialErr == nil { + if timeout > 0 { + _ = gmRaw.SetDeadline(time.Now().Add(timeout)) + } + gmConn := gmtls.Client(gmRaw, &gmtls.Config{ GMSupport: gmtls.NewGMSupport(), InsecureSkipVerify: true, - }, - ) - if gmErr == nil { + }) + gmErr := gmConn.Handshake() _ = gmConn.Close() - return "https-gm" + if gmErr == nil { + return "https-gm" + } } } @@ -212,7 +224,7 @@ func (w *WebPortDetector) tryHTTP(ctx context.Context, client *http.Client, sess // globalState 全局 State 兼容指针(向后兼容不接受 State 的旧调用方) // 新代码应通过 State 方法访问服务缓存 -var globalState *common.State +var globalState atomic.Pointer[common.State] // IsWebServiceByFingerprint 基于服务指纹判断Web服务 - 保持API兼容 // 服务识别规则 - 编译期常量,避免运行时分配 @@ -280,14 +292,14 @@ func isDefinitelyNonWeb(serviceInfo *ServiceInfo) bool { // SetGlobalState 设置全局 State(RunScan 入口调用,兼容旧代码路径) func SetGlobalState(state *common.State) { - globalState = state + globalState.Store(state) } func resolveState(state *common.State) *common.State { if state != nil { return state } - return globalState + return globalState.Load() } // CacheServiceInfoWithState 缓存服务信息到指定 State @@ -344,6 +356,21 @@ func GetWebServiceInfoWithState(state *common.State, host string, port int) (*Se return info, true } +// SetWebServiceProtocolWithState 线程安全地更新缓存的 Web 服务协议(写时复制,避免并发写 Extras map) +func SetWebServiceProtocolWithState(state *common.State, host string, port int, protocol string) { + info, exists := GetCachedServiceInfoWithState(state, host, port) + if !exists || info == nil { + return + } + cloned := *info + cloned.Extras = make(map[string]string, len(info.Extras)+1) + for k, v := range info.Extras { + cloned.Extras[k] = v + } + cloned.Extras["protocol"] = protocol + CacheServiceInfoWithState(state, host, port, &cloned) +} + // IsMarkedWebService 检查是否为 Web 服务(使用全局 State) func IsMarkedWebService(host string, port int) bool { _, exists := GetWebServiceInfo(host, port) @@ -488,7 +515,11 @@ func (s *WebScanStrategy) createTargetFromURLWithSession(baseInfo common.HostInf } // 标记为Web服务,确保Web插件能识别此目标 - MarkAsWebService(urlInfo.Host, urlInfo.Port, &ServiceInfo{Name: "http"}) + var targetState *common.State + if session != nil { + targetState = session.State + } + CacheServiceInfoWithState(targetState, urlInfo.Host, urlInfo.Port, &ServiceInfo{Name: "http"}) return &urlInfo } diff --git a/main_cli.go b/main_cli.go index 526b3b95..cf8a5739 100644 --- a/main_cli.go +++ b/main_cli.go @@ -61,20 +61,28 @@ func run() int { return 1 } - // 设置信号处理,确保 Ctrl+C 时能正确保存结果 - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) + // 设置信号处理:首次 Ctrl+C 通过 context 优雅取消并落盘;再次 Ctrl+C 立即强退 + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() go func() { - <-sigChan + <-ctx.Done() common.LogInfo(i18n.GetText("received_exit_signal")) - _ = common.Cleanup() // 确保结果写入磁盘 - os.Exit(130) // 128 + SIGINT(2) = 130,标准的中断退出码 + // 监听二次中断信号以防底层阻塞无法退出 + forceSig := make(chan os.Signal, 1) + signal.Notify(forceSig, os.Interrupt, syscall.SIGTERM) + defer signal.Stop(forceSig) + <-forceSig + _ = common.Cleanup() + os.Exit(130) }() defer func() { _ = common.Cleanup() }() defer common.CloseLogger() // 执行扫描 - if _, err := core.RunScan(context.Background(), *result.Info, result.Session); err != nil { + if _, err := core.RunScan(ctx, *result.Info, result.Session); err != nil { + if ctx.Err() != nil { + return 130 + } common.LogError(i18n.Tr("error_generic", err)) return 1 } diff --git a/pkg/fscan/scanner.go b/pkg/fscan/scanner.go index d48628df..3cebc16e 100644 --- a/pkg/fscan/scanner.go +++ b/pkg/fscan/scanner.go @@ -306,6 +306,15 @@ func (s *Scanner) scanOne(ctx context.Context, target Target, sink common.Result if err != nil { return core.ScanReport{}, err } + // 直接注入强类型凭据,避免通过 FlagVars 逗号拼接导致含逗号的用户名/密码被错误拆分 + if len(s.config.Usernames) > 0 { + for serviceName := range cfg.Credentials.Userdict { + cfg.Credentials.Userdict[serviceName] = append([]string(nil), s.config.Usernames...) + } + } + if len(s.config.Passwords) > 0 { + cfg.Credentials.Passwords = append([]string(nil), s.config.Passwords...) + } if len(s.config.UserPassPairs) > 0 { cfg.Credentials.UserPassPairs = make([]commonconfig.CredentialPair, 0, len(s.config.UserPassPairs)) for _, pair := range s.config.UserPassPairs { @@ -314,6 +323,11 @@ func (s *Scanner) scanOne(ctx context.Context, target Target, sink common.Result Password: pair.Password, }) } + } else if len(s.config.Usernames) == 1 && len(s.config.Passwords) == 1 { + cfg.Credentials.UserPassPairs = []commonconfig.CredentialPair{{ + Username: s.config.Usernames[0], + Password: s.config.Passwords[0], + }} } cfg.Output.DisableSave = true cfg.Output.Silent = true @@ -430,7 +444,7 @@ func buildFlagVars(config Config, target Target) *common.FlagVars { PocName: config.POCName, PocFull: config.POCFull, PocNum: pocConcurrency, - DisablePocScan: config.DisablePOCScan, + DisablePocScan: config.DisablePOCScan || !config.AllowUnsafePlugins, PacketRateLimit: config.PacketRateLimit, MaxPacketCount: config.MaxPacketCount, ICMPRate: icmpRate, diff --git a/plugins/services/cassandra.go b/plugins/services/cassandra.go index bc505d3f..b797cfa2 100644 --- a/plugins/services/cassandra.go +++ b/plugins/services/cassandra.go @@ -29,7 +29,6 @@ func NewCassandraPlugin() *CassandraPlugin { func (p *CassandraPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State target := info.Target() if config.DisableBrute { @@ -50,7 +49,7 @@ func (p *CassandraPlugin) Scan(ctx context.Context, info *common.HostInfo, sessi } } - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "cassandra", testConfig) @@ -62,9 +61,9 @@ func (p *CassandraPlugin) Scan(ctx context.Context, info *common.HostInfo, sessi return result } -func (p *CassandraPlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *CassandraPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doCassandraAuth(ctx, info, cred, config, state) + return p.doCassandraAuth(ctx, info, cred, session) } } @@ -86,12 +85,13 @@ const ( maxCQLFrameBody = 1024 * 1024 ) -func (p *CassandraPlugin) doCassandraAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *CassandraPlugin) doCassandraAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State addr := info.Target() timeout := config.ModuleTimeout() - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", addr) + conn, err := dialServiceTCP(ctx, session, addr, timeout) if err != nil { state.IncrementTCPFailedPacketCount() return &AuthResult{Success: false, ErrorType: classifyCassandraErrorType(err), Error: err} @@ -273,10 +273,8 @@ func (p *CassandraPlugin) tryNoAuthConnection(ctx context.Context, info *common. addr := info.Target() timeout := config.ModuleTimeout() - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", addr) + conn, err := dialServiceTCP(ctx, session, addr, timeout) if err != nil { - state.IncrementTCPFailedPacketCount() return nil } defer conn.Close() @@ -325,10 +323,8 @@ func (p *CassandraPlugin) identifyService(ctx context.Context, info *common.Host addr := info.Target() timeout := config.ModuleTimeout() - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", addr) + conn, err := dialServiceTCP(ctx, session, addr, timeout) if err != nil { - state.IncrementTCPFailedPacketCount() return &ScanResult{Success: false, Service: "cassandra", Error: err} } defer conn.Close() diff --git a/plugins/services/credential_tester.go b/plugins/services/credential_tester.go index 27844a7e..232c6bd5 100644 --- a/plugins/services/credential_tester.go +++ b/plugins/services/credential_tester.go @@ -3,9 +3,11 @@ package services import ( "context" "database/sql" + "errors" "fmt" "io" "net" + "strings" "sync" "sync/atomic" "time" @@ -327,7 +329,13 @@ func workerTestCredentials( case ErrorTypeNetwork: consecutiveNetErrors++ case ErrorTypeThrottle: - time.Sleep(500 * time.Millisecond) + timer := time.NewTimer(500 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return + case <-timer.C: + } default: consecutiveNetErrors = 0 } @@ -429,18 +437,27 @@ func ClassifyError(err error, authKeywords, networkKeywords []string) ErrorType return ErrorTypeUnknown } - errStr := err.Error() + errLower := strings.ToLower(err.Error()) - // 先检查认证错误 + // 先检查认证错误(避免包装了 io.EOF / net.Error 的认证拒绝被误判为网络错误) for _, keyword := range authKeywords { - if containsIgnoreCase(errStr, keyword) { + if keyword != "" && strings.Contains(errLower, strings.ToLower(keyword)) { return ErrorTypeAuth } } - // 再检查网络错误 + // 优先使用结构化错误类型判断标准网络/超时错误 + if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { + return ErrorTypeNetwork + } + var netErr net.Error + if errors.As(err, &netErr) { + return ErrorTypeNetwork + } + + // 再按关键字兜底检查网络错误 for _, keyword := range networkKeywords { - if containsIgnoreCase(errStr, keyword) { + if keyword != "" && strings.Contains(errLower, strings.ToLower(keyword)) { return ErrorTypeNetwork } } @@ -448,48 +465,12 @@ func ClassifyError(err error, authKeywords, networkKeywords []string) ErrorType return ErrorTypeUnknown } -// containsIgnoreCase 忽略大小写的字符串包含检查 func containsIgnoreCase(s, substr string) bool { - return len(s) >= len(substr) && - (s == substr || - len(substr) == 0 || - findIgnoreCase(s, substr) >= 0) + return strings.Contains(strings.ToLower(s), strings.ToLower(substr)) } -// findIgnoreCase 忽略大小写查找子串 -func findIgnoreCase(s, substr string) int { - if len(substr) == 0 { - return 0 - } - if len(substr) > len(s) { - return -1 - } - for i := 0; i <= len(s)-len(substr); i++ { - if matchIgnoreCase(s[i:i+len(substr)], substr) { - return i - } - } - return -1 -} - -// matchIgnoreCase 忽略大小写比较 func matchIgnoreCase(a, b string) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - ca, cb := a[i], b[i] - if ca >= 'A' && ca <= 'Z' { - ca += 'a' - 'A' - } - if cb >= 'A' && cb <= 'Z' { - cb += 'a' - 'A' - } - if ca != cb { - return false - } - } - return true + return strings.EqualFold(a, b) } // ============================================================================= diff --git a/plugins/services/elasticsearch.go b/plugins/services/elasticsearch.go index 500174d2..2eab8012 100644 --- a/plugins/services/elasticsearch.go +++ b/plugins/services/elasticsearch.go @@ -7,6 +7,7 @@ import ( "crypto/tls" "encoding/base64" "fmt" + "net" "net/http" "github.com/shadow1ng/fscan/common" @@ -53,8 +54,27 @@ func (p *ElasticsearchPlugin) Scan(ctx context.Context, info *common.HostInfo, s } } + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + DialContext: func(dialCtx context.Context, network, addr string) (net.Conn, error) { + return dialServiceTCP(dialCtx, session, addr, config.ModuleTimeout()) + }, + } + defer transport.CloseIdleConnections() + client := &http.Client{ + Timeout: config.ModuleTimeout(), + Transport: transport, + } + for _, cred := range credentials { - if p.testCredential(ctx, info, cred, session) { + if ctx.Err() != nil { + return &ScanResult{ + Success: false, + Service: "elasticsearch", + Error: ctx.Err(), + } + } + if p.testCredentialWithClient(ctx, client, info, cred, session) { session.LogVuln(i18n.Tr("elasticsearch_credential", target, cred.Username, cred.Password)) return &ScanResult{ Success: true, @@ -75,13 +95,21 @@ func (p *ElasticsearchPlugin) Scan(ctx context.Context, info *common.HostInfo, s func (p *ElasticsearchPlugin) testCredential(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) bool { config := session.Config - client := &http.Client{ - Timeout: config.ModuleTimeout(), - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + DialContext: func(dialCtx context.Context, network, addr string) (net.Conn, error) { + return dialServiceTCP(dialCtx, session, addr, config.ModuleTimeout()) }, } + defer transport.CloseIdleConnections() + client := &http.Client{ + Timeout: config.ModuleTimeout(), + Transport: transport, + } + return p.testCredentialWithClient(ctx, client, info, cred, session) +} +func (p *ElasticsearchPlugin) testCredentialWithClient(ctx context.Context, client *http.Client, info *common.HostInfo, cred Credential, session *common.ScanSession) bool { // 构建URL protocol := "http" if info.Port == 9443 { diff --git a/plugins/services/kafka.go b/plugins/services/kafka.go index 1e5af2dd..fd248735 100644 --- a/plugins/services/kafka.go +++ b/plugins/services/kafka.go @@ -29,7 +29,6 @@ func NewKafkaPlugin() *KafkaPlugin { func (p *KafkaPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State if config.DisableBrute { return p.identifyService(ctx, info, session) } @@ -45,7 +44,7 @@ func (p *KafkaPlugin) Scan(ctx context.Context, info *common.HostInfo, session * } } - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "kafka", testConfig) @@ -57,20 +56,21 @@ func (p *KafkaPlugin) Scan(ctx context.Context, info *common.HostInfo, session * return result } -func (p *KafkaPlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *KafkaPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doKafkaAuth(ctx, info, cred, config, state) + return p.doKafkaAuth(ctx, info, cred, session) } } // ── raw TCP Kafka 实现 ────────────────────────────────────────── -func (p *KafkaPlugin) doKafkaAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *KafkaPlugin) doKafkaAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State target := info.Target() timeout := config.ModuleTimeout() - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", target) + conn, err := dialServiceTCP(ctx, session, target, timeout) if err != nil { state.IncrementTCPFailedPacketCount() return &AuthResult{ @@ -244,10 +244,8 @@ func (p *KafkaPlugin) identifyService(ctx context.Context, info *common.HostInfo target := info.Target() timeout := config.ModuleTimeout() - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", target) + conn, err := dialServiceTCP(ctx, session, target, timeout) if err != nil { - state.IncrementTCPFailedPacketCount() return &ScanResult{ Success: false, Service: "kafka", diff --git a/plugins/services/mongodb.go b/plugins/services/mongodb.go index 2fb7d28e..6f0ccd57 100644 --- a/plugins/services/mongodb.go +++ b/plugins/services/mongodb.go @@ -13,7 +13,6 @@ import ( "fmt" "io" "math" - "net" "strconv" "strings" "sync/atomic" @@ -38,7 +37,6 @@ func NewMongoDBPlugin() *MongoDBPlugin { func (p *MongoDBPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State target := info.Target() if config.DisableBrute { @@ -69,7 +67,7 @@ func (p *MongoDBPlugin) Scan(ctx context.Context, info *common.HostInfo, session } } - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "mongodb", testConfig) @@ -81,19 +79,21 @@ func (p *MongoDBPlugin) Scan(ctx context.Context, info *common.HostInfo, session return result } -func (p *MongoDBPlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *MongoDBPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doMongoDBAuth(ctx, info, cred, config, state) + return p.doMongoDBAuth(ctx, info, cred, session) } } // ── raw TCP MongoDB SCRAM 认证 ────────────────────────────────── -func (p *MongoDBPlugin) doMongoDBAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *MongoDBPlugin) doMongoDBAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State addr := info.Target() timeout := config.ModuleTimeout() - conn, err := dialTCP(ctx, addr, timeout) + conn, err := dialServiceTCP(ctx, session, addr, timeout) if err != nil { state.IncrementTCPFailedPacketCount() return &AuthResult{Success: false, ErrorType: classifyMongoDBErrorType(err), Error: err} @@ -554,12 +554,6 @@ func mongoHMAC(key, data []byte) []byte { return mac.Sum(nil) } -// dialTCP 带超时的 TCP 连接 -func dialTCP(ctx context.Context, addr string, timeout time.Duration) (net.Conn, error) { - dialer := net.Dialer{Timeout: timeout} - return dialer.DialContext(ctx, "tcp", addr) -} - // randomString 生成加密安全的随机字符串 func randomString(n int) string { const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" diff --git a/plugins/services/mssql.go b/plugins/services/mssql.go index b26ecca6..41770978 100644 --- a/plugins/services/mssql.go +++ b/plugins/services/mssql.go @@ -25,7 +25,6 @@ func NewMSSQLPlugin() *MSSQLPlugin { func (p *MSSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State if config.DisableBrute { return p.identifyService(ctx, info, session) } @@ -42,7 +41,7 @@ func (p *MSSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, session * } // 使用公共框架进行并发凭据测试 - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "mssql", testConfig) @@ -55,18 +54,20 @@ func (p *MSSQLPlugin) Scan(ctx context.Context, info *common.HostInfo, session * } // createAuthFunc 创建MSSQL认证函数 -func (p *MSSQLPlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *MSSQLPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doMSSQLAuth(ctx, info, cred, config, state) + return p.doMSSQLAuth(ctx, info, cred, session) } } // doMSSQLAuth 执行MSSQL认证 -func (p *MSSQLPlugin) doMSSQLAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *MSSQLPlugin) doMSSQLAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State authCtx, cancel := context.WithTimeout(ctx, config.ModuleTimeout()) defer cancel() - _, err := mssqlRawLogin(authCtx, info.Host, info.Port, cred.Username, cred.Password, config.ModuleTimeout()) + _, err := mssqlRawLoginWithSession(authCtx, session, info.Host, info.Port, cred.Username, cred.Password, config.ModuleTimeout()) if err != nil { state.IncrementTCPFailedPacketCount() return &AuthResult{ diff --git a/plugins/services/mssql_raw.go b/plugins/services/mssql_raw.go index 4d2a2425..a3b1ee43 100644 --- a/plugins/services/mssql_raw.go +++ b/plugins/services/mssql_raw.go @@ -12,6 +12,8 @@ import ( "sort" "time" "unicode/utf16" + + "github.com/shadow1ng/fscan/common" ) const ( @@ -75,9 +77,12 @@ func (e mssqlRawError) Error() string { } func mssqlRawLogin(ctx context.Context, host string, port int, username, password string, timeout time.Duration) (*mssqlRawResult, error) { + return mssqlRawLoginWithSession(ctx, nil, host, port, username, password, timeout) +} + +func mssqlRawLoginWithSession(ctx context.Context, session *common.ScanSession, host string, port int, username, password string, timeout time.Duration) (*mssqlRawResult, error) { target := net.JoinHostPort(host, fmt.Sprint(port)) - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", target) + conn, err := dialServiceTCP(ctx, session, target, timeout) if err != nil { return nil, err } diff --git a/plugins/services/netbios.go b/plugins/services/netbios.go index b9ff5b62..45da2e9a 100644 --- a/plugins/services/netbios.go +++ b/plugins/services/netbios.go @@ -7,7 +7,6 @@ import ( "context" "encoding/binary" "fmt" - "net" "strings" "time" @@ -32,8 +31,6 @@ func NewNetBIOSPlugin() *NetBIOSPlugin { // Scan 执行NetBIOS扫描 - 收集Windows主机和域信息 func (p *NetBIOSPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { - config := session.Config - state := session.State target := info.Target() // 多模块扫描会共享端口列表,跳过其他模块的端口。 @@ -46,7 +43,7 @@ func (p *NetBIOSPlugin) Scan(ctx context.Context, info *common.HostInfo, session if info.Port == 137 { // UDP端口137 - NetBIOS名称服务 - netbiosInfo, err = p.queryNetBIOSNames(info.Host, config, state) + netbiosInfo, err = p.queryNetBIOSNames(ctx, info.Host, session) } else { // TCP端口139 - NetBIOS会话服务 netbiosInfo, err = p.queryNetBIOSSession(ctx, info.Host, session) @@ -149,7 +146,8 @@ func (ni *NetBIOSInfo) Summary() string { } // queryNetBIOSNames 查询NetBIOS名称服务(UDP 137) -func (p *NetBIOSPlugin) queryNetBIOSNames(host string, config *common.Config, state *common.State) (*NetBIOSInfo, error) { +func (p *NetBIOSPlugin) queryNetBIOSNames(ctx context.Context, host string, session *common.ScanSession) (*NetBIOSInfo, error) { + config := session.Config // NetBIOS名称查询数据包 queryPacket := []byte{ 0x66, 0x66, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -160,11 +158,10 @@ func (p *NetBIOSPlugin) queryNetBIOSNames(host string, config *common.Config, st target := fmt.Sprintf("%s:137", host) - conn, err := net.DialTimeout("udp", target, config.ModuleTimeout()) + conn, err := session.DialUDP(ctx, target, config.ModuleTimeout()) if err != nil { return nil, fmt.Errorf("%s: %w", i18n.GetText("netbios_name_connect_failed"), err) } - state.IncrementUDPPacketCount() defer func() { _ = conn.Close() }() _ = conn.SetDeadline(time.Now().Add(config.ModuleTimeout())) diff --git a/plugins/services/oracle.go b/plugins/services/oracle.go index 106132fb..b2b65ddc 100644 --- a/plugins/services/oracle.go +++ b/plugins/services/oracle.go @@ -24,7 +24,6 @@ func NewOraclePlugin() *OraclePlugin { func (p *OraclePlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config - state := session.State target := info.Target() if config.DisableBrute { @@ -47,7 +46,7 @@ func (p *OraclePlugin) Scan(ctx context.Context, info *common.HostInfo, session } // 使用公共框架进行并发凭据测试 - authFn := p.createAuthFunc(info, config, state) + authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "oracle", testConfig) @@ -60,19 +59,21 @@ func (p *OraclePlugin) Scan(ctx context.Context, info *common.HostInfo, session } // createAuthFunc 创建Oracle认证函数 -func (p *OraclePlugin) createAuthFunc(info *common.HostInfo, config *common.Config, state *common.State) AuthFunc { +func (p *OraclePlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doOracleAuth(ctx, info, cred, config, state) + return p.doOracleAuth(ctx, info, cred, session) } } // doOracleAuth 执行 Oracle 认证(raw TNS 协议) -func (p *OraclePlugin) doOracleAuth(ctx context.Context, info *common.HostInfo, cred Credential, config *common.Config, state *common.State) *AuthResult { +func (p *OraclePlugin) doOracleAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { + config := session.Config + state := session.State serviceNames := []string{"XE", "ORCL", "XEPDB1"} for _, serviceName := range serviceNames { connectCtx, cancel := context.WithTimeout(ctx, config.ModuleTimeout()) - err := oracleRawAuth(connectCtx, info.Host, info.Port, serviceName, cred.Username, cred.Password, config.ModuleTimeout()) + err := oracleRawAuthWithSession(connectCtx, session, info.Host, info.Port, serviceName, cred.Username, cred.Password, config.ModuleTimeout()) cancel() if err == nil { state.IncrementTCPSuccessPacketCount() @@ -123,8 +124,6 @@ func classifyOracleErrorType(err error) ErrorType { // testUnauthorizedAccess 测试Oracle未授权访问 func (p *OraclePlugin) testUnauthorizedAccess(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { - config := session.Config - state := session.State target := info.Target() defaultAccounts := []Credential{ @@ -134,7 +133,7 @@ func (p *OraclePlugin) testUnauthorizedAccess(ctx context.Context, info *common. } for _, cred := range defaultAccounts { - result := p.doOracleAuth(ctx, info, cred, config, state) + result := p.doOracleAuth(ctx, info, cred, session) if result.Success { if result.Conn != nil { _ = result.Conn.Close() diff --git a/plugins/services/oracle_raw.go b/plugins/services/oracle_raw.go index 21160b22..a059b7bb 100644 --- a/plugins/services/oracle_raw.go +++ b/plugins/services/oracle_raw.go @@ -41,6 +41,8 @@ import ( "strconv" "strings" "time" + + "github.com/shadow1ng/fscan/common" ) const ( @@ -96,9 +98,12 @@ type oracleSummary struct { } func oracleRawAuth(ctx context.Context, host string, port int, serviceName, username, password string, timeout time.Duration) error { + return oracleRawAuthWithSession(ctx, nil, host, port, serviceName, username, password, timeout) +} + +func oracleRawAuthWithSession(ctx context.Context, session *common.ScanSession, host string, port int, serviceName, username, password string, timeout time.Duration) error { addr := net.JoinHostPort(host, strconv.Itoa(port)) - dialer := net.Dialer{Timeout: timeout} - conn, err := dialer.DialContext(ctx, "tcp", addr) + conn, err := dialServiceTCP(ctx, session, addr, timeout) if err != nil { return err } diff --git a/plugins/services/redis.go b/plugins/services/redis.go index 34b9d4cf..03d6ce64 100644 --- a/plugins/services/redis.go +++ b/plugins/services/redis.go @@ -59,7 +59,9 @@ func (p *RedisPlugin) Scan(ctx context.Context, info *common.HostInfo, session * // 使用公共框架进行并发凭据测试 authFn := p.createAuthFunc(info, session) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) - testConfig.Concurrency = 20 // Redis 默认并发度更高 + if testConfig.Concurrency <= 0 { + testConfig.Concurrency = 20 + } result := TestCredentialsConcurrently(ctx, credentials, authFn, "redis", testConfig) diff --git a/plugins/services/types.go b/plugins/services/types.go index 8a46fe92..540273bc 100644 --- a/plugins/services/types.go +++ b/plugins/services/types.go @@ -2,6 +2,7 @@ package services import ( "context" + "net" "time" "github.com/shadow1ng/fscan/common" @@ -35,6 +36,15 @@ func RegisterUDPPluginWithPorts(name string, factory func() Plugin, ports []int) var GenerateCredentials = plugins.GenerateCredentials +// dialServiceTCP 统一通过 ScanSession 建立 TCP 连接(支持代理、限速、ctx 取消与发包计数)。 +// session 为 nil 时回退到标准 net.Dialer,兼容无会话单测。 +func dialServiceTCP(ctx context.Context, session *common.ScanSession, addr string, timeout time.Duration) (net.Conn, error) { + if session != nil { + return session.DialTCP(ctx, "tcp", addr, timeout) + } + return (&net.Dialer{Timeout: timeout}).DialContext(ctx, "tcp", addr) +} + // udpProbe 执行带超时保护的 UDP 探测(防止 Write/Read 在某些内核下永久阻塞) // 返回读到的数据和长度,超时/错误返回 nil func udpProbe(ctx context.Context, session *common.ScanSession, target string, timeout time.Duration, pkt []byte, bufSize int) ([]byte, int) { diff --git a/plugins/web/webtitle.go b/plugins/web/webtitle.go index 825e0499..2becaf69 100644 --- a/plugins/web/webtitle.go +++ b/plugins/web/webtitle.go @@ -137,8 +137,8 @@ func (p *WebTitlePlugin) getWebTitle(ctx context.Context, info *common.HostInfo, } baseURL := webTitleURL(urlScheme, info.Host, info.Port) - // 选择对应的 HTTP 客户端 - clientNR, clientR := webTitleHTTPClients(isGM) + // 选择对应的会话级 HTTP 客户端 + clientNR, clientR := webTitleHTTPClientsWithSession(session, isGM) // 构建显示用URL(隐藏标准端口) var displayURL string @@ -175,7 +175,7 @@ func (p *WebTitlePlugin) getWebTitle(ctx context.Context, info *common.HostInfo, checkDataList = append(checkDataList, WebScan.CheckDatas{ Body: body, Headers: p.formatHeaders(resp.Header), - Favicon: p.fetchFaviconHash(ctx, baseURL), + Favicon: p.fetchFaviconHashWithClient(ctx, clientR, baseURL), }) title := p.extractTitle(string(body)) @@ -202,7 +202,7 @@ func (p *WebTitlePlugin) getWebTitle(ctx context.Context, info *common.HostInfo, checkDataList = append(checkDataList, WebScan.CheckDatas{ Body: bodyRedirect, Headers: p.formatHeaders(respRedirect.Header), - Favicon: p.fetchFaviconHash(ctx, redirectURL), + Favicon: p.fetchFaviconHashWithClient(ctx, clientR, redirectURL), }) // 如果原始页面没有标题,使用跳转后页面的标题 @@ -300,27 +300,19 @@ func (p *WebTitlePlugin) triggerPocScan(ctx context.Context, info *common.HostIn } func webTitleHTTPClients(isGM bool) (*http.Client, *http.Client) { - if isGM { - return firstHTTPClient(lib.ClientNoRedirectGM, defaultNoRedirectClient()), firstHTTPClient(lib.ClientGM, http.DefaultClient) - } - return firstHTTPClient(lib.ClientNoRedirect, defaultNoRedirectClient()), firstHTTPClient(lib.Client, http.DefaultClient) + return webTitleHTTPClientsWithSession(nil, isGM) } -func firstHTTPClient(clients ...*http.Client) *http.Client { - for _, client := range clients { - if client != nil { - return client - } +func webTitleHTTPClientsWithSession(session *common.ScanSession, isGM bool) (*http.Client, *http.Client) { + nr := lib.GetSessionHTTPClient(session, false, isGM) + r := lib.GetSessionHTTPClient(session, true, isGM) + if nr == nil { + nr = lib.GetSessionHTTPClient(session, false, false) } - return http.DefaultClient -} - -func defaultNoRedirectClient() *http.Client { - return &http.Client{ - CheckRedirect: func(*http.Request, []*http.Request) error { - return http.ErrUseLastResponse - }, + if r == nil { + r = lib.GetSessionHTTPClient(session, true, false) } + return nr, r } func readWebTitleBody(r io.Reader) ([]byte, error) { @@ -353,7 +345,11 @@ func (p *WebTitlePlugin) detectProtocol(ctx context.Context, info *common.HostIn host := info.Host port := info.Port - serviceInfo, exists := core.GetWebServiceInfo(host, port) + var state *common.State + if session != nil { + state = session.State + } + serviceInfo, exists := core.GetWebServiceInfoWithState(state, host, port) if exists { // 第一优先级:检查已缓存的协议检测结果 @@ -365,11 +361,7 @@ func (p *WebTitlePlugin) detectProtocol(ctx context.Context, info *common.HostIn // 注意:普通的"http"服务名不直接返回,因为可能是-u模式默认添加的协议 serviceName := strings.ToLower(serviceInfo.Name) if common.ContainsAny(serviceName, "https-gm", "https", "ssl", "tls") { - // 缓存协议信息到Extras - if serviceInfo.Extras == nil { - serviceInfo.Extras = make(map[string]string) - } - serviceInfo.Extras["protocol"] = "https" + core.SetWebServiceProtocolWithState(state, host, port, "https") return "https" } } @@ -380,10 +372,7 @@ func (p *WebTitlePlugin) detectProtocol(ctx context.Context, info *common.HostIn if detected != "" { // 缓存检测结果(避免重复检测) if exists { - if serviceInfo.Extras == nil { - serviceInfo.Extras = make(map[string]string) - } - serviceInfo.Extras["protocol"] = detected + core.SetWebServiceProtocolWithState(state, host, port, detected) } return detected } @@ -424,6 +413,10 @@ func truncateRunes(s string, maxRunes int) string { // fetchFaviconHash 下载 favicon.ico 并计算 hash func (p *WebTitlePlugin) fetchFaviconHash(ctx context.Context, baseURL string) fingerprint.FaviconHashes { + return p.fetchFaviconHashWithClient(ctx, nil, baseURL) +} + +func (p *WebTitlePlugin) fetchFaviconHashWithClient(ctx context.Context, client *http.Client, baseURL string) fingerprint.FaviconHashes { // 构造 favicon URL u, err := url.Parse(baseURL) if err != nil { @@ -438,7 +431,10 @@ func (p *WebTitlePlugin) fetchFaviconHash(ctx context.Context, baseURL string) f } req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36") - resp, err := lib.Client.Do(req) + if client == nil { + client = lib.GetHTTPClient(true, false) + } + resp, err := client.Do(req) if err != nil { return fingerprint.FaviconHashes{} } diff --git a/plugins/web/webtitle_test.go b/plugins/web/webtitle_test.go index 6d441aa3..d810b01d 100644 --- a/plugins/web/webtitle_test.go +++ b/plugins/web/webtitle_test.go @@ -251,13 +251,6 @@ func TestWebTitleHTTPClientsGM(t *testing.T) { } } -func TestFirstHTTPClientAllNil(t *testing.T) { - got := firstHTTPClient(nil, nil, nil) - if got != http.DefaultClient { - t.Fatalf("firstHTTPClient all nil = %v, want http.DefaultClient", got) - } -} - func TestFetchFaviconHashNon200(t *testing.T) { previous := lib.Client lib.Client = &http.Client{ diff --git a/web/api/project.go b/web/api/project.go index 14693846..488d7735 100644 --- a/web/api/project.go +++ b/web/api/project.go @@ -32,16 +32,23 @@ type ProjectStore struct { dir string } -var globalProjectStore *ProjectStore - -func init() { - home, _ := os.UserHomeDir() - dir := filepath.Join(home, ".fscan", "projects") - globalProjectStore = &ProjectStore{ - projects: make(map[string]*ProjectCache), - dir: dir, - } - globalProjectStore.loadAll() +var ( + globalProjectStoreOnce sync.Once + globalProjectStore *ProjectStore +) + +func getGlobalProjectStore() *ProjectStore { + globalProjectStoreOnce.Do(func() { + home, _ := os.UserHomeDir() + dir := filepath.Join(home, ".fscan", "projects") + ps := &ProjectStore{ + projects: make(map[string]*ProjectCache), + dir: dir, + } + ps.loadAll() + globalProjectStore = ps + }) + return globalProjectStore } // loadAll 从磁盘加载所有项目 @@ -204,7 +211,7 @@ type ProjectHandler struct { } func NewProjectHandler() *ProjectHandler { - return &ProjectHandler{store: globalProjectStore} + return &ProjectHandler{store: getGlobalProjectStore()} } // List 列出所有项目 diff --git a/web/api/result.go b/web/api/result.go index 1ec9c16a..04ddcba0 100644 --- a/web/api/result.go +++ b/web/api/result.go @@ -36,15 +36,21 @@ type ResultStore struct { db *sql.DB } -// 全局结果存储 -var globalResultStore *ResultStore +// 全局结果存储(按需懒初始化,避免包 init() 产生磁盘 I/O 与 panic) +var ( + globalResultStoreOnce sync.Once + globalResultStore *ResultStore +) -func init() { - store, err := NewResultStore() - if err != nil { - panic(fmt.Sprintf("failed to init result store: %v", err)) - } - globalResultStore = store +func getGlobalResultStore() *ResultStore { + globalResultStoreOnce.Do(func() { + store, err := NewResultStore() + if err != nil { + panic(fmt.Sprintf("failed to init result store: %v", err)) + } + globalResultStore = store + }) + return globalResultStore } // dbPath 返回数据库文件路径 @@ -275,7 +281,7 @@ type ResultHandler struct { // NewResultHandler 创建结果处理器 func NewResultHandler() *ResultHandler { return &ResultHandler{ - store: globalResultStore, + store: getGlobalResultStore(), } } diff --git a/web/api/scan.go b/web/api/scan.go index f9327f00..9ae6ac04 100644 --- a/web/api/scan.go +++ b/web/api/scan.go @@ -12,6 +12,7 @@ import ( "time" "github.com/shadow1ng/fscan/common" + "github.com/shadow1ng/fscan/common/output" "github.com/shadow1ng/fscan/core" "github.com/shadow1ng/fscan/web/ws" ) @@ -88,7 +89,7 @@ type ScanHandler struct { func NewScanHandler(hub *ws.Hub) *ScanHandler { return &ScanHandler{ hub: hub, - results: globalResultStore, + results: getGlobalResultStore(), } } @@ -126,8 +127,9 @@ func (h *ScanHandler) Start(w http.ResponseWriter, r *http.Request) { return } + startTime := time.Now() h.mu.Lock() - h.startTime = time.Now() + h.startTime = startTime h.mu.Unlock() // 清空旧结果 @@ -136,7 +138,7 @@ func (h *ScanHandler) Start(w http.ResponseWriter, r *http.Request) { // 广播扫描开始 h.hub.Broadcast(ws.MsgScanStarted, map[string]interface{}{ "host": req.Host, - "start_time": h.startTime, + "start_time": startTime, }) // 异步执行扫描 @@ -144,7 +146,7 @@ func (h *ScanHandler) Start(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]interface{}{ "status": "started", - "start_time": h.startTime, + "start_time": startTime, }) } @@ -160,11 +162,11 @@ func (h *ScanHandler) runScan(req ScanRequest) { cancel() h.mu.Lock() h.cancelFn = nil + startTime := h.startTime h.mu.Unlock() - common.ClearResultCallback() atomic.StoreInt32(&h.state, int32(ScanStateIdle)) h.hub.Broadcast(ws.MsgScanCompleted, map[string]interface{}{ - "duration": time.Since(h.startTime).Seconds(), + "duration": time.Since(startTime).Seconds(), "stats": h.results.Stats(), }) }() @@ -176,24 +178,21 @@ func (h *ScanHandler) runScan(req ScanRequest) { } state := session.State - // 过渡桥:全局状态同步(待 Phase 5 移除) - common.SetGlobalConfig(session.Config) - common.SetGlobalState(state) - // 项目缓存注入:把已知的 host:port 加入扫描目标 if req.ProjectID != "" { - if cached := globalProjectStore.CachedHostPorts(req.ProjectID); len(cached) > 0 { + if cached := getGlobalProjectStore().CachedHostPorts(req.ProjectID); len(cached) > 0 { state.SetHostPorts(append(state.GetHostPorts(), cached...)) } } - // 设置WebSocket结果回调 - common.SetResultCallback(func(result interface{}) { + // 通过会话 ResultSink 直接接收结果并推送 WebSocket(不依赖全局回调与全局单例) + session.ResultSink = func(result *output.ScanResult) error { item := h.results.Add(result) if item != nil { h.hub.Broadcast(ws.MsgScanResult, item) } - }) + return nil + } // 执行扫描 if _, err := core.RunScan(ctx, info, session); err != nil && !errors.Is(err, context.Canceled) { @@ -204,7 +203,7 @@ func (h *ScanHandler) runScan(req ScanRequest) { if req.ProjectID != "" { items := h.results.List() if len(items) > 0 { - _ = globalProjectStore.MergeResults(req.ProjectID, items) + _ = getGlobalProjectStore().MergeResults(req.ProjectID, items) } } } diff --git a/web/ws/hub.go b/web/ws/hub.go index d68adb63..18974552 100644 --- a/web/ws/hub.go +++ b/web/ws/hub.go @@ -45,9 +45,34 @@ type Message struct { // Client WebSocket客户端 type Client struct { - hub *Hub - conn *websocket.Conn - send chan []byte + hub *Hub + conn *websocket.Conn + send chan []byte + mu sync.Mutex + closed bool +} + +func (c *Client) trySend(data []byte) bool { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return false + } + select { + case c.send <- data: + return true + default: + return false + } +} + +func (c *Client) closeSend() { + c.mu.Lock() + defer c.mu.Unlock() + if !c.closed { + c.closed = true + close(c.send) + } } // Hub 管理所有WebSocket连接 @@ -56,6 +81,8 @@ type Hub struct { broadcast chan []byte register chan *Client unregister chan *Client + done chan struct{} + stopOnce sync.Once mu sync.RWMutex } @@ -66,13 +93,30 @@ func NewHub() *Hub { broadcast: make(chan []byte, 256), register: make(chan *Client), unregister: make(chan *Client), + done: make(chan struct{}), } } +// Stop 优雅停止Hub +func (h *Hub) Stop() { + h.stopOnce.Do(func() { + close(h.done) + }) +} + // Run 启动Hub func (h *Hub) Run() { for { select { + case <-h.done: + h.mu.Lock() + for client := range h.clients { + client.closeSend() + delete(h.clients, client) + } + h.mu.Unlock() + return + case client := <-h.register: h.mu.Lock() h.clients[client] = true @@ -85,24 +129,22 @@ func (h *Hub) Run() { Data: map[string]string{"status": "connected"}, } if data, err := json.Marshal(msg); err == nil { - client.send <- data + client.trySend(data) } case client := <-h.unregister: h.mu.Lock() if _, ok := h.clients[client]; ok { delete(h.clients, client) - close(client.send) + client.closeSend() } h.mu.Unlock() case message := <-h.broadcast: h.mu.Lock() for client := range h.clients { - select { - case client.send <- message: - default: - close(client.send) + if !client.trySend(message) { + client.closeSend() delete(h.clients, client) } } @@ -119,7 +161,10 @@ func (h *Hub) Broadcast(msgType MessageType, data interface{}) { Data: data, } if jsonData, err := json.Marshal(msg); err == nil { - h.broadcast <- jsonData + select { + case h.broadcast <- jsonData: + case <-h.done: + } } } @@ -177,7 +222,7 @@ func (c *Client) readPump() { Timestamp: time.Now().UnixMilli(), } if data, err := json.Marshal(pong); err == nil { - c.send <- data + c.trySend(data) } } } diff --git a/webscan/fingerprint/enhanced.go b/webscan/fingerprint/enhanced.go index 3739b6e5..b652ae23 100644 --- a/webscan/fingerprint/enhanced.go +++ b/webscan/fingerprint/enhanced.go @@ -100,6 +100,8 @@ func MatchEnhancedFingerprints(body []byte, headers string, favicon FaviconHashe } bodyStr := string(body) + bodyLower := strings.ToLower(bodyStr) + headersLower := strings.ToLower(headers) fingerprints := enhancedDB.Fingerprints total := len(fingerprints) @@ -115,8 +117,8 @@ func MatchEnhancedFingerprints(body []byte, headers string, favicon FaviconHashe // 每个 worker 处理的指纹数量 chunkSize := (total + workers - 1) / workers - // 结果收集 channel(带优先级信息) - resultCh := make(chan fingerprintMatch, total) + // 每个 worker 写入独立分片,避免分配大容量 channel 与额外关闭协程 + workerMatches := make([][]fingerprintMatch, workers) var wg sync.WaitGroup // 启动 worker @@ -131,36 +133,34 @@ func MatchEnhancedFingerprints(body []byte, headers string, favicon FaviconHashe } wg.Add(1) - go func(fps []*EnhancedFingerprint) { + go func(idx int, fps []*EnhancedFingerprint) { defer wg.Done() + var local []fingerprintMatch for _, fp := range fps { if len(fp.HTTP) == 0 { continue } httpRule := fp.HTTP[0] for _, matcher := range httpRule.Matchers { - if matchMatcher(matcher, bodyStr, headers, favicon) { - resultCh <- fingerprintMatch{ + if matchMatcherPrecomputed(matcher, bodyStr, bodyLower, headers, headersLower, favicon) { + local = append(local, fingerprintMatch{ Name: fp.Info.Name, Priority: calcPriority(fp, matcher.Type), - } + }) break } } } - }(fingerprints[start:end]) + workerMatches[idx] = local + }(i, fingerprints[start:end]) } - // 等待所有 worker 完成后关闭 channel - go func() { - wg.Wait() - close(resultCh) - }() + wg.Wait() // 收集结果 var matches []fingerprintMatch - for m := range resultCh { - matches = append(matches, m) + for _, local := range workerMatches { + matches = append(matches, local...) } // 按优先级排序(降序) @@ -214,10 +214,21 @@ func matchMatcher(matcher struct { CaseInsensitive bool `json:"case-insensitive"` Condition string `json:"condition"` }, body, headers string, favicon FaviconHashes) bool { + return matchMatcherPrecomputed(matcher, body, "", headers, "", favicon) +} +func matchMatcherPrecomputed(matcher struct { + Type string `json:"type"` + Words []string `json:"words"` + Regex []string `json:"regex"` + Hash []string `json:"hash"` + Part string `json:"part"` + CaseInsensitive bool `json:"case-insensitive"` + Condition string `json:"condition"` +}, body, bodyLower, headers, headersLower string, favicon FaviconHashes) bool { switch matcher.Type { case "word": - return matchWords(matcher, body, headers) + return matchWordsPrecomputed(matcher, body, bodyLower, headers, headersLower) case "regex": return matchRegex(matcher, body, headers) case "favicon": @@ -237,16 +248,40 @@ func matchWords(matcher struct { CaseInsensitive bool `json:"case-insensitive"` Condition string `json:"condition"` }, body, headers string) bool { + return matchWordsPrecomputed(matcher, body, "", headers, "") +} - // 确定匹配目标 - target := body +func matchWordsPrecomputed(matcher struct { + Type string `json:"type"` + Words []string `json:"words"` + Regex []string `json:"regex"` + Hash []string `json:"hash"` + Part string `json:"part"` + CaseInsensitive bool `json:"case-insensitive"` + Condition string `json:"condition"` +}, body, bodyLower, headers, headersLower string) bool { + // 确定匹配目标(优先使用预计算的小写副本,避免每条规则重复拷贝完整 Body) + var target string if matcher.Part == "header" { - target = headers - } - - // CaseInsensitive: target 转小写一次,Words 已在加载时预处理(直接调用时也兼容未预处理的词) - if matcher.CaseInsensitive { - target = strings.ToLower(target) + if matcher.CaseInsensitive { + if headersLower != "" || headers == "" { + target = headersLower + } else { + target = strings.ToLower(headers) + } + } else { + target = headers + } + } else { + if matcher.CaseInsensitive { + if bodyLower != "" || body == "" { + target = bodyLower + } else { + target = strings.ToLower(body) + } + } else { + target = body + } } // 默认condition为or diff --git a/webscan/fingerprint_scanner.go b/webscan/fingerprint_scanner.go index 6030735f..2884ac04 100644 --- a/webscan/fingerprint_scanner.go +++ b/webscan/fingerprint_scanner.go @@ -51,6 +51,7 @@ func InfoCheck(URL string, CheckData *[]CheckDatas) []string { // matchByRegex 使用正则规则匹配指纹 func matchByRegex(data CheckDatas) []string { var matched []string + bodyStr := string(data.Body) for _, rule := range fingerprint.RuleDatas { // 跳过编译失败的规则 @@ -62,7 +63,7 @@ func matchByRegex(data CheckDatas) []string { var isMatch bool switch rule.Type { case "code": - isMatch = rule.Compiled.MatchString(string(data.Body)) + isMatch = rule.Compiled.MatchString(bodyStr) default: isMatch = rule.Compiled.MatchString(data.Headers) } diff --git a/webscan/lib/Client.go b/webscan/lib/Client.go index 18a7e91e..1266831b 100644 --- a/webscan/lib/Client.go +++ b/webscan/lib/Client.go @@ -32,7 +32,7 @@ const ( ProxySocks5URL = "socks5://127.0.0.1:1080" ) -var gmtlsStdoutMu sync.Mutex +var clientMu sync.RWMutex // 全局HTTP客户端变量 var ( @@ -44,6 +44,127 @@ var ( keepAlive = 5 * time.Second // 连接保持时间 ) +// HTTPClientSet 封装单次扫描会话独立的 HTTP/国密客户端集合,避免并发扫描互相覆写全局客户端。 +type HTTPClientSet struct { + Client *http.Client + ClientNoRedirect *http.Client + ClientGM *http.Client + ClientNoRedirectGM *http.Client +} + +// Get 根据是否跟随重定向和是否国密返回对应客户端 +func (s *HTTPClientSet) Get(followRedirect, isGM bool) *http.Client { + if s == nil { + return nil + } + switch { + case isGM && followRedirect: + return s.ClientGM + case isGM && !followRedirect: + return s.ClientNoRedirectGM + case !isGM && followRedirect: + return s.Client + default: + return s.ClientNoRedirect + } +} + +// Close 释放客户端集合持有的空闲连接 +func (s *HTTPClientSet) Close() { + if s == nil { + return + } + if s.Client != nil { + if tr, ok := s.Client.Transport.(*http.Transport); ok { + tr.CloseIdleConnections() + } + } + if s.ClientGM != nil { + if tr, ok := s.ClientGM.Transport.(*http.Transport); ok { + tr.CloseIdleConnections() + } + } +} + +// GetHTTPClient 线程安全地获取全局 HTTP 客户端(未初始化时回退到默认客户端,避免 nil panic) +func GetHTTPClient(followRedirect, isGM bool) *http.Client { + clientMu.RLock() + var c *http.Client + switch { + case isGM && followRedirect: + c = ClientGM + case isGM && !followRedirect: + c = ClientNoRedirectGM + case !isGM && followRedirect: + c = Client + default: + c = ClientNoRedirect + } + clientMu.RUnlock() + if c != nil { + return c + } + if isGM { + return nil + } + fallback := &http.Client{Timeout: dialTimeout} + if !followRedirect { + fallback.CheckRedirect = func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + } + } + return fallback +} + +// GetSessionHTTPClient 优先从 ScanSession 获取独立 HTTP 客户端,未绑定时回退全局客户端 +func GetSessionHTTPClient(session *common.ScanSession, followRedirect, isGM bool) *http.Client { + if session != nil { + if set, ok := session.HTTPClients().(*HTTPClientSet); ok && set != nil { + if c := set.Get(followRedirect, isGM); c != nil { + return c + } + } + } + return GetHTTPClient(followRedirect, isGM) +} + +// NewHTTPClientSet 为单个扫描配置构建独立的 HTTP 客户端集合(不修改全局变量) +func NewHTTPClientSet(cfg *common.Config) (*HTTPClientSet, error) { + pocNum := cfg.POC.Num + if pocNum == 0 { + pocNum = 20 + } + set, err := buildHTTPClientSet(pocNum, cfg.Network.HTTPProxy, cfg.Network.WebTimeout, cfg.Network.MaxRedirects, &cfg.Network) + if err != nil { + return nil, fmt.Errorf("%s: %w", i18n.GetText("webscan_http_client_init_failed"), err) + } + return set, nil +} + +// InitSessionHTTP 为 ScanSession 初始化并绑定独立 HTTP 客户端集合(并发安全) +func InitSessionHTTP(session *common.ScanSession) (*HTTPClientSet, error) { + if session == nil || session.Config == nil { + return nil, fmt.Errorf("nil scan session") + } + set, err := NewHTTPClientSet(session.Config) + if err != nil { + return nil, err + } + session.SetHTTPClients(set) + + // 兼容仍直接访问全局 lib.Client 的遗留路径:仅在全局未初始化时填充,不覆写已有客户端 + clientMu.Lock() + if Client == nil { + Client = set.Client + ClientNoRedirect = set.ClientNoRedirect + ClientGM = set.ClientGM + ClientNoRedirectGM = set.ClientNoRedirectGM + } + clientMu.Unlock() + + return set, nil +} + // Inithttp 初始化HTTP客户端配置 func Inithttp(cfg *common.Config) error { // 获取POC并发数,默认20 @@ -87,7 +208,7 @@ func configureHTTPProxy(tr *http.Transport, legacyProxy string, networkConfig *c proxyConfig.Address = networkConfig.Socks5Proxy } - proxyManager := proxy.NewProxyManager(proxyConfig) + proxyManager, _ := proxy.NewIsolatedProxyManager(proxyConfig, false) proxyDialer, err := proxyManager.GetDialer() if err != nil { return fmt.Errorf("%s: %w", i18n.GetText("webscan_socks5_proxy_config_failed"), err) @@ -138,8 +259,36 @@ func normalizeHTTPProxyURL(proxyURL string) string { return "http://" + proxyURL } -// InitHTTPClient 创建HTTP客户端 +// InitHTTPClient 创建并更新全局 HTTP 客户端(兼容旧入口) func InitHTTPClient(ThreadsNum int, DownProxy string, Timeout time.Duration, maxRedirects int, networkConfig *common.NetworkConfig) error { + set, err := buildHTTPClientSet(ThreadsNum, DownProxy, Timeout, maxRedirects, networkConfig) + if err != nil { + return err + } + + clientMu.Lock() + oldClient, oldClientGM := Client, ClientGM + Client = set.Client + ClientNoRedirect = set.ClientNoRedirect + ClientGM = set.ClientGM + ClientNoRedirectGM = set.ClientNoRedirectGM + clientMu.Unlock() + + if oldClient != nil { + if oldTr, ok := oldClient.Transport.(*http.Transport); ok { + oldTr.CloseIdleConnections() + } + } + if oldClientGM != nil { + if oldTr, ok := oldClientGM.Transport.(*http.Transport); ok { + oldTr.CloseIdleConnections() + } + } + + return nil +} + +func buildHTTPClientSet(ThreadsNum int, DownProxy string, Timeout time.Duration, maxRedirects int, networkConfig *common.NetworkConfig) (*HTTPClientSet, error) { // 配置基础连接参数 dialer := &net.Dialer{ Timeout: dialTimeout, @@ -176,11 +325,11 @@ func InitHTTPClient(ThreadsNum int, DownProxy string, Timeout time.Duration, max // 统一配置代理 if err := configureHTTPProxy(tr, DownProxy, networkConfig); err != nil { - return err + return nil, err } // 创建标准HTTP客户端(限制重定向次数) - Client = &http.Client{ + newClient := &http.Client{ Transport: tr, Timeout: Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { @@ -192,33 +341,36 @@ func InitHTTPClient(ThreadsNum int, DownProxy string, Timeout time.Duration, max } // 创建不跟随重定向的HTTP客户端 - ClientNoRedirect = &http.Client{ + newClientNoRedirect := &http.Client{ Transport: tr, Timeout: Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } - // 创建国密TLS客户端(用于连接国密HTTPS站点) + // 创建国密TLS客户端(复用 tr.DialContext 以继承代理配置与 ctx 取消,不再劫持进程 os.Stdout) + baseDialContext := tr.DialContext trGM := &http.Transport{ + Proxy: tr.Proxy, DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - dialer := &net.Dialer{ - Timeout: dialTimeout, - KeepAlive: keepAlive, + rawConn, err := baseDialContext(ctx, network, addr) + if err != nil { + return nil, err } - // 抑制 gmtls 库的 fmt.Println("handshake error") 噪声 - gmtlsStdoutMu.Lock() - orig := os.Stdout - if devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0); err == nil { - os.Stdout = devNull - defer devNull.Close() + if deadline, ok := ctx.Deadline(); ok { + _ = rawConn.SetDeadline(deadline) + } else { + _ = rawConn.SetDeadline(time.Now().Add(dialTimeout)) } - conn, err := gmtls.DialWithDialer(dialer, network, addr, &gmtls.Config{ + gmConn := gmtls.Client(rawConn, &gmtls.Config{ GMSupport: gmtls.NewGMSupport(), InsecureSkipVerify: true, }) - os.Stdout = orig - gmtlsStdoutMu.Unlock() - return conn, err + if err := gmConn.Handshake(); err != nil { + _ = rawConn.Close() + return nil, err + } + _ = rawConn.SetDeadline(time.Time{}) + return gmConn, nil }, MaxConnsPerHost: 20, MaxIdleConns: 20, @@ -228,7 +380,7 @@ func InitHTTPClient(ThreadsNum int, DownProxy string, Timeout time.Duration, max DisableKeepAlives: false, } - ClientGM = &http.Client{ + newClientGM := &http.Client{ Transport: trGM, Timeout: Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { @@ -239,13 +391,18 @@ func InitHTTPClient(ThreadsNum int, DownProxy string, Timeout time.Duration, max }, } - ClientNoRedirectGM = &http.Client{ + newClientNoRedirectGM := &http.Client{ Transport: trGM, Timeout: Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, } - return nil + return &HTTPClientSet{ + Client: newClient, + ClientNoRedirect: newClientNoRedirect, + ClientGM: newClientGM, + ClientNoRedirectGM: newClientNoRedirectGM, + }, nil } // Poc 定义漏洞检测配置结构 diff --git a/webscan/lib/Eval.go b/webscan/lib/Eval.go index 51398fa9..211844be 100644 --- a/webscan/lib/Eval.go +++ b/webscan/lib/Eval.go @@ -486,7 +486,7 @@ func DoRequest(req *http.Request, redirect bool, session *common.ScanSession) (* if err != nil { reason = err.Error() } - common.LogError(i18n.Tr("webscan_request_restricted", req.URL.String(), reason)) + session.LogError(i18n.Tr("webscan_request_restricted", req.URL.String(), reason)) return nil, fmt.Errorf("%s", i18n.Tr("network_rate_limited", reason)) } } else { @@ -502,11 +502,7 @@ func DoRequest(req *http.Request, redirect bool, session *common.ScanSession) (* err error ) - if redirect { - oResp, err = requestClient(true).Do(req) - } else { - oResp, err = requestClient(false).Do(req) - } + oResp, err = GetSessionHTTPClient(session, redirect, false).Do(req) // 标准TLS握手级别失败时,尝试国密TLS客户端 // 跳过连接超时、拒绝等非 TLS 相关错误,避免无意义的国密握手尝试 @@ -516,17 +512,9 @@ func DoRequest(req *http.Request, redirect bool, session *common.ScanSession) (* req.Body = body } } - if redirect { - if clientGM := gmRequestClient(true); clientGM != nil { - if oResp2, err2 := clientGM.Do(req); err2 == nil { - oResp, err = oResp2, nil - } - } - } else { - if clientGM := gmRequestClient(false); clientGM != nil { - if oResp2, err2 := clientGM.Do(req); err2 == nil { - oResp, err = oResp2, nil - } + if clientGM := GetSessionHTTPClient(session, redirect, true); clientGM != nil { + if oResp2, err2 := clientGM.Do(req); err2 == nil { + oResp, err = oResp2, nil } } } diff --git a/webscan/lib/poc_adapter.go b/webscan/lib/poc_adapter.go index 597414ea..ffa5a208 100644 --- a/webscan/lib/poc_adapter.go +++ b/webscan/lib/poc_adapter.go @@ -247,28 +247,43 @@ func (n *NucleiPocAdapter) ToFscanPoc() (*Poc, error) { paths = []string{"{{BaseURL}}"} } - for _, path := range paths { - rule := Rules{ - Method: method, - Path: normalizeNucleiPath(path), - Headers: httpReq.Headers, - Body: httpReq.Body, - } + // 转换matchers为expression + expr := "response.status == 200" + if len(httpReq.Matchers) > 0 { + expr = convertNucleiMatchers(httpReq.Matchers, httpReq.MatchersCondition) + } - // 转换matchers为expression - if len(httpReq.Matchers) > 0 { - expr := convertNucleiMatchers(httpReq.Matchers, httpReq.MatchersCondition) - rule.Expression = expr - } else { - // 默认检查200状态码 - rule.Expression = "response.status == 200" + // Nuclei 中单个 HTTP 块配置多个 path 表示 OR 语义(任一路径命中即成功), + // 而 fscan 的 poc.Rules 是 AND 语义、poc.Groups 是 OR 语义。 + if len(paths) > 1 && len(n.HTTP) == 1 { + for i, path := range paths { + rule := Rules{ + Method: method, + Path: normalizeNucleiPath(path), + Headers: httpReq.Headers, + Body: httpReq.Body, + Expression: expr, + } + poc.Groups = append(poc.Groups, RuleItem{ + Key: fmt.Sprintf("path-%d", i), + Value: []Rules{rule}, + }) + } + } else { + for _, path := range paths { + rule := Rules{ + Method: method, + Path: normalizeNucleiPath(path), + Headers: httpReq.Headers, + Body: httpReq.Body, + Expression: expr, + } + poc.Rules = append(poc.Rules, rule) } - - poc.Rules = append(poc.Rules, rule) } } - if len(poc.Rules) == 0 { + if len(poc.Rules) == 0 && len(poc.Groups) == 0 { return nil, fmt.Errorf("%s", i18n.GetText("webscan_nuclei_no_http_rules")) } @@ -310,11 +325,11 @@ func convertNucleiMatchers(matchers []NucleiMatcher, matchersCondition string) s matcherConds = append(matcherConds, "false") } - // 单个matcher内的条件组合 + // 单个matcher内的条件组合(Nuclei 规范默认 OR,显式指定 and 时为 AND) if len(matcherConds) > 0 { - connector := " && " - if strings.EqualFold(m.Condition, "or") { - connector = " || " + connector := " || " + if strings.EqualFold(m.Condition, "and") { + connector = " && " } var combined string diff --git a/webscan/lib/poc_adapter_example_test.go b/webscan/lib/poc_adapter_example_test.go index 48c9a52a..dfefb77b 100644 --- a/webscan/lib/poc_adapter_example_test.go +++ b/webscan/lib/poc_adapter_example_test.go @@ -77,8 +77,14 @@ http: fmt.Printf(" ✓ 名称: %s\n", poc2.GetName()) fscanPoc2, _ := poc2.ToFscanPoc() - fmt.Printf(" ✓ 规则数: %d (Nuclei的2个path转为2个rule)\n", len(fscanPoc2.Rules)) - fmt.Printf(" ✓ 第一条规则表达式: %s\n", fscanPoc2.Rules[0].Expression[:80]+"...") + fmt.Printf(" ✓ 规则组数: %d (Nuclei的2个path转为2个OR规则组)\n", len(fscanPoc2.Groups)) + if len(fscanPoc2.Groups) > 0 && len(fscanPoc2.Groups[0].Value) > 0 { + expr := fscanPoc2.Groups[0].Value[0].Expression + if len(expr) > 80 { + expr = expr[:80] + "..." + } + fmt.Printf(" ✓ 第一条规则表达式: %s\n", expr) + } fmt.Println() // 示例3: 格式检测 diff --git a/webscan/lib/poc_adapter_test.go b/webscan/lib/poc_adapter_test.go index c6dbe68f..ec2e00dd 100644 --- a/webscan/lib/poc_adapter_test.go +++ b/webscan/lib/poc_adapter_test.go @@ -166,12 +166,15 @@ http: t.Errorf("Poc.Name = %v, want %v", poc.Name, "Test Nuclei Template") } - // Nuclei的两个path应该转换为2个rule - if len(poc.Rules) != 2 { - t.Errorf("len(Poc.Rules) = %v, want %v", len(poc.Rules), 2) + // Nuclei的两个path是OR语义,应该转换为2个规则组 + if len(poc.Groups) != 2 { + t.Fatalf("len(Poc.Groups) = %v, want %v", len(poc.Groups), 2) + } + if len(poc.Groups[0].Value) != 1 || len(poc.Groups[1].Value) != 1 { + t.Fatalf("unexpected group rule counts: %d, %d", len(poc.Groups[0].Value), len(poc.Groups[1].Value)) } - if poc.Rules[0].Path != "/admin" || poc.Rules[1].Path != "/api" { - t.Fatalf("Nuclei paths = %q, %q; want /admin, /api", poc.Rules[0].Path, poc.Rules[1].Path) + if poc.Groups[0].Value[0].Path != "/admin" || poc.Groups[1].Value[0].Path != "/api" { + t.Fatalf("Nuclei paths = %q, %q; want /admin, /api", poc.Groups[0].Value[0].Path, poc.Groups[1].Value[0].Path) } if poc.Detail.Author != "pdteam" { @@ -179,7 +182,7 @@ http: } // 验证expression包含word匹配 - if poc.Rules[0].Expression == "" { + if poc.Groups[0].Value[0].Expression == "" { t.Error("Rule.Expression should not be empty") } } diff --git a/webscan/lib/poc_executor.go b/webscan/lib/poc_executor.go index c87f8007..6b06f2a6 100644 --- a/webscan/lib/poc_executor.go +++ b/webscan/lib/poc_executor.go @@ -71,6 +71,8 @@ func CheckMultiPoc(req *http.Request, pocs []*Poc, workers int, pocCtx *POCConte workers = 1 } + ctx := req.Context() + // 创建任务通道,缓冲区大小为POC列表长度 tasks := make(chan Task, len(pocs)) var wg sync.WaitGroup @@ -82,11 +84,17 @@ func CheckMultiPoc(req *http.Request, pocs []*Poc, workers int, pocCtx *POCConte defer wg.Done() // 从任务通道循环获取任务 for task := range tasks { + if ctx.Err() != nil { + return + } // 执行POC检测,返回是否存在漏洞、错误信息和漏洞名称 isVulnerable, vulName, err := executePoc(task.Req, task.Poc, pocCtx) // 处理执行过程中的错误 if err != nil { + if ctx.Err() != nil { + return + } pocCtx.Session.LogError(i18n.Tr("webscan_poc_exec_error", task.Poc.Name, err)) continue } @@ -101,10 +109,15 @@ func CheckMultiPoc(req *http.Request, pocs []*Poc, workers int, pocCtx *POCConte } // 分发所有POC任务到通道 +dispatchLoop: for _, poc := range pocs { - tasks <- Task{ + select { + case <-ctx.Done(): + break dispatchLoop + case tasks <- Task{ Req: req, Poc: poc, + }: } } From b43e55d96e1078df52b89903c430b432846c913e Mon Sep 17 00:00:00 2001 From: ZacharyZcR Date: Wed, 2 Dec 2026 00:28:22 +0800 Subject: [PATCH 2/3] ci: parallelize workflow jobs, use prebuilt golangci-lint, and clean unused helpers --- .github/workflows/test-build.yml | 109 +++++++------------------------ .golangci.yml | 9 ++- plugins/services/oracle_raw.go | 4 -- webscan/lib/Eval.go | 24 ------- 4 files changed, 28 insertions(+), 118 deletions(-) diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml index 164e3285..5e881e12 100644 --- a/.github/workflows/test-build.yml +++ b/.github/workflows/test-build.yml @@ -35,6 +35,10 @@ on: - '**/*.jpeg' workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: contents: read @@ -45,7 +49,7 @@ jobs: lint: name: 代码检查 runs-on: ubuntu-latest - timeout-minutes: 10 + timeout-minutes: 5 steps: - name: 检出代码 @@ -58,54 +62,15 @@ jobs: cache: true - name: 运行 golangci-lint - run: | - # 安装 golangci-lint v2 (需 Go 1.22+,仅用于静态分析,不影响二进制兼容性) - go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.12.1 - - # 运行检查 - golangci-lint run --timeout=5m > lint_output.txt 2>&1 || true - cat lint_output.txt - - # 过滤非关键问题(复杂度建议和 staticcheck 风格建议不阻塞 CI) - CRITICAL=$(grep -E "\.go:[0-9]+:[0-9]+:" lint_output.txt \ - | grep -vE "gocognit|gocyclo|QF[0-9]+| S[0-9]+|ST[0-9]+" || true) - if [ -n "$CRITICAL" ]; then - echo "❌ Linting failed with critical issues:" - echo "$CRITICAL" | head -20 - exit 1 - fi - echo "✅ Lint 检查通过" - - - name: 检查代码复杂度(质量门禁) - run: | - echo "### 🚦 复杂度质量门禁" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - - # 检查认知复杂度>80的函数 - COMPLEX_FUNCS=$(golangci-lint run --disable-all --enable=gocognit --out-format=line-number 2>&1 | grep "cognitive complexity" | grep -v "typechecking" || true) - - if [ -n "$COMPLEX_FUNCS" ]; then - HIGH_COMPLEX=$(echo "$COMPLEX_FUNCS" | awk '{print $NF}' | sed 's/[()]//g' | awk -F'>' '{if ($1 > 80) print}' | wc -l) - - if [ "$HIGH_COMPLEX" -gt 0 ]; then - echo "❌ **发现 $HIGH_COMPLEX 个复杂度>80的函数**" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo '```' >> $GITHUB_STEP_SUMMARY - echo "$COMPLEX_FUNCS" | awk '{print $NF}' | sed 's/[()]//g' | awk -F'>' '{if ($1 > 80) print "复杂度:", $1, "- 必须重构"}' >> $GITHUB_STEP_SUMMARY - echo '```' >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "⚠️ 请重构复杂度>80的函数后再提交" >> $GITHUB_STEP_SUMMARY - exit 1 - fi - fi - - echo "✅ 代码复杂度检查通过(所有函数≤80)" >> $GITHUB_STEP_SUMMARY + uses: golangci/golangci-lint-action@v7 + with: + version: v2.12.1 + args: --timeout=4m test: - name: 单元测试和构建 + name: 单元测试 runs-on: ubuntu-latest - timeout-minutes: 10 - needs: lint + timeout-minutes: 8 steps: - name: 检出代码 @@ -117,19 +82,14 @@ jobs: go-version: '1.25' cache: true - - name: 下载依赖 - run: | - go mod download - go mod verify - - name: 运行测试 run: | - # 排除第三方grdp库测试(存在环境依赖问题) + # 排除第三方 grdp 库测试(存在环境依赖问题) PKGS=$(go list ./... | grep -v '/libs/grdp/') go test -vet=off -race -coverprofile=coverage.out -covermode=atomic $PKGS - name: Web 接口回归测试 - run: go test -vet=off -race -tags web ./web/api + run: go test -vet=off -race -tags web ./web/... - name: 上传覆盖率 uses: actions/upload-artifact@v4 @@ -138,44 +98,21 @@ jobs: path: coverage.out retention-days: 7 - - name: 显示覆盖率 - run: | - echo "### 测试覆盖率报告" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - go tool cover -func=coverage.out >> $GITHUB_STEP_SUMMARY - - - name: 检查覆盖率(质量门禁) + - name: 覆盖率摘要 run: | - echo "" >> $GITHUB_STEP_SUMMARY - echo "### 🚦 覆盖率质量门禁" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - - # 提取总体覆盖率(awk 整数比较,不需要 bc) TOTAL_COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print int($3)}') - - echo "总体覆盖率: ${TOTAL_COVERAGE}%" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - - # 警告阈值:总体<40% - if [ "$TOTAL_COVERAGE" -lt 40 ]; then - echo "⚠️ **警告**: 总体覆盖率 ${TOTAL_COVERAGE}% < 40%,建议补充测试" >> $GITHUB_STEP_SUMMARY - fi - - # 检查是否有新增的未测试文件(0%覆盖率) ZERO_COVERAGE_FILES=$(go tool cover -func=coverage.out | awk '$3 == "0.0%" && $1 !~ /_test\.go/' | wc -l) - if [ "$ZERO_COVERAGE_FILES" -gt 0 ]; then - echo "⚠️ **警告**: 发现 $ZERO_COVERAGE_FILES 个文件覆盖率为0%" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "请为新代码补充单元测试" >> $GITHUB_STEP_SUMMARY - else - echo "✅ 覆盖率检查通过" >> $GITHUB_STEP_SUMMARY - fi + { + echo "### 🚦 测试覆盖率摘要" + echo "" + echo "- 总体覆盖率: **${TOTAL_COVERAGE}%**" + echo "- 0% 覆盖函数/条目数: **${ZERO_COVERAGE_FILES}**" + } >> "$GITHUB_STEP_SUMMARY" build: name: 构建验证 runs-on: ubuntu-latest timeout-minutes: 5 - needs: test steps: - name: 检出代码 @@ -187,9 +124,7 @@ jobs: go-version: '1.25' cache: true - - name: 构建验证 + - name: 构建验证(CLI & Web) run: | - # 只验证能否编译通过,不需要多平台构建 - echo "🔨 验证 Linux/amd64 构建..." CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /dev/null . - echo "✅ 构建成功" + go build -tags web -o /dev/null . diff --git a/.golangci.yml b/.golangci.yml index 325a3e51..83ca873a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,12 +12,17 @@ linters: - staticcheck - unused - ineffassign - - gocyclo - gocognit settings: govet: disable: - printf + staticcheck: + checks: + - "all" + - "-ST*" + - "-S*" + - "-QF*" errcheck: check-type-assertions: true exclude-functions: @@ -26,8 +31,6 @@ linters: - os.Remove - (github.com/hirochachacha/go-smb2.Session).Logoff - (github.com/hirochachacha/go-smb2.Share).Umount - gocyclo: - min-complexity: 35 gocognit: min-complexity: 80 exclusions: diff --git a/plugins/services/oracle_raw.go b/plugins/services/oracle_raw.go index a059b7bb..b014d3cf 100644 --- a/plugins/services/oracle_raw.go +++ b/plugins/services/oracle_raw.go @@ -97,10 +97,6 @@ type oracleSummary struct { errorMessage []byte } -func oracleRawAuth(ctx context.Context, host string, port int, serviceName, username, password string, timeout time.Duration) error { - return oracleRawAuthWithSession(ctx, nil, host, port, serviceName, username, password, timeout) -} - func oracleRawAuthWithSession(ctx context.Context, session *common.ScanSession, host string, port int, serviceName, username, password string, timeout time.Duration) error { addr := net.JoinHostPort(host, strconv.Itoa(port)) conn, err := dialServiceTCP(ctx, session, addr, timeout) diff --git a/webscan/lib/Eval.go b/webscan/lib/Eval.go index 211844be..5cbacefa 100644 --- a/webscan/lib/Eval.go +++ b/webscan/lib/Eval.go @@ -538,30 +538,6 @@ func DoRequest(req *http.Request, redirect bool, session *common.ScanSession) (* return resp, err } -func requestClient(redirect bool) *http.Client { - if redirect { - if Client != nil { - return Client - } - return http.DefaultClient - } - if ClientNoRedirect != nil { - return ClientNoRedirect - } - return &http.Client{ - CheckRedirect: func(*http.Request, []*http.Request) error { - return http.ErrUseLastResponse - }, - } -} - -func gmRequestClient(redirect bool) *http.Client { - if redirect { - return ClientGM - } - return ClientNoRedirectGM -} - // ParseURL 解析 TargetURL 并转换为自定义 TargetURL 类型 func ParseURL(u *url.URL) *UrlType { return &UrlType{ From 9b05856bbcada693edca81e6fea1165dfc14975f Mon Sep 17 00:00:00 2001 From: ZacharyZcR Date: Wed, 2 Dec 2026 00:42:53 +0800 Subject: [PATCH 3/3] fix: harden service plugins, propagate ICMP context, cache base CEL programs, and guard SDK language state --- core/icmp.go | 94 ++++++++++++++++++++++++++------- pkg/fscan/scanner.go | 35 ++++++++++-- plugins/services/imap.go | 12 ++++- plugins/services/ms17010_exp.go | 4 +- plugins/services/neo4j.go | 15 +++--- plugins/services/pop3.go | 12 ++++- plugins/services/rabbitmq.go | 14 ++--- plugins/services/rdp.go | 17 +++--- plugins/services/telnet.go | 77 ++++++++++++++++++++------- plugins/services/types.go | 33 ++++++++++++ webscan/lib/Eval.go | 16 +++++- 11 files changed, 258 insertions(+), 71 deletions(-) diff --git a/core/icmp.go b/core/icmp.go index 247273f6..570ab80b 100644 --- a/core/icmp.go +++ b/core/icmp.go @@ -61,15 +61,19 @@ func CheckLive(ctx context.Context, hostslist []string, Ping bool, session *comm // 根据Ping参数选择检测方式 if Ping { // 使用ping方式探测 - RunPing(hostslist, chanHosts, &livewg) + runPingContext(ctx, hostslist, chanHosts, &livewg) } else { - probeWithICMP(hostslist, chanHosts, &aliveHosts, &aliveHostsMu, config, state, &livewg) + probeWithICMP(ctx, hostslist, chanHosts, &aliveHosts, &aliveHostsMu, config, state, &livewg) } // 等待所有检测完成 livewg.Wait() close(chanHosts) + if ctx.Err() != nil { + return aliveHosts + } + // TCP 补充探测:当 ICMP/Ping 响应率过低时自动启用 // 这对防火墙过滤 ICMP 的环境特别有用 aliveHosts = tcpSupplementaryProbe(ctx, hostslist, aliveHosts, session) @@ -165,36 +169,40 @@ func handleAliveHosts(chanHosts chan string, hostslist []string, isPing bool, al } // probeWithICMP 使用ICMP方式探测 -func probeWithICMP(hostslist []string, chanHosts chan string, aliveHosts *[]string, aliveHostsMu *sync.Mutex, config *common.Config, state *common.State, livewg *sync.WaitGroup) { +func probeWithICMP(ctx context.Context, hostslist []string, chanHosts chan string, aliveHosts *[]string, aliveHostsMu *sync.Mutex, config *common.Config, state *common.State, livewg *sync.WaitGroup) { // 代理模式下自动禁用ICMP,直接降级为Ping // ICMP在代理环境无法正常工作 if shouldDisableICMP() { if !config.Output.Silent { common.LogInfo(i18n.GetText("proxy_mode_disable_icmp")) } - RunPing(hostslist, chanHosts, livewg) + runPingContext(ctx, hostslist, chanHosts, livewg) return } // 尝试监听本地ICMP conn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0") if err == nil { - RunIcmp1(hostslist, conn, chanHosts, aliveHosts, aliveHostsMu, config, state, livewg) + runIcmp1Context(ctx, hostslist, conn, chanHosts, aliveHosts, aliveHostsMu, config, state, livewg) return } // 尝试无监听ICMP探测 - conn2, err := net.DialTimeout("ip4:icmp", "127.0.0.1", 3*time.Second) + conn2, err := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, "ip4:icmp", "127.0.0.1") if err == nil { defer func() { _ = conn2.Close() }() - RunIcmp2(hostslist, chanHosts, config, state, livewg) + runIcmp2Context(ctx, hostslist, chanHosts, config, state, livewg) + return + } + + if ctx.Err() != nil { return } common.LogInfo(i18n.GetText("switching_to_ping")) // 降级使用ping探测 - RunPing(hostslist, chanHosts, livewg) + runPingContext(ctx, hostslist, chanHosts, livewg) } // shouldDisableICMP 检查是否应该禁用ICMP @@ -258,6 +266,10 @@ const ( // - 只有"连续 500ms 无新响应"才提前结束 // - 保留原有最大等待时间作为兜底 func waitAdaptive(hostslist []string, aliveHosts *[]string, aliveHostsMu *sync.Mutex) { + waitAdaptiveContext(context.Background(), hostslist, aliveHosts, aliveHostsMu) +} + +func waitAdaptiveContext(ctx context.Context, hostslist []string, aliveHosts *[]string, aliveHostsMu *sync.Mutex) { totalHosts := len(hostslist) // 根据主机数量设置最大超时时间(保持原有逻辑作为兜底) @@ -270,8 +282,15 @@ func waitAdaptive(hostslist []string, aliveHosts *[]string, aliveHostsMu *sync.M lastAliveCount := 0 lastChangeTime := start + ticker := time.NewTicker(icmpCheckInterval) + defer ticker.Stop() + for { - time.Sleep(icmpCheckInterval) // 避免 CPU 空转 + select { + case <-ctx.Done(): + return + case <-ticker.C: + } // 读取当前存活数 aliveHostsMu.Lock() @@ -316,6 +335,10 @@ func waitAdaptive(hostslist []string, aliveHosts *[]string, aliveHostsMu *sync.M // RunIcmp1 使用ICMP批量探测主机存活(监听模式) func RunIcmp1(hostslist []string, conn *icmp.PacketConn, chanHosts chan string, aliveHosts *[]string, aliveHostsMu *sync.Mutex, config *common.Config, state *common.State, livewg *sync.WaitGroup) { + runIcmp1Context(context.Background(), hostslist, conn, chanHosts, aliveHosts, aliveHostsMu, config, state, livewg) +} + +func runIcmp1Context(ctx context.Context, hostslist []string, conn *icmp.PacketConn, chanHosts chan string, aliveHosts *[]string, aliveHostsMu *sync.Mutex, config *common.Config, state *common.State, livewg *sync.WaitGroup) { // 使用atomic.Bool保证并发安全 var endflag atomic.Bool var listenerWg sync.WaitGroup @@ -388,14 +411,22 @@ func RunIcmp1(hostslist []string, conn *icmp.PacketConn, chanHosts chan string, limiter := state.GetICMPLimiter(config.Network.ICMPRate) for i := range packets { + if ctx.Err() != nil { + break + } limiter.Wait(1) + if ctx.Err() != nil { + break + } _, _ = conn.WriteTo(packets[i].data, packets[i].dst) } // 自适应等待响应 // 算法:监控响应增量,连续一段时间无新响应则提前结束 // 保守原则:保留最大等待时间兜底,确保不漏掉慢响应主机 - waitAdaptive(hostslist, aliveHosts, aliveHostsMu) + if ctx.Err() == nil { + waitAdaptiveContext(ctx, hostslist, aliveHosts, aliveHostsMu) + } endflag.Store(true) _ = conn.Close() @@ -404,6 +435,10 @@ func RunIcmp1(hostslist []string, conn *icmp.PacketConn, chanHosts chan string, // RunIcmp2 使用ICMP并发探测主机存活(无监听模式) func RunIcmp2(hostslist []string, chanHosts chan string, config *common.Config, state *common.State, livewg *sync.WaitGroup) { + runIcmp2Context(context.Background(), hostslist, chanHosts, config, state, livewg) +} + +func runIcmp2Context(ctx context.Context, hostslist []string, chanHosts chan string, config *common.Config, state *common.State, livewg *sync.WaitGroup) { // 控制并发数 num := 1000 if len(hostslist) < num { @@ -415,9 +450,14 @@ func RunIcmp2(hostslist []string, chanHosts chan string, config *common.Config, rateLimiter := state.GetICMPLimiter(config.Network.ICMPRate) // 获取速率限制器 // 并发探测 +icmp2Loop: for _, host := range hostslist { + select { + case <-ctx.Done(): + break icmp2Loop + case limiter <- struct{}{}: + } wg.Add(1) - limiter <- struct{}{} go func(host string) { defer func() { @@ -425,8 +465,11 @@ func RunIcmp2(hostslist []string, chanHosts chan string, config *common.Config, wg.Done() }() + if ctx.Err() != nil { + return + } rateLimiter.Wait(1) // 等待令牌,控制发包速率 - if icmpalive(host) { + if icmpaliveContext(ctx, host) { livewg.Add(1) select { case chanHosts <- host: @@ -444,11 +487,11 @@ func RunIcmp2(hostslist []string, chanHosts chan string, config *common.Config, } // icmpalive 检测主机ICMP是否存活 -func icmpalive(host string) bool { +func icmpaliveContext(ctx context.Context, host string) bool { startTime := time.Now() // 建立ICMP连接 - conn, err := net.DialTimeout("ip4:icmp", host, 6*time.Second) + conn, err := (&net.Dialer{Timeout: 6 * time.Second}).DialContext(ctx, "ip4:icmp", host) if err != nil { return false } @@ -476,6 +519,10 @@ func icmpalive(host string) bool { // RunPing 使用系统Ping命令并发探测主机存活 func RunPing(hostslist []string, chanHosts chan string, livewg *sync.WaitGroup) { + runPingContext(context.Background(), hostslist, chanHosts, livewg) +} + +func runPingContext(ctx context.Context, hostslist []string, chanHosts chan string, livewg *sync.WaitGroup) { var wg sync.WaitGroup // 并发数根据主机数动态调整,上限 200 concurrency := len(hostslist) @@ -485,9 +532,14 @@ func RunPing(hostslist []string, chanHosts chan string, livewg *sync.WaitGroup) limiter := make(chan struct{}, concurrency) // 并发探测 +pingLoop: for _, host := range hostslist { + select { + case <-ctx.Done(): + break pingLoop + case limiter <- struct{}{}: + } wg.Add(1) - limiter <- struct{}{} go func(host string) { defer func() { @@ -495,7 +547,7 @@ func RunPing(hostslist []string, chanHosts chan string, livewg *sync.WaitGroup) wg.Done() }() - if ExecCommandPing(host) { + if execCommandPingContext(ctx, host) { livewg.Add(1) select { case chanHosts <- host: @@ -524,6 +576,10 @@ func containsPingError(output string) bool { // ExecCommandPing 执行系统Ping命令检测主机存活 func ExecCommandPing(ip string) bool { + return execCommandPingContext(context.Background(), ip) +} + +func execCommandPingContext(ctx context.Context, ip string) bool { // 过滤黑名单字符(命令注入防护) for _, char := range pingForbiddenChars { if strings.Contains(ip, char) { @@ -535,11 +591,11 @@ func ExecCommandPing(ip string) bool { // 根据操作系统选择不同的ping命令 switch runtime.GOOS { case "windows": - command = exec.Command("cmd", "/c", "ping -n 1 -w 1 "+ip+" && echo true || echo false") + command = exec.CommandContext(ctx, "cmd", "/c", "ping -n 1 -w 1 "+ip+" && echo true || echo false") case "darwin": - command = exec.Command("/bin/bash", "-c", "ping -c 1 -W 1 "+ip+" && echo true || echo false") + command = exec.CommandContext(ctx, "/bin/bash", "-c", "ping -c 1 -W 1 "+ip+" && echo true || echo false") default: // linux - command = exec.Command("/bin/bash", "-c", "ping -c 1 -w 1 "+ip+" && echo true || echo false") + command = exec.CommandContext(ctx, "/bin/bash", "-c", "ping -c 1 -w 1 "+ip+" && echo true || echo false") } // 捕获命令输出 diff --git a/pkg/fscan/scanner.go b/pkg/fscan/scanner.go index 3cebc16e..7f9be6ab 100644 --- a/pkg/fscan/scanner.go +++ b/pkg/fscan/scanner.go @@ -292,14 +292,43 @@ func (s *Scanner) injectTaskID(result *Result) { result.Details["task_id"] = s.config.TaskID } +var ( + sdkLangMu sync.Mutex + sdkLangRefs int + sdkLangSaved string +) + +func pushSDKLanguage(lang string) func() { + sdkLangMu.Lock() + if sdkLangRefs == 0 { + sdkLangSaved = i18n.GetLanguage() + } + sdkLangRefs++ + i18n.SetLanguage(lang) + sdkLangMu.Unlock() + + var once sync.Once + return func() { + once.Do(func() { + sdkLangMu.Lock() + if sdkLangRefs > 0 { + sdkLangRefs-- + if sdkLangRefs == 0 { + i18n.SetLanguage(sdkLangSaved) + } + } + sdkLangMu.Unlock() + }) + } +} + func (s *Scanner) scanOne(ctx context.Context, target Target, sink common.ResultSink, opts scanOpts) (core.ScanReport, error) { fv := buildFlagVars(s.config, target) info := common.HostInfo{Host: strings.TrimSpace(target.Host), URL: strings.TrimSpace(target.URL)} if strings.TrimSpace(s.config.Language) != "" { - previousLanguage := i18n.GetLanguage() - i18n.SetLanguage(fv.Language) - defer i18n.SetLanguage(previousLanguage) + restoreLanguage := pushSDKLanguage(fv.Language) + defer restoreLanguage() } cfg, state, err := common.BuildConfig(fv, &info) diff --git a/plugins/services/imap.go b/plugins/services/imap.go index a028144d..9af3e4d3 100644 --- a/plugins/services/imap.go +++ b/plugins/services/imap.go @@ -5,6 +5,7 @@ package services import ( "bufio" "context" + "net" "strings" "time" @@ -28,7 +29,7 @@ func (p *IMAPPlugin) Scan(ctx context.Context, info *common.HostInfo, session *c } addr := info.Target() - conn, err := session.DialTCP(ctx, "tcp", addr, timeout) + conn, err := dialIMAP(ctx, session, addr, info.Port, timeout) if err != nil { return &ScanResult{Success: false, Service: "imap"} } @@ -73,9 +74,16 @@ func (p *IMAPPlugin) Scan(ctx context.Context, info *common.HostInfo, session *c return serviceResult } +func dialIMAP(ctx context.Context, session *common.ScanSession, addr string, port int, timeout time.Duration) (net.Conn, error) { + if port == 993 { + return dialServiceTLS(ctx, session, addr, timeout) + } + return dialServiceTCP(ctx, session, addr, timeout) +} + func (p *IMAPPlugin) tryLogin(ctx context.Context, info *common.HostInfo, cred plugins.Credential, timeout time.Duration, session *common.ScanSession) *ScanResult { addr := info.Target() - conn, err := session.DialTCP(ctx, "tcp", addr, timeout) + conn, err := dialIMAP(ctx, session, addr, info.Port, timeout) if err != nil { return nil } diff --git a/plugins/services/ms17010_exp.go b/plugins/services/ms17010_exp.go index 56ccb36e..e7045283 100644 --- a/plugins/services/ms17010_exp.go +++ b/plugins/services/ms17010_exp.go @@ -789,7 +789,7 @@ func makeSMB1EchoPacket(treeID, userID uint16) []byte { } func smb1FreeHole(address string, start bool) (net.Conn, error) { - conn, err := net.Dial("tcp", address) + conn, err := net.DialTimeout("tcp", address, 10*time.Second) if err != nil { return nil, fmt.Errorf("failed to connect host: %s", err) } @@ -917,7 +917,7 @@ func smb2Grooms(address string, grooms int) ([]net.Conn, error) { } }() for i := 0; i < grooms; i++ { - conn, err := net.Dial("tcp", address) + conn, err := net.DialTimeout("tcp", address, 10*time.Second) if err != nil { return nil, fmt.Errorf("failed to connect target: %s", err) } diff --git a/plugins/services/neo4j.go b/plugins/services/neo4j.go index b4c5fb56..f3d32f45 100644 --- a/plugins/services/neo4j.go +++ b/plugins/services/neo4j.go @@ -47,8 +47,10 @@ func (p *Neo4jPlugin) Scan(ctx context.Context, info *common.HostInfo, session * } } - // 使用公共框架进行并发凭据测试 - authFn := p.createAuthFunc(info, session) + // 使用公共框架进行并发凭据测试(复用同一个 HTTP 连接池) + client, closeClient := newServiceHTTPClient(session, config.ModuleTimeout()) + defer closeClient() + authFn := p.createAuthFunc(info, session, client) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "neo4j", testConfig) @@ -61,19 +63,16 @@ func (p *Neo4jPlugin) Scan(ctx context.Context, info *common.HostInfo, session * } // createAuthFunc 创建Neo4j认证函数 -func (p *Neo4jPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { +func (p *Neo4jPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession, client *http.Client) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doNeo4jAuth(ctx, info, cred, session) + return p.doNeo4jAuth(ctx, info, cred, session, client) } } // doNeo4jAuth 执行Neo4j认证 -func (p *Neo4jPlugin) doNeo4jAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { - config := session.Config +func (p *Neo4jPlugin) doNeo4jAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession, client *http.Client) *AuthResult { baseURL := "http://" + info.Target() - client := &http.Client{Timeout: config.ModuleTimeout()} - req, err := http.NewRequestWithContext(ctx, "GET", baseURL+"/user/neo4j", nil) if err != nil { return &AuthResult{ diff --git a/plugins/services/pop3.go b/plugins/services/pop3.go index a83d8a56..1fff8a9e 100644 --- a/plugins/services/pop3.go +++ b/plugins/services/pop3.go @@ -6,6 +6,7 @@ import ( "bufio" "context" "fmt" + "net" "strings" "time" @@ -29,7 +30,7 @@ func (p *POP3Plugin) Scan(ctx context.Context, info *common.HostInfo, session *c } addr := info.Target() - conn, err := session.DialTCP(ctx, "tcp", addr, timeout) + conn, err := dialPOP3(ctx, session, addr, info.Port, timeout) if err != nil { return &ScanResult{Success: false, Service: "pop3"} } @@ -74,9 +75,16 @@ func (p *POP3Plugin) Scan(ctx context.Context, info *common.HostInfo, session *c return serviceResult } +func dialPOP3(ctx context.Context, session *common.ScanSession, addr string, port int, timeout time.Duration) (net.Conn, error) { + if port == 995 { + return dialServiceTLS(ctx, session, addr, timeout) + } + return dialServiceTCP(ctx, session, addr, timeout) +} + func (p *POP3Plugin) tryLogin(ctx context.Context, info *common.HostInfo, cred plugins.Credential, timeout time.Duration, session *common.ScanSession) *ScanResult { addr := info.Target() - conn, err := session.DialTCP(ctx, "tcp", addr, timeout) + conn, err := dialPOP3(ctx, session, addr, info.Port, timeout) if err != nil { return nil } diff --git a/plugins/services/rabbitmq.go b/plugins/services/rabbitmq.go index 216a3011..e4fa72d9 100644 --- a/plugins/services/rabbitmq.go +++ b/plugins/services/rabbitmq.go @@ -51,8 +51,10 @@ func (p *RabbitMQPlugin) Scan(ctx context.Context, info *common.HostInfo, sessio } } - // 使用公共框架进行并发凭据测试 - authFn := p.createAuthFunc(info, session) + // 使用公共框架进行并发凭据测试(复用同一个 HTTP 连接池) + client, closeClient := newServiceHTTPClient(session, config.ModuleTimeout()) + defer closeClient() + authFn := p.createAuthFunc(info, session, client) testConfig := DefaultConcurrentTestConfigWithTarget(config, info) result := TestCredentialsConcurrently(ctx, credentials, authFn, "rabbitmq", testConfig) @@ -65,15 +67,14 @@ func (p *RabbitMQPlugin) Scan(ctx context.Context, info *common.HostInfo, sessio } // createAuthFunc 创建RabbitMQ认证函数 -func (p *RabbitMQPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession) AuthFunc { +func (p *RabbitMQPlugin) createAuthFunc(info *common.HostInfo, session *common.ScanSession, client *http.Client) AuthFunc { return func(ctx context.Context, cred Credential) *AuthResult { - return p.doRabbitMQAuth(ctx, info, cred, session) + return p.doRabbitMQAuth(ctx, info, cred, session, client) } } // doRabbitMQAuth 执行RabbitMQ认证 -func (p *RabbitMQPlugin) doRabbitMQAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession) *AuthResult { - config := session.Config +func (p *RabbitMQPlugin) doRabbitMQAuth(ctx context.Context, info *common.HostInfo, cred Credential, session *common.ScanSession, client *http.Client) *AuthResult { // 对于AMQP端口,使用HTTP管理接口 port := info.Port if port == 5672 || port == 5671 { @@ -84,7 +85,6 @@ func (p *RabbitMQPlugin) doRabbitMQAuth(ctx context.Context, info *common.HostIn } baseURL := "http://" + net.JoinHostPort(info.Host, strconv.Itoa(port)) - client := &http.Client{Timeout: config.ModuleTimeout()} req, err := http.NewRequestWithContext(ctx, "GET", baseURL+"/api/overview", nil) if err != nil { diff --git a/plugins/services/rdp.go b/plugins/services/rdp.go index 73281e4f..d10b9bbf 100644 --- a/plugins/services/rdp.go +++ b/plugins/services/rdp.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "strings" + "sync" "github.com/shadow1ng/fscan/common" "github.com/shadow1ng/fscan/common/i18n" @@ -27,19 +28,23 @@ func NewRDPPlugin() *RDPPlugin { } } +// grdp 的 login.LogLever / login.Socks5Proxy 是第三方库包级全局变量,用互斥锁避免并发扫描串代理。 +var rdpGlobalMu sync.Mutex + // Scan 执行RDP扫描 - 系统指纹识别 + 真实暴力破解 func (p *RDPPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *ScanResult { config := session.Config state := session.State target := info.Target() - // 配置grdp日志级别 + rdpGlobalMu.Lock() + prevProxy := login.Socks5Proxy login.LogLever = glog.NONE // 静默模式,避免干扰输出 - - // 配置代理 - if config.Network.Socks5Proxy != "" { - login.Socks5Proxy = config.Network.Socks5Proxy - } + login.Socks5Proxy = config.Network.Socks5Proxy + defer func() { + login.Socks5Proxy = prevProxy + rdpGlobalMu.Unlock() + }() // 生成测试凭据(提前生成,用于判断是否为单一凭据测试) credentials := GenerateCredentials("rdp", config) diff --git a/plugins/services/telnet.go b/plugins/services/telnet.go index ca9d5395..8c0beace 100644 --- a/plugins/services/telnet.go +++ b/plugins/services/telnet.go @@ -132,7 +132,7 @@ func (p *TelnetPlugin) doTelnetAuth(ctx context.Context, info *common.HostInfo, _ = conn.SetDeadline(time.Now().Add(session.Config.ModuleTimeout())) - if p.performTelnetAuth(conn, cred.Username, cred.Password) { + if p.performTelnetAuth(ctx, conn, cred.Username, cred.Password) { resultChan <- &AuthResult{ Success: true, Conn: &telnetConnWrapper{conn}, @@ -233,7 +233,9 @@ func (p *TelnetPlugin) testUnauthAccess(ctx context.Context, info *common.HostIn _ = conn.SetReadDeadline(time.Now().Add(telnetBannerTimeout)) n, err := conn.Read(buffer) if err != nil { - time.Sleep(telnetRetryDelay) + if !sleepCtx(ctx, telnetRetryDelay) { + return + } continue } @@ -259,7 +261,9 @@ func (p *TelnetPlugin) testUnauthAccess(ctx context.Context, info *common.HostIn break } - time.Sleep(telnetRetryDelay) + if !sleepCtx(ctx, telnetRetryDelay) { + return + } } resultChan <- nil @@ -273,8 +277,19 @@ func (p *TelnetPlugin) testUnauthAccess(ctx context.Context, info *common.HostIn } } +func sleepCtx(ctx context.Context, d time.Duration) bool { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return false + case <-timer.C: + return true + } +} + // performTelnetAuth 执行Telnet认证 -func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password string) bool { +func (p *TelnetPlugin) performTelnetAuth(ctx context.Context, conn net.Conn, username, password string) bool { buffer := make([]byte, 1024) loginPromptReceived := false @@ -287,7 +302,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin _ = conn.SetReadDeadline(time.Now().Add(telnetReadTimeout)) n, err := conn.Read(buffer) if err != nil { - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } continue } @@ -303,7 +320,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin break } - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } } if !loginPromptReceived { @@ -315,7 +334,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin return false } - time.Sleep(telnetRetryDelay) + if !sleepCtx(ctx, telnetRetryDelay) { + return false + } passwordPromptReceived := false attempts = 0 maxPasswordAttempts := 5 @@ -326,7 +347,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin _ = conn.SetReadDeadline(time.Now().Add(telnetReadTimeout)) n, readErr := conn.Read(buffer) if readErr != nil { - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } continue } @@ -339,7 +362,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin break } - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } } if !passwordPromptReceived { @@ -351,7 +376,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin return false } - time.Sleep(telnetAuthDelay) + if !sleepCtx(ctx, telnetAuthDelay) { + return false + } attempts = 0 maxResultAttempts := 5 @@ -361,7 +388,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin _ = conn.SetReadDeadline(time.Now().Add(telnetReadTimeout)) n, err := conn.Read(buffer) if err != nil { - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } continue } @@ -376,7 +405,9 @@ func (p *TelnetPlugin) performTelnetAuth(conn net.Conn, username, password strin return false } - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + return false + } } return false @@ -634,7 +665,7 @@ func (p *TelnetPlugin) verifyCommandExecution(ctx context.Context, info *common. // 需要认证时先登录 if username != "" || password != "" { - if !p.performTelnetAuth(conn, username, password) { + if !p.performTelnetAuth(ctx, conn, username, password) { resultChan <- rceResult{} return } @@ -644,11 +675,13 @@ func (p *TelnetPlugin) verifyCommandExecution(ctx context.Context, info *common. } // 等待 shell 稳定后清空缓冲区 - time.Sleep(telnetRetryDelay) + if !sleepCtx(ctx, telnetRetryDelay) { + return + } p.drainBuffer(conn) // 尝试 Linux/Unix 命令 - output, err := p.sendCommand(conn, "echo CMD_START && id && uname -a && echo CMD_END\r\n", telnetRCECmdTimeout) + output, err := p.sendCommand(ctx, conn, "echo CMD_START && id && uname -a && echo CMD_END\r\n", telnetRCECmdTimeout) if err == nil && strings.Contains(output, "CMD_START") { if osType := p.detectOSType(output); osType != "" { resultChan <- rceResult{true, osType, p.extractEvidence(output)} @@ -657,7 +690,7 @@ func (p *TelnetPlugin) verifyCommandExecution(ctx context.Context, info *common. } // 尝试 Windows 命令 - output, err = p.sendCommand(conn, "echo CMD_START && whoami && ver && echo CMD_END\r\n", telnetRCECmdTimeout) + output, err = p.sendCommand(ctx, conn, "echo CMD_START && whoami && ver && echo CMD_END\r\n", telnetRCECmdTimeout) if err == nil && strings.Contains(output, "CMD_START") { lower := strings.ToLower(output) if strings.Contains(lower, "windows") || strings.Contains(lower, "microsoft") { @@ -667,7 +700,7 @@ func (p *TelnetPlugin) verifyCommandExecution(ctx context.Context, info *common. } // 尝试网络设备命令 - output, err = p.sendCommand(conn, "show version\r\n", telnetRCECmdTimeout) + output, err = p.sendCommand(ctx, conn, "show version\r\n", telnetRCECmdTimeout) if err == nil { if strings.Contains(output, "Cisco IOS") { resultChan <- rceResult{true, "Cisco IOS", p.extractEvidence(output)} @@ -691,13 +724,15 @@ func (p *TelnetPlugin) verifyCommandExecution(ctx context.Context, info *common. } // sendCommand 发送命令并读取输出 -func (p *TelnetPlugin) sendCommand(conn net.Conn, cmd string, timeout time.Duration) (string, error) { +func (p *TelnetPlugin) sendCommand(ctx context.Context, conn net.Conn, cmd string, timeout time.Duration) (string, error) { _ = conn.SetWriteDeadline(time.Now().Add(timeout)) if _, err := conn.Write([]byte(cmd)); err != nil { return "", err } - time.Sleep(telnetAuthDelay) + if !sleepCtx(ctx, telnetAuthDelay) { + return "", ctx.Err() + } _ = conn.SetReadDeadline(time.Now().Add(timeout)) var result strings.Builder @@ -713,7 +748,9 @@ func (p *TelnetPlugin) sendCommand(conn net.Conn, cmd string, timeout time.Durat if err != nil { break } - time.Sleep(telnetReadDelay) + if !sleepCtx(ctx, telnetReadDelay) { + break + } } return result.String(), nil diff --git a/plugins/services/types.go b/plugins/services/types.go index 540273bc..788d1e9c 100644 --- a/plugins/services/types.go +++ b/plugins/services/types.go @@ -2,7 +2,9 @@ package services import ( "context" + "crypto/tls" "net" + "net/http" "time" "github.com/shadow1ng/fscan/common" @@ -45,6 +47,37 @@ func dialServiceTCP(ctx context.Context, session *common.ScanSession, addr strin return (&net.Dialer{Timeout: timeout}).DialContext(ctx, "tcp", addr) } +// dialServiceTLS 通过 ScanSession 建立 TCP 连接后执行 TLS 握手(支持代理、限速与 ctx 取消)。 +func dialServiceTLS(ctx context.Context, session *common.ScanSession, addr string, timeout time.Duration) (net.Conn, error) { + rawConn, err := dialServiceTCP(ctx, session, addr, timeout) + if err != nil { + return nil, err + } + if timeout > 0 { + _ = rawConn.SetDeadline(time.Now().Add(timeout)) + } + tlsConn := tls.Client(rawConn, &tls.Config{ + InsecureSkipVerify: true, + MinVersion: tls.VersionTLS10, + }) + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = rawConn.Close() + return nil, err + } + return tlsConn, nil +} + +// newServiceHTTPClient 创建复用连接池且走 session.DialTCP 的服务 HTTP 客户端。 +func newServiceHTTPClient(session *common.ScanSession, timeout time.Duration) (*http.Client, func()) { + tr := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + DialContext: func(dialCtx context.Context, network, addr string) (net.Conn, error) { + return dialServiceTCP(dialCtx, session, addr, timeout) + }, + } + return &http.Client{Timeout: timeout, Transport: tr}, tr.CloseIdleConnections +} + // udpProbe 执行带超时保护的 UDP 探测(防止 Write/Read 在某些内核下永久阻塞) // 返回读到的数据和长度,超时/错误返回 nil func udpProbe(ctx context.Context, session *common.ScanSession, target string, timeout time.Duration, pkt []byte, bufSize int) ([]byte, int) { diff --git a/webscan/lib/Eval.go b/webscan/lib/Eval.go index 5cbacefa..b7a4c825 100644 --- a/webscan/lib/Eval.go +++ b/webscan/lib/Eval.go @@ -139,6 +139,9 @@ func MakeVarDecl(key, value string) *exprpb.Decl { } } +// baseProgCache 跨目标、跨会话共享基础 CEL 环境下的已编译 Program,避免重复编译 AST。 +var baseProgCache sync.Map // map[string]cel.Program + // CelProgCache 缓存编译后的 CEL Program,避免同一 POC 内重复编译 // 在 executePoc 中创建,同一个 POC 的所有规则/参数组合共享 type CelProgCache map[string]cel.Program @@ -155,8 +158,15 @@ func EvaluateCached(env *cel.Env, expression string, params map[string]interface } var program cel.Program + useGlobalBaseCache := env == baseEnv && baseEnv != nil - if cache != nil { + if useGlobalBaseCache { + if cached, ok := baseProgCache.Load(expression); ok { + if prog, ok := cached.(cel.Program); ok { + program = prog + } + } + } else if cache != nil { if cached, ok := cache[expression]; ok { program = cached } @@ -174,7 +184,9 @@ func EvaluateCached(env *cel.Env, expression string, params map[string]interface return nil, fmt.Errorf("%s: %w", i18n.GetText("webscan_program_create_failed"), err) } - if cache != nil { + if useGlobalBaseCache { + baseProgCache.Store(expression, program) + } else if cache != nil { cache[expression] = program } }