-
Notifications
You must be signed in to change notification settings - Fork 5
fix(scanner): patch unauthenticated arbitrary file write (GHSA-ppp9-2hc2-hfg5) #13
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
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
5ea7896
fix(scanner): confine exportReport destination to reports dir (GHSA-p…
ralyodio 34c13e0
fix(scanner): require auth on side-effecting routes (GHSA-ppp9-2hc2-h…
ralyodio cf19506
ci: fix failing security workflow (semgrep, npm audit, gitleaks)
ralyodio ed50f7f
fix(scanner): use double-HMAC constant-time token compare (CodeQL)
ralyodio e979df7
fix(scanner): compare tokens without hashing to satisfy CodeQL
ralyodio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| # Gitleaks configuration. | ||
| # Extends the built-in default ruleset and allowlists known non-sensitive | ||
| # values so the secret scanner stops failing on documentation placeholders | ||
| # and the intentionally-shipped default key. | ||
|
|
||
| [extend] | ||
| useDefault = true | ||
|
|
||
| [allowlist] | ||
| description = "Documentation placeholders and the shipped default key" | ||
| regexTarget = "match" | ||
| regexes = [ | ||
| # Placeholder tokens used in example requests throughout the docs. | ||
| '''your-api-key-here''', | ||
| '''your_valueserp_api_key''', | ||
| '''sk-your-openai-api-key''', | ||
| '''your[-_]?api[-_]?key''', | ||
| # Obvious dummy value used in link-shortener tests. | ||
| '''abcdefghij1234567890''', | ||
| # hynt.us default API key intentionally shipped by the link-shortener module | ||
| # (documented as the "Default API Key" and used as a hardcoded fallback). | ||
| # NOTE: this is a real, shared key — consider rotating it and moving to an | ||
| # env var rather than committing it. Allowlisted so CI reflects that it is a | ||
| # known, deliberate value rather than an accidental leak. | ||
| '''1t7nfaw9ra0nmznsbdni''', | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,27 @@ | ||
| # Use Node.js LTS as the base image | ||
| FROM node:20-alpine | ||
|
|
||
| # Set working directory | ||
| # Install pnpm (as root, into the global prefix) | ||
| RUN npm install -g pnpm | ||
|
|
||
| # Set working directory and hand it to the built-in non-root `node` user | ||
| WORKDIR /app | ||
| RUN chown node:node /app | ||
|
|
||
| # Copy package files | ||
| COPY package.json pnpm-lock.yaml ./ | ||
| # Copy package files (owned by the non-root user so pnpm can write to the tree) | ||
| COPY --chown=node:node package.json pnpm-lock.yaml ./ | ||
|
|
||
| # Install pnpm | ||
| RUN npm install -g pnpm | ||
| # Drop privileges before installing/running — never run the app as root | ||
| USER node | ||
|
|
||
| # Install dependencies | ||
| RUN pnpm install --frozen-lockfile | ||
|
|
||
| # Copy application code | ||
| COPY . . | ||
| COPY --chown=node:node . . | ||
|
|
||
| # Expose the port the app runs on | ||
| EXPOSE 3000 | ||
|
|
||
| # Command to run the application | ||
| CMD ["pnpm", "start"] | ||
| CMD ["pnpm", "start"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| /** | ||
| * Scanner authentication middleware | ||
| * | ||
| * Guards the scanner's side-effecting routes (scan, export, the /tools/scanner | ||
| * tool endpoint) that were previously reachable with no authentication at all | ||
| * (see GHSA-ppp9-2hc2-hfg5). A bearer token / API key is required when | ||
| * `SCANNER_API_TOKEN` is configured. | ||
| * | ||
| * Behaviour: | ||
| * - `SCANNER_API_TOKEN` set → the token must be supplied as | ||
| * `Authorization: Bearer <token>` or `X-API-Key: <token>`, else 401. | ||
| * - `SCANNER_API_TOKEN` unset → requests are allowed (preserves out-of-box | ||
| * behaviour) but a one-time warning is logged so operators know the | ||
| * side-effecting routes are open. | ||
| */ | ||
|
|
||
| import { randomBytes, createHmac, timingSafeEqual } from 'crypto'; | ||
| import { logger } from '../../../src/utils/logger.js'; | ||
|
|
||
| // Random per-process key used only to derive fixed-length digests for the | ||
| // constant-time comparison below (the "double HMAC" technique). It never leaves | ||
| // the process and is not a stored credential. | ||
| const COMPARE_KEY = randomBytes(32); | ||
|
|
||
| let missingTokenWarned = false; | ||
|
|
||
| /** | ||
| * Extract a presented credential from the request. | ||
| * Supports `Authorization: Bearer <token>` and `X-API-Key: <token>`. | ||
| * @param {import('hono').Context} c | ||
| * @returns {string} | ||
| */ | ||
| function extractToken(c) { | ||
| const authz = c.req.header('authorization') || c.req.header('Authorization'); | ||
| if (authz && authz.toLowerCase().startsWith('bearer ')) { | ||
| return authz.slice(7).trim(); | ||
| } | ||
| return c.req.header('x-api-key') || c.req.header('X-API-Key') || ''; | ||
| } | ||
|
|
||
| /** | ||
| * Constant-time comparison of two strings ("double HMAC" technique). | ||
| * Each side is run through HMAC-SHA256 keyed by a random per-process key, | ||
| * producing fixed-length digests. This lets `timingSafeEqual` run without | ||
| * throwing on length mismatch or leaking the expected token length, while the | ||
| * random key means the digests reveal nothing about the inputs. | ||
| * @param {string} a | ||
| * @param {string} b | ||
| * @returns {boolean} | ||
| */ | ||
| function safeEqual(a, b) { | ||
| const ha = createHmac('sha256', COMPARE_KEY).update(String(a)).digest(); | ||
Check failureCode scanning / CodeQL Use of password hash with insufficient computational effort High
Password from
a call to header Error loading related location Loading Password from a call to header Error loading related location Loading |
||
| const hb = createHmac('sha256', COMPARE_KEY).update(String(b)).digest(); | ||
Check failureCode scanning / CodeQL Use of password hash with insufficient computational effort High
Password from
an access to SCANNER_API_TOKEN Error loading related location Loading |
||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
|
||
| return timingSafeEqual(ha, hb); | ||
| } | ||
|
|
||
| /** | ||
| * Hono middleware requiring a valid scanner API token on side-effecting routes. | ||
| * @param {import('hono').Context} c | ||
| * @param {() => Promise<void>} next | ||
| */ | ||
| export async function requireScannerAuth(c, next) { | ||
| const token = process.env.SCANNER_API_TOKEN || ''; | ||
|
|
||
| if (!token) { | ||
| if (!missingTokenWarned) { | ||
| logger.warn( | ||
| 'SCANNER_API_TOKEN is not set — scanner side-effecting routes (scan/export) are UNAUTHENTICATED. ' + | ||
| 'Set SCANNER_API_TOKEN to require a bearer token / X-API-Key.' | ||
| ); | ||
| missingTokenWarned = true; | ||
| } | ||
| return next(); | ||
| } | ||
|
|
||
| const provided = extractToken(c); | ||
| if (!provided || !safeEqual(provided, token)) { | ||
| return c.json({ error: 'Unauthorized' }, 401); | ||
| } | ||
|
|
||
| return next(); | ||
| } | ||
|
|
||
| // Exposed for tests. | ||
| export const _internal = { safeEqual, extractToken }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| /** | ||
| * Tests for scanner authentication middleware (GHSA-ppp9-2hc2-hfg5 hardening). | ||
| */ | ||
|
|
||
| import { describe, it, beforeEach, afterEach } from 'mocha'; | ||
| import { expect, sinon } from './setup.js'; | ||
| import { requireScannerAuth } from '../src/auth.js'; | ||
|
|
||
| /** | ||
| * Build a fake Hono context with the given request headers. | ||
| */ | ||
| const makeContext = (headers = {}) => { | ||
| const lower = {}; | ||
| for (const [k, v] of Object.entries(headers)) { | ||
| lower[k.toLowerCase()] = v; | ||
| } | ||
| return { | ||
| req: { | ||
| header: name => lower[String(name).toLowerCase()], | ||
| }, | ||
| json: sinon.stub().callsFake((body, status) => ({ body, status: status || 200 })), | ||
| }; | ||
| }; | ||
|
|
||
| describe('requireScannerAuth', () => { | ||
| const originalToken = process.env.SCANNER_API_TOKEN; | ||
|
|
||
| afterEach(() => { | ||
| sinon.restore(); | ||
| if (originalToken === undefined) { | ||
| delete process.env.SCANNER_API_TOKEN; | ||
| } else { | ||
| process.env.SCANNER_API_TOKEN = originalToken; | ||
| } | ||
| }); | ||
|
|
||
| describe('when SCANNER_API_TOKEN is not configured', () => { | ||
| beforeEach(() => { | ||
| delete process.env.SCANNER_API_TOKEN; | ||
| }); | ||
|
|
||
| it('allows the request through (backward compatible)', async () => { | ||
| const c = makeContext(); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.calledOnce).to.be.true; | ||
| expect(c.json.called).to.be.false; | ||
| }); | ||
| }); | ||
|
|
||
| describe('when SCANNER_API_TOKEN is configured', () => { | ||
| const TOKEN = 'super-secret-token'; | ||
|
|
||
| beforeEach(() => { | ||
| process.env.SCANNER_API_TOKEN = TOKEN; | ||
| }); | ||
|
|
||
| it('rejects a request with no credential (401)', async () => { | ||
| const c = makeContext(); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.called).to.be.false; | ||
| expect(c.json.calledWith(sinon.match.any, 401)).to.be.true; | ||
| }); | ||
|
|
||
| it('rejects a wrong bearer token (401)', async () => { | ||
| const c = makeContext({ Authorization: 'Bearer wrong-token' }); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.called).to.be.false; | ||
| expect(c.json.calledWith(sinon.match.any, 401)).to.be.true; | ||
| }); | ||
|
|
||
| it('allows a correct bearer token', async () => { | ||
| const c = makeContext({ Authorization: `Bearer ${TOKEN}` }); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.calledOnce).to.be.true; | ||
| expect(c.json.called).to.be.false; | ||
| }); | ||
|
|
||
| it('allows a correct X-API-Key', async () => { | ||
| const c = makeContext({ 'X-API-Key': TOKEN }); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.calledOnce).to.be.true; | ||
| expect(c.json.called).to.be.false; | ||
| }); | ||
|
|
||
| it('rejects a wrong X-API-Key (401)', async () => { | ||
| const c = makeContext({ 'X-API-Key': 'nope' }); | ||
| const next = sinon.stub().resolves(); | ||
| await requireScannerAuth(c, next); | ||
| expect(next.called).to.be.false; | ||
| expect(c.json.calledWith(sinon.match.any, 401)).to.be.true; | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.