<p>I want to create an allocator which provides memory with the following attributes:</p>

<ul>
<li>cannot be paged to disk.    </li>
<li>is incredibly hard to access through an attached debugger</li>
</ul>

<p>The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.</p>

<p><strong>Updates</strong></p>

<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194">Josh</a> mentions using <code>VirtualAlloc</code> to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the <code>VirtualLock</code> function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.</p>

<pre><code>//
template&lt;class _Ty&gt;
class LockedVirtualMemAllocator : public std::allocator&lt;_Ty&gt;
{
public:
    template&lt;class _Other&gt;
    LockedVirtualMemAllocator&lt;_Ty&gt;&amp; operator=(const LockedVirtualMemAllocator&lt;_Other&gt;&amp;)
    {   // assign from a related LockedVirtualMemAllocator (do nothing)
        return (*this);
    }

    template&lt;class Other&gt;
    struct rebind {
        typedef LockedVirtualMemAllocator&lt;Other&gt; other;
    };

    pointer allocate( size_type _n )
    {
        SIZE_T  allocLen = (_n * sizeof(_Ty));
        DWORD   allocType = MEM_COMMIT;
        DWORD   allocProtect = PAGE_READWRITE;
        LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
        if ( pMem != NULL ) {
            ::VirtualLock( pMem, allocLen );
        }
        return reinterpret_cast&lt;pointer&gt;( pMem );
    }
    pointer allocate( size_type _n, const void* )
    {
        return allocate( _n );
    }

    void deallocate(void* _pPtr, size_type _n )
    {
        if ( _pPtr != NULL ) {
            SIZE_T  allocLen = (_n * sizeof(_Ty));
            ::SecureZeroMemory( _pPtr, allocLen );
            ::VirtualUnlock( _pPtr, allocLen );
            ::VirtualFree( _pPtr, 0, MEM_RELEASE );
        }
    }
};
</code></pre>

<p>and is used</p>

<pre><code> //a memory safe std::string
 typedef std::basic_string&lt;char, std::char_traits&lt;char&gt;, 
                           LockedVirtualMemAllocato&lt;char&gt; &gt; modulestring_t;
</code></pre>

<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708">Ted Percival</a> mentions mlock, but I have no implementation of that yet.</p>

<p>I found <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography by Neil Furguson and Bruce Schneier</a> quite helpful as well.</p>

