Lister les rôles d’administrateur Office 365 et suivre les changements

Les rôles d’administrateur sont la clé de votre royaume

Office 365 permet aux organisations de déléguer de manière granulaire les privilèges administratifs.

Office 365 contient de nombreux rôles administratifs intégrés. Parmi eux, nous trouvons administrateur général, administrateur Exchange, administrateur d’utilisateurs, administrateur de facturation, lecteur général, etc.

Ces privilèges doivent être vérifiés régulièrement.

Lorsque vous avez peu d’admin informatique, il est assez simple d’identifier les rôles d’administrateur. Mais lorsque vous avez un tenant plus important et/ou beaucoup d’administrateurs, il devient difficile de suivre les changements. En effet, le portail Office 365 ou le portail Azure AD ne fournit aucun rapport de rôles d’administrateur.

Cet article vous propose deux scripts :

  • un script pour suivre les changements de rôles d’administrateur au cours des 90 derniers jours
  • un script pour obtenir un rapport sur les rôles d’administrateur Office 365 et leurs membres

Pour d’autres scripts/astuces utiles, je te recommande de lire ceci.

Suivi des changements des rôles administrateurs

Le script PowerShell suivant indique toutes les modifications concernant les rôles d’administrateur (ajouter ou supprimer un membre).

Vous pouvez trouver la dernière version de ce script sur mon GitHub.

<#
.SYNOPSIS
Search-AdminRoleChanges.ps1 - Reports on Office 365 Admin Role

.DESCRIPTION 
This script produces a report of the membership of Office 365 admin role groups.
By default, the report contains only the groups with members.
To get all the role, included empty roles, add -IncludeEmptyRoles $true

.OUTPUTS
The report is output to an array contained all the audit logs found.
To export in a csv, do Search-AdminRoleChanges | Export-CSV -NoTypeInformation "$(Get-Date -Format yyyyMMdd)_adminRolesChange.csv"

.EXAMPLE
Search-AdminRoleChanges

.LINK

https://github.com/itpro-tips/Microsoft365-Toolbox/blob/master/Audit/Search-AdminRolesChanges.ps1


.NOTES
Written by Bastien Perez (ITPro-Tips.com)
For more Office 365/Microsoft 365 tips and news, check out ITPro-Tips.com.

Version history:
V1.0, 17 august 2020 - Initial version

Copyright (c) 2020 Bastien Perez (ITPro-Tips.com)

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.

#>

# Admin roles list: https://docs.microsoft.com/en-us/microsoft-365/compliance/search-the-audit-log-in-security-and-compliance?view=o365-worldwide
function Search-AdminRoleChanges {
	[CmdletBinding()]
	param (
	)
    
    try {
        Import-Module exchangeonlinemanagement -ErrorAction stop
    }
    catch {
        Write-Warning 'First, install the official Microsoft Exchange Online Management module : Install-Module exchangeonlinemanagement'
        return
    }

    try {
        $records = Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date).AddDays(1) -Operations ('Add Member to Role', 'Remove Member From Role') -ResultSize 2000 -Formatted-ErrorAction Stop
    }
    catch {
        Connect-ExchangeOnline
        $records = Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date).AddDays(1) -Operations ('Add Member to Role', 'Remove Member From Role') -ResultSize 2000 -Formatted
    }

	if ($records.Count -eq 0) {
		Write-Host 'No audit logs found'
	}
	else {
		Write-Host "Processing $($Records.Count) audit records..."
   
		$report = New-Object System.Collections.Generic.List[Object]
		ForEach ($record in $records) {
			$auditData = ConvertFrom-Json $record.Auditdata
			# Only process the additions of guest users to groups
	
			$timeStamp = Get-Date $record.CreationDate -format g
			# Try and find the timestamp when the Guest account was created in AAD
	
			$object = [PSCustomObject]@{
				TimeStamp      = $timeStamp
			
				ObjectId       = $auditData.ObjectId
				Action         = $auditData.Operation
				Actor          = $auditData.UserId
				ActorIpAddress	= $auditData.ActorIpAddress
				RoleName       = $auditData.modifiedproperties.newvalue[1]
			}      
	   
			$report.Add($object)
		}
	
		return $report
	}
}

Lister les rôles d’administrateur Office 365

Le script PowerShell suivant extrait tous les rôles d’administrateur Office 365 et leurs membre.

Le script utilise le module MSOnline car, même si Microsoft recommande le module AzureAD, le module MSOnline renvoie l’état MFA.

Vous pouvez trouver la dernière version de ce script sur mon GitHub.

<#
.SYNOPSIS
Get-MsolRoleReport.ps1 - Reports on Office 365 Admin Role
.DESCRIPTION 
This script produces a report of the membership of Office 365 admin role groups.
By default, the report contains only the groups with members.
To get all the role, included empty roles, add -IncludeEmptyRoles $true
.OUTPUTS
The report is output to an array contained all the audit logs found.
To export in a csv, do Get-MsolRoleReport | Export-CSV -NoTypeInformation "$(Get-Date -Format yyyyMMdd)_adminRoles.csv" -Encoding UTF8
.EXAMPLE
Get-MsolRoleReport
.EXAMPLE
Get-MsolRoleReport -IncludeEmptyRoles $true
.EXAMPLE
Get-MsolRoleReport | Export-CSV -NoTypeInformation "$(Get-Date -Format yyyyMMdd)_adminRoles.csv" -Encoding UTF8
.LINK

