File and Directory Security Using IPrincipal

I need to access the files and directories that the current IPrincipal has access to using the Directory.GetDirectories () and Directory.GetFiles () methods without specifying other files. The process itself starts as NETWORK SERVICE, so it must change the principal to the current user (via IPrincipal) for the duration of these calls.

I tried changing Thread.CurrentPrincipal to a new IPrincipal before the file access part, but it doesn't seem to matter.

Is there anything else I can do, or am I missing something?

+3
source share
3 answers

Windows , , . WindowsIdentity, . .

, .

Windows API, Windows:

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

API WindowsIdentity:

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

, , :

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

, IDisposable, _userToken:

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

, . . , , .

0

You can use the DllImport and winonUser win32 APIs to impersonate another user.

-1
source

Source: https://habr.com/ru/post/1705691/


All Articles