added logger

triing to add logger and some queue features (main loop can send and retrieve items form queue based on schedule and communication with dekstop interface)
This commit is contained in:
jakani24
2023-12-23 20:15:44 +01:00
parent 45f8ad413f
commit a7e323618c
92 changed files with 966 additions and 16 deletions

View File

@@ -4,11 +4,15 @@
#include <curl/curl.h>
#include <openssl/md5.h>
//#include <yara.h>
#include "app_ctrl.h"
#include "md5hash.h"
#include "connect.h"
#include "scan.h"
#include "app_ctrl.h"
#include "queue_ctrl.h"
#include "well_known.h"
#include "local_com.h"
#include "local_schedule.h"
#include "log.h"
int main() {
printf("welcome to the jakach security tool main thread\n");
//main thread:
@@ -19,9 +23,28 @@ int main() {
*/
while (!app_stop()) {
//run all the tasks described above
//check for tasks in com
//check for scheduled tasks
//execute tasks
//check_for_com_tasks(MAIN_COM,MAIN_COM_PATH);
log(LOGLEVEL::INFO,"test");
printf("check_from_com:%d\n",check_for_com_tasks(MAIN_COM, MAIN_COM_PATH));
printf("check_from_task:%d\n", check_for_sched_tasks(SCHED,SCHED_PATH));
//unlock_task("tsk1"); else it will only be executed once. but this function has to be called at the end of the task. else it will nvr be executed again. this would be bad :(
Sleep(1000);
int queue_size=get_queue_size();
for (int i = 0; i < queue_size; i++) {
char* queue_entry = new char[300 * 2 + 5];
queue_entry[0] = '\0';
queue_pop(queue_entry);
printf("%s\n", queue_entry);
delete[] queue_entry;
}
printf("\n\n\n");
}

View File

@@ -110,6 +110,7 @@
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions);CURL_STATICLIB</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>c:\Program Files\OpenSSL-Win64\include\;c:\vcpkg\vcpkg-2023.08.09\installed\x64-windows\include\</AdditionalIncludeDirectories>
<LanguageStandard>stdcpp20</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -139,6 +140,9 @@
<ClCompile Include="app_ctrl.h" />
<ClCompile Include="client_backend.cpp" />
<ClCompile Include="connect.cpp" />
<ClCompile Include="local_com.cpp" />
<ClCompile Include="local_schedule.cpp" />
<ClCompile Include="log.cpp" />
<ClCompile Include="md5hash.cpp" />
<ClCompile Include="permissions.cpp" />
<ClCompile Include="queue _ctrl.cpp" />
@@ -146,10 +150,14 @@
</ItemGroup>
<ItemGroup>
<ClInclude Include="connect.h" />
<ClInclude Include="local_com.h" />
<ClInclude Include="local_schedule.h" />
<ClInclude Include="log.h" />
<ClInclude Include="md5hash.h" />
<ClInclude Include="permissions.h" />
<ClInclude Include="queue_ctrl.h" />
<ClInclude Include="scan.h" />
<ClInclude Include="well_known.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@@ -39,6 +39,15 @@
<ClCompile Include="queue _ctrl.cpp">
<Filter>Headerdateien</Filter>
</ClCompile>
<ClCompile Include="local_com.cpp">
<Filter>Headerdateien</Filter>
</ClCompile>
<ClCompile Include="local_schedule.cpp">
<Filter>Headerdateien</Filter>
</ClCompile>
<ClCompile Include="log.cpp">
<Filter>Headerdateien</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="md5hash.h">
@@ -56,5 +65,17 @@
<ClInclude Include="queue_ctrl.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="well_known.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="local_com.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="local_schedule.h">
<Filter>Headerdateien</Filter>
</ClInclude>
<ClInclude Include="log.h">
<Filter>Headerdateien</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,59 @@
#ifndef LOCAL_COM_CPP
#define LOCAL_COM_CPP
#include "local_com.h"
int check_for_com_tasks(const char* com_name, const char* com_path) {
//check for new tasks in com file and add them into the queue
FILE* fp=nullptr;
char* command=new char [300];
if ((fopen_s(&fp,com_path, "r")) != 0) {
//panic, create log entry, return 1;
//no com file found = no communication needed
delete[] command;
return 1;
}
else {
while (!feof(fp)) {
fscanf_s(fp, "%s", command, 295); // get the command
if (!feof(fp)) { //last line =\n we dont want to process that
//printf("%s\n", command);
//we scanned the command, now we will scan the path. If the process does not need a path the path will be nopath. (set from client)
//get a full path. => " = start, second "= end
char* path = new char[300];
path[0] = '\0';
//search for starting ", then loop until ending "
int cnt = 0;
int chr = 0;
fgetc(fp);
fgetc(fp);
while (cnt < 295 && chr != '\"') {
chr = fgetc(fp); //get a char
if(chr!='\"')
path[cnt] = chr;
path[cnt+1] = '\0';
cnt++;
}
//printf("%s\n", path);
//we now have the command and the path. Now we will add it to the queue
char* queue_entry = new char[300*2+5]; //to enshure we have enough space
queue_entry[0] = '\0';
strcpy_s(queue_entry,600, command); //copy the command
strcat_s(queue_entry, 600, ";"); //add a ; to seperate command and path
//printf("%d\n", strlen(path));
strcat_s(queue_entry, 600, path); //add the path
//printf("%s::%d\n",queue_entry,strlen(queue_entry));
queue_push(queue_entry);
//(queue_entry);
delete[] queue_entry;
delete[] path;
}
}
}
remove(com_path);
fclose(fp);
delete[] command;
return 0;
}
#endif // !LOCAL_COM_CPP

View File

@@ -0,0 +1,7 @@
#pragma once
#include <iostream>
#include <cstdio>
#include "queue_ctrl.h"
#include "well_known.h"
int check_for_com_tasks(const char* com_name, const char* com_path);

View File

@@ -0,0 +1,174 @@
#ifndef LOCAL_SCHEDULE_CPP
#define LOCAL_SCHEDULE_CPP
#include "local_schedule.h"
#include "queue_ctrl.h"
/*
* To do:
* read scheduled tasks form file
* process time and date to determine if task should be executed
* add task to queue
*/
// Map to store task execution states
std::map<std::string, bool> task_states;
bool is_valid_field(const std::string& field, int value) {
if (field == "*") {
return true; // Wildcard matches any value
}
// Parse the field and check for matches
std::istringstream iss(field);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, ',')) {
if (std::find(token.begin(), token.end(), '-') != token.end()) {
// Range of values
int start, end;
if (sscanf_s(token.c_str(), "%d-%d", &start, &end) == 2 && value >= start && value <= end) {
return true;
}
}
else {
// Single value
int singleValue;
if (sscanf_s(token.c_str(), "%d", &singleValue) == 1 && value == singleValue) {
return true;
}
}
}
return false;
}
bool is_task_due(const std::string& task_name, const std::string& cron_expression, const std::tm& current_time) {
std::istringstream iss(cron_expression);
std::vector<std::string> fields;
std::string field;
while (iss >> field) {
fields.push_back(field);
}
// Check if the 'fields' vector has at least 5 elements
if (fields.size() < 5) {
// Handle the case where the cron expression is not well-formed
std::cerr << "Error: Invalid cron expression." << std::endl;
return false;
}
// Check if the task should be executed
if (is_valid_field(fields[0], current_time.tm_min) &&
is_valid_field(fields[1], current_time.tm_hour) &&
is_valid_field(fields[2], current_time.tm_mday) &&
is_valid_field(fields[3], current_time.tm_mon + 1) &&
is_valid_field(fields[4], current_time.tm_wday + 1)) {
// Check if the task has already been executed in this minute
if (!task_states[task_name]) {
// Set the flag to indicate that the task has been executed
task_states[task_name] = true;
return true;
}
}
else {
// Reset the flag for a new minute
task_states[task_name] = false;
}
return false;
}
void unlock_task(const std::string& task_name) {
// Unlock the task by setting its state to false
task_states[task_name] = false;
}
int check_for_sched_tasks(const char* sched_name, const char* sched_path) {
FILE* fp = nullptr;
char* command = new char[300];
if ((fopen_s(&fp, sched_path, "r")) != 0) {
//panic, create log entry, return 1;
//no schedule file found. this is not normal
delete[] command;
return 1;
}
else {
while (!feof(fp)) {
//read date-time config. it starts with " and ends with "
char* datetime = new char[300];
datetime[0] = '\0';
//search for datetime, starting ", then loop until ending "
int cnt = 0;
int chr = 0;
chr = fgetc(fp);//read in the first ", or at least try it
//printf("%c\n", chr);
if (chr == '\"'){
chr = 0;
while (cnt < 295 && chr != '\"') {
chr = fgetc(fp); //get a char
if (chr != '\"')
datetime[cnt] = chr;
datetime[cnt + 1] = '\0';
cnt++;
//printf("scanning...\n");
}
}
//now we had datetime. we can scan the command and the path now
fscanf_s(fp, "%s", command, 295); // get the command
char* path = new char[300];
path[0] = '\0';
//search for datetime, starting ", then loop until ending "
cnt = 0;
chr = 0;
fgetc(fp); //get th ewhitespoace after the command
chr = fgetc(fp);//read in the first ", or at least try it
if (chr == '\"') {
chr = 0;
while (cnt < 295 && chr != '\"') {
chr = fgetc(fp); //get a char
if (chr != '\"')
path[cnt] = chr;
path[cnt + 1] = '\0';
cnt++;
}
}
//now get the taskname
char* taskname = new char[300];
taskname[0] = '\0';
fscanf_s(fp, "%s", taskname, 295); // get the taskname
//lets check if the command should be executed
//get the current time
std::time_t t = std::time(nullptr);
struct std::tm current_time;
localtime_s(&current_time, &t);
//printf("%s\n", datetime);
if (strcmp(datetime, "") != 0 && strcmp(command, "") != 0 && strcmp(path, "") != 0 && strcmp(taskname, "") != 0) {
if (is_task_due(taskname,datetime, current_time)) {
//printf("command:%s\n", command);
//printf("path:%s\n", path);
//now we can build up the command for the queue
char* queue_entry = new char[300 * 2 + 5]; //to enshure we have enough space
queue_entry[0] = '\0';
strcpy_s(queue_entry, 600, command); //copy the command
strcat_s(queue_entry, 600, ";"); //add a ; to seperate command and path
//printf("%d\n", strlen(path));
strcat_s(queue_entry, 600, path); //add the path
//printf("%s::%d\n",queue_entry,strlen(queue_entry));
queue_push(queue_entry);
delete[] queue_entry;
}
}
else {
//echo something was malformatted
}
delete[] datetime;
delete[] path;
delete[] taskname;
}
}
delete[] command;
fclose(fp);
return 0;
}
#endif // !LOCAL_SCHEDULE_CPP

View File

@@ -0,0 +1,12 @@
#pragma once
#ifndef LOCAL_SCHEDULE_H
#define LOCAL_SCHEDULE_H
#include <iostream>
#include <ctime>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
int check_for_sched_tasks(const char* sched_name, const char* sched_path);
void unlock_task(const std::string& task_name);
#endif // !LOCAL_SCHEDULE_H

View File

@@ -0,0 +1,59 @@
#ifndef LOG_CPP
#define LOG_CPP
#include "log.h"
std::string get_loglevel(LOGLEVEL level) {
switch (level) {
case LOGLEVEL::INFO:
return "INFO";
case LOGLEVEL::WARN:
return "WARNING";
case LOGLEVEL::ERR:
return "ERROR";
default:
return "UNKNOWN";
}
}
template <typename... Args>
void log(LOGLEVEL level, const std::string& message, Args&&... args) {
std::string prefix = get_loglevel(level);
std::time_t now = std::time(nullptr);
std::tm tm = *std::localtime(&now);
std::ostringstream logStream;
logStream << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << " " << prefix << message;
if constexpr (sizeof...(args) > 0) {
((logStream << ' ' << std::forward<Args>(args)), ...);
}
logStream << std::endl;
std::string logString = logStream.str();
// Open the file based on log level
std::ofstream logFile;
switch (level) {
case LOGLEVEL::INFO:
logFile.open(INFOFILE, std::ios_base::app);
break;
case LOGLEVEL::WARNING:
logFile.open(WARNFILE, std::ios_base::app);
break;
case LOGLEVEL::ERROR:
logFile.open(ERRORFILE, std::ios_base::app);
break;
}
// Write the log to the file
if (logFile.is_open()) {
logFile << logString.c_str();
logFile.close();
}
//write the log to the general file
logFile.open(LOGFILE, std::ios_base::app);
if (logFile.is_open()) {
logFile << logString.c_str();
logFile.close();
}
}
#endif

