A Quick Note…

Thanks to Girish Bharadwaj for the GMail invite. I’m officially one of the Cool People now, thanks to him! Check out his blog when you get a chance.

More About FAST_MUTEX

In an earlier post, I said that FAST_MUTEXes are more efficient than spin locks to use if you don’t need to synchronize at DISPATCH_LEVEL. In particular, that is true, in the sense of overall system efficiency (which was the intended sense), and as an added bonus, they actually seem to be faster to acquire in the uncontended case.

However, according to the disassembly, they hit the dispatcher lock in just the same way as regular KMUTEXes on release and on contended acquire. This makes those paths slower than the corresponding spin lock paths. The overall system efficiency gain is still worthwhile, though. Peter Wieland from Microsoft posted on NTDEV about this today.

Some Peculiar Peculiarities

A couple of odd things keep happening lately. First, a private high school that I do occasional volunteer work for tried to deploy XP SP2 onto an administrative computer today, and it slowed the entire box waaaay down. Windows would take 30 seconds to open, IMs would take 20 seconds to send, etc. It was terrible. After listening to this particular administrator’s agony for 5 minutes, I told her to just call Microsoft, as I had heard they were providing free tech support for SP2.

Well, it was true – they were. According to the administrator, the support person had heard of the problem, and the only known workaround was to uninstall the service pack. This is obviously not an optimal solution, and I didn’t get out there with a kernel debugger, so I really have no idea what went wrong. Anybody else have similar experiences?

Another oddball thing is this .Text blog. There is one bug that I keep running across, but aside from that, it’s a fine blogging package. However, it crashes on my Mac. I don’t get it – both Safari (default Mac browser, based on Konq) and latest Mac IE segfault and kindly ask me if I’d like to file a bug report with Apple. I don’t expect too much sympathy from the crowd that is likely to read this blog 🙂 but nonetheless, it’s weird. I’ve had maybe 3 other segfaults ever in the last 12+ months of active use. This .Text crash is pretty reliable, too. Who knows.

More .Text issues

For some reason, the last post leads to a weird .Text error if you click the feedback link. Sooo, if you have feedback for that previous post, whack the feedback link below *this* post.

More On IOCTL Security

Hello blogosphere! I’m back from an extended holiday weekend and feeling much refreshed. Let’s see if that improves the quality of these posts. 🙂

First, though, I’d like to give a Black Lump Of Coal (as opposed to a Gold Star(TM)) to Blockbuster Videos – the people who rent movies for a few nights – for their new marketing campaign. First, they are finally trying to answer NetFlix by going to a flat, per-month pricing model. OK, so that’s not so bad (but it still won’t compete with NetFlix), but in the process, they’ve created the Worst Euphamism Ever: they refer to an end to “EXTENDED VIEWING FEES”. Hahaha! They’re “Late Fees” when they’re trying to scare you into returning DVDs on time, threatening your credit, and in general, chewing you out for being a horrible person (this actually happened to my sister-in-law!). BUT, now that being late is a SELLING POINT, they’re conveniently called EXTENDED VIEWING FEES! Black Lump Of Coal, big time.

OK, with that little rant out of the way, let’s talk about two common security issues with IOCTLs. First, if you use either METHOD_DIRECT or METHOD_BUFFERED, you are guaranteed that the buffer will point to valid memory. It’ll be NonPagedPool or else it’ll be locked down with MmProbeAndLockPages(). – the OS locks down your pages for you.

HOWEVER, with METHOD_DIRECT, you *are* at risk of another kind of attack. Suppose that the user program has two threads in his program. Your driver receives the IOCTL request on thread 1 and validates its buffer. Then, thread 2 changes the contents of the buffer out from under it. Then, thread 1 reads something out of that buffer – say, for example, the valid length of the buffer (bad idea — this is given to you by the OS). Now you have an incorrect buffer length, and you’re either going to be reading or writing into memory you shouldn’t be. This can range from a crash to a security hole. The correct thing to do here is to “capture” the arguments once, up front. Once captured (via an RtlCopyMemory() or something similar), work only on the captured copy of the parameters.

METHOD_BUFFERED avoids this whole mess by capturing both the input buffer and the output buffer for you. The OS probes the buffers and then copies the input into a captured buffer. The output is also copied back by the OS. All of this is presumably done within the safe confines of proper OS-level exception handling, so you don’t risk crashing the system.

