跳到正文

个人记录

防 JC 脚本

Segment_Bugcat约 38 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 38 分钟

版本

  1. v3当前
  2. v2
  3. v1

UNJC.cpp

C++
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <string>
#include <atomic>
#include <thread>
#include <chrono>
#include <random>

std::atomic <bool> disableInput(true); // Input disable flag
std::atomic <bool> shutdownFlag(false); // Program shutdown flag
std::atomic <size_t> sequencePosition(0); // Current sequence position
std::atomic <bool> sequenceActive(false); // Sequence input active status
std::atomic <long long> lastKeyTime(0); // Last key press time
static const std::vector <std::vector <DWORD> > unlockCombinations = {
    Your Keys Here
};

// 函数声明
void sigint_handler(int sig);
long long getCurrentTime();
bool checkUnlockCombination(DWORD vkCode);
bool checkContinuousSequence(DWORD vkCode);
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam);
void DisableSecurityOptions();
void EnableSecurityOptions();
bool TerminateTaskManager();
void securityMonitorThread();
bool TerminateProcessByName(const std::string& processName);
void BlockCommandPrompts();
void UnblockCommandPrompts();

// Block Ctrl+C interrupt
void sigint_handler(int sig) {
    // Do nothing, ignore Ctrl+C
}

// Get current timestamp (milliseconds)
long long getCurrentTime() {
    return std::chrono::duration_cast <std::chrono::milliseconds>(
        std::chrono::system_clock::now().time_since_epoch()
    ).count();
}

// Check for unlock combination keys
bool checkUnlockCombination(DWORD vkCode) {
    static std::vector <size_t> combinationPositions(unlockCombinations.size(), 0);
    static long long lastCheckTime = getCurrentTime();

    long long currentTime = getCurrentTime();

    // Timeout reset all sequences
    if (currentTime - lastCheckTime > 60000) // 60 second timeout
        for (size_t i = 0;i < combinationPositions.size();i++) combinationPositions[i] = 0;
    lastCheckTime = currentTime;

    for (size_t i = 0;i < unlockCombinations.size();i++) {
        if (vkCode == unlockCombinations[i][combinationPositions[i]]) {
            combinationPositions[i]++;
            if (combinationPositions[i] == unlockCombinations[i].size()) {
                // Successfully matched a combination
                for (size_t j = 0;j < combinationPositions.size();j++) combinationPositions[j] = 0;
                return true;
            }
        }
		else combinationPositions[i] = 0;
    }

    return false;
}

bool checkContinuousSequence(DWORD vkCode) {
    static std::vector <DWORD> inputBuffer;
    static long long lastInputTime = getCurrentTime();

    long long currentTime = getCurrentTime();

    // Reset buffer if more than 10 seconds between key presses
    if (currentTime - lastInputTime > 10000) inputBuffer.clear();
    lastInputTime = currentTime;

    // Add current key to buffer
    inputBuffer.push_back(vkCode);

    // Keep buffer size reasonable
    if (inputBuffer.size() > 20) inputBuffer.erase(inputBuffer.begin());

    // Check if buffer contains any of the unlock combinations
    for (const auto& combination : unlockCombinations) {
        if (inputBuffer.size() >= combination.size()) {
            for (size_t i = 0;i <= inputBuffer.size() - combination.size();i++) {
                bool match = true;
                for (size_t j = 0;j < combination.size();j++) {
                    if (inputBuffer[i + j] != combination[j]) {
                        match = false;
                        break;
                    }
                }
                if (match) {
                    inputBuffer.clear();
                    return true;
                }
            }
        }
    }

    return false;
}

