Recipe 15.11. Authenticating an SSL Client over HTTPSCredit: Rob Riggs ProblemYou want your Python application to check SSL client authentication, by delegating, over HTTPS, to an Apache server that is running mod_ssl . SolutionThe 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
To safely perform SSL authentication, you will
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
See AlsoDescriptions 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. |
Chapter 16. Programs About Programs
Introduction Recipe 16.1. Verifying Whether a String Represents a Valid Number Recipe 16.2. Importing a Dynamically Generated Module
Recipe 16.3. Importing from a Module Whose
Recipe 16.4. Associating Parameters with a Function (Currying) Recipe 16.5. Composing Functions Recipe 16.6. Colorizing Python Source Using the Built-in Tokenizer Recipe 16.7. Merging and Splitting Tokens Recipe 16.8. Checking Whether a String Has Balanced Parentheses Recipe 16.9. Simulating Enumerations in Python Recipe 16.10. Referring to a List Comprehension While Building It Recipe 16.11. Automating the py2exe Compilation of Scripts into Windows Executables Recipe 16.12. Binding Main Script and Modules into One Executable on Unix |