Click here to Skip to main content
12,697,779 members (27,089 online)
Click here to Skip to main content
Add your own
alternative version


106 bookmarked

Reading and Writing to Raw Disk Sectors

, 2 Aug 2008 GPL3
Rate this:
Please Sign up or sign in to vote.
Bypasses upper filter of class disk driver for reading and writing to disk


This is a tool to read and write raw disk sectors on Windows systems (NT5.0, 5.1 kernels)
Inspiration to write this tool came to me when I had my laptop infected with some malware which was sitting on top of disk class driver as an upper filter and not allowing me to write to disk sectors using user mode disk editing tools like WinHex.

After a few days, I thought I should write a utility to read and write raw disk sectors by directly
communicating with disk class driver.


To understand this article, one should have knowledge of C Programming and Windows Driver Programming.

We will go through the following topics to understand the utility in a better way:

  1. Device stack for storage drivers
  2. Enumerating device objects representing disks and partitions
  3. How to read/write to sectors

1. Device Stack for Storage Drivers

Microsoft provides generic storage drivers for managing the storage on a logical level and thus abstracting hardware details from upper level file system and other file drivers. This is called disk class driver (a driver to handle disk class of hardware, i.e. "disk.sys").

Similarly to handle SCSI, IDE hardware devices, Microsoft provides generic port interface drivers to which drivers supplied by specific vendors for their disk devices can be dynamically linked.

E.g. scsiport.sys (old interface) storport.sys (new interface) is used as an interface to SCSI port while Pciidex.sys is used as an interface to IDE port.

2. Enumerating Device Objects Representing Disks and Partitions

There is a question which needs to be answered first.

How does the OS come to know that a harddisk has been attached to the system?

Whenever a new disk device is attached to the system, SCSI and IDE port drivers create device object (although PCI driver is the first one which comes into the picture) to represent a SCSI/IDE device and inform I/O manager about it. I/O manager in turn queries the devices to know their device id and vendor id. Depending on dev id and vendor id, I/O manager decides (through registry or INF file mechanism) which driver is suitable to handle this device (driver supplied by vendor) and loads the hardware device driver which creates device objects representing the Functions device objects for the device and attaches itself to lower devices created by respective port drivers.

I/O manager informs disk class driver (disk.sys) of new disks added into the system. Disk class driver then creates the device objects representing the raw disks.

If a valid partition is present on the system, then it creates device objects for the respective partitions too.

E.g. Device objects created by disk class driver are as follows:

  • \Device\Harddisk0\DR(0) --> Represents Raw Harddisk 0
  • \Device\Harddisk0\DP(1)0x7e000-0x7ff50c00+2 --> Represents partition 2 of disk 0

The first hexadecimal digit shows the start and thsecond shows the length of partition.

That means all the device objects representing disks and partitions are chained in driver object of disk class driver (i.e. disk.sys).

Now to enumerate the device objects created, you first need to have access to the driver object of disk class driver.

The solution is to use undocumented Object management kernel function "ObReferenceObjectByName" prototype:

NTSTATUS ObReferenceObjectByName(
        PVOID *Object); 

The first argument is a Unicode string, i.e. "\Driver\disk", object receives the pointer to the DRIVER_OBJECT of disk.sys.

From DRIVER_OBJECT, you can enumerate all the device objects created by disk class driver and store pointer to device objects responsible for raw disks and partitions. The following snippet will clear the things:

// DeviceType 7 corresponds to FILE_DISK_DEVICE Type Device Object and

 // It should have name too that's why Flags checks for 0x40 (DO_DEVICE_HAS_NAME )

                if (pDeviceObject->DeviceType == 7
                        && (pDeviceObjectTemp->Flags & 0x40))

3. How to Read/Write to Sectors

Once you have pointers to device objects for raw disks and partitions, reading and writing to those raw disks/partitions is not a difficult thing. You only have to do a IoCallDriver on the respective device object with IRP_MJ_READ/IRP_MJ_WRITE function codes initialized in the IRPs.

The following code will make things clear:


PDEVICE_OBJECT pDevObj; //Device object representing disk/partition

KEVENT Event; 

// Trying to read some arbitrary sector number 1169944 and 
// by default assuming sector size 

// 512 



        lDiskOffset.QuadPart = 1169944*512;
        sBuf = ExAllocatePool(NonPagedPool, size);
        if (!sBuf) {
        KeInitializeEvent(&Event, NotificationEvent, FALSE);
        memset(sBuf, '0x00', size);
        pIrp = IoBuildSynchronousFsdRequest(IRP_MJ_WRITE/*IRP_MJ_READ*/, 
			pDevObj, sBuf, size, &lDiskOffset, &Event, &ioStatus);
        if (!pIrp) {
        status = IoCallDriver(pDevObj, pIrp);

        if (status == STATUS_PENDING) {
            KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE,    NULL);
            status = ioStatus.Status;


Given above is just a sample code for sending a write operation to sector number 1169944.

Points of Interest

While writing the code, I was just doing a READ operation for verifying my results. I didn't take care while passing data buffer for write operations in the design (Please see driver code for more explanations). So I implemented an ugly hack for passing user mode buffer for write operations. I will improve it in future releases.


  • 2nd August, 2008: Initial post


This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


About the Author

Software Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionMessage Removed Pin
Vincent_RICHOMME8-May-16 13:12
memberVincent_RICHOMME8-May-16 13:12 
QuestionRead Muliple Sectors Pin
Alistair Budd24-Mar-13 15:54
memberAlistair Budd24-Mar-13 15:54 
AnswerRe: Read Muliple Sectors Pin
Member 106914641-Apr-14 22:31
memberMember 106914641-Apr-14 22:31 
QuestionC# Pin
mr_rastegari4-Dec-12 6:46
membermr_rastegari4-Dec-12 6:46 
AnswerRe: C# Pin
mr_rastegari3-Aug-13 1:06
membermr_rastegari3-Aug-13 1:06 
GeneralRe: C# Pin
YDLU14-Apr-16 11:54
memberYDLU14-Apr-16 11:54 
QuestionQuestion Pin
RomTibi27-Jan-12 22:55
memberRomTibi27-Jan-12 22:55 
QuestionWindows 7 x64 Pin
cmleevt17-Nov-11 9:57
membercmleevt17-Nov-11 9:57 
GeneralHello If I want to read and write F: how to write the contents of disk! Pin
ajmajm16-May-11 0:23
memberajmajm16-May-11 0:23 
GeneralLook at it from the other angle Pin
Will228-Apr-11 2:15
memberWill228-Apr-11 2:15 
GeneralRead/Write 1-2 Bytes in MBR only Pin
BrianPeterson19-Nov-09 19:44
memberBrianPeterson19-Nov-09 19:44 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
dkg041419-Nov-09 20:04
memberdkg041419-Nov-09 20:04 
QuestionRe: Read/Write 1-2 Bytes in MBR only [modified] Pin
BrianPeterson25-Mar-10 15:10
memberBrianPeterson25-Mar-10 15:10 
AnswerRe: Read/Write 1-2 Bytes in MBR only Pin
dkg041426-Mar-10 9:20
memberdkg041426-Mar-10 9:20 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
BrianPeterson26-Mar-10 11:05
memberBrianPeterson26-Mar-10 11:05 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
BrianPeterson26-Mar-10 16:11
memberBrianPeterson26-Mar-10 16:11 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
dkg041426-Mar-10 19:37
memberdkg041426-Mar-10 19:37 
GeneralRe: Read/Write 1-2 Bytes in MBR only [modified] Pin
BrianPeterson26-Mar-10 19:59
memberBrianPeterson26-Mar-10 19:59 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
BrianPeterson26-Mar-10 22:28
memberBrianPeterson26-Mar-10 22:28 
GeneralRe: Read/Write 1-2 Bytes in MBR only Pin
dkg041427-Mar-10 0:22
memberdkg041427-Mar-10 0:22 
QuestionRe: Read/Write 1-2 Bytes in MBR only Pin
BrianPeterson27-Mar-10 9:52
memberBrianPeterson27-Mar-10 9:52 
Unfortunately I think I am doing it in the completion routine of IRP_MN_START_DEVICE (run in DiskPerfIrpCompletion()). Ok, doing the operation in the first IO op comes sounds reasonable... it will obviously be taking operations at that time... lol. So lets see... an IO flag initialized to zero and then increment it so its only done on the first operation and not every operation... need to have a function take in IRP_MJ_READ & IRP_MJ_WRITE easy enough...

Now building the IRP with IoCallDriver should be pretty easy only catch I'm seeing on that is do I just send it to the next device below me as below or as in your driver you had a pointer to the specific raw disk to read.

          IN PDEVICE_OBJECT DeviceObject,
          IN PIRP Irp)
// 1) check for first operation or not. If it is build our take our actions,
// otherwise pass it on untouched. 

// 2) build the irp for the next device in the chain with a IRP_MJ_READ or 
// IRP_MJ_WRITE with the necessary buffers, etc (similar to what you did in
// sector.sys?)
lDiskOffset.QuadPart = (pDiskObj->ulSectorSize) * (pDiskLoc->ullSectorNum);
		KeInitializeEvent(&Event, NotificationEvent, FALSE);
pIrp = IoBuildSynchronousFsdRequest(MajorFunc, pDiskObj->pDiskDevObj, pBuff, 
		pDiskObj->ulSectorSize, &lDiskOffset, 
		&Event, &ioStatus);

// 3) Modify physical device DACL to enforce BLP Security Model if necessary 
// via ZwSetSecurityObject or equivalent

// 4)Let the IRP we are holding go on through

IF it is the latter, I have proven I can get a working name for the raw disk (L"\\DosDevices\\PhysicalDrive%d"), but how do I convert that to something I can use as a target of my irp to gurantee I get the raw disk (sort of the reverse action of ObQueryNameString) to represent your pDiskDevObj? Can I use the deviceExtension->PhysicalDeviceObject which is set during Add_Device?

The next question that I see then is since I can't use the ZwRead/WriteFile operations because Zw calls will send the IRP from top of the stack. And since my device is in the stack which is already holding the IOs will get another IO generated by me and I will end up in a deadlock.... How does ZwSetSecurityObject get a Handle (an action that takes ZwCreateFile typically)? Or does that not matter now, since I've read/written to the raw disk already by this point and all other irps received are passed through me (other than this first one) or will this too end in deadlock? Is there a way to do ZwSetSecurityObject without causing deadlock prior to releasing the first trapped irp?
GeneralDisk/Partition Sectors Pin
trlacey28-Oct-09 9:23
membertrlacey28-Oct-09 9:23 
GeneralRe: Disk/Partition Sectors Pin
dkg041429-Oct-09 21:11
memberdkg041429-Oct-09 21:11 
GeneralRe: Disk/Partition Sectors Pin
trlacey30-Oct-09 8:48
membertrlacey30-Oct-09 8:48 
GeneralRe: Disk/Partition Sectors Pin
dkg041431-Oct-09 21:29
memberdkg041431-Oct-09 21:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 2 Aug 2008
Article Copyright 2008 by dkg0414
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid