def setUp(self): super(BaseTestCase, self).setUp() self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) self.useFixture(fixtures.MockPatchObject(sys, 'exit', side_effect=UnexpectedExit)) self.useFixture(log_fixture.get_logging_handle_error_fixture()) warnings.filterwarnings('error', category=DeprecationWarning, module='^keystone\\.') warnings.simplefilter('error', exc.SAWarning) self.addCleanup(warnings.resetwarnings) # Ensure we have an empty threadlocal context at the start of each # test. self.assertIsNone(oslo_context.get_current()) self.useFixture(oslo_ctx_fixture.ClearRequestContext()) orig_debug_level = ldap.get_option(ldap.OPT_DEBUG_LEVEL) self.addCleanup(ldap.set_option, ldap.OPT_DEBUG_LEVEL, orig_debug_level) orig_tls_cacertfile = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_CACERTFILE, orig_tls_cacertfile) orig_tls_cacertdir = ldap.get_option(ldap.OPT_X_TLS_CACERTDIR) # Setting orig_tls_cacertdir to None is not allowed. if orig_tls_cacertdir is None: orig_tls_cacertdir = '' self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_CACERTDIR, orig_tls_cacertdir) orig_tls_require_cert = ldap.get_option(ldap.OPT_X_TLS_REQUIRE_CERT) self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_REQUIRE_CERT, orig_tls_require_cert) self.addCleanup(ks_ldap.PooledLDAPHandler.connection_pools.clear)
def __init__(self): self.ldap_URL = ldap.get_option(ldap.OPT_URI) self.ldap = ldap.initialize(self.ldap_URL) self.ldap_base = ldap.get_option(ldap.OPT_DEFBASE) if not self.ldap_base: # TODO: Remove this when F20 servers are gone self.ldap_base = "dc=scripts,dc=mit,dc=edu" self.ldap_base = "ou=VirtualHosts," + self.ldap_base
def test_base_ldap_connection_deref_option(self): deref = ldap_common.parse_deref('default') ldap_wrapper = ldap_common.LdapWrapper(CONF.ldap.url, CONF.ldap.page_size, alias_dereferencing=deref) self.assertEqual(ldap.get_option(ldap.OPT_DEREF), ldap_wrapper.conn.get_option(ldap.OPT_DEREF)) deref = ldap_common.parse_deref('always') ldap_wrapper = ldap_common.LdapWrapper(CONF.ldap.url, CONF.ldap.page_size, alias_dereferencing=deref) self.assertEqual(ldap.DEREF_ALWAYS, ldap_wrapper.conn.get_option(ldap.OPT_DEREF)) deref = ldap_common.parse_deref('finding') ldap_wrapper = ldap_common.LdapWrapper(CONF.ldap.url, CONF.ldap.page_size, alias_dereferencing=deref) self.assertEqual(ldap.DEREF_FINDING, ldap_wrapper.conn.get_option(ldap.OPT_DEREF)) deref = ldap_common.parse_deref('never') ldap_wrapper = ldap_common.LdapWrapper(CONF.ldap.url, CONF.ldap.page_size, alias_dereferencing=deref) self.assertEqual(ldap.DEREF_NEVER, ldap_wrapper.conn.get_option(ldap.OPT_DEREF)) deref = ldap_common.parse_deref('searching') ldap_wrapper = ldap_common.LdapWrapper(CONF.ldap.url, CONF.ldap.page_size, alias_dereferencing=deref) self.assertEqual(ldap.DEREF_SEARCHING, ldap_wrapper.conn.get_option(ldap.OPT_DEREF))
def _VerifyLdapAuth(self, username, password): """Perform simple LDAP auth. Args: username: string username password: string password Returns: Boolean. True if authenticated. Raises: common.AuthenticationError: if LDAP errors occur besides auth failures """ try: # need to set_option first, before initialize(). # this is potentially abusive to other ldap module users. if not self.ldap_server_tls_require_cert: old_option = ldap.get_option(ldap.OPT_X_TLS_REQUIRE_CERT) ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) con = ldap.initialize(self.ldap_server_uri) if self.ldap_server_start_tls: con.start_tls_s() if not self.ldap_server_tls_require_cert: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, old_option) con.bind_s(self.ldap_server_bind % username, password) self.ldap_con = con return True except ldap.INVALID_CREDENTIALS, e: self.ldap_con = None return False
def ldap_auth(request): email = "" password = "" state = "empty" if request.POST: email = request.POST.get('email') password = request.POST.get('password') print("DEBUG: " + email + "/" + password) logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) print("DEBUG(OPT_X_TLS_REQUIRE_CERT): " + str(ldap.get_option(ldap.OPT_X_TLS_REQUIRE_CERT))) print("DEBUG(OPT_X_TLS_NEVER): " + str(ldap.OPT_X_TLS_NEVER)) user = authenticate(username=email, password=password) if user is not None: login(request, user) state = "Valid account" else: state = "Inactive account" ## NORMAL RENDER template = loader.get_template('firewall_rules/ldap_auth.html') #context = RequestContext(request, {'state': state, 'username': username}) context = {'state': state, 'email': email} #return render_to_response('firewall_rules/ldap_auth.html', RequestContext(request, {'state': state, 'username': username})) return HttpResponse(template.render(context, request))
def get_ldap_cert_path(): """ Get path to LDAP certificate used by system. :return: """ if LDAPSettings.LDAP_IMPORT_SUCCESS: return ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) return ''
def setUp(self): super(BaseTestCase, self).setUp() self.useFixture(fixtures.NestedTempfile()) self.useFixture(fixtures.TempHomeDir()) self.useFixture( fixtures.MockPatchObject(sys, 'exit', side_effect=UnexpectedExit)) self.useFixture(log_fixture.get_logging_handle_error_fixture()) warnings.filterwarnings('error', category=DeprecationWarning, module='^keystone\\.') warnings.filterwarnings( 'ignore', category=DeprecationWarning, message=r"Using function/method 'db_version\(\)' is deprecated") warnings.simplefilter('error', exc.SAWarning) if hasattr(exc, "RemovedIn20Warning"): warnings.simplefilter('ignore', exc.RemovedIn20Warning) self.addCleanup(warnings.resetwarnings) # Ensure we have an empty threadlocal context at the start of each # test. self.assertIsNone(oslo_context.get_current()) self.useFixture(oslo_ctx_fixture.ClearRequestContext()) orig_debug_level = ldap.get_option(ldap.OPT_DEBUG_LEVEL) self.addCleanup(ldap.set_option, ldap.OPT_DEBUG_LEVEL, orig_debug_level) orig_tls_cacertfile = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) if orig_tls_cacertfile is None: orig_tls_cacertfile = '' self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_CACERTFILE, orig_tls_cacertfile) orig_tls_cacertdir = ldap.get_option(ldap.OPT_X_TLS_CACERTDIR) # Setting orig_tls_cacertdir to None is not allowed. if orig_tls_cacertdir is None: orig_tls_cacertdir = '' self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_CACERTDIR, orig_tls_cacertdir) orig_tls_require_cert = ldap.get_option(ldap.OPT_X_TLS_REQUIRE_CERT) self.addCleanup(ldap.set_option, ldap.OPT_X_TLS_REQUIRE_CERT, orig_tls_require_cert) self.addCleanup(ks_ldap.PooledLDAPHandler.connection_pools.clear)
def userinfo(): """ Get current user's common name and email from LDAP Returns: Tuple of (name, email) """ l = ldap.initialize(ldap.get_option(ldap.OPT_URI)) people = 'ou=People,dc=apac,dc=edu,dc=au' info = l.search_s(people, ldap.SCOPE_SUBTREE, '(uid=%s)'%getpass.getuser()) return (info[0][1]['cn'][0],info[0][1]['mail'][0])
def main(): print "api info:", ldap.get_option(ldap.OPT_API_INFO) #ldap.set_option(ldap.OPT_DEBUG_LEVEL, 7) print "debug level:", ldap.get_option(ldap.OPT_DEBUG_LEVEL) rc = LdapRc() print(repr(rc)) lobj = rc.initialize() print(repr(lobj)) try: x = rc.bind_s(lobj) except ValueError as e: raise print('BASE = ' + rc.ldaprc['BASE']) ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0) y = lobj.search_s(rc.ldaprc['BASE'], ldap.SCOPE_SUBTREE, '(objectClass=*)', ['cn']) pprint(y)
def test_certdir_trust_ldaps(self): # We need this to actually exist, so we create a tempdir. certdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, certdir) self.config_fixture.config(group='ldap', url='ldaps://localhost', use_tls=False, tls_cacertdir=certdir) self._init_ldap_connection(CONF) # Ensure the cert trust option is set. self.assertEqual(certdir, ldap.get_option(ldap.OPT_X_TLS_CACERTDIR))
def hasChilds(self, dn): # try operational attributes attrs = self.lo.search_s(dn, ldap.SCOPE_BASE, "(objectClass=*)", ["hasSubordinates"]) if "hasSubordinates" in attrs: if attrs["hasSubordinates"][0] == "TRUE": return True elif attrs["hasSubordinates"][0] == "FALSE": return False # do onelevel search old_sizelimit = ldap.get_option(ldap.OPT_SIZELIMIT) ldap.set_option(ldap.OPT_SIZELIMIT, 1) result = self.lo.search_s(dn, ldap.SCOPE_ONELEVEL, "(objectClass=*)", [""]) ldap.set_option(ldap.OPT_SIZELIMIT, old_sizelimit)
def test_certfile_trust_ldaps(self): # We need this to actually exist, so we create a tempfile. (handle, certfile) = tempfile.mkstemp() self.addCleanup(os.unlink, certfile) self.addCleanup(os.close, handle) self.config_fixture.config(group='ldap', url='ldaps://localhost', use_tls=False, tls_cacertfile=certfile) self._init_ldap_connection(CONF) # Ensure the cert trust option is set. self.assertEqual(certfile, ldap.get_option(ldap.OPT_X_TLS_CACERTFILE))
def hasChilds(self, dn): # try operational attributes attrs = self.lo.search_s(dn, ldap.SCOPE_BASE, '(objectClass=*)', ['hasSubordinates']) if 'hasSubordinates' in attrs: if attrs['hasSubordinates'][0] == 'TRUE': return True elif attrs['hasSubordinates'][0] == 'FALSE': return False # do onelevel search old_sizelimit = ldap.get_option(ldap.OPT_SIZELIMIT) ldap.set_option(ldap.OPT_SIZELIMIT, 1) result = self.lo.search_s(dn, ldap.SCOPE_ONELEVEL, '(objectClass=*)', ['']) ldap.set_option(ldap.OPT_SIZELIMIT, old_sizelimit)
def requires_tls(skip_nss=False): """Decorator for TLS tests Tests are not skipped on CI (e.g. Travis CI) :param skip_nss: Skip test when libldap is compiled with NSS as TLS lib """ if not ldap.TLS_AVAIL: return skip_unless_travis("test needs ldap.TLS_AVAIL") elif skip_nss and ldap.get_option(ldap.OPT_X_TLS_PACKAGE) == 'MozNSS': return skip_unless_travis( "Test doesn't work correctly with Mozilla NSS, see " "https://bugzilla.redhat.com/show_bug.cgi?id=1519167") else: return identity
def _set_cacertificate(cacertificates, ca_dir=None): ''' This function sets the CA certfificate. It creates a temporary file if it does not exist. :param cacertificate: CA certificates that should be used for LDAP connections :type cacertificate: list :return: the cert file name or None ''' ca_file = None if len(cacertificates) == 0: log.debug("[_set_cacertificate] No CA certificate.") return ca_file # Either set the ca file to be located in the linotp cache_dir or if it # does not exist, in a temporaty directory. if ca_dir == None: ca_dir = tempfile.gettempdir() ca_file = "%s/linotp_ldap_cacerts.pem" % ca_dir # As the CA certificate can be written on every first request # after the server start, we do not need to verify the old certificate. try: fil = open(ca_file, "w") for cacert in cacertificates: cert = cacert.strip() if ("-----BEGIN CERTIFICATE-----" in cert and "-----END CERTIFICATE-----" in cert): fil.write(cert) fil.write("\n") fil.close() except Exception as exc: log.error("[_set_cacertificate] Error creating CA certificate file: " "%r. %r" % (ca_file, exc)) raise exc log.debug("[_set_cacertificate] setting file %s" % ca_file) reload(ldap) ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, ca_file) ca_file = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) return ca_file
def main(): """The main function.""" opts = docopt.docopt(__doc__, version='0.1.0') loglevel = logging.WARNING if opts['--debug']: loglevel = logging.DEBUG elif opts['--verbose']: loglevel = logging.INFO elif opts['--quiet']: loglevel = logging.ERROR logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=loglevel, stream=sys.stderr) if opts['--prompt-password']: opts['--bindpw'] = getpass.getpass() uri = opts['--uri'] if opts['--uri'] else ldap.get_option(ldap.OPT_URI) conn = ldap.initialize(uri) base = opts['--base'] if opts['--base'] else ('ou=Hosts,%s' % get_ldap_base(conn, opts['--ldap-conf'])) # pylint: disable-msg=C0103 dn = [rdn.split('=') for rdn in base.split(',')] dcs = [v for k, v in dn if k == 'dc'] zones = ['.'.join(dcs)] if opts['--zone']: zones = opts['--zone'] if opts['--binddn']: conn.simple_bind_s(opts['--binddn'], opts['--bindpw']) generate_zonefiles(conn, base, zones, outdir=opts['--output-dir'], serial=opts['--serial'], reverse=opts['--reverse'])
def run(): '''The main function''' (opts, args) = parse_args() if args: user = args[0] else: user = getpass.getuser() userdn = USERDN % (user, get_ldap_base()) ldapconn = ldap.initialize(ldap.get_option(ldap.OPT_URI)) default_shell = get_old_shell(ldapconn, userdn) if opts.binddn: binddn = opts.binddn else: binddn = USERDN % (user, get_ldap_base()) if opts.shell: new_shell = opts.shell elif opts.default: new_shell = get_default_shell() else: print 'Changing the login shell for %s' % user print 'Enter the new value, or press ENTER for the default' new_shell = raw_input('\tLogin Shell [%s]: ' % default_shell) if new_shell == '': new_shell = default_shell if not is_shell_ok(new_shell): print '%s not found in %s' % (new_shell, SHELLS) return passwd = getpass.getpass('LDAP bind password:') ldapconn.simple_bind_s(binddn, passwd) change_shell(ldapconn, userdn, new_shell)
def bind(self): """ bind() - this function starts an ldap conncetion """ if self.l_obj is not None: return self.l_obj if self.bind_not_possible: t2 = datetime.now() tdelta = t2 - self.bind_not_possible_time # If we try a bind within 30 seconds, we will # bail out! if tdelta.seconds > BIND_NOT_POSSIBLE_TIMEOUT or tdelta.days > 1: log.info("[bind] Resetting the bind_not_possible timeout.") self.bind_not_possible = False else: log.error("[bind] LDAP bind timed out the last time. " "So we do not try to bind again at this moment. " "Skipping for performance sake! " "Trying a real bind again in %r seconds" % (BIND_NOT_POSSIBLE_TIMEOUT - tdelta.seconds)) return False uri = "" urilist = self.ldapuri.split(',') i = 0 log.debug("[bind] trying to bind to one of the servers: %r" % urilist) l_obj = None while i < len(urilist): uri = urilist[i] try: log.debug("[bind] LDAP: Try to bind to %r", uri) l_obj = ldap.initialize(uri, trace_level=0) if uri.startswith('ldaps'): # the setting of the CERTFILE is required only once old_cert_file = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) if self.CERTFILE is not None and old_cert_file == None: ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, self.CERTFILE) # referrals for AD log.debug("[bind] checking noreferrals: %r" % self.noreferrals) if self.noreferrals: l_obj.set_option(ldap.OPT_REFERRALS, 0) l_obj.network_timeout = self.timeout # This is HIGH debug # log.debug("[bind] %s, %s" %(self.binddn, self.bindpw)) dn_encode = self.binddn.encode(ENCODING) pw_encode = self.bindpw.encode(ENCODING) l_obj.simple_bind_s(dn_encode, pw_encode) if i > 0: urilist[i] = urilist[0] urilist[0] = uri self.ldapuri = ','.join(urilist) self.l_obj = l_obj return l_obj except ldap.LDAPError as e: log.error("[bind] LDAP error: %r" % e) log.error("[bind] LDAPURI : %r" % uri) log.error("[bind] %s" % traceback.format_exc()) i = i + 1 # We were not able to do a successful bind! :-( self.bind_not_possible = True self.bind_not_possible_time = datetime.now() self.l_obj = l_obj return l_obj
def testconnection(cls, params): """ This is used to test if the given parameter set will do a successful LDAP connection. :param params: - BINDDN - BINDPW - LDAPURI - TIMEOUT - LDAPBASE - LOGINNAMEATTRIBUTE': 'sAMAccountName', - LDAPSEARCHFILTER': '(sAMAccountName=*)(objectClass=user)', - LDAPFILTER': '(&(sAMAccountName=%s)(objectClass=user))', - USERINFO': '{ "username": "******", "phone" : "telephoneNumber", "mobile" : "mobile", "email" : "mail", "surname" : "sn", "givenname" : "givenName" }' - SIZELIMIT - NOREFERRALS - CACERTIFICATE """ old_cert_file = None l = None status = "success" try: # do a bind uri = params['LDAPURI'] l = ldap.initialize(uri, trace_level=0) if uri.startswith('ldaps'): # for test purpose, we create a temporay file with only this cert old_cert_file = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) # put all certs in a set test_set = set() test_set.update(cls.ca_certs) # including the test one cert = params.get('CACERTIFICATE') test_set.add(cert.strip().replace('\r\n', '\n')) cls.CERTFILE = _set_cacertificate(test_set, ca_dir=cls.ca_dir) # referrals for AD log.debug("[testconnection] checking noreferrals: %s" % params.get('NOREFERRALS', "False")) if "True" == params.get('NOREFERRALS', "False"): l.set_option(ldap.OPT_REFERRALS, 0) l.network_timeout = float(params['TIMEOUT']) dn_encode = params['BINDDN'].encode(ENCODING) pw_encode = params['BINDPW'].encode(ENCODING) l.simple_bind_s(dn_encode, pw_encode) # get a userlist: resultList = [] searchFilter = "(&" + params['LDAPSEARCHFILTER'] + ")" sizelimit = int(DEFAULT_SIZELIMIT) try: sizelimit = int(params.get("SIZELIMIT", DEFAULT_SIZELIMIT)) except ValueError: sizelimit = int(DEFAULT_SIZELIMIT) ldap_result_id = l.search_ext(params['LDAPBASE'], ldap.SCOPE_SUBTREE, filterstr=searchFilter, sizelimit=sizelimit) while 1: userdata = {} result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: # compose response as we like it userdata["userid"] = result_data[0][0] resultList.append(userdata) except ldap.SIZELIMIT_EXCEEDED as e: if len(resultList) < sizelimit: status = "success SIZELIMIT_EXCEEDED" log.warning("[testconnection] LDAP Error: %r" % e) except ldap.LDAPError as e: status = "error" log.error("[testconnection] LDAP Error: %s\n%s" % (str(e), traceback.format_exc())) return (status, str(e)) finally: # unbind if l: l.unbind_s() # restore the old_cert_file if old_cert_file != None: cls.CERTFILE = _set_cacertificate(cls.ca_certs, ca_dir=cls.ca_dir) return (status, resultList)
def bind(self): """ bind() - this function starts an ldap conncetion """ if self.l_obj is not None: return self.l_obj if self.bind_not_possible: t2 = datetime.now() tdelta = t2 - self.bind_not_possible_time # If we try a bind within 30 seconds, we will # bail out! if tdelta.seconds > BIND_NOT_POSSIBLE_TIMEOUT or tdelta.days > 1: log.info("[bind] Resetting the bind_not_possible timeout.") self.bind_not_possible = False else: log.error("[bind] LDAP bind timed out the last time. " "So we do not try to bind again at this moment. " "Skipping for performance sake! " "Trying a real bind again in %r seconds" % (BIND_NOT_POSSIBLE_TIMEOUT - tdelta.seconds)) return False uri = "" urilist = self.ldapuri.split(',') i = 0 log.debug("[bind] trying to bind to one of the servers: %r" % urilist) l_obj = None while i < len(urilist): uri = urilist[i] try: log.debug("[bind] LDAP: Try to bind to %r", uri) l_obj = ldap.initialize(uri, trace_level=0) if uri.startswith('ldaps'): # the setting of the CERTFILE is required only once old_cert_file = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) if self.CERTFILE is not None and old_cert_file == None: ldap.set_option( ldap.OPT_X_TLS_CACERTFILE, self.CERTFILE) # referrals for AD log.debug("[bind] checking noreferrals: %r" % self.noreferrals) if self.noreferrals: l_obj.set_option(ldap.OPT_REFERRALS, 0) l_obj.network_timeout = self.timeout # This is HIGH debug #log.debug("[bind] %s, %s" %(self.binddn, self.bindpw)) dn_encode = self.binddn.encode(ENCODING) pw_encode = self.bindpw.encode(ENCODING) l_obj.simple_bind_s(dn_encode, pw_encode) if i > 0: urilist[i] = urilist[0] urilist[0] = uri self.ldapuri = ','.join(urilist) self.l_obj = l_obj return l_obj except ldap.LDAPError as e: log.error("[bind] LDAP error: %r" % e) log.error("[bind] LDAPURI : %r" % uri) log.error("[bind] %s" % traceback.format_exc()) i = i + 1 # We were not able to do a successful bind! :-( self.bind_not_possible = True self.bind_not_possible_time = datetime.now() self.l_obj = l_obj return l_obj
import ldap ldap.set_option(ldap.OPT_DEREF,0) print ldap.get_option(ldap.OPT_DEREF) ldap.set_option(ldap.OPT_DEREF,1) print ldap.get_option(ldap.OPT_DEREF) ldap.set_option(ldap.OPT_DEREF,2) print ldap.get_option(ldap.OPT_DEREF) print ldap.get_option(ldap.OPT_TIMEOUT) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT) ldap.set_option(ldap.OPT_TIMEOUT,0.0) print ldap.get_option(ldap.OPT_TIMEOUT) ldap.set_option(ldap.OPT_NETWORK_TIMEOUT,0.0) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT) ldap.set_option(ldap.OPT_TIMEOUT,30.0) print ldap.get_option(ldap.OPT_TIMEOUT) ldap.set_option(ldap.OPT_NETWORK_TIMEOUT,30.0) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT)
import ldap ldap.set_option(ldap.OPT_DEREF, 0) print ldap.get_option(ldap.OPT_DEREF) ldap.set_option(ldap.OPT_DEREF, 1) print ldap.get_option(ldap.OPT_DEREF) ldap.set_option(ldap.OPT_DEREF, 2) print ldap.get_option(ldap.OPT_DEREF) print ldap.get_option(ldap.OPT_TIMEOUT) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT) ldap.set_option(ldap.OPT_TIMEOUT, 0.0) print ldap.get_option(ldap.OPT_TIMEOUT) ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 0.0) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT) ldap.set_option(ldap.OPT_TIMEOUT, 30.0) print ldap.get_option(ldap.OPT_TIMEOUT) ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 30.0) print ldap.get_option(ldap.OPT_NETWORK_TIMEOUT)
def get_option(self, option): return ldap.get_option(option)
def testconnection(cls, params): ''' This is used to test if the given parameter set will do a successful LDAP connection. params are: BINDDN BINDPW LDAPURI TIMEOUT LDAPBASE LOGINNAMEATTRIBUTE': 'sAMAccountName', LDAPSEARCHFILTER': '(sAMAccountName=*)(objectClass=user)', LDAPFILTER': '(&(sAMAccountName=%s)(objectClass=user))', USERINFO': '{ "username": "******", "phone" : "telephoneNumber", "mobile" : "mobile", "email" : "mail", "surname" : "sn", "givenname" : "givenName" }' SIZELIMIT NOREFERRALS CACERTIFICATE ''' old_cert_file = None try: # do a bind uri = params['LDAPURI'] l = ldap.initialize(uri, trace_level=0) if uri.startswith('ldaps'): ## for test purpose, we create a temporay file with only this cert old_cert_file = ldap.get_option(ldap.OPT_X_TLS_CACERTFILE) ##put all certs in a set test_set = set() test_set.update(cls.ca_certs) ## including the test one cert = params.get('CACERTIFICATE') test_set.add(cert.strip().replace('\r\n', '\n')) cls.CERTFILE = _set_cacertificate(test_set, ca_dir=cls.ca_dir) # referrals for AD log.debug("[testconnection] checking noreferrals: %s" % params.get('NOREFERRALS', "False")) if "True" == params.get('NOREFERRALS', "False"): l.set_option(ldap.OPT_REFERRALS, 0) l.network_timeout = float(params['TIMEOUT']) dn_encode = params['BINDDN'].encode(ENCODING) pw_encode = params['BINDPW'].encode(ENCODING) l.simple_bind_s(dn_encode, pw_encode) # get a userlist: resultList = [] searchFilter = "(&" + params['LDAPSEARCHFILTER'] + ")" sizelimit = int(DEFAULT_SIZELIMIT) try: sizelimit = int(params.get("SIZELIMIT")) except: pass ldap_result_id = l.search_ext(params['LDAPBASE'], ldap.SCOPE_SUBTREE, filterstr=searchFilter, sizelimit=sizelimit) while 1: userdata = {} result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: # compose response as we like it userdata["userid"] = result_data[0][0] resultList.append(userdata) # unbind l.unbind_s() except ldap.LDAPError as e: log.error("[testconnection] LDAP Error: %s\n%s" % (str(e), traceback.format_exc())) return ("error", str(e)) finally: #restore the old_cert_file if old_cert_file != None: cls.CERTFILE = _set_cacertificate(cls.ca_certs, ca_dir=cls.ca_dir) return ("success", resultList)
# # Test under Alpine: # docker run --rm -i -t python:2-alpine sh # # apk update # apk add ca-certificates build-base openldap-dev # pip install python-ldap # # import ldap ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 5) ldap.set_option(ldap.OPT_PROTOCOL_VERSION, ldap.VERSION3) # # Useful under some OSes? # Was necessary for Alpine Linux (with ca-certificates package) # Was getting this error: # ldap.SERVER_DOWN: {'info': 'error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed (self signed certificate in certificate chain)', 'desc': "Can't contact LDAP server"} # if not ldap.get_option(ldap.OPT_X_TLS_CACERTDIR): ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, '/etc/ssl/certs') ld = ldap.initialize('ldaps://ldap.YOUR.BUSINESS.COM') ld.simple_bind_s('<DOMAIN>\\' + '<USERNAME>', '<PASSWORD>')
import ldap host="localhost:1390" print "API info:",ldap.get_option(ldap.OPT_API_INFO) print "debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL) #print "Setting debug level to 255..." #ldap.set_option(ldap.OPT_DEBUG_LEVEL,255) #print "debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL) print "default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT) print "Setting default size limit to 10..." ldap.set_option(ldap.OPT_SIZELIMIT,10) print "default size limit:",ldap.get_option(ldap.OPT_SIZELIMIT) print "Creating connection to",host,"..." l=ldap.init(host) print "size limit:",l.get_option(ldap.OPT_SIZELIMIT) print "Setting connection size limit to 20..." l.set_option(ldap.OPT_SIZELIMIT,20) print "size limit:",l.get_option(ldap.OPT_SIZELIMIT) #print "Setting time limit to 60 secs..." l.set_option(ldap.OPT_TIMELIMIT,60) #print "time limit:",l.get_option(ldap.OPT_TIMELIMIT) print "Binding..." l.simple_bind_s("","")
#!/usr/bin/env python # Alberto Coduti - Mar 2019 import ldap from sys import exit try: l = ldap.initialize('ldaps://192.167.206.103:636') l.simple_bind() except ldap.LDAPError, error: print "\nError %s - %s: %s\n" % (error[0]['errno'], error[0]['info'], error[0]['desc']) exit(-1) print "Connesso a %s" % ldap.get_option(48) baseDN = "dc=cm,dc=cluster" searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = "uid=*coduti*" ldap_result = l.search_s(baseDN, searchScope, searchFilter, retrieveAttributes) print ldap_result[0][1]['mail']
import ldap host = "localhost:1390" print("API info:", ldap.get_option(ldap.OPT_API_INFO)) print("debug level:", ldap.get_option(ldap.OPT_DEBUG_LEVEL)) #print("Setting debug level to 255...") #ldap.set_option(ldap.OPT_DEBUG_LEVEL,255) #print("debug level:",ldap.get_option(ldap.OPT_DEBUG_LEVEL)) print("default size limit:", ldap.get_option(ldap.OPT_SIZELIMIT)) print("Setting default size limit to 10...") ldap.set_option(ldap.OPT_SIZELIMIT, 10) print("default size limit:", ldap.get_option(ldap.OPT_SIZELIMIT)) print("Creating connection to", host, "...") l = ldap.init(host) print("size limit:", l.get_option(ldap.OPT_SIZELIMIT)) print("Setting connection size limit to 20...") l.set_option(ldap.OPT_SIZELIMIT, 20) print("size limit:", l.get_option(ldap.OPT_SIZELIMIT)) #print("Setting time limit to 60 secs...") l.set_option(ldap.OPT_TIMELIMIT, 60) #print("time limit:",l.get_option(ldap.OPT_TIMELIMIT)) print("Binding...") l.simple_bind_s("", "")
def main(args): """Main function.""" # pylint: disable-msg=R0914 logging.getLogger().setLevel(logging.INFO) logging.getLogger().addHandler(logging.StreamHandler(sys.stderr)) loghandler = logging.handlers.SysLogHandler(address='/dev/log', facility=logging.handlers.SysLogHandler.LOG_AUTH) loghandler.setFormatter(logging.Formatter('sshldapauthkey %(levelname)-9s' '%(message)s')) logging.getLogger().addHandler(loghandler) if len(args) != 1: logging.critical('Usage: sshauthkey <USERNAME>') sys.exit(1) uid = args[0] if uid in IGNORE_USERS: return conn = ldap.initialize(ldap.get_option(ldap.OPT_URI)) base = get_ldap_base(conn) conn.simple_bind_s(BINDDN, BINDPW) filterstr = ldap.filter.filter_format('(&(uid=%s)' '(objectClass=posixAccount)' '(objectClass=shadowAccount)' '(objectClass=ldapPublicKey))', (uid,)) results = conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, ('sshPublicKey',)) if len(results) != 1: logging.error('too many results for uid=%s', uid) sys.exit(2) for result in results: dname, attrs = result if 'sshPublicKey' in attrs: pubkeys = attrs['sshPublicKey'] for pubkey in pubkeys: match = PUBKEY_RE.match(pubkey) if not match: logging.warning('Could not parse ssh key in dn %s: %s', dname, pubkey) continue parts = match.groupdict() typ = parts['type'] key = parts['key'] comment = parts['comment'] if typ == 'ssh-dss': logging.error('DSA key type is no longer secure') continue options = parse_options(parts['options']) options.update(DEFAULT_OPTIONS) if options is None: line = '%s %s %s' % (typ, key, comment) else: line = '%s %s %s %s' % (format_options(options), typ, key, comment) try: print line except IOError as ioe: if ioe.errno == errno.EPIPE: logging.debug('sshd closed pipe') return logging.exception('Exception when printing')