// Check secret sequence
bool checkSecretSequence(DWORD vkCode) {
    long long currentTime = getCurrentTime();

    // Reset sequence if no key pressed for 2 seconds
    if (currentTime - lastKeyTime > 2000) {
        sequencePosition = 0;
        sequenceActive = false;
    }

    lastKeyTime = currentTime;

    if (!sequenceActive) {
        // Check if sequence starts (first key)
        if (vkCode == unlockCombinations[0][0]) {  // 修复这里
            sequenceActive = true;
            sequencePosition = 1;
            return false;
        }
    }
    else {
        // Check next key in sequence
        if (sequencePosition < unlockCombinations[0].size() &&  // 添加边界检查
            vkCode == unlockCombinations[0][sequencePosition]) {
            sequencePosition++;
            if (sequencePosition == unlockCombinations[0].size()) {  // 修复这里
                // Sequence completed
                sequencePosition = 0;
                sequenceActive = false;
                return true;
            }
        }
        else {
            // Key doesn't match, reset sequence
            sequencePosition = 0;
            sequenceActive = false;
        }
    }

    return false;
}

// Keyboard hook, monitor all keys
LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode >= 0 && wParam == WM_KEYDOWN) {
        KBDLLHOOKSTRUCT* pKey = (KBDLLHOOKSTRUCT*)lParam;
        DWORD vkCode = pKey -> vkCode;

        // Check various unlock conditions
        if (checkUnlockCombination(vkCode) ||
            checkSecretSequence(vkCode) ||
            checkContinuousSequence(vkCode)) {
            disableInput = false;
            shutdownFlag = true;
            PostQuitMessage(0); // Send quit message
            return 1;
        }

        // Block all keyboard input
        if (disableInput) {
            // Specifically block system shortcuts including Win+L, Win+D, Alt+F4, etc.
            if (vkCode == VK_ESCAPE || vkCode == VK_TAB ||
                vkCode == VK_LWIN || vkCode == VK_RWIN ||
                vkCode == 'L' || vkCode == 'D' || // Block Win+L (lock), Win+D (desktop)
                vkCode == VK_F4 || // Block F4 key (part of Alt+F4)
                (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState(VK_MENU) && vkCode == VK_DELETE) || // Ctrl+Alt+Del
                (GetAsyncKeyState(VK_LWIN) && vkCode == 'L') || // Win+L
                (GetAsyncKeyState(VK_LWIN) && vkCode == 'D') || // Win+D
                (GetAsyncKeyState(VK_CONTROL) && vkCode == VK_ESCAPE) || // Ctrl+Esc (Start menu)
                (GetAsyncKeyState(VK_MENU) && vkCode == VK_F4)) { // Alt+F4 (Close window)
                return 1;
            }
            return 1; // Block all other keyboard input
        }
    }

    // Also block Alt+F4 when Alt key is pressed and F4 is released
    if (nCode >= 0 && wParam == WM_KEYUP) {
        KBDLLHOOKSTRUCT* pKey = (KBDLLHOOKSTRUCT*)lParam;
        DWORD vkCode = pKey -> vkCode;

        if (disableInput && vkCode == VK_F4 && GetAsyncKeyState(VK_MENU) & 0x8000) return 1; // Block F4 key release when Alt is held down
    }

    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

