Python win32security.LookupAccountSid() Examples

The following are 20 code examples of win32security.LookupAccountSid(). 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: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def get_file_owner(self, file_path):
        """Returns the user name of the owner of the specified file.

        @param file_path: The path of the file.
        @type file_path: str

        @return: The user name of the owner.
        @rtype: str
        """
        sd = win32security.GetFileSecurity(
            file_path, win32security.OWNER_SECURITY_INFORMATION
        )
        owner_sid = sd.GetSecurityDescriptorOwner()
        name, domain, account_type = win32security.LookupAccountSid(None, owner_sid)
        if name == "Administrators":
            return self.__local_administrators
        else:
            return "%s\\%s" % (domain, name) 
Example #2
Source File: win32-identd.py    From code with MIT License 6 votes vote down vote up
def get_pid_owner(self, fd, pid):
        try:
            proc = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION, False, pid)
            token = win32security.OpenProcessToken(proc, win32con.TOKEN_QUERY)
            user_sid, user_attr = win32security.GetTokenInformation(token,
                        win32security.TokenUser)
            user = win32security.LookupAccountSid(None, user_sid)
            return user_sid, user[0], user[1]
        except win32api.error as e:
            self.logEx("error",
                "%s failed" % funcname,
                ("exception",   e),
                ("function",    e.funcname),
                ("error",       "[%(winerror)d] %(strerror)s" % e),
                None,
                ("process",     pid),)
            raise 
Example #3
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 6 votes vote down vote up
def check_user_paths():
	for user_path in get_user_paths():
		user_sid_s = user_path[0]
		try:
			user_sid  = win32security.ConvertStringSidToSid(user_sid_s)
			principle, domain, type = win32security.LookupAccountSid(remote_server, user_sid)
			user_fq = domain + "\\" + principle
		except:
			print "WARNING: Can't convert sid %s to name.  Skipping." % user_sid_s
			continue
	
		path = user_path[1]
		vprint("Checking path of %s" % user_fq)
		global tmp_trusted_principles_fq
		tmp_trusted_principles_fq = (user_fq)
		check_path(path, "WPC015")
		tmp_trusted_principles_fq = () 
Example #4
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_user_paths():
	for user_path in get_user_paths():
		user_sid_s = user_path[0]
		try:
			user_sid  = win32security.ConvertStringSidToSid(user_sid_s)
			principle, domain, type = win32security.LookupAccountSid(remote_server, user_sid)
			user_fq = domain + "\\" + principle
		except:
			print "WARNING: Can't convert sid %s to name.  Skipping." % user_sid_s
			continue
	
		path = user_path[1]
		vprint("Checking path of %s" % user_fq)
		global tmp_trusted_principles_fq
		tmp_trusted_principles_fq = (user_fq)
		check_path(path, "WPC015")
		tmp_trusted_principles_fq = () 
Example #5
Source File: _path.py    From Computable with MIT License 6 votes vote down vote up
def get_owner(self):
        r""" Return the name of the owner of this file or directory.

        This follows symbolic links.

        On Windows, this returns a name of the form ur'DOMAIN\User Name'.
        On Windows, a group can own a file or directory.
        """
        if os.name == 'nt':
            if win32security is None:
                raise Exception("path.owner requires win32all to be installed")
            desc = win32security.GetFileSecurity(
                self, win32security.OWNER_SECURITY_INFORMATION)
            sid = desc.GetSecurityDescriptorOwner()
            account, domain, typecode = win32security.LookupAccountSid(None, sid)
            return domain + u'\\' + account
        else:
            if pwd is None:
                raise NotImplementedError("path.owner is not implemented on this platform.")
            st = self.stat()
            return pwd.getpwuid(st.st_uid).pw_name 
