Created
February 5, 2024 15:33
-
-
Save WKL-Sec/a659f785fca45fb847b5bc1fdb72e67f to your computer and use it in GitHub Desktop.
Folder Path Verification C++ Sample: A concise C++ example demonstrating how to verify an application's execution path against a specified directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# White Knight Labs - Offensive Development Course | |
# Guardrails - Folder Check | |
#include <windows.h> // Include Windows-specific headers for system calls | |
#include <iostream> // Include for input and output stream operations | |
#include <string> // Include for using string class | |
#include <algorithm> // Include for standard algorithms, e.g., std::transform | |
#include <cctype> // Include for character handling functions, e.g., std::tolower | |
// Function to check if the path of the current executable is under a specified path | |
bool isUnderSpecifiedPath(const std::string& path) { | |
// Convert path to lowercase for case-insensitive comparison | |
std::string lowerPath = path; | |
// Use transform to apply std::tolower to each character in the path | |
std::transform(lowerPath.begin(), lowerPath.end(), lowerPath.begin(), | |
[](unsigned char c) -> unsigned char { return std::tolower(c); }); | |
// Specify the directory to check against, ensuring it's in lowercase for accurate comparison | |
std::string specifiedPath = "c:\\windows\\system32"; | |
// Use rfind to check if the specifiedPath is the beginning of lowerPath | |
return lowerPath.rfind(specifiedPath, 0) == 0; | |
} | |
int main() { | |
// Buffer to hold the path of the current executable | |
char pathBuffer[MAX_PATH]; | |
// GetModuleFileName retrieves the path of the executable file of the current process | |
if (GetModuleFileName(NULL, pathBuffer, MAX_PATH) == 0) { | |
// If retrieving the path fails, print an error message and return an error code | |
std::cerr << "Failed to get module file name." << std::endl; | |
return 1; | |
} | |
// Convert the path buffer to a std::string for easier handling | |
std::string currentPath = pathBuffer; | |
// Check if the current executable path is under the specified path | |
if (isUnderSpecifiedPath(currentPath)) { | |
// If true, print confirmation message | |
std::cout << "Running under set path" << std::endl; | |
// This is where you can place the code that should only execute under the specified path | |
} else { | |
// If false, print a message indicating the executable is not under the specified path | |
std::cerr << "Not running under set path" << std::endl; | |
exit(1); | |
} | |
return 0; // Program executed successfully | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment