简体   繁体   中英

Is it possible to set subjectAltName using pyOpenSSL?

I need to generate SSL certificates from Python using pyOpenSSL. Does anyone know if it's possible to set subjectAltName? From the documentation ( https://pythonhosted.org/pyOpenSSL/api/crypto.html#x509-objects ) it doesn't seem so. In fact, only a set_subject method is provided. Is there any way to add that to the certificate?

san_list = ["DNS:*.google.com", "DNS:google.ym"]
cert.add_extensions([
    OpenSSL.crypto.X509Extension(
        "subjectAltName", False, ", ".join(san_list)
   )
])

I thought I would expand on Vans S's answer as I've been going insane trying to work out why my csrgen script isn't working and I've finally cracked it. Sadly this wasn't obvious (to me) at all. Normally I'd not care, as most of my certificates are one name per cert, so the CN in the subject is usually fine. However now that Chrome won't accept certificates without the SANs set (and assuming FF/IE will follow soon if not already) this is a show-stopper now.

My Python 3 looked like this (where self is a class which inherits from crypto.X509Req ).

# Add base constraints
self.add_extensions([
    crypto.X509Extension(
        b"keyUsage", False,
        b"Digital Signature, Non Repudiation, Key Encipherment"),
    crypto.X509Extension(
        b"basicConstraints", False, b"CA:FALSE"),
    crypto.X509Extension(
        b'extendedKeyUsage', False, b'serverAuth, clientAuth'),
])

# If there are multiple names, add them all as SANs.
if self.sans:
    self.add_extensions([crypto.X509Extension(
        b"subjectAltName", False, self.sans.encode())])

Which to me looks like it should work. It runs, produces no errors, produces no warnings, and generates a CSR and a key pair, but the CSR doesn't have a SAN extension .

The solution? X509Req().add_extensions() only works once! The second time I'm calling it here seems to do absolutely nothing. So the following works.

# Add all extensions in one go as only the first call to 
# add_extensions actually does anything. Subsequent calls will fail 
# silently.
self.add_extensions([
    crypto.X509Extension(
        b"keyUsage", False,
        b"Digital Signature, Non Repudiation, Key Encipherment"),
    crypto.X509Extension(
        b"basicConstraints", False, b"CA:FALSE"),
    crypto.X509Extension(
        b'extendedKeyUsage', False, b'serverAuth, clientAuth'),
    crypto.X509Extension(
        b"subjectAltName", False, self.sans.encode())
])

I eventually solved it. I'd missed that subjectAltName is considered a standard extension. So it can be added using pyOpenSSL's method add_extensions.

More info can be found at https://www.openssl.org/docs/apps/x509v3_config.html#STANDARD_EXTENSIONS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM