Recipe15.11.Authenticating an SSL Client over HTTPS


Recipe 15.11. Authenticating an SSL Client over HTTPS

Credit: Rob Riggs

Problem

You want your Python application to check SSL client authentication, by delegating, over HTTPS, to an Apache server that is running mod_ssl.

Solution

The Apache web server has good support for SSL, and we can write a Python script to exploit that support to authenticate a client. For example:

import httplib CERT_FILE = '/home/robr/mycert' PKEY_FILE = '/home/robr/mycert' HOSTNAME = 'localhost' conn = httplib.HTTPSConnection(HOSTNAME,            key_file = PKEY_FILE, cert_file = CERT_FILE) conn.putrequest('GET', '/ssltest/') conn.endheaders( ) response = conn.getresponse( ) print response.read( )

Discussion

The Solution code assumes that mycert is a certificate file formatted by PEM (Privacy-enhanced Electronic Mail), which includes both the public certificate and the private key. You can keep the public and private keys in separate files: you need to pass the names of the files in question as the values for the key_file and cert_file arguments of HTTPSConnection.

To safely perform SSL authentication, you will generally set up your own certification authority (CA). You do not want to enable a third-party organization to hand out all the "keys" to the locks that you put up to protect your security.

The Apache server installation that you use for this authentication needs to be configured to require SSL client authentication with the appropriate CA. My httpd.conf file contains the stanza:

SSLCACertificatePath /etc/httpd/conf/ssl.crt SSLCACertificateFile /etc/httpd/conf/ssl.crt/myCA.crt SSLVerifyClient      require SSLVerifyDepth       2 SSLRequireSSL

The configuration of an Apache server cannot refer to more than one SSLCACertificateFile. You can put more than one CA certificate in that file, but doing so grants authentication to any client who has a certificate from any one of the certificate authorities you accept, which is unlikely to be what you want. Therefore, this recipe is fully applicable only when you can reasonably set up an Apache server to accept your own CA as the sole recognized one. In exchange for this modest inconvenience, however, you do get a handy and robust approach to client authentication between web-enabled applications, particularly good for SOAP or XML-RPC implementations, or custom applications that communicate via HTTP/HTTPS.

See Also

Descriptions of SSL and its use with Apache can be found at http://httpd.apache.org/docs-2.0/ssl/ssl_howto.html and http://www.pseudonym.org/ssl/ssl_cook.html. The httplib module is part of the Python Standard Library and is documented in a chapter of the Library Reference portion of Python's online documentation.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net