web-dev-qa-db-ja.com

.NETで偽装を行う方法

.NETでユーザーになりすます簡単な方法はありますか?

これまで、すべての偽装要件に コードプロジェクトのこのクラス を使用してきました。

.NET Frameworkを使用してそれを行うより良い方法はありますか?

偽装する必要があるIDを表すユーザー資格情報セット(ユーザー名、パスワード、ドメイン名)があります。

124
ashwnacharya

.NET偽装の概念の概要をいくつか紹介します。

基本的に、.NETフレームワークですぐに使用できるこれらのクラスを活用します。

しかし、コードはしばしば長くなる可能性があり、そのためプロセスを簡素化しようとする参照のような多くの例を見ることができます。

57
Eric Schoonover

.NETスペースでの「なりすまし」とは、通常、特定のユーザーアカウントでコードを実行することを意味します。これらの2つのアイデアは頻繁に組み合わされますが、ユーザー名とパスワードを介してそのユーザーアカウントにアクセスすることとは別の概念です。それらの両方を説明し、内部で使用する SimpleImpersonation ライブラリの使用方法を説明します。

なりすまし

偽装用のAPIは、System.Security.Principal名前空間を介して.NETで提供されます。

  • 新しいコード(.NET 4.6 + 、. NET Coreなど)では通常、 WindowsIdentity.RunImpersonated を使用する必要があります。これは、ユーザーアカウントのトークンへのハンドルを受け入れ、コードのActionまたはFunc<T>のいずれかを受け入れます。実行します。

    WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
    });
    

    または

    var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
    {
        // do whatever you want as this user.
        return result;
    });
    
  • 古いコードでは、 WindowsIdentity.Impersonate メソッドを使用してWindowsImpersonationContextオブジェクトを取得していました。このオブジェクトはIDisposableを実装するため、通常はusingブロックから呼び出す必要があります。

    using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
    {
        // do whatever you want as this user.
    }
    

    このAPIは.NET Frameworkにまだ存在しますが、通常は避ける必要があり、.NET Coreまたは.NET Standardでは使用できません。

ユーザーアカウントへのアクセス

ユーザー名とパスワードを使用してWindowsのユーザーアカウントにアクセスするためのAPIは、 LogonUser -Win32ネイティブAPIです。現在、それを呼び出すための組み込みの.NET APIはないため、P/Invokeに頼らなければなりません。

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);

これは基本的な呼び出しの定義ですが、実際に運用環境で使用するためにはさらに多くの考慮事項があります。

  • 「安全な」アクセスパターンでハンドルを取得します。
  • ネイティブハンドルを適切に閉じる
  • コードアクセスセキュリティ(CAS)の信頼レベル(.NET Frameworkのみ)
  • ユーザーのキーストロークで安全に収集できる場合は、SecureStringを渡します。

このすべてを説明するために記述するコードの量は、StackOverflowの答えであるIMHOにあるべきものを超えています。

組み合わせられた簡単なアプローチ

このすべてを自分で記述するのではなく、偽装とユーザーアクセスを単一のAPIに結合するmy SimpleImpersonation ライブラリの使用を検討してください。同じシンプルなAPIで、最新のコードベースと古いコードベースの両方でうまく機能します。

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
}); 

または

var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
    return something;
});

WindowsIdentity.RunImpersonated APIに非常に似ていますが、トークンハンドルについて何も知っている必要はありません。

これは、バージョン3.0.0以降のAPIです。詳細については、プロジェクトのreadmeを参照してください。また、以前のバージョンのライブラリでは、WindowsIdentity.Impersonateに似たIDisposableパターンのAPIが使用されていました。新しいバージョンの方がはるかに安全であり、両方とも内部で使用されています。

269

これはおそらくあなたが望むものです:

using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
     //your code goes here
}

しかし、私は本当にあなたを助けるためにもっと詳細が必要です。構成ファイルを使用して偽装を行うことができます(Webサイトでこれを実行しようとしている場合)、またはWCFサービスの場合はメソッドデコレーター(属性)を使用するか、...を通じてアイデアを得ることができます。

また、特定のサービス(またはWebアプリ)を呼び出したクライアントのなりすましについて話している場合は、適切なトークンを渡すようにクライアントを正しく構成する必要があります。

