• The Old New Thing

    Your debugging code can be a security vulnerability: Loading optional debugging DLLs without a full path

    • 49 Comments

    Remember, the bad guys don't care that your feature exists just for debugging purposes. If it's there, they will attack it.

    Consider the following code:

    DOCLOADINGPROC g_pfnOnDocLoading;
    
    void LoadDebuggingHooks()
    {
     HMODULE hmodDebug = LoadLibrary(TEXT("DebugHooks.dll"));
     if (!hmodDebug) return;
     g_pfnOnDocLoading = (DOCLOADINGPROC)
                   GetProcAddress(hmodDebug, "OnDocLoading");
     ...
    }
    
    HRESULT LoadDocument(...)
    {
     ...
     if (g_pfnOnDocLoading) {
       // let the debugging hook replace the stream
       g_pfnOnDocLoading(&pstmDoc);
     }
     ...
    }
    

    When you need to debug the program, you can install the DebugHooks.dll DLL into the application directory. The code above looks for that DLL and if present, gets some function pointers from it. For illustrative purposes, I've included one debugging hook. The idea of this example (and it's just an example, so let's not argue about whether it's a good example) is that when we're about to load a document, we call the OnDocLoading function, telling it about the document that was just loaded. The OnDocLoading function wraps the IStream inside another object so that the contents of the document can be logged byte-by-byte as it is loaded, in an attempt to narrow down exactly where document loading fails. Or it can be used for testing purposes to inject I/O errors into the document loading path to confirm that the program behaves properly under those conditions. Use your imagination.

    But this debugging code is also a security vulnerability.

    Recall that the library search path searches directories in the following order:

    1. The directory containing the application EXE.
    2. The system32 directory.
    3. The system directory.
    4. The Windows directory.
    5. The current directory.
    6. The PATH.

    When debugging your program, you install DebugHooks.dll into the application directory so that it is found in step 1. But when your program isn't being debugged, the search in step 1 fails, and the search continues in the other directories. The DLL is not found in steps 2 through 4, and then we reach step 5: The current directory.

    And now you're pwned.

    Your application typically does not have direct control over the current directory. The user can run your program from any directory, and that directory ends up as your current directory. And then your LoadLibrary call searches the current directory, and if a bad guy put a rogue DLL in the current directory, your program just becames the victim of code injection.

    This is made particularly dangerous when your application is associated with a file type, because the user can run your application just by double-clicking an associated document.

    When you double-click a document, Explorer sets the current directory of the document handler application to the directory that contains the document being opened. This is necessary for applications which look around in the current directory for supporting files. For example, consider a hypothetical application LitWare Writer associated with *.LIT files. A LitWare Writer document ABC.LIT file is really just the representative for a family of files, ABC.LIT (the main document), ABC.LTC (the document index and table of contents), ABC.LDC (the custom spell check dictionary for the document), ABC.LLT (the custom document layout template), and so on. When you open the document C:\PROPOSAL\ABC.LIT, LitWare Writer looks for the other parts of your document in the current directory, rather than in C:\PROPOSAL. To help these applications find their files, Explorer specifies to the CreateProcess function that it should set the initial current directory of LitWare Writer to C:\PROPOSAL.

    Now, you might argue that programs like LitWare Writer (which look for the ancillary files of a multi-file document in the current directory instead of the directory containing the primary file of the multi-file document) are poorly-written, and I would agree with you, but Windows needs to work even with poorly-written programs. (Pre-emptive snarky comment: Windows is itself a poorly-written program.) There are a lot of poorly-written programs out there, some of them industry leaders in their market (see above pre-emptive snarky comment) and if Windows stopped accommodating them, people would say it was the fault of Windows and not the programs.

    I can even see in my mind's eye the bug report that resulted in this behavior being added to the MS-DOS Executive:

    "This program has worked just fine in MS-DOS, but in Windows, it doesn't work. Stupid Windows."

    Customers tend not to be happy with the reply, "Actually, that program has simply been lucky for the past X years. The authors of the program never considered the case where the document being opened is not in the current directory. And it got away with it, because the way you opened the document was to use the chdir command to move to the directory that contained your document, and then to type LWW ABC.LIT. If you had ever done LWW C:\PROPOSAL\ABC.LIT you would have run into the same problem. The behavior is by design."

    In response to "The behavior is by design" is usually "Well, a design that prevents me from getting my work done is a crappy design." or a much terser "No it's not, it's a bug." (Don't believe me? Just read Slashdot.)

    So to make these programs work in spite of themselves, the MS-DOS Executive sets the current directory of the program being launched to the directory containing the document itself. This was not an unreasonable decision because it gets the program working again, and it's not like the program cared about the current directory it inherited from the MS-DOS Executive, since it had no control over that either!

    But it means that if you launched a program by double-clicking an associated document, then unless that program takes steps to change its current directory, it will have the document's containing folder as its current directory, which prevents you from deleting that directory.

    Bonus chatter: I wrote this series of entries nearly two years ago, and even then, I didn't consider this to be anything particularly groundbreaking, but apparently some people rediscovered it a few months ago and are falling all over themselves to claim credit for having found it first. It's like a new generations of teenagers who think they invented sex. For the record, here is some official guidance. (And just to be clear, that's official guidance on the current directory attack, not official guidance on sex.)

    History chatter: Why is the current directory even considered at all? The answer goes back to CP/M. In CP/M, there was no PATH. Everything executed from the current directory. The rest is a chain of backward compatibility.

  • The Old New Thing

    The curse of the current directory

    • 44 Comments

    The current directory is both a convenience and a curse. It's a convenience because it saves you a lot of typing and enables the use of relative paths. It's a curse because of everything else.

    The root cause of this curse is that the Windows NT family of operating systems keeps open a handle to the process's current directory. (Pre-emptive Yuhong Bao comment: The Windows 95 series of operating systems, on the other hand, did not keep the current directory open, which had its own set of problems not relevant to this discussion.)

    The primary consequence of this curse is that you can't delete a directory if it is the current directory of a running process. I see people stumble upon this all the time without realizing it.

    I am trying to delete a directory X, but when I try, I get the error message The process cannot access the file because it is being used by another process.. After some hunting around, I found that directory X is being held open by someapp.exe. Why the heck is someapp.exe holding my directory open, and how do I get it to stop?

    The value of someapp.exe changes over time, but the underlying problem is the same. And when this happens, people tend to blame someapp.exe for stupidly holding a directory open.

    Most of the time, someapp.exe is just a victim of the curse of the current directory.

    First, let's take the case where someapp.exe is explorer.exe. Why is the current directory of Explore set to this directory?

    Well, one reason might be another curse of the current directory, namely, that the current directory is a process-wide setting. If a shell extension decided to call SetCurrentDirectory, then that changes the current directory for all of Explorer. And if that shell extension doesn't bother to call SetCurrentDirectory a second time to reset the current directory to what it was, then the current directory gets stuck at the new directory, and Explorer has now been conned into changing its current directory permanently to your directory.

    Mind you, the shell extension might have tried to do the right thing by setting the current directory back to its original location, but the attempt might have failed:

    GetCurrentDirectory(Old) // returns C:\Previous
    SetCurrentDirectory(New) // changes to C:\Victim
    .. do stuff ..
    SetCurrentDirectory(Old) // changes to C:\Previous - fails?
    

    That second call to SetCurrentDirectory can fail if, while the shell extension is busy doing stuff, the directory C:\Previous is deleted. Now the shell extension can't change the directory back, so it's left stuck at C:\Victim, and now you can't delete C:\Victim because it is Explorer's new current directory.

    (The preferred behavior, by the way, is for the shell extension not to call SetCurrentDirectory in the first place. Just operate on full paths. Since the current directory is a process-wide setting, you can't be sure that some other thread hasn't called SetCurrentDirectory out from under you.)

    Mind you, making the current directory a per-thread concept doesn't solve this problem completely, because the current directory for the thread (if such a thing existed) would still have a handle open until the thread exited. But if the current directory had been a per-thread concept, and if the thread were associated with an Explorer window, then closing that window would at least encourage that thread to exit and let you unstick the directory. That is, unless you did a Terminate­Thread, in which case the handle would be leaked and your attempt to release the handle only ensures that it never happens. (Note to technology hypochondriacs: This paragraph was a hypothetical and consequently will be completely ineffective at solving your problem.)

    The story isn't over yet, but I'll need to digress for a bit in order to lay the groundwork for the next stage of the curse.

    Bonus chatter: Hello, people. "The story isn't over yet." Please don't try to guess the next chapter in the story.

  • The Old New Thing

    Is there any vendor bias in the way the Start menu determines which programs are most frequently used?

    • 39 Comments

    Chrissy wants to know if there is a bias towards Microsoft products in the selection of most frequently used programs on the Start menu.

    The only bias is in the initial default MFU list, the one that appears upon a fresh login. In Windows XP, the default Start menu MFU contains six slots. The first three point to Windows applications, and the second three point to programs chosen by the OEM. (If the OEM chooses not to take advantage of this feature, or if this is a boxed version of the product, then the second three slots also point to Windows applications.) Which specific three (or six) programs get displayed depend on the system configuration, so it's not like there's a single initial Start menu that applies to everyone.

    Once those initial MFU items are selected, the Start menu algorithm proceeds in a vendor-blind manner. (Indeed, it doesn't even know who the vendor is; no part of the algorithm looks at file version information.)

    The precise algorithm that is used for determining which programs go on the MFU over time has been reviewed by government-appointed regulators, who have not raised any concerns over vendor bias.

    So I hate to say it, Chrissy, but I think it's all in your head.

  • The Old New Thing

    Why does the Win32 Time service require the date to be correct before it will set the time?

    • 43 Comments

    Public Service Announcement: Daylight Saving Time ends in most parts of the United States this weekend.

    Andy points out that if you attempt to synchronize your clock when the date is set incorrectly, the operation fails with the error message "An error occurred while Windows was synchronizing with time.windows.com. For security reasons, Windows cannot synchronize with the server because your date does not match. Please fix the date and try again." He wonders what the security risk is.

    First of all, for people who are trying to solve the problem, the solution is to follow the steps in the error message. Set your date to the correct date, then try again. If that doesn't help, also set the time to something close to the correct time. Once your time gets close, the time server can nudge it the rest of the way.

    Back to the original question: What is the security risk being defended against, here?

    At first glance, you might think that the server is attempting to defend itself against a client whose time is set incorrectly, but actually the potential attack is in reverse: Your computer is protecting itself against a rogue time server.

    The Kerberos authentication protocol relies heavily on all participants agreeing on what time it is (with some slop tolerance). If somebody manages to fool the client into synchronizing its time against a rogue server (for example, by using a DNS poisoning attack), the attacker can use that invalid date (typically a backdate) as a foothold for the next level of attacks.

    The default configuration for the Windows Time service is to reject attempts to change the clock on domain-joined machines by more than 15 hours. You can change the configuration settings by following the instructions in this KB article (which happens also to have been the source material for most of this article).

  • The Old New Thing

    The story of MUI, as told by others (with some commentary)

    • 33 Comments

    First, the story as told by others:

    Now the question you're all going to ask so I may as well answer it: Why is this information kept in a desktop.ini file instead of being attached to the file itself (say, in an alternate stream)? If it were in an alternate stream, then it would track the file when it was moved or copied.

    First answer: Because alternate streams require NTFS. Localized names were introduced in Windows 2000, and Windows 2000 gave you the option of formatting your drive as FAT or NTFS. (It wasn't until Windows Vista that NTFS became mandatory.) Therefore the mechanism for localized names needed to work when your drive was formatted as FAT.

    Okay, fine, maybe you tell people, "Sorry, this feature requires NTFS." All those multinational corporations who use FAT-formatted drives in the year 2000 are screwed.

    Well, placing the information in an alternate data stream means that each file would have to be accessed just to get its name. Remember, it's more efficient when you buy in bulk. Consider a directory with 500 files. A simple directory listing like one provided by cmd.exe takes, say, seven I/O requests (open directory, five "give me the next 100 files", close directory). If each file had to be opened in order to probe for an alternate stream, you now have 507 I/O requests: open directory, five "give me the next 100 files", close directory; and then 500 "open alternate stream on this file" calls that fail. And that was the optimistic case where the localized name doesn't exist. For the pessimistic case where every file has a localized name, the I/O count balloons to 1507: open directory, five "give me the next 100 files", close directory; and then 500 × (open alternate stream, read localized name, close alternate stream).

    You increased the number of I/O requests by a factor of over 200. And when you are looking at files on a slow network (hello, multinational company with servers all over the world), that factor can be deadly. Suppose the ping time to the server is 500ms. The cmd.exe program gets you the directory listing in three and a half seconds. The alternate data stream localized name version takes twelve minutes.

    On the other hand, if all the localized names are placed in a single file, then the I/O count is only 10: open directory, five "give me the next 100 files", close directory; open desktop.ini, read contents, close desktop.ini. We're down to five seconds. Not as good as three and a half seconds, but way better than twelve minutes. And if, in the common case, the directory contains no localized names, the open desktop.ini step fails, and we save two I/O's, bringing our time down to four seconds. And then you can be clever and say, "Wait a second, I already have the directory listing; I can just look at the results to see if desktop.ini is on the list. If not, then I don't even have to bother trying to open it!" Now you are back to three and a half seconds.

    Okay, maybe you tell people, "Sorry, this feature requires a high-speed network." All those multinational corporations with servers around the world are screwed. The theoretically highest-speed network connection between New York and Tokyo has a 72ms ping time because that's how fast it takes light itself to travel that distance and back. Your 500-file directory takes nearly two minutes to display.

    Seeing as multinational corporations were the initial target audience for the MUI feature (since they're the ones who are most likely to have users with different language preferences), designing your feature so that your target audience can't use it seems like a pretty bad execution plan.

    A file's name is traditionally considered metadata, and traditionally, metadata is visible without requiring access to the file. A file can show up in a directory listing even though you don't have access to it. But if the file's localized name is stored in the file itself, you now have the situation where you don't even know the name of the file because you can't access it. This is even worse than I'm sorry, you don't have permission to know where this shortcut file should show up in the Explorer window. This would be I'm sorry, you don't have permission to know the name of the file in this directory listing.

    Remember that reading from an alternate data stream triggers a recall if the file had been archived to tape. You don't want to have to restore an entire directory from tape just because somebody opened the folder in Explorer.

    And finally, alternate data streams are very fragile. Any tool that processes a file has a decent chance of inadvertently destroying the alternate data streams. (And good luck if your backup program doesn't preserve the alternate data streams.)

  • The Old New Thing

    The quiet fading away of the CtlPanelClass

    • 23 Comments

    If you search MSDN for CtlPanelClass, you'll find a few really old Knowledge Base articles that include it in a list of "class names of common Windows applications." I'm not sure why the Knowledge Base articles bothered to list those classes; there is no technical reason for applications to need to know this, and including the information merely encourages programmers to rely on the window class name in strange undocumented ways. (This is another one of those cases where a Knowledge Base article written to assist in troubleshooting becomes interpreted as formal documentation.)

    Windows Vista finally got rid of that window class. It took only ten years.

    The window class was used by the old Windows 3.1 Control Panel application. Back in Windows 3.1, the Control Panel was a standalone application and was not integrated into the shell namespace (in large part because there was no such thing as a shell namespace back then for it to be a part of).

    There was one program which not only searched for a window of that specific class name, but it also sent the window WM_COMMAND messages, since of course it knew what the menu IDs were for the Control Panel application, and it knew that the Windows developers would never change the IDs or replace the standalone Control Panel application with anything else.

    When the standalone Control Panel application was converted to a virtual folder, it also came with some decoys in order to maintain compatibility with older programs that relied on the old behavior in strange undocumented ways.

    One of those decoys, the CtlPanelClass was removed for Windows Vista. A crash was traced back to a bug in the decoy window which manifested itself if a control panel took more than ten seconds to launch itself. To fix the bug, we just removed the decoy window, but we were prepared to write a compatibility shim in case there were people still running that ancient application from 1993. We didn't actually turn the compatibility shim on, but we were ready just in case.

    We removed the decoy and crossed our fingers.

    We got lucky. Nobody noticed.

  • The Old New Thing

    The wisdom of seventh graders: Being President

    • 28 Comments

    Today is Election Day in the United States. Some years ago, seventh grade students (age 12) were asked to imagine they had just been elected president and to give an address to the nation on one thing they would change.

    Remember, these are only the most entertaining ideas. Do not assume all student ideas are like these.

    • Ban "all types of non-purpose car racing."
    • Defend against zombie attack.
    • Withdraw from Iraq and use the money to fund electric cars and ban smoking.
    • Repeal all taxes.
    • Name Arnold Schwarzenegger as Vice President.
    • Shorten all school days to increase learning.
    • Build a holographic wall at the border. For the immigrants who don't fall for it and run right through, station border patrol just behind it.
    • Shut down all cigarette factories. "If you somehow manage to get cigarettes, we don't care."
    • Make chocolate milk the official drink.

    And this sentence came from a student destined for greatness as a politician: "Something must be done, and I will make it happen."

  • The Old New Thing

    Saying that your case is different doesn't make it so

    • 24 Comments

    A customer wanted to do one of those user-hostile things that Windows doesn't make easy to do (the sort of thing I tend to call out on this Web site). After receiving an explanation that Windows doesn't provide a way of doing what they want because it abuses the component in question and goes against user expectations, the customer countered, "Yes, we understand that, but our case is different."

    The customer then proceeded to explain how they intended to use this newfound power (if only they could figure out how to do it) and under what circumstances they intend to invoke it. Their explanation was interesting in that the description could be applied to any other program on the planet.

    Yes, we understand that, but our case is different. We would do this only after the user installs the program or reconfigures it from the Add or Remove Programs control panel. After a few days, we would stop doing it, unless triggered by a reinstall or a reconfiguration.

    So far, there's nothing here that explains why your program should be able to do this, but not, say, Photoshop. There is no evidence that this program is any different from the tens of thousands of other programs out there, many of which probably want to do that very same thing this program wants to do.

    Just because you say that your case is different doesn't make it so.

  • The Old New Thing

    Why doesn't the End Task button end my task immediately?

    • 64 Comments

    Commenter littleguru asks, "Why does the End Now button not kill the process immediately?"

    When you click the End Now button, the process really does end now, but not before a brief message from our sponsor.

    When you kill a hung application, Windows Error Reporting steps in to record the state of the hung application so it can be submitted to the mother ship (with your permission). If you are running Windows XP or Windows Vista, you can briefly see a process called dumprep.exe or WerFault.exe; these are the guys who are doing the data collection.

    After being uploaded to Microsoft, these failure reports are studied to determine why the application stopped responding and what could be done to fix it. I've been asked to do quite a few of these analyses myself, and sometimes it's something pretty mundane (an application sends a cross-thread message while holding a critical section, and the thread can't receive the message because it's stuck waiting for the critical section that the sender is holding—classic deadlock), and sometimes it's something pretty weird (application has a bug if the number of sound output devices is not equal to one). Whatever the reason, I write up my analysis, and the people who are in charge of such things make arrangements for the information to be sent back to the vendors who wrote the application (assuming the vendors are registered with Winqual).

    If you don't want Windows Error Reporting to collect application crash and hang reports, you can disable it from the Group Policy Editor under Windows Error Reporting. Of course, if you do this, then you don't get to vote on which program crashes and failures Microsoft should work on fixing.

    Note: This entry is an experiment: I mentioned Windows Error Reporting and WHQL. If people complain about digital certificate authorities, that'll just confirm my bias against returning to those old debugging stories.

    Update: Experimental results obtained. No more stories involving Windows Error Reporting and WHQL.

  • The Old New Thing

    It's the Great Pumpkin, Charlie Brown: The world of competitive pumpkin-growing

    • 7 Comments

    Bill Littlefield of NPR's sports program Only a Game interviews Susan Warren about competitive pumpkin-growing. [Direct link - Real format] An excerpt from her book Backyard Giants was printed in The Wall Street Journal: The Race to Break the Squash Barrier, the quest to grow a one-ton pumpkin. I'm fascinated by these subcultures of people obsessed with one thing.

Page 125 of 432 (4,312 items) «123124125126127»