BSOD when Unloading driver

hi to all
i am refering to the this very nice article found at
http://www.codeproject.com/KB/system/soviet_protector.aspx

i managed to compile it. and works fine
however i get BSOD when i close the Application that is doing buffered input/output with the Driver. i get “DRIVER_UNLOADED_WITHOUT_CANCELLING_PENDING_OPERATIONS”
i think it is because of the code in the driver that is waiting for the respose in the while loop

while( 1)
{
KeDelayExecutionThread(KernelMode,0,&li);
memmove(&a,&output[0],4);
if(!a)break;
}

here the output[0] is modified by the application.
and the application is closed (without taking response by user (MessageBox)) so this buffer is invalid . so i am getting this BSOD

am i right ?

if so then how can i grace fully Unload the Driver.

thanks with Regards
deep

No, it is because somewhere in the driver it pended an IRP (IoMarkPending)
and it has not been canceled. Right now I can’t comment more since
codeproject seems to be operating at about 1 baud. But it has nothing to do
with the code you list below, and probably a lot to do with a flawed cancel
handling.


Don Burn (MVP, Windows DDK)
Windows 2k/XP/2k3 Filesystem and Driver Consulting
Website: http://www.windrvr.com
Blog: http://msmvps.com/blogs/WinDrvr
Remove StopSpam to reply

wrote in message news:xxxxx@ntdev…
> hi to all
> i am refering to the this very nice article found at
> http://www.codeproject.com/KB/system/soviet_protector.aspx
>
> i managed to compile it. and works fine
> however i get BSOD when i close the Application that is doing buffered
> input/output with the Driver. i get
> “DRIVER_UNLOADED_WITHOUT_CANCELLING_PENDING_OPERATIONS”
> i think it is because of the code in the driver that is waiting for the
> respose in the while loop
>
> while( 1)
> {
> KeDelayExecutionThread(KernelMode,0,&li);
> memmove(&a,&output[0],4);
> if(!a)break;
> }
>
> here the output[0] is modified by the application.
> and the application is closed (without taking response by user
> (MessageBox)) so this buffer is invalid . so i am getting this BSOD
>
> am i right ?
>
> if so then how can i grace fully Unload the Driver.
>
>
> thanks with Regards
> deep
>
>
>
>
>
>
>

hello thank for the reply !

here is the code that is in the Driver

#include “ntddk.h”

struct SYS_SERVICE_TABLE {
void **ServiceTable;
unsigned long CounterTable;
unsigned long ServiceLimit;
void **ArgumentsTable;
};

const WCHAR devicename=L"\Device\Protector";
const WCHAR devicelink=L"\DosDevices\PROTECTOR";

KEVENT event;

ULONG Index,RealCallee;
char*output;
extern struct SYS_SERVICE_TABLE *KeServiceDescriptorTable;

//this function decides whether we should allow NtCreateSection() call to be successfull
ULONG __stdcall check(PULONG arg)
{

HANDLE hand=0;PFILE_OBJECT file=0;POBJECT_HANDLE_INFORMATION info;ULONG a;char*buff;
ANSI_STRING str; LARGE_INTEGER li;li.QuadPart=-10000;

//check the flags. If PAGE_EXECUTE access to the section is not requested,
//it does not make sense to be bothered about it
if((arg[4]&0xf0)==0)return 1;
if((arg[5]&0x01000000)==0)return 1;

//get the file name via the file handle
hand=(HANDLE)arg[6];
ObReferenceObjectByHandle(hand,0,0,KernelMode,&file,&info);
if(!file)return 1;
RtlUnicodeStringToAnsiString(&str,&file->FileName,1);

a=str.Length;buff=str.Buffer;
while(1)
{
if(buff[a]==‘.’){a++;break;}
a–;
}
ObDereferenceObject(file);

//if it is not executable, it does not make sense to be bothered about it
//return 1
if(_stricmp(&buff[a],“exe”)){RtlFreeAnsiString(&str);return 1;}

//now we are going to ask user’s opinion. Write file name to the buffer, and wait until
//the user indicates the response (1 as a first DWORD means we can proceed)

//synchronize access to the buffer
KeWaitForSingleObject(&event,Executive,KernelMode,0,0);

// set first 2 DWORD of a buffer to zero, copy the string into the buffer, and loop
//until the user sets first DWORD to 1. The value of the second DWORD indicates user’s
//response
strcpy(&output[8],buff);
RtlFreeAnsiString(&str);

a=1;
memmove(&output[0],&a,4);
while(1)
{
KeDelayExecutionThread(KernelMode,0,&li);
memmove(&a,&output[0],4);
if(!a)break;
}
memmove(&a,&output[4],4);
KeSetEvent(&event,0,0);

return a;
}

//just saves execution contect and calls check()
_declspec(naked) Proxy()
{

_asm{

//save execution contect and calls check() -the rest depends upon the value check() returns
// if it is 1, proceed to the actual callee. Otherwise,return STATUS_ACCESS_DENIED
pushfd
pushad
mov ebx,esp
add ebx,40
push ebx
call check
cmp eax,1
jne block

//proceed to the actual callee
popad
popfd
jmp RealCallee

//return STATUS_ACCESS_DENIED
block:popad
mov ebx, dword ptr[esp+8]
mov dword ptr[ebx],0
mov eax,0xC0000022L
popfd
ret 32

}
}

NTSTATUS DrvDispatch(IN PDEVICE_OBJECT device,IN PIRP Irp)

{
UCHAR*buff=0; ULONG a,base;

PIO_STACK_LOCATION loc=IoGetCurrentIrpStackLocation(Irp);

if(loc->Parameters.DeviceIoControl.IoControlCode==1000)
{
buff=(UCHAR*)Irp->AssociatedIrp.SystemBuffer;

// hook service dispatch table
// this gets the virtual address in the calling process virtual address space and then maps that
// addresses to the physical address (RAM) then locks that page
memmove(&Index,buff,4);
a=4*Index+(ULONG)KeServiceDescriptorTable->ServiceTable;
base=(ULONG)MmMapIoSpace(MmGetPhysicalAddress((void*)a),4,0); //returns the base virtual address space
a=(ULONG)&Proxy; //

_asm
{
mov eax,base
mov ebx,dword ptr[eax]
mov RealCallee,ebx
mov ebx,a
mov dword ptr[eax],ebx
}

MmUnmapIoSpace(base,4);

memmove(&a,&buff[4],4);
output=(char*)MmMapIoSpace(MmGetPhysicalAddress((void*)a),256,0);
}

Irp->IoStatus.Status=0;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return 0;

}

// nothing special
NTSTATUS DrvCreateClose(IN PDEVICE_OBJECT device,IN PIRP Irp)

{

Irp->IoStatus.Information=0;
Irp->IoStatus.Status=0;
IoCompleteRequest(Irp,IO_NO_INCREMENT);
return 0;

}

// nothing special -just a cleanup
void DrvUnload(IN PDRIVER_OBJECT driver)
{
UNICODE_STRING devlink;
ULONG a,base;

//unhook dispatch table
a=4*Index+(ULONG)KeServiceDescriptorTable->ServiceTable;
base=(ULONG)MmMapIoSpace(MmGetPhysicalAddress((void*)a),4,0);

_asm
{
mov eax,base
mov ebx,RealCallee
mov dword ptr[eax],ebx
}

MmUnmapIoSpace(base,4);
MmUnmapIoSpace(output,256);

RtlInitUnicodeString(&devlink,devicelink);
IoDeleteSymbolicLink(&devlink);
IoDeleteDevice(driver->DeviceObject);
}

//DriverEntry just creates our device - nothing special here
NTSTATUS DriverEntry(IN PDRIVER_OBJECT driver,IN PUNICODE_STRING path)
{

PDEVICE_OBJECT devobject=0;

UNICODE_STRING devlink,devname;

ULONG a,b;

RtlInitUnicodeString(&devname,devicename);
RtlInitUnicodeString(&devlink,devicelink);

IoCreateDevice(driver,256,&devname,FILE_DEVICE_UNKNOWN,0,TRUE,&devobject);
IoCreateSymbolicLink(&devlink,&devname);

driver->MajorFunction[IRP_MJ_DEVICE_CONTROL]=DrvDispatch;
driver->MajorFunction[IRP_MJ_CREATE]=DrvCreateClose;
driver->MajorFunction[IRP_MJ_CLOSE]=DrvCreateClose;
driver->DriverUnload=DrvUnload;
KeInitializeEvent(&event,SynchronizationEvent,1);

return 0;
}

