Here is a short PHP sample script of how to connect to an OpenLDAP server using the secure LDAPS protocol (port 636).
PHP uses the LDAP settings from the LDAP base packages. in the case of CentOS 7 they are configured in /etc/openldap/ldap.conf . Following two entries are the only ones that are important:
TLS_CACERTDIR /etc/openldap/certs TLS_REQCERT demand
The first line gives the location of the public CA certificate that was used to sign the LDAP server certificate. The second line rejects all invalid certificates. To make the first line work, we need to import the public CA certificate into the local NSS database. For that we use the certutil command line utility (root privileges required):
certutil -A -n ldap -t "C,," -d dbm:/etc/openldap/certs -i /etc/ssl/certs/ldap-ca.pem certutil -L -d dbm:/etc/openldap/certs
The first line imports an existing CA certificate into the database (with the nickname “ldap” which should be unique). The certificate database uses the old Berkeley DB format, so we need to prefix the location with “dbm:”. There are 2 files that make up the certificate database:
- cert8.db
- key3.db
The second line of the code example merely lists all existing database entries. It should now include our new CA certificate for LDAP connections:
[root@centos7]# certutil -L -d dbm:/etc/openldap/certs Certificate Nickname Trust Attributes SSL,S/MIME,JAR/XPI ldap C,,
Notice the 3 trust attributes for our new CA certificate. In our case the first field needs to include the trust “C”. For a description of all possible values, see “man certutil”.
Now that we installed the CA certificate for LDAPS connections, we can actually try to make a connection to the LDAP server with PHP5.
<?php $server = "ldaps://ldap.example.org"; echo "Connecting to $server ...n"; #ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7); $ldapconn = ldap_connect($server, 636) or die("ERROR: Unable to connect to $servern"); ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); $ldapbind = ldap_bind($ldapconn) or die("ERROR: Unable to bind to $servern"); echo "Ok, now connected to $servern"; ldap_unbind($ldapconn); ?>
Here we make an anonymous connection to the LDAP server. You can also provide a username and password for the ldap_bind() function call. Now call this script from the command line (needs yum package “php-cli”):
$ php php-test.php Connecting to ldaps://ldap.example.org ... Ok, now connected to ldaps://ldap.example.org
Important things to note:
- Call ldap_set_option() to activate debug output.
- ldap_connect() does not actually connect to the LDAP server. It only initializes internal data structures and variables. The network connection to port 636 will be made by ldap_bind().
- You need to explicitly set the LDAP protocol version to 3. Otherwise version 2 will be used, which will not work with contemporary OpenLDAP servers.