[C++] Adding firewall exceptions
#1
Hellow

I'm trying to add firewall exceptions programmatically using C++, I don't get any compiler errors but yet it ain't working.

Code:
Code:
#include <iostream>
#include <string>
#include <windows.h>
#include <stdlib.h>

using namespace std;


char toAuth[1026];
char *getRegisteryKey() {
    HKEY hk = 0;

    if (RegCreateKeyA(HKEY_LOCAL_MACHINE, "SYSTEM\\Select", &hk) != ERROR_SUCCESS) cout << "1" << endl;
    int i;
    DWORD bufferSize = 4;

    if (RegQueryValueExA(hk, "Current", NULL, NULL, (BYTE*)&i, &bufferSize) == ERROR_SUCCESS) {
        sprintf(toAuth, "SYSTEM\\ControlSet%03d\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\AuthorizedApplications\\List", i);    
    } else cout << "2" << endl;
    RegCloseKey(hk);
}

void addFirewallException(string path) {
    HKEY hk;
    DWORD disposInfo;
    
    string key = path + ":*:Enabled:@xpsp2res.dll,-22019";

    cout << RegCreateKeyExA(HKEY_LOCAL_MACHINE, getRegisteryKey(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hk, &disposInfo) << endl;
    cout << RegSetValueExA(hk, path.c_str(), 0, REG_SZ, (BYTE*)key.c_str(), (DWORD)key.length()) << endl;
    RegCloseKey(hk);
}

int main()
{
    addFirewallException("c:\\users\\name\\desktop\\test123.exe");
    return 0;
}

Output:
1010
6

Which are the error-codes outputted by the function in addFirewallException().

Does anyone know what I'm doing wrong, and how I can add firewall-exceptions using C++?

Thanks!
Reply
#2
Its not clear that your application is running with elevated privileges.
Reply
#3
Getting the same error when running as administrator though.
Reply
#4
Am not familiar with these functions. But here's some general pointers.

getRegistryKey() does not have a return statement (as it perhaps should).

However, since you are using a global variable toAuth to fetch the key, you could call getRegisteryKey() explicity and then pass toAuth as the 2nd argument to RegCreateKeyExA ().

Moreover, what do you want toAuth to be ?
If the value of 'i' is to go into toAuth, you need to include a format specifier (%d) in the second argument.
Code:
sprintf(toAuth, "SYSTEM\\ControlSet%03d\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile\\AuthorizedApplications\\List", i);

Also, use snprintf() instead of sprintf().

Do a cout of the values of 'i', toAuth, to ensure they are correct.
Passing a integer variable as a BYTE * needs to be handled. Hence check the value of variable 'i'.

Check the return value of all functions before you do a cout.

Ref: RegCreateKeyEx()
Reply
#5
Editing the registry is always the last option if there is no other alternative.

In this case there is an excellent example of using the Windows API. This will ensure that the settings are changed correctly and other applications are notified if the change.
Reply




Users browsing this thread: 1 Guest(s)