21
src/client_backend/log.h Normal file
View File

@@ -0,0 +1,21 @@
#ifndef LOG_H
#define LOG_H
#include <iostream>
#include <ctime>
#include <iomanip>
#include <sstream>
#include "well_known.h"
enum class LOGLEVEL {
INFO,
WARN,
ERR
};
std::string get_loglevel(LOGLEVEL level);
template <typename... Args>
void log(LOGLEVEL level, const std::string& message, Args&&... args);
#endif // LOGGER_H

View File

@@ -29,7 +29,7 @@ BOOL create_file_protection(SECURITY_ATTRIBUTES* pSA)
// Administrators are allowed full control.
// Modify these values as needed to generate the proper
// DACL for your application.
TCHAR* szSD = TEXT("D:")
LPCSTR szSD = TEXT("D:")
TEXT("(D;OICI;GA;;;BG)") // Deny access to guest users
TEXT("(D;OICI;GA;;;AN)") // Deny access to unauthenticated users
//TEXT("(D;OICI;GA;;;AU)") // Deny access to authenticated users do not execute else not even admins have rights anymore :(

View File

@@ -0,0 +1,14 @@
#pragma once
#define MAIN_COM "main_com.txt"
#define MAIN_COM_PATH "C:\\Program Files\\cyberhex\\com\\main_com.txt"
#define SECURE_COM "secure_com.txt"
#define SECURE_COM_PATH "C:\\Program Files\\cyberhex\\secure\\com\\secure_com.txt"
#define SCHED "sched.txt"
#define SCHED_PATH "C:\\Program Files\\cyberhex\\secure\\settings\\sched.txt"
#define LOGFILE "C:\\Program Files\\cyberhex\\secure\\log\\log.txt"
#define INFOFILE "C:\\Program Files\\cyberhex\\secure\\log\\info.txt"
#define WARNFILE "C:\\Program Files\\cyberhex\\secure\\log\\warn.txt"
#define ERRORFILE "C:\\Program Files\\cyberhex\\secure\\log\\error.txt"