[{'answer_id': 8476, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 2, 'selected': False, 'text': '<p>What you are asking for is handled at the OS level.  Once the data is in your program, it is liable to be paged out.</p>\n\n<p>For accessing the memory, a motivated individual can attach a hardware debugger.</p>\n'}, {'answer_id': 8482, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': 3, 'selected': False, 'text': "<p>Let's take this a bit at a time:</p>\n\n<blockquote>\n  <p>I want to create an allocator which\n  provides memory with the following\n  attributes:</p>\n</blockquote>\n\n<p>That's fair enough.</p>\n\n<blockquote>\n<pre><code>* cannot be paged to disk.\n</code></pre>\n</blockquote>\n\n<p>That's going to be hard. As far as I am aware, you cannot disable Virtual Paging as it is handled by the OS. If there is a way, then you'll be spelunking in the bowels of the OS.</p>\n\n<blockquote>\n<pre><code>* is incredibly hard to access through an attached debugger\n</code></pre>\n</blockquote>\n\n<p>You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit.</p>\n\n<blockquote>\n  <p>The idea is that this will contain\n  sensitive information (like licence\n  information) which should be\n  inaccessible to the user. I have done\n  the usual research online and asked a\n  few other people about this, but I\n  cannot find a good place start on this\n  problem.</p>\n</blockquote>\n\n<p>Keep all sensitive information off the machine. Seriously. Don't store sensitive information in memory. Write a custom delete routine that will automatically remove all data from any allocations you perform. Never allow general access to a machine with sensitive material on it. If you perform db access, make sure all access is sanitized before firing. Only people with specific log-ins are allowed to access. No general group access.</p>\n\n<blockquote>\n  <p>On a side note, what other methods are\n  there of accessing the memory of a\n  process other than attaching a\n  debugger?</p>\n</blockquote>\n\n<p>Taking a dump of the memory.</p>\n"}, {'answer_id': 8486, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 5, 'selected': True, 'text': "<p>You can't really protect against memory access.  You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory.  Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way.</p>\n\n<p>Even if you could somehow completely lock down your process and guarantee that the OS would <em>never</em> allow anyone else to access your process, you still don't have full protection.  The entire OS could be running in a virtual machine, which could be paused and inspected at any time.</p>\n\n<p>You <em>cannot</em> protect memory contents from the owner of the system.  Hollywood and the music industry have been aching for this for years.  If it were possible, they'd already be doing it.</p>\n"}, {'answer_id': 8490, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 1, 'selected': False, 'text': "<p>@graham</p>\n\n<blockquote>\n  <p>You could run it through PGP and store it encrypted in memory and unencrypt it as needed. Massive performance hit.</p>\n</blockquote>\n\n<p>Then you'd have to hold the key in memory.  That would make it a little harder, but definitely not impossible.  Anyone motivated will still manage to get the data from memory.</p>\n"}, {'answer_id': 8530, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': -1, 'selected': False, 'text': '<p>@Derek: Oh, but with trusted computing, you can use <a href="http://en.wikipedia.org/wiki/Trusted_Computing#Memory_curtaining" rel="nofollow noreferrer">memory curtaining</a>! :-P&lt;/devils-advocate&gt;</p>\n'}, {'answer_id': 8540, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': -1, 'selected': False, 'text': "<p>@roo</p>\n<blockquote>\n<p>I was really hoping that is was possible, and that I just hadn't found it yet. Your example just made me realise that that is exactly what we are trying to do - only allow access to files in the context of our program and so preserve the IP.</p>\n<p>I guess I have to accept that there is no truly secure way to store someone’s files on another computer, especially if at some point access is allowed to that file by the owner.</p>\n</blockquote>\n<p>That's definitely the problem.  You can store something securely so long as you never grant access, but as soon as you grant access, your control is gone.  You can make it a little bit more difficult, but that's all.</p>\n"}, {'answer_id': 8544, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': -1, 'selected': False, 'text': '<p>@Chris</p>\n\n<blockquote>\n  <p>Oh, but with trusted computing, you can use memory curtaining! :-P</p>\n</blockquote>\n\n<p>But then you have to actually be willing to pay for a computer someone else owns.  :p</p>\n'}, {'answer_id': 8600, 'author': 'graham.reeds', 'author_id': 342, 'author_profile': 'https://Stackoverflow.com/users/342', 'pm_score': -1, 'selected': False, 'text': '<p>@Derek Park</p>\n\n<p>He only said harder, not impossible. PGP would make it harder, not impossible.</p>\n'}, {'answer_id': 27194, 'author': 'Josh', 'author_id': 257, 'author_profile': 'https://Stackoverflow.com/users/257', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re developing for Windows, there are ways you can restrict access to memory, but absolutely blocking out others is not doable.  If you\'re hoping to keep a secret secret, read <a href="http://www.microsoft.com/mspress/books/5957.aspx" rel="nofollow noreferrer"><em>Writing Secure Code</em></a> - which addresses this problem at some length, but be aware that you have no way of knowing if your code is running on a real machine or a virtual machine.  There\'s a bunch of Win32 API stuff to deal with crypto that handles this kind of thing, including safe storage of secrets - the book talks about that.  You can look at the online <a href="http://msdn.microsoft.com/en-us/library/aa380256(VS.85).aspx" rel="nofollow noreferrer">Microsoft CyproAPI</a> for details; the OS designers recognise this very problem and the need to keep the cleartext secure (again, read <em>Writing Secure Code</em>).</p>\n\n<p>The Win32 API function <a href="http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx" rel="nofollow noreferrer"><code>VirtualAlloc</code></a> is the OS level memory allocator.  It allows you to set access protection; what you could do is set access to <code>PAGE_GUARD</code> or <code>PAGE_NOACCESS</code>, and flip the access to something friendlier while your program reads, and reset it afterward, but that\'s merely a speed hump if someone is trying really hard to peek at your secret.</p>\n\n<p>In summary, look at the crypto APIs on your platform, they\'ll address the problem better than something you hack up yourself.</p>\n'}, {'answer_id': 38708, 'author': 'T Percival', 'author_id': 954, 'author_profile': 'https://Stackoverflow.com/users/954', 'pm_score': 3, 'selected': False, 'text': '<p>On Unix systems you can use <a href="http://linux.die.net/man/2/mlock" rel="noreferrer">mlock(2)</a> to lock memory pages into RAM, preventing them being paged.</p>\n\n<blockquote>\n  <p>mlock() and mlockall() respectively lock part or all of the calling\n  process’s virtual address space into RAM, preventing that memory from\n  being paged to the swap area.</p>\n</blockquote>\n\n<p>There is a limit to how much memory each process can lock, it can be shown with <code>ulimit -l</code> and is measured in kilobytes. On my system, the default limit is 32 kiB per process.</p>\n'}, {'answer_id': 3542315, 'author': 'Jeffrey Walton', 'author_id': 357494, 'author_profile': 'https://Stackoverflow.com/users/357494', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n  <p>You cannot protect memory contents from the owner of the system.\n  Hollywood and the music industry have been aching for this for years.\n  If it were possible, they\'d already be doing it.</p>\n</blockquote>\n\n<p>Have you had a look at Vista (and above) <a href="https://web.archive.org/web/20100905221322/http://www.microsoft.com/whdc/system/vista/process_vista.mspx" rel="nofollow noreferrer">Protected Processes</a> (direct <a href="http://download.microsoft.com/download/a/f/7/af7777e5-7dcd-4800-8a0a-b18336565f5b/process_Vista.doc" rel="nofollow noreferrer">.doc download</a>). I believe the operating system-enforced protection is courtesy of the entertainment industry.</p>\n'}, {'answer_id': 7960311, 'author': 'kgriffs', 'author_id': 21784, 'author_profile': 'https://Stackoverflow.com/users/21784', 'pm_score': 0, 'selected': False, 'text': '<p>Your best bet is to implement something similar to .NET\'s SecureString class, and be very careful to zero out any plaintext copies of your data as soon as you are done (don\'t forget to cleanup even when exceptions are thrown). A good way to do this with std::string and such is to use a <a href="http://www.codeproject.com/KB/cpp/allocator.aspx" rel="nofollow">custom allocator</a>. </p>\n\n<p>On Windows, if you use CryptProtectMemory (or RtlEncryptMemory for older systems), the encryption password is stored in non-pageable (kernel?) memory. In my testing, these functions are pretty darn fast, esp. taking into account the protection they are giving you.</p>\n\n<p>On other systems, I like to use Blowfish since it\'s a good mix between speed and strength. In the latter case, you will have to randomly generate your own password (16+ bytes of entropy for Blowfish) at program startup. Unfortunately, there\'s not a whole lot you can do to protect that password without OS support, although you might use general obfuscation techniques to embed a hard-coded salt value into your executable that you can combine with the password (every little bit helps).</p>\n\n<p>Overall, this strategy is only one part of a broader defense-in-depth approach. Also keep in mind that simple bugs such as buffer overflows and not sanitizing program input remain by far the most common attack vectors.</p>\n'}, {'answer_id': 33568256, 'author': 'Bent Cardan', 'author_id': 917118, 'author_profile': 'https://Stackoverflow.com/users/917118', 'pm_score': 3, 'selected': False, 'text': "<p>install Libsodium, use allocation mechanisms by #including <code>&lt;sodium.h&gt;</code></p>\n\n<h2>Guarded heap allocations</h2>\n\n<p>Slower than malloc() and friends, they require 3 or 4 extra pages of virtual memory.</p>\n\n<pre><code>void *sodium_malloc(size_t size);\n</code></pre>\n\n<p>Allocate memory to store sensitive data using <code>sodium_malloc()</code> and <code>sodium_allocarray()</code>.  You'll need to first call <code>sodium_init()</code> before using these heap guards.</p>\n\n<pre><code>void *sodium_allocarray(size_t count, size_t size);\n</code></pre>\n\n<p>The <code>sodium_allocarray()</code> function returns a pointer from which count objects that are size bytes of memory each can be accessed. It provides the same guarantees as <code>sodium_malloc()</code> but also protects against arithmetic overflows when <code>count * size</code> exceeds <code>SIZE_MAX</code>.</p>\n\n<p>These functions add guard pages around the protected data to make it less likely to be accessible in a heartbleed-like scenario. </p>\n\n<p>In addition, the protection for memory regions allocated that way can be changed using the locking memory operations: <code>sodium_mprotect_noaccess()</code>, <code>sodium_mprotect_readonly()</code> and <code>sodium_mprotect_readwrite()</code>.</p>\n\n<p>After <code>sodium_malloc</code> you can use <code>sodium_free()</code> to unlock and deallocate memory. At this point in your implementation consider zeroing the memory after use.</p>\n\n<h2>zero the memory after use</h2>\n\n<pre><code>void sodium_memzero(void * const pnt, const size_t len);\n</code></pre>\n\n<p>After use, sensitive data should be overwritten, but memset() and hand-written code can be silently stripped out by an optimizing compiler or by the linker.</p>\n\n<p>The sodium_memzero() function tries to effectively zero len bytes starting at pnt, even if optimizations are being applied to the code.</p>\n\n<h2>locking the memory allocation</h2>\n\n<pre><code>int sodium_mlock(void * const addr, const size_t len);\n</code></pre>\n\n<p>The <code>sodium_mlock()</code> function locks at least len bytes of memory starting at addr. This can help avoid swapping sensitive data to disk.</p>\n\n<pre><code>int sodium_mprotect_noaccess(void *ptr);\n</code></pre>\n\n<p>The sodium_mprotect_noaccess() function makes a region allocated using sodium_malloc() or sodium_allocarray() inaccessible. It cannot be read or written, but the data are preserved. This function can be used to make confidential data inaccessible except when actually needed for a specific operation.</p>\n\n<pre><code>int sodium_mprotect_readonly(void *ptr);\n</code></pre>\n\n<p>The sodium_mprotect_readonly() function marks a region allocated using sodium_malloc() or sodium_allocarray() as read-only. Attempting to modify the data will cause the process to terminate.</p>\n\n<pre><code>int sodium_mprotect_readwrite(void *ptr);\n</code></pre>\n\n<p>The <code>sodium_mprotect_readwrite()</code> function marks a region allocated using <code>sodium_malloc()</code> or <code>sodium_allocarray()</code> as readable and writable, after having been protected using <code>sodium_mprotect_readonly()</code> or <code>sodium_mprotect_noaccess()</code>.</p>\n"}]
['https://Stackoverflow.com/questions/8451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716/']