Connect to apacheds using python-ldap over ldaps

340 Views Asked by At

I have installed one ApacheDS (Apache directory) and am trying to connect it over ldaps. I am able to successfully authenticate it over ldap (port 10389) but getting below error when trying to get it working over ldaps.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/ldap/ldapobject.py", line 445, in simple_bind_s
    msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
  File "/usr/local/lib/python3.6/dist-packages/ldap/ldapobject.py", line 439, in simple_bind
    return self._ldap_call(self._l.simple_bind,who,cred,RequestControlTuples(serverctrls),RequestControlTuples(clientctrls))
  File "/usr/local/lib/python3.6/dist-packages/ldap/ldapobject.py", line 331, in _ldap_call
    reraise(exc_type, exc_value, exc_traceback)
  File "/usr/local/lib/python3.6/dist-packages/ldap/compat.py", line 44, in reraise
    raise exc_value
  File "/usr/local/lib/python3.6/dist-packages/ldap/ldapobject.py", line 315, in _ldap_call
    result = func(*args,**kwargs)
ldap.SERVER_DOWN: {'desc': "Can't contact LDAP server", 'errno': 2, 'info': '(unknown error code)'}
>>>

I understand this is due to certificate validation.

Code used for authentication is:

import ldap
import os
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
ls = ldap.initialize('ldaps://10.120.213.106:10636', trace_level=2)
ls.set_option(ldap.OPT_REFERRALS, 0)
ls.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
ls.set_option(ldap.OPT_X_TLS,ldap.OPT_X_TLS_DEMAND)
ls.set_option(ldap.OPT_X_TLS_DEMAND, True)
ls.set_option(ldap.OPT_DEBUG_LEVEL, 4095)
ls.set_option(ldap.OPT_X_TLS_CACERTFILE, "/tmp/server.cer")
ls.simple_bind_s('uid=admin,ou=system', 'secret')

I am not able to locate self signed certificate that ApacheDS provides by default, so I created a certificate and a keystore using

keytool -genkey -keyalg "RSA" -dname "cn=hax,ou=some,dc=com, o=ASF, c=US" -alias hax -keystore hax.ks -storepass secret -validity 730

and then exported certificate in trusted keystore using:

keytool -export -keystore hax.ks -alias hax -file hax.cer
keytool -import -file hax.cer -alias hax -keystore trusted.ks -storepass secret

Configure apacheDS to use hax.ks as keysotre and restarted it. I have tried ls.set_option(ldap.OPT_X_TLS_CACERTFILE, "/tmp/trusted.ks") too but no luck.

What am I missing here? Note: I am able to connect by setting ldap.OPT_X_TLS_REQUIRE_CERT to allow or never. But I don't want to do that but validate certificates.

1

There are 1 best solutions below

0
mvreijn On

For scripts connecting to testing or development servers, I always use

ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

Also, it is recommended to use the StartTLS extension, so connect to the plaintext port (389 or 10389) and then issue

conn.start_tls_s()