Python win32security.DACL_SECURITY_INFORMATION Examples

The following are 12 code examples of win32security.DACL_SECURITY_INFORMATION(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32security , or try the search function .
Example #1
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 6 votes vote down vote up
def check_registry():
	for key_string in reg_paths:
		parts = key_string.split("\\")
		hive = parts[0]
		key_string = "\\".join(parts[1:])
		try:
			keyh = win32api.RegOpenKeyEx(getattr(win32con, hive), key_string, 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
		except:
			#print "Can't open: " + hive + "\\" + key_string
			continue
		
		sd = win32api.RegGetKeySecurity(keyh, win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION)
		weak_perms = check_weak_write_perms_by_sd(hive + "\\" + key_string, 'reg', sd)
		if weak_perms:
			vprint(hive + "\\" + key_string)
			#print weak_perms
			if verbose == 0:
				sys.stdout.write(".")
			save_issue("WPC003", "writable_reg_paths", weak_perms)
			# print_weak_perms("x", weak_perms)
	print

# TODO save_issue("WPC009", "writable_eventlog_key", weak_perms)  # weak perms on event log reg key 
Example #2
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 6 votes vote down vote up
def check_registry():
	for key_string in reg_paths:
		parts = key_string.split("\\")
		hive = parts[0]
		key_string = "\\".join(parts[1:])
		try:
			keyh = win32api.RegOpenKeyEx(getattr(win32con, hive), key_string, 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
		except:
			#print "Can't open: " + hive + "\\" + key_string
			continue
		
		sd = win32api.RegGetKeySecurity(keyh, win32security.DACL_SECURITY_INFORMATION | win32security.OWNER_SECURITY_INFORMATION)
		weak_perms = check_weak_write_perms_by_sd(hive + "\\" + key_string, 'reg', sd)
		if weak_perms:
			vprint(hive + "\\" + key_string)
			#print weak_perms
			if verbose == 0:
				sys.stdout.write(".")
			save_issue("WPC003", "writable_reg_paths", weak_perms)
			# print_weak_perms("x", weak_perms)
	print

# TODO save_issue("WPC009", "writable_eventlog_key", weak_perms)  # weak perms on event log reg key 
Example #3
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 5 votes vote down vote up
def check_weak_perms(object_name, object_type_s, perms):
	object_type = None
	if object_type_s == 'file':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'directory':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'service':
		object_type = win32security.SE_SERVICE
	
	if object_type == win32security.SE_FILE_OBJECT:
#		if not os.path.exists(object_name):
#			print "WARNING: %s doesn't exist" % object_name
			
		if os.path.isfile(object_name):
			object_type_s = 'file'
		else:
			object_type_s = 'directory'
	
	if object_type == None:
		print "ERROR: Unknown object type %s" % object_type_s
		exit(1)
		
	try: 
		sd = win32security.GetNamedSecurityInfo (
			object_name,
			object_type,
			win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
		)
	except:
		# print "WARNING: Can't get security descriptor for " + object_name + ".  skipping.  (" + details[2] + ")"
		return []
	
	return check_weak_perms_sd(object_name, object_type_s, sd, perms) 
Example #4
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 5 votes vote down vote up
def dump_perms(object_name, object_type_s, options={}):
	object_type = None
	if object_type_s == 'file':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'directory':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'service':
		object_type = win32security.SE_SERVICE
	
	if object_type == win32security.SE_FILE_OBJECT:
#		if not os.path.exists(object_name):
#			print "WARNING: %s doesn't exist" % object_name
			
		if os.path.isfile(object_name):
			object_type_s = 'file'
		else:
			object_type_s = 'directory'
	
	if object_type == None:
		print "ERROR: Unknown object type %s" % object_type_s
		exit(1)
		
	try: 
		sd = win32security.GetNamedSecurityInfo (
			object_name,
			object_type,
			win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
		)
	except:
		# print "WARNING: Can't get security descriptor for " + object_name + ".  skipping.  (" + details[2] + ")"
		return []
	
	return dump_sd(object_name, object_type_s, sd, options) 
Example #5
Source File: file_path.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def change_acl_for_delete(path):
    """Zaps the SECURITY_DESCRIPTOR's DACL on a directory entry that is tedious
    to delete.

    This function is a heavy hammer. It discards the SECURITY_DESCRIPTOR and
    creates a new one with only one DACL set to user:FILE_ALL_ACCESS.

    Used as last resort.
    """
    STANDARD_RIGHTS_REQUIRED = 0xf0000
    SYNCHRONIZE = 0x100000
    FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff

    import win32security
    user, _domain, _type = win32security.LookupAccountName(
        '', getpass.getuser())
    sd = win32security.SECURITY_DESCRIPTOR()
    sd.Initialize()
    sd.SetSecurityDescriptorOwner(user, False)
    dacl = win32security.ACL()
    dacl.Initialize()
    dacl.AddAccessAllowedAce(
        win32security.ACL_REVISION_DS, FILE_ALL_ACCESS, user)
    sd.SetSecurityDescriptorDacl(1, dacl, 0)
    # Note that this assumes the object is either owned by the current user or
    # its group or that the current ACL permits this. Otherwise it will silently
    # fail.
    win32security.SetFileSecurity(
        fs.extend(path), win32security.DACL_SECURITY_INFORMATION, sd)
    # It's important to also look for the read only bit after, as it's possible
    # the set_read_only() call to remove the read only bit had silently failed
    # because there was no DACL for the user.
    if not (os.stat(path).st_mode & stat.S_IWUSR):
      os.chmod(path, 0o777) 
Example #6
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 5 votes vote down vote up
def check_weak_perms(object_name, object_type_s, perms):
	object_type = None
	if object_type_s == 'file':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'directory':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'service':
		object_type = win32security.SE_SERVICE
	
	if object_type == win32security.SE_FILE_OBJECT:
#		if not os.path.exists(object_name):
#			print "WARNING: %s doesn't exist" % object_name
			
		if os.path.isfile(object_name):
			object_type_s = 'file'
		else:
			object_type_s = 'directory'
	
	if object_type is None:
		print "ERROR: Unknown object type %s" % object_type_s
		exit(1)
		
	try: 
		sd = win32security.GetNamedSecurityInfo (
			object_name,
			object_type,
			win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
		)
	except:
		# print "WARNING: Can't get security descriptor for " + object_name + ".  skipping.  (" + details[2] + ")"
		return []
	
	return check_weak_perms_sd(object_name, object_type_s, sd, perms) 
Example #7
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 5 votes vote down vote up
def dump_perms(object_name, object_type_s, options={}):
	object_type = None
	if object_type_s == 'file':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'directory':
		object_type = win32security.SE_FILE_OBJECT
	if object_type_s == 'service':
		object_type = win32security.SE_SERVICE
	
	if object_type == win32security.SE_FILE_OBJECT:
#		if not os.path.exists(object_name):
#			print "WARNING: %s doesn't exist" % object_name
			
		if os.path.isfile(object_name):
			object_type_s = 'file'
		else:
			object_type_s = 'directory'
	
	if object_type is None:
		print "ERROR: Unknown object type %s" % object_type_s
		exit(1)
		
	try: 
		sd = win32security.GetNamedSecurityInfo (
			object_name,
			object_type,
			win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
		)
	except:
		# print "WARNING: Can't get security descriptor for " + object_name + ".  skipping.  (" + details[2] + ")"
		return []
	
	return dump_sd(object_name, object_type_s, sd, options) 
Example #8
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 4 votes vote down vote up
def check_weak_perms_sd(object_name, object_type_s, sd, perms):
	dacl= sd.GetSecurityDescriptorDacl()
	if dacl == None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()
	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = "INVALIDSID!"

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		#print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		#print "[D] ACE is for %s\\%s" % (principle, domain)
		#print "[D] ACE Perm mask: " + int2bin(ace[1])
		#print "[D] ace_type: " + str(ace[0][0])
		#print "[D] DACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION)
		if principle_is_trusted(principle, domain):
			#print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if principle_is_trusted(owner_name, owner_domain):
				continue
			else:
				principle = "CREATOR OWNER [%s]" % owner_fq
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		if not ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			vprint("WARNING: Unimplmented ACE type encountered: " + ace_type_s + ".  skipping.")
			continue

		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				if getattr(mod, perm) & ace[1] == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm])
	return weak_perms 
Example #9
Source File: windows-privesc-check.py    From WHP with Do What The F*ck You Want To Public License 4 votes vote down vote up
def check_event_logs():
	key_string = "HKEY_LOCAL_MACHINE\\" + eventlog_key_hklm
	try:
		keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, eventlog_key_hklm , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
	except:
		print "Can't open: " + key_string
		return 0
		
	subkeys = win32api.RegEnumKeyEx(keyh)
	for subkey in subkeys:
		# print key_string + "\\" + subkey[0]
		sys.stdout.write(".")
		try:
			subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
		except:
			print "Can't open: " + key_string
		else:
			subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh)
			# print "\tChild Nodes: %s subkeys, %s values" % (subkey_count, value_count)
			
			try:
				filename, type = win32api.RegQueryValueEx(subkeyh, "DisplayNameFile")
			except:
				pass
			else:
				weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file')
				if weak_perms:
					# print "------------------------------------------------"
					# print "Weak permissions found on event log display DLL:"
					# print_weak_perms("File", weak_perms)
					sys.stdout.write("!")
					save_issue("WPC008", "writable_eventlog_dll", weak_perms)
				
			try:
				filename, type = win32api.RegQueryValueEx(subkeyh, "File")
			except:
				pass
			else:
				weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file')
				if weak_perms:
					# print "------------------------------------------------"
					# print "Weak permissions found on event log file:"
					# print_weak_perms("File", weak_perms)
					sys.stdout.write("!")
					save_issue("WPC007", "writable_eventlog_file", weak_perms)
	print
		#sd = win32api.RegGetKeySecurity(subkeyh, win32security.DACL_SECURITY_INFORMATION) # TODO: get owner too?
		#print "\tDACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) 
