sentrion 0.0.0-stage → 2.0.0
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.
- package/LICENSE +21 -0
- package/README.md +134 -2
- package/bin/sentrion.js +11 -0
- package/lib/cli.js +117 -0
- package/lib/cmd-allow.js +16 -0
- package/lib/cmd-doctor.js +40 -0
- package/lib/cmd-init.js +26 -0
- package/lib/cmd-mode.js +22 -0
- package/lib/cmd-rules.js +51 -0
- package/lib/cmd-scan.js +58 -0
- package/lib/cmd-shell-init.js +28 -0
- package/lib/cmd-test.js +26 -0
- package/lib/cmd-trust.js +53 -0
- package/lib/cmd-update.js +59 -0
- package/lib/data/malware.json +56 -0
- package/lib/data/typosquats.json +13 -0
- package/lib/guard.js +246 -0
- package/lib/hook.js +257 -0
- package/lib/policy.js +109 -0
- package/lib/proxy.js +61 -0
- package/lib/py/sitecustomize.py +167 -0
- package/lib/report.js +131 -0
- package/lib/rules.js +43 -0
- package/lib/scan.js +131 -0
- package/lib/sensors.js +112 -0
- package/lib/store.js +32 -0
- package/lib/ui.js +63 -0
- package/package.json +43 -4
package/lib/policy.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Policy: built-in defaults merged with ~/.sentrion/policy.json (user) and
|
|
3
|
+
// ./.sentrion.json (project). A project policy may only make things STRICTER,
|
|
4
|
+
// never looser, so a cloned repo cannot ship a config that disables the guard.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { RULES } = require('./rules.js');
|
|
10
|
+
|
|
11
|
+
const DEFAULTS = {
|
|
12
|
+
mode: 'prompt', // prompt | enforce | audit | learn
|
|
13
|
+
askTimeoutSec: 60,
|
|
14
|
+
install: {
|
|
15
|
+
allowHosts: [
|
|
16
|
+
'registry.npmjs.org', 'registry.yarnpkg.com',
|
|
17
|
+
'pypi.org', 'files.pythonhosted.org',
|
|
18
|
+
'github.com', 'codeload.github.com', 'objects.githubusercontent.com',
|
|
19
|
+
],
|
|
20
|
+
minPackageAgeHours: 48,
|
|
21
|
+
},
|
|
22
|
+
run: { allowHosts: [], allowListen: ['127.0.0.1', '::1', 'localhost'] },
|
|
23
|
+
secrets: {
|
|
24
|
+
paths: [
|
|
25
|
+
'~/.ssh', '~/.aws', '~/.npmrc', '~/.config/gcloud', '~/.docker/config.json',
|
|
26
|
+
'~/.gnupg', '~/.kube/config', '~/.netrc', '~/.git-credentials',
|
|
27
|
+
'~/Library/Keychains', 'AppData/Roaming/npm',
|
|
28
|
+
],
|
|
29
|
+
stripEnv: ['NPM_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN', 'AWS_ACCESS_KEY_ID',
|
|
30
|
+
'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN', 'GOOGLE_APPLICATION_CREDENTIALS',
|
|
31
|
+
'OPENAI_API_KEY', 'ANTHROPIC_API_KEY'],
|
|
32
|
+
},
|
|
33
|
+
rules: {}, // per-id override, e.g. {"SCAN-02":"warn"}
|
|
34
|
+
trust: {}, // "pkg@range": { scripts:"allow", hosts:[...], spawn:[...] }
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const STRICT_ORDER = { allow: 0, warn: 1, ask: 2, block: 3 };
|
|
38
|
+
|
|
39
|
+
function expandHome(p) {
|
|
40
|
+
if (p.startsWith('~')) return path.join(os.homedir(), p.slice(1));
|
|
41
|
+
return p;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function readJSON(file) {
|
|
45
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); }
|
|
46
|
+
catch { return null; }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function deepMerge(base, over) {
|
|
50
|
+
if (!over) return base;
|
|
51
|
+
const out = Array.isArray(base) ? base.slice() : { ...base };
|
|
52
|
+
for (const k of Object.keys(over)) {
|
|
53
|
+
if (over[k] && typeof over[k] === 'object' && !Array.isArray(over[k])) {
|
|
54
|
+
out[k] = deepMerge(base[k] || {}, over[k]);
|
|
55
|
+
} else if (Array.isArray(over[k]) && Array.isArray(base[k])) {
|
|
56
|
+
out[k] = [...new Set([...base[k], ...over[k]])];
|
|
57
|
+
} else {
|
|
58
|
+
out[k] = over[k];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Built-in floor for a rule: the stricter of its two phase defaults. A project
|
|
65
|
+
// override applies to both phases, so to never loosen it must be at least this
|
|
66
|
+
// strict.
|
|
67
|
+
function builtinFloor(id) {
|
|
68
|
+
const r = RULES[id];
|
|
69
|
+
if (!r) return STRICT_ORDER.ask;
|
|
70
|
+
return Math.max(STRICT_ORDER[r.install] ?? 2, STRICT_ORDER[r.run] ?? 2);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Project overrides may only raise strictness of per-rule actions. The baseline
|
|
74
|
+
// is the current effective action: the user's explicit override if set, else the
|
|
75
|
+
// built-in default floor. This closes the gap where a project could relax a rule
|
|
76
|
+
// the user had not explicitly set (surfaced by adversarial test T7).
|
|
77
|
+
function clampRules(userRules, projectRules) {
|
|
78
|
+
const out = { ...userRules };
|
|
79
|
+
for (const [id, act] of Object.entries(projectRules || {})) {
|
|
80
|
+
const curStrict = (id in out) ? (STRICT_ORDER[out[id]] ?? 2) : builtinFloor(id);
|
|
81
|
+
if ((STRICT_ORDER[act] ?? 2) >= curStrict) out[id] = act;
|
|
82
|
+
}
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function load(opts = {}) {
|
|
87
|
+
const userFile = path.join(os.homedir(), '.sentrion', 'policy.json');
|
|
88
|
+
const projFile = path.join(process.cwd(), '.sentrion.json');
|
|
89
|
+
let p = deepMerge(DEFAULTS, readJSON(userFile) || {});
|
|
90
|
+
const proj = readJSON(projFile);
|
|
91
|
+
if (proj) {
|
|
92
|
+
const projRules = proj.rules; delete proj.rules;
|
|
93
|
+
// project may add allowHosts/secrets but not drop the mode to something looser
|
|
94
|
+
const merged = deepMerge(p, proj);
|
|
95
|
+
merged.rules = clampRules(p.rules, projRules);
|
|
96
|
+
// a project cannot switch enforce/prompt down to audit
|
|
97
|
+
if (STRICT_ORDER[({audit:'allow',learn:'warn',prompt:'ask',enforce:'block'})[proj.mode]] <
|
|
98
|
+
STRICT_ORDER[({audit:'allow',learn:'warn',prompt:'ask',enforce:'block'})[p.mode]]) {
|
|
99
|
+
merged.mode = p.mode;
|
|
100
|
+
}
|
|
101
|
+
p = merged;
|
|
102
|
+
}
|
|
103
|
+
if (opts.mode) p.mode = opts.mode;
|
|
104
|
+
if (opts.ci) { p.mode = 'enforce'; p.nonInteractive = true; }
|
|
105
|
+
p.secrets.paths = p.secrets.paths.map(expandHome);
|
|
106
|
+
return p;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
module.exports = { load, DEFAULTS, expandHome };
|
package/lib/proxy.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// A tiny allowlist egress proxy. Child processes that honour HTTP(S)_PROXY
|
|
3
|
+
// (pip, many fetch libraries, package managers) are routed through it; any host
|
|
4
|
+
// not on the allowlist is refused here as a second line of defence behind the
|
|
5
|
+
// language hooks. Zero dependencies.
|
|
6
|
+
|
|
7
|
+
const http = require('http');
|
|
8
|
+
const net = require('net');
|
|
9
|
+
|
|
10
|
+
function hostOf(s) {
|
|
11
|
+
return String(s || '').split(':')[0].toLowerCase();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function start(allowHosts, onEvent) {
|
|
15
|
+
const allow = new Set((allowHosts || []).map((h) => h.toLowerCase()));
|
|
16
|
+
const ok = (host) => {
|
|
17
|
+
const h = hostOf(host);
|
|
18
|
+
return h === 'localhost' || h === '127.0.0.1' || h === '::1' || allow.has(h);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const server = http.createServer((req, res) => {
|
|
22
|
+
// plain HTTP proxying
|
|
23
|
+
let host;
|
|
24
|
+
try { host = new URL(req.url).hostname; } catch { host = hostOf(req.headers.host); }
|
|
25
|
+
if (!ok(host)) {
|
|
26
|
+
onEvent && onEvent({ rule: 'NET-01', host, via: 'proxy' });
|
|
27
|
+
res.writeHead(403); res.end('Sentrion: egress to ' + host + ' blocked'); return;
|
|
28
|
+
}
|
|
29
|
+
const u = new URL(req.url);
|
|
30
|
+
const p = http.request({ host: u.hostname, port: u.port || 80, path: u.pathname + u.search, method: req.method, headers: req.headers },
|
|
31
|
+
(pr) => { res.writeHead(pr.statusCode, pr.headers); pr.pipe(res); });
|
|
32
|
+
p.on('error', () => { try { res.writeHead(502); res.end(); } catch {} });
|
|
33
|
+
req.pipe(p);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// HTTPS tunnelling via CONNECT
|
|
37
|
+
server.on('connect', (req, clientSocket, head) => {
|
|
38
|
+
const host = hostOf(req.url);
|
|
39
|
+
if (!ok(host)) {
|
|
40
|
+
onEvent && onEvent({ rule: 'NET-01', host, via: 'proxy' });
|
|
41
|
+
clientSocket.write('HTTP/1.1 403 Forbidden\r\n\r\nSentrion: egress blocked\r\n');
|
|
42
|
+
clientSocket.end(); return;
|
|
43
|
+
}
|
|
44
|
+
const [h, port] = req.url.split(':');
|
|
45
|
+
const upstream = net.connect(port || 443, h, () => {
|
|
46
|
+
clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
|
|
47
|
+
upstream.write(head); upstream.pipe(clientSocket); clientSocket.pipe(upstream);
|
|
48
|
+
});
|
|
49
|
+
upstream.on('error', () => clientSocket.end());
|
|
50
|
+
clientSocket.on('error', () => upstream.end());
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
server.listen(0, '127.0.0.1', () => {
|
|
55
|
+
const { port } = server.address();
|
|
56
|
+
resolve({ port, url: `http://127.0.0.1:${port}`, close: () => { try { server.close(); } catch {} } });
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
module.exports = { start };
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SentriX Tier-1 hook for Python (auto-imported via PYTHONPATH).
|
|
3
|
+
|
|
4
|
+
Uses PEP 578 audit hooks (sys.addaudithook) to catch the same dangerous actions
|
|
5
|
+
the Node hook does — secret reads, outbound connections, shell/subprocess, and
|
|
6
|
+
download-then-execute — and decides BEFORE the action happens. On a deny it
|
|
7
|
+
raises, which aborts the call at its source. Pure stdlib, no dependencies.
|
|
8
|
+
"""
|
|
9
|
+
import sys, os, json, time, random, re
|
|
10
|
+
|
|
11
|
+
_SESSION = os.environ.get("SENTRIX_SESSION")
|
|
12
|
+
if _SESSION and os.environ.get("SENTRIX_PYHOOK_ACTIVE") != "1":
|
|
13
|
+
os.environ["SENTRIX_PYHOOK_ACTIVE"] = "1"
|
|
14
|
+
try:
|
|
15
|
+
_CFG = json.loads(os.environ.get("SENTRIX_CONFIG", "{}"))
|
|
16
|
+
except Exception:
|
|
17
|
+
_CFG = {}
|
|
18
|
+
|
|
19
|
+
_PHASE = _CFG.get("phase", "run")
|
|
20
|
+
_MODE = _CFG.get("mode", "prompt")
|
|
21
|
+
_NONINT = bool(_CFG.get("nonInteractive"))
|
|
22
|
+
_ALLOW = set(h.lower() for h in _CFG.get("allowHosts", []))
|
|
23
|
+
_SECRETS = [str(p) for p in _CFG.get("secretPaths", [])]
|
|
24
|
+
_RULES = _CFG.get("rules", {})
|
|
25
|
+
_WATCH = (_PHASE == "run") or bool(os.environ.get("npm_lifecycle_event"))
|
|
26
|
+
_EVENTS = os.path.join(_SESSION, "events.jsonl")
|
|
27
|
+
_DEC = os.path.join(_SESSION, "decisions")
|
|
28
|
+
_PKG = os.environ.get("npm_package_name")
|
|
29
|
+
_seq = [0]
|
|
30
|
+
|
|
31
|
+
# rule -> (title, base action per phase)
|
|
32
|
+
_RULEDEF = {
|
|
33
|
+
"FILE-01": ("reads a secret (ssh/aws/npmrc/keychain/wallet)", "high"),
|
|
34
|
+
"PROC-01": ("install/run script spawned a shell", "high"),
|
|
35
|
+
"PROC-02": ("downloads a file, then executes it", "critical"),
|
|
36
|
+
"PROC-05": ("privilege escalation (sudo/su/pkexec)", "high"),
|
|
37
|
+
"NET-01": ("outbound to a host not in the install allowlist", "high"),
|
|
38
|
+
"NET-04": ("shell wired to a network socket (reverse shell)", "critical"),
|
|
39
|
+
"NET-05": ("upload to paste site / raw IP / chat webhook", "high"),
|
|
40
|
+
"PERS-01": ("writes a startup/persistence location", "high"),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def _emit(obj):
|
|
44
|
+
try:
|
|
45
|
+
with open(_EVENTS, "a") as f:
|
|
46
|
+
f.write(json.dumps(obj) + "\n")
|
|
47
|
+
except Exception:
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
def _base(rule):
|
|
51
|
+
ov = _RULES.get(rule)
|
|
52
|
+
if ov:
|
|
53
|
+
return ov
|
|
54
|
+
if rule in ("PROC-02", "NET-04", "FILE-03"):
|
|
55
|
+
return "block"
|
|
56
|
+
if rule in ("NET-01",):
|
|
57
|
+
return "block" if _PHASE == "install" else "allow"
|
|
58
|
+
if rule in ("NET-05", "PROC-05", "FILE-01", "PERS-01"):
|
|
59
|
+
return "block" if _PHASE == "install" else "ask"
|
|
60
|
+
if rule == "PROC-01":
|
|
61
|
+
return "ask" if _PHASE == "install" else "allow"
|
|
62
|
+
return "ask"
|
|
63
|
+
|
|
64
|
+
def _wait_decision(eid):
|
|
65
|
+
f = os.path.join(_DEC, eid + ".json")
|
|
66
|
+
until = time.time() + _CFG.get("askTimeoutSec", 60)
|
|
67
|
+
while time.time() < until:
|
|
68
|
+
try:
|
|
69
|
+
with open(f) as fh:
|
|
70
|
+
return json.load(fh).get("action")
|
|
71
|
+
except Exception:
|
|
72
|
+
time.sleep(0.08)
|
|
73
|
+
return "K"
|
|
74
|
+
|
|
75
|
+
def _decide(rule, detail):
|
|
76
|
+
eid = "py%d-%d" % (os.getpid(), _seq.__setitem__(0, _seq[0] + 1) or _seq[0])
|
|
77
|
+
base = _base(rule)
|
|
78
|
+
title, sev = _RULEDEF.get(rule, (rule, "medium"))
|
|
79
|
+
_emit({"t": int(time.time() * 1000), "pid": os.getpid(), "pkg": _PKG,
|
|
80
|
+
"kind": "event", "id": eid, "rule": rule, "title": title,
|
|
81
|
+
"sev": sev, "phase": _PHASE, "base": base, "detail": detail})
|
|
82
|
+
if base in ("allow", "warn"):
|
|
83
|
+
return True
|
|
84
|
+
if _MODE in ("audit", "learn"):
|
|
85
|
+
return True
|
|
86
|
+
if _MODE == "enforce" or _NONINT:
|
|
87
|
+
_emit({"kind": "decision", "id": eid, "action": "K", "auto": True})
|
|
88
|
+
return False
|
|
89
|
+
action = _wait_decision(eid)
|
|
90
|
+
_emit({"kind": "resolved", "id": eid, "action": action})
|
|
91
|
+
return action in ("A", "P")
|
|
92
|
+
|
|
93
|
+
def _is_secret(path):
|
|
94
|
+
try:
|
|
95
|
+
ap = os.path.realpath(str(path))
|
|
96
|
+
return any(ap == s or ap.startswith(s + os.sep) for s in _SECRETS)
|
|
97
|
+
except Exception:
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
_STARTUP = ("/autostart", "launchagents", "launchdaemons", "systemd",
|
|
101
|
+
"cron", ".bashrc", ".zshrc", ".profile", "startup")
|
|
102
|
+
|
|
103
|
+
def _host_allowed(h):
|
|
104
|
+
h = (h or "").lower()
|
|
105
|
+
return (not h) or h in _ALLOW or h in ("localhost", "127.0.0.1", "::1")
|
|
106
|
+
|
|
107
|
+
def _net_rule(h):
|
|
108
|
+
h = (h or "").lower()
|
|
109
|
+
if re.search(r"(pastebin|hastebin|transfer\.sh|discord\.com/api/webhooks|api\.telegram\.org)", h):
|
|
110
|
+
return "NET-05"
|
|
111
|
+
if re.match(r"^\d+\.\d+\.\d+\.\d+$", h) and not h.startswith("127."):
|
|
112
|
+
return "NET-05"
|
|
113
|
+
if _host_allowed(h):
|
|
114
|
+
return None
|
|
115
|
+
return "NET-01" if _PHASE == "install" else "NET-01"
|
|
116
|
+
|
|
117
|
+
def _classify_cmd(s):
|
|
118
|
+
s = str(s)
|
|
119
|
+
if re.search(r"(curl|wget|fetch)[^\n|]*\|\s*(sh|bash|python|node|perl)", s, re.I):
|
|
120
|
+
return "PROC-02"
|
|
121
|
+
if re.search(r"/dev/(tcp|udp)/", s, re.I):
|
|
122
|
+
return "NET-04"
|
|
123
|
+
if not _WATCH:
|
|
124
|
+
return None
|
|
125
|
+
if re.match(r"^\s*(sudo|su|pkexec|doas)\b", s):
|
|
126
|
+
return "PROC-05"
|
|
127
|
+
if re.search(r"\b(sh|bash|zsh|dash|cmd|powershell|pwsh)\b", s, re.I):
|
|
128
|
+
return "PROC-01"
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
def _hook(event, args):
|
|
132
|
+
try:
|
|
133
|
+
if event == "open":
|
|
134
|
+
path, mode = args[0], (args[1] or "")
|
|
135
|
+
if _WATCH and _is_secret(path) and (not mode or "r" in str(mode)):
|
|
136
|
+
if not _decide("FILE-01", {"path": str(path)}):
|
|
137
|
+
raise PermissionError("SentriX blocked FILE-01: read of secret %s" % path)
|
|
138
|
+
if _WATCH and mode and ("w" in str(mode) or "a" in str(mode)):
|
|
139
|
+
low = str(path).lower()
|
|
140
|
+
if any(h in low for h in _STARTUP):
|
|
141
|
+
if not _decide("PERS-01", {"path": str(path)}):
|
|
142
|
+
raise PermissionError("SentriX blocked PERS-01: write to %s" % path)
|
|
143
|
+
elif event == "socket.connect":
|
|
144
|
+
addr = args[1] if len(args) > 1 else None
|
|
145
|
+
host = addr[0] if isinstance(addr, (tuple, list)) and addr else None
|
|
146
|
+
if host:
|
|
147
|
+
rule = _net_rule(str(host))
|
|
148
|
+
if rule and not _decide(rule, {"host": str(host)}):
|
|
149
|
+
raise PermissionError("SentriX blocked %s: connect to %s" % (rule, host))
|
|
150
|
+
elif event in ("subprocess.Popen", "os.exec"):
|
|
151
|
+
cmd = args[1] if event == "subprocess.Popen" and len(args) > 1 else (args[0] if args else "")
|
|
152
|
+
if isinstance(cmd, (list, tuple)):
|
|
153
|
+
cmd = " ".join(str(c) for c in cmd)
|
|
154
|
+
rule = _classify_cmd(cmd)
|
|
155
|
+
if rule and not _decide(rule, {"cmd": str(cmd)[:200]}):
|
|
156
|
+
raise PermissionError("SentriX blocked %s: %s" % (rule, str(cmd)[:80]))
|
|
157
|
+
elif event == "os.system":
|
|
158
|
+
rule = _classify_cmd(args[0] if args else "")
|
|
159
|
+
if rule and not _decide(rule, {"cmd": str(args[0])[:200]}):
|
|
160
|
+
raise PermissionError("SentriX blocked %s" % rule)
|
|
161
|
+
except PermissionError:
|
|
162
|
+
raise
|
|
163
|
+
except Exception:
|
|
164
|
+
pass
|
|
165
|
+
|
|
166
|
+
sys.addaudithook(_hook)
|
|
167
|
+
_emit({"kind": "hook-ready", "lang": "python", "phase": _PHASE, "mode": _MODE})
|
package/lib/report.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Incident store and `sentrion report`. One incident per guarded command that
|
|
3
|
+
// produced at least one ask/block event — the whole attack chain in one file,
|
|
4
|
+
// not a pile of alerts.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { c, tag, sev } = require('./ui.js');
|
|
10
|
+
|
|
11
|
+
const DIR = path.join(os.homedir(), '.sentrion', 'incidents');
|
|
12
|
+
|
|
13
|
+
function ensureDir() { fs.mkdirSync(DIR, { recursive: true }); }
|
|
14
|
+
|
|
15
|
+
function save(incident) {
|
|
16
|
+
ensureDir();
|
|
17
|
+
const file = path.join(DIR, `${incident.id}.json`);
|
|
18
|
+
fs.writeFileSync(file, JSON.stringify(incident, null, 2));
|
|
19
|
+
return file;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function list() {
|
|
23
|
+
try {
|
|
24
|
+
return fs.readdirSync(DIR).filter((f) => f.endsWith('.json'))
|
|
25
|
+
.map((f) => JSON.parse(fs.readFileSync(path.join(DIR, f), 'utf8')))
|
|
26
|
+
.sort((a, b) => b.startedAt - a.startedAt);
|
|
27
|
+
} catch { return []; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function fmtTime(ms) { return new Date(ms).toISOString().replace('T', ' ').slice(0, 19); }
|
|
31
|
+
|
|
32
|
+
// human-readable incident, matching the terminal mock
|
|
33
|
+
function render(inc) {
|
|
34
|
+
const L = [];
|
|
35
|
+
const verdict = inc.outcome === 'blocked'
|
|
36
|
+
? c.redBg(' BLOCKED ') : inc.outcome === 'allowed'
|
|
37
|
+
? c.green(' ALLOWED ') : c.yellow(' ' + inc.outcome.toUpperCase() + ' ');
|
|
38
|
+
L.push('');
|
|
39
|
+
L.push(` ${tag()} ${verdict} ${c.bold('incident ' + inc.id)} ${c.dim(fmtTime(inc.startedAt))}`);
|
|
40
|
+
L.push('');
|
|
41
|
+
L.push(` command ${inc.command}`);
|
|
42
|
+
L.push(` phase ${inc.phase} os ${inc.os} mode ${inc.mode}`);
|
|
43
|
+
if (inc.package) L.push(` package ${c.white(inc.package)}`);
|
|
44
|
+
L.push('');
|
|
45
|
+
if (inc.events && inc.events.length) {
|
|
46
|
+
L.push(c.bold(' Timeline'));
|
|
47
|
+
const t0 = inc.events[0].t;
|
|
48
|
+
for (const e of inc.events) {
|
|
49
|
+
if (e.kind !== 'event') continue;
|
|
50
|
+
const dt = ((e.t - t0) / 1000).toFixed(2).padStart(5);
|
|
51
|
+
const col = sev[e.sev] || c.yellow;
|
|
52
|
+
const d = e.detail ? JSON.stringify(e.detail).slice(0, 60) : '';
|
|
53
|
+
L.push(` ${c.dim('+' + dt + 's')} ${col(e.rule.padEnd(8))} ${e.title}`);
|
|
54
|
+
if (d) L.push(` ${c.dim(d)}`);
|
|
55
|
+
}
|
|
56
|
+
L.push('');
|
|
57
|
+
}
|
|
58
|
+
if (inc.reason) { L.push(c.bold(' Why')); L.push(' ' + inc.reason); L.push(''); }
|
|
59
|
+
const prevented = inc.prevented || [];
|
|
60
|
+
if (prevented.length) {
|
|
61
|
+
L.push(c.bold(' Prevented ') + prevented.map((p) => c.green('✓ ') + p).join(' '));
|
|
62
|
+
L.push('');
|
|
63
|
+
}
|
|
64
|
+
if (inc.next && inc.next.length) {
|
|
65
|
+
L.push(c.bold(' Next'));
|
|
66
|
+
inc.next.forEach((n, i) => L.push(` ${i + 1} ${n}`));
|
|
67
|
+
}
|
|
68
|
+
L.push(c.dim(` evidence ${path.join(DIR, inc.id + '.json')}`));
|
|
69
|
+
L.push('');
|
|
70
|
+
return L.join('\n');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// SARIF 2.1.0 export for CI code-scanning dashboards.
|
|
74
|
+
function toSarif(inc) {
|
|
75
|
+
const { RULES } = require('./rules.js');
|
|
76
|
+
const fired = (inc.events || []).filter((e) => e.kind === 'event');
|
|
77
|
+
const ruleIds = [...new Set(fired.map((e) => e.rule))];
|
|
78
|
+
return {
|
|
79
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
80
|
+
version: '2.1.0',
|
|
81
|
+
runs: [{
|
|
82
|
+
tool: { driver: {
|
|
83
|
+
name: 'Sentrion', informationUri: 'https://github.com/imeerai/sentrion',
|
|
84
|
+
version: require('../package.json').version,
|
|
85
|
+
rules: ruleIds.map((id) => ({
|
|
86
|
+
id, name: (RULES[id] && RULES[id].title) || id,
|
|
87
|
+
shortDescription: { text: (RULES[id] && RULES[id].title) || id },
|
|
88
|
+
defaultConfiguration: { level: 'error' },
|
|
89
|
+
})),
|
|
90
|
+
} },
|
|
91
|
+
results: fired.map((e) => ({
|
|
92
|
+
ruleId: e.rule,
|
|
93
|
+
level: e.base === 'block' ? 'error' : e.base === 'ask' ? 'warning' : 'note',
|
|
94
|
+
message: { text: `${e.title}${e.detail ? ' — ' + JSON.stringify(e.detail) : ''}` },
|
|
95
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: inc.package || inc.command } } }],
|
|
96
|
+
properties: { phase: e.phase, severity: e.sev, incident: inc.id },
|
|
97
|
+
})),
|
|
98
|
+
}],
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function pick(which, items) {
|
|
103
|
+
const w = (which || '').replace(/^--/, '');
|
|
104
|
+
if (w === 'list' || w === 'all') return { listing: items };
|
|
105
|
+
const inc = (w && w !== 'last') ? items.find((i) => i.id === w) : items[0];
|
|
106
|
+
return { inc };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function show(which, opts = {}) {
|
|
110
|
+
const items = list();
|
|
111
|
+
if (!items.length) {
|
|
112
|
+
if (opts.json) console.log(JSON.stringify(which && /^(--)?(list|all)$/.test(which) ? [] : null));
|
|
113
|
+
else console.log('No incidents recorded yet.');
|
|
114
|
+
return 0;
|
|
115
|
+
}
|
|
116
|
+
const { listing, inc } = pick(which, items);
|
|
117
|
+
|
|
118
|
+
if (listing) {
|
|
119
|
+
if (opts.json) { console.log(JSON.stringify(listing, null, 2)); return 0; }
|
|
120
|
+
for (const i of listing) console.log(` ${i.id} ${fmtTime(i.startedAt)} ${i.outcome.padEnd(8)} ${i.command}`);
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
if (!inc) { if (opts.json) console.log('null'); else console.log('Incident not found.'); return 1; }
|
|
124
|
+
|
|
125
|
+
if (opts.format === 'sarif') { console.log(JSON.stringify(toSarif(inc), null, 2)); return 0; }
|
|
126
|
+
if (opts.json) { console.log(JSON.stringify(inc, null, 2)); return 0; }
|
|
127
|
+
console.log(render(inc));
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = { save, list, show, render, toSarif, DIR };
|
package/lib/rules.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Sentrion rule set. Each rule: id, title, severity, and the default action
|
|
3
|
+
// per phase ("install" vs "run"). Actions: "block" | "ask" | "warn" | "allow".
|
|
4
|
+
// The decision engine turns these into an allow/deny, honouring the mode
|
|
5
|
+
// (prompt / enforce / audit / learn) and the trust store.
|
|
6
|
+
|
|
7
|
+
const RULES = {
|
|
8
|
+
// --- pre-flight (static, before any code runs) ---
|
|
9
|
+
'SCAN-01': { title: 'package is on a known-malicious list', sev: 'critical', install: 'block', run: 'block' },
|
|
10
|
+
'SCAN-02': { title: 'version published less than 48h ago', sev: 'medium', install: 'ask', run: 'allow' },
|
|
11
|
+
'SCAN-03': { title: 'patch release adds a new install script', sev: 'high', install: 'block', run: 'allow' },
|
|
12
|
+
'SCAN-04': { title: 'name is a typosquat of a popular package', sev: 'high', install: 'ask', run: 'allow' },
|
|
13
|
+
'SCAN-05': { title: 'obfuscated / high-entropy code', sev: 'medium', install: 'ask', run: 'warn' },
|
|
14
|
+
'SCAN-06': { title: 'dependency from git, url or tarball', sev: 'low', install: 'ask', run: 'allow' },
|
|
15
|
+
'REPO-01': { title: '.vscode/tasks.json runs on folder open', sev: 'high', install: 'warn', run: 'warn' },
|
|
16
|
+
'REPO-02': { title: 'repo script pipes a download into a shell', sev: 'high', install: 'ask', run: 'ask' },
|
|
17
|
+
|
|
18
|
+
// --- runtime behaviour ---
|
|
19
|
+
'PROC-01': { title: 'install/run script spawned a shell', sev: 'high', install: 'ask', run: 'allow' },
|
|
20
|
+
'PROC-02': { title: 'downloads a file, then executes it', sev: 'critical', install: 'block', run: 'block' },
|
|
21
|
+
'PROC-03': { title: 'starts a runtime the project does not use (bun/deno/new binary)', sev: 'high', install: 'block', run: 'ask' },
|
|
22
|
+
'PROC-04': { title: 'child outlives the command (detached/backgrounded)', sev: 'high', install: 'block', run: 'ask' },
|
|
23
|
+
'PROC-05': { title: 'privilege escalation (sudo/su/pkexec/runas)', sev: 'high', install: 'block', run: 'ask' },
|
|
24
|
+
'PERS-01': { title: 'writes a startup/persistence location', sev: 'high', install: 'block', run: 'ask' },
|
|
25
|
+
'FILE-01': { title: 'reads a secret (ssh/aws/npmrc/keychain/wallet)', sev: 'high', install: 'block', run: 'ask' },
|
|
26
|
+
'FILE-02': { title: 'writes into another package / .git hooks / CI workflow', sev: 'high', install: 'block', run: 'ask' },
|
|
27
|
+
'FILE-03': { title: 'mass delete or overwrite under $HOME', sev: 'critical', install: 'block', run: 'block' },
|
|
28
|
+
'NET-01': { title: 'outbound to a host not in the install allowlist', sev: 'high', install: 'block', run: 'allow' },
|
|
29
|
+
'NET-02': { title: 'first connection to a new host during a run', sev: 'medium', install: 'allow', run: 'ask' },
|
|
30
|
+
'NET-03': { title: 'opens a listening socket on all interfaces', sev: 'medium', install: 'ask', run: 'ask' },
|
|
31
|
+
'NET-04': { title: 'shell wired to a network socket (reverse shell)', sev: 'critical', install: 'block', run: 'block' },
|
|
32
|
+
'NET-05': { title: 'upload to paste site / raw IP / chat webhook / new repo', sev: 'high', install: 'block', run: 'ask' },
|
|
33
|
+
'TOK-01': { title: 'runs npm publish / token / gh repo create from a dependency', sev: 'high', install: 'block', run: 'ask' },
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
// Base action for a rule in a given phase, before mode/trust is applied.
|
|
37
|
+
function baseAction(ruleId, phase) {
|
|
38
|
+
const r = RULES[ruleId];
|
|
39
|
+
if (!r) return 'ask';
|
|
40
|
+
return (phase === 'install' ? r.install : r.run) || 'ask';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
module.exports = { RULES, baseAction };
|
package/lib/scan.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Static pre-flight scan — runs no code. Two entry points:
|
|
3
|
+
// scanRepo(dir) : inspect a project/clone for the fake-interview patterns
|
|
4
|
+
// scanName(spec) : best-effort lookup of a package by name (uses `npm view`
|
|
5
|
+
// if the registry is reachable; degrades gracefully offline)
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const cp = require('child_process');
|
|
11
|
+
const { RULES } = require('./rules.js');
|
|
12
|
+
|
|
13
|
+
// Threat lists: prefer the user's refreshed copy (~/.sentrion/lists, written by
|
|
14
|
+
// `sentrion update`), fall back to the bundled seed. Loaded once per process.
|
|
15
|
+
function readList(name) {
|
|
16
|
+
const user = path.join(os.homedir(), '.sentrion', 'lists', name);
|
|
17
|
+
const bundled = path.join(__dirname, 'data', name);
|
|
18
|
+
for (const f of [user, bundled]) {
|
|
19
|
+
try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch {}
|
|
20
|
+
}
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
const KNOWN_MALICIOUS = new Set((readList('malware.json').packages) || [
|
|
24
|
+
'event-stream@3.3.6', 'flatmap-stream', 'ua-parser-js@0.7.29',
|
|
25
|
+
]);
|
|
26
|
+
const POPULAR = (readList('typosquats.json').popular) || ['express', 'react', 'lodash',
|
|
27
|
+
'axios', 'chalk', 'debug', 'commander', 'next', 'vue', 'webpack'];
|
|
28
|
+
|
|
29
|
+
function levenshtein(a, b) {
|
|
30
|
+
const m = a.length, n = b.length;
|
|
31
|
+
const d = Array.from({ length: m + 1 }, (_, i) => [i, ...Array(n).fill(0)]);
|
|
32
|
+
for (let j = 0; j <= n; j++) d[0][j] = j;
|
|
33
|
+
for (let i = 1; i <= m; i++)
|
|
34
|
+
for (let j = 1; j <= n; j++)
|
|
35
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1,
|
|
36
|
+
d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
37
|
+
return d[m][n];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function looksObfuscated(src) {
|
|
41
|
+
if (/eval\s*\(\s*(atob|Buffer\.from|unescape)/.test(src)) return true;
|
|
42
|
+
if (/\\x[0-9a-f]{2}(\\x[0-9a-f]{2}){20,}/i.test(src)) return true;
|
|
43
|
+
// very long single token (packed payload)
|
|
44
|
+
if (/[A-Za-z0-9+/=]{300,}/.test(src)) return true;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function finding(rule, detail) {
|
|
49
|
+
return { rule, title: RULES[rule] ? RULES[rule].title : rule, sev: RULES[rule] ? RULES[rule].sev : 'medium', detail };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function scanRepo(dir) {
|
|
53
|
+
const findings = [];
|
|
54
|
+
const root = path.resolve(dir);
|
|
55
|
+
|
|
56
|
+
// package.json lifecycle scripts
|
|
57
|
+
try {
|
|
58
|
+
const pj = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
|
59
|
+
for (const [name, body] of Object.entries(pj.scripts || {})) {
|
|
60
|
+
if (/(curl|wget)[^\n|]*\|\s*(sh|bash|node|python)/i.test(body))
|
|
61
|
+
findings.push(finding('REPO-02', { script: name, body: body.slice(0, 120) }));
|
|
62
|
+
if (/^(pre|post)?install$/.test(name) || name === 'prepare')
|
|
63
|
+
findings.push(finding('SCAN-03', { script: name, body: body.slice(0, 120) }));
|
|
64
|
+
}
|
|
65
|
+
for (const dep of Object.keys({ ...pj.dependencies, ...pj.devDependencies })) {
|
|
66
|
+
const v = (pj.dependencies || {})[dep] || (pj.devDependencies || {})[dep] || '';
|
|
67
|
+
if (/^(git|github:|https?:|file:)/.test(v)) findings.push(finding('SCAN-06', { dep, v }));
|
|
68
|
+
for (const pop of POPULAR) {
|
|
69
|
+
if (dep !== pop && levenshtein(dep, pop) === 1) findings.push(finding('SCAN-04', { dep, like: pop }));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
} catch {}
|
|
73
|
+
|
|
74
|
+
// VS Code auto-run task
|
|
75
|
+
try {
|
|
76
|
+
const t = fs.readFileSync(path.join(root, '.vscode', 'tasks.json'), 'utf8');
|
|
77
|
+
if (/"runOn"\s*:\s*"folderOpen"/.test(t) || /"folderOpen"/.test(t))
|
|
78
|
+
findings.push(finding('REPO-01', { file: '.vscode/tasks.json' }));
|
|
79
|
+
} catch {}
|
|
80
|
+
|
|
81
|
+
// obfuscation / disguised code across small source files
|
|
82
|
+
walk(root, (file) => {
|
|
83
|
+
if (!/\.(js|cjs|mjs|ts|py|woff2?|ttf|json)$/i.test(file)) return;
|
|
84
|
+
let src;
|
|
85
|
+
try { src = fs.readFileSync(file, 'utf8'); } catch { return; }
|
|
86
|
+
if (/\.(woff2?|ttf)$/i.test(file) && /function|=>|require\(|import /.test(src))
|
|
87
|
+
findings.push(finding('SCAN-05', { file: path.relative(root, file), note: 'font file contains JavaScript' }));
|
|
88
|
+
else if (/\.(js|cjs|mjs|ts|py)$/i.test(file) && looksObfuscated(src))
|
|
89
|
+
findings.push(finding('SCAN-05', { file: path.relative(root, file) }));
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return findings;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function walk(dir, fn, depth = 0) {
|
|
96
|
+
if (depth > 6) return;
|
|
97
|
+
let entries = [];
|
|
98
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
99
|
+
for (const e of entries) {
|
|
100
|
+
if (e.name === 'node_modules' || e.name === '.git') continue;
|
|
101
|
+
const p = path.join(dir, e.name);
|
|
102
|
+
if (e.isDirectory()) walk(p, fn, depth + 1);
|
|
103
|
+
else fn(p);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function scanName(spec, policy) {
|
|
108
|
+
const findings = [];
|
|
109
|
+
if (KNOWN_MALICIOUS.has(spec) || KNOWN_MALICIOUS.has(spec.split('@')[0]))
|
|
110
|
+
findings.push(finding('SCAN-01', { spec }));
|
|
111
|
+
const name = spec.replace(/@[^/]*$/, '');
|
|
112
|
+
for (const pop of POPULAR)
|
|
113
|
+
if (name !== pop && levenshtein(name, pop) === 1) findings.push(finding('SCAN-04', { name, like: pop }));
|
|
114
|
+
|
|
115
|
+
// best-effort registry metadata (age + has-script); skipped silently offline
|
|
116
|
+
try {
|
|
117
|
+
const out = cp.execFileSync('npm', ['view', spec, 'time.modified', 'scripts', '--json'],
|
|
118
|
+
{ encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
119
|
+
const meta = JSON.parse(out);
|
|
120
|
+
const modified = meta['time.modified'] || meta.time?.modified;
|
|
121
|
+
if (modified) {
|
|
122
|
+
const ageH = (Date.now() - Date.parse(modified)) / 3.6e6;
|
|
123
|
+
const min = (policy?.install?.minPackageAgeHours) || 48;
|
|
124
|
+
if (ageH < min) findings.push(finding('SCAN-02', { ageHours: Math.round(ageH) }));
|
|
125
|
+
}
|
|
126
|
+
} catch { findings.push({ rule: 'INFO', title: 'registry not reachable — age check skipped', sev: 'low' }); }
|
|
127
|
+
|
|
128
|
+
return findings;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = { scanRepo, scanName, finding };
|