Skip to content

Commit

Permalink
webhook stuff for auditlogs
Browse files Browse the repository at this point in the history
  • Loading branch information
KelvinTegelaar committed Aug 6, 2023
1 parent c629a27 commit abada21
Show file tree
Hide file tree
Showing 12 changed files with 311 additions and 78 deletions.
4 changes: 1 addition & 3 deletions ListGenericTestFunction/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ param($Request, $TriggerMetadata)

$APIName = $TriggerMetadata.FunctionName
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message 'Accessed this API' -Sev 'Debug'
$body = '{"userPreferredMethodForSecondaryAuthentication": "push"}'
$graphRequest = New-GraphPOSTRequest -body $body -type PATCH -uri 'https://graph.microsoft.com/beta/users/b4156a0c-91c5-4195-bb1b-41b96d0806a7/authentication/signInPreferences' -tenantid $TenantFilter

$graphRequest = $request.headers
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = @($graphRequest)
Expand Down
19 changes: 19 additions & 0 deletions ListWebhookAlert/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
}
]
}
16 changes: 16 additions & 0 deletions ListWebhookAlert/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

$APIName = $TriggerMetadata.FunctionName
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"
$WebhookTable = Get-CIPPTable -TableName webhookTable
$WebhookRow = Get-AzDataTableEntity @WebhookTable

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = @($WebhookRow)
})

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions Modules/CIPPCore/Public/New-CIPPGraphSubscription.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ function New-CIPPGraphSubscription {
$TenantFilter,
[bool]$auditLogAPI = $false,
$TypeofSubscription,
$BaseURL,
$Resource,
$EventType,
$APIName = "Create Webhook",
Expand All @@ -13,7 +14,7 @@ function New-CIPPGraphSubscription {
$expiredate = (Get-Date).AddDays(1).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$params = @{
changeType = $TypeofSubscription
notificationUrl = "https://webhook.site/9650bc4a-0120-41de-8ffd-6616e71244e1?EventType=$EventType&CIPPID=$CIPPID"
notificationUrl = "$BaseURL?EventType=$EventType&CIPPID=$CIPPID"
resource = $Resource
expirationDateTime = $expiredate
} | ConvertTo-Json
Expand All @@ -23,10 +24,10 @@ function New-CIPPGraphSubscription {
if ($auditLogAPI) {
$AuditLogParams = @{
webhook = @{
"address" = "https://webhook.site/9650bc4a-0120-41de-8ffd-6616e71244e1/"
"address" = "$BaseURL?EventType=$EventType&CIPPID=$CIPPID"
}
} | ConvertTo-Json
$AuditLog = New-GraphPOSTRequest -uri "https://manage.office.com/api/v1.0/$($TenantFilter)/activity/feed/subscriptions/start?contentType=$EventType&PublisherIdentifier=$($TenantFilter)" -tenantid $TenantFilter -type -scope "https://manage.office.com/.default" POST -body $AuditLogparams -verbose
$AuditLog = New-GraphPOSTRequest -uri "https://manage.office.com/api/v1.0/$($TenantFilter)/activity/feed/subscriptions/start?contentType=$EventType&PublisherIdentifier=$($TenantFilter)" -tenantid $TenantFilter -type POST -scope "https://manage.office.com/.default" -body $AuditLogparams -verbose
$WebhookRow = @{
PartitionKey = [string]$TenantFilter
RowKey = [string]$CIPPID
Expand Down
2 changes: 1 addition & 1 deletion Modules/CIPPCore/Public/Remove-CIPPGraphSubcription.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function Remove-CIPPGraphSubscription {
$GraphRequest = New-GraphPostRequest -uri "https://graph.microsoft.com/beta/subscriptions/$($oldId.ID)" -tenantid $TenantFilter -type DELETE -body {} -Verbose
$null = Remove-AzDataTableEntity @WebhookTable -Entity $WebhookRow
}
return "Remove webhook subscription to $($GraphRequest.value.notificationUrl)"
return "Removed webhook subscription to $($GraphRequest.value.notificationUrl)"

}
catch {
Expand Down
90 changes: 90 additions & 0 deletions Modules/CIPPCore/Public/Send-CIPPAlert.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@

function Send-CIPPAlert {
[CmdletBinding()]
param (
$Type,
$Title,
$HTMLContent,
$JSONContent,
$TenantFilter,
$APIName = "Send Alert",
$ExecutingUser
)

$Table = Get-CIPPTable -TableName SchedulerConfig
$Filter = "RowKey eq 'CippNotifications' and PartitionKey eq 'CippNotifications'"
$Config = [pscustomobject](Get-AzDataTableEntity @Table -Filter $Filter)
if ($Type -eq 'email') {
try {
if ($Config.email -like '*@*') {
$Recipients = $Config.email.split(",").trim() | ForEach-Object { if ($_ -like '*@*') { [pscustomobject]@{EmailAddress = @{Address = $_ } } } }
$PowerShellBody = [PSCustomObject]@{
message = @{
subject = $Title
body = @{
contentType = "HTML"
content = $HTMLcontent
}
toRecipients = @($Recipients)
}
saveToSentItems = "true"
}

$JSONBody = ConvertTo-Json -Compress -Depth 10 -InputObject $PowerShellBody
New-GraphPostRequest -uri 'https://graph.microsoft.com/v1.0/me/sendMail' -tenantid $env:TenantID -NoAuthCheck $true -type POST -body ($JSONBody)
}

}
catch {
Write-Host "Could not send alerts to email: $($_.Exception.message)"
Write-LogMessage -API 'Alerts' -message "Could not send alerts to : $($_.Exception.message)" -sev info
}

}
if ($Type -eq 'webhook') {
try {
if ($Config.webhook -ne '') {
switch -wildcard ($config.webhook) {

'*webhook.office.com*' {
$JSonBody = "{`"text`": `"You've setup your alert policies to be alerted whenever specific events happen. We've found some of these events in the log. <br><br>$JSONContent`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}

'*discord.com*' {
$JSonBody = "{`"content`": `"You've setup your alert policies to be alerted whenever specific events happen. We've found some of these events in the log. $JSONContent`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}
default {
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONContent
}
}

}

}
catch {
Write-Host "Could not send alerts to webhook: $($_.Exception.message)"
Write-LogMessage -API 'Alerts' -message "Could not send alerts to : $($_.Exception.message)" -sev info
}
}
if ($Type -eq 'psa') {
if ($config.sendtoIntegration) {
try {

$Alert = @{
TenantId = $Tenant
AlertText = "$HTMLContent"
AlertTitle = "$($Title)"
}
New-CippExtAlert -Alert $Alert
}
catch {
Write-Host "Could not send alerts to ticketing system: $($_.Exception.message)"
Write-LogMessage -API 'Alerts' -message "Could not send alerts to : $($_.Exception.message)" -sev info
}
}
}
}


16 changes: 16 additions & 0 deletions PublicWebhooks/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": ["get", "post"]
},
{
"type": "http",
"direction": "out",
"name": "Response"
}
]
}
44 changes: 44 additions & 0 deletions PublicWebhooks/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
$WebhookTable = Get-CIPPTable -TableName webhookTable
$Webhooks = Get-AzDataTableEntity @WebhookTable

$WebhookAlertTable = Get-CIPPTable -TableName webhookAlertTable
$WebhookAlerts = Get-AzDataTableEntity $WebhookAlertTable
$url = ($request.headers.'x-ms-original-url').split('/api') | Select-Object -First 1

if ($Request.CIPPID -in $Webhooks.CIPPID) {
if ($Request.query.ValidationToken -or $Request.body.validationCode) {
$body = $request.query.ValidationToken
}

if ($Request.body.ContentUri) {
if ($Request.body.ContentUri -notlike "https://manage.office.com/api/v1.0/*") { exit }
$TenantFilter = (Get-Tenants | Where-Object -Property customerId -EQ $Request.body.TenantID).defaultDomainName
$Data = New-GraphPostRequest -type GET -uri "$($request.body.contenturi)" -tenantid $TenantFilter -scope "https://manage.office.com/.default"
}
else {
$TenantFilter = $Data.Tenant
$Data = $Request.body
}

foreach ($Item in $Data) {
if ($item.Operation -in $WebhookAlerts.Operation) {
Invoke-CippWebhookProcessing -TenantFilter $TenantFilter -Data $Data -CIPPPURL $url
}
}

$body = "OK"
}
else {
$body = "This webhook is not authorized."
}


# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
19 changes: 19 additions & 0 deletions RemoveWebhookAlert/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
}
]
}
24 changes: 24 additions & 0 deletions RemoveWebhookAlert/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

$APIName = $TriggerMetadata.FunctionName
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"
Import-Module CippCore
try {
$Results = Remove-CIPPGraphSubscription -TenantFilter $Request.query.TenantFilter -CIPPID $Request.query.CIPPID
$body = [pscustomobject]@{"Results" = $Results }
}
catch {
Write-LogMessage -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Failed to remove webhook alert. $($_.Exception.Message)" -Sev "Error"
$body = [pscustomobject]@{"Results" = "Failed to remove webhook alert: $($_.Exception.Message)" }
}


# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})

2 changes: 2 additions & 0 deletions Scheduler_CIPPNotifications/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ catch {
Write-Host "Could not send alerts to email: $($_.Exception.message)"
Write-LogMessage -API 'Alerts' -message "Could not send alerts to : $($_.Exception.message)" -sev info
}


try {
Write-Host $($config | ConvertTo-Json)
Write-Host $config.webhook
Expand Down

0 comments on commit abada21

Please sign in to comment.