Skip to content

Instantly share code, notes, and snippets.

@bloodearnest
Last active April 23, 2024 15:23
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save bloodearnest/9017111a313777b9cce5 to your computer and use it in GitHub Desktop.
Save bloodearnest/9017111a313777b9cce5 to your computer and use it in GitHub Desktop.
Create a self-signed x509 certificate with python cryptography library
# Copyright 2018 Simon Davy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# WARNING: the code in the gist generates self-signed certs, for the purposes of testing in development.
# Do not use these certs in production, or You Will Have A Bad Time.
#
# Caveat emptor
#
from datetime import datetime, timedelta
import ipaddress
def generate_selfsigned_cert(hostname, ip_addresses=None, key=None):
"""Generates self signed certificate for a hostname, and optional IP addresses."""
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# Generate our key
if key is None:
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend(),
)
name = x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, hostname)
])
# best practice seem to be to include the hostname in the SAN, which *SHOULD* mean COMMON_NAME is ignored.
alt_names = [x509.DNSName(hostname)]
# allow addressing by IP, for when you don't have real DNS (common in most testing scenarios
if ip_addresses:
for addr in ip_addresses:
# openssl wants DNSnames for ips...
alt_names.append(x509.DNSName(addr))
# ... whereas golang's crypto/tls is stricter, and needs IPAddresses
# note: older versions of cryptography do not understand ip_address objects
alt_names.append(x509.IPAddress(ipaddress.ip_address(addr)))
san = x509.SubjectAlternativeName(alt_names)
# path_len=0 means this cert can only sign itself, not other certs.
basic_contraints = x509.BasicConstraints(ca=True, path_length=0)
now = datetime.utcnow()
cert = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.public_key(key.public_key())
.serial_number(1000)
.not_valid_before(now)
.not_valid_after(now + timedelta(days=10*365))
.add_extension(basic_contraints, False)
.add_extension(san, False)
.sign(key, hashes.SHA256(), default_backend())
)
cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM)
key_pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
return cert_pem, key_pem
@USSX-Hares
Copy link

Hi, @bloodearnest.
Could you provide a license for that file?

@bloodearnest
Copy link
Author

Done!

@bloodearnest
Copy link
Author

Also updated it to a newer version I had to support golang's tls implementation

@rramani80
Copy link

Any samples for signing a csr with the generated self signed cert and the private key

@feenes
Copy link

feenes commented Aug 20, 2019

Thanks a lot for the snippet.

some imports are missing:

from datetime import datetime
from datetime import timedelta

I also had to change two other lines and add one more import:

import ipaddress
...
        x509.IPAddress(ipaddress.ip_address(ppublic_ip)),
        x509.IPAddress(ipaddress.ip_address(pprivate_ip)),

One could also increase the key size to 2048

@kurtbrose
Copy link

recommend, it is 2018, we should probably be generating 4096-bit RSA not 1024

@feenes
Copy link

feenes commented Oct 17, 2019

minimum 2048 I think.

Difficult to find the right recommendation. I'm no expert

I don't say following links are correct, but perhaps they give some idea:
https://paragonie.com/blog/2019/03/definitive-2019-guide-cryptographic-key-sizes-and-algorithm-recommendations
https://crypto.stackexchange.com/questions/19655/what-is-the-history-of-recommended-rsa-key-sizes

@bloodearnest
Copy link
Author

bloodearnest commented Oct 18, 2019

Hi

Two points:

a) This generates a self signed cert. It should be used for testing and development only, it's not safe to use for production use, given the lack of an explicit external trust chain (e.g. for revocation). Therefore using "the correct" key size is kind of irrelevant.

b) This is a gist: it's an example, not a product. If you are generating certs for real, the key size needed depends on your threat model. Feel free to modify it as needed for your use case.

@feenes
Copy link

feenes commented Oct 18, 2019

