使用ADVAPI32.DLL:LogonUserA()冒充远程机器的本地用户(Using advap

2019-06-24 00:30发布

我需要能够在远程机器上运行RegLoadKey(),它可能是我的计算机和远程计算机不在同一个域中。 如果是这样,下面的代码工作正常,我可以模拟一个具有机器上的管理员权限的用户。 否则,如果我们谈论的本地用户,根据此讨论中,我发现......

http://www.eggheadcafe.com/conversation.aspx?messageid=34224301&threadid=34224226

......必须有我的机器上的本地用户使用相同的用户名和密码。 啊。 有没有办法解决,一个方法是什么?

using System.Runtime.InteropServices;
using System.Security.Principal;

[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

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

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

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

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

public WindowsImpersonationContext WearDrag(string Username, string Password, string DomainOrMachine)
{
    WindowsImpersonationContext impersonationContext;
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if (RevertToSelf())
    {
        if (LogonUserA(Username, DomainOrMachine, Password,
            LOGON32_LOGON_INTERACTIVE,
            LOGON32_PROVIDER_DEFAULT, ref token) != 0)
        {
            if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
            {
                tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                impersonationContext = tempWindowsIdentity.Impersonate();
                if (impersonationContext != null)
                {
                    CloseHandle(token);
                    CloseHandle(tokenDuplicate);
                    return impersonationContext;
                }
            }
        }
    }
    if (token != IntPtr.Zero)
        CloseHandle(token);
    if (tokenDuplicate != IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return null;
}

Answer 1:

下面是我一直使用的是什么,而不必定义本地用户:

const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_DEFAULT = 0;

bool isSuccess = LogonUser(username, domain, password,
            LOGON32_LOGON_NEW_CREDENTIALS,
            LOGON32_PROVIDER_DEFAULT, ref token);

之后:

WindowsIdentity newIdentity = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();

我不重复,虽然手柄。

另一种看法 - 我不使用LogonUserA,我简单地使用LogonUser的。



文章来源: Using advapi32.dll:LogonUserA() to impersonate a remote machine's local user