Reliability of corrupted state exception handling

912 Views Asked by At

I'm currently looking into reliability features and exception handling of C# / .NET

These are especially the HandleProcessCorruptedStateExceptions attribute and CER s with PrepareConstrainedRegions.

Now I was reading the reference source code of the SecureString class, as this is a place where it is highly security critical to keep data encrypted even in exceptional situations, and found places similar like this:

[HandleProcessCorruptedStateExceptions]
//...

    RuntimeHelpers.PrepareConstrainedRegions();
    try
    {
        Unprotect();
        // ...
    }
    catch(Exception)
    {
        Protect();
        throw;
    }
    finally
    {
        Protect();
        // ...
    }

What is the reason for the catch block? Isn't the finally block sufficient to re-protect data?

Or could those corrupted state exceptions only affect catch and terminate the application afterwards?

2

There are 2 best solutions below

0
On

Code duplication in catch block is needed because of security breach in exception filtering feature (not provided by C#, but Visual Basic and others offer it). It allows malicious user to execute their code in your try-catch-finally block, after exception is caught and before finally block is executed.

Threat looks like this: Visual Basic user of your library causes exception after Unprotect() (even OutOfMemoryException by running out of memory), CLR finds no catch block, then CLR executes user's exception filter code, this code steals Unprotect()-ed data, and only then CLR executes Protect() in finally block.

So, put security cleanup code in both catch and finally blocks, usual cleanup stays in finally only.

1
On

Finally blocks are almost always called, except in a few cases. See

Does the C# "finally" block ALWAYS execute? for more.

So yes, the protect is always called in the Finally.