---
title: "C/C++底层实现指定磁盘只读"
author: "winzenghua"
date: "2009-10-16T11:20:00Z"
tags: []
slug: "c-c"
draft: false
lastmod: "2009-10-16T11:20:00Z"
id: 948101
url: "https://java4gis.iteye.com/blog/948101"
---

燕狂徒写的驱动挂钩，限制磁盘只读，

用于保证涉密计算机的稳定，相当于将磁盘变成ROM

#include "ntddk.h"  
#include &lt;srb.h&gt;  
#include &lt;scsi.h&gt;

#define DRIVERNAME "OnlyRead(GongXiPeng!)"// for use in messages

typedef struct tagDEVICE\_EXTENSION {  
PDEVICE\_OBJECT DeviceObject;// device object this extension belongs to  
PDEVICE\_OBJECT LowerDeviceObject;// next lower driver in same stack  
PDEVICE\_OBJECT Pdo;// the PDO  
IO\_REMOVE\_LOCK RemoveLock;  
} DEVICE\_EXTENSION, \*PDEVICE\_EXTENSION;

VOID RemoveDevice(IN PDEVICE\_OBJECT fdo);  
NTSTATUS CompleteRequest(IN PIRP Irp, IN NTSTATUS status, IN ULONG\_PTR info);  
NTSTATUS DispatchForSCSI(IN PDEVICE\_OBJECT fido, IN PIRP Irp);  
NTSTATUS AddDevice(IN PDRIVER\_OBJECT DriverObject, IN PDEVICE\_OBJECT pdo);

NTSTATUS DispatchAny(IN PDEVICE\_OBJECT fido, IN PIRP Irp);  
NTSTATUS DispatchPower(IN PDEVICE\_OBJECT fido, IN PIRP Irp);  
NTSTATUS DispatchPnp(IN PDEVICE\_OBJECT fido, IN PIRP Irp);  
NTSTATUS DispatchWmi(IN PDEVICE\_OBJECT fido, IN PIRP Irp);  
ULONG GetDeviceTypeToUse(PDEVICE\_OBJECT pdo);  
NTSTATUS StartDeviceCompletionRoutine(PDEVICE\_OBJECT fido, PIRP Irp, PDEVICE\_EXTENSION pdx);  
NTSTATUS UsageNotificationCompletionRoutine(PDEVICE\_OBJECT fido, PIRP Irp, PDEVICE\_EXTENSION pdx);

VOID DriverUnload(IN PDRIVER\_OBJECT fido);

NTSTATUS  
DriverEntry(  
IN PDRIVER\_OBJECT DriverObject,  
IN PUNICODE\_STRING RegistryPath  
)  
{  
int i;

KdPrint(("准备驱动加载"));  
UNREFERENCED\_PARAMETER(RegistryPath);  
DriverObject-&gt;DriverUnload = DriverUnload;  
DriverObject-&gt;DriverExtension-&gt;AddDevice = AddDevice;  
for (i = 0; i &lt; IRP\_MJ\_MAXIMUM\_FUNCTION; ++i)  
DriverObject-&gt;MajorFunction\[i] = DispatchAny;  
DriverObject-&gt;MajorFunction\[IRP\_MJ\_POWER] = DispatchPower;  
DriverObject-&gt;MajorFunction\[IRP\_MJ\_PNP] = DispatchPnp;  
DriverObject-&gt;MajorFunction\[IRP\_MJ\_SCSI] = DispatchForSCSI;

return(STATUS\_SUCCESS);  
}

VOID DriverUnload(IN PDRIVER\_OBJECT DriverObject)  
{// DriverUnload  
PAGED\_CODE();  
//UNREFERENCED\_PARAMETER(DriverObject);  
KdPrint((DRIVERNAME " - Entering DriverUnload: DriverObject %8.8lX\\n", DriverObject));  
}