Example #6
Source File: win32netdemo.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def LocalGroupEnum():
    "Enumerates all the local groups"
    resume = 0
    nmembers = 0
    while 1:
        data, total, resume = win32net.NetLocalGroupEnum(server, 1, resume)
        for group in data:
            verbose("Found group %(name)s:%(comment)s " % group)
            memberresume = 0
            while 1:
                memberdata, total, memberresume = win32net.NetLocalGroupGetMembers(server, group['name'], 2, resume)
                for member in memberdata:
                    # Just for the sake of it, we convert the SID to a username
                    username, domain, type = win32security.LookupAccountSid(server, member['sid'])
                    nmembers = nmembers + 1
                    verbose(" Member %s (%s)" % (username, member['domainandname']))
                if memberresume==0:
                    break
        if not resume:
            break
    assert nmembers, "Couldnt find a single member in a single group!"
    print "Enumerated all the local groups" 
Example #7
Source File: localized_names.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def LookupUserGroupFromRid(TargetComputer, Rid):
    # get the account domain Sid on the target machine
    # note: if you were looking up multiple sids based on the same
    # account domain, only need to call this once.
    umi2 = NetUserModalsGet(TargetComputer, 2)
    domain_sid = umi2['domain_id']
    
    SubAuthorityCount = domain_sid.GetSubAuthorityCount()
    
    # create and init new sid with acct domain Sid + acct Rid
    sid = pywintypes.SID()
    sid.Initialize(domain_sid.GetSidIdentifierAuthority(),
                   SubAuthorityCount+1)

    # copy existing subauthorities from account domain Sid into
    # new Sid
    for i in range(SubAuthorityCount):
        sid.SetSubAuthority(i, domain_sid.GetSubAuthority(i))

    # append Rid to new Sid
    sid.SetSubAuthority(SubAuthorityCount, Rid)

    name, domain, typ = LookupAccountSid(TargetComputer, sid)
    return name 
Example #8
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_sd(object_name, object_type_s, sd, options={}):
	perms = all_perms
	if not sd:
		return 
	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 = None

	group_sid = sd.GetSecurityDescriptorGroup()
	try:
		group_name, group_domain, type = win32security.LookupAccountSid(remote_server, group_sid)
		group_fq = group_domain + "\\" + group_name
	except:
		try:
			group_fq = group_name = win32security.ConvertSidToStringSid(group_sid)
			group_domain = ""
		except:
			group_domain = ""
			group_fq = group_name = "[none]"

	if owner_info:
		print "\tOwner: " + str(owner_fq)
		print "\tGroup: " + str(group_fq)
		
	weak_perms = []
	dump_acl(object_name, object_type_s, dacl, options)
	return 
Example #9
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_processes():
	pids = win32process.EnumProcesses()
	# TODO also check out WMI.  It might not be running, but it could help if it is:  
	#      http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f50065064173ccb
	# TODO process explorer can find quite a lot more information than this script.  This script has several problems:
	# TODO I can't open 64-bit processes for a 32-bit app.  I get this error:
	# ERROR: can't open 6100: 299 EnumProcessModules, Only part of a ReadProcessMemory
	#        or WriteProcessMemory request was completed.
	# TODO I can't seem to get the name of elevated processes (user running as me, but with admin privs)
	# TODO I can't get details of certain processes runnign as SYSTEM on xp (e.g. pid 4 "system", csrss.exe)
	# TODO should be able to find name (and threads?) for all processes.  Not necessarily path.

	for pid in sorted(pids):
		# TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx
		# TODO could we connect with PROCESS_QUERY_LIMITED_INFORMATION instead on Vista+
		try:
			ph = win32api.OpenProcess(win32con.PROCESS_VM_READ | win32con.PROCESS_QUERY_INFORMATION , False, pid)
		except:
			# print "ERROR: can't connected to PID " + str(pid)
			sys.stdout.write("?")
			continue
		else:
			user = "unknown\\unknown"
			try:
				tokenh = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY)
			except:
				pass
			else:
				sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser)
				#source = win32security.GetTokenInformation(tokenh, TokenSource)
				if sidObj:
					accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj)
					# print "pid=%d accountname=%s domainname=%s wow64=%s" % (pid, accountName, domainName, win32process.IsWow64Process(ph))
					user = domainName + "\\" + accountName

			# print "PID %d is running as %s" % (pid, user)
			sys.stdout.write(".")
			try:
				mhs = win32process.EnumProcessModules(ph)
				# print mhs
			except:
				continue
			
			mhs = list(mhs)
			exe = win32process.GetModuleFileNameEx(ph, mhs.pop(0))
			weak_perms = check_weak_write_perms(exe, 'file')
			# print_weak_perms("PID " + str(pid) + " running as " + user + ":", weak_perms)
			if weak_perms:
				save_issue("WPC016", "weak_perms_exes", weak_perms)
				sys.stdout.write("!")
				
			for mh in mhs:
				# print "PID %d (%s) has loaded module: %s" % (pid, exe, win32process.GetModuleFileNameEx(ph, mh))
				dll = win32process.GetModuleFileNameEx(ph, mh)
				weak_perms = check_weak_write_perms(dll, 'file')
				# print_weak_perms("DLL used by PID " + str(pid) + " running as " + user + " (" + exe + "):", weak_perms)
				if weak_perms:
					save_issue("WPC016", "weak_perms_dlls", weak_perms)
					sys.stdout.write("!")
	print 
