Home > C++, VC++, Windows API > How to create protected/readonly pages?

How to create protected/readonly pages?

Ever wondered if at all it’s possible to allocate read only chunk of memory. Now you may ask why we would  need to do something like this, well may be just for security reasons. So ideally what happens when we try write to read only memory? We typically get a message box which says…

—————————
Microsoft Visual C++
—————————
Unhandled exception in StaticArray.exe: 0xC0000005: Access Violation.
—————————
OK
—————————

It’s a final good-bye re-worded ;), unless there is a try/catch statement guarding this particular block!

Aha, This looks great! There are two functions in windows called VirtualAlloc and VirtualProtect. Use VirtualAlloc to allocate read only pages and just in case we wanna write something after we allocate a page but before we protect such a page then we use VirtualProtect.

Here is a sample function which creates a read only memory straightaway…

LPVOID CreateReadOnlyMemory( const DWORD MemSize )
{
// Take a look at the last parameter to this function
   return VirtualAlloc( NULL, MemSize, MEM_COMMIT, PAGE_READONLY );
}

int main()
{
LPBYTE pByte = static_cast< LPBYTE >( CreateReadOnlyMemory( MAX_PATH ));
try
{
pByte[0] = 10;
}
catch( … )
{
cout < < "\nCaught access violation error!!!"; } cout << "\nYippee! We survived access violation error, Mwhahaha!!!"; pByte[0] = 20; // This time doomed! }[/sourcecode] To remove a read only protection call VirtualProtect with any suitable access specifier mentioned in MSDN.

Advertisements
  1. February 23, 2009 at 4:15 am

    Just a demo mate, and also that’s what I meant by

    “and just in case we wanna write something after we allocate a page but before we protect such a page then we use VirtualProtect.”

  2. bw
    February 21, 2009 at 8:55 pm

    in my opinion it’s pointless, first of all if you need to allocate read only memory you would most probably put some data there first, so better solution would be to allocate RW memory and protect it afterwards with VirtualProtect

  3. February 17, 2009 at 4:23 am

    Thanks and glad to see you back again!

  4. John Schroedl
    February 16, 2009 at 4:22 pm

    Nice one! I think I’ll be able to use this. Thanks

    John

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: