Ejemplo n.º 1
0
def shell_as(th, enable_privs=0):
    t = thread(th)
    print t.as_text()
    new_tokenh = win32security.DuplicateTokenEx(
        th, 3, win32con.MAXIMUM_ALLOWED, win32security.TokenPrimary,
        win32security.SECURITY_ATTRIBUTES())
    print "new_tokenh: %s" % new_tokenh
    print "Impersonating..."
    if enable_privs:
        get_all_privs(new_tokenh)
    commandLine = "cmd"
    si = win32process.STARTUPINFO()
    print "pysecdump: Starting shell with required privileges..."
    (hProcess, hThread, dwProcessId,
     dwThreadId) = win32process.CreateProcessAsUser(
         new_tokenh,
         None,  # AppName
         commandLine,  # Command line
         None,  # Process Security
         None,  # ThreadSecurity
         1,  # Inherit Handles?
         win32process.NORMAL_PRIORITY_CLASS,
         None,  # New environment
         None,  # Current directory
         si)  # startup info.
    win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
    print "pysecdump: Quitting"
Ejemplo n.º 2
0
 def LockWorkStation(self):
     try:
         logging.debug("LockWorkStation was called.")
         sessionId = GetActiveSessionId()
         if sessionId != 0xffffffff:
             logging.debug("Locking workstation (session %d)", sessionId)
             dupToken = None
             userToken = win32ts.WTSQueryUserToken(sessionId)
             if userToken is not None:
                 logging.debug("Got the active user token.")
                 # The following access rights are required for
                 # CreateProcessAsUser.
                 access = win32security.TOKEN_QUERY
                 access |= win32security.TOKEN_DUPLICATE
                 access |= win32security.TOKEN_ASSIGN_PRIMARY
                 dupToken = win32security.DuplicateTokenEx(
                     userToken, win32security.SecurityImpersonation, access,
                     win32security.TokenPrimary, None)
                 userToken.Close()
             if dupToken is not None:
                 logging.debug("Duplicated the active user token.")
                 lockCmd = os.path.join(os.environ['WINDIR'],
                                        "system32\\rundll32.exe")
                 lockCmd += " user32.dll,LockWorkStation"
                 logging.debug("Executing \"%s\".", lockCmd)
                 win32process.CreateProcessAsUser(
                     dupToken, None, lockCmd, None, None, 0, 0, None, None,
                     win32process.STARTUPINFO())
                 dupToken.Close()
         else:
             logging.debug("No active session. Ignoring lock workstation "
                           "command.")
     except:
         logging.exception("LockWorkStation exception")
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def run(args, cwd=None, as_admin=False, cmd_window=False):
    """ Run an arbitrary command. """
    if isinstance(args, str):
        args = [args]
    args = list(args)

    if cwd is None:
        cwd = os.getenv("USERPROFILE")

    if as_admin:
        subprocess.call(args, shell=True, cwd=cwd)
    else:
        # We have to do all this nonsense to spawn the process
        # as the logged in user, rather than as the administrator
        # that PyleWM is running as
        startup_info = STARTUPINFO()
        process_information = PROCESS_INFORMATION()

        shell_window = ctypes.windll.user32.GetShellWindow()
        thread_id, process_id = win32process.GetWindowThreadProcessId(
            shell_window)
        shell_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                            False, process_id)
        shell_token = win32security.OpenProcessToken(shell_handle,
                                                     win32con.TOKEN_DUPLICATE)

        spawn_token = win32security.DuplicateTokenEx(
            shell_token, win32security.SecurityImpersonation,
            win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY
            | win32con.TOKEN_DUPLICATE
            | win32con.TOKEN_ADJUST_DEFAULT | 0x0100,
            win32security.TokenPrimary, None)

        escaped_commandline = ""
        for arg in args:
            escaped_commandline += '"'
            escaped_commandline += arg
            escaped_commandline += '" '

        # Try to lookup where the exe is from PATH
        executable = args[0]
        if not os.path.isfile(executable):
            executable = shutil.which(executable)

        success = ctypes.windll.advapi32.CreateProcessWithTokenW(
            int(spawn_token), 0, executable, escaped_commandline,
            win32con.CREATE_NO_WINDOW
            if not cmd_window else win32con.CREATE_NEW_CONSOLE, None,
            os.getcwd(), ctypes.pointer(startup_info),
            ctypes.pointer(process_information))

        if not success:
            error = ctypes.get_last_error()
            raise pywintypes.error(error, 'CreateProcessWithTokenW',
                                   win32api.FormatMessageW(error))
def getusertoken():
    print("Getting winlogon pid...")
    winlogon_pid = get_pid('winlogon.exe')
    print("PID:" + str(winlogon_pid))

    p = win32api.OpenProcess(1024, 0, get_pid('winlogon.exe'))
    t = win32security.OpenProcessToken(p, win32security.TOKEN_DUPLICATE)

    primaryToken = win32security.DuplicateTokenEx(
        t, win32security.SecurityImpersonation, win32security.TOKEN_ALL_ACCESS,
        win32security.TokenPrimary)
    return primaryToken
Ejemplo n.º 6
0
Archivo: win.py Proyecto: umutbb/hubble
def dup_token(th):
    '''
    duplicate the access token
    '''
    # TODO: is `duplicate_token` the same?
    sec_attr = win32security.SECURITY_ATTRIBUTES()
    sec_attr.bInheritHandle = True
    return win32security.DuplicateTokenEx(
        th,
        win32security.SecurityImpersonation,
        win32con.MAXIMUM_ALLOWED,
        win32security.TokenPrimary,
        sec_attr,
    )
Ejemplo n.º 7
0
def duplicate_shell_token():
    hWndShell = user32.GetShellWindow()
    if not hWndShell:
        raise pywintypes.error(winerror.ERROR_FILE_NOT_FOUND, 'GetShellWindow',
                               'no shell window')
    tid, pid = win32process.GetWindowThreadProcessId(hWndShell)
    hProcShell = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      False, pid)
    hTokenShell = win32security.OpenProcessToken(hProcShell,
                                                 win32con.TOKEN_DUPLICATE)
    return win32security.DuplicateTokenEx(
        hTokenShell, win32security.SecurityImpersonation,
        win32con.TOKEN_ASSIGN_PRIMARY | win32con.TOKEN_DUPLICATE
        | win32con.TOKEN_QUERY | win32con.TOKEN_ADJUST_DEFAULT
        | TOKEN_ADJUST_SESSIONID, win32security.TokenPrimary, None)
Ejemplo n.º 8
0
 def runProcessInteractWithUser(self):
     hToken = win32security.OpenProcessToken(
         win32api.GetCurrentProcess(),
         win32con.TOKEN_DUPLICATE | win32con.TOKEN_ADJUST_DEFAULT
         | win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY)
     hNewToken = win32security.DuplicateTokenEx(
         hToken, win32security.SecurityImpersonation,
         win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)
     # Create sid level
     sessionId = win32ts.WTSGetActiveConsoleSessionId()
     win32security.SetTokenInformation(hNewToken,
                                       win32security.TokenSessionId,
                                       sessionId)
     priority = win32con.NORMAL_PRIORITY_CLASS | win32con.CREATE_NEW_CONSOLE
     startup = win32process.STARTUPINFO()
     handle, thread_id, pid, tid = win32process.CreateProcessAsUser(
         hNewToken, self.filePath, None, None, None, False, priority, None,
         None, startup)
