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…

[sourcecode language=’cpp’]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.

4 thoughts on “How to create protected/readonly pages?

  1. 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

  2. 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.”

Appreciate your comments...