-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
376 lines (321 loc) · 9.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
const fs = require("fs");
const net = require("net");
const child_process = require("child_process");
const vm = require("vm");
const dgram = require("dgram");
const dns = require("dns");
const worker_threads = require("worker_threads");
const PRIV_ALL = "*";
const PRIV_FILESYSTEM = "fs";
const PRIV_NETWORK = "net";
const PRIV_CHILD_PROCESS = "child_process";
const PRIV_VM = "vm";
const PRIV_DGRAM = "dgram";
const PRIV_DNS = "dns";
const PRIV_WORKER_THREADS = "worker_threads";
const PRIV_PROCESS = "process";
const { Worker } = require("worker_threads");
// These are the controlled modules
const controlledModules = {
fs: fs,
net: net,
child_process: child_process,
vm: vm,
dgram: dgram,
dns: dns,
worker_threads: worker_threads,
process: process,
};
// We only override some of the function on 'process'
const processKeysToOverride = [
"binding",
"abort",
"exit",
"chdir",
"dlopen",
"initgroups",
"kill",
"setegid",
"seteuid",
"setgid",
"setgroups",
"umask",
];
// This is a flag to ensure it's only initialised once
let byrnesInitialised = false;
const allowCache = {};
const defaultAllowList = [
{
// This is to allow 'require()' to work from anywhere
module: "internal/modules/cjs/loader.js",
privileges: [PRIV_FILESYSTEM],
alwaysAllow: true,
},
{
// This is to allow 'new Buffer()' to work from anywhere
module: "internal/util.js",
privileges: [PRIV_VM],
alwaysAllow: true,
},
{
// This is to allow this library to access everything (as it will always be in the call stack)
module: [__dirname, "node_modules/byrnesjs/"],
privileges: PRIV_ALL,
},
{
// Allow anonymous blocks and internal NodeJS code
module: ["<anonymous>", "internal/"],
privileges: PRIV_ALL,
},
{
// This is the set of internal libraries which access the filesystem
module: [
"fs.js",
"events.js",
"_stream_writable.js",
"timers.js",
"net.js",
],
privileges: [PRIV_FILESYSTEM],
},
{
// This is the set of internal libararies which access the network
module: ["tty.js", "http.js", "_http_server.js"],
privileges: [PRIV_NETWORK],
},
{
// This is the set of internal libararies which access the network
module: "net.js",
privileges: [PRIV_DNS],
},
{
module: "child_process.js",
privileges: [PRIV_CHILD_PROCESS, PRIV_NETWORK],
},
];
// This pattern is used to parse the stack entries
const stackEntryPattern = /^\s+at\s[^(]+\((([^:)]+):\d*:?\d*)\)$/gm;
const nodeModulePattern = /^node_modules\/[^\/]+$/;
module.exports = {
PRIV_ALL,
PRIV_FILESYSTEM,
PRIV_NETWORK,
PRIV_CHILD_PROCESS,
PRIV_VM,
PRIV_DGRAM,
PRIV_DNS,
PRIV_WORKER_THREADS,
PRIV_PROCESS,
init: (options) => {
// Prevent the library being initialised multiple times
if (byrnesInitialised) {
throw new Error("ByrnesJS is already initialised");
}
byrnesInitialised = true;
// Merge the supplied allow list
const allows = [...defaultAllowList];
if (options.allow) {
allows.push(...options.allow);
}
if (!options.rootDir) {
throw new Error("rootDir is required");
}
// And the rest of the options
const opts = {
rootDir: options.rootDir,
logOnly: options.logOnly || false,
logger: options.logger || console,
logOnlyStack: options.logOnlyStack || false,
violationLogger:
options.violationLogger && typeof options.violationLogger == "function"
? options.violationLogger
: console.error,
};
// Refactor the allow list into something more useful to check against
const allowByOperation = {};
allows.forEach((allow) => {
let privileges = Array.isArray(allow.privileges)
? allow.privileges
: [allow.privileges];
if (privileges.includes("*")) {
privileges = Object.keys(controlledModules);
}
privileges.forEach((privilege) => {
let newAllows;
if (Array.isArray(allow.module)) {
newAllows = allow.module.map((path) => ({
path: path,
alwaysAllow: !!allow.alwaysAllow,
}));
} else {
newAllows = [
{ path: allow.module, alwaysAllow: !!allow.alwaysAllow },
];
}
// If it's a 'node_module' allow and doesn't have a slash then add one.
newAllows.forEach((allow) => {
if(allow.path.match(nodeModulePattern)) {
allow.path += "/";
}
});
if (allowByOperation[privilege]) {
allowByOperation[privilege].push(...newAllows);
} else {
allowByOperation[privilege] = newAllows;
}
});
});
// Initialise the logging
// This is done through a worker so that it's in a different stack frame.
const loggingWorker = new Worker(`${__dirname}/logging.js`);
const loggingMessages = [];
// Unref the thread when it starts so that it doesn't hold the process open
loggingWorker.on("online", () => {
if (loggingMessages.length == 0) {
loggingWorker.unref();
}
});
loggingWorker.on("message", () => {
while (loggingMessages.length > 0) {
const message = loggingMessages.shift();
opts.violationLogger(message);
}
loggingWorker.unref();
});
function logIssue(message) {
// We ref() the worker to ensure that the message gets logged before the process quits.
loggingWorker.ref();
loggingMessages.push(message);
loggingWorker.postMessage(message);
}
// This function is called by the privileged function wrapper to do the actual check
function doFunctionCall(
privilegeId,
functionName,
actualFunc,
stackString,
thisArg,
args,
newTarget
) {
const stackMatches = [...stackString.matchAll(stackEntryPattern)];
for (let stackMatch of stackMatches) {
const stackEntry = stackMatch[2];
const allowed = checkAllowed(stackEntry, privilegeId);
if (!allowed) {
if (opts.logOnly) {
logIssue(
`ByrnesJS: Detected unexpected access to '${privilegeId}.${functionName}()' from '${stackEntry}'`
);
if (opts.logOnlyStack) {
logIssue(stackString);
}
// break;
} else {
const error = new Error(
`ByrnesJS: Access to '${privilegeId}.${functionName}()' is denied from '${stackEntry}'`
);
logIssue(error.message);
throw error;
}
} else {
if (allowed.alwaysAllow) {
if (newTarget) {
return new actualFunc(...args);
} else {
return actualFunc.apply(thisArg, args);
}
}
}
}
if (newTarget) {
return new actualFunc(...args);
} else {
return actualFunc.apply(thisArg, args);
}
}
// This checks a single stack entry for a certain operation
function checkAllowed(path, operation) {
if (path in allowCache) {
if (operation in allowCache[path]) {
return allowCache[path][operation];
}
} else {
allowCache[path] = {};
}
let stackEntry = path;
const nodeModulesRoot = stackEntry.lastIndexOf("node_modules");
if (nodeModulesRoot > -1) {
stackEntry = stackEntry.substring(nodeModulesRoot);
} else if (stackEntry.startsWith(opts.rootDir)) {
stackEntry = stackEntry.substring(opts.rootDir.length);
}
for (const allow of allowByOperation[operation]) {
if (stackEntry.startsWith(allow.path)) {
allowCache[path][operation] = { alwaysAllow: allow.alwaysAllow };
return allowCache[path][operation];
}
}
allowCache[path][operation] = false;
return false;
}
// This goes through each of the privileged modules and wraps all the functions within
for (const privilegeId in controlledModules) {
const privilegedModule = controlledModules[privilegeId];
let keys;
if (privilegeId === "process") {
// We will only override certain functions in process as it's so commonly used
keys = processKeysToOverride;
} else {
keys = [];
for (const key in privilegedModule) {
keys.push(key);
}
}
for (const key of keys) {
if (
privilegedModule.hasOwnProperty(key) &&
typeof privilegedModule[key] == "function"
) {
// If it's a function then we will wrap it with our access check code
const actualFunc = privilegedModule[key];
if (actualFunc.constructor.name === "AsyncFunction") {
privilegedModule[key] = async function () {
const stackString = new Error().stack;
return await doFunctionCall(
privilegeId,
key,
actualFunc,
stackString,
this,
Array.from(arguments),
new.target
);
};
} else {
privilegedModule[key] = function () {
const stackString = new Error().stack;
return doFunctionCall(
privilegeId,
key,
actualFunc,
stackString,
this,
Array.from(arguments),
new.target
);
};
}
// Copy across the prototype
privilegedModule[key].prototype = actualFunc.prototype;
// And any other properties. This ensures that `fs.realpath.native` and `fs.realpathSync.native` are still accessible
for (const name in actualFunc) {
if (actualFunc.hasOwnProperty(name)) {
privilegedModule[key][name] = actualFunc[name];
}
}
}
}
}
},
};