Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Audit Shared Mailbox Activities Using PowerShell

Auditing Shared Mailbox Activities in Microsoft 365 Using PowerShell


Auditing shared mailbox activities is a critical task in Microsoft 365 environments to ensure compliance, monitor user actions, and detect unauthorized access or modifications. Microsoft 365 provides robust audit logging capabilities, which can be leveraged using PowerShell to track activities such as email deletions, access events, and modifications performed by delegated users or administrators.


This article introduces a PowerShell script designed to simplify the process of auditing shared mailbox activities. The script retrieves audit logs, filters specific actions, and exports the results into a CSV file for further analysis.




Why Audit Shared Mailbox Activities?


Shared mailboxes are often used by teams to manage shared email accounts, such as support@domain.com or info@domain.com. However, without proper monitoring, these mailboxes can be vulnerable to:



  • Unauthorized deletions of emails or folders.

  • Unauthorized access by users or external entities.

  • Misuse of permissions, such as sending emails on behalf of the shared mailbox.


By auditing shared mailbox activities, administrators can:



  • Identify suspicious or unauthorized actions.

  • Ensure compliance with organizational policies.

  • Generate reports for forensic analysis or audits.




Key Features of the PowerShell Script


The script simplifies the auditing process by offering the following features:
1. Retrieve Audit Logs:



  • Fetches audit logs for up to 180 days (default) or a custom date range.

  • Tracks activities for a specific shared mailbox.


2. Track Specific Actions:



  • Monitors actions such as SendAs, SendOnBehalf, FolderBind, HardDelete, SoftDelete, MoveToDeletedItems, and more.

  • Identifies actions performed by admins, delegated users, and external users (optional).


3. Export Results:



  • Exports the audit log data into a CSV file for easy analysis and reporting.


4. Flexible Authentication:



  • Supports MFA-enabled accounts, non-MFA credentials, and certificate-based authentication for unattended or scheduled execution.


5. Automatic Module Installation:



  • Automatically installs the Exchange Online Management (EXO) module if it is not already installed.


6. Scheduler-Friendly:



  • Can be integrated into automated tasks or scheduled jobs for regular audits.




Prerequisites


Before running the script, ensure the following:
1. Permissions:



  • You must have Global Admin or Audit Log Search permissions in Microsoft 365.
    2. Audit Logging:

  • Unified Audit Logging must be enabled in the Microsoft Purview compliance portal.

  • Verify and enable audit logging using:
     Get-AdminAuditLogConfig
    Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true

    3. PowerShell Module:


  • Install the Exchange Online Management module if not already installed:
     Install-Module ExchangeOnlineManagement -Repository PSGallery -Force




How to Use the Script


Step 1: Connect to Exchange Online


Before running the script, connect to Exchange Online using the following command:


Connect-ExchangeOnline -UserPrincipalName admin@yourdomain.com

For certificate-based authentication, use:


Connect-ExchangeOnline -AppId <ClientId> -CertificateThumbprint <Thumbprint> -Organization <YourDomain>



Step 2: Run the Script


Save the provided PowerShell script as Audit-SharedMailbox.ps1 and execute it with the following command:


.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "support@yourdomain.com"

This retrieves all activities performed on the shared mailbox support@yourdomain.com within the last 180 days.




Step 3: Filter Specific Actions


To focus on specific actions, such as email deletions, modify the script to include only relevant operations:


Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -Operations "HardDelete", "SoftDelete", "MoveToDeletedItems"

This retrieves logs related to email deletions in the past 30 days.




Step 4: Export Results to CSV


The script automatically exports the results to a CSV file. Alternatively, you can manually export the results using:


Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-30) -EndDate (Get-Date) -Operations "HardDelete", "SoftDelete", "MoveToDeletedItems" | Export-Csv -Path "C:\AuditResults.csv" -NoTypeInformation

The CSV file includes columns such as:



  • Activity Time

  • Performed by

  • Performed Operation

  • Shared Mailbox Name

  • Result Status

  • Logon Type

  • External Access

  • More Info




Step 5: Disconnect Exchange Online


After completing the audit, disconnect the Exchange Online session:


Disconnect-ExchangeOnline -Confirm:$false



Customizing the Script


The script is highly customizable to suit your organization's needs:



  • Custom Date Range: Specify a start and end date using the -StartDate and -EndDate parameters.

  • Include External Access: Use the -IncludeExternalAccess switch to include activities performed by external users.

  • Certificate-Based Authentication: Use the -Organization, -ClientId, and -CertificateThumbprint parameters for unattended execution.




Best Practices


1. Enable Audit Logging:



  • Ensure Unified Audit Logging is enabled in your Microsoft 365 tenant.
    2. Regular Audits:

  • Schedule the script to run periodically (e.g., weekly or monthly) to monitor shared mailbox activities.
    3. Review CSV Reports:

  • Analyze the exported CSV files to identify trends or suspicious activities.
    4. Limit Access:

  • Restrict shared mailbox access to only authorized users and regularly review permissions.




Final Notes



  • If the script returns no results, verify that:

    • Audit logging is enabled.

    • The shared mailbox has been accessed or modified during the specified time range.


  • Adjust the $IntervalTimeInMinutes variable in the script to optimize performance for large datasets.




Full Script


<#
.SYNOPSIS
Audita atividades em shared mailboxes no Microsoft 365\.

.DESCRIPTION
Este script recupera logs de auditoria para uma shared mailbox específica e exporta os resultados para um arquivo CSV.

.PARAMETER SharedMailboxUPN
O UPN da shared mailbox a ser auditada (ex: suporte@dominio.com).

.PARAMETER StartDate
A data de início para a auditoria (padrão: 180 dias atrás).

.PARAMETER EndDate
A data de término para a auditoria (padrão: data atual).

.PARAMETER OutputPath
O caminho e nome do arquivo CSV de saída.

.PARAMETER IncludeExternalAccess
Inclui atividades realizadas por usuários externos.

.PARAMETER Operations
Filtra as operações a serem auditadas (padrão: SendAs, SendOnBehalf, HardDelete, SoftDelete).

.EXAMPLE
.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "suporte@dominio.com"

.EXAMPLE
.\Audit-SharedMailbox.ps1 -SharedMailboxUPN "suporte@dominio.com" -StartDate "2024-01-01" -EndDate "2024-01-31" -Operations "SendAs", "HardDelete"
#>

Param (
[Parameter(Mandatory = $true)]
[ValidatePattern('^[a-zA-Z0-9\._%+-]+@[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,}$')]
[string]$SharedMailboxUPN,

[Nullable[DateTime]]$StartDate,
[Nullable[DateTime]]$EndDate,
[string]$OutputPath = "$PSScriptRoot\Audit_Shared_Mailbox_Activities_$((Get-Date -format yyyy-MMM-dd).ToString()).csv",
[switch]$IncludeExternalAccess,
[string[]]$Operations = @('SendAs', 'SendOnBehalf', 'HardDelete', 'SoftDelete', 'MoveToDeletedItems')
)

# Função para escrever logs
function Write-Log {
Param ([string]$Message)
$Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Add-Content -Path $LogFile -Value "[$Timestamp] $Message"
}

# Configuração de logs
$LogFile = "$PSScriptRoot\Audit_Shared_Mailbox_Log_$((Get-Date -format yyyy-MMM-dd).ToString()).log"
Write-Log "Iniciando script de auditoria para a shared mailbox: $SharedMailboxUPN"

# Validação de datas
if (-not $StartDate) { $StartDate = (Get-Date).AddDays(-180) }
if (-not $EndDate) { $EndDate = Get-Date }

if ($StartDate -gt $EndDate) {
Write-Host "A data de início não pode ser maior que a data de término." -ForegroundColor Red
Write-Log "Erro: Data de início maior que data de término."
Exit
}

Write-Log "Período de auditoria: $StartDate até $EndDate"

# Conectar ao Exchange Online
Try {
Write-Log "Conectando ao Exchange Online..."
Connect-ExchangeOnline -UserPrincipalName $env:USERNAME -ShowBanner:$false -ErrorAction Stop
Write-Log "Conexão ao Exchange Online bem-sucedida."
}
Catch {
Write-Host "Falha ao conectar ao Exchange Online: $_" -ForegroundColor Red
Write-Log "Falha ao conectar ao Exchange Online: $_"
Exit
}

# Recuperar logs de auditoria com paginação
$SessionId = [Guid]::NewGuid().ToString()
$Results = @()
$Page = 1

Write-Log "Iniciando recuperação de logs de auditoria..."
do {
Write-Log "Recuperando página $Page..."
$AuditLogs = Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -SessionId $SessionId -SessionCommand ReturnLargeSet -ResultSize 5000 -Operations $Operations
$Results += $AuditLogs
$Page++
} while ($AuditLogs.Count -eq 5000)

Write-Log "Recuperação de logs concluída. Total de registros: $($Results.Count)"

# Filtrar resultados
$FilteredResults = @()
foreach ($Log in $Results) {
$AuditData = $Log.AuditData | ConvertFrom-Json

# Filtrar acessos externos (se necessário)
if (-not $IncludeExternalAccess -and $AuditData.ExternalAccess -eq $true) {
continue
}

# Filtrar atividades da shared mailbox específica
if ($AuditData.MailboxOwnerUPN -eq $SharedMailboxUPN) {
$FilteredResults += [PSCustomObject]@{
'Activity Time' = (Get-Date $AuditData.CreationTime).ToLocalTime()
'Performed by' = $AuditData.UserId
'Performed Operation' = $AuditData.Operation
'Shared Mailbox Name' = $AuditData.MailboxOwnerUPN
'Logon Type' = if ($AuditData.LogonType -eq 1) { "Administrator" } elseif ($AuditData.LogonType -eq 2) { "Delegated" } else { "Microsoft Datacenter" }
'Result Status' = $AuditData.ResultStatus
'External Access' = $AuditData.ExternalAccess
'More Info' = $Log.AuditData
}
}
}

Write-Log "Filtragem concluída. Total de registros filtrados: $($FilteredResults.Count)"

# Exportar resultados para CSV
Try {
$FilteredResults | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Host "Relatório exportado para: $OutputPath" -ForegroundColor Green
Write-Log "Relatório exportado para: $OutputPath"
}
Catch {
Write-Host "Falha ao exportar o relatório: $_" -ForegroundColor Red
Write-Log "Falha ao exportar o relatório: $_"
}

# Desconectar do Exchange Online
Try {
Write-Log "Desconectando do Exchange Online..."
Disconnect-ExchangeOnline -Confirm:$false
Write-Log "Desconexão bem-sucedida."
}
Catch {
Write-Host "Falha ao desconectar do Exchange Online: $_" -ForegroundColor Red
Write-Log "Falha ao desconectar do Exchange Online: $_"
}

Write-Log "Script concluído."



To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.