Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 5 additions & 0 deletions change-notes/2023-09-13-JWT-signature-queries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
category: newQuery
---
* Added JWT Confusion query `go/jwt-alg-confusion`
* Added JWT Parsing without Signature Check query `go/jwt-insecure-signing`
1 change: 1 addition & 0 deletions go/ql/lib/go.qll
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import semmle.go.frameworks.Glog
import semmle.go.frameworks.GoMicro
import semmle.go.frameworks.GoRestfulHttp
import semmle.go.frameworks.Gqlgen
import semmle.go.frameworks.JWT
import semmle.go.frameworks.K8sIoApimachineryPkgRuntime
import semmle.go.frameworks.K8sIoApiCoreV1
import semmle.go.frameworks.K8sIoClientGo
Expand Down
87 changes: 87 additions & 0 deletions go/ql/lib/semmle/go/frameworks/JWT.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/** Provides models of commonly used functions in common JWT packages. */

import go

/**
* Provides models of commonly used functions in common JWT packages.
*/
module JWT {
string packageLestrrat() { result = package("github.com/lestrrat-go/jwx/v2/jwt", "") }
Comment thread
Kwstubbs marked this conversation as resolved.

string packageLestrratv1() { result = package("github.com/lestrrat-go/jwx/jwt", "") }
Comment thread
Kwstubbs marked this conversation as resolved.

string packagePathModern() {
result = package(["github.com/golang-jwt/jwt/v5", "github.com/golang-jwt/jwt/v4"], "")
Comment thread
Kwstubbs marked this conversation as resolved.
}

string packagePathOld() { result = package("github.com/golang-jwt/jwt", "") }

class NewParser extends Function {
/**
* Call in golang-jwt to create new parser.
*/
NewParser() { this.hasQualifiedName(packagePathModern(), "NewParser") }
}

class WithValidMethods extends Function {
/**
* Call to WithValidMethods in golang-jwt to specify allowed algorithms.
*/
WithValidMethods() { this.hasQualifiedName(packagePathModern(), "WithValidMethods") }
}

class SafeJwtParserMethod extends Method {
/**
* Methods to parse token that check token signature.
*/
SafeJwtParserMethod() {
this.hasQualifiedName(packagePathModern(), "Parser", ["Parse", "ParseWithClaims"])
}
}

class SafeJwtParserFunc extends Function {
/**
* Functions to parse token that check token signature.
*/
SafeJwtParserFunc() {
this.hasQualifiedName([packagePathModern(), packagePathOld()], ["Parse", "ParseWithClaims"])
}
}

class UnafeJwtParserMethod extends Method {
Comment thread
Kwstubbs marked this conversation as resolved.
/**
* Methods to parse token that don't token signature.
*/
UnafeJwtParserMethod() {
this.hasQualifiedName(packagePathModern(), "Parser", "ParseUnverified")
}
}

class LestrratParse extends Function {
/**
* v2 Function to parse token that check token signature.
*/
LestrratParse() { this.hasQualifiedName(packageLestrrat(), "Parse") }
}
Comment on lines +64 to +69
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.

This model isn't used anywhere. Did you mean to use it somewhere? Or did you model it for completeness? Consider deleting - the model can easily be added in future if it is needed.


class LestrratParsev1 extends Function {
/**
* v1 Function to parse token that check token signature.
*/
LestrratParsev1() { this.hasQualifiedName(packageLestrratv1(), "Parse") }
}

class LestrratVerify extends Function {
/**
* Funciton included as parse option to verify token.
*/
LestrratVerify() { this.hasQualifiedName(packageLestrratv1(), "WithVerify") }
}

class LestrratParseInsecure extends Function {
/**
* Funciton to parse token that don't check signature.
*/
LestrratParseInsecure() { this.hasQualifiedName(packageLestrrat(), "ParseInsecure") }
}
}
34 changes: 34 additions & 0 deletions go/ql/src/experimental/CWE-347/Algorithm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"fmt"

"github.com/golang-jwt/jwt/v5"
)

type JWT struct {
privateKey []byte
publicKey []byte
}

func (j JWT) Validate(token string) (interface{}, error) {
key, err := jwt.ParseRSAPublicKeyFromPEM(j.publicKey)
if err != nil {
return "", fmt.Errorf("validate: parse key: %w", err)
}

tok, err := jwt.Parse(token, func(jwtToken *jwt.Token) (interface{}, error) {

return key, nil
})
if err != nil {
return nil, fmt.Errorf("validate: %w", err)
}

claims, ok := tok.Claims.(jwt.MapClaims)
if !ok || !tok.Valid {
return nil, fmt.Errorf("validate: invalid")
}

return claims["dat"], nil
}
35 changes: 35 additions & 0 deletions go/ql/src/experimental/CWE-347/JWTParsingAlgorithm.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Not verifying the JWT algorithim present in a JWT token when verifying its signature may result in algorithim confusion.
</p>

</overview>
<recommendation>

<p>
Before presenting a key to verify a signature, ensure that the key corresponds to the algorithim present in the JWT token.
</p>

</recommendation>
<example>

<p>
The following code uses the asymmetric public key to verify the JWT token and assumes that the algorithim is RSA.
By not checking the signature, an attacker can specify the HMAC option and use the same public key, which is assumed to be public and often at endpoint /jwt/jwks.jso, to sign the JWT token and bypass authentication.
</p>

<sample src="Algorithm.go" />

