Monday, March 23, 2009

python-ldap authentication and you

Or me, at least.

Here's how I managed to make my python client code running on a Debian/Ubuntu box authenticate against a Windows Active Directory LDAP server:
  1. Obtain the server's cert: openssl s_client -showcerts -connect myserver.com:636 > their_server.pem

  2. Edit the resulting file to isolate just the cert you want. In my case, the file had two certs embedded in it, plus some identifying cruft. Preceding the first, desired cert was a block that looked like this: 0 s:/C=US/ST=MyState/L=MyCity/O=My Company Inc./OU=Information Technology/OU=For Intranet Use Only/CN=my.host.com, followed by -----BEGIN CERTIFICATE-----. Next came VeriSign's cert. Delete everything but the CERTIFICATE block for your server, including the BEGIN and END lines, and save to /etc/ssl/certs/myserver.pem -- you can save to any location, really.


And here's the code:
#!/usr/bin/env python

import ldap
#ldap.set_option(ldap.OPT_DEBUG_LEVEL,4095)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,"/etc/ssl/certs/myserver.pem")
l = ldap.initialize("ldaps://myserver.com:636")
l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
l.simple_bind_s("username@DOMAIN","password")

No comments: