À l'aide de advapi32.dll:LogonUserA() pour usurper l'identité d'une machine distante d'utilisateur local

J'ai besoin d'être en mesure d'exécuter RegLoadKey() sur une machine distante, et il se peut que ma machine et la machine distante ne sont pas dans le même domaine. Si elles le sont, le code ci-dessous fonctionne bien et je peux emprunter l'identité d'un utilisateur qui dispose de privilèges d'administrateur sur la machine. Autrement, si nous parlons d'utilisateurs locaux, en fonction de cette discussion que j'ai trouvé...

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

...Il y a à être un utilisateur local sur ma machine avec le même nom d'utilisateur et mot de passe. Ugh. Est-il un moyen de contourner cela?

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;
}

OriginalL'auteur JCCyC | 2009-06-23