Example #10
Source File: localized_names.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def LookupAliasFromRid(TargetComputer, Rid):
    # Sid is the same regardless of machine, since the well-known
    # BUILTIN domain is referenced.
    sid = pywintypes.SID()
    sid.Initialize(SECURITY_NT_AUTHORITY, 2)

    for i, r in enumerate((SECURITY_BUILTIN_DOMAIN_RID, Rid)):
        sid.SetSubAuthority(i, r)

    name, domain, typ = LookupAccountSid(TargetComputer, sid)
    return name 
Example #11
Source File: path.py    From click-configfile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __get_owner_windows(self):
        """
        Return the name of the owner of this file or directory. Follow
        symbolic links.

        Return a name of the form ``r'DOMAIN\\User Name'``; may be a group.

        .. seealso:: :attr:`owner`
        """
        desc = win32security.GetFileSecurity(
            self, win32security.OWNER_SECURITY_INFORMATION)
        sid = desc.GetSecurityDescriptorOwner()
        account, domain, typecode = win32security.LookupAccountSid(None, sid)
        return domain + '\\' + account 
Example #12
Source File: utils.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def sid2username(sid):
    """Convert an object sid to a string account name"""
    account = win32security.LookupAccountSid(None, sid)
    return account[0] 
Example #13
Source File: utils.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def check_permissions(path, logger):
    logger.info("I am", win32api.GetUserNameEx(win32con.NameSamCompatible))
    logger.info(path)
    sd = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION)
    owner_sid = sd.GetSecurityDescriptorOwner()
    name, domain, _ = win32security.LookupAccountSid(None, owner_sid)
    logger.info("File owned by %s\\%s" % (domain, name)) 
Example #14
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 5 votes vote down vote up
def dump_sd(object_name, object_type_s, sd, options={}):
	perms = all_perms
	if not sd:
		return 
	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 = None

	group_sid = sd.GetSecurityDescriptorGroup()
	try:
		group_name, group_domain, type = win32security.LookupAccountSid(remote_server, group_sid)
		group_fq = group_domain + "\\" + group_name
	except:
		try:
			group_fq = group_name = win32security.ConvertSidToStringSid(group_sid)
			group_domain = ""
		except:
			group_domain = ""
			group_fq = group_name = "[none]"

	if owner_info:
		print "\tOwner: " + str(owner_fq)
		print "\tGroup: " + str(group_fq)
		
	weak_perms = []
	dump_acl(object_name, object_type_s, dacl, options)
	return 