.NOTES
Written by Bastien Perez (ITPro-Tips.com)
For more Office 365/Microsoft 365 tips and news, check out ITPro-Tips.com.
Version history:
V1.0, 17 august 2020 - Initial version
Copyright (c) 2020 Bastien Perez (ITPro-Tips.com)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
#>
function Get-MsolRoleReport {
    [CmdletBinding()]
    param (
        [boolean]$IncludeEmptyRoles
    )

    try {
        Import-Module MSOnline -ErrorAction stop
    }
    catch {
        Write-Warning 'First, install the official Microsoft MSOnline module : Install-Module MSOnline'
        return
    }

    try {
        $msolRoles = Get-MsolRole -ErrorAction Stop
    }
    catch {
        Connect-MsolService
        $msolRoles = Get-MsolRole
    }

    # Use MsolService because returns more role and allows MFA status 
    
    $rolesMembership = New-Object 'System.Collections.Generic.List[System.Object]'

    foreach ($msolRole in $msolRoles) {

        # Global administrator is called Company administrator in Microsoft Graph API and Azure AD PowerShell https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/directory-assign-admin-roles#global-administrator--company-administrator
        # Other roles also have another name, but the name is understable
        switch ($msolRole.Name) {
            'Company Administrator' {
                $msolRole.Name = 'Company Administrator/Global administrator'
                break
            }
        }

        Write-Host -ForegroundColor green "Processing role $($msolRole.Name)..." -NoNewline
        
        try {

            $roleMembers = Get-MsolRoleMember -RoleObjectId $msolRole.ObjectId
            
            Write-Host -ForegroundColor green " $($roleMembers.count) member(s) found"

            if ($IncludeEmptyRoles -and $roleMembers.count -eq 0) {
                $object = [PSCustomObject] [ordered]@{
                    'Role'                    = $msolRole.Name
                    'RoleDescription'         = $msolRole.Description
                    'MemberDisplayName'       = '-'
                    'MemberUserPrincipalName' = '-'
                    'MemberEmail'             = '-'
                    'MemberAlternateEmail'    = '-'
                    'RoleMemberType'          = '-'
                    'MemberAccountEnabled'    = '-'
                    'MemberLastDirSyncTime'   = '-'
                    'MemberMFAState'          = '-'
                    'MemberObjectID'          = '-'
                }
                
                $rolesMembership.Add($object)

                # break the loop
                continue
            }

            foreach ($roleMember in $roleMembers) {                
                # if user already exist in the arraylist, we look for to prevent a new Get-MsolUser (time consuming)
                # Select only the first if user already exists in multiple roles
                if ($rolesMembership.MemberObjectID -contains $roleMember.ObjectID) {
                    $found = $rolesMembership | Where-Object { $_.MemberObjectID -eq $roleMember.ObjectID } | Select-Object -First 1
                    $object = [PSCustomObject] [ordered]@{
                        'Role'                    = $msolRole.Name
                        'RoleDescription'         = $msolRole.Description
                        'MemberDisplayName'       = $found.MemberDisplayName
                        'MemberUserPrincipalName' = $found.MemberUserPrincipalName
                        'MemberEmail'             = $found.MemberEmail
                        'MemberAlternateEmail'    = $found.MemberAlternateEmail
                        'RoleMemberType'          = $found.RoleMemberType
                        'MemberAccountEnabled'    = $found.MemberAccountEnabled
                        'MemberLastDirSyncTime'   = $found.MemberLastDirSyncTime
                        'MemberMFAState'          = $found.MemberMFAState
                        'MemberObjectID'          = $found.MemberObjectID
                    }
                }
                else {
                    if ($roleMember.RoleMemberType -eq 'ServicePrincipal') {
                        $member = Get-MsolServicePrincipal -SearchString $roleMember.DisplayName
                    }
                    # Sometimes, user is service account, not present in Office 365. We set ErrorAction SilentlyContinue to prevent error. not handle non user type
                    else {
                        $member = Get-MsolUser -objectid $roleMember.ObjectID -ErrorAction SilentlyContinue
                    }
                    
                    
                    $MFAState = $member.StrongAuthenticationRequirements.State
                    
                    if ($null -eq $MFA) {
                        $MFAState = 'Disabled'
                    }
    
                    if ($null -eq $member.LastDirSyncTime) {
                        $lastDirSyncTime = 'Not a synchronized user'
                    }
                    else {
                        $lastDirSyncTime = $member.LastDirSyncTime
                    }

                    $object = [PSCustomObject] [ordered]@{
                        'Role'                    = $msolRole.Name
                        'RoleDescription'         = $msolRole.Description
                        'MemberDisplayName'       = $roleMember.DisplayName
                        'MemberUserPrincipalName' = $member.UserPrincipalName
                        'MemberEmail'             = $roleMember.EmailAddress
                        'MemberAlternateEmail'    = $member.AlternateEmailAddresses | ForEach-Object { $_ -join '|' }
                        'RoleMemberType'          = $roleMember.RoleMemberType
                        'MemberAccountEnabled'    = -not $member.AccountEnabled # BlockCredential is the opposite 
                        'MemberLastDirSyncTime'   = $lastDirSyncTime
                        'MemberMFAState'          = $MFAState
                        'MemberObjectID'          = $member.ObjectId
                    }
                }

                $rolesMembership.Add($object)
            }
        }
        catch {
            Write-Warning $_.Exception.Message
        }
    }
    
    return $rolesMembership
}

Leave a Reply

Close Menu