Ok, finally got the download.

First this is hooking which is really a terrible idea saying it is a
nice article is full of shit. Second it is poorly done hooking what has
happened is you are screwing up a stack and basically not handling it
correctly. Of course the real rule is if you hook, you never unload.
Sorry, make that the second rule, if you hook for a comercial use you will
be dispised for the rest of your life.

If you are going to play with junk like this spend a lot of time to
learn the kernel, and don’t expect a lot of help from good driver
developers.


Don Burn (MVP, Windows DDK)
Windows 2k/XP/2k3 Filesystem and Driver Consulting
Website: http://www.windrvr.com
Blog: http://msmvps.com/blogs/WinDrvr
Remove StopSpam to reply

wrote in message news:xxxxx@ntdev…
> hi to all
> i am refering to the this very nice article found at
> http://www.codeproject.com/KB/system/soviet_protector.aspx
>
> i managed to compile it. and works fine
> however i get BSOD when i close the Application that is doing buffered
> input/output with the Driver. i get
> “DRIVER_UNLOADED_WITHOUT_CANCELLING_PENDING_OPERATIONS”
> i think it is because of the code in the driver that is waiting for the
> respose in the while loop
>
> while( 1)
> {
> KeDelayExecutionThread(KernelMode,0,&li);
> memmove(&a,&output[0],4);
> if(!a)break;
> }
>
> here the output[0] is modified by the application.
> and the application is closed (without taking response by user
> (MessageBox)) so this buffer is invalid . so i am getting this BSOD
>
> am i right ?
>
> if so then how can i grace fully Unload the Driver.
>
>
> thanks with Regards
> deep
>
>
>
>
>
>
>

Don,

First this is hooking which is really a terrible idea saying it is a nice article is full of shit.

This is not the question of hooking in itself but rather of HOW it get done. More on it below.

Second it is poorly done hooking

This is just a demo. First, as you have already pointed out, you cannot unload your driver if you hook (as you will see shortly, this is the only reason why the OP crashes). Second, there are just a couple of bugs there. IIRC, I made an assumption that SSDT does not break the page boundary, which is wrong - if it does not hold true on some OS version, you are going to bluescreen right upon trying to hook SSDT. It is OK for the proof-of-concept code -
I just could not have imagined that someone may want to use it in its current form the the production purposes.

As I have eventually discovered, quite a few people try to use it for the commercial purposes in its current form. I have never expected it to work this way - I thought that more or less reasonable people would know the difference between the proof-of-concept and production code, so that they would realize that, in order to move it to production, one needs to introduce an awful lot of validation. However, it does not seem to work this way - they just grab a raw sample code and try to use it

it is because somewhere in the driver it pended an IRP (IoMarkPending)
and it has not been canceled.

Not at all - it does not use the inverted call. Instead, it relies upon polling. The reason why it crashes is because it is supposed to receive an IOCTL that informs it that it should unhook SSDT. However, the OP just terminates an app, so that it unloads a driver without unhooking SSDT…

Anton Bassov

Sysinternals did the same thing when they released early versions of filemon
and regmon source. They and especially filemon have been the basis of many
file system filters for encryption, compression, and security for many
years. They were designed specifically for testing usage and were not
active filters and the accompanying documentation said they were for people
to learn from, but their use in a product required a license. They were
just as successful as you have been. Maybe that is why there are no good
production quality examples for many of the esoteric driver types.

The PHB says: “I heard about this program/driver on the web and it should
only take a few hours to turn it into a product we can sell”.

The VB programmer who has been hired to write drivers says: “I am new so it
will take a couple of weeks”.

The CEO says: “We have enough money to last for two months and since the
product will be ready in two weeks I won’t have to sell any more pieces off
to raise more money”.

Crash, burn, and welcome to the unemployment office for the workers.

