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
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// `sentrion update` — refresh the malware + typosquat lists that `scan` relies on.
|
|
3
|
+
// Copies the bundled seed into ~/.sentrion/lists/ and, if a feed is reachable
|
|
4
|
+
// (env SENTRION_FEED, a JSON url), merges extra entries. Offline it still works:
|
|
5
|
+
// it refreshes from the bundled set and says so. Zero dependencies.
|
|
6
|
+
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const https = require('https');
|
|
10
|
+
const store = require('./store.js');
|
|
11
|
+
const { c, tag } = require('./ui.js');
|
|
12
|
+
|
|
13
|
+
const BUNDLED = path.join(__dirname, 'data');
|
|
14
|
+
|
|
15
|
+
function fetchJSON(url) {
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
try {
|
|
18
|
+
const req = https.get(url, { timeout: 8000 }, (res) => {
|
|
19
|
+
if (res.statusCode !== 200) { res.resume(); return resolve(null); }
|
|
20
|
+
let body = '';
|
|
21
|
+
res.on('data', (d) => { body += d; });
|
|
22
|
+
res.on('end', () => { try { resolve(JSON.parse(body)); } catch { resolve(null); } });
|
|
23
|
+
});
|
|
24
|
+
req.on('error', () => resolve(null));
|
|
25
|
+
req.on('timeout', () => { req.destroy(); resolve(null); });
|
|
26
|
+
} catch { resolve(null); }
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = async function update() {
|
|
31
|
+
const dir = store.listsDir();
|
|
32
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
33
|
+
|
|
34
|
+
const malware = JSON.parse(fs.readFileSync(path.join(BUNDLED, 'malware.json'), 'utf8'));
|
|
35
|
+
const typos = JSON.parse(fs.readFileSync(path.join(BUNDLED, 'typosquats.json'), 'utf8'));
|
|
36
|
+
|
|
37
|
+
let online = false;
|
|
38
|
+
const feed = process.env.SENTRION_FEED;
|
|
39
|
+
if (feed) {
|
|
40
|
+
const extra = await fetchJSON(feed);
|
|
41
|
+
if (extra) {
|
|
42
|
+
online = true;
|
|
43
|
+
if (Array.isArray(extra.packages)) malware.packages = [...new Set([...malware.packages, ...extra.packages])];
|
|
44
|
+
if (Array.isArray(extra.popular)) typos.popular = [...new Set([...typos.popular, ...extra.popular])];
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const stamp = new Date().toISOString();
|
|
49
|
+
malware.refreshedAt = stamp; typos.refreshedAt = stamp;
|
|
50
|
+
fs.writeFileSync(path.join(dir, 'malware.json'), JSON.stringify(malware, null, 2) + '\n');
|
|
51
|
+
fs.writeFileSync(path.join(dir, 'typosquats.json'), JSON.stringify(typos, null, 2) + '\n');
|
|
52
|
+
|
|
53
|
+
process.stdout.write(`\n ${tag()} ${c.green('lists refreshed')}`);
|
|
54
|
+
process.stdout.write(`\n malware ${c.white(String(malware.packages.length))} entries`);
|
|
55
|
+
process.stdout.write(`\n typosquats ${c.white(String(typos.popular.length))} protected names`);
|
|
56
|
+
process.stdout.write(`\n source ${online ? c.green('feed + bundled') : c.yellow('bundled seed (offline or no SENTRION_FEED)')}`);
|
|
57
|
+
process.stdout.write(`\n ${c.dim(dir)}\n\n`);
|
|
58
|
+
return 0;
|
|
59
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"updatedAt": "2026-11-16",
|
|
3
|
+
"source": "bundled seed (historical npm/pypi supply-chain incidents)",
|
|
4
|
+
"packages": [
|
|
5
|
+
"event-stream@3.3.6",
|
|
6
|
+
"flatmap-stream",
|
|
7
|
+
"ua-parser-js@0.7.29",
|
|
8
|
+
"ua-parser-js@0.8.0",
|
|
9
|
+
"ua-parser-js@1.0.0",
|
|
10
|
+
"coa@2.0.3",
|
|
11
|
+
"coa@2.0.4",
|
|
12
|
+
"rc@1.2.9",
|
|
13
|
+
"rc@1.3.9",
|
|
14
|
+
"rc@2.3.9",
|
|
15
|
+
"node-ipc@10.1.1",
|
|
16
|
+
"node-ipc@10.1.2",
|
|
17
|
+
"colors@1.4.44-liberty-2",
|
|
18
|
+
"faker@6.6.6",
|
|
19
|
+
"@solana/web3.js@1.95.6",
|
|
20
|
+
"@solana/web3.js@1.95.7",
|
|
21
|
+
"@ctrl/tinycolor@4.1.1",
|
|
22
|
+
"@ctrl/tinycolor@4.1.2",
|
|
23
|
+
"eslint-scope@3.7.2",
|
|
24
|
+
"electron-native-notify",
|
|
25
|
+
"getcookies",
|
|
26
|
+
"http-proxy-middlewares",
|
|
27
|
+
"node-fabric",
|
|
28
|
+
"noblox.js-proxy",
|
|
29
|
+
"rate-map",
|
|
30
|
+
"bb-builder",
|
|
31
|
+
"crossenv",
|
|
32
|
+
"cross-env.js",
|
|
33
|
+
"mongose",
|
|
34
|
+
"discord.dll",
|
|
35
|
+
"twilio-npm",
|
|
36
|
+
"loadyaml",
|
|
37
|
+
"fix-error",
|
|
38
|
+
"angluar",
|
|
39
|
+
"babelcli",
|
|
40
|
+
"d3.js",
|
|
41
|
+
"ffmepg",
|
|
42
|
+
"gruntcli",
|
|
43
|
+
"jquery.js",
|
|
44
|
+
"mariadb.js",
|
|
45
|
+
"mssql-node",
|
|
46
|
+
"mysqljs",
|
|
47
|
+
"nodesqlite",
|
|
48
|
+
"sqlite.js",
|
|
49
|
+
"sqliter",
|
|
50
|
+
"sqlserver",
|
|
51
|
+
"python-dateutil2",
|
|
52
|
+
"jeIlyfish",
|
|
53
|
+
"colourama",
|
|
54
|
+
"requests3"
|
|
55
|
+
]
|
|
56
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"updatedAt": "2026-11-16",
|
|
3
|
+
"source": "bundled seed (popular names to protect from 1-edit typosquats)",
|
|
4
|
+
"popular": [
|
|
5
|
+
"express", "react", "react-dom", "lodash", "axios", "chalk", "debug",
|
|
6
|
+
"commander", "next", "vue", "webpack", "crypto-js", "dotenv", "moment",
|
|
7
|
+
"uuid", "typescript", "eslint", "prettier", "jest", "mocha", "socket.io",
|
|
8
|
+
"mongoose", "pg", "mysql", "redis", "bcrypt", "jsonwebtoken", "passport",
|
|
9
|
+
"cors", "body-parser", "node-fetch", "yargs", "rxjs", "three",
|
|
10
|
+
"tailwindcss", "requests", "numpy", "pandas", "flask", "django",
|
|
11
|
+
"pillow", "scipy", "pytest", "colorama"
|
|
12
|
+
]
|
|
13
|
+
}
|
package/lib/guard.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The guard: prepare a session, launch the command under the Tier-1 hook and
|
|
3
|
+
// Tier-2 sensors, stream events, surface K/A/P prompts, kill the tree on a
|
|
4
|
+
// block, and write one incident per run.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const crypto = require('crypto');
|
|
10
|
+
const cp = require('child_process');
|
|
11
|
+
|
|
12
|
+
const policyLib = require('./policy.js');
|
|
13
|
+
const sensors = require('./sensors.js');
|
|
14
|
+
const report = require('./report.js');
|
|
15
|
+
const { c, tag, sev, promptKAP } = require('./ui.js');
|
|
16
|
+
|
|
17
|
+
const HOOK = path.join(__dirname, 'hook.js');
|
|
18
|
+
|
|
19
|
+
// classify what the user is running → phase + a short label
|
|
20
|
+
function classify(argv) {
|
|
21
|
+
const first = (argv[0] || '').toLowerCase();
|
|
22
|
+
const installers = ['npm', 'pnpm', 'yarn', 'bun', 'pip', 'pip3', 'uv', 'poetry', 'npx'];
|
|
23
|
+
const isInstall = installers.includes(first) &&
|
|
24
|
+
/^(install|i|add|ci|update|upgrade|rebuild)$/.test((argv[1] || '').toLowerCase());
|
|
25
|
+
const runtime = ['node', 'python', 'python3', 'ruby', 'bun', 'deno', 'php'].includes(first) ? first : null;
|
|
26
|
+
return { phase: isInstall ? 'install' : 'run', projectRuntime: runtime === 'python3' ? 'python' : runtime };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function newSession() {
|
|
30
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sentrion-'));
|
|
31
|
+
fs.mkdirSync(path.join(dir, 'decisions'), { recursive: true });
|
|
32
|
+
fs.writeFileSync(path.join(dir, 'events.jsonl'), '');
|
|
33
|
+
return dir;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// env for the child: scrub secrets, route egress via the proxy, load both hooks
|
|
37
|
+
function childEnv(policy, phase, projectRuntime, session, proxyUrl) {
|
|
38
|
+
const env = { ...process.env };
|
|
39
|
+
for (const k of policy.secrets.stripEnv) {
|
|
40
|
+
if (env[k]) env[k] = 'sentrion-canary-' + crypto.randomBytes(6).toString('hex');
|
|
41
|
+
}
|
|
42
|
+
const allowHosts = phase === 'install'
|
|
43
|
+
? policy.install.allowHosts
|
|
44
|
+
: [...policy.install.allowHosts, ...policy.run.allowHosts];
|
|
45
|
+
const cfg = {
|
|
46
|
+
phase, mode: policy.mode, nonInteractive: !!policy.nonInteractive,
|
|
47
|
+
askTimeoutSec: policy.askTimeoutSec, allowHosts,
|
|
48
|
+
secretPaths: policy.secrets.paths, rules: policy.rules, projectRuntime,
|
|
49
|
+
};
|
|
50
|
+
env.SENTRION_SESSION = session;
|
|
51
|
+
env.SENTRION_CONFIG = JSON.stringify(cfg);
|
|
52
|
+
// Tier-1 Node hook
|
|
53
|
+
const pre = `--require ${JSON.stringify(HOOK)}`;
|
|
54
|
+
env.NODE_OPTIONS = env.NODE_OPTIONS ? env.NODE_OPTIONS + ' ' + pre : pre;
|
|
55
|
+
// Tier-1 Python hook (sitecustomize on PYTHONPATH)
|
|
56
|
+
const pydir = path.join(__dirname, 'py');
|
|
57
|
+
env.PYTHONPATH = env.PYTHONPATH ? pydir + path.delimiter + env.PYTHONPATH : pydir;
|
|
58
|
+
// egress proxy for children that honour it (pip, fetch libs, package managers)
|
|
59
|
+
if (proxyUrl) {
|
|
60
|
+
env.HTTP_PROXY = proxyUrl; env.HTTPS_PROXY = proxyUrl;
|
|
61
|
+
env.http_proxy = proxyUrl; env.https_proxy = proxyUrl;
|
|
62
|
+
env.NO_PROXY = 'localhost,127.0.0.1,::1';
|
|
63
|
+
}
|
|
64
|
+
return env;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function run(argv, opts = {}) {
|
|
68
|
+
const policy = policyLib.load(opts);
|
|
69
|
+
const { phase, projectRuntime } = classify(argv);
|
|
70
|
+
const session = newSession();
|
|
71
|
+
|
|
72
|
+
// start the allowlist egress proxy
|
|
73
|
+
const allowHosts = phase === 'install'
|
|
74
|
+
? policy.install.allowHosts
|
|
75
|
+
: [...policy.install.allowHosts, ...policy.run.allowHosts];
|
|
76
|
+
let proxy = null;
|
|
77
|
+
const proxyEvents = [];
|
|
78
|
+
try { proxy = await require('./proxy.js').start(allowHosts, (e) => proxyEvents.push(e)); } catch {}
|
|
79
|
+
|
|
80
|
+
const quiet = !!opts.quiet;
|
|
81
|
+
const env = childEnv(policy, phase, projectRuntime, session, proxy && proxy.url);
|
|
82
|
+
if (opts.sandbox) { env.HOME = opts.sandbox; env.USERPROFILE = opts.sandbox; }
|
|
83
|
+
|
|
84
|
+
const id = crypto.randomBytes(3).toString('hex') + '-' + String(Date.now()).slice(-2);
|
|
85
|
+
const incident = {
|
|
86
|
+
id, command: argv.join(' '), phase, mode: policy.mode,
|
|
87
|
+
os: process.platform, startedAt: Date.now(),
|
|
88
|
+
package: null, events: [], outcome: 'allowed', prevented: [], next: [],
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
if (!quiet) {
|
|
92
|
+
process.stdout.write(`\n ${tag()} ${c.dim(`${require('../package.json').version} guard ${policy.mode} ${process.platform}`)}\n`);
|
|
93
|
+
process.stdout.write(` ${c.cyan('▸')} launch ${c.white(argv.join(' '))}\n`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const child = cp.spawn(argv[0], argv.slice(1), {
|
|
97
|
+
env, stdio: 'inherit', detached: process.platform !== 'win32', shell: false,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// fail-closed: if the guard itself is killed, take the whole group with it
|
|
101
|
+
const onExit = () => { try { sensors.killTree(child.pid); } catch {} };
|
|
102
|
+
process.on('SIGINT', () => { onExit(); process.exit(130); });
|
|
103
|
+
process.on('SIGTERM', () => { onExit(); process.exit(143); });
|
|
104
|
+
process.on('exit', onExit);
|
|
105
|
+
|
|
106
|
+
let blocked = false;
|
|
107
|
+
|
|
108
|
+
// stream events from the hook
|
|
109
|
+
const eventsFile = path.join(session, 'events.jsonl');
|
|
110
|
+
let offset = 0;
|
|
111
|
+
let carry = '';
|
|
112
|
+
const pump = async (final = false) => {
|
|
113
|
+
let txt;
|
|
114
|
+
try { txt = fs.readFileSync(eventsFile, 'utf8'); } catch { return; }
|
|
115
|
+
carry += txt.slice(offset); offset = txt.length;
|
|
116
|
+
// only process complete (newline-terminated) lines; keep any remainder
|
|
117
|
+
const nl = carry.lastIndexOf('\n');
|
|
118
|
+
let chunk;
|
|
119
|
+
if (nl === -1) { if (!final) return; chunk = carry; carry = ''; }
|
|
120
|
+
else { chunk = carry.slice(0, nl); carry = carry.slice(nl + 1); }
|
|
121
|
+
for (const line of chunk.split('\n')) {
|
|
122
|
+
if (!line.trim()) continue;
|
|
123
|
+
let e; try { e = JSON.parse(line); } catch { continue; }
|
|
124
|
+
if (e.pkg && !incident.package) incident.package = e.pkg + (e.lifecycle ? ` (${e.lifecycle})` : '');
|
|
125
|
+
if (e.kind === 'event') {
|
|
126
|
+
incident.events.push(e);
|
|
127
|
+
printEvent(e);
|
|
128
|
+
if ((e.base === 'ask' || e.base === 'block') && !policy.nonInteractive && policy.mode === 'prompt') {
|
|
129
|
+
await handlePrompt(e);
|
|
130
|
+
} else if (policy.mode === 'enforce' || policy.nonInteractive) {
|
|
131
|
+
if (e.base === 'block' || e.base === 'ask') markBlocked(e);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
function printEvent(e) {
|
|
138
|
+
if (quiet && e.base !== 'ask' && e.base !== 'block') return;
|
|
139
|
+
const col = sev[e.sev] || c.yellow;
|
|
140
|
+
const mark = (e.base === 'block') ? c.red('✕') : (e.base === 'ask') ? c.yellow('!') : c.dim('·');
|
|
141
|
+
process.stdout.write(` ${mark} ${col(e.rule.padEnd(8))} ${e.title}\n`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function markBlocked(e) {
|
|
145
|
+
blocked = true;
|
|
146
|
+
incident.outcome = 'blocked';
|
|
147
|
+
if (!incident.reason) incident.reason = describe(e);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function handlePrompt(e) {
|
|
151
|
+
sensors.pauseTree(child.pid);
|
|
152
|
+
process.stdout.write(`\n ${c.redBg(' PAUSED ')} ${c.white(e.rule)} ${e.title}\n`);
|
|
153
|
+
if (e.detail) process.stdout.write(` ${c.dim(JSON.stringify(e.detail).slice(0, 80))}\n`);
|
|
154
|
+
const action = await promptKAP(policy.askTimeoutSec);
|
|
155
|
+
fs.writeFileSync(path.join(session, 'decisions', e.id + '.json'), JSON.stringify({ action }));
|
|
156
|
+
if (action === 'K') {
|
|
157
|
+
markBlocked(e);
|
|
158
|
+
sensors.killTree(child.pid);
|
|
159
|
+
} else {
|
|
160
|
+
incident.prevented.push(`allowed ${e.rule} by your choice (${action})`);
|
|
161
|
+
// "P" = always trust: persist a narrow trust entry for this package so a
|
|
162
|
+
// later version that does something new no longer matches and we ask again.
|
|
163
|
+
if (action === 'P' && e.pkg) {
|
|
164
|
+
try {
|
|
165
|
+
const f = require('./store.js').update((o) => {
|
|
166
|
+
o.trust = o.trust || {}; o.trust[e.pkg] = o.trust[e.pkg] || { scripts: 'allow' };
|
|
167
|
+
});
|
|
168
|
+
if (!quiet) process.stdout.write(` ${c.green('trusted')} ${e.pkg} ${c.dim('(' + f + ')')}\n`);
|
|
169
|
+
} catch {}
|
|
170
|
+
}
|
|
171
|
+
sensors.resumeTree(child.pid);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const timer = setInterval(pump, 100);
|
|
176
|
+
|
|
177
|
+
const code = await new Promise((resolve) => {
|
|
178
|
+
child.on('exit', (c2) => resolve(c2));
|
|
179
|
+
child.on('error', () => resolve(1));
|
|
180
|
+
});
|
|
181
|
+
await pump(true);
|
|
182
|
+
clearInterval(timer);
|
|
183
|
+
if (proxy) proxy.close();
|
|
184
|
+
|
|
185
|
+
// fold in any egress the proxy refused (children that used HTTP(S)_PROXY)
|
|
186
|
+
for (const pe of proxyEvents) {
|
|
187
|
+
incident.events.push({ t: Date.now(), kind: 'event', id: 'proxy', rule: pe.rule,
|
|
188
|
+
title: 'egress blocked by proxy', sev: 'high', phase, base: 'block', detail: { host: pe.host } });
|
|
189
|
+
blocked = true; incident.outcome = 'blocked';
|
|
190
|
+
if (!incident.reason) incident.reason = `Egress to ${pe.host} was refused by the Sentrion proxy.`;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// decide outcome + evidence
|
|
194
|
+
if (blocked || incident.outcome === 'blocked') {
|
|
195
|
+
incident.outcome = 'blocked';
|
|
196
|
+
incident.prevented = computePrevented(incident);
|
|
197
|
+
incident.reason = incident.reason || 'A guarded step tried a blocked action; Sentrion stopped it.';
|
|
198
|
+
incident.next = [
|
|
199
|
+
'inspect the package/version and pin a known-good one',
|
|
200
|
+
`export it: sentrion report ${id} --format sarif`,
|
|
201
|
+
];
|
|
202
|
+
sensors.killTree(child.pid);
|
|
203
|
+
} else if (incident.events.length) {
|
|
204
|
+
incident.outcome = 'allowed-with-warnings';
|
|
205
|
+
} else {
|
|
206
|
+
incident.outcome = 'allowed';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const hasConcern = incident.events.some((e) => e.base === 'ask' || e.base === 'block');
|
|
210
|
+
if (hasConcern || incident.outcome.startsWith('blocked')) report.save(incident);
|
|
211
|
+
|
|
212
|
+
try { fs.rmSync(session, { recursive: true, force: true }); } catch {}
|
|
213
|
+
|
|
214
|
+
// summary line
|
|
215
|
+
if (incident.outcome === 'blocked') {
|
|
216
|
+
process.stdout.write(`\n ${c.redBg(' BLOCKED ')} ${c.bold(incident.reason)}\n`);
|
|
217
|
+
process.stdout.write(c.dim(` sentrion report ${id} for the full incident\n\n`));
|
|
218
|
+
return 87; // distinctive non-zero exit so CI fails
|
|
219
|
+
}
|
|
220
|
+
if (!quiet) process.stdout.write(`\n ${c.green('✓ ALLOW')} ${argv.join(' ')} ${c.dim(incident.events.length ? incident.events.length + ' notes' : '0 prompts')}\n\n`);
|
|
221
|
+
return code || 0;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function describe(e) {
|
|
225
|
+
const m = {
|
|
226
|
+
'NET-01': 'An install script tried to reach a server outside the registry allowlist.',
|
|
227
|
+
'NET-04': 'A process wired a shell to a network socket (reverse shell).',
|
|
228
|
+
'PROC-02': 'A script tried to download a file and run it.',
|
|
229
|
+
'FILE-01': 'A script tried to read a secret file (only a canary was exposed).',
|
|
230
|
+
'PERS-01': 'A script tried to install itself into a startup location.',
|
|
231
|
+
};
|
|
232
|
+
return m[e.rule] || `${e.rule}: ${e.title}.`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function computePrevented(inc) {
|
|
236
|
+
const out = [];
|
|
237
|
+
const rules = new Set(inc.events.map((e) => e.rule));
|
|
238
|
+
if (rules.has('NET-01') || rules.has('NET-05') || rules.has('NET-04')) out.push('no data sent');
|
|
239
|
+
if (rules.has('PROC-02') || rules.has('PROC-01')) out.push('no downloaded file executed');
|
|
240
|
+
if (rules.has('FILE-01')) out.push('real secret never exposed (canary only)');
|
|
241
|
+
if (rules.has('PERS-01')) out.push('no persistence written');
|
|
242
|
+
if (!out.length) out.push('process tree killed before completion');
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
module.exports = { run, classify };
|
package/lib/hook.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/*
|
|
3
|
+
* Sentrion Tier-1 language hook.
|
|
4
|
+
*
|
|
5
|
+
* Loaded into a guarded Node process via NODE_OPTIONS="--require <this>".
|
|
6
|
+
* It patches the dangerous entry points a supply-chain payload uses —
|
|
7
|
+
* spawning processes, opening network connections, reading secret files,
|
|
8
|
+
* writing persistence — classifies each against the rule set, and asks the
|
|
9
|
+
* parent guard for a decision BEFORE the action happens. On a deny it throws,
|
|
10
|
+
* which aborts the malicious call at its source (before any shell runs or any
|
|
11
|
+
* byte leaves the machine).
|
|
12
|
+
*
|
|
13
|
+
* Everything here uses the ORIGINAL stdlib functions captured before patching,
|
|
14
|
+
* so the hook never trips its own traps.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
if (process.env.SENTRION_HOOK_ACTIVE === '1' || !process.env.SENTRION_SESSION) {
|
|
18
|
+
// already hooked, or not launched by Sentrion — do nothing
|
|
19
|
+
module.exports = {};
|
|
20
|
+
} else {
|
|
21
|
+
process.env.SENTRION_HOOK_ACTIVE = '1';
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
const net = require('net');
|
|
27
|
+
const http = require('http');
|
|
28
|
+
const https = require('https');
|
|
29
|
+
const cp = require('child_process');
|
|
30
|
+
|
|
31
|
+
// --- originals (never patched) ---
|
|
32
|
+
const O = {
|
|
33
|
+
readFileSync: fs.readFileSync.bind(fs),
|
|
34
|
+
writeFileSync: fs.writeFileSync.bind(fs),
|
|
35
|
+
appendFileSync: fs.appendFileSync.bind(fs),
|
|
36
|
+
existsSync: fs.existsSync.bind(fs),
|
|
37
|
+
mkdirSync: fs.mkdirSync.bind(fs),
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const SESSION = process.env.SENTRION_SESSION;
|
|
41
|
+
const CFG = JSON.parse(process.env.SENTRION_CONFIG || '{}');
|
|
42
|
+
const PHASE = CFG.phase || 'run';
|
|
43
|
+
const MODE = CFG.mode || 'prompt';
|
|
44
|
+
const NONINT = !!CFG.nonInteractive;
|
|
45
|
+
const ALLOW_HOSTS = new Set(CFG.allowHosts || []);
|
|
46
|
+
const SECRET_PATHS = (CFG.secretPaths || []).map(String);
|
|
47
|
+
const PKG = process.env.npm_package_name || null;
|
|
48
|
+
const LIFECYCLE = process.env.npm_lifecycle_event || null;
|
|
49
|
+
// Only treat secret reads / persistence / shell spawns as suspicious when we
|
|
50
|
+
// are inside a package lifecycle script, or when the user is directly running
|
|
51
|
+
// code (run phase). This keeps the package manager's OWN reads of ~/.npmrc,
|
|
52
|
+
// cache dirs, etc. from tripping the guard during an install.
|
|
53
|
+
const WATCH = (PHASE === 'run') || !!LIFECYCLE;
|
|
54
|
+
const EVENTS = path.join(SESSION, 'events.jsonl');
|
|
55
|
+
const DEC_DIR = path.join(SESSION, 'decisions');
|
|
56
|
+
|
|
57
|
+
const { RULES, baseAction } = require('./rules.js');
|
|
58
|
+
|
|
59
|
+
let seq = 0;
|
|
60
|
+
function emit(obj) {
|
|
61
|
+
const line = JSON.stringify({ t: Date.now(), pid: process.pid, pkg: PKG, lifecycle: LIFECYCLE, ...obj }) + '\n';
|
|
62
|
+
try { O.appendFileSync(EVENTS, line); } catch {}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function sleep(ms) {
|
|
66
|
+
try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }
|
|
67
|
+
catch { const end = Date.now() + ms; while (Date.now() < end) {} }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Ask the parent for a decision and block (cooperatively) until it answers.
|
|
71
|
+
function waitDecision(id) {
|
|
72
|
+
const f = path.join(DEC_DIR, id + '.json');
|
|
73
|
+
const timeoutMs = (CFG.askTimeoutSec || 60) * 1000;
|
|
74
|
+
const until = Date.now() + timeoutMs;
|
|
75
|
+
while (Date.now() < until) {
|
|
76
|
+
try { return JSON.parse(O.readFileSync(f, 'utf8')).action; } catch {}
|
|
77
|
+
sleep(80);
|
|
78
|
+
}
|
|
79
|
+
return 'K'; // no answer → safe default: kill
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Returns true if the action may proceed, false if it must be blocked.
|
|
83
|
+
function decide(ruleId, detail) {
|
|
84
|
+
const id = `${process.pid}-${++seq}`;
|
|
85
|
+
let base = baseAction(ruleId, PHASE);
|
|
86
|
+
const override = (CFG.rules || {})[ruleId];
|
|
87
|
+
if (override) base = override;
|
|
88
|
+
|
|
89
|
+
emit({ kind: 'event', id, rule: ruleId, title: RULES[ruleId] ? RULES[ruleId].title : ruleId,
|
|
90
|
+
sev: RULES[ruleId] ? RULES[ruleId].sev : 'medium', phase: PHASE, base, detail });
|
|
91
|
+
|
|
92
|
+
if (base === 'allow' || base === 'warn') return true;
|
|
93
|
+
|
|
94
|
+
if (MODE === 'audit' || MODE === 'learn') return true; // record only
|
|
95
|
+
if (MODE === 'enforce' || NONINT) { // no human → deny ask+block
|
|
96
|
+
emit({ kind: 'decision', id, action: 'K', auto: true });
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
// prompt mode: ask the parent (who shows K / A / P)
|
|
100
|
+
const action = waitDecision(id);
|
|
101
|
+
emit({ kind: 'resolved', id, action });
|
|
102
|
+
return action === 'A' || action === 'P';
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ---- helpers ----
|
|
106
|
+
const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'cmd', 'cmd.exe', 'powershell', 'powershell.exe', 'pwsh']);
|
|
107
|
+
const FETCHERS = new Set(['curl', 'wget', 'certutil', 'bitsadmin', 'nc', 'ncat', 'socat']);
|
|
108
|
+
const RUNTIMES = new Set(['bun', 'deno', 'python', 'python3', 'ruby', 'perl', 'php']);
|
|
109
|
+
const PRIV = new Set(['sudo', 'su', 'pkexec', 'doas', 'runas']);
|
|
110
|
+
|
|
111
|
+
function baseName(cmd) {
|
|
112
|
+
if (!cmd) return '';
|
|
113
|
+
return String(cmd).split(/[\\/]/).pop().toLowerCase();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function classifyCommand(cmd, args, isExecString) {
|
|
117
|
+
// exec()/execSync() run their argument through a shell, so the "binary" is
|
|
118
|
+
// the whole command line; scan the string and treat it as a shell call.
|
|
119
|
+
const full = isExecString ? String(cmd) : [cmd, ...(args || [])].join(' ');
|
|
120
|
+
const b = isExecString ? 'sh' : baseName(cmd);
|
|
121
|
+
// never-legit patterns: always checked, even for the package manager core
|
|
122
|
+
if (/(curl|wget|fetch)[^\n|]*\|\s*(sh|bash|python|node|perl)/i.test(full)) return 'PROC-02';
|
|
123
|
+
if (/\/dev\/(tcp|udp)\//i.test(full)) return 'NET-04';
|
|
124
|
+
if (/npm\s+(publish|token)|gh\s+repo\s+create/i.test(full)) return 'TOK-01';
|
|
125
|
+
if (b === 'bun' || b === 'deno') return 'PROC-03';
|
|
126
|
+
if (RUNTIMES.has(b) && CFG.projectRuntime && b !== CFG.projectRuntime) return 'PROC-03';
|
|
127
|
+
// the rest are only suspicious inside a lifecycle script / guarded run
|
|
128
|
+
if (!WATCH) return null;
|
|
129
|
+
if (PRIV.has(b)) return 'PROC-05';
|
|
130
|
+
if (FETCHERS.has(b)) return PHASE === 'install' ? 'PROC-02' : 'PROC-01';
|
|
131
|
+
if (SHELLS.has(b) || isExecString) return 'PROC-01';
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isSecret(p) {
|
|
136
|
+
try {
|
|
137
|
+
const abs = path.resolve(String(p));
|
|
138
|
+
return SECRET_PATHS.some((s) => abs === s || abs.startsWith(s + path.sep));
|
|
139
|
+
} catch { return false; }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const STARTUP_HINTS = ['/autostart', 'launchagents', 'launchdaemons', 'systemd', 'cron',
|
|
143
|
+
'.bashrc', '.zshrc', '.profile', 'currentversion\\run', 'startup'];
|
|
144
|
+
function isPersistence(p) {
|
|
145
|
+
const s = String(p).toLowerCase();
|
|
146
|
+
return STARTUP_HINTS.some((h) => s.includes(h));
|
|
147
|
+
}
|
|
148
|
+
function isForeignPackageWrite(p) {
|
|
149
|
+
const s = String(p).toLowerCase();
|
|
150
|
+
return s.includes('.git/hooks') || s.includes('.git\\hooks') ||
|
|
151
|
+
s.includes('.github/workflows') || /node_modules\/(?!\.)/.test(s) && !s.includes(process.cwd().toLowerCase());
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function hostAllowed(host) {
|
|
155
|
+
if (!host) return true;
|
|
156
|
+
const h = String(host).toLowerCase();
|
|
157
|
+
if (ALLOW_HOSTS.has(h)) return true;
|
|
158
|
+
// allow loopback always
|
|
159
|
+
if (h === 'localhost' || h === '127.0.0.1' || h === '::1') return true;
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function netRule(host) {
|
|
164
|
+
const h = String(host || '').toLowerCase();
|
|
165
|
+
if (/\b(pastebin|hastebin|transfer\.sh|discord\.com\/api\/webhooks|api\.telegram\.org)\b/.test(h)) return 'NET-05';
|
|
166
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(h) && !h.startsWith('127.')) return 'NET-05';
|
|
167
|
+
if (hostAllowed(h)) return null;
|
|
168
|
+
return PHASE === 'install' ? 'NET-01' : 'NET-02';
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---- patch: child_process ----
|
|
172
|
+
function guardSpawn(name) {
|
|
173
|
+
const orig = cp[name];
|
|
174
|
+
if (!orig) return;
|
|
175
|
+
cp[name] = function (cmd, args) {
|
|
176
|
+
const isExecString = (name === 'exec' || name === 'execSync');
|
|
177
|
+
const rule = classifyCommand(cmd, Array.isArray(args) ? args : [], isExecString);
|
|
178
|
+
if (rule && !decide(rule, { cmd: String(cmd).slice(0, 200), args: Array.isArray(args) ? args.slice(0, 8) : undefined })) {
|
|
179
|
+
throw new Error(`Sentrion blocked ${rule}: ${baseName(cmd)} (${RULES[rule].title})`);
|
|
180
|
+
}
|
|
181
|
+
return orig.apply(this, arguments);
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
['spawn', 'spawnSync', 'exec', 'execSync', 'execFile', 'execFileSync', 'fork'].forEach(guardSpawn);
|
|
185
|
+
|
|
186
|
+
// ---- patch: network ----
|
|
187
|
+
function hostFromArgs(args) {
|
|
188
|
+
const a = args[0];
|
|
189
|
+
if (a && typeof a === 'object') return a.host || a.hostname;
|
|
190
|
+
if (typeof a === 'string' && !/^\//.test(a)) {
|
|
191
|
+
// connect(port, host) — host is the 2nd string arg
|
|
192
|
+
if (typeof args[1] === 'string') return args[1];
|
|
193
|
+
return undefined; // connect(port) → localhost
|
|
194
|
+
}
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
function checkNet(host) {
|
|
198
|
+
const rule = netRule(host);
|
|
199
|
+
if (rule && !decide(rule, { host })) {
|
|
200
|
+
throw new Error(`Sentrion blocked ${rule}: connection to ${host} (${RULES[rule].title})`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const origProtoConnect = net.Socket.prototype.connect;
|
|
204
|
+
net.Socket.prototype.connect = function (...args) { checkNet(hostFromArgs(args)); return origProtoConnect.apply(this, args); };
|
|
205
|
+
for (const fn of ['connect', 'createConnection']) {
|
|
206
|
+
const orig = net[fn];
|
|
207
|
+
if (typeof orig === 'function') net[fn] = function (...args) { checkNet(hostFromArgs(args)); return orig.apply(this, args); };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function guardRequest(mod, name) {
|
|
211
|
+
const orig = mod[name];
|
|
212
|
+
mod[name] = function (a, b) {
|
|
213
|
+
let host;
|
|
214
|
+
if (typeof a === 'string') { try { host = new URL(a).hostname; } catch {} }
|
|
215
|
+
else if (a && typeof a === 'object') host = a.hostname || a.host;
|
|
216
|
+
const rule = netRule(host);
|
|
217
|
+
if (rule && !decide(rule, { host })) {
|
|
218
|
+
throw new Error(`Sentrion blocked ${rule}: request to ${host} (${RULES[rule].title})`);
|
|
219
|
+
}
|
|
220
|
+
return orig.apply(this, arguments);
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
guardRequest(http, 'request'); guardRequest(http, 'get');
|
|
224
|
+
guardRequest(https, 'request'); guardRequest(https, 'get');
|
|
225
|
+
|
|
226
|
+
// ---- patch: secret reads ----
|
|
227
|
+
function guardRead(name) {
|
|
228
|
+
const orig = fs[name];
|
|
229
|
+
if (!orig) return;
|
|
230
|
+
fs[name] = function (p) {
|
|
231
|
+
if (WATCH && isSecret(p) && !decide('FILE-01', { path: String(p) })) {
|
|
232
|
+
throw new Error(`Sentrion blocked FILE-01: read of secret ${p}`);
|
|
233
|
+
}
|
|
234
|
+
return orig.apply(this, arguments);
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
['readFile', 'readFileSync', 'open', 'openSync', 'createReadStream'].forEach(guardRead);
|
|
238
|
+
|
|
239
|
+
// ---- patch: dangerous writes ----
|
|
240
|
+
function guardWrite(name) {
|
|
241
|
+
const orig = fs[name];
|
|
242
|
+
if (!orig) return;
|
|
243
|
+
fs[name] = function (p) {
|
|
244
|
+
let rule = null;
|
|
245
|
+
if (WATCH && isPersistence(p)) rule = 'PERS-01';
|
|
246
|
+
else if (WATCH && isForeignPackageWrite(p)) rule = 'FILE-02';
|
|
247
|
+
if (rule && !decide(rule, { path: String(p) })) {
|
|
248
|
+
throw new Error(`Sentrion blocked ${rule}: write to ${p}`);
|
|
249
|
+
}
|
|
250
|
+
return orig.apply(this, arguments);
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
['writeFile', 'writeFileSync', 'appendFile', 'appendFileSync', 'createWriteStream'].forEach(guardWrite);
|
|
254
|
+
|
|
255
|
+
emit({ kind: 'hook-ready', phase: PHASE, mode: MODE });
|
|
256
|
+
module.exports = {};
|
|
257
|
+
}
|