-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMSGraph.psm1
More file actions
440 lines (376 loc) · 13.7 KB
/
MSGraph.psm1
File metadata and controls
440 lines (376 loc) · 13.7 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<#
ClientId for DSRE Graph Query, used instead of public PS endpoint. Uses delegated permissions:
Azure Active Directory Graph
Directory.AccessAsUser.All Delegated Access the directory as the signed-in user
User.Read Delegated Sign in and read user profile
Microsoft Graph
Directory.AccessAsUser.All Delegated Access directory as the signed in user
IdentityRiskEvent.Read.All Delegated Read identity risk event information
IdentityRiskyUser.Read.All Delegated Read identity risky user information
#>
#$MSGAuthInfo.ClientId = "392aec2b-77bb-4316-9325-75c4f472c545"
<#
Class or hashtable ...
class MSGEnvironment
{
[string]$Name
[string]$AzureEndpoint
[string]$GraphEndpoint
MSGEnvironment(
[string]$n,
[string]$a,
[string]$g
)
{
$this.Name = $n
$this.AzureEndpoint = $a
$this.GraphEndpoint = $g
}
}
[System.Collections.ArrayList]$msgEnvironmentTable = @(
[MSGEnvironment]::new("AzurePPE", "https://login.windows-ppe.net", "https://graph.microsoft-ppe.com"),
[MSGEnvironment]::new("AzureCloud", "https://login.microsoftonline.com", "https://graph.microsoft.com"),
[MSGEnvironment]::new("AzureUSGovernment", "https://login.microsoftonline.us", "https://graph.microsoft.us")
[MSGEnvironment]::new("AzureUSDoD", "https://login.microsoftonline.us", "https://dod-graph.microsoft.us" )
)
#>
$msgEnvironmentTable = @{
'AzurePPE' = @('https://login.windows-ppe.net', 'https://graph.microsoft-ppe.com')
'AzureCloud' = @('https://login.microsoftonline.com', 'https://graph.microsoft.com')
'AzureUSGovernment' = @('https://login.microsoftonline.us', 'https://graph.microsoft.us')
'AzureUSDoD' = @('https://login.microsoftonline.us', 'https://dod-graph.microsoft.us')
}
function Connect-MSG
{
<#
.SYNOPSIS
Connects user to Azure AD
.DESCRIPTION
Connects with an authenticated account to use MSGraph cmdlets
.PARAMETER AccountId
Specifies the ID of an account.
.PARAMETER ApplicationId
Specifies the application ID of the service principal.
.PARAMETER AzureEnvironmentName
Specifies the name of the Azure environment. The acceptable values for this parameter are:
- AzureCloud
- AzurePPE
The default value is AzureCloud.
.PARAMETER CertificateName
Specifies the certificate of a digital public key X.509 certificate
.PARAMETER CertificateThumbprint
Specifies the certificate thumbprint of a digital public key X.509 certificate
.PARAMETER Force
Forces a complete re-authentication instead of refresh of existing session.
.PARAMETER GraphVersion
Specifies the version of MSGraph to use. The acceptable values for this parameter are:
- V1.0
- beta
The default value is beta
.PARAMETER StoreLocation
Specifies the store location to use for certificate lookup to use. The acceptable values for this parameter are:
- CurrentUser
- LocalMachine
The default value is CurrentUser
.PARAMETER KeyVaultURI
Specifies the full URI for the KeyVault to use, e.g. https://mykv.vault.azure.net
.PARAMETER KeyVaultSecret
Specified the name of the secret to retrieve from KeyVault for authentication
.PARAMETER TenantId
Specifies the ID of a tenant.
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignment', '')]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')]
[CmdletBinding(DefaultParameterSetName = 'User')]
param(
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[string]$TenantId,
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[ValidateSet(
'v1.0',
'beta')]
[string]$GraphVersion,
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[ValidateSet(
'AzurePPE',
'AzureCloud',
'AzureUSGovernment',
'AzureUSDoD')]
[string]$AzureEnvironmentName,
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[ValidateNotNullOrEmpty()]
[string]$CertificateThumbprint,
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[ValidateNotNullOrEmpty()]
[string]$CertificateName,
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[ValidateNotNullOrEmpty()]
[ValidateSet(
'LocalMachine',
'CurrentUser',
'KeyVault')]
[string]$StoreLocation,
[Parameter(Mandatory = $False,
ParameterSetName = 'User')]
[ValidateNotNullOrEmpty()]
[string]$AccountId,
[Parameter(Mandatory = $False,
ParameterSetName = 'User')]
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[Alias('ClientId')]
[ValidatePattern('^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$')]
[string]$ApplicationId,
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[string]$KeyVaultURI,
[Parameter(Mandatory = $False,
ParameterSetName = 'AppId')]
[string]$KeyVaultSecret,
[Parameter(Mandatory = $False)]
[switch]$Force
)
begin
{
if ($null -eq $global:_MSGMaxRetry)
{
Set-Variable -Name _MSGMaxRetry -Scope Global -Value 5 -Option ReadOnly
}
$MSGConfig = Get-MSGConfig
$isInitialized = ($MSGConfig.Initialized -eq $true)
#region Validation
if ([string]::IsNullOrEmpty($AzureEnvironmentName))
{
if ([string]::IsNullOrEmpty($MSGConfig.Environment))
{
$AzureEnvironmentName = 'AzureCloud'
}
else
{
$AzureEnvironmentName = $MSGConfig.Environment
}
}
if ([string]::IsNullOrEmpty($StoreLocation))
{
if ([string]::IsNullOrEmpty($MSGConfig.StoreLocation))
{
$StoreLocation = 'CurrentUser'
}
else
{
$StoreLocation = $MSGConfig.StoreLocation
}
}
if ([string]::IsNullOrEmpty($TenantId))
{
if (-not [string]::IsNullOrEmpty($MSGConfig.TenantId))
{
$TenantId = $MSGConfig.TenantId
}
elseif (-not [string]::IsNullOrEmpty($MSGConfig.TenantDomain))
{
$TenantId = $MSGConfig.TenantDomain
}
else
{
$TenantId = $TenantDomain = 'microsoft.onmicrosoft.com'
}
}
if ([string]::IsNullOrEmpty($GraphVersion))
{
if ([string]::IsNullOrEmpty($MSGConfig.GraphVersion))
{
$GraphVersion = 'beta'
}
else
{
$GraphVersion = $MSGConfig.GraphVersion
}
}
if ([string]::IsNullOrEmpty($ApplicationId))
{
if ([string]::IsNullOrEmpty($MSGConfig.ApplicationId))
{
$ApplicationId = '1b730954-1685-4b74-9bfd-dac224a7b894'
}
else
{
$ApplicationId = $MSGConfig.ApplicationId
}
}
# Validate KeyVault parameters
if ($PSBoundParameters['StoreLocation'] -eq 'KeyVault')
{
if ([string]::IsNullOrEmpty($PSBoundParameters['KeyVaultURI']))
{
throw 'A KeyVault URI must be supplied'
}
}
#endregion Validation
$msgEnvironment = $msgEnvironmentTable[$AzureEnvironmentName]
$MSGAuthInfo = [PSCustomObject]@{
TenantDomain = $TenantDomain
TenantId = $TenantId
GraphVersion = $GraphVersion
ApplicationId = $ApplicationId
Environment = $AzureEnvironmentName
User = $AccountId
AuthType = $Null
StoreLocation = $StoreLocation
KeyVaultURI = $KeyVaultURI
Initialized = $isInitialized
GraphUrl = $msgEnvironment[1]
Authority = $msgEnvironment[0]
}
Set-MSGConfig -ConfigObject $MSGAuthInfo
}
process
{
$MSGAuthInfo = Get-MSGConfig
$Params = @{
Tenant = $MSGAuthInfo.TenantId
ClientId = $MSGAuthInfo.ApplicationId
GraphEndPoint = $MSGAuthInfo.GraphUrl
Authority = $MSGAuthInfo.Authority
}
switch ($PsCmdlet.ParameterSetName.ToLower())
{
'user'
{
if (-not [string]::IsNullOrEmpty($AccountId))
{
$Params.Add('AccountId', $AccountId)
}
if ($Force)
{
$Params.Add('Force', $Force)
}
$MSGAuthInfo.AuthType = 'User'
Set-MSGConfig -ConfigObject $MSGAuthInfo
$res = Get-UserAuthenticationResult @Params -Debug:$DebugPreference -Verbose:$VerbosePreference
break
}
'appid'
{
$Params.Add('StoreLocation', $StoreLocation)
if (-not [string]::IsNullOrEmpty($CertificateThumbprint))
{
$Params.Add('Thumbprint', $CertificateThumbprint)
Add-Member -InputObject $MSGAuthInfo -MemberType NoteProperty -Name ThumbPrint -Value $CertificateThumbprint
}
elseif (-not [string]::IsNullOrEmpty($CertificateName))
{
$Params.Add('CertificateName', $CertificateName)
Add-Member -InputObject $MSGAuthInfo -MemberType NoteProperty -Name Certificate -Value $CertificateName
}
else
{
throw 'Missing thumbprint or name for certificate to use'
}
$MSGAuthInfo.AuthType = 'App'
$MSGAuthInfo.User = $MSGAuthInfo.ApplicationId
Set-MSGConfig -ConfigObject $MSGAuthInfo
$res = Get-AppAuthenticationResult @Params -Debug:$DebugPreference -Verbose:$VerbosePreference
break
}
}
$authInfo = Get-AzureAdAccessTokenInfo -AccessToken ($res -split ' ')[1]
$script:scopes = $authInfo.scp
$MSGAuthInfo = Get-MSGConfig
$MSGAuthInfo.Initialized = $true
$MSGAuthInfo.TenantId = $authInfo.tid
if (![string]::IsNullOrEmpty($authInfo.upn))
{
$MSGAuthInfo.User = $authInfo.upn
}
Set-MSGConfig -ConfigObject $MSGAuthInfo
$MSGAuthInfo.TenantDomain = ((Get-MSGOrganization -Properties verifieddomains).verifiedDomains | Where-Object isDefault -EQ $true).name
Set-MSGConfig -ConfigObject $MSGAuthInfo
if ($MSGAuthInfo.AuthType -eq 'User' -and $global:PIMRoleDictionary.Count -le 1)
{
Write-Verbose 'Setting up PIM role information ...'
<#
Yes, I hate using a global variable but the retrieval calls can be expensive so I persist through each invocation of Connect-MSG
#>
$global:PIMRoleDictionary = New-RoleMapping
Write-Verbose 'Done!'
}
Get-MSGCurrentSession
}
}
function Get-MSGCurrentSession
{
<#
.SYNOPSIS
Returns the current session information
.DESCRIPTION
Returns the current session information
.EXAMPLE
Get-MSGCurrentSession
Account Environment TenantId TenantDomain AccountType
------- ----------- -------- ------------ -----------
myuser@microsoft.com AzureCloud 72f988bf-86f1-41af-91ab-2d7cd011db47 microsoft.onmicrosoft.com User
#>
begin
{
$MSGAuthInfo = Get-MSGConfig
}
process
{
if ([string]::IsNullOrEmpty($MSGAuthInfo.TenantDomain))
{
$MSGAuthInfo.TenantDomain = ((Get-MSGOrganization -Properties verifieddomains).verifiedDomains | Where-Object isDefault -EQ $true).name
}
[PSCustomObject][Ordered]@{
PSTypeName = 'MSGraph.Account'
Account = $MSGAuthInfo.User
Environment = $MSGAuthInfo.Environment
Scopes = $script:scopes -split ' '
TenantId = $MSGAuthInfo.TenantId
TenantDomain = $MSGAuthInfo.TenantDomain
AccountType = if ($MSGAuthInfo.AuthType -eq 'App')
{
'ServicePrincipal'
}
else
{
$MSGAuthInfo.AuthType
}
}
}
}
function Get-MSGProfile
{
$MSGAuthInfo = Get-MSGConfig
[PSCustomObject]@{
Name = $MSGAuthInfo.GraphVersion
Description = "Microsoft Graph $($MSGAuthInfo.GraphVersion) API version"
}
}
function Set-MSGProfile
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateSet(
'v1.0',
'beta')]
[string]$GraphVersion
)
$MSGAuthInfo = Get-MSGConfig
$MSGAuthInfo.GraphVersion = $GraphVersion
Set-MSGConfig -ConfigObject $MSGAuthInfo
}
function Get-MSGEnvironmentList
{
$msgEnvironmentTable
}