How to use the ldap3.utils.dn.safe_dn function in ldap3

To help you get started, we’ve selected a few ldap3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cannatag / ldap3 / ldap3 / extend / standard / PersistentSearch.py View on Github external
dereference_aliases,
                 attributes,
                 size_limit,
                 time_limit,
                 controls,
                 changes_only,
                 events_type,
                 notifications,
                 streaming,
                 callback
                 ):
        if connection.strategy.sync:
            raise LDAPExtensionError('Persistent Search needs an asynchronous streaming connection')

        if connection.check_names and search_base:
            search_base = safe_dn(search_base)

        self.connection = connection
        self.changes_only = changes_only
        self.notifications = notifications
        self.message_id = None
        self.base = search_base
        self.filter = search_filter
        self.scope = search_scope
        self.dereference_aliases = dereference_aliases
        self.attributes = attributes
        self.size_limit = size_limit
        self.time_limit = time_limit
        self.connection.strategy.streaming = streaming
        if callback and callable(callback):
            self.connection.strategy.callback = callback
        elif callback:
github rroemhild / flask-ldapconn / flask_ldapconn / entry.py View on Github external
def generate_dn_from_entry(self):
        rdn_list = list()
        for key, attr in self._attributes.items():
            if attr.name in self.entry_rdn:
                if len(self._attributes[key]) == 1:
                    rdn = '{attr}={value}'.format(
                        attr=attr.name,
                        value=self._attributes[key].value
                    )
                    rdn_list.append(rdn)
        dn = '{rdn},{base_dn}'.format(rdn='+'.join(rdn_list),
                                      base_dn=self.base_dn)
        self._dn = safe_dn(dn)
github cannatag / ldap3 / ldap3 / strategy / mockBase.py View on Github external
def add_entry(self, dn, attributes, validate=True):
        with self.connection.server.dit_lock:
            escaped_dn = safe_dn(dn)
            if escaped_dn not in self.connection.server.dit:
                new_entry = CaseInsensitiveDict()
                for attribute in attributes:
                    if attribute in self.operational_attributes:  # no restore of operational attributes, should be computed at runtime
                        continue
                    if not isinstance(attributes[attribute], SEQUENCE_TYPES):  # entry attributes are always lists of bytes values
                        attributes[attribute] = [attributes[attribute]]
                    if self.connection.server.schema and self.connection.server.schema.attribute_types[attribute].single_value and len(attributes[attribute]) > 1:  # multiple values in single-valued attribute
                        return False
                    if attribute.lower() == 'objectclass' and self.connection.server.schema:  # builds the objectClass hierarchy only if schema is present
                        class_set = set()
                        for object_class in attributes['objectClass']:
                            if self.connection.server.schema.object_classes and object_class not in self.connection.server.schema.object_classes:
                                return False
                            # walkups the class hierarchy and buils a set of all classes in it
                            class_set.add(object_class)
github cannatag / ldap3 / ldap3 / strategy / mockBase.py View on Github external
new_rdn = request['newRdn']
        delete_old_rdn = request['deleteOldRdn']
        new_superior = safe_dn(request['newSuperior']) if request['newSuperior'] else ''
        dn_components = to_dn(dn)
        if dn in self.connection.server.dit:
            if new_superior and new_rdn:  # performs move in the DIT
                new_dn = safe_dn(dn_components[0] + ',' + new_superior)
                self.connection.server.dit[new_dn] = self.connection.server.dit[dn].copy()
                moved_entry = self.connection.server.dit[new_dn]
                if delete_old_rdn:
                    del self.connection.server.dit[dn]
                result_code = RESULT_SUCCESS
                message = 'entry moved'
                moved_entry['entryDN'] = [to_raw(new_dn)]
            elif new_rdn and not new_superior:  # performs rename
                new_dn = safe_dn(new_rdn + ',' + safe_dn(dn_components[1:]))
                self.connection.server.dit[new_dn] = self.connection.server.dit[dn].copy()
                renamed_entry = self.connection.server.dit[new_dn]
                del self.connection.server.dit[dn]
                renamed_entry['entryDN'] = [to_raw(new_dn)]

                for rdn in safe_rdn(new_dn, decompose=True):  # adds rdns to entry attributes
                    renamed_entry[rdn[0]] = [to_raw(rdn[1])]

                result_code = RESULT_SUCCESS
                message = 'entry rdn renamed'
            else:
                result_code = RESULT_UNWILLING_TO_PERFORM
                message = 'newRdn or newSuperior missing'
        else:
            result_code = RESULT_NO_SUCH_OBJECT
            message = 'object not found'
github cannatag / ldap3 / ldap3 / strategy / MockBase.py View on Github external
#         operation       ENUMERATED {
        #             add     (0),
        #             delete  (1),
        #             replace (2),
        #             ...  },
        #         modification    PartialAttribute } }
        #
        # ModifyResponse ::= [APPLICATION 7] LDAPResult
        #
        # request: entry, changes
        # response: LDAPResult
        #
        # changes is a dictionary in the form {'attribute': [(operation, [val1, ...]), ...], ...}
        # operation is 0 (add), 1 (delete), 2 (replace), 3 (increment)
        request = modify_request_to_dict(request_message)
        dn = safe_dn(request['entry'])
        changes = request['changes']
        result_code = 0
        message = ''
        rdns = [rdn[0] for rdn in safe_rdn(dn, decompose=True)]
        if dn in self.entries:
            original_entry = self.entries[dn].copy()  # to preserve atomicity of operation
            for modification in changes:
                operation = modification['operation']
                attribute = modification['attribute']['type']
                elements = modification['attribute']['value']
                if operation == 0:  # add
                    if attribute not in self.entries[dn] and elements:  # attribute not present, creates the new attribute and add elements
                        self.entries[dn][attribute] = elements
                    else:  # attribute present, adds elements to current values
                        self.entries[dn][attribute].extend(elements)
                elif operation == 1:  # delete
