@ejouan/lxray 0.0.0-stage → 1.2.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 +43 -0
- package/README.md +181 -2
- package/bin/lxray-setup-root.js +31 -0
- package/package.json +47 -4
- package/setup/lxray-audit +26 -0
- package/setup/lxray-audit-request.path +10 -0
- package/setup/lxray-audit-request.service +9 -0
- package/setup/lxray-audit-requests +13 -0
- package/setup/lxray-audit.service +9 -0
- package/setup/lxray-audit.timer +11 -0
- package/src/executor.js +160 -0
- package/src/index.js +384 -0
- package/src/installer.js +121 -0
- package/src/middleware.js +127 -0
- package/src/monitoring.js +154 -0
- package/src/plugins.js +56 -0
- package/src/remote.js +256 -0
- package/src/report.js +118 -0
- package/types/index.d.ts +178 -0
package/src/index.js
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @ejouan/lxray - Node.js SDK for LXRAY, the X-ray for Linux servers.
|
|
5
|
+
*
|
|
6
|
+
* Three ways to get a report, from least to most privileged:
|
|
7
|
+
* audit() runs LXRAY under the app's own account (partial snapshot when not root)
|
|
8
|
+
* audit({ privileged: true }) runs the root-owned wrapper `lxray-audit` through `sudo -n` (installed once by an admin)
|
|
9
|
+
* readLatest() reads the newest report written by a scheduled root run (no rights needed)
|
|
10
|
+
* requestRootAudit() asks systemd for a root audit now and waits for it (no rights needed)
|
|
11
|
+
* Plus remote audits over SSH (remote.js) and an HTTP handler (middleware.js).
|
|
12
|
+
*/
|
|
13
|
+
const fs = require('node:fs/promises');
|
|
14
|
+
const os = require('node:os');
|
|
15
|
+
const path = require('node:path');
|
|
16
|
+
const { execLxray, execNoShell, resolveBinary, checkPython } = require('./executor');
|
|
17
|
+
const { REPORT_FILES, FORMATS, findSnapshotDir, findArchive, findReportDir, readReports, summarize } = require('./report');
|
|
18
|
+
const { PLUGINS, QUICK_SKIPPED, resolvePlugins } = require('./plugins');
|
|
19
|
+
|
|
20
|
+
const PROFILES = Object.freeze(['quick', 'standard', 'full']);
|
|
21
|
+
const DEFAULT_WRAPPER = '/usr/local/sbin/lxray-audit';
|
|
22
|
+
const DEFAULT_SPOOL = '/var/lib/lxray/reports';
|
|
23
|
+
const DEFAULT_REQUESTS = '/var/lib/lxray/requests';
|
|
24
|
+
|
|
25
|
+
function validateFormats(options) {
|
|
26
|
+
let formats = options.formats ?? (options.format ? [options.format] : []);
|
|
27
|
+
if (typeof formats === 'string') formats = formats.split(',');
|
|
28
|
+
formats = formats.map((f) => String(f).trim().toLowerCase()).map((f) => (f === 'text' ? 'txt' : f === 'markdown' ? 'md' : f));
|
|
29
|
+
for (const f of formats) if (!FORMATS.includes(f)) throw new TypeError(`Unknown format "${f}" (json, html, md, txt)`);
|
|
30
|
+
if (!formats.includes('json')) formats.unshift('json'); // the summary always needs the JSON
|
|
31
|
+
return [...new Set(formats)];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function validateProfile(p) {
|
|
35
|
+
if (p === undefined || p === null) return undefined;
|
|
36
|
+
if (!PROFILES.includes(p)) throw new TypeError(`Unknown profile "${p}" (quick, standard, full)`);
|
|
37
|
+
return p;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** CLI flags shared by run / collect, from validated options. */
|
|
41
|
+
function cliFlags(options) {
|
|
42
|
+
const args = [];
|
|
43
|
+
const only = resolvePlugins(options.only);
|
|
44
|
+
const exclude = resolvePlugins(options.exclude);
|
|
45
|
+
const profile = validateProfile(options.profile);
|
|
46
|
+
if (only.length) args.push('--only', only.join(','));
|
|
47
|
+
if (exclude.length) args.push('--exclude', exclude.join(','));
|
|
48
|
+
if (profile) args.push('--profile', profile);
|
|
49
|
+
if (options.timeout !== undefined) {
|
|
50
|
+
const t = Number(options.timeout);
|
|
51
|
+
if (!Number.isInteger(t) || t < 1 || t > 3600) throw new TypeError('timeout: whole seconds between 1 and 3600 (per command)');
|
|
52
|
+
args.push('--timeout', String(t));
|
|
53
|
+
}
|
|
54
|
+
if (options.redactIps) args.push('--redact-ips');
|
|
55
|
+
if (options.noRedact) args.push('--no-redact');
|
|
56
|
+
if (Array.isArray(options.extraArgs)) args.push(...options.extraArgs.map(String));
|
|
57
|
+
if (typeof options.onLog !== 'function') args.push('--quiet'); // with onLog, LXRAY's progress lines are streamed
|
|
58
|
+
return args;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function warnings(options) {
|
|
62
|
+
const w = [];
|
|
63
|
+
if (options.profile === 'quick') {
|
|
64
|
+
const skipped = resolvePlugins(options.only).filter((id) => QUICK_SKIPPED.includes(id));
|
|
65
|
+
if (skipped.length) w.push(`The quick profile skips ${skipped.join(', ')}: use profile "standard" to collect them.`);
|
|
66
|
+
}
|
|
67
|
+
return w;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function tempDir(prefix) {
|
|
71
|
+
return fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Builds the result object from a folder that contains the report files. */
|
|
75
|
+
async function buildResult(reportDir, formats, extra) {
|
|
76
|
+
const files = await readReports(reportDir, formats);
|
|
77
|
+
return { summary: summarize(files.report), ...files, ...extra };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Runs a full LXRAY audit on this machine and returns the reports.
|
|
82
|
+
*
|
|
83
|
+
* @param {object} [options]
|
|
84
|
+
* @param {Array<'json'|'html'|'md'|'txt'>|string} [options.formats=['json']] formats to return (JSON always included)
|
|
85
|
+
* @param {'quick'|'standard'|'full'} [options.profile] collection depth (LXRAY default: standard)
|
|
86
|
+
* @param {string[]} [options.only] plugins to run (ids like "70-security" or aliases like "security")
|
|
87
|
+
* @param {string[]} [options.exclude] plugins to skip
|
|
88
|
+
* @param {number} [options.timeout] per-command timeout of the collector, in seconds
|
|
89
|
+
* @param {boolean} [options.redactIps] mask IP addresses in the reports
|
|
90
|
+
* @param {boolean} [options.noRedact] keep secrets unmasked (masked by default)
|
|
91
|
+
* @param {boolean} [options.archive] also build the .tar.gz snapshot (implies keepArtifacts)
|
|
92
|
+
* @param {boolean} [options.keepArtifacts] keep the output folder (returned as outdir)
|
|
93
|
+
* @param {string} [options.outdir] write there instead of a private temporary folder (kept)
|
|
94
|
+
* @param {boolean} [options.privileged] run the root wrapper through `sudo -n` (see README "Root access")
|
|
95
|
+
* @param {string} [options.wrapperPath] path of the root wrapper (default /usr/local/sbin/lxray-audit)
|
|
96
|
+
* @param {boolean} [options.autoInstall] install a user-space copy of LXRAY if missing (GPG-verified)
|
|
97
|
+
* @param {string} [options.binaryPath] explicit path of the lxray executable
|
|
98
|
+
* @param {number} [options.processTimeout=600000] overall time limit in milliseconds
|
|
99
|
+
*/
|
|
100
|
+
async function audit(options = {}) {
|
|
101
|
+
const started = Date.now();
|
|
102
|
+
const formats = validateFormats(options);
|
|
103
|
+
if (options.privileged) return privilegedAudit({ ...options, formats }, started);
|
|
104
|
+
|
|
105
|
+
let binaryPath = options.binaryPath;
|
|
106
|
+
if (options.autoInstall) {
|
|
107
|
+
try {
|
|
108
|
+
binaryPath = await resolveBinary(binaryPath);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
if (e.code !== 'LXRAY_NOT_FOUND') throw e;
|
|
111
|
+
binaryPath = (await require('./installer').install(options.installOptions)).binaryPath;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const keep = Boolean(options.outdir || options.keepArtifacts || options.archive);
|
|
116
|
+
const outdir = options.outdir ? path.resolve(options.outdir) : await tempDir('lxray-run-');
|
|
117
|
+
try {
|
|
118
|
+
const args = ['--outdir', outdir, '--format', formats.join(','), ...cliFlags(options)];
|
|
119
|
+
if (!options.archive) args.push('--no-tar');
|
|
120
|
+
const { binary, code } = await execLxray('run', args, { binaryPath, processTimeout: options.processTimeout ?? 600000, onLog: options.onLog });
|
|
121
|
+
const reportDir = await findReportDir(outdir);
|
|
122
|
+
if (!reportDir) throw new Error(`LXRAY finished but wrote no report under ${outdir}`);
|
|
123
|
+
return await buildResult(reportDir, formats, {
|
|
124
|
+
binary,
|
|
125
|
+
durationMs: Date.now() - started,
|
|
126
|
+
privileged: false,
|
|
127
|
+
partial: code === 3,
|
|
128
|
+
isRoot: typeof process.getuid === 'function' && process.getuid() === 0,
|
|
129
|
+
warnings: warnings(options),
|
|
130
|
+
...(keep ? { outdir, snapshotDir: await findSnapshotDir(outdir), archivePath: await findArchive(outdir) } : {})
|
|
131
|
+
});
|
|
132
|
+
} finally {
|
|
133
|
+
if (!keep) await fs.rm(outdir, { recursive: true, force: true }).catch(() => {});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Root audit through the wrapper installed by an administrator (see setup/lxray-audit).
|
|
139
|
+
* The wrapper only takes a profile; it writes into the spool folder and prints the report folder.
|
|
140
|
+
*/
|
|
141
|
+
async function privilegedAudit(options, started) {
|
|
142
|
+
const wrapper = options.wrapperPath || DEFAULT_WRAPPER;
|
|
143
|
+
const profile = validateProfile(options.profile) || 'standard';
|
|
144
|
+
if (options.only || options.exclude || options.outdir) {
|
|
145
|
+
throw new TypeError('privileged audits take only "profile": plugin selection and outdir are fixed by the root wrapper');
|
|
146
|
+
}
|
|
147
|
+
let out;
|
|
148
|
+
try {
|
|
149
|
+
out = await execNoShell('sudo', ['-n', wrapper, profile], { timeout: options.processTimeout ?? 900000 });
|
|
150
|
+
} catch (e) {
|
|
151
|
+
if (/a password is required|not allowed|may not run sudo|command not found|no such file/i.test(`${e.stderr} ${e.message}`)) {
|
|
152
|
+
const err = new Error(`Privileged audit refused: the root wrapper ${wrapper} is not installed or this account may not run it. ` +
|
|
153
|
+
'Ask an administrator to run the commands printed by `npx lxray-setup-root` once.');
|
|
154
|
+
err.code = 'LXRAY_PRIVILEGE_DENIED';
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
throw e;
|
|
158
|
+
}
|
|
159
|
+
const reportDir = out.stdout.trim().split('\n').pop();
|
|
160
|
+
if (!reportDir || !path.isAbsolute(reportDir)) throw new Error(`The root wrapper did not return a report folder (got: ${out.stdout.slice(-200)})`);
|
|
161
|
+
return buildResult(reportDir, options.formats, { binary: wrapper, durationMs: Date.now() - started, privileged: true, isRoot: true, warnings: [], reportDir });
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Newest report written by a scheduled root run (wrapper or LXRAY timer) in the spool folder.
|
|
166
|
+
* Needs only read access to that folder.
|
|
167
|
+
* @param {{ spoolDir?: string, formats?: string[]|string, maxAgeMinutes?: number }} [options]
|
|
168
|
+
*/
|
|
169
|
+
async function readLatest(options = {}) {
|
|
170
|
+
const spool = options.spoolDir || DEFAULT_SPOOL;
|
|
171
|
+
const formats = validateFormats(options);
|
|
172
|
+
let entries;
|
|
173
|
+
try {
|
|
174
|
+
entries = (await fs.readdir(spool, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name).sort();
|
|
175
|
+
} catch (e) {
|
|
176
|
+
const err = new Error(`No readable report spool at ${spool} (${e.code}). See README "Root access", mode 3.`);
|
|
177
|
+
err.code = 'LXRAY_NO_SPOOL';
|
|
178
|
+
throw err;
|
|
179
|
+
}
|
|
180
|
+
for (const name of entries.reverse()) {
|
|
181
|
+
const dir = path.join(spool, name);
|
|
182
|
+
const reportDir = await findReportDir(dir);
|
|
183
|
+
if (!reportDir) continue;
|
|
184
|
+
const stat = await fs.stat(path.join(reportDir, REPORT_FILES.json));
|
|
185
|
+
const ageMinutes = (Date.now() - stat.mtimeMs) / 60000;
|
|
186
|
+
if (options.maxAgeMinutes !== undefined && ageMinutes > options.maxAgeMinutes) {
|
|
187
|
+
const err = new Error(`Newest report is ${Math.round(ageMinutes)} min old (limit ${options.maxAgeMinutes})`);
|
|
188
|
+
err.code = 'LXRAY_STALE';
|
|
189
|
+
throw err;
|
|
190
|
+
}
|
|
191
|
+
return buildResult(reportDir, formats, { reportDir, ageMinutes: Math.round(ageMinutes), privileged: true });
|
|
192
|
+
}
|
|
193
|
+
const err = new Error(`No report found in ${spool}`);
|
|
194
|
+
err.code = 'LXRAY_NO_REPORT';
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Asks the system for a complete root audit WITHOUT the app having any privilege (mode 3, on demand):
|
|
200
|
+
* drops "<profile>.request" into the request folder; systemd (lxray-audit-request.path) runs the root
|
|
201
|
+
* wrapper; this function waits for the new report in the spool and returns it.
|
|
202
|
+
* The app's account must be in the "lxray" group. Set up once with `npx lxray-setup-root`.
|
|
203
|
+
* @param {{ profile?: string, formats?: string[]|string, requestDir?: string, spoolDir?: string, waitMs?: number, pollMs?: number }} [options]
|
|
204
|
+
*/
|
|
205
|
+
async function requestRootAudit(options = {}) {
|
|
206
|
+
const started = Date.now();
|
|
207
|
+
const profile = validateProfile(options.profile) || 'standard';
|
|
208
|
+
const requestDir = options.requestDir || DEFAULT_REQUESTS;
|
|
209
|
+
const spool = options.spoolDir || DEFAULT_SPOOL;
|
|
210
|
+
const waitMs = options.waitMs ?? 15 * 60000;
|
|
211
|
+
const pollMs = options.pollMs ?? 2000;
|
|
212
|
+
const listDirs = async () => {
|
|
213
|
+
try {
|
|
214
|
+
return (await fs.readdir(spool, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name);
|
|
215
|
+
} catch {
|
|
216
|
+
return [];
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
const before = new Set(await listDirs());
|
|
220
|
+
try {
|
|
221
|
+
await fs.writeFile(path.join(requestDir, `${profile}.request`), `${new Date().toISOString()}
|
|
222
|
+
`, { mode: 0o660 });
|
|
223
|
+
} catch (e) {
|
|
224
|
+
const err = new Error(`Cannot request a root audit in ${requestDir} (${e.code}): run \`npx lxray-setup-root\` and add this account to the lxray group.`);
|
|
225
|
+
err.code = 'LXRAY_PRIVILEGE_DENIED';
|
|
226
|
+
throw err;
|
|
227
|
+
}
|
|
228
|
+
while (Date.now() - started < waitMs) {
|
|
229
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
230
|
+
// any audit folder that did not exist before the request (names can tie within one second)
|
|
231
|
+
for (const name of (await listDirs()).filter((n) => !before.has(n)).sort().reverse()) {
|
|
232
|
+
const reportDir = await findReportDir(path.join(spool, name));
|
|
233
|
+
if (!reportDir) continue;
|
|
234
|
+
try {
|
|
235
|
+
return await buildResult(reportDir, validateFormats(options), { reportDir, durationMs: Date.now() - started, privileged: true, isRoot: true, warnings: [] });
|
|
236
|
+
} catch {
|
|
237
|
+
// files still being written: next poll
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const err = new Error(`No root report after ${Math.round(waitMs / 1000)} s: is lxray-audit-request.path active?`);
|
|
242
|
+
err.code = 'LXRAY_TIMEOUT';
|
|
243
|
+
throw err;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Collects a raw snapshot (no analysis) and returns where it is. The caller owns the files.
|
|
248
|
+
* @returns {Promise<{ archivePath: string|null, snapshotDir: string|null, outdir: string }>}
|
|
249
|
+
*/
|
|
250
|
+
async function collect(options = {}) {
|
|
251
|
+
const outdir = options.outdir ? path.resolve(options.outdir) : await tempDir('lxray-collect-');
|
|
252
|
+
const args = ['--outdir', outdir, ...cliFlags(options)];
|
|
253
|
+
if (options.noTar) args.push('--no-tar');
|
|
254
|
+
const { code } = await execLxray('collect', args, { binaryPath: options.binaryPath, processTimeout: options.processTimeout ?? 600000, onLog: options.onLog });
|
|
255
|
+
return { outdir, snapshotDir: await findSnapshotDir(outdir), archivePath: await findArchive(outdir), partial: code === 3 };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Analyzes an existing snapshot (folder or .tar.gz), for example one collected on another machine.
|
|
260
|
+
* @param {string} target
|
|
261
|
+
* @param {{ formats?: string[]|string, outdir?: string, keepArtifacts?: boolean, binaryPath?: string, processTimeout?: number }} [options]
|
|
262
|
+
*/
|
|
263
|
+
async function analyze(target, options = {}) {
|
|
264
|
+
if (!target) throw new TypeError('analyze() needs the path of a snapshot folder or .tar.gz');
|
|
265
|
+
const formats = validateFormats(options);
|
|
266
|
+
const keep = Boolean(options.outdir || options.keepArtifacts);
|
|
267
|
+
const outdir = options.outdir ? path.resolve(options.outdir) : await tempDir('lxray-analyze-');
|
|
268
|
+
try {
|
|
269
|
+
await execLxray('analyze', [path.resolve(target), '--outdir', outdir, '--format', formats.join(','), '--quiet'],
|
|
270
|
+
{ binaryPath: options.binaryPath, processTimeout: options.processTimeout ?? 300000 });
|
|
271
|
+
const reportDir = await findReportDir(outdir);
|
|
272
|
+
if (!reportDir) throw new Error(`lxray analyze wrote no report in ${outdir}`);
|
|
273
|
+
return await buildResult(reportDir, formats, keep ? { outdir } : {});
|
|
274
|
+
} finally {
|
|
275
|
+
if (!keep) await fs.rm(outdir, { recursive: true, force: true }).catch(() => {});
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Installed plugins, as reported by `lxray plugins`. */
|
|
280
|
+
async function plugins(options = {}) {
|
|
281
|
+
const { stdout } = await execLxray('plugins', [], { binaryPath: options.binaryPath, processTimeout: 30000 });
|
|
282
|
+
return stdout.split('\n').slice(2).map((l) => l.trim()).filter(Boolean).map((l) => {
|
|
283
|
+
const [id, ...rest] = l.split(/\s+/);
|
|
284
|
+
const known = PLUGINS.find((p) => p.id === id);
|
|
285
|
+
return { id, alias: known?.alias ?? null, description: rest.join(' ') || known?.title || '' };
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Tools LXRAY can use on this machine (`lxray deps`): which are present, which are missing,
|
|
291
|
+
* and the packages to install. With { install: true } runs `lxray deps --install` (needs root).
|
|
292
|
+
* @returns {Promise<{ platform: object, tools: Array<{group, probe, ok, unlocks}>, missingPackages: string[], installCommand: string|null }>}
|
|
293
|
+
*/
|
|
294
|
+
async function deps(options = {}) {
|
|
295
|
+
const args = options.install ? ['--install'] : [];
|
|
296
|
+
const { stdout } = await execLxray('deps', args, { binaryPath: options.binaryPath, processTimeout: options.processTimeout ?? (options.install ? 900000 : 60000), onLog: options.onLog });
|
|
297
|
+
const clean = stdout.replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
|
|
298
|
+
const platform = {};
|
|
299
|
+
const tools = [];
|
|
300
|
+
let missingPackages = [];
|
|
301
|
+
let installCommand = null;
|
|
302
|
+
for (const line of clean.split(/\r?\n/)) {
|
|
303
|
+
const kv = /^\s{2}(platform|family|pkg mgr|init)\s+(.*)$/.exec(line);
|
|
304
|
+
if (kv) { platform[kv[1].replace(' ', '')] = kv[2].trim(); continue; }
|
|
305
|
+
const row = /^(\S+)\s+(\S+)\s+(ok|MISSING)\s+(.*)$/.exec(line);
|
|
306
|
+
if (row && row[1] !== 'GROUP') { tools.push({ group: row[1], probe: row[2], ok: row[3] === 'ok', unlocks: row[4].trim() }); continue; }
|
|
307
|
+
const miss = /missing packages:\s*(.*)$/.exec(line);
|
|
308
|
+
if (miss) missingPackages = miss[1].trim().split(/\s+/).filter(Boolean);
|
|
309
|
+
const cmd = /install with:\s*(.*)$/.exec(line);
|
|
310
|
+
if (cmd) installCommand = cmd[1].trim();
|
|
311
|
+
}
|
|
312
|
+
return { platform, tools, missingPackages, installCommand };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Installed LXRAY version ("1.2.0"). */
|
|
316
|
+
async function version(options = {}) {
|
|
317
|
+
const { stdout } = await execLxray('version', [], { binaryPath: options.binaryPath, processTimeout: 30000 });
|
|
318
|
+
const m = /(\d+\.\d+\.\d+)/.exec(stdout);
|
|
319
|
+
return m ? m[1] : stdout.trim();
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** What this machine offers: LXRAY, Python, privileges, root wrapper, spool. */
|
|
323
|
+
async function checkEnvironment(options = {}) {
|
|
324
|
+
const isRoot = typeof process.getuid === 'function' && process.getuid() === 0;
|
|
325
|
+
let binaryPath = null, lxrayVersion = null;
|
|
326
|
+
try {
|
|
327
|
+
binaryPath = await resolveBinary(options.binaryPath);
|
|
328
|
+
lxrayVersion = await version({ binaryPath });
|
|
329
|
+
} catch {
|
|
330
|
+
// not installed
|
|
331
|
+
}
|
|
332
|
+
const python = await checkPython();
|
|
333
|
+
const wrapper = options.wrapperPath || DEFAULT_WRAPPER;
|
|
334
|
+
const spool = options.spoolDir || DEFAULT_SPOOL;
|
|
335
|
+
const exists = async (p) => fs.access(p).then(() => true, () => false);
|
|
336
|
+
return {
|
|
337
|
+
platform: process.platform,
|
|
338
|
+
supported: process.platform === 'linux',
|
|
339
|
+
installed: Boolean(binaryPath),
|
|
340
|
+
binaryPath,
|
|
341
|
+
lxrayVersion,
|
|
342
|
+
pythonAvailable: python.available,
|
|
343
|
+
pythonVersion: python.version,
|
|
344
|
+
isRoot,
|
|
345
|
+
rootWrapperInstalled: await exists(wrapper),
|
|
346
|
+
spoolReadable: await exists(spool),
|
|
347
|
+
plugins: PLUGINS,
|
|
348
|
+
note: isRoot
|
|
349
|
+
? 'Running as root: every check is evaluated.'
|
|
350
|
+
: 'Not root: LXRAY reads what this account can read and lists the checks it could not evaluate. Use privileged mode or readLatest() for complete reports.'
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
module.exports = {
|
|
355
|
+
audit,
|
|
356
|
+
run: audit,
|
|
357
|
+
readLatest,
|
|
358
|
+
requestRootAudit,
|
|
359
|
+
collect,
|
|
360
|
+
analyze,
|
|
361
|
+
plugins,
|
|
362
|
+
deps,
|
|
363
|
+
version,
|
|
364
|
+
checkEnvironment,
|
|
365
|
+
summarize,
|
|
366
|
+
resolvePlugins,
|
|
367
|
+
PLUGINS,
|
|
368
|
+
PROFILES,
|
|
369
|
+
FORMATS,
|
|
370
|
+
REPORT_FILES,
|
|
371
|
+
DEFAULT_WRAPPER,
|
|
372
|
+
DEFAULT_SPOOL,
|
|
373
|
+
DEFAULT_REQUESTS,
|
|
374
|
+
// lazy, so that requiring the SDK does not load what is not used (and no circular require)
|
|
375
|
+
get install() { return require('./installer').install; },
|
|
376
|
+
get createAuditHandler() { return require('./middleware').createAuditHandler; },
|
|
377
|
+
get remoteAudit() { return require('./remote').remoteAudit; },
|
|
378
|
+
get auditFleet() { return require('./remote').auditFleet; },
|
|
379
|
+
get remoteCollect() { return require('./remote').remoteCollect; },
|
|
380
|
+
get evaluate() { return require('./monitoring').evaluate; },
|
|
381
|
+
get compare() { return require('./monitoring').compare; },
|
|
382
|
+
get toPrometheus() { return require('./monitoring').toPrometheus; },
|
|
383
|
+
get saveReports() { return require('./monitoring').saveReports; }
|
|
384
|
+
};
|
package/src/installer.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* User-space installation of LXRAY (no root, no package manager): downloads the official
|
|
5
|
+
* release archive from GitHub, checks its GPG signature against the LXRAY signing key
|
|
6
|
+
* (fingerprint pinned below), then unpacks it into ~/.local/share/lxray.
|
|
7
|
+
*/
|
|
8
|
+
const https = require('node:https');
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const fsp = require('node:fs/promises');
|
|
11
|
+
const path = require('node:path');
|
|
12
|
+
const os = require('node:os');
|
|
13
|
+
const { execNoShell } = require('./executor');
|
|
14
|
+
|
|
15
|
+
const RELEASES_API = 'https://api.github.com/repos/eljouan/lxray/releases';
|
|
16
|
+
const DEFAULT_INSTALL_DIR = path.join(os.homedir(), '.local/share/lxray');
|
|
17
|
+
const EXPECTED_GPG_FINGERPRINT = '20453DAF3BD4BDC9B0351D193F70F7EA1C48682C';
|
|
18
|
+
const ALLOWED_HOSTS = new Set(['api.github.com', 'github.com', 'objects.githubusercontent.com', 'release-assets.githubusercontent.com']);
|
|
19
|
+
|
|
20
|
+
function get(url, redirects = 0) {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const u = new URL(url);
|
|
23
|
+
if (u.protocol !== 'https:' || !ALLOWED_HOSTS.has(u.hostname)) return reject(new Error(`Refusing to download from ${u.hostname}`));
|
|
24
|
+
https.get(u, { headers: { 'User-Agent': 'lxray-node-installer', Accept: 'application/octet-stream, application/vnd.github+json' } }, (res) => {
|
|
25
|
+
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
26
|
+
res.resume();
|
|
27
|
+
if (redirects > 5) return reject(new Error('Too many redirects'));
|
|
28
|
+
return resolve(get(new URL(res.headers.location, u).href, redirects + 1));
|
|
29
|
+
}
|
|
30
|
+
if (res.statusCode !== 200) {
|
|
31
|
+
res.resume();
|
|
32
|
+
return reject(new Error(`HTTP ${res.statusCode} for ${u.href}`));
|
|
33
|
+
}
|
|
34
|
+
resolve(res);
|
|
35
|
+
}).on('error', reject);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function fetchJson(url) {
|
|
40
|
+
const res = await get(url);
|
|
41
|
+
let body = '';
|
|
42
|
+
res.setEncoding('utf8');
|
|
43
|
+
for await (const chunk of res) body += chunk;
|
|
44
|
+
return JSON.parse(body);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function download(url, dest, maxBytes = 50 * 1024 * 1024) {
|
|
48
|
+
const res = await get(url);
|
|
49
|
+
let size = 0;
|
|
50
|
+
await new Promise((resolve, reject) => {
|
|
51
|
+
const out = fs.createWriteStream(dest, { mode: 0o600 });
|
|
52
|
+
res.on('data', (c) => {
|
|
53
|
+
size += c.length;
|
|
54
|
+
if (size > maxBytes) { res.destroy(new Error('Download too large')); }
|
|
55
|
+
});
|
|
56
|
+
res.on('error', reject);
|
|
57
|
+
out.on('error', reject);
|
|
58
|
+
out.on('finish', resolve);
|
|
59
|
+
res.pipe(out);
|
|
60
|
+
});
|
|
61
|
+
return dest;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Imports the key in a throw-away keyring, checks its fingerprint, then the detached signature. */
|
|
65
|
+
async function verifyGpgSignature(file, signature, publicKey, expected = EXPECTED_GPG_FINGERPRINT) {
|
|
66
|
+
const home = await fsp.mkdtemp(path.join(os.tmpdir(), 'lxray-gpg-'));
|
|
67
|
+
try {
|
|
68
|
+
await fsp.chmod(home, 0o700);
|
|
69
|
+
const env = { GNUPGHOME: home };
|
|
70
|
+
await execNoShell('gpg', ['--batch', '--quiet', '--import', publicKey], { env, timeout: 30000 });
|
|
71
|
+
const { stdout } = await execNoShell('gpg', ['--batch', '--with-colons', '--fingerprint'], { env, timeout: 30000 });
|
|
72
|
+
const fprs = stdout.split('\n').filter((l) => l.startsWith('fpr:')).map((l) => l.split(':')[9]);
|
|
73
|
+
const want = expected.replace(/\s+/g, '').toUpperCase();
|
|
74
|
+
if (!fprs.includes(want)) throw new Error(`Signing key fingerprint mismatch: expected ${want}, got ${fprs.join(', ') || 'none'}`);
|
|
75
|
+
await execNoShell('gpg', ['--batch', '--trust-model', 'always', '--verify', signature, file], { env, timeout: 30000 });
|
|
76
|
+
} finally {
|
|
77
|
+
await fsp.rm(home, { recursive: true, force: true }).catch(() => {});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {{ installDir?: string, version?: string, verifyGpg?: boolean, expectedFingerprint?: string }} [options]
|
|
83
|
+
* @returns {Promise<{ binaryPath: string, version: string, installDir: string, gpgVerified: boolean }>}
|
|
84
|
+
*/
|
|
85
|
+
async function install(options = {}) {
|
|
86
|
+
const installDir = path.resolve(options.installDir || DEFAULT_INSTALL_DIR);
|
|
87
|
+
const verify = options.verifyGpg !== false;
|
|
88
|
+
if (options.version && !/^v?\d+\.\d+\.\d+$/.test(options.version)) throw new TypeError('version: like 1.2.0');
|
|
89
|
+
const tag = options.version ? (options.version.startsWith('v') ? options.version : `v${options.version}`) : null;
|
|
90
|
+
const release = await fetchJson(tag ? `${RELEASES_API}/tags/${tag}` : `${RELEASES_API}/latest`);
|
|
91
|
+
const assets = Array.isArray(release.assets) ? release.assets : [];
|
|
92
|
+
const archive = assets.find((a) => /^lxray-\d+\.\d+\.\d+-linux\.tar\.gz$/.test(a.name));
|
|
93
|
+
if (!archive) throw new Error(`No lxray-<version>-linux.tar.gz in release ${release.tag_name}`);
|
|
94
|
+
|
|
95
|
+
const work = await fsp.mkdtemp(path.join(os.tmpdir(), 'lxray-dl-'));
|
|
96
|
+
try {
|
|
97
|
+
const tgz = await download(archive.browser_download_url, path.join(work, archive.name));
|
|
98
|
+
let gpgVerified = false;
|
|
99
|
+
if (verify) {
|
|
100
|
+
const sig = assets.find((a) => a.name === `${archive.name}.asc`);
|
|
101
|
+
const key = assets.find((a) => a.name === 'jouan.asc');
|
|
102
|
+
if (!sig || !key) throw new Error('The release lacks the signature (.asc) or the signing key (jouan.asc)');
|
|
103
|
+
await download(sig.browser_download_url, path.join(work, sig.name), 1024 * 1024);
|
|
104
|
+
await download(key.browser_download_url, path.join(work, key.name), 1024 * 1024);
|
|
105
|
+
await verifyGpgSignature(tgz, path.join(work, sig.name), path.join(work, key.name), options.expectedFingerprint);
|
|
106
|
+
gpgVerified = true;
|
|
107
|
+
}
|
|
108
|
+
// refuse archives with absolute paths or ".." before extracting
|
|
109
|
+
const { stdout: listing } = await execNoShell('tar', ['-tzf', tgz], { timeout: 60000 });
|
|
110
|
+
if (listing.split('\n').some((p) => p.startsWith('/') || p.split('/').includes('..'))) throw new Error('Unsafe paths in the archive');
|
|
111
|
+
await fsp.mkdir(installDir, { recursive: true });
|
|
112
|
+
await execNoShell('tar', ['-xzf', tgz, '-C', installDir, '--strip-components=1', '--no-same-owner'], { timeout: 120000 });
|
|
113
|
+
const binaryPath = path.join(installDir, 'bin', 'lxray');
|
|
114
|
+
await fsp.chmod(binaryPath, 0o755);
|
|
115
|
+
return { binaryPath, version: String(release.tag_name || '').replace(/^v/, ''), installDir, gpgVerified };
|
|
116
|
+
} finally {
|
|
117
|
+
await fsp.rm(work, { recursive: true, force: true }).catch(() => {});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
module.exports = { install, verifyGpgSignature, DEFAULT_INSTALL_DIR, EXPECTED_GPG_FINGERPRINT };
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* HTTP handler (Express, Connect or plain node:http) serving LXRAY audits of this machine.
|
|
5
|
+
* GET ?format=html|json|md|txt run an audit (or read the latest root report, see `source`)
|
|
6
|
+
* GET ?format=summary score, grade and issues only (JSON)
|
|
7
|
+
* GET ?format=metrics Prometheus metrics (text exposition)
|
|
8
|
+
* GET ?format=check monitoring state OK/WARNING/CRITICAL (JSON, HTTP 200/200/503 with checkHttpStatus)
|
|
9
|
+
* GET ?format=status what this machine offers (checkEnvironment)
|
|
10
|
+
* GET ?format=archive raw .tar.gz snapshot (only with allowArchive: true)
|
|
11
|
+
*
|
|
12
|
+
* Safety: `authorize(req)` is mandatory; one audit at a time; per-client rate limit keyed on the
|
|
13
|
+
* socket address (X-Forwarded-For is only used when trustProxy: true); HTML reports are served
|
|
14
|
+
* with a sandbox Content-Security-Policy.
|
|
15
|
+
*/
|
|
16
|
+
const fs = require('node:fs');
|
|
17
|
+
const path = require('node:path');
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} options
|
|
21
|
+
* @param {(req: any) => boolean|Promise<boolean>} options.authorize REQUIRED
|
|
22
|
+
* @param {'audit'|'privileged'|'latest'} [options.source='audit'] where reports come from
|
|
23
|
+
* @param {'html'|'json'|'md'|'txt'|'summary'} [options.defaultFormat='html']
|
|
24
|
+
* @param {boolean} [options.allowArchive=false]
|
|
25
|
+
* @param {number} [options.rateLimitWindowMs=60000]
|
|
26
|
+
* @param {number} [options.rateLimitMax=3]
|
|
27
|
+
* @param {boolean} [options.trustProxy=false] use the first X-Forwarded-For address as client key
|
|
28
|
+
* @param {(req: any) => string} [options.keyGenerator]
|
|
29
|
+
* @param {object} [options.auditOptions] options passed to audit() / readLatest() (profile, only, redactIps...)
|
|
30
|
+
* @param {object} [options.checkRules] thresholds for ?format=check (see evaluate(): minScore, warnScore, maxCritical...)
|
|
31
|
+
* @param {boolean} [options.checkHttpStatus=false] ?format=check answers 503 when CRITICAL (for HTTP probes)
|
|
32
|
+
*/
|
|
33
|
+
function createAuditHandler(options = {}) {
|
|
34
|
+
if (!options || typeof options.authorize !== 'function') {
|
|
35
|
+
throw new TypeError('createAuditHandler() requires an authorize(req) function: server diagnostics must never be public.');
|
|
36
|
+
}
|
|
37
|
+
const {
|
|
38
|
+
authorize, source = 'audit', defaultFormat = 'html', allowArchive = false,
|
|
39
|
+
rateLimitWindowMs = 60000, rateLimitMax = 3, trustProxy = false, keyGenerator, auditOptions = {}, checkRules = {}, checkHttpStatus = false
|
|
40
|
+
} = options;
|
|
41
|
+
if (!['audit', 'privileged', 'latest'].includes(source)) throw new TypeError('source: audit, privileged or latest');
|
|
42
|
+
const hits = new Map();
|
|
43
|
+
let busy = false;
|
|
44
|
+
|
|
45
|
+
const clientKey = (req) => {
|
|
46
|
+
if (typeof keyGenerator === 'function') return String(keyGenerator(req));
|
|
47
|
+
if (trustProxy) {
|
|
48
|
+
const xff = String(req.headers?.['x-forwarded-for'] || '').split(',')[0].trim();
|
|
49
|
+
if (xff) return xff;
|
|
50
|
+
}
|
|
51
|
+
return String(req.socket?.remoteAddress || 'unknown');
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const send = (res, status, type, body, headers = {}) => {
|
|
55
|
+
res.statusCode = status;
|
|
56
|
+
res.setHeader('Content-Type', type);
|
|
57
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
58
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
59
|
+
for (const [k, v] of Object.entries(headers)) res.setHeader(k, v);
|
|
60
|
+
res.end(body);
|
|
61
|
+
};
|
|
62
|
+
const json = (res, status, obj, headers) => send(res, status, 'application/json; charset=utf-8', JSON.stringify(obj), headers);
|
|
63
|
+
|
|
64
|
+
return async function lxrayAuditHandler(req, res, next) {
|
|
65
|
+
try {
|
|
66
|
+
if (!(await authorize(req))) return json(res, 403, { error: 'forbidden' });
|
|
67
|
+
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
const key = clientKey(req);
|
|
70
|
+
const recent = (hits.get(key) || []).filter((t) => now - t < rateLimitWindowMs);
|
|
71
|
+
if (recent.length >= rateLimitMax) {
|
|
72
|
+
hits.set(key, recent);
|
|
73
|
+
return json(res, 429, { error: 'rate_limited' }, { 'Retry-After': String(Math.ceil((rateLimitWindowMs - (now - recent[0])) / 1000)) });
|
|
74
|
+
}
|
|
75
|
+
recent.push(now);
|
|
76
|
+
hits.set(key, recent);
|
|
77
|
+
if (hits.size > 10000) for (const [k, v] of hits) if (!v.some((t) => now - t < rateLimitWindowMs)) hits.delete(k);
|
|
78
|
+
|
|
79
|
+
const lx = require('./index');
|
|
80
|
+
const url = new URL(req.url || '/', 'http://localhost');
|
|
81
|
+
const format = String(req.query?.format || url.searchParams.get('format') || defaultFormat).toLowerCase();
|
|
82
|
+
|
|
83
|
+
if (format === 'status') return json(res, 200, await lx.checkEnvironment(auditOptions));
|
|
84
|
+
if (!['html', 'json', 'md', 'txt', 'summary', 'metrics', 'check', 'archive'].includes(format)) return json(res, 400, { error: 'unknown_format' });
|
|
85
|
+
if (format === 'archive' && (!allowArchive || source !== 'audit')) return json(res, 403, { error: 'archive_disabled' });
|
|
86
|
+
if (busy) return json(res, 429, { error: 'audit_in_progress' }, { 'Retry-After': '15' });
|
|
87
|
+
|
|
88
|
+
busy = true;
|
|
89
|
+
try {
|
|
90
|
+
if (format === 'archive') {
|
|
91
|
+
const r = await lx.collect(auditOptions);
|
|
92
|
+
if (!r.archivePath) return json(res, 500, { error: 'no_archive' });
|
|
93
|
+
await new Promise((resolve, reject) => {
|
|
94
|
+
res.statusCode = 200;
|
|
95
|
+
res.setHeader('Content-Type', 'application/gzip');
|
|
96
|
+
res.setHeader('Content-Disposition', `attachment; filename="${path.basename(r.archivePath)}"`);
|
|
97
|
+
fs.createReadStream(r.archivePath).on('error', reject).on('end', resolve).pipe(res);
|
|
98
|
+
}).finally(() => fs.promises.rm(r.outdir, { recursive: true, force: true }).catch(() => {})); // our own temp folder only
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
const formats = ['summary', 'metrics', 'check'].includes(format) ? ['json'] : [format];
|
|
102
|
+
const result = source === 'latest'
|
|
103
|
+
? await lx.readLatest({ ...auditOptions, formats })
|
|
104
|
+
: await lx.audit({ ...auditOptions, formats, privileged: source === 'privileged' });
|
|
105
|
+
if (format === 'summary') return json(res, 200, result.summary);
|
|
106
|
+
if (format === 'metrics') return send(res, 200, 'text/plain; version=0.0.4; charset=utf-8', lx.toPrometheus(result));
|
|
107
|
+
if (format === 'check') {
|
|
108
|
+
const c = lx.evaluate(result, checkRules);
|
|
109
|
+
return json(res, checkHttpStatus && c.status === 'critical' ? 503 : 200, c);
|
|
110
|
+
}
|
|
111
|
+
if (format === 'json') return json(res, 200, result.report);
|
|
112
|
+
if (format === 'html') {
|
|
113
|
+
return send(res, 200, 'text/html; charset=utf-8', result.html,
|
|
114
|
+
{ 'Content-Security-Policy': "sandbox allow-same-origin; default-src 'none'; style-src 'unsafe-inline'; img-src data:; script-src 'unsafe-inline'" });
|
|
115
|
+
}
|
|
116
|
+
return send(res, 200, 'text/plain; charset=utf-8', format === 'md' ? result.markdown : result.text);
|
|
117
|
+
} finally {
|
|
118
|
+
busy = false;
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (typeof next === 'function') return next(error);
|
|
122
|
+
return json(res, 500, { error: 'audit_failed', message: error.message });
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { createAuditHandler };
|