次の方法で共有


ASP.NET アプリケーションに偽装を実装する

この記事では、ASP.NET アプリケーションで偽装を実装するさまざまな方法について説明します。

元の製品バージョン: ASP.NET
元の KB 番号: 306158

まとめ

この記事では、Web.config ファイルを変更し、コードの特定のセクションを実行して偽装を実装する方法について説明します。

これは、次の Microsoft .NET Framework クラス ライブラリ名前空間を参照します。

  • System.Web.Security
  • System.Security.Principal
  • System.Runtime.InteropServices

次のコードを使用して、スレッドが実行しているユーザーを特定できます。

System.Security.Principal.WindowsIdentity.GetCurrent().Name

IIS で認証されたアカウントまたはユーザーを偽装する

ASP.NET アプリケーション内のすべてのページに対するすべての要求で、インターネット インフォメーション サービス (IIS) 認証ユーザーの権限を借用するには、このアプリケーションの Web.config ファイルに<identity> タグを含め、偽装属性を true に設定する必要があります。 例えば次が挙げられます。

<identity impersonate="true" />

ASP.NET アプリケーションのすべての要求に対して特定のユーザーを偽装する

ASP.NET アプリケーションのすべてのページのすべての要求に対して特定のユーザーの権限を借用するには、そのアプリケーションの Web.config ファイルの<identity> タグにuserName属性とpassword属性を指定します。 例えば次が挙げられます。

<identity impersonate="true" userName="<accountName>" password="<credentialPlaceholder>"/>

Note

スレッド上の特定のユーザーを偽装するプロセスの ID には、オペレーティング システム特権の一部として Act が必要です。 既定では、Aspnet_wp.exe プロセスは ASPNET という名前のコンピューター アカウントで実行されます。 ただし、このアカウントには、特定のユーザーを偽装するために必要な特権はありません。 特定のユーザーを偽装しようとすると、エラー メッセージが表示されます。 この情報は、.NET Framework 1.0 にのみ適用されます。 この特権は、.NET Framework 1.1 では必要ありません。

この問題を回避するには、次のいずれかの方法を使用します。

  • オペレーティング システムの一部として Act ASPNET アカウント (最小特権アカウント) に特権を付与します。

    Note

    この方法を使用して問題を回避することはできますが、Microsoft ではこの方法をお勧めしません。

  • Aspnet_wp.exe プロセスが実行されるアカウントを、Machine.config ファイルの <processModel> 構成セクションのシステム アカウントに変更します。

コードで認証ユーザーを偽装する

コードの特定のセクションを実行する場合にのみ、認証ユーザー (User.Identity) を偽装するには、次のコードを使用します。 この方法では、認証ユーザー ID が WindowsIdentity型である必要があります。

  • Visual Basic .NET

    Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
    Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity
    currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
    impersonationContext = currentWindowsIdentity.Impersonate()
    'Insert your code that runs under the security context of the authenticating user here.
    impersonationContext.Undo()
    
  • Visual C# .NET

    System.Security.Principal.WindowsImpersonationContext impersonationContext;
    impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
    //Insert your code that runs under the security context of the authenticating user here.
    impersonationContext.Undo();
    

コードで特定のユーザーを偽装する

コードの特定のセクションを実行するときにのみ特定のユーザーを偽装するには、次のコードを使用します。

Visual Basic .NET

<%@ Page Language="VB" %>
<%@ Import Namespace = "System.Web" %>
<%@ Import Namespace = "System.Web.Security" %>
<%@ Import Namespace = "System.Security.Principal" %>
<%@ Import Namespace = "System.Runtime.InteropServices" %>

<script runat=server>
Dim LOGON32_LOGON_INTERACTIVE As Integer = 2
Dim LOGON32_PROVIDER_DEFAULT As Integer = 0
Dim impersonationContext As WindowsImpersonationContext

Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, _
                        ByVal lpszDomain As String, _
                        ByVal lpszPassword As String, _
                        ByVal dwLogonType As Integer, _
                        ByVal dwLogonProvider As Integer, _
                        ByRef phToken As IntPtr) As Integer

