本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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()
示例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)))
示例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)))
示例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)
示例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)