mandacaru-edr 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mandacaru/__init__.py +8 -0
- mandacaru/cli.py +177 -0
- mandacaru/collectors/__init__.py +0 -0
- mandacaru/collectors/ebpf.py +78 -0
- mandacaru/collectors/fsmon.py +59 -0
- mandacaru/collectors/procmon.py +65 -0
- mandacaru/config.py +99 -0
- mandacaru/detectors/__init__.py +0 -0
- mandacaru/detectors/behavior.py +120 -0
- mandacaru/detectors/static.py +159 -0
- mandacaru/engine.py +91 -0
- mandacaru/events.py +41 -0
- mandacaru/rules/yara/base.yar +111 -0
- mandacaru_edr-0.2.0.dist-info/METADATA +154 -0
- mandacaru_edr-0.2.0.dist-info/RECORD +19 -0
- mandacaru_edr-0.2.0.dist-info/WHEEL +5 -0
- mandacaru_edr-0.2.0.dist-info/entry_points.txt +2 -0
- mandacaru_edr-0.2.0.dist-info/licenses/LICENSE +674 -0
- mandacaru_edr-0.2.0.dist-info/top_level.txt +1 -0
mandacaru/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Mandacaru - antivirus/EDR de codigo aberto contra ataques conduzidos por IA.
|
|
2
|
+
# Copyright (C) 2026 Vandyck Diniz
|
|
3
|
+
#
|
|
4
|
+
# This program is free software: you can redistribute it and/or modify it
|
|
5
|
+
# under the terms of the GNU General Public License as published by the Free
|
|
6
|
+
# Software Foundation, either version 3 of the License, or (at your option)
|
|
7
|
+
# any later version. See the LICENSE file.
|
|
8
|
+
__version__ = "0.2.0"
|
mandacaru/cli.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""CLI: `mandacaru scan CAMINHO` e `mandacaru monitor`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import queue
|
|
7
|
+
import signal
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import replace
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .collectors import ebpf
|
|
16
|
+
from .collectors.fsmon import FileMonitor
|
|
17
|
+
from .collectors.procmon import ProcessMonitor
|
|
18
|
+
from .config import DEFAULT_PATH, Config, ConfigError, load_config
|
|
19
|
+
from .detectors.static import StaticScanner
|
|
20
|
+
from .engine import Engine, console_sink, jsonl_sink
|
|
21
|
+
from .events import Severity
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CliError(Exception):
|
|
25
|
+
"""Erro de uso que vira uma linha em stderr e saida 1, sem traceback."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
USER_DIRS = ("Downloads", "Documents", "Documentos", "Desktop", "Área de Trabalho")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def default_watch_paths(euid: int | None = None, home_root: Path = Path("/home")) -> list[str]:
|
|
32
|
+
"""Pastas vigiadas por padrao. Como root (servico), as de cada usuario em /home, nao /root."""
|
|
33
|
+
if euid is None and hasattr(os, "geteuid"):
|
|
34
|
+
euid = os.geteuid()
|
|
35
|
+
if euid == 0:
|
|
36
|
+
homes = sorted(h for h in home_root.iterdir() if h.is_dir()) if home_root.is_dir() else []
|
|
37
|
+
else:
|
|
38
|
+
homes = [Path.home()]
|
|
39
|
+
cands = [h / d for h in homes for d in USER_DIRS]
|
|
40
|
+
if os.name == "posix":
|
|
41
|
+
cands += [Path("/tmp"), Path("/dev/shm")]
|
|
42
|
+
return [str(p) for p in cands if p.exists()]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def effective_config(args: argparse.Namespace) -> Config:
|
|
46
|
+
"""Config final: flag da CLI > arquivo > padrao."""
|
|
47
|
+
cfg = load_config(args.config)
|
|
48
|
+
changes: dict = {}
|
|
49
|
+
if args.rules:
|
|
50
|
+
changes["rule_dirs"] = cfg.rule_dirs + tuple(args.rules)
|
|
51
|
+
if args.json:
|
|
52
|
+
changes["json_path"] = args.json
|
|
53
|
+
elif args.cmd == "scan":
|
|
54
|
+
# o json do arquivo e o log do servico (so root grava); scan avulso so grava com --json
|
|
55
|
+
changes["json_path"] = None
|
|
56
|
+
if args.min_severity:
|
|
57
|
+
changes["min_severity"] = Severity[args.min_severity]
|
|
58
|
+
if args.cmd == "monitor":
|
|
59
|
+
if args.paths:
|
|
60
|
+
changes["watch_paths"] = tuple(args.paths)
|
|
61
|
+
if args.no_ebpf:
|
|
62
|
+
changes["ebpf"] = False
|
|
63
|
+
cfg = replace(cfg, **changes)
|
|
64
|
+
if cfg.json_path:
|
|
65
|
+
# o proprio arquivo de alertas nao pode gerar novos alertas (laco no monitor)
|
|
66
|
+
cfg = replace(cfg, exclude=cfg.exclude + (os.path.abspath(cfg.json_path),))
|
|
67
|
+
return cfg
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def resolve_watch_paths(paths: list[str]) -> list[str]:
|
|
71
|
+
"""Avisa de cada pasta que nao existe; sem nenhuma, o monitor nao protegeria nada."""
|
|
72
|
+
existing = [p for p in paths if Path(p).is_dir()]
|
|
73
|
+
for p in paths:
|
|
74
|
+
if p not in existing:
|
|
75
|
+
print(f"[mandacaru] aviso: pasta vigiada nao existe: {p}", file=sys.stderr)
|
|
76
|
+
if not existing:
|
|
77
|
+
raise CliError("nenhuma pasta vigiada existe; confira [monitor] paths")
|
|
78
|
+
return existing
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def open_alert_log(path: str):
|
|
82
|
+
try:
|
|
83
|
+
return open(path, "a", encoding="utf-8")
|
|
84
|
+
except OSError as exc:
|
|
85
|
+
raise CliError(f"nao foi possivel gravar alertas em {path}: {exc.strerror or exc}") from exc
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def cmd_scan(args) -> int:
|
|
89
|
+
cfg = effective_config(args)
|
|
90
|
+
scanner = StaticScanner(cfg.rule_dirs, cfg.exclude)
|
|
91
|
+
sink = console_sink(cfg.min_severity)
|
|
92
|
+
out = jsonl_sink(open_alert_log(cfg.json_path)) if cfg.json_path else None
|
|
93
|
+
worst = Severity.INFO
|
|
94
|
+
n = 0
|
|
95
|
+
for path in args.paths:
|
|
96
|
+
for a in scanner.scan_tree(path):
|
|
97
|
+
n += 1
|
|
98
|
+
worst = max(worst, a.severity)
|
|
99
|
+
sink(a)
|
|
100
|
+
if out:
|
|
101
|
+
out(a)
|
|
102
|
+
print(f"{n} alerta(s). Pior severidade: {worst.name}", file=sys.stderr)
|
|
103
|
+
return 0 if worst < Severity.HIGH else 2
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def start_process_collector(q: queue.Queue, use_ebpf: bool) -> tuple[str, Callable[[], None]]:
|
|
107
|
+
"""Inicia o coletor de processos; eBPF que falha ao subir cai para psutil em vez de derrubar o agente."""
|
|
108
|
+
if use_ebpf and ebpf.available():
|
|
109
|
+
try:
|
|
110
|
+
tracer = ebpf.ExecTracer(q)
|
|
111
|
+
tracer.start()
|
|
112
|
+
return "ebpf", tracer.stop
|
|
113
|
+
except Exception as exc: # BCC falha de varias formas: sem headers, WSL, conteiner
|
|
114
|
+
print(f"[mandacaru] eBPF indisponivel ({exc}); usando psutil", file=sys.stderr)
|
|
115
|
+
pm = ProcessMonitor(q)
|
|
116
|
+
pm.start()
|
|
117
|
+
return "psutil", pm.stop
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cmd_monitor(args) -> int:
|
|
121
|
+
cfg = effective_config(args)
|
|
122
|
+
sinks = [console_sink(cfg.min_severity)]
|
|
123
|
+
if cfg.json_path:
|
|
124
|
+
sinks.append(jsonl_sink(open_alert_log(cfg.json_path)))
|
|
125
|
+
engine = Engine(sinks, scanner=StaticScanner(cfg.rule_dirs, cfg.exclude))
|
|
126
|
+
paths = resolve_watch_paths(list(cfg.watch_paths) or default_watch_paths())
|
|
127
|
+
|
|
128
|
+
kind, stop_procs = start_process_collector(engine.q, cfg.ebpf)
|
|
129
|
+
stoppers = [stop_procs]
|
|
130
|
+
print(f"[mandacaru] processos: {'eBPF (kernel)' if kind == 'ebpf' else 'psutil (polling)'}", file=sys.stderr)
|
|
131
|
+
fm = FileMonitor(paths, engine.q)
|
|
132
|
+
fm.start()
|
|
133
|
+
stoppers.append(fm.stop)
|
|
134
|
+
print(f"[mandacaru] vigiando arquivos em: {', '.join(paths)}", file=sys.stderr)
|
|
135
|
+
|
|
136
|
+
done = threading.Event()
|
|
137
|
+
signal.signal(signal.SIGINT, lambda *_: done.set())
|
|
138
|
+
if hasattr(signal, "SIGTERM"):
|
|
139
|
+
signal.signal(signal.SIGTERM, lambda *_: done.set())
|
|
140
|
+
t = threading.Thread(target=engine.run, daemon=True)
|
|
141
|
+
t.start()
|
|
142
|
+
done.wait()
|
|
143
|
+
for s in stoppers:
|
|
144
|
+
s()
|
|
145
|
+
engine.stop()
|
|
146
|
+
return 0
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
150
|
+
ap = argparse.ArgumentParser(prog="mandacaru", description="Antivirus/EDR GPLv3 contra ataques conduzidos por IA")
|
|
151
|
+
ap.add_argument("--version", action="version", version=__version__)
|
|
152
|
+
ap.add_argument("--config", help=f"arquivo de configuracao TOML (padrao: {DEFAULT_PATH}, se existir)")
|
|
153
|
+
ap.add_argument("--rules", action="append", default=[], help="pasta extra com regras .yar")
|
|
154
|
+
ap.add_argument("--json", help="grava alertas em JSON Lines neste arquivo")
|
|
155
|
+
ap.add_argument("--min-severity", default=None, choices=[s.name for s in Severity])
|
|
156
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
157
|
+
s = sub.add_parser("scan", help="varre arquivos/pastas")
|
|
158
|
+
s.add_argument("paths", nargs="+")
|
|
159
|
+
s.set_defaults(fn=cmd_scan)
|
|
160
|
+
m = sub.add_parser("monitor", help="monitora processos e arquivos em tempo real")
|
|
161
|
+
m.add_argument("paths", nargs="*", help="pastas a vigiar (padrao: Downloads, Documentos, /tmp...)")
|
|
162
|
+
m.add_argument("--no-ebpf", action="store_true")
|
|
163
|
+
m.set_defaults(fn=cmd_monitor)
|
|
164
|
+
return ap
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def main(argv=None) -> int:
|
|
168
|
+
args = build_parser().parse_args(argv)
|
|
169
|
+
try:
|
|
170
|
+
return args.fn(args)
|
|
171
|
+
except (ConfigError, CliError) as exc:
|
|
172
|
+
print(f"mandacaru: erro: {exc}", file=sys.stderr)
|
|
173
|
+
return 1
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if __name__ == "__main__":
|
|
177
|
+
sys.exit(main())
|
|
File without changes
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Coletor eBPF (Linux, root): captura todo execve direto do kernel.
|
|
2
|
+
|
|
3
|
+
Pega processos que vivem milissegundos, que o polling do psutil perde.
|
|
4
|
+
Requer o BCC do sistema: `sudo apt install bpfcc-tools python3-bpfcc`.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
import queue
|
|
10
|
+
import threading
|
|
11
|
+
|
|
12
|
+
from ..events import Event
|
|
13
|
+
|
|
14
|
+
BPF_PROGRAM = r"""
|
|
15
|
+
#include <linux/sched.h>
|
|
16
|
+
struct data_t {
|
|
17
|
+
u32 pid;
|
|
18
|
+
u32 ppid;
|
|
19
|
+
char comm[TASK_COMM_LEN];
|
|
20
|
+
char pcomm[TASK_COMM_LEN];
|
|
21
|
+
char fname[256];
|
|
22
|
+
};
|
|
23
|
+
BPF_PERF_OUTPUT(events);
|
|
24
|
+
|
|
25
|
+
TRACEPOINT_PROBE(syscalls, sys_enter_execve) {
|
|
26
|
+
struct data_t d = {};
|
|
27
|
+
struct task_struct *t = (struct task_struct *)bpf_get_current_task();
|
|
28
|
+
d.pid = bpf_get_current_pid_tgid() >> 32;
|
|
29
|
+
d.ppid = t->real_parent->tgid;
|
|
30
|
+
bpf_get_current_comm(&d.comm, sizeof(d.comm));
|
|
31
|
+
bpf_probe_read_kernel_str(&d.pcomm, sizeof(d.pcomm), t->real_parent->comm);
|
|
32
|
+
bpf_probe_read_user_str(&d.fname, sizeof(d.fname), args->filename);
|
|
33
|
+
events.perf_submit(args, &d, sizeof(d));
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def available() -> bool:
|
|
40
|
+
if os.name != "posix" or os.geteuid() != 0:
|
|
41
|
+
return False
|
|
42
|
+
try:
|
|
43
|
+
import bcc # noqa: F401
|
|
44
|
+
return True
|
|
45
|
+
except ImportError:
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ExecTracer(threading.Thread):
|
|
50
|
+
def __init__(self, out: queue.Queue):
|
|
51
|
+
super().__init__(daemon=True, name="ebpf-exec")
|
|
52
|
+
from bcc import BPF
|
|
53
|
+
self.out = out
|
|
54
|
+
self.bpf = BPF(text=BPF_PROGRAM)
|
|
55
|
+
self.bpf["events"].open_perf_buffer(self._on_event)
|
|
56
|
+
self._stop = threading.Event()
|
|
57
|
+
|
|
58
|
+
def _on_event(self, cpu, data, size):
|
|
59
|
+
e = self.bpf["events"].event(data)
|
|
60
|
+
exe = e.fname.decode(errors="replace")
|
|
61
|
+
cmdline = []
|
|
62
|
+
try:
|
|
63
|
+
with open(f"/proc/{e.pid}/cmdline", "rb") as fh:
|
|
64
|
+
cmdline = [c.decode(errors="replace") for c in fh.read().split(b"\0") if c]
|
|
65
|
+
except OSError:
|
|
66
|
+
pass
|
|
67
|
+
parent = e.pcomm.decode(errors="replace")
|
|
68
|
+
self.out.put(Event("process_start", {
|
|
69
|
+
"pid": e.pid, "ppid": e.ppid, "exe": exe, "name": os.path.basename(exe),
|
|
70
|
+
"cmdline": cmdline, "parent_name": parent, "ancestry": [parent], "remote_conns": [],
|
|
71
|
+
}, source="ebpf"))
|
|
72
|
+
|
|
73
|
+
def stop(self):
|
|
74
|
+
self._stop.set()
|
|
75
|
+
|
|
76
|
+
def run(self):
|
|
77
|
+
while not self._stop.is_set():
|
|
78
|
+
self.bpf.perf_buffer_poll(timeout=200)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Coletor de arquivos (watchdog: inotify no Linux, ReadDirectoryChangesW no Windows)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import queue
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from watchdog.events import FileSystemEvent, FileSystemEventHandler
|
|
8
|
+
from watchdog.observers import Observer
|
|
9
|
+
|
|
10
|
+
from ..detectors.static import shannon_entropy
|
|
11
|
+
from ..events import Event
|
|
12
|
+
|
|
13
|
+
SAMPLE = 4096
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def sample_entropy(path: str) -> float | None:
|
|
17
|
+
try:
|
|
18
|
+
with open(path, "rb") as fh:
|
|
19
|
+
data = fh.read(SAMPLE)
|
|
20
|
+
return shannon_entropy(data) if len(data) >= 512 else None
|
|
21
|
+
except OSError:
|
|
22
|
+
return None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Handler(FileSystemEventHandler):
|
|
26
|
+
def __init__(self, out: queue.Queue):
|
|
27
|
+
self.out = out
|
|
28
|
+
|
|
29
|
+
def _emit(self, kind: str, path: str, **extra):
|
|
30
|
+
self.out.put(Event(kind, {"path": path, "entropy": sample_entropy(extra.get("dest", path)), **extra},
|
|
31
|
+
source="fsmon"))
|
|
32
|
+
|
|
33
|
+
def on_created(self, e: FileSystemEvent):
|
|
34
|
+
if not e.is_directory:
|
|
35
|
+
self._emit("file_create", e.src_path)
|
|
36
|
+
|
|
37
|
+
def on_modified(self, e: FileSystemEvent):
|
|
38
|
+
if not e.is_directory:
|
|
39
|
+
self._emit("file_write", e.src_path)
|
|
40
|
+
|
|
41
|
+
def on_moved(self, e: FileSystemEvent):
|
|
42
|
+
if not e.is_directory:
|
|
43
|
+
self._emit("file_rename", e.src_path, dest=e.dest_path)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class FileMonitor:
|
|
47
|
+
def __init__(self, paths: list[str], out: queue.Queue):
|
|
48
|
+
self.observer = Observer()
|
|
49
|
+
handler = _Handler(out)
|
|
50
|
+
for p in paths:
|
|
51
|
+
if Path(p).exists():
|
|
52
|
+
self.observer.schedule(handler, p, recursive=True)
|
|
53
|
+
|
|
54
|
+
def start(self):
|
|
55
|
+
self.observer.start()
|
|
56
|
+
|
|
57
|
+
def stop(self):
|
|
58
|
+
self.observer.stop()
|
|
59
|
+
self.observer.join(timeout=3)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Coletor de processos multiplataforma (psutil, por polling).
|
|
2
|
+
|
|
3
|
+
E o fallback universal. No Linux com root, o coletor eBPF ve processos de
|
|
4
|
+
vida curta que o polling pode perder.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import queue
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import psutil
|
|
13
|
+
|
|
14
|
+
from ..events import Event
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def describe(proc: psutil.Process) -> dict:
|
|
18
|
+
with proc.oneshot():
|
|
19
|
+
info = {"pid": proc.pid, "ppid": proc.ppid(), "name": proc.name()}
|
|
20
|
+
for key, fn in (("exe", proc.exe), ("cmdline", proc.cmdline), ("user", proc.username)):
|
|
21
|
+
try:
|
|
22
|
+
info[key] = fn()
|
|
23
|
+
except (psutil.AccessDenied, psutil.ZombieProcess, OSError):
|
|
24
|
+
info[key] = None
|
|
25
|
+
ancestry = []
|
|
26
|
+
try:
|
|
27
|
+
for p in proc.parents()[:6]:
|
|
28
|
+
ancestry.append(p.name())
|
|
29
|
+
except (psutil.Error, OSError):
|
|
30
|
+
pass
|
|
31
|
+
info["parent_name"] = ancestry[0] if ancestry else None
|
|
32
|
+
info["ancestry"] = ancestry
|
|
33
|
+
try:
|
|
34
|
+
# net_connections so existe no psutil >= 6; antes disso (Ubuntu 24.04) e connections
|
|
35
|
+
conns = getattr(proc, "net_connections", None) or proc.connections
|
|
36
|
+
info["remote_conns"] = [f"{c.raddr.ip}:{c.raddr.port}" for c in conns(kind="inet") if c.raddr]
|
|
37
|
+
except (psutil.Error, OSError, AttributeError):
|
|
38
|
+
info["remote_conns"] = []
|
|
39
|
+
return info
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ProcessMonitor(threading.Thread):
|
|
43
|
+
def __init__(self, out: queue.Queue, interval: float = 0.5):
|
|
44
|
+
super().__init__(daemon=True, name="procmon")
|
|
45
|
+
self.out, self.interval = out, interval
|
|
46
|
+
self._stop = threading.Event()
|
|
47
|
+
self._seen = {p.pid: p.create_time() for p in psutil.process_iter(["create_time"])}
|
|
48
|
+
|
|
49
|
+
def stop(self):
|
|
50
|
+
self._stop.set()
|
|
51
|
+
|
|
52
|
+
def run(self):
|
|
53
|
+
while not self._stop.is_set():
|
|
54
|
+
current = {}
|
|
55
|
+
for p in psutil.process_iter(["create_time"]):
|
|
56
|
+
ct = p.info.get("create_time")
|
|
57
|
+
current[p.pid] = ct
|
|
58
|
+
if self._seen.get(p.pid) == ct:
|
|
59
|
+
continue
|
|
60
|
+
try:
|
|
61
|
+
self.out.put(Event("process_start", describe(p), source="procmon"))
|
|
62
|
+
except psutil.Error:
|
|
63
|
+
pass
|
|
64
|
+
self._seen = current
|
|
65
|
+
time.sleep(self.interval)
|
mandacaru/config.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Configuracao do Mandacaru a partir de um arquivo TOML.
|
|
2
|
+
|
|
3
|
+
Chave desconhecida ou tipo errado e erro, nunca e ignorado: um erro de
|
|
4
|
+
digitacao nao pode desligar protecao em silencio.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import os
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
import tomllib
|
|
14
|
+
except ModuleNotFoundError: # Python 3.10
|
|
15
|
+
import tomli as tomllib
|
|
16
|
+
|
|
17
|
+
from .events import Severity
|
|
18
|
+
|
|
19
|
+
DEFAULT_PATH = "/etc/mandacaru/config.toml"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ConfigError(ValueError):
|
|
23
|
+
"""Arquivo de configuracao ausente, ilegivel ou invalido."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Config:
|
|
28
|
+
watch_paths: tuple[str, ...] = ()
|
|
29
|
+
ebpf: bool = True
|
|
30
|
+
min_severity: Severity = Severity.LOW
|
|
31
|
+
json_path: str | None = None
|
|
32
|
+
rule_dirs: tuple[str, ...] = ()
|
|
33
|
+
exclude: tuple[str, ...] = ()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _str_list(value, key: str) -> tuple[str, ...]:
|
|
37
|
+
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
38
|
+
raise ConfigError(f"{key}: esperava uma lista de textos")
|
|
39
|
+
return tuple(value)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _bool(value, key: str) -> bool:
|
|
43
|
+
if not isinstance(value, bool):
|
|
44
|
+
raise ConfigError(f"{key}: esperava true ou false")
|
|
45
|
+
return value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _str(value, key: str) -> str:
|
|
49
|
+
if not isinstance(value, str):
|
|
50
|
+
raise ConfigError(f"{key}: esperava um texto")
|
|
51
|
+
return value
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _severity(value, key: str) -> Severity:
|
|
55
|
+
name = _str(value, key).upper()
|
|
56
|
+
if name not in Severity.__members__:
|
|
57
|
+
raise ConfigError(f"{key}: valor invalido {value!r}; use um de {', '.join(Severity.__members__)}")
|
|
58
|
+
return Severity[name]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# secao -> chave -> (campo do Config, conversor)
|
|
62
|
+
_SCHEMA = {
|
|
63
|
+
"monitor": {"paths": ("watch_paths", _str_list), "ebpf": ("ebpf", _bool)},
|
|
64
|
+
"alerts": {"min_severity": ("min_severity", _severity), "json": ("json_path", _str)},
|
|
65
|
+
"rules": {"dirs": ("rule_dirs", _str_list)},
|
|
66
|
+
"exclude": {"paths": ("exclude", _str_list)},
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def load_config(path: str | os.PathLike | None = None) -> Config:
|
|
71
|
+
"""Le o config. Sem `path`, usa DEFAULT_PATH se existir, senao os padroes."""
|
|
72
|
+
if path is None:
|
|
73
|
+
if not Path(DEFAULT_PATH).is_file():
|
|
74
|
+
return Config()
|
|
75
|
+
path = DEFAULT_PATH
|
|
76
|
+
try:
|
|
77
|
+
with open(path, "rb") as fh:
|
|
78
|
+
raw = tomllib.load(fh)
|
|
79
|
+
except OSError as exc:
|
|
80
|
+
raise ConfigError(f"{path}: nao foi possivel ler ({exc.strerror or exc})") from exc
|
|
81
|
+
except tomllib.TOMLDecodeError as exc:
|
|
82
|
+
raise ConfigError(f"{path}: TOML invalido: {exc}") from exc
|
|
83
|
+
|
|
84
|
+
fields = {}
|
|
85
|
+
try:
|
|
86
|
+
for section, body in raw.items():
|
|
87
|
+
if section not in _SCHEMA:
|
|
88
|
+
raise ConfigError(f"secao desconhecida [{section}]; validas: {', '.join(_SCHEMA)}")
|
|
89
|
+
if not isinstance(body, dict):
|
|
90
|
+
raise ConfigError(f"{section}: esperava uma secao [{section}]")
|
|
91
|
+
for key, value in body.items():
|
|
92
|
+
if key not in _SCHEMA[section]:
|
|
93
|
+
raise ConfigError(
|
|
94
|
+
f"chave desconhecida {section}.{key}; validas: {', '.join(_SCHEMA[section])}")
|
|
95
|
+
field, convert = _SCHEMA[section][key]
|
|
96
|
+
fields[field] = convert(value, f"{section}.{key}")
|
|
97
|
+
except ConfigError as exc:
|
|
98
|
+
raise ConfigError(f"{path}: {exc}") from None
|
|
99
|
+
return Config(**fields)
|
|
File without changes
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Deteccao por comportamento: regras com estado sobre o fluxo de eventos.
|
|
2
|
+
|
|
3
|
+
Aqui mora a defesa contra malware polimorfico/gerado por IA: o codigo muda,
|
|
4
|
+
mas o que ele precisa *fazer* (criptografar em massa, abrir shell a partir
|
|
5
|
+
de um servico, ler credenciais) continua igual.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
from collections import defaultdict, deque
|
|
12
|
+
from pathlib import PurePath
|
|
13
|
+
|
|
14
|
+
from ..events import Alert, Event, Severity
|
|
15
|
+
|
|
16
|
+
SHELLS = {"sh", "bash", "zsh", "dash", "fish", "cmd.exe", "powershell.exe", "pwsh", "pwsh.exe"}
|
|
17
|
+
SERVICE_PARENTS = {"nginx", "apache2", "httpd", "php-fpm", "node", "java", "tomcat", "w3wp.exe",
|
|
18
|
+
"winword.exe", "excel.exe", "outlook.exe", "postgres", "mysqld"}
|
|
19
|
+
AI_AGENT_HINTS = ("claude", "mcp", "ollama", "codex", "aider", "copilot", "cursor", "langchain", "autogen")
|
|
20
|
+
TEMP_DIRS = ("/tmp/", "/var/tmp/", "/dev/shm/", "\\appdata\\local\\temp\\", "\\windows\\temp\\")
|
|
21
|
+
SENSITIVE = (".ssh/", ".aws/credentials", ".env", ".kube/config", ".docker/config.json",
|
|
22
|
+
"login data", "cookies", "keychain", ".gnupg/", "id_rsa", "id_ed25519", ".netrc",
|
|
23
|
+
".git-credentials")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _name(path_or_name: str | None) -> str:
|
|
27
|
+
return PurePath(path_or_name or "").name.lower()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class BehaviorEngine:
|
|
31
|
+
def __init__(self, burst_window: float = 10.0, burst_threshold: int = 25,
|
|
32
|
+
entropy_threshold: float = 7.2, cooldown: float = 60.0):
|
|
33
|
+
self.burst_window = burst_window
|
|
34
|
+
self.burst_threshold = burst_threshold
|
|
35
|
+
self.entropy_threshold = entropy_threshold
|
|
36
|
+
self.cooldown = cooldown
|
|
37
|
+
self._writes: dict[str, deque] = defaultdict(deque) # dir -> timestamps de escritas de alta entropia
|
|
38
|
+
self._last_alert: dict[str, float] = {}
|
|
39
|
+
|
|
40
|
+
# -- utilitario: evita inundar o usuario com o mesmo alerta
|
|
41
|
+
def _fire(self, key: str, alert: Alert) -> list[Alert]:
|
|
42
|
+
now = time.time()
|
|
43
|
+
if now - self._last_alert.get(key, 0) < self.cooldown:
|
|
44
|
+
return []
|
|
45
|
+
self._last_alert[key] = now
|
|
46
|
+
return [alert]
|
|
47
|
+
|
|
48
|
+
def handle(self, ev: Event) -> list[Alert]:
|
|
49
|
+
if ev.kind == "process_start":
|
|
50
|
+
return self._on_process(ev)
|
|
51
|
+
if ev.kind in ("file_write", "file_rename", "file_create"):
|
|
52
|
+
return self._on_file(ev)
|
|
53
|
+
return []
|
|
54
|
+
|
|
55
|
+
# ----------------------------------------------------------- processos
|
|
56
|
+
def _on_process(self, ev: Event) -> list[Alert]:
|
|
57
|
+
d = ev.data
|
|
58
|
+
exe = (d.get("exe") or "").lower()
|
|
59
|
+
name = _name(d.get("name") or exe)
|
|
60
|
+
parent = _name(d.get("parent_name"))
|
|
61
|
+
cmd = " ".join(d.get("cmdline") or []).lower()
|
|
62
|
+
ancestry = [_name(a) for a in d.get("ancestry", [])]
|
|
63
|
+
out: list[Alert] = []
|
|
64
|
+
|
|
65
|
+
# 1) shell aberto por servico/aplicativo de escritorio
|
|
66
|
+
if name in SHELLS and parent in SERVICE_PARENTS:
|
|
67
|
+
out += self._fire(f"svcshell:{d.get('pid')}", Alert(
|
|
68
|
+
"behavior.service_spawned_shell", Severity.HIGH,
|
|
69
|
+
f"{parent} abriu um shell ({name})",
|
|
70
|
+
{"pid": d.get("pid"), "parent": parent, "cmdline": cmd}, ["T1059", "T1190"]))
|
|
71
|
+
|
|
72
|
+
# 2) execucao a partir de diretorio temporario
|
|
73
|
+
if exe and any(t in exe for t in TEMP_DIRS):
|
|
74
|
+
out += self._fire(f"tmpexec:{exe}", Alert(
|
|
75
|
+
"behavior.exec_from_temp", Severity.MEDIUM,
|
|
76
|
+
f"Executavel rodando de pasta temporaria: {exe}",
|
|
77
|
+
{"pid": d.get("pid"), "exe": exe, "cmdline": cmd}, ["T1204"]))
|
|
78
|
+
|
|
79
|
+
# 3) shell com conexao de rede ativa (possivel shell reverso)
|
|
80
|
+
if name in SHELLS and d.get("remote_conns"):
|
|
81
|
+
out += self._fire(f"revshell:{d.get('pid')}", Alert(
|
|
82
|
+
"behavior.shell_with_network", Severity.CRITICAL,
|
|
83
|
+
f"Shell {name} com conexao de rede ativa",
|
|
84
|
+
{"pid": d.get("pid"), "conns": d.get("remote_conns")}, ["T1059"]))
|
|
85
|
+
|
|
86
|
+
# 4) agente de IA (ou servidor MCP) mexendo em credenciais
|
|
87
|
+
if any(h in a for a in ancestry + [parent, name] for h in AI_AGENT_HINTS):
|
|
88
|
+
hits = [s for s in SENSITIVE if s in cmd]
|
|
89
|
+
if hits:
|
|
90
|
+
out += self._fire(f"agentcred:{d.get('pid')}", Alert(
|
|
91
|
+
"behavior.ai_agent_credential_access", Severity.HIGH,
|
|
92
|
+
"Processo iniciado por agente de IA acessando credenciais",
|
|
93
|
+
{"pid": d.get("pid"), "ancestry": ancestry, "cmdline": cmd, "matched": hits},
|
|
94
|
+
["T1552", "T1059"]))
|
|
95
|
+
if name in SHELLS and any(k in cmd for k in ("curl", "wget", "invoke-webrequest", "nc ", "scp ")):
|
|
96
|
+
out += self._fire(f"agentexfil:{d.get('pid')}", Alert(
|
|
97
|
+
"behavior.ai_agent_network_shell", Severity.MEDIUM,
|
|
98
|
+
"Agente de IA abriu shell com ferramenta de rede",
|
|
99
|
+
{"pid": d.get("pid"), "ancestry": ancestry, "cmdline": cmd}, ["T1041"]))
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
# ------------------------------------------------------------ arquivos
|
|
103
|
+
def _on_file(self, ev: Event) -> list[Alert]:
|
|
104
|
+
d = ev.data
|
|
105
|
+
path = d.get("dest") or d.get("path") or ""
|
|
106
|
+
ent = d.get("entropy")
|
|
107
|
+
if ent is None or ent < self.entropy_threshold:
|
|
108
|
+
return []
|
|
109
|
+
folder = os.path.dirname(path)
|
|
110
|
+
q = self._writes[folder]
|
|
111
|
+
q.append(ev.ts)
|
|
112
|
+
while q and ev.ts - q[0] > self.burst_window:
|
|
113
|
+
q.popleft()
|
|
114
|
+
if len(q) >= self.burst_threshold:
|
|
115
|
+
return self._fire(f"ransom:{folder}", Alert(
|
|
116
|
+
"behavior.ransomware_burst", Severity.CRITICAL,
|
|
117
|
+
f"{len(q)} arquivos reescritos com conteudo cifrado em {self.burst_window:.0f}s",
|
|
118
|
+
{"folder": folder, "count": len(q), "last_file": path, "entropy": round(ent, 2)},
|
|
119
|
+
["T1486"]))
|
|
120
|
+
return []
|