advapi32.dll:LogonUserA()を使用して、リモートマシンのローカルユーザーになりすます

StackOverflow https://stackoverflow.com/questions/1035116

質問

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;
}
役に立ちましたか?

解決

これは、ローカルユーザーを定義せずに使用しているものです。

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を使用します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top