Example #1
0
 def init_ldap(ldap_server=server,
               ldap_port=port,
               ldap_basedn=base_dn,
               ldap_mode=mode,
               secure=secure,
               cert_path=cert_path,
               cert_file=cert_file):
     """
     Inicialize ldap connection
     """
     logger.info('[%s] Initialize ldap connection' % str(ldap_server))
     if secure:
         if not ldap_port:
             ldap_port = 636
         con = ldap.initialize(
             "ldaps://" + ldap_server + ":" + str(ldap_port))
         if cert_path:
             con.set_option(ldap.OPT_X_TLS_CACERTDIR, cert_path)
         if cert_file:
             con.set_option(ldap.OPT_X_TLS_CACERTFILE, cert_file)
     else:
         if not ldap_port:
             ldap_port = 389
         con = ldap.initialize(
             "ldap://" + ldap_server + ":" + str(ldap_port))
     return con
    def authenticate(self, username, password, options):
        """
        See abstract method documentation.
        """
        log.debug("Username: %s" % username)
        log.debug("Options: %s" % options)

        failure_mode = False  # reject but continue
        if options.get('continue-on-failure', 'False') == 'False':
            failure_mode = None  # reject and do not continue

        try:
            import ldap
        except:
            log.debug("User: %s, ACTIVEDIRECTORY: False (no ldap)" % (username))
            return (failure_mode, '')

        # do AD search (if required)
        vars = {'username': username, 'password': password}
        if 'search-fields' in options:
            try:
                # setup connection
                ldap.set_option(ldap.OPT_REFERRALS, 0)
                l = ldap.initialize(_get_subs(options, 'server', vars))
                l.protocol_version = 3
                l.simple_bind_s(_get_subs(options, 'search-user', vars), _get_subs(options, 'search-password', vars))
                scope = ldap.SCOPE_SUBTREE

                # setup search
                attributes = map(lambda s: s.strip().format(**vars), options['search-fields'].split(','))
                result = l.search(_get_subs(options, 'search-base', vars), scope, _get_subs(options, 'search-filter', vars), attributes)

                # parse results
                _, suser = l.result(result, 60)
                _, attrs = suser[0]
                log.debug(("AD Search attributes: %s" % attrs))
                if hasattr(attrs, 'has_key'):
                    for attr in attributes:
                        if attr in attrs:
                            vars[attr] = str(attrs[attr][0])
                        else:
                            vars[attr] = ""
            except Exception:
                log.exception('ACTIVEDIRECTORY Search Exception for User: %s' % username)
                return (failure_mode, '')
        # end search

        # bind as user to check their credentials
        try:
            # setup connection
            ldap.set_option(ldap.OPT_REFERRALS, 0)
            l = ldap.initialize(_get_subs(options, 'server', vars))
            l.protocol_version = 3
            l.simple_bind_s(_get_subs(options, 'bind-user', vars), _get_subs(options, 'bind-password', vars))
        except Exception:
            log.exception('ACTIVEDIRECTORY Authenticate Exception for User %s' % username)
            return (failure_mode, '')

        log.debug("User: %s, ACTIVEDIRECTORY: True" % (username))
        return (True, _get_subs(options, 'auto-register-username', vars))
Example #3
0
def get_users(opts):
	ldap_server = input("LDAP Server: ")
	ldap_domain = input("LDAP Domain: ")
	username = input("LDAP Username: "******"LDAP '%s' Password: "******"%s@%s" % (username, domain), password)
Example #4
0
def do_login():
  proxy_user = app.config['ldap.proxy_user']
  proxy_pass = app.config['ldap.proxy_pass']
  ldap_server = app.config['ldap.ldap_server']
  ldap_search_base = app.config['ldap.ldap_search_base']
  signing_key = app.config['security.key']

  username = request.forms.get('username')
  password = request.forms.get('password')
  filter = app.config['ldap.username_attribute'] + "=" + username

  try:
    l = ldap.initialize(ldap_server)
    l.simple_bind_s(proxy_user, proxy_pass)
    result = l.search_s(ldap_search_base, ldap.SCOPE_SUBTREE, filter, None)
    if result == []:
      template = engine.get_template('login.html')
      return template.render({'ldap_error':'User ' + username + ' not found!'})
    bind_dn = result[0][0]
    l.unbind_s()

    l = ldap.initialize(ldap_server)
    l.simple_bind_s(bind_dn, password)

  except ldap.LDAPError as e:
    template = engine.get_template('login.html')
    return template.render({'ldap_error':e})
  
  response.set_cookie("auth", username, secret=signing_key, httponly=True)
  redirect("/")
Example #5
0
def auth_user(username,password):
	app.logger.debug("trackit.user.auth_user for " + username)

	if username == '':
		return False
	if password == '':
		return False

	## connect to LDAP and turn off referals
	l = ldap.initialize(app.config['LDAP_URI'])
	l.set_option(ldap.OPT_REFERRALS, 0)

	## and bind to the server with a username/password if needed in order to search for the full DN for the user who is logging in.
	try:
		if app.config['LDAP_ANON_BIND']:
			l.simple_bind_s()
		else:
			l.simple_bind_s( (app.config['LDAP_BIND_USER']), (app.config['LDAP_BIND_PW']) )
	except ldap.LDAPError as e:
		flash('Internal Error - Could not connect to LDAP directory: ' + str(e),'alert-danger')
		app.logger.error("Could not bind to LDAP: " + str(e))
		trackit.errors.fatal(e)

	app.logger.debug("trackit.user.auth_user ldap bind succeeded ")

	## Now search for the user object to bind as
	try:
		results = l.search_s(app.config['LDAP_SEARCH_BASE'], ldap.SCOPE_SUBTREE,(app.config['LDAP_USER_ATTRIBUTE']) + "=" + username)
	except ldap.LDAPError as e:
		app.logger.debug("trackit.user.auth_user no object found in ldap")
		return False

	app.logger.debug("trackit.user.auth_user ldap results found ")

	## handle the search results
	for result in results:
		dn	= result[0]
		attrs	= result[1]

		if dn == None:
			## No dn returned. Return false.
			return False

		else:
			## Found the DN. Yay! Now bind with that DN and the password the user supplied
			try:
				app.logger.debug("trackit.user.auth_user ldap attempting ldap simple bind as " + str(dn))
				lauth = ldap.initialize(app.config['LDAP_URI'])
				lauth.set_option(ldap.OPT_REFERRALS, 0)
				lauth.simple_bind_s( (dn), (password) )
				return True
			except ldap.LDAPError as e:
				## password was wrong
				app.logger.debug("trackit.core.auth_user ldap bind failed as " + str(dn))
				return False

			app.logger.debug("trackit.core.auth_user ldap bind succeeded as " + str(dn))

	## Catch all return false for LDAP auth
	return False
Example #6
0
    def _authenticate(self, ldap_server, base_dn, username, password,
            valid_groups):
        """Authenticate a user against an LDAP server.

        Also checks that the given user is a member of one of the groups
        in 'valid_groups'. If valid_groups is empty no group membership
        is required.
        """
        ldap_con = ldap.initialize(ldap_server)
        ldap_con.simple_bind_s('', '')
        if type(base_dn) == unicode:
            base_dn = base_dn.encode('utf-8')
        try:
            search_user = '******' % (username)
            res = ldap_con.search_s(base_dn, ldap.SCOPE_SUBTREE, search_user,
                    attrsonly = True, attrlist = ['uid'])
            if len(res) != 1:
                return None
            dn, attrs = res[0]
#            if not self._userInValidGroup(ldap_con, base_dn, dn, valid_groups):
#                return None
        finally:
            ldap_con.unbind()
        try:
            l = ldap.initialize(ldap_server)
            l.simple_bind_s(dn, password)
            l.unbind()
        except ldap.INVALID_CREDENTIALS:
            return None
        except ldap.LDAPError, e:
            return None
Example #7
0
    def _start_daemon(self):
        """Start the instance."""
        if subprocess.call(["slapd", "-F", self.conf_slapd_d_dir,
                            "-h", self.url_list]) != 0:
            raise Exception("Failed to start slapd")

        #
        # Wait until it is available
        #
        attempt = 0
        while True:
            try:
                ldap_conn = ldap.initialize(self.ldapi_url)
                ldap_conn.simple_bind_s(self.admin_rdn + ",cn=config",
                                        self.admin_pw)
                ldap_conn.unbind_s()
                ldap_conn = ldap.initialize(self.ldap_url)
                ldap_conn.simple_bind_s(self.admin_dn, self.admin_pw)
                ldap_conn.unbind_s()
                break
            except ldap.SERVER_DOWN:
                pass
            attempt = attempt + 1
            if attempt > 30:
                raise Exception("Failed to start slapd")
            time.sleep(1)
def init_conn():
    try:
        con = ldap.initialize("""  my LDAP server """)
    except:
        con = ldap.initialize("""  my Backup LDAP server """)    
    con.simple_bind_s(""" bind to some DB """)
    return con
Example #9
0
def main(args):
    """
    Process a file contain a list of user accounts to create.
    """

    options = _create_parser().parse_args(args = args)

    user = getuser()

    if user != 'atool':
        raise RuntimeError("Not running as correct user: "******" (run as atool)")

    lock = get_lock()

    options.calnet_ldap = ldap.initialize(options.calnet_ldap_url)
    options.calnet_ldap.simple_bind_s("", "")
    options.calnet_ldap.protocol_version = ldap.VERSION3

    options.ocf_ldap = ldap.initialize(options.ocf_ldap_url)
    options.ocf_ldap.simple_bind_s("", "")
    options.ocf_ldap.protocol_version = ldap.VERSION3

    if options.backup:
        backup(options)

    filter_stage(options)
    create_stage(options)
Example #10
0
 def __init__(self, database, ldap_base, ldap_server, ldap_port = None):
     self.database = database
     self.ldap_base = ldap_base
     if ldap_port == None:
         self.l = ldap.initialize('ldap://%s' % ldap_server)
     else:
         self.l = ldap.initialize('ldap://%s:%d' % (ldap_server, ldap_port))
     self.l.protocol_version = ldap.VERSION3
Example #11
0
    def setup(self):
        """Setup the instance."""
        ldapi_socket = self.run_dir + "/ldapi"
        self.ldapi_url = "ldapi://" + url_quote(ldapi_socket, "")
        self.url_list = self.ldapi_url + " " + self.ldap_url

        os.makedirs(self.conf_slapd_d_dir)
        os.makedirs(self.run_dir)
        os.makedirs(self.data_dir)

        super(FakeAD, self)._setup_config()
        self._setup_config()

        # Start the daemon
        super(FakeAD, self)._start_daemon()

        # Relax requirement of surname attribute presence in person
        modlist = [
            (ldap.MOD_DELETE, "olcObjectClasses",
             b"{4}( 2.5.6.6 NAME 'person' DESC 'RFC2256: a person' SUP top "
             b"STRUCTURAL MUST ( sn $ cn ) MAY ( userPassword $ "
             b"telephoneNumber $ seeAlso $ description ) )"),
            (ldap.MOD_ADD, "olcObjectClasses",
             b"{4}( 2.5.6.6 NAME 'person' DESC 'RFC2256: a person' SUP top "
             b"STRUCTURAL MUST ( cn ) MAY ( sn $ userPassword $ "
             b"telephoneNumber $ seeAlso $ description ) )"),
        ]
        ldap_conn = ldap.initialize(self.ldapi_url)
        ldap_conn.simple_bind_s(self.admin_rdn + ",cn=config", self.admin_pw)
        ldap_conn.modify_s("cn={0}core,cn=schema,cn=config", modlist)
        ldap_conn.unbind_s()

        # restart daemon for reloading schema
        super(FakeAD, self)._stop_daemon()
        super(FakeAD, self)._start_daemon()

        # Add data
        ldap_conn = ldap.initialize(self.ldap_url)
        ldap_conn.simple_bind_s(self.admin_dn, self.admin_pw)
        ldap_conn.add_s(self.base_dn, [
            ("objectClass", [b"dcObject", b"organization"]),
            ("o", b"Example Company"),
        ])
        ldap_conn.add_s("cn=Manager," + self.base_dn, [
            ("objectClass", b"organizationalRole"),
        ])
        for ou in ("Users", "Groups", "Netgroups", "Services", "Policies"):
            ldap_conn.add_s("ou=" + ou + "," + self.base_dn, [
                ("objectClass", [b"top", b"organizationalUnit"]),
            ])
        ldap_conn.unbind_s()

        # import data from real AD
        subprocess.check_call(
            ["ldapadd", "-x", "-w", self.admin_pw, "-D",
             self.admin_dn, "-H", self.ldap_url,
             "-f", "data/ad_data.ldif"],
        )
Example #12
0
    def __init__(self, hostname, port=None, dn='', password='',
                 encryption=None, require_cert=None, debug=False,
                 initialize_kwargs=None, options=None):
        """
        Bind to hostname:port using the passed distinguished name (DN), as
        ``dn``, and password.

        If no user and password is given, try to connect anonymously with a
        blank DN and password.

        ``encryption`` should be one of ``'tls'``, ``'ssl'``, or ``None``.
        If ``'tls'``, then the standard port 389 is used by default and after
        binding, tls is started.  If ``'ssl'``, then port 636 is used by
        default.

        ``require_cert`` is None by default.  Set this to ``True`` or
        ``False`` to set the ``OPT_X_TLS_REQUIRE_CERT`` ldap option.

        If ``debug`` is ``True``, debug options are turned on within ldap and
        statements are ouput to standard error.  Default is ``False``.

        If give, ``options`` should be a dictionary of any additional
        connection-specific ldap  options to set, e.g.:
        ``{'OPT_TIMELIMIT': 3}``.
        """

        self._search_defaults = {}

        if not encryption or encryption == 'tls':
            protocol = 'ldap'
            if not port:
                port = 389
        elif encryption == 'ssl':
            protocol = 'ldaps'
            if not port:
                port = 636
        else:
            raise InvalidEncryptionProtocol(
                "Invalid encryption protocol, must be one of: 'tls' or 'ssl'.")

        if require_cert is not None:
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, require_cert)
        if debug:
            ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255)
        else:
            ldap.set_option(ldap.OPT_DEBUG_LEVEL, 0)

        uri = '%s://%s:%s' % (protocol, hostname, port)
        if initialize_kwargs:
            self.connection = ldap.initialize(uri, **initialize_kwargs)
        else:
            self.connection = ldap.initialize(uri)
        if options:
            for name, value in options.iteritems():
                self.connection.set_option(getattr(ldap, name), value)
        if encryption == 'tls':
            self.connection.start_tls_s()
        self.connection.simple_bind_s(dn, password)
Example #13
0
def get_ldap_user(username, password):
    """Try to authenticate using the global LDAP configuration file.

    Return the username on success.
    """
    ldap_cfg = LdapConfig()
    con = ldap.initialize(ldap_cfg.server())
    if not ldap_cfg.bind_anonymous():
        con.simple_bind_s(ldap_cfg.bind_user(),
                            ldap_cfg.bind_pass())

    baseDN = ldap_cfg.root_search()
    searchScope = ldap.SCOPE_SUBTREE
    retrieveAttributes = None

    # XXX : Needs sanitation
    searchFilter = '(uid=' + username + ')'

    timeout = 0
    count = 0

    # find the user's dn
    result_id = con.search(baseDN,
                        searchScope,
                        searchFilter,
                        retrieveAttributes)
    result_set = []
    while 1:
        result_type, result_data = con.result(result_id, timeout)
        if (result_data == []):
            break
        else:
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)

    if len(result_set) == 0:
        #no results
        return None

    if len(result_set) > 1:
        # too many results for the same uid
        raise

    user_dn, entry = result_set[0][0]
    if not ldap_cfg.bind_anonymous():
        con.unbind_s()

    # check the password
    try:
        con = ldap.initialize(ldap_cfg.server())
        con.simple_bind_s(user_dn, password)
    except ldap.INVALID_CREDENTIALS:
        return None
    except:
        raise

    return entry['cn'][0]
Example #14
0
	def _connect(self):
		try:
			if not self.secure:
				self.ld = ldap.initialize("ldap://%s:%s" % (self.server, self.port))
			else:
				self.ld = ldap.initialize("ldaps://%s:%s" % (self.server, self.port))
		except ldap.LDAPError, e:
			print 'Cannot connect, %s' % e
			exit(1)
Example #15
0
    def test_volatile_modification(self):
        self.mockldap.start()
        conn1 = ldap.initialize('')
        conn1.directory['cn=alice,ou=example,o=test']['userPassword'][0] = 'modified'
        self.mockldap.stop()

        self.mockldap.start()
        conn2 = ldap.initialize('')
        self.mockldap.stop()

        self.assertNotEqual(conn1.directory, conn2.directory)
Example #16
0
    def process_authentication_request(self, request):
        username = request.POST['username'].strip()
        password = request.POST['password']
        uid = str(settings.LDAP_USER_MASK) % username

        #an empty password will cause ldap to try an anonymous bind. This is picked up here
        if not password:
            raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))

        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if(settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(str(settings.LDAP_BIND_DN), str(settings.LDAP_BIND_SECRET))
            search = ldapo.search_s(str(settings.LDAP_BASE_DN), ldap.SCOPE_SUBTREE, uid)
        except ldap.LDAPError:
            #could not bind using credentials specified in ldap config
            raise InvalidAuthentication(_('Login failed - LDAP bind error. Please contact your system administrator'))

        ldapo.unbind_s()

        if not search:
            #could not find user
            raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))

        #now try to bind as selected user; should raise exception if bind fails
        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if(settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(uid + ',' + str(settings.LDAP_BASE_DN),password)
        except ldap.LDAPError:
            #could not bind as user - password is incorrect
            raise InvalidAuthentication(_('Login failed. Please enter valid username and password (both are case-sensitive)'))
        ldapo.unbind_s()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            userinfo = search[0][1]
            usernameVal = userinfo[str(settings.LDAP_UID)][0]           
            emailVal = usernameVal + '@schrodinger.com'
            if str(settings.LDAP_MAIL) in userinfo:
              emailVal = userinfo[str(settings.LDAP_MAIL)][0]           
            _user = User( username = usernameVal, 
                          email = emailVal,
                          real_name = userinfo[str(settings.LDAP_NAME)][0] )
            _user.email_isvalid = True
            _user.set_unusable_password()
            _user.save()
            UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()
            return _user
Example #17
0
def isuser(uname, pw):

    ldapconf = cherrypy.request.app.config.get("ldap")

    if "base_dn" in ldapconf and ldapconf.get("base_dn"):
        user = "******" % (uname, ldapconf.get("base_dn"))
    else:
        user = uname

    try:
        con = ldap.initialize(ldapconf.get("host", "ldap://localhost"))

        UserObj = {'uname': uname, 'groups': []}
        #first bind as the user to make sure we can login
        con.simple_bind_s(user, pw)

        #if LDAP_BIND_USER is defined, rebind as that user to get some additional info
        bind_dn = ldapconf.get("bind_dn", None)

        if bind_dn is not None:
            admincon = ldap.initialize(ldapconf.get("host", "ldap://localhost"))
            admincon.simple_bind_s(bind_dn, ldapconf.get("bind_password"))
            filter = "(uid=" + uname + ")"
            result = get_search_results(admincon.search_s(
                ldapconf.get("base_dn"),
                ldap.SCOPE_SUBTREE,
                filter,
                ldapconf.get("user_attributes")
            ))[0]

            for key in result.get_attr_names():
                UserObj[key] = result.get_attr_values(key)[0]

            filter = "(member=" + user + ")"
            groups = get_search_results(admincon.search_s(ldapconf.get("groupBaseDn"), ldap.SCOPE_SUBTREE, filter, ['cn']))

            for group in groups:
                UserObj['groups'].append(group.get_attributes()["cn"][0])

        print "Logged In User: %s" % (UserObj)
        cherrypy.session["user"] = UserObj

        return True

    except ldap.SERVER_DOWN:
        print "SERVER CONNECTION DOWN: Should we try to re-establish our tunnel somehow? root needs to do that..."
        return False

    except ldap.INVALID_CREDENTIALS, e:
        return False
Example #18
0
def get_user(credentials):
    ldap_cfg = LdapConfig()
    con = ldap.initialize(ldap_cfg.server())
    con.simple_bind_s(ldap_cfg.bind_user(),
                        ldap_cfg.bind_pass())

    baseDN = ldap_cfg.root_search()
    searchScope = ldap.SCOPE_SUBTREE
    retrieveAttributes = None 
    # XXX : Needs sanitation
    searchFilter = '(uid=' + credentials['username'] + ')'
    timeout = 0
    count = 0

    # find the user's dn
    result_id = con.search(baseDN, 
                        searchScope, 
                        searchFilter, 
                        retrieveAttributes)
    result_set = []
    while 1:
        result_type, result_data = con.result(result_id, timeout)
        if (result_data == []):
            break
        else:
            if result_type == ldap.RES_SEARCH_ENTRY:
                result_set.append(result_data)

    if len(result_set) == 0:
        #no results
        return None

    if len(result_set) > 1:
        # too many results for the same uid
        raise

    user_dn, entry = result_set[0][0]	
    con.unbind_s()
    
    # check the password 
    try:  
        con = ldap.initialize(ldap_cfg.server())
        con.simple_bind_s(user_dn,
                          credentials['password'])
    except ldap.INVALID_CREDENTIALS:
        return None
    except:
        raise

    return entry['cn'][0]
Example #19
0
def create_ldap_connection(ldap_server, ldap_connection_timeout):
    ldap_connection = None
    timeout = None
    try:
        timeout = float(ldap_connection_timeout)
    except ValueError:
        pass
    print 'Timeout', timeout
    if ldap_server != None:
        if timeout != None:
            ldap_connection = initialize(ldap_server, timeout)
        else:
            ldap_connection = initialize(ldap_server)
    return ldap_connection
Example #20
0
    def authenticate(self, username=None, password=None):
        if password == "" or password is None or username is None:
            raise Exception('Invalid user or password')

        username, password = username.strip(), password.strip()
        try:
            conn = ldap.initialize(LDAP_URL)
            if LDAP_BINDNAME != '':
                conn.simple_bind_s(LDAP_BINDNAME, LDAP_BINDPASS)
            result = conn.search_ext_s(LDAP_BASECN, ldap.SCOPE_SUBTREE,
                                       LDAP_FILTER % username, None)
            conn.unbind_s()
        except ldap.SERVER_DOWN:
            # raise Exception('Authentication server is down')
            return None

        if len(result) == 0:
            return None
        dn = result[0][0]

        try:
            conn = ldap.initialize(LDAP_URL)
            conn.simple_bind_s(dn, password)
            conn.unbind_s()
        except ldap.NO_SUCH_OBJECT:
            return None
        except ldap.INVALID_CREDENTIALS:
            return None
        except ldap.UNWILLING_TO_PERFORM:
            return None
        except UnicodeEncodeError:
            logging.error('Unicode password crashed ldap')
            return None

        # create or get user here:
        data = result[0][1]
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            first_name = data['givenName'][0].decode('utf8')
            last_name = data['sn'][0].decode('utf8')
            user = User(username=username, first_name=first_name,
                        last_name=last_name, email=data['mail'][0])
            user.is_staff = False
            user.is_superuser = False
            user.is_active = True
            # IMPORTANT: login only via ldap
            user.set_unusable_password()
            user.save()
        return user
Example #21
0
def authenticate(username, password):
	if len(username) == 0:
		return False
	if len(password) == 0:
		return False

	## connect to LDAP and turn off referals
	l = ldap.initialize(app.config['LDAP_URI'])
	l.set_option(ldap.OPT_REFERRALS, 0)

	## and bind to the server with a username/password if needed in order to search for the full DN for the user who is logging in.
	try:
		if app.config['LDAP_ANON_BIND']:
			l.simple_bind_s()
		else:
			l.simple_bind_s( (app.config['LDAP_BIND_USER']), (app.config['LDAP_BIND_PW']) )
	except ldap.LDAPError as e:
		flash('Internal Error - Could not connect to LDAP directory: ' + str(e),'alert-danger')
		app.logger.error("Could not bind to LDAP: " + str(e))
		abort(500)

	## Now search for the user object to bind as
	try:
		results = l.search_s(app.config['LDAP_SEARCH_BASE'], ldap.SCOPE_SUBTREE,(app.config['LDAP_USER_ATTRIBUTE']) + "=" + username)
	except ldap.LDAPError as e:
		return False

	## handle the search results
	for result in results:
		dn	= result[0]
		attrs	= result[1]

		if dn == None:
			## No dn returned. Return false.
			return False
		else:
			## Found the DN. Yay! Now bind with that DN and the password the user supplied
			try:
				lauth = ldap.initialize(app.config['LDAP_URI'])
				lauth.set_option(ldap.OPT_REFERRALS, 0)
				lauth.simple_bind_s( (dn), (password) )
			except ldap.LDAPError as e:
				## password was wrong
				return False

			## Return that LDAP auth succeeded
			return True

	## Catch all return false for LDAP auth
	return False
Example #22
0
    def check_auth(self, user, password):
        # If we do not have an ldap uri, no auth :)
        if not self.ldap_uri:
            return False
        
        print "Trying to auth by ldap", user, password

        c = self.app.datamgr.get_contact(user)

        if not c:
            print "AD/Ldap : invalid user (not founded)", user
            return False

        # first we need to find the principalname of this entry
        # because it can be a user name like j.gabes, but we should auth by ldap
        # with [email protected] for example
        elts = self.find_contact_entry(c)

        try :
            account_name = elts['userPrincipalName'][0]
        except KeyError:
            print "Cannot find the userPrincipalName entry, so use the user entry"
            account_name = user

        local_con = ldap.initialize(self.ldap_uri)
        local_con.set_option(ldap.OPT_REFERRALS,0)
        
        # Any errors will throw an ldap.LDAPError exception
        # or related exception so you can ignore the result
        try:
            local_con.simple_bind_s(account_name, password)
            print "AD/Ldap Connection done with", user, password
            return True
        except ldap.LDAPError, exp:
            print "LMdap auth error:", exp
Example #23
0
  def _ldget(self, url):
    """Get data from LDAP."""
    result = []

    ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, self._cacertdir)
    l = ldap.initialize(url)
    l.protocol_version = ldap.VERSION3

    # Fetch paged results from ldap server.
    # This is needed because there is a size limit on the CERN ldap server
    # side to return at most 1000 entries per request.
    # For more information, see http://tools.ietf.org/html/rfc2696.html
    srv_ctrls = [ldap.controls.SimplePagedResultsControl(criticality=False, cookie="")]
    while True:
      srv_ctrls[0].size = 1000 # dont necessarily need to match the server limit
      s = l.search_ext('OU=Users,OU=Organic Units,DC=cern,DC=ch',
                       ldap.SCOPE_SUBTREE,
                       '(memberOf:1.2.840.113556.1.4.1941:=CN=cms-authorized-users,OU=e-groups,OU=Workgroups,DC=cern,DC=ch)',
                       ['sAMAccountName','displayName','employeeID','mail','altSecurityIdentities','userAccountControl'],
                       serverctrls=srv_ctrls,
                       sizelimit=0)
      _, res_data, _, srv_ctrls = l.result3(s, timeout=100)
      result.extend(res_data)
      if not srv_ctrls[0].cookie: break

    if not result:
      raise RuntimeError("Ldap returned no data for %s" % url)
    return result
Example #24
0
    def setup(self, config, model_version):
        """Called before the plugin is asked to do anything."""

        if config.getboolean('Data Model Options', 'ldap_plugin_enabled'):
            self.plugin_enabled = True
            LOG.debug("LDAP plugin enabled")

            ldap_url = config.get('Data Model Options', 'ldap_server')
            ldap_dc = config.get('Data Model Options', 'ldap_dc')

            ldap_ou_group = config.get('Data Model Options', 'ldap_ou_group')
            ldap_ou_user = config.get('Data Model Options', 'ldap_ou_user')

            ldap_timeout = config.getfloat(
                'Data Model Options', 'ldap_timeout')

            self.ldap_dn_user = "******" + ldap_ou_user + "," + ldap_dc
            self.ldap_dn_group = "ou=" + ldap_ou_group + "," + ldap_dc

            LOG.debug("URL: " + ldap_url)
            LOG.debug("Base DC: " + ldap_dc)
            LOG.debug("DN for groups: " + self.ldap_dn_group)
            LOG.debug("DN for users: " + self.ldap_dn_user)

            self.ldap_ctx = ldap.initialize(ldap_url)
            self.ldap_ctx.set_option(ldap.OPT_NETWORK_TIMEOUT, ldap_timeout)

            self.config = config
            self.model_version = model_version
        else:
            self.plugin_enabled = False
Example #25
0
    def ldap_lookup(self):

        username = self.username

        if username:

            for host in self.hosts:

                con = ldap.initialize(host)

                if con.simple_bind():
                    base_dn = "dc=psu,dc=edu"

                    _filter = "(uid=%s)" % username

                    results = con.search_s( base_dn, ldap.SCOPE_SUBTREE, _filter, self.attrs )

                    for r in results:
                        (_id, data) = r

                        for (k,v) in data.iteritems():

                            if isinstance(v, (tuple, list)):
                                if len(v) == 1:
                                    data[k] = v[0]

                        data['ldap_host'] = self.ldap_host(host)

                        return data
        return {}
Example #26
0
def index(req):
    server=server_info.get_info(req)
    language=gettext.translation('messages',dir, languages=[server[4]])
    _=language.ugettext

    ldap_server = ldap.initialize('ldap://'+server[2])
    ldap_server.protocol_version = ldap.VERSION3
    page=template_page.page_header()+'<title>'+_('delete')+'</title></head><body>'
    try:
        ldap_server.bind_s(server[0],server[1])
        base_dn=server[3]
        counter=0
        filter = '(objectclass=*)'
        attrs = ["*"]
        result=ldap_server.search_s(base_dn,ldap.SCOPE_SUBTREE,filter,attrs)
        page+='<form method="post" action="delete_user.py/remove"><div align="left">'
        for dn in result:
            page+='<input type="checkbox" name="remove" value="'+dn[0]+'">'+dn[0]+'<br/>'
            counter+=1
        page+='<input type="submit" value="'+_('submit')+'">'
        page+='</body></html>'
    except:
        page+=_('there is some problem please')+' <a href="./">'+_('try')+'</a>'+_('again')+'.</body></html>'
    ldap_server.unbind()
    return page
Example #27
0
 def _cursor(self):
     if self.connection is None:
         self.connection = ldap.initialize(settings.LDAPDB_SERVER_URI)
         self.connection.simple_bind_s(
             settings.LDAPDB_BIND_DN,
             settings.LDAPDB_BIND_PASSWORD)
     return DatabaseCursor(self.connection)
Example #28
0
    def __init__(self):
        if not ldap:
            raise ImportError(_('ldap not installed'))

        self.lobj = ldap.initialize(CONF.ldap_dns_url)
        self.lobj.simple_bind_s(CONF.ldap_dns_user,
                                CONF.ldap_dns_password)
Example #29
0
def _ldap_init(webapp):
    ldap_obj = ldap.initialize(webapp.app.config['LDAP_DATABASE_URI'])
    ldap_obj.bind_s('cn=Manager,dc=%s,dc=%s' % (
        webapp.app.config['openldap_server_domain_name'].split('.')[0],
        webapp.app.config['openldap_server_domain_name'].split('.')[1]),
        webapp.app.config['openldap_server_rootpw'], ldap.AUTH_SIMPLE)
    return ldap_obj
def openConnection(host, port, binddn="", passwd=""):
    """Open a new connection to an LDAP server"""
    uri = "ldap://%s:%d/" % (host, port)
    server = ldap.initialize(uri)
    server.simple_bind_s(binddn, passwd)

    return server
Example #31
0
    def __init__(self,
                 url,
                 page_size,
                 alias_dereferencing=None,
                 use_tls=False,
                 tls_cacertfile=None,
                 tls_cacertdir=None,
                 tls_req_cert='demand'):
        LOG.debug(_("LDAP init: url=%s"), url)
        LOG.debug(
            _('LDAP init: use_tls=%(use_tls)s\n'
              'tls_cacertfile=%(tls_cacertfile)s\n'
              'tls_cacertdir=%(tls_cacertdir)s\n'
              'tls_req_cert=%(tls_req_cert)s\n'
              'tls_avail=%(tls_avail)s\n') % {
                  'use_tls': use_tls,
                  'tls_cacertfile': tls_cacertfile,
                  'tls_cacertdir': tls_cacertdir,
                  'tls_req_cert': tls_req_cert,
                  'tls_avail': ldap.TLS_AVAIL
              })

        #NOTE(topol)
        #for extra debugging uncomment the following line
        #ldap.set_option(ldap.OPT_DEBUG_LEVEL, 4095)

        using_ldaps = url.lower().startswith("ldaps")

        if use_tls and using_ldaps:
            raise AssertionError(_('Invalid TLS / LDAPS combination'))

        if use_tls:
            if not ldap.TLS_AVAIL:
                raise ValueError(
                    _('Invalid LDAP TLS_AVAIL option: %s. TLS'
                      'not available') % ldap.TLS_AVAIL)
            if tls_cacertfile:
                #NOTE(topol)
                #python ldap TLS does not verify CACERTFILE or CACERTDIR
                #so we add some extra simple sanity check verification
                #Also, setting these values globally (i.e. on the ldap object)
                #works but these values are ignored when setting them on the
                #connection
                if not os.path.isfile(tls_cacertfile):
                    raise IOError(
                        _("tls_cacertfile %s not found "
                          "or is not a file") % tls_cacertfile)
                ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, tls_cacertfile)
            elif tls_cacertdir:
                #NOTE(topol)
                #python ldap TLS does not verify CACERTFILE or CACERTDIR
                #so we add some extra simple sanity check verification
                #Also, setting these values globally (i.e. on the ldap object)
                #works but these values are ignored when setting them on the
                #connection
                if not os.path.isdir(tls_cacertdir):
                    raise IOError(
                        _("tls_cacertdir %s not found "
                          "or is not a directory") % tls_cacertdir)
                ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, tls_cacertdir)
            if tls_req_cert in LDAP_TLS_CERTS.values():
                ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, tls_req_cert)
            else:
                LOG.debug(_("LDAP TLS: invalid TLS_REQUIRE_CERT Option=%s"),
                          tls_req_cert)

        self.conn = ldap.initialize(url)
        self.conn.protocol_version = ldap.VERSION3

        if alias_dereferencing is not None:
            self.conn.set_option(ldap.OPT_DEREF, alias_dereferencing)
        self.page_size = page_size

        if use_tls:
            self.conn.start_tls_s()
Example #32
0
 def __init__(self):
     """connect to ldap on init"""
     self.con = ldap.initialize(app.config['LDAP_URL'])
     self.con.simple_bind_s(app.config['LDAP_USER'],
                            app.config['LDAP_PASS'])
Example #33
0
    def authenticate(self, request):
        username = request.POST['username']
        password = request.POST['password']

        if not username or not password:
            return None

        l = None

        try:
            userRDN = self._login_attr + '=' + username
            l = ldap.initialize(self._url)
            l.protocol_version = ldap.VERSION3

            # To authenticate, we need the user's distinguished name (DN).
            try:
                # If all of your users share the same organizational unit,
                # e.g. "ou=People,dc=example,dc=com", then the DN can be
                # constructed by concatening the user's relative DN
                # e.g. "uid=jsmith" with self._user_base, separated by
                # a comma.
                userDN = userRDN + ',' + self._user_base
                l.simple_bind_s(userDN, password)
            except ldap.LDAPError:
                # We failed to bind using the simple method of constructing
                # the userDN, so let's query the directory for the userDN.
                if self._admin_user and self._admin_pass:
                    l.simple_bind_s(self._admin_user, self._admin_pass)
                ldap_result = l.search_s(self._base, ldap.SCOPE_SUBTREE,
                                         userRDN)
                userDN = ldap_result[0][0]
                l.simple_bind_s(userDN, password)

            # No LDAPError raised so far, so authentication was successful.
            # Now let's get the attributes we need for this user:
            if self._admin_user and self._admin_pass:
                l.simple_bind_s(self._admin_user, self._admin_pass)
            retrieveAttributes = list(self._user_attr_map.keys()) + \
                                 [self._login_attr]
            ldap_result = l.search_s(self._base, ldap.SCOPE_SUBTREE, userRDN,
                                     retrieveAttributes)

            if ldap_result[0][1][self._login_attr][0] == username.encode():
                # check if the given username in combination with the LDAP
                # auth method is already in the UserAuthentication table
                user = ldap_result[0][1]
                return {
                    tardis_key: user[ldap_key][0].decode()
                    for ldap_key, tardis_key in self._user_attr_map.items()
                }
            return None

        except ldap.LDAPError:
            logger.exception("ldap error")
            return None
        except IndexError:
            logger.exception("index error")
            return None
        finally:
            if l:
                l.unbind_s()
