Skip to content

[New Query - githubsecuritylab/cs/unverified-jwt-payload-decode] - JWT payload decoded without signature verification - #275

Draft
felickz wants to merge 4 commits into
mainfrom
copilot/add-query-for-jwt-payload
Draft

felickz wants to merge 4 commits into
mainfrom
copilot/add-query-for-jwt-payload

Conversation

@felickz

@felickz felickz commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Adds a C# query that reports code that splits a JWT on . and base64-decodes the payload segment when nothing shows the signature was checked (CWE-345, CWE-347). Anyone can create a token with any claims, so claims read this way can be forged.

var payload = jwt.Split('.')[1];
payload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
var json = Encoding.UTF8.GetString(Convert.FromBase64String(payload)); // reported

No existing query covers this. The queries in csharp/src/security/JsonWebTokenHandler/ and the standard C# queries only inspect TokenValidationParameters and validation delegates.

Query (csharp/src/security/CWE-345/UnverifiedJwtPayloadDecode.ql)

  • Source: element [1] of a Split('.') or Split(".") result, found by local flow from the call.

  • Sinks: the first argument of:

    • Convert.FromBase64String and Convert.TryFromBase64String
    • Base64UrlEncoder.Decode and Base64UrlEncoder.DecodeBytes
    • WebEncoders.Base64UrlDecode
  • Flow: global taint tracking, so PadRight, Replace and helper methods are followed.

  • Manual-verification exclusion: a source is dropped when element [2] of the same Split result, or its decoded bytes, reaches a comparison operator or an argument of a method whose name contains verify or equals.

    • Logging the signature does not count.
    • The last step uses local taint because CryptographicOperations.FixedTimeEquals takes ReadOnlySpan<byte>. The implicit byte[] conversion breaks plain local flow and would otherwise flag correct HMAC checks.
  • Library-validation exclusion: the decode is not reported when one of these runs before it, checked by control-flow-node dominance:

    • JwtSecurityTokenHandler.ValidateToken on the same token.
    • JsonWebTokenHandler.ValidateTokenAsync on the same token, followed by an if (!result.IsValid) throw check.

    In both cases the TokenValidationParameters initializer must set ValidateIssuerSigningKey = true and IssuerSigningKey.

  • Metadata: path-problem, precision medium, security-severity 8.1, tagged experimental. The default csharp.qls suite selects it.

  • Query help: .qhelp with BAD and GOOD samples and a known-limitations section.

Tests (csharp/test/security/CWE-345/UnverifiedJwtPayloadDecode/)

  • Inline expectations: cases are marked // $ Alert and // $ Source. There are 11 BAD cases (one per sink, helper flow, logged signature, decode before validation, disabled signing-key validation, unchecked async result) and 7 GOOD ones (header-only decode, HMAC with FixedTimeEquals, != comparison, library validation sync and async, non-. split).
  • Stubs: only the shared stubs under codeql/csharp/ql/test/resources/stubs (JWT 7.7.1, Newtonsoft.Json, ASP.NET Core). There is no custom stub file.
  • New csharp/test/TestUtilities/InlineExpectationsTestQuery.ql: a thin wrapper around the upstream post-processor. The copy in the cached codeql/csharp-all package cannot be compiled from a qlref in this repository.

For review

  • Security or audit: the query does not show the token is attacker-controlled. A token already validated elsewhere (remote service, middleware, custom helper, indirectly built parameters) is still reported. Please confirm that medium precision in the default suite is right; the alternative is audit/ at very-low precision.
  • Detection limits: only Split with a . literal is recognized. The synchronous JsonWebTokenHandler.ValidateToken is not treated as validation.
  • True positive from a real project: to be added by the maintainer.
  • Follow-up: bump the version of githubsecuritylab/codeql-csharp-queries at release.

Copilot AI balanced review requested due to automatic review settings November 26, 2026 06:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot wasn't able to review any files in this pull request. Check if the Files changed in this pull request are included in default exclusions.

…with tests

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 06:44
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
@felickz felickz changed the title [WIP] Add query for JWT payload decoding without signature check [New Query - githubsecuritylab/cs/unverified-jwt-payload-decode] - JWT payload decoded without signature verification Nov 26, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical suppression flaws can hide unverified JWT claim use when signature checks are late or optional, validation failures are caught, or invalid-result rejection is conditional.

3 open issues

Review effort: Balanced

@felickz

felickz commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

@copilot Please address the three open review findings, each with a regression case in the test:

  1. Exclude only decodes that verification dominates: tie the exclusion to the source and decode pair, and drop a result only when the read of the signature segment dominates the decode. Add a late check and an optional check (if (checkSignature)) as alerts.
  2. Require successful validation: a validation call whose failure is caught and ignored must not suppress the result. Add the caught failure as an alert.
  3. Require the valid-result check to guard the decode: suppress only when the decode is reached solely through the valid branch, not when a throw merely exists in the invalid branch. Add the conditional throw as an alert.

Keep these checks local to the method (dominance and guards), without another global flow. Rerun the test and the gates of your profile, and report the alert count before and after. The Build CodeQL Packs run on the current head is still in progress: check its result and fix any failure.

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings December 1, 2026 19:01

Copilot AI commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

@copilot Please address the three open review findings, each with a regression case in the test:

  1. [Exclude only decodes that verification dominates](https://github.com/GitHubSecurityLab/CodeQL-Comm...

Fixed in 585b6cb. Targeted alerts: 11 before → 31 after, including the added regressions. Pinned-CLI test, strict compile, format, help and suite checks passed. The original-head Build CodeQL Packs run and results validation passed; the new commit has not yet been covered by that run.

Comment on lines +287 to +291
if (!validation.IsValid)
{
if (reject)
throw new UnauthorizedAccessException();
}
Comment on lines +270 to +272
catch (Exception)
{
}
Comment on lines +311 to +313
catch (Exception)
{
}
Comment on lines +334 to +336
catch (Exception)
{
}
Comment on lines +384 to +386
catch (Exception)
{
}
Comment on lines +469 to +471
catch (Exception)
{
}
Comment on lines +486 to +488
catch (Exception)
{
}
Comment on lines +270 to +272
catch (Exception)
{
}
Comment on lines +311 to +313
catch (Exception)
{
}
Comment on lines +334 to +336
catch (Exception)
{
}

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

A critical finding remains: the Boolean status from Convert.TryFromBase64String is treated as decoded signature data, suppressing alerts for arbitrary base64-decodable signatures without verification.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

High severity Convert.TryFromBase64String returns a Boolean status, but this branch treats it as decoded…

csharp/​src/​security/​CWE-345/​UnverifiedJwtPayloadDecode.ql:51

Convert.TryFromBase64String returns a Boolean status, but this branch treats it as decoded signature data. Consequently, if (Convert.TryFromBase64String(parts[2], buffer, out var n) == true) return Base64UrlEncoder.Decode(parts[1]); suppresses the alert even though an arbitrary base64-decodable signature passes the check. Exclude this status return from signature values and add a regression for this case; any support for decoded signature bytes should track the output buffer instead.

3 resolved since last review

Review effort: Balanced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C#: add a query for a JWT payload that is decoded without checking its signature

3 participants