Python win32security.OpenProcessToken() Examples

The following are 9 code examples of win32security.OpenProcessToken(). 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: inject-dll.py    From WpadEscape with GNU General Public License v3.0 7 votes vote down vote up
def enable_privilege(privilege_name):
    success = False
    privilege_id = win32security.LookupPrivilegeValue(
        None,
        privilege_name
    )

    new_privilege = [(privilege_id, win32con.SE_PRIVILEGE_ENABLED)]

    h_token = win32security.OpenProcessToken(
        win32process.GetCurrentProcess(),
        win32security.TOKEN_ALL_ACCESS
    )

    if h_token:
        success = win32security.AdjustTokenPrivileges(
            h_token, 0, new_privilege
        )

        close_handle(h_token)

    return success 
Example #2
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 get_extra_privs():
	# Try to give ourselves some extra privs (only works if we're admin):
	# SeBackupPrivilege   - so we can read anything
	# SeDebugPrivilege    - so we can find out about other processes (otherwise OpenProcess will fail for some)
	# SeSecurityPrivilege - ??? what does this do?
	
	# Problem: Vista+ support "Protected" processes, e.g. audiodg.exe.  We can't see info about these.
	# Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34
	
	th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)
	privs = win32security.GetTokenInformation(th, TokenPrivileges)
	newprivs = []
	for privtuple in privs:
		if privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeBackupPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeDebugPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeSecurityPrivilege"):
			print "Added privilege " + str(privtuple[0])
			# privtuple[1] = 2 # tuples are immutable.  WHY?!
			newprivs.append((privtuple[0], 2)) # SE_PRIVILEGE_ENABLED
		else:
			newprivs.append((privtuple[0], privtuple[1]))
				
	# Adjust privs
	privs = tuple(newprivs)
	str(win32security.AdjustTokenPrivileges(th, False , privs)) 
Example #3
Source File: windowsprivcheck.py    From LHF with GNU General Public License v3.0 6 votes vote down vote up
def get_extra_privs():
	# Try to give ourselves some extra privs (only works if we're admin):
	# SeBackupPrivilege   - so we can read anything
	# SeDebugPrivilege    - so we can find out about other processes (otherwise OpenProcess will fail for some)
	# SeSecurityPrivilege - ??? what does this do?
	
	# Problem: Vista+ support "Protected" processes, e.g. audiodg.exe.  We can't see info about these.
	# Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34
	
	th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)
	privs = win32security.GetTokenInformation(th, TokenPrivileges)
	newprivs = []
	for privtuple in privs:
		if privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeBackupPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeDebugPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(remote_server, "SeSecurityPrivilege"):
			print "Added privilege " + str(privtuple[0])
			# privtuple[1] = 2 # tuples are immutable.  WHY?!
			newprivs.append((privtuple[0], 2)) # SE_PRIVILEGE_ENABLED
		else:
			newprivs.append((privtuple[0], privtuple[1]))
				
	# Adjust privs
	privs = tuple(newprivs)
	str(win32security.AdjustTokenPrivileges(th, False , privs)) 
Example #4
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 #5
Source File: query_information.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def GetDomainName():
    try:
        tok = win32security.OpenThreadToken(win32api.GetCurrentThread(),
                                            TOKEN_QUERY, 1)
    except win32api.error, details:
        if details[0] != winerror.ERROR_NO_TOKEN:
            raise
        # attempt to open the process token, since no thread token
        # exists
        tok = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                             TOKEN_QUERY) 
Example #6
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 #7
Source File: privilege.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def acquire_privilege(privilege):
    process = win32process.GetCurrentProcess()
    token = win32security.OpenProcessToken(
        process,
        win32security.TOKEN_ADJUST_PRIVILEGES |
        win32security.TOKEN_QUERY)
    priv_luid = win32security.LookupPrivilegeValue(None, privilege)
    privilege_enable = [(priv_luid, win32security.SE_PRIVILEGE_ENABLED)]
    privilege_disable = [(priv_luid, win32security.SE_PRIVILEGE_REMOVED)]
    win32security.AdjustTokenPrivileges(token, False, privilege_enable)

    try:
        yield
    finally:
        win32security.AdjustTokenPrivileges(token, False, privilege_disable) 
Example #8
Source File: mem.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def seDebug():
        try:
            """SEDebug"""
            flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY
            htoken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
            id = win32security.LookupPrivilegeValue(None, "seDebugPrivilege")
            newPrivileges = [(id, win32security.SE_PRIVILEGE_ENABLED)]
            win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
        except Exception as e:
            print 'je me vautre'
            pass 
Example #9
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