2009-03-31 6 views
3

現在のIPrincipalがアクセスできるファイルとディレクトリには、Directory.GetDirectories()メソッドとDirectory.GetFiles()メソッドを使用してアクセスする必要があります。プロセス自体はNETWORK SERVICEとして実行されているため、これらの呼び出しの間、プリンシパルを(IPrincipal経由で)現在のユーザーに変更する必要があります。IPrincipalを使用したファイルとディレクトリのセキュリティ

ファイルアクセスの前にThread.CurrentPrincipalを新しいIPrincipalに変更しようとしましたが、違いはありません。

何か他に何かできますか、それとも何か不足していますか?

+0

私はそれがIPrincipal –

答えて

5

Windows偽装は、ログインの詳細を使用してユーザートークンを取得することでこの問題を解決します。このトークンを使用してWindowsIdentityを取得し、次にそれを使用して偽装コンテキストを生成することができます。このコンテキストスコープ内で、ファイルシステムに偽装されたユーザーとしてアクセスできます。

もちろん、このアプローチを使用するには、ユーザー名とパスワードを保存する必要があります。

まず、Windowsからのユーザートークンを取得するために必要なWindows APIを定義します。

internal class WindowsAPI 
{ 
    public const int LOGON32_PROVIDER_DEFAULT = 0; 
    public const int LOGON32_LOGON_INTERACTIVE = 2; 

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

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

その後、WindowsIdentityをAQUIREこれらのAPIを使用します。

private WindowsIdentity GetIdentity(string userName, string password) 
{ 
    _userToken = IntPtr.Zero; 

    if (!WindowsAPI.LogonUser(
     userName, 
     AbbGrainDomain, 
     password, 
     WindowsAPI.LOGON32_LOGON_INTERACTIVE, WindowsAPI.LOGON32_PROVIDER_DEFAULT, 
     ref _userToken 
    )) 
    { 
     int errorCode = Marshal.GetLastWin32Error(); 
     throw new System.ComponentModel.Win32Exception(errorCode); 
    } 

    return new WindowsIdentity(_userToken); 
} 

そして最後に、このIDを使用偽装コンテキストを生成します。

public List<string> GetDirectories(string searchPath) 
{ 
    using (WindowsImpersonationContext wic = GetIdentity().Impersonate()) 
    { 
     var directories = new List<string>(); 

     var di = new DirectoryInfo(searchPath); 
     directories.AddRange(di.GetDirectories().Select(d => d.FullName)); 

     return directories; 
    } 
} 

最後に、偽装コンテキストをクリーンアップすることが重要ですウィンドウはID_posableパターンを使用して、格納された_userTokenを使用して処理します。

if (_userToken != IntPtr.Zero) 
    WindowsAPI.CloseHandle(_userToken); 
0

私はあなたがこれを正しい方法で行っているとは思わない。偽装の使用を検討する必要があります。たとえば、これを行う方法についてはthisチュートリアルをご覧ください。

-1

DllImportとLogonUser win32 APIを使用して、別のユーザーを偽装することができます。

関連する問題