</example>

<references>
<li>Pentesterlab: <a
href="https://blog.pentesterlab.com/exploring-algorithm-confusion-attacks-on-jwt-exploiting-ecdsa-23f7ff83390f">Exploring Algorithm Confusion Attacks on JWT</a>.
</li>
</references>

</qhelp>
41 changes: 41 additions & 0 deletions go/ql/src/experimental/CWE-347/JWTParsingAlgorithm.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* @name JWT Method Check
* @description Trusting the Method provided by the incoming JWT token may lead to an algorithim confusion
* @kind problem
* @problem.severity error
* @security-severity 8.0
* @precision medium
* @id go/jwt-alg-confusion
* @tags security
* external/cwe/cwe-347
*/

import go
import JWT
import DataFlow

from CallNode c, Function func
where
(
c.getTarget() = func and
// //Flow from NewParser to Parse (check that this call to Parse does not use a Parser that sets Valid Methods)
(
func instanceof SafeJwtParserMethod and
not exists(CallNode c2, WithValidMethods wvm, NewParser m |
c2.getTarget() = m and
(
c2.getCall().getAnArgument() = wvm.getACall().asExpr() and
DataFlow::localFlow(c2.getAResult(), c.getReceiver())
)
)
or
//ParserFunc creates a new default Parser on call that accepts all methods
func instanceof SafeJwtParserFunc
) and
//Check that the Parse(function or method) does not check the Token Method field, which most likely is a check for method type
not exists(Field f |
f.hasQualifiedName(packagePathModern(), "Token", "Method") and
f.getARead().getRoot() = c.getCall().getAnArgument()
)
)
select c, "This Parse Call to Verify the JWT token may be vulnerable to algorithim confusion"
29 changes: 29 additions & 0 deletions go/ql/src/experimental/CWE-347/JWTParsingSignature.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @name JWT Insecure Parsing
* @description Parsing JWT tokens without checking the signature may result in an authentication bypass
* @kind problem
* @problem.severity error
* @security-severity 8.0
* @precision medium
* @id go/jwt-insecure-signing
* @tags security
* external/cwe/cwe-347
*/

import go
import JWT
import DataFlow

from CallNode c, LestrratParsev1 lp
where
c.getTarget() instanceof LestrratParseInsecure
or
c.getTarget() instanceof UnafeJwtParserMethod
or
c.getTarget() = lp and
not exists(LestrratVerify lv |
c.getCall().getAnArgument() = lv.getACall().asExpr() and
not c.getCall().getArgument(0) = lv.getACall().asExpr()
)
Comment thread Fixed
select c,
"This call to Parse to accept JWT token does not check the signature, which may allow an attacker to forget tokens"
40 changes: 40 additions & 0 deletions go/ql/test/experimental/CWE-347/JWTInsecureParsingLestrratv2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"time"

"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwk"
"github.com/lestrrat-go/jwx/v2/jwt"
)

func ExampleJWT_Parse() {
jwkSymmetricKey, _ := jwk.FromRaw([]byte(`abracadabra`))
tok, err := jwt.NewBuilder().
Issuer(`github.com/lestrrat-go/jwx`).
IssuedAt(time.Now().Add(-5 * time.Minute)).
Expiration(time.Now().Add(time.Hour)).
Build()
v, err := jwt.Sign(tok, jwt.WithKey(jwa.HS256, jwkSymmetricKey))
if err != nil {
return
}
jwtSignedWithHS256 := v
tok, err = jwt.Parse(jwtSignedWithHS256)
if err != nil {
return
}
tok, err = jwt.Parse(jwtSignedWithHS256, jwt.WithKey(jwa.HS256, jwkSymmetricKey))
if err != nil {
return
}
tok, err = jwt.ParseInsecure(jwtSignedWithHS256)
if err != nil {
return
}
_ = tok
// OUTPUT:
}
func main() {
ExampleJWT_Parse()
}
42 changes: 42 additions & 0 deletions go/ql/test/experimental/CWE-347/JWTInsecureParsingLesttrat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package main

import (
"fmt"
"time"

"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
)

func ExampleJWT_Parse() {
jwkSymmetricKey := []byte(`abracadabra`)
tok, err := jwt.NewBuilder().
Issuer(`github.com/lestrrat-go/jwx`).
IssuedAt(time.Now().Add(-5 * time.Minute)).
Expiration(time.Now().Add(time.Hour)).
Build()
alg := jwa.HS256
v, err := jwt.Sign(tok, alg, jwkSymmetricKey)
if err != nil {
fmt.Errorf(`failed to sign token with HS256: %w`, err)
return
}
jwtSignedWithHS256 := v
//Bad
tok, err = jwt.Parse(jwtSignedWithHS256)
if err != nil {
fmt.Printf("%s\n", err)
return
}
//Good
tok, err = jwt.Parse(jwtSignedWithHS256, jwt.WithVerify(alg, jwkSymmetricKey))
if err != nil {
fmt.Printf("%s\n", err)
return
}
_ = tok
// OUTPUT:
}
func main() {
ExampleJWT_Parse()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
| JWTParsingAlgorithm.go:20:4:23:5 | call to Parse | This Parse Call to Verify the JWT token may be vulnerable to algorithim confusion |
| JWTParsingAlgorithm.go:38:22:41:5 | call to Parse | This Parse Call to Verify the JWT token may be vulnerable to algorithim confusion |
Loading