API实现修改注册表权限

转来的文章,由于他也是转的,而且没有写出处,所以我也不写了。这个代码,有时候可能需要用到。比如写程序克隆用户的时候。

#include <Windows.h>
#include <Aclapi.h>
#pragma comment (lib,"Advapi32.lib")

void main()
{
DWORD dwRet;

// 下面这个字符串的值修改为想要进行权限操作的注册表项,注册表每一级的权限是不一样的,所以需要很具体地指定到某一级
LPSTR SamName = "MACHINE\\SAM\\SAM";
PSECURITY_DESCRIPTOR pSD = NULL;
PACL pOldDacl = NULL;
PACL pNewDacl = NULL;
EXPLICIT_ACCESS ea;
HKEY hKey = NULL;

// 获取SAM主键的DACL
dwRet = GetNamedSecurityInfo(SamName, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
NULL, NULL, &pOldDacl, NULL, &pSD);
if (dwRet != ERROR_SUCCESS)
{
printf("GetNamedSecurityInfo Error: %d\n", dwRet);
goto FreeAndExit;
}

// 创建一个ACE,允许Everyone完全控制对象,并允许子对象继承此权限
ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
BuildExplicitAccessWithName(&ea, "Everyone", KEY_ALL_ACCESS, SET_ACCESS,
SUB_CONTAINERS_AND_OBJECTS_INHERIT);

// 将新的ACE加入DACL
dwRet = SetEntriesInAcl(1, &ea, pOldDacl, &pNewDacl);
if (dwRet != ERROR_SUCCESS)
{
printf("SetEntriesInAcl Error: %d\n", dwRet);
goto FreeAndExit;
}

// 更新SAM主键的DACL
dwRet = SetNamedSecurityInfo(SamName, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
NULL, NULL, pNewDacl, NULL);
if (dwRet != ERROR_SUCCESS)
{
printf("SetNamedSecurityInfo Error: %d\n", dwRet);
goto FreeAndExit;
}

// 打开SAM的子键
dwRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SAM\\SAM\\Domains\\Account\\Users\\000001F4",
0, KEY_ALL_ACCESS, &hKey);
if (dwRet != ERROR_SUCCESS)
{
printf("RegOpenKeyEx Error: %d\n", dwRet);
goto FreeAndExit;
}

printf("Open SAM Subkey Successfully.\n");

FreeAndExit:
if (hKey) RegCloseKey(hKey);
if (pNewDacl) LocalFree(pNewDacl);
// 还原SAM主键的DACL
if (pOldDacl) SetNamedSecurityInfo(SamName, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
NULL, NULL, pOldDacl, NULL);
if (pSD) LocalFree(pSD);
return;
}

 



文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 12338