Is it possible to set subjectAltName using pyOpenS

2019-05-26 01:46发布

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?

3条回答
仙女界的扛把子
2楼-- · 2019-05-26 01:59
san_list = ["DNS:*.google.com", "DNS:google.ym"]
cert.add_extensions([
    OpenSSL.crypto.X509Extension(
        "subjectAltName", False, ", ".join(san_list)
   )
])
查看更多
等我变得足够好
3楼-- · 2019-05-26 02:13

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())
])
查看更多
Juvenile、少年°
4楼-- · 2019-05-26 02:17

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

查看更多
登录 后发表回答