Pinvoke NtOpenFile和NtQueryEaFile以便在C#中读取NTFS扩展属性

时间:2014-12-05 23:04:32

标签: c# pinvoke ntfs

我试图在C#中为扩展属性(而不是备用数据流!)编写一个简单的NTFS读取器函数。它将在稍后的某些PowerShell脚本中使用,所以我需要使用C#。

到目前为止,我收集了一些关于NtOpenFile的信息:

 [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct OBJECT_ATTRIBUTES
        {
            public Int32 Length;
            public IntPtr RootDirectory;
            public IntPtr ObjectName;
            public uint   Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;

        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct IO_STATUS_BLOCK
        {
            public uint status;
            public IntPtr information;
        }   

        [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = true)]
        public static extern int NtOpenFile(
            out  IntPtr handle,
            System.IO.FileAccess access,
            ref OBJECT_ATTRIBUTES objectAttributes,
            out IO_STATUS_BLOCK ioStatus,
            System.IO.FileShare share,
            uint openOptions
            );

但仍然没有NtQueryEaFile上的信息,也没有演示代码来调用它并编组其结果,谢谢你的帮助!

EDIT1 进一步了解这个新代码,但在调用NtQueryEaFile之后仍然停留在某个点“拒绝访问”。有什么想法吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System.ComponentModel;
using HANDLE = System.IntPtr;

namespace ConsoleApplication1
{
    class Program
    {
        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct OBJECT_ATTRIBUTES
        {
            public Int32 Length;
            public IntPtr RootDirectory;
            public IntPtr ObjectName;
            public uint   Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;

        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct IO_STATUS_BLOCK
        {
            public uint status;
            public IntPtr information;
        }

        [StructLayout(LayoutKind.Sequential, Pack = 0)]
        public struct UNICODE_STRING
        {
            public ushort Length;
            public ushort MaximumLength;
            public IntPtr Buffer;

        }


        [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = true)]
        public static extern uint NtOpenFile(
            out  IntPtr handle,
            System.IO.FileAccess access,
            ref OBJECT_ATTRIBUTES objectAttributes,
            out IO_STATUS_BLOCK ioStatus,
            System.IO.FileShare share,
            uint openOptions
            );


        [DllImport("ntdll.dll", ExactSpelling = true, SetLastError = true)]
        public static extern uint NtQueryEaFile(
            IntPtr handle,
            out IO_STATUS_BLOCK ioStatus,
            out IntPtr buffer,
            uint  length,
            bool retSingleEntry,
            IntPtr eaList,
            uint  eaListLength,
            IntPtr eaIndex,
            bool restartScan
            );

        [DllImport("ntdll.dll")]
        public static extern void RtlInitUnicodeString(
            out UNICODE_STRING DestinationString,
            [MarshalAs(UnmanagedType.LPWStr)] string SourceString);

        [DllImport("ntdll.dll")]
        public static extern uint RtlNtStatusToDosError(uint Status);

        [DllImport("kernel32.dll")]
        public static extern uint FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId,
            int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr Arguments);

        static void Main(string[] args)
        {
            UInt32 FILE_OPEN = 0x1;
            UInt32 OBJ_CASE_INSENSITIVE = 0x40;
            UInt32 FILE_READ_EA = 8;
            UInt32 FILE_RANDOM_ACCESS = 0x00000800;
            UInt32 FILE_DIRECTORY_FILE = 0x00000002;
            UInt32 FILE_NON_DIRECTORY_FILE = 0x00000040;
            UInt32 FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000;
            uint NT_SUCCESS = 0x0;
            bool restartScan = false;
            bool returnSingleEntry = false;

            IntPtr _RootHandle; //This will need to be initialized with the root handle, can use CreateFile from kernel32.dll
            _RootHandle = IntPtr.Zero;

            UNICODE_STRING unicodeString;
            RtlInitUnicodeString(out unicodeString, @"\??\C:\temp");
            IntPtr unicodeIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(unicodeString));
            Marshal.StructureToPtr(unicodeString, unicodeIntPtr, false);

            OBJECT_ATTRIBUTES objAttributes = new OBJECT_ATTRIBUTES();
            IO_STATUS_BLOCK ioStatusBlock = new IO_STATUS_BLOCK();
            //Microsoft.Win32.SafeHandles.SafeFileHandle hFile;
            HANDLE hFile;


            objAttributes.Length = System.Convert.ToInt32(Marshal.SizeOf(objAttributes));
            objAttributes.ObjectName = unicodeIntPtr;
            objAttributes.RootDirectory = _RootHandle;
            objAttributes.Attributes = OBJ_CASE_INSENSITIVE;
            objAttributes.SecurityDescriptor = IntPtr.Zero;
            objAttributes.SecurityQualityOfService = IntPtr.Zero;

            uint status = NtOpenFile(out hFile, FileAccess.Read, ref objAttributes, out ioStatusBlock, FileShare.Read, FILE_DIRECTORY_FILE | FILE_READ_EA | FILE_OPEN_FOR_BACKUP_INTENT);
            if (status != NT_SUCCESS)
                ExitWithError(status);           

            IntPtr buffer = Marshal.AllocHGlobal(65535);
            status = NtQueryEaFile(hFile, out ioStatusBlock, out buffer, System.Convert.ToUInt32(Marshal.SizeOf(buffer)), returnSingleEntry, IntPtr.Zero, 0, IntPtr.Zero, restartScan);
            if (status != NT_SUCCESS)
                ExitWithError(status);   

        }

        public static void ExitWithError(uint errorCode)
        {
            Console.WriteLine(GetSystemMessage(RtlNtStatusToDosError(errorCode)));
            Environment.Exit(1);
        }

        public static string GetSystemMessage(uint errorCode)
        {
            int capacity = 512;
            int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
            StringBuilder sb = new StringBuilder(capacity);
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, errorCode, 0,
                sb, sb.Capacity, IntPtr.Zero);
            int i = sb.Length;
            if (i > 0 && sb[i - 1] == 10) i--;
            if (i > 0 && sb[i - 1] == 13) i--;
            sb.Length = i;
            return sb.ToString();
        }

    }
}