// Mouse hook, block all mouse input
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (disableInput) {
        // 扩展鼠标操作禁用范围
        if (wParam == WM_LBUTTONDOWN || wParam == WM_RBUTTONDOWN ||
            wParam == WM_MBUTTONDOWN || wParam == WM_MOUSEWHEEL ||
            wParam == WM_LBUTTONUP ||  // 移除重复的 WM_MOUSEWHEEL
            wParam == WM_RBUTTONUP || wParam == WM_MBUTTONUP ||
            wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK ||
            wParam == WM_MBUTTONDBLCLK || wParam == WM_XBUTTONDOWN ||
            wParam == WM_XBUTTONUP || wParam == WM_XBUTTONDBLCLK) {
            return 1; // 阻止所有鼠标输入
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

void DisableSecurityOptions() {
    HKEY hKey;
    DWORD value = 1;

    // Disable Task Manager
    if (RegCreateKeyEx(HKEY_CURRENT_USER,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
                      0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKey, "DisableTaskMgr", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
        RegCloseKey(hKey);
    }

    // Disable Lock Workstation
    if (RegCreateKeyEx(HKEY_CURRENT_USER,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
                      0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKey, "DisableLockWorkstation", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
        RegCloseKey(hKey);
    }

    // Disable Run dialog
    if (RegCreateKeyEx(HKEY_CURRENT_USER,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                      0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKey, "NoRun", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
        RegCloseKey(hKey);
    }

    // 禁用U盘自动运行功能 - 通过修改注册表
    HKEY hKeyAutoRun;
    DWORD disableValue = 0xFF;  // 禁用所有驱动器的自动运行

    // 方法1: 通过Explorer键值禁用
    if (RegCreateKeyEx(HKEY_CURRENT_USER,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                      0, NULL, 0, KEY_WRITE, NULL, &hKeyAutoRun, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKeyAutoRun, "NoDriveTypeAutoRun", 0, REG_DWORD,
                     (const BYTE*)&disableValue, sizeof(disableValue));
        RegCloseKey(hKeyAutoRun);
    }

    // 方法2: 通过MountPoints2权限控制彻底禁用:cite[1]:cite[5]
    HKEY hKeyMountPoints;
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2",
                    0, KEY_WRITE, &hKeyMountPoints) == ERROR_SUCCESS) {
        // 设置权限拒绝所有用户访问(需要更复杂的ACL操作,这里简化实现)
        // 实际应用中可能需要使用SetSecurityInfo或SetNamedSecurityInfo函数
        // 这里通过设置特殊值来模拟权限限制
        DWORD denyAccess = 1;
        RegSetValueEx(hKeyMountPoints, "DisableAutoRun", 0, REG_DWORD,
                     (const BYTE*)&denyAccess, sizeof(denyAccess));
        RegCloseKey(hKeyMountPoints);
    }

    // 方法3: 禁用所有驱动器的自动运行(更彻底的方法)
    if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                      0, NULL, 0, KEY_WRITE, NULL, &hKeyAutoRun, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKeyAutoRun, "NoDriveTypeAutoRun", 0, REG_DWORD,
                     (const BYTE*)&disableValue, sizeof(disableValue));
        RegCloseKey(hKeyAutoRun);
    }
}

void EnableSecurityOptions() {
    HKEY hKey;

    // 恢复 HKEY_CURRENT_USER 下的系统策略
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "DisableTaskMgr");
        RegDeleteValue(hKey, "DisableLockWorkstation");
        RegCloseKey(hKey);
    }

    // 恢复 Explorer 策略
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "NoRun");
        RegCloseKey(hKey);
    }

    // 恢复命令行相关设置
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Policies\\Microsoft\\Windows\\System",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "DisableCMD");
        RegCloseKey(hKey);
    }

    // 强制刷新注册表更改
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
                      (LPARAM)"Policy", SMTO_BLOCK, 1000, NULL);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
                      (LPARAM)"Windows", SMTO_BLOCK, 1000, NULL);

    // 恢复命令行功能
    UnblockCommandPrompts();

    // 恢复U盘自动运行设置

    // 删除Explorer中的自动运行限制
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "NoDriveTypeAutoRun");
        RegCloseKey(hKey);
    }

    // 恢复MountPoints2的设置
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "DisableAutoRun");
        RegCloseKey(hKey);
    }

    // 删除本地机器中的自动运行限制
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "NoDriveTypeAutoRun");
        RegCloseKey(hKey);
    }
}

// 阻止命令行程序通过注册表
void BlockCommandPrompts() {
    HKEY hKey;
    DWORD value = 1;

    if (RegCreateKeyEx(HKEY_CURRENT_USER,
                      "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                      0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) {
        RegSetValueEx(hKey, "NoRun", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
        RegCloseKey(hKey);
    }
}

void UnblockCommandPrompts() {
    HKEY hKey;

    // 恢复运行功能
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "NoRun");
        RegCloseKey(hKey);
    }

    // 恢复命令行禁用设置
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Policies\\Microsoft\\Windows\\System",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "DisableCMD");
        RegCloseKey(hKey);
    }

    // 恢复 PowerShell 禁用设置
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Policies\\Microsoft\\Windows\\PowerShell",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "Disable");
        RegCloseKey(hKey);
    }

    // 恢复 AppCompatFlags 设置
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                    "Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags\\Layers",
                    0, KEY_WRITE, &hKey) == ERROR_SUCCESS) {
        RegDeleteValue(hKey, "C:\\Windows\\System32\\cmd.exe");
        RegDeleteValue(hKey, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
        RegCloseKey(hKey);
    }
}

