bool Test_VirtualAlloc() { size_t memsize = 2 * 1024 * 1024; SIZE_T min = 0, max = 0; ::GetProcessWorkingSetSize(::GetCurrentProcess(), &min, &max); printf("min: %u KB, max: %u KB\n", min/1024, max/1024); { BYTE *pBuf = (BYTE*)VirtualAlloc(NULL, memsize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); printf("VirtualAlloc: %p\n", pBuf); BOOL ret = VirtualLock(pBuf, memsize); printf("VirtualLock: %d\n", ret); memset(pBuf, 0, memsize); // getchar(); void *pa[10]; for (int i = 0; i < 10; i++) { pa[i] = malloc(10 * 1024 * 1024); memset(pa[i], 0, 10 * 1024 * 1024); } getchar(); for (int i = 0; i < 10; i++) { free(pa[i]); } if (ret) VirtualUnlock(pBuf, memsize); VirtualFree(pBuf, memsize, 0); } min += 2 * 1024 * 1024; max += 2 * 1024 * 1024; ::SetProcessWorkingSetSize(::GetCurrentProcess(), min, max); printf("min: %u KB, max: %u KB\n", min / 1024, max / 1024); { BYTE *pBuf = (BYTE*)VirtualAlloc(NULL, memsize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); printf("VirtualAlloc: %p\n", pBuf); BOOL ret = VirtualLock(pBuf, memsize); printf("VirtualLock: %d\n", ret); memset(pBuf, 0, memsize); // getchar(); if (ret) VirtualUnlock(pBuf, memsize); VirtualFree(pBuf, memsize, 0); } return 0; }
char* disk_buffer_pool::allocate_buffer(char const* category) { mutex::scoped_lock l(m_pool_mutex); TORRENT_ASSERT(m_magic == 0x1337); #ifdef TORRENT_DISABLE_POOL_ALLOCATOR char* ret = page_aligned_allocator::malloc(m_block_size); #else char* ret = (char*)m_pool.ordered_malloc(); m_pool.set_next_size(m_settings.cache_buffer_chunk_size); #endif ++m_in_use; #if TORRENT_USE_MLOCK if (m_settings.lock_disk_cache) { #ifdef TORRENT_WINDOWS VirtualLock(ret, m_block_size); #else mlock(ret, m_block_size); #endif } #endif #if defined TORRENT_DISK_STATS || defined TORRENT_STATS ++m_allocations; #endif #ifdef TORRENT_DISK_STATS ++m_categories[category]; m_buf_to_category[ret] = category; m_log << log_time() << " " << category << ": " << m_categories[category] << "\n"; #endif TORRENT_ASSERT(ret == 0 || is_disk_buffer(ret, l)); return ret; }
static void lockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); if( VirtualLock( ( void * ) memHdrPtr, memHdrPtr->size ) ) memHdrPtr->flags |= MEM_FLAG_LOCKED; }
PCRYPTO_INFO crypto_open () { #ifndef GST_WINDOWS_BOOT /* Do the crt allocation */ PCRYPTO_INFO cryptoInfo = (PCRYPTO_INFO) GSTalloc (sizeof (CRYPTO_INFO)); if (cryptoInfo == NULL) return NULL; memset (cryptoInfo, 0, sizeof (CRYPTO_INFO)); #ifndef DEVICE_DRIVER VirtualLock (cryptoInfo, sizeof (CRYPTO_INFO)); #endif cryptoInfo->ea = -1; return cryptoInfo; #else // GST_WINDOWS_BOOT #if 0 if (CryptoInfoBufferInUse) GST_THROW_FATAL_EXCEPTION; #endif CryptoInfoBufferInUse = 1; return &CryptoInfoBuffer; #endif // GST_WINDOWS_BOOT }
PTR MemAllocLocked( UINT32 uiSize ) { PTR ptr; if ( !fMemManagerInit ) DbgMessage( TOPIC_MEMORY_MANAGER, DBG_LEVEL_0, String("MemAllocLocked: Warning -- Memory manager not initialized!!! ") ); ptr = VirtualAlloc( NULL, uiSize, MEM_COMMIT, PAGE_READWRITE ); if ( ptr ) { VirtualLock( ptr, uiSize ); guiMemTotal += uiSize; guiMemAlloced += uiSize; MemDebugCounter++; } else { DbgMessage( TOPIC_MEMORY_MANAGER, DBG_LEVEL_0, String("MemAllocLocked failed: %d bytes", uiSize) ); } #ifdef DEBUG_MEM_LEAKS DbgMessage( TOPIC_MEMORY_MANAGER, DBG_LEVEL_1, String("MemAllocLocked %p: %d bytes", ptr, uiSize) ); #endif return( ptr ); }
BOOL My_VirtualLock() { LPVOID lpAddress=NULL; SIZE_T dwSize=NULL; BOOL returnVal_Real = NULL; BOOL returnVal_Intercepted = NULL; DWORD error_Real = 0; DWORD error_Intercepted = 0; disableInterception(); returnVal_Real = VirtualLock (lpAddress,dwSize); error_Real = GetLastError(); enableInterception(); returnVal_Intercepted = VirtualLock (lpAddress,dwSize); error_Intercepted = GetLastError(); return ((returnVal_Real == returnVal_Intercepted) && (error_Real == error_Intercepted)); }
bool MemoryPageLocker::Lock(const void* addr, size_t len) { #ifdef WIN32 return VirtualLock(const_cast<void*>(addr), len) != 0; #else return mlock(addr, len) == 0; #endif }
/* Init the random number generator, setup the hooks, and start the thread */ int Randinit () { DWORD dwLastError = ERROR_SUCCESS; if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) TC_THROW_FATAL_EXCEPTION; if(bRandDidInit) return 0; InitializeCriticalSection (&critRandProt); bRandDidInit = TRUE; CryptoAPILastError = ERROR_SUCCESS; ProcessedMouseEventsCounter = 0; if (pRandPool == NULL) { pRandPool = (unsigned char *) TCalloc (RANDOMPOOL_ALLOCSIZE); if (pRandPool == NULL) goto error; bDidSlowPoll = FALSE; RandomPoolEnrichedByUser = FALSE; memset (pRandPool, 0, RANDOMPOOL_ALLOCSIZE); VirtualLock (pRandPool, RANDOMPOOL_ALLOCSIZE); } hKeyboard = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)&KeyboardProc, NULL, GetCurrentThreadId ()); if (hKeyboard == 0) handleWin32Error (0, SRC_POS); hMouse = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)&MouseProc, NULL, GetCurrentThreadId ()); if (hMouse == 0) { handleWin32Error (0, SRC_POS); goto error; } if (!CryptAcquireContext (&hCryptProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { CryptoAPIAvailable = FALSE; CryptoAPILastError = GetLastError (); goto error; } else CryptoAPIAvailable = TRUE; if (!(PeriodicFastPollThreadHandle = (HANDLE) _beginthreadex (NULL, 0, PeriodicFastPollThreadProc, NULL, 0, NULL))) goto error; return 0; error: dwLastError = GetLastError(); RandStop (TRUE); SetLastError (dwLastError); return 1; }
int mlock(const void *addr, size_t len) { if (VirtualLock((LPVOID)addr, len)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; }
bool lockPage(void* addr, int len){ #if defined(Q_WS_X11) || defined(Q_WS_MAC) return (mlock(addr, len)==0); #elif defined(Q_WS_WIN) return VirtualLock(addr, len); #else return false; #endif }
int mlock(const void *addr, size_t len) { if (VirtualLock((LPVOID)addr, len)) return 0; errno = EBADF; return -1; }
// Allocate memory void* salloc(size_t len) { #ifdef SENSITIVE_NON_PAGED // Allocate memory on a page boundary #ifndef _WIN32 void* ptr = (void*) valloc(len); #else pointer r = (pointer) VirtualAlloc(NULL, n * sizeof(T), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #endif if (ptr == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Lock the memory so it doesn't get swapped out #ifndef _WIN32 if (mlock((const void*) ptr, len) != 0) #else if (VirtualLock((const void*) r, n * sizeof(T)) == 0) #endif { ERROR_MSG("Could not allocate non-paged memory for secure storage"); // Hmmm... best to not return any allocated space in this case #ifndef _WIN32 free(ptr); #else VirtualFree((const void*) pre, MEM_RELEASE); #endif return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(ptr, len); return ptr; #else void* ptr = (void*) malloc(len); if (ptr == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(ptr, len); return ptr; #endif // SENSITIVE_NON_PAGED }
int mlock(const void *addr, size_t len) { if (VirtualLock((LPVOID)addr, len)) return 0; else { errno = windowsErrorToErrno(GetLastError()); return -1; } }
int mlock(const void* addr, size_t len) { if (VirtualLock((LPVOID)addr, len) != FALSE) { errno = 0; return 0; } errno = last_error(EPERM); return -1; }
void* inmem_malloc(size_t size) { void *ptr = malloc(size); if (ptr == NULL) { printf("inmem_malloc failed!\n"); exit(1); } VirtualLock(ptr, size); return ptr; }
void* prim_virtualProtect(void * arg1,DWORD arg2,DWORD arg3) { static struct {HsInt gc_failed;HsPtr gc_failstring;} gc_result; int gc_failed; char* gc_failstring; do { BOOL res1=VirtualLock(arg1,arg2); if ((gc_failed = ( res1=0 ))) {gc_failstring = ErrorWin("VirtualProtect") ;} else {gc_failed = 0;} gc_result.gc_failed = gc_failed; gc_result.gc_failstring = gc_failstring; return(&gc_result);} while(0); }
/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ static void goodG2B1() { wchar_t * password; /* Initialize Data */ password = L""; switch(5) { case 6: /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); break; default: password = (wchar_t *)malloc(100*sizeof(wchar_t)); if (password == NULL) { printLine("Memory could not be allocated"); exit(1); } /* FIX: Use VirtualLock() to lock the buffer into memory */ if(!VirtualLock(password, 100*sizeof(wchar_t))) { printLine("Memory could not be locked"); exit(1); } /* INCIDENTAL FLAW: CWE-259 Hardcoded Password */ wcscpy(password, L"Password1234!"); break; } { HANDLE pHandle; wchar_t * username = L"User"; wchar_t * domain = L"Domain"; /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserW( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } /* POTENTIAL FLAW: Sensitive data possibly improperly locked */ free(password); } }
void main(void) { // local variables LPVOID lpvAddr; DWORD cbSize; BOOL vLock; LPVOID commit; // amount of memory we'll allocate cbSize = 512; // try to allocate some memory lpvAddr = VirtualAlloc(NULL,cbSize,MEM_RESERVE,PAGE_NOACCESS); // failed ... if(lpvAddr == NULL) fprintf(stdout,"VirtualAlloc failed on RESERVE with %ld\n", GetLastError()); // try to commit the allocated memory commit = VirtualAlloc(NULL,cbSize,MEM_COMMIT,PAGE_READONLY|PAGE_GUARD); // failed ... if(commit == NULL) fprintf(stderr,"VirtualAlloc failed on COMMIT with %ld\n", GetLastError()); else // success! fprintf(stderr,"Committed %lu bytes at address %lp\n", cbSize,commit); // try to lock the committed memory vLock = VirtualLock(commit,cbSize); // failed ... if(!vLock) fprintf(stderr,"Cannot lock at %lp, error = %lu\n", commit,GetLastError()); else // success! fprintf(stderr,"Lock Achieved at %lp\n",commit); // try to lock the committed memory again vLock = VirtualLock(commit,cbSize); // failed ... if(!vLock) fprintf(stderr,"Cannot get 2nd lock at %lp, error = %lu\n", commit,GetLastError()); else // success! fprintf(stderr,"2nd Lock Achieved at %lp\n",commit); }
void *Win32LockedPageAllocator::AllocateLocked(size_t len, bool *lockingSuccess) { len = align_up(len, page_size); void *addr = VirtualAlloc(nullptr, len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (addr) { // VirtualLock is used to attempt to keep keying material out of swap. Note // that it does not provide this as a guarantee, but, in practice, memory // that has been VirtualLock'd almost never gets written to the pagefile // except in rare circumstances where memory is extremely low. *lockingSuccess = VirtualLock(const_cast<void*>(addr), len) != 0; } return addr; }
static void test_ws_functions(void) { PSAPI_WS_WATCH_INFORMATION wswi[4096]; ULONG_PTR pages[4096]; char *addr; unsigned int i; todo_wine w32_err(pEmptyWorkingSet(NULL), ERROR_INVALID_HANDLE); todo_wine w32_err(pEmptyWorkingSet(hpSR), ERROR_ACCESS_DENIED); w32_suc(pEmptyWorkingSet(hpAA)); todo_wine w32_err(pInitializeProcessForWsWatch(NULL), ERROR_INVALID_HANDLE); w32_suc(pInitializeProcessForWsWatch(hpAA)); if(!w32_suc(addr = VirtualAlloc(NULL, 1, MEM_COMMIT, PAGE_READWRITE))) return; if(!VirtualLock(addr, 1)) { trace("locking failed (error=%d) - skipping test\n", GetLastError()); goto free_page; } todo_wine if(w32_suc(pQueryWorkingSet(hpQI, pages, 4096 * sizeof(ULONG_PTR)))) { for(i = 0; i < pages[0]; i++) if((pages[i+1] & ~0xfffL) == (ULONG_PTR)addr) { ok(1, "QueryWorkingSet found our page\n"); goto test_gwsc; } ok(0, "QueryWorkingSet didn't find our page\n"); } test_gwsc: todo_wine if(w32_suc(pGetWsChanges(hpQI, wswi, sizeof(wswi)))) { for(i = 0; wswi[i].FaultingVa; i++) if(((ULONG_PTR)wswi[i].FaultingVa & ~0xfffL) == (ULONG_PTR)addr) { ok(1, "GetWsChanges found our page\n"); goto free_page; } ok(0, "GetWsChanges didn't find our page\n"); } free_page: VirtualFree(addr, 0, MEM_RELEASE); }
/** * Helper: try to prevent the <b>sz</b> bytes at <b>mem</b> from being swapped * to disk. Return 0 on success or if the facility is not available on this * OS; return -1 on failure. */ static int lock_mem(void *mem, size_t sz) { #ifdef _WIN32 return VirtualLock(mem, sz) ? 0 : -1; #elif defined(HAVE_MLOCK) return mlock(mem, sz); #else (void) mem; (void) sz; return 0; #endif }
/* Init the random number generator, setup the hooks, and start the thread */ int Randinit () { if (GetMaxPkcs5OutSize() > RNG_POOL_SIZE) TC_THROW_FATAL_EXCEPTION; if(bRandDidInit) return 0; InitializeCriticalSection (&critRandProt); bRandDidInit = TRUE; if (pRandPool == NULL) { pRandPool = (unsigned char *) TCalloc (RANDOMPOOL_ALLOCSIZE); if (pRandPool == NULL) goto error; bDidSlowPoll = FALSE; RandomPoolEnrichedByUser = FALSE; memset (pRandPool, 0, RANDOMPOOL_ALLOCSIZE); VirtualLock (pRandPool, RANDOMPOOL_ALLOCSIZE); } hKeyboard = SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC)&KeyboardProc, NULL, GetCurrentThreadId ()); if (hKeyboard == 0) handleWin32Error (0); hMouse = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)&MouseProc, NULL, GetCurrentThreadId ()); if (hMouse == 0) { handleWin32Error (0); goto error; } if (!CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0) && !CryptAcquireContext (&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) CryptoAPIAvailable = FALSE; else CryptoAPIAvailable = TRUE; if (!(PeriodicFastPollThreadHandle = (HANDLE) _beginthreadex (NULL, 0, PeriodicFastPollThreadProc, NULL, 0, NULL))) goto error; return 0; error: RandStop (TRUE); return 1; }
int uMemLock(void *addr, size_t size, sys_call_error_fun fun) { #ifdef _WIN32 if (VirtualLock(addr, size) == 0) { sys_call_error("VirtualLock"); return -1; } else return 0; #else int res = mlock(addr, size); if (res == -1) sys_call_error("mlock"); return res; #endif }
/** * allocate memory. Uses sqlite's internall malloc wrapper so memory can be * reference counted and leak detection works. Unless compiled with OMIT_MEMLOCK * attempts to lock the memory pages so sensitive information won't be swapped */ void* sqlcipher_malloc(int sz) { void *ptr = sqlite3Malloc(sz); sqlcipher_memset(ptr, 0, sz); #ifndef OMIT_MEMLOCK if(ptr) { #if defined(__unix__) || defined(__APPLE__) mlock(ptr, sz); #elif defined(_WIN32) #if !(defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP || WINAPI_FAMILY == WINAPI_FAMILY_APP)) VirtualLock(ptr, sz); #endif #endif } #endif return ptr; }
/* goodG2B() uses the GoodSource with the BadSink */ static void goodG2BSource(wchar_t * &password) { password = (wchar_t *)malloc(100*sizeof(wchar_t)); if (password == NULL) { printLine("Memory could not be allocated"); exit(1); } /* FIX: Use VirtualLock() to lock the buffer into memory */ if(!VirtualLock(password, 100*sizeof(wchar_t))) { printLine("Memory could not be locked"); exit(1); } /* INCIDENTAL FLAW: CWE-259 Hardcoded Password */ wcscpy(password, L"Password1234!"); }
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { char * password; /* Initialize Data */ password = ""; if(globalReturnsTrue()) { password = (char *)malloc(100*sizeof(char)); if (password == NULL) { printLine("Memory could not be allocated"); exit(1); } /* FIX: Use VirtualLock() to lock the buffer into memory */ if(!VirtualLock(password, 100*sizeof(char))) { printLine("Memory could not be locked"); exit(1); } /* INCIDENTAL FLAW: CWE-259 Hardcoded Password */ strcpy(password, "Password1234!"); } { HANDLE pHandle; char * username = "******"; char * domain = "Domain"; /* Use the password in LogonUser() to establish that it is "sensitive" */ if (LogonUserA( username, domain, password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &pHandle) != 0) { printLine("User logged in successfully."); CloseHandle(pHandle); } else { printLine("Unable to login."); } /* POTENTIAL FLAW: Sensitive data possibly improperly locked */ free(password); } }
static void protected_value_xor (ProtectedValue *pvalue, gboolean to_clear) { if (to_clear) { if (! pvalue->cvalue) { guint i, l; ensure_static_blob_filled (); l = protected_get_length (pvalue->pvalue, pvalue->offset); pvalue->cvalue = malloc (sizeof (gchar) * (l + 1)); for (i = 0; i < l; i++) pvalue->cvalue [i] = pvalue->pvalue [i] ^ random_blob [pvalue->offset + i]; pvalue->cvalue [l] = 0; #ifdef G_OS_WIN32 VirtualLock (pvalue->cvalue, sizeof (gchar) * (l + 1)); #else #ifdef USE_MLOCK mlock (pvalue->cvalue, sizeof (gchar) * (l + 1)); #endif #endif /*g_print ("Unmangled [%s]\n", pvalue->cvalue);*/ } } else { if (pvalue->cvalue) { /*g_print ("Mangled [%s]\n", pvalue->cvalue);*/ guint i; for (i = 0; ; i++) { gchar c; c = pvalue->cvalue[i]; pvalue->cvalue[i] = g_random_int_range (1, 255); if (!c) break; } #ifdef G_OS_WIN32 VirtualUnlock (pvalue->cvalue, sizeof (gchar) * (i + 1)); #else #ifdef USE_MLOCK munlock (pvalue->cvalue, sizeof (gchar) * (i + 1)); #endif #endif free (pvalue->cvalue); pvalue->cvalue = NULL; } } }
/* * Lock a region of memory in physical memory so that it cannot be swapped * out. * * req: TLV_TYPE_BASE_ADDRESS - The base address to lock * req: TLV_TYPE_LENGTH - The size of the region to lock */ DWORD request_sys_process_memory_lock(Remote *remote, Packet *packet) { Packet *response = packet_create_response(packet); LPVOID base; SIZE_T size; DWORD result = ERROR_SUCCESS; base = (LPVOID)packet_get_tlv_value_qword(packet, TLV_TYPE_BASE_ADDRESS); size = packet_get_tlv_value_uint(packet, TLV_TYPE_LENGTH); if (!VirtualLock(base, size)) result = GetLastError(); // Transmit the response packet_transmit_response(result, remote, response); return ERROR_SUCCESS; }
static void ensure_static_blob_filled (void) { if (random_blob [0] == 0) { guint i; for (i = 0; i < RANDOM_BLOB_SIZE; i++) { random_blob [i] = g_random_int_range (1, 255); /*g_print ("%02x ", (guchar) random_blob [i]);*/ } #ifdef G_OS_WIN32 VirtualLock (random_blob, sizeof (gchar) * RANDOM_BLOB_SIZE); #else #ifdef USE_MLOCK mlock (random_blob, sizeof (gchar) * RANDOM_BLOB_SIZE); #endif #endif } }
void MappedMemory::create(const char *fn, size_t len) { assert(fn != NULL && *fn != 0); int share = FILE_SHARE_READ; // int prot = FILE_MAP_READ; int mode = GENERIC_READ; size = 0; used = 0; map = NULL; if(!use_mapping) { assert(len > 0); // cannot use dummy for r/o... map = (caddr_t)malloc(len); if(!map) fault(); size = len; return; } if(*fn == '/') ++fn; if(len) { // prot = FILE_MAP_WRITE; mode |= GENERIC_WRITE; share |= FILE_SHARE_WRITE; fd = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, len, fn); } else fd = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, fn); if(fd == INVALID_HANDLE_VALUE || fd == NULL) return; map = (caddr_t)MapViewOfFile(fd, FILE_MAP_ALL_ACCESS, 0, 0, len); if(map) { size = len; VirtualLock(map, size); } else fault(); }