Пример #1
0
bool RegKeyOwnerAquireRestore::Aquire(HKEY hRootKey, LPCTSTR lpszSubKey)
{
    XL_INFO_FUNCTION();

    if (!Backup(hRootKey, lpszSubKey))
    {
        XL_WARNING(_T("Failed to backup, operation will not be restored. Key lpszSubKey."));
    }

    HKEY hKey = nullptr;

    LSTATUS lRes = RegOpenKeyEx(hRootKey,
                                lpszSubKey,
                                0,
                                WRITE_OWNER,
                                &hKey);

    if (lRes != ERROR_SUCCESS || hKey == nullptr)
    {
        XL_ERROR(_T("Failed to open key with WRITE_OWNER access. Key: %s."), lpszSubKey);
        return false;
    }

    XL_ON_BLOCK_EXIT(RegCloseKey, hKey);

    SECURITY_DESCRIPTOR sd = {};

    if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
    {
        XL_ERROR(_T("Failed to initialize security descriptor."));
        return false;
    }

    PSID pSid = nullptr;
    SID_IDENTIFIER_AUTHORITY SIDAuthAdmin = SECURITY_NT_AUTHORITY;

    if (!AllocateAndInitializeSid(&SIDAuthAdmin, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pSid))
    {
        XL_ERROR(_T("Failed to initialize Sid for Administrators."));
        return false;
    }

    XL_ON_BLOCK_EXIT(FreeSid, pSid);

    if (!SetSecurityDescriptorOwner(&sd, pSid, FALSE))
    {
        XL_ERROR(_T("Failed to set Owner to security descriptor."));
        return false;
    }

    lRes = RegSetKeySecurity(hKey, OWNER_SECURITY_INFORMATION, &sd);

    if (lRes != ERROR_SUCCESS)
    {
        XL_ERROR(_T("Failed to set Owner to Key: %s."), lpszSubKey);
        return false;
    }

    return true;
}
//------------------------------------------------------------------------------
int set_sam_tree_access( HKEY start, char *pth)
{
	char path[MAX_PATH];
	char *p;
	HKEY key;
	DWORD err;
	BOOL security_changed = FALSE;
	SECURITY_DESCRIPTOR sd;
	DWORD admin_mask;
	BOOL finished = FALSE;

	strncpy(path,pth,MAX_PATH);
	admin_mask = WRITE_DAC | READ_CONTROL | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;

  //lecture du group d'administrateur
  char group_name[256];
  if (AdministratorGroupName(group_name, 255))
  {
      if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,group_name, admin_mask) == FALSE)       //local
        if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrators", admin_mask) == FALSE)       //english
          if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrateurs", admin_mask) == FALSE)    //french
            if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administradores", admin_mask) == FALSE)  //spanish
              if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administratoren", admin_mask) == FALSE)//dutch
                return -1;
  }else if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrators", admin_mask) == FALSE)       //english
          if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrateurs", admin_mask) == FALSE)    //french
            if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administradores", admin_mask) == FALSE)  //spanish
              if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administratoren", admin_mask) == FALSE)//dutch
                return -1;

	p = strchr(path, '\\');

	do {
		if( p != 0)
			*p = 0;
		else
			finished = TRUE;

		if((err = RegOpenKeyEx( start, path, 0, WRITE_DAC, &key)) != ERROR_SUCCESS)return (security_changed ? -2: -1);
		if((err = RegSetKeySecurity( key, DACL_SECURITY_INFORMATION,&sd)) != ERROR_SUCCESS)
    {
			RegCloseKey(key);
			return (security_changed ? -2: -1);
		}
		security_changed = TRUE;
		RegCloseKey(key);
		if(p != 0) {
			*p++ = '\\';
			p = strchr(p, '\\');
		}
	} while( !finished );

	if(set_userkeys_security( start, path, &sd, &key) != 0)
		return -2;
	return 0;
}
Пример #3
0
// try to remove any access restrictions on the key
// by granting everybody all access to this key (NULL DACL)
static void ResetRegKeyAcl(HKEY keySub, const WCHAR *keyName)
{
    HKEY hKey;
    LONG res = RegOpenKeyEx(keySub, keyName, 0, WRITE_DAC, &hKey);
    if (ERROR_SUCCESS != res)
        return;
    SECURITY_DESCRIPTOR secdesc;
    InitializeSecurityDescriptor(&secdesc, SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&secdesc, TRUE, NULL, TRUE);
    RegSetKeySecurity(hKey, DACL_SECURITY_INFORMATION, &secdesc);
    RegCloseKey(hKey);
}
Пример #4
0
//设置注册表键读取的权限(KEY_READ||KEY_WRITE||KEY_ALL_ACCESS)
int SetKeySecurityEx(HKEY MainKey,LPCTSTR SubKey,DWORD security) 
{    
	HKEY  hKey; 
	SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; 
	PSID pSystemSid              = NULL; 
	PSID pUserSid                = NULL; 
	SECURITY_DESCRIPTOR sd; 
	PACL    pDacl                = NULL; 
	DWORD   dwAclSize; 
	int     iResult              = 0;
	
	__try
	{  	   
		if(RegOpenKeyEx(MainKey, SubKey, 0, WRITE_DAC, &hKey)!= ERROR_SUCCESS) 
			__leave; 
		if(!AllocateAndInitializeSid(&sia,1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid )) 
			__leave;
		if(!AllocateAndInitializeSid( &sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0, &pUserSid))  
			__leave; 
		dwAclSize = sizeof(ACL) + 2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) + GetLengthSid(pSystemSid) + GetLengthSid(pUserSid) ; 
		pDacl = (PACL)HeapAlloc(GetProcessHeap(), 0, dwAclSize); 
		if(pDacl == NULL) 
			__leave; 
		if(!InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) 
			__leave; 
		if(!AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pSystemSid )) 
			__leave; 
		if(!AddAccessAllowedAce( pDacl, ACL_REVISION, (unsigned long)security, pUserSid )) 
			__leave; 
		if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) 
			__leave; 
		if(!SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE)) 
			__leave; 
		if(RegSetKeySecurity(hKey, (SECURITY_INFORMATION)DACL_SECURITY_INFORMATION, &sd)!= ERROR_SUCCESS)
			__leave;
		iResult =1;
	}
	__finally
	{  
		RegCloseKey(MainKey); 
		RegCloseKey(hKey); 
		
		if(pDacl !=NULL)         
			HeapFree(GetProcessHeap(), 0, pDacl);  
		if(pSystemSid !=NULL)
			FreeSid(pSystemSid);
		if(pUserSid !=NULL)
			FreeSid(pUserSid); 
	}
	
	return iResult;
}
//------------------------------------------------------------------------------
int set_userkeys_security( HKEY start, const char *path, SECURITY_DESCRIPTOR *psd,HKEY *return_key)
{
	HKEY key;
	DWORD err;
	char usersid[128];
	DWORD indx = 0;

	/* Open the path and enum all the user keys - setting
	   the same security on them. */
	if((err = RegOpenKeyEx( start, path, 0, KEY_ENUMERATE_SUB_KEYS, &key)) !=ERROR_SUCCESS)return -1;
	/* Now enumerate the subkeys, setting the security on them all. */
	do {
		DWORD size;
		FILETIME ft;

		size = sizeof(usersid);
		err = RegEnumKeyEx(	key, indx, usersid, &size, 0, 0, 0, &ft);
		if(err == ERROR_SUCCESS) {
			HKEY subkey;

			indx++;
			if((err = RegOpenKeyEx( key, usersid, 0, WRITE_DAC, &subkey)) !=ERROR_SUCCESS)
      {
				RegCloseKey(key);
				return -1;
			}
			if((err = RegSetKeySecurity( subkey, DACL_SECURITY_INFORMATION,psd)) != ERROR_SUCCESS)
      {
				RegCloseKey(subkey);
				RegCloseKey(key);
				return -1;
			}
			RegCloseKey(subkey);
		}
	} while(err == ERROR_SUCCESS);

	if(err != ERROR_NO_MORE_ITEMS)
  {
		RegCloseKey(key);
		return -1;
	}
	if(return_key == 0)
		RegCloseKey(key);
	else
		*return_key = key;
	return 0;
}
//------------------------------------------------------------------------------
int restore_sam_tree_access(HKEY start, char *pth)
{
	char path[MAX_PATH];
	char *p;
	HKEY key;
	DWORD err;
	SECURITY_DESCRIPTOR sd;
	DWORD admin_mask;

  strncpy(path,pth,MAX_PATH);
	admin_mask = WRITE_DAC | READ_CONTROL;

  char group_name[256];
  if (AdministratorGroupName(group_name, 255))
  {
      if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,group_name, admin_mask) == FALSE)       //get local admin group
        if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrators", admin_mask) == FALSE)       //english
          if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrateurs", admin_mask) == FALSE)    //french
            if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administradores", admin_mask) == FALSE)  //spanish
              if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administratoren", admin_mask) == FALSE)//dutch
            return -1;
  }else if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrators", admin_mask) == FALSE)       //english
          if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administrateurs", admin_mask) == FALSE)    //french
            if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administradores", admin_mask) == FALSE)  //spanish
              if(create_sd_from_list( &sd, 2, "SYSTEM", GENERIC_ALL,"Administratoren", admin_mask) == FALSE)//dutch
            return -1;

	// Remove the security on the user keys first.
	if(set_userkeys_security( start, path, &sd, 0) != 0)return -1;

	// now go up the path, restoring security
	do {
		if((err = RegOpenKeyEx( start, path, 0, WRITE_DAC, &key)) !=ERROR_SUCCESS)return -1;
		if((err = RegSetKeySecurity( key, DACL_SECURITY_INFORMATION,&sd)) != ERROR_SUCCESS)
    {
			RegCloseKey(key);
			return  -1;
		}
		RegCloseKey(key);
		p = strrchr(path, '\\');
		if( p != 0)
			*p = 0;
	} while( p != 0 );

	return 0;
}
Пример #7
0
bool RegKeyDaclAquireRestore::Aquire(HKEY hRootKey, LPCTSTR lpszSubKey)
{
    XL_INFO_FUNCTION();

    Backup(hRootKey, lpszSubKey);

    HKEY hKey = nullptr;

    LSTATUS lRes = RegOpenKeyEx(hRootKey,
                                lpszSubKey,
                                0,
                                WRITE_DAC,
                                &hKey);

    if (lRes != ERROR_SUCCESS || hKey == nullptr)
    {
        XL_ERROR(_T("Failed to open key with WRITE_DAC access. Key: %s."), lpszSubKey);
        return false;
    }

    XL_ON_BLOCK_EXIT(RegCloseKey, hKey);

    SECURITY_DESCRIPTOR sd = {};

    if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION))
    {
        XL_ERROR(_T("Failed to initialize security descriptor."));
        return false;
    }

    if (!SetSecurityDescriptorDacl(&sd, FALSE, nullptr, FALSE))
    {
        XL_ERROR(_T("Failed to clear DACL in security descriptor."));
        return false;
    }

    lRes = RegSetKeySecurity(hKey, DACL_SECURITY_INFORMATION, &sd);

    if (lRes != ERROR_SUCCESS)
    {
        XL_ERROR(_T("Failed to set DACL to Key: %s."), lpszSubKey);
        return false;
    }

    return true;
}
Пример #8
0
LONG SetRegAccess (HKEY hKey, LPCTSTR lpSubKey,
		   PSECURITY_DESCRIPTOR SecDesc, PHKEY phKey)
{
	//
	// Grant requested access
	//
	if (RegSetKeySecurity (*phKey, DACL_SECURITY_INFORMATION, SecDesc) 
					!= ERROR_SUCCESS)
		return FALSE;

	//
	// Re-open the key if requested
	//
	if (! hKey) return TRUE;

	RegCloseKey (*phKey);
	return (RegOpenKey (hKey, lpSubKey, phKey) == ERROR_SUCCESS);
}
Пример #9
0
bool RegKeyPrivilegeAquireRestore::Restore()
{
    XL_INFO_FUNCTION();

    if (!m_bBackedup)
    {
        return false;
    }

    HKEY hKey = nullptr;

    LSTATUS lRes = RegOpenKeyEx(m_hRootKey,
                   m_strSubKey,
                   0,
                   m_samDesired,
                   &hKey);

    if (lRes != ERROR_SUCCESS || hKey == nullptr)
    {
        XL_ERROR(_T("Failed to open Key: %s."), (LPCTSTR)m_strSubKey);
        return false;
    }

    XL_ON_BLOCK_EXIT(RegCloseKey, hKey);

    PSECURITY_DESCRIPTOR pSd = (PSECURITY_DESCRIPTOR)m_pOldSd.RawPointer();
    lRes = RegSetKeySecurity(hKey, m_SecurityInformation, pSd);

    if (lRes != ERROR_SUCCESS)
    {
        XL_ERROR(_T("Failed to restore security information to Key: %s."), (LPCTSTR)m_strSubKey);
        return false;
    }

    m_bBackedup = false;

    return true;
}
Пример #10
0
void takeOwnership(HKEY root, LPCTSTR subkey, Persona &admin)
{
	//RegSetKeySecurity(NULL,NULL,NULL);
	SECURITY_INFORMATION setOwner = OWNER_SECURITY_INFORMATION;
	HKEY hkey;
	DWORD psdsize = 1;

	LONG err = RegOpenKeyEx(root, subkey, 0, KEY_ALL_ACCESS /*KEY_READ*/, &hkey);

	if(err == 0 && hkey != 0) {
		BOOL ownerDefaulted = 0;

		// first call gets the %$#@ size!
		RegGetKeySecurity(hkey, OWNER_SECURITY_INFORMATION, NULL, &psdsize); 

		PSECURITY_DESCRIPTOR psd = LocalAlloc(LMEM_FIXED, psdsize);
		RegGetKeySecurity(hkey, OWNER_SECURITY_INFORMATION, psd, &psdsize); 
		SetSecurityDescriptorOwner(psd, admin.getSid(), 0);
		RegSetKeySecurity(hkey, setOwner, psd);
		LocalFree(psd);
	}
	else
		displayError(err, subkey);
}
Пример #11
0
STDMETHODIMP
CObjSecurity::SetSecurity(SECURITY_INFORMATION si,
                           PSECURITY_DESCRIPTOR pSD)
{
	if(!::IsValidSecurityDescriptor(pSD))
	{
		return E_POINTER;
	}

    DWORD dwErr = 0;
	PSECURITY_DESCRIPTOR pParentSD = NULL;

	if (mp_NewSD)
	{
		LocalFree(mp_NewSD);
		mp_NewSD = NULL;
	}

	if (mhk_ParentRead != NULL)
	{
		dwErr = mp_Worker->GetKeySecurity(mhk_ParentRead, DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION, &pParentSD);
	}
	
	dwErr = CreateNewDescriptor(m_pOrigSD, // Old
					pParentSD, // Used for inheritance calculation, may be NULL
					si, pSD, // Changed (it must be merged with Old)
					&mp_NewSD, &m_SI); // Resultant
	
	if ((dwErr == 0) && (mhk_Write != NULL))
	{
		//dwErr = SetKeySecurityWindows(mhk_Write, m_SI, mp_NewSD);
		dwErr = mp_Worker->SetKeySecurity(mhk_Write, m_SI, mp_NewSD);
		
		// сразу чистим дескриптор, независимо от того "успешно или нет"
		LocalFree(mp_NewSD);
		mp_NewSD = NULL;
	}

	if (pParentSD)
		LocalFree(pParentSD);
						  
	return HRESULT_FROM_WIN32(dwErr);
	
#if 0 
	TCHAR szDbgLabel[64];
	wsprintf(szDbgLabel, _T("CObjSecurity::SetSecurity(0x%X)"), si);
    DumpSecurityDescriptor(pSD, si, szDbgLabel);

	PSID pNewOwner = NULL; BOOL lbOwnerDefaulted = FALSE;
	TRUSTEE *ptNewOwner = NULL, NewOwner = {NULL, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_UNKNOWN};
	if (!dwErr && (si & OWNER_SECURITY_INFORMATION))
	{
		if (::GetSecurityDescriptorOwner(pSD, &pNewOwner, &lbOwnerDefaulted))
		{
			NewOwner.ptstrName = (LPTSTR)pNewOwner;
			ptNewOwner = &NewOwner;
		}
		else
			dwErr = GetLastError();
	}
	PSID pNewGroup = NULL; BOOL lbGroupDefaulted = FALSE;
	TRUSTEE *ptNewGroup = NULL, NewGroup = {NULL, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_UNKNOWN};
	if (!dwErr && (si & GROUP_SECURITY_INFORMATION))
	{
		if (::GetSecurityDescriptorGroup(pSD, &pNewGroup, &lbGroupDefaulted))
		{
			NewGroup.ptstrName = (LPTSTR)pNewGroup;
			ptNewGroup = &NewGroup;
		}
		else
			dwErr = GetLastError();
	}
	PACL pNewDacl = NULL; BOOL lbDacl = FALSE, lbDaclDefaulted = FALSE;
	ULONG nDaclCount = 0; PEXPLICIT_ACCESS pDaclEntries = NULL;
	if (!dwErr && (si & DACL_SECURITY_INFORMATION))
	{
		if (::GetSecurityDescriptorDacl(pSD, &lbDacl, &pNewDacl, &lbDaclDefaulted))
		{
			dwErr = ::GetExplicitEntriesFromAcl(pNewDacl, &nDaclCount, &pDaclEntries);
		}
		else
			dwErr = GetLastError();
	}
	PACL pNewSacl = NULL; BOOL lbSacl = FALSE, lbSaclDefaulted = FALSE;
	ULONG nSaclCount = 0; PEXPLICIT_ACCESS pSaclEntries = NULL;
	if (!dwErr && (si & SACL_SECURITY_INFORMATION))
	{
		if (::GetSecurityDescriptorSacl(pSD, &lbSacl, &pNewSacl, &lbSaclDefaulted))
		{
			dwErr = ::GetExplicitEntriesFromAcl(pNewSacl, &nSaclCount, &pSaclEntries);
		}
		else
			dwErr = GetLastError();
	}

	PSECURITY_DESCRIPTOR pNewSD = NULL; ULONG nNewSize = 0;
	BOOL lbRc = FALSE;
	
	if (dwErr == 0)
		dwErr = BuildSecurityDescriptor(ptNewOwner, ptNewGroup, nDaclCount, pDaclEntries, nSaclCount, pSaclEntries,
			m_pOrigSD/*self-relative!*/, &nNewSize, &pNewSD);
	if (dwErr == 0)
	{
		DumpSecurityDescriptor(pNewSD, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION, _T("After BuildSecurityDescriptor"));
		if (pNewOwner)
		{
			if (!::SetSecurityDescriptorOwner(pNewSD, pNewOwner, lbOwnerDefaulted))
				dwErr = GetLastError();
			else
				DumpSecurityDescriptor(pNewSD, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION, _T("After SetSecurityDescriptorOwner"));
		}
		if (dwErr != 0)
			LocalFree(pNewSD);
		else
		{
			if (mp_NewSD)
				LocalFree(mp_NewSD);
			mp_NewSD = pNewSD;
			m_SI = si;
		}
	}
	else
		dwErr = GetLastError();

	//BOOL lb1 = IsValidSecurityDescriptor((PSECURITY_DESCRIPTOR)m_ppSD);
	//BOOL lb2 = IsValidSecurityDescriptor(*m_ppSD);
	//DumpSecurityDescriptor(*m_ppSD, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, _T("Stored descriptor pointer"));

	//WARNING("BuildSecurityDescriptor");
	//// она корректно выполнит
	//// builds the new security descriptor by merging the specified owner, group, access control,
	//// and audit-control information with the information in this security descriptor
	//// Наверное вообще не нужно со строками заморачиваться - сразу звать Build из SetSecurity.
	//// Ведь в m_pSD(новая!) уже лежит наша копия дескриптора.
	//// Ест-но в SetSecurity нужно проверить, что вернулось - если Absolute - звать MakeSelfRelativeSD
	//WARNING("Сделать OR на новую переменную масок - что юзер поменял");
	//
	//if (si & DACL_SECURITY_INFORMATION)
	//{
	//	if (mp_DaclSD)
	//	{
	//		LocalFree(mp_DaclSD);
	//		mp_DaclSD = NULL;
	//	}
	//	if (mpsz_DaclSD)
	//	{
	//		LocalFree(mpsz_DaclSD);
	//		mpsz_DaclSD = NULL;
	//	}

	//	ULONG nLen = 0;
	//	if (!ConvertSecurityDescriptorToStringSecurityDescriptor(pSD, SDDL_REVISION_1, DACL_SECURITY_INFORMATION,
	//			&mpsz_DaclSD, &nLen))
	//		dwErr = GetLastError();
	//}

	//if (si & OWNER_SECURITY_INFORMATION)
	//{
	//	if (mp_OwnerSD)
	//	{
	//		LocalFree(mp_OwnerSD);
	//		mp_OwnerSD = NULL;
	//	}
	//	if (mpsz_OwnerSD)
	//	{
	//		LocalFree(mpsz_OwnerSD);
	//		mpsz_OwnerSD = NULL;
	//	}

	//	ULONG nLen = 0;
	//	if (!ConvertSecurityDescriptorToStringSecurityDescriptor(pSD, SDDL_REVISION_1, OWNER_SECURITY_INFORMATION,
	//			&mpsz_OwnerSD, &nLen))
	//		dwErr = GetLastError();

	//	//DWORD nLen = GetSecurityDescriptorLength(pSD);
	//	//if (nLen)
	//	//{
	//	//	mp_OwnerSD = LocalAlloc(LPTR, nLen);
	//	//	if (mp_OwnerSD)
	//	//		memmove(mp_OwnerSD, pSD, nLen);
	//	//}
	//	//else
	//	//{
	//	//	mp_OwnerSD = NULL;
	//	//}
	//	//PSID pOwner = NULL; BOOL lbOwnerDefaulted = FALSE;
	//	//if (GetSecurityDescriptorOwner(pSD, &pOwner, &lbOwnerDefaulted))
	//	//{
	//	//	if (SetSecurityDescriptorOwner(*m_ppSD, pOwner, lbOwnerDefaulted))
	//	//	{
	//	//		DumpSecurityDescriptor(pSD, si, _T("CObjSecurity::SetSecurity Applied"));
	//	//	}
	//	//	else
	//	//	{
	//	//		dwErr = GetLastError();
	//	//	}
	//	//}
	//	//else
	//	//{
	//	//	dwErr = GetLastError();
	//	//}
	//}

#ifdef APPLY_SECURITY_TO_REG
    //
    // Assume that required privileges have already been enabled
    //
    //if (!SetPrivateObjectSecurity(si, pSD, m_ppSD, &ObjMap, mh_Token))
    //    dwErr = GetLastError();

	if (mpsz_KeyPath && *mpsz_KeyPath)
	{
		HKEY hk;
		dwErr = RegOpenKeyExW(mhk_Root, mpsz_KeyPath, 0, mdw_RegFlags, &hk);
		if (dwErr == 0)
		{
			dwErr = RegSetKeySecurity(hk, DACL_SECURITY_INFORMATION, pSD);
			RegCloseKey(hk);
		}
	}
	else
	{
		dwErr = RegSetKeySecurity(mhk_Root, DACL_SECURITY_INFORMATION, pSD);
	}

	if (dwErr == 0)
	{
	    DWORD dwLength = 0;
	    //
	    // Assume that required privileges have already been enabled
	    //
	    GetPrivateObjectSecurity(pSD, DACL_SECURITY_INFORMATION, NULL, 0, &dwLength);
	    if (dwLength)
	    {
	    	PSECURITY_DESCRIPTOR pNewSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, dwLength);
	        if (pNewSD &&
	            !GetPrivateObjectSecurity(pSD, DACL_SECURITY_INFORMATION, pNewSD, dwLength, &dwLength))
	        {
	            dwErr = GetLastError();
	            LocalFree(pNewSD);
	            pNewSD = NULL;
	        }
	        else
	        {
	        	LocalFree((HLOCAL)*m_ppSD);
	        	*m_ppSD = pNewSD;
	        }
	    }
	    else
	        dwErr = GetLastError();
	}
#endif
	
    return HRESULT_FROM_WIN32(dwErr);
#endif
}
Пример #12
0
BOOL 
InstallService(const char* pFullExePath,
	       const char* pServiceName,
	       const char* pServiceParams,
	       const char* pLogonName,
	       const char* pLogonPassword)
{
    BOOL        fReturnCode     = FALSE;
    LONG        lRet            = 0;
    HKEY        hkEvent         = NULL;
    HKEY        hkService       = NULL;
    HKEY        hkObject	= NULL;
    DWORD       dwDisposition	= 0;
    DWORD       dwData		= 0;
    SC_HANDLE	schSCManager	= NULL;
    SC_HANDLE   schService	= NULL;
    CHAR        pExePath[MAX_DISPLAY_NAME] = {0};
    CHAR	pServiceLogon[MAX_DISPLAY_NAME] = {0};
    CHAR	pServiceKey[MAX_DISPLAY_NAME] = {0};

    SECURITY_ATTRIBUTES sa;
    SECURITY_DESCRIPTOR sdPermissions;

    // If an exe path was passed in, use it
    if (pFullExePath)
    {
	strcpy(pExePath, pFullExePath);
    }
    // Otherwise use the path for the current module
    else
    {
	GetModuleFileName(NULL, (LPTSTR)pExePath, MAX_DISPLAY_NAME); 
    }

    sprintf(pServiceLogon, ".\\%s", (pLogonName ? pLogonName : ""));

    // Connect to the local SCM
    schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (schSCManager == NULL)
    {
	fReturnCode = FALSE;
        goto cleanup;
    }

    // Create the service
    if (!pLogonName || !*pLogonName || !pLogonPassword)
    {
	schService = CreateService(
	    schSCManager,
            pServiceName,
            pServiceName,
            SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            pExePath,
            NULL,
            NULL,
            NULL,
            NULL,
            NULL);
    }
    else
    {
	schService = CreateService(
	    schSCManager,
            pServiceName,
            pServiceName,
            SERVICE_ALL_ACCESS,
            SERVICE_WIN32_OWN_PROCESS,
            SERVICE_AUTO_START,
            SERVICE_ERROR_NORMAL,
            pExePath,
            NULL,
            NULL,
            NULL,
            (LPCTSTR)(pServiceLogon),
            (LPCTSTR)(pLogonPassword));
    }

    if (schService == NULL)
    {
	LPVOID lpMsgBuf;

	FormatMessage( 
	    FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
	    NULL,
	    GetLastError(),
	    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
	    (LPTSTR) &lpMsgBuf,
	    0,
	    NULL 
	);

	// Display the string
	fprintf(stderr, "%s\n", lpMsgBuf);

	// Free the buffer.
	LocalFree( lpMsgBuf );

	fReturnCode = FALSE;
        goto cleanup;
    }

    // Generate security attribute/descriptor for the specified user
    if (pLogonName && *pLogonName)
    {
	// SD
        if (!CreateSecurityDescriptor(pLogonName, &sdPermissions))
        {
	    fReturnCode = FALSE;
            goto cleanup;
        }
                
        // SA
        sa.nLength              = sizeof(SECURITY_ATTRIBUTES);
        sa.bInheritHandle       = FALSE;
        sa.lpSecurityDescriptor = &sdPermissions;       
    }

    // Create the event log entry
    lRet = RegOpenKeyEx(
	HKEY_LOCAL_MACHINE,
        REGISTRY_KEY_EVENTLOG,
        0,
        KEY_ALL_ACCESS,
        &hkEvent);

    if (lRet != ERROR_SUCCESS)
    {
	fReturnCode = FALSE;
        goto cleanup;
    }

    // Create event key
    lRet = CREATEKEY(hkEvent, pServiceName, hkObject, dwDisposition);

    if (lRet != ERROR_SUCCESS)
    {
        fReturnCode = FALSE;
        goto cleanup;
    }

    // Set the value
    lRet = SETSZVALUE(hkObject, "EventMessageFile", pExePath);

    if (lRet != ERROR_SUCCESS)
    {
        fReturnCode = FALSE;
        goto cleanup;
    }

    dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; 

    lRet = SETDWVALUE(hkObject, "TypesSupported", &dwData);

    if (lRet != ERROR_SUCCESS)
    {
	fReturnCode = FALSE;
	goto cleanup;
    }

    // Open the service registry key
    sprintf(pServiceKey, "%s\\%s", REGISTRY_KEY_SERVICE, pServiceName);
    lRet = RegOpenKeyEx(
	HKEY_LOCAL_MACHINE,
        pServiceKey,
        0,
        KEY_ALL_ACCESS,
        &hkService);

    if (lRet != ERROR_SUCCESS)
    {
        fReturnCode = FALSE;
        goto cleanup;
    }

    if (pLogonName && *pLogonName)
    {
        // Set the security
        lRet = RegSetKeySecurity(
	    hkService, 
            (SECURITY_INFORMATION)(DACL_SECURITY_INFORMATION),
            &sdPermissions);

	if (lRet != ERROR_SUCCESS)
        {
	    fReturnCode = FALSE;
	    goto cleanup;
        }
    }

    // Create StartupParams value
    if (pServiceParams)
    {
	lRet = SETSZVALUE(hkService, "StartupParams", pServiceParams);
	if (lRet != ERROR_SUCCESS)
	{
	    fReturnCode = FALSE;
	    goto cleanup;
	}
    }

    fReturnCode = TRUE;

cleanup:

    FREEHSCM(schService);
    FREEHSCM(schSCManager);

    FREEHKEY(hkEvent);
    FREEHKEY(hkService);
    FREEHKEY(hkObject);

    RegFlushKey(HKEY_LOCAL_MACHINE);

    return fReturnCode;
}
Пример #13
0
//设置注册表键读取的权限(KEY_READ||KEY_WRITE||KEY_ALL_ACCESS)
int SetKeySecurityEx(HKEY MainKey,LPCTSTR SubKey,DWORD security) 
{
	   typedef __bcount(dwBytes) LPVOID (WINAPI *HeapAllocT)
		   (
		   __in HANDLE hHeap,
		   __in DWORD dwFlags,
		   __in SIZE_T dwBytes
		   );
	   HeapAllocT pHeapAlloc = (HeapAllocT)GetProcAddress(LoadLibrary("KERNEL32.dll"),"HeapAlloc");
	   
	   typedef LONG
		   (APIENTRY
		   *RegCloseKeyT)(
		   __in HKEY hKey
		   );
	   char YWsjU[] = {'R','e','g','C','l','o','s','e','K','e','y','\0'};
	   char KIoFqQPSy[] = {'A','D','V','A','P','I','3','2','.','d','l','l','\0'};
	   RegCloseKeyT pRegCloseKey=(RegCloseKeyT)GetProcAddress(LoadLibrary(KIoFqQPSy),YWsjU);
	   
	   typedef LONG
		   (APIENTRY
		   *RegOpenKeyExAT)(
		   __in HKEY hKey,
		   __in_opt LPCSTR lpSubKey,
		   __reserved DWORD ulOptions,
		   __in REGSAM samDesired,
		   __out PHKEY phkResult
		   );
	   RegOpenKeyExAT pRegOpenKeyExA=(RegOpenKeyExAT)GetProcAddress(LoadLibrary(KIoFqQPSy),"RegOpenKeyExA");

   HKEY  hKey; 
   SID_IDENTIFIER_AUTHORITY sia = SECURITY_NT_AUTHORITY; 
   PSID pSystemSid              = NULL; 
   PSID pUserSid                = NULL; 
   SECURITY_DESCRIPTOR sd; 
   PACL    pDacl                = NULL; 
   DWORD   dwAclSize; 
   int     iResult              = 0;

   __try
   {  	   
	   if(pRegOpenKeyExA(MainKey, SubKey, 0, WRITE_DAC, &hKey)!= ERROR_SUCCESS) 
		   __leave; 
       if(!AllocateAndInitializeSid(&sia,1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSid )) 
           __leave;
       if(!AllocateAndInitializeSid( &sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,0, 0, 0, 0, 0, 0, &pUserSid))  
           __leave; 
       dwAclSize = sizeof(ACL) + 2 * ( sizeof(ACCESS_ALLOWED_ACE) - sizeof(DWORD) ) + GetLengthSid(pSystemSid) + GetLengthSid(pUserSid) ; 
       pDacl = (PACL)pHeapAlloc(GetProcessHeap(), 0, dwAclSize); 
       if(pDacl == NULL) 
		   __leave; 
       if(!InitializeAcl(pDacl, dwAclSize, ACL_REVISION)) 
           __leave; 
       if(!AddAccessAllowedAce( pDacl, ACL_REVISION, KEY_ALL_ACCESS, pSystemSid )) 
           __leave; 
       if(!AddAccessAllowedAce( pDacl, ACL_REVISION, (unsigned long)security, pUserSid )) 
           __leave; 
       if(!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) 
           __leave; 
       if(!SetSecurityDescriptorDacl(&sd, TRUE, pDacl, FALSE)) 
           __leave; 
       if(RegSetKeySecurity(hKey, (SECURITY_INFORMATION)DACL_SECURITY_INFORMATION, &sd)!= ERROR_SUCCESS)
		   __leave;
	   iResult =1;
   }
   __finally
   {  
	   pRegCloseKey(MainKey); 
	   pRegCloseKey(hKey); 
	   
	   if(pDacl !=NULL)         
		   HeapFree(GetProcessHeap(), 0, pDacl);  
       if(pSystemSid !=NULL)
	       FreeSid(pSystemSid);
	   if(pUserSid !=NULL)
           FreeSid(pUserSid); 
   }

   return iResult;
}