wrote in message news:xxxxx@ntdev…
> Don,
>
>> First this is hooking which is really a terrible idea saying it is a nice
>> article is full of shit.
>
> This is not the question of hooking in itself but rather of HOW it get
> done. More on it below.
>
>
>> Second it is poorly done hooking
>
> This is just a demo. First, as you have already pointed out, you cannot
> unload your driver if you hook (as you will see shortly, this is the only
> reason why the OP crashes). Second, there are just a couple of bugs there.
> IIRC, I made an assumption that SSDT does not break the page boundary,
> which is wrong - if it does not hold true on some OS version, you are
> going to bluescreen right upon trying to hook SSDT. It is OK for the
> proof-of-concept code -
> I just could not have imagined that someone may want to use it in its
> current form the the production purposes.
>
> As I have eventually discovered, quite a few people try to use it for the
> commercial purposes in its current form. I have never expected it to work
> this way - I thought that more or less reasonable people would know the
> difference between the proof-of-concept and production code, so that they
> would realize that, in order to move it to production, one needs to
> introduce an awful lot of validation. However, it does not seem to work
> this way - they just grab a raw sample code and try to use it
>
>> it is because somewhere in the driver it pended an IRP (IoMarkPending)
>> and it has not been canceled.
>
> Not at all - it does not use the inverted call. Instead, it relies upon
> polling. The reason why it crashes is because it is supposed to receive an
> IOCTL that informs it that it should unhook SSDT. However, the OP just
> terminates an app, so that it unloads a driver without unhooking SSDT…
>
> Anton Bassov
>

David,

The PHB says: “I heard about this program/driver on the web and it should only
take a few hours to turn it into a product we can sell”. The VB programmer
who has been hired to write drivers says: “I am new so it will take a couple of weeks”.
The CEO says: “We have enough money to last for two months and since the product
will be ready in two weeks I won’t have to sell any more pieces off to raise
more money”. >Crash, burn, and welcome to the unemployment office for the workers.

Few weeks ago I’ve seen quite an interesting observation on one of the threads that said the following: " You, guys, are proud of writing good drivers, but an end user seems to be fully content with a driver that works 90% of the time". The most interesting thing here is that the poster, indeed, had a good point.

Believe me or not, but I know of the company that seems to be *extremely* successful these days, despite the fact that their driver is crap that has been developed around one of the well-known hooking samples that is available on the web, and no one in the whole company has a slightest idea about the rules of good design. For example, they do quite a few things that reasonable people would do in a helper user-mode app right in a driver. In general, their technical “expertize” is comparable to the one you have described above ( I already don’t mention the fact that the very purpose of their product is, in my opinion, at least questionable). However, they have quite a few large institutional clients who are more than willing to buy their crap.

In other words, when it comes to making money, the keyword seems to be “successful marketing”, rather than “good design”. Therefore, there is no guarantee that the imaginary company that you have mentioned above is going to get busted that quickly(if ever)…

Anton Bassov

“Don’t Worry, Be Crappy”.

On Feb 7, 2008 7:43 PM, wrote:

> David,
>
> > The PHB says: “I heard about this program/driver on the web and it
> should only
> > take a few hours to turn it into a product we can sell”. The VB
> programmer
> > who has been hired to write drivers says: “I am new so it will take a
> couple of weeks”.
> > The CEO says: “We have enough money to last for two months and since the
> product
> > will be ready in two weeks I won’t have to sell any more pieces off to
> raise
> > more money”. >Crash, burn, and welcome to the unemployment office for
> the workers.
>
> Few weeks ago I’ve seen quite an interesting observation on one of the
> threads that said the following: " You, guys, are proud of writing good
> drivers, but an end user seems to be fully content with a driver that works
> 90% of the time". The most interesting thing here is that the poster,
> indeed, had a good point.
>
> Believe me or not, but I know of the company that seems to be extremely
> successful these days, despite the fact that their driver is crap that has
> been developed around one of the well-known hooking samples that is
> available on the web, and no one in the whole company has a slightest idea
> about the rules of good design. For example, they do quite a few things
> that reasonable people would do in a helper user-mode app right in a driver.
> In general, their technical “expertize” is comparable to the one you have
> described above ( I already don’t mention the fact that the very purpose of
> their product is, in my opinion, at least questionable). However, they have
> quite a few large institutional clients who are more than willing to buy
> their crap.
>
> In other words, when it comes to making money, the keyword seems to be
> “successful marketing”, rather than “good design”. Therefore, there is no
> guarantee that the imaginary company that you have mentioned above is going
> to get busted that quickly(if ever)…
>
> Anton Bassov
>
> —
> NTDEV is sponsored by OSR
>
> For our schedule of WDF, WDM, debugging and other seminars visit:
> http://www.osr.com/seminars
>
> To unsubscribe, visit the List Server section of OSR Online at
> http://www.osronline.com/page.cfm?name=ListServer
>


