C++杀毒软件 需要windows 10以上

​
#include <windows.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <thread>
#include <chrono>
#include <filesystem>
#include <psapi.h>
#include <tlhelp32.h>
#include <atlbase.h>
#include <atlcom.h>
#include <appmodel.h>

namespace fs = std::filesystem;

HINSTANCE hInst;
HWND hMainWnd, hLogWnd;
std::thread monitorThread, backgroundThread;
std::vector<std::string> virusSignatures;

std::vector<std::string> loadVirusSignatures(const std::string& configFilePath);
bool containsVirusSignature(const std::string& filePath, const std::vector<std::string>& virusSignatures);
std::vector<std::string> scanDirectory(const std::string& directoryPath, const std::vector<std::string>& virusSignatures);
void saveReport(const std::string& reportPath, const std::vector<std::string>& infectedFiles);
double GetProcessCpuUsage(DWORD processID);
void MonitorHighCpuUsageProcesses(double threshold);
void backgroundTask(const std::vector<std::string>& virusSignatures, const std::string& directoryPath, const std::string& reportPath, double cpuUsageThreshold);
void AddToStartup(const std::string& appName, const std::string& appPath);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void StartMonitoring();
void StartScanning();
void RemoveNonMicrosoftStoreApps();
bool IsMicrosoftStoreApp(const std::wstring& appName);
void LogMessage(const std::string& message);

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE: {
        CreateWindow(TEXT("BUTTON"), TEXT("Monitor programs"), WS_VISIBLE | WS_CHILD, 10, 10, 150, 30, hWnd, (HMENU)1, hInst, NULL);
        CreateWindow(TEXT("BUTTON"), TEXT("Start Scanning"), WS_VISIBLE | WS_CHILD, 10, 50, 150, 30, hWnd, (HMENU)2, hInst, NULL);
        CreateWindow(TEXT("BUTTON"), TEXT("Remove Malicious Apps"), WS_VISIBLE | WS_CHILD, 10, 90, 150, 30, hWnd, (HMENU)3, hInst, NULL);
        hLogWnd = CreateWindow(TEXT("EDIT"), NULL, WS_VISIBLE | WS_CHILD | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL, 10, 130, 300, 200, hWnd, NULL, hInst, NULL);
        break;
    }
    case WM_COMMAND: {
        switch (LOWORD(wParam)) {
        case 1:
            StartMonitoring();
            break;
        case 2:
            StartScanning();
            break;
        case 3:
            RemoveNonMicrosoftStoreApps();
            break;
        }
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

void LogMessage(const std::string& message) {
    int len = GetWindowTextLength(hLogWnd);
    SendMessage(hLogWnd, EM_SETSEL, len, len);
    SendMessage(hLogWnd, EM_REPLACESEL, 0, (LPARAM)message.c_str());
}

void StartMonitoring() {
    monitorThread = std::thread(MonitorHighCpuUsageProcesses, 20.0);
    monitorThread.detach();
    LogMessage("Started monitoring high CPU usage processes.\n");
}

void StartScanning() {
    std::string directoryPathC = "C:\\";
    std::string directoryPathD = "D:\\";
    std::string reportPath = "scan_report.txt";
    backgroundThread = std::thread(backgroundTask, virusSignatures, directoryPathC, reportPath, 20.0);
    backgroundThread.detach();
    backgroundThread = std::thread(backgroundTask, virusSignatures, directoryPathD, reportPath, 20.0);
    backgroundThread.detach();
    LogMessage("Started background scanning on C: and D: drives.\n");
}

void MonitorHighCpuUsageProcesses(double threshold) {
    while (true) {
        HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if (hProcessSnap == INVALID_HANDLE_VALUE) {
            LogMessage("Unable to create toolhelp snapshot!\n");
            continue;
        }

        PROCESSENTRY32 pe32;
        pe32.dwSize = sizeof(PROCESSENTRY32);

        if (!Process32First(hProcessSnap, &pe32)) {
            LogMessage("Unable to get first process!\n");
            CloseHandle(hProcessSnap);
            continue;
        }

        do {
            double cpuUsage = GetProcessCpuUsage(pe32.th32ProcessID);
            if (cpuUsage > threshold) {
                std::string logMsg = "Malicious program detected: " + std::string(pe32.szExeFile) + " (PID: " + std::to_string(pe32.th32ProcessID) + ") - " + std::to_string(cpuUsage) + "%\n";
                LogMessage(logMsg);
                std::string command = "taskkill /PID " + std::to_string(pe32.th32ProcessID) + " /F";
                system(command.c_str());

                std::string notificationCommand = "powershell -Command \"[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('High CPU usage detected and process terminated: " + std::string(pe32.szExeFile) + "')\"";
                system(notificationCommand.c_str());
            }
        } while (Process32Next(hProcessSnap, &pe32));

        CloseHandle(hProcessSnap);
        std::this_thread::sleep_for(std::chrono::seconds(5));
    }
}

void backgroundTask(const std::vector<std::string>& virusSignatures, const std::string& directoryPath, const std::string& reportPath, double cpuUsageThreshold) {
    while (true) {
        std::vector<std::string> infectedFiles = scanDirectory(directoryPath, virusSignatures);
        saveReport(reportPath, infectedFiles);

        std::string logMsg = "Scanning complete. Infected files: " + std::to_string(infectedFiles.size()) + "\n";
        LogMessage(logMsg);

        std::this_thread::sleep_for(std::chrono::hours(1));
    }
}

std::vector<std::string> loadVirusSignatures(const std::string& configFilePath) {
    std::vector<std::string> virusSignatures;
    std::ifstream configFile(configFilePath);
    if (!configFile.is_open()) {
        LogMessage("Unable to open virus signature config file: " + configFilePath + "\n");
        return virusSignatures;
    }

    std::string line;
    while (std::getline(configFile, line)) {
        virusSignatures.push_back(line);
    }

    return virusSignatures;
}

bool containsVirusSignature(const std::string& filePath, const std::vector<std::string>& virusSignatures) {
    std::ifstream file(filePath, std::ios::binary);
    if (!file.is_open()) {
        return false;
    }

    std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());

    for (const auto& signature : virusSignatures) {
        if (content.find(signature) != std::string::npos) {
            return true;
        }
    }

    return false;
}

