Search code examples
cregistryassertion

Editing registry values breaks entire system


I'm having some troubles making a program that needs to edit some registry values NOT brick my entire pc. So below is the code that runs before the error also below. I have confirmed that manually editing the registry values works, but for some reason, this bricks my entire pc (I'm using a VM to demonstrate)

void startBCPE(DWORD SSIP, DWORD ST, DWORD SP, char CL[20]) {
    //Sets registery values for BCPE 
    HKEY key;
    RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\Setup", 0, KEY_ALL_ACCESS, &key);
    if (RegSetValueExA(key, "SystemSetupInProgress", 0, REG_DWORD, (LPBYTE)&SSIP, sizeof((LPBYTE)&SSIP)) != ERROR_SUCCESS || 
        RegSetValueExA(key, "SetupType", 0, REG_DWORD, (LPBYTE)&ST, sizeof((LPBYTE)&ST)) != ERROR_SUCCESS ||
        RegSetValueExA(key, "SetupType", 0, REG_DWORD, (LPBYTE)&ST, sizeof((LPBYTE)&ST) != ERROR_SUCCESS ||
        RegSetValueExA(key, "SetupPhase", 0, REG_DWORD, (LPBYTE)&SP, sizeof((LPBYTE)&SP)) != ERROR_SUCCESS ||
        RegSetValueExA(key, "CmdLine", 0, REG_SZ, (LPBYTE)&CL, sizeof(CL)) != ERROR_SUCCESS)) {
        printf("error"); //runs if any above instruction results in an error, THIS CODE DOES NOT RUN
    }
    
    RegCloseKey(key);
    return;
}

so after the code runs you can't run anything as admin and the computer will not sign you in if you log out or restart.

Edit: hello I am back with some new info, It appears that the registry values its been writing are corrupted or something because CMDline is "8}-"


Solution

  • This is wrong:

    RegSetValueExA(key, "CmdLine", 0, REG_SZ, (LPBYTE)&CL, sizeof(CL));
    

    sizeof(CL) is not the length of your string but it's the size of a pointer on your platform (either 4 or 8 in your case).

    Nor is sizeof(CL) 20 as the char CL[20] declaration might suggest. In this context char CL[20] ist strictly equivalent this char *CL.

    Also (LPBYTE)&CL is wrong, you don't want the address of the pointer, you want the address of your data, you need (LPBYTE)CL (without the &). CL is alsready the pointer do your data.

    So you're basically writing some garbage into the Cmdline value of the SYSTEM\\Setup key in the registry, which might very well mess up Windows.

    So you want this:

    RegSetValueExA(key, "CmdLine", 0, REG_SZ, (LPBYTE)CL, strlen(CL) + 1);
    

    The + 1 is for taking into account the string null terminator.

    Read carefully the the lpData and the cbData sections of the RegSetValueExA documentation.