Ejemplo n.º 9
0
    def runScreenShotApp3_old(self):
        # Get the current security token
        token = win32security.OpenProcessToken(
            win32process.GetCurrentProcess(), win32security.TOKEN_ALL_ACCESS)

        # Make a copy
        #token2 = win32security.DuplicateToken(token)
        token2 = win32security.DuplicateTokenEx(
            token, win32security.SecurityImpersonation,
            win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

        # Find the session id - we will grab the console/keyboard
        #proc_id = win32process.GetCurrentProcessId()
        #session_id = win32ts.ProcessIdToSessionId(proc_id)
        session_id = win32ts.WTSGetActiveConsoleSessionId()

        # Make this token target our session
        win32security.SetTokenInformation(token2, win32security.TokenSessionId,
                                          session_id)
Ejemplo n.º 10
0
def run_os_command_impersonated(cmd, user, password, domain='.'):
    si = win32process.STARTUPINFO()

    out_handle, err_handle, out_file, err_file = _create_tmp_files()

    ok, si.hStdInput = _safe_duplicate_handle(
        win32api.GetStdHandle(win32api.STD_INPUT_HANDLE))

    if not ok:
        raise Exception("Unable to create StdInput for child process")
    ok, si.hStdOutput = _safe_duplicate_handle(out_handle)
    if not ok:
        raise Exception("Unable to create StdOut for child process")
    ok, si.hStdError = _safe_duplicate_handle(err_handle)
    if not ok:
        raise Exception("Unable to create StdErr for child process")

    si.dwFlags = win32process.STARTF_USESTDHANDLES
    si.lpDesktop = ""

    user_token = win32security.LogonUser(user, domain, password,
                                         win32con.LOGON32_LOGON_SERVICE,
                                         win32con.LOGON32_PROVIDER_DEFAULT)
    primary_token = win32security.DuplicateTokenEx(
        user_token, win32security.SecurityImpersonation, 0,
        win32security.TokenPrimary)
    info = win32process.CreateProcessAsUser(primary_token, None, cmd, None,
                                            None, 1, 0, None, None, si)

    hProcess, hThread, dwProcessId, dwThreadId = info
    hThread.Close()

    try:
        win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
    except KeyboardInterrupt:
        pass

    out, err = _get_files_output(out_file, err_file)
    exitcode = win32process.GetExitCodeProcess(hProcess)

    return exitcode, out, err
Ejemplo n.º 11
0
    def runScreenShotApp(self):
        global DISABLE_SSHOT
        if DISABLE_SSHOT is True:
            return

        # Get the session id for the console
        session_id = win32ts.WTSGetActiveConsoleSessionId()
        if session_id == 0xffffffff:
            # User not logged in right now?
            logging.info("No console user")
            return None

        # logging.info("Got Console: " + str(session_id))

        # Login to the terminal service to get the user token for the console id
        svr = win32ts.WTSOpenServer(".")
        user_token = win32ts.WTSQueryUserToken(session_id)
        # logging.info("User Token " + str(user_token))

        # Copy the token
        user_token_copy = win32security.DuplicateTokenEx(
            user_token, win32security.SecurityImpersonation,
            win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

        # Put this token in the logged in session
        win32security.SetTokenInformation(user_token_copy,
                                          win32security.TokenSessionId,
                                          session_id)

        # Switch to the user
        # win32security.ImpersonateLoggedOnUser(user_token)
        # logging.info("Impersonating " + win32api.GetUserName())

        # Run the screen shot app
        # app_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
        # cmd = os.path.join(app_path, "sshot\\dist\\sshot.exe")
        cmd = os.path.join(ROOT_FOLDER, "ope_laptop_binaries\\sshot\\sshot.exe"
                           )  # "c:\\programdata\\ope\\bin\\sshot.exe"
        # cmd = "cmd.exe"
        logging.info("Running sshot app " + cmd)

        # Use win create process function
        si = win32process.STARTUPINFO()
        si.dwFlags = win32process.STARTF_USESHOWWINDOW
        si.wShowWindow = win32con.SW_NORMAL
        # si.lpDesktop = "WinSta0\Default"
        si.lpDesktop = ""

        # Setup envinroment for the user
        environment = win32profile.CreateEnvironmentBlock(user_token, False)

        try:
            (
                hProcess, hThread, dwProcessId, dwThreadId
            ) = win32process.CreateProcessAsUser(
                user_token_copy,
                None,  # AppName (really command line, blank if cmd line supplied)
                "\"" + cmd + "\"",  # Command Line (blank if app supplied)
                None,  # Process Attributes
                None,  # Thread Attributes
                0,  # Inherits Handles
                win32con.
                NORMAL_PRIORITY_CLASS,  # or win32con.CREATE_NEW_CONSOLE,
                environment,  # Environment
                os.path.dirname(cmd),  # Curr directory
                si)  # Startup info

            # logging.info("Process Started: " + str(dwProcessId))
            # logging.info(hProcess)
        except Exception as e:
            logging.info("Error launching process: " + str(e))

        # logging.info(os.system(cmd))

        # Return us to normal security
        # win32security.RevertToSelf()

        # Cleanup
        win32ts.WTSCloseServer(svr)
        user_token.close()
        user_token_copy.close()

        return
Ejemplo n.º 12
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))
Ejemplo n.º 13
0
def CreateProc(appname, cmdline=None):
    global cfg
    #找到winlogon.exe的进程信息,然后复制它的token,再赋权新的token,用新token创建的新进程,就有前台交互权限了
    p = getProcess(caption='winlogon.exe')[0]
    pid = p['pid']
    if cfg['debug']:
        mylog("pid=%d,type=%s" % (pid, type(pid)))
    #通过winlogon.exe的pid打开进程,获得它的句柄
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    #通过winlogon.exe的句柄,获得它的令牌(经测试,admin权限运行的程序,只能用TOKEN_QUERY方式打开,service方式运行的程序,有全部权限)
    token_handle = win32security.OpenProcessToken(
        handle, win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY
        | win32con.TOKEN_DUPLICATE)
    if cfg['debug']:
        print("winlogon.exe's handle=%s,token=%s" % (handle, token_handle))
    res = None
    #通过winlogon.exe的令牌,复制一个新令牌(经测试,admin权限运行的程序,权限不足,service方式运行的程序,有全部权限)
    dup_th = win32security.DuplicateTokenEx(
        token_handle,
        win32security.SecurityImpersonation,
        win32security.TOKEN_ALL_ACCESS,
        win32security.TokenPrimary,
    )
    #通过winlogon.exe的pid,获得它的session id(经测试,admin权限运行的程序,没TCB权限,需要service方式运行的程序,有全部权限)
    curr_session_id = win32ts.ProcessIdToSessionId(pid)
    if cfg['debug']:
        print("dup_th=%s" % dup_th)
    #获得系统默认的程序启动信息(初始化程序所需的,标准输出、桌面选择等信息)
    startup = win32process.STARTUPINFO()
    if cfg['debug']:
        print(startup)
    #下面的这个win32con.CREATE_NEW_CONSOLE权限必须给,要不后面CreateProcessAsUser时看到执行了,然后程序就没了
    priority = win32con.NORMAL_PRIORITY_CLASS | win32con.CREATE_NEW_CONSOLE
    if cfg['debug']:
        mylog("in CreateProc(),appname=%s,cmdline=%s" % (appname, cmdline))
    (hProcess, hThread, dwProcessId, dwThreadId) = (None, None, None, None)
    #通过winlogon.exe的session id获得它的console令牌
    console_user_token = win32ts.WTSQueryUserToken(curr_session_id)
    #通过winlogon.exe的console令牌,获得它的环境profile设置信息
    environment = win32profile.CreateEnvironmentBlock(console_user_token,
                                                      False)
    #给复制出来的token,绑定对应的session id,使之基于和winlogon.exe一样的会话
    win32security.SetTokenInformation(dup_th, win32security.TokenSessionId,
                                      curr_session_id)
    #设置调整权限的flag权限
    flags = win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY
    #设置权限1:找到SE_DEBUG_NAME的权限的id,给p1
    p1 = win32security.LookupPrivilegeValue(None, win32con.SE_DEBUG_NAME)
    newPrivileges = [(p1, win32con.SE_PRIVILEGE_ENABLED)]
    #把复制出来的winlogon.exe的token,增加新权限(也即是SE_DEBUG_NAME权限)
    win32security.AdjustTokenPrivileges(dup_th, False, newPrivileges)
    if cfg['debug']:
        privs = getPrivs(dup_th)
        mylog("privs=%s" % "\n".join(privs))
    #下面准备启动程序需要的重定向的标准输出和标准错误输出的文件句柄,但目前似乎没有重定向成功:(
    fh_stdout = win32file.CreateFile(
        os.path.join(app_path, "watchdog.stdout"), win32file.GENERIC_WRITE,
        win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
        win32file.OPEN_ALWAYS, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0)
    fh_stderr = win32file.CreateFile(
        os.path.join(app_path, "watchdog.stderr"), win32file.GENERIC_WRITE,
        win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
        win32file.OPEN_ALWAYS, win32file.FILE_FLAG_SEQUENTIAL_SCAN, 0)
    startup.hStdOutput = fh_stdout
    startup.hStdError = fh_stderr

    #下面开始尝试用复制好的token:dup_th,并也给了足够的权限的token,然后来启动指定程序
    try:
        (hProcess, hThread, dwProcessId,
         dwThreadId) = win32process.CreateProcessAsUser(
             dup_th, appname, cmdline, None, None, True, priority, None, None,
             startup)
    except Exception as e:
        mylog("in CreateProc(),return False,ERROR:%s" % str(e))
        return False
    mylog("%s,%s,%s,%s" % (hProcess, hThread, dwProcessId, dwThreadId))
    if dwProcessId == None:
        #创建进程失败
        mylog(
            "Can not get dwProcessId from win32process.CreateProcessAsUser()")
        return False
    try:
        time.sleep(2)
        mylog("dwProcessId=%s" % dwProcessId)
        process = psutil.Process(dwProcessId)
    except Exception as e:
        mylog("CreateProc(),try to psutil.Process(),ERROR:%s" % str(e))
    mylog("process:%s" % process)
    return_code = None
    try:
        return_code = process.wait(10)
    except Exception as e:
        mylog("CreateProc(),try to process.wait(),ERROR:%s" % str(e))
        mylog("Maybe Child process Running already , but not quit")
    mylog("CreateProc return code=%s" % str(return_code))
