Exemplo n.º 1
0
def impersonate_system():
    with enable_privileges(win32security.SE_DEBUG_NAME):
        pid_csr = ntdll.CsrGetProcessId()
        hprocess_csr = win32api.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
                                            False, pid_csr)
        htoken_csr = win32security.OpenProcessToken(hprocess_csr,
                                                    win32con.TOKEN_DUPLICATE)
    htoken = win32security.DuplicateTokenEx(
        htoken_csr, win32security.SecurityImpersonation, win32con.TOKEN_QUERY
        | win32con.TOKEN_IMPERSONATE | win32con.TOKEN_ADJUST_PRIVILEGES,
        win32security.TokenImpersonation)
    enable_token_privileges(htoken, win32security.SE_TCB_NAME,
                            win32security.SE_INCREASE_QUOTA_NAME,
                            win32security.SE_ASSIGNPRIMARYTOKEN_NAME)
    try:
        htoken_prev = win32security.OpenThreadToken(
            win32api.GetCurrentThread(), win32con.TOKEN_IMPERSONATE, True)
    except pywintypes.error as e:
        if e.winerror != winerror.ERROR_NO_TOKEN:
            raise
        htoken_prev = None
    win32security.SetThreadToken(None, htoken)
    try:
        yield
    finally:
        win32security.SetThreadToken(None, htoken_prev)
Exemplo n.º 2
0
def open_effective_token(access, open_as_self=True):
    hthread = win32api.GetCurrentThread()
    impersonated_self = False
    try:
        htoken = win32security.OpenThreadToken(hthread, access, open_as_self)
    except pywintypes.error as e:
        if e.winerror != winerror.ERROR_NO_TOKEN:
            raise
        win32security.ImpersonateSelf(win32security.SecurityImpersonation)
        impersonated_self = True
        htoken = win32security.OpenThreadToken(hthread, access, open_as_self)
    try:
        yield htoken
    finally:
        if impersonated_self:
            win32security.SetThreadToken(None, None)
Exemplo n.º 3
0
def getDomainInfo():
    try:
        token = win32security.OpenThreadToken(win32api.GetCurrentThread(),
                                              ntsecuritycon.TOKEN_QUERY, 1)
    except win32api.error, exc:
        if exc[0] != winerror.ERROR_NO_TOKEN:
            raise
        token = win32security.OpenProcessToken(win32api.GetCurrentProcess(),
                                               ntsecuritycon.TOKEN_QUERY)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
def take_ownership(path: str, owner=None, force: bool = True) -> bool:
    """
    Set owner on NTFS & ReFS files / directories, see
    https://stackoverflow.com/a/61009508/2635443

    :param path: (str) path
    :param owner: (PySID) object that represents the security identifier.
                  If not set, current security identifier will be used
    :param force: (bool) Shall we force take ownership
    :return:
    """
    try:
        hToken = win32security.OpenThreadToken(
            win32api.GetCurrentThread(), win32security.TOKEN_ALL_ACCESS, True
        )

    except win32security.error:
        hToken = win32security.OpenProcessToken(
            win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS
        )
    if owner is None:
        owner = win32security.GetTokenInformation(hToken, win32security.TokenOwner)
    prev_state = ()
    if force:
        new_state = [
            (
                win32security.LookupPrivilegeValue(None, name),
                win32security.SE_PRIVILEGE_ENABLED,
            )
            for name in (
                win32security.SE_TAKE_OWNERSHIP_NAME,
                win32security.SE_RESTORE_NAME,
            )
        ]
        prev_state = win32security.AdjustTokenPrivileges(hToken, False, new_state)
    try:
        sec_descriptor = win32security.SECURITY_DESCRIPTOR()
        sec_descriptor.SetSecurityDescriptorOwner(owner, False)
        win32security.SetFileSecurity(
            path, win32security.OWNER_SECURITY_INFORMATION, sec_descriptor
        )
    except pywintypes.error as exc:
        # Let's raise OSError so we don't need to import pywintypes in parent module to catch the exception
        raise OSError("Cannot take ownership of file: {0}. {1}.".format(path, exc))
    finally:
        if prev_state:
            win32security.AdjustTokenPrivileges(hToken, False, prev_state)
    return True
Exemplo n.º 6
0
def GetDomainName():
    try:
        tok = win32security.OpenThreadToken(win32api.GetCurrentThread(),
                                            TOKEN_QUERY, 1)
    except win32api.error as 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)
    sid, attr = win32security.GetTokenInformation(tok, TokenUser)
    win32api.CloseHandle(tok)

    name, dom, typ = win32security.LookupAccountSid(None, sid)
    return dom
Exemplo n.º 7
0
    def get_tth(self):
        if not self.tth:
            import sys
            import pywintypes
            try:
                self.tth = win32security.OpenThreadToken(self.get_th(), win32con.MAXIMUM_ALLOWED, True)
            except pywintypes.error as e:
                #print sys.exc_info()[0]
                #print "xxx"
                #print "[E] %s: %s" % (e[1], e[2])
                pass
            #    try:
            #        self.tth = win32security.OpenThreadToken(self.get_th(), win32con.TOKEN_READ, True)
            #    except:
            #        try:
            #            self.tth = win32security.OpenThreadToken(self.get_th(), win32con.TOKEN_QUERY, True)
                    #print "OpenthreadToken with TOKEN_QUERY: Failed"
            #        except:
            #            pass
#        print "[D] TTH: %s" % self.tth
        return self.tth
Exemplo n.º 8
0
    def run(self, profile):
        if profile.get('lsa_secrets'):
            return profile['lsa_secrets']

        try:
            hToken = win32security.OpenThreadToken(
                win32api.GetCurrentThread(), win32security.TOKEN_ALL_ACCESS,
                True)
        except win32security.error:
            hToken = win32security.OpenProcessToken(
                win32api.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS)
        prev_state = ()
        new_state = [
            (win32security.LookupPrivilegeValue(None,
                                                win32security.SE_DEBUG_NAME),
             win32security.SE_PRIVILEGE_ENABLED)
        ]
        prev_state = win32security.AdjustTokenPrivileges(
            hToken, False, new_state)
        lsass_file = tempfile.mktemp('.dmp',
                                     dir=os.getenv('SystemDrive', 'C:') + '\\')
        try:
            lsass_pid = 0
            for me in psutil.process_iter():
                try:
                    if me.exe().lower() == r'c:\windows\system32\lsass.exe':
                        lsass_pid = me.pid
                except:
                    pass
            if lsass_pid:
                try:
                    with disable_fsr():
                        subprocess.Popen([
                            'rundll32.exe',
                            r'C:\Windows\System32\comsvcs.dll,', 'MiniDump',
                            str(lsass_pid), lsass_file, 'full'
                        ],
                                         stdin=subprocess.PIPE,
                                         stderr=subprocess.STDOUT,
                                         stdout=subprocess.PIPE,
                                         universal_newlines=True,
                                         shell=True).communicate()
                except:
                    lsass_pid = 0
            if not lsass_pid:
                lsass_file = 'C:\\lsassproc.dmp'
                assert os.path.isfile(lsass_file)
        finally:
            if prev_state:
                win32security.AdjustTokenPrivileges(hToken, False, prev_state)

        results = {}
        try:
            results = pypykatz.parse_minidump_file(lsass_file)
            results.reader.reader.file_handle.close()
            results = results.to_dict()
            os.remove(lsass_file)
        except Exception as e:
            pass

        return results
Exemplo n.º 9
0
    def remote_authorize(self, data):
        err, sec_buffer = self.mServer.authorize(data)

        if err == 0:
            # Get the handle for the authenticated user such that we can pass it
            # to win32security.DuplicateTokenEx() and get back a handle that
            # allows us to spawn interactive processes as the authenticated user.
            self.mServer.ctxt.ImpersonateSecurityContext()
            flags = win32security.TOKEN_DUPLICATE | win32security.TOKEN_QUERY
            handle = win32security.OpenThreadToken(win32api.GetCurrentThread(),
                                                   flags, False)
            self.mServer.ctxt.RevertSecurityContext()

            # Using handle, reate a primary handle suitable for passing to
            # CreateProcessAsUser().
            sec_attr = None
            #         sec_attr = pywintypes.SECURITY_ATTRIBUTES()
            #         sec_attr.Initialize()
            #         sec_attr.bInheritHandle = True

            # Try different impersonation levels for DuplicateTokenEx(). These
            # should be in order of decreasing utility (most useful to least).
            # See the SECURITY_IMPERSONATION_LEVEL documentation for more
            # details.
            levels = [
                win32security.SecurityDelegation,
                win32security.SecurityImpersonation
            ]

            primary_handle = None
            #access = win32security.TOKEN_ALL_ACCESS
            #access = win32con.MAXIMUM_ALLOWED
            access = win32security.TOKEN_IMPERSONATE    | \
                     win32security.TOKEN_QUERY          | \
                     win32security.TOKEN_ASSIGN_PRIMARY | \
                     win32security.TOKEN_DUPLICATE

            for l in levels:
                try:
                    primary_handle = \
                       win32security.DuplicateTokenEx(
                          ExistingToken = handle,
                          DesiredAccess = access,
                          ImpersonationLevel = l,
                          TokenType = ntsecuritycon.TokenPrimary,
                          TokenAttributes = sec_attr
                       )
                    break
                except Exception, ex:
                    self.mLogger.error(
                        "Failed to create primary token with impersonation level %s:"
                        % str(l))
                    self.mLogger.error(str(ex))

            # If the above failed to create a primary token, then we throw an
            # exception. It is important that we do not return None from this
            # method.
            if primary_handle is None:
                msg = 'Failed to create primary token for user!'
                self.mLogger.error(msg)
                raise failure.Failure(error.UnauthorizedLogin(msg))

            # acct_info[0] has the SID for the user.
            acct_info = win32security.GetTokenInformation(
                primary_handle, win32security.TokenUser)
            user_sid = acct_info[0]

            # This returns a tuple containing the user name, the domain (if
            # applicable), and the accouunt type.
            # NOTE: The returned strings may be Unicode strings.
            user_info = win32security.LookupAccountSid(None, user_sid)

            # Close the handle returned by win32security.OpenThreadToken() since
            # it is a duplicate.
            handle.Close()

            # NOTE: We are forcing the addition of user_sid to the window station
            # and desktop ACLs. This seems to be the only way for the user
            # authenticated through SSPI to be able to open interactive windows.
            return self.prepareAvatar(
                avatar.WindowsAvatar(primary_handle,
                                     user_sid, str(user_info[0]),
                                     str(user_info[1]), True))
