Skip to content
Draft
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
76 changes: 76 additions & 0 deletions csharp/src/security/CWE-345/UnverifiedJwtPayloadDecode.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
A JSON Web Token (JWT) has three base64url-encoded segments separated by <code>.</code>: a header, a payload
with the claims, and a signature. The claims can only be trusted after the signature has been checked against
a trusted key. Anyone can create a token with any payload, for example one that claims an administrator role.
</p>
<p>
This query reports code that splits a token on <code>.</code> and base64-decodes the payload segment
(index <code>1</code>) without evidence that the signature has been verified. Claims that are decoded without
being authenticated can be forged.
</p>
</overview>

<recommendation>
<p>
Do not parse JWT claims by hand. Use a JWT library such as
<code>System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken</code> or
<code>Microsoft.IdentityModel.JsonWebTokens.JsonWebTokenHandler.ValidateTokenAsync</code>, with
<code>TokenValidationParameters</code> that require a valid signature, and read the claims from the validated result.
</p>
<p>
If the token was already validated somewhere else, for example by a remote authentication service, read the
claims from that validated result, not from the raw token string.
</p>
</recommendation>

<example>
<p>
In the following example, the payload is decoded and the <code>roles</code> claim is trusted without checking the
signature. An attacker can send a forged token with <code>"roles": ["ADMIN"]</code>:
</p>

<sample src="UnverifiedJwtPayloadDecodeBad.cs" />

<p>
The following example validates the token signature before it reads any claims:
</p>

<sample src="UnverifiedJwtPayloadDecodeGood.cs" />
</example>

<section title="Known limitations">
<ul>
<li>
A read of the signature segment (index <code>2</code>) of the same <code>Split</code> result counts as evidence of
verification only when it, or its base64-decoded value, reaches a comparison or an argument of a method whose name
contains <code>verify</code> or <code>equals</code>. The query does not check that the result of that comparison
is used, or that the comparison is a correct cryptographic check. Logging the segment does not count.
</li>
<li>
Validation by a library is recognized when a call to <code>JwtSecurityTokenHandler.ValidateToken</code> on the same
token dominates the decode, and the <code>TokenValidationParameters</code> object initializer passed to it enables
<code>ValidateIssuerSigningKey</code> and sets <code>IssuerSigningKey</code>. For
<code>JsonWebTokenHandler.ValidateTokenAsync</code>, the decode must also be dominated by an
<code>if (!result.IsValid)</code> check whose branch throws.
</li>
<li>
Code that has the token validated elsewhere before it decodes the payload, for example by a remote service, by
middleware, by a custom helper, or with parameters that are configured indirectly, is still reported.
</li>
</ul>
</section>

<references>
<li>CWE: <a href="https://cwe.mitre.org/data/definitions/345.html">CWE-345: Insufficient Verification of Data Authenticity</a>.</li>
<li>CWE: <a href="https://cwe.mitre.org/data/definitions/347.html">CWE-347: Improper Verification of Cryptographic Signature</a>.</li>
<li>IETF: <a href="https://www.rfc-editor.org/rfc/rfc7519">RFC 7519: JSON Web Token (JWT)</a>.</li>
<li>OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html">JSON Web Token Cheat Sheet</a>.</li>
</references>

</qhelp>
170 changes: 170 additions & 0 deletions csharp/src/security/CWE-345/UnverifiedJwtPayloadDecode.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/**
* @name JWT payload decoded without signature verification
* @description Base64-decoding the payload segment of a JSON Web Token without verifying
* the token signature lets an attacker forge claims such as roles or user
* identifiers.
* @kind path-problem
* @problem.severity error
* @security-severity 8.1
* @precision medium
* @id githubsecuritylab/cs/unverified-jwt-payload-decode
* @tags security
* experimental
* external/cwe/cwe-345
* external/cwe/cwe-347
*/

import csharp
import semmle.code.csharp.dataflow.TaintTracking
import UnverifiedJwtPayloadDecodeFlow::PathGraph

/** A call to `string.Split` whose separator is the JWT segment separator `.`. */
class JwtSplitCall extends MethodCall {
JwtSplitCall() {
this.getTarget().hasFullyQualifiedName("System", "String", "Split") and
exists(Expr sep | sep = this.getArgument(0) |
sep.(CharLiteral).getValue() = "."
or
sep.(StringLiteral).getValue() = "."
)
}

/** Holds if `aa` reads segment `index` of the result of this call. */
predicate readsSegment(ArrayAccess aa, int index) {
DataFlow::localExprFlow(this, aa.getQualifier()) and
aa.getIndex(0).getValue().toInt() = index
}

/**
* Gets an expression that holds the signature segment, or its decoded value. Local taint
* steps follow conversions such as `byte[]` to `ReadOnlySpan<byte>`.
*/
private Expr getASignatureValue() {
exists(ArrayAccess signature | this.readsSegment(signature, 2) |
TaintTracking::localExprTaint(signature, result)
or
exists(Base64DecodeCall decoder |
DataFlow::localExprFlow(signature, decoder.getArgument(0)) and
TaintTracking::localExprTaint(decoder, result)
)
)
}

/**
* Holds if the signature segment flows into a comparison, or into an argument of a
* method whose name contains `verify` or `equals`.
*/
predicate verifiesSignature() {
exists(ComparisonOperation comparison | this.getASignatureValue() = comparison.getAnOperand())
or
exists(MethodCall verification |
this.getASignatureValue() = verification.getAnArgument() and
verification.getTarget().getName().toLowerCase().matches(["%verify%", "%equals%"])
)
}
}