NTSTATUS AddDevice(IN PDRIVER\_OBJECT DriverObject, IN PDEVICE\_OBJECT pdo)  
{// AddDevice

NTSTATUS status;  
PDEVICE\_OBJECT fido;  
PDEVICE\_EXTENSION pdx;  
PDEVICE\_OBJECT fdo;

PAGED\_CODE();

status = IoCreateDevice(DriverObject, sizeof(DEVICE\_EXTENSION), NULL,  
GetDeviceTypeToUse(pdo), 0, FALSE, &fido);  
if (!NT\_SUCCESS(status))  
{// can't create device object  
KdPrint((DRIVERNAME " - IoCreateDevice failed - %X\\n", status));  
return status;  
}// can't create device object

pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
do  
{// finish initialization  
IoInitializeRemoveLock(&pdx-&gt;RemoveLock, 0, 0, 0);  
pdx-&gt;DeviceObject = fido;  
pdx-&gt;Pdo = pdo;  
//将过滤驱动附加在底层驱动之上  
fdo = IoAttachDeviceToDeviceStack(fido, pdo);  
if (!fdo)  
{// can't attach  
KdPrint((DRIVERNAME " - IoAttachDeviceToDeviceStack failed\\n"));  
status = STATUS\_DEVICE\_REMOVED;  
break;  
}// can't attach  
//记录底层驱动  
pdx-&gt;LowerDeviceObject = fdo;  
//由于不知道底层驱动是直接IO还是BufferIO，因此将标志都置上  
fido-&gt;Flags |= fdo-&gt;Flags & (DO\_DIRECT\_IO | DO\_BUFFERED\_IO | DO\_POWER\_PAGABLE);  
// Clear the "initializing" flag so that we can get IRPs  
fido-&gt;Flags &= ~DO\_DEVICE\_INITIALIZING;  
}while (FALSE);// finish initialization

if (!NT\_SUCCESS(status))  
{// need to cleanup  
if (pdx-&gt;LowerDeviceObject)  
IoDetachDevice(pdx-&gt;LowerDeviceObject);  
IoDeleteDevice(fido);  
}// need to cleanup

return status;  
}// AddDevice

///////////////////////////////////////////////////////////////////////////////  
// GetDeviceTypeToUse returns the device object type of the next lower device  
// object. This helps overcome a bug in some Win2K file systems which expect the  
// topmost FiDO in a storage stack to have a VPB and, hence, to have been created  
// with a type such as FILE\_DEVICE\_DISK.  
#pragma PAGEDCODE  
ULONG GetDeviceTypeToUse(PDEVICE\_OBJECT pdo)  
{// GetDeviceTypeToUse  
PDEVICE\_OBJECT ldo;  
ULONG devtype;  
ldo = IoGetAttachedDeviceReference(pdo);  
if (!ldo)  
return FILE\_DEVICE\_UNKNOWN;  
devtype = ldo-&gt;DeviceType;  
ObDereferenceObject(ldo);  
return devtype;  
}// GetDeviceTypeToUse