Binary file not shown.

View File

@@ -0,0 +1,10 @@
{
"Version": "1.2",
"Data": {
"Source": "c:\\users\\janis\\documents\\projekte_mit_c\\ma\\ma\\src\\client_backend\\app_ctrl.h",
"ProvidedModule": "",
"Includes": [],
"ImportedModules": [],
"ImportedHeaderUnits": []
}
}

View File

@@ -0,0 +1,22 @@
{
"version": 1,
"revision": 0,
"rules": [
{
"primary-output": "x64\\Debug\\app_ctrl.h.obj",
"outputs": [
"C:\\Users\\janis\\Documents\\Projekte_mit_c\\ma\\ma\\src\\client_backend\\x64\\Debug\\vc143.pdb",
"x64\\Debug\\",
"C:\\Users\\janis\\Documents\\Projekte_mit_c\\ma\\ma\\src\\client_backend\\x64\\Debug\\app_ctrl.h.ifc"
],
"provides": [
{
"logical-name": "app_ctrl.h",
"source-path": "c:\\users\\janis\\documents\\projekte_mit_c\\ma\\ma\\src\\client_backend\\app_ctrl.h",
"lookup-method": "absolute"
}
],
"requires": []
}
]
}

View File

@@ -0,0 +1,10 @@
{
"Version": "1.2",
"Data": {
"Source": "c:\\users\\janis\\documents\\projekte_mit_c\\ma\\ma\\src\\client_backend\\app_ctrl.h",
"ProvidedModule": "",
"Includes": [],
"ImportedModules": [],
"ImportedHeaderUnits": []
}
}

