Compare commits

...

4 Commits

Author SHA1 Message Date
wuko233 a1faa3c9b5 [cmd] 设置不处理按键为ESC 2026-04-08 15:22:04 +08:00
wuko233 99e314c925 [monitor] 可疑文件去重 2026-04-08 15:16:23 +08:00
wuko233 13f46f4405 [monitor] 文件检测支持防抖动 2026-04-08 14:52:52 +08:00
wuko233 826c4a24ec [cmd] 去除哈希与序号表示 2026-04-08 14:31:00 +08:00
2 changed files with 119 additions and 24 deletions

View File

@ -13,6 +13,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"go.uber.org/zap" "go.uber.org/zap"
"golang.org/x/term"
) )
var SafeCmd = &cobra.Command{ var SafeCmd = &cobra.Command{
@ -30,6 +31,25 @@ var SafeCmd = &cobra.Command{
}, },
} }
func readKeyWithESC() (string, error) {
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return "", err
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
b := make([]byte, 1)
_, err = os.Stdin.Read(b)
if err != nil {
return "", err
}
if b[0] == 27 { // ESC
return "ESC", nil
}
return string(b), nil
}
func interactiveSafe(cfg *config.Config) { func interactiveSafe(cfg *config.Config) {
dataDir := cfg.Storage.DataDir dataDir := cfg.Storage.DataDir
@ -47,21 +67,22 @@ func interactiveSafe(cfg *config.Config) {
fmt.Println("║ 可疑文件清单 (" + fmt.Sprintf("%d", len(dubiousFiles)) + "个) ║") fmt.Println("║ 可疑文件清单 (" + fmt.Sprintf("%d", len(dubiousFiles)) + "个) ║")
fmt.Println("╠══════════════════════════════════════════════╣") fmt.Println("╠══════════════════════════════════════════════╣")
for i, file := range dubiousFiles { for _, file := range dubiousFiles {
fmt.Printf("║ %d. %-40s║\n", i+1, file.Path) fmt.Printf("║ %-45s║\n", file.Path)
fmt.Printf("║ Hash: %-36s║\n", file.Hash[:8]+"...")
} }
fmt.Println("╚══════════════════════════════════════════════╝") fmt.Println("╚══════════════════════════════════════════════╝")
fmt.Println("\n请选择操作:") fmt.Println("\n请选择操作:")
fmt.Println("[1] 将以上可疑文件全部确认为安全 (移至白名单)") fmt.Println("[1] 将以上可疑文件全部确认为安全 (移至白名单)")
// Todo: 支持逐个确认 // Todo: 支持逐个确认
fmt.Println("[2] 退出不处理") fmt.Println("[ESC] 退出不处理")
fmt.Print("请输入选项 (1-2): ") fmt.Print("请输入选项: ")
reader := bufio.NewReader(os.Stdin) input, err := readKeyWithESC()
input, _ := reader.ReadString('\n') if err != nil {
input = strings.TrimSpace(input) fmt.Printf("读取输入失败: %v\n", err)
return
}
switch input { switch input {
case "1": case "1":
@ -71,7 +92,7 @@ func interactiveSafe(cfg *config.Config) {
} else { } else {
fmt.Println("已将可疑文件移入白名单。") fmt.Println("已将可疑文件移入白名单。")
} }
case "2": case "ESC":
fmt.Println("已取消操作。") fmt.Println("已取消操作。")
default: default:
fmt.Println("无效选项,已退出。") fmt.Println("无效选项,已退出。")

View File

@ -1,6 +1,10 @@
package detector package detector
import ( import (
"bufio"
"os"
"path/filepath"
"strings"
"sync" "sync"
"sysmonitord/internal/config" "sysmonitord/internal/config"
"sysmonitord/internal/scanner/hash" "sysmonitord/internal/scanner/hash"
@ -14,22 +18,63 @@ import (
type FileDetector struct { type FileDetector struct {
cfg *config.Config cfg *config.Config
whiteList map[string]string whiteList map[string]string
dubiousCache map[string]string
storageDir string storageDir string
mu sync.RWMutex mu sync.RWMutex
timer map[string]*time.Timer
debDuration time.Duration
} }
func NewFileDetector(cfg *config.Config) (*FileDetector, error) { func NewFileDetector(cfg *config.Config) (*FileDetector, error) {
d := &FileDetector{ d := &FileDetector{
cfg: cfg, cfg: cfg,
storageDir: cfg.Storage.DataDir, storageDir: cfg.Storage.DataDir,
timer: make(map[string]*time.Timer),
debDuration: 1 * time.Second,
dubiousCache: make(map[string]string),
} }
if err := d.loadWhiteList(); err != nil { if err := d.loadWhiteList(); err != nil {
return nil, err return nil, err
} }
if err := d.loadDubiousCache(); err != nil {
logger.Log.Warn("[monitor] 加载可疑文件缓存失败,使用空缓存...", zap.Error((err)))
}
return d, nil return d, nil
} }
func (d *FileDetector) loadDubiousCache() error {
filePath := filepath.Join(d.storageDir, d.cfg.Storage.DubiousFileListFile)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
return nil
}
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := strings.Split(line, ":")
if len(parts) >= 2 {
d.dubiousCache[parts[0]] = parts[1]
}
}
logger.Log.Debug("[monitor] 可疑文件缓存加载成功", zap.Int("count", len(d.dubiousCache)))
return scanner.Err()
}
func (d *FileDetector) loadWhiteList() error { func (d *FileDetector) loadWhiteList() error {
whiteMap, err := storage.LoadFileSystemWhitelist(d.cfg.Storage.DataDir, d.cfg.Storage.FileSystemFile) whiteMap, err := storage.LoadFileSystemWhitelist(d.cfg.Storage.DataDir, d.cfg.Storage.FileSystemFile)
if err != nil { if err != nil {
@ -46,6 +91,22 @@ func (d *FileDetector) loadWhiteList() error {
func (d *FileDetector) HandleEvent(eventPath string, opStr string) { func (d *FileDetector) HandleEvent(eventPath string, opStr string) {
// Todo: 忽略临时文件等 // Todo: 忽略临时文件等
d.mu.Lock()
defer d.mu.Unlock()
if t, exists := d.timer[eventPath]; exists {
t.Stop()
}
d.timer[eventPath] = time.AfterFunc(d.debDuration, func() {
d.processEvent(eventPath)
d.mu.Lock()
delete(d.timer, eventPath)
d.mu.Unlock()
})
}
func (d *FileDetector) processEvent(eventPath string) {
info, err := storage.GetFileInfo(eventPath) info, err := storage.GetFileInfo(eventPath)
if err != nil { if err != nil {
logger.Log.Warn("[monitor] 获取文件信息失败", zap.String("path", eventPath), zap.Error(err)) logger.Log.Warn("[monitor] 获取文件信息失败", zap.String("path", eventPath), zap.Error(err))
@ -85,6 +146,15 @@ func (d *FileDetector) HandleEvent(eventPath string, opStr string) {
} }
if isSuspicious { if isSuspicious {
d.mu.Lock()
cachedHash, exist := d.dubiousCache[eventPath]
if !exist || cachedHash != curHash {
d.dubiousCache[eventPath] = curHash
d.mu.Unlock()
logger.Log.Warn("[monitor] 可疑文件事件", zap.String("path", eventPath), zap.String("reason", reason), zap.String("hash", curHash)) logger.Log.Warn("[monitor] 可疑文件事件", zap.String("path", eventPath), zap.String("reason", reason), zap.String("hash", curHash))
dubiousInfo := storage.DubiousFileInfo{ dubiousInfo := storage.DubiousFileInfo{
Path: eventPath, Path: eventPath,
@ -94,5 +164,9 @@ func (d *FileDetector) HandleEvent(eventPath string, opStr string) {
if err := storage.SaveDubiousFiles(dubiousInfo, d.storageDir, d.cfg.Storage.DubiousFileListFile); err != nil { if err := storage.SaveDubiousFiles(dubiousInfo, d.storageDir, d.cfg.Storage.DubiousFileListFile); err != nil {
logger.Log.Error("[monitor] 保存可疑文件信息失败", zap.String("path", eventPath), zap.Error(err)) logger.Log.Error("[monitor] 保存可疑文件信息失败", zap.String("path", eventPath), zap.Error(err))
} }
} else {
d.mu.Unlock()
logger.Log.Debug("[monitor] 文件事件已存在于可疑缓存中,忽略重复事件", zap.String("path", eventPath), zap.String("reason", reason), zap.String("hash", curHash))
}
} }
} }