Question

I use httplib.HTTPSConnection with private key:

h = httplib.HTTPSConnection(url, key_file='../cert/priv.pem', cert_file='../cert/srv_test.crt')

Then I am asked to enter the password to that private key. Is there any option to enter such password not from user input (console) but from other source (code, environment)? Maybe something like in Java:

-Djavax.net.ssl.keyStorePassword=my_secret_passwd
Was it helpful?

Solution

The private key file is loaded in Python's _ssl module (the part that's written in C). From _ssl.c, line 333:

ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM);

This is an OpenSSL function which loads the given key file. If a password is provided, it will call a password callback function. As that function defaults to asking the user, you will have to override it using SSL_CTX_set_default_passwd_cb_userdata. Unfortunately, this function is not included in the standard library or M2Crypto (Python OpenSSL wrapper), but you can find it in pyopenssl.

In order to create a socket from a password-protected key file, you would have to do something like:

from OpenSSL import SSL
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_passwd_cb(lambda *unused: "yourpassword")
ctx.use_privatekey_file(keyFilename)
ctx.use_certificate_file(certFilename)
someSocket = SSL.Connection(ctx, socket.socket())

Creating a HTTPS connection is a bit harder and I don't know how to do it with pyopenssl, but there's an example provided in pyopenssl's source code (test_ssl.py:242).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top