std::vector<std::string> scanDirectory(const std::string& directoryPath, const std::vector<std::string>& virusSignatures) {
    std::vector<std::string> infectedFiles;

    for (const auto& entry : fs::recursive_directory_iterator(directoryPath)) {
        if (fs::is_regular_file(entry.path())) {
            std::string filePath = entry.path().string();
            if (containsVirusSignature(filePath, virusSignatures)) {
                infectedFiles.push_back(filePath);
                LogMessage("Infected file detected: " + filePath + "\n");
            } else if (filePath.ends_with(".vbs") || filePath.ends_with(".bat") || filePath.ends_with(".cmd")) {
                std::error_code ec;
                fs::remove(filePath, ec);
                if (!ec) {
                    LogMessage("Deleted script file: " + filePath + "\n");
                } else {
                    LogMessage("Failed to delete script file: " + filePath + "\n");
                }
            }
        }
    }

    return infectedFiles;
}

void saveReport(const std::string& reportPath, const std::vector<std::string>& infectedFiles) {
    std::ofstream reportFile(reportPath, std::ios::app);
    if (!reportFile.is_open()) {
        LogMessage("Unable to open report file: " + reportPath + "\n");
        return;
    }

    for (const auto& file : infectedFiles) {
        reportFile << file << "\n";
    }
}

double GetProcessCpuUsage(DWORD processID) {
    FILETIME ftCreation, ftExit, ftKernel, ftUser;
    ULARGE_INTEGER liKernel, liUser;

    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
    if (!hProcess) {
        return 0.0;
    }

    if (GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser)) {
        CloseHandle(hProcess);
        liKernel.LowPart = ftKernel.dwLowDateTime;
        liKernel.HighPart = ftKernel.dwHighDateTime;
        liUser.LowPart = ftUser.dwLowDateTime;
        liUser.HighPart = ftUser.dwHighDateTime;

        return (liKernel.QuadPart + liUser.QuadPart) / 10000.0;
    }

    CloseHandle(hProcess);
    return 0.0;
}