EDIT2 在审核完此代码后:http://jbutera.net/mirror/git/alexpux/Cygwin/winsup/cygwin/ntea.cc我修改了以下内容:

NtOpenFile现在是:

[DllImport("ntdll.dll", ExactSpelling = true)]
        public static extern uint NtOpenFile(
            out  SafeFileHandle  handle,
            UInt32 access,
            ref OBJECT_ATTRIBUTES objectAttributes,
            out IO_STATUS_BLOCK ioStatus,
            System.IO.FileShare share,
            uint openOptions
            );

NtQueryEaFile现在是:

[DllImport("ntdll.dll", ExactSpelling = true)]
public static extern uint NtQueryEaFile(
    SafeFileHandle handle,
    out IO_STATUS_BLOCK ioStatus,
    out IntPtr buffer,
    uint  length,
    bool retSingleEntry,
    IntPtr eaList,
    uint  eaListLength,
    IntPtr eaIndex,
    bool restartScan
    );

现在调用NtOpenFile:

UInt32 FILE_OPEN = 0x1;
            UInt32 OBJ_CASE_INSENSITIVE = 0x40;
            UInt32 FILE_READ_EA = 8;
            UInt32 FILE_RANDOM_ACCESS = 0x00000800;
            UInt32 FILE_DIRECTORY_FILE = 0x00000002;
            UInt32 FILE_NON_DIRECTORY_FILE = 0x00000040;
            UInt32 FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000;
            UInt32 READ_CONTROL = 0x00020000;
            const UInt32 STATUS_NO_EAS_ON_FILE = 0xC0000052;

            uint status = NtOpenFile(out hFile, READ_CONTROL | FILE_READ_EA, ref objAttributes, out ioStatusBlock, FileShare.ReadWrite | FileShare.Delete, FILE_OPEN_FOR_BACKUP_INTENT);
            if (status != NT_SUCCESS)
                ExitWithError(status);           

            IntPtr buffer = Marshal.AllocHGlobal(65535);

            // status = NtQueryEaFile(fileHandle, &ioStatus, qbuf, sizeof(FILE_FULL_EA_INFORMATION), TRUE, NULL, 0, &QueryEAIndex, FALSE);
            status = NtQueryEaFile(hFile, out ioStatusBlock,out buffer, System.Convert.ToUInt32(Marshal.SizeOf(buffer)), returnSingleEntry, IntPtr.Zero, 0, IntPtr.Zero, restartScan);
            switch (status)
            {
                case STATUS_NO_EAS_ON_FILE:
                    Console.WriteLine("No EAs found");
                    break;

                case NT_SUCCESS:
                    Console.WriteLine("EAs found !");
                    break;

                default:
                    ExitWithError(status);
                    break;
            }                    

猜猜是什么?它的工作原理!嗯..几乎......读取没有EAs的目录会抛出STATUS_NO_EAS_ON_FILE。但是使用EA读取目录会抛出STATUS_BUFFER_TOO_SMALL(根据http://msdn.microsoft.com/fr-fr/library/cc704588.aspx),所以我的缓冲区定义/分配确实有一些pbr: - /

1 个答案:

答案 0 :(得分:0)

MSDN上提供了NtOpenFile的文档。对于NtQueryEaFile,我认为您可以参考Windows驱动程序工具包中的ZwQueryEaFile例程(see on MSDN)。大多数Zw...例程复制本机NT API调用(Nt...),因此签名应该相同。

P {Invoke for NtQueryEaFile(来自ZwQueryEaFile):

[DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
public static extern UInt32 NtQueryEaFile(
    [In] SafeFileHandle FileHandle,
    [Out] out IO_STATUS_BLOCK IoStatusBlock,
    [Out] out IntPtr Buffer,
    [In] UInt32 Length,
    [In] Boolean ReturnSingleEntry,
    [In, Optional] IntPtr EaList,
    [In] UInt32 EaListLength,
    [In, Optional] UInt32 EaIndex,
    [In] Boolean RestartScan
);