Example #1
0
    def _load_user_attrs(self):
        if self.dn is not None:
            search = LDAPSearch(self.dn, ldap.SCOPE_BASE)
            results = search.execute(self.connection)

            if results is not None and len(results) > 0:
                self._user_attrs = results[0][1]
Example #2
0
    def _load_user_attrs(self):
        if self.dn is not None:
            search = LDAPSearch(self.dn, ldap.SCOPE_BASE, attrlist=self.settings.USER_ATTRLIST)
            results = search.execute(self.connection)

            if results is not None and len(results) > 0:
                self._user_attrs = results[0][1]
Example #3
0
    def _load_user_attrs(self):
        if self.dn is not None:
            search = LDAPSearch(self.dn, self.ldap.SCOPE_BASE)
            results = search.execute(self.connection)

            if results is not None and len(results) > 0:
                self._user_attrs = results[0][1]
Example #4
0
    def _load_user_attrs(self):
        if self.dn is not None:
            search = LDAPSearch(self.dn, ldap.SCOPE_BASE, attrlist=self.settings.USER_ATTRLIST)
            results = search.execute(self.connection)

            if results is not None and len(results) > 0:
                self._user_attrs = results[0][1]
Example #5
0
def update_user_foreign_keys(sender,
                             instance=None,
                             created=False,
                             user=None,
                             ldap_user=None,
                             **kwargs):
    backend = panopticum.ldap.PanopticumLDAPBackend()
    for model_field_name, val in backend.settings.FOREIGNKEY_USER_ATTR_MAP.items(
    ):
        model_search_field = "name"
        create = True

        # handle custom settings like:
        #"manager": {
        #   "searchField": "dn",
        #   "ldapFieldName": "manager",
        #   "create": False, # doesn't create object if it not exist
        #}
        if isinstance(val, dict):
            ldap_field_name = val['ldapFieldName']
            model_search_field = val.get("searchField", model_search_field)
            create = val.get("create", create)
        else:
            ldap_field_name = val

        if ldap_field_name not in ldap_user.attrs.data:
            continue
        ldap_value = ldap_user.attrs.data[ldap_field_name][0]
        if not ldap_value:
            continue
        # get model from models.Field object
        field_model = getattr(backend.get_user_model(),
                              model_field_name).field.related_model
        if not field_model:
            continue

        if create:
            if issubclass(field_model, backend.get_user_model()) \
                    and not backend.get_user_model().objects.filter(**{model_search_field:ldap_value}).exists():
                # make raw request to LDAP for getting raw LDAP attrs
                search = LDAPSearch(ldap_value, ldap.SCOPE_BASE)
                related_ldap_attrs = search.execute(
                    ldap_user._get_connection())[0][1]
                field_model_instance, _ = backend.update_user(
                    related_ldap_attrs)
            else:
                # Example: models.User.get_or_create('dn=...')
                field_model_instance = field_model.objects.get_or_create(
                    **{model_search_field: ldap_value})[0]
        else:
            try:
                field_model_instance = field_model.objects.get(
                    **{model_search_field: ldap_value})
            except ObjectDoesNotExist:
                continue

        # Example: loggedin_user.manager = models.User(dn="cn=John.Doe,ou=users,dn=example,dn=com")
        setattr(user, model_field_name, field_model_instance)
Example #6
0
    def handle(self, *args, **options):

        os_environ_dict = dict(os.environ)
        environ = settings_backend.get_settings_environ(os_environ_dict)

        ldap_enabled = environ.get('LS2_LDAP_ENABLED', False)
        if ldap_enabled == False:
            raise CommandError("LDAP is not enabled")

        server_uri = environ.get('LS2_LDAP_SERVER_URI')
        if server_uri == None:
            raise CommandError("LDAP server URI info missing")

        self.stdout.write(
            self.style.SUCCESS(f'Attempting to connect to {server_uri}'))

        ##ignore cert errors for now
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

        ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)

        l = ldap.initialize(server_uri, trace_level=0)
        self.stdout.write(self.style.SUCCESS(f'Server initialization success'))

        bind_dn = environ.get('LS2_LDAP_BIND_DN')
        bind_password = environ.get('LS2_LDAP_BIND_PASSWORD')
        if bind_dn == None or bind_password == None:
            raise CommandError("LDAP bind user info missing")

        self.stdout.write(
            self.style.SUCCESS(f'Attempting to bind with DN {bind_dn}'))
        r = l.simple_bind_s(bind_dn, bind_password)
        self.stdout.write(self.style.SUCCESS(f'Bind Successful'))

        ldap_search_base_dn = environ.get('LS2_LDAP_SEARCH_BASE_DN')
        ldap_search_scope = ldap.SCOPE_SUBTREE
        ldap_search_filter_template = environ.get('LS2_LDAP_SEARCH_FILTER')

        user = options['username']
        password = getpass.getpass()

        self.stdout.write(
            f'Attempting to search for {user} in \"{ldap_search_base_dn}\"')
        self.stdout.write(f'Filter {filter}')

        ldap_search = LDAPSearch(ldap_search_base_dn, ldap.SCOPE_SUBTREE,
                                 ldap_search_filter_template)

        results = ldap_search.execute(l, {'user': user})
        if results is not None and len(results) == 1:
            pass
        else:
            raise CommandError("NOT FOUND")

        user_dn = results[0][0]
        l.simple_bind_s(user_dn, password)
        self.stdout.write('Test Successful')
Example #7
0
def fetch_users():
    """ Copy some behavior from django-auth-ldap login. Unfortunately django-auth-ldap library allow
     populate users only by username. But user LDAP structure can contain user foreign key with different
     value, for example DN instead username. For example LDAP attrs:
     {
        "cn=John.Doe,ou=users,dn=example,dn=com",
        "company": "Some company",
        "manager": "cn=big.boss,ou=users,dn=example,dn=com",
        ...
     }
     At this example will be all ok if "manager" = "big.boss". Also "CN" ca be different with "username".
     For resolving "manager" field we should make request to LDAP by CN, get LDAP attrs, and create
     manager django user from LDAP attrs.
     """
    updated = 0
    added = 0
    backend = PanopticumLDAPBackend()

    if backend.settings.REQUIRE_GROUP:
        filterstr = f'(&(objectClass=USER)(memberOf={backend.settings.REQUIRE_GROUP}))'
    else:
        filterstr = f'(objectClass=USER)'

    search = LDAPSearch(backend.settings.USER_SEARCH.base_dn,
                        backend.settings.USER_SEARCH.scope, filterstr)

    # define connection to LDAP
    connection = backend.ldap.initialize(backend.settings.SERVER_URI,
                                         bytes_mode=False)
    if backend.settings.BIND_DN:
        connection.simple_bind_s(backend.settings.BIND_DN,
                                 backend.settings.BIND_PASSWORD)
    for opt, value in backend.settings.CONNECTION_OPTIONS.items():
        connection.set_option(opt, value)

    if backend.settings.START_TLS:
        logger.debug("Initiating TLS")
        connection.start_tls_s()

    ldap_attrs = search.execute(connection)
    logger.info(f'Found {len(ldap_attrs)} entries')
    for ldap_attr in ldap_attrs:
        logger.debug(
            f"process {ldap_attr[1].data[backend.settings.USER_SEARCH_FIELD.lower()]}"
        )
        user, built = backend.update_user(ldap_attr[1])
        if built:
            added += 1
            logger.info(f'Add {user.username}')
        else:
            updated += 1
            logger.info(f'Update {user.username}')

    logger.info(f'added {added} users')
    logger.info(f'updated {updated} users')
Example #8
0
 def import_all_users(self):
     ldap_backend = LDAPBackend()
     ldap_user = _LDAPUser(ldap_backend, username="")
     ldap_search = LDAPSearch(self.search_dn,
                              ldap.SCOPE_SUBTREE,
                              filterstr=self.filter,
                              attrlist=[self.username_attribute])
     results = ldap_search.execute(connection=ldap_user.connection)
     for result in results:
         if self.simple_search:
             search_term = result[1][self.username_attribute][0]
         else:
             search_term = result[0].split(',')[0].split('=')[1]
         ldap_backend.populate_user(search_term)
