Skip to content

Support verifying signatures directly with cryptography.x509.Certificate #7939

Closed

Description

@kislyuk

When replacing instances of pyOpenSSL usage with cryptography, most operations are far easier and more logical in cryptography, however one area where cryptography's interface could be more ergonomic is the extraction and application of certificate public keys for verifying. PyOpenSSL provides a high level method, OpenSSL.crypto.verify(), which takes an x509 certificate object, signature, data, and digest algorithm id. This elides the configuration details and API variations between the different public keys and algorithm settings that are included in the x509 certificate metadata. As far as I can tell, there is no equivalent method in cryptography, so all implementers have to write this code themselves every time, which can be hazardous.

This is a feature request for adding a cryptography.x509.Certificate.verify() method with semantics similar to those of OpenSSL.crypto.verify(), or guidance in the documentation for these use cases.

Activity

  1. alex commented on Dec 26, 2022

    @alex
    Member

    To be clear, you're requesting an API to verify that data (bytes) is signed by the public key in the certificate -- not anything to verify that a certificate has a valid signature/chain?

  2. kislyuk commented on Dec 26, 2022

    @kislyuk
    Author

    That's right. I'm aware of the difficulties in implementing certificate chain verification to cryptography's high quality standard, and I expect that it would be best to treat that as a separate effort. This issue is limited to providing less room for error in extracting and applying the public key and signature algorithm settings.

    Thanks for all your hard work on cryptography.

  3. reaperhulk commented on Dec 27, 2022

    @reaperhulk
    Member

    I've implemented this as a quick experiment, but the API is a bit unfortunate due to the goal of papering over the differences in verify APIs. It takes a hash_algorithm but that needs to be None when you have an EdDSA key (where such an algorithm is meaningless except in ph variants, which OpenSSL does not support), so in practice callers still need to know what types of keys they expect to see and what hash algorithms are permissible. Additionally, we need to entirely drop PSS as a supported signature padding for RSA since that requires significant amounts of out of band metadata about parameters.

    I'm not entirely opposed to landing this, but I'm curious what errors you have seen/are worried about? Right now this doesn't seem like much of a win in terms of complexity reduction, but perhaps I'm too close to the problem.

  4. kislyuk commented on Jan 15, 2023

    @kislyuk
    Author

    @reaperhulk would it be acceptable to ignore hash_algorithm for algorithms that don't use it?

    Also, I'm not sure if I understand why PSS could not be supported. My (probably naive) understanding is that the PSS parameters can be encoded in the X.509 certificate as specified in RFC 4055, so a method attached to the certificate would extract those parameters from the certificate and pass them in. Is this not how it works?

    My concern actually relates to this act of extracting signature parameters from the X.509 certificate, since that seems pretty complicated and I would rather trust cryptography to do it right. But also, I feel like any application that uses this higher level API would be able to leverage it to support the full variety of signature algorithms that can be conveyed by X.509 certs in a standard way, instead of e.g. explicitly listing (or assuming) RSA-PKCS1 and/or ECDSA and not supporting RSASSA-PSS or EdDSA. My hope was that the heavy lifting of extracting the parameters could be done in a single trusted place instead of repeated by every application.

  5. reaperhulk commented on Jan 15, 2023

    @reaperhulk
    Member

    I was still having trouble understanding the ask, so I dug through how OpenSSL does this. pyOpenSSL calls EVP_Verify* functions, which in turn find the algorithm by using EVP_PKEY_CTX_new_from_pkey. This relies on OpenSSL knowing the type of the underlying key where it distinguishes between RSA and RSA-PSS as a fundamental type.

    We do not support that behavior in cryptography (partially because the OpenSSL forks don't all support RSA keys with explicit PSS parameters and partially because we're not-so-secretly hoping RSA PSS certificates will just quietly die), so trying to operate that way isn't going to work well for us. Additionally, this model appears to assume that any unconstrained RSA public key can only sign using PKCS1v1.5, which is not actually true (although perhaps it is effectively true in practice due to APIs like this existing). Note that in RFC 4055 section 3.1 it is not a requirement that an RSA key itself have PSS params, only the signature on the certificate.

    So, I'm closer to understanding (I hope!), but in the DSA, ECDSA, and EdDSA cases there are no parameters to extract so signature verification is very straightforward, while for RSA we can't distinguish for the twin reasons of lack of RSA-PSS key support and the "bare RSA must be PKCS1v1.5" situation.

  6. kislyuk commented on Jan 16, 2023

    @kislyuk
    Author

    @reaperhulk thanks, this clarifies things a lot.

    My basic ask was to have either an API that elides the details of X.509 public key extraction and use, or an endorsed piece of documentation on how to do it in applications that use X.509 without TLS. Now I understand that the choice of hash algorithm can't be elided and isn't conveyed by X.509 (correct me if I'm wrong) but perhaps it would be reasonable to specify the expected hash algorithm for signature algorithms that need it, and ignore it for those that don't need it.

    I did a bit of digging and realized that OpenSSL.crypto.verify() is not as smart as I expected it to be. It's able to distinguish between RSA-PKCS1, DSA, and ECDSA keys, but in my tests it couldn't verify with a RSASSA-PSS key or an EdDSA key.

    Using cryptography, in the absence of a single API, an implementer can do something like

    pubkey = cert.public_key()
    if isinstance(pubkey, rsa.RSAPublicKey):
        pubkey.verify(signature, message, ...)
    elif isinstance(pubkey, ec.EllipticCurvePublicKey):
        ...
    

    but that still doesn't solve the RSA-PKCS vs. RSA-PSS issue. To solve that, I have to look in the X.509 fields that cryptography doesn't seem to provide direct access to (asn1crypto.x509.TbsCertificate.load(cert.tbs_certificate_bytes)["subject_public_key_info"]["algorithm"] which can be rsa or rsassa_pss). It also requires quite a bit of X.509 domain knowledge (e.g. I understand cert.signature_algorithm_oid is not what I'm looking for). And I think it's not super ergonomic and doesn't give implementers an opportunity to future-proof their applications for e.g. ed25519 support.

    With all this in mind, I understand the reluctance to support an API for this, but can a recipe be added to https://cryptography.io/en/latest/x509/tutorial/ to outline the endorsed way to do this? Also, could subject_public_key_info.algorithm be exposed in cryptography.X509.Certificate, for those who do need to deal with RSA-PSS?

    this model appears to assume that any unconstrained RSA public key can only sign using PKCS1v1.5, which is not actually true

    Does the use of a PKCS1 OID (https://oidref.com/1.2.840.113549.1.1) not signify that a PKCS1 padding should be used?

    For reference, here's the test code that I used. If I understand correctly, the code in the for loop is what an implementer would have to use today.

    from functools import partial
    from subprocess import call
    
    import OpenSSL.crypto
    from cryptography import x509
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, ed25519
    from asn1crypto.x509 import TbsCertificate
    
    run = partial(call, shell=True, executable="/bin/bash")
    message = b"abc"
    signatures = {}
    
    pss_padding = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH)
    pkcs_padding = padding.PKCS1v15()
    
    run("openssl req -x509 -nodes -subj '/CN=test' -days 1 -newkey rsa -keyout rsa-key.pem -out rsa-cert.pem")
    with open("rsa-cert.pem", "rb") as fh:
        rsa_cert = x509.load_pem_x509_certificate(fh.read())
    with open("rsa-key.pem", "rb") as fh:
        rsa_key = serialization.load_pem_private_key(fh.read(), password=None)
    signatures[rsa_cert] = rsa_key.sign(message, pkcs_padding, hashes.SHA512())
    
    # Does not work on LibreSSL
    run("openssl req -x509 -nodes -subj '/CN=test' -days 1 -newkey rsa-pss -keyout rsapss-key.pem -out rsapss-cert.pem")
    with open("rsapss-cert.pem", "rb") as fh:
        rsapss_cert = x509.load_pem_x509_certificate(fh.read())
    with open("rsapss-key.pem", "rb") as fh:
        rsapss_key = serialization.load_pem_private_key(fh.read(), password=None)
    signatures[rsapss_cert] = rsapss_key.sign(message, pss_padding, hashes.SHA512())
    
    run(
        "openssl req -x509 -nodes -subj '/CN=test' -days 1 -newkey ec:<(openssl ecparam -name secp384r1) -keyout ec-key.pem -out ec-cert.pem"
    )
    with open("ec-cert.pem", "rb") as fh:
        ec_cert = x509.load_pem_x509_certificate(fh.read())
    with open("ec-key.pem", "rb") as fh:
        ec_key = serialization.load_pem_private_key(fh.read(), password=None)
    signatures[ec_cert] = ec_key.sign(message, ec.ECDSA(hashes.SHA512()))
    
    run(
        "openssl req -x509 -nodes -subj '/CN=test' -days 1 -newkey dsa:<(openssl dsaparam 2048) -keyout dsa-key.pem -out dsa-cert.pem"
    )
    with open("dsa-cert.pem", "rb") as fh:
        dsa_cert = x509.load_pem_x509_certificate(fh.read())
    with open("dsa-key.pem", "rb") as fh:
        dsa_key = serialization.load_pem_private_key(fh.read(), password=None)
    signatures[dsa_cert] = dsa_key.sign(message, hashes.SHA512())
    
    # Does not work on LibreSSL
    run("openssl req -x509 -nodes -subj '/CN=test' -days 1 -newkey ed25519 -keyout ed25519-key.pem -out ed25519-cert.pem")
    with open("ed25519-cert.pem", "rb") as fh:
        ed25519_cert = x509.load_pem_x509_certificate(fh.read())
    with open("ed25519-key.pem", "rb") as fh:
        ed25519_key = serialization.load_pem_private_key(fh.read(), password=None)
    signatures[ed25519_cert] = ed25519_key.sign(message)
    
    for cert, signature in signatures.items():
        pubkey = cert.public_key()
        alg = TbsCertificate.load(cert.tbs_certificate_bytes)["subject_public_key_info"]["algorithm"]
        if alg["algorithm"].native == 'rsassa_pss':
            verify_args = [pss_padding, hashes.SHA512()]
        elif alg["algorithm"].native == 'rsa':
            verify_args = [pkcs_padding, hashes.SHA512()]
        elif alg["algorithm"].native == 'ec':
            verify_args = [ec.ECDSA(hashes.SHA512())]
        elif alg["algorithm"].native == 'ed25519':
            verify_args = []
        elif alg["algorithm"].native == 'dsa':
            verify_args = [hashes.SHA512()]
        pubkey.verify(signature, message, *verify_args)
    
        try:
            OpenSSL.crypto.verify(OpenSSL.crypto.X509.from_cryptography(cert), signature, message, "sha512")
        except Exception as e:
            print(f"Error in OpenSSL.crypto.verify with {type(pubkey)}: {e}")
  7. reaperhulk commented on Nov 1, 2023

    @reaperhulk
    Member

    We'd be happy to take a PR that enhances our documentation to better explain how people can do this verification, but at this time we won't be exposing an API.

  8. locked as resolved and limited conversation to collaborators on Jan 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions