-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathAssert-LPMSGraph.ps1
More file actions
308 lines (273 loc) · 13.1 KB
/
Assert-LPMSGraph.ps1
File metadata and controls
308 lines (273 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
function Assert-LPMSGraph {
<#
.SYNOPSIS
Validates all prerequisites and requirements for using the LeastPrivilegedMSGraph module.
.DESCRIPTION
The Assert-LPMSGraph function performs a comprehensive validation of all prerequisites required
to successfully use the LeastPrivilegedMSGraph module. It checks multiple components including:
- Entra Service Connectivity: Verifies authentication to required services (LogAnalytics, Graph, Azure)
- Azure AD Premium License: Confirms that Microsoft Entra ID P1 or higher license is available
- Diagnostic Settings: Validates that MicrosoftGraphActivityLogs diagnostic settings are configured
- Log Analytics Access: Tests workspace access and verifies MicrosoftGraphActivityLogs data availability
- Microsoft Graph API Permissions: Confirms sufficient permissions to read applications
The function returns a detailed result object containing the overall status, individual check results,
tenant ID, and timestamp. Each check includes a name, status (Passed/Failed), descriptive message,
and any error details encountered.
This function is useful for troubleshooting setup issues and confirming that the environment is
properly configured before performing permission analysis operations.
.EXAMPLE
PS C:\> Assert-LPMSGraph
Runs all prerequisite checks and returns a detailed validation report.
.EXAMPLE
PS C:\> $result = Assert-LPMSGraph
PS C:\> $result.Checks | Where-Object Status -eq 'Failed'
Stores the validation result and filters to show only failed checks.
.EXAMPLE
PS C:\> Assert-LPMSGraph | Select-Object -ExpandProperty Checks | Format-Table Name, Status, Message -AutoSize
Displays all validation checks in a formatted table showing name, status, and message.
.OUTPUTS
PSCustomObject
Returns an object with the following properties:
- OverallStatus: String indicating "Passed" or "Failed"
- Checks: Array of check result objects, each containing Name, Status, Message, and Error properties
- TenantId: The current tenant ID from the authentication token
- Timestamp: UTC timestamp when the validation was performed
.NOTES
Prerequisites:
- Must be connected to Entra services using Connect-EntraService
- Requires access to Azure AD tenant with appropriate permissions
- Requires Azure AD Premium P1 or higher license for activity logging
This function does not modify any settings or configurations. It only performs read-only validation checks.
.LINK
https://mynster9361.github.io/Least_Privileged_MSGraph/commands/Assert-LPMSGraph.html
#>
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
)
$testResults = [System.Collections.ArrayList]::new()
$overallSuccess = $true
# Get current tenant ID if available
$currentTenantId = $null
try {
$token = Get-EntraToken | Select-Object -First 1
if ($token) {
$currentTenantId = $token.TenantId
}
}
catch {
Write-PSFMessage -Level Debug -Message "Could not retrieve tenant ID from token"
}
Write-PSFMessage -Level Verbose -Message "Starting LeastPrivilegedMSGraph prerequisites validation..."
#region Service Connectivity Check
Write-PSFMessage -Level Verbose -Message "Checking Entra service connectivity..."
try {
$step = "Entra Service Connectivity"
$tokens = Get-EntraToken
$requiredServices = @('LogAnalytics', 'Azure')
$graphServices = @('Graph', 'GraphBeta')
$connectedServices = $tokens.Service
$missingServices = $requiredServices | Where-Object { $_ -notin $connectedServices }
$hasGraphService = $connectedServices | Where-Object { $_ -in $graphServices }
if ($missingServices.Count -gt 0 -or -not $hasGraphService) {
$overallSuccess = $false
$errorMessage = @()
if ($missingServices.Count -gt 0) {
$errorMessage += "Missing authentication for services: $($missingServices -join ', ')"
}
if (-not $hasGraphService) {
$errorMessage += "Missing authentication for Graph service (Graph or GraphBeta required)"
}
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "$($errorMessage -join '. '). Please run Connect-EntraService with these services."
Error = $null
})
}
else {
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Passed"
Message = "Successfully authenticated to required services: $($connectedServices -join ', ')"
Error = $null
})
Write-PSFMessage -Level Verbose -Message "Entra service connectivity check passed"
}
}
catch {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Failed to verify service connectivity"
Error = $_.Exception.Message
})
Write-PSFMessage -Level Debug -Message "Entra service connectivity check failed: $($_.Exception.Message)"
}
#endregion Service Connectivity Check
#region License Requirement Check
Write-PSFMessage -Level Verbose -Message "Checking Azure AD Premium license availability..."
try {
$step = "Azure AD Premium License"
$skus = Invoke-EntraRequest -Method GET -Path "/subscribedSkus" -Service "Graph" | Where-Object { $_.servicePlans.servicePlanName -match "AAD_PREMIUM" }
if ($null -eq $skus -or $skus.Count -eq 0) {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Microsoft Entra ID P1 or higher is required for activity logging"
Error = $null
})
}
else {
$skuNames = $skus.skuPartNumber | Where-Object { $_ -match "AAD_PREMIUM" } | Sort-Object -Unique | Join-String -Separator ', '
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Passed"
Message = "Found necessary licenses: $skuNames"
Error = $null
})
Write-PSFMessage -Level Verbose -Message "License check passed: $skuNames"
}
}
catch {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Azure AD Premium P1 or higher is required for activity logging. Unable to verify license."
Error = $_.Exception.Message
})
Write-PSFMessage -Level Debug -Message "License check failed: $($_.Exception.Message)"
}
#endregion License Requirement Check
#region Diagnostic Settings Check
# This will verify that diagnostic settings are properly configured for MicrosoftGraphActivityLogs
Write-PSFMessage -Level Verbose -Message "Checking diagnostic settings for MicrosoftGraphActivityLogs..."
try {
$step = "Diagnostic Settings Configuration"
$uri = "/providers/microsoft.aadiam/diagnosticSettings"
$diagSettings = Invoke-EntraRequest -Method GET -Path $uri -Service "Azure" -Query @{ 'api-version' = '2017-04-01-preview' } | Where-Object { $_.properties.logs -match "MicrosoftGraphActivityLogs" } -DebugAction SilentlyContinue
if ($null -eq $diagSettings -or $diagSettings.Count -eq 0) {
Write-PSFMessage -Level Debug -Message "No diagnostic settings found for MicrosoftGraphActivityLogs"
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "MicrosoftGraphActivityLogs diagnostic settings are not configured or could not be retrieved"
Error = $null
})
}
else {
foreach ($setting in $diagSettings) {
if ($setting.properties.logs -match "MicrosoftGraphActivityLogs") {
Write-PSFMessage -Level Debug -Message "Found diagnostic setting: $($setting.name)"
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Passed"
Message = "MicrosoftGraphActivityLogs diagnostic settings are configured in setting: $($setting.name) - Workspace: $($setting.properties.workspaceId)"
Error = $null
})
}
}
Write-PSFMessage -Level Verbose -Message "Diagnostic settings check passed"
}
}
catch {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Cannot retrieve diagnostic settings for MicrosoftGraphActivityLogs"
Error = $_.Exception.Message
})
Write-PSFMessage -Level Verbose -Message "Diagnostic settings check failed: $($_.Exception.Message)"
}
#endregion Diagnostic Settings Check
#region Log Analytics Access Check
Write-PSFMessage -Level Verbose -Message "Verifying Log Analytics workspace access and data availability..."
try {
$kqlQuery = @"
MicrosoftGraphActivityLogs
| take 1
"@
$body = @{
query = $kqlQuery
options = @{
truncationMaxSize = 67108864
}
workspaceFilters = @{
regions = @()
}
}
$step = "Log Analytics Workspace Access"
$response = Invoke-EntraRequest -Service "LogAnalytics" -Method POST -Path "/v1$($diagSettings.properties.workspaceId)/query" -Body ($body | ConvertTo-Json -Depth 15)
if ($null -eq $response.tables -or $null -eq $response.tables.rows -or $response.tables.rows.Count -eq 0) {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "No MicrosoftGraphActivityLogs data found in workspace $WorkspaceId. Ensure diagnostic settings are correctly configured. And you have waited sufficient time for data to populate."
Error = $null
})
}
else {
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Passed"
Message = "Successfully queried workspace $WorkspaceId and found MicrosoftGraphActivityLogs data"
Error = $null
})
Write-PSFMessage -Level Verbose -Message "Log Analytics access check passed"
}
}
catch {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Cannot access or query Log Analytics workspace. Ensure you have proper access permissions. Least privileged role 'Log Analytics Reader' on the Log Analytics workspace."
Error = $_.Exception.Message
})
Write-PSFMessage -Level Debug -Message "Log Analytics access check failed: $($_.Exception.Message)"
}
#endregion Log Analytics Access Check
#region Microsoft Graph API Permissions Check
Write-PSFMessage -Level Verbose -Message "Verifying Microsoft Graph API permissions..."
try {
$step = "Microsoft Graph API Permissions"
Invoke-EntraRequest -Method GET -Path "/applications" -Service "Graph" -Query @{ '$top' = '1' } -NoPaging | Out-Null
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Passed"
Message = "Successfully retrieved applications from Microsoft Graph"
Error = $null
})
Write-PSFMessage -Level Verbose -Message "Microsoft Graph permissions check passed"
}
catch {
$overallSuccess = $false
[void]$testResults.Add([PSCustomObject]@{
Name = $step
Status = "Failed"
Message = "Cannot read applications from Microsoft Graph. Requires Application.Read.All permission or application reader role."
Error = $_.Exception.Message
})
Write-PSFMessage -Level Debug -Message "Microsoft Graph permissions check failed: $($_.Exception.Message)"
}
#endregion Microsoft Graph API Permissions Check
# Build final result object
$result = [PSCustomObject]@{
OverallStatus = if ($overallSuccess) {
"Passed"
}
else {
"Failed"
}
Checks = $testResults.ToArray()
TenantId = $currentTenantId
Timestamp = [datetime]::UtcNow
}
return $result
}