Example #9
0
    def handle(self, *args, **options):
        ldap_backend = LDAPBackend()
        dummy_user = _LDAPUser(ldap_backend, username="******")
        user_search = LDAPSearch(settings.AUTH_LDAP_USER_DN,
                                 ldap.SCOPE_SUBTREE, "(uid=*)")

        user_data = user_search.execute(dummy_user.connection)
        list_of_current_ldap_users = self.process_user_list(user_data)

        known_users = self.filter_django_users(User.objects.all())
        num_deleted_users = 0
        num_imported_users = 0

        for user in known_users:
            if user.username in list_of_current_ldap_users:
                index = list_of_current_ldap_users.index(user.username)
                list_of_current_ldap_users.pop(index)
            else:
                if not user.is_superuser:
                    user.delete()
                    num_deleted_users += 1

        # if there are any usernames left, we need to add new users to the database
        for username in list_of_current_ldap_users:
            django_user = ldap_backend.populate_user(username)
            if django_user is None:
                self.stderr.write(
                    self.style.ERROR(
                        f"Could not create user with username {username}"))
                continue

            ldap_backend.update_mail_addresses(django_user)
            ldap_backend.set_groups_of_user(django_user)

            num_imported_users += 1

        self.stdout.write(self.style.SUCCESS("Import Complete"))
        self.stdout.write(
            self.style.SUCCESS(
                f"Imported {num_imported_users} users into the database."))
        self.stdout.write(
            self.style.SUCCESS(
                f"Deleted {num_deleted_users} users from the database."))
 def _load_user_attrs(self):
     search = LDAPSearch(self.dn, self.ldap.SCOPE_BASE)
     results = search.execute(self.connection)
     
     self._user_attrs = results[0][1]
Example #11
0
def main():

    os_environ_dict = dict(os.environ)
    environ = settings_backend.get_settings_environ(os_environ_dict)

    ldap_enabled = environ.get('LS2_LDAP_ENABLED', False)
    if ldap_enabled == False:
        sys.exit("LDAP is not enabled")

    server_uri = environ.get('LS2_LDAP_SERVER_URI')
    print(f'Attempting to connect to {server_uri}')

    ##ignore cert errors for now
    ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)

    ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)

    l = ldap.initialize(server_uri, trace_level=0)
    print(l)
    print(f'Server initialization success')

    bind_dn = environ.get('LS2_LDAP_BIND_DN')
    bind_password = environ.get('LS2_LDAP_BIND_PASSWORD')
    if bind_dn == None or bind_password == None:
        sys.exit("LDAP bind user info missing")

    print(f'Attempting to bind with DN {bind_dn}')
    r = l.simple_bind_s(bind_dn, bind_password)

    print(f'Bind Successful')
    ldap_search_base_dn = environ.get('LS2_LDAP_SEARCH_BASE_DN')
    ldap_search_scope = ldap.SCOPE_SUBTREE
    ldap_search_filter_template = environ.get('LS2_LDAP_SEARCH_FILTER')

    user = input("Enter a username: "******"{ldap_search_base_dn}\"')

    # filter = ldap_search_filter_template % {'user': user}
    print(f'Filter {filter}')
    # result = l.search_s(ldap_search_base_dn,ldap_search_scope,filter)[0]
    # print(result[0])
    # user_dn = result[0]

    # r = l.simple_bind_s(user_dn, password)
    # print('Test Successful')

    ldap_search = LDAPSearch(ldap_search_base_dn, ldap.SCOPE_SUBTREE,
                             ldap_search_filter_template)

    print(ldap_search)
    results = ldap_search.execute(l, {'user': user})
    if results is not None and len(results) == 1:
        # print(results[0])
        pass
    else:
        print("NOT FOUND")

    user_dn = results[0][0]
    l.simple_bind_s(user_dn, password)
    print('Test Successful')