Example #10
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def check_weak_perms_sd(object_name, object_type_s, sd, perms):
	dacl= sd.GetSecurityDescriptorDacl()
	if dacl is None:
		print "No Discretionary ACL"
		return []

	owner_sid = sd.GetSecurityDescriptorOwner()
	try:
		owner_name, owner_domain, type = win32security.LookupAccountSid(remote_server, owner_sid)
		owner_fq = owner_domain + "\\" + owner_name
	except:
		try:
			owner_fq = owner_name = win32security.ConvertSidToStringSid(owner_sid)
			owner_domain = ""
		except:
			owner_domain = ""
			owner_fq = owner_name = "INVALIDSID!"

	weak_perms = []
	for ace_no in range(0, dacl.GetAceCount()):
		#print "[D] ACE #%d" % ace_no
		ace = dacl.GetAce(ace_no)
		flags = ace[0][1]
		
		try:
			principle, domain, type = win32security.LookupAccountSid(remote_server, ace[2])
		except:
			principle = win32security.ConvertSidToStringSid(ace[2])
			domain = ""
		
		#print "[D] ACE is for %s\\%s" % (principle, domain)
		#print "[D] ACE Perm mask: " + int2bin(ace[1])
		#print "[D] ace_type: " + str(ace[0][0])
		#print "[D] DACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION)
		if principle_is_trusted(principle, domain):
			#print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if principle_is_trusted(owner_name, owner_domain):
				continue
			else:
				principle = "CREATOR OWNER [%s]" % owner_fq
		
		for i in ("ACCESS_ALLOWED_ACE_TYPE", "ACCESS_DENIED_ACE_TYPE", "SYSTEM_AUDIT_ACE_TYPE", "SYSTEM_ALARM_ACE_TYPE"):
			if getattr(ntsecuritycon, i) == ace[0][0]:
				ace_type_s = i
		
		if not ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			vprint("WARNING: Unimplmented ACE type encountered: " + ace_type_s + ".  skipping.")
			continue

		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				if getattr(mod, perm) & ace[1] == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm])
	return weak_perms 
