mirror of
https://github.com/shadow1ng/fscan.git
synced 2026-09-25 20:51:52 +08:00
Harden scan robustness and tests
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
//go:build !debug
|
||||
// +build !debug
|
||||
|
||||
package debug
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestStubStartStop(t *testing.T) {
|
||||
Start()
|
||||
Stop()
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDNSCacheResolveIPAndCacheHit(t *testing.T) {
|
||||
cache := &dnsCache{}
|
||||
|
||||
first, err := cache.ResolveIP("127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveIP loopback error = %v", err)
|
||||
}
|
||||
second, err := cache.ResolveIP("127.0.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveIP cached loopback error = %v", err)
|
||||
}
|
||||
if first != second {
|
||||
t.Fatal("ResolveIP should return cached address on second lookup")
|
||||
}
|
||||
|
||||
if _, err := cache.ResolveIP("bad host with spaces"); err == nil {
|
||||
t.Fatal("ResolveIP should reject an invalid host")
|
||||
}
|
||||
}
|
||||
+51
-1
@@ -1,6 +1,10 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHostInfoTargetUsesBracketedIPv6(t *testing.T) {
|
||||
info := &HostInfo{Host: "2001:db8::1", Port: 443}
|
||||
@@ -15,3 +19,49 @@ func TestHostInfoTargetDoesNotDoubleBracketIPv6(t *testing.T) {
|
||||
t.Fatalf("Target() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobalHelpersAndPacketLimitErrors(t *testing.T) {
|
||||
if GetVersion() == "" {
|
||||
t.Fatal("GetVersion returned empty string")
|
||||
}
|
||||
if !ContainsAny("hello fscan", "none", "scan") {
|
||||
t.Fatal("ContainsAny should find a matching substring")
|
||||
}
|
||||
if ContainsAny("hello fscan", "none", "missing") {
|
||||
t.Fatal("ContainsAny should return false when nothing matches")
|
||||
}
|
||||
|
||||
maxErr := &PacketLimitError{Sentinel: ErrMaxPacketReached, Limit: 5, Current: 5}
|
||||
if !errors.Is(maxErr, ErrMaxPacketReached) || !strings.Contains(maxErr.Error(), "5") {
|
||||
t.Fatalf("max packet error = %v", maxErr)
|
||||
}
|
||||
|
||||
rateErr := &PacketLimitError{Sentinel: ErrPacketRateLimited, Limit: 3, Current: 2}
|
||||
if !errors.Is(rateErr, ErrPacketRateLimited) || !strings.Contains(rateErr.Error(), "3") {
|
||||
t.Fatalf("rate limit error = %v", rateErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanSendPacketUsesGlobalConfigAndState(t *testing.T) {
|
||||
previousConfig := GetGlobalConfig()
|
||||
previousState := GetGlobalState()
|
||||
t.Cleanup(func() {
|
||||
SetGlobalConfig(previousConfig)
|
||||
SetGlobalState(previousState)
|
||||
})
|
||||
|
||||
cfg := NewConfig()
|
||||
cfg.Network.MaxPacketCount = 1
|
||||
state := NewState()
|
||||
state.IncrementPacketCount()
|
||||
SetGlobalConfig(cfg)
|
||||
SetGlobalState(state)
|
||||
|
||||
ok, reason := CanSendPacket()
|
||||
if ok {
|
||||
t.Fatal("CanSendPacket should reject when max packet count is reached")
|
||||
}
|
||||
if reason == "" {
|
||||
t.Fatal("CanSendPacket should return a rejection reason")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLanguageLifecycleAndFallbacks(t *testing.T) {
|
||||
original := GetLanguage()
|
||||
t.Cleanup(func() { SetLanguage(original) })
|
||||
|
||||
SetLanguage(LangEN)
|
||||
if got := GetLanguage(); got != LangEN {
|
||||
t.Fatalf("language = %q, want %q", got, LangEN)
|
||||
}
|
||||
if got := GetText("concurrency_plugin"); got == "" || got == "concurrency_plugin" {
|
||||
t.Fatalf("english text = %q, want translated text", got)
|
||||
}
|
||||
if got := Tr("debug_cpu_profile_started", "/tmp/profiles"); !strings.Contains(got, "/tmp/profiles") {
|
||||
t.Fatalf("formatted english text = %q, want path included", got)
|
||||
}
|
||||
|
||||
SetLanguage(LangZH)
|
||||
if got := GetLanguage(); got != LangZH {
|
||||
t.Fatalf("language = %q, want %q", got, LangZH)
|
||||
}
|
||||
if got := GetText("concurrency_plugin"); got == "" || got == "concurrency_plugin" {
|
||||
t.Fatalf("chinese text = %q, want translated text", got)
|
||||
}
|
||||
|
||||
if got := GetText("missing_translation_key"); got != "missing_translation_key" {
|
||||
t.Fatalf("missing GetText = %q, want key", got)
|
||||
}
|
||||
if got := Tr("missing_translation_key", "ignored"); got != "missing_translation_key" {
|
||||
t.Fatalf("missing Tr = %q, want key", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateExclusiveParams(t *testing.T) {
|
||||
previous := GetFlagVars()
|
||||
t.Cleanup(func() { flagVars = previous })
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
info *HostInfo
|
||||
flags *FlagVars
|
||||
wantErr string
|
||||
}{
|
||||
{name: "host only", info: &HostInfo{Host: "127.0.0.1"}, flags: &FlagVars{}},
|
||||
{name: "url only", info: &HostInfo{}, flags: &FlagVars{TargetURL: "http://example.com"}},
|
||||
{name: "local only", info: &HostInfo{}, flags: &FlagVars{LocalPlugin: "sshkey"}},
|
||||
{name: "host and url conflict", info: &HostInfo{Host: "127.0.0.1"}, flags: &FlagVars{TargetURL: "http://example.com"}, wantErr: "-h"},
|
||||
{name: "host url local conflict", info: &HostInfo{Host: "127.0.0.1"}, flags: &FlagVars{TargetURL: "http://example.com", LocalPlugin: "sshkey"}, wantErr: "-local"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
flagVars = tt.flags
|
||||
err := ValidateExclusiveParams(tt.info)
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("ValidateExclusiveParams error = %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("ValidateExclusiveParams error = %v, want containing %q", err, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanupWithoutOutput(t *testing.T) {
|
||||
oldResultOutput := ResultOutput
|
||||
oldStdoutWriter := StdoutWriter
|
||||
t.Cleanup(func() {
|
||||
ResultOutput = oldResultOutput
|
||||
StdoutWriter = oldStdoutWriter
|
||||
})
|
||||
|
||||
ResultOutput = nil
|
||||
StdoutWriter = nil
|
||||
if err := Cleanup(); err != nil {
|
||||
t.Fatalf("Cleanup error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func preserveLoggerForTest(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
loggerMu.Lock()
|
||||
oldSilentRefs := silentLoggerRefs
|
||||
silentLoggerRefs = 0
|
||||
resetLoggerLocked()
|
||||
loggerMu.Unlock()
|
||||
|
||||
t.Cleanup(func() {
|
||||
loggerMu.Lock()
|
||||
closeLoggerLocked()
|
||||
silentLoggerRefs = oldSilentRefs
|
||||
resetLoggerLocked()
|
||||
loggerMu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func TestLoggerFacadeSilentLifecycle(t *testing.T) {
|
||||
preserveLoggerForTest(t)
|
||||
|
||||
previousFlags := GetFlagVars()
|
||||
previousState := GetGlobalState()
|
||||
t.Cleanup(func() {
|
||||
flagVars = previousFlags
|
||||
SetGlobalState(previousState)
|
||||
})
|
||||
flagVars = &FlagVars{Silent: true, LogLevel: "debug"}
|
||||
SetGlobalState(NewState())
|
||||
|
||||
InitLogger()
|
||||
LogDebug("debug")
|
||||
LogInfo("info")
|
||||
LogSuccess("success")
|
||||
LogVuln("vuln")
|
||||
LogError("error")
|
||||
CloseLogger()
|
||||
}
|
||||
|
||||
func TestPushSilentLoggerReferenceCount(t *testing.T) {
|
||||
preserveLoggerForTest(t)
|
||||
|
||||
restoreOne := PushSilentLogger()
|
||||
restoreTwo := PushSilentLogger()
|
||||
if silentLoggerRefs != 2 {
|
||||
t.Fatalf("silent refs = %d, want 2", silentLoggerRefs)
|
||||
}
|
||||
|
||||
restoreOne()
|
||||
restoreOne()
|
||||
if silentLoggerRefs != 1 {
|
||||
t.Fatalf("silent refs after first restore = %d, want 1", silentLoggerRefs)
|
||||
}
|
||||
|
||||
restoreTwo()
|
||||
if silentLoggerRefs != 0 {
|
||||
t.Fatalf("silent refs after second restore = %d, want 0", silentLoggerRefs)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package logging
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -160,6 +162,13 @@ func TestLogger_AllLevels(t *testing.T) {
|
||||
wantMsg: "success message",
|
||||
wantPfx: PrefixSuccess,
|
||||
},
|
||||
{
|
||||
name: "Vuln级别",
|
||||
logFunc: logger.Vuln,
|
||||
message: "vuln message",
|
||||
wantMsg: "vuln message",
|
||||
wantPfx: PrefixVuln,
|
||||
},
|
||||
{
|
||||
name: "Error级别",
|
||||
logFunc: logger.Error,
|
||||
@@ -650,3 +659,34 @@ func TestLogger_Initialize(t *testing.T) {
|
||||
|
||||
t.Logf("✓ Initialize测试通过")
|
||||
}
|
||||
|
||||
func TestLogger_CloseClosesDebugFile(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "debug.log")
|
||||
logger := NewLogger(&LoggerConfig{
|
||||
Level: LevelAll,
|
||||
EnableColor: false,
|
||||
ShowProgress: false,
|
||||
StartTime: time.Now(),
|
||||
LevelColors: GetDefaultLevelColors(),
|
||||
DebugLogFile: path,
|
||||
})
|
||||
if logger.debugFile == nil {
|
||||
t.Fatal("debug file should be opened")
|
||||
}
|
||||
|
||||
logger.Info("debug file line")
|
||||
logger.Close()
|
||||
if logger.debugFile != nil {
|
||||
t.Fatal("debug file should be nil after Close")
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read debug file: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(content), "debug file line") {
|
||||
t.Fatalf("debug file content = %q", string(content))
|
||||
}
|
||||
|
||||
logger.Close()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/shadow1ng/fscan/common/proxy"
|
||||
)
|
||||
|
||||
func TestNetworkFacadeProxyState(t *testing.T) {
|
||||
t.Cleanup(func() { proxy.AutoConfigureProxy(proxy.DefaultProxyConfig()) })
|
||||
proxy.AutoConfigureProxy(proxy.DefaultProxyConfig())
|
||||
|
||||
if IsProxyEnabled() || IsSOCKS5Proxy() || !IsProxyReliable() {
|
||||
t.Fatal("direct global proxy state should be disabled and reliable")
|
||||
}
|
||||
|
||||
proxy.AutoConfigureProxy(&proxy.ProxyConfig{Type: proxy.ProxyTypeSOCKS5})
|
||||
if !IsProxyEnabled() || !IsSOCKS5Proxy() || !IsProxyReliable() {
|
||||
t.Fatal("SOCKS5 global proxy state should be enabled and SOCKS5")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeHTTPDoUsesGlobalPacketLimit(t *testing.T) {
|
||||
previousConfig := GetGlobalConfig()
|
||||
previousState := GetGlobalState()
|
||||
t.Cleanup(func() {
|
||||
SetGlobalConfig(previousConfig)
|
||||
SetGlobalState(previousState)
|
||||
})
|
||||
|
||||
cfg := NewConfig()
|
||||
cfg.Network.MaxPacketCount = 1
|
||||
state := NewState()
|
||||
state.IncrementPacketCount()
|
||||
SetGlobalConfig(cfg)
|
||||
SetGlobalState(state)
|
||||
|
||||
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
|
||||
t.Fatal("transport should not be called when packet limit is reached")
|
||||
return nil, nil
|
||||
})}
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://example.com", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if resp, err := SafeHTTPDo(client, req); err == nil || resp != nil {
|
||||
t.Fatalf("SafeHTTPDo = resp %#v err %v, want limit error", resp, err)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
package output
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSplitHostPort(t *testing.T) {
|
||||
tests := []struct {
|
||||
@@ -33,3 +38,85 @@ func TestSplitHostPort(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewStdoutNDJSONWriter(t *testing.T) {
|
||||
writer := NewStdoutNDJSONWriter()
|
||||
if writer == nil || writer.writer == nil {
|
||||
t.Fatalf("NewStdoutNDJSONWriter = %#v, want initialized writer", writer)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdoutNDJSONWriterWriteResult(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
writer := &StdoutNDJSONWriter{writer: bufio.NewWriter(&buf)}
|
||||
|
||||
result := &ScanResult{
|
||||
Type: TypeService,
|
||||
Target: "[2001:db8::1]:8443",
|
||||
Status: "OPEN",
|
||||
Details: map[string]interface{}{
|
||||
"port": float64(9443),
|
||||
"service": "https",
|
||||
"protocol": "tcp",
|
||||
"banner": 123,
|
||||
"title": "admin",
|
||||
"url": "https://[2001:db8::1]:8443",
|
||||
"vulnerability": "weak credential",
|
||||
"username": "admin",
|
||||
"password": "secret",
|
||||
"plugin": "webtitle",
|
||||
"version": "1.2.3",
|
||||
"os": "linux",
|
||||
},
|
||||
}
|
||||
|
||||
if err := writer.WriteResult(result); err != nil {
|
||||
t.Fatalf("WriteResult error = %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("Close error = %v", err)
|
||||
}
|
||||
|
||||
var rec ndjsonRecord
|
||||
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &rec); err != nil {
|
||||
t.Fatalf("invalid ndjson output %q: %v", buf.String(), err)
|
||||
}
|
||||
if rec.Host != "2001:db8::1" || rec.Port != 9443 {
|
||||
t.Fatalf("host/port = %q/%d", rec.Host, rec.Port)
|
||||
}
|
||||
if rec.Service != "https" || rec.Protocol != "tcp" || rec.Banner != "123" || rec.Title != "admin" {
|
||||
t.Fatalf("flattened fields missing: %#v", rec)
|
||||
}
|
||||
if rec.URL != "https://[2001:db8::1]:8443" || rec.Vulnerability != "weak credential" {
|
||||
t.Fatalf("url/vuln fields missing: %#v", rec)
|
||||
}
|
||||
if rec.Username != "admin" || rec.Password != "secret" || rec.Plugin != "webtitle" || rec.Version != "1.2.3" || rec.OS != "linux" {
|
||||
t.Fatalf("credential/plugin fields missing: %#v", rec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStdoutNDJSONFlattenFallbacks(t *testing.T) {
|
||||
writer := &StdoutNDJSONWriter{writer: bufio.NewWriter(&bytes.Buffer{})}
|
||||
|
||||
rec := writer.flatten(&ScanResult{
|
||||
Type: TypeHost,
|
||||
Target: "2001:db8::1",
|
||||
Status: "ALIVE",
|
||||
Details: map[string]interface{}{
|
||||
"port": int64(22),
|
||||
},
|
||||
})
|
||||
if rec.Host != "2001:db8::1" || rec.Port != 22 {
|
||||
t.Fatalf("flatten fallback = %#v", rec)
|
||||
}
|
||||
|
||||
if got, ok := toInt("22"); ok || got != 0 {
|
||||
t.Fatalf("toInt string = %d/%v, want 0/false", got, ok)
|
||||
}
|
||||
if got := strVal(map[string]interface{}{}, "missing"); got != "" {
|
||||
t.Fatalf("missing strVal = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,19 @@ func escapeControlChars(s string) string {
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func truncateString(s string, maxRunes int) string {
|
||||
if maxRunes < 0 {
|
||||
return s
|
||||
}
|
||||
for i := range s {
|
||||
if maxRunes == 0 {
|
||||
return s[:i] + "..."
|
||||
}
|
||||
maxRunes--
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func targetWithPort(target string, port interface{}) string {
|
||||
if port == nil {
|
||||
return target
|
||||
@@ -196,10 +209,8 @@ func (w *TXTWriter) formatServiceLine(result *ScanResult) string {
|
||||
parts = append(parts, service)
|
||||
}
|
||||
if banner != "" {
|
||||
if len(banner) > 100 {
|
||||
banner = banner[:100] + "..."
|
||||
}
|
||||
banner = escapeControlChars(banner)
|
||||
banner = truncateString(banner, 100)
|
||||
parts = append(parts, banner)
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
@@ -745,9 +756,7 @@ func (w *CSVWriter) formatServiceRecord(result *ScanResult) []string {
|
||||
fingerprints = formatFingerprints(result.Details["fingerprints"])
|
||||
if b, ok := result.Details["banner"].(string); ok {
|
||||
banner = escapeControlChars(b)
|
||||
if len(banner) > 100 {
|
||||
banner = banner[:100] + "..."
|
||||
}
|
||||
banner = truncateString(banner, 100)
|
||||
}
|
||||
}
|
||||
target := result.Target
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
/*
|
||||
@@ -82,6 +83,94 @@ func TestTargetWithPortIPv6(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanResultFormatDetailsAndDefaultManagerConfig(t *testing.T) {
|
||||
result := &ScanResult{
|
||||
Details: map[string]interface{}{
|
||||
"service": "ssh",
|
||||
"port": 22,
|
||||
"banner": "OpenSSH",
|
||||
},
|
||||
}
|
||||
got := result.FormatDetails(";", "%s=%v")
|
||||
want := "banner=OpenSSH;port=22;service=ssh"
|
||||
if got != want {
|
||||
t.Fatalf("FormatDetails = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
empty := (&ScanResult{}).FormatDetails(";", "%s=%v")
|
||||
if empty != "" {
|
||||
t.Fatalf("empty FormatDetails = %q, want empty", empty)
|
||||
}
|
||||
|
||||
cfg := DefaultManagerConfig("out.json", FormatJSON)
|
||||
if cfg.OutputPath != "out.json" || cfg.Format != FormatJSON {
|
||||
t.Fatalf("DefaultManagerConfig = %#v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSVWriterFormatRecords(t *testing.T) {
|
||||
writer := &CSVWriter{}
|
||||
|
||||
host := writer.formatHostRecord(&ScanResult{Target: "192.168.1.1"})
|
||||
if len(host) != 1 || host[0] != "192.168.1.1" {
|
||||
t.Fatalf("host record = %#v", host)
|
||||
}
|
||||
|
||||
port := writer.formatPortRecord(&ScanResult{
|
||||
Target: "192.168.1.1",
|
||||
Details: map[string]interface{}{"port": 22},
|
||||
})
|
||||
if got, want := strings.Join(port, "|"), "192.168.1.1|22|open"; got != want {
|
||||
t.Fatalf("port record = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
longBanner := strings.Repeat("界", 105)
|
||||
service := writer.formatServiceRecord(&ScanResult{
|
||||
Target: "2001:db8::1",
|
||||
Details: map[string]interface{}{
|
||||
"port": 443,
|
||||
"name": "https",
|
||||
"version": "1.2.3",
|
||||
"title": "hello\nworld",
|
||||
"status": 200,
|
||||
"server": "nginx\r\nunit",
|
||||
"fingerprints": []interface{}{"fp1", "", "fp2", 3},
|
||||
"banner": longBanner,
|
||||
},
|
||||
})
|
||||
if service[0] != "[2001:db8::1]:443" || service[1] != "https" || service[2] != "1.2.3" {
|
||||
t.Fatalf("service identity fields = %#v", service)
|
||||
}
|
||||
if service[3] != "hello\\nworld" || service[4] != "200" || service[5] != "nginx\\r\\nunit" {
|
||||
t.Fatalf("service text fields = %#v", service)
|
||||
}
|
||||
if service[6] != "fp1,fp2" {
|
||||
t.Fatalf("fingerprints = %q, want fp1,fp2", service[6])
|
||||
}
|
||||
if !utf8.ValidString(service[7]) || len([]rune(service[7])) != 103 || !strings.HasSuffix(service[7], "...") {
|
||||
t.Fatalf("truncated banner = len %d value %q", len(service[7]), service[7])
|
||||
}
|
||||
|
||||
vuln := writer.formatVulnRecord(&ScanResult{
|
||||
Target: "http://example.com",
|
||||
Status: "vulnerable",
|
||||
Details: map[string]interface{}{"type": "poc"},
|
||||
})
|
||||
if got, want := strings.Join(vuln, "|"), "http://example.com|poc|vulnerable"; got != want {
|
||||
t.Fatalf("vuln record = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if got := formatFingerprints([]string{"a", "b"}); got != "a,b" {
|
||||
t.Fatalf("string fingerprints = %q", got)
|
||||
}
|
||||
if got := formatFingerprints(123); got != "" {
|
||||
t.Fatalf("unsupported fingerprints = %q, want empty", got)
|
||||
}
|
||||
if writer.GetFormat() != FormatCSV {
|
||||
t.Fatalf("csv GetFormat = %q", writer.GetFormat())
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// TXTWriter - 基础功能测试
|
||||
// =============================================================================
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/shadow1ng/fscan/common/output"
|
||||
)
|
||||
|
||||
func readTestFile(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", path, err)
|
||||
}
|
||||
return string(content)
|
||||
}
|
||||
|
||||
func preserveOutputAPIGlobals(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
globalMu.RLock()
|
||||
oldConfig := globalConfig
|
||||
oldState := globalState
|
||||
globalMu.RUnlock()
|
||||
|
||||
oldFlagVars := flagVars
|
||||
oldResultOutput := ResultOutput
|
||||
oldStdoutWriter := StdoutWriter
|
||||
|
||||
t.Cleanup(func() {
|
||||
if ResultOutput != nil && ResultOutput != oldResultOutput {
|
||||
_ = ResultOutput.Close()
|
||||
}
|
||||
if StdoutWriter != nil && StdoutWriter != oldStdoutWriter {
|
||||
_ = StdoutWriter.Close()
|
||||
}
|
||||
ClearResultCallback()
|
||||
|
||||
globalMu.Lock()
|
||||
globalConfig = oldConfig
|
||||
globalState = oldState
|
||||
globalMu.Unlock()
|
||||
|
||||
flagVars = oldFlagVars
|
||||
ResultOutput = oldResultOutput
|
||||
StdoutWriter = oldStdoutWriter
|
||||
})
|
||||
|
||||
ClearResultCallback()
|
||||
flagVars = &FlagVars{}
|
||||
ResultOutput = nil
|
||||
StdoutWriter = nil
|
||||
SetGlobalConfig(NewConfig())
|
||||
SetGlobalState(NewState())
|
||||
}
|
||||
|
||||
func TestInitOutputValidationAndDefaultExtension(t *testing.T) {
|
||||
preserveOutputAPIGlobals(t)
|
||||
|
||||
flagVars = &FlagVars{DisableSave: true}
|
||||
if err := InitOutput(); err != nil {
|
||||
t.Fatalf("InitOutput disable save error = %v", err)
|
||||
}
|
||||
if ResultOutput != nil {
|
||||
t.Fatalf("ResultOutput = %#v, want nil when save is disabled", ResultOutput)
|
||||
}
|
||||
|
||||
flagVars = &FlagVars{OutputFormat: "txt"}
|
||||
if err := InitOutput(); err == nil || !strings.Contains(err.Error(), "output file not specified") {
|
||||
t.Fatalf("missing output error = %v", err)
|
||||
}
|
||||
|
||||
flagVars = &FlagVars{Outputfile: "out.bad", OutputFormat: "xml"}
|
||||
if err := InitOutput(); err == nil || !strings.Contains(err.Error(), "invalid output format") {
|
||||
t.Fatalf("invalid format error = %v", err)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
flagVars = &FlagVars{Outputfile: "result.txt", OutputFormat: "json"}
|
||||
if err := InitOutput(); err != nil {
|
||||
t.Fatalf("InitOutput json error = %v", err)
|
||||
}
|
||||
if ResultOutput == nil {
|
||||
t.Fatal("ResultOutput should be initialized")
|
||||
}
|
||||
if err := SaveResult(&output.ScanResult{
|
||||
Time: time.Date(2026, 6, 13, 1, 2, 3, 0, time.UTC),
|
||||
Type: output.TypeHost,
|
||||
Target: "127.0.0.1",
|
||||
Status: "ALIVE",
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveResult json error = %v", err)
|
||||
}
|
||||
if err := CloseOutput(); err != nil {
|
||||
t.Fatalf("CloseOutput error = %v", err)
|
||||
}
|
||||
if content := readTestFile(t, filepath.Join(dir, "result.json")); !strings.Contains(content, "127.0.0.1") {
|
||||
t.Fatalf("result.json content = %q, want saved target", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveResultFacadeCallbackAndDisabledSave(t *testing.T) {
|
||||
preserveOutputAPIGlobals(t)
|
||||
|
||||
cfg := NewConfig()
|
||||
cfg.Output.DisableSave = true
|
||||
SetGlobalConfig(cfg)
|
||||
|
||||
flagVars = &FlagVars{DisableSave: true}
|
||||
if err := InitOutput(); err != nil {
|
||||
t.Fatalf("InitOutput disable save error = %v", err)
|
||||
}
|
||||
|
||||
called := false
|
||||
SetResultCallback(func(payload interface{}) {
|
||||
called = true
|
||||
data, ok := payload.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("callback payload type = %T", payload)
|
||||
}
|
||||
if data["type"] != string(output.TypeVuln) || data["target"] != "http://example.com" {
|
||||
t.Fatalf("callback payload = %#v", data)
|
||||
}
|
||||
})
|
||||
|
||||
if err := SaveResult(nil); err != nil {
|
||||
t.Fatalf("SaveResult nil error = %v", err)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("nil result should not notify callback")
|
||||
}
|
||||
|
||||
if err := SaveResult(&output.ScanResult{
|
||||
Type: output.TypeVuln,
|
||||
Target: "http://example.com",
|
||||
Status: "vulnerable",
|
||||
Details: map[string]interface{}{"type": "poc"},
|
||||
}); err != nil {
|
||||
t.Fatalf("SaveResult disabled save error = %v", err)
|
||||
}
|
||||
if !called {
|
||||
t.Fatal("callback was not notified")
|
||||
}
|
||||
if err := CloseOutput(); err != nil {
|
||||
t.Fatalf("CloseOutput disabled save error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package parsers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -103,3 +104,65 @@ func TestHostIteratorReadsLongHostFileLine(t *testing.T) {
|
||||
t.Fatalf("batch = %#v, want long host", batch)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiHostSourceAndMatcherCIDR(t *testing.T) {
|
||||
src := &multiHostSource{sources: []hostSource{
|
||||
&singleHostSource{host: "192.168.1.1"},
|
||||
&singleHostSource{host: "192.168.1.2"},
|
||||
}}
|
||||
|
||||
host, ok, err := src.Next()
|
||||
if err != nil || !ok || host != "192.168.1.1" {
|
||||
t.Fatalf("first Next = %q/%v/%v", host, ok, err)
|
||||
}
|
||||
host, ok, err = src.Next()
|
||||
if err != nil || !ok || host != "192.168.1.2" {
|
||||
t.Fatalf("second Next = %q/%v/%v", host, ok, err)
|
||||
}
|
||||
host, ok, err = src.Next()
|
||||
if err != nil || ok || host != "" {
|
||||
t.Fatalf("exhausted Next = %q/%v/%v", host, ok, err)
|
||||
}
|
||||
if err := src.Close(); err != nil {
|
||||
t.Fatalf("Close error = %v", err)
|
||||
}
|
||||
|
||||
matcher := newHostMatcher()
|
||||
if err := matcher.add("192.168.1.0/30,example.com"); err != nil {
|
||||
t.Fatalf("matcher add error = %v", err)
|
||||
}
|
||||
if !matcher.match("192.168.1.1") || !matcher.match("192.168.1.2") || !matcher.match("example.com") {
|
||||
t.Fatal("matcher should match CIDR hosts and exact host")
|
||||
}
|
||||
if matcher.match("192.168.1.3") || matcher.match("nope.example") {
|
||||
t.Fatal("matcher matched hosts outside its rules")
|
||||
}
|
||||
if err := matcher.add("2001:db8::/126"); err == nil {
|
||||
t.Fatal("IPv6 CIDR should be rejected by IPv4-only matcher")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseHostSourcesIgnoresCloseErrors(t *testing.T) {
|
||||
first := &closeTrackingSource{err: errors.New("close failed")}
|
||||
second := &closeTrackingSource{}
|
||||
|
||||
closeHostSources([]hostSource{first, second})
|
||||
|
||||
if !first.closed || !second.closed {
|
||||
t.Fatalf("sources closed = %v/%v, want both true", first.closed, second.closed)
|
||||
}
|
||||
}
|
||||
|
||||
type closeTrackingSource struct {
|
||||
closed bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *closeTrackingSource) Next() (string, bool, error) {
|
||||
return "", false, nil
|
||||
}
|
||||
|
||||
func (s *closeTrackingSource) Close() error {
|
||||
s.closed = true
|
||||
return s.err
|
||||
}
|
||||
|
||||
@@ -386,6 +386,15 @@ func TestParsePort_PortGroups(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePortGroupsRequireWholeToken(t *testing.T) {
|
||||
if got := ParsePort("web8080"); len(got) != 0 {
|
||||
t.Fatalf("ParsePort(web8080) = %v, want empty invalid token", got)
|
||||
}
|
||||
if got := ParsePort("web,8080"); len(got) == 0 || got[len(got)-1] != 28018 {
|
||||
t.Fatalf("ParsePort(web,8080) = %v, want expanded web group", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestParsePort_WhitespaceHandling 测试空格处理
|
||||
func TestParsePort_WhitespaceHandling(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
||||
@@ -200,11 +200,14 @@ func parsePortRange(rangeStr string) []int {
|
||||
// expandPortGroups 展开端口组
|
||||
func expandPortGroups(ports string) string {
|
||||
portGroups := config.GetPortGroups()
|
||||
result := ports
|
||||
for group, portList := range portGroups {
|
||||
result = strings.ReplaceAll(result, group, portList)
|
||||
parts := strings.Split(ports, ",")
|
||||
for i, part := range parts {
|
||||
token := strings.TrimSpace(part)
|
||||
if portList, ok := portGroups[token]; ok {
|
||||
parts[i] = portList
|
||||
}
|
||||
}
|
||||
return result
|
||||
return strings.Join(parts, ",")
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProgressTextHelpers(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want int
|
||||
}{
|
||||
{name: "ascii", in: "abc", want: 3},
|
||||
{name: "cjk", in: "中文", want: 4},
|
||||
{name: "mixed", in: "a中", want: 3},
|
||||
{name: "symbol", in: "★", want: 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := displayWidth(tt.in); got != tt.want {
|
||||
t.Fatalf("displayWidth(%q) = %d, want %d", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
truncateTests := []struct {
|
||||
name string
|
||||
in string
|
||||
width int
|
||||
want string
|
||||
}{
|
||||
{name: "exact mixed width", in: "abc中文", width: 5, want: "abc中"},
|
||||
{name: "wide char does not fit", in: "中文", width: 1, want: ""},
|
||||
{name: "zero width", in: "abc", width: 0, want: ""},
|
||||
{name: "negative width", in: "abc", width: -1, want: ""},
|
||||
}
|
||||
for _, tt := range truncateTests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := truncateToWidth(tt.in, tt.width); got != tt.want {
|
||||
t.Fatalf("truncateToWidth(%q, %d) = %q, want %q", tt.in, tt.width, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if got := stripAnsiCodes("\033[31mred\033[0m plain"); got != "red plain" {
|
||||
t.Fatalf("stripAnsiCodes removed ANSI = %q, want %q", got, "red plain")
|
||||
}
|
||||
if got := stripAnsiCodes("plain"); got != "plain" {
|
||||
t.Fatalf("stripAnsiCodes plain = %q, want plain", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatDuration(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in time.Duration
|
||||
want string
|
||||
}{
|
||||
{name: "seconds", in: 1500 * time.Millisecond, want: "1.5s"},
|
||||
{name: "minutes", in: 90 * time.Second, want: "1.5m"},
|
||||
{name: "hours", in: 150 * time.Minute, want: "2.5h"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := formatDuration(tt.in); got != tt.want {
|
||||
t.Fatalf("formatDuration(%s) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyMonitorTaskStats(t *testing.T) {
|
||||
monitor := &ConcurrencyMonitor{}
|
||||
|
||||
if status := monitor.GetConcurrencyStatus(); status != "" {
|
||||
t.Fatalf("initial status = %q, want empty", status)
|
||||
}
|
||||
|
||||
monitor.StartPluginTask()
|
||||
monitor.StartPluginTask()
|
||||
|
||||
active, total := monitor.GetPluginTaskStats()
|
||||
if active != 2 || total != 2 {
|
||||
t.Fatalf("stats after start = active %d total %d, want 2/2", active, total)
|
||||
}
|
||||
if status := monitor.GetConcurrencyStatus(); !strings.HasSuffix(status, ":2") {
|
||||
t.Fatalf("status after start = %q, want suffix :2", status)
|
||||
}
|
||||
|
||||
monitor.FinishPluginTask()
|
||||
active, total = monitor.GetPluginTaskStats()
|
||||
if active != 1 || total != 2 {
|
||||
t.Fatalf("stats after one finish = active %d total %d, want 1/2", active, total)
|
||||
}
|
||||
|
||||
monitor.FinishPluginTask()
|
||||
if status := monitor.GetConcurrencyStatus(); status != "" {
|
||||
t.Fatalf("status after all finish = %q, want empty", status)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -54,6 +55,9 @@ func (h *httpDialer) DialContext(ctx context.Context, network, address string) (
|
||||
|
||||
// sendConnectRequest 发送HTTP CONNECT请求
|
||||
func (h *httpDialer) sendConnectRequest(conn net.Conn, address string) error {
|
||||
if strings.ContainsAny(address, "\r\n") {
|
||||
return NewProxyError(ErrTypeProtocol, "invalid CONNECT target", ErrCodeHTTPReadRespFailed, nil)
|
||||
}
|
||||
// 构建CONNECT请求
|
||||
req := fmt.Sprintf(HTTPConnectRequestFormat, address, address)
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHTTPDialerRejectsConnectTargetWithLineBreak(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
defer client.Close()
|
||||
defer server.Close()
|
||||
|
||||
dialer := &httpDialer{
|
||||
config: &ProxyConfig{Timeout: time.Second},
|
||||
stats: &ProxyStats{},
|
||||
}
|
||||
|
||||
err := dialer.sendConnectRequest(client, "example.com:80\r\nX-Injected: yes")
|
||||
if err == nil {
|
||||
t.Fatal("sendConnectRequest() error = nil, want invalid target error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestResultCallbackLifecycle(t *testing.T) {
|
||||
ClearResultCallback()
|
||||
t.Cleanup(ClearResultCallback)
|
||||
|
||||
called := false
|
||||
SetResultCallback(func(result interface{}) {
|
||||
called = true
|
||||
if result != "payload" {
|
||||
t.Fatalf("callback payload = %#v", result)
|
||||
}
|
||||
})
|
||||
|
||||
NotifyResult("payload")
|
||||
if !called {
|
||||
t.Fatal("callback was not called")
|
||||
}
|
||||
|
||||
called = false
|
||||
ClearResultCallback()
|
||||
NotifyResult("payload")
|
||||
if called {
|
||||
t.Fatal("callback should not be called after ClearResultCallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStateRuntimeTargetsAndShellFlags(t *testing.T) {
|
||||
state := NewState()
|
||||
|
||||
urls := []string{"http://example.com", "https://example.org"}
|
||||
state.SetURLs(urls)
|
||||
if got := state.GetURLs(); len(got) != 2 || got[0] != urls[0] || got[1] != urls[1] {
|
||||
t.Fatalf("urls = %#v", got)
|
||||
}
|
||||
|
||||
hostPorts := []string{"127.0.0.1:80", "[::1]:443"}
|
||||
state.SetHostPorts(hostPorts)
|
||||
if got := state.GetHostPorts(); len(got) != 2 || got[0] != hostPorts[0] || got[1] != hostPorts[1] {
|
||||
t.Fatalf("hostPorts = %#v", got)
|
||||
}
|
||||
state.ClearHostPorts()
|
||||
if got := state.GetHostPorts(); got != nil {
|
||||
t.Fatalf("hostPorts after clear = %#v, want nil", got)
|
||||
}
|
||||
|
||||
state.SetForwardShellActive(true)
|
||||
state.SetReverseShellActive(true)
|
||||
state.SetSocks5ProxyActive(true)
|
||||
if !state.IsForwardShellActive() || !state.IsReverseShellActive() || !state.IsSocks5ProxyActive() {
|
||||
t.Fatal("shell/proxy flags should be active")
|
||||
}
|
||||
|
||||
state.SetForwardShellActive(false)
|
||||
state.SetReverseShellActive(false)
|
||||
state.SetSocks5ProxyActive(false)
|
||||
if state.IsForwardShellActive() || state.IsReverseShellActive() || state.IsSocks5ProxyActive() {
|
||||
t.Fatal("shell/proxy flags should be inactive")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user