| 16 | #include "uwp/uwp.hpp" |
| 17 | |
| 18 | void HardenProcess() |
| 19 | { |
| 20 | // Higher logging levels might end up loading more DLLs while we're trying |
| 21 | // to enable mitigations for DLL loading. |
| 22 | // OK for debug builds because it makes it readable from the log file |
| 23 | // but in release we'd rather not. |
| 24 | // This entire thing happens before config is loaded, so trace will never log. |
| 25 | static constexpr spdlog::level::level_enum level = |
| 26 | #ifdef _DEBUG |
| 27 | spdlog::level::warn; |
| 28 | #else |
| 29 | spdlog::level::trace; |
| 30 | #endif |
| 31 | |
| 32 | if (!SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT)) |
| 33 | { |
| 34 | LastErrorHandle(level, L"Couldn't enable safe DLL search mode."); |
| 35 | } |
| 36 | |
| 37 | if (!HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0)) |
| 38 | { |
| 39 | LastErrorHandle(level, L"Couldn't enable termination on heap corruption."); |
| 40 | } |
| 41 | |
| 42 | PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY handle_policy{}; |
| 43 | handle_policy.RaiseExceptionOnInvalidHandleReference = true; |
| 44 | handle_policy.HandleExceptionsPermanentlyEnabled = true; |
| 45 | if (!SetProcessMitigationPolicy(ProcessStrictHandleCheckPolicy, &handle_policy, sizeof(handle_policy))) |
| 46 | { |
| 47 | LastErrorHandle(level, L"Couldn't enable strict handle checks."); |
| 48 | } |
| 49 | |
| 50 | PROCESS_MITIGATION_ASLR_POLICY aslr_policy; |
| 51 | if (GetProcessMitigationPolicy(GetCurrentProcess(), ProcessASLRPolicy, &aslr_policy, sizeof(aslr_policy))) |
| 52 | { |
| 53 | aslr_policy.EnableForceRelocateImages = true; |
| 54 | aslr_policy.DisallowStrippedImages = true; |
| 55 | if (!SetProcessMitigationPolicy(ProcessASLRPolicy, &aslr_policy, sizeof(aslr_policy))) |
| 56 | { |
| 57 | LastErrorHandle(level, L"Couldn't enable image force relocation."); |
| 58 | } |
| 59 | } |
| 60 | else |
| 61 | { |
| 62 | LastErrorHandle(level, L"Couldn't get current ASLR policy."); |
| 63 | } |
| 64 | |
| 65 | PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY extension_policy{}; |
| 66 | extension_policy.DisableExtensionPoints = true; |
| 67 | if (!SetProcessMitigationPolicy(ProcessExtensionPointDisablePolicy, &extension_policy, sizeof(extension_policy))) |
| 68 | { |
| 69 | LastErrorHandle(level, L"Couldn't disable extension point DLLs."); |
| 70 | } |
| 71 | |
| 72 | PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY signature_policy{}; |
| 73 | signature_policy.MitigationOptIn = true; |
| 74 | if (!SetProcessMitigationPolicy(ProcessSignaturePolicy, &signature_policy, sizeof(signature_policy))) |
| 75 | { |