Example #11
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def check_event_logs():
	key_string = "HKEY_LOCAL_MACHINE\\" + eventlog_key_hklm
	try:
		keyh = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, eventlog_key_hklm , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
	except:
		print "Can't open: " + key_string
		return 0
		
	subkeys = win32api.RegEnumKeyEx(keyh)
	for subkey in subkeys:
		# print key_string + "\\" + subkey[0]
		sys.stdout.write(".")
		try:
			subkeyh = win32api.RegOpenKeyEx(keyh, subkey[0] , 0, win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE | win32con.KEY_READ)
		except:
			print "Can't open: " + key_string
		else:
			subkey_count, value_count, mod_time = win32api.RegQueryInfoKey(subkeyh)
			# print "\tChild Nodes: %s subkeys, %s values" % (subkey_count, value_count)
			
			try:
				filename, type = win32api.RegQueryValueEx(subkeyh, "DisplayNameFile")
			except:
				pass
			else:
				weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file')
				if weak_perms:
					# print "------------------------------------------------"
					# print "Weak permissions found on event log display DLL:"
					# print_weak_perms("File", weak_perms)
					sys.stdout.write("!")
					save_issue("WPC008", "writable_eventlog_dll", weak_perms)
				
			try:
				filename, type = win32api.RegQueryValueEx(subkeyh, "File")
			except:
				pass
			else:
				weak_perms = check_weak_write_perms(os.path.expandvars(filename), 'file')
				if weak_perms:
					# print "------------------------------------------------"
					# print "Weak permissions found on event log file:"
					# print_weak_perms("File", weak_perms)
					sys.stdout.write("!")
					save_issue("WPC007", "writable_eventlog_file", weak_perms)
	print
		#sd = win32api.RegGetKeySecurity(subkeyh, win32security.DACL_SECURITY_INFORMATION) # TODO: get owner too?
		#print "\tDACL: " + win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(sd, win32security.SDDL_REVISION_1, win32security.DACL_SECURITY_INFORMATION) 
