Hi,
I am trying to access the registry of a remote computer (windows 2003).
Following the remarks in the article:
http://msdn.microsoft.com/en-us/library/ms724840(v=vs.85).aspx
I used both Impersonation and WNetAddConnection2.
Here is my code:
void ConnectRemoteRegistry(LPCSTR machine, LPWSTR wRemoteName, LPWSTR wUser, LPWSTR wPass,
LPCSTR cUser, LPCSTR cPass, std::string keyName)
{
DWORD dwRetVal;
NETRESOURCE nr;
DWORD dwFlags;
memset(&nr, 0, sizeof (NETRESOURCE));
nr.dwType = RESOURCETYPE_ANY;
nr.lpLocalName = NULL;
nr.lpRemoteName = wRemoteName;
nr.lpProvider = NULL;
dwFlags = CONNECT_UPDATE_PROFILE;
dwRetVal = WNetAddConnection2(&nr, wPass, wUser, dwFlags);
if (dwRetVal == NO_ERROR)
wprintf(L"Connection added to %s\n", nr.lpRemoteName);
else
wprintf(L"WNetAddConnection2 failed with error: %u\n", dwRetVal);
HANDLE _token;
dwRetVal = LogonUserA(cUser, NULL, cPass, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT,
&_token);
if(dwRetVal != ERROR_SUCCESS)
{
wprintf(L"LogonUserA failed with error: %u\n", dwRetVal);
}
dwRetVal = ImpersonateLoggedOnUser(_token);
if(dwRetVal != ERROR_SUCCESS)
{
wprintf(L"ImpersonateLoggedOnUser failed with error: %u\n", dwRetVal);
}
HKEY root(HKEY_LOCAL_MACHINE);
HKEY r;
LONG rc = ::RegConnectRegistryA(machine, root, &r);
if (rc != ERROR_SUCCESS)
{
wprintf(L"RegConnectRegistryA failed with error: %u\n", dwRetVal);
}
HKEY key_handle;
rc = ::RegOpenKeyExA(r,keyName.c_str(), REG_OPTION_OPEN_LINK,
KEY_QUERY_VALUE, & key_handle);
if (rc != ERROR_SUCCESS)
{
wprintf(L"RegOpenKeyExA failed with error: %u\n", dwRetVal);
}
RegCloseKey(r);
RevertToSelf();
dwRetVal = WNetCancelConnection2(nr.lpRemoteName, CONNECT_UPDATE_PROFILE, true);
if (dwRetVal != NO_ERROR)
wprintf(L"WNetCancelConnection2 failed with error: %u\n", dwRetVal);
}
I am using a local administrator of the remote machine.
WNetAddConnection2 to c$ is completed successfully.
LogonUserA and ImpersonateLoggedOnUser are completed successfully.
RegConnectRegistryA is also completed successfully.
The problem is that RegOpenKeyExA returns 5 - access denied.
Can you please advise why that might be?
Thanks.