CreateProcessAsUser用户上下文

时间:2014-02-17 12:32:51

标签: c# windows windows-services createprocessasuser

我已经搜索了很长时间但找不到合适的解决方案: - (

我创建了一个窗口服务,它使用CreateProcessAsUser(http://www.pinvoke.net/default.aspx/advapi32/createprocessasuser.html),WTSEnumerateSessions等在每台登录到计算机的用户上启动客户端...

这已经很好了。客户端在用户的会话中启动,显示其任务栏图标,与服务的通信工作正常。

我遇到的问题是我需要让客户端在用户的个人资料中存储临时文件。我尝试从一个小的日志文件开始,以便我可以跟踪我的用户最终可能遇到的任何错误。不幸的是我无法保存到用户的临时文件夹,因为客户端似乎在LocalSystem的上下文中运行,尽管WindowsIdentity显示正确的用户:System.IO.Path.GetTempPath()总是返回'C:\ Windows \ Temp'但是我的用户的没有管理权限,所以他们无法在那里写...此外,我计划将设置存储在当前用户的注册表中,这也不起作用。我认为这在某种程度上与错误的临时路径有关。

我也尝试过CreateEnvironmentBlock(http://www.pinvoke.net/default.aspx/userenv/CreateEnvironmentBlock.html),但我无法让它工作,我找到一篇文章说这在Vista或更高版本上不再有用,所以我不再研究那个。

为了进行测试,我创建了一个小测试表单:

        MessageBox.Show("Temp: " + System.IO.Path.GetTempPath() + Environment.NewLine + "User: " + WindowsIdentity.GetCurrent().Name, "Before impersonation");

        WindowsIdentity currentUserId = WindowsIdentity.GetCurrent();
        WindowsImpersonationContext impersonatedUser = currentUserId.Impersonate();

        MessageBox.Show("Temp: " + System.IO.Path.GetTempPath() + Environment.NewLine + "User: " + WindowsIdentity.GetCurrent().Name, "After impersonation");

这个在模仿之前和之后总是显示相同的结果:“Temp:C:\ Windows \ Temp User:testdomain \ testuser”: - (

如果这有助于我的功能启动进程(用户令牌由WTSEnumerateSessions提供) - 当然这仅适用于LocalSystem的上下文:

    public static Process StartProcessAsUser(IntPtr UserToken, string App, string AppPath, string AppParameters)
    {
        Process ResultProcess = null;

        IntPtr hDupedToken = IntPtr.Zero;
        NativeProcessAPI.PROCESS_INFORMATION oProcessInformation = new NativeProcessAPI.PROCESS_INFORMATION();

        try
        {
            NativeProcessAPI.SECURITY_ATTRIBUTES oSecurityAttributes = new NativeProcessAPI.SECURITY_ATTRIBUTES();
            oSecurityAttributes.Length = Marshal.SizeOf(oSecurityAttributes);

            bool result = NativeProcessAPI.DuplicateTokenEx(
                  UserToken,
                  NativeProcessAPI.GENERIC_ALL_ACCESS,
                  ref oSecurityAttributes,
                  (int)NativeProcessAPI.SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                  (int)NativeProcessAPI.TOKEN_TYPE.TokenPrimary,
                  ref hDupedToken
               );

            if (!result)
            {
                return null;
            }

            NativeProcessAPI.STARTUPINFO oStartupInfo = new NativeProcessAPI.STARTUPINFO();
            oStartupInfo.cb = Marshal.SizeOf(oStartupInfo);
            oStartupInfo.lpDesktop = String.Empty;

            result = NativeProcessAPI.CreateProcessAsUser(
                                 hDupedToken,
                                 null,
                                 App + " " + AppParameters,
                                 ref oSecurityAttributes, ref oSecurityAttributes,
                                 false, 0, IntPtr.Zero,
                                 AppPath, ref oStartupInfo, ref oProcessInformation
                           );

            if (result)
            {
                try
                {
                    int ProcessID = oProcessInformation.dwProcessID;

                    try
                    {
                        ResultProcess = System.Diagnostics.Process.GetProcessById(ProcessID);
                    }
                    catch
                    {
                        ResultProcess = null;
                    }
                }
                catch (Exception ex)
                {
                    ResultProcess = null;
                }
            }
        }
        catch
        {
            ResultProcess = null;
        }
        finally
        {
            if (oProcessInformation.hProcess != IntPtr.Zero)
                NativeProcessAPI.CloseHandle(oProcessInformation.hProcess);
            if (oProcessInformation.hThread != IntPtr.Zero)
                NativeProcessAPI.CloseHandle(oProcessInformation.hThread);
            if (hDupedToken != IntPtr.Zero)
                NativeProcessAPI.CloseHandle(hDupedToken);
        }

        return ResultProcess;
    }

我是如何在用户的上下文中而不是在LocalSystem的上下文中启动我的进程的?

非常感谢!

2 个答案:

答案 0 :(得分:0)

好的我找到了一个解决方法:我使用WindowsIdentity提供的SID切换到使用USERS配置单元而不是CURRENT_USER配置单元:

Microsoft.Win32.Registry.Users.OpenSubKey(System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString() + ..., true)

虽然从用户的“环境”和“易变环境”注册表路径获取环境变量而不仅仅使用.Net的内置函数感觉有点不舒服,但这种方法很完美...

但非常感谢你的帮助; - )

编辑: 我不会将此标记为答案,因为它是a)我自己的解决方案和b)只是一种解决方法

答案 1 :(得分:0)

让其他人知道如何执行此操作:CreateEnvironmentBlock是您需要使用的。

DuplicateTokenEx(userToken, MAXIMUM_ALLOWED | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, IntPtr.Zero, SecurityIdentification, TokenPrimary, out dupUserToken);
CreateEnvironmentBlock(out envBlock, dupUserToken, false);
CreateProcessAsUserW(dupUserToken, null, cmdLine, IntPtr.Zero, IntPtr.Zero, false,
            (uint)(CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT),
            envBlock, processDir, ref startupInfo, out procInfo);
相关问题