Connecting to LDAP over self-signed TLS with Python

Needed to figure out how to do this. The documentation for python’s ldap module was worse than useless, it is actually misleading. Not much help from other sources either. Until I came across this post from 2013 by Bram Neijt. Thank you Bram!

Like Bram I tried importing the certificate, but the OpenLDAP libraries that python ldap is based on wouldn’t have that. This is the same problem you’ll see in php-ldap, which is also based on the same OpenLDAP libraries. The answer in the case of either OpenLDAP’s own utilities or php is to modify or create an /etc/openldap/ldap.conf file and insert “LDAPTLS_REQCERT=never” into it.

For the python module the answer wasn’t too difficult, once you have someone demonstrate it to you as Bram does. Basically you need to set an option on the python ldap library, as distinct from methods you might use to make the connection.

As a result you’ll wind up writing something like this:

#!/usr/bin/python
# Test LDAP operations with python
import ldap
import sys

server = 'ldap://ldap.example.com:1389'
# LDAPTLS_REQCERT=never
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
l = ldap.initialize(server)
try:
    l.start_tls_s()
except ldap.LDAPError, e:
    print e.message['info']
sys.exit()
This entry was posted in System Administration on by .

About phil

My name is Phil Lembo. In my day job I’m an enterprise IT architect for a leading distribution and services company. The rest of my time I try to maintain a semi-normal family life in the suburbs of Raleigh, NC. E-mail me at philipATlembobrothersDOTcom. The opinions expressed here are entirely my own and not those of my employers, past, present or future (except where I quote others, who will need to accept responsibility for their own rants).