Skip to content

Fix prototype-polluting assignments #4041

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,13 @@ describe('AddressBookController', () => {
).toBe(true);
});

it('should return false to indicate an address book entry has NOT been deleted due to unsafe input', () => {
const controller = new AddressBookController();
// @ts-expect-error Suppressing error to test runtime behavior
expect(controller.delete('__proto__', '0x01')).toBe(false);
expect(controller.delete(toHex(1), 'constructor')).toBe(false);
});

it('should return false to indicate an address book entry has NOT been deleted', () => {
const controller = new AddressBookController();
controller.set('0x32Be343B94f860124dC4fEe278FDCBD38C102D88', '0x00');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BaseControllerV1 } from '@metamask/base-controller';
import {
normalizeEnsName,
isValidHexAddress,
isSafeDynamicKey,
toChecksumHexAddress,
toHex,
} from '@metamask/controller-utils';
Expand Down Expand Up @@ -110,6 +111,7 @@ export class AddressBookController extends BaseControllerV1<
delete(chainId: Hex, address: string) {
address = toChecksumHexAddress(address);
if (
![chainId, address].every((key) => isSafeDynamicKey(key)) ||
!isValidHexAddress(address) ||
!this.state.addressBook[chainId] ||
!this.state.addressBook[chainId][address]
Expand Down
8 changes: 4 additions & 4 deletions packages/controller-utils/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ module.exports = merge(baseConfig, {
// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 68.05,
functions: 80.55,
lines: 69.82,
statements: 70.17,
branches: 78.12,
functions: 85.41,
lines: 87.3,
statements: 86.5,
},
},

Expand Down
30 changes: 29 additions & 1 deletion packages/controller-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,32 @@
export * from './constants';
export * from './util';
export type { NonEmptyArray } from './util';
export {
BNToHex,
convertHexToDecimal,
fetchWithErrorHandling,
fractionBN,
fromHex,
getBuyURL,
gweiDecToWEIBN,
handleFetch,
hexToBN,
hexToText,
isNonEmptyArray,
isPlainObject,
isSafeChainId,
isSafeDynamicKey,
isSmartContractCode,
isValidJson,
isValidHexAddress,
normalizeEnsName,
query,
safelyExecute,
safelyExecuteWithTimeout,
successfulFetch,
timeoutFetch,
toChecksumHexAddress,
toHex,
weiHexToGweiDec,
} from './util';
export * from './types';
export * from './siwe';
11 changes: 10 additions & 1 deletion packages/controller-utils/src/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,21 @@ const SOME_API = 'https://someapi.com';
const SOME_FAILING_API = 'https://somefailingapi.com';

describe('util', () => {
it('isSafeDynamicKey', () => {
expect(util.isSafeDynamicKey(util.toHex(MAX_SAFE_CHAIN_ID))).toBe(true);
expect(util.isSafeDynamicKey('')).toBe(true);
for (const badKey of util.PROTOTYPE_POLLUTION_BLOCKLIST) {
expect(util.isSafeDynamicKey(badKey)).toBe(false);
}
// @ts-expect-error - ensure that non-string input return false.
expect(util.isSafeDynamicKey(null)).toBe(false);
});
it('isSafeChainId', () => {
expect(util.isSafeChainId(util.toHex(MAX_SAFE_CHAIN_ID + 1))).toBe(false);
expect(util.isSafeChainId(util.toHex(MAX_SAFE_CHAIN_ID))).toBe(true);
expect(util.isSafeChainId(util.toHex(0))).toBe(false);
expect(util.isSafeChainId('0xinvalid')).toBe(false);
// @ts-expect-error - ensure that string args return false.
// @ts-expect-error - ensure that non-string args return false.
expect(util.isSafeChainId('test')).toBe(false);
});

Expand Down
20 changes: 20 additions & 0 deletions packages/controller-utils/src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,26 @@ import { MAX_SAFE_CHAIN_ID } from './constants';

const TIMEOUT_ERROR = new Error('timeout');

export const PROTOTYPE_POLLUTION_BLOCKLIST = [
'__proto__',
'constructor',
'prototype',
] as const;

/**
* Checks whether a dynamic property key could be used in
* a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).
*
* @param key - The dynamic key to validate.
* @returns Whether the given dynamic key is safe to use.
*/
export function isSafeDynamicKey(key: string): boolean {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not intending to block this PR, but this seems like it could be useful for @metamask/utils.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not opposed to moving it down the line if it fits better there!

return (
typeof key === 'string' &&
!PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)
);
}

/**
* Checks whether the given number primitive chain ID is safe.
* Because some cryptographic libraries we use expect the chain ID to be a
Expand Down
10 changes: 10 additions & 0 deletions packages/ens-controller/src/EnsController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,16 @@ describe('EnsController', () => {
expect(controller.state.ensEntries['0x1']).toBeUndefined();
});

it('should return false if an ENS entry was NOT deleted due to unsafe input', () => {
const messenger = getMessenger();
const controller = new EnsController({
messenger,
});
// @ts-expect-error Suppressing error to test runtime behavior
expect(controller.delete('__proto__', 'bar')).toBe(false);
expect(controller.delete(toHex(2), 'constructor')).toBe(false);
});

it('should return false if an ENS entry was NOT deleted', () => {
const messenger = getMessenger();
const controller = new EnsController({
Expand Down
2 changes: 2 additions & 0 deletions packages/ens-controller/src/EnsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { ChainId } from '@metamask/controller-utils';
import {
normalizeEnsName,
isValidHexAddress,
isSafeDynamicKey,
toChecksumHexAddress,
CHAIN_ID_TO_ETHERS_NETWORK_NAME_MAP,
convertHexToDecimal,
Expand Down Expand Up @@ -194,6 +195,7 @@ export class EnsController extends BaseController<
delete(chainId: Hex, ensName: string): boolean {
const normalizedEnsName = normalizeEnsName(ensName);
if (
!isSafeDynamicKey(chainId) ||
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a test for this? Seems important to check.

Copy link
Contributor

@legobeat legobeat Mar 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The type as well as the following code assumes that chainId is Hex, which if true implies that isSafeDynamicKey9chainId) would also be true.

Maybe adding a runtime-check that the chainId actually starts with 0x will do just as well here as well as in packages/address-book-controller/src/AddressBookController.ts?

A function like isSafeDynamicKey still could be useful for other cases where untrusted input string can't be assumed to be hex (indexing on method names anywhere?) but it seems like a simpler hex-prefix check will solve for all the cases covered in this PR?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's true that isValidHexAddress for address and isSafeChainId for chainId would be sufficient validation to fix the violations currently found by the scanner.

However, it seems worth it to implement more generalized blocklisting logic for this vulnerability (https://portswigger.net/web-security/prototype-pollution/preventing#sanitizing-property-keys), which will also directly placate the CodeQL scanner.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, we could definitely make more improvements that would ensure we can protect against this vulnerability more generally.

That seems unrelated to my comment, though. Should we add tests which attempt to call delete with __proto__, constructor, and prototype and verify that they don't do anything?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added tests for all three files here: a145237. Coverage is up to 100 for the three modules. I didn't test every string in the blocklist, but it seems like verifying that the validation works should be enough?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Testing that it essentially just gets called is fine. Do we need tests for the function itself, though?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah of course I'll add that right now.

!normalizedEnsName ||
!this.state.ensEntries[chainId] ||
!this.state.ensEntries[chainId][normalizedEnsName]
Expand Down
1 change: 1 addition & 0 deletions packages/name-controller/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
},
"dependencies": {
"@metamask/base-controller": "^5.0.1",
"@metamask/controller-utils": "^9.0.2",
"@metamask/utils": "^8.3.0",
"async-mutex": "^0.2.6"
},
Expand Down
58 changes: 58 additions & 0 deletions packages/name-controller/src/NameController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,64 @@ describe('NameController', () => {
});
});

it('does not update if passed unsafe input', () => {
const provider1 = createMockProvider(1);

const controller = new NameController({
...CONTROLLER_ARGS_MOCK,
providers: [provider1],
state: {
names: {
[NameType.ETHEREUM_ADDRESS]: {
[VALUE_MOCK]: {
[CHAIN_ID_MOCK]: {
name: null,
sourceId: null,
origin: null,
proposedNames: {
[SOURCE_ID_MOCK]: {
proposedNames: [PROPOSED_NAME_MOCK, PROPOSED_NAME_2_MOCK],
lastRequestTime: null,
updateDelay: null,
},
},
},
},
},
},
},
});

controller.setName({
value: '__proto__',
type: NameType.ETHEREUM_ADDRESS,
name: NAME_MOCK,
sourceId: `${SOURCE_ID_MOCK}1`,
variation: CHAIN_ID_MOCK,
});

expect(controller.state.names).toStrictEqual<
NameControllerState['names']
>({
[NameType.ETHEREUM_ADDRESS]: {
[VALUE_MOCK]: {
[CHAIN_ID_MOCK]: {
name: null,
sourceId: null,
origin: null,
proposedNames: {
[SOURCE_ID_MOCK]: {
proposedNames: [PROPOSED_NAME_MOCK, PROPOSED_NAME_2_MOCK],
lastRequestTime: null,
updateDelay: null,
},
},
},
},
},
});
});

it('does not throw if variation is fallback and type is Ethereum address', () => {
const controller = new NameController(CONTROLLER_ARGS_MOCK);

Expand Down
9 changes: 9 additions & 0 deletions packages/name-controller/src/NameController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
RestrictedControllerMessenger,
} from '@metamask/base-controller';
import { BaseController } from '@metamask/base-controller';
import { isSafeDynamicKey } from '@metamask/controller-utils';

import type {
NameProvider,
Expand Down Expand Up @@ -441,6 +442,14 @@ export class NameController extends BaseController<
const normalizedValue = this.#normalizeValue(value, type);
const normalizedVariation = this.#normalizeVariation(variationKey, type);

if (
[normalizedValue, normalizedVariation].some(
(key) => !isSafeDynamicKey(key),
)
) {
return;
}

this.update((state) => {
const typeEntries = state.names[type] || {};
state.names[type] = typeEntries;
Expand Down
1 change: 1 addition & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2540,6 +2540,7 @@ __metadata:
dependencies:
"@metamask/auto-changelog": ^3.4.4
"@metamask/base-controller": ^5.0.1
"@metamask/controller-utils": ^9.0.2
"@metamask/utils": ^8.3.0
"@types/jest": ^27.4.1
async-mutex: ^0.2.6
Expand Down