/**
* An access to the payload segment (index 1) of a JWT split on `.`, where the
* signature segment (index 2) is not used in a verification-like operation.
*/
class JwtPayloadSegment extends ArrayAccess {
JwtSplitCall split;

JwtPayloadSegment() {
split.readsSegment(this, 1) and
not split.verifiesSignature()
}

/** Gets the `Split` call whose result this access reads. */
JwtSplitCall getSplitCall() { result = split }
}

/** A call to a base64 decoding method. */
class Base64DecodeCall extends MethodCall {
Base64DecodeCall() {
this.getTarget()
.hasFullyQualifiedName("System", "Convert", ["FromBase64String", "TryFromBase64String"])
or
this.getTarget()
.hasFullyQualifiedName("Microsoft.IdentityModel.Tokens", "Base64UrlEncoder",
["Decode", "DecodeBytes"])
or
this.getTarget()
.hasFullyQualifiedName("Microsoft.AspNetCore.WebUtilities", "WebEncoders", "Base64UrlDecode")
}
}

/**
* Holds if `parameters` comes from a `TokenValidationParameters` object creation whose
* initializer enables `ValidateIssuerSigningKey` and sets `IssuerSigningKey`.
*/
predicate hasSignatureValidationEnabled(Expr parameters) {
exists(
ObjectCreation creation, ObjectInitializer initializer, MemberInitializer enabled,
MemberInitializer key
|
DataFlow::localExprFlow(creation, parameters) and
initializer = creation.getInitializer() and
enabled = initializer.getAMemberInitializer() and
enabled.getLeftOperand().(PropertyAccess).getTarget().hasName("ValidateIssuerSigningKey") and
enabled.getRightOperand().(BoolLiteral).getBoolValue() = true and
key = initializer.getAMemberInitializer() and
key.getLeftOperand().(PropertyAccess).getTarget().hasName("IssuerSigningKey")
)
}

/**
* Holds if the token whose payload is `payload` is validated by a JWT library, with
* signing key validation enabled, before `decoder` runs.
*/
predicate validatedBeforeDecode(JwtPayloadSegment payload, Base64DecodeCall decoder) {
exists(JwtSplitCall split, MethodCall validation |
split = payload.getSplitCall() and
validation
.getTarget()
.hasFullyQualifiedName("System.IdentityModel.Tokens.Jwt", "JwtSecurityTokenHandler",
"ValidateToken") and
DataFlow::localExprFlow(validation.getArgument(0), split.getQualifier()) and
hasSignatureValidationEnabled(validation.getArgument(1)) and
validation.getControlFlowNode().dominates(decoder.getControlFlowNode())
)
or
exists(
JwtSplitCall split, MethodCall validation, AwaitExpr awaited, IfStmt guard,
LogicalNotExpr invalidResult, PropertyAccess isValid, ThrowStmt failure
|
split = payload.getSplitCall() and
validation
.getTarget()
.hasFullyQualifiedName("Microsoft.IdentityModel.JsonWebTokens", "JsonWebTokenHandler",
"ValidateTokenAsync") and
DataFlow::localExprFlow(validation.getArgument(0), split.getQualifier()) and
hasSignatureValidationEnabled(validation.getArgument(1)) and
awaited.getExpr() = validation and
DataFlow::localExprFlow(awaited, isValid.getQualifier()) and
isValid.getTarget().hasName("IsValid") and
invalidResult = guard.getCondition() and
invalidResult.getOperand() = isValid and
failure.getParent*() = guard.getThen() and
guard.getControlFlowNode().dominates(decoder.getControlFlowNode())
Comment on lines +149 to +150
)
}

module UnverifiedJwtPayloadDecodeConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { source.asExpr() instanceof JwtPayloadSegment }

predicate isSink(DataFlow::Node sink) {
exists(Base64DecodeCall decoder | sink.asExpr() = decoder.getArgument(0))
}
}

module UnverifiedJwtPayloadDecodeFlow = TaintTracking::Global<UnverifiedJwtPayloadDecodeConfig>;

from UnverifiedJwtPayloadDecodeFlow::PathNode source, UnverifiedJwtPayloadDecodeFlow::PathNode sink
where
UnverifiedJwtPayloadDecodeFlow::flowPath(source, sink) and
not validatedBeforeDecode(source.getNode().asExpr(), sink.getNode().asExpr().getParent())
select sink.getNode(), source, sink,
"$@ is base64-decoded without the token signature being verified, so its claims can be forged.",
source.getNode(), "This JWT payload segment"
7 changes: 7 additions & 0 deletions csharp/src/security/CWE-345/UnverifiedJwtPayloadDecodeBad.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
public static IList<string> GetRoles(string jwt)
{
var payload = jwt.Split('.')[1];
payload = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
var json = Encoding.UTF8.GetString(Convert.FromBase64String(payload)); // BAD
return JObject.Parse(json)["roles"].Values<string>().ToList();
}
12 changes: 12 additions & 0 deletions csharp/src/security/CWE-345/UnverifiedJwtPayloadDecodeGood.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public static IEnumerable<string> GetRoles(string jwt, SecurityKey key)
{
var parameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
ValidIssuer = "https://issuer.example",
ValidAudience = "my-api"
};
var principal = new JwtSecurityTokenHandler().ValidateToken(jwt, parameters, out _); // GOOD
return principal.FindAll(ClaimTypes.Role).Select(c => c.Value);
}
9 changes: 9 additions & 0 deletions csharp/test/TestUtilities/InlineExpectationsTestQuery.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/**
* @kind test-postprocess
*/

private import csharp
private import codeql.util.test.InlineExpectationsTest as T
private import utils.test.internal.InlineExpectationsTestImpl
import T::TestPostProcessing
import T::TestPostProcessing::Make<Impl>
Loading