Assembly SEH
From UIC
Inside Structured Exception Handling
Contents |
| Infos | |
|---|---|
| Author: | The Owl |
| Email: | |
| Website: | |
| Date: | 01/01/2001 (dd/mm/yyyy) |
| Level: |
|
| Language: | English |
| Comments: | |
Link e Riferimenti
Introduzione
SEH is a rather poorly documented field of the Win32 API, especially when it comes to assembly level implementation details. Having run into some protection schemes based on SEH i was forced to do some research on my own, the result of which i will present here.
First we will have a look at some concepts regarding SEH, then we shall see how it is implemented for high level language constructs, and finally i will present some code which implements the well known executable protection trick called the running line - for Win32 apps.
One note here: this whole doc is way less thorough than it could or in fact should be. Feel free to contribute...
Essay
As we all know software written by human beings often suffers from this very fact ;-). Effects of ill-behaved code bring the execution environment into what is called an exceptional state where execution has to be suspended until some entity resolves the problem and decides how to go on (e.g. resume or terminate execution).
In the wonderful world of Win32 each thread represents an execution environment with its own set of registers (on x86 machines this includes the general purpose registers, segment registers, DRx registers and the floating point registers as well).
When a thread attempts to execute an instruction that the processor does not want to, an exception will be raised and control will ultimately be passed to what is called an exception handler. An x86 processor has some 19 types of exceptions, however as life is always more complicated than it appears to be, some of them can be generated in very different situations. Intelligence built into the kernel exception handlers will eventually decide how to cope with each one of them.
Not only the processor can detect exceptional situations though. At a higher abstraction level, the operating system modules may also decide that certain attempted operations are not to be performed until some conditions are met (e.g. accessing allocated but not yet committed memory).
Since a multitasking/multithreaded operating system represents a rather complex environment, the generic kernel behaviour may not always be the best one. So it is quite natural to let the faulting thread try to recover from the exception. Microsoft calls her implementation of this mechanism Structured Exception Handling (SEH), details of which are unfortunately not very well documented (to my knowledge that is).
Implementation
First let's have a look at how a high level language programmer can make use of SEH. Since the primary language used to develop Win32 apps is C (and lately C++), SEH can be accessed at this level in the easiest way.
Microsoft extended the language with 4 new keywords:
- __try
- __except
- __finally
- __leave
Examples
The examples below show how they can be used in ones's own programs.
1) Example for __try/__leave/__finally
//\ do something useless
if (0) {
__leave;
} else {
}
}
__finally {
//\ "must execute" code here
}
The idea is to enclose some piece of code in a __try{} block and put everything that needs to be executed into the __finally{} block (no matter what errors occur in the __try{} block). This will even catch a premature return from the __try{} block, although at a rather high cost as far as code size/execution time overhead is concerned. For this reason one should use the __leave keyword to leave a __try{} block.
2) Example for __try/__except
//\ stupid code faults all the time ;-)
}
__except (MyExceptionFilter()) {
//\ let's deal with it
}
Here we have an extended implementation of the previous idea. namely now we can tell the runtime environment what we would like to do in case of an exception by having our exception filter function return an appropriate code. Our choices are:
| | |
|---|---|
| EXCEPTION_EXECUTE_HANDLER |
This will execute the __except{} block |
| EXCEPTION_CONTINUE_EXECUTION |
This will attempt to resume execution as if nothing had happened. Of course if the exception filter function did not resolve the problem, one will get the same exception again.... |
| EXCEPTION_CONTINUE_SEARCH |
Since __try{} blocks can be nested and/or exceptions may not be handled at some level deep in the function call hieararchy, we can instruct the runtime environment to search for an exception handler at the next higher level. Eventually the default handler will be called which will terminate the application. |
Note Finali
Greets:
Acp, animadei, bunter, ghiribizzo, gij, g-rom, groo, josephco, lordbyte, marquis, quine, randall flagg, slava, xoanon
Disclaimer
I documenti qui pubblicati sono da considerarsi pubblici e liberamente distribuibili, a patto che se ne citi la fonte di provenienza. Tutti i documenti presenti su queste pagine sono stati scritti esclusivamente a scopo di ricerca, nessuna di queste analisi è stata fatta per fini commerciali, o dietro alcun tipo di compenso. I documenti pubblicati presentano delle analisi puramente teoriche della struttura di un programma, in nessun caso il software è stato realmente disassemblato o modificato; ogni corrispondenza presente tra i documenti pubblicati e le istruzioni del software oggetto dell'analisi, è da ritenersi puramente casuale. Tutti i documenti vengono inviati in forma anonima ed automaticamente pubblicati, i diritti di tali opere appartengono esclusivamente al firmatario del documento (se presente), in nessun caso il gestore di questo sito, o del server su cui risiede, può essere ritenuto responsabile dei contenuti qui presenti, oltretutto il gestore del sito non è in grado di risalire all'identità del mittente dei documenti. Tutti i documenti ed i file di questo sito non presentano alcun tipo di garanzia, pertanto ne è sconsigliata a tutti la lettura o l'esecuzione, lo staff non si assume alcuna responsabilità per quanto riguarda l'uso improprio di tali documenti e/o file, è doveroso aggiungere che ogni riferimento a fatti cose o persone è da considerarsi PURAMENTE casuale. Tutti coloro che potrebbero ritenersi moralmente offesi dai contenuti di queste pagine, sono tenuti ad uscire immediatamente da questo sito.
Vogliamo inoltre ricordare che il Reverse Engineering è uno strumento tecnologico di grande potenza ed importanza, senza di esso non sarebbe possibile creare antivirus, scoprire funzioni malevoli e non dichiarate all'interno di un programma di pubblico utilizzo. Non sarebbe possibile scoprire, in assenza di un sistema sicuro per il controllo dell'integrità, se il "tal" programma è realmente quello che l'utente ha scelto di installare ed eseguire, né sarebbe possibile continuare lo sviluppo di quei programmi (o l'utilizzo di quelle periferiche) ritenuti obsoleti e non più supportati dalle fonti ufficiali.
Categories: Assembly | The Owl | 2001