【问题标题】:Using impersonation to launch processes (indirectly) in C#在 C# 中使用模拟(间接)启动进程
【发布时间】:2012-04-14 15:13:51
【问题描述】:

我正在开发一个使用 Selenium 来控制浏览器的应用程序。 Selenium 在初始化时启动浏览器,因此我从不直接在浏览器的 .exe 上调用 Process.Start。我希望 Selenium 及其所有子进程在与我的应用程序不同的用户下运行(因为我不希望它访问我的源代码)。使用找到here 的模拟示例,我试图用模拟包装Selenium 代码,但似乎所有子进程都是由启动其父进程的用户启动的。

有谁知道用模拟用户包装一段代码并让所有子进程以模拟用户的权限启动的方法?如果没有,实现这一目标的最佳策略是什么?在另一个进程中运行所有 Selenium 逻辑并以某种方式将命令传递给它?

【问题讨论】:

  • 为什么不避免麻烦并将此应用程序设置为每次通过批处理文件激活时以指定用户身份运行。 >>technet.microsoft.com/en-us/library/cc772672.aspx
  • 唯一的问题是,这个应用程序的 DLL 是我特别想阻止权限的那个——如果我这样做,我不会遇到各种问题吗?
  • 尝试对dll文件设置受限权限,这样只有一个用户可以运行它(管理员用户)support.microsoft.com/kb/308419
  • 我需要运行我的应用程序的用户能够使用 DLL 文件,然后将所有子进程作为不同的用户生成,这样他们就无法访问它们。据我所知,除非在调用 Process.Start 时明确指定另一个用户(我不能这样做),否则子进程将以父进程的用户开始,即使在应用程序中模拟了不同的用户
  • 创建新进程总是使用primary token of the launching process,而不是模拟令牌 (However, the system uses the primary token of the process rather than the impersonation token of the calling thread in the following situations:) 听起来你最好在另一个进程中运行 Selenium 并使用 IPC。

标签: c# .net windows selenium impersonation


【解决方案1】:

试试这个。

本课程让您能够以用户身份进行午餐处理,

我在这里使用 Explorer 会话。

using System.Runtime.InteropServices;
using System;
using System.Diagnostics;


