Python和LDAP通过SSL

pgx2nnw8  于 2023-11-15  发布在  Python
关注(0)|答案(2)|浏览(102)

我尝试用python查询Active Directory服务器,它工作正常。但是现在我不想在线路上发送未加密的凭据,所以我想使用LDAP。有没有简单的方法来做到这一点?到目前为止,我发现我必须添加这个选项:

l.set_option(ldap.OPT_X_TLS_CACERTFILE,'/path/to/my/Ca.pem')

字符串
但是我实际上并不想获得CA证书或正确的证书并进行验证。当然,从安全的Angular 来看,我应该验证我的通信伙伴是正确的,但我不关心我的内部网络,并希望这更容易处理。如果我只是将LDAP URL从ldap更改为ldaps,我会得到以下错误:

Traceback (most recent call last):
  File "./ldap-to-sql.py", line 21, in <module>
    bind = l.simple_bind_s(USERNAME, PASS)
  File "/usr/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 214, in simple_bind_s
    msgid = self.simple_bind(who,cred,serverctrls,clientctrls)
  File "/usr/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 208, in simple_bind
    return self._ldap_call(self._l.simple_bind,who,cred,RequestControlTuples(serverctrls),RequestControlTuples(clientctrls))
  File "/usr/local/lib/python2.7/site-packages/ldap/ldapobject.py", line 106, in _ldap_call
    result = func(*args,**kwargs)
ldap.SERVER_DOWN: {'info': 'SSLHandshake() failed: misc. bad certificate (-9825)', 'desc': "Can't contact LDAP server"}

thigvfpy

thigvfpy1#

我用Samba 4 DC和Python ldap模块做了一些测试,我做了这个例子:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import ldap, ldapurl, subprocess, sys, shlex, os

GrupoLDAP = "Domain Users" #Grupo a recuperar
CACert = '/etc/cert/ca.cert.pem' #Certificado CA

ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACert)
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_HARD)

proto = 'ldaps' #Protocolo
server = 'domain.com' #Dirección del servidor (mismo nombre del Certificado)
port = 636 #Puerto seguro para ldaps

try:
    url = ldapurl.LDAPUrl(urlscheme=proto, hostport="%s:%s" % (server, str(port))).initializeUrl()
    ldap_obj = ldap.initialize(url)
    ldap_obj.simple_bind_s('[email protected]','PassWord')

    base = 'OU=Users,DC=domain,DC=com' #Ruta y UO del grupo

    scope = ldap.SCOPE_SUBTREE

    query = '(&(objectClass=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))'

    res_attrs = ['sAMAccountName', 'cn']
    #res_attrs = ['*']
    res = ldap_obj.search_s(base, scope, query, res_attrs)
except ldap.LDAPError as Error:
    print "Ha ocurrido un error al conectar o realizar la query al servidor LDAP:\n\n%s" % Error
    sys.exit(1)

字符串
证书需要CN中的证书,并由CA证书签名,以避免证书错误。在我向同一个证书添加第二个DC之前,它一直在工作,但如果你只有一个DC,它应该可以工作。我不知道它在Windows LDAP上如何工作,但似乎是类似的。
问候!!

qxsslcnc

qxsslcnc2#

两年前,嗯……好吧,可能太晚了。
但是,请尝试下面代码。适用于python/ldap/active directory/TLS。

import ldap
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
l = ldap.initialize("ldaps://ad.xxx.yyy:636")
l.set_option(ldap.OPT_REFERRALS, 0)
l.simple_bind_s("xxx\username", 'pw')
l.search_s('DC=AD,DC=XXX,DC=YYY', ldap.SCOPE_SUBTREE, '(samaccountname=username)', ['displayname'])

字符串

相关问题