Skip to content

Commit c1aacf0

Browse files
nobledMatt Corallo
authored andcommitted
mlock() all private keys in memory
Inline comment and idea come from the encprivkeys branch by Matt Corallo <matt@bluematt.me>.
1 parent acd6501 commit c1aacf0

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

src/serialize.h

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,18 @@ typedef unsigned long long uint64;
2828
#if defined(_MSC_VER) && _MSC_VER < 1300
2929
#define for if (false) ; else for
3030
#endif
31+
32+
#ifdef __WXMSW__
33+
// This is used to attempt to keep keying material out of swap
34+
// Note that VirtualLock does not provide this as a guarantee on Windows,
35+
// but, in practice, memory that has been VirtualLock'd almost never gets written to
36+
// the pagefile except in rare circumstances where memory is extremely low.
37+
#define mlock(p, n) VirtualLock((p), (n));
38+
#define munlock(p, n) VirtualUnlock((p), (n));
39+
#else
40+
#include <sys/mman.h>
41+
#endif
42+
3143
class CScript;
3244
class CDataStream;
3345
class CAutoFile;
@@ -755,7 +767,8 @@ struct ser_streamplaceholder
755767

756768

757769
//
758-
// Allocator that clears its contents before deletion
770+
// Allocator that locks its contents from being paged
771+
// out of memory and clears its contents before deletion.
759772
//
760773
template<typename T>
761774
struct secure_allocator : public std::allocator<T>
@@ -777,10 +790,22 @@ struct secure_allocator : public std::allocator<T>
777790
template<typename _Other> struct rebind
778791
{ typedef secure_allocator<_Other> other; };
779792

793+
T* allocate(std::size_t n, const void *hint = 0)
794+
{
795+
T *p;
796+
p = std::allocator<T>::allocate(n, hint);
797+
if (p != NULL)
798+
mlock(p, sizeof(T) * n);
799+
return p;
800+
}
801+
780802
void deallocate(T* p, std::size_t n)
781803
{
782804
if (p != NULL)
805+
{
783806
memset(p, 0, sizeof(T) * n);
807+
munlock(p, sizeof(T) * n);
808+
}
784809
std::allocator<T>::deallocate(p, n);
785810
}
786811
};

0 commit comments

Comments
 (0)