Mark Roddy

How about specifics so someone can contine the argument? I would like to
know which drivers you think use dangerous techniques. If you think a
technique is dangerous, I would equate it to mixing your own nitro not being
sure of the correct percentages of each chemical and which order is correct.
Yes, I know some who use techniques that are dangerous, but in some cases it
is required. There are no ways to achieve the desired results with the OS
structure and provided capabilities. Just as testing some of the rename
combinations can’t be done with win32 calls, sometimes seeing certain
activities can’t be achieved without hooking. With 64-bit Vista and its
anti-hook technology, avoiding hooking is easier for two reasons: 1) You
will constantly have to update your hook methods as Microsoft changes their
anti-hook code. 2) You have someone else to blame when the bad guys get
around the anti-hook code and bypass you. It is also easier to just have
your code run as a hypervisor if you want to control the system. Server
2008 has the capability for it to run its own hypervisor which won’t allow
another program/driver to do it after it has loaded.

I haven’t seen any comments about the new exFAT file system. The web has
almost no details about it other than cluster size and that transactions are
supported. No on-disk layouts. Maybe it is the new NTFS, since NTFS really
dislikes removable media and drives. Another black box to reverse engineer!
Maybe it is just for the patentability since FAT is no longer under patent.
I missed any mention of it, but I didn’t do that much with the betas of
Longhorn and Vista SP1. Too much work in an area not associated with file
systems or storage to do.

wrote in message news:xxxxx@ntdev…
> David,
>
>> The PHB says: “I heard about this program/driver on the web and it should
>> only
>> take a few hours to turn it into a product we can sell”. The VB
>> programmer
>> who has been hired to write drivers says: “I am new so it will take a
>> couple of weeks”.
>> The CEO says: “We have enough money to last for two months and since the
>> product
>> will be ready in two weeks I won’t have to sell any more pieces off to
>> raise
>> more money”. >Crash, burn, and welcome to the unemployment office for
>> the workers.
>
> Few weeks ago I’ve seen quite an interesting observation on one of the
> threads that said the following: " You, guys, are proud of writing good
> drivers, but an end user seems to be fully content with a driver that
> works 90% of the time". The most interesting thing here is that the
> poster, indeed, had a good point.
>
> Believe me or not, but I know of the company that seems to be extremely
> successful these days, despite the fact that their driver is crap that has
> been developed around one of the well-known hooking samples that is
> available on the web, and no one in the whole company has a slightest
> idea about the rules of good design. For example, they do quite a few
> things that reasonable people would do in a helper user-mode app right in
> a driver. In general, their technical “expertize” is comparable to the one
> you have described above ( I already don’t mention the fact that the very
> purpose of their product is, in my opinion, at least questionable).
> However, they have quite a few large institutional clients who are more
> than willing to buy their crap.
>
> In other words, when it comes to making money, the keyword seems to be
> “successful marketing”, rather than “good design”. Therefore, there is no
> guarantee that the imaginary company that you have mentioned above is
> going to get busted that quickly(if ever)…
>
> Anton Bassov
>

> How about specifics so someone can contine the argument?

Unfortunately, I cannot do it for the legal reasons. The only think I can tell you for sure is that their driver can be rewritten as a “proper” filter without either a slightest problem or too much work. The only reason why I gave you this example is to show you that marketing may be far more important than quality. As I said already, I just cannot see any practical usefulness of their product in itself, but, because of their successful marketing, their customers are made believe that they need it badly (which is not-so-uncommon scenario when it comes to the security products)…

sometimes seeing certain activities can’t be achieved without hooking.

Well, controlling process creation, i.e. the thing my article is about, is just one example of such
requirement. However, your statement does not apply to their product - their driver can be rewritten as a filter without a slightest problem. The only reason why they use hooking is because a web sample their product is built around relies upon hooking, rather than filtering - they just have no clue about a software design whatsoever …

