CVE-2022-29217 (Python)

PyJWT is a Python implementation of RFC 7519. PyJWT supports multiple different JWT signing algorithms. With JWT, an attacker submitting the JWT token can choose the used signing algorithm. The PyJWT library requires that the application chooses what algorithms are supported. The application can specify `jwt.algorithms.get_default_algorithms()` to get support for all algorithms, or specify a single algorithm. The issue is not that big as `algorithms=jwt.algorithms.get_default_algorithms()` has to be used. Users should upgrade to v2.4.0 to receive a patch for this issue. As a workaround, always be explicit with the algorithms that are accepted and expected when decoding.

Weakness:
CWE-327: name: Use of a Broken or Risky Cryptographic Algorithm
description: The product uses a broken or risky cryptographic algorithm or protocol.

Repository: https://github.com/jpadilla/pyjwt

Vulnerable code:
file_path: jwt/algorithms.py
snippet:     def prepare_key(self, key):
        key = force_bytes(key)

        invalid_strings = [
            b"-----BEGIN PUBLIC KEY-----",
            b"-----BEGIN CERTIFICATE-----",
            b"-----BEGIN RSA PUBLIC KEY-----",
            b"ssh-rsa",
        ]

        if any(string_value in key for string_value in invalid_strings):
            raise InvalidKeyError(
                "The specified key is an asymmetric key or x509 certificate and"
                " should not be used as an HMAC secret."
            )

        return key

file_path: jwt/algorithms.py
snippet:         def prepare_key(self, key):

            if isinstance(
                key,
                (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey),
            ):
                return key

            if isinstance(key, (bytes, str)):
                if isinstance(key, str):
                    key = key.encode("utf-8")
                str_key = key.decode("utf-8")

                if "-----BEGIN PUBLIC" in str_key:
                    return load_pem_public_key(key)
                if "-----BEGIN PRIVATE" in str_key:
                    return load_pem_private_key(key, password=None)
                if str_key[0:4] == "ssh-":
                    return load_ssh_public_key(key)

            raise TypeError("Expecting a PEM-formatted or OpenSSH key.")

Fixed code:
file_path: jwt/algorithms.py
snippet:     def prepare_key(self, key):
        key = force_bytes(key)

        if is_pem_format(key) or is_ssh_key(key):
            raise InvalidKeyError(
                "The specified key is an asymmetric key or x509 certificate and"
                " should not be used as an HMAC secret."
            )

        return key

file_path: jwt/algorithms.py
snippet:         def prepare_key(self, key):
            if isinstance(key, (bytes, str)):
                if isinstance(key, str):
                    key = key.encode("utf-8")
                str_key = key.decode("utf-8")

                if "-----BEGIN PUBLIC" in str_key:
                    key = load_pem_public_key(key)
                elif "-----BEGIN PRIVATE" in str_key:
                    key = load_pem_private_key(key, password=None)
                elif str_key[0:4] == "ssh-":
                    key = load_ssh_public_key(key)

            # Explicit check the key to prevent confusing errors from cryptography
            if not isinstance(
                key,
                (Ed25519PrivateKey, Ed25519PublicKey, Ed448PrivateKey, Ed448PublicKey),
            ):
                raise InvalidKeyError(
                    "Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for EdDSA algorithms"
                )

            return key

file_path: jwt/utils.py
snippet: 

# Based on https://github.com/hynek/pem/blob/7ad94db26b0bc21d10953f5dbad3acfdfacf57aa/src/pem/_core.py#L224-L252
_PEMS = {
    b"CERTIFICATE",
    b"TRUSTED CERTIFICATE",
    b"PRIVATE KEY",
    b"PUBLIC KEY",
    b"ENCRYPTED PRIVATE KEY",
    b"OPENSSH PRIVATE KEY",
    b"DSA PRIVATE KEY",
    b"RSA PRIVATE KEY",
    b"RSA PUBLIC KEY",
    b"EC PRIVATE KEY",
    b"DH PARAMETERS",
    b"NEW CERTIFICATE REQUEST",
    b"CERTIFICATE REQUEST",
    b"SSH2 PUBLIC KEY",
    b"SSH2 ENCRYPTED PRIVATE KEY",
    b"X509 CRL",
}

_PEM_RE = re.compile(
    b"----[- ]BEGIN ("
    + b"|".join(_PEMS)
    + b""")[- ]----\r?
.+?\r?
----[- ]END \\1[- ]----\r?\n?""",
    re.DOTALL,
)

file_path: jwt/utils.py
snippet: def is_pem_format(key: bytes) -> bool:
    return bool(_PEM_RE.search(key))


# Based on https://github.com/pyca/cryptography/blob/bcb70852d577b3f490f015378c75cba74986297b/src/cryptography/hazmat/primitives/serialization/ssh.py#L40-L46
_CERT_SUFFIX = b"-cert-v01@openssh.com"
_SSH_PUBKEY_RC = re.compile(br"\A(\S+)[ \t]+(\S+)")
_SSH_KEY_FORMATS = [
    b"ssh-ed25519",
    b"ssh-rsa",
    b"ssh-dss",
    b"ecdsa-sha2-nistp256",
    b"ecdsa-sha2-nistp384",
    b"ecdsa-sha2-nistp521",
]

file_path: jwt/utils.py
snippet: def is_ssh_key(key: bytes) -> bool:
    if any(string_value in key for string_value in _SSH_KEY_FORMATS):
        return True

    ssh_pubkey_match = _SSH_PUBKEY_RC.match(key)
    if ssh_pubkey_match:
        key_type = ssh_pubkey_match.group(1)
        if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]:
            return True

    return False