Reactos
at master 86 lines 2.1 kB view raw
1// 2// __security_init_cookie.c 3// 4// Copyright (c) 2024 Timo Kreuzer 5// 6// Implementation of __security_init_cookie. 7// 8// SPDX-License-Identifier: MIT 9// 10 11#include <internal_shared.h> 12 13#ifdef _WIN64 14#define DEFAULT_SECURITY_COOKIE 0x00002B992DDFA232ull 15#define _rotlptr _rotl64 16#else 17#define DEFAULT_SECURITY_COOKIE 0xBB40E64E 18#define _rotlptr _rotl 19#endif 20 21uintptr_t __security_cookie = DEFAULT_SECURITY_COOKIE; 22uintptr_t __security_cookie_complement = ~DEFAULT_SECURITY_COOKIE; 23 24void __security_init_cookie(void) 25{ 26 LARGE_INTEGER performanceCounter; 27 FILETIME fileTime; 28 uintptr_t randomValue = (uintptr_t)0x27E30B2C16B07297ull; 29 30#if defined(_M_IX86) || defined(_M_X64) 31 if (IsProcessorFeaturePresent(PF_RDRAND_INSTRUCTION_AVAILABLE)) 32 { 33#ifdef _M_X64 34 while (!_rdrand64_step(&randomValue)) 35 _mm_pause(); 36#else 37 while (!_rdrand32_step(&randomValue)) 38 _mm_pause(); 39#endif 40 } 41 42 if (IsProcessorFeaturePresent(PF_RDTSC_INSTRUCTION_AVAILABLE)) 43 { 44 randomValue += __rdtsc(); 45 } 46#endif 47 48 randomValue += (uintptr_t)&randomValue; 49 randomValue ^= GetTickCount(); 50 51 QueryPerformanceCounter(&performanceCounter); 52#ifdef _WIN64 53 randomValue ^= performanceCounter.QuadPart; 54#else 55 randomValue ^= performanceCounter.LowPart; 56 randomValue ^= performanceCounter.HighPart; 57#endif 58 59 randomValue += GetCurrentThreadId(); 60 randomValue = _rotlptr(randomValue, GetCurrentThreadId() >> 2); 61 62#if (_WIN32_WINNT >= _WIN32_WINNT_WIN8) 63 GetSystemTimePreciseAsFileTime(&fileTime); 64#else 65 GetSystemTimeAsFileTime(&fileTime); 66#endif 67 randomValue += fileTime.dwLowDateTime; 68 randomValue += fileTime.dwHighDateTime; 69 70 randomValue += GetCurrentProcessId(); 71 randomValue = _rotlptr(randomValue, GetCurrentProcessId() >> 2); 72 73#ifdef _WIN64 74 /* Zero out highest 16 bits */ 75 randomValue &= 0x0000FFFFFFFFFFFFull; 76#endif 77 78 /* Avoid the default security cookie */ 79 if (randomValue == DEFAULT_SECURITY_COOKIE) 80 { 81 randomValue++; 82 } 83 84 __security_cookie = randomValue; 85 __security_cookie_complement = ~randomValue; 86}