-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
M365_Apps_Hudu.ps1
445 lines (374 loc) · 14.4 KB
/
M365_Apps_Hudu.ps1
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
#####################################################################
# Get a Hudu API Key from https://yourhududomain.com/admin/api_keys
$HuduAPIKey = "abcdefghijklmn1234556789"
# Set the base domain of your Hudu instance without a trailing /
$HuduBaseDomain = "https://your.hudu.domain"
$HuduAssetLayoutName = "M365 Azure AD Apps"
#####################################################################
########################## Azure AD ###########################
$customerExclude =@("Example Customer 1","Example Customer 2")
$ApplicationId = "Your APP ID"
$ApplicationSecret = ConvertTo-SecureString -AsPlainText "Your App Secret" -Force
$TenantID = "Your Tenant ID"
$RefreshToken = "Your Long Refresh Token"
$ExchangeRefreshToken = "Your Long Exchange Refresh Token"
$upn = '[email protected]'
#####################################################################
# Enable sending alerts on dns change to a teams webhook
$enableTeamsAlerts = $false
$teamsWebhook = "https://yourteamswebhookurl.com/1234567898"
# Enable sending alerts on dns change to an email address
$enableEmailAlerts = $false
$mailTo = "[email protected]"
$mailFrom = "[email protected]"
$mailServer = "mail.domain.com"
$mailPort = "25"
$mailUseSSL = $true
$mailUser = "user"
$mailPass = "pass"
#####################################################################
function Send-TeamsAlert {
Param (
[PSCustomObject]$JSONBody
)
if ($enableTeamsAlerts) {
$TeamMessageBody = ConvertTo-Json $JSONBody -Depth 100
$parameters = @{
"URI" = $teamsWebhook
"Method" = 'POST'
"Body" = $TeamMessageBody
"ContentType" = 'application/json'
}
$result = Invoke-RestMethod @parameters
}
}
function Send-EmailAlert {
Param (
[string]$body,
[string]$mailSubject
)
if ($enableEmailAlerts){
$password = ConvertTo-SecureString $mailPass -AsPlainText -Force
$mailcred = New-Object System.Management.Automation.PSCredential ($mailUser, $password)
$sendMailParams = @{
From = $mailFrom
To = $mailTo
Subject = $mailSubject
Body = $body
SMTPServer = $mailServer
UseSsl = $mailUseSSL
Credential = $mailcred
}
Send-MailMessage @sendMailParams -BodyAsHtml
}
}
function Check-PermChange {
Param (
[string]$currentPerm = '',
[string]$newPerm = '',
[string]$permType = '',
[string]$appName = '',
[string]$companyName = ''
)
$Comp = Compare-Object -ReferenceObject $($currentPerm -split "`n") -DifferenceObject $($newPerm -split "`n")
if ($Comp){
# Send Teams Alert
$removed = ($Comp | where-object -filter {$_.SideIndicator -eq "<="}).InputObject | out-string
$newperms = ($Comp | where-object -filter {$_.SideIndicator -eq "=>"}).InputObject | out-string
$outText = ""
if ($removed){
$outText = "<h3>Removed Permissions</h3><table>$removed</table>"
}
if ($newperms){
$outText = "$outText<h3>New Permissions</h3><table>$newperms</table>"
}
$JSONBody = [PSCustomObject][Ordered]@{
"@type" = "MessageCard"
"@context" = "http://schema.org/extensions"
"summary" = "$companyName - $appName - Azure AD App $permType permission change detected"
"themeColor" = '0078D7'
"sections" = @(
@{
"activityTitle" = "$companyName - $appName - Azure AD App $permType permission change detected"
"markdown" = $true
},
@{
"startGroup" = $true
"text" = $outText
}
)
}
Send-TeamsAlert -JSONBody $JSONBody
$oldVal = ($Comp | where-object -filter {$_.SideIndicator -eq "<="}).InputObject | out-string
$newVal = ($Comp | where-object -filter {$_.SideIndicator -eq "=>"}).InputObject | out-string
$mailSubject = "$companyName - $appName - Azure AD App $permType permission change detected"
$body = "
<style>
table{
border-collapse: collapse;
margin: 5px 0;
font-size: 0.8em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
h2, p{
font-size: 0.8em;
font-family: sans-serif;
}
th, td {
padding: 5px 5px;
max-width: 400px;
width:auto;
}
thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
tr {
border-bottom: 1px solid #dddddd;
}
tr:nth-of-type(even) {
background-color: #f3f3f3;
}
</style>
<h3>$mailSubject</h3>
$outText
</table>
"
Send-EmailAlert -mailSubject $mailSubject -body $body
}
}
#Get the Hudu API Module if not installed
if (Get-Module -ListAvailable -Name HuduAPI) {
Import-Module HuduAPI
} else {
Install-Module HuduAPI -Force
Import-Module HuduAPI
}
#Set Hudu logon information
New-HuduAPIKey $HuduAPIKey
New-HuduBaseUrl $HuduBaseDomain
$Layout = Get-HuduAssetLayouts -name $HuduAssetLayoutName
if (!$Layout) {
$AssetLayoutFields = @(
@{
label = 'Logo'
field_type = 'RichText'
show_in_list = 'false'
position = 1
},
@{
label = 'Homepage'
field_type = 'RichText'
show_in_list = 'false'
position = 2
},
@{
label = 'Publisher Domain'
field_type = 'RichText'
show_in_list = 'false'
position = 3
},
@{
label = 'OAuth2 Permissions'
field_type = 'RichText'
show_in_list = 'false'
position = 4
},
@{
label = 'App Permissions'
field_type = 'RichText'
show_in_list = 'false'
position = 5
},
@{
label = 'Delegated Permissions'
field_type = 'RichText'
show_in_list = 'false'
position = 6
},
@{
label = 'Granted Date'
field_type = 'Text'
show_in_list = 'false'
position = 7
}
)
Write-Host "Creating New Asset Layout $HuduAssetLayoutName"
$NewLayout = New-HuduAssetLayout -name $HuduAssetLayoutName -icon "fas fa-sitemap" -color "#00adef" -icon_color "#ffffff" -include_passwords $false -include_photos $false -include_comments $false -include_files $false -fields $AssetLayoutFields
$Layout = Get-HuduAssetLayouts -name $HuduAssetLayoutName
}
#Connect to your Azure AD Account.
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)
$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID
Connect-AzureAD -AadAccessToken $aadGraphToken.AccessToken -AccountId $UPN -MsAccessToken $graphToken.AccessToken -TenantId $tenantID | Out-Null
$Customers = Get-AzureADContract -All:$true
Disconnect-AzureAD
#Login to Hudu
New-HuduAPIKey $HuduAPIKey
New-HuduBaseUrl $HuduBaseDomain
foreach ($Customer in $Customers) {
#Check if customer should be excluded
if (-Not ($customerExclude -contains $customer.DisplayName)){
$Applications = ''
#First lets check for the company
#Check if they are in Hudu before doing any unnessisary work
$defaultdomain = $customer.DefaultDomainName
$hududomain = Get-HuduWebsites -name "https://$defaultdomain"
if ($($hududomain.id.count) -gt 0) {
write-host "Processing $($customer.Displayname)" -foregroundColor green
$CustAadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.windows.net/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
$CustGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes "https://graph.microsoft.com/.default" -ServicePrincipal -Tenant $customer.CustomerContextId
Connect-AzureAD -AadAccessToken $CustAadGraphToken.AccessToken -AccountId $upn -MsAccessToken $CustGraphToken.AccessToken -TenantId $customer.CustomerContextId | out-null
$Applications = Get-AzureADApplication -All:$true
foreach ($app in $Applications){
$allsp = Get-AzureADServicePrincipal -All $true
write-host "$($app.displayName)" -foregroundColor green
$appName = $app.DisplayName
if ($appName){
$appsp = Get-AzureADServicePrincipal -All $true | Where-Object {$_.AppId -eq $app.AppId}
$AppDelegatedDate = ""
$grantedDate = ""
if ($appsp.ObjectId){
$AppDelegatedDate = ((Get-AzureADServiceAppRoleAssignedTo -ObjectId $appsp.ObjectId).CreationTimestamp)| Sort-Object {[DateTime]$_} | Select -First 1 | Out-String
}
if ($AppDelegatedDate -eq ""){
$AppDelegatedDate = "Unknown"
}
$DelegatedPermissions = [System.Collections.ArrayList]@()
$AppPermissions = [System.Collections.ArrayList]@()
$OAuth2Permissions = [System.Collections.ArrayList]@()
foreach ($oauth in $app.Oauth2Permissions){
$perm = $oauth | select @{N='Permission'; E={$_.value}}, @{N='Name'; E={$_.AdminConsentDisplayName}}, @{N='Description'; E={$_.AdminConsentDescription}}
$null = $OAuth2Permissions.add($perm)
}
foreach ($reqperm in $App.requiredResourceAccess){
$sp = $allsp | Where-Object {$_.AppId -eq $reqperm.ResourceAppId}
foreach ($permission in $($reqperm.ResourceAccess)){
if ($permission.type -eq "Scope") {
$perm = $sp.Oauth2Permissions | Where-Object {$_.Id -eq $permission.id} | select @{N='Permission'; E={$_.value}}, @{N='Name'; E={$_.AdminConsentDisplayName}}, @{N='Description'; E={$_.AdminConsentDescription}}
$null = $DelegatedPermissions.add($perm)
}
if ($permission.type -eq "Role") {
$perm = $sp.AppRoles | Where-Object {$_.Id -eq $permission.id} | select @{N='Permission'; E={$_.value}}, @{N='Name'; E={$_.DisplayName}}, @{N='Description'; E={$_.Description}}
$null = $AppPermissions.add($perm)
}
}
}
$OAuthHTML = ($OAuth2Permissions | ConvertTo-Html -Fragment | Out-String) -replace "[^a-zA-Z0-9. ,&`"-@<>/#_;]", ''
$OAuthHTML = $OAuthHTML -replace "'", ''
$AppHTML = ($AppPermissions | ConvertTo-Html -Fragment | Out-String) -replace "[^a-zA-Z0-9. ,&`"-@<>/#_;]", ''
$AppHTML = $AppHTML -replace "'", ''
$DelegatedHTML = ($DelegatedPermissions | ConvertTo-Html -Fragment | Out-String) -replace "[^a-zA-Z0-9. ,&`"-@<>/#_;]", ''
$DelegatedHTML = $DelegatedHTML -replace "'", ''
if ($($app.AppLogoURL)){
$LogoHTML = "<img src=`"$($app.AppLogoURL)`"></img>"
} else {
$LogoHTML = ''
}
$AssetFields = @{
'logo' = $LogoHTML
'homepage' = $($app.Homepage)
'publisher_domain' = $($app.PublisherDomain)
'oauth2_permissions' = $OAuthHTML
'app_permissions' = $AppHTML
'delegated_permissions' = $DelegatedHTML
'granted_date' = $AppDelegatedDate
}
$companyid = $hududomain.company_id
$companyName = $hududomain.company_name
#Swap out # as Hudu doesn't like it when searching
$AssetName = $appName
#Check if there is already an asset
$Asset = Get-HuduAssets -name $AssetName -companyid $companyid -assetlayoutid $Layout.id
#If the Asset does not exist, we edit the body to be in the form of a new asset, if not, we just upload.
if (!$Asset) {
Write-Host "Creating new Asset"
$outText = ""
if (($OAuthHTML | measure-object -line).lines -gt 2){
$outText = "OAuth Permissions: $OAuthHTML"
}
if (($AppHTML | measure-object -line).lines -gt 2){
write-host "AppHTML"
$outText = "$outText App Permissions: $AppHTML"
}
if (($DelegatedHTML | measure-object -line).lines -gt 2){
$outText = "$outText Delegated Permissions: $DelegatedHTML"
}
$JSONBody = [PSCustomObject][Ordered]@{
"@type" = "MessageCard"
"@context" = "http://schema.org/extensions"
"summary" = "$companyName - $appName - Azure AD - New Application Detected"
"themeColor" = '0078D7'
"sections" = @(
@{
"activityTitle" = "$companyName - $appName - Azure AD: New Application Detected"
"markdown" = $true
},
@{
"startGroup" = $true
"text" = $outText
}
)
}
Send-TeamsAlert -JSONBody $JSONBody
Write-Host "Sent Teams Alert"
$mailSubject = "$companyName - $appName - Azure AD: New Application Detected"
$body = "
<style>
table{
border-collapse: collapse;
margin: 5px 0;
font-size: 0.8em;
font-family: sans-serif;
min-width: 400px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}
h2, p{
font-size: 0.8em;
font-family: sans-serif;
}
th, td {
padding: 5px 5px;
max-width: 400px;
width:auto;
}
thead tr {
background-color: #009879;
color: #ffffff;
text-align: left;
}
tr {
border-bottom: 1px solid #dddddd;
}
tr:nth-of-type(even) {
background-color: #f3f3f3;
}
</style>
<h3>$mailSubject</h3>
$outText
"
Send-EmailAlert -mailSubject $mailSubject -body $body
Write-Host "Sent Email Alert"
$Asset = New-HuduAsset -name $AssetName -company_id $companyid -asset_layout_id $Layout.id -fields $AssetFields
Write-Host "Created Asset"
}
else {
$oauth_cur_value = ($Asset.fields | where-object -filter {$_.label -eq "OAuth2 Permissions"}).value
$app_cur_value = ($Asset.fields | where-object -filter {$_.label -eq "App Permissions"}).value
$del_cur_value = ($Asset.fields | where-object -filter {$_.label -eq "Delegated Permissions"}).value
Check-PermChange -currentPerm $oauth_cur_value -newPerm $OAuthHTML -permType "OAuth2" -appName $AssetName -companyName $hududomain.company_name
Check-PermChange -currentPerm $app_cur_value -newPerm $AppHTML -permType "App" -appName $AssetName -companyName $hududomain.company_name
Check-PermChange -currentPerm $del_cur_value -newPerm $DelegatedHTML -permType "Delegated" -appName $AssetName -companyName $hududomain.company_name
Write-Host "Updating Asset"
$Asset = Set-HuduAsset -asset_id $Asset.id -name $AssetName -company_id $companyid -asset_layout_id $Layout.id -fields $AssetFields
}
}
}
Disconnect-AzureAD
}
}
}