void AddToStartup(const std::string& appName, const std::string& appPath) {
    HKEY hKey;
    LONG result = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &hKey);
    if (result != ERROR_SUCCESS) {
        LogMessage("Failed to open startup registry key.\n");
        return;
    }

    result = RegSetValueEx(hKey, appName.c_str(), 0, REG_SZ, (BYTE*)appPath.c_str(), appPath.size() + 1);
    if (result == ERROR_SUCCESS) {
        LogMessage("Successfully added to startup.\n");
    } else {
        LogMessage("Failed to add to startup.\n");
    }

    RegCloseKey(hKey);
}

bool IsMicrosoftStoreApp(const std::wstring& appName) {
    CComPtr<IAppxPackageManager> packageManager;
    HRESULT hr = CoCreateInstance(__uuidof(AppxPackageManager), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&packageManager));
    if (FAILED(hr)) {
        return false;
    }

    CComPtr<IAppxPackageQuery> query;
    hr = packageManager->QueryInterface(IID_PPV_ARGS(&query));
    if (FAILED(hr)) {
        return false;
    }

    CComPtr<IAppxPackageCollection> packages;
    hr = query->GetInstalledPackages(&packages);
    if (FAILED(hr)) {
        return false;
    }

    UINT32 count = 0;
    hr = packages->GetCount(&count);
    if (FAILED(hr)) {
        return false;
    }

    for (UINT32 i = 0; i < count; ++i) {
        CComPtr<IAppxPackage> package;
        hr = packages->GetAt(i, &package);
        if (FAILED(hr)) {
            continue;
        }

        CComBSTR name;
        hr = package->GetName(&name);
        if (FAILED(hr)) {
            continue;
        }

        if (appName == name) {
            return true;
        }
    }

    return false;
}

void RemoveNonMicrosoftStoreApps() {
    LogMessage("Removing non-Microsoft Store applications.\n");

    CComPtr<IAppxPackageManager> packageManager;
    HRESULT hr = CoCreateInstance(__uuidof(AppxPackageManager), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&packageManager));
    if (FAILED(hr)) {
        LogMessage("Failed to create AppxPackageManager instance.\n");
        return;
    }

    CComPtr<IAppxPackageQuery> query;
    hr = packageManager->QueryInterface(IID_PPV_ARGS(&query));
    if (FAILED(hr)) {
        LogMessage("Failed to query package manager.\n");
        return;
    }

    CComPtr<IAppxPackageCollection> packages;
    hr = query->GetInstalledPackages(&packages);
    if (FAILED(hr)) {
        LogMessage("Failed to get installed packages.\n");
        return;
    }

    UINT32 count = 0;
    hr = packages->GetCount(&count);
    if (FAILED(hr)) {
        LogMessage("Failed to get package count.\n");
        return;
    }

    for (UINT32 i = 0; i < count; ++i) {
        CComPtr<IAppxPackage> package;
        hr = packages->GetAt(i, &package);
        if (FAILED(hr)) {
            continue;
        }

        CComBSTR name;
        hr = package->GetName(&name);
        if (FAILED(hr)) {
            continue;
        }

        if (!IsMicrosoftStoreApp(name)) {
            LogMessage("Removing non-Microsoft Store application: " + std::wstring(name) + "\n");
            hr = packageManager->RemovePackage(name);
            if (FAILED(hr)) {
                LogMessage("Failed to remove application: " + std::wstring(name) + "\n");
            }
        }
    }
}

int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) {
    hInst = hInstance;

    WNDCLASS wc = {};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = TEXT("VirusKillerClass");

    RegisterClass(&wc);

    hMainWnd = CreateWindowEx(0, wc.lpszClassName, TEXT("Virus Killer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);

    if (hMainWnd == NULL) {
        return 0;
    }

    ShowWindow(hMainWnd, nCmdShow);

    virusSignatures = loadVirusSignatures("virus_signatures.txt");

    MSG msg = {};
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int)msg.wParam;
}

​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值