Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to clean up stack contents?

Tags:

c++

c

pci-dss

We are under a PCI PA-DSS certification and one of its requirements is to avoid writing clean PAN (card number) to disk. The application is not writing such information to disk, but if the operating system (Windows, in this case) needs to swap, the memory contents is written to page file. Therefore the application must clean up the memory to prevent from RAM capturer services to read sensitive data.

There are three situations to handle:

  • heap allocation (malloc): before freeing the memory, the area can be cleaned up with memset
  • static or global data: after being used, the area can be cleaned up using memset
  • local data (function member): the data is put on stack and is not accessible after the function is finished

For example:

void test()
{
  char card_number[17];

  strcpy(card_number, "4000000000000000");
}

After test executes, the memory still contains the card_number information.

One instruction could zero the variable card_number at the end of test, but this should be for all functions in the program.

memset(card_number, 0, sizeof(card_number));

Is there a way to clean up the stack at some point, like right before the program finishes?

like image 548
Juliano Avatar asked Jun 01 '17 18:06

Juliano


People also ask

Is it always necessary to clean up the stack?

There is only a certain amount of stack for a given thread of execution. Its purpose is to temporarily hold data needed when a function is called (such as the return address and parameters passed to the function). If you do not clean up the stack when your function exits, you will eventually run out of stack space.

What happens if stack memory is full?

If a program consumes more memory than the stack size, a stack overflow occurs, resulting in a program failure.

What happens when the stack gets filled?

When the stack fills up, you get a StackOverflowException exception. Of course the stack may fill up, if your code has a bug which causes runaway recursion, or if you use recursion to implement an algorithm which is unsuitable for recursion, like for example linear search.

How is stack memory cleared?

When a stack page is accessed for the first time, the operating system creates a new zero pages. In forking systems the stack gets cleared out whenever a new executable is loaded.


1 Answers

Cleaning the stack right when the program finishes might be too late, it could have already been swapped out during any point at its runtime. You should keep your sentitive data only in memory locked with VirtualLock so it does not get swapped out. This has to happen before said sensitive data is read.

There is a small limit on how much memory you can lock like this so you can propably not lock the whole stack and should avoid storing sensitive data on the stack at all.

like image 129
Grollicus Avatar answered Sep 23 '22 04:09

Grollicus