Declare Auto Function DuplicateToken Lib "advapi32.dll" ( _
                        ByVal ExistingTokenHandle As IntPtr, _
                        ByVal ImpersonationLevel As Integer, _
                        ByRef DuplicateTokenHandle As IntPtr) As Integer

Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long

Public Sub Page_Load(ByVal s As Object, ByVal e As EventArgs)
    If impersonateValidUser("username", "___domain", "password") Then
         'Insert your code that runs under the security context of a specific user here.
         undoImpersonation()
    Else
         'Your impersonation failed. Therefore, include a fail-safe mechanism here.
    End If
End Sub

Private Function impersonateValidUser(ByVal userName As String, _
ByVal ___domain As String, ByVal password As String) As Boolean

    Dim tempWindowsIdentity As WindowsIdentity
    Dim token As IntPtr = IntPtr.Zero
    Dim tokenDuplicate As IntPtr = IntPtr.Zero
    impersonateValidUser = False

    If RevertToSelf() Then
        If LogonUserA(userName, ___domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
            If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
                tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
                impersonationContext = tempWindowsIdentity.Impersonate()
                If Not impersonationContext Is Nothing Then
                    impersonateValidUser = True
                End If
            End If
        End If
    End If
    If Not tokenDuplicate.Equals(IntPtr.Zero) Then
        CloseHandle(tokenDuplicate)
    End If
    If Not token.Equals(IntPtr.Zero) Then
        CloseHandle(token)
    End If
End Function

Private Sub undoImpersonation()
    impersonationContext.Undo()
End Sub
</script>

Visual C# .NET

<%@ Page Language="C#"%>
<%@ Import Namespace = "System.Web" %>
<%@ Import Namespace = "System.Web.Security" %>
<%@ Import Namespace = "System.Security.Principal" %>
<%@ Import Namespace = "System.Runtime.InteropServices" %>

<script runat=server>
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

[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 void Page_Load(Object s, EventArgs e)
{
    if(impersonateValidUser("username", "___domain", "password"))
    {
        //Insert your code that runs under the security context of a specific user here.
        undoImpersonation();
    }
    else
    {
        //Your impersonation failed. Therefore, include a fail-safe mechanism here.
    }
}

private bool impersonateValidUser(String userName, String ___domain, String password)
{
    WindowsIdentity tempWindowsIdentity;
    IntPtr token = IntPtr.Zero;
    IntPtr tokenDuplicate = IntPtr.Zero;

    if(RevertToSelf())
    {
        if(LogonUserA(userName, ___domain, 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 true;
                }
            }
        }
    }
    if(token!= IntPtr.Zero)
        CloseHandle(token);
    if(tokenDuplicate!=IntPtr.Zero)
        CloseHandle(tokenDuplicate);
    return false;
}

private void undoImpersonation()
{
    impersonationContext.Undo();
}
</script>

Aspnet_wp.exe プロセスが Windows 2000 ベースのコンピューターで実行されている場合、スレッドで特定のユーザーを偽装するプロセスの ID には、オペレーティング システムの一部としてAct 権限が必要です。 Aspnet_wp.exe プロセスが Windows XP ベースのコンピューターまたは Windows Server 2003 ベースのコンピューターで実行されている場合はオペレーティング システムの一部としてAct 特権は必要ありません。 既定では、Aspnet_wp.exe プロセスは ASPNET という名前のコンピューター アカウントで実行されます。 ただし、このアカウントには、特定のユーザーを偽装するために必要な特権はありません。 特定のユーザーを偽装しようとすると、エラー メッセージが表示されます。

この問題を回避するには、次のいずれかの方法を使用します。

  • オペレーティング システムの一部として Act ASPNET アカウントに特権を付与します。

    Note

    この問題を回避するには、この方法はお勧めしません。

  • Aspnet_wp.exe プロセスが実行されるアカウントを、Machine.config ファイルの <processModel> 構成セクションのシステム アカウントに変更します。

関連情報

ASP.NET セキュリティの概要