Example #34
0
If a username is specified, this will be used as the SASL ID. 
Otherwise,the username will be retrieved from the 
environment.""" % sys.argv[0]

if len(sys.argv) > 1:
    if sys.argv[1] == "-h" or sys.argv[1] == "--help":
        print usage
        sys.exit()
    user_name = sys.argv[1]
else:
    user_name = getpass.getuser()

pw = getpass.getpass("Password for %s: " % user_name)

try:
    con = ldap.initialize("ldap://ed-p-gl.emea.nsn-net.net:389")
    auth_tokens = ldap.sasl.digest_md5(user_name, pw)

    try:
        con.sasl_interactive_bind_s("", auth_tokens)
        sys.stdout.write(con.whoami_s())
        sys.stdout.write("n")
    except ldap.LDAPError, e:
        sys.stderr.write("Fatal Error.n")
        if type(e.message) == dict:
            for (k, v) in e.message.iteritems():
                sys.stderr.write("%s: %sn" % (k, v))
        else:
            sys.stderr.write("Error: %sn" % e.message)

        sys.exit()
Example #35
0
    def authenticate(self, email, username, password, options):
        """
        See abstract method documentation.
        """
        log.debug("LDAP authenticate: email is %s" % email)
        log.debug("LDAP authenticate: username is %s" % username)
        log.debug("LDAP authenticate: options are %s" % options)

        failure_mode = False  # reject but continue
        if options.get('continue-on-failure', 'False') == 'False':
            failure_mode = None  # reject and do not continue

        if _get_bool(options, 'login-use-username', False):
            if username is None:
                log.debug(
                    'LDAP authenticate: username must be used to login, cannot be None'
                )
                return (failure_mode, '', '')
        else:
            if email is None:
                log.debug(
                    'LDAP authenticate: email must be used to login, cannot be None'
                )
                return (failure_mode, '', '')

        try:
            import ldap
        except:
            log.debug('LDAP authenticate: could not load ldap module')
            return (failure_mode, '', '')

        # do LDAP search (if required)
        params = {'email': email, 'username': username, 'password': password}
        if 'search-fields' in options:
            try:
                # setup connection
                ldap.set_option(ldap.OPT_REFERRALS, 0)
                l = ldap.initialize(_get_subs(options, 'server', params))
                l.protocol_version = 3

                if 'search-user' in options:
                    l.simple_bind_s(
                        _get_subs(options, 'search-user', params),
                        _get_subs(options, 'search-password', params))
                else:
                    l.simple_bind_s()

                scope = ldap.SCOPE_SUBTREE

                # setup search
                attributes = [
                    _.strip().format(**params)
                    for _ in options['search-fields'].split(',')
                ]
                result = l.search(_get_subs(options, 'search-base',
                                            params), scope,
                                  _get_subs(options, 'search-filter', params),
                                  attributes)

                # parse results
                _, suser = l.result(result, 60)
                dn, attrs = suser[0]
                log.debug(("LDAP authenticate: dn is %s" % dn))
                log.debug(
                    ("LDAP authenticate: search attributes are %s" % attrs))
                if hasattr(attrs, 'has_key'):
                    for attr in attributes:
                        if attr in attrs:
                            params[attr] = str(attrs[attr][0])
                        else:
                            params[attr] = ""
                params['dn'] = dn
            except Exception:
                log.exception('LDAP authenticate: search exception')
                return (failure_mode, '', '')
        # end search

        # bind as user to check their credentials
        try:
            # setup connection
            ldap.set_option(ldap.OPT_REFERRALS, 0)
            l = ldap.initialize(_get_subs(options, 'server', params))
            l.protocol_version = 3
            l.simple_bind_s(_get_subs(options, 'bind-user', params),
                            _get_subs(options, 'bind-password', params))
        except Exception:
            log.exception('LDAP authenticate: bind exception')
            return (failure_mode, '', '')

        log.debug('LDAP authentication successful')
        return (True, _get_subs(options, 'auto-register-email', params),
                _get_subs(options, 'auto-register-username', params))
Example #36
0
 def _unbind(self):
     self._conn.unbind()
     self._conn = ldap.initialize(self._uri, trace_level=0)
Example #37
0
 def _get_connection(self):
     if self._connection is None:
         self._connection = ldap.initialize('ldap://127.0.0.1:10389',
                                            bytes_mode=False)
         # optionå’Œtls
     return self._connection
Example #38
0
from flask import Flask,request,Response,json
import ldap,jsonify
con =ldap.initialize('ldap://10.21.74.44:3060')
con.simple_bind_s("cn=orcladmin", "Oracle#123")
ldap_base = "dc=in,dc=ril,dc=com"
app = Flask(__name__)



#create user 
#sample request
#curl -i -X POST http://10.21.74.44:5000/create --data '{"fullname":"test9.testSN9","lastname":"testSN9","desc":"developer","mobile":"1234567890","password":"******"}' -H 'Content-Type: application/json'



@app.route('/create', methods=['POST'])
def create():
    if request.method == 'POST':
     try:

        data = request.get_json()  #converting to python dictionary
        print('Data Received: "{data}"'.format(data=data))
        dn="cn="+data['fullname']+","+"cn=users,"+ldap_base
        entry ={"cn":data['fullname'],"sn":data['lastname'],"objectClass":"person","description":data['desc'],"telephoneNumber":data['mobile'],"userPassword":data['password']}
        parsed_entry=[(i,bytes(j,encoding='utf-8'))for i,j in entry.items()]
        con.add_s(dn,parsed_entry)
        rValue = "Created user : "******"\n"
        return Response(
          mimetype="application/json",
          response=rValue,
          status=200
Example #39
0
    record_schema = avro.load(AVROLOADPATH)
    producer = AvroProducer(conf, default_value_schema=record_schema)

    try:
        producer.produce(topic=KAFKATOPIC, value=mce)
        producer.poll(0)
        sys.stdout.write('\n%s has been successfully produced!\n' % mce)
    except ValueError as e:
        sys.stdout.write('Message serialization failed %s' % e)
    producer.flush()


ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)
ldap.set_option(ldap.OPT_REFERRALS, 0)

l = ldap.initialize(LDAPSERVER)
l.protocol_version = 3

try:
    l.simple_bind_s(LDAPUSER, LDAPPASSWORD)
except ldap.LDAPError as e:
    exit('LDAP bind failed: %s' % e)

lc = create_controls(PAGESIZE)

while True:
    try:
        msgid = l.search_ext(BASEDN,
                             ldap.SCOPE_SUBTREE,
                             SEARCHFILTER,
                             ATTRLIST,
Example #40
0
    def auth_user_ldap(self, username, password):
        """
            Method for authenticating user, auth LDAP style.
            depends on ldap module that is not mandatory requirement
            for F.A.B.

            :param username:
                The username
            :param password:
                The password
        """
        if username is None or username == "":
            return None
        user = self.find_user(username=username)
        if user is not None and (not user.is_active()):
            return None
        else:
            try:
                import ldap
            except:
                raise Exception("No ldap library for python.")
            try:
                if self.auth_ldap_allow_self_signed:
                    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT,
                                    ldap.OPT_X_TLS_ALLOW)
                con = ldap.initialize(self.auth_ldap_server)
                con.set_option(ldap.OPT_REFERRALS, 0)
                if self.auth_ldap_use_tls:
                    try:
                        con.start_tls_s()
                    except Exception:
                        log.info(
                            LOGMSG_ERR_SEC_AUTH_LDAP_TLS.format(
                                self.auth_ldap_server))
                        return None
                # Authenticate user
                if not self._bind_ldap(ldap, con, username, password):
                    if user:
                        self.update_user_auth_stat(user, False)
                    log.info(LOGMSG_WAR_SEC_LOGIN_FAILED.format(username))
                    return None
                # If user does not exist on the DB and not self user registration, go away
                if not user and not self.auth_user_registration:
                    return None
                # User does not exist, create one if self registration.
                elif not user and self.auth_user_registration:
                    new_user = self._search_ldap(ldap, con, username)
                    if not new_user:
                        log.warning(LOGMSG_WAR_SEC_NOLDAP_OBJ.format(username))
                        return None
                    ldap_user_info = new_user[0][1]
                    if self.auth_user_registration and user is None:
                        user = self.add_user(
                            username=username,
                            first_name=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_firstname_field,
                                username),
                            last_name=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_lastname_field,
                                username),
                            email=self.ldap_extract(
                                ldap_user_info, self.auth_ldap_email_field,
                                username + '@email.notfound'),
                            role=self.find_role(
                                self.auth_user_registration_role))

                self.update_user_auth_stat(user)
                return user

            except ldap.LDAPError as e:
                if type(e.message) == dict and 'desc' in e.message:
                    log.error(
                        LOGMSG_ERR_SEC_AUTH_LDAP.format(e.message['desc']))
                    return None
                else:
                    log.error(e)
                    return None
Example #41
0
from flask import Flask, request, Response, json
import ldap, jsonify

con = ldap.initialize('ldap://10.131.40.84:389')
ldap_base = "dc=in,dc=ril,dc=com"
app = Flask(__name__)
#sample curl
#curl -i -X GET http://10.21.74.44:5500/search?username=shubham3.kumar -H 'Content-Type: application/json'


@app.route('/rilsearch', methods=['GET'])
def create():
    if request.method == 'GET':
        try:
            con.set_option(ldap.OPT_REFERRALS, 0)
            # con.simple_bind_s("CN=Anjaneyulu.Dollaa,OU=CONSULTANT,OU=USERS,OU=CORPORATE,OU=RELIANCE HYDROCARBON,DC=in,DC=ril,DC=com","ril@1234")
            con.simple_bind_s(
                "CN=Shubham3.Kumar,OU=TRAINING,OU=USERS,OU=RCP,OU=MH_MUM,DC=in,DC=ril,DC=com",
                "Shubh1023")

            username = request.args.get('username', "")
            filter = "(&(objectClass=person)(sAMAccountName=rohan.jain))"
            attr = None
            results = con.search_s(ldap_base, ldap.SCOPE_SUBTREE, filter, attr)
            rDict = results[0][1]
            #rDictDecoded = {i:j[0].decode('utf-8') for i,j in rDict.items()}
            if len(results) != 0:
                rValue = rDict
                code = 200
            elif len(results) == 0:
                rValue = "User Not Found!"
Example #42
0
 def bind(self):
     self.conn = ldap.initialize(self.ldapServer)
     self.conn.protocal_version = self.version
     self.conn.simple_bind_s(self.ldapBind, self.ldapPass)
Example #43
0
def check(request):
    # must be superuser
    if not request.user.is_superuser:
        return nopermission(request)

    # templates
    templates_ok = True

    for html_setting in ('about', 'privacy', 'privacy_newsletter', 'login',
                         'add_user'):
        try:
            HTMLSetting.objects.get(key=html_setting)
        except HTMLSetting.DoesNotExist:
            templates_ok = False

    for text_setting in ('privacy', ):
        try:
            TextSetting.objects.get(key=text_setting)
        except TextSetting.DoesNotExist:
            templates_ok = False

    # mail
    mail_ok = True
    try:
        mail_conn = mail.get_connection()
        if isinstance(mail_conn, EmailBackend):
            mail_conn.open()
    except (ConnectionRefusedError, OSError):
        mail_ok = False

    # celery
    celery_broker_ok = True
    try:
        celery_conn = kombu.Connection(settings.CELERY_BROKER_URL)
        celery_conn.ensure_connection(max_retries=1)
    except kombu.exceptions.OperationalError:
        celery_broker_ok = False

    # ldap
    if 'django_auth_ldap.backend.LDAPBackend' in settings.AUTHENTICATION_BACKENDS:
        ldap_configured = True
        ldap_ok = True
        try:
            ldap_conn = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)
            ldap_conn.simple_bind_s(settings.AUTH_LDAP_BIND_DN,
                                    settings.AUTH_LDAP_BIND_PASSWORD)
        except ldap.LDAPError:  # noqa: E1101
            ldap_ok = False
    else:
        ldap_configured = False
        ldap_ok = False

    # headers
    for header, value in request.META.items():
        if header.startswith('HTTP_'):
            print(header + " " + value)
    header_host = request.META.get('HTTP_HOST')
    header_x_real_ip = request.META.get('HTTP_X_REAL_IP')
    header_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    header_x_forwarded_proto = request.META.get('HTTP_X_FORWARDED_PROTO')

    context = {
        'templates_ok': templates_ok,
        'mail_ok': mail_ok,
        'celery_broker_ok': celery_broker_ok,
        'ldap_configured': ldap_configured,
        'ldap_ok': ldap_ok,
        'header_host': header_host,
        'header_x_real_ip': header_x_real_ip,
        'header_x_forwarded_for': header_x_forwarded_for,
        'header_x_forwarded_proto': header_x_forwarded_proto,
    }
    return render(request, 'toolsettings/check.html', context)
Example #44
0
 def __init__(self, server='ldap://xldap.cern.ch'):
     self.server = server
     self.ldap = ldap.initialize(self.server)
Example #45
0
#!/bin/python

# Script that returns the number of interns working for ARCC.
# Depending on what is done with intern accounts when they leave ARCC,
# this script may also give the number total number of interns ever hired.
# This is done by querying ARCC's LDAP server to get the number of
# of members in the arccinterns group.

import ldap

ldap_srv = 'ldaps://arccidm1.arcc.uwyo.edu'

arcc_d = ldap.initialize(ldap_srv)

arcc_d.simple_bind_s()

base = 'dc=arcc,dc=uwyo,dc=edu'
filt = 'cn=arccinterns'
arccinterns = arcc_d.search_s(base, ldap.SCOPE_SUBTREE, filt)
arcc_d.unbind()

users = arccinterns[0][1]['memberUid']

print len(users)

Example #46
0
    def login(self, request, user_obj, **kw):
        username = kw.get('username')
        password = kw.get('password')
        _ = request.getText

        # we require non-empty password as ldap bind does a anon (not password
        # protected) bind if the password is empty and SUCCEEDS!
        if not password:
            return ContinueLogin(
                user_obj,
                _('Missing password. Please enter user name and password.'))

        try:
            try:
                u = None
                dn = None
                server = self.server_uri
                coding = self.coding
                logging.debug("Setting misc. ldap options...")
                ldap.set_option(ldap.OPT_PROTOCOL_VERSION,
                                ldap.VERSION3)  # ldap v2 is outdated
                ldap.set_option(ldap.OPT_REFERRALS, self.referrals)
                ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, self.timeout)

                if hasattr(ldap, 'TLS_AVAIL') and ldap.TLS_AVAIL:
                    for option, value in (
                        (ldap.OPT_X_TLS_CACERTDIR, self.tls_cacertdir),
                        (ldap.OPT_X_TLS_CACERTFILE, self.tls_cacertfile),
                        (ldap.OPT_X_TLS_CERTFILE, self.tls_certfile),
                        (ldap.OPT_X_TLS_KEYFILE, self.tls_keyfile),
                        (ldap.OPT_X_TLS_REQUIRE_CERT, self.tls_require_cert),
                        (ldap.OPT_X_TLS, self.start_tls),
                            #(ldap.OPT_X_TLS_ALLOW, 1),
                    ):
                        if value is not None:
                            ldap.set_option(option, value)

                logging.debug("Trying to initialize %r." % server)
                l = ldap.initialize(server)
                logging.debug("Connected to LDAP server %r." % server)

                if self.start_tls and server.startswith('ldap:'):
                    logging.debug("Trying to start TLS to %r." % server)
                    try:
                        l.start_tls_s()
                        logging.debug("Using TLS to %r." % server)
                    except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR), err:
                        logging.warning(
                            "Couldn't establish TLS to %r (err: %s)." %
                            (server, str(err)))
                        raise

                # you can use %(username)s and %(password)s here to get the stuff entered in the form:
                binddn = self.bind_dn % locals()
                bindpw = self.bind_pw % locals()
                basedn = self.base_dn % locals()
                l.simple_bind_s(binddn.encode(coding), bindpw.encode(coding))
                logging.debug("Bound with binddn %r" % binddn)

                # you can use %(username)s here to get the stuff entered in the form:
                filterstr = self.search_filter % locals()
                logging.debug("Searching %r" % filterstr)
                attrs = [
                    getattr(self, attr) for attr in [
                        'email_attribute',
                        'aliasname_attribute',
                        'surname_attribute',
                        'givenname_attribute',
                    ] if getattr(self, attr) is not None
                ]
                lusers = l.search_st(basedn,
                                     self.scope,
                                     filterstr.encode(coding),
                                     attrlist=attrs,
                                     timeout=self.timeout)
                # we remove entries with dn == None to get the real result list:
                lusers = [(dn, ldap_dict) for dn, ldap_dict in lusers
                          if dn is not None]
                for dn, ldap_dict in lusers:
                    logging.debug("dn:%r" % dn)
                    for key, val in ldap_dict.items():
                        logging.debug("    %r: %r" % (key, val))

                result_length = len(lusers)
                if result_length != 1:
                    if result_length > 1:
                        logging.warning(
                            "Search found more than one (%d) matches for %r." %
                            (result_length, filterstr))
                    if result_length == 0:
                        logging.debug("Search found no matches for %r." %
                                      (filterstr, ))
                    if self.report_invalid_credentials:
                        return ContinueLogin(
                            user_obj, _("Invalid username or password."))
                    else:
                        return ContinueLogin(user_obj)

                dn, ldap_dict = lusers[0]
                if not self.bind_once:
                    logging.debug("DN found is %r, trying to bind with pw" %
                                  dn)
                    l.simple_bind_s(dn, password.encode(coding))
                    logging.debug("Bound with dn %r (username: %r)" %
                                  (dn, username))

                if self.email_callback is None:
                    if self.email_attribute:
                        email = ldap_dict.get(self.email_attribute,
                                              [''])[0].decode(coding)
                    else:
                        email = None
                else:
                    email = self.email_callback(ldap_dict)

                aliasname = ''
                try:
                    aliasname = ldap_dict[self.aliasname_attribute][0]
                except (KeyError, IndexError):
                    pass
                if not aliasname:
                    sn = ldap_dict.get(self.surname_attribute, [''])[0]
                    gn = ldap_dict.get(self.givenname_attribute, [''])[0]
                    if sn and gn:
                        aliasname = "%s, %s" % (sn, gn)
                    elif sn:
                        aliasname = sn
                aliasname = aliasname.decode(coding)

                if self.name_callback:
                    username = self.name_callback(ldap_dict)

                if email:
                    u = user.User(request,
                                  auth_username=username,
                                  auth_method=self.name,
                                  auth_attribs=(
                                      'name',
                                      'password',
                                      'email',
                                      'mailto_author',
                                  ))
                    u.email = email
                else:
                    u = user.User(request,
                                  auth_username=username,
                                  auth_method=self.name,
                                  auth_attribs=(
                                      'name',
                                      'password',
                                      'mailto_author',
                                  ))
                u.name = username
                u.aliasname = aliasname
                u.remember_me = 0  # 0 enforces cookie_lifetime config param
                logging.debug(
                    "creating user object with name %r email %r alias %r" %
                    (username, email, aliasname))

            except ldap.INVALID_CREDENTIALS, err:
                logging.debug(
                    "invalid credentials (wrong password?) for dn %r (username: %r)"
                    % (dn, username))
                return CancelLogin(_("Invalid username or password."))
Example #47
0
def connectToLDAP(ldapSrv,ldapPort,ldapBinduser,ldapPassword):
    connect = ldap.initialize("LDAP://"+ldapSrv+":"+ldapPort)
    connect.simple_bind_s(ldapBinduser,ldapPassword)
   # print ("Соединение  - "+str(connect))
    return connect
Example #48
0
 def validate(self):
     from docassemble.webapp.daredis import r
     from flask import request, abort
     key = 'da:failedlogin:ip:' + str(get_requester_ip(request))
     failed_attempts = r.get(key)
     if failed_attempts is not None and int(failed_attempts) > daconfig['attempt limit']:
         abort(404)
     if daconfig['ldap login'].get('enable', False):
         ldap_server = daconfig['ldap login'].get('server', 'localhost').strip()
         username = self.email.data
         password = self.password.data
         connect = ldap.initialize('ldap://' + ldap_server)
         connect.set_option(ldap.OPT_REFERRALS, 0)
         try:
             connect.simple_bind_s(username, password)
             if not (connect.whoami_s() is None):
                 connect.unbind_s()
                 from flask import current_app
                 user_manager = current_app.user_manager
                 user, user_email = user_manager.find_user_by_email(self.email.data)
                 if not user:
                     from docassemble.base.generate_key import random_alphanumeric
                     from docassemble.webapp.db_object import db
                     from docassemble.webapp.users.models import UserModel, Role
                     while True:
                         new_social = 'ldap$' + random_alphanumeric(32)
                         existing_user = db.session.execute(select(UserModel).filter_by(social_id=new_social)).scalar()
                         if existing_user:
                             continue
                         break
                     user = UserModel(social_id=new_social, email=self.email.data, nickname='', active=True)
                     user_role = db.session.execute(select(Role).filter_by(name='user')).scalar_one()
                     user.roles.append(user_role)
                     db.session.add(user)
                     db.session.commit()
                 result = True
             else:
                 connect.unbind_s()
                 result = super().validate()
         except (ldap.LDAPError, ldap.INVALID_CREDENTIALS):
             connect.unbind_s()
             result = super().validate()
     else:
         from flask import current_app
         user_manager = current_app.user_manager
         user, user_email = user_manager.find_user_by_email(self.email.data)
         if user is None:
             if daconfig.get('confirm registration', False):
                 self.email.errors = list()
                 self.email.errors.append(word("Incorrect Email and/or Password"))
                 self.password.errors = list()
                 self.password.errors.append(word("Incorrect Email and/or Password"))
             else:
                 self.email.errors = list(self.email.errors)
                 self.email.errors.append(word("Account did not exist."))
             return False
         if user and (user.password is None or (user.social_id is not None and not user.social_id.startswith('local$'))):
             self.email.errors = list(self.email.errors)
             if user.social_id.startswith('google$'):
                 self.email.errors.append(word("You need to log in with Google."))
             elif user.social_id.startswith('azure$'):
                 self.email.errors.append(word("You need to log in with Azure."))
             elif user.social_id.startswith('auth0$'):
                 self.email.errors.append(word("You need to log in with Auth0."))
             elif user.social_id.startswith('twitter$'):
                 self.email.errors.append(word("You need to log in with Twitter."))
             elif user.social_id.startswith('facebook$'):
                 self.email.errors.append(word("You need to log in with Facebook."))
             else:
                 self.email.errors.append(word("You cannot log in this way."))
             return False
         #sys.stderr.write("Trying super validate\n")
         result = super().validate()
         #sys.stderr.write("Super validate response was " + repr(result) + "\n")
     if result is False:
         r.incr(key)
         r.expire(key, daconfig['ban period'])
     elif failed_attempts is not None:
         r.delete(key)
     return result
Example #49
0
def maint_ldapgroups():

    import ldap
    import ldap.modlist
    import common.logger as _logger
    import common.credentials.ldap as _ldap
    from collections import defaultdict
    _logger.log('[' + __name__ + '] refreshing ldap groups',
                _logger.LogLevel.INFO)

    # sadly ldap group memberships work this way :/

    ldap_conn = ldap.initialize(_ldap.ldap_host, bytes_mode=False)
    try:
        ldap_conn.simple_bind_s(_ldap.admin_dn, _ldap.admin_dn_password)
    except ldap.LDAPError as error:
        _logger.log(
            '[' + __name__ + '] LDAP connection error: {}'.format(error),
            _logger.LogLevel.ERROR)

    # fetch all the users

    try:
        users = ldap_conn.search_s('ou=People,dc=triumvirate,dc=rocks',
                                   ldap.SCOPE_SUBTREE,
                                   filterstr='(objectclass=pilot)',
                                   attrlist=['authGroup'])
        user_count = users.__len__()
    except ldap.LDAPError as error:
        _logger.log(
            '[' + __name__ + '] unable to fetch ldap users: {}'.format(error),
            _logger.LogLevel.ERROR)

    _logger.log('[' + __name__ + '] total ldap users: {}'.format(user_count),
                _logger.LogLevel.DEBUG)

    # form an dict of groups with each entry being
    # an array of user DNs that will populate the ldap group

    # do not update the following groups:
    skip = ['internal']

    newgroupmembers = defaultdict(list)

    for user in users:
        dn, groups = user
        groups = groups['authGroup']
        groups = list(map(lambda x: x.decode('utf-8'), groups))
        for group in groups:
            newgroupmembers[group].append(dn)

    for item in skip:
        del newgroupmembers[item]

    # now iterate through each group, and ldapmodify

    for group in newgroupmembers:
        _logger.log('[' + __name__ + '] updating group {0}'.format(group),
                    _logger.LogLevel.DEBUG)
        dn = 'cn={},ou=Groups,dc=triumvirate,dc=rocks'.format(group)
        members = list(map(lambda x: x.encode('utf-8'),
                           newgroupmembers[group]))
        # https://www.packtpub.com/books/content/python-ldap-applications-extra-ldap-operations-and-ldap-url-library
        mod_attrs = [(ldap.MOD_REPLACE, 'member', members)]
        try:
            result = ldap_conn.modify_s(dn, mod_attrs)
        except ldap.LDAPError as error:
            _logger.log(
                '[' + __name__ +
                '] unable to update group {0} memberlist: {1}'.format(
                    group, error), _logger.LogLevel.ERROR)
        _logger.log('[' + __name__ + '] group {0} updated'.format(group),
                    _logger.LogLevel.DEBUG)

    _logger.log('[' + __name__ + '] all ldap groups synchronized',
                _logger.LogLevel.DEBUG)
Example #50
0
def init_target():
    os.system(
        'ssh root@gary-testvm python /mnt/hgfs/workspaces/lotus/main/vmdir/tools/vdcmerge/test/test_config.py'
    )


#main function
init_source()
#init_target()

source_uri = 'ldap://%s:%s' % (source_host, source_port)
target_uri = 'ldap://%s:%s' % (target_host, target_port)
source_dn = 'cn=%s,cn=users,dc=%s' % (source_username, source_domain)
target_dn = 'cn=%s,cn=users,dc=%s' % (target_username, target_domain)
#initialize and log in ldap servers
s = ldap.initialize(source_uri)
s.simple_bind_s(source_dn, source_password)

t = ldap.initialize(target_uri)
t.simple_bind_s(target_dn, target_password)

dfs_clean(t, target_base)

#add test data
dfs_add(s, source_base, LAYER_NUM)
dfs_add(t, target_base, 0)

#call vdcmerge
cmdline = '%s -p %s -d %s -u %s -w %s -b %s -i %s -H %s -P %s -D %s -U %s -W %s -B %s' % (
    vdcmerge, source_port, source_domain, source_username, source_password,
    source_base, server_id, target_host, target_port, target_domain,
#!/usr/bin/env python
"""
This sample script demonstrates the use of the pre-read control (see RFC 4527).