Example #15
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 #16
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 dump_acl(object_name, object_type_s, sd, options={}):
	dacl = sd
	if dacl == None:
		print "No Discretionary ACL"
		return []

	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 = ""
		
		mask = ace[1]
		if ace[1] < 0:
			mask = ace[1] + 2**32

		if ignore_trusted and principle_is_trusted(principle, domain):
			# print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if ignore_trusted and principle_is_trusted(owner_name, owner_domain):
				#print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain)
				continue
			else:
				principle = "CREATOR OWNER [%s\%s]" % (domain, principle)
		
		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
		
		ace_type_short = ace_type_s
		
		if ace_type_s == "ACCESS_DENIED_ACE_TYPE":
			ace_type_short = "DENY"
		
		if ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			ace_type_short = "ALLOW"

		if weak_perms_only:
			perms = dangerous_perms_write
		else:
			perms = all_perms
			
		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				#print "Checking for perm %s in ACE %s" % (perm, mask)
				if getattr(mod, perm) & mask == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm, ace_type_short])
	print_weak_perms(object_type_s, weak_perms, options) 
Example #17
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 #18
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def dump_acl(object_name, object_type_s, sd, options={}):
	dacl = sd
	if dacl is None:
		print "No Discretionary ACL"
		return []

	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 = ""
		
		mask = ace[1]
		if ace[1] < 0:
			mask = ace[1] + 2**32

		if ignore_trusted and principle_is_trusted(principle, domain):
			# print "[D] Ignoring trusted principle %s\\%s" % (principle, domain)
			continue
		
		if principle == "CREATOR OWNER":
			if ignore_trusted and principle_is_trusted(owner_name, owner_domain):
				#print "[D] Ignoring trusted principle (creator owner) %s\\%s" % (principle, domain)
				continue
			else:
				principle = "CREATOR OWNER [%s\%s]" % (domain, principle)
		
		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
		
		ace_type_short = ace_type_s
		
		if ace_type_s == "ACCESS_DENIED_ACE_TYPE":
			ace_type_short = "DENY"
		
		if ace_type_s == "ACCESS_ALLOWED_ACE_TYPE":
			ace_type_short = "ALLOW"

		if weak_perms_only:
			perms = dangerous_perms_write
		else:
			perms = all_perms
			
		for mod, perms_tuple in perms[object_type_s].iteritems():
			for perm in perms_tuple:
				#print "Checking for perm %s in ACE %s" % (perm, mask)
				if getattr(mod, perm) & mask == getattr(mod, perm):
					weak_perms.append([object_name, domain, principle, perm, ace_type_short])
	print_weak_perms(object_type_s, weak_perms, options) 