///////////////////////////////////////////////////////////////////////////////  
#pragma LOCKEDCODE// make no assumptions about pageability of dispatch fcns  
NTSTATUS DispatchAny(IN PDEVICE\_OBJECT fido, IN PIRP Irp)  
{// DispatchAny  
NTSTATUS status;  
PDEVICE\_EXTENSION pdx;  
PIO\_STACK\_LOCATION stack;

#if DBG  
static char* irpname\[] =  
{  
"IRP\_MJ\_CREATE",  
"IRP\_MJ\_CREATE\_NAMED\_PIPE",  
"IRP\_MJ\_CLOSE",  
"IRP\_MJ\_READ",  
"IRP\_MJ\_WRITE",  
"IRP\_MJ\_QUERY\_INFORMATION",  
"IRP\_MJ\_SET\_INFORMATION",  
"IRP\_MJ\_QUERY\_EA",  
"IRP\_MJ\_SET\_EA",  
"IRP\_MJ\_FLUSH\_BUFFERS",  
"IRP\_MJ\_QUERY\_VOLUME\_INFORMATION",  
"IRP\_MJ\_SET\_VOLUME\_INFORMATION",  
"IRP\_MJ\_DIRECTORY\_CONTROL",  
"IRP\_MJ\_FILE\_SYSTEM\_CONTROL",  
"IRP\_MJ\_DEVICE\_CONTROL",  
"IRP\_MJ\_INTERNAL\_DEVICE\_CONTROL",  
"IRP\_MJ\_SHUTDOWN",  
"IRP\_MJ\_LOCK\_CONTROL",  
"IRP\_MJ\_CLEANUP",  
"IRP\_MJ\_CREATE\_MAILSLOT",  
"IRP\_MJ\_QUERY\_SECURITY",  
"IRP\_MJ\_SET\_SECURITY",  
"IRP\_MJ\_POWER",  
"IRP\_MJ\_SYSTEM\_CONTROL",  
"IRP\_MJ\_DEVICE\_CHANGE",  
"IRP\_MJ\_QUERY\_QUOTA",  
"IRP\_MJ\_SET\_QUOTA",  
"IRP\_MJ\_PNP",  
};  
UCHAR type;  
#endif

pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
stack = IoGetCurrentIrpStackLocation(Irp);  
#if DBG  
type = stack-&gt;MajorFunction;  
if (type &gt;= IRP\_MJ\_MAXIMUM\_FUNCTION)  
KdPrint((DRIVERNAME " - Unknown IRP, major type %X\\n", type));  
else  
KdPrint((DRIVERNAME " - %s\\n", irpname\[type]));  
#endif  
// Pass request down without additional processing  
status = IoAcquireRemoveLock(&pdx-&gt;RemoveLock, Irp);  
if (!NT\_SUCCESS(status))  
return CompleteRequest(Irp, status, 0);  
IoSkipCurrentIrpStackLocation(Irp);  
status = IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return status;  
}// DispatchAny

///////////////////////////////////////////////////////////////////////////////  
#pragma LOCKEDCODE  
NTSTATUS CompleteRequest(IN PIRP Irp, IN NTSTATUS status, IN ULONG\_PTR info)  
{// CompleteRequest  
Irp-&gt;IoStatus.Status = status;  
Irp-&gt;IoStatus.Information = info;  
IoCompleteRequest(Irp, IO\_NO\_INCREMENT);  
return status;  
}// CompleteRequest

NTSTATUS  
USBSCSICompletion( IN PDEVICE\_OBJECT DeviceObject,  
IN PIRP Irp,  
IN PVOID Context )  
{  
PDEVICE\_EXTENSION pdx;  
PIO\_STACK\_LOCATION irpStack;  
PSCSI\_REQUEST\_BLOCK CurSrb;  
PCDB cdb;  
UCHAR opCode;  
PMODE\_PARAMETER\_HEADER modeData;

pdx = ( PDEVICE\_EXTENSION )DeviceObject-&gt;DeviceExtension;  
IoAcquireRemoveLock(&pdx-&gt;RemoveLock,Irp);  
irpStack = IoGetCurrentIrpStackLocation( Irp );

CurSrb=irpStack-&gt;Parameters.Scsi.Srb;  
cdb = (PCDB)CurSrb-&gt;Cdb;  
opCode=cdb-&gt;CDB6GENERIC.OperationCode;  
if(opCode==SCSIOP\_MODE\_SENSE && CurSrb-&gt;DataBuffer  
&& CurSrb-&gt;DataTransferLength &gt;=  
sizeof(MODE\_PARAMETER\_HEADER))  
{  
KdPrint(("SCSIOP\_MODE\_SENSE comming!\\n"));  
modeData = (PMODE\_PARAMETER\_HEADER)CurSrb-&gt;DataBuffer;  
modeData-&gt;DeviceSpecificParameter |= MODE\_DSP\_WRITE\_PROTECT;  
}

if ( Irp-&gt;PendingReturned )  
{  
IoMarkIrpPending( Irp );  
}  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock,Irp);  
return Irp-&gt;IoStatus.Status ;  
}

