mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-22 19:21:52 +08:00
feat: v2.1.0 核心重构与功能增强
## 架构重构
- 全局变量消除,迁移至 Config/State 对象
- SMB 插件融合(smb/smb2/smbghost/smbinfo)
- 服务探测重构,实现 Nmap 风格 fallback 机制
- 输出系统重构,TXT 实时刷盘 + 双写机制
- i18n 框架升级至 go-i18n
## 性能优化
- 正则表达式预编译
- 内存优化 map[string]struct{}
- 并发指纹匹配
- SOCKS5 连接复用
- 滑动窗口调度 + 自适应线程池
## 新功能
- Web 管理界面
- 多格式 POC 适配(xray/afrog)
- 增强指纹库(3139条)
- Favicon hash 指纹识别
- 插件选择性编译(Build Tags)
- fscan-lab 靶场环境
- 默认端口扩展(62→133)
## 构建系统
- 添加 no_local tag 支持排除本地插件
- 多版本构建:fscan/fscan-nolocal/fscan-web
- CI 添加 snapshot 模式支持仅测试构建
## Bug 修复
- 修复 120+ 个问题,包括 RDP panic、批量扫描漏报、
JSON 输出格式、Redis 检测、Context 超时等
## 测试增强
- 单元测试覆盖率 74-100%
- 并发安全测试
- 集成测试(Web/端口/服务/SSH/ICMP)
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
//go:build web
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// ScanPreset 扫描预设
|
||||
type ScanPreset struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
NameEn string `json:"name_en"`
|
||||
Description string `json:"description"`
|
||||
DescEn string `json:"description_en"`
|
||||
Ports string `json:"ports"`
|
||||
ScanMode string `json:"scan_mode"`
|
||||
ThreadNum int `json:"thread_num"`
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
|
||||
// PluginInfo 插件信息
|
||||
type PluginInfo struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"` // service, web, local
|
||||
Description string `json:"description"`
|
||||
DescEn string `json:"description_en"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// ConfigHandler 配置处理器
|
||||
type ConfigHandler struct{}
|
||||
|
||||
// NewConfigHandler 创建配置处理器
|
||||
func NewConfigHandler() *ConfigHandler {
|
||||
return &ConfigHandler{}
|
||||
}
|
||||
|
||||
// 预设配置
|
||||
var presets = []ScanPreset{
|
||||
{
|
||||
ID: "quick",
|
||||
Name: "快速扫描",
|
||||
NameEn: "Quick Scan",
|
||||
Description: "仅扫描常用端口,速度最快",
|
||||
DescEn: "Scan common ports only, fastest speed",
|
||||
Ports: "21,22,23,80,443,445,1433,3306,3389,6379,8080",
|
||||
ScanMode: "all",
|
||||
ThreadNum: 1000,
|
||||
Timeout: 2,
|
||||
},
|
||||
{
|
||||
ID: "standard",
|
||||
Name: "标准扫描",
|
||||
NameEn: "Standard Scan",
|
||||
Description: "扫描主要端口,平衡速度和覆盖",
|
||||
DescEn: "Scan main ports, balance between speed and coverage",
|
||||
Ports: "21,22,23,25,80,110,135,139,143,443,445,465,587,993,995,1433,1521,3306,3389,5432,5900,6379,8080,8443,9000,27017",
|
||||
ScanMode: "all",
|
||||
ThreadNum: 600,
|
||||
Timeout: 3,
|
||||
},
|
||||
{
|
||||
ID: "full",
|
||||
Name: "完整扫描",
|
||||
NameEn: "Full Scan",
|
||||
Description: "扫描所有常用端口,最完整",
|
||||
DescEn: "Scan all common ports, most comprehensive",
|
||||
Ports: "1-1000,1433,1521,3306,3389,5432,5900,6379,8000-9000,27017",
|
||||
ScanMode: "all",
|
||||
ThreadNum: 400,
|
||||
Timeout: 5,
|
||||
},
|
||||
{
|
||||
ID: "stealth",
|
||||
Name: "隐蔽扫描",
|
||||
NameEn: "Stealth Scan",
|
||||
Description: "低速扫描,减少被检测风险",
|
||||
DescEn: "Low-speed scan, reduce detection risk",
|
||||
Ports: "21,22,23,80,443,445,3389,8080",
|
||||
ScanMode: "all",
|
||||
ThreadNum: 50,
|
||||
Timeout: 10,
|
||||
},
|
||||
{
|
||||
ID: "web",
|
||||
Name: "Web专项",
|
||||
NameEn: "Web Focus",
|
||||
Description: "专注Web服务和漏洞检测",
|
||||
DescEn: "Focus on web services and vulnerability detection",
|
||||
Ports: "80,443,8080,8443,8000,8888,9000,9090,9999",
|
||||
ScanMode: "all",
|
||||
ThreadNum: 200,
|
||||
Timeout: 5,
|
||||
},
|
||||
}
|
||||
|
||||
// 插件列表
|
||||
var plugins = []PluginInfo{
|
||||
// 服务类
|
||||
{Name: "ssh", Type: "service", Description: "SSH服务检测与爆破", DescEn: "SSH service detection and brute force", Enabled: true},
|
||||
{Name: "smb", Type: "service", Description: "SMB服务检测与爆破", DescEn: "SMB service detection and brute force", Enabled: true},
|
||||
{Name: "rdp", Type: "service", Description: "RDP服务检测", DescEn: "RDP service detection", Enabled: true},
|
||||
{Name: "mysql", Type: "service", Description: "MySQL数据库检测与爆破", DescEn: "MySQL database detection and brute force", Enabled: true},
|
||||
{Name: "mssql", Type: "service", Description: "MSSQL数据库检测与爆破", DescEn: "MSSQL database detection and brute force", Enabled: true},
|
||||
{Name: "postgresql", Type: "service", Description: "PostgreSQL数据库检测与爆破", DescEn: "PostgreSQL database detection and brute force", Enabled: true},
|
||||
{Name: "redis", Type: "service", Description: "Redis服务检测与未授权访问", DescEn: "Redis service detection and unauthorized access", Enabled: true},
|
||||
{Name: "mongodb", Type: "service", Description: "MongoDB数据库检测", DescEn: "MongoDB database detection", Enabled: true},
|
||||
{Name: "ftp", Type: "service", Description: "FTP服务检测与爆破", DescEn: "FTP service detection and brute force", Enabled: true},
|
||||
{Name: "telnet", Type: "service", Description: "Telnet服务检测", DescEn: "Telnet service detection", Enabled: true},
|
||||
|
||||
// Web类
|
||||
{Name: "webinfo", Type: "web", Description: "Web指纹识别", DescEn: "Web fingerprinting", Enabled: true},
|
||||
{Name: "poc", Type: "web", Description: "POC漏洞检测", DescEn: "POC vulnerability detection", Enabled: true},
|
||||
|
||||
// 本地类
|
||||
{Name: "avdetect", Type: "local", Description: "杀软检测", DescEn: "Antivirus detection", Enabled: false},
|
||||
{Name: "cleaner", Type: "local", Description: "痕迹清理", DescEn: "Trace cleaning", Enabled: false},
|
||||
}
|
||||
|
||||
// Presets 获取扫描预设
|
||||
func (h *ConfigHandler) Presets(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, presets)
|
||||
}
|
||||
|
||||
// Plugins 获取插件列表
|
||||
func (h *ConfigHandler) Plugins(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, plugins)
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
//go:build web
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ResultItem 扫描结果项
|
||||
type ResultItem struct {
|
||||
ID int64 `json:"id"`
|
||||
Time time.Time `json:"time"`
|
||||
Type string `json:"type"` // host, port, service, vuln
|
||||
Target string `json:"target"`
|
||||
Status string `json:"status"`
|
||||
Details interface{} `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// ResultStore 结果存储
|
||||
type ResultStore struct {
|
||||
mu sync.RWMutex
|
||||
items []ResultItem
|
||||
counter int64
|
||||
stats ScanStats
|
||||
// 去重
|
||||
seen map[string]bool
|
||||
// service 类型按 target 索引,用于更新
|
||||
serviceIndex map[string]int
|
||||
}
|
||||
|
||||
// 全局结果存储
|
||||
var globalResultStore = &ResultStore{
|
||||
items: make([]ResultItem, 0),
|
||||
seen: make(map[string]bool),
|
||||
serviceIndex: make(map[string]int),
|
||||
}
|
||||
|
||||
// Add 添加结果,返回格式化后的结果项(去重,重复则返回nil)
|
||||
func (s *ResultStore) Add(result interface{}) *ResultItem {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
item := ResultItem{
|
||||
Time: time.Now(),
|
||||
Details: result,
|
||||
}
|
||||
|
||||
// 根据结果类型分类
|
||||
if m, ok := result.(map[string]interface{}); ok {
|
||||
if t, ok := m["type"].(string); ok {
|
||||
item.Type = strings.ToLower(t) // 统一转小写
|
||||
}
|
||||
if target, ok := m["target"].(string); ok {
|
||||
item.Target = target
|
||||
}
|
||||
if status, ok := m["status"].(string); ok {
|
||||
item.Status = status
|
||||
}
|
||||
// 从details提取更多信息
|
||||
if details, ok := m["details"].(map[string]interface{}); ok {
|
||||
item.Details = details
|
||||
// 组合 target:port
|
||||
if port, ok := details["port"]; ok {
|
||||
if item.Target != "" && !strings.Contains(item.Target, ":") {
|
||||
item.Target = fmt.Sprintf("%s:%v", item.Target, port)
|
||||
}
|
||||
}
|
||||
// 构建更有意义的status
|
||||
item.Status = buildStatusFromDetails(item.Type, item.Status, details)
|
||||
}
|
||||
}
|
||||
|
||||
// 生成去重键
|
||||
key := fmt.Sprintf("%s|%s|%s", item.Type, item.Target, item.Status)
|
||||
if s.seen[key] {
|
||||
return nil // 完全重复,不添加
|
||||
}
|
||||
|
||||
// service/port 类型特殊处理:同一 target 只保留最详细的
|
||||
if item.Type == "service" || item.Type == "port" {
|
||||
indexKey := item.Type + "|" + item.Target
|
||||
if idx, exists := s.serviceIndex[indexKey]; exists {
|
||||
oldStatus := s.items[idx].Status
|
||||
// 如果旧的是基础状态,新的更详细,则更新
|
||||
if (oldStatus == "identified" || oldStatus == "open" || oldStatus == "") &&
|
||||
item.Status != "identified" && item.Status != "open" && item.Status != "" {
|
||||
s.items[idx].Status = item.Status
|
||||
s.items[idx].Details = item.Details
|
||||
s.items[idx].Time = item.Time
|
||||
s.seen[key] = true
|
||||
return &s.items[idx]
|
||||
}
|
||||
// 否则跳过(保留已有信息)
|
||||
return nil
|
||||
}
|
||||
// 新记录,记录索引
|
||||
s.serviceIndex[indexKey] = len(s.items)
|
||||
}
|
||||
|
||||
s.seen[key] = true
|
||||
|
||||
// 统计
|
||||
switch item.Type {
|
||||
case "host":
|
||||
s.stats.HostsScanned++
|
||||
case "port":
|
||||
s.stats.PortsScanned++
|
||||
case "service":
|
||||
s.stats.ServicesFound++
|
||||
case "vuln":
|
||||
s.stats.VulnsFound++
|
||||
}
|
||||
|
||||
s.counter++
|
||||
item.ID = s.counter
|
||||
s.items = append(s.items, item)
|
||||
return &item
|
||||
}
|
||||
|
||||
// List 获取所有结果
|
||||
func (s *ResultStore) List() []ResultItem {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return append([]ResultItem{}, s.items...)
|
||||
}
|
||||
|
||||
// Stats 获取统计信息
|
||||
func (s *ResultStore) Stats() ScanStats {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.stats
|
||||
}
|
||||
|
||||
// Clear 清空结果
|
||||
func (s *ResultStore) Clear() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.items = make([]ResultItem, 0)
|
||||
s.counter = 0
|
||||
s.stats = ScanStats{}
|
||||
s.seen = make(map[string]bool)
|
||||
s.serviceIndex = make(map[string]int)
|
||||
}
|
||||
|
||||
// ResultHandler 结果处理器
|
||||
type ResultHandler struct {
|
||||
store *ResultStore
|
||||
}
|
||||
|
||||
// NewResultHandler 创建结果处理器
|
||||
func NewResultHandler() *ResultHandler {
|
||||
return &ResultHandler{
|
||||
store: globalResultStore,
|
||||
}
|
||||
}
|
||||
|
||||
// List 获取结果列表
|
||||
func (h *ResultHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 支持类型过滤
|
||||
typeFilter := r.URL.Query().Get("type")
|
||||
items := h.store.List()
|
||||
|
||||
if typeFilter != "" {
|
||||
filtered := make([]ResultItem, 0)
|
||||
for _, item := range items {
|
||||
if item.Type == typeFilter {
|
||||
filtered = append(filtered, item)
|
||||
}
|
||||
}
|
||||
items = filtered
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"items": items,
|
||||
"total": len(items),
|
||||
"stats": h.store.Stats(),
|
||||
})
|
||||
}
|
||||
|
||||
// ExportOutput 导出输出结构(与CLI格式一致)
|
||||
type ExportOutput struct {
|
||||
ScanTime time.Time `json:"scan_time"`
|
||||
Summary ExportSummary `json:"summary"`
|
||||
Hosts []ResultItem `json:"hosts,omitempty"`
|
||||
Ports []ResultItem `json:"ports,omitempty"`
|
||||
Services []ResultItem `json:"services,omitempty"`
|
||||
Vulns []ResultItem `json:"vulns,omitempty"`
|
||||
}
|
||||
|
||||
// ExportSummary 导出摘要
|
||||
type ExportSummary struct {
|
||||
TotalHosts int `json:"total_hosts"`
|
||||
TotalPorts int `json:"total_ports"`
|
||||
TotalServices int `json:"total_services"`
|
||||
TotalVulns int `json:"total_vulns"`
|
||||
}
|
||||
|
||||
// Export 导出结果(与CLI格式一致)
|
||||
func (h *ResultHandler) Export(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
format := r.URL.Query().Get("format")
|
||||
if format == "" {
|
||||
format = "json"
|
||||
}
|
||||
|
||||
items := h.store.List()
|
||||
|
||||
// 按类型分类
|
||||
var hosts, ports, services, vulns []ResultItem
|
||||
for _, item := range items {
|
||||
switch item.Type {
|
||||
case "host":
|
||||
hosts = append(hosts, item)
|
||||
case "port":
|
||||
ports = append(ports, item)
|
||||
case "service":
|
||||
services = append(services, item)
|
||||
case "vuln":
|
||||
vulns = append(vulns, item)
|
||||
}
|
||||
}
|
||||
|
||||
switch format {
|
||||
case "json":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=fscan_results.json")
|
||||
|
||||
output := ExportOutput{
|
||||
ScanTime: time.Now(),
|
||||
Summary: ExportSummary{
|
||||
TotalHosts: len(hosts),
|
||||
TotalPorts: len(ports),
|
||||
TotalServices: len(services),
|
||||
TotalVulns: len(vulns),
|
||||
},
|
||||
Hosts: hosts,
|
||||
Ports: ports,
|
||||
Services: services,
|
||||
Vulns: vulns,
|
||||
}
|
||||
json.NewEncoder(w).Encode(output)
|
||||
|
||||
case "csv":
|
||||
w.Header().Set("Content-Type", "text/csv")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=fscan_results.csv")
|
||||
writer := csv.NewWriter(w)
|
||||
|
||||
// Hosts section
|
||||
if len(hosts) > 0 {
|
||||
writer.Write([]string{"# Hosts"})
|
||||
writer.Write([]string{"Target"})
|
||||
for _, item := range hosts {
|
||||
writer.Write([]string{item.Target})
|
||||
}
|
||||
writer.Write([]string{})
|
||||
}
|
||||
|
||||
// Ports section
|
||||
if len(ports) > 0 {
|
||||
writer.Write([]string{"# Ports"})
|
||||
writer.Write([]string{"Target", "Port", "Status"})
|
||||
for _, item := range ports {
|
||||
port := extractPort(item.Target)
|
||||
target := extractHost(item.Target)
|
||||
writer.Write([]string{target, port, "open"})
|
||||
}
|
||||
writer.Write([]string{})
|
||||
}
|
||||
|
||||
// Services section
|
||||
if len(services) > 0 {
|
||||
writer.Write([]string{"# Services"})
|
||||
writer.Write([]string{"Target", "Service", "Version", "Banner"})
|
||||
for _, item := range services {
|
||||
service, version, banner := extractServiceInfo(item.Details)
|
||||
writer.Write([]string{item.Target, service, version, banner})
|
||||
}
|
||||
writer.Write([]string{})
|
||||
}
|
||||
|
||||
// Vulns section
|
||||
if len(vulns) > 0 {
|
||||
writer.Write([]string{"# Vulns"})
|
||||
writer.Write([]string{"Target", "Type", "Details"})
|
||||
for _, item := range vulns {
|
||||
vulnType := extractVulnType(item.Details)
|
||||
writer.Write([]string{item.Target, vulnType, item.Status})
|
||||
}
|
||||
writer.Write([]string{})
|
||||
}
|
||||
|
||||
writer.Flush()
|
||||
|
||||
default:
|
||||
http.Error(w, "Unsupported format", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
// extractPort 从 "ip:port" 中提取端口
|
||||
func extractPort(target string) string {
|
||||
if idx := strings.LastIndex(target, ":"); idx != -1 {
|
||||
return target[idx+1:]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// extractHost 从 "ip:port" 中提取主机
|
||||
func extractHost(target string) string {
|
||||
if idx := strings.LastIndex(target, ":"); idx != -1 {
|
||||
return target[:idx]
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
// extractServiceInfo 从 details 中提取服务信息
|
||||
func extractServiceInfo(details interface{}) (service, version, banner string) {
|
||||
if m, ok := details.(map[string]interface{}); ok {
|
||||
if s, ok := m["service"].(string); ok {
|
||||
service = s
|
||||
}
|
||||
if s, ok := m["name"].(string); ok && service == "" {
|
||||
service = s
|
||||
}
|
||||
if v, ok := m["version"].(string); ok {
|
||||
version = v
|
||||
}
|
||||
if b, ok := m["banner"].(string); ok {
|
||||
banner = escapeControlChars(b)
|
||||
if len(banner) > 100 {
|
||||
banner = banner[:100] + "..."
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// extractVulnType 从 details 中提取漏洞类型
|
||||
func extractVulnType(details interface{}) string {
|
||||
if m, ok := details.(map[string]interface{}); ok {
|
||||
if t, ok := m["type"].(string); ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// escapeControlChars 转义控制字符
|
||||
func escapeControlChars(s string) string {
|
||||
replacer := strings.NewReplacer(
|
||||
"\r\n", "\\r\\n",
|
||||
"\n", "\\n",
|
||||
"\r", "\\r",
|
||||
"\t", "\\t",
|
||||
)
|
||||
return replacer.Replace(s)
|
||||
}
|
||||
|
||||
// Clear 清空结果
|
||||
func (h *ResultHandler) Clear(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
h.store.Clear()
|
||||
writeJSON(w, http.StatusOK, map[string]string{
|
||||
"status": "cleared",
|
||||
})
|
||||
}
|
||||
|
||||
// buildStatusFromDetails 从details构建可读的status
|
||||
func buildStatusFromDetails(resultType, originalStatus string, details map[string]interface{}) string {
|
||||
var parts []string
|
||||
|
||||
switch resultType {
|
||||
case "port":
|
||||
return "open"
|
||||
|
||||
case "service":
|
||||
// 服务名
|
||||
if name, ok := details["name"].(string); ok && name != "" {
|
||||
parts = append(parts, name)
|
||||
}
|
||||
// 版本
|
||||
if version, ok := details["version"].(string); ok && version != "" {
|
||||
parts = append(parts, version)
|
||||
}
|
||||
// 产品
|
||||
if product, ok := details["product"].(string); ok && product != "" {
|
||||
parts = append(parts, product)
|
||||
}
|
||||
// 系统
|
||||
if os, ok := details["os"].(string); ok && os != "" {
|
||||
parts = append(parts, os)
|
||||
}
|
||||
if len(parts) > 0 {
|
||||
return strings.Join(parts, " | ")
|
||||
}
|
||||
|
||||
case "vuln":
|
||||
// 统一漏洞显示格式
|
||||
return normalizeVulnStatus(originalStatus, details)
|
||||
|
||||
case "host":
|
||||
return "alive"
|
||||
}
|
||||
|
||||
return originalStatus
|
||||
}
|
||||
|
||||
// normalizeVulnStatus 统一漏洞状态显示
|
||||
func normalizeVulnStatus(status string, details map[string]interface{}) string {
|
||||
// 英文转中文映射
|
||||
vulnTranslations := map[string]string{
|
||||
"weak_credential": "弱口令",
|
||||
"unauthorized": "未授权访问",
|
||||
"unauth": "未授权访问",
|
||||
"anonymous": "匿名访问",
|
||||
"CVE": "漏洞",
|
||||
}
|
||||
|
||||
// 处理 "weak_credential: user:pass" 格式
|
||||
if strings.HasPrefix(status, "weak_credential:") {
|
||||
cred := strings.TrimPrefix(status, "weak_credential:")
|
||||
cred = strings.TrimSpace(cred)
|
||||
return fmt.Sprintf("弱口令: %s", cred)
|
||||
}
|
||||
|
||||
// 处理其他已知格式
|
||||
for eng, chn := range vulnTranslations {
|
||||
if strings.Contains(strings.ToLower(status), strings.ToLower(eng)) {
|
||||
// 如果已经是中文格式,直接返回
|
||||
if strings.Contains(status, chn) {
|
||||
return status
|
||||
}
|
||||
// 替换英文部分
|
||||
return strings.Replace(status, eng, chn, 1)
|
||||
}
|
||||
}
|
||||
|
||||
return status
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
//go:build web
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/shadow1ng/fscan/web/ws"
|
||||
)
|
||||
|
||||
// RegisterRoutes 注册所有API路由
|
||||
func RegisterRoutes(mux *http.ServeMux, hub *ws.Hub) {
|
||||
// 扫描管理
|
||||
scanHandler := NewScanHandler(hub)
|
||||
mux.HandleFunc("/api/scan/start", scanHandler.Start)
|
||||
mux.HandleFunc("/api/scan/stop", scanHandler.Stop)
|
||||
mux.HandleFunc("/api/scan/status", scanHandler.Status)
|
||||
|
||||
// 结果查询
|
||||
resultHandler := NewResultHandler()
|
||||
mux.HandleFunc("/api/results", resultHandler.List)
|
||||
mux.HandleFunc("/api/results/export", resultHandler.Export)
|
||||
mux.HandleFunc("/api/results/clear", resultHandler.Clear)
|
||||
|
||||
// 配置
|
||||
configHandler := NewConfigHandler()
|
||||
mux.HandleFunc("/api/config/presets", configHandler.Presets)
|
||||
mux.HandleFunc("/api/config/plugins", configHandler.Plugins)
|
||||
|
||||
// 系统信息
|
||||
mux.HandleFunc("/api/system/info", systemInfo)
|
||||
mux.HandleFunc("/api/health", healthCheck)
|
||||
}
|
||||
|
||||
// healthCheck 健康检查
|
||||
func healthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":"ok"}`))
|
||||
}
|
||||
|
||||
// systemInfo 系统信息
|
||||
func systemInfo(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"version":"2.1.1","build":"web"}`))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !web
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/shadow1ng/fscan/web/ws"
|
||||
)
|
||||
|
||||
// RegisterRoutes 非Web版本的空实现
|
||||
func RegisterRoutes(mux *http.ServeMux, hub *ws.Hub) {
|
||||
// 非Web版本不注册任何路由
|
||||
}
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
//go:build web
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/shadow1ng/fscan/common"
|
||||
"github.com/shadow1ng/fscan/core"
|
||||
"github.com/shadow1ng/fscan/web/ws"
|
||||
)
|
||||
|
||||
// ScanState 扫描状态
|
||||
type ScanState int32
|
||||
|
||||
const (
|
||||
ScanStateIdle ScanState = iota
|
||||
ScanStateRunning
|
||||
ScanStateStopping
|
||||
)
|
||||
|
||||
// ScanRequest 扫描请求
|
||||
type ScanRequest struct {
|
||||
// 目标
|
||||
Host string `json:"host"`
|
||||
Ports string `json:"ports"`
|
||||
ExcludeHosts string `json:"exclude_hosts"`
|
||||
ExcludePorts string `json:"exclude_ports"`
|
||||
|
||||
// 扫描控制
|
||||
ScanMode string `json:"scan_mode"`
|
||||
ThreadNum int `json:"thread_num"`
|
||||
Timeout int `json:"timeout"`
|
||||
ModuleThreadNum int `json:"module_thread_num"`
|
||||
DisablePing bool `json:"disable_ping"`
|
||||
DisableBrute bool `json:"disable_brute"`
|
||||
AliveOnly bool `json:"alive_only"`
|
||||
|
||||
// 认证
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Domain string `json:"domain"`
|
||||
|
||||
// POC
|
||||
PocPath string `json:"poc_path"`
|
||||
PocName string `json:"poc_name"`
|
||||
PocFull bool `json:"poc_full"`
|
||||
DisablePoc bool `json:"disable_poc"`
|
||||
}
|
||||
|
||||
// ScanStatus 扫描状态响应
|
||||
type ScanStatus struct {
|
||||
State string `json:"state"`
|
||||
StartTime time.Time `json:"start_time,omitempty"`
|
||||
Progress float64 `json:"progress"`
|
||||
Stats ScanStats `json:"stats"`
|
||||
}
|
||||
|
||||
// ScanStats 扫描统计
|
||||
type ScanStats struct {
|
||||
HostsScanned int `json:"hosts_scanned"`
|
||||
PortsScanned int `json:"ports_scanned"`
|
||||
ServicesFound int `json:"services_found"`
|
||||
VulnsFound int `json:"vulns_found"`
|
||||
}
|
||||
|
||||
// ScanHandler 扫描处理器
|
||||
type ScanHandler struct {
|
||||
hub *ws.Hub
|
||||
state int32
|
||||
startTime time.Time
|
||||
stopChan chan struct{}
|
||||
mu sync.RWMutex
|
||||
results *ResultStore
|
||||
}
|
||||
|
||||
// NewScanHandler 创建扫描处理器
|
||||
func NewScanHandler(hub *ws.Hub) *ScanHandler {
|
||||
return &ScanHandler{
|
||||
hub: hub,
|
||||
results: globalResultStore,
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动扫描
|
||||
func (h *ScanHandler) Start(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
// 检查是否已在扫描
|
||||
if !atomic.CompareAndSwapInt32(&h.state, int32(ScanStateIdle), int32(ScanStateRunning)) {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "scan already running",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 解析请求
|
||||
var req ScanRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
atomic.StoreInt32(&h.state, int32(ScanStateIdle))
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"error": "invalid request: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证必填参数
|
||||
if req.Host == "" {
|
||||
atomic.StoreInt32(&h.state, int32(ScanStateIdle))
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"error": "host is required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
h.mu.Lock()
|
||||
h.startTime = time.Now()
|
||||
h.stopChan = make(chan struct{})
|
||||
h.mu.Unlock()
|
||||
|
||||
// 清空旧结果
|
||||
h.results.Clear()
|
||||
|
||||
// 广播扫描开始
|
||||
h.hub.Broadcast(ws.MsgScanStarted, map[string]interface{}{
|
||||
"host": req.Host,
|
||||
"start_time": h.startTime,
|
||||
})
|
||||
|
||||
// 异步执行扫描
|
||||
go h.runScan(req)
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]interface{}{
|
||||
"status": "started",
|
||||
"start_time": h.startTime,
|
||||
})
|
||||
}
|
||||
|
||||
// runScan 执行扫描
|
||||
func (h *ScanHandler) runScan(req ScanRequest) {
|
||||
defer func() {
|
||||
common.ClearResultCallback() // 清除回调
|
||||
atomic.StoreInt32(&h.state, int32(ScanStateIdle))
|
||||
h.hub.Broadcast(ws.MsgScanCompleted, map[string]interface{}{
|
||||
"duration": time.Since(h.startTime).Seconds(),
|
||||
"stats": h.results.Stats(),
|
||||
})
|
||||
}()
|
||||
|
||||
// 构建HostInfo
|
||||
info := common.HostInfo{
|
||||
Host: req.Host,
|
||||
}
|
||||
|
||||
// 构建FlagVars
|
||||
fv := &common.FlagVars{}
|
||||
fv.Ports = req.Ports
|
||||
if fv.Ports == "" {
|
||||
fv.Ports = "21,22,23,25,80,110,135,139,143,443,445,465,587,993,995,1433,1521,3306,3389,5432,5900,6379,8080,8443,9000,27017"
|
||||
}
|
||||
fv.ExcludeHosts = req.ExcludeHosts
|
||||
fv.ExcludePorts = req.ExcludePorts
|
||||
fv.ScanMode = req.ScanMode
|
||||
if fv.ScanMode == "" {
|
||||
fv.ScanMode = "all"
|
||||
}
|
||||
fv.ThreadNum = req.ThreadNum
|
||||
if fv.ThreadNum == 0 {
|
||||
fv.ThreadNum = 600
|
||||
}
|
||||
fv.TimeoutSec = int64(req.Timeout)
|
||||
if fv.TimeoutSec == 0 {
|
||||
fv.TimeoutSec = 3
|
||||
}
|
||||
fv.ModuleThreadNum = req.ModuleThreadNum
|
||||
if fv.ModuleThreadNum == 0 {
|
||||
fv.ModuleThreadNum = 20
|
||||
}
|
||||
fv.DisablePing = req.DisablePing
|
||||
fv.DisableBrute = req.DisableBrute
|
||||
fv.AliveOnly = req.AliveOnly
|
||||
fv.Username = req.Username
|
||||
fv.Password = req.Password
|
||||
fv.Domain = req.Domain
|
||||
fv.PocPath = req.PocPath
|
||||
fv.PocName = req.PocName
|
||||
fv.PocFull = req.PocFull
|
||||
fv.DisablePocScan = req.DisablePoc
|
||||
fv.DisableSave = true // Web模式不保存到文件
|
||||
fv.Silent = true // 静默模式
|
||||
|
||||
// 构建Config
|
||||
config := common.BuildConfigFromFlags(fv)
|
||||
state := common.NewState()
|
||||
|
||||
// 设置WebSocket结果回调
|
||||
common.SetResultCallback(func(result interface{}) {
|
||||
item := h.results.Add(result)
|
||||
if item != nil {
|
||||
h.hub.Broadcast(ws.MsgScanResult, item)
|
||||
}
|
||||
})
|
||||
|
||||
// 执行扫描
|
||||
core.RunScan(info, config, state)
|
||||
}
|
||||
|
||||
// Stop 停止扫描
|
||||
func (h *ScanHandler) Stop(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if atomic.LoadInt32(&h.state) != int32(ScanStateRunning) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"error": "no scan running",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
atomic.StoreInt32(&h.state, int32(ScanStateStopping))
|
||||
|
||||
h.mu.Lock()
|
||||
if h.stopChan != nil {
|
||||
close(h.stopChan)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string]string{
|
||||
"status": "stopping",
|
||||
})
|
||||
}
|
||||
|
||||
// Status 获取扫描状态
|
||||
func (h *ScanHandler) Status(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
state := atomic.LoadInt32(&h.state)
|
||||
stateStr := "idle"
|
||||
switch ScanState(state) {
|
||||
case ScanStateRunning:
|
||||
stateStr = "running"
|
||||
case ScanStateStopping:
|
||||
stateStr = "stopping"
|
||||
}
|
||||
|
||||
h.mu.RLock()
|
||||
startTime := h.startTime
|
||||
h.mu.RUnlock()
|
||||
|
||||
// 从 ProgressManager 获取进度百分比
|
||||
progress := common.GetProgressPercent()
|
||||
|
||||
status := ScanStatus{
|
||||
State: stateStr,
|
||||
StartTime: startTime,
|
||||
Progress: progress,
|
||||
Stats: h.results.Stats(),
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, status)
|
||||
}
|
||||
|
||||
// writeJSON 写入JSON响应
|
||||
func writeJSON(w http.ResponseWriter, status int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
Reference in New Issue
Block a user