[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
    public IntPtr hProcess;
    public IntPtr hThread;
    public uint dwProcessId;
    public uint dwThreadId;
 }



 [StructLayout(LayoutKind.Sequential)]
 internal struct SECURITY_ATTRIBUTES
 {
    public uint nLength;
    public IntPtr lpSecurityDescriptor;
    public bool bInheritHandle;
  }


  [StructLayout(LayoutKind.Sequential)]
  public struct STARTUPINFO
  {
      public uint cb;
      public string lpReserved;
      public string lpDesktop;
      public string lpTitle;
      public uint dwX;
      public uint dwY;
      public uint dwXSize;
      public uint dwYSize;
      public uint dwXCountChars;
      public uint dwYCountChars;
      public uint dwFillAttribute;
      public uint dwFlags;
      public short wShowWindow;
      public short cbReserved2;
      public IntPtr lpReserved2;
      public IntPtr hStdInput;
      public IntPtr hStdOutput;
      public IntPtr hStdError;

  }

   internal enum SECURITY_IMPERSONATION_LEVEL
   {
       SecurityAnonymous,
       SecurityIdentification,
       SecurityImpersonation,
       SecurityDelegation
    }

    internal enum TOKEN_TYPE
    {
         TokenPrimary = 1,
         TokenImpersonation
     }

 public class ProcessAsUser
 {

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CreateProcessAsUser(
    IntPtr hToken,
    string lpApplicationName,
    string lpCommandLine,
    ref SECURITY_ATTRIBUTES lpProcessAttributes,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    bool bInheritHandles,
    uint dwCreationFlags,
    IntPtr lpEnvironment,
    string lpCurrentDirectory,
    ref STARTUPINFO lpStartupInfo,
    out PROCESS_INFORMATION lpProcessInformation);


[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
private static extern bool DuplicateTokenEx(
    IntPtr hExistingToken,
    uint dwDesiredAccess,
    ref SECURITY_ATTRIBUTES lpThreadAttributes,
    Int32 ImpersonationLevel,
    Int32 dwTokenType,
    ref IntPtr phNewToken);


[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
    IntPtr ProcessHandle,
    UInt32 DesiredAccess,
    ref IntPtr TokenHandle);

[DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(
        ref IntPtr lpEnvironment,
        IntPtr hToken,
        bool bInherit);


[DllImport("userenv.dll", SetLastError = true)]
private static extern bool DestroyEnvironmentBlock(
        IntPtr lpEnvironment);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(
    IntPtr hObject);

private const short SW_SHOW = 5;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_DUPLICATE = 0x0002;
private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
private const int GENERIC_ALL_ACCESS = 0x10000000;
private const int STARTF_USESHOWWINDOW = 0x00000001;
private const int STARTF_FORCEONFEEDBACK = 0x00000040;
private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;


private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
{
    bool result = false;


    PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
    SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
    SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
    saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
    saThread.nLength = (uint)Marshal.SizeOf(saThread);

    STARTUPINFO si = new STARTUPINFO();
    si.cb = (uint)Marshal.SizeOf(si);


    //if this member is NULL, the new process inherits the desktop 
    //and window station of its parent process. If this member is 
    //an empty string, the process does not inherit the desktop and 
    //window station of its parent process; instead, the system 
    //determines if a new desktop and window station need to be created. 
    //If the impersonated user already has a desktop, the system uses the 
    //existing desktop. 

    si.lpDesktop = @"WinSta0\Default"; //Modify as needed 
    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
    si.wShowWindow = SW_SHOW;
    //Set other si properties as required. 

    result = CreateProcessAsUser(
        token,
        null,
        cmdLine,
        ref saProcess,
        ref saThread,
        false,
        CREATE_UNICODE_ENVIRONMENT,
        envBlock,
        null,
        ref si,
        out pi);


    if (result == false)
    {
        int error = Marshal.GetLastWin32Error();
        string message = String.Format("CreateProcessAsUser Error: {0}", error);
        Debug.WriteLine(message);

    }

    return result;
}


private static IntPtr GetPrimaryToken(int processId)
{
    IntPtr token = IntPtr.Zero;
    IntPtr primaryToken = IntPtr.Zero;
    bool retVal = false;
    Process p = null;

    try
    {
        p = Process.GetProcessById(processId);
    }

    catch (ArgumentException)
    {

        string details = String.Format("ProcessID {0} Not Available", processId);
        Debug.WriteLine(details);
        throw;
    }


    //Gets impersonation token 
    retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
    if (retVal == true)
    {

        SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
        sa.nLength = (uint)Marshal.SizeOf(sa);

        //Convert the impersonation token into Primary token 
        retVal = DuplicateTokenEx(
            token,
            TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
            ref sa,
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
            (int)TOKEN_TYPE.TokenPrimary,
            ref primaryToken);

        //Close the Token that was previously opened. 
        CloseHandle(token);
        if (retVal == false)
        {
            string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
            Debug.WriteLine(message);
        }

    }

    else
    {

        string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
        Debug.WriteLine(message);

    }

    //We'll Close this token after it is used. 
    return primaryToken;

}

private static IntPtr GetEnvironmentBlock(IntPtr token)
{

    IntPtr envBlock = IntPtr.Zero;
    bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
    if (retVal == false)
    {

        //Environment Block, things like common paths to My Documents etc. 
        //Will not be created if "false" 
        //It should not adversley affect CreateProcessAsUser. 

        string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
        Debug.WriteLine(message);

    }
    return envBlock;
}

public static bool Launch(string appCmdLine /*,int processId*/)
{

    bool ret = false;

    //Either specify the processID explicitly 
    //Or try to get it from a process owned by the user. 
    //In this case assuming there is only one explorer.exe 

    Process[] ps = Process.GetProcessesByName("explorer");
    int processId = -1;//=processId 
    if (ps.Length > 0)
    {
        processId = ps[0].Id;
    }

    if (processId > 1)
    {
        IntPtr token = GetPrimaryToken(processId);

        if (token != IntPtr.Zero)
        {

            IntPtr envBlock = GetEnvironmentBlock(token);
            ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
            if (envBlock != IntPtr.Zero)
                DestroyEnvironmentBlock(envBlock);

            CloseHandle(token);
        }

    }
    return ret;
}

}

【讨论】:

  • 这就需要我专门启动进程了吧?有没有一种方法可以说“从现在开始,该进程启动的所有处理都将作为用户 X 启动”?我无法直接访问可能正在启动进程的第三方 DLL。
猜你喜欢
  • 2017-10-21
  • 2011-01-14
  • 2010-09-25
  • 1970-01-01
  • 2017-07-12
  • 2014-10-16
  • 2019-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多