Error running Flask with self signed certificates "No such file or directory"

Viewed 2821

Running a test for Flask+Self Signed Certificates based on this guide

Flask server:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
    return '<html><head></head><body><p>blabla</body></html>'

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=443, ssl_context=('cert.pem', 'key.pem'))

I generated a certificate using:

openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365

And when I run the server (sudo python test.py) I get the following error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/abuyoyo/.local/lib/python2.7/site-packages/werkzeug/serving.py", line 774, in inner
    fd=fd)
  File "/home/abuyoyo/.local/lib/python2.7/site-packages/werkzeug/serving.py", line 660, in make_server
    passthrough_errors, ssl_context, fd=fd)
  File "/home/abuyoyo/.local/lib/python2.7/site-packages/werkzeug/serving.py", line 601, in __init__
    self.socket = ssl_context.wrap_socket(sock, server_side=True)
  File "/home/abuyoyo/.local/lib/python2.7/site-packages/werkzeug/serving.py", line 511, in wrap_socket
    ssl_version=self._protocol, **kwargs)
  File "/usr/lib/python2.7/ssl.py", line 949, in wrap_socket
    ciphers=ciphers)
  File "/usr/lib/python2.7/ssl.py", line 560, in __init__
    self._context.load_cert_chain(certfile, keyfile)
IOError: [Errno 2] No such file or directory

I tied absolute paths to the certs, I tried wrong paths but I get the same error every time.

3 Answers

Looks like a file permissions issue. Create a specific folder to store them in and give it permissions to the user that manages your server.

Just as an example, considering "www" is the user you are starting your server as:

$ sudo mkdir /etc/ssl/certs/myPythonServerCert
$ sudo chown www:www /etc/ssl/certs/myPythonServerCert
$ sudo chmod 500 /etc/ssl/certs/myPythonServerCert

This would create a folder in /etc/ssl/certs only accessible and readable by the www user. Put your certificates ther, it should work.

Issue with permissions to the path.

Moving the certs to /tmp resolved the issue.

Moving the certs under /tmp resolved the issue. /tmp has 777 permission. I have placed the cert.pem and key.pem files to the sub directory in /tmp.

Related