I recently got a few support cases from customers seeking to connect Postgres with LDAP (usually with some form of SSL/TLS encryption, to ensure security). I spent a bit of time trying to create a consistently reproducible environment where LDAP could be used to authenticate PostgreSQL connections, and wanted to write it down somewhere. The trickiest part was to get LDAP + encryption working, and I think I’ve got a somwhat-reliable way to stand up an environment for testing.
Setting up LDAP seems intimidating, as there’s a whole suite of commands and options to explore. I mean, there are jobs dedicated to this sector of IT Management, not to mention the plethora of different architectures (Active Directory, Kerberos, GSSAPI, PAM, etc.) Thankfully,Osixiahas made it easy by providing adocker container. Now, it’s a simple as
Out of the box, LDAP works. All you need to do is create an LDAP user, create a counterpart in Postgres withCREATE ROLE, and configurepg_hba.confaccordingly:
HUPthe server, sign in withpsqland all is good:
Setting upLDAP + StartTLS
It takes a little extra work to make the Docker container behave in a way that Postgres can talk to it withStartTLS. The first step is create your own Certificate Authority, then an SSL certificate and sign it. Working with SSL/TLS is also intimidating (with all the ciphers, acronyms, versions, and such), and I won’t go into that here, but I was surprised to find thatit wasn’t terribly hard to get the 3 things that I needed. After that, you need to create your LDAP Docker container by including the--env LDAP_TLS_VERIFY_CLIENT=tryflag in thedocker runstatement, as mentioned inIssue #105. Finally, you’ll need to copy your CA cert, SSL cert, and SSL key into/container/service/slapd/assets/. Once those are all in place (you may need to do adocker restart ldap-service), verify thatLDAP + StartTLSis working properly by doing a simpleldapsearchfrom the client side (i.e., wherever you’re running Postgres):
If that’s successful, go into yourpg_hba.conffile and addldaptls=1:
HUPthe server, and you should be able to log in withLDAP + StartTLSauthentication:
You can verify that Postgres is indeed usingStartTLSby inspecting the LDAP server’s logs:
Getting PostgreSQL working with LDAP and with SSL/TLS can be intimidating, but it doesn’t have to be. With a bit of poking around on Google, and finding the right resources, what seemed to be a herculian task actually became quite doable. One important lesson I learned through these support cases, and in setting up this environment, was that it’s very important to verify from the client side with ldapsearch or ldapwhoami with the -Z flag to make sure LDAP with encryption was properly set up. Some people tested only on the LDAP/server side, not on the Postgres side, and lost many hours trying to wrangle with pg_hba.conf and ultimately blaming Postgres for being buggy in its implementation of LDAP authentication, when in reality it was LDAP that was misconfigured.