View File

@@ -0,0 +1,9 @@
{
"Version": "1.1",
"Data": {
"Source": "c:\\users\\janis\\documents\\projekte_mit_c\\ma\\ma\\src\\client_backend\\app_ctrl.h",
"ProvidedModule": "",
"ImportedModules": [],
"ImportedHeaderUnits": []
}
}

View File

@@ -1,2 +1,6 @@
 client_backend.cpp
client_backend.vcxproj -> C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\client_backend.exe
 Quellen werden auf Modulabhängigkeiten überprüft...
client_backend.cpp
log.cpp
Code wird generiert...
client_backend.obj : error LNK2019: Verweis auf nicht aufgelöstes externes Symbol ""void __cdecl log<>(enum LOGLEVEL,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (??$log@$$V@@YAXW4LOGLEVEL@@AEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)" in Funktion "main".
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\client_backend.exe : fatal error LNK1120: 1 nicht aufgelöste Externe

View File

@@ -1,7 +1,10 @@
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\app_ctrl.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\app_ctrl.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\app_ctrl.h;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\app_ctrl.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\app_ctrl.h;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\app_ctrl.h.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\client_backend.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\client_backend.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\connect.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\connect.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\local_com.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\local_com.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\local_schedule.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\local_schedule.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\log.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\log.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\md5hash.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\md5hash.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\permissions.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\permissions.obj
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\queue _ctrl.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\x64\Debug\queue _ctrl.obj

View File

@@ -1,2 +1,2 @@
PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.37.32822:TargetPlatformVersion=10.0.22621.0:VcpkgTriplet=x64-windows:
PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.38.33130:TargetPlatformVersion=10.0.22621.0:VcpkgTriplet=x64-windows:
Debug|x64|C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\client_backend\|

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

View File

@@ -0,0 +1 @@
<EFBFBD><EFBFBD>

Binary file not shown.

View File

@@ -80,6 +80,34 @@ BOOL create_dacl(SECURITY_ATTRIBUTES* pSA)
//TEXT("(A;OICI;GA;;;AA)"); // Allow full control to administrators
if (NULL == pSA)
return FALSE;
return ConvertStringSecurityDescriptorToSecurityDescriptor(
szSD,
SDDL_REVISION_1,
&(pSA->lpSecurityDescriptor),
NULL);
}
BOOL create_insecure_dacl(SECURITY_ATTRIBUTES* pSA)
{
// Define the SDDL for the DACL. This example sets
// the following access:
// Built-in guests are denied all access.
// Anonymous logon is denied all access.
// Authenticated users are allowed
// read/write/execute access.
// Administrators are allowed full control.
// Modify these values as needed to generate the proper
// DACL for your application.
const wchar_t* szSD = TEXT("D:")
TEXT("(D;OICI;GA;;;BG)") // Deny access to authenticated users
TEXT("(D;OICI;GA;;;AN)") // Deny access to authenticated users
TEXT("(A;OICI;GA;;;AU)") // Deny access to authenticated users
TEXT("(A;OICI;GA;;;BA)"); // Allow full control to builtinadministrators
//TEXT("(A;OICI;GA;;;AA)"); // Allow full control to administrators
if (NULL == pSA)
return FALSE;
@@ -129,6 +157,46 @@ int create_secure_folder(LPCWSTR folderpath) {
}
return error;
}
int create_insecure_folder(LPCWSTR folderpath) {
int error = 0;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = FALSE;// objects are not inherited
// Call function to set the DACL. The DACL
// is set in the SECURITY_ATTRIBUTES
// lpSecurityDescriptor member.
if (!create_insecure_dacl(&sa))
{
// Error encountered; generate message and exit.
//printf("Failed to create access control list\n");
error = 1;
}
// Use the updated SECURITY_ATTRIBUTES to specify
// security attributes for securable objects.
// This example uses security attributes during
// creation of a new directory.
if (error == 0) {
if (0 == CreateDirectory(folderpath, &sa))
{
// Error encountered; generate message and exit.
//could not create directory
error = 2;
}
}
// Free the memory allocated for the SECURITY_DESCRIPTOR.
if (error == 0) {
if (NULL != LocalFree(sa.lpSecurityDescriptor))
{
// Error encountered; generate message and exit.
//printf("Failed to free the allocated memory\n");
error = 3;
}
}
return error;
}
int main()
{
printf("Welcome to the Cyberhex installer!\n");
@@ -144,18 +212,22 @@ int main()
//we started the app as admin. This process can be terminated now
exit(0);
}
}else {
}
else {
// We're admin, so we can do admin stuff here ...
printf("Creating directorys\n");
printf("Creating directory for application\n");
CreateDirectory(L"C:\\Program Files\\cyberhex", NULL); //create main folder for cyberhex
printf("Creating directory for communication\n");
CreateDirectory(L"C:\\Program Files\\cyberhex\\com", NULL); //create folder for communication with desktop client
printf("Creating directory for desktop client\n");
CreateDirectory(L"C:\\Program Files\\cyberhex\\app", NULL); //create folder for desktop client application
printf("Creating directory for secure files\n");
error = create_secure_folder(L"C:\\Program Files\\cyberhex\\secure"); //create secure folder
if (error == 0){
error = create_insecure_folder(L"C:\\Program Files\\cyberhex"); //create main folder for cyberhex
if (error == 0) {
printf("Creating directory for communication\n");
error = create_insecure_folder(L"C:\\Program Files\\cyberhex\\com"); //create folder for communication with desktop client
}if (error == 0) {
printf("Creating directory for desktop client\n");
error = create_insecure_folder(L"C:\\Program Files\\cyberhex\\app"); //create folder for desktop client application
}if (error == 0) {
printf("Creating directory for secure files\n");
error = create_secure_folder(L"C:\\Program Files\\cyberhex\\secure"); //create secure folder
}if (error == 0){
printf("Creating directory for database\n");
error = create_secure_folder(L"C:\\Program Files\\cyberhex\\secure\\database"); //create secure folder for hash database
}if (error == 0){
@@ -206,7 +278,7 @@ int main()
}
LPCWSTR serviceName = L"cyberhex_background_service";
LPCWSTR servicePath = L"C:\\Path\\To\\Your\\Executable.exe";
LPCWSTR servicePath = L"C:\\Program Files\\cyberhex\\secure\\app\\cyberhex.exe";
SC_HANDLE hService = CreateService(
hSCManager,

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,198 @@
// ma_uninstaller.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
//
//todo:
/* remove folders
* remove background task
*/
#include <iostream>
#include <Windows.h>
//check if programm is run as admin
bool is_admin() {
BOOL fIsRunAsAdmin = FALSE;
PSID pAdminSID = NULL;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
if (AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0,
&pAdminSID)) {
if (!CheckTokenMembership(NULL, pAdminSID, &fIsRunAsAdmin)) {
fIsRunAsAdmin = FALSE;
}
FreeSid(pAdminSID);
}
return (fIsRunAsAdmin != 0);
}
bool run_as_admin() {
wchar_t szPath[MAX_PATH];
if (GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) {
// Launch itself as admin
SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.lpVerb = L"runas";
sei.lpFile = szPath;
sei.hwnd = NULL;
sei.nShow = SW_NORMAL;
if (!ShellExecuteEx(&sei)) {
DWORD dwError = GetLastError();
if (dwError == ERROR_CANCELLED)
{
// The user refused to allow privileges elevation.
return false;
}
}
else {
// End the calling process. User allowd admin rights
return true;
}
}
return false;
}
bool remove_dir(const std::wstring& path) {
// Remove the directory and its contents recursively
if (!RemoveDirectory(path.c_str())) {
DWORD error = GetLastError();
if (error != ERROR_DIR_NOT_EMPTY) {
// Failed to remove the directory
std::wcerr << L"Error removing directory '" << path << L"'. Error code: " << error << std::endl;
return false;
}
// The directory is not empty, so we need to remove its contents first
WIN32_FIND_DATA findFileData;
HANDLE hFind = FindFirstFile((path + L"\\*").c_str(), &findFileData);
if (hFind == INVALID_HANDLE_VALUE) {
std::wcerr << L"Error finding files in directory '" << path << L"'. Error code: " << GetLastError() << std::endl;
return false;
}
do {
if (wcscmp(findFileData.cFileName, L".") != 0 && wcscmp(findFileData.cFileName, L"..") != 0) {
std::wstring filePath = path + L"\\" + findFileData.cFileName;
if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// Recursively remove subdirectories
if (!remove_dir(filePath)) {
FindClose(hFind);
return false;
}
}
else {
// Delete files in the directory
if (DeleteFile(filePath.c_str()) == FALSE) {
std::wcerr << L"Error deleting file '" << filePath << L"'. Error code: " << GetLastError() << std::endl;
FindClose(hFind);
return false;
}
}
}
} while (FindNextFile(hFind, &findFileData) != 0);
FindClose(hFind);
// Try to remove the directory again after its contents have been deleted
if (!RemoveDirectory(path.c_str())) {
std::wcerr << L"Error removing directory '" << path << L"'. Error code: " << GetLastError() << std::endl;
return false;
}
}
return true;
}
int main()
{
printf("Welcome to the Cyberhex uninstaller!\n");
int error = 0;
if (!is_admin()) {
printf("We are not administrator, requesting UAC\n");
if (!run_as_admin()) {
printf("We did not get administrative rights. Please restart the uninstaller!\n");
MessageBox(NULL, L"Please start the uninstaller with amdin privileges!", L"Error", MB_OK);
exit(1);
}
else {
//we started the app as admin. This process can be terminated now
exit(0);
}
}
else {
printf("Removing directorys\n");
printf("Removing directory for application\n");
error = remove_dir(L"C:\\Program Files\\Cyberhex");
if (error == 0)
error = 4;
else
error = 0;
if (error == 0) {
printf("Removing background task\n");
SC_HANDLE hSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_ALL_ACCESS);
if (!hSCManager) {
//std::cerr << "Failed to open service control manager. Error code: " << GetLastError() << std::endl;
//return 1;
error = 1;
}
LPCWSTR serviceName = L"cyberhex_background_service";
SC_HANDLE hService = OpenService(hSCManager, serviceName, DELETE);
if (!hService) {
//std::cerr << "Failed to open service. Error code: " << GetLastError() << std::endl;
CloseServiceHandle(hSCManager);
//return 1;
error = 2;
}
if (!DeleteService(hService)) {
//std::cerr << "Failed to delete service. Error code: " << GetLastError() << std::endl;
error = 3;
}
else {
//std::cout << "Service deleted successfully." << std::endl;
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
}
}
switch (error) {
case 0:
printf("Uninstall finished successfully!\n");
MessageBox(NULL, L"Uninstall finished successfully!", L"Success", MB_OK);
break;
case 1:
printf("Failed to open service control manager.\n");
MessageBox(NULL, L"Failed to open service control manager!", L"Error", MB_OK);
break;
case 2:
printf("Failed to open service.\n");
MessageBox(NULL, L"Failed to open service!", L"Error", MB_OK);
break;
case 3:
printf("Failed to delete service.\n");
MessageBox(NULL, L"Failed to delete service!", L"Error", MB_OK);
break;
case 4:
printf("Failed to remove directory.\n");
MessageBox(NULL, L"Failed to remove directory!", L"Error", MB_OK);
default:
printf("Unknown error\n");
MessageBox(NULL, L"Unknown error!", L"Error", MB_OK);
break;
}
}
// Programm ausführen: STRG+F5 oder Menüeintrag "Debuggen" > "Starten ohne Debuggen starten"
// Programm debuggen: F5 oder "Debuggen" > Menü "Debuggen starten"
// Tipps für den Einstieg:
// 1. Verwenden Sie das Projektmappen-Explorer-Fenster zum Hinzufügen/Verwalten von Dateien.
// 2. Verwenden Sie das Team Explorer-Fenster zum Herstellen einer Verbindung mit der Quellcodeverwaltung.
// 3. Verwenden Sie das Ausgabefenster, um die Buildausgabe und andere Nachrichten anzuzeigen.
// 4. Verwenden Sie das Fenster "Fehlerliste", um Fehler anzuzeigen.
// 5. Wechseln Sie zu "Projekt" > "Neues Element hinzufügen", um neue Codedateien zu erstellen, bzw. zu "Projekt" > "Vorhandenes Element hinzufügen", um dem Projekt vorhandene Codedateien hinzuzufügen.
// 6. Um dieses Projekt später erneut zu öffnen, wechseln Sie zu "Datei" > "Öffnen" > "Projekt", und wählen Sie die SLN-Datei aus.

View File

@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ma_uninstaller", "ma_uninstaller.vcxproj", "{A8DFEDE3-F066-4583-94C9-257F88DFF56A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Debug|x64.ActiveCfg = Debug|x64
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Debug|x64.Build.0 = Debug|x64
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Debug|x86.ActiveCfg = Debug|Win32
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Debug|x86.Build.0 = Debug|Win32
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Release|x64.ActiveCfg = Release|x64
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Release|x64.Build.0 = Release|x64
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Release|x86.ActiveCfg = Release|Win32
{A8DFEDE3-F066-4583-94C9-257F88DFF56A}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {53B44BA8-CBBC-4D67-A9ED-B37B204BD2C5}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,135 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{a8dfede3-f066-4583-94c9-257f88dff56a}</ProjectGuid>
<RootNamespace>mauninstaller</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="ma_uninstaller.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Quelldateien">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Headerdateien">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Ressourcendateien">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="ma_uninstaller.cpp">
<Filter>Quelldateien</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ProjectOutputs>
<ProjectOutput>
<FullPath>C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\x64\Debug\ma_uninstaller.exe</FullPath>
</ProjectOutput>
</ProjectOutputs>
<ContentFiles />
<SatelliteDlls />
<NonRecipeFileRefs />
</Project>

Binary file not shown.

View File

@@ -0,0 +1,2 @@
 ma_uninstaller.cpp
ma_uninstaller.vcxproj -> C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\x64\Debug\ma_uninstaller.exe

Binary file not shown.

View File

@@ -0,0 +1 @@
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\ma_uninstaller.cpp;C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\x64\Debug\ma_uninstaller.obj

View File

@@ -0,0 +1,2 @@
PlatformToolSet=v143:VCToolArchitecture=Native64Bit:VCToolsVersion=14.38.33130:TargetPlatformVersion=10.0.22621.0:VcpkgTriplet=x64-windows:
Debug|x64|C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\|

View File

@@ -0,0 +1 @@
C:\Users\janis\Documents\Projekte_mit_c\ma\ma\src\ma_uninstaller\x64\Debug\ma_uninstaller.exe

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1 @@