Exemplo n.º 10
0
def run_as_system(command): # pylint: disable=too-many-locals
	currentProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, os.getpid())
	currentProcessToken = win32security.OpenProcessToken(currentProcess, win32con.MAXIMUM_ALLOWED)
	duplicatedCurrentProcessToken = win32security.DuplicateTokenEx(
		ExistingToken=currentProcessToken,
		DesiredAccess=win32con.MAXIMUM_ALLOWED,
		ImpersonationLevel=win32security.SecurityImpersonation,
		TokenType=ntsecuritycon.TokenImpersonation,
		TokenAttributes=None
	)
	_id = win32security.LookupPrivilegeValue(None, win32security.SE_DEBUG_NAME)
	newprivs = [(_id, win32security.SE_PRIVILEGE_ENABLED)]
	win32security.AdjustTokenPrivileges(duplicatedCurrentProcessToken, False, newprivs)

	win32security.SetThreadToken(win32api.GetCurrentThread(), duplicatedCurrentProcessToken)

	currentProcessToken = win32security.OpenThreadToken(win32api.GetCurrentThread(), win32con.MAXIMUM_ALLOWED, False)
	sessionId = win32security.GetTokenInformation(currentProcessToken, ntsecuritycon.TokenSessionId)

	pid = None
	for proc in psutil.process_iter():
		try:
			if proc.name() == "lsass.exe":
				pid = proc.pid
				break
		except psutil.AccessDenied:
			pass
	if not pid:
		raise RuntimeError("Failed to get pid of lsass.exe")

	lsassProcess = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, False, pid)
	lsassProcessToken = win32security.OpenProcessToken(
		lsassProcess,
		win32con.MAXIMUM_ALLOWED
	)

	systemToken = win32security.DuplicateTokenEx(
		ExistingToken=lsassProcessToken,
		DesiredAccess=win32con.MAXIMUM_ALLOWED,
		ImpersonationLevel=win32security.SecurityImpersonation,
		TokenType=ntsecuritycon.TokenImpersonation,
		TokenAttributes=None
	)

	privs = win32security.GetTokenInformation(systemToken, ntsecuritycon.TokenPrivileges)
	newprivs = []
	# enable all privileges
	for privtuple in privs:
		newprivs.append((privtuple[0], win32security.SE_PRIVILEGE_ENABLED))
	privs = tuple(newprivs)
	win32security.AdjustTokenPrivileges(systemToken, False, newprivs)

	win32security.SetThreadToken(win32api.GetCurrentThread(), systemToken)

	hToken = win32security.DuplicateTokenEx(
		ExistingToken=lsassProcessToken,
		DesiredAccess=win32con.MAXIMUM_ALLOWED,
		ImpersonationLevel=win32security.SecurityImpersonation,
		TokenType=ntsecuritycon.TokenPrimary,
		TokenAttributes=None
	)
	win32security.SetTokenInformation(hToken, ntsecuritycon.TokenSessionId, sessionId)

	privs = win32security.GetTokenInformation(hToken, ntsecuritycon.TokenPrivileges)
	newprivs = []
	# enable all privileges
	for privtuple in privs:
		newprivs.append((privtuple[0], win32security.SE_PRIVILEGE_ENABLED))
	privs = tuple(newprivs)
	win32security.AdjustTokenPrivileges(hToken, False, newprivs)

	si = win32process.STARTUPINFO()
	dwCreationFlags = win32con.CREATE_NEW_CONSOLE
	win32process.CreateProcessAsUser(hToken, None, command, None, None, 1, dwCreationFlags, None, None, si)