Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


September 06, 2000

Structured Exception Handling and Security


RSS
Subscribe to Windows IT Pro | See More Security Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Structured exception handling (SEH) is a useful set of functionality included in the Win32 API that lets C code handle errors in your application in much the same way that C++ handles exceptions. (To learn more about exception handling with C++ code, read the Win32 software development kit—SDK—topic "Using Structured Exception Handling with C++."

Exception handling in C consists of three blocks: try, finally, and except. You encase any code for which you want to handle exceptions in a __try block; any code you place in a __finally block always executes no matter how you exit the __try block; and the __except block lets you customize how you handle exceptions. Let’s look at a quick example.

void foo(char* arg)
	{
    char buf[30];
    char* buf2;

    __try
    {
        strcpy(buf, arg);
        buf2 = malloc(30);
        strcpy(buf2, arg);
    }

    __except( MyHandler( GetExceptionCode() ))
    {
        printf( "Ended up in the handler - whoops!\n" );
    }

    __finally
    {
        if( buf2 != NULL )
            free( buf2 );
    }
}

If an exception occurs while any of the code in the __try block is executing, the OS starts looking for an exception handler. Because most code doesn’t have its own exception handler, the stack unwinds until you hit the handler that the OS puts around your application for you, and you see the familiar pop-up message telling you that your application has an unhandled exception at a certain address. I provided a handler in the code example, and the next code to execute will be your MyHandler() function, which takes the exception code as an int, and is expected to return an int. There are three possible returns:

  • EXCEPTION_CONTINUE_EXECUTION—this return ignores the exception and continues execution at the point where the exception occurred. You rarely want to use this option.
  • EXCEPTION_CONTINUE_SEARCH—this return tells the OS that you don’t know how to deal with this exception and to start looking for a higher-level exception handler.
  • EXCEPTION_EXECUTE_HANDLER—this return causes the code in your __except block to execute. One good way to use this return is to log extended debugging information that you can use to help diagnose problems that only occur in the field. If you want, you can now throw the exception to a higher-level exception handler by calling RaiseException().

Regardless of how you handle the exception, any time the code exits the __try block, the __finally block executes. In the code example, you use the __finally block to make sure that you never leave the function without freeing the memory you allocated (which is about all this particular example does correctly). In my <A HREF="http://www.windowsitsecurity.com/Articles/Index.cfm?ArticleID=9796">last article </A>, I used a goto statement to ensure that no matter where I needed to exit a fairly complicated function, that the code cleaned up all the memory I’d allocated. If I’d wanted to be a little more elegant, I could have enclosed my code in a __try block, then used a __leave to cause the code to jump into the __finally block. In most cases, these two constructs are equivalent. One benefit is that your code reviewer will usually look at __try, __finally, and __leave and think you’re pretty smart. But the real and useful benefit to using this approach over goto is that no matter how you leave the __try block—whether it is just by getting to the end of the section, an explicit __leave call, or by raising an exception—the __finally block will always execute. If you have opened Server Message Block (SMB) connections or accessed some other system resource (e.g., a shared mutex or semaphore), you’ll get a chance to at least try to clean up shared resources. Remember that exceptions can occur in a system API or a third-party library, so the problem might not even be in your code. This type of construct also lets you implement the same type of cleanup in C as destructors allow for in C++.

Now that I’ve explained how SEH works and why you should use it, let’s look at when you shouldn’t use it and why. In my article on buffer overruns, I explained how attackers can use code like that in the code example to overwrite the stack and control your application. Now that you have enclosed the offending code in a try-except block, you’re safe—right? Not at all! One problem is that the exception handler pointer also resides on the stack. Anything that can overwrite your return address can also overwrite your exception handler pointer. A buffer overrun just gives attackers two ways to make your code do what they like—either on exit to the function or at a point where an exception occurs.

When I was working on the ISS Scanner, we used SEH to help us find problems that we could only reproduce at the customer’s site, and the exception dumps often took me right to the line of code that was producing the error. However, don’t assume that SEH will help you protect your code against an attacker. Although SEH has many benefits, it's no substitute for writing solid, secure code in the first place. You can't use SEH in place of proper error checking and attention to detail. Ideally, you should use both to make your code more robust.

End of Article



Reader Comments
This code doesn't compile! A separate __try statement is required for each of the __except and __finally statements.

Seth June 21, 2004


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Friday at PASS Europe 2006

Kevin talks about the closing day of the event and shares a funny Microsoft film. ...

Escape From Yesterworld

Kevin points you to the funniest SQL Server website ever! ...


Security Whitepapers Anti-Virus Is Dead: The Advent of the Graylist Approach to Computer Protection

Getting the Job Done: Comparing Approaches for Desktop Software Lockdown

Instant Messaging, VoIP, P2P, and games in the workplace: How to take back control

Related Events Check out our list of Free Email Newsletters!

Security eBooks Spam Fighting and Email Security for the 21st Century

Understanding and Leveraging Code Signing Technologies

A Guide to Windows Certification and Public Keys

Related Security Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Maximize your SharePoint Investment – 8 Cities
Discover best practices and tips for both architecting and administering SharePoint. Early Bird Price of $99 through Sept 15th.

Find a new job now on the all new IT Job Hound!
Search jobs, post your resume, and set up job e-mail alerts!

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Top Tools for Virtualization Disaster Recovery & Replication
View this web seminar on August 14th to learn about two tools that will result in faster backup and restore with P2V disaster recovery.

SharePointConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

VMworld 2008 - Sign Up Today!
Join your peers on September 15-18 at The Venetian Hotel in Las Vegas as VMware hosts VMworld 2008, the leading Virtualization event.



Entrust Unified Communications Certs
Secure Exchange 2007 and save 20%. Now through Sept. 2008.

Increase Application Performance
Free White Paper by Editor's Best winner, Texas Memory Systems.

Need to convert between XML, DBs, EDI, and Excel? Try MapForce free!
Drag & drop to transform between popular data formats – get results instantly or generate code.

Microsoft® Tech•Ed EMEA 2008 IT Professionals
Advance your thinking with new ideas and practical real-world solutions at Microsoft’s FIVE day technical infrastructure conference 3-7 Nov., 2008. Register before 26 September 2008 to save €300.

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Are You Really Compliant with Software Regulations?
View this web seminar that will help you with compliance best practices and check out a management solution to assure that you won’t be in jeopardy of an audit.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16.
Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro Windows Dev Pro IT Job Hound ITTV
IT Library Technical Resources Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing