Skip to content
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
3 changes: 0 additions & 3 deletions eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -1037,9 +1037,6 @@
},
"packages/solana-wallet-snap/src/core/validation/structs.ts": {
"@typescript-eslint/no-unused-vars": {
"count": 2
},
"@typescript-eslint/restrict-template-expressions": {
"count": 1
}
},
Expand Down
1 change: 1 addition & 0 deletions packages/snap-networks-utils/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Add a `safeMerge` utility for shallowly merging objects. ([#166](https://github.com/MetaMask/internal-snaps/pull/166))
- Add a `UrlStruct` utility for validating safe HTTP, HTTPS, and WebSocket URLs. ([#174](https://github.com/MetaMask/internal-snaps/pull/174))

### Changed

Expand Down
1 change: 1 addition & 0 deletions packages/snap-networks-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export {
type RemoteFeatureFlagsProviderMessenger,
} from './providers/remote-feature-flags/RemoteFeatureFlagsProvider';
export { safeMerge } from './safeMerge/safeMerge';
export { UrlStruct } from './urlStruct/urlStruct';
export { Logger, LogLevel } from './logger';
export type {
LoggerOptions,
Expand Down
154 changes: 154 additions & 0 deletions packages/snap-networks-utils/src/urlStruct/urlStruct.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/* eslint-disable jest/require-to-throw-message */
import { assert, is } from '@metamask/superstruct';

import { UrlStruct } from './urlStruct';

describe('UrlStruct', () => {
it('validates valid URLs', () => {
const validUrls = [
'http://example.com',
'https://example.com',
'https://www.example.com',
'https://sub.example.com',
'https://example.com/path',
'https://example.com/path?query=123',
'https://example.com/path?query=123&other=456',
'https://example.com:8080',
'https://example.com/path-with-hyphens',
'https://example.com/path_with_underscore',
'http://localhost:8899',
'wss://example.com',
];

validUrls.forEach((url) => {
expect(() => assert(url, UrlStruct)).not.toThrow();
expect(is(url, UrlStruct)).toBe(true);
});
});

it('rejects invalid URLs', () => {
const invalidUrls = [
'',
'not-a-url',
'ftp://example.com',
'example.com',
'http:/example.com',
'http://example',
'http:///example.com',
'http:// example.com',
// eslint-disable-next-line no-script-url
'javascript:alert(1)',
'data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==',
];

invalidUrls.forEach((url) => {
expect(() => assert(url, UrlStruct)).toThrow();
expect(is(url, UrlStruct)).toBe(false);
});
});

it('includes the real parser reason when URL format is invalid', () => {
expect(() => assert('http:// example.com', UrlStruct)).toThrow(
'Invalid URL format: Invalid URL',
);
});

it.each([
'https://example%2f.com',
'https://example.com:abc',
'https://example.com:342abc',
])('rejects malformed URL parser input: %s', (url) => {
expect(() => assert(url, UrlStruct)).toThrow(
'Invalid URL format: Invalid URL',
);
});

it.each(['https://example.com/%', 'https://example.com/%ZZ'])(
'rejects malformed percent encoding: %s',
(url) => {
expect(() => assert(url, UrlStruct)).toThrow(
'Invalid URL format: URI malformed',
);
},
);

it.each(['https://example.com\\path', 'https://user@example.com'])(
'rejects hostname protocol-pollution input: %s',
(url) => {
expect(() => assert(url, UrlStruct)).toThrow(
'URL contains protocol pollution attempts',
);
},
);

it('rejects malicious URLs', () => {
const maliciousUrls = [
// XSS Attacks
'https://example.com?<script>alert(1)</script>',
'https://example.com?<img src="x" onerror="alert(1)">',
'https://example.com?<iframe src="https://malicious.com"></iframe>',
'https://example.com?<form action="https://malicious.com"></form>',
'https://example.com?<object data="https://malicious.com"></object>',
'https://example.com?<embed src="https://malicious.com"></embed>',
'https://example.com?<applet code="https://malicious.com"></applet>',
'https://example.com?<meta http-equiv="refresh" content="0; url=https://malicious.com">',
'https://example.com?<link rel="stylesheet" href="https://malicious.com">',
'https://example.com?<style>body{background-image:url(https://malicious.com/image.jpg)}</style>',
'https://example.com?<script>eval(atob("YWxlcnQoMSk="))</script>',

// Additional XSS Variants
'https://example.com?<svg onload="alert(1)">',
'https://example.com?<img src="javascript:alert(1)">',
'https://example.com?<a href="javascript:alert(1)">',
'https://example.com?<div onclick="alert(1)">',

// SQL Injection Attempts
'https://example.com?id=1%27%20OR%20%271%27=%271',
'https://example.com?id=1%20UNION%20SELECT%20*%20FROM%20users',

// Directory Traversal
'https://example.com/../../../etc/passwd',
'https://example.com/..%2f..%2f..%2fetc%2fpasswd',

// Command Injection
'https://example.com?cmd=|ls',
'https://example.com?cmd=;cat%20/etc/passwd',

// Protocol Pollution
'https://example.com\\@evil.com',
'https://example.com%2f@evil.com',
'https://example.com?url=javascript:alert(1)',

// Unicode/UTF-8 Attacks
'https://example.com/%2e%2e/%2e%2e/%2e%2e/etc/passwd',
'https://example.com/⒕⒖⒗',

// CRLF Injection
'https://example.com?%0d%0aContent-Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK',

// Open Redirect
'https://example.com?redirect=//evil.com',
'https://example.com?url=https://evil.com',

// HTML Injection without script tags
'https://example.com?param=<marquee>test</marquee>',
'https://example.com?param=<base href="https://evil.com/">',

// Data URI schemes
'data:text/html,<script>alert(1)</script>',
'data:application/x-javascript,alert(1)',

// Null Byte Attacks
'https://example.com/file.jpg%00.php',

// Template Injection
// eslint-disable-next-line no-template-curly-in-string
'https://example.com?${7*7}',
'https://example.com?#{7*7}',
];
maliciousUrls.forEach((url) => {
expect(() => assert(url, UrlStruct)).toThrow();
expect(is(url, UrlStruct)).toBe(false);
});
});
});
108 changes: 108 additions & 0 deletions packages/snap-networks-utils/src/urlStruct/urlStruct.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { refine, string } from '@metamask/superstruct';

/**
* Validates that a string is a valid and safe URL.
*
* It rejects:
* - Non-HTTP/HTTPS/WSS protocols
* - Malformed URL format or incorrect protocol format
* - Invalid hostname format (must follow proper domain naming conventions)
* - Protocol pollution attempts (backslashes, @ symbol, %2f@, %5c@)
* - Invalid hostname characters (backslashes, @ symbol, forward slashes, encoded forward slashes)
* - Directory traversal attempts (../, ..%2f, ..%2F)
*
* Dangerous patterns including:
* - HTML tags.
* - JavaScript protocol.
* - Data URI scheme.
* - Template injection (${...}, #{...}).
* - Command injection (|, ;).
* - CRLF injection.
* - URL credential injection.
* - SQL injection attempts.
* - Open redirect parameters.
* - Non-printable characters.
*/
export const UrlStruct = refine(string(), 'safe-url', (value) => {
try {
// Basic URL validation
const url = new URL(value);

// Protocol check
const supportedProtocols = ['http:', 'https:', 'wss:'];
if (!supportedProtocols.includes(url.protocol)) {
return `URL must use one of the following protocols: ${supportedProtocols.join(', ')}`;
}

// Validate URL format
if (!value.match(/^(https?|wss):\/\/[^/]+\/?/u)) {
return 'Malformed URL - incorrect protocol format';
}

// Validate hostname format. Accepts localhost and ports (needed for tests)
const hostname = url.hostname.toLowerCase();
if (
hostname !== 'localhost' &&
(!hostname.includes('.') ||
!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/u.test(
hostname,
))
) {
return 'Invalid hostname format';
}

// Check for protocol pollution in the entire URL
const decodedValue = decodeURIComponent(value.toLowerCase());
if (
value.includes('\\') ||
value.includes('@') ||
decodedValue.includes('\\') ||
decodedValue.includes('@') ||
value.toLowerCase().includes('%2f@') ||
value.toLowerCase().includes('%5c@')
) {
return 'URL contains protocol pollution attempts';
}

// Check for directory traversal
if (
value.includes('../') ||
value.includes('..%2f') ||
value.includes('..%2F')
) {
return 'Directory traversal attempts are not allowed';
}

// Check for dangerous patterns
const dangerousPatterns = [
/<[^>]*>/u, // HTML tags
/javascript:/u, // JavaScript protocol
/data:/u, // Data URI scheme
/\\[@\\]/u, // Enhanced protocol pollution check
/%2f@/u, // Protocol pollution
/[^\x20-\x7E]/u, // Non-printable characters
/\$\{.*?\}/u, // Template injection
/#\{.*?\}/u, // Template injection
/[|;]/u, // Command injection
/%0[acd]|%0[acd]/u, // CRLF injection
/\/\/\w+@/u, // URL credential injection
// Enhanced SQL injection patterns
/(?:[^a-z]|^)(?:union\s+(?:all\s+)?select|select\s+(?:.*\s+)?from|insert\s+into|update\s+.*\s+set|delete\s+from|drop\s+table|alter\s+table|create\s+table|exec(?:ute)?|union|where\s+[\d\w]\s*=\s*[\d\w]|\bor\b\s*[\d\w]\s*=\s*[\d\w])/iu,
/'.*?(?:OR|UNION|SELECT|FROM|WHERE).*?'/iu, // SQL injection
/%27.*?(?:OR|UNION|SELECT|FROM|WHERE).*?(?:%27|')/iu, // URL-encoded SQL injection
/%20(?:OR|UNION|SELECT|FROM|WHERE)%20/iu, // URL-encoded SQL keywords
/[?&](?:url|redirect|next|return_to|return_url|goto|destination|continue|redirect_uri)=(?:[^&]*\/\/|https?:)/iu, // Open redirect parameters
/[?&](?:url|redirect|next|return_to|return_url|goto|destination|continue|redirect_uri)=%(?:[^&]*\/\/|https?:)/iu, // URL-encoded open redirect parameters
];

for (const patt of dangerousPatterns) {
if (patt.test(decodedValue)) {
return 'URL contains potentially malicious patterns';
}
}

return true;
} catch (error) {
return `Invalid URL format: ${(error as Error).message}`;
}
});
2 changes: 1 addition & 1 deletion packages/solana-wallet-snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/MetaMask/internal-snaps.git"
},
"source": {
"shasum": "2c2WNzBfLdP/UYJdepbBVpyYrpjzuSob/iobC9JJRLo=",
"shasum": "/PhLDvRV3M/0N7rlAqg7pypEkZAHTfFNP9/TNxi8G80=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */

import { UrlStruct } from '@metamask/snap-networks-utils';
import { assert } from '@metamask/superstruct';

import type { ICache } from '../../caching/ICache';
Expand All @@ -8,7 +9,6 @@ import type { Serializable } from '../../serialization/types';
import type { ConfigProvider } from '../../services/config';
import { buildUrl } from '../../utils/buildUrl';
import { trackError } from '../../utils/errors';
import { UrlStruct } from '../../validation/structs';
import type {
Balance,
Nft,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */

import type { CaipAssetType } from '@metamask/keyring-api';
import { UrlStruct } from '@metamask/snap-networks-utils';
import type { Logger } from '@metamask/snap-networks-utils';
import { array, assert } from '@metamask/superstruct';
import { CaipAssetTypeStruct } from '@metamask/utils';
Expand All @@ -12,7 +13,6 @@ import type { Serializable } from '../../serialization/types';
import type { ConfigProvider } from '../../services/config';
import { buildUrl } from '../../utils/buildUrl';
import logger from '../../utils/logger';
import { UrlStruct } from '../../validation/structs';
import type {
ExchangeRate,
FiatTicker,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { UrlStruct } from '@metamask/snap-networks-utils';
import type { Logger } from '@metamask/snap-networks-utils';
import type { FungibleAssetMetadata } from '@metamask/snaps-sdk';
import { array, assert } from '@metamask/superstruct';
Expand All @@ -9,7 +10,6 @@ import { Network, TokenCaipAssetTypeStruct } from '../../constants/solana';
import type { ConfigProvider } from '../../services/config';
import { buildUrl } from '../../utils/buildUrl';
import logger from '../../utils/logger';
import { UrlStruct } from '../../validation/structs';
import type { TokenMetadataStruct } from './structs';
import { TokenMetadataResponseStruct } from './structs';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { UrlStruct } from '@metamask/snap-networks-utils';
import {
array,
integer,
Expand All @@ -7,7 +8,6 @@ import {
} from '@metamask/superstruct';

import { TokenCaipAssetTypeFromStringStruct } from '../../constants/solana';
import { UrlStruct } from '../../validation/structs';

export const TokenMetadataStruct = object({
decimals: integer(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { LogLevel } from '@metamask/snap-networks-utils';
/* eslint-disable no-restricted-globals */
import { UrlStruct, LogLevel } from '@metamask/snap-networks-utils';
import type { Infer } from '@metamask/superstruct';
import {
array,
Expand All @@ -14,7 +14,6 @@ import { uniq } from 'lodash';

import { Network, Networks } from '../../constants/solana';
import { getClientStatus } from '../../utils/interface';
import { UrlStruct } from '../../validation/structs';

export const SUPPORTED_NETWORKS = [Network.Mainnet, Network.Devnet];

Expand Down Expand Up @@ -56,7 +55,7 @@ const EnvStruct = object({
LOCAL_API_BASE_URL: string(),
});

export type Env = Infer<typeof EnvStruct>;
type Env = Infer<typeof EnvStruct>;

export type NetworkConfig = (typeof Networks)[Network] & {
rpcUrls: string[];
Expand Down
2 changes: 1 addition & 1 deletion packages/solana-wallet-snap/src/core/utils/buildUrl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { UrlStruct } from '@metamask/snap-networks-utils';
import { assert } from '@metamask/superstruct';

import { UrlStruct } from '../validation/structs';
import { sanitizeControlCharacters, sanitizeUri } from './sanitize';

export type BuildUrlParams = {
Expand Down
Loading