Authenticating Against Active Directory With Python
I’m a proponent of centralized authentication mechanisms, as the complexity of managing the password database for each system can be overwhelming. A lot of organizations are already using Microsoft’s Active Directory product, and it has proven to be rather easy to perform simple authentication against. I’m posting this here because it is certainly security related, and I haven’t seen a quick howto out there covering this specific use case.
Prerequisites
I am testing this on a Debian Etch server, and only had to install the ‘python-ldap’ package.
Code
#!/usr/bin/env python
import ldap, sys
# fully qualified path to your ldap server
# if you'd like to use an encrypted channel, just use 'ldaps' instead of 'ldap'
LDAP_SERVER='ldap://mydomain.local'
# fully qualified AD user name
LDAP_USERNAME='myuser@mydomain.local'
# your password
LDAP_PASSWORD='mypass'
try:
# build a client
ldap_client = ldap.initialize(LDAP_SERVER)
# perform a synchronous bind
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
except ldap.INVALID_CREDENTIALS, e:
print "Invalid credentials: ",e
sys.exit()
except ldap.SERVER_DOWN, e:
print "Your server appears to be down: ", e
sys.exit()
# all is well
print 'connected!'
ldap_client.unbind()
Tags: active directory, authentication, debian, howto, linux, microsoft, python, security, sysadmin
March 7, 2008 at 10:59 pm
Hey MG, this code looks a lot like what I did in Wasabi this week. Does it encrypt the LDAP connection? I want to figure out how to do that for our FogBugz customers.
March 8, 2008 at 7:29 am
Jacob - from rote, the Python LDAP module will do LDAP over SSL if you change your connection string to ‘ldaps://mydomain.local’.
Remember, though - a lot of LDAP servers have SSL off by default, including Active Directory. You may want to include a helpful test for customers that at least looks for basic connectivity to port 636 or 3269 before accepting the parameter as valid. I think a lot of people assume that SSL support is on out of the box.