Anton Bassov

To Don
You said that it is full of shit! i said this article good and nice because i found it good at understanding the Kernel things. i think that doing such things gives you more inside of how OS works. i am not expert like you !. i am just a beginner! But you will agree that while learning you must have passed this process. Other wise you will not be able to comment on this. As you have to make silly mistakes that then you learn from those mistakes.
So silly or poor design it may be as it looks to you because you are expert in this field. But this article succeeded giving me some glimpse of "How things work”. Thought wrong or poorly designed it may be. Rest I do not agree on the point that you raised
That hooking is bad. Hooking is neutral. The purpose of hooking determines whether it is good or bad.

Second: if you hook for a commercial use you will be disposed for the rest of your life

This I want to ask you as I did not understand it. There are many software available in the market that does such things. Are they not legal? Or they can be sued for that use.
Like for example process hardening for parental control. Does it also come this category?
Though I am not using it for commercial use. And if I use it for commercial purpose that what is risk?

To :
anton bassov:
Thanks for sharing this information

But I want to ask if (someone can tell) that on driver unload you have written the code to unhook .then why it is failing to unhook.

with regards to all
deep

> Second: if you hook for a commercial use you will be disposed for the rest of your life

This I want to ask you as I did not understand it.

You should participate in the NG, so that you will have no questions when you see Don’s statement like that - instead, you will just say “Well, this is Don…”.

And if I use it for commercial purpose that what is risk?

Consider the scenario when 2 drivers want to hook the same export, and each of them wants to be the first in a call chain. It is fun to watch it for everyone, apart from the user. Now consider the scenario of Windows goes Linux way and makes dispatch table non-exported symbol, i.e. something that Linux did in the kernel version2.6. What is going to happen to your product???
The list goes on and on. I already don’t mention the scenario when invalid parameters are passed to a given API - you have to validate everything you touch…

But I want to ask if (someone can tell) that on driver
unload you have written the code to unhook .then why it is failing to unhook.

Because you unhook it not on unload but upon clicking a button. As I told you already, this is just a demo that is meant to be proof-of-concept only. Therefore, you should not take its failures too seriously - there are a couple of bugs in it anyway…

Anton Bassov

hello to All
here is a interesting finding
http://www.matousec.com/projects/windows-personal-firewall-analysis/plague-in-security-software-drivers.php

this article discuss about the vulnerabilites in the function and provide the utility for
checking the SSDT hooks
now i have Kaspersky AntiVirus (KA) and i run this tool to check whether KA does some kind of SSDT hooking. surpisingly it shows many ! now please can anybody explain that this shows comiercial hooks or not if so then … should they be disposed of for the rest of their life !

and do not take it otherwise. i just want to understand!

deep
regards!

From a technique point of view, AV’s and to a lesser extent some
firewalls are implemented not unlike the worst of malware; they are
profoundly invasive. While ill may not be their intent, they still
suffer from the same problems that anything implemented using hooking
and/or patching does, all of which can result in system instability,
gross reduction in performance and responsiveness, and, like malware,
are often very difficult to get rid of. Whether or not they are worth
it is a matter of opinion based on how one evaluates the legitimacy of
the threat, and what other measures are taken. Personally, assuming
that your machine is on a properly secured and maintained network at the
server/hardware, I don’t think either makes sense when you factor in
that they are not free, and that they are both really, really
irritating, but this is not really my thing.

In any case, anything based on hooking/patching is nearing the end,
assuming that we actually start using x64 Vista soon.

mm

xxxxx@yahoo.co.in wrote:

hello to All
here is a interesting finding
http://www.matousec.com/projects/windows-personal-firewall-analysis/plague-in-security-software-drivers.php

this article discuss about the vulnerabilites in the function and provide the utility for
checking the SSDT hooks
now i have Kaspersky AntiVirus (KA) and i run this tool to check whether KA does some kind of SSDT hooking. surpisingly it shows many ! now please can anybody explain that this shows comiercial hooks or not if so then … should they be disposed of for the rest of their life !

and do not take it otherwise. i just want to understand!

deep
regards!