github cannatag / ldap3 / ldap3 / abstract / entry.py View on Github external
self.__dict__.clear()
                self._state = EntryState(dn, cursor)
                self._state.set_status(STATUS_DELETED)
                return True
            return False
        elif self.entry_status == STATUS_READY_FOR_MOVING:
            result = self.entry_cursor.connection.modify_dn(self.entry_dn, '+'.join(safe_rdn(self.entry_dn)), new_superior=self._state._to)
            if not self.entry_cursor.connection.strategy.sync:
                response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
            else:
                response = self.entry_cursor.connection.response
                result = self.entry_cursor.connection.result
                request = self.entry_cursor.connection.request
            self.entry_cursor._store_operation_in_history(request, result, response)
            if result['result'] == RESULT_SUCCESS:
                self._state.dn = safe_dn('+'.join(safe_rdn(self.entry_dn)) + ',' + self._state._to)
                if refresh:
                    if self.entry_refresh():
                        if self._state.origin and self.entry_cursor.connection.server == self._state.origin.entry_cursor.connection.server:  # refresh dn of origin
                            self._state.origin._state.dn = self.entry_dn
                self._state.set_status(STATUS_COMMITTED)
                self._state._to = None
                return True
            return False
        elif self.entry_status == STATUS_READY_FOR_RENAMING:
            rdn = '+'.join(safe_rdn(self._state._to))
            result = self.entry_cursor.connection.modify_dn(self.entry_dn, rdn)
            if not self.entry_cursor.connection.strategy.sync:
                response, result, request = self.entry_cursor.connection.get_response(result, get_request=True)
            else:
                response = self.entry_cursor.connection.response
                result = self.entry_cursor.connection.result
github cannatag / ldap3 / ldap3 / extend / novell / removeMembersFromGroups.py View on Github external
Raises LDAPInvalidDnError if members or groups are not found in the DIT.

    """
    if not isinstance(members_dn, SEQUENCE_TYPES):
        members_dn = [members_dn]

    if not isinstance(groups_dn, SEQUENCE_TYPES):
        groups_dn = [groups_dn]

    if connection.check_names:  # builds new lists with sanitized dn
        safe_members_dn = []
        safe_groups_dn = []
        for member_dn in members_dn:
            safe_members_dn.append(safe_dn(member_dn))
        for group_dn in groups_dn:
            safe_groups_dn.append(safe_dn(group_dn))

        members_dn = safe_members_dn
        groups_dn = safe_groups_dn

    transaction_control = None
    error = False

    if transaction:
        transaction_control = connection.extend.novell.start_transaction()

    if not error:
        for member in members_dn:
            if fix:  # checks for existance of member and for already assigned groups
                result = connection.search(member, '(objectclass=*)', BASE, dereference_aliases=DEREF_NEVER, attributes=['securityEquals', 'groupMembership'])

                if not connection.strategy.sync:
github agdsn / pycroft / ldap_sync / record.py View on Github external
def dn_from_cn(name, base):
    return safe_dn(["cn={}".format(name), base])
github cannatag / ldap3 / ldap3 / extend / standard / modifyPassword.py View on Github external
def __init__(self, connection, user=None, old_password=None, new_password=None, hash_algorithm=None, salt=None, controls=None):
        ExtendedOperation.__init__(self, connection, controls)  # calls super __init__()
        if user:
            if connection.check_names:
                user = safe_dn(user)
            self.request_value['userIdentity'] = user
        if old_password:
            if not isinstance(old_password, bytes):  # bytes are returned raw, as per RFC (4.2)
                old_password = validate_simple_password(old_password, True)
            self.request_value['oldPasswd'] = old_password
        if new_password:
            if not isinstance(new_password, bytes):  # bytes are returned raw, as per RFC (4.2)
                new_password = validate_simple_password(new_password, True)
            if hash_algorithm is None or hash_algorithm == HASHED_NONE:
                self.request_value['newPasswd'] = new_password
            else:
                self.request_value['newPasswd'] = hashed(hash_algorithm, new_password, salt)
github cannatag / ldap3 / ldap3 / extend / microsoft / unlockAccount.py View on Github external
def ad_unlock_account(connection, user_dn, controls=None):
    if connection.check_names:
        user_dn = safe_dn(user_dn)
    result = connection.modify(user_dn,
                               {'lockoutTime': [(MODIFY_REPLACE, ['0'])]},
                               controls)

    if not connection.strategy.sync:
        _, result = connection.get_response(result)
    else:
        result = connection.result

    # change successful, returns True
    if result['result'] == RESULT_SUCCESS:
        return True

    # change was not successful, raises exception if raise_exception = True in connection or returns the operation result, error code is in result['result']
    if connection.raise_exceptions:
        from ...core.exceptions import LDAPOperationResult