Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在模拟时使用Process.Start(窗口应用程序)_C#_Impersonation - Fatal编程技术网

C# 在模拟时使用Process.Start(窗口应用程序)

C# 在模拟时使用Process.Start(窗口应用程序),c#,impersonation,C#,Impersonation,我试图在模拟下使用Process.Start(),这几天我一直在google上,我遇到的大多数答案都是在ASP.net下,但我正在为Windows应用程序开发,所以我很难找到根本原因 这是我的模拟代码 private void impersonateValidUser(string userName, string domain, string password) { WindowsIdentity tempWindowsIdentity = n

我试图在模拟下使用Process.Start(),这几天我一直在google上,我遇到的大多数答案都是在ASP.net下,但我正在为Windows应用程序开发,所以我很难找到根本原因

这是我的模拟代码

     private void impersonateValidUser(string userName, string domain, string password)
        {
            WindowsIdentity tempWindowsIdentity = null;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;            
            if ( LogonUser( userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
            {
                if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
                {
                    tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
                    mImpersonationContext = tempWindowsIdentity.Impersonate();
                }
            }
        } 
我正试图通过我的程序打开文档(none.exe,如.txt.doc)

到目前为止,我能够通过模拟用户检测目录/文件,因为我没有授予当前登录用户访问权限,所以假设该目录/文件对我的当前登录用户不可见。但每当我试图打开文档时,都会出现错误

    System.ComponentModel.Win32Exception (0x80004005): Access is denied
如果我错了,请纠正我,所以在这个场景中,我不想将UseShellExecute设置为false(也不想将processStartInfo设置为用户名和密码输入),因为它是针对可执行文件(?),我也遇到了CreateProcessAsUser函数,而且这个函数似乎也不适用于我的情况,从这个例子中,我读到它也适用于.exe文件

如果有人能启发我,我将不胜感激

更新:模拟类

public class Impersonator : IDisposable
{
    #region P/Invoke

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern int LogonUser( string lpszUserName,
                                         string lpszDomain,
                                         string lpszPassword,
                                         int dwLogonType,
                                         int dwLogonProvider,
                                         ref IntPtr phToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int DuplicateToken( IntPtr hToken,
                                              int impersonationLevel,
                                              ref IntPtr hNewToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool RevertToSelf();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool CloseHandle(IntPtr handle);
    #endregion

    #region Constants
    private const int LOGON32_LOGON_INTERACTIVE = 2;
    private const int LOGON32_PROVIDER_DEFAULT = 0; 
    #endregion

    #region Attributes
    private WindowsImpersonationContext mImpersonationContext = null;
    #endregion

    #region Public methods.

    public Impersonator( string userName, string domainName, string password)
    {
        impersonateValidUser(userName, domainName, password);
    }

    #endregion

    #region IDisposable member.
    public void Dispose()
    {
        undoImpersonation();
    }
    #endregion

    #region Private member.

    private void impersonateValidUser(string userName, string domain, string password)
    {
        WindowsIdentity tempWindowsIdentity = null;
        IntPtr token = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        try
        {
            if ( RevertToSelf() )
            {
                if ( LogonUser( userName, domain, password,
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                {
                    if ( DuplicateToken( token, 2, ref tokenDuplicate ) != 0 )
                    {
                        tempWindowsIdentity = new WindowsIdentity( tokenDuplicate );
                        mImpersonationContext = tempWindowsIdentity.Impersonate();
                    }
                    else
                    {
                        throw new Win32Exception( Marshal.GetLastWin32Error() );
                    }
                }
                else
                {
                    throw new Win32Exception( Marshal.GetLastWin32Error() );
                }
            }
            else
            {
                throw new Win32Exception( Marshal.GetLastWin32Error() );
            }
        }
        finally
        {
            if ( token != IntPtr.Zero )
            {
                CloseHandle( token );
            }
            if ( tokenDuplicate != IntPtr.Zero )
            {
                CloseHandle( tokenDuplicate );
            }
        }
    }

    /// <summary>
    /// Reverts the impersonation.
    /// </summary>
    private void undoImpersonation()
    {
        if ( mImpersonationContext != null )
        {
            mImpersonationContext.Undo();
        }   
    }

    #endregion
}
公共类模拟程序:IDisposable
{
#区域P/调用
[DllImport(“advapi32.dll”,SetLastError=true)]
私有静态外部int LogonUser(字符串lpszUserName,
字符串lpszDomain,
字符串lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport(“advapi32.dll”,CharSet=CharSet.Auto,SetLastError=true)]
私有静态外部int DuplicateToken(IntPtr),
int模拟级别,
参考IntPtr hNewToken);
[DllImport(“advapi32.dll”,CharSet=CharSet.Auto,SetLastError=true)]
私有静态外部bool retertoself();
[DllImport(“kernel32.dll”,CharSet=CharSet.Auto)]
私有静态外部布尔闭合句柄(IntPtr句柄);
#端区
#区域常数
private const int LOGON32\u LOGON\u INTERACTIVE=2;
private const int LOGON32_PROVIDER_DEFAULT=0;
#端区
#区域属性
私有WindowsImpersonationContext mImpersonationContext=null;
#端区
#区域公共方法。
公共模拟程序(字符串用户名、字符串域名、字符串密码)
{
impersonateValidUser(用户名、域名、密码);
}
#端区
#区域IDisposable成员。
公共空间处置()
{
取消模拟();
}
#端区
#区域私人成员。
私有void impersonateValidUser(字符串用户名、字符串域、字符串密码)
{
WindowsIdentity tempWindowsIdentity=null;
IntPtr令牌=IntPtr.Zero;
IntPtr-tokenDuplicate=IntPtr.Zero;
尝试
{
if(restortoself())
{
if(登录用户)(用户名、域、密码、,
LOGON32\u LOGON\u INTERACTIVE,LOGON32\u PROVIDER\u DEFAULT,ref token)!=0)
{
if(DuplicateToken(token,2,ref tokenDuplicate)!=0)
{
tempWindowsIdentity=新的WindowsIdentity(令牌复制);
mImpersonationContext=tempWindowsIdentity.Impersonate();
}
其他的
{
抛出新的Win32Exception(Marshal.GetLastWin32Error());
}
}
其他的
{
抛出新的Win32Exception(Marshal.GetLastWin32Error());
}
}
其他的
{
抛出新的Win32Exception(Marshal.GetLastWin32Error());
}
}
最后
{
if(令牌!=IntPtr.Zero)
{
闭合手柄(令牌);
}
如果(令牌重复!=IntPtr.Zero)
{
闭合手柄(重复);
}
}
}
/// 
///还原模拟。
/// 
私有无效撤消模拟()
{
if(mImpersonationContext!=null)
{
mImpersonationContext.Undo();
}   
}
#端区
}

以下是我用来模拟用户的完整类:

/// <summary>
/// Provide a context to impersonate operations.
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonate : IDisposable
{
    /// <summary>
    /// Initialize a new instance of the ImpersonateValidUser class with the specified user name, password, and domain.
    /// </summary>
    /// <param name="userName">The user name associated with the impersonation.</param>
    /// <param name="password">The password for the user name associated with the impersonation.</param>
    /// <param name="domain">The domain associated with the impersonation.</param>
    /// <exception cref="ArgumentException">If the logon operation failed.</exception>
    public Impersonate(string userName, SecureString password, string domain)
    {
        ValidateParameters(userName, password, domain);
        WindowsIdentity tempWindowsIdentity;
        IntPtr userAccountToken = IntPtr.Zero;
        IntPtr passwordPointer = IntPtr.Zero;
        IntPtr tokenDuplicate = IntPtr.Zero;

        try
        {
            if (Kernel32.RevertToSelf())
            {
                // Marshal the SecureString to unmanaged memory.
                passwordPointer = Marshal.SecureStringToGlobalAllocUnicode(password);

                if (Advapi32.LogonUser(userName, domain, passwordPointer, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref userAccountToken))
                {
                    if (Advapi32.DuplicateToken(userAccountToken, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            return;
                        }
                    }
                }
            }
        }
        finally
        {
            // Zero-out and free the unmanaged string reference.
            Marshal.ZeroFreeGlobalAllocUnicode(passwordPointer);

            // Close the token handle.
            if (userAccountToken != IntPtr.Zero)
                Kernel32.CloseHandle(userAccountToken);
            if (tokenDuplicate != IntPtr.Zero)
                Kernel32.CloseHandle(tokenDuplicate);
        }

        throw new ArgumentException(string.Format("Logon operation failed for userName {0}.", userName));
    }

    /// <summary>
    /// Reverts the user context to the Windows user represented by the WindowsImpersonationContext.
    /// </summary>
    public void UndoImpersonation()
    {
        impersonationContext.Undo();
    }

    /// <summary>
    /// Releases all resources used by <see cref="Impersonate"/> :
    /// - Reverts the user context to the Windows user represented by this object : <see cref="System.Security.Principal.WindowsImpersonationContext"/>.Undo().
    /// - Dispose the <see cref="System.Security.Principal.WindowsImpersonationContext"/>.
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (impersonationContext != null)
            {
                //UndoImpersonation();
                impersonationContext.Dispose();
                impersonationContext = null;
            }
        }
    }

    private void ValidateParameters(string userName, SecureString password, string domain)
    {
        if (string.IsNullOrWhiteSpace(userName))
        {
            throw new ArgumentNullException("userName");
        }
        if (password == null || password.Length == 0)
        {
            throw new ArgumentNullException("password");
        }
        if (string.IsNullOrWhiteSpace(userName))
        {
            throw new ArgumentNullException("domain");
        }
    }

    private WindowsImpersonationContext impersonationContext;

    private const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;
}
所以你可以这样使用它:

using (var imp = new Impersonate(DomainUserID, SecurePassword, Domain))
{
    Process.Start(filePath);
}

模拟时不能使用
UseShellExecute=true
。这与shell在Windows中的执行方式有关。基本上,所有内容都会传递给shell,shell会查找如何处理动词(“打开”),然后在拥有shell的用户下启动应用程序,该用户不是模拟用户-如果没有会话,模拟用户实际上没有shell

尽管您使用不同的机制模拟用户,但for
UseShellExecute
仍适用于您的情况:

如果
UserName
属性不为null或空字符串,或者调用
Process.Start(ProcessStartInfo)
方法时将引发
InvalidOperationException
,则
UseShellExecute
必须为false


要解决此问题,最简单的方法可能是自己查找已注册的应用程序,如回答中所述:。通过相关应用程序的路径,您可以作为另一个用户启动可执行文件。

您可以发布您的模拟程序类的所有代码吗,我刚刚更新了问题。稍后我将测试您发布并更新的代码,干杯:-DIt要求您使用PInvoke RunProcessAsUser,这要正确实现要困难得多。试着别针
var secure = new SecureString();
foreach (char c in "myclearpassword")
{
    secure.AppendChar(c);
}
using (var imp = new Impersonate(DomainUserID, SecurePassword, Domain))
{
    Process.Start(filePath);
}