Remediation and Hardening - O365
Remediation and Hardening - O365
Remediation and Hardening - O365
Table of Contents
Overview..................................................................................................................................................... 3
Background........................................................................................................................................ 3
Goals and Objectives...................................................................................................................... 3
Remediation Strategy........................................................................................................................... 4
Remediation Sequencing.............................................................................................................. 5
AD FS Attack Mitigation...................................................................................................................... 6
Conclusion................................................................................................................................................39
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 3
Overview
Background
In December 2020, FireEye uncovered and publicly disclosed a
widespread campaign conducted by the threat group we track
as UNC2452. In some, but not all, of the intrusions associated
with this campaign where Mandiant has visibility, the attacker
used their access to on-premises networks to gain unauthorized
access to the victim’s Microsoft 365 environment.
1. Steal the Active Directory Federation Services (AD FS) token-signing certificate and use it to forge tokens for
arbitrary users (sometimes described as Golden SAML). This would allow the attacker to authenticate into a
federated resource provider (such as Microsoft 365) as any user, without the need for that user’s password or their
corresponding multi-factor authentication (MFA) mechanism.
2. Modify or add trusted domains in Azure AD to add a new federated Identity provider (IdP) that the attacker controls. This
would allow the attacker to forge tokens for arbitrary users and has been described as an Azure AD backdoor.
3. Compromise the credentials of on-premises user accounts that are synchronized to Microsoft 365 and are assigned high
privileged directory roles, such as Global Administrator or Application Administrator.
4. Hijack an existing Microsoft 365 application by adding a rogue credential to it in order to use the legitimate permissions
assigned to the application, such as the ability to read email, send email as an arbitrary user, access user calendars, etc.,
while bypassing MFA.
Remediation Strategy
Developing a successful strategy to eradicate UNC2452 access to a victim’s environment is contingent upon many factors, so
each organization must develop their own unique plan. Two of the most important factors are the actions taken by the attacker
and the specifics of the victim’s environment.
To help victims plan their own strategy, Table 1 provides a high-level overview of techniques related to Microsoft 365 with links
to corresponding remediation and hardening steps.
Attack Technique: TA0006 Step 1: Issue new AD FS Certificates Step 1: AD FS Service Account – Best Practices
Golden SAML Attack T1552
Step 2: Revoke Microsoft 365 Refresh Tokens Step 2: AD FS Logging and Auditing
T1552.004
T1199 Step 3: AD FS Servers - Account Access
Restrictions and Inbound Connectivity
Hardening
Step 1: Review and Configure Cloud-Only Step 2: Limit Privileged Users to Trusted IPs
Accounts for Privileged Role Holders
Attack Technique: Step 3: Enhance Mailbox Auditing
TA0006 Step 2: Rotate All Passwords for Cloud-Only
Abuse Azure AD
T1552 Accounts Step 4: Review Azure Application and Service
Privileged Roles
Step 3: Invalidate Refresh Tokens for Each Principal Permissions
Cloud-Only Account
Step 5: Enforce multi-factor authentication
(MFA) for Accounts
Attack Technique: T1114 Step 1: Review and Remediate Keys
Hijack Azure AD T1114.002 Associated with Service Principals and Step 6: Review all registered MFA devices
Applications T1098.001 Applications
Step 7: Review Partner (Cloud Service
Step 2: Invalidate All Existing Refresh Tokens
Provider) Relationships
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 5
1. Implement short term hardening measures to mitigate g. Rotating other internal credentials or secrets
risk of similar attacks
4. Rotate the AD FS token-signing and token-decrypting
2. Eliminate any attacker remote access to the certificates used with SAML tokens (twice)
on-premises environment, which could include:
5. Rotate credentials for impacted cloud accounts
a. Implementing network blocks and DNS sinkholes
b. Removing remote access backdoors, including 6. Remove attacker created identity providers and
impacted SolarWinds software custom domains
c. Un-enrolling attacker multi-factor authentication
7. Remove attacker certificates and passwords from
(MFA) tokens applications and service principals
d. Rotating secrets associated with remote access MFA
token generation 8. Revoke all existing refresh tokens for Microsoft 365
Note: this will force all users to re-enter their credentials
to utilize Microsoft 365 services through clients such as
Outlook and Teams.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 6
AD FS Attack Mitigation
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 7
ATTACK TECHNIQUE:
Microsoft AD FS uses a “claim-based” identity model The foundation of the security of AD FS is the
to identify roles, permissions, or groups associated confidentiality of the token-signing certificate, which is
with a user authentication. A claim can be any piece of used to digitally sign SAML tokens issued by the AD FS
information about the requesting user’s identity, such as a service. Exposure of the token-signing certificate and
group they belong to, or whether an MFA authentication private key, paired with any compromised AD account (to
was performed during login. For example, if MFA query users’ ImmutableIDs), would allow an attacker to
occurred during the AD FS login, then the claim shown in issue their own forged but verifiable SAML tokens. Taking
Figure 1 would be provided by AD FS. it a step further, a one-time extraction of all ImmutableIDs
and the token-signing certificate with private key would
Multiple claims associated with the authentication are allow the attacker to issue SAML tokens for any user in
packaged into an XML document, known as a SAML token, the organization regardless of their password and any
and digitally signed to ensure verifiability and to prevent password resets that occur afterwards. The attacker
unauthorized modification. When Microsoft 365 receives can insert any claim they want into the SAML token.
a SAML token issued by an AD FS service, it performs This could include the claim detailed in Figure 1, which
the following steps to ensure its validity before providing states that the user performed MFA at the AD FS service.
access to the resource (listed in no particular order): This forged SAML token will bypass MFA requirements
imposed by the cloud application.
• Verify that the digital signature of the SAML token is
valid and uses a known keypair The locations of the token-signing certificate and private
• Verify the SAML token is constructed properly and key depend on how an organization has chosen to
complies with the standard implement AD FS. On-premises AD FS infrastructure
can consist of either a single or multiple AD FS servers,
• Verify that the SAML token has not expired
a database instance, and either single or multiple AD FS
• Verify that the token was issued by a source that web application proxy server(s) housed in a DMZ (Figure
Microsoft 365 expects (the issuer) 2). Most organizations will likely leverage an AD FS server
• Verify that the unique identifier for the user (the farm, using a local Windows Internal Database (WID).
ImmutableID) matches a user in Azure AD
• Evaluate conditional access policies, if any
Figure 1. <saml:AttributeValue>http://schemas.microsoft.com/claims/multipleauthn</
Example SAML claim
saml:AttributeValue>
for Microsoft 365.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 8
Figure 2.
https://docs.
microsoft.com/
en-us/windows-
server/identity/ad- NLB NLB
fs/deployment/
best-practices- Firewall Firewall
securing-ad-fs Active AD FS Web
Directory Application
Proxy
INTRANET DMZ
In the default installation of AD FS, the token-signing This data is stored within an Active Directory
certificate is automatically generated and valid for one attribute CN=ADFS,CN=Microsoft,CN=Program
year. The AD FS service will handle the certificate rollover Data,DC=<domain>,DC=<suffix>. In addition to
process. The following points detail how the token-signing obtaining the token-signing certificate, an attacker
certificate is stored on the AD FS server: would also need to obtain the value from Active
Directory for decrypting the token-signing certificate. By
• The token-signing certificate is stored as a base64 default, this value is only readable by the AD FS service
encoded encrypted blob within the database used by account and Domain Administrators.
the AD FS servers.
Note: If multiple AD FS certificate containers are
• The token-signing certificate is protected using a present in Active Directory, from an AD FS server,
Windows technology called Distributed Key Manager the PowerShell command (Get-AdfsProperties).
(DKM). AD FS uses a key derivation function to CertificateSharingContainer can be used to identify the
derive an AES key that is used to decrypt the token- container that will be used by DKM.
signing certificate stored in the AD FS database.
Figure 3.
Active Directory -
AD FS Container
Attributes.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 9
The AD FS service also makes use of other certificates that First, the attacker must obtain the encrypted token-
are out of scope for this whitepaper. For example, each signing certificate. The threat actor has used a number
cloud application can define a token-decrypting certificate, of techniques to extract the encrypted blob from the
which is used to encrypt the SAML token as it is transmitted IdentityServerPolicy.ServiceSettings table. Mandiant has
to the cloud resource. This option is not widely used. observed techniques including:
Note: If an AD FS server farm model is leveraged, the • Stealing the backup files for the database: Connecting
same token-signing and decryption certificates are used to the server via SMB and copying the database file
by all the AD FS servers. AdfsConfiguration.mdf off the server
• Querying the database via PowerShell: Connecting to
The default configuration for AD FS uses a built-in MSSQL
the server to execute PowerShell that then connects to
database service called Windows Internal Database (WID).
and queries the WID service for the table rows.
The WID service is only accessible from the local host via
a specific named pipe and does not listen on the standard – SELECT ServiceSettingsData from
TCP port 1433. IdentityServerPolicy.ServiceSettings
• Querying the database via custom executable:
The WID service stores the backing files for the AD FS
Writing a custom executable to disk and executing it.
database in the following locations:
The executable queried the WID for the table row and
• C:\Windows\WID\Data\AdfsConfiguration.mdf wrote the output to disk.
• C:\Windows\WID\Data\AdfsConfiguration_log.ldf Next, the attacker must obtain the secret DKM value from
Active Directory to decrypt the token-signing certificate.
A default configuration of AD FS using the WID service will
Mandiant has observed the threat actor using open-source
generate a database table named IdentityServerPolicy.
tools such as ADFind to query Active Directory for the
ServiceSettings to store the token-signing certificate.
DKM value used to decrypt the encrypted token-signing
Technique certificate. Figure 4 details an ADFind query used by
Once UNC2452 had gained on-premises access to an UNC2452 to obtain this value.
organization’s environment, Mandiant observed them
With the certificate and DKM value, the attacker now has
targeting on-premises AD FS servers with the goal of
the data they need to forge SAML tokens and access
obtaining the token-signing certificate to forge SAML
cloud-based resources, while bypassing MFA requirements
tokens. There are two steps an attacker must take to
and the need to know a user’s password (GoldenSAML).
obtain the token-signing certificate and private key.
Figure 5.
Get-ADFSCertificate -CertificateType Token-Signing
Command to Get-ADFSCertificate -CertificateType Token-Decrypting
review the
properties of AD
FS certificates.
Connect-MSOLService
Get-MSOLFederatedProperty -DomainName <domain>
Update-MSOLFederationDomain -DomainName <domain>
Get-MSOLFederatedProperty -DomainName <domain>
** 2nd Iteration **
Connect-MSOLService
Get-MSOLFederatedProperty -DomainName <domain>
Update-MSOLFederationDomain -DomainName <domain>
Get-MSOLFederatedProperty -DomainName <domain>
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 11
Once completed, ensure that the output from the Get -MSOLFederatedProperty -DomainName command only includes
the certificate thumbprints and validity dates that match the recently rotated certificates, and that the certificate
thumbprint from the previously (potentially compromised) certificates are not present in Azure AD.
If an organization maintains backup copies of the token-signing and token-decrypting certificates, the certificate backups
should not be stored on the local AD FS servers and should be secured and password-protected using a separate
enterprise vaulting / backup-storage technology (preferably offline storage).
Figure 7. Connect-AzureAD
PowerShell commands to Get-AzureADuser -all $true | Revoke-AzureADUserAllRefreshToken
connect to Azure AD and
revoke existing refresh tokens.
Hardening
Proactive hardening steps can be leveraged to secure on-premises AD FS infrastructure. While the scope of
generalized on-premises hardening workstreams can be cumbersome and often represent multiple layers of defenses,
the most prudent steps related to AD FS hardening and mitigating the previously noted attacker techniques are
noted below.
– Alternatively, configure a dedicated on-premises account that is only leveraged as an AD FS service account and has
restricted access rights
• Step 2: Review AD FS Logging and Auditing Settings
Note: If an organization needs to change the existing AD FS service account to leverage a gMSA (rather than a
static service account), this process can be complex and may require assistance from Microsoft support. For specific
information related to this process, reference:
• https://gallery.technet.microsoft.com/scriptcenter/Active-Directory-ddb67df0
• https://social.technet.microsoft.com/Forums/windowsserver/en-US/8f558762-f92c-4803-916c-cc36ecc7c988/adfs-
2016-change-service-account-to-gmsa?forum=ADFS#75f9b050-ad0b-461a-92a4-796180d6c6d2
• https://github.com/Microsoft/adfsToolbox/tree/master/serviceAccountModule
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 12
• Errors
• FailureAudits
• SuccessAudits
• Information
• Verbose
• Warnings
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 13
Mandiant’s recommended settings for configuring the Enable AD FS Security and Service Account Auditing
audit level for AD FS services running on Windows Server In addition to audit levels, Mandiant recommends enabling
2012R2 are shown in Figure 9. security auditing in AD FS. Security auditing provides
visibility to authentication events performed through the
For AD FS services running on Windows Server 2016+, AD FS service, including issued claims, security token
there are three configurable audit levels: validation failures, IP addresses for requests and user
agent information. By default, both “Success audits” and
• Basic (default): no more than 5 events will be logged
“Failure audits” are not enabled, which can severely affect
for a single request
monitoring and investigative efforts.
• Verbose: all events will be logged
To enable security auditing for AD FS events, implement
• None: auditing is disabled (not recommended)
the following steps:
Mandiant’s recommended settings for configuring the
1. On each AD FS server - Navigate to Local Security
audit level for AD FS services running on Windows Server
Policy > Security Settings > Local Policies > User Rights
2016+ is shown in Figure 10.
Assignment > Generate security audits (Figure 11)
Note: While Mandiant’s recommendation of including • Local Security Setting tab > verify that the AD FS
Verbose auditing will provide the most information related service account is listed. If not listed, add the account.
to AD FS events, this setting will likely cause event logs
to rotate faster and should be utilized in conjunction with
event log forwarding to a SIEM.
Figure 11.
Local Security Policy -
Generate Security Audits
configuration.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 14
2. To record audits generated by the AD FS service within the Security event log, on each AD FS server - Navigate to
Local Security Policy > Security Settings > Advanced Audit Policy Configuration > System Audit Policies > Object
Access
• Audit Application Generated tab > Select both “Success” and “Failure” (Figure 12)
• This can also be accomplished using an elevated command prompt, and running the command noted in Figure 13.
Figure 12.
Local Security Policy – Audit
Application Generated
configuration.
For additional information related to AD FS logging and auditing—in addition to specific Event IDs (per Operating
System platform) which can be leveraged for troubleshooting and investigative purposes, reference:
https://adfshelp.microsoft.com/AdfsEventViewer/GetAdfsEventList
1. On Domain Controllers, ensure that the “Audit Directory Service Access” subcategory (within the “DS Access”
category) is configured for auditing. This configuration can be enforced using settings defined within a Group Policy
Object (GPO) linked to Domain Controllers (Figure 16).
2. Ensure that auditing for “Read All Properties” is configured for the CN=ADFS,CN=Microsoft,CN=Program
Data,DC=<domain>,DC=<suffix> parent (and child) containers in Active Directory. This can be accomplished using
ADSIEdit (Figure 17).
Figure 16.
GPO configuration example
for enforcing “Directory
Service Access” auditing for
Domain Controllers.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 16
Figure 17.
Configuring auditing for
the ADFS container using
ADSIEdit.
3. Within Security event logs on Domain Controllers, monitor for Event ID 4662. Targeted monitoring related to EID 4662
events for potential DKM access include:
• ObjectName contains the GUIDs of the AD FS DKM Containers for the token-signing and token-decrypting
certificates (can be found using ADSIEdit and navigating to CN=ADFS,CN=Microsoft,CN=Program
Data,DC=<domain>,DC=<suffix>)
• ObjectName contains the path of CN=CryptoPolicy,CN=ADFS,CN=Microsoft,CN=Program
Data,DC=<domain>,DC=<suffix>
Figure 18. Example Event ID 4662 - recorded when accessing the DKM container in AD using PowerShell.
Note: When an AD FS server is rebooted or the AD FS additional correlation on AD FS servers related to the
service is restarted, the service account legitimately detections noted above can be leveraged, including:
running AD FS services will access the containers in
Active Directory for certificate decryption using DKM. To • System Event Log - Event ID 7036
further enhance monitoring and reduce false positives, • System Event Log – Event ID 1074
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 17
Figure 19.
System Event Log - Event ID
7036.
Figure 20.
System Event Log - Event ID
1074.
Step 3: AD FS Servers - Account Access Restrictions and In addition to authentication considerations, inbound
Inbound Connectivity Hardening access to AD FS servers should be restricted to the
On-premises AD FS servers should be considered Tier following small subset of ports / protocols required for
0 assets. Mandiant recommends restricting access to inbound connectivity (Figure 21).
the AD FS servers to an even smaller subset of unique
accounts than the typical “Domain Administrators” group. • TCP/80 (HTTP)
Furthermore, Mandiant recommends that the accounts • TCP/443 (HTTPs)
in this subset are explicitly prevented (via Group Policy)
• TCP/5985 (WinRM)
from authenticating to Tier 1 and Tier 2 assets, to prevent
their credentials from being potentially recoverable on less • TCP/808 (Windows Server 2012R2) or
secure systems. Particular attention should also be paid TCP/1501 (Windows Server 2016+)
to the local administrator account on the AD FS system,
ensuring that its password is strong and unique.
ATTACK TECHNIQUE:
Figure 22.
{
Event recorded
when a new “OrganizationId”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
domain is “CreationTime”: “2020-06-23T23:03:32.0000000Z”,
federated, and a “RecordType”: 8,
federated realm “Operation”: “Set domain authentication.”,
object is created.
“UserType”: 0,
“Workload”: “AzureActiveDirectory”,
“ClientIP”: “1.1.1.1”,
“Version”: 1,
“UserId”: “doug@victim.onmicrosoft.com”,
“ObjectId”: “Not Available”,
“ResultStatus”: “Success”,
“ModifiedProperties”: [
{
“Name”: “IssuerUri”,
“NewValue”: “[\r\n \”http://any.sts/16B45E3B\”\r\n]”,
“OldValue”: “[]”
},
{
“Name”: “Included Updated Properties”,
“NewValue”: “IssuerUri,LiveType”,
“OldValue”: “”
},
{
“Name”: “LiveType”,
“NewValue”: “[\r\n \”Federated\”\r\n]”,
“OldValue”: “[\r\n \”Managed\”\r\n]”
}
],
}
Figure 23 shows a sample event recorded in the Unified the user that performed the action, the IP address the
Audit Log when an existing federated realm object for action was performed from, as well as the domain that
a domain is modified. In most organizations, domain was modified. It does not record what elements of the
federation settings will be updated infrequently. federated realm object were modified. Additional analysis
Organizations should create rules to alert on the log using MSOnline PowerShell (detailed in the hardening and
events that get generated by these activities and audit remediation sections) will be needed to identify whether
them to ensure they are legitimate. The event records the signing-certificate was modified.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 22
Figure 23.
{
Event recorded
“OrganizationId”: “ xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx “,
when an existing
federated realm “CreationTime”: “2020-12-04T18:41:45.0000000Z”,
object is modified. “RecordType”: 8,
“Operation”: “Set federation settings on domain.”,
“UserType”: 0,
“Workload”: “AzureActiveDirectory”,
“ClientIP”: “1.1.1.1”,
“Version”: 1,
“UserId”: “victim@test.onmicrosoft.com”,
“ResultStatus”: “Success”,
“Id”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
“ObjectId”: “Not Available”,
“ModifiedProperties”: [],
“AzureActiveDirectoryEventType”: 1,
“ExtendedProperties”: [
{
“Value”: “{}”,
“Name”: “additionalDetails”
},
{
“Value”: “Domain”,
“Name”: “extendedAuditEventCategory”
}
],
“SupportTicketId”: “”,
“ActorIpAddress”: “1.1.1.1”,
“Target”: [
{
“Type”: 1,
“ID”: “test.com”
}
],
“
}
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 23
Remediation
The Azure AD Investigator auditing script, available from the FireEye GitHub repository, contains a module that
will enumerate all domains in a Microsoft 365 tenant. The script will output all unverified domains, domains that are
configured for federation, as well as domains with a federated realm object that is evidence of the AADBackdoor tool.
Administrators should review this output to ensure that only expected domains are configured as federated and that the
federation login pages are expected as well.
Step 1: Review Configured Domains and Trusts Within Microsoft 365 and Remove Untrusted Domains
1. Enumerate all Registered Domains
Organizations should proactively review the scope of configured domains within a Microsoft 365 tenant, including the
configured authentication methods (Managed or Federated). The PowerShell cmdlets noted in Figure 24 will provide a
listing of configured domains and the associated authentication methods.
Organizations should assess each domain’s verification status and authentication mode. These settings should be
reviewed for legitimacy and functional operation. If a domain is no longer in use, or the domain’s existence cannot be
readily identified, it should be investigated and removed from the tenant (Figure 25).
ATTACK TECHNIQUE:
Manage all aspects of Azure AD and Microsoft services Complete control over the Microsoft 365
Global administrator
that use it environment
Privileged role administrator Manage role assignments Privilege escalation via privileged roles
Hybrid identity administrator Can update federation settings for domains Ability to install an azure AD backdoor
Technique Remediation
Organizations will often grant privileged roles to user Step 1: Review and Configure Cloud-Only Accounts for
identities that are synced from on-premises Active Directory. Privileged Role Holders
Most commonly, this includes a privileged on-premises Organizations should review the scope of accounts
account being used to manage Azure AD and Microsoft 365 assigned privileged permissions and roles in Microsoft 365.
resources. This can present a security risk as it facilitates Additionally, the roles and accounts with privileged access
lateral movement from the on-premises environment to the should be cloud-only accounts (not accounts synced from
cloud environment. Mandiant has observed threat actors on-premises identity stores such as Active Directory).
performing reconnaissance to identify on-premises AD All privileged cloud-only accounts should leverage MFA
accounts that hold privileged roles and target them for through either conditional access polices or security defaults.
credential theft. Once in possession of credentials for an
account that holds a privileged directory role, the threat 1. Review Accounts assigned Privileged Roles
actor uses it to connect to Microsoft 365 and establish a
foothold for directly accessing cloud resources without the Using the PowerShell commands referenced in Figure
continued need for on-premises access. 26, review each account that is assigned to a privileged
role in Azure AD. Any identified on-premises synced
accounts that are configured with a privileged role
in Azure AD should be replaced with a cloud-only
account. Cloud-only accounts are denoted by the
@<tenant>.onmicrosoft.com domain suffix.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 25
ImmutableIDs act as an anchor attribute between synced on-premises identities and their cloud account counterpart.
If a cloud-only account has an ImmutableID, then a threat actor could forge a SAML token for the account, even though
it is considered cloud-only. For this reason, all cloud-only accounts should not be configured with an ImmutableID.
The PowerShell command noted in Figure 27 can be leveraged to review cloud-only accounts with an ImmutableID.
3. For accounts that contain an ImmutableID value, delete and recreate the account
ATTACK TECHNIQUE:
Technique Detection
Mandiant has observed UNC2452 adding additional The Azure AD Audit log and the Unified Audit Log record
certificates or secrets to existing applications and service when credentials are added to both service principals
principals. To accomplish this, the threat actor first needed and App Registrations. In most organizations, credentials
to compromise an account with a privileged directory will be added to service principals and App Registrations
role that was granted the ability to modify Enterprise infrequently. Organizations should create rules to alert on
Applications or Application Registrations. A frequently the log events that get generated by these activities and
targeted role was the Application Administrator, because audit them to ensure they are legitimate. For example,
it allowed complete control over applications in Azure Microsoft has published suggested hunting rules using
AD. Once in possession of those credentials, UNC2452 Sentinel to identify these activities.
modified the application by using one of the following
techniques: Figure 30 shows a sample event from the Unified Audit
Log that is recorded when a credential is added to an App
• Modification of an application via the browser: Registration. The event includes the user that performed
The attacker connected to the Azure Portal with a web the action, the ID of the application that was modified,
browser and added a new secret to an App Registration details on the credential that was added, and more. Of
that had permissions to read all mail. There is no note are the ClientIP and ActorIPAddress fields. When
supported way to add a credential to an Enterprise the credential is added via the Azure Portal, the IP address
Application (service principal) via the browser. that gets recorded is a Microsoft IP address. This hides the
true IP address of the action and can make searching for
• Modification of an application via PowerShell:
activities by IP address prone to missing data.
The attacker connected to the Microsoft 365 tenant
using Azure AD PowerShell. Once connected they
added certificates to App Registrations and
Enterprise Applications that had the mail.read and
files.read permission.
Mandiant has observed UNC2452 first performing
reconnaissance of an organization’s Azure AD to
identify existing applications that already have sensitive
permissions set, such as mail.read and files.read. Once a
viable application was identified, UNC2452 added a rogue
credential to it using one of the methods detailed above.
At a minimum this allowed UNC2452 to access any user’s
data in the victim tenant without MFA.
Figure 30.
{
Sample event
“OrganizationId”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
recorded when
a credential is “CreationTime”: “2021-01-09T18:40:16.0000000Z”,
added to an App “RecordType”: 8,
Registration. “Operation”: “Update application – Certificates and secrets management “,
“Workload”: “AzureActiveDirectory”,
“UserType”: 0,
“ClientIP”: “20.190.130.49”,
“Version”: 1,
“UserId”: “doug@testing.onmicrosoft.com”,
“ObjectId”: “Application_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
“Id”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
“ResultStatus”: “Success”,
“ModifiedProperties”: [
{
“Name”: “KeyDescription”,
“NewValue”: “[\r\n \”[KeyIdentifier= xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx
xxx,KeyType=Password,KeyUsage=Verify,DisplayName=test]\”\r\n]”,
“OldValue”: “[]”
},
{
“Name”: “Included Updated Properties”,
“NewValue”: “KeyDescription”,
“OldValue”: “”
}
],
“AzureActiveDirectoryEventType”: 1,
“ExtendedProperties”: [
{
“Value”: “{\”User-Agent\”:\”Mozilla/5.0 (Macintosh; Intel Mac OS
X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88
Safari/537.36\”}”,
“Name”: “additionalDetails”
},
}
}
A similar event is recorded when credentials are added to a service principal. Figure 31 details a sample log event from the
Unified Audit Log.
When a credential that has been added to an application is used to login to Microsoft 365, it is recorded differently than
an interactive user sign-in. In the Azure Portal these logins can be viewed by navigating to Sign-Ins under the Azure
Active Directory blade and then clicking the service principal Sign-ins tab. The sign-in log records the IP address that
performed the sign-in, but not the credential that was used. Note that currently these sign-ins are not recorded in the
Unified Audit Log.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 29
Figure 31.
Sample event {
recorded when “OrganizationId”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
a credential is “CreationTime”: “2021-01-07T21:32:13.0000000Z”,
added to a service “RecordType”: 8,
principal.
“Operation”: “Add service principal credentials.”,
“UserType”: 0,
“Workload”: “AzureActiveDirectory”,
“ClientIP”: “1.1.1.1”,
“Version”: 1,
“UserId”: “doug@test.onmicrosoft.com”,
“ObjectId”: “xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx”,
“Id”: “ xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx “,
“ResultStatus”: “Success”,
“ModifiedProperties”: [
{
“Name”: “KeyDescription”,
“NewValue”: “[\r\n \”[KeyIdentifier=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
xx,KeyType=Symmetric,KeyUsage=Verify,DisplayName=]\”\r\n]”,
“OldValue”: “[]”
},
}
Remediation
The Azure AD Investigator auditing script, available from the FireEye GitHub repository, contains a module that will
enumerate all applications and service principals in a Microsoft 365 tenant. The script will output all applications and
service principals that have both certain high-risk application permissions assigned to them and an assigned credential.
These are applications that a threat actor may have used to connect to Microsoft 365 and access data. Administrators
will need to work with their security and IT teams to validate that the credentials added to the applications and service
principals are legitimate.
Step 1: Review and Remediate Keys Associated with Service Principals and Applications
Organizations can leverage Azure PowerShell to review and remediate service principals or applications that may be
configured with credentials for remote authentication using either a static secret or certificate.
Figure 35.
Connect-AzAccount
PowerShell commands to ** Remove all credentials associated with a service principal **
remove credentials associated Get-AzADApplication -ObjectId <> | Remove- AzADAppCredential
with an application – or
remove a specific application.
** Remove a specific credential (KeyID) associated with a service
principal **
Remove-AzADAppCredential -ObjectId <> -KeyId <>
** Remove a specific application **
Remove-AzADApplication -ObjectId <>
To identify on-premises Active Directory users that do not utilize Azure AD, Azure AD Sign-in logs can be reviewed
(Figure 37 - Figure 39).
Figure 37.
PowerShell Connect-AzureAD
command to Get-AzureADAuditSignInLogs -Filter “UserPrincipalName eq <UPN>” | Select-
review Azure AD Object UserPrincipalName, CreatedDateTime, AppDisplayName, AppId, IpAddress |
sign-in logs to Export-csv signins.csv -Append
identify potentially
dormant accounts
by UPN.
Figure 38.
#Export members of AD OU to CSV
PowerShell
Get-ADUser -Filter * -SearchBase “<OU PATH>” | Select-object
commands to
review Azure AD UserPrincipalName | Export-csv OUMembers.csv
sign-in logs to
identify potentially #Import CSV into variable
dormant accounts $Users = Import-csv OUMembers.csv
by AD OU.
2. Configure filtering with Azure AD Connect c. Cloud apps or admins > Include
For more information regarding Azure AD Connect i. Select All cloud apps
filtering, reference: d. Conditions > Locations
https://docs.microsoft.com/en-us/azure/active-directory/
hybrid/how-to-connect-sync-configure-filtering i. Under Configure, select Yes
Note: Before applying verbose Mailbox Auditing settings, an organization should verify that their centralized log or SIEM
platform can handle the increased logging volume.
The PowerShell command noted in Figure 43 will add the MailBoxLogin auditing setting to the AuditOwner logon type
for each mailbox:
Figure 43.
Connect-ExchangeOnline
PowerShell command to add Get-Mailbox -Resultsize Unlimited -Filter {(RecipientTypeDetails
the MailBoxLogin setting for
-eq “UserMailBox”) -and (SKUAssigned -eq “True”)} | Set-Mailbox
the AuditOwner logon type.
-AuditOwner @{Add=MailBoxLogin}
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 34
To enable the highest level of logging available with E3 licensing, the PowerShell command noted in Figure 44 can be run
on each mailbox to replace auditing settings for each logon type,
Figure 44.
Connect-ExchangeOnline
PowerShell Set-Mailbox -Identity <UPN> `
command to
-AuditAdmin MoveToDeletedItems,SoftDelete,HardDelete,SendAs,SendOnBehalf,
replace auditing
settings with UpdateFolderPermissions,UpdateInboxRules,UpdateCalendarDelegation `
optimized E3 -AuditDelegate MoveToDeletedItems,SoftDelete,HardDelete,SendAs,
settings for each SendOnBehalf,UpdateFolderPermissions,UpdateInboxRules `
logon type. -AuditOwner MoveToDeletedItems,SoftDelete,HardDelete,MailboxLogin,
UpdateFolderPermissions,UpdateInboxRules,UpdateCalendarDelegation
Mandiant recommends that MailItemsAccessed be enabled for all logon types for highly sensitive mailboxes.
The PowerShell command noted in Figure 45 will add the MailItemsAccessed audit setting for the AuditOwner,
AuditDelegate, and AuditAdmin logon types for a specific mailbox.
To enable the highest level of logging available for E5 licensing, the PowerShell command noted in Figure 46 can be
ran on each mailbox to replace auditing settings for each logon type.
Note: If Microsoft releases new auditing settings, the new settings will not be automatically applied to mailboxes where
custom audit settings have previously been configured. New auditing settings will need to be manually applied.
Once an application has been granted permissions, an attacker can utilize the application to access user accounts with
little to no other security controls. This is commonly leveraged by attackers since they can bypass MFA requirements
and maintain persistence to targeted employee’s data.
For this reason, it is important to have visibility over which applications have been granted OAuth access to user
accounts within the tenant.
Create-AppConsentGrantReport.ps1 is an open-source PowerShell script that will enumerate all permission grants
for all applications in a Microsoft 365 tenant. This output can then be reviewed to identify overly permissive and
suspicious applications.
Many applications have legitimate use cases that warrant permissive access to applications (email applications and
cloud-based collaboration platforms) in a Microsoft 365 tenant. The output from this script report should be thoroughly
reviewed to determine which applications can be removed from the tenant or have their privileges reduced.
For applications that are granted the ‘Application’ Consent Type for mail permissions (Mail.Read,Mail.Send,Mail.
ReadWrite,Mail.ReadBasic,Mail.ReadBasic.All), these applications are granted the rights to all mailboxes in the tenant,
without needing specific account credentials to access a mailbox. Applications assigned these permissions can be
reviewed by filtering the PermissionType column by Application on the ConsentGrantData tab generated within the
Create-AppConsentGrantReport report (Figure 48).
While some legitimate applications require this privilege grant, they commonly do not need access to every mailbox.
To limit which mailboxes the application can access, it is recommended to apply an Application Access Policy to the
application.
• Login to https://portal.azure.com
• Users can consent to apps accessing company data for the groups they own to No
• Set Users can request admin consent to apps they are unable to consent to No
• Under User Consent for Applications select Do not allow user consent
• Under Group owner consent for apps accessing data select Do not allow group owner consent
For smaller organizations that need a quick baseline of enabled security settings (including MFA enforcement and blocking
legacy authentication protocols) to create a hardened security posture for Microsoft 365, the grouping of settings known
as “Security Defaults” should be considered. Security Defaults are free (available at any tier) and replace the older and
deprecated baseline policies.
• If Conditional Access policies are currently being leveraged (Azure AD Premium P1 license), Security Defaults should not be
used.
• If an organization has complex security requirements, Conditional Access policies should be used over Security
Defaults.
• If an organization has Azure Active Directory Premium licenses, Security Defaults should not be used.
• If an organization uses Security Defaults and then decides to migrate to using Conditional Access policies, Security
Defaults will first need to be disabled.
Note: This process should also include reviewing any accounts that can bypass MFA requirements, to include evaluating
the operational impact and associated risk of leveraging such a configuration.
The PowerShell script syntax noted in Figure 49 can be used to generate a report of MFA devices registered with Azure AD.
WHITE PAPER | REMEDIATION AND HARDENING STRATEGIES FOR MICROSOFT 365 TO DEFEND AGAINST UNC2452 37
Figure 49.
Connect-MsolService
PowerShell script
to identify all MFA
$Result=@()
devices registered $users = Get-MsolUser -All
with Azure AD. $users | ForEach-Object {
$user = $_
$mfaStatus = $_.StrongAuthenticationRequirements.State
$phoneApp = $_.StrongAuthenticationPhoneAppDetails
$methodTypes = $_.StrongAuthenticationMethods
The scope of permissions assigned to partners should be reviewed and verified – as partners can exist as Global Admin
or Helpdesk Admin roles. Delegated admin roles (Admin Agents and Helpdesk Agents) are also available when partner
relationships are present. Based on the roles assigned, members of either groups can access the customer’s Azure AD
tenant and Microsoft 365 services using their partner credentials and perform administrative actions on behalf of the
customer.
• The Admin Agent group is assigned to the Global Administrator role in the customer’s Azure AD tenant.
• The Helpdesk Agent group is assigned to the Helpdesk Administrator role in the customer’s Azure AD tenant.
1. Review Microsoft 365 Partner Relationships that have Delegated Admin Privileges
Any cloud service provider delegated administrative privileges should be reviewed and potentially removed.
Proactively, an organization would want assurance from the cloud service provider that the provider’s network and
Microsoft 365 tenant are secured and hardened appropriately.
Conclusion
While UNC2452 has demonstrated a level of sophistication and evasiveness,
the observed techniques are both detectable and defensible. This white paper
outlines steps that represent actionable measures that can be leveraged to not
only remediate observed techniques, but also to empower organizations to
detect and harden against similar tactics.