With METHOD_NEITHER, things get even worse. In addition to the attacks described above, the usermode program can actually invalidate the entire buffer. The pages aren’t probed and locked by the OS, and the address you will be referencing will be a usermode address. Finally, there’s one other consideration: because it is a usermode address, you cannot touch it unless you’re in the context of the calling process. Otherwise, you’ll be reading from or writing to the wrong process, also leading to either a security hole or a crash.

Some IOCTL Code Definition Tips

We’ve all* defined our own IOCTL codes in the past. They’re a primary way to enable user-mode -> driver and driver -> driver communication. Although they were probably originally envsioned in the context of storage-related drivers, Microsoft supports the use of an IOCTL dispatch in most kinds of drivers. NDIS, for example, supports NdisMRegisterDevice for the explicit purpose of providing access to the IOCTL framework in network drivers.

IOCTL codes are defined using the CTL_CODE() macro, which is part of ntddk.h in kernel-mode and winioctl.h in user-mode. The first parameter takes a Device Type, which can either be one of the Microsoft-defined device types (see the DDK headers for a list) or a custom device type code.

There are a couple of things to keep in mind here. The first is that the Device Type parameter must match the device type that is passed into IoCreateDevice(). Also, If you define a custom device type, it should be above 0x8000. The bottom 15 bits are what actually represent the device type, and the 16th bit is known as the Common bit. The DDK requires that the Common bit be set on all custom Device Types. Another way of saying this is by requiring all custom codes to be between 0x8000 and 0xFFFF. Similarly, the function code is required to be between 0x800 and 0xFFF, because the top bit (“Custom” in this case) is required to be set for non-Microsoft-defined function codes. Playing by the rules will make your driver as compatible as possible with all releases of the OS, present and future.

Method is one of METHOD_BUFFERED, METHOD_IN_DIRECT, METHOD_OUT_DIRECT, or METHOD_NEITHER. METHOD_BUFFERED is the most common transfer method, and is generally the safest and easiest to use. This method double-buffers your data by copying it from the supplied user-mode buffer into a newly-created kernel-mode buffer, and then passing that new buffer to your driver instead of the original one. If you’re transferring less than one page of data (4K on x86), and especially if you’r doing it infrequently, this is the way to go. If you’re tranferring larger amounts of data, one of the DIRECT methods may make sense. This is particularly true if you’re going to wind up DMAing your data to or from a device, but it is also true if you just want to avoid the double-buffer in general. I’m not going to discuss METHOD_NEITHER at the moment, other than to say that you shouldn’t use it. I’ll get in to more detail about why another day.

The final knob to turn is the RequiredAccess parameter. I admit that I really didn’t understand what this parameter was for until quite a while after I wrote my first driver. It turns out that it is a method for enforcing some small but nontrivial amount of access control on who can call your IOCTL. This specifies the kind of access the user must have to the device, as specified in the CreateFile() call, in order for the IO manager to let the IRP through. FILE_ANY_ACCESS means that they can send the IRP with virtually any access at all, as long as they have an open file handle to the driver. FILE_READ_ACCESS and FILE_WRITE_ACCESS loosely correlate to the ability to read and write data to and from the device.

Most driver writers just set this to FILE_ANY_ACCESS and forget about it. This is, of course, exactly the wrong thing to do. A much better strategy is to specify the most restrictive access possible (FILE_READ_ACCESS|FILE_WRITE_ACCESS — yes, you can OR them together) whenever possible, and only remove bits when necessary (“necessary” depends on the kind of driver you’re writing). This parameter is particularly important in IOCTLs where you’re actually reading and writing data — why would you allow a user to read data from an IOCTL if you wouldn’t allow the same user to read data using ReadFile()? — but it should probably be applied carefully to all IOCTLs.

Finally, it might be obvious, but try to name your IOCTL codes something obvious. My office has a standard that goes IOCTL__. In other words, you might have IOCTL_POSVPN_SET_INFO to configure our VPN driver. This goes with the standard rants about variable naming, and is generally an important thing if you want someone else to be able to work on your code.

OK, I expect everyone to run out and tighten up their use of CTL_CODE(). When you’re done with that, go listen to Fred Jones, Part 2, by Ben Folds. It’ll make you a Better Person.

Happy hacking!

* OK, “All” might be a bit of an exaggeration. 🙂

Inside the NT Insider

I just got the latest edition of the NT Insider from OSR in the mail today. They really out-did themselves with this issue. It’s 52 pages of my favorite topic: testing! There are lots of articles about debugging, testing, and so on. They’re well-written, as usual, and form a teriffic resource for budding driver developers and seasoned pros alike.

If you haven’t done so already, go over to www.osronline.com and register for a subscription. You won’t be sorry.

Two Quickies

If you’ve spent much time looking at Microsoft sample code or reading through the DDK headers, you’ve probably noticed a macro called PAGED_CODE(). The DDK defines it as:

#if DBG
#define PAGED_CODE() \
    { if (KeGetCurrentIrql() > APC_LEVEL) { \
         KdPrint(( "EX: Pageable code called at IRQL %d\n", KeGetCurrentIrql() )); \
         ASSERT(FALSE); \
    } \
#else
#define PAGED_CODE() NOP_FUNCTION;
#endif

As you can see, this function makes sure your code is being called at <= APC_LEVEL, which is a requirement for things like referencing pageable memory. It's a good idea to put this at the top of all of your functions that require <= APC_LEVEL. Because it compiles out in free builds, there's no real harm in using it. You'll be a better person for it.

Another nice thing to do is to mark your segments as pageable or as init if possible. Most of the Microsoft samples do this. it’s accomplished with a couple of pragma directives:

#pragma alloc_text (INIT, DriverEntry)
#pragma alloc_text (PAGE, AddDevice)

The idea here is to use the first pragma on any functions (like DriverEntry) that will never be called again after they run the first time. The OS can then discard them completely and not waste any more resources on them. The secnd pragma marks functions as pageable. meaning that the code can be paged out to disk if needed, to make room for other processes to execute. Note that this cannot be done for any code that might run at DISPATCH_LEVEL or higher, and as such is nicely mated with the PAGED_CODE() macro.

The Joy of NUMA

Dr. HardwareBlog has an article up about Non-Uniform Memory Architectures on his blog. It looks like the first in a series. This has interesting ramifications for all developers, including kernel-mode development. Keep an eye on it.

Driver Developer’s Toolbox, Part 2: WinDBG

It’s another back-to-basics day. Lots of driver developers post questions on various forums that basically boil down to “how do I debug my driver?”. Let me see if I can clear things up a bit.

If you want to be a serious driver developer, you will need a debugger. I know you don’t write bugs 🙂 but you might not understand something about the way the OS is behaving underneath you, so there is still a need to get good with a debugger. Furthermore, you’ll never understand how a computer works in general, or how Windows works in particular, until you’ve done some time staring at a debugging console. You need a debugger if you plan on using the checked build, running driver verifier, disabling system file protection, or looking at the output from your DbgPrint/KdPrint statements. And, of course, you need a debugger because there’s no other way: there is no printf() debugging or MessageBox() debugging in the kernel.

Taxonomy of Debuggers

There are really only two debuggers that are in common use in the driver development community. One is a product called SoftICE, from Compuware (formerly NuMega). It’s a good product, and above all, it’s a phenomenal hack, considering the way they’re able to slip the debugger between Windows and the bare iron. Because of this approach, SoftICE works on the actual computer you’re trying to debug (as opposed to WinDBG). One other benefit of SoftICE is that it runs on Windows 9x. If you’re a Poor Unfortunate Soul stuck with supporting one of those fine versions of Windows, SoftICE may be a good idea: the other debugger (wdeb386.exe) is *absolutely horrible*. Really. Unusable. Promise.

SoftICE does have a couple of drawbacks, though. First, it’s expensive. It only comes bundled with other products that you may not want or need. In fact, for the price of SoftICE, you can probably buy either VMWare (below) or a second computer to use as a debugging target. The bigger issue to me, however, is that it’s not the standard. Most kernel-mode programmers work with WinDBG. Questions about your driver that have debugger involvement will almost always be answered in the context of WinDBG. If you ever call Microsoft Product Support Services for help, WinDBG will be the assumption. That said, SoftICE really is a great product. if you want to go down that path, knock yourself out.

In general, though, it’s probably best to go to WHDC and download the Debugging Tools for Windows (also known as WinDBG). WinDBG (pronounced either “win-d-b-g” or “wind-bag”, depending on who you ask) is an incredibly powerful, feature-rich debugger for kernel-mode (and user-mode!) applications. In addition to the standard debugger intrinsics, Microsoft has shipped dozens of deubgger extensions that do higher-level things like look for locks, dump the contents of IRPs in a way that makes sense, and so on.

Setting Up Your Debugger

Getting kernel debugging set up is a little bit of a pain. There are two basic ways to go about it. The first way is to use two computers, conneted to each other by either a standard null-modem cable or by a FireWire cable. I’ve heard nothing but complaints about FireWire from Gary Little, a frequent contributor to NTDEV and the public Microsoft newsgroups, and I have never used it myself, so I generally recommend the good old fashioned rs-232 connection. One thing worth noting is that it has to be a plain-jane RS-232 port on the target machine; USB serial ports and the like won’t work, as they depend on the kernel loading lots of drivers to get them to work.

In addition to a physical connection, you have to modify the debug target computer’s boot.ini file. Generally, I remove the “/FASTBOOT” switch and add “/SOS /DEBUG /DEBUGPORT:COM1 /BAUDRATE:115200”. Speed is everything, so you want to use the highest baud rate that your box supports. Once you make the modifications, your computer will boot to a boot menu and prompt you as to whether or not you want to launch the debugging mode. Choose the “[Debugger Enabled]” option to make the kernel look for a kernel debugger.

If you don’t have a second computer handy, there is a new feature introduced with Windows XP that may be of some use. It adds the ability to do a limited form of local kernel debugging. This is similar to the livekd tool that was shipped with Inside Windows 2000, and is useful as a learning tool. It cannot be used to do any sort of invasive kernel debugging, though, so it’s mostly inappropriate for kernel development.

Another way to avoid getting a second debugging target computer is to use VMWare or Microsoft VirtualPC. I use VMWare every day to develop and test drivers. It is amazingly good for this sort of development. You can do remote kernel debugging over a named pipe from host to guest, and you can set up restore points, so you never have to worry about crashing and burning on a test computer. No more 10-minute re-ghosting procedures – restoring a crashed vm takes 10 seconds on my test computer. Note, however, that this is not totally sufficient for kernel development, as VMWare doesn’t emulate a multi-processor VM yet, and it can’t do 64-bit CPUs. All things considered, I’d never be caught trying to do driver development without VMWare. I’ve never used VirtualPC, but I hear it’s similar. VPC has the advantage of being included in MSDN subscriptions.

Working With The Debugger
In your debugging host computer, start WinDBG, choose Kernel Debug from the menu, and enter in the appropriate communication parameters. Once you hit OK, the deubgger will check the target computer, and you’re ready to go. Hit “Ctrl+Break” to break into the target. What you do from here is best learned by reading the debugger’s help file; typte .hh at the kd> prompt for more.

If your computer crashes while a debugger is attached, it won’t bluescreen. Instead, it will break into the debugger and give you a chance to figure out what is going on. One of the most useful commands to type at the kd> prompt on a crashed computer is “!analyze -v”. It will invoke an analysis extension in the debugger that is extremely good at figuring out what is wrong with the crashed computer. If you ever post a question on a public forum about a crashing driver, please be sure to include output from this command.

In order to get !analyze -v to work correctly, you must be running the correct symbols. Fortunately, Microsoft has fixed the Hell of Symbols in recent years. In current debuggers, you can use a symbol path that points to an Internet server from which the correct symbols are automatically downloaded. Not 100% of the OS symbols are found on the symbol server yet, so I also use an old-fashioned symbol directory for things such as service pack symbols, checked build symbols, etc. My symbol path winds up looking like:

srv*x:\symbols\symserv*http://msdl.microsoft.com/download/symbols;x:\symbols\2ksp4chk;...

Once your symbols are set up correctly, issuing a .reload command from the kd> prompt will load symbols to match the running binaries. The stack (‘kb’ at the kd> prompt) should now look more reasonable, depending on the kind of crash you have.

Wrap-Up
I only have one complaint about WinDBG: the Hell of Docking. Microsoft recently re-worked the user interface (I think this happened with 6.3), and I can’t get the damned thing to lay out the way I want it to any more. If anyone from Microsoft is reading, *please*, free us from the Hell of Docking! Let my people go!

I hope you’ve found this little tutorial useful. Debugging is an art form that takes a lifetime to master, and a nontrivial amount of learning just to become basically functional. The help file is good, and there are other resources on the Internet (particularly on microsoft.com). Also, don’t hesitate to post any questions to the WINDBG mailing list hosted by www.osronline.com, or to one of the public Microsoft newsgroups dealing with debugging. The OSR list is monitored by several people who know exactly what they’re doing, and the Microsoft groups get a lot of Microsoft employee participation from people that have abvoe-average amounts of clue.

Happy debugging!