Example #19
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 4 votes vote down vote up
def check_processes():
	pids = win32process.EnumProcesses()
	# TODO also check out WMI.  It might not be running, but it could help if it is:  
	#      http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f50065064173ccb
	# TODO process explorer can find quite a lot more information than this script.  This script has several problems:
	# TODO I can't open 64-bit processes for a 32-bit app.  I get this error:
	# ERROR: can't open 6100: 299 EnumProcessModules, Only part of a ReadProcessMemory
	#        or WriteProcessMemory request was completed.
	# TODO I can't seem to get the name of elevated processes (user running as me, but with admin privs)
	# TODO I can't get details of certain processes runnign as SYSTEM on xp (e.g. pid 4 "system", csrss.exe)
	# TODO should be able to find name (and threads?) for all processes.  Not necessarily path.

	for pid in sorted(pids):
		# TODO there's a security descriptor for each process accessible via GetSecurityInfo according to http://msdn.microsoft.com/en-us/library/ms684880%28VS.85%29.aspx
		# TODO could we connect with PROCESS_QUERY_LIMITED_INFORMATION instead on Vista+
		try:
			ph = win32api.OpenProcess(win32con.PROCESS_VM_READ | win32con.PROCESS_QUERY_INFORMATION , False, pid)
		except:
			# print "ERROR: can't connected to PID " + str(pid)
			sys.stdout.write("?")
			continue
		else:
			user = "unknown\\unknown"
			try:
				tokenh = win32security.OpenProcessToken(ph, win32con.TOKEN_QUERY)
			except:
				pass
			else:
				sidObj, intVal = win32security.GetTokenInformation(tokenh, TokenUser)
				#source = win32security.GetTokenInformation(tokenh, TokenSource)
				if sidObj:
					accountName, domainName, accountTypeInt = win32security.LookupAccountSid(remote_server, sidObj)
					# print "pid=%d accountname=%s domainname=%s wow64=%s" % (pid, accountName, domainName, win32process.IsWow64Process(ph))
					user = domainName + "\\" + accountName

			# print "PID %d is running as %s" % (pid, user)
			sys.stdout.write(".")
			try:
				mhs = win32process.EnumProcessModules(ph)
				# print mhs
			except:
				continue
			
			mhs = list(mhs)
			exe = win32process.GetModuleFileNameEx(ph, mhs.pop(0))
			weak_perms = check_weak_write_perms(exe, 'file')
			# print_weak_perms("PID " + str(pid) + " running as " + user + ":", weak_perms)
			if weak_perms:
				save_issue("WPC016", "weak_perms_exes", weak_perms)
				sys.stdout.write("!")
				
			for mh in mhs:
				# print "PID %d (%s) has loaded module: %s" % (pid, exe, win32process.GetModuleFileNameEx(ph, mh))
				dll = win32process.GetModuleFileNameEx(ph, mh)
				weak_perms = check_weak_write_perms(dll, 'file')
				# print_weak_perms("DLL used by PID " + str(pid) + " running as " + user + " (" + exe + "):", weak_perms)
				if weak_perms:
					save_issue("WPC016", "weak_perms_dlls", weak_perms)
					sys.stdout.write("!")
	print 
Example #20
Source File: GetTokenInformation.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def dump_token(th):
    token_type=win32security.GetTokenInformation(th, win32security.TokenType)
    print 'TokenType:', token_type, TOKEN_TYPE.lookup_name(token_type)
    if token_type==win32security.TokenImpersonation:
        imp_lvl=win32security.GetTokenInformation(th, win32security.TokenImpersonationLevel)
        print 'TokenImpersonationLevel:', imp_lvl, SECURITY_IMPERSONATION_LEVEL.lookup_name(imp_lvl)

    print 'TokenSessionId:', win32security.GetTokenInformation(th, win32security.TokenSessionId)

    privs=win32security.GetTokenInformation(th,win32security.TokenPrivileges)
    print 'TokenPrivileges:'
    for priv_luid, priv_flags in privs:
        flag_names, unk=TOKEN_PRIVILEGE_ATTRIBUTES.lookup_flags(priv_flags)
        flag_desc = ' '.join(flag_names)
        if (unk):
            flag_desc += '(' + str(unk) + ')'

        priv_name=win32security.LookupPrivilegeName('',priv_luid)
        priv_desc=win32security.LookupPrivilegeDisplayName('',priv_name)
        print '\t', priv_name, priv_desc, priv_flags, flag_desc

    print 'TokenGroups:'
    groups=win32security.GetTokenInformation(th,win32security.TokenGroups)
    for group_sid, group_attr in groups:
        flag_names, unk=TOKEN_GROUP_ATTRIBUTES.lookup_flags(group_attr)
        flag_desc = ' '.join(flag_names)
        if (unk):
            flag_desc += '(' + str(unk) + ')'
        if group_attr & TOKEN_GROUP_ATTRIBUTES.SE_GROUP_LOGON_ID:
            sid_desc = 'Logon sid'
        else:
            sid_desc=win32security.LookupAccountSid('',group_sid)
        print '\t',group_sid, sid_desc, group_attr, flag_desc

    ## Vista token information types, will throw (87, 'GetTokenInformation', 'The parameter is incorrect.') on earier OS
    try:
        is_elevated=win32security.GetTokenInformation(th, win32security.TokenElevation)
        print 'TokenElevation:', is_elevated
    except pywintypes.error, details:
        if details.winerror != winerror.ERROR_INVALID_PARAMETER:
            raise
        return None