C#WriteFile()停止在USB驱动器上的扇区242写入

时间:2012-08-22 21:00:22

标签: c# file-io deviceiocontrol

我编写了以下代码,将0xFF写入USB存储设备上的所有字节。由于某种原因,WriteFile()调用在扇区242开始出错。我在两个独立的USB存储设备上完成了这个操作,然后在十六进制编辑器中检查设备。扇区242似乎是FAT16格式化设备上文件分配表的开始,以及NTFS设备上引导区域的开始。我确信它在这些确切的位置错误并不是巧合,但是我不知道如何改变这种行为。我在WriteFile失败时收到的HRESULT是-2147024891,即E_ACCESSDENIED。有谁知道可能导致问题的原因是什么?

注意:如果您要在本地系统上运行此代码,请非常小心,因为我已经硬编码了USB设备的物理设备ID。请务必使用您尝试写入的设备更新deviceId变量。你不想破坏你的硬盘。

    public enum EMoveMethod : uint
    {
        Begin = 0,
        Current = 1,
        End = 2
    }

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern uint SetFilePointer([In] SafeFileHandle hFile, [In] long lDistanceToMove, [Out] out int lpDistanceToMoveHigh, [In] EMoveMethod dwMoveMethod);

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    [DllImport("kernel32", SetLastError = true)]
    internal extern static int ReadFile(SafeFileHandle handle, byte[] bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped_MustBeZero);

    [DllImport("kernel32.dll", SetLastError = true)]
    internal extern static int WriteFile(SafeFileHandle handle, byte[] bytes, int numBytesToWrite, out int numBytesWritten, IntPtr overlapped_MustBeZero);

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool DeviceIoControl(SafeFileHandle hDevice, uint dwIoControlCode, byte[] lpInBuffer, int nInBufferSize, byte[] lpOutBuffer, int nOutBufferSize, out int lpBytesReturned, IntPtr lpOverlapped);

    [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
    private static extern bool CloseHandle(SafeFileHandle handle);

public void wipeDisk()
{
        const uint OPEN_EXISTING = 3;
        const uint GENERIC_WRITE = (0x40000000);
        const uint FSCTL_LOCK_VOLUME = 0x00090018;
        const uint FSCTL_UNLOCK_VOLUME = 0x0009001c;
        const uint FSCTL_DISMOUNT_VOLUME = 0x00090020;

        bool success = false;
        int intOut;
        string deviceId = @"\\.\PHYSICALDRIVE2";
        long DiskSize = 2056320000;

        SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
        if (diskHandle.IsInvalid)
        {
            Console.WriteLine(deviceId + " open error.");
            return;
        }

        Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened.");

        success = DeviceIoControl(diskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
        if (!success)
        {
            Console.WriteLine(deviceId + " lock error.");
            CloseHandle(diskHandle);
            return;
        }

        Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked.");

        success = DeviceIoControl(diskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
        if (!success)
        {
            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error.");
            DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
            CloseHandle(diskHandle);
            return;
        }

        Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unmounted.");

        int numBytesPerSector = 512;
        long numTotalSectors = DiskSize / 512;

        byte[] junkBytes = new byte[512];
        for (int x = 0; x < 512; x++)
        {
            junkBytes[x] = 0xFF;
        }

        for (long sectorNum = 0; sectorNum < numTotalSectors; sectorNum++)
        {
            int numBytesWritten = 0;
            int moveToHigh;

            uint rvalsfp = SetFilePointer(diskHandle, sectorNum * numBytesPerSector, out moveToHigh, EMoveMethod.Begin);

            Console.WriteLine("File pointer set " + Marshal.GetHRForLastWin32Error().ToString() + ": " + (sectorNum * numBytesPerSector).ToString());

            int rval = WriteFile(diskHandle, junkBytes, junkBytes.Length, out numBytesWritten, IntPtr.Zero);

            if (numBytesWritten != junkBytes.Length)
            {
                Console.WriteLine("Write error on track " + sectorNum.ToString() + " from " + (sectorNum * numBytesPerSector).ToString() + "-" + moveToHigh.ToString() + " " + Marshal.GetHRForLastWin32Error().ToString() + ": Only " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written.");
                break;
            }
            else
            {
                Console.WriteLine("Write success " + Marshal.GetHRForLastWin32Error().ToString() + ": " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written.");
            }
        }

        success = DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
        if (success)
        {
            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked.");
        }
        else
        {
            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString());
        }

        success = CloseHandle(diskHandle);
        if (success)
        {
            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed.");
        }
        else
        {
            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString());
        }
}

修改/更新

使用第三方工具对USB设备进行低级擦除后,我能够成功运行。驱动器完全归零后,我能够成功写入设备。一旦识别出有效的fat或ntfs文件系统并使用

,似乎windows就锁定了设备。
    const uint FSCTL_LOCK_VOLUME = 0x00090018;
    const uint FSCTL_DISMOUNT_VOLUME = 0x00090020;

与DeviceIoControl配对似乎没有覆盖设备上的锁定窗口。

有没有人知道如何在具有有效文件系统的驱动器上使用DeviceIoControl在Windows中成功锁定可移动USB设备?

我使用了几个第三方工具来完成我正在尝试的工作并且它们成功运行。我知道这是可能的,但我读过的所有MSDN文档都没有帮助解决问题。

编辑/更新2

这取自http://msdn.microsoft.com/en-us/library/ff551353.aspx

“应用程序需要锁定卷,卸载卷或两者,然后才能发出DASD I / O.这是Windows Vista的新功能,用于解决潜在的恶意技术。

  1. 文件系统将阻止对磁盘保留部分的所有写操作。在这种情况下,那些保留部分包括MBR和两个FAT区域。要阻止这些区域,您需要通过发送FSCTL_LOCK_VOLUME来锁定卷。您必须在执行实际写入操作的同一卷句柄上发出此结构。如果存在打开的文件句柄,则此请求可能会失败。在这种情况下,应用程序可以通过发出FSCTL_DISMOUNT_VOLUME强制卸载文件系统。但是,在文件句柄关闭之前,实际上不会卸载卷。在此之前,应用程序可以使用当前打开的相同文件句柄继续发出DASD I / O.

  2. 文件系统已知卷空间之外的扩展区域将阻止写入操作。要允许对此区域执行写入操作,必须在卷句柄上发出FSCTL_ALLOW_EXTENDED_DASD_IO。

  3. 您可以使用Win32 API例程DeviceIoControl来发布所有以前的FSCTS。“

    我相信这正是我们在上面的代码中实现的,但似乎没有正常工作。我们正在处理并锁定和卸载设备,以便我们能够正确地写入受保护区域吗?

    编辑/更新3

    好的,这是打开磁盘和列的当前顺序.. 锁定,卸载等方法只是我们认为错误的顺序。

    SafeFileHandle volumeHandle = CreateFile("\\.\E:",...);
    LockVolume(volumeHandle);
    DismountVolume(volumeHandle);
    SafeFileHandle diskHandle = CreateFile("\\.\PHYSICALDRIVE1"...);
    WriteStuff(diskHandle);
    //Fails...
    UnlockVolume(volumeHandle);
    CloseVolume(volumeHandle);
    CloseDisk(diskHandle);
    

    我仍然得到相同的结果,它只在磁盘被删除时才有效。

5 个答案:

答案 0 :(得分:5)

此处磁盘驱动器之间存在混淆。

如果您想要完全访问磁盘(在您使用\\.\PHYSICALDRIVE时就是这种情况),则必须锁定所有已安装的卷,基本上都是物理磁盘的分区(即驱动器

不要在FSCTL_LOCK_VOLUME返回的句柄上使用CreateFile("\\.\PHYSICALDRIVE"...),而是使用{获取每个已装入卷(这是一个驱动器,而不是物理磁盘)的句柄{1}}模式。

您可以使用string.Replace("\\\\.\\{0}:", DriveLetter)获取给定物理磁盘的已装入卷列表(最终,您需要一个字母列表)。


编辑:

来自MSDN

  

如果满足以下条件之一,则磁盘句柄上的写入将成功   条件是真的:

     

要写入的部门不属于   卷的范围。

     

要写入的扇区属于已安装的扇区   音量,但您已明确锁定或卸下音量   使用FSCTL_LOCK_VOLUME或FSCTL_DISMOUNT_VOLUME。

     

行业   写入属于没有挂载文件系统的卷   比RAW。

基本上,你应该做的是:

  • 获取每个卷的句柄
  • 在每个卷上使用IOCTL_DISK_GET_DRIVE_LAYOUT FSCTL_LOCK_VOLUME。如果卷中没有使用文件(即任何进程没有打开任何文件的句柄),FSCTL_DISMOUNT_VOLUME就足够了
  • 获取物理磁盘的句柄
  • 写入物理磁盘
  • 关闭两个手柄。关闭音量手柄将释放锁定。

还要确保您使用管理员权限(提升过程)运行您的应用程序。

答案 1 :(得分:1)

我猜你正在使用Windows Vista或更晚。操作系统将阻止任何直接写入这些扇区的尝试,因此您需要先进行锁定。更多相关信息:

http://msdn.microsoft.com/en-us/library/ff551353.aspx

此外,只需检查SO即可发布此帖:

CreateFile: direct write operation to raw disk "Access is denied" - Vista, Win7

那里的调查信息可能会有所帮助,HTH ......

答案 2 :(得分:1)

修改

我已编辑此答案以反映ken2k的建议。

ken2k的建议确实解决了我遇到的问题。我不确定为什么我以前尝试使用这种方法是不成功的,但是我刚刚重新访问/调整了我的代码,这种方法似乎确实正常工作。

以下是我用来解决此问题的步骤:

  • 获取物理磁盘的句柄
  • 获取物理磁盘上每个逻辑驱动器的句柄
  • 锁定物理磁盘上的每个驱动器
  • 卸下物理磁盘上的每个驱动器
  • 锁定物理磁盘(可选)
  • 卸下物理磁盘(可选)
  • 使用物理磁盘句柄将整个物理磁盘清零
  • 解锁每个逻辑驱动器
  • 解锁物理磁盘(仅当您选择锁定磁盘时)
  • 关闭逻辑驱动器句柄
  • 关闭物理磁盘句柄

注意:如果您希望在不终止程序的情况下进行背靠背磁盘操作,并且已使用FSCTL_DISMOUNT_VOLUME功能,则需要使用类似于以下内容的方式“重新安装”磁盘:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive");

System.IO.DriveInfo.GetDrives();

要在尝试锁定每个逻辑驱动器时将逻辑驱动器ID映射到物理磁盘ID,请使用以下代码将逻辑驱动器标签链接到物理磁盘标签:

    List<string> driveLetters = new List<string>();
    string deviceId = @"\\.\PHYSICALDRIVE1";
    string queryString = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + deviceId + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
    ManagementObjectSearcher diskSearcher = new ManagementObjectSearcher("root\\CIMV2", queryString);
    ManagementObjectCollection diskMoc = diskSearcher.Get();
    foreach (ManagementObject diskMo in diskMoc)
    {
        queryString = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + diskMo["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition";
        ManagementObjectSearcher driveSearcher = new ManagementObjectSearcher("root\\CIMV2", queryString);

        ManagementObjectCollection driveMoc = driveSearcher.Get();
        foreach (ManagementObject driveMo in driveMoc)
        {
            driveLetters.Add("\\\\.\\" + driveMo["DeviceID"].ToString());
        }
    }

例如,如果物理磁盘标签是\。\ PHYSICALDRIVE1并且它包含一个带有驱动器号“E”的逻辑驱动器,则上面的代码将映射\。\ E:到\。\ PHYSICALDRIVE1。

根据ken2k的建议,也可以使用IOCTL_DISK_GET_DRIVE_LAYOUT功能完成此映射。

希望这对其他人有用!

感谢大家帮助我指出正确的方向!

答案 3 :(得分:0)

对于此命令,我确实运行并检查了它。 SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_WRITE, 0/*Here*/ , IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

将GENERIC_WRITE参数的第一个零下一个平均更改为3 FILE_SHARE_READ | FILE_SHARE_WRITE(1 | 2)获得良好的结果。 我将其和设备ID更改为驱动器名称相同\。\ f:我的USB驱动器名称。最后,我用这段代码代替: SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_WRITE, 3 , IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); 祝你好运

答案 4 :(得分:0)

im测试遵循代码,需要修复我的usb磁盘以隐藏rootkit病毒。所以写这段代码:

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RootKeyremover
{
    public partial class Form1 : Form
    {
        public enum EMoveMethod : uint
        {
            Begin = 0,
            Current = 1,
            End = 2
        }

        [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint SetFilePointer([In] SafeFileHandle hFile, [In] long lDistanceToMove, [Out] out int lpDistanceToMoveHigh, [In] EMoveMethod dwMoveMethod);

        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);

        [DllImport("kernel32", SetLastError = true)]
        internal extern static int ReadFile(SafeFileHandle handle, byte[] bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped_MustBeZero);

        [DllImport("kernel32.dll", SetLastError = true)]
        internal extern static int WriteFile(SafeFileHandle handle, byte[] bytes, int numBytesToWrite, out int numBytesWritten, IntPtr overlapped_MustBeZero);

        [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool DeviceIoControl(SafeFileHandle hDevice, uint dwIoControlCode, byte[] lpInBuffer, int nInBufferSize, byte[] lpOutBuffer, int nOutBufferSize, out int lpBytesReturned, IntPtr lpOverlapped);

        [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
        private static extern bool CloseHandle(SafeFileHandle handle);

        public Form1()
        {
            InitializeComponent();
        }

                   
        public void wipeDisk()
        {
            const short FILE_ATTRIBUTE_NORMAL = 0x80;
            const short INVALID_HANDLE_VALUE = -1;
            const uint GENERIC_READ = 0x80000000;
            const uint OPEN_EXISTING = 3;
            const uint GENERIC_WRITE = (0x40000000);
            const uint FSCTL_LOCK_VOLUME = 0x00090018;
            const uint FSCTL_UNLOCK_VOLUME = 0x0009001c;
            const uint FSCTL_DISMOUNT_VOLUME = 0x00090020;

            bool success = false;
            int intOut;
            //@"\\.\PHYSICALDRIVE2"
            string deviceId = @"\\.\" + comboBox1.Text.Substring(0,2);
            long DiskSize = 2056320000;

            SafeFileHandle diskHandle = CreateFile(deviceId, GENERIC_READ | GENERIC_WRITE, 3, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            if (diskHandle.IsInvalid)
            {
                Console.WriteLine(deviceId + " open error.");
                return;
            }

            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": opened.");

            success = DeviceIoControl(diskHandle, FSCTL_LOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
            if (!success)
            {
                Console.WriteLine(deviceId + " lock error.");
                CloseHandle(diskHandle);
                return;
            }

            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": locked.");

            success = DeviceIoControl(diskHandle, FSCTL_DISMOUNT_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
            if (!success)
            {
                Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": dismount error.");
                DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
                CloseHandle(diskHandle);
                return;
            }

            Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unmounted.");

            int numBytesPerSector = 512;
            long numTotalSectors = DiskSize / 512;

            byte[] junkBytes = new byte[512];

            
            int k =0 ;
            IntPtr l= (IntPtr)0 ;
            SetFilePointer(diskHandle, 0, out k, EMoveMethod.Begin);
            ReadFile(diskHandle, junkBytes, (int)512,out k,l);
            //3e 17e 1f1-1fb
            //for (int x = 0x3e; x < 0x17e; x++)
            //{
            //    junkBytes[x] = 0x00;
            //}
            //for (int x = 0x1f1; x < 0x1fb; x++)
            //{
            //    junkBytes[x] = 0x00;
            //}
            for (int x = 0x1e1; x < 0x1ee; x++)
            {
                junkBytes[x] = 0x00;
            }

            //diskHandle = CreateFile(deviceId, GENERIC_WRITE, 3, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            for (long sectorNum = 0; sectorNum < 1; sectorNum++)
            {
                int numBytesWritten = 0;
                int moveToHigh;

                uint rvalsfp = SetFilePointer(diskHandle, sectorNum * numBytesPerSector, out moveToHigh, EMoveMethod.Begin);

                Console.WriteLine("File pointer set " + Marshal.GetHRForLastWin32Error().ToString() + ": " + (sectorNum * numBytesPerSector).ToString());

                int rval = WriteFile(diskHandle, junkBytes, junkBytes.Length, out numBytesWritten, IntPtr.Zero);

                if (numBytesWritten != junkBytes.Length)
                {
                    Console.WriteLine("Write error on track " + sectorNum.ToString() + " from " + (sectorNum * numBytesPerSector).ToString() + "-" + moveToHigh.ToString() + " " + Marshal.GetHRForLastWin32Error().ToString() + ": Only " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written.");
                    break;
                }
                else
                {
                    Console.WriteLine("Write success " + Marshal.GetHRForLastWin32Error().ToString() + ": " + numBytesWritten.ToString() + "/" + junkBytes.Length.ToString() + " bytes written.");
                }
            }

            success = DeviceIoControl(diskHandle, FSCTL_UNLOCK_VOLUME, null, 0, null, 0, out intOut, IntPtr.Zero);
            if (success)
            {
                Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlocked.");
            }
            else
            {
                Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": unlock error: " + Marshal.GetHRForLastWin32Error().ToString());
            }

            success = CloseHandle(diskHandle);
            if (success)
            {
                Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": handle closed.");
            }
            else
            {
                Console.WriteLine(deviceId + " " + Marshal.GetHRForLastWin32Error().ToString() + ": close handle error: " + Marshal.GetHRForLastWin32Error().ToString());
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            wipeDisk();
            MessageBox.Show("اتمام عملیات پاک سازی");
        }

        private void comboBox1_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                if (drive.DriveType == DriveType.Removable)
                {
                    comboBox1.Items.Add(drive.Name);
                }
            }
            if (comboBox1.Items.Count <= 0)
                button2.Enabled = false;
            else
            {
                button2.Enabled = true;
                comboBox1.SelectedIndex = 0;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1_Click(null, null);

        }
    }
}