@patrickdk77/office-defuse 0.1.0 → 0.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/README.md +278 -36
- package/dist/biff.d.ts +62 -0
- package/dist/biff.js +95 -0
- package/dist/cfb-writer.d.ts +25 -0
- package/dist/cfb-writer.js +314 -0
- package/dist/cfb.d.ts +58 -0
- package/dist/cfb.js +456 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +357 -0
- package/dist/contained.d.ts +46 -0
- package/dist/contained.js +152 -0
- package/dist/context.d.ts +140 -17
- package/dist/context.js +135 -37
- package/dist/crc32.d.ts +8 -2
- package/dist/crc32.js +44 -4
- package/dist/engine.d.ts +12 -1
- package/dist/engine.js +336 -42
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +27 -1
- package/dist/fields.d.ts +36 -0
- package/dist/fields.js +139 -0
- package/dist/findings.d.ts +2 -1
- package/dist/findings.js +44 -9
- package/dist/flat.d.ts +33 -0
- package/dist/flat.js +486 -0
- package/dist/formats.d.ts +7 -0
- package/dist/formats.js +5 -1
- package/dist/formulas.d.ts +27 -0
- package/dist/formulas.js +157 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +8 -1
- package/dist/index.mjs +1 -1
- package/dist/io.d.ts +62 -1
- package/dist/io.js +245 -1
- package/dist/links.d.ts +27 -0
- package/dist/links.js +106 -1
- package/dist/msg.d.ts +8 -0
- package/dist/msg.js +251 -0
- package/dist/objects.d.ts +45 -0
- package/dist/objects.js +204 -0
- package/dist/odf.d.ts +66 -2
- package/dist/odf.js +181 -64
- package/dist/offcrypto.d.ts +54 -0
- package/dist/offcrypto.js +647 -0
- package/dist/ole.d.ts +12 -0
- package/dist/ole.js +139 -0
- package/dist/oleobj.d.ts +85 -0
- package/dist/oleobj.js +215 -0
- package/dist/ooxml.d.ts +83 -2
- package/dist/ooxml.js +358 -145
- package/dist/package.d.ts +3 -0
- package/dist/package.js +21 -0
- package/dist/plan.d.ts +104 -0
- package/dist/plan.js +73 -0
- package/dist/plugins.d.ts +8 -0
- package/dist/plugins.js +60 -0
- package/dist/ppt.d.ts +8 -0
- package/dist/ppt.js +281 -0
- package/dist/rewrite-cfb.d.ts +14 -0
- package/dist/rewrite-cfb.js +52 -0
- package/dist/rewrite-rtf.d.ts +9 -0
- package/dist/rewrite-rtf.js +45 -0
- package/dist/rewrite-xml.d.ts +36 -0
- package/dist/rewrite-xml.js +341 -0
- package/dist/rewrite-zip.d.ts +8 -0
- package/dist/rewrite-zip.js +498 -0
- package/dist/rtf.d.ts +8 -0
- package/dist/rtf.js +712 -0
- package/dist/rtfcomp.d.ts +7 -0
- package/dist/rtfcomp.js +80 -0
- package/dist/score.js +1 -1
- package/dist/sniff.d.ts +5 -0
- package/dist/sniff.js +38 -0
- package/dist/types.d.ts +66 -2
- package/dist/types.js +33 -0
- package/dist/vsd.d.ts +13 -0
- package/dist/vsd.js +689 -0
- package/dist/word.d.ts +9 -0
- package/dist/word.js +194 -0
- package/dist/xls.d.ts +27 -0
- package/dist/xls.js +208 -0
- package/dist/xml.d.ts +30 -0
- package/dist/xml.js +45 -23
- package/dist/zip-writer.d.ts +4 -0
- package/dist/zip-writer.js +20 -7
- package/dist/zip.d.ts +9 -2
- package/dist/zip.js +61 -4
- package/package.json +6 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
4
|
+
if (k2 === undefined) k2 = k;
|
|
5
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
6
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
7
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
8
|
+
}
|
|
9
|
+
Object.defineProperty(o, k2, desc);
|
|
10
|
+
}) : (function(o, m, k, k2) {
|
|
11
|
+
if (k2 === undefined) k2 = k;
|
|
12
|
+
o[k2] = m[k];
|
|
13
|
+
}));
|
|
14
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
15
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
16
|
+
}) : function(o, v) {
|
|
17
|
+
o["default"] = v;
|
|
18
|
+
});
|
|
19
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
20
|
+
var ownKeys = function(o) {
|
|
21
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
22
|
+
var ar = [];
|
|
23
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
24
|
+
return ar;
|
|
25
|
+
};
|
|
26
|
+
return ownKeys(o);
|
|
27
|
+
};
|
|
28
|
+
return function (mod) {
|
|
29
|
+
if (mod && mod.__esModule) return mod;
|
|
30
|
+
var result = {};
|
|
31
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
32
|
+
__setModuleDefault(result, mod);
|
|
33
|
+
return result;
|
|
34
|
+
};
|
|
35
|
+
})();
|
|
36
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
37
|
+
exports.main = main;
|
|
38
|
+
const fs = __importStar(require("node:fs"));
|
|
39
|
+
const fsp = __importStar(require("node:fs/promises"));
|
|
40
|
+
const path = __importStar(require("node:path"));
|
|
41
|
+
const promises_1 = require("node:stream/promises");
|
|
42
|
+
const node_url_1 = require("node:url");
|
|
43
|
+
const engine_1 = require("./engine");
|
|
44
|
+
const errors_1 = require("./errors");
|
|
45
|
+
const io_1 = require("./io");
|
|
46
|
+
const plugins_1 = require("./plugins");
|
|
47
|
+
const USAGE = `Usage:
|
|
48
|
+
office-defuse inspect <file> [options]
|
|
49
|
+
office-defuse defuse <in> <out> [options]
|
|
50
|
+
|
|
51
|
+
Options:
|
|
52
|
+
--password-file <path> read passwords from a file, one per line; OFFICE_DEFUSE_PASSWORD holds one
|
|
53
|
+
--plugin <module> load file plugins from a file or an installed package, repeatable
|
|
54
|
+
--config <module> load a whole options object, repeatable; the other options apply on top
|
|
55
|
+
--defuse-embedded-office defuse Office files inside the file with office-defuse and keep them
|
|
56
|
+
--limit <name>=<value> fileSize, entries, decompressedBytes, totalDecompressedBytes, xmlDepth,
|
|
57
|
+
xmlTokenSize, xmlEntityDepth, xmlEntityExpansions, xmlEntitySize, rtfDepth,
|
|
58
|
+
nestingDepth, timeMs; sizes accept kb, mb, gb
|
|
59
|
+
--json print the result as JSON
|
|
60
|
+
|
|
61
|
+
Use - for stdin or stdout.
|
|
62
|
+
Exit codes: 0 clean, 1 stripped or strippable, 2 rejected, 3 usage or I/O error.`;
|
|
63
|
+
class UsageError extends Error {
|
|
64
|
+
}
|
|
65
|
+
const SIZES = new Set(['fileSize', 'decompressedBytes', 'totalDecompressedBytes']);
|
|
66
|
+
const COUNTS = new Set(['entries', 'xmlDepth', 'xmlTokenSize', 'xmlEntityDepth', 'xmlEntityExpansions', 'xmlEntitySize', 'rtfDepth', 'nestingDepth', 'timeMs']);
|
|
67
|
+
function parseSize(v) {
|
|
68
|
+
const m = /^(\d+(?:\.\d+)?)\s*(b|kb|k|mb|m|gb|g)?$/i.exec(v.trim());
|
|
69
|
+
if (!m)
|
|
70
|
+
throw new UsageError(`Bad size "${v}"`);
|
|
71
|
+
const mult = { b: 1, k: 1024, kb: 1024, m: 1024 ** 2, mb: 1024 ** 2, g: 1024 ** 3, gb: 1024 ** 3 };
|
|
72
|
+
return Math.round(Number(m[1]) * mult[(m[2] ?? 'b').toLowerCase()]);
|
|
73
|
+
}
|
|
74
|
+
// A real dynamic import. TypeScript would compile import() to require() for CommonJS output,
|
|
75
|
+
// and require() cannot load ES modules or file URLs.
|
|
76
|
+
const dynamicImport = new Function('specifier', 'return import(specifier)');
|
|
77
|
+
/** Reads `key` from `v` the way `v?.[key]` does, for a value whose shape is not known. */
|
|
78
|
+
function prop(v, key) {
|
|
79
|
+
return (typeof v === 'object' && v !== null) || typeof v === 'function' ? v[key] : undefined;
|
|
80
|
+
}
|
|
81
|
+
const isObject = (v) => typeof v === 'object' && v !== null;
|
|
82
|
+
async function loadModule(spec) {
|
|
83
|
+
// A bare name ending in .js can be a file in the working directory or a package with that name. The file wins.
|
|
84
|
+
const looksLikePath = spec.startsWith('.') || path.isAbsolute(spec) || (/\.(c|m)?js$/.test(spec) && fs.statSync(spec, { throwIfNoEntry: false })?.isFile() === true);
|
|
85
|
+
let resolved;
|
|
86
|
+
if (looksLikePath)
|
|
87
|
+
resolved = path.resolve(process.cwd(), spec);
|
|
88
|
+
else {
|
|
89
|
+
try {
|
|
90
|
+
resolved = require.resolve(spec, { paths: [process.cwd()] });
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
// require.resolve applies only the "require" condition, so a package that exports only "import" ends up here.
|
|
94
|
+
if (e.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED')
|
|
95
|
+
throw e;
|
|
96
|
+
const name = spec
|
|
97
|
+
.split('/')
|
|
98
|
+
.slice(0, spec.startsWith('@') ? 2 : 1)
|
|
99
|
+
.join('/');
|
|
100
|
+
const subpath = `.${spec.slice(name.length)}`;
|
|
101
|
+
for (let dir = process.cwd(); resolved === undefined; dir = path.dirname(dir)) {
|
|
102
|
+
const pkg = path.join(dir, 'node_modules', name);
|
|
103
|
+
if (fs.existsSync(path.join(pkg, 'package.json'))) {
|
|
104
|
+
const exp = JSON.parse(fs.readFileSync(path.join(pkg, 'package.json'), 'utf8')).exports;
|
|
105
|
+
const isMap = isObject(exp) && Object.keys(exp).some(k => k.startsWith('.'));
|
|
106
|
+
let target;
|
|
107
|
+
let match;
|
|
108
|
+
if (!isMap)
|
|
109
|
+
target = subpath === '.' ? exp : undefined;
|
|
110
|
+
else if (Object.hasOwn(exp, subpath) && !subpath.includes('*'))
|
|
111
|
+
target = exp[subpath];
|
|
112
|
+
else {
|
|
113
|
+
// A pattern key holds one "*". Node prefers the longest text before the "*", then the longest key, and puts
|
|
114
|
+
// what the "*" matched into the target.
|
|
115
|
+
let best = '';
|
|
116
|
+
for (const k of Object.keys(exp)) {
|
|
117
|
+
const star = k.indexOf('*');
|
|
118
|
+
const trailer = k.slice(star + 1);
|
|
119
|
+
if (star < 0 || trailer.includes('*') || !subpath.startsWith(k.slice(0, star)) || subpath.length === star)
|
|
120
|
+
continue;
|
|
121
|
+
if (trailer && (!subpath.endsWith(trailer) || subpath.length < k.length))
|
|
122
|
+
continue;
|
|
123
|
+
if (!best || star > best.indexOf('*') || (star === best.indexOf('*') && k.length > best.length))
|
|
124
|
+
best = k;
|
|
125
|
+
}
|
|
126
|
+
if (best) {
|
|
127
|
+
target = exp[best];
|
|
128
|
+
match = subpath.slice(best.indexOf('*'), subpath.length - (best.length - best.indexOf('*') - 1));
|
|
129
|
+
// Node refuses a match that would step outside the pattern's directory.
|
|
130
|
+
if (match.split(/[/\\]/).some(s => s === '' || s === '.' || s === '..' || s.toLowerCase() === 'node_modules'))
|
|
131
|
+
throw e;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
// Node takes the first condition it supports, in the order the package lists them.
|
|
135
|
+
while (isObject(target) && !Array.isArray(target))
|
|
136
|
+
target = target[Object.keys(target).find(k => k === 'node' || k === 'import' || k === 'default') ?? ''];
|
|
137
|
+
if (typeof target !== 'string')
|
|
138
|
+
throw e;
|
|
139
|
+
resolved = path.resolve(pkg, match === undefined ? target : target.replaceAll('*', match));
|
|
140
|
+
}
|
|
141
|
+
else if (path.dirname(dir) === dir)
|
|
142
|
+
throw e;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return dynamicImport((0, node_url_1.pathToFileURL)(resolved).href);
|
|
147
|
+
}
|
|
148
|
+
function pluginsFrom(mod) {
|
|
149
|
+
// import() gives a CommonJS module a default export holding module.exports, so the named exports come first.
|
|
150
|
+
const value = prop(mod, 'plugins') ?? prop(prop(mod, 'default'), 'plugins') ?? prop(mod, 'plugin') ?? prop(prop(mod, 'default'), 'plugin') ?? prop(mod, 'default');
|
|
151
|
+
const list = Array.isArray(value) ? value : [value];
|
|
152
|
+
for (const p of list)
|
|
153
|
+
if (!p || prop(p, 'kind') !== 'file')
|
|
154
|
+
throw new UsageError('A plugin module must export plugins with kind "file"');
|
|
155
|
+
// The loop above checked each entry's kind, which is as far as a plugin's shape can be checked here.
|
|
156
|
+
return list;
|
|
157
|
+
}
|
|
158
|
+
async function parse(argv) {
|
|
159
|
+
const [command, ...rest] = argv;
|
|
160
|
+
if (command !== 'inspect' && command !== 'defuse')
|
|
161
|
+
throw new UsageError(command ? `Unknown command "${command}"` : 'No command');
|
|
162
|
+
const positional = [];
|
|
163
|
+
// Every --config module goes in first and the flags apply on top, wherever they sit on the command line.
|
|
164
|
+
const options = {};
|
|
165
|
+
const ordered = [];
|
|
166
|
+
const limits = {};
|
|
167
|
+
let password = process.env.OFFICE_DEFUSE_PASSWORD;
|
|
168
|
+
let json = false;
|
|
169
|
+
for (let i = 0; i < rest.length; i++) {
|
|
170
|
+
const a = rest[i];
|
|
171
|
+
const next = () => {
|
|
172
|
+
const v = rest[++i];
|
|
173
|
+
if (v === undefined)
|
|
174
|
+
throw new UsageError(`${a} needs a value`);
|
|
175
|
+
return v;
|
|
176
|
+
};
|
|
177
|
+
switch (a) {
|
|
178
|
+
case '--password-file':
|
|
179
|
+
// A blank line holds no password, so it adds nothing to the list.
|
|
180
|
+
password = (await fsp.readFile(next(), 'utf8'))
|
|
181
|
+
.split('\n')
|
|
182
|
+
.map(line => line.replace(/\r$/, ''))
|
|
183
|
+
.filter(line => line !== '');
|
|
184
|
+
break;
|
|
185
|
+
case '--plugin':
|
|
186
|
+
ordered.push(...pluginsFrom(await loadModule(next())));
|
|
187
|
+
break;
|
|
188
|
+
case '--config': {
|
|
189
|
+
const mod = await loadModule(next());
|
|
190
|
+
// The module's shape is the caller's to get right, as OfficeOptions documents it.
|
|
191
|
+
const cfg = (prop(mod, 'default') ?? mod);
|
|
192
|
+
// Modules combine: plugin lists join in order and limits merge. For any other option the later module wins.
|
|
193
|
+
Object.assign(options, cfg, {
|
|
194
|
+
filePlugins: [...(options.filePlugins ?? []), ...(cfg.filePlugins ?? [])],
|
|
195
|
+
limits: { ...options.limits, ...cfg.limits },
|
|
196
|
+
});
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
case '--defuse-embedded-office':
|
|
200
|
+
ordered.push((0, plugins_1.officePlugin)());
|
|
201
|
+
break;
|
|
202
|
+
case '--limit': {
|
|
203
|
+
const [name, value] = next().split('=');
|
|
204
|
+
if (value === undefined)
|
|
205
|
+
throw new UsageError('--limit expects name=value');
|
|
206
|
+
if (SIZES.has(name))
|
|
207
|
+
limits[name] = parseSize(value);
|
|
208
|
+
else if (COUNTS.has(name)) {
|
|
209
|
+
// Number('abc') is NaN, and no comparison with NaN is true, so the limit would never apply.
|
|
210
|
+
if (!/^\d+$/.test(value.trim()))
|
|
211
|
+
throw new UsageError(`Bad value for ${name}: "${value}"`);
|
|
212
|
+
limits[name] = Number(value);
|
|
213
|
+
}
|
|
214
|
+
else
|
|
215
|
+
throw new UsageError(`Unknown limit "${name}"`);
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
case '--json':
|
|
219
|
+
json = true;
|
|
220
|
+
break;
|
|
221
|
+
default:
|
|
222
|
+
if (a === '--password' || a.startsWith('--password='))
|
|
223
|
+
throw new UsageError('Pass the password with --password-file or OFFICE_DEFUSE_PASSWORD, not on the command line');
|
|
224
|
+
// What follows "=" can be a secret typed in the wrong place, and stderr often ends up in a log.
|
|
225
|
+
if (a.startsWith('--'))
|
|
226
|
+
throw new UsageError(`Unknown option ${a.replace(/=.*/s, '=...')}`);
|
|
227
|
+
positional.push(a);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (ordered.length)
|
|
231
|
+
options.filePlugins = [...(options.filePlugins ?? []), ...ordered];
|
|
232
|
+
if (Object.keys(limits).length)
|
|
233
|
+
options.limits = { ...(options.limits ?? {}), ...limits };
|
|
234
|
+
if (password !== undefined)
|
|
235
|
+
options.password = password;
|
|
236
|
+
return { command, positional, options, json };
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* The input as a source. stdin is copied to a temporary file first. The copy stops one byte past `fileSize`, so the
|
|
240
|
+
* engine rejects the upload as too large without the rest being read, and at the deadline, where the source then
|
|
241
|
+
* fails the run for time.
|
|
242
|
+
*/
|
|
243
|
+
async function inputSource(p, tempDir, fileSize, deadline) {
|
|
244
|
+
if (p !== '-') {
|
|
245
|
+
return {
|
|
246
|
+
source: (0, io_1.fileSource)(p),
|
|
247
|
+
cleanup: async () => {
|
|
248
|
+
// The caller's own file stays.
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const temp = new io_1.TempDir(tempDir);
|
|
253
|
+
try {
|
|
254
|
+
const file = await temp.file('.office');
|
|
255
|
+
let room = (fileSize ?? Number.POSITIVE_INFINITY) + 1;
|
|
256
|
+
try {
|
|
257
|
+
await (0, promises_1.pipeline)(process.stdin, async function* (chunks) {
|
|
258
|
+
for await (const c of chunks) {
|
|
259
|
+
yield c.subarray(0, room);
|
|
260
|
+
room -= c.length;
|
|
261
|
+
if (room <= 0)
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
}, fs.createWriteStream(file), { signal: deadline === undefined ? undefined : AbortSignal.timeout(Math.max(0, deadline - Date.now())) });
|
|
265
|
+
}
|
|
266
|
+
catch (e) {
|
|
267
|
+
if (e.name !== 'AbortError')
|
|
268
|
+
throw e;
|
|
269
|
+
const late = () => Promise.reject(new errors_1.TimeLimitError('Time limit exceeded'));
|
|
270
|
+
return { source: { size: late, read: late }, cleanup: () => temp.cleanup() };
|
|
271
|
+
}
|
|
272
|
+
return { source: (0, io_1.fileSource)(file), cleanup: () => temp.cleanup() };
|
|
273
|
+
}
|
|
274
|
+
catch (e) {
|
|
275
|
+
await temp.cleanup();
|
|
276
|
+
throw e;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/** Writes a control character as a JSON escape, since text from the file could otherwise drive the terminal. */
|
|
280
|
+
const escaped = (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
281
|
+
function report(label, i) {
|
|
282
|
+
const lines = [`${label}: ${i.status}, risk ${i.risk}${i.score === null ? '' : ` (score ${i.score})`}, ${i.format ? i.format.toUpperCase() : '?'}`];
|
|
283
|
+
for (const f of i.findings)
|
|
284
|
+
lines.push(` ${f.action.padEnd(6)} ${f.category}/${f.detail}${f.location ? ` [${f.location}]` : ''}: ${f.description}`);
|
|
285
|
+
// A location can hold a part name, a field code or a link from the file. A line break in one would print a line of
|
|
286
|
+
// its own.
|
|
287
|
+
return lines.map(l => l.replace(/\p{Cc}/gu, escaped)).join('\n');
|
|
288
|
+
}
|
|
289
|
+
async function main(argv) {
|
|
290
|
+
let parsed;
|
|
291
|
+
try {
|
|
292
|
+
parsed = await parse(argv);
|
|
293
|
+
}
|
|
294
|
+
catch (e) {
|
|
295
|
+
process.stderr.write(`${e.message}\n\n${USAGE}\n`);
|
|
296
|
+
return 3;
|
|
297
|
+
}
|
|
298
|
+
const { command, positional, options, json } = parsed;
|
|
299
|
+
try {
|
|
300
|
+
if (command === 'inspect' && positional.length !== 1)
|
|
301
|
+
throw new UsageError('inspect takes one file');
|
|
302
|
+
if (command === 'defuse' && positional.length !== 2)
|
|
303
|
+
throw new UsageError('defuse takes an input and an output');
|
|
304
|
+
const toStdout = command === 'defuse' && positional[1] === '-';
|
|
305
|
+
if (command === 'defuse' && positional[0] !== '-' && !toStdout) {
|
|
306
|
+
// A failed write deletes the partial output, which here would be the only copy of the input.
|
|
307
|
+
const [a, b] = await Promise.all([fsp.stat(positional[0]), fsp.stat(positional[1]).catch(() => undefined)]);
|
|
308
|
+
if (b && a.dev === b.dev && a.ino === b.ino)
|
|
309
|
+
throw new UsageError('The input and the output are the same file');
|
|
310
|
+
}
|
|
311
|
+
// Reading stdin counts toward the time limit, so the run gets what is left of it.
|
|
312
|
+
const deadline = options.limits?.timeMs === undefined ? undefined : Date.now() + options.limits.timeMs;
|
|
313
|
+
const input = await inputSource(positional[0], options.tempDir, options.limits?.fileSize, deadline);
|
|
314
|
+
const runOptions = deadline === undefined ? options : { ...options, limits: { ...options.limits, timeMs: deadline - Date.now() } };
|
|
315
|
+
let text;
|
|
316
|
+
let code;
|
|
317
|
+
try {
|
|
318
|
+
if (command === 'inspect') {
|
|
319
|
+
const r = await (0, engine_1.inspectOfficeSource)(input.source, runOptions);
|
|
320
|
+
text = json ? JSON.stringify(r, null, 2) : report('inspection', r);
|
|
321
|
+
code = r.status === 'clean' ? 0 : r.status === 'strippable' ? 1 : 2;
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
const r = await (0, engine_1.disarmOfficeSource)(input.source, toStdout ? (0, io_1.writableSink)(process.stdout) : (0, io_1.fileSink)(positional[1]), runOptions);
|
|
325
|
+
text = json ? JSON.stringify(r, null, 2) : [`result: ${r.status}`, report('before', r.before), ...(r.after && r.status === 'defused' ? [report('after', r.after)] : [])].join('\n');
|
|
326
|
+
code = r.status === 'clean' ? 0 : r.status === 'defused' ? 1 : 2;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
finally {
|
|
330
|
+
await input.source.close?.();
|
|
331
|
+
await input.cleanup();
|
|
332
|
+
}
|
|
333
|
+
// JSON.stringify escapes C0 controls but not DEL or the C1 range.
|
|
334
|
+
if (json)
|
|
335
|
+
text = text.replace(/[\u007f-\u009f]/g, escaped);
|
|
336
|
+
// The report shares stdout only when the file goes elsewhere. A report nobody can read is an I/O error.
|
|
337
|
+
const out = toStdout ? process.stderr : process.stdout;
|
|
338
|
+
await new Promise((resolve, reject) => out.write(`${text}\n`, e => (e ? reject(e) : resolve())));
|
|
339
|
+
return code;
|
|
340
|
+
}
|
|
341
|
+
catch (e) {
|
|
342
|
+
process.stderr.write(`${e instanceof UsageError ? `${e.message}\n\n${USAGE}` : `Error: ${e.message}`}\n`);
|
|
343
|
+
return 3;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (require.main === module) {
|
|
347
|
+
// main() learns of a failed write from its callback. Node emits the failure as an 'error' event as well, which
|
|
348
|
+
// with no listener would end the process with exit code 1.
|
|
349
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
350
|
+
stream.on('error', () => {
|
|
351
|
+
process.exitCode = 3;
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
main(process.argv.slice(2)).then(code => {
|
|
355
|
+
process.exitCode = code;
|
|
356
|
+
});
|
|
357
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { RunContext, RunState } from './context';
|
|
2
|
+
import { SpillSink } from './io';
|
|
3
|
+
import { type DefuseFinding, type OfficeOptions, type PluginContext } from './types';
|
|
4
|
+
/** The key under which office-defuse hands its run's options to a plugin. No other package can name it. */
|
|
5
|
+
export declare const RUN_OPTIONS: unique symbol;
|
|
6
|
+
/** A plugin context as office-defuse makes it. */
|
|
7
|
+
export type RunPluginContext = PluginContext & {
|
|
8
|
+
[RUN_OPTIONS]?: OfficeOptions;
|
|
9
|
+
};
|
|
10
|
+
/** What the plugins decided about a file inside the file. Undefined from `decideContained` means no plugin took it. */
|
|
11
|
+
export interface ContainedDecision {
|
|
12
|
+
keep: boolean;
|
|
13
|
+
/** The bytes a plugin kept in place of the file's own. */
|
|
14
|
+
replacement?: SpillSink;
|
|
15
|
+
}
|
|
16
|
+
/** A file found inside the file, as the format rules hand it over. */
|
|
17
|
+
export interface InnerFile {
|
|
18
|
+
name?: string;
|
|
19
|
+
/** The MIME type the container gives the file, such as a part's content type. */
|
|
20
|
+
declaredType?: string;
|
|
21
|
+
location: string;
|
|
22
|
+
/** The file's bytes, in order. */
|
|
23
|
+
chunks(): AsyncIterable<Uint8Array>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Adds the findings a plugin reported from inside a file, labeled with the file's name and place. A reject inside the
|
|
27
|
+
* file means the file goes, not the one that holds it, so it is recorded here as strip.
|
|
28
|
+
*/
|
|
29
|
+
export declare function pushContained(ctx: RunContext, found: DefuseFinding[] | undefined, location: string, name: string | undefined): void;
|
|
30
|
+
/**
|
|
31
|
+
* Shows a file found inside the file to the plugins, as pdf-defuse shows an attached file. The first plugin that
|
|
32
|
+
* accepts it decides: 'passed' and 'scrubbed' keep it, with the bytes the plugin wrote when it wrote any, and
|
|
33
|
+
* 'removed', a failure or a scrub that wrote nothing remove it. Its findings come into this run's report. When no
|
|
34
|
+
* plugin accepts the file, this returns undefined and the rules the file gets without plugins decide.
|
|
35
|
+
*
|
|
36
|
+
* In the run that checks an output, the plugins are not asked again. A file whose MD5 matches what a plugin kept in
|
|
37
|
+
* the upload's run is taken as kept, with the findings the plugin reported for its output.
|
|
38
|
+
*/
|
|
39
|
+
export declare function decideContained(ctx: RunContext, inner: InnerFile): Promise<ContainedDecision | undefined>;
|
|
40
|
+
/**
|
|
41
|
+
* The rule a file gets for being there, such as EMBEDDED/OLE_OBJECT, applies when no plugin took the file. A plugin
|
|
42
|
+
* that kept the file turns those findings to info, since the content stays.
|
|
43
|
+
*/
|
|
44
|
+
export declare function presence(decision: ContainedDecision | undefined): 'info' | undefined;
|
|
45
|
+
/** Bytes in a spill sink the run holds until it ends, as the rewrite takes a plugin's output. */
|
|
46
|
+
export declare function spillOf(run: RunState, bytes: Uint8Array): Promise<SpillSink>;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RUN_OPTIONS = void 0;
|
|
4
|
+
exports.pushContained = pushContained;
|
|
5
|
+
exports.decideContained = decideContained;
|
|
6
|
+
exports.presence = presence;
|
|
7
|
+
exports.spillOf = spillOf;
|
|
8
|
+
const errors_1 = require("./errors");
|
|
9
|
+
const io_1 = require("./io");
|
|
10
|
+
const sniff_1 = require("./sniff");
|
|
11
|
+
const types_1 = require("./types");
|
|
12
|
+
/** The key under which office-defuse hands its run's options to a plugin. No other package can name it. */
|
|
13
|
+
exports.RUN_OPTIONS = Symbol('office-defuse run options');
|
|
14
|
+
/**
|
|
15
|
+
* Throws on an error a plugin threw that stops the whole tree. An I/O error fails this run as one of its own would,
|
|
16
|
+
* so its cause goes up.
|
|
17
|
+
*/
|
|
18
|
+
function passOn(run, e) {
|
|
19
|
+
const code = (0, errors_1.stopsTree)(e);
|
|
20
|
+
if (code === 'DEFUSE_IO') {
|
|
21
|
+
const cause = e.cause ?? e;
|
|
22
|
+
run.temp.ioError ??= cause;
|
|
23
|
+
throw cause;
|
|
24
|
+
}
|
|
25
|
+
if (code === 'DEFUSE_LIMIT')
|
|
26
|
+
throw e;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Adds the findings a plugin reported from inside a file, labeled with the file's name and place. A reject inside the
|
|
30
|
+
* file means the file goes, not the one that holds it, so it is recorded here as strip.
|
|
31
|
+
*/
|
|
32
|
+
function pushContained(ctx, found, location, name) {
|
|
33
|
+
const label = name || 'unnamed file';
|
|
34
|
+
ctx.push((found ?? []).map(f => ({
|
|
35
|
+
...f,
|
|
36
|
+
action: f.action === 'reject' ? 'strip' : f.action,
|
|
37
|
+
location: f.location ? `${location} > ${f.location}` : location,
|
|
38
|
+
data: f.data && { ...f.data },
|
|
39
|
+
attachment: f.attachment ? `${label} > ${f.attachment}` : label,
|
|
40
|
+
})));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Shows a file found inside the file to the plugins, as pdf-defuse shows an attached file. The first plugin that
|
|
44
|
+
* accepts it decides: 'passed' and 'scrubbed' keep it, with the bytes the plugin wrote when it wrote any, and
|
|
45
|
+
* 'removed', a failure or a scrub that wrote nothing remove it. Its findings come into this run's report. When no
|
|
46
|
+
* plugin accepts the file, this returns undefined and the rules the file gets without plugins decide.
|
|
47
|
+
*
|
|
48
|
+
* In the run that checks an output, the plugins are not asked again. A file whose MD5 matches what a plugin kept in
|
|
49
|
+
* the upload's run is taken as kept, with the findings the plugin reported for its output.
|
|
50
|
+
*/
|
|
51
|
+
async function decideContained(ctx, inner) {
|
|
52
|
+
const run = ctx.run;
|
|
53
|
+
const plugins = run.options.filePlugins ?? [];
|
|
54
|
+
if (!plugins.length && !run.verify?.size)
|
|
55
|
+
return undefined;
|
|
56
|
+
const decoded = new io_1.SpillSink(run.temp, run.threshold);
|
|
57
|
+
try {
|
|
58
|
+
for await (const c of inner.chunks())
|
|
59
|
+
await decoded.write(c);
|
|
60
|
+
await decoded.close();
|
|
61
|
+
const hash = decoded.digest();
|
|
62
|
+
const name = inner.name;
|
|
63
|
+
const expected = run.verify?.get(hash);
|
|
64
|
+
if (expected) {
|
|
65
|
+
ctx.report(types_1.OfficeCategory.Embedded, expected.result === 'passed' ? types_1.OfficeDetail.PluginPassed : types_1.OfficeDetail.PluginScrubbed, inner.location, { plugin: expected.plugin, name: name ?? '' });
|
|
66
|
+
pushContained(ctx, expected.findings, inner.location, name);
|
|
67
|
+
return { keep: true };
|
|
68
|
+
}
|
|
69
|
+
if (!plugins.length)
|
|
70
|
+
return undefined;
|
|
71
|
+
const source = decoded.source();
|
|
72
|
+
try {
|
|
73
|
+
const head = await source.read(0, Math.min(1024, decoded.length));
|
|
74
|
+
const file = { name, declaredType: inner.declaredType, sniffedType: (0, sniff_1.sniffType)(head), size: decoded.length, location: inner.location, depth: run.depth + 1, source };
|
|
75
|
+
const context = { depth: file.depth, deadline: run.deadline, [exports.RUN_OPTIONS]: run.options };
|
|
76
|
+
for (const plugin of plugins) {
|
|
77
|
+
try {
|
|
78
|
+
if (!(await plugin.accepts(file)))
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
passOn(run, e);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
// Copies a plugin keeps wait in memory until the rewrite, so all of them together stay under one threshold.
|
|
86
|
+
const out = new io_1.SpillSink(run.temp, Math.max(0, run.threshold - run.retained));
|
|
87
|
+
const data = { plugin: plugin.name, name: name ?? '' };
|
|
88
|
+
try {
|
|
89
|
+
const answer = await plugin.process(file, out, context);
|
|
90
|
+
const r = typeof answer === 'string' ? { result: answer } : (answer ?? {});
|
|
91
|
+
await out.close();
|
|
92
|
+
let keep = false;
|
|
93
|
+
if (r.result === 'passed') {
|
|
94
|
+
ctx.report(types_1.OfficeCategory.Embedded, types_1.OfficeDetail.PluginPassed, inner.location, data);
|
|
95
|
+
// Bytes the plugin wrote are the ones kept, such as a document rewritten with nothing removed. A container
|
|
96
|
+
// the rewrite cannot change keeps the file as it was, which the plugin passed too.
|
|
97
|
+
const passed = { result: 'passed', plugin: plugin.name, findings: r.outputFindings };
|
|
98
|
+
run.kept.set(hash, passed);
|
|
99
|
+
if (out.length > 0)
|
|
100
|
+
run.kept.set(out.digest(), passed);
|
|
101
|
+
keep = true;
|
|
102
|
+
}
|
|
103
|
+
else if (r.result === 'scrubbed' && out.length > 0) {
|
|
104
|
+
ctx.report(types_1.OfficeCategory.Embedded, types_1.OfficeDetail.PluginScrubbed, inner.location, data);
|
|
105
|
+
run.kept.set(out.digest(), { result: 'scrubbed', plugin: plugin.name, findings: r.outputFindings });
|
|
106
|
+
keep = true;
|
|
107
|
+
}
|
|
108
|
+
else
|
|
109
|
+
ctx.removal(types_1.OfficeCategory.Embedded, r.result === 'removed' ? types_1.OfficeDetail.PluginRemoved : types_1.OfficeDetail.PluginFailed, inner.location, data);
|
|
110
|
+
pushContained(ctx, r.findings, inner.location, name);
|
|
111
|
+
const replacement = keep && out.length > 0 ? out : undefined;
|
|
112
|
+
if (replacement) {
|
|
113
|
+
if (!replacement.spilled)
|
|
114
|
+
run.retained += replacement.length;
|
|
115
|
+
run.held.push(replacement);
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
await out.dispose();
|
|
119
|
+
return { keep, replacement };
|
|
120
|
+
}
|
|
121
|
+
catch (e) {
|
|
122
|
+
await out.dispose();
|
|
123
|
+
passOn(run, e);
|
|
124
|
+
ctx.removal(types_1.OfficeCategory.Embedded, types_1.OfficeDetail.PluginFailed, inner.location, data);
|
|
125
|
+
return { keep: false };
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
await source.close?.();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
await decoded.dispose();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The rule a file gets for being there, such as EMBEDDED/OLE_OBJECT, applies when no plugin took the file. A plugin
|
|
140
|
+
* that kept the file turns those findings to info, since the content stays.
|
|
141
|
+
*/
|
|
142
|
+
function presence(decision) {
|
|
143
|
+
return decision?.keep ? 'info' : undefined;
|
|
144
|
+
}
|
|
145
|
+
/** Bytes in a spill sink the run holds until it ends, as the rewrite takes a plugin's output. */
|
|
146
|
+
async function spillOf(run, bytes) {
|
|
147
|
+
const sink = new io_1.SpillSink(run.temp, run.threshold);
|
|
148
|
+
run.held.push(sink);
|
|
149
|
+
await sink.write(bytes);
|
|
150
|
+
await sink.close();
|
|
151
|
+
return sink;
|
|
152
|
+
}
|