C++ Logo


Advanced search

Re: Memory Safety and Page Protected Memory

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Thu, 29 Feb 2024 08:53:49 +0000

> Let's say you designate a piece of memory intended to store passwords. How would you prevent the application from accessing it when in parts "when the access is illegitimate"

Like this...

void password_check()
{ char username[20];
 char password[20];
 char* page_protected_password = (char*) memory_safe_alloc(20);

void do_something_stupid(char* username)
{ // not this obvious, but code in this function does:
 char* password = username+20;// uh, oh!

The page_protected_password is in its own bubble. A programmer can't land in the page_protected_password buffer by overrunning some nearby pointer like username. Nor can the programmer overrun the page_protected_password buffer without a segfault or signal triggered.

You are right if thinking that get_pass(page_protected_password), or any function passed that pointer, may do whatever it likes with page_protected_password. Being memory safe gives protection from buffer overruns, doesn't mean error-proof.


Ok, I can totally see the possible construction of a class let's call it "ProtectedMemory", that could be used like this:

ProtectedMemory sensitive_data;
sensitive_data.allocate(size, alignment);
sensitive_data.unlock(); //switches to OS privileged mode to unlock the data and returns to caller
legitimate_use_function(sensitive_data.data()); //ok
sensitive_data.lock(); //switches to OS privileged mode to lock the data and returns to caller
sneaky_bad_function(sensitive_data.data()); //segfaults

Now this wouldn't be full proof, you would still be able to have illegitimate access to sensitive memory while the buffer is unlocked (not entirely sure if it is possible to limit access to specific threads only), and it wouldn't do much if a malicious attacker gets random code execution. But it may be able to make it harder to access via a buffer overrun even if it doesn't stop it completely.

This of course will require some cooperation of the operating system to be able to implement it, and lets hope it doesn't cause a more serious bug where a badly crafted unlock command unlocks access to memory in a different application. But it looks feasible in theory, but someone with a better understanding of the topic might be able to weigh in on this.

Received on 2024-02-29 08:53:54