I am trying to connect to ldap server from python framework with the help of ldap3 libraries on Mac M1.
from ldap3 import Server, Connection, SUBTREE, ALL, Tls, MODIFY_REPLACE
from fastapi import FastAPI
from typing import Union
from pydantic import BaseModel
import ssl
app = FastAPI()
tls_configuration = Tls(validate=ssl.CERT_REQUIRED,version=ssl.PROTOCOL_TLSv1_2,ca_certs_file="./app/client_cert.pem")
server = Server("ldaps://ldaps.adserver.com",port=636,use_ssl=True,tls=tls_configuration, get_info=ALL)
conn = Connection(server, user='mydomain.com\user', password='DemoPass%',auto_bind=True,authentication="NTLM")
print(f"Connection: {conn}")
I have extracted certificate using below command and saved --Begin Certificate-- to --End Certificate-- in .pem format file in app folder.
openssl s_client -connect ldaps.adserver.com:636
When trying to test the connection, I am still receiving certificate invalid error.
Traceback (most recent call last):
File "/Users/demo/Documents/GitHub/project/app/main.py", line 13, in <module>
conn = Connection(server, user='domain\user', password='DemoPass%',auto_bind=True,authentication="NTLM")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/core/connection.py", line 363, in __init__
self._do_auto_bind()
File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/core/connection.py", line 387, in _do_auto_bind
self.open(read_server_info=False)
File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/strategy/sync.py", line 57, in open
BaseStrategy.open(self, reset_usage, read_server_info)
File "/Users/demo/anaconda3/lib/python3.11/site-packages/ldap3/strategy/base.py", line 146, in open
raise exception_history[0][0]
ldap3.core.exceptions.LDAPSocketOpenError: ("('socket ssl wrapping error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1006)',)",)
How do I verify if .pem file I have created is valid and how to use it in python ldap3.
The error complains about the issuer, not the certificate as far as I see. You should get the issuer certificate (it may be an intermediate or a root certificate) you should get all the certificates in the chain up to the root certificate if they are not in your trusted stores.
Pls rename the pem file to a cer file and double click in Windows. You will see in the Details tab the Issuer field, you should get that issuer certificate from the LDAP server providers. You may require a single file with all certificate chain packaged. Then those certificates should be installed in your trusted store on which your code runs. You may trace these chain verification events on CAPI2 logs Event Viewer- Application and Services - Microsoft - Windows -CAPI2 - Operational when the code runs. First you should enable logs, it can fill up quickly.