This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Use cryptography based JWT parser for increased speed
Switches to using python cryptography library instead of jose/jwt (which relied on python ecdsa library). Also discovered lots of fun discrepencies between how ecdsa and libssl sign things. closes #785
- Loading branch information
Showing
2 changed files
with
103 additions
and
17 deletions.
There are no files selected for viewing
This file contains 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 @@ | ||
import base64 | ||
import binascii | ||
import json | ||
from cryptography.hazmat.backends import default_backend | ||
from cryptography.hazmat.primitives.asymmetric import ec | ||
from cryptography.hazmat.primitives import hashes | ||
|
||
from pyasn1.type import univ, namedtype | ||
from pyasn1.codec.der.encoder import encode | ||
|
||
|
||
"""Why hand roll? | ||
Most python JWT libraries either use a python elliptic curve library directly, | ||
or call one that does, or is abandoned, or a dozen other reasons. | ||
After spending half a day looking for reasonable replacements, I decided to | ||
just write the functions we need directly. | ||
THIS IS NOT A FULL JWT REPLACEMENT. | ||
""" | ||
|
||
|
||
def repad(string): | ||
# type: (str) -> str | ||
"""Adds padding to strings for base64 decoding""" | ||
if len(string) % 4: | ||
string += '===='[len(string) % 4:] | ||
return string | ||
|
||
|
||
class VerifyJWT: | ||
|
||
def __init__(self): # pragma: no cover | ||
pass | ||
|
||
@classmethod | ||
def raw_sig_to_der(cls, auth): | ||
# type: (cls, str) -> str | ||
"""Fix the JWT auth token. | ||
The `ecdsa` library signs using a raw, 32octet pair of values (r,s). | ||
Cryptography, which uses OpenSSL, uses a DER sequence of (s, r). | ||
This function converts the raw ecdsa to DER. | ||
""" | ||
payload, asig = auth.rsplit(".", 1) | ||
sig = base64.urlsafe_b64decode(repad(asig).encode('utf8')) | ||
if len(sig) != 64: | ||
return auth | ||
|
||
# ecdsa and openssl transpose the "r" and "s" values of the signatures. | ||
# for ecdsa signature is (r, s) | ||
# for openssl, signature is (s, r) | ||
# It's ok, though, because neither label them, even though openssl | ||
# uses namedtypes, with the names set to "" | ||
# | ||
# Oh frabjous day! | ||
ds = univ.Sequence( | ||
componentType=namedtype.NamedTypes() | ||
).setComponents( | ||
univ.Integer(int(binascii.hexlify(sig[:32]), 16)), | ||
univ.Integer(int(binascii.hexlify(sig[32:]), 16)), | ||
) | ||
encoded = encode(ds) | ||
new_sig = base64.urlsafe_b64encode(encoded) | ||
return "{}.{}".format(payload, new_sig) | ||
|
||
@classmethod | ||
def decode(cls, token, key=None, *args, **kwargs): | ||
# type (cls, str, str) -> dict() | ||
"""Decode a web token into a assertion dictionary. | ||
This attempts to rectify both ecdsa and openssl generated | ||
signatures. We use the built-in cryptography library since it wraps | ||
libssl and is faster than the python only approach. | ||
This raises an InvalidSignature exception if the signature fails. | ||
""" | ||
# convert the signature if needed. | ||
token = cls.raw_sig_to_der(token) | ||
sig_material, signature = token.rsplit('.', 1) | ||
pkey = ec.EllipticCurvePublicNumbers.from_encoded_point( | ||
ec.SECP256R1(), | ||
key | ||
).public_key(default_backend()) | ||
# eventually this would be a map of algs to signing algorithms. | ||
|
||
verifier = pkey.verifier( | ||
base64.urlsafe_b64decode(repad(signature.encode())), | ||
ec.ECDSA(hashes.SHA256())) | ||
verifier.update(sig_material.encode()) | ||
# This will raise an InvalidSignature exception if failure. | ||
# It will be captured externally. | ||
verifier.verify() | ||
return json.loads( | ||
base64.urlsafe_b64decode(repad(sig_material.split('.')[1]))) |
This file contains 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