Skip to content

Commit

Permalink
module: protect against prototype mutation
Browse files Browse the repository at this point in the history
Ensures that mutating the `Object` prototype does not influence the
parsing of `package.json` files.

PR-URL: #44007
Reviewed-By: Geoffrey Booth <[email protected]>
  • Loading branch information
aduh95 authored and ruyadorno committed Aug 22, 2022
1 parent 4755ad5 commit 05802c2
Show file tree
Hide file tree
Showing 8 changed files with 96 additions and 15 deletions.
3 changes: 2 additions & 1 deletion lib/internal/modules/cjs/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const path = require('path');
const { pathToFileURL, fileURLToPath, URL } = require('internal/url');

const { getOptionValue } = require('internal/options');
const { setOwnProperty } = require('internal/util');
const userConditions = getOptionValue('--conditions');

let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
Expand Down Expand Up @@ -117,7 +118,7 @@ function makeRequireFunction(mod, redirects) {

resolve.paths = paths;

require.main = process.mainModule;
setOwnProperty(require, 'main', process.mainModule);

// Enable support to add extra extension types.
require.extensions = Module._extensions;
Expand Down
21 changes: 10 additions & 11 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ const {
maybeCacheSourceMap,
} = require('internal/source_map/source_map_cache');
const { pathToFileURL, fileURLToPath, isURLInstance } = require('internal/url');
const { deprecate, kEmptyObject } = require('internal/util');
const { deprecate, kEmptyObject, filterOwnProperties, setOwnProperty } = require('internal/util');
const vm = require('vm');
const assert = require('internal/assert');
const fs = require('fs');
Expand Down Expand Up @@ -172,7 +172,7 @@ const moduleParentCache = new SafeWeakMap();
function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
this.exports = {};
setOwnProperty(this, 'exports', {});
moduleParentCache.set(this, parent);
updateChildren(parent, this, false);
this.filename = null;
Expand Down Expand Up @@ -312,14 +312,13 @@ function readPackage(requestPath) {
}

try {
const parsed = JSONParse(json);
const filtered = {
name: parsed.name,
main: parsed.main,
exports: parsed.exports,
imports: parsed.imports,
type: parsed.type
};
const filtered = filterOwnProperties(JSONParse(json), [
'name',
'main',
'exports',
'imports',
'type',
]);
packageJsonCache.set(jsonPath, filtered);
return filtered;
} catch (e) {
Expand Down Expand Up @@ -1185,7 +1184,7 @@ Module._extensions['.json'] = function(module, filename) {
}

try {
module.exports = JSONParse(stripBOM(content));
setOwnProperty(module, 'exports', JSONParse(stripBOM(content)));
} catch (err) {
err.message = filename + ': ' + err.message;
throw err;
Expand Down
6 changes: 4 additions & 2 deletions lib/internal/modules/esm/package_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const {
JSONParse,
ObjectPrototypeHasOwnProperty,
SafeMap,
StringPrototypeEndsWith,
} = primordials;
Expand All @@ -11,6 +12,7 @@ const {
} = require('internal/errors').codes;

const packageJsonReader = require('internal/modules/package_json_reader');
const { filterOwnProperties } = require('internal/util');


/**
Expand Down Expand Up @@ -66,8 +68,8 @@ function getPackageConfig(path, specifier, base) {
);
}

let { imports, main, name, type } = packageJSON;
const { exports } = packageJSON;
let { imports, main, name, type } = filterOwnProperties(packageJSON, ['imports', 'main', 'name', 'type']);
const exports = ObjectPrototypeHasOwnProperty(packageJSON, 'exports') ? packageJSON.exports : undefined;
if (typeof imports !== 'object' || imports === null) {
imports = undefined;
}
Expand Down
32 changes: 32 additions & 0 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const {
ObjectGetOwnPropertyDescriptors,
ObjectGetPrototypeOf,
ObjectFreeze,
ObjectPrototypeHasOwnProperty,
ObjectSetPrototypeOf,
Promise,
ReflectApply,
Expand Down Expand Up @@ -507,6 +508,35 @@ ObjectFreeze(kEnumerableProperty);

const kEmptyObject = ObjectFreeze(ObjectCreate(null));

function filterOwnProperties(source, keys) {
const filtered = ObjectCreate(null);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (ObjectPrototypeHasOwnProperty(source, key)) {
filtered[key] = source[key];
}
}

return filtered;
}

/**
* Mimics `obj[key] = value` but ignoring potential prototype inheritance.
* @param {any} obj
* @param {string} key
* @param {any} value
* @returns {any}
*/
function setOwnProperty(obj, key, value) {
return ObjectDefineProperty(obj, key, {
__proto__: null,
configurable: true,
enumerable: true,
value,
writable: true,
});
}

module.exports = {
assertCrypto,
cachedResult,
Expand All @@ -519,6 +549,7 @@ module.exports = {
emitExperimentalWarning,
exposeInterface,
filterDuplicateStrings,
filterOwnProperties,
getConstructorOf,
getSystemErrorMap,
getSystemErrorName,
Expand Down Expand Up @@ -549,4 +580,5 @@ module.exports = {

kEmptyObject,
kEnumerableProperty,
setOwnProperty,
};
3 changes: 2 additions & 1 deletion test/fixtures/es-module-specifiers/index.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import explicit from 'explicit-main';
import implicit from 'implicit-main';
import implicitModule from 'implicit-main-type-module';
import noMain from 'no-main-field';

function getImplicitCommonjs () {
return import('implicit-main-type-commonjs');
}

export {explicit, implicit, implicitModule, getImplicitCommonjs};
export {explicit, implicit, implicitModule, getImplicitCommonjs, noMain};
export default 'success';

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

43 changes: 43 additions & 0 deletions test/parallel/test-module-prototype-mutation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'use strict';
const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('assert');

Object.defineProperty(Object.prototype, 'name', {
__proto__: null,
get: common.mustNotCall('get %Object.prototype%.name'),
set: common.mustNotCall('set %Object.prototype%.name'),
enumerable: false,
});
Object.defineProperty(Object.prototype, 'main', {
__proto__: null,
get: common.mustNotCall('get %Object.prototype%.main'),
set: common.mustNotCall('set %Object.prototype%.main'),
enumerable: false,
});
Object.defineProperty(Object.prototype, 'type', {
__proto__: null,
get: common.mustNotCall('get %Object.prototype%.type'),
set: common.mustNotCall('set %Object.prototype%.type'),
enumerable: false,
});
Object.defineProperty(Object.prototype, 'exports', {
__proto__: null,
get: common.mustNotCall('get %Object.prototype%.exports'),
set: common.mustNotCall('set %Object.prototype%.exports'),
enumerable: false,
});
Object.defineProperty(Object.prototype, 'imports', {
__proto__: null,
get: common.mustNotCall('get %Object.prototype%.imports'),
set: common.mustNotCall('set %Object.prototype%.imports'),
enumerable: false,
});

assert.strictEqual(
require(fixtures.path('es-module-specifiers', 'node_modules', 'no-main-field')),
'no main field'
);

import(fixtures.fileURL('es-module-specifiers', 'index.mjs'))
.then(common.mustCall((module) => assert.strictEqual(module.noMain, 'no main field')));

0 comments on commit 05802c2

Please sign in to comment.