Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using .der certificate in python/flask

I have a python flask app where I created a cert and key file using ssl and put that in the code as follows

if __name__=='__main__':
    context=('cert.crt','keys.key')
    app.run('0.0.0.0',ssl_context=context,debug=True) 

However they are not valid. In the server I have deployed the code there are 2 files 'sslca-chain.der' and 'SSLCA-Chain.pem'. How do I use that in the code instead of the above?

like image 405
payesh Avatar asked Aug 04 '26 08:08

payesh


1 Answers

The two files you have mentioned are the same thing (chain certificates) just in different formats.

It is best to configure a reverse proxy (like nginx) to handle the SSL stuff rather than include it in your flask application.

Python only handles PEM format files natively.

However, if you must - you need two files - the certificate file, and the key file.

If you got your certificate from a third party CA, then they will provide you the certificate file.

The key file is always with you, and should be kept secret.

Since you have a certificate chain, you must provide a custom context to the application and include all the files in your chain, as the load_cert_chain method only takes one argument for the certificate file.

So, in short what you have to do is:

  1. Make sure your PEM file contains your server certificate.
  2. Create a custom context with the PEM file and your key file.
  3. Pass this custom context to Flask

A PEM file is just a text file that contains all the certificates in a specific order; the order is:

-----BEGIN CERTIFICATE----- 
(Your Primary SSL certificate) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Intermediate certificate) 
-----END CERTIFICATE----- 
-----BEGIN CERTIFICATE----- 
(Your Root certificate) 
-----END CERTIFICATE-----

The -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- lines are important and should be included

Once you have verified that your PEM file contains your server certificate, here is how you would configure it for flask:

import ssl

ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) # use TLS to avoid POODLE
ctx.load_cert_chain('/path/to/sslca-chain.pem', '/path/to/server.key')
app.run('0.0.0.0',ssl_context=ctx,debug=True) 
like image 185
Burhan Khalid Avatar answered Aug 05 '26 23:08

Burhan Khalid