Monitoring Unauthorized Access in SharePoint Online using PnP PowerShell

Loading

Unauthorized access to SharePoint Online can lead to data breaches, compliance violations, and security risks. Monitoring unauthorized access attempts using PnP PowerShell helps organizations:

✔ Detect suspicious login activities
✔ Track failed access attempts
✔ Identify unauthorized user activities
✔ Audit sensitive file access
✔ Take immediate security actions

This guide explains how to monitor and audit unauthorized access in SharePoint Online using PnP PowerShell.


Step 1: Install & Update PnP PowerShell

Ensure you have PnP PowerShell installed:

Install-Module -Name PnP.PowerShell -Force -AllowClobber

If already installed, update it:

Update-Module -Name PnP.PowerShell

Step 2: Connect to SharePoint Online

To monitor SharePoint access, connect to Microsoft 365 Security & Compliance Center using PnP PowerShell:

Connect-PnPOnline -Url "https://yourtenant-admin.sharepoint.com" -Interactive

For app-based authentication, use:

$tenantId = "your-tenant-id"
$clientId = "your-client-id"
$clientSecret = "your-client-secret"

Connect-PnPOnline -Tenant $tenantId -ClientId $clientId -ClientSecret $clientSecret -Url "https://yourtenant-admin.sharepoint.com"

Step 3: Enable Audit Logging in SharePoint Online

Before monitoring unauthorized access, audit logging must be enabled:

Set-PnPTenant -AuditLogTrimmingEnabled $true
Set-PnPTenant -AuditLogRetentionPeriod 90 # Retain logs for 90 days

Ensures all SharePoint access events are logged
Prevents logs from being automatically deleted


Step 4: Retrieve Unauthorized Access Attempts

Get Failed Login Attempts

Unauthorized users often attempt logins with incorrect credentials.

$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")  # Last 7 days
$endDate = (Get-Date).ToString("yyyy-MM-dd")

$failedLogins = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations "UserLoginFailed" -ResultSize 1000

$failedLogins | Select-Object CreationDate, UserIds, ClientIP, Workload | Format-Table -AutoSize

✔ Fetches failed login attempts in SharePoint Online.
✔ Displays date, user, IP address, and workload.


Track Unauthorized File Access

Identify users accessing sensitive files without permission:

$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")
$endDate = (Get-Date).ToString("yyyy-MM-dd")

$unauthorizedAccess = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations "FileAccessed" -ResultSize 1000

$unauthorizedAccess | Where-Object { $_.UserIds -notmatch "yourdomain.com" } | Select-Object CreationDate, UserIds, Operation, ObjectId, ClientIP | Format-Table -AutoSize

✔ Identifies external or unauthorized users accessing files.


Monitor Sharing Policy Violations

Users may share files externally without authorization.

$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")
$endDate = (Get-Date).ToString("yyyy-MM-dd")

$externalShares = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations "SharedFileExternally" -ResultSize 1000

$externalShares | Select-Object CreationDate, UserIds, Operation, ObjectId, ClientIP | Format-Table -AutoSize

✔ Fetches unauthorized file sharing attempts.


Identify Privilege Escalation Attempts

Unauthorized users may attempt to elevate permissions in SharePoint.

$startDate = (Get-Date).AddDays(-7).ToString("yyyy-MM-dd")
$endDate = (Get-Date).ToString("yyyy-MM-dd")

$privilegeAttempts = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations "AddedSiteCollectionAdmin" -ResultSize 1000

$privilegeAttempts | Select-Object CreationDate, UserIds, Operation, ObjectId, ClientIP | Format-Table -AutoSize

✔ Detects users attempting to gain admin privileges.


Step 5: Generate Unauthorized Access Reports

To export logs into a CSV report for security teams:

$reportPath = "C:\Reports\UnauthorizedAccessReport.csv"

$failedLogins + $unauthorizedAccess + $externalShares + $privilegeAttempts | Export-Csv -Path $reportPath -NoTypeInformation

Write-Host "Unauthorized Access Report saved at: $reportPath"

✔ Saves all security events into a report for analysis.


Step 6: Notify Security Team About Unauthorized Access

Send email alerts for unauthorized activities:

$smtpServer = "smtp.yourcompany.com"
$securityTeam = "security@yourcompany.com"
$subject = "SharePoint Unauthorized Access Alert"
$body = "Unauthorized access detected in SharePoint Online. Please review the attached report."

Send-MailMessage -To $securityTeam -From "admin@yourcompany.com" -Subject $subject -Body $body -Attachments $reportPath -SmtpServer $smtpServer

Notifies security teams immediately for action.


Step 7: Automate Monitoring & Scheduling

To run the script automatically, save it as MonitorUnauthorizedAccess.ps1 and schedule it using Task Scheduler or Azure Automation.

Example Task Scheduler command:

powershell.exe -ExecutionPolicy Bypass -File "C:\Scripts\MonitorUnauthorizedAccess.ps1"

✔ Ensures continuous monitoring of unauthorized access.


Step 8: Take Action Against Unauthorized Users

To block unauthorized users:

Set-AzureADUser -ObjectId "user@external.com" -AccountEnabled $false
Write-Host "Blocked unauthorized user: user@external.com"

✔ Prevents further unauthorized access attempts.

To revoke external user access:

Remove-PnPExternalUser -ExternalUser "user@external.com"
Write-Host "Revoked external user's access."

✔ Ensures only authorized users can access SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *