Securing Sensitive data in a program

Many applications need to handle sensitive data either in memory or on disk. If this sensitive data is not protected properly, it might lead to loss of secrecy or integrity of the data. It is very difficult (or expensive) to completely secure all the sensitive data. Users tend to use same passwords everywhere. So, even if your program is a simple game which stores user's profile information and requires user to enter a password, the user might choose the same password he uses for his online bank account for your game program! Now user's bank account is only as much secure as your program chooses it to be.
There are simple steps in which you can secure sensitive data in your program:

#include <sys/mman.h>

void *locking_alloc(size_t numbytes) {

     static short have_warned = 0;
     void *mem = malloc(numbytes);

     if(mlock(mem, numbytes) && !have_warned) {

       /* We probably do not have permission.
        * Sometimes, it might not be possible to lock enough memory.
        */

       fprintf(stderr, "Warning: Using insecure memory!\n");

       have_warned = 1;

     }     

     return mem;
}

For Unlocking the locked memory:

munlock(mem, numbytes)

There are certain negative consequences of above method. Not letting the page get swapped might cause a performance hit on the system. Also, if you lock two buffers which are on the same page and then unlock one of them, the other would also get unlocked. Typically, it is recommended to keep all the sensitive data in a single chunk (using structures, within the same virtual page) and then lock/unlock this structure. NOTE: these calls are privileged and might not be able to lock a page on certain systems at all.

Risk Assessment

If sensitive data is not handled correctly in a program, attacker can gain access to it.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC18-C

medium

probable

medium

P8

L2

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

References

\[[MSDN|AA. C References#MSDN]\] [{{EncodePointer()}}|http://msdn.microsoft.com/en-us/library/bb432254(VS.85).aspx], [{{DecodePointer()}}|http://msdn.microsoft.com/en-us/library/bb432242(VS.85).aspx]