diff --git a/powershell/assets/MaesterSettings.psd1 b/powershell/assets/MaesterSettings.psd1 index c5aecd9439..21edb4c77e 100644 --- a/powershell/assets/MaesterSettings.psd1 +++ b/powershell/assets/MaesterSettings.psd1 @@ -29,6 +29,7 @@ SchemaVersion = '1.0' Settings = @{ EmergencyAccessAccounts = @{ Type = 'object[]'; Items = @{ Properties = @{ Id = $null; UserPrincipalName = $null; Type = @('User', 'Group') }; RequireAny = @('Id', 'UserPrincipalName') }; Default = @(); Sensitive = $false; Description = 'Emergency access (break glass) accounts and groups. Checks of Conditional Access, privileged roles and sign-in activity treat them as the exception they are.' } + HardDeletionProtectedObjects = @{ Type = 'object[]'; Items = @{ Properties = @{ Id = $null; Type = @('User', 'Group', 'Application', 'ServicePrincipal') }; RequireAny = @('Id') }; Default = @(); Sensitive = $false; Description = 'Critical users, groups, applications and service principals (Type and Id) that must have Hard Deletion Protection enabled.' } ParkedDomains = @{ Type = 'string[]'; Kind = 'Entra.Domain'; Default = @(); Sensitive = $false; Description = 'Accepted domains that never send email. The email authentication checks expect them to deny all mail.' } DefenderEndpointPolicyFiltering = @{ Type = 'string'; AllowedValues = @('All', 'IncludeUnassigned', 'OnlyAssigned'); Default = 'OnlyAssigned'; Sensitive = $false; Description = 'Which Defender for Endpoint policies the Defender checks read: All, IncludeUnassigned or OnlyAssigned.' } DefenderEndpointComplianceLogic = @{ Type = 'string'; AllowedValues = @('EffectivePolicy', 'AllPolicies', 'AnyPolicy'); Default = 'EffectivePolicy'; Sensitive = $false; Description = 'How the Defender for Endpoint checks combine policies: EffectivePolicy, AllPolicies or AnyPolicy.' } diff --git a/powershell/assets/MaesterTaxonomy.psd1 b/powershell/assets/MaesterTaxonomy.psd1 index 1c0373c93f..3e7cdcf392 100644 --- a/powershell/assets/MaesterTaxonomy.psd1 +++ b/powershell/assets/MaesterTaxonomy.psd1 @@ -42,6 +42,7 @@ @{ Key = 'agent-identities'; Name = 'Agent identities' } @{ Key = 'monitoring'; Name = 'Logs and monitoring' } @{ Key = 'recommendations'; Name = 'Entra recommendations' } + @{ Key = 'backup-and-recovery'; Name = 'Backup and recovery' } ) } @{ diff --git a/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 new file mode 100644 index 0000000000..79dc47d2ac --- /dev/null +++ b/powershell/internal/checks/maester/entra/Format-MtEntraHardDeletionTable.ps1 @@ -0,0 +1,56 @@ +function Format-MtEntraHardDeletionTable { + <# + .SYNOPSIS + Formats Hard Deletion Protection objects as a Markdown table, capped at a number of rows. + + .DESCRIPTION + Builds a table with the columns Type, Object ID, Display name and one more column taken from + the StateProperty. The display name comes from the tenant, so it goes through + Get-MtSafeMarkdown: a name that looks like a link or an image is shown as text, and a pipe or + a line break does not break the row. + + When there are more rows than Limit, the table shows the first Limit rows and a line gives + the total. + + .PARAMETER InputObject + The objects to list. Each has Type, Id and DisplayName. + + .PARAMETER StateProperty + The property shown in the last column, for example Status or State. + + .PARAMETER StateHeading + The heading of the last column. + + .PARAMETER Limit + The most rows to show. The default is 25. + + .EXAMPLE + Format-MtEntraHardDeletionTable -InputObject $Rows -StateProperty Status -StateHeading Status + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [object[]] $InputObject, + + [Parameter(Mandatory)] + [string] $StateProperty, + + [Parameter(Mandatory)] + [string] $StateHeading, + + [Parameter()] + [ValidateRange(1, 1000)] + [int] $Limit = 25 + ) + + $Table = "| Type | Object ID | Display name | $StateHeading |`n| --- | --- | --- | --- |" + foreach ($Row in @($InputObject | Select-Object -First $Limit)) { + $DisplayName = Get-MtSafeMarkdown -Text ([string]$Row.DisplayName) + $Table += "`n| $($Row.Type) | $($Row.Id) | $DisplayName | $($Row.$StateProperty) |" + } + if (@($InputObject).Count -gt $Limit) { + $Table += "`n`nShowing the first $Limit of $(@($InputObject).Count) objects." + } + $Table +} diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 new file mode 100644 index 0000000000..cfa37cec6d --- /dev/null +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionObjectStatus.ps1 @@ -0,0 +1,105 @@ +function Get-MtEntraHardDeletionObjectStatus { + <# + .SYNOPSIS + Returns the Hard Deletion Protection status of one object listed in the Maester config. + + .DESCRIPTION + Reads the object from Microsoft Graph beta. Status is 'Protected', 'Not protected', + 'Soft deleted' or 'Not found'. + + When the active lookup returns HTTP 404, the function reads the object through the + documented single-item route, directory/deletedItems/{id}, and checks that its @odata.type is + the configured type or one of its Agent ID subtypes: agentUser for User, + agentIdentityBlueprint for Application, and agentIdentity or + agentIdentityBlueprintPrincipal for ServicePrincipal. + + It reports 'Soft deleted' when it finds the object there, whether or not the object has + protection. An object of another type, a response without an @odata.type, or no object + gives 'Not found'. Any Graph error other than a 404 is thrown. + + The Id must be the object ID, a GUID. The function uses its canonical lower-case form in both + requests and in the result, so the result matches the objects that + Get-MtEntraHardDeletionProtectedObject returns. + + .PARAMETER Configured + A HardDeletionProtectedObjects entry with Type and Id. + + .EXAMPLE + Get-MtEntraHardDeletionObjectStatus -Configured $Entry + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [object] $Configured + ) + + # GraphTypes are the @odata.type values a deleted object of this type can have. Agent ID objects + # are covered through their underlying user, application and service principal types. + $EndpointByType = @{ + user = @{ + Name = 'User'; Path = 'users'; GraphTypes = @('user', 'agentUser') + } + group = @{ Name = 'Group'; Path = 'groups'; GraphTypes = @('group') } + application = @{ + Name = 'Application'; Path = 'applications' + GraphTypes = @('application', 'agentIdentityBlueprint') + } + serviceprincipal = @{ + Name = 'ServicePrincipal'; Path = 'servicePrincipals' + GraphTypes = @( + 'servicePrincipal', 'agentIdentity', 'agentIdentityBlueprintPrincipal' + ) + } + } + + $Type = ([string]$Configured.Type).ToLowerInvariant() + $ParsedId = [guid]::Empty + $IdIsGuid = [guid]::TryParse([string]$Configured.Id, [ref]$ParsedId) + if (!$EndpointByType.ContainsKey($Type) -or !$IdIsGuid) { + throw ( + "Invalid HardDeletionProtectedObjects entry (Type '$($Configured.Type)', " + + "Id '$($Configured.Id)'). Type must be User, Group, Application or " + + 'ServicePrincipal and Id must be the object ID (a GUID).' + ) + } + $Endpoint = $EndpointByType[$Type] + $AcceptedTypes = @($Endpoint.GraphTypes | ForEach-Object { "#microsoft.graph.$_" }) + $Id = $ParsedId.ToString() + + $Object = $null + $Status = 'Not found' + try { + $Object = Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri "$($Endpoint.Path)/$Id" ` + -Select @('id', 'displayName', 'isHardDeleteProtectionEnabled') -ErrorAction Stop + $Status = if ($Object.isHardDeleteProtectionEnabled -eq $true) { + 'Protected' + } else { + 'Not protected' + } + } catch { + if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } + } + + if (!$Object) { + try { + $Deleted = Invoke-MtGraphRequest -ApiVersion 'beta' ` + -RelativeUri "directory/deletedItems/$Id" ` + -Select @('id', 'displayName') -ErrorAction Stop + $DeletedType = [string]$Deleted.'@odata.type' + if ($DeletedType -in $AcceptedTypes) { + $Object = $Deleted + $Status = 'Soft deleted' + } + } catch { + if (!(Test-MtGraphNotFoundError -ErrorRecord $_)) { throw } + } + } + + [pscustomobject]@{ + Type = $Endpoint.Name + Id = $Id + DisplayName = if ($Object) { [string]$Object.displayName } else { '' } + Status = $Status + } +} diff --git a/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 new file mode 100644 index 0000000000..fa8589f326 --- /dev/null +++ b/powershell/internal/checks/maester/entra/Get-MtEntraHardDeletionProtectedObject.ps1 @@ -0,0 +1,65 @@ +function Get-MtEntraHardDeletionProtectedObject { + <# + .SYNOPSIS + Returns the users, groups, applications and service principals that have Hard Deletion + Protection. + + .DESCRIPTION + Queries Microsoft Graph beta for objects whose isHardDeleteProtectionEnabled property is + true, both among active objects and among soft-deleted ones. Each result has Type, Id, + DisplayName and State ('Active' or 'Soft deleted'). + + The reads happen one after the other, so the scan is not a snapshot. An object that is soft + deleted or restored while it runs can show up in both reads, or in neither. The function + returns an object seen in both reads once, with the State 'Active or soft deleted', and does + not claim that either read is newer. An object seen in neither read is missed. + + .EXAMPLE + Get-MtEntraHardDeletionProtectedObject + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $DeletedRoot = 'directory/deletedItems/microsoft.graph' + $Sources = @( + @{ Type = 'User'; Path = 'users'; Deleted = "$DeletedRoot.user" } + @{ Type = 'Group'; Path = 'groups'; Deleted = "$DeletedRoot.group" } + @{ Type = 'Application'; Path = 'applications'; Deleted = "$DeletedRoot.application" } + @{ + Type = 'ServicePrincipal' + Path = 'servicePrincipals' + Deleted = "$DeletedRoot.servicePrincipal" + } + ) + + $Observed = [System.Collections.Generic.List[object]]::new() + foreach ($Source in $Sources) { + foreach ($State in 'Active', 'Soft deleted') { + $Path = if ($State -eq 'Active') { $Source.Path } else { $Source.Deleted } + $Objects = @( + Invoke-MtGraphRequest -ApiVersion 'beta' -RelativeUri $Path ` + -Filter 'isHardDeleteProtectionEnabled eq true' ` + -Select @('id', 'displayName') -ErrorAction Stop + ) + foreach ($Object in $Objects) { + $Observed.Add([pscustomobject]@{ + Type = $Source.Type + Id = [string]$Object.id + DisplayName = [string]$Object.displayName + State = $State + }) + } + } + } + + foreach ($Group in @($Observed | Group-Object -Property Type, Id)) { + $States = @($Group.Group.State | Select-Object -Unique) + [pscustomobject]@{ + Type = $Group.Group[0].Type + Id = $Group.Group[0].Id + DisplayName = $Group.Group[0].DisplayName + State = if ($States.Count -eq 1) { $States[0] } else { 'Active or soft deleted' } + } + } +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..51a6f7e37a 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 610, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2500,6 +2500,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1276", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2582,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3163,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1276", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4008,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4545,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1276", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 new file mode 100644 index 0000000000..76b1fb9213 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraHardDeletionProtection.Tests.ps1 @@ -0,0 +1,447 @@ +Describe 'Test-MtEntraHardDeletionProtection' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # Check functions that became native tests are not exported. + Use-MtModuleFunction -Name Test-MtEntraHardDeletionProtection + + $script:UserId = '11111111-1111-1111-1111-111111111111' + $script:GroupId = '22222222-2222-2222-2222-222222222222' + $script:UserRow = "User \| $($script:UserId) \|" + $script:GroupRow = "Group \| $($script:GroupId) \|" + + function Get-Entry { + param($Type, $Id) + [pscustomobject]@{ Type = $Type; Id = $Id } + } + + function Get-GraphObject { + param($Id, $Name, $Protected = $null) + [pscustomobject]@{ + id = $Id; displayName = $Name; isHardDeleteProtectionEnabled = $Protected + } + } + + function Get-InventoryObject { + param($Id, $Name) + [pscustomobject]@{ id = $Id; displayName = $Name } + } + + function Get-DeletedObject { + param($Id, $Name, $ODataType) + [pscustomobject]@{ id = $Id; displayName = $Name; '@odata.type' = $ODataType } + } + + function Invoke-Check { + Test-MtEntraHardDeletionProtection -HardDeletionProtectedObjects $State.Listed + } + } + + BeforeEach { + $State = @{ + Detail = $null; Investigate = $false; Listed = @(); Protected = @{} + ObjectById = @{}; DeletedById = @{}; Sequence = @{}; Seen = @{}; Wrap = $false + } + # The exception Invoke-MtGraphRequest lets through for a request Graph answers with 404. + $NotFoundError = [Microsoft.PowerShell.Commands.HttpResponseException]::new( + 'Response status code does not indicate success: NotFound (Not Found).', + [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::NotFound) + ) + + Mock -ModuleName Maester Add-MtTestResultDetail -MockWith { + param($Result, [switch] $Investigate) + $State.Detail = $Result + $State.Investigate = [bool]$Investigate + }.GetNewClosure() + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + param($RelativeUri) + # The real parameter is an array, and a hashtable lookup with an array returns an array. + $uri = [string]$RelativeUri + $notFound = $NotFoundError + if ($State.Wrap) { + $notFound = [System.InvalidOperationException]::new( + 'Request failed.', $NotFoundError + ) + } + $id = $uri.Split('/')[-1] + if ($uri -match '^directory/deletedItems/[0-9a-fA-F-]{36}$') { + if ($null -eq $State.DeletedById[$id]) { throw $notFound } + return $State.DeletedById[$id] + } + if ($uri -match '^(users|groups|applications|servicePrincipals)/[^/]+$') { + if ($State.Sequence.ContainsKey($uri)) { + $step = [int]$State.Seen[$uri] + $State.Seen[$uri] = $step + 1 + $answers = $State.Sequence[$uri] + return $answers[[Math]::Min($step, $answers.Count - 1)] + } + if ($null -eq $State.ObjectById[$uri]) { throw $notFound } + return $State.ObjectById[$uri] + } + if ($State.Protected.Keys -contains $uri) { return $State.Protected[$uri] } + return @() + }.GetNewClosure() + } + + AfterEach { + if ($null -ne $State.Detail) { + $State.Detail | Should -Not -Match '`[^`]+`' + } + } + + Context 'No objects are listed' { + It 'is Investigate and says nothing is protected yet' { + Invoke-Check | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match 'verified manually' + $State.Detail | Should -Match 'The scan did not find any objects with Hard Deletion' + } + + It 'is Investigate and lists the protected objects it finds' { + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( + Get-InventoryObject $script:GroupId 'Deleted group' + ) + + Invoke-Check | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match '2 object\(s\) have Hard Deletion Protection' + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Active" + $State.Detail | Should -Match "$($script:GroupRow) Deleted group \| Soft deleted" + } + + It 'counts an object once when it shows up as both active and soft deleted' { + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + $State.Protected['directory/deletedItems/microsoft.graph.user'] = @( + Get-InventoryObject $script:UserId 'Admin One' + ) + + Invoke-Check | Should -BeNullOrEmpty + $State.Detail | Should -Match '1 object\(s\) have Hard Deletion Protection' + $State.Detail | Should -Match 'Admin One \| Active or soft deleted' + } + } + + Context 'Objects are listed' { + It 'passes when every listed object is protected and nothing else is' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + + Invoke-Check | Should -BeTrue + $State.Investigate | Should -BeFalse + $State.Detail | Should -Match 'Well done' + } + + It 'is Investigate when listed objects pass but other protected objects are not listed' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @( + Get-InventoryObject $script:UserId 'Admin One' + Get-InventoryObject $script:GroupId 'Other admin' + ) + + Invoke-Check | Should -BeNullOrEmpty + $State.Investigate | Should -BeTrue + $State.Detail | Should -Match 'Other admin' + $State.Detail | Should -Not -Match 'Admin One \|' + } + + It 'fails and lists an unprotected object, even when others are not listed' { + $State.Listed = @(Get-Entry user $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Plain | User' + $State.Protected['groups'] = @(Get-InventoryObject $script:GroupId 'Some group') + + Invoke-Check | Should -BeFalse + $State.Investigate | Should -BeFalse + $State.Detail | Should -Match '1 of 1 listed object' + $State.Detail | Should -Match "$($script:UserRow) Plain \\\| User \| Not protected" + $State.Detail | Should -Match 'Some group' + } + + It 'fails an object that cannot be found' { + $State.Listed = @(Get-Entry Group $script:GroupId) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match 'Not found' + } + + It 'fails a listed object that is protected but soft deleted' { + $State.Listed = @(Get-Entry Group $script:GroupId) + $State.DeletedById[$script:GroupId] = + Get-DeletedObject $script:GroupId 'Deleted group' ` + -ODataType '#microsoft.graph.group' + $State.Protected['directory/deletedItems/microsoft.graph.group'] = @( + Get-InventoryObject $script:GroupId 'Deleted group' + ) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:GroupRow) Deleted group \| Soft deleted" + } + + It 'reports a listed object soft deleted without protection as soft deleted' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.DeletedById[$script:UserId] = + Get-DeletedObject $script:UserId 'Removed user' ` + -ODataType '#microsoft.graph.user' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Removed user \| Soft deleted" + $State.Detail | Should -Not -Match 'Not found' + } + + It 'reads a deleted object through the documented deletedItems route, once' { + $State.Listed = @(Get-Entry Group $script:GroupId) + + Invoke-Check | Should -BeFalse + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly ` + -ParameterFilter { + $RelativeUri -eq 'directory/deletedItems/22222222-2222-2222-2222-222222222222' + } + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly ` + -ParameterFilter { + $RelativeUri -like 'directory/deletedItems/microsoft.graph.*/22222222-*' + } + } + + It 'reports a deleted object of another type as not found' { + $State.Listed = @(Get-Entry Group $script:UserId) + $State.DeletedById[$script:UserId] = + Get-DeletedObject $script:UserId 'Removed user' ` + -ODataType '#microsoft.graph.user' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "Group \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Not -Match 'Soft deleted' + } + + It 'reports a deleted object without an @odata.type as not found' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.DeletedById[$script:UserId] = Get-InventoryObject $script:UserId 'Removed user' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) \| Not found" + $State.Detail | Should -Not -Match 'Soft deleted' + } + + It 'reports a soft-deleted listed as as soft deleted' -ForEach @( + @{ Type = 'User'; Subtype = 'agentUser' } + @{ Type = 'Application'; Subtype = 'agentIdentityBlueprint' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentity' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentityBlueprintPrincipal' } + ) { + $State.Listed = @(Get-Entry $Type $script:UserId) + $State.DeletedById[$script:UserId] = Get-DeletedObject $script:UserId 'Agent object' ` + -ODataType "#microsoft.graph.$Subtype" + + Invoke-Check | Should -BeFalse + $Row = "$Type \| $($script:UserId) \| Agent object" + $State.Detail | Should -Match "$Row \| Soft deleted" + } + + It 'reports a soft-deleted listed as as not found' -ForEach @( + @{ Type = 'Group'; Subtype = 'agentUser' } + @{ Type = 'User'; Subtype = 'agentIdentity' } + @{ Type = 'Application'; Subtype = 'agentUser' } + @{ Type = 'ServicePrincipal'; Subtype = 'agentIdentityBlueprint' } + ) { + $State.Listed = @(Get-Entry $Type $script:UserId) + $State.DeletedById[$script:UserId] = Get-DeletedObject $script:UserId 'Agent object' ` + -ODataType "#microsoft.graph.$Subtype" + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$Type \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Not -Match 'Soft deleted' + } + + It 'shows a display name that looks like a link or an image as plain text' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry Group $script:GroupId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId '[Sign in](https://phish.example)' + $State.ObjectById["groups/$($script:GroupId)"] = + Get-GraphObject $script:GroupId '![x](https://attacker.example/p.png)' + + Invoke-Check | Should -BeFalse + $State.Detail.Contains('\[Sign in\]\(https\://phish.example\)') | Should -BeTrue + $State.Detail.Contains('\!\[x\]\(https\://attacker.example/p.png\)') | Should -BeTrue + $State.Detail.Contains('[Sign in](') | Should -BeFalse + $State.Detail.Contains('![x](') | Should -BeFalse + } + + It 'reports a 404 that sits on the inner exception as not found' { + $State.Listed = @(Get-Entry Group $script:GroupId) + $State.Wrap = $true + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:GroupRow) \| Not found" + } + + It 'rejects an Id that is not a GUID without calling Graph' { + InModuleScope Maester { + $Entry = [pscustomobject]@{ Type = 'User'; Id = 'admin@contoso.com' } + { Get-MtEntraHardDeletionObjectStatus -Configured $Entry } | + Should -Throw '*Id must be the object ID (a GUID)*' + } + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 0 -Exactly + } + + It 'fails the check with an error that names the entry when an Id is not a GUID' { + $State.Listed = @(Get-Entry User 'admin@contoso.com') + + { Invoke-Check } | Should -Throw "*Id 'admin@contoso.com'*" + } + + It 'keeps a display name with line breaks in one table cell' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId "Ops`r`nTeam`nLead" + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Ops Team Lead \| Not protected" + } + + It 'counts an entry that is listed more than once as one object' { + $HexId = 'aabbccdd-1111-2222-3333-eeeeffff0000' + $State.Listed = @( + Get-Entry User $HexId + Get-Entry user $HexId.ToUpperInvariant() + Get-Entry User "{$HexId}" + Get-Entry Group $script:GroupId + ) + $State.ObjectById["users/$HexId"] = Get-GraphObject $HexId 'Plain user' + + $HexId | Should -Not -BeExactly $HexId.ToUpperInvariant() + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match '2 of 2 listed object\(s\)' + [regex]::Matches($State.Detail, "\| User \| $HexId \|").Count | Should -Be 1 + $State.Detail | Should -Match "$($script:GroupRow) \| Not found" + } + + It 'keeps one passing row when an entry is listed twice and both lookups pass' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + + Invoke-Check | Should -BeTrue + $State.Detail | Should -Match 'All 1 listed object\(s\)' + } + + It 'lets a failing lookup win when an entry is listed twice and the lookups differ' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.Sequence["users/$($script:UserId)"] = @( + Get-GraphObject $script:UserId 'Admin One' -Protected $true + Get-GraphObject $script:UserId 'Admin One' -Protected $null + ) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match '1 of 1 listed object' + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Not protected" + } + + It 'keeps the failure when the failing lookup comes first' { + $State.Listed = @(Get-Entry User $script:UserId; Get-Entry User "{$script:UserId}") + $State.Sequence["users/$($script:UserId)"] = @( + Get-GraphObject $script:UserId 'Admin One' -Protected $null + Get-GraphObject $script:UserId 'Admin One' -Protected $true + ) + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Not protected" + } + + It 'uses the canonical lower-case form of the Id in the request and in the result' { + $State.Listed = @(Get-Entry User '{AAAAAAAA-1111-2222-3333-BBBBBBBBBBBB}') + $State.ObjectById['users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb'] = + Get-GraphObject 'aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' 'Mixed case' + + Invoke-Check | Should -BeFalse + $State.Detail | Should -MatchExactly ( + 'User \| aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb \| Mixed case \| Not protected' + ) + Should -Invoke -ModuleName Maester Invoke-MtGraphRequest -Times 1 -Exactly ` + -ParameterFilter { $RelativeUri -ceq 'users/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb' } + } + + It 'keeps a protected object in the unlisted table when listed under another Type' { + $State.Listed = @(Get-Entry Group $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + + Invoke-Check | Should -BeFalse + $State.Detail | Should -Match "Group \| $($script:UserId) \| \| Not found" + $State.Detail | Should -Match "$($script:UserRow) Admin One \| Active" + } + + It 'does not list a correctly listed object as unlisted' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['users'] = @(Get-InventoryObject $script:UserId 'Admin One') + + Invoke-Check | Should -BeTrue + $State.Detail | Should -Not -Match 'other object' + } + + It 'shows the first 25 unlisted objects and the total' { + $State.Listed = @(Get-Entry User $script:UserId) + $State.ObjectById["users/$($script:UserId)"] = + Get-GraphObject $script:UserId 'Admin One' -Protected $true + $State.Protected['groups'] = @( + 1..30 | ForEach-Object { + Get-InventoryObject ('33333333-3333-3333-3333-{0:D12}' -f $_) "Group $_" + } + ) + + Invoke-Check | Should -BeNullOrEmpty + $State.Detail | Should -Match '30 other object\(s\)' + $State.Detail | Should -Match 'Showing the first 25 of 30 objects' + $State.Detail | Should -Match 'Group 25 \|' + $State.Detail | Should -Not -Match 'Group 26 \|' + } + } + + Context 'Errors' { + It 'throws for an invalid object type' { + $State.Listed = @(Get-Entry Device $script:UserId) + + { Invoke-Check } | + Should -Throw '*Type must be User, Group, Application or ServicePrincipal*' + } + + It 'throws for a Graph error that is not a 404' { + $State.Listed = @(Get-Entry User $script:UserId) + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + param($RelativeUri) + if ($RelativeUri -like 'users/*') { + throw [Microsoft.PowerShell.Commands.HttpResponseException]::new( + 'Response status code does not indicate success: Forbidden (Forbidden).', + [System.Net.Http.HttpResponseMessage]::new( + [System.Net.HttpStatusCode]::Forbidden + ) + ) + } + return @() + } + + { Invoke-Check } | Should -Throw '*Forbidden*' + } + + It 'throws, instead of reporting Not found, when the error has no HTTP response' { + $State.Listed = @(Get-Entry User $script:UserId) + Mock -ModuleName Maester Invoke-MtGraphRequest -MockWith { + param($RelativeUri) + if ($RelativeUri -like 'users/*') { + throw [System.InvalidOperationException]::new('Batch request failed.') + } + return @() + } + + { Invoke-Check } | Should -Throw '*Batch request failed*' + } + } +} diff --git a/tests/maester/entra/Test.MT.1276.md b/tests/maester/entra/Test.MT.1276.md new file mode 100644 index 0000000000..2e84db137b --- /dev/null +++ b/tests/maester/entra/Test.MT.1276.md @@ -0,0 +1,54 @@ +Critical Entra objects should have Hard Deletion Protection enabled. + +This test reads the users, groups, applications and service principals listed in the +`HardDeletionProtectedObjects` setting of the Maester config and compares each one with its Hard Deletion +Protection setting in Microsoft Entra. Any listed object that is not protected, is soft deleted, or cannot be found +fails the test. If nothing is listed, or every listed object is protected but other objects in Microsoft Entra +have protection and are not listed, the result is **Investigate**: check whether the list is complete. + +Protection limits destructive deletion by a compromised administrator. For seven days after an object is soft +deleted, it cannot be permanently deleted, which gives time to notice and restore it (MITRE T1485 Data +Destruction). After the seven days, permanent deletion is possible again. Soft deletion still removes access, so +for T1531 Account Access Removal the benefit is recovery: the object can be restored while protection holds. + +See [Hard Deletion Protection](https://maester.dev/docs/configuration/hard-deletion-protection) for the +configuration format and for suggestions on which objects to list. + +#### Remediation action: + +For an object with the status **Not protected**, first check that it can be protected. Users and groups +synchronized from on-premises Active Directory and mail-enabled security groups cannot be, and also show as not +protected. Remove them from the config, or protect another object instead. For an object that can be protected: + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. +2. Browse to **Backup and recovery** > **Hard deletion protection**. +3. Select **Add protection** and choose one object type. +4. Select the reported objects (up to 20 per operation) and review the permanent-protection warning. +5. Select **Save**. + +For an object with the status **Soft deleted**: protection can only be enabled on an active object, so restore the +object first. A restored object keeps protection if it already had it. If it did not, follow the steps above. + +* A user or a group: restore it from **Deleted users** or **Deleted groups** in the Microsoft Entra admin center. +* An application: restore it from **App registrations** > **Deleted applications**. +* A service principal: the admin center does not show deleted service principals. If its application registration + was deleted too, restore the registration from **Deleted applications** first, which also restores its service + principal. Otherwise restore the service principal with Microsoft Graph, + `POST https://graph.microsoft.com/v1.0/directory/deletedItems/{id}/restore`, or with + `Restore-MgDirectoryDeletedItem -DirectoryObjectId `, as at least an Application Administrator or Cloud + Application Administrator. Use a separate delegated Graph connection that has `Application.ReadWrite.All`, not + the read-only connection Maester uses. Customers cannot restore a deleted managed identity. + +For an object with the status **Not found**: check the `Type` and `Id` in the Maester config. The `Id` is the object +ID, not the application (client) ID or a user principal name. If the object was permanently deleted, remove it from +the config. + +Protection is permanent and cannot be removed once enabled. + +#### Related links + +* [Configure Hard Deletion Protection in Microsoft Entra (preview)](https://learn.microsoft.com/entra/backup/configure-hard-deletion-protection) +* [Restore a soft deleted enterprise application](https://learn.microsoft.com/entra/identity/enterprise-apps/restore-application) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1276.ps1 b/tests/maester/entra/Test.MT.1276.ps1 new file mode 100644 index 0000000000..0f569d51fb --- /dev/null +++ b/tests/maester/entra/Test.MT.1276.ps1 @@ -0,0 +1,117 @@ +function Test-MtEntraHardDeletionProtection { + <# + .SYNOPSIS + Checks that the critical Entra objects in the Maester config have Hard Deletion Protection. + + .DESCRIPTION + Takes the HardDeletionProtectedObjects setting as a parameter and checks that each listed + user, group, application or service principal has isHardDeleteProtectionEnabled set to + true. Protection is permanent once enabled, so Maester never guesses which objects are + critical. + + The result is Failed when a listed object is not protected, is soft deleted or cannot be + found. The result is Investigate when nothing is listed, or when every listed object is + protected but other objects in the tenant have protection and are not listed, because the + config and the tenant then disagree. + + Hard Deletion Protection is in preview and the property is only available in Microsoft + Graph beta. + + .EXAMPLE + Invoke-Maester -TestId MT.1276 -IncludePreview + + .LINK + https://maester.dev/docs/tests/MT.1276 + #> + [MaesterTest( + Id = 'MT.1276', + Title = 'Critical Entra objects should have Hard Deletion Protection enabled (Preview).', + Product = 'entra', + Feature = 'backup-and-recovery', + Area = 'data-protection', + ResourceType = 'Tenant', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Low', + Mitre = ('T1485', 'T1531'), + Service = 'Graph', + Lifecycle = 'Preview', + Author = 'agnivesh' + )] + [CmdletBinding()] + [OutputType([bool])] + param ( + # The objects to check, from the HardDeletionProtectedObjects setting: a Type and an Id. + [MaesterParameter(Setting = 'HardDeletionProtectedObjects')] + [object[]] $HardDeletionProtectedObjects = @() + ) + + $ConfiguredObjects = @($HardDeletionProtectedObjects | Where-Object { $_ }) + $Protected = @(Get-MtEntraHardDeletionProtectedObject) + + if ($ConfiguredObjects.Count -eq 0) { + $Result = 'No objects are listed in HardDeletionProtectedObjects in the Maester ' + + "config, so Hard Deletion Protection must be verified manually.`n`n" + if ($Protected.Count -gt 0) { + $Result += "These $($Protected.Count) object(s) have Hard Deletion Protection in " + + 'Microsoft Entra. Add the ones that matter to the config so this test can ' + + "check them:`n`n" + $Result += Format-MtEntraHardDeletionTable -InputObject $Protected ` + -StateProperty State -StateHeading State + } else { + $Result += 'The scan did not find any objects with Hard Deletion Protection. Add ' + + 'the critical objects that support it to ' + + 'GlobalSettings.HardDeletionProtectedObjects, then enable protection on ' + + 'them. See https://maester.dev/docs/configuration/hard-deletion-protection ' + + 'for the format and for the objects that support it.' + } + Add-MtTestResultDetail -Investigate -Result $Result + return $null + } + + # An entry listed twice counts once. When the two lookups disagree, the failure wins. + $RowIndex = @{} + $Rows = [System.Collections.Generic.List[object]]::new() + foreach ($Configured in $ConfiguredObjects) { + $Row = Get-MtEntraHardDeletionObjectStatus -Configured $Configured + $Key = "$($Row.Type)|$($Row.Id)" + if (-not $RowIndex.ContainsKey($Key)) { + $RowIndex[$Key] = $Rows.Count + $Rows.Add($Row) + } elseif ($Rows[$RowIndex[$Key]].Status -eq 'Protected' -and $Row.Status -ne 'Protected') { + $Rows[$RowIndex[$Key]] = $Row + } + } + + $Unlisted = @($Protected | Where-Object { -not $RowIndex.ContainsKey("$($_.Type)|$($_.Id)") }) + $UnlistedTable = '' + if ($Unlisted.Count -gt 0) { + $UnlistedTable = "`n`n$($Unlisted.Count) other object(s) have Hard Deletion Protection " + + "in Microsoft Entra but are not listed in the Maester config:`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Unlisted ` + -StateProperty State -StateHeading State) + } + + $Failing = @($Rows | Where-Object { $_.Status -ne 'Protected' }) + if ($Failing.Count -gt 0) { + $Result = "$($Failing.Count) of $($Rows.Count) listed object(s) do not have Hard " + + "Deletion Protection enabled, or are deleted or missing.`n`n" + + (Format-MtEntraHardDeletionTable -InputObject $Failing ` + -StateProperty Status -StateHeading Status) + Add-MtTestResultDetail -Result ($Result + $UnlistedTable) + return $false + } + + if ($Unlisted.Count -gt 0) { + $Result = "All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled. " + + 'Check whether the other protected objects below belong in the Maester config.' + + $UnlistedTable + Add-MtTestResultDetail -Investigate -Result $Result + return $null + } + + Add-MtTestResultDetail -Result ( + "Well done. All $($Rows.Count) listed object(s) have Hard Deletion Protection enabled." + ) + return $true +} diff --git a/website/docs/configuration/hard-deletion-protection.md b/website/docs/configuration/hard-deletion-protection.md new file mode 100644 index 0000000000..f97069c1b1 --- /dev/null +++ b/website/docs/configuration/hard-deletion-protection.md @@ -0,0 +1,201 @@ +--- +title: Hard Deletion Protection +sidebar: + order: 3 +--- + +# Configuring Hard Deletion Protection + +Hard Deletion Protection (preview) is a Microsoft Entra feature that stops a protected object from being permanently deleted during the first seven days after it is soft deleted. The object can still be soft deleted and restored, so you have time to notice the deletion, investigate it and recover the object. + +Maester includes tests that check the objects you list in the Maester configuration against their Hard Deletion Protection setting in Microsoft Entra. + +:::caution +Protection is **permanent**. Once enabled on an object it cannot be removed, and soft deleting the object does not undo it. Soft delete an object that you protected by mistake only if you want to retire it: it stops working while it is deleted, you can restore it for up to 30 days, and you can permanently delete it seven days after the soft delete. Microsoft intends the feature for selected critical objects, not for every object in the tenant. +::: + +## How Hard Deletion Protection Works + +- The seven-day protection window starts when the object is soft deleted. +- An attempt to permanently delete the object during the window is blocked. In testing, Microsoft Graph returned `403 Forbidden` with the `Authorization_RequestDenied` error code and a message that gives the time the window ends. The Microsoft Graph reference documents `409 Conflict` for this case, so match on the message and not on the status code if you build detection around it. +- After the window ends, the object can be permanently deleted as normal. +- If you restore the object, protection stays enabled. If you soft delete it again, a new seven-day window starts. +- Protection can only be enabled on active (not deleted) objects. +- Enabling protection is recorded in the Microsoft Entra audit logs. + +Supported objects: + +| Object | Notes | +|--------|-------| +| Users | Cloud-only users, including guests. Users synchronized from on-premises Active Directory are not supported. | +| Groups | Cloud-only Microsoft 365 and security groups. Mail-enabled security groups and distribution groups are not supported. | +| Applications | App registrations in your tenant. | +| Service principals | Service principals in your tenant, such as enterprise applications. Some system-created service principals, such as those for Azure Automation accounts, cannot be protected. | + +Microsoft Entra Agent ID objects are supported through their underlying user, application and service principal types. No additional license is required. + +## Configuration Format + +Hard Deletion Protection objects are configured in the `GlobalSettings` section of your custom `maester-config.json` file. + +### Basic Structure + +```json +{ + "GlobalSettings": { + "HardDeletionProtectedObjects": [] + } +} +``` + +An empty list is the default. Add one entry per critical object, as in the examples below. + +### Supported Parameters + +Each entry in the `HardDeletionProtectedObjects` array supports the following parameters: + +| Parameter | Required | Description | +|-----------|----------|-------------| +| `Type` | Yes | The type of object. Must be `User`, `Group`, `Application` or `ServicePrincipal` | +| `Id` | Yes | The Object ID (GUID) of the object | + +For an application, use the **Object ID** of the app registration, not the Application (client) ID. For a service principal, use the Object ID of the enterprise application. + +Maester checks the list before a run starts. A `Type` that is not one of the four values, or an entry without an `Id`, stops the run with a message that names the entry. A property name that is not listed above, such as `ObjectId`, is reported as a warning. An entry without a `Type`, or with an `Id` that is not a GUID (a user principal name, for example), passes that check and then makes the test fail with an error that names the entry. + +## Configuration Examples + +```json +{ + "GlobalSettings": { + "HardDeletionProtectedObjects": [ + { "Type": "User", "Id": "00000000-0000-0000-0000-000000000001" }, + { "Type": "Group", "Id": "00000000-0000-0000-0000-000000000002" }, + { "Type": "Application", "Id": "00000000-0000-0000-0000-000000000003" }, + { "Type": "ServicePrincipal", "Id": "00000000-0000-0000-0000-000000000004" } + ] + } +} +``` + +## What the Test Reports + +| Situation | Result | +|-----------|--------| +| Every listed object has protection enabled, and no other object in Microsoft Entra has protection | **Passed** | +| Every listed object has protection enabled, but other objects in Microsoft Entra have protection and are not listed | **Investigate**. The other objects are listed so you can decide whether they belong in the configuration | +| A listed object does not have protection enabled, or Microsoft Entra returns no value for it | **Failed**, and the object is listed in the result | +| A listed object is soft deleted | **Failed**, and the object is listed with the status `Soft deleted` | +| A listed object does not exist | **Failed**, and the object is listed with the status `Not found` | +| No objects are listed in the configuration | **Investigate**. Protection has to be verified manually. The objects that already have protection in Microsoft Entra are listed to help you build the configuration | + +Microsoft Graph returns `null` for an object that is not protected, so an unprotected object and an object that cannot be protected (such as a synchronized user) both appear as not protected. + +The result lists at most 25 objects in each table and gives the total when there are more. Every table shows the object type, object ID and display name, and one more column: + +- **Status** in the table of failing listed objects. It is `Not protected`, `Soft deleted` or `Not found`. This is the outcome of the check for that entry. +- **State** in the table of protected objects that are not in the configuration, which is also the table you get when nothing is listed. It is `Active` or `Soft deleted`, and `Active or soft deleted` when the two reads of the run disagree about an object, for example because it was deleted between them. The result does not say which read is newer. + +A failed result also lists the protected objects that are not in the configuration, so you can see both gaps at once. + +The scan for protected objects reads the active and the deleted objects one after the other, so it is not a snapshot. An object that is soft deleted or restored while the scan runs can be listed twice (shown once, with the state `Active or soft deleted`), or be missed. If an object you expect is missing from a table, run the test again, which answers a missed scan. Running it again does not show objects beyond the table limit of 25: to see all of them, use the Microsoft Entra admin center or Microsoft Graph. + +## Which Objects to Protect + +Protect the objects whose permanent loss would be hard to recover from or would help an attacker hide their tracks. These are suggestions, not requirements. Start small and add objects as you decide they are critical. + +### Users + +- **Emergency access (break glass) accounts** - Losing them can lock you out of the tenant. See [Emergency Access Accounts](./emergency-access-accounts.md). +- **Administrators** - Global Administrators and other holders of privileged roles. Protection can stop a departing administrator or an attacker from removing the accounts that can undo their changes. +- **Executives and other VIP accounts** - Accounts with high-value mailboxes and data, and accounts that are often targeted. +- **Critical business accounts** - Finance, HR and legal approvers, and accounts that own critical processes. +- **Dedicated service accounts** - Cloud-only user accounts that applications or integrations sign in with. + +### Groups + +- **Role-assignable groups** - Groups that grant Microsoft Entra roles. +- **Groups used in Conditional Access policies** - Groups that policies include or exclude, such as emergency access or exception groups. +- **Groups that grant access to sensitive apps or data** - Including the Microsoft 365 groups behind critical teams and sites. + +### Applications and service principals + +- **Applications with high-privilege permissions** - For example Microsoft Graph application permissions that can read or change many objects. +- **Line-of-business and single sign-on apps** - Apps that many users depend on to work. +- **Automation and pipeline identities** - Apps and service principals used by deployment pipelines, backup tools and security tooling, and the workload identities behind agents. +- **Identity infrastructure apps** - Apps that other services or federation depend on. + +### What not to protect + +- Test and temporary objects, since protection cannot be undone. +- Users synchronized from on-premises Active Directory, which are not supported. +- Whole categories of objects. The feature is not designed for blanket protection, and you can protect only 20 objects of one type per operation in the portal. + +## Enabling Protection + +Maester does not enable protection. Use the Microsoft Entra admin center or Microsoft Graph. + +### Microsoft Entra admin center + +1. Sign in to the [Microsoft Entra admin center](https://entra.microsoft.com) as at least a **Microsoft Entra Backup Administrator**. +2. Browse to **Backup and recovery** > **Hard deletion protection**. +3. Select **Add protection** and choose one object type. +4. Select up to 20 objects and review the permanent-protection warning. +5. Select **Save**. + +### Microsoft Graph + +Set `isHardDeleteProtectionEnabled` to `true` on the object with the Microsoft Graph beta endpoint. The calling app or user needs the `HardDeletionSetting.ReadWrite.Enable` permission, and the caller must have the Microsoft Entra Backup Administrator role. + +```powershell +Connect-MgGraph -Scopes 'HardDeletionSetting.ReadWrite.Enable' + +$body = @{ isHardDeleteProtectionEnabled = $true } +Invoke-MgGraphRequest -Method PATCH -Uri 'https://graph.microsoft.com/beta/users/' -Body $body +``` + +Use `groups`, `applications` or `servicePrincipals` in place of `users` for the other object types. + +## Finding Object IDs + +### In the Microsoft Entra admin center + +1. Go to the [Microsoft Entra admin center](https://entra.microsoft.com) +2. Open **Users**, **Groups**, **App registrations** or **Enterprise applications** +3. Search for the object +4. Copy the **Object ID** from its overview page + +### With PowerShell + +```powershell +Get-MgUser -UserId "admin@contoso.com" | Select-Object Id, UserPrincipalName +Get-MgGroup -Filter "displayName eq 'Privileged Access Group'" | Select-Object Id, DisplayName +Get-MgApplication -Filter "displayName eq 'Contoso Deployment'" | Select-Object Id, DisplayName +Get-MgServicePrincipal -Filter "displayName eq 'Contoso Deployment'" | Select-Object Id, DisplayName +``` + +## Related Tests + +| Test ID | Description | +|---------|-------------| +| MT.1276 | Critical Entra objects should have Hard Deletion Protection enabled (Preview) | + +MT.1276 is a preview test. Run it with the `-IncludePreview` switch of `Invoke-Maester`. + +## Best Practices + +1. **Protect deliberately** - Protection is permanent, so list only the objects you are sure about. + +2. **Combine it with Protected Actions** - Protected Actions can require phishing-resistant MFA before someone permanently deletes an object. Hard Deletion Protection blocks the deletion during its window even when the user passes that check. Protected Actions needs Microsoft Entra ID P1 or P2. + +3. **Monitor deletions** - Protection does not stop soft deletion. Alert on deletions of your critical objects so that you notice them within the seven days. + +4. **Keep the list current** - Add new critical objects as you create them and review the list when staff or roles change. + +## Learn More + +- [Configure Hard Deletion Protection in Microsoft Entra (preview)](https://learn.microsoft.com/entra/backup/configure-hard-deletion-protection) +- [Microsoft Graph permissions reference: HardDeletionSetting.ReadWrite.Enable](https://learn.microsoft.com/graph/permissions-reference) +- [Hard Deletion Protection for Entra ID Directory Objects (Office 365 for IT Pros)](https://office365itpros.com/2026/11/09/hard-deletion-protection/) +- [Microsoft adds hard deletion protection for Entra ID (Our Cloud Network)](https://ourcloudnetwork.com/microsoft-adds-hard-deletion-protection-for-entra-id/) +- [Hard Deletion Protection in Microsoft Entra ID (HTMD)](https://www.anoopcnair.com/hard-deletion-protection-in-microsoft-entra-id/) diff --git a/website/docs/configuration/overview.md b/website/docs/configuration/overview.md index 54bce6c518..7c3a649a58 100644 --- a/website/docs/configuration/overview.md +++ b/website/docs/configuration/overview.md @@ -141,6 +141,7 @@ The following global settings are available for customization: | `DefenderEndpointPolicyFiltering` | Which Defender for Endpoint policies the Defender checks read: `All`, `IncludeUnassigned` or `OnlyAssigned` (default) | This page | | `DefenderEndpointComplianceLogic` | How the Defender for Endpoint checks combine policies: `EffectivePolicy` (default), `AllPolicies` or `AnyPolicy` | This page | | `XspmExternalDataUris` | Override the HTTPS sources used by XSPM Advanced Hunting queries | This page | +| `HardDeletionProtectedObjects` | Define the critical users, groups, applications and service principals that must have Hard Deletion Protection enabled | [Hard Deletion Protection](./hard-deletion-protection.md) | The GitHub and Dataverse settings are listed in the [run configuration reference](./run-configuration.md#globalsettings). diff --git a/website/docs/configuration/run-configuration.md b/website/docs/configuration/run-configuration.md index 06c37a8e9d..bfcbf28477 100644 --- a/website/docs/configuration/run-configuration.md +++ b/website/docs/configuration/run-configuration.md @@ -80,6 +80,10 @@ Keys Maester does not know are kept and passed through, so they do no harm. The "EmergencyAccessAccounts": [ { "Type": "User", "UserPrincipalName": "BreakGlass1@contoso.com" }, { "Type": "Group", "Id": "00000000-0000-0000-0000-000000000000" } + ], + "HardDeletionProtectedObjects": [ + { "Type": "User", "Id": "00000000-0000-0000-0000-000000000001" }, + { "Type": "ServicePrincipal", "Id": "00000000-0000-0000-0000-000000000002" } ] }, "Selection": { @@ -153,6 +157,7 @@ Maester knows these: | `DefenderEndpointComplianceLogic` | string | `EffectivePolicy` | Defender for Endpoint checks. | | `DataverseEnvironmentUrl` | string | | Copilot Studio checks. | | `AzureDevOpsOrganization` | string | | Default organization for `Connect-Maester -Service AzureDevOps`. | +| `HardDeletionProtectedObjects` | array | none | Critical objects (`Type` and `Id`) that must have Hard Deletion Protection enabled. See [Hard Deletion Protection](./hard-deletion-protection.md). | | `GitHubOrganization` | string | | GitHub checks. | | `GitHubApiBaseUri` | string | `https://api.github.com` | GitHub checks. | | `GitHubApiVersion` | string | `2022-11-28` | GitHub checks. | diff --git a/website/src/data/test-builder.json b/website/src/data/test-builder.json index 2b025d35ea..ad93d32bbc 100644 --- a/website/src/data/test-builder.json +++ b/website/src/data/test-builder.json @@ -310,6 +310,10 @@ { "key": "recommendations", "name": "Entra recommendations" + }, + { + "key": "backup-and-recovery", + "name": "Backup and recovery" } ] }, @@ -18321,6 +18325,15 @@ "description": "GitHub organization that the GitHub checks read.", "connection": true }, + { + "name": "HardDeletionProtectedObjects", + "type": "object[]", + "kind": null, + "default": [], + "allowedValues": [], + "description": "Critical users, groups, applications and service principals (Type and Id) that must have Hard Deletion Protection enabled.", + "connection": false + }, { "name": "ParkedDomains", "type": "string[]", @@ -18399,6 +18412,11 @@ "type": "int", "tests": 1 }, + { + "name": "HardDeletionProtectedObjects", + "type": "object[]", + "tests": 1 + }, { "name": "MailboxServicePlanIds", "type": "string[]",