True the key size is kind of irrelevant. I would still use 2048 though. (That's why I used the word 'could' in my initial comment)

However the other changes, that I suggested are necessary for the snippet to work. (at least with my python versions in my environment)

@kurtbrose
Copy link

def didn't mean to be negative; it is extremely helpful to put the code out there! thank you!

regarding production usage of self-signed certs -- there are use cases where SRP or PSK would be more appropriate but the application or library being used doesn't support them

that is, you control both ends of the communication and can distribute public certs directly via a side-channel rather than relying on public-key infrastructure / root certificates

or, maybe you have a trusted channel to distribute certs over, but you still care about impersonation -- e.g. ssh or PGP type use cases

@feenes
Copy link

feenes commented Oct 18, 2019

just as info: I used above snippet with my above mentioned modification to write a solution, that creates a self signed cert and starts up a simple https server for development only. (All written in Python, such, that code runs under windows or linux)

Stuff like this will be more and more important for dev, as some advanced stuff / features just won't work without https.

So true in such cases key size is completely irrelevant as long as server and browser don't complain

@bloodearnest
Copy link
Author

def didn't mean to be negative; it is extremely helpful to put the code out there! thank you!

No worries. Just wanted to clarify that this is not intended for production use.

regarding production usage of self-signed certs -- there are use cases where SRP or PSK would be more appropriate but the application or library being used doesn't support them

that is, you control both ends of the communication and can distribute public certs directly via a side-channel rather than relying on public-key infrastructure / root certificates

or, maybe you have a trusted channel to distribute certs over, but you still care about impersonation -- e.g. ssh or PGP type use cases

Agreed. But my understanding of the problem is not about how you distribute and trust the cert - it was the self-signing. The same private key is used for authentication and encryption. So you have no protection in the case of a compromise.

You could modify the above code to generate a signing cert, and then use that to sign a cert for TLS. How you distribute and trust the signing cert is up to you, but you keep its key private. You wouldn't be distributing the trust root private key by default.

So even if using a trusted side channel to distribute certs and your own trusty root, I would not, based on my current understanding, use a self-signed cert in production.

I think I may update the code with a disclaimer to that effect.

As to the python changes, yeah, will update those.

@kurtbrose
Copy link

kurtbrose commented Oct 21, 2019

this is an interesting discussion, but I think I didn't communicate properly what I meant

re: "same private key is used for authentication and encryption" that is good knowledge to have! the recommendation I've heard is use a given RSA key for either encryption OR signing never both; however, I don't think that is relevant to self-signed vs CA signed certs

the context I'm imagining is SSL between two servers both controlled by the same entity

each service gets a separate self-signed keypair; the public keys are handed out on demand;

https://en.wikipedia.org/wiki/Self-signed_certificate#Security_issues

The trust issues of an entity accepting a new self-signed certificate are similar to the issues of an
 entity trusting the addition of a new CA certificate. The parties in a self-signed PKI must establish 
trust with each other (using procedures outside the PKI), and confirm the accurate transfer of public keys 

...

Revocation of self-signed certificates differs from CA signed certificates. The self-signed certificate 
cannot (by nature) be revoked by a CA.[2] Revocation of a self-signed certificate is accomplished 
by removing it from the whitelist of trusted certificates (essentially the same as revoking trust in a CA).

Within a single org's data-center, you already have a trusted way to distribute certs -- the same way you deploy code (-:

Imagine internally, rather than a certificate chain you just have a central "certificate service" that hands out certificates for internal services. At deployment time, services are provisioned with their cert and private key, as well as the self-signed public certs of all other services.

@bloodearnest
Copy link
Author

bloodearnest commented Oct 25, 2019

Sorry, mucked up my earlier reply, misread the wikipedia article.

Yes there are scenarios that trusted side channel distributed self-signed keys are viable. But;

a) I would probably use a self-generated CA in most of those scenarios anyway. It makes rotation of certs easier and safer (they have built in expiry), and is easy to do, so why not? Edit: also allows tighter control of who can generate those certs if needed.

b) In the context of a random gist on the internet that generates self-signed certs for the specific purpose of use in development, I think that a big "Do not use in production" is entirely warranted. The above code also uses an arbitrary serial number, and a 10 year expiry, as well as IP address SANs, all of which are potentially a bad idea in production. So if I encourage people to think a bit before copy/pasting this blindly by saying "do no use in production", I'm ok with that.

@mhechthz
Copy link

mhechthz commented Mar 10, 2020

THANK YOU VERY MUCH - you safed my day, since I needed a valid certificate for an OPCUA-server that wanted to have an application URI (free test server from PROSYS). So I added:

def generate_selfsigned_cert(hostname, ip_addresses=None, URI=None, key=None):

and

if URI: alt_names.append(x509.UniformResourceIdentifier(URI))

In my python OPCUA-client I added the line

client.application_uri = "theAboveCodedURI"

and all was ok!!!

@evanH13
Copy link

evanH13 commented Jun 14, 2020

Is anyone having an issue with browsers trusting the cert? I'm writing a Python program that spins up a simple web server and I'm trying to SSL wrap the socket using the cert and key generated with this program (thank you, by the way). My web server launches, but when I navigate to the server in my web browser, Chrome, and Safari error out saying that my cert is invalid.

@bloodearnest
Copy link
Author

Is anyone having an issue with browsers trusting the cert? I'm writing a Python program that spins up a simple web server and I'm trying to SSL wrap the socket using the cert and key generated with this program (thank you, by the way). My web server launches, but when I navigate to the server in my web browser, Chrome, and Safari error out saying that my cert is invalid.

This cert will not work with modern browsers without some additional steps, as it is not signed by a root certificate that your browser trusts.

If you need this, then you'll need to configure your browser to either a) ignore that the certificate is invalid or b) add the certificate as a trusted certificate in the browser. Googling "add certificate to chrome" (or firefox) should show you how to do this if needed.

@evanH13
Copy link

evanH13 commented Jun 14, 2020

Ahhhhh yes yes, that makes total sense. Thank you for the quick response!

@NoahCardoza
Copy link

NoahCardoza commented Sep 5, 2020

Any advice on going about generating a CA and then using that to sign the certificate? I'll be needing this shortly for a project in which I'm trying to only use the standard libraries.

EDIT: Just noticed that this was using cryptography with is not part of the stdlib. Still interested in how it would work though!

@enorrmann
Copy link

how an I save this generated cert and key to a file ?

@bloodearnest
Copy link
Author

bloodearnest commented Sep 23, 2020

Any advice on going about generating a CA and then using that to sign the certificate? I'll be needing this shortly for a project in which I'm trying to only use the standard libraries.

EDIT: Just noticed that this was using cryptography with is not part of the stdlib. Still interested in how it would work though!

Yes, you do need cryptography for this example, probably should be more explicit about that

Regards creating CA, I think you'd have to do some more work. You could create the root cert as above, although you'd need to tweak somethings (e.g. filling organisation info, no subject, remove SAN/CommonName data, and increase path_len to 1 or more). This would in theory allow you to sign a CSR with this key pair.

Cryptography has docs for generating CSRs[1] for a domain, and I think you may be able to add the root CA to the CSR object and sign it. But it may also not be directly supported by cryptography's high level x509 API, you might have to dig a big deeper.

[1] https://cryptography.io/en/latest/x509/tutorial/#creating-a-certificate-signing-request-csr

@bloodearnest
Copy link
Author

how an I save this generated cert and key to a file ?

The function returns python bytestrings, so write them out as normal?

e.g.

open('key.pem', 'wb').write(key_pem)
open('cert.pem', 'wb').write(cert_pem)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment