Compare commits

..

No commits in common. "a1faa3c9b5bc5c5c2e1a93142dd73156b53a22e7" and "f06484ed24497878580770f05c15e2c9adeaacc8" have entirely different histories.

2 changed files with 24 additions and 119 deletions

View File

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

View File

@ -1,10 +1,6 @@
package detector
import (
"bufio"
"os"
"path/filepath"
"strings"
"sync"
"sysmonitord/internal/config"
"sysmonitord/internal/scanner/hash"
@ -16,65 +12,24 @@ import (
)
type FileDetector struct {
cfg *config.Config
whiteList map[string]string
dubiousCache map[string]string
storageDir string
mu sync.RWMutex
timer map[string]*time.Timer
debDuration time.Duration
cfg *config.Config
whiteList map[string]string
storageDir string
mu sync.RWMutex
}
func NewFileDetector(cfg *config.Config) (*FileDetector, error) {
d := &FileDetector{
cfg: cfg,
storageDir: cfg.Storage.DataDir,
timer: make(map[string]*time.Timer),
debDuration: 1 * time.Second,
dubiousCache: make(map[string]string),
cfg: cfg,
storageDir: cfg.Storage.DataDir,
}
if err := d.loadWhiteList(); err != nil {
return nil, err
}
if err := d.loadDubiousCache(); err != nil {
logger.Log.Warn("[monitor] 加载可疑文件缓存失败,使用空缓存...", zap.Error((err)))
}
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 {
whiteMap, err := storage.LoadFileSystemWhitelist(d.cfg.Storage.DataDir, d.cfg.Storage.FileSystemFile)
if err != nil {
@ -91,22 +46,6 @@ func (d *FileDetector) loadWhiteList() error {
func (d *FileDetector) HandleEvent(eventPath string, opStr string) {
// 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)
if err != nil {
logger.Log.Warn("[monitor] 获取文件信息失败", zap.String("path", eventPath), zap.Error(err))
@ -146,27 +85,14 @@ func (d *FileDetector) processEvent(eventPath string) {
}
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))
dubiousInfo := storage.DubiousFileInfo{
Path: eventPath,
Hash: curHash,
DiscoveredAt: time.Now().Format("2006-01-02 15:04:05"),
}
if err := storage.SaveDubiousFiles(dubiousInfo, d.storageDir, d.cfg.Storage.DubiousFileListFile); err != nil {
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))
logger.Log.Warn("[monitor] 可疑文件事件", zap.String("path", eventPath), zap.String("reason", reason), zap.String("hash", curHash))
dubiousInfo := storage.DubiousFileInfo{
Path: eventPath,
Hash: curHash,
DiscoveredAt: time.Now().Format("2006-01-02 15:04:05"),
}
if err := storage.SaveDubiousFiles(dubiousInfo, d.storageDir, d.cfg.Storage.DubiousFileListFile); err != nil {
logger.Log.Error("[monitor] 保存可疑文件信息失败", zap.String("path", eventPath), zap.Error(err))
}
}
}