Example #12
Source File: WnfDump.py    From wnfun with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def PrintWnfRuntimeStatus(StateName, CheckSd, DumpSd, MaxSize, DumpData):
    exists = 2
    read, changeStamp, dataBuffer, bufferSize = ReadWnfData(StateName)

    write =  CheckWriteAccess(StateName)
    if write:
        # see if anyone is listening for notifications on this state name.
        exists = QueryWnfInfoClass(StateName, 'WnfInfoSubscribersPresent')
    
    internalName =  WNF_STATE_NAME_INTERNAL()
    internalName.value = StateName ^ WNF_STATE_KEY

    if not CheckInternalName(internalName):
        return False

    if internalName.b.NameLifetime == WNF_STATE_NAME_LIFETIME['WnfWellKnownStateName'].value:
        name = GetWnfName(StateName)
        if name == "":
            char3 = format(internalName.b.Unique >> 37 & 0xff, 'c')
            char4 = format(internalName.b.Unique >> 45 & 0xff, 'c')
            char3 = char3 if char3.isprintable() else " "
            char4 = char4 if char4.isprintable() else " "
            
            name ="{:c}{:c}{}{}.{:0>3} 0x{:x}".format(
                internalName.b.Unique >> 21 & 0xff,
                internalName.b.Unique >> 29 & 0xff,
                char3,
                char4,
                internalName.b.Unique & 0xFFFFF,
                StateName)
    else:
        name = "0x{:x}".format(StateName)
    print("| {:<64}| {} | {} | {} | {} | {} | {:^7} | {:^7} | {:^7} |".format(
            name,
            WnfDataScopeStrings[internalName.b.DataScope][0],
            WnfLifetimeStrings[internalName.b.NameLifetime][0],
            'Y' if internalName.b.PermanentData else 'N',
            ("RW" if write else "RO") if read else ("WO" if write else "NA"),
            'A' if exists == 1 else 'U' if exists == 2 else 'I',
            bufferSize,
            MaxSize,
            changeStamp
        ))  
    
    if DumpSd != False and CheckSd != None:
        strSd = win32security.ConvertSecurityDescriptorToStringSecurityDescriptor(
            CheckSd, win32security.SDDL_REVISION_1, 
            win32security.DACL_SECURITY_INFORMATION | 
            win32security.SACL_SECURITY_INFORMATION | 
            win32security.LABEL_SECURITY_INFORMATION)
        print("\n\t{}".format(strSd))

    if DumpData != False and read != False and bufferSize != 0:
        print("\n")
        hexdump(dataBuffer.raw[0:bufferSize])
        print("\n")

    return True