最後に、本当にしたいことが委任である場合、ユーザーとマシンが委任に対して信頼されるように、ADを正しくセットアップする必要もあります。

編集:
こちらをご覧ください here さまざまなユーザーになりすます方法や詳細なドキュメントをご覧ください。

19
Esteban Araya

Matt Johnsonの答えをvb.netに移植しました。ログオンタイプの列挙型を追加しました。 LOGON32_LOGON_INTERACTIVEは、SQLサーバーで機能する最初の列挙値でした。私の接続文字列は信頼されました。接続文字列にユーザー名/パスワードがありません。

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote Shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

Usingステートメントで使用して、偽装して実行するコードを含める必要があります。

6
toddmo

以前の回答から詳細を表示しますnugetパッケージを作成しました Nuget

Github のコード

サンプル:使用できます:

           string login = "";
           string domain = "";
           string password = "";

           using (UserImpersonation user = new UserImpersonation(login, domain, password))
           {
               if (user.ImpersonateValidUser())
               {
                   File.WriteAllText("test.txt", "your text");
                   Console.WriteLine("File writed");
               }
               else
               {
                   Console.WriteLine("User not connected");
               }
           }

完全なコードを見る:

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


/// <summary>
/// Object to change the user authticated
/// </summary>
public class UserImpersonation : IDisposable
{
    /// <summary>
    /// Logon method (check athetification) from advapi32.dll
    /// </summary>
    /// <param name="lpszUserName"></param>
    /// <param name="lpszDomain"></param>
    /// <param name="lpszPassword"></param>
    /// <param name="dwLogonType"></param>
    /// <param name="dwLogonProvider"></param>
    /// <param name="phToken"></param>
    /// <returns></returns>
    [DllImport("advapi32.dll")]
    private static extern bool LogonUser(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

    /// <summary>
    /// Close
    /// </summary>
    /// <param name="handle"></param>
    /// <returns></returns>
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    private WindowsImpersonationContext _windowsImpersonationContext;
    private IntPtr _tokenHandle;
    private string _userName;
    private string _domain;
    private string _passWord;

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

    /// <summary>
    /// Initialize a UserImpersonation
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="domain"></param>
    /// <param name="passWord"></param>
    public UserImpersonation(string userName, string domain, string passWord)
    {
        _userName = userName;
        _domain = domain;
        _passWord = passWord;
    }

    /// <summary>
    /// Valiate the user inforamtion
    /// </summary>
    /// <returns></returns>
    public bool ImpersonateValidUser()
    {
        bool returnValue = LogonUser(_userName, _domain, _passWord,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref _tokenHandle);

        if (false == returnValue)
        {
            return false;
        }

        WindowsIdentity newId = new WindowsIdentity(_tokenHandle);
        _windowsImpersonationContext = newId.Impersonate();
        return true;
    }

    #region IDisposable Members

    /// <summary>
    /// Dispose the UserImpersonation connection
    /// </summary>
    public void Dispose()
    {
        if (_windowsImpersonationContext != null)
            _windowsImpersonationContext.Undo();
        if (_tokenHandle != IntPtr.Zero)
            CloseHandle(_tokenHandle);
    }

    #endregion
}
3
Cedric Michel

私はパーティーにかなり遅れていることを知っていますが、 Phillip Allan-Harding のライブラリは、この場合と同様のものに最適であると考えています。

このような小さなコードだけが必要です。

private const string LOGIN = "mamy";
private const string DOMAIN = "mongo";
private const string PASSWORD = "HelloMongo2017";

private void DBConnection()
{
    using (Impersonator user = new Impersonator(LOGIN, DOMAIN, PASSWORD, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50))
    {
    }
}

そして、彼のクラスを追加します。

。NET(C#)ネットワーク資格情報による偽装

偽装ログオンにネットワーク資格情報が必要な場合は、私の例を使用できますが、さらにオプションがあります。

2

このソリューションを使用できます。 (nugetパッケージを使用)ソースコードはGithubで入手できます: https://github.com/michelcedric/UserImpersonation

詳細 https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/

0
Cedric Michel