bool TerminateProcessByName(const std::string& processName) {
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE) return false;

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

    // 获取当前进程ID和父进程ID
    DWORD currentProcessId = GetCurrentProcessId();
    DWORD parentProcessId = 0;

    // 使用简单的方法获取父进程ID
    HANDLE hCurrentProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, currentProcessId);
    if (hCurrentProcess) {
        // 使用 Process32First/Next 来查找当前进程的父进程ID
        if (Process32First(hSnapshot, &pe)) {
            do {
                if (pe.th32ProcessID == currentProcessId) {
                    parentProcessId = pe.th32ParentProcessID;
                    break;
                }
            } while (Process32Next(hSnapshot, &pe));
        }
        CloseHandle(hCurrentProcess);
    }

    // 重新开始遍历进程
    Process32First(hSnapshot, &pe);

    bool found = false;
    do {
        if (_stricmp(pe.szExeFile, processName.c_str()) == 0) {
            // 跳过系统关键进程、当前进程和父进程
            if (pe.th32ProcessID == currentProcessId ||
                pe.th32ProcessID == parentProcessId ||
                pe.th32ProcessID == 0 ||
                pe.th32ProcessID == 4) { // System and Idle processes
                continue;
            }

            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pe.th32ProcessID);
            if (hProcess != NULL) {
                // 尝试优雅终止
                if (TerminateProcess(hProcess, 0)) found = true;
                CloseHandle(hProcess);
            }
        }
    } while (Process32Next(hSnapshot, &pe));

    CloseHandle(hSnapshot);
    return found;
}

// Check if taskmgr.exe is running and terminate it
bool TerminateTaskManager() {
    return TerminateProcessByName("taskmgr.exe");
}

void securityMonitorThread() {
    while (!shutdownFlag) {
        if (!shutdownFlag) { // 只在未关闭时监控
            // Check and terminate Task Manager if running
            TerminateTaskManager();

            // Check and terminate command prompts if running
            const char* blockedProcesses[] = {
                "cmd.exe",
                "powershell.exe",
                "pwsh.exe",
                "conhost.exe",
                "wscript.exe",
                "cscript.exe",
                "bash.exe", // WSL
                "wsl.exe",  // WSL
                "regedit.exe",
                "msconfig.exe",
                "mmc.exe",
                NULL
            };

            for (int i = 0;blockedProcesses[i] != NULL && !shutdownFlag;i++) TerminateProcessByName(blockedProcesses[i]);
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
}

bool IsRunningAsAdmin() {
    BOOL isAdmin = FALSE;
    PSID adminGroup = 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, &adminGroup)) {
        if (!CheckTokenMembership(NULL, adminGroup, &isAdmin)) isAdmin = FALSE;
        FreeSid(adminGroup);
    }
    return isAdmin;
}

int main() {
    if (!IsRunningAsAdmin()) {
        MessageBox(NULL, "Please run this program as administrator", "Permission Error", MB_ICONERROR | MB_OK);
        return 1;
    }

    // Set signal handler to ignore Ctrl+C
    signal(SIGINT, sigint_handler);

    // Install hooks
    HHOOK keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, 0);
    HHOOK mouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseProc, NULL, 0);

    if (keyboardHook == NULL || mouseHook == NULL) {
        std::cerr << "Failed to install hooks!" << std::endl;
        return 1;
    }

    // Disable security options
    DisableSecurityOptions();

    // Start security monitoring thread
    std::thread monitorThread(securityMonitorThread);

    // Message loop
    MSG msg;
    while (!shutdownFlag) {
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
            if (msg.message == WM_QUIT) break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
		else std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    // Cleanup - 确保正确的顺序
    shutdownFlag = true;

    // 等待监控线程退出
    if (monitorThread.joinable()) monitorThread.join();

    // 恢复系统设置
    EnableSecurityOptions();

    // 卸载钩子
    UnhookWindowsHookEx(keyboardHook);
    UnhookWindowsHookEx(mouseHook);

    // 确保系统有足够时间恢复
    std::this_thread::sleep_for(std::chrono::seconds(1));
    return 0;
}
原文