views:

209

answers:

2

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
+3  A: 

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).

AndiDog
Thanks! I changed my client from `httplib.HTTPSConnection` to simple socket client with SSL support and it works!
Michał Niklas
A: 

Hi Michal,

Could you please provide a part of code which is working ? Thanks

Fabian
AndiDog did it. Do you have any problems with his code? I installed PyOpenSSL and changed HTTP client from `httplib` based to socket based (I manually set HTTP headers etc.).
Michał Niklas