forked from KelvinTegelaar/CIPP-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphHelper.psm1
667 lines (601 loc) · 35.2 KB
/
GraphHelper.psm1
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
function Get-CIPPTable {
[CmdletBinding()]
param (
$tablename = 'CippLogs'
)
$Context = New-AzDataTableContext -ConnectionString $env:AzureWebJobsStorage -TableName $tablename
New-AzDataTable -Context $Context | Out-Null
@{
Context = $Context
}
}
function Get-NormalizedError {
[CmdletBinding()]
param (
[string]$message
)
switch -Wildcard ($message) {
'Request not applicable to target tenant.' { 'Required license not available for this tenant' }
"Neither tenant is B2C or tenant doesn't have premium license" { 'This feature requires a P1 license or higher' }
'Response status code does not indicate success: 400 (Bad Request).' { 'Error 400 occured. There is an issue with the token configuration for this tenant. Please perform an access check' }
'*Microsoft.Skype.Sync.Pstn.Tnm.Common.Http.HttpResponseException*' { 'Could not connect to Teams Admin center - Tenant might be missing a Teams license' }
'*Provide valid credential.*' { 'Error 400: There is an issue with your Exchange Token configuration. Please perform an access check for this tenant' }
'*This indicate that a subscription within the tenant has lapsed*' { 'There is no exchange subscription available, or it has lapsed. Check licensing information.' }
'*User was not found.*' { 'The relationship between this tenant and the partner has been dissolved from the tenant side.' }
'*The user or administrator has not consented to use the application*' { 'AADSTS65001: The user you have used for your Secure Application Model is a guest in this tenant, or your are using GDAP and have not added the user to the correct group. Please delete the guest user to gain access to this tenant' }
'*AADSTS50020*' { 'AADSTS50020: The user you have used for your Secure Application Model is a guest in this tenant, or your are using GDAP and have not added the user to the correct group. Please delete the guest user to gain access to this tenant' }
'*invalid or malformed*' { 'The request is malformed. You have entered incorrect tokens or have not performed a clear of the token cache after entering new tokens. Please see the troubleshooting documentation on how to execute a clear of the token cache.' }
'*Windows Store repository apps feature is not supported for this tenant*' { 'This tenant does not have WinGet support available' }
'*AADSTS650051*' { 'The application does not exist yet. Try again in 30 seconds.' }
'*AppLifecycle_2210*' { 'Failed to call Intune APIs: Does the tenant have a license available?' }
Default { $message }
}
}
function Get-GraphToken($tenantid, $scope, $AsApp, $AppID, $refreshToken, $ReturnRefresh) {
if (!$scope) { $scope = 'https://graph.microsoft.com/.default' }
$AuthBody = @{
client_id = $env:ApplicationID
client_secret = $env:ApplicationSecret
scope = $Scope
refresh_token = $env:RefreshToken
grant_type = 'refresh_token'
}
if ($asApp -eq $true) {
$AuthBody = @{
client_id = $env:ApplicationID
client_secret = $env:ApplicationSecret
scope = $Scope
grant_type = 'client_credentials'
}
}
if ($null -ne $AppID -and $null -ne $refreshToken) {
$AuthBody = @{
client_id = $appid
refresh_token = $RefreshToken
scope = $Scope
grant_type = 'refresh_token'
}
}
if (!$tenantid) { $tenantid = $env:TenantID }
try {
$AccessToken = (Invoke-RestMethod -Method post -Uri "https://login.microsoftonline.com/$($tenantid)/oauth2/v2.0/token" -Body $Authbody -ErrorAction Stop)
if ($ReturnRefresh) { $header = $AccessToken } else { $header = @{ Authorization = "Bearer $($AccessToken.access_token)" } }
return $header
Write-Host $header['Authorization']
}
catch {
# Track consecutive Graph API failures
$TenantsTable = Get-CippTable -tablename Tenants
$Filter = "PartitionKey eq 'Tenants' and (defaultDomainName eq '{0}' or customerId eq '{0}')" -f $tenantid
$Tenant = Get-AzDataTableEntity @TenantsTable -Filter $Filter
if (!$Tenant.RowKey) {
$donotset = $true
$Tenant = [pscustomobject]@{
GraphErrorCount = $null
LastGraphTokenError = $null
LastGraphError = $null
PartitionKey = 'TenantFailed'
RowKey = 'Failed'
}
}
$Tenant.LastGraphError = if ( $_.ErrorDetails.Message) {
$msg = $_.ErrorDetails.Message | ConvertFrom-Json
"$($msg.error):$($msg.error_description)"
}
else {
$_.Exception.message
}
$Tenant.GraphErrorCount++
if (!$donotset) { Update-AzDataTableEntity @TenantsTable -Entity $Tenant }
throw "$($Tenant.LastGraphError)"
}
}
function Write-LogMessage ($message, $tenant = 'None', $API = 'None', $user, $sev) {
$username = ([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($user)) | ConvertFrom-Json).userDetails
$Table = Get-CIPPTable -tablename CippLogs
if (!$tenant) { $tenant = 'None' }
if (!$username) { $username = 'CIPP' }
if ($sev -eq 'Debug' -and $env:DebugMode -ne 'true') {
Write-Information 'Not writing to log file - Debug mode is not enabled.'
return
}
$PartitionKey = (Get-Date -UFormat '%Y%m%d').ToString()
$TableRow = @{
'Tenant' = [string]$tenant
'API' = [string]$API
'Message' = [string]$message
'Username' = [string]$username
'Severity' = [string]$sev
'SentAsAlert' = $false
'PartitionKey' = $PartitionKey
'RowKey' = ([guid]::NewGuid()).ToString()
}
$Table.Entity = $TableRow
Add-AzDataTableEntity @Table | Out-Null
}
function New-GraphGetRequest {
Param(
$uri,
$tenantid,
$scope,
$AsApp,
$noPagination,
$NoAuthCheck,
[switch]$ComplexFilter,
[switch]$CountOnly
)
if ($scope -eq 'ExchangeOnline') {
$AccessToken = Get-ClassicAPIToken -resource 'https://outlook.office365.com' -Tenantid $tenantid
$headers = @{ Authorization = "Bearer $($AccessToken.access_token)" }
}
else {
$headers = Get-GraphToken -tenantid $tenantid -scope $scope -AsApp $asapp
}
if ($ComplexFilter) {
$headers['ConsistencyLevel'] = 'eventual'
}
Write-Verbose "Using $($uri) as url"
$nextURL = $uri
# Track consecutive Graph API failures
$TenantsTable = Get-CippTable -tablename Tenants
$Filter = "PartitionKey eq 'Tenants' and (defaultDomainName eq '{0}' or customerId eq '{0}')" -f $tenantid
$Tenant = Get-AzDataTableEntity @TenantsTable -Filter $Filter
if (!$Tenant) {
$Tenant = @{
GraphErrorCount = 0
LastGraphError = $null
PartitionKey = 'TenantFailed'
RowKey = 'Failed'
}
}
if ((Get-AuthorisedRequest -Uri $uri -TenantID $tenantid) -or $NoAuthCheck) {
$ReturnedData = do {
try {
$Data = (Invoke-RestMethod -Uri $nextURL -Method GET -Headers $headers -ContentType 'application/json; charset=utf-8')
if ($CountOnly) {
$Data.'@odata.count'
$nextURL = $null
}
else {
if ($data.value) { $data.value } else { ($Data) }
if ($noPagination) { $nextURL = $null } else { $nextURL = $data.'@odata.nextLink' }
}
}
catch {
$Message = ($_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue).error.message
if ($Message -eq $null) { $Message = $($_.Exception.Message) }
if ($Message -ne 'Request not applicable to target tenant.') {
$Tenant.LastGraphError = $Message
$Tenant.GraphErrorCount++
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
}
throw $Message
}
} until ($null -eq $NextURL)
$Tenant.LastGraphError = ''
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
return $ReturnedData
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function New-GraphPOSTRequest ($uri, $tenantid, $body, $type, $scope, $AsApp, $NoAuthCheck) {
$headers = Get-GraphToken -tenantid $tenantid -scope $scope -AsApp $asapp
Write-Verbose "Using $($uri) as url"
if (!$type) {
$type = 'POST'
}
if ((Get-AuthorisedRequest -Uri $uri -TenantID $tenantid) -or $NoAuthCheck) {
try {
$ReturnedData = (Invoke-RestMethod -Uri $($uri) -Method $TYPE -Body $body -Headers $headers -ContentType 'application/json; charset=utf-8')
}
catch {
$Message = ($_.ErrorDetails.Message | ConvertFrom-Json -ErrorAction SilentlyContinue).error.message
if ($Message -eq $null) { $Message = $($_.Exception.Message) }
throw $Message
}
return $ReturnedData
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function convert-skuname($skuname, $skuID) {
Set-Location (Get-Item $PSScriptRoot).FullName
$ConvertTable = Import-Csv Conversiontable.csv
if ($skuname) { $ReturnedName = ($ConvertTable | Where-Object { $_.String_Id -eq $skuname } | Select-Object -Last 1).'Product_Display_Name' }
if ($skuID) { $ReturnedName = ($ConvertTable | Where-Object { $_.guid -eq $skuid } | Select-Object -Last 1).'Product_Display_Name' }
if ($ReturnedName) { return $ReturnedName } else { return $skuname, $skuID }
}
function Get-ClassicAPIToken($tenantID, $Resource) {
Write-Host 'Using classic'
$uri = "https://login.microsoftonline.com/$($TenantID)/oauth2/token"
$Body = @{
client_id = $env:ApplicationID
client_secret = $env:ApplicationSecret
resource = $Resource
refresh_token = $env:RefreshToken
grant_type = 'refresh_token'
}
try {
$token = Invoke-RestMethod $uri -Body $body -ContentType 'application/x-www-form-urlencoded' -ErrorAction SilentlyContinue -Method post
return $token
}
catch {
# Track consecutive Graph API failures
$TenantsTable = Get-CippTable -tablename Tenants
$Filter = "PartitionKey eq 'Tenants' and (defaultDomainName eq '{0}' or customerId eq '{0}')" -f $tenantid
$Tenant = Get-AzDataTableEntity @TenantsTable -Filter $Filter
if (!$Tenant) {
$Tenant = @{
GraphErrorCount = $null
LastGraphTokenError = $null
PartitionKey = 'TenantFailed'
RowKey = 'Failed'
}
}
$Tenant.LastGraphError = $_.Exception.Message
$Tenant.GraphErrorCount++
Update-AzDataTableEntity @TenantsTable -Entity $Tenant
Throw "Failed to obtain Classic API Token for $TenantID - $_"
}
}
function New-TeamsAPIGetRequest($Uri, $tenantID, $Method = 'GET', $Resource = '48ac35b8-9aa8-4d74-927d-1f4a14a0b239', $ContentType = 'application/json') {
$token = Get-ClassicAPIToken -Tenant $tenantid -Resource $Resource
$NextURL = $Uri
if ((Get-AuthorisedRequest -Uri $uri -TenantID $tenantid)) {
$ReturnedData = do {
try {
$Data = Invoke-RestMethod -ContentType "$ContentType;charset=UTF-8" -Uri $NextURL -Method $Method -Headers @{
Authorization = "Bearer $($token.access_token)";
'x-ms-client-request-id' = [guid]::NewGuid().ToString();
'x-ms-client-session-id' = [guid]::NewGuid().ToString()
'x-ms-correlation-id' = [guid]::NewGuid()
'X-Requested-With' = 'XMLHttpRequest'
'x-ms-tnm-applicationid' = '045268c0-445e-4ac1-9157-d58f67b167d9'
}
$Data
if ($noPagination) { $nextURL = $null } else { $nextURL = $data.NextLink }
}
catch {
throw "Failed to make Teams API Get Request $_"
}
} until ($null -eq $NextURL)
return $ReturnedData
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function New-ClassicAPIGetRequest($TenantID, $Uri, $Method = 'GET', $Resource = 'https://admin.microsoft.com', $ContentType = 'application/json') {
$token = Get-ClassicAPIToken -Tenant $tenantID -Resource $Resource
$NextURL = $Uri
if ((Get-AuthorisedRequest -Uri $uri -TenantID $tenantid)) {
$ReturnedData = do {
try {
$Data = Invoke-RestMethod -ContentType "$ContentType;charset=UTF-8" -Uri $NextURL -Method $Method -Headers @{
Authorization = "Bearer $($token.access_token)";
'x-ms-client-request-id' = [guid]::NewGuid().ToString();
'x-ms-client-session-id' = [guid]::NewGuid().ToString()
'x-ms-correlation-id' = [guid]::NewGuid()
'X-Requested-With' = 'XMLHttpRequest'
}
$Data
if ($noPagination) { $nextURL = $null } else { $nextURL = $data.NextLink }
}
catch {
throw "Failed to make Classic Get Request $_"
}
} until ($null -eq $NextURL)
return $ReturnedData
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function New-ClassicAPIPostRequest($TenantID, $Uri, $Method = 'POST', $Resource = 'https://admin.microsoft.com', $Body) {
$token = Get-ClassicAPIToken -Tenant $tenantID -Resource $Resource
if ((Get-AuthorisedRequest -Uri $uri -TenantID $tenantid)) {
try {
$ReturnedData = Invoke-RestMethod -ContentType 'application/json;charset=UTF-8' -Uri $Uri -Method $Method -Body $Body -Headers @{
Authorization = "Bearer $($token.access_token)";
'x-ms-client-request-id' = [guid]::NewGuid().ToString();
'x-ms-client-session-id' = [guid]::NewGuid().ToString()
'x-ms-correlation-id' = [guid]::NewGuid()
'X-Requested-With' = 'XMLHttpRequest'
'X-RequestForceAuthentication' = $true
}
}
catch {
throw "Failed to make Classic Get Request $_"
}
return $ReturnedData
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function Get-AuthorisedRequest($TenantID, $Uri) {
if ($uri -like 'https://graph.microsoft.com/beta/contracts*' -or $uri -like '*/customers/*' -or $uri -eq 'https://graph.microsoft.com/v1.0/me/sendMail' -or $uri -like '*/tenantRelationships/*') {
return $true
}
if ($TenantID -in (Get-Tenants).defaultDomainName) {
return $true
}
else {
return $false
}
}
function Get-Tenants {
param (
[Parameter( ParameterSetName = 'Skip', Mandatory = $True )]
[switch]$SkipList,
[Parameter( ParameterSetName = 'Standard')]
[switch]$IncludeAll,
[switch]$IncludeErrors
)
$TenantsTable = Get-CippTable -tablename 'Tenants'
$ExcludedFilter = "PartitionKey eq 'Tenants' and Excluded eq true"
$SkipListCache = Get-AzDataTableEntity @TenantsTable -Filter $ExcludedFilter
if ($IncludeAll) {
$Filter = "PartitionKey eq 'Tenants'"
}
else {
$Filter = "PartitionKey eq 'Tenants' and Excluded eq false and GraphErrorCount lt 50"
}
$IncludedTenantsCache = Get-AzDataTableEntity @TenantsTable -Filter $Filter
$LastRefresh = ($IncludedTenantsCache | Where-Object { $_.customerId } | Sort-Object LastRefresh | Select-Object -First 1).LastRefresh | Get-Date
if ($LastRefresh -lt (Get-Date).Addhours(-24).ToUniversalTime()) {
try {
Write-Host "Renewing. Cache not hit. $LastRefresh"
$TenantList = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/managedTenants/tenants?`$top=999" -tenantid $env:TenantID ) | Select-Object id, @{l = 'customerId'; e = { $_.tenantId } }, @{l = 'DefaultdomainName'; e = { [string]($_.contract.defaultDomainName) } } , @{l = 'MigratedToNewTenantAPI'; e = { $true } }, DisplayName, domains, tenantStatusInformation | Where-Object -Property defaultDomainName -NotIn $SkipListCache.defaultDomainName
}
catch {
Write-Host 'probably no license for Lighthouse. Using old API.'
}
if (!$TenantList.customerId) {
$TenantList = (New-GraphGetRequest -uri "https://graph.microsoft.com/beta/contracts?`$top=999" -tenantid $env:TenantID ) | Select-Object id, customerId, DefaultdomainName, DisplayName, domains | Where-Object -Property defaultDomainName -NotIn $SkipListCache.defaultDomainName
}
$IncludedTenantsCache = [system.collections.generic.list[hashtable]]::new()
if ($env:PartnerTenantAvailable) {
$IncludedTenantsCache.Add(@{
RowKey = $env:TenantID
PartitionKey = 'Tenants'
customerId = $env:TenantID
defaultDomainName = $env:TenantID
displayName = '*Partner Tenant'
domains = 'PartnerTenant'
Excluded = $false
ExcludeUser = ''
ExcludeDate = ''
GraphErrorCount = 0
LastGraphError = ''
LastRefresh = (Get-Date).ToUniversalTime()
}) | Out-Null
}
foreach ($Tenant in $TenantList) {
if ($Tenant.defaultDomainName -eq 'Invalid') { continue }
$IncludedTenantsCache.Add(@{
RowKey = [string]$Tenant.customerId
PartitionKey = 'Tenants'
customerId = [string]$Tenant.customerId
defaultDomainName = [string]$Tenant.defaultDomainName
displayName = [string]$Tenant.DisplayName
delegatedPrivilegeStatus = [string]$Tenant.tenantStatusInformation.delegatedPrivilegeStatus
domains = ''
Excluded = $false
ExcludeUser = ''
ExcludeDate = ''
GraphErrorCount = 0
LastGraphError = ''
LastRefresh = (Get-Date).ToUniversalTime()
}) | Out-Null
}
if ($IncludedTenantsCache) {
$TenantsTable.Force = $true
Add-AzDataTableEntity @TenantsTable -Entity $IncludedTenantsCache
}
}
if ($SkipList) {
return $SkipListCache
}
return ($IncludedTenantsCache | Sort-Object -Property displayName)
}
function Remove-CIPPCache {
param (
$TenantsOnly
)
# Remove all tenants except excluded
$TenantsTable = Get-CippTable -tablename 'Tenants'
$Filter = "PartitionKey eq 'Tenants' and Excluded eq false"
$ClearIncludedTenants = Get-AzDataTableEntity @TenantsTable -Filter $Filter
Remove-AzDataTableEntity @TenantsTable -Entity $ClearIncludedTenants
if ($tenantsonly -eq 'false') {
Write-Host 'Clearing all'
# Remove Domain Analyser cached results
$DomainsTable = Get-CippTable -tablename 'Domains'
$Filter = "PartitionKey eq 'TenantDomains'"
$ClearDomainAnalyserRows = Get-AzDataTableEntity @DomainsTable -Filter $Filter | ForEach-Object {
$_.DomainAnalyser = ''
$_
}
Update-AzDataTableEntity @DomainsTable -Entity $ClearDomainAnalyserRows
#Clear BPA
$BPATable = Get-CippTable -tablename 'cachebpa'
$ClearBPARows = Get-AzDataTableEntity @BPATable
Remove-AzDataTableEntity @BPATable -Entity $ClearBPARows
$Script:SkipListCache = $Null
$Script:SkipListCacheEmpty = $Null
$Script:IncludedTenantsCache = $Null
}
}
function New-ExoRequest ($tenantid, $cmdlet, $cmdParams, $useSystemMailbox, $Anchor) {
$token = Get-ClassicAPIToken -resource 'https://outlook.office365.com' -Tenantid $tenantid
if ((Get-AuthorisedRequest -TenantID $tenantid)) {
$tenant = (get-tenants | Where-Object -Property defaultDomainName -EQ $tenantid).customerId
if ($cmdParams) {
$Params = $cmdParams
}
else {
$Params = @{}
}
$ExoBody = ConvertTo-Json -Depth 5 -InputObject @{
CmdletInput = @{
CmdletName = $cmdlet
Parameters = $Params
}
}
if (!$Anchor) {
if ($cmdparams.Identity) { $Anchor = $cmdparams.Identity }
if ($cmdparams.anr) { $Anchor = $cmdparams.anr }
if ($cmdparams.User) { $Anchor = $cmdparams.User }
if (!$Anchor -or $useSystemMailbox) {
$OnMicrosoft = (New-GraphGetRequest -uri 'https://graph.microsoft.com/beta/domains?$top=999' -tenantid $tenantid | Where-Object -Property isInitial -EQ $true).id
$anchor = "UPN:SystemMailbox{bb558c35-97f1-4cb9-8ff7-d53741dc928c}@$($OnMicrosoft)"
}
}
Write-Host "Using $Anchor"
$Headers = @{
Authorization = "Bearer $($token.access_token)"
Prefer = 'odata.maxpagesize = 1000'
'X-AnchorMailbox' = $anchor
}
try {
$ReturnedData = Invoke-RestMethod "https://outlook.office365.com/adminapi/beta/$($tenant)/InvokeCommand" -Method POST -Body $ExoBody -Headers $Headers -ContentType 'application/json; charset=utf-8'
}
catch {
$ReportedError = ($_.ErrorDetails | ConvertFrom-Json -ErrorAction SilentlyContinue)
$Message = if ($ReportedError.error.details.message) { $ReportedError.error.details.message } else { $ReportedError.error.innererror.internalException.message }
if ($Message -eq $null) { $Message = $($_.Exception.Message) }
throw $Message
}
return $ReturnedData.value
}
else {
Write-Error 'Not allowed. You cannot manage your own tenant or tenants not under your scope'
}
}
function Read-JwtAccessDetails {
<#
.SYNOPSIS
Parse Microsoft JWT access tokens
.DESCRIPTION
Extract JWT access token details for verification
.PARAMETER Token
Token to get details for
#>
[cmdletbinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Token
)
# Default token object
$TokenDetails = [PSCustomObject]@{
AppId = ''
AppName = ''
Audience = ''
AuthMethods = ''
IPAddress = ''
Name = ''
Scope = ''
TenantId = ''
UserPrincipalName = ''
}
if (!$Token.Contains('.') -or !$token.StartsWith('eyJ')) { return $TokenDetails }
# Get token payload
$tokenPayload = $token.Split('.')[1].Replace('-', '+').Replace('_', '/')
while ($tokenPayload.Length % 4) {
$tokenPayload = '{0}=' -f $tokenPayload
}
# Convert base64 to json to object
$tokenByteArray = [System.Convert]::FromBase64String($tokenPayload)
$tokenArray = [System.Text.Encoding]::ASCII.GetString($tokenByteArray)
$TokenObj = $tokenArray | ConvertFrom-Json
# Convert token details to human readable
$TokenDetails.AppId = $TokenObj.appid
$TokenDetails.AppName = $TokenObj.app_displayname
$TokenDetails.Audience = $TokenObj.aud
$TokenDetails.AuthMethods = $TokenObj.amr
$TokenDetails.IPAddress = $TokenObj.ipaddr
$TokenDetails.Name = $TokenObj.name
$TokenDetails.Scope = $TokenObj.scp -split ' '
$TokenDetails.TenantId = $TokenObj.tid
$TokenDetails.UserPrincipalName = $TokenObj.upn
return $TokenDetails
}
function Get-CIPPMSolUsers {
[CmdletBinding()]
param (
[string]$tenant
)
$AADGraphtoken = (Get-GraphToken -scope 'https://graph.windows.net/.default')
$tenantid = (get-tenants | Where-Object -Property defaultDomainName -EQ $tenant).customerId
$TrackingGuid = (New-Guid).GUID
$LogonPost = @"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header><a:Action s:mustUnderstand="1">http://provisioning.microsoftonline.com/IProvisioningWebService/MsolConnect</a:Action><a:MessageID>urn:uuid:$TrackingGuid</a:MessageID><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo><UserIdentityHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BearerToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">$($AADGraphtoken['Authorization'])</BearerToken><LiveToken i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService"/></UserIdentityHeader><ClientVersionHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ClientId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">50afce61-c917-435b-8c6d-60aa5a8b8aa7</ClientId><Version xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">1.2.183.57</Version></ClientVersionHeader><ContractVersionHeader xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BecVersion xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">Version47</BecVersion></ContractVersionHeader><TrackingHeader xmlns="http://becwebservice.microsoftonline.com/">$($TrackingGuid)</TrackingHeader><a:To s:mustUnderstand="1">https://provisioningapi.microsoftonline.com/provisioningwebservice.svc</a:To></s:Header><s:Body><MsolConnect xmlns="http://provisioning.microsoftonline.com/"><request xmlns:b="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><b:BecVersion>Version4</b:BecVersion><b:TenantId i:nil="true"/><b:VerifiedDomain i:nil="true"/></request></MsolConnect></s:Body></s:Envelope>
"@
$DataBlob = (Invoke-RestMethod -Method POST -Uri 'https://provisioningapi.microsoftonline.com/provisioningwebservice.svc' -ContentType 'application/soap+xml; charset=utf-8' -Body $LogonPost).envelope.header.BecContext.DataBlob.'#text'
$MSOLXML = @"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header><a:Action s:mustUnderstand="1">http://provisioning.microsoftonline.com/IProvisioningWebService/ListUsers</a:Action><a:MessageID>urn:uuid:$TrackingGuid</a:MessageID><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo><UserIdentityHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BearerToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">$($AADGraphtoken['Authorization'])</BearerToken><LiveToken i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService"/></UserIdentityHeader><BecContext xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><DataBlob xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">$DataBlob</DataBlob><PartitionId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">2</PartitionId></BecContext><ClientVersionHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ClientId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">50afce61-c917-435b-8c6d-60aa5a8b8aa7</ClientId><Version xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">1.2.183.57</Version></ClientVersionHeader><ContractVersionHeader xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BecVersion xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">Version47</BecVersion></ContractVersionHeader><TrackingHeader xmlns="http://becwebservice.microsoftonline.com/">4e6cb653-c968-4a3a-8a11-2c8919218aeb</TrackingHeader><a:To s:mustUnderstand="1">https://provisioningapi.microsoftonline.com/provisioningwebservice.svc</a:To></s:Header><s:Body><ListUsers xmlns="http://provisioning.microsoftonline.com/"><request xmlns:b="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><b:BecVersion>Version16</b:BecVersion><b:TenantId>$($tenantid)</b:TenantId><b:VerifiedDomain i:nil="true"/><b:UserSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration"><c:PageSize>500</c:PageSize><c:SearchString i:nil="true"/><c:SortDirection>Ascending</c:SortDirection><c:SortField>None</c:SortField><c:AccountSku i:nil="true"/><c:BlackberryUsersOnly i:nil="true"/><c:City i:nil="true"/><c:Country i:nil="true"/><c:Department i:nil="true"/><c:DomainName i:nil="true"/><c:EnabledFilter i:nil="true"/><c:HasErrorsOnly i:nil="true"/><c:IncludedProperties i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/><c:IndirectLicenseFilter i:nil="true"/><c:LicenseReconciliationNeededOnly i:nil="true"/><c:ReturnDeletedUsers i:nil="true"/><c:State i:nil="true"/><c:Synchronized i:nil="true"/><c:Title i:nil="true"/><c:UnlicensedUsersOnly i:nil="true"/><c:UsageLocation i:nil="true"/></b:UserSearchDefinition></request></ListUsers></s:Body></s:Envelope>
"@
$userlist = do {
if ($null -eq $page) {
$Page = (Invoke-RestMethod -Uri 'https://provisioningapi.microsoftonline.com/provisioningwebservice.svc' -Method post -Body $MSOLXML -ContentType 'application/soap+xml; charset=utf-8').envelope.body.ListUsersResponse.listusersresult.returnvalue
$Page.results.user
}
else {
$Page = (Invoke-RestMethod -Uri 'https://provisioningapi.microsoftonline.com/provisioningwebservice.svc' -Method post -Body $MSOLXML -ContentType 'application/soap+xml; charset=utf-8').envelope.body.NavigateUserResultsResponse.NavigateUserResultsResult.returnvalue
$Page.results.user
}
$MSOLXML = @"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing"><s:Header><a:Action s:mustUnderstand="1">http://provisioning.microsoftonline.com/IProvisioningWebService/NavigateUserResults</a:Action><a:MessageID>urn:uuid:$TrackingGuid</a:MessageID><a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo><UserIdentityHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BearerToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">$($AADGraphtoken['Authorization'])</BearerToken><LiveToken i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService"/></UserIdentityHeader><BecContext xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><DataBlob xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">$DataBlob</DataBlob><PartitionId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">130</PartitionId></BecContext><ClientVersionHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ClientId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">50afce61-c917-435b-8c6d-60aa5a8b8aa7</ClientId><Version xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">1.2.183.57</Version></ClientVersionHeader><ContractVersionHeader xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><BecVersion xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">Version47</BecVersion></ContractVersionHeader><TrackingHeader xmlns="http://becwebservice.microsoftonline.com/">$($TrackingGuid)</TrackingHeader><a:To s:mustUnderstand="1">https://provisioningapi.microsoftonline.com/provisioningwebservice.svc</a:To></s:Header><s:Body><NavigateUserResults xmlns="http://provisioning.microsoftonline.com/"><request xmlns:b="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><b:BecVersion>Version16</b:BecVersion><b:TenantId>$($tenantid)</b:TenantId><b:VerifiedDomain i:nil="true"/><b:ListContext>$($page.listcontext)</b:ListContext><b:PageToNavigate>Next</b:PageToNavigate></request></NavigateUserResults></s:Body></s:Envelope>
"@
} until ($page.IsLastPage -eq $true -or $null -eq $page)
return $userlist
}
function New-DeviceLogin {
[CmdletBinding()]
param (
[string]$clientid,
[string]$scope,
[switch]$FirstLogon,
[string]$device_code,
[string]$TenantId
)
$encodedscope = [uri]::EscapeDataString($scope)
if ($FirstLogon) {
if ($TenantID) {
$ReturnCode = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$($TenantID)/oauth2/v2.0/devicecode" -Method POST -Body "client_id=$($Clientid)&scope=$encodedscope+offline_access+profile+openid"
}
else {
$ReturnCode = Invoke-RestMethod -Uri 'https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode' -Method POST -Body "client_id=$($Clientid)&scope=$encodedscope+offline_access+profile+openid"
}
}
else {
$Checking = Invoke-RestMethod -SkipHttpErrorCheck -Uri 'https://login.microsoftonline.com/organizations/oauth2/v2.0/token' -Method POST -Body "client_id=$($Clientid)&scope=$encodedscope+offline_access+profile+openid&grant_type=device_code&device_code=$($device_code)"
if ($checking.refresh_token) {
$ReturnCode = $Checking
}
else {
$returncode = $Checking.error
}
}
return $ReturnCode
}
function New-passwordString {
[CmdletBinding()]
param (
[int]$count = 12
)
Set-Location (Get-Item $PSScriptRoot).FullName
$SettingsTable = Get-CippTable -tablename 'Settings'
$PasswordType = (Get-AzDataTableEntity @SettingsTable).passwordType
if ($PasswordType -eq 'Correct-Battery-Horse') {
$Words = Get-Content .\words.txt
(Get-Random -InputObject $words -Count 4) -join '-'
}
else {
-join ('abcdefghkmnrstuvwxyzABCDEFGHKLMNPRSTUVWXYZ23456789$%&*#'.ToCharArray() | Get-Random -Count $count)
}
}