具有提升权限的 CreateProcessAsUser

gor*_*tde 6 windows service winapi

我的服务在本地系统权限下运行,需要在用户会话中启动具有管理员权限的应用程序。

我得到的是:

  1. WTSGetActiveConsoleSessionID()
  2. WTSQueryUserToken用于会话 ID
  3. CreateProcessAsUser

问题是我需要以管理员身份运行该进程(步骤 3),而不要求用户提供管理员密码。

在Linux系统上我会简单地执行“su”,但是要在Windows系统上实现这一点吗?

gor*_*tde 3

我终于找到了解决这个问题的方法:

public void launchProcessInUserSession(String process) throws WindowsAPIException {

        final DWORD interactiveSessionId = kernel32.WTSGetActiveConsoleSessionId();
        final DWORD serviceSessionId = getCurrentSessionId();

        final HANDLEByReference pExecutionToken = new HANDLEByReference();

        final HANDLE currentProcessToken = getCurrentProcessToken();
        try {

            final HANDLE interactiveUserToken = getUserToken(interactiveSessionId);

            checkAPIError(advapi32.DuplicateTokenEx(currentProcessToken, WinNT.TOKEN_ALL_ACCESS, null, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                    WinNT.TOKEN_TYPE.TokenPrimary, pExecutionToken));
        } finally {
            kernel32.CloseHandle(currentProcessToken);
        }

        final HANDLE executionToken = pExecutionToken.getValue();
        try {
            checkAPIError(advapi32.SetTokenInformation(executionToken, TOKEN_INFORMATION_CLASS.TokenSessionId, new IntByReference(interactiveSessionId.intValue()), DWORD.SIZE));

            final WinBase.STARTUPINFO si = new WinBase.STARTUPINFO();
            final PROCESS_INFORMATION processInfo = new WinBase.PROCESS_INFORMATION();
            final int dwFlags = WinBase.DETACHED_PROCESS;

            checkAPIError(advapi32.CreateProcessAsUser(executionToken, null, process, null, null, false, dwFlags, null, null, si, processInfo));
            LOGGER.debug("Execution done. Process ID is {}", processInfo.dwProcessId);
        } finally {
            kernel32.CloseHandle(executionToken);
        }
    }
Run Code Online (Sandbox Code Playgroud)