Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateFile in Kernel32.dll does not allow me to open a physical disk

I am trying to use the following code to get the MBR from PhysicalDrive0:

private static byte[] ReadMbr(string lpFileName)
{
   byte[] mbr = new byte[512];

   using (SafeFileHandle drive = CreateFile(
         lpFileName: lpFileName,
         dwDesiredAccess: (uint) EFileAccess.GenericRead, //DO NOT MODIFY THE MBR!!!
         dwShareMode: (uint)EFileShare.Write | (uint)EFileShare.Read | (uint)EFileShare.Delete,
         SecurityAttributes: IntPtr.Zero,
         dwCreationDisposition: (uint) ECreationDisposition.OpenAlways,
         dwFlagsAndAttributes: (uint)EFileAttributes.System,
         hTemplateFile: IntPtr.Zero))
   {
      if (drive.IsInvalid)
         throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error());

      //Get the 1st 512 bytes of the volume (MBR)
      using (FileStream stream = new FileStream(drive, FileAccess.Read))
      {
         stream.Read(mbr, 0, 512);
      }
   }

   return mbr;
}

I have tried passing

  • \\.\PhysicalDisk0
  • \\.\PhysicalDrive0
  • \\.\PhysicalDisk0:
  • \\.\PhysicalDrive0

and none of them work. I am running it as administrator. I can also get \\.\C: to work and display the VBR without any issues.

For the record:

-I am running Windows Server 2008 R2.

References

  • MSDN: CreateFile function
  • MSDN: Naming Files, Paths, and Namespaces
like image 353
Dan Balthaser Avatar asked Nov 26 '10 19:11

Dan Balthaser


1 Answers

From the CreateFile() documentation:

The following requirements must be met for such a call to succeed:

  • The caller must have administrative privileges. For more information, see Running with Special Privileges.
  • The dwCreationDisposition parameter must have the OPEN_EXISTING flag.
  • When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag.

You might want to try passing ECreationDisposition.OpenExisting in dwCreationDisposition.

like image 163
Frédéric Hamidi Avatar answered Oct 09 '22 01:10

Frédéric Hamidi