Ejemplo n.º 14
0
    def get_active_user_token():
        # Figure out the active user token we need to use to run the app as
        ret = None

        # Get the current user name
        user_name = win32api.GetUserName()

        if user_name != "SYSTEM":
            # Running as a logged in user, get the current users token
            current_process = win32process.GetCurrentProcess()
            token = win32security.OpenProcessToken(current_process,
                                                   win32con.MAXIMUM_ALLOWED)
            # win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)  #

            ret = token

            return ret

        #if user_name == "SYSTEM":
        #    p("}}gnStarted by SYSTEM user (OPEService) - trying to switch user identity}}xx")

        # Get a list of Terminal Service sessions and see which one is active
        active_session = UserAccounts.WTS_INVALID_SESSION_ID
        station_name = ""
        sessions = win32ts.WTSEnumerateSessions(None, 1, 0)

        for session in sessions:
            if session['State'] == UserAccounts.WTSActive:
                # Found the active session
                active_session = session['SessionId']
                station_name = session["WinStationName"]

        # If we didn't find one, try this way
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            active_session = win32ts.WTSGetActiveConsoleSessionId()
        if active_session == UserAccounts.WTS_INVALID_SESSION_ID:
            # User not logged in right now? or lock screen up?
            p("}}gnNo console user or desktop locked}}xx", log_level=1)
            return ret

        # Get the current console session
        #p("Got Console: " + str(active_session), debug_level=5)

        # Login to the terminal service to get the user token for the console id so we can impersonate it
        try:
            #svr = win32ts.WTSOpenServer(".")
            #win32ts.WTSCloseServer(svr)
            user_token = win32ts.WTSQueryUserToken(active_session)

            # Copy the token so we can modify it
            user_token_copy = win32security.DuplicateTokenEx(
                user_token, win32security.SecurityImpersonation,
                win32security.TOKEN_ALL_ACCESS, win32security.TokenPrimary)

            ret = user_token_copy
            user_token.close()
        except Exception as ex:
            p("}}rnUnknown Error - trying to get WTS UserToken\n" + str(ex) +
              "}}xx",
              debug_level=1)
            return ret

        #p("User Token Found " + str(user_token_copy), debug_level=5)

        return ret
Ejemplo n.º 15
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)