-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGet-GraphScriptPermissions.ps1
More file actions
291 lines (212 loc) · 7.8 KB
/
Get-GraphScriptPermissions.ps1
File metadata and controls
291 lines (212 loc) · 7.8 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
<#PSScriptInfo
.VERSION 1.0.0
.DESCRIPTION Analyze a PowerShell script for Microsoft Graph cmdlets and required permissions.
.GUID e452ad1e-a89e-4160-9356-c97415e6cc37
.AUTHOR Gabriel Delaney
.COMPANYNAME Phoenix Horizons LLC
.COPYRIGHT 2025 Phoenix Horizons LLC
.TAGS Graph, PowerShell, Permissions
.LICENSEURI https://github.com/TheTolkienBlackGuy/Get-GraphScriptPermissions/blob/main/LICENSE
.PROJECTURI https://github.com/TheTolkienBlackGuy/Get-GraphScriptPermissions
.ICONURI
.EXTERNALMODULEDEPENDENCIES Microsoft.Graph.Authentication
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES Initial release
.PRIVATEDATA
#>
<#
.SYNOPSIS
Analyze a PowerShell script for Microsoft Graph cmdlets and required permissions.
.DESCRIPTION
Parses a script, finds Microsoft Graph cmdlets, and returns the least privileged
and full permission sets for each. Optionally exports the results.
.PARAMETER ScriptPath
The path to the script file to analyze.
.PARAMETER OutputPath
Optional path to export results as CSV.
.EXAMPLE
.\Get-GraphScriptPermissions.ps1 -ScriptPath .\myscript.ps1
.EXAMPLE
.\Get-GraphScriptPermissions.ps1 -ScriptPath .\myscript.ps1 -OutputPath .\permissions.csv
.INPUTS
System.String
.OUTPUTS
System.Object[]
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[ValidateScript({Test-Path -Path $_})]
[string]$ScriptPath,
[Parameter(Mandatory=$false,Position=1)]
[string]$OutputPath
)
#requires -Modules Microsoft.Graph.Authentication
#region Helper functions
# Function to find the Graph cmdlets in a script
Function Find-GraphCmdletString {
<#
.SYNOPSIS
Extracts cmdlets that query the Graph API from a script.
.DESCRIPTION
Extracts cmdlets that query the Graph API from a script.
.PARAMETER Content
The content of the script to search.
.EXAMPLE
Find-GraphCmdletString -Content $script_content
.EXAMPLE
Get-Content -Path $script_path | Find-GraphCmdletString
.INPUTS
System.String
.OUTPUTS
System.Object[]
#>
[CmdletBinding()]
[OutputType([system.object[]])]
Param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[object]$Content
)
Begin {
# Get the cmdlets that do not query the Graph API
$exclusions = (Get-Command -Module Microsoft.Graph.Authentication).Name
# Get the approved verbs
$approved_verbs = (Get-Verb).Verb
# Create a regex pattern to match the approved verbs followed by -Mg and any alphanumeric characters
$pattern = "($($approved_verbs -join '|'))-Mg\w+"
# Initialize an array to store the results
$line_number = 0
} Process {
foreach ($line in $content) {
# Increment the line number
$line_number++
# Skip empty lines
If (!$line) {
continue
}
# Remove comments
$line = $line -replace '\s*#.*$',''
# Skip lines that are just comments. Currently doesn't support block comments.
if ($line.Trim().StartsWith("#")) {
continue
}
# Find all cmdlets in the line
$cmdlet_matches = ($line | Select-String -Pattern $pattern -AllMatches).Matches.Value
foreach ($cmdlet in $cmdlet_matches) {
# Microsoft.Graph.Authentication do not query the Graph API so we can ignore them
If ($cmdlet -in $exclusions) {
continue
}
$obj = [ordered] @{}
# Add the cmdlet to the object
$obj["Cmdlet"] = $cmdlet
$obj["Line"] = $line.Trim()
$obj["LineNumber"] = $line_number
[pscustomobject]$obj
}
}
}
}
# Function to get the permissions for a given Graph cmdlet
Function Get-GraphCmdletPermissions {
<#
.SYNOPSIS
Wrapper for Find-MgGraphCommand that extracts permissions.
.DESCRIPTION
For a given Graph cmdlet, returns the least privileged permission,
all valid permissions, and the cmdlet name.
.PARAMETER Cmdlet
The Graph cmdlet to query.
.EXAMPLE
Get-GraphCmdletPermissions -Cmdlet Get-MgUser
.INPUTS
System.String
.OUTPUTS
System.Object
#>
[CmdletBinding()]
[OutputType([System.Object])]
Param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Cmdlet,
[Parameter(Mandatory=$false,Position=1)]
[string]$ApiVersion = "v1.0"
)
Begin {
# Create the parameters for Find-MgGraphCommand
$find_cmd_params = @{}
$find_cmd_params["Command"] = $cmdlet
$find_cmd_params["ApiVersion"] = $apiVersion
# Initialize the has_scope variable
$has_scope = $false
# Get the Graph context
$context = Get-MgContext
# If the context is not authenticated with Microsoft Graph, throw a warning
If ($context) {
$current_scopes = $context.Scopes
}
} Process {
Try {
# Get the permissions for the cmdlet
$permissions = (Find-MgGraphCommand @find_cmd_params ).Permissions | Where-Object {
$_.FullDescription -notlike "Allows you*" -and $_.FullDescription -notmatch "\byour\b"
}
} Catch {
Write-Error "$($_.Exception.Message)" -ErrorAction Stop
}
# Check if the current scopes have any of the permissions
Foreach ($scope in $current_scopes) {
If ($scope -in $permissions.Name) {
$has_scope = $true
Break
}
}
# Create the object
$obj = [ordered] @{}
$obj["Cmdlet"] = $cmdlet
$obj["LeastPrivilegedEffectivePermission"] = If ($permissions) { $permissions[0].Name } Else { "None" }
$obj["Description"] = If ($permissions) { $permissions[0].Description } Else { "None" }
$obj["Permissions"] = If ($permissions) { ($permissions.Name | Select-Object -Unique) -join ", " } Else { "None" }
$obj["HasScope"] = $has_scope
} End {
# Return the object
[pscustomobject]$obj
}
}
#endregion
#region Main
# Initialize the results list
$results = [System.Collections.Generic.List[System.Object]]::new()
# Get the script content
$script_content = Get-Content -Path $scriptPath
# Find the Graph cmdlets in the script
$graph_cmdlets = $script_content | Find-GraphCmdletString
# Group by cmdlet and merge line numbers
$grouped = $graph_cmdlets | Group-Object -Property Cmdlet
# Get the permissions for each Graph cmdlet
foreach ($group in $grouped) {
$perm_info = Get-GraphCmdletPermissions -Cmdlet $group.Name
# Create the object
$obj = [ordered] @{}
$obj["Cmdlet"] = $group.Name
$obj["LineNumbers"] = ($group.Group.LineNumber -join ", ")
$obj["LeastPrivilegedEffectivePermission"] = $perm_info.LeastPrivilegedEffectivePermission
$obj["Description"] = $perm_info.Description
$obj["Permissions"] = $perm_info.Permissions | Select-Object -Unique
$obj["HasScope"] = $perm_info.HasScope
# Add the object to the results list
[void]$results.Add([pscustomobject]$obj)
}
#endregion
#region Output
if ($outputPath) {
try {
$results | Export-Csv -Path $outputPath -NoTypeInformation -Force
Write-Output "Results exported to $outputPath"
} catch {
Write-Warning "Failed to export results to $outputPath. $($_.Exception.Message)"
}
}
$results
#endregion