///////////////////////////////////////////////////////////////////////////////  
NTSTATUS DispatchPower(IN PDEVICE\_OBJECT fido, IN PIRP Irp)  
{// DispatchPower  
/*  
#if DBG  
PIO\_STACK\_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);  
ULONG fcn = stack-&gt;MinorFunction;  
static char* fcnname\[] =  
{  
"IRP\_MN\_WAIT\_WAKE",  
"IRP\_MN\_POWER\_SEQUENCE",  
"IRP\_MN\_SET\_POWER",  
"IRP\_MN\_QUERY\_POWER",  
};

if (fcn == IRP\_MN\_SET\_POWER || fcn == IRP\_MN\_QUERY\_POWER)  
{  
static char* sysstate\[] =  
{  
"PowerSystemUnspecified",  
"PowerSystemWorking",  
"PowerSystemSleeping1",  
"PowerSystemSleeping2",  
"PowerSystemSleeping3",  
"PowerSystemHibernate",  
"PowerSystemShutdown",  
"PowerSystemMaximum",  
};

static char* devstate\[] =  
{  
"PowerDeviceUnspecified",  
"PowerDeviceD0",  
"PowerDeviceD1",  
"PowerDeviceD2",  
"PowerDeviceD3",  
"PowerDeviceMaximum",  
};

ULONG context = stack-&gt;Parameters.Power.SystemContext;  
POWER\_STATE\_TYPE type = stack-&gt;Parameters.Power.Type;  
KdPrint((DRIVERNAME " - IRP\_MJ\_POWER (%s)", fcnname\[fcn]));  
if (type == SystemPowerState)  
KdPrint((", SystemPowerState = %s\\n", sysstate\[stack-&gt;Parameters.Power.State.SystemState]));  
else  
KdPrint((", DevicePowerState = %s\\n", devstate\[stack-&gt;Parameters.Power.State.DeviceState]));  
}  
else if (fcn &lt; arraysize(fcnname))  
KdPrint((DRIVERNAME " - IRP\_MJ\_POWER (%s)\\n", fcnname\[fcn]));  
else  
KdPrint((DRIVERNAME " - IRP\_MJ\_POWER (%2.2X)\\n", fcn));  
#endif // DBG  
\*/  
PDEVICE\_EXTENSION pdx;  
NTSTATUS status;

pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
PoStartNextPowerIrp(Irp);// must be done while we own the IRP  
status = IoAcquireRemoveLock(&pdx-&gt;RemoveLock, Irp);  
if (!NT\_SUCCESS(status))  
return CompleteRequest(Irp, status, 0);  
IoSkipCurrentIrpStackLocation(Irp);  
status = PoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return status;  
}// DispatchPower

///////////////////////////////////////////////////////////////////////////////  
NTSTATUS DispatchPnp(IN PDEVICE\_OBJECT fido, IN PIRP Irp)  
{// DispatchPnp  
PIO\_STACK\_LOCATION stack;  
ULONG fcn;  
NTSTATUS status;  
PDEVICE\_EXTENSION pdx;

stack = IoGetCurrentIrpStackLocation(Irp);  
fcn = stack-&gt;MinorFunction;  
pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
status = IoAcquireRemoveLock(&pdx-&gt;RemoveLock, Irp);  
if (!NT\_SUCCESS(status))  
return CompleteRequest(Irp, status, 0);  
// Handle usage notification specially in order to track power pageable  
// flag correctly. We need to avoid allowing a non-pageable handler to be  
// layered on top of a pageable handler.  
if (fcn == IRP\_MN\_DEVICE\_USAGE\_NOTIFICATION)  
{// usage notification  
if (!fido-&gt;AttachedDevice || (fido-&gt;AttachedDevice-&gt;Flags & DO\_POWER\_PAGABLE))  
fido-&gt;Flags |= DO\_POWER\_PAGABLE;  
IoCopyCurrentIrpStackLocationToNext(Irp);  
IoSetCompletionRoutine(Irp, (PIO\_COMPLETION\_ROUTINE) UsageNotificationCompletionRoutine,  
(PVOID) pdx, TRUE, TRUE, TRUE);  
return IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
}// usage notification

// Handle start device specially in order to correctly inherit  
// FILE\_REMOVABLE\_MEDIA  
if (fcn == IRP\_MN\_START\_DEVICE)  
{// device start  
IoCopyCurrentIrpStackLocationToNext(Irp);  
IoSetCompletionRoutine(Irp, (PIO\_COMPLETION\_ROUTINE) StartDeviceCompletionRoutine,  
(PVOID) pdx, TRUE, TRUE, TRUE);  
return IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
}// device start

// Handle remove device specially in order to cleanup device stack  
if (fcn == IRP\_MN\_REMOVE\_DEVICE)  
{// remove device  
IoSkipCurrentIrpStackLocation(Irp);  
status = IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
IoReleaseRemoveLockAndWait(&pdx-&gt;RemoveLock, Irp);  
RemoveDevice(fido);  
return status;  
}// remove device

// Simply forward any other type of PnP request  
IoSkipCurrentIrpStackLocation(Irp);  
status = IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return status;  
}

///////////////////////////////////////////////////////////////////////////////  
#pragma PAGEDCODE  
VOID RemoveDevice(IN PDEVICE\_OBJECT fido)  
{// RemoveDevice  
PDEVICE\_EXTENSION pdx;

KdPrint(("Enter RemoveDevice"));  
PAGED\_CODE();  
pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
if (pdx-&gt;LowerDeviceObject)  
IoDetachDevice(pdx-&gt;LowerDeviceObject);  
IoDeleteDevice(fido);  
}

///////////////////////////////////////////////////////////////////////////////  
#pragma LOCKEDCODE  
NTSTATUS StartDeviceCompletionRoutine(PDEVICE\_OBJECT fido, PIRP Irp, PDEVICE\_EXTENSION pdx)  
{// StartDeviceCompletionRoutine  
if (Irp-&gt;PendingReturned)  
IoMarkIrpPending(Irp);  
// Inherit FILE\_REMOVABLE\_MEDIA flag from lower object. This is necessary  
// for a disk filter, but it isn't available until start-device time. Drivers  
// above us may examine the flag as part of their own start-device processing, too.  
if (pdx-&gt;LowerDeviceObject-&gt;Characteristics & FILE\_REMOVABLE\_MEDIA)  
fido-&gt;Characteristics |= FILE\_REMOVABLE\_MEDIA;  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return STATUS\_SUCCESS;  
}// StartDeviceCompletionRoutine

///////////////////////////////////////////////////////////////////////////////  
#pragma LOCKEDCODE  
NTSTATUS UsageNotificationCompletionRoutine(PDEVICE\_OBJECT fido, PIRP Irp, PDEVICE\_EXTENSION pdx)  
{// UsageNotificationCompletionRoutine  
if (Irp-&gt;PendingReturned)  
IoMarkIrpPending(Irp);  
// If lower driver cleared pageable flag, we must do the same  
if (!(pdx-&gt;LowerDeviceObject-&gt;Flags & DO\_POWER\_PAGABLE))  
fido-&gt;Flags &= ~DO\_POWER\_PAGABLE;  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return STATUS\_SUCCESS;  
}// UsageNotificationCompletionRoutine

#pragma LOCKEDCODE// force inline functions into nonpaged code

#pragma LOCKEDCODE  
NTSTATUS DispatchForSCSI(IN PDEVICE\_OBJECT fido, IN PIRP Irp)  
{  
PDEVICE\_EXTENSION pdx;  
PIO\_STACK\_LOCATION irpStack;  
NTSTATUS status;

//KdPrint((DRIVERNAME " - Enter DispatchForSCSI \\n"));  
pdx = (PDEVICE\_EXTENSION) fido-&gt;DeviceExtension;  
irpStack = IoGetCurrentIrpStackLocation(Irp);  
// Pass request down without additional processing  
status = IoAcquireRemoveLock(&pdx-&gt;RemoveLock, Irp);  
if (!NT\_SUCCESS(status))  
return CompleteRequest(Irp, status, 0);  
IoCopyCurrentIrpStackLocationToNext(Irp);  
IoSetCompletionRoutine( Irp,  
USBSCSICompletion,  
NULL,  
TRUE,  
TRUE,  
TRUE );  
status = IoCallDriver(pdx-&gt;LowerDeviceObject, Irp);  
IoReleaseRemoveLock(&pdx-&gt;RemoveLock, Irp);  
return status;  
}  
///////////////////////////////////////////////////////////////////////////////  
#pragma LOCKEDCODE// make no assumptions about pageability of dispatch fcns