-
Notifications
You must be signed in to change notification settings - Fork 44
[APS-19009] security(cli): --ignore-scripts + validate npm_dependencies (lifecycle-script RCE) #1172
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
base: master
Are you sure you want to change the base?
[APS-19009] security(cli): --ignore-scripts + validate npm_dependencies (lifecycle-script RCE) #1172
Changes from all commits
e578fad
ad117a0
70fbc8e
fba71e0
37ef6ad
4e0aa6f
c5430ef
8441042
251c7b2
8df7a40
1f42201
ecc9674
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,9 +33,23 @@ | |
|
|
||
| // Combine win and mac specific dependencies if present | ||
| const combinedDependencies = combineMacWinNpmDependencies(runSettings); | ||
| if (combinedDependencies && Object.keys(combinedDependencies).length > 0) { | ||
| // APS-19009: drop any dependency whose name is not a valid npm package name (strips | ||
| // shell-metacharacter payloads like "left-pad; cat /flag"). Version specs are NOT validated | ||
| // (git / file: / tarball-url are legitimate), and a bad entry is skipped, not aborted, so a | ||
| // customer session is never blocked. RCE itself is closed by --ignore-scripts (see below). | ||
| const NPM_NAME_RE = /^(@[a-zA-Z0-9-~][a-zA-Z0-9-._~]*\/)?[a-zA-Z0-9-~][a-zA-Z0-9-._~]*$/; | ||
| const safeDependencies = {}; | ||
| for (const depName of Object.keys(combinedDependencies || {})) { | ||
| const depVersion = combinedDependencies[depName]; | ||
| if (!NPM_NAME_RE.test(depName) || typeof depVersion !== 'string') { | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Low] PR description overstates version-spec validation The PR body says the fix validates version specs and rejects Suggestion: No code change needed. Update the PR body to match the code: package names are validated; version specs are deliberately left unvalidated because git/file/tarball specs are legitimate and RCE is closed by Reviewer: stack:code-review |
||
| logger.warn(`Skipping npm_dependencies entry "${depName}": not a valid npm package name. This dependency will not be installed.`); | ||
| continue; | ||
| } | ||
| safeDependencies[depName] = depVersion; | ||
| } | ||
| if (Object.keys(safeDependencies).length > 0) { | ||
| Object.assign(packageJSON, { | ||
| devDependencies: combinedDependencies, | ||
| devDependencies: safeDependencies, | ||
| }); | ||
| } | ||
|
|
||
|
|
@@ -97,12 +111,15 @@ | |
|
|
||
| // add --legacy-peer-deps flag while installing dependencies for npm v7+ | ||
| // For more info please read "Peer Dependencies" section here -> https://github.blog/2021-02-02-npm-7-is-now-generally-available/ | ||
| // APS-19009: --ignore-scripts blocks lifecycle-script (postinstall) RCE. shell:true is kept | ||
| // on purpose — the command line is static (package names live in package.json, not on the CLI) | ||
| // and shell:true is needed for the output redirection and for npm.cmd on Windows. | ||
| if (parseInt(npm_major_version) >= 7) { | ||
| logger.debug(`Running NPM install command: npm install --legacy-peer-deps --loglevel verbose > ../npm_install_debug.log`); | ||
| nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--legacy-peer-deps', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true}); | ||
| logger.debug(`Running NPM install command: npm install --legacy-peer-deps --ignore-scripts --loglevel verbose > ../npm_install_debug.log`); | ||
| nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--legacy-peer-deps', '--ignore-scripts', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true}); // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true | ||
| } else { | ||
| logger.debug(`Running NPM install command: 'npm install --loglevel verbose > ../npm_install_debug.log'`); | ||
| nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true}); | ||
| logger.debug(`Running NPM install command: 'npm install --ignore-scripts --loglevel verbose > ../npm_install_debug.log'`); | ||
| nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--ignore-scripts', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true}); // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true | ||
| } | ||
| nodeProcess.on('close', nodeProcessCloseCallback); | ||
| nodeProcess.on('error', nodeProcessErrorCallback); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| 'use strict'; | ||
|
|
||
| const path = require('path'); | ||
|
|
||
| /** | ||
| * Security validation helpers shared across the CLI. | ||
| * | ||
| * These guard the "untrusted edges" of the CLI: | ||
| * - override/response URLs that could redirect API traffic or uploads | ||
| * (APS-19010, APS-19011) | ||
| * - config-file paths that could escape the project directory (APS-19008) | ||
| * | ||
| * Kept dependency-free (stdlib only) so the logic can be unit tested without | ||
| * pulling in the CLI's network/config stack. | ||
| */ | ||
|
|
||
| // Hosts the CLI is allowed to talk to for API / upload endpoints. Covers | ||
| // production, staging (bsstag.com) and local development. Anything else is | ||
| // treated as attacker-controlled and rejected. | ||
| const ALLOWED_HOST_SUFFIXES = ['.browserstack.com', '.bsstag.com']; | ||
| // Note: URL parsing yields '[::1]' (bracketed) as the hostname for IPv6 loopback. | ||
| const ALLOWED_EXACT_HOSTS = ['browserstack.com', 'bsstag.com', 'localhost', '127.0.0.1', '[::1]']; | ||
|
|
||
| /** | ||
| * Returns true if the given URL points at a BrowserStack (prod/staging) host or | ||
| * localhost. Only http/https are accepted. Any parse failure returns false | ||
| * (fail-closed). | ||
| * @param {string} urlString | ||
| * @returns {boolean} | ||
| */ | ||
| function isAllowedBrowserstackUrl(urlString) { | ||
| if (typeof urlString !== 'string' || urlString.trim() === '') { | ||
| return false; | ||
| } | ||
| let parsed; | ||
| try { | ||
| parsed = new URL(urlString); | ||
| } catch (e) { | ||
| return false; | ||
| } | ||
| if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { | ||
| return false; | ||
| } | ||
| const host = parsed.hostname.toLowerCase(); | ||
| if (ALLOWED_EXACT_HOSTS.includes(host)) { | ||
| return true; | ||
| } | ||
| return ALLOWED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix)); | ||
| } | ||
|
|
||
| /** | ||
| * Resolves a candidate path and asserts it stays inside baseDir. Used to stop | ||
| * config-file path traversal (e.g. --config-file ../../outside/browserstack.json). | ||
| * @param {string} candidatePath | ||
| * @param {string} baseDir defaults to process.cwd() | ||
| * @returns {boolean} | ||
| */ | ||
| function isPathInsideBase(candidatePath, baseDir) { | ||
| if (typeof candidatePath !== 'string' || candidatePath === '') { | ||
| return false; | ||
| } | ||
| // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- these resolves ARE the traversal guard: the value is normalized here only so the containment check below can reject anything outside `base`. | ||
| const base = path.resolve(baseDir || process.cwd()); | ||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
|
||
| // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- see above; resolved path is validated by the startsWith(base) check, not used to read the FS unchecked. | ||
| const resolved = path.resolve(base, candidatePath); | ||
|
|
||
| // Must be the base itself or a descendant (base + separator prefix). | ||
| return resolved === base || resolved.startsWith(base + path.sep); | ||
| } | ||
|
|
||
| /** | ||
| * Structural (NOT cryptographic) validation of a JWT: three non-empty | ||
| * base64url segments. The CLI is not the token issuer and has no key to verify | ||
| * the signature, so this only rejects obviously-malformed / MITM-swapped | ||
| * garbage tokens. Defence-in-depth, not an integrity guarantee. | ||
| * @param {string} token | ||
| * @returns {boolean} | ||
| */ | ||
| function isWellFormedJwt(token) { | ||
| if (typeof token !== 'string') { | ||
| return false; | ||
| } | ||
| const parts = token.split('.'); | ||
| if (parts.length !== 3) { | ||
| return false; | ||
| } | ||
| return parts.every((p) => /^[A-Za-z0-9_-]+$/.test(p)); | ||
| } | ||
|
|
||
| module.exports = { | ||
| isAllowedBrowserstackUrl, | ||
| isPathInsideBase, | ||
| isWellFormedJwt, | ||
| ALLOWED_HOST_SUFFIXES, | ||
| ALLOWED_EXACT_HOSTS, | ||
| }; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
here should we not initailised it to false ?