Originally contributed by Andreas Hasenack <*****@*****.**>
"""
from __future__ import print_function

import pprint, ldap, ldap.modlist

from ldap.controls.readentry import PreReadControl, PostReadControl

uri = "ldap://localhost:2071/"

l = ldap.initialize(uri, trace_level=2)
l.simple_bind_s('uid=diradm,ou=schulung,dc=stroeder,dc=local', 'testsecret')

print(
    """#---------------------------------------------------------------------------
# Add new entry
#---------------------------------------------------------------------------
""")

new_test_dn = "uid=ablume,ou=Users,ou=schulung,dc=stroeder,dc=local"
new_test_dn2 = "uid=ablume2,ou=Users,ou=schulung,dc=stroeder,dc=local"
new_test_entry = {
    'objectClass': ['account', 'posixAccount'],
    'uid': ['ablume'],
    'cn': ['Anna Blume'],
    'uidNumber': ['10000'],
    'gidNumber': ['10000'],
Example #52
0
    def __init__(self):
        if not ldap:
            raise ImportError(_('ldap not installed'))

        self.lobj = ldap.initialize(CONF.ldap_dns_url)
        self.lobj.simple_bind_s(CONF.ldap_dns_user, CONF.ldap_dns_password)
Example #53
0
# Set debugging level
ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255)
ldapmodule_trace_level = 2
ldapmodule_trace_file = sys.stderr

lu = ldapurl.LDAPUrl(sys.argv[1])

print('Old password')
oldpw = getpass.getpass()
print('New password')
newpw = getpass.getpass()

# Set path name of file containing all CA certificates
# needed to validate server certificates
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,
                '/etc/httpd/ssl.crt/myCA-cacerts.pem')

# Create LDAPObject instance
l = ldap.initialize(lu.initializeUrl(),
                    trace_level=ldapmodule_trace_level,
                    trace_file=ldapmodule_trace_file)

l.protocol_version = ldap.VERSION3

l.simple_bind_s(lu.dn, oldpw)

l.passwd(lu.dn, oldpw, newpw)

l.unbind_s()
Example #54
0
    def process_authentication_request(self, request):
        username = request.POST['username'].strip()
        password = request.POST['password']
        uid = str(settings.LDAP_USER_MASK) % username

        #an empty password will cause ldap to try an anonymous bind. This is picked up here
        if not password:
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(str(settings.LDAP_BIND_DN),
                                str(settings.LDAP_BIND_SECRET))
            search = ldapo.search_s(str(settings.LDAP_BASE_DN),
                                    ldap.SCOPE_SUBTREE, uid)
        except ldap.LDAPError:
            #could not bind using credentials specified in ldap config
            raise InvalidAuthentication(
                _('Login failed - LDAP bind error. Please contact your system administrator'
                  ))

        ldapo.unbind_s()

        if not search:
            #could not find user
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))

        #now try to bind as selected user; should raise exception if bind fails
        ldapo = ldap.initialize(str(settings.LDAP_SERVER))
        if (settings.LDAP_USE_TLS):
            ldapo.start_tls_s()
        ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
        try:
            ldapo.simple_bind_s(uid + ',' + str(settings.LDAP_BASE_DN),
                                password)
        except ldap.LDAPError:
            #could not bind as user - password is incorrect
            raise InvalidAuthentication(
                _('Login failed. Please enter valid username and password (both are case-sensitive)'
                  ))
        ldapo.unbind_s()

        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            userinfo = search[0][1]
            usernameVal = userinfo[str(settings.LDAP_UID)][0]
            emailVal = usernameVal + '@schrodinger.com'
            if str(settings.LDAP_MAIL) in userinfo:
                emailVal = userinfo[str(settings.LDAP_MAIL)][0]
            _user = User(username=usernameVal,
                         email=emailVal,
                         real_name=userinfo[str(settings.LDAP_NAME)][0])
            _user.email_isvalid = True
            _user.set_unusable_password()
            _user.save()
            UserJoinsAction(user=_user, ip=request.META['REMOTE_ADDR']).save()
            return _user
# Purpose:  Add missing attribute/value pairs required by Dovecot-2.3.
# Date:     Apr 12, 2018.

import ldap

# Note:
#   * bind_dn must have write privilege on LDAP server.
uri = 'ldap://127.0.0.1:389'
basedn = 'o=domains,dc=example,dc=com'
bind_dn = 'cn=Manager,dc=example,dc=com'
bind_pw = 'password'

# Initialize LDAP connection.
print "* Connecting to LDAP server: %s" % uri
conn = ldap.initialize(
    uri=uri,
    trace_level=0,
)
conn.bind_s(bind_dn, bind_pw)

# Get all mail users.
print "* Get mail accounts ..."
allUsers = conn.search_s(
    basedn, ldap.SCOPE_SUBTREE,
    "(&(objectClass=mailUser)(|(enabledService=imapsecured)(enabledService=pop3secured)(enabledService=smtpsecured)))",
    ['mail', 'enabledService'])

total = len(allUsers)
print "* Updating %d user(s)." % (total)

# Counter.
count = 1
Example #56
0
 def __init__(self):
     self.ad = ldap.initialize(AD_DOMAIN)
     self.ad.protocol_version = 3
     self.ad.set_option(ldap.O, 0)
Example #57
0
if form.getvalue('get_ldap_email'):
    username = form.getvalue('get_ldap_email')
    import ldap

    server = sql.get_setting('ldap_server')
    port = sql.get_setting('ldap_port')
    user = sql.get_setting('ldap_user')
    password = sql.get_setting('ldap_password')
    ldap_base = sql.get_setting('ldap_base')
    domain = sql.get_setting('ldap_domain')
    ldap_search_field = sql.get_setting('ldap_search_field')
    ldap_class_search = sql.get_setting('ldap_class_search')
    ldap_user_attribute = sql.get_setting('ldap_user_attribute')

    l = ldap.initialize(server + ':' + port)
    try:
        l.protocol_version = ldap.VERSION3
        l.set_option(ldap.OPT_REFERRALS, 0)

        bind = l.simple_bind_s(user, password)

        criteria = "(&(objectClass=" + ldap_class_search + ")(" + ldap_user_attribute + "=" + username + "))"
        attributes = [ldap_search_field]
        result = l.search_s(ldap_base, ldap.SCOPE_SUBTREE, criteria,
                            attributes)

        results = [entry for dn, entry in result if isinstance(entry, dict)]
        try:
            print('["' + results[0][ldap_search_field][0].decode("utf-8") +
                  '","' + domain + '"]')
Example #58
0
def get_ldap_connection():
    conn = ldap.initialize(app.config['LDAP_PROVIDER_URL'])
    return conn
Example #59
0
    def _open(self):
        """
        We can only intialize a single host. In this case,
        we iterate through a list of hosts until we get one that
        works and then use that to set our LDAP handle.

        SASL GSSAPI bind only succeeds when DNS reverse lookup zone
        is correctly populated. Fall through to simple bind if this
        fails.
        """
        res = None
        if self._isopen:
            return True

        if self.hosts:
            saved_simple_error = None
            saved_gssapi_error = None
            for server in self.hosts:
                try:
                    self._handle = pyldap.initialize(server)
                except Exception as e:
                    self.logger.debug(
                        f'Failed to initialize ldap connection to [{server}]: ({e}). Moving to next server.'
                    )
                    continue

                res = None
                pyldap.protocol_version = pyldap.VERSION3
                pyldap.set_option(pyldap.OPT_REFERRALS, 0)
                pyldap.set_option(pyldap.OPT_NETWORK_TIMEOUT,
                                  self.ldap['dns_timeout'])

                if SSL(self.ldap['ssl']) != SSL.NOSSL:
                    if self.ldap['certificate']:
                        pyldap.set_option(
                            pyldap.OPT_X_TLS_CERTFILE,
                            f"/etc/certificates/{self.ldap['cert_name']}.crt")
                        pyldap.set_option(
                            pyldap.OPT_X_TLS_KEYFILE,
                            f"/etc/certificates/{self.ldap['cert_name']}.key")

                    pyldap.set_option(pyldap.OPT_X_TLS_CACERTFILE,
                                      '/etc/ssl/truenas_cacerts.pem')
                    if self.ldap['validate_certificates']:
                        pyldap.set_option(pyldap.OPT_X_TLS_REQUIRE_CERT,
                                          pyldap.OPT_X_TLS_DEMAND)
                    else:
                        pyldap.set_option(pyldap.OPT_X_TLS_REQUIRE_CERT,
                                          pyldap.OPT_X_TLS_ALLOW)

                    try:
                        pyldap.set_option(pyldap.OPT_X_TLS_NEWCTX, 0)
                    except Exception:
                        self.logger.warning(
                            'Failed to initialize new TLS context.',
                            exc_info=True)

                if SSL(self.ldap['ssl']) == SSL.USESTARTTLS:
                    try:
                        self._handle.start_tls_s()

                    except pyldap.LDAPError as e:
                        self.logger.debug(
                            'Encountered error initializing start_tls: %s', e)
                        saved_simple_error = e
                        continue

                if self.ldap['anonbind']:
                    try:
                        res = self._handle.simple_bind_s()
                        break
                    except Exception as e:
                        saved_simple_error = e
                        self.logger.debug('Anonymous bind failed: %s' % e)
                        continue

                if self.ldap['certificate']:
                    try:
                        res = self._handle.sasl_non_interactive_bind_s(
                            'EXTERNAL')
                        if self.ldap['verbose_logging']:
                            self.logger.debug(
                                'Successfully bound to [%s] using client certificate.',
                                server)
                        break
                    except Exception as e:
                        saved_simple_error = e
                        self.logger.debug('SASL EXTERNAL bind failed.',
                                          exc_info=True)
                        continue

                if self.ldap['kerberos_principal']:
                    try:
                        self._handle.set_option(pyldap.OPT_X_SASL_NOCANON, 1)
                        self._handle.sasl_gssapi_bind_s()
                        res = True
                        break
                    except Exception as e:
                        saved_gssapi_error = e
                        self.logger.debug(
                            f'SASL GSSAPI bind failed: {e}. Attempting simple bind'
                        )

                try:
                    res = self._handle.simple_bind_s(self.ldap['binddn'],
                                                     self.ldap['bindpw'])
                    break
                except Exception as e:
                    self.logger.debug(
                        f'Failed to bind to [{server}] using [{self.ldap["binddn"]}]: {e}'
                    )
                    saved_simple_error = e
                    continue

            if res:
                self._isopen = True

            elif saved_gssapi_error:
                self._convert_exception(saved_gssapi_error)

            elif saved_simple_error:
                self._convert_exception(saved_simple_error)

        return (self._isopen is True)
Example #60
0
 def _cursor(self):
     if self.connection is None:
         self.connection = ldap.initialize(self.settings_dict['NAME'])
         self.connection.simple_bind_s(self.settings_dict['USER'],
                                       self.settings_dict['PASSWORD'])
     return DatabaseCursor(self.connection)