Tag Archives: signed

Handle self-signed certificates with PHPs LDAP-Extension

Often I see questions on StackOverflow stating that connecting to LDAP-Servers secured with self-signed certificates is difficult and troublesome. Very often the accepted answer or the one with the most votes is actually the worst answer, as usually it requires to completely ignore certificates. So basically swapping the certificate would not be noticed, leaving the connection wide open for a Man-in-the-Middle attack and therefore somehow defeating the purpose of secure connections.

But how does one connect securely to an LDAP-Server secured with a self-signed certificate?

I did some tests and summarized my findings in a github-repo.

In essence it boils down to retrieving the current certificate either from the admin of the LDAP-Server or via OpenSSL using this command:

$ echo \
| openssl s_client -connect openldap:636 2> /dev/null \
| openssl x509 -text \
| sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p' \
> /path/to/cert.pem

And then – at least when you have a supported PHP-Version – add the following lines to your ldap-code:

ldap_set_option(null, LDAP_OPT_X_TLS_CACERTDIR, '/path/to');
ldap_set_option(null, LDAP_OPT_X_TLS_CACERTFILE, '/path/to/cert.pem');

// either
$ldap = ldap_connect('ldaps://ldap.example.org:636');
// or
$ldap = ldap_connect('ldap://ldap.example.org:389');
ldap_start_tls($ldap);

Note: It’s important to call ldap_set_option before the first LDAP-Command and use null as the first argument. Otherwise it will not work 😉

You want more info? Have a look at the Repos README