Skip to content

Commit

Permalink
Setup new scheduling engine.
Browse files Browse the repository at this point in the history
  • Loading branch information
KelvinTegelaar committed Feb 3, 2022
1 parent 1a5eb93 commit f140018
Show file tree
Hide file tree
Showing 15 changed files with 220 additions and 39 deletions.
24 changes: 24 additions & 0 deletions AddAlert/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"name": "Request",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "Response"
},
{
"name": "starter",
"direction": "in",
"type": "durableClient"
}
]
}
47 changes: 47 additions & 0 deletions AddAlert/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using namespace System.Net

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

$APIName = $TriggerMetadata.FunctionName
Log-Request -user $request.headers.'x-ms-client-principal' -API $APINAME -message "Accessed this API" -Sev "Debug"

Write-Host "PowerShell HTTP trigger function processed a request."

$Tenants = ($Request.body | Select-Object Select_*).psobject.properties.value
$Results = foreach ($Tenant in $tenants) {
try {
$CompleteObject = [PSCustomObject]@{
tenant = $tenant
AdminPassword = $Request.body.AdminPassword
DefenderMalware = $Request.body.DefenderMalware
DefenderStatus = $Request.body.DefenderStatus
DisableRestart = $Request.body.DisableRestart
InstallAsSystem = $Request.body.InstallAsSystem
MFAAdmins = $Request.body.MFAAdmins
MFAAlertUsers = $Request.body.MFAAlertUsers
NewApprovedApp = $Request.body.NewApprovedApp
NewGA = $Request.body.NewGA
NewRole = $Request.body.NewRole
QuotaUsed = $Request.body.QuotaUsed
UnusedLicenses = $Request.body.UnusedLicenses
Type = "Alert"

} | ConvertTo-Json
$JSONFile = New-Item -Path ".\Cache_Scheduler\$tenant.alert.json" -Value $CompleteObject -Force -ErrorAction Stop
"Succesfully added Alert for $($Tenant) to queue."
Log-Request -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Succesfully added Alert for $($Tenant) to queue." -Sev "Info"
}
catch {
Log-Request -user $request.headers.'x-ms-client-principal' -API $APINAME -tenant $tenant -message "Failed to add Alert for for $($Tenant) to queue" -Sev "Error"
"Failed to add Alert for for $($Tenant) to queue"
}
}

$body = [pscustomobject]@{"Results" = @($results) }

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
3 changes: 2 additions & 1 deletion ExecNotificationConfig/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ Log-Request -user $request.headers.'x-ms-client-principal' -API $APINAME -messa
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
$results = try {
$Request.body | ConvertTo-Json | Set-Content ".\SendNotifications\Config.Json"
$Request.body | ConvertTo-Json | Set-Content ".\Config\Config_Notifications.Json"
Set-Content '.\Cache_Scheduler\_DefaultNotifications.json' -Value '{ "tenant": "any","Type": "CIPPNotifications" }'
"succesfully set the configuration"
}
catch {
Expand Down
9 changes: 9 additions & 0 deletions Scheduler_Alert/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bindings": [
{
"name": "tenant",
"direction": "in",
"type": "activityTrigger"
}
]
}
10 changes: 10 additions & 0 deletions Scheduler_Alert/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
param($tenant)

try {
#$Alerts = Get-Content ".\Cache_Scheduler\$tenant.alert.json" | ConvertFrom-Json
Write-Host "GENERATING ALERT!!!!"
#Write-Host $Alerts
}
catch {
Log-request -API "Scheduler" -tenant $tenant -message "Failed to get alerts for $($tenant) Error: $($_.exception.message)" -sev Error
}
11 changes: 11 additions & 0 deletions Scheduler_CIPPNotifications/Config.Json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"addStandardsDeploy": true,
"webhook": "mywebhook.com",
"addPolicy": true,
"email": "[email protected]",
"addChocoApp": true,
"addUser": true,
"removeUser": true,
"removeStandard": true,
"tokenUpdater": true
}
9 changes: 9 additions & 0 deletions Scheduler_CIPPNotifications/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bindings": [
{
"name": "tenant",
"direction": "in",
"type": "activityTrigger"
}
]
}
55 changes: 27 additions & 28 deletions SendNotifications/run.ps1 → Scheduler_CIPPNotifications/run.ps1
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
# Input bindings are passed in via param block.
param($Timer)
param($tenant)

# Get the current universal time in the default string format.
$currentUTCtime = (Get-Date).ToUniversalTime()

if (Test-Path '.\SendNotifications\Config.json') {
$Config = Get-Content '.\SendNotifications\Config.json' | ConvertFrom-Json
if (Test-Path '.\Config\Config_Notifications.Json') {
$Config = Get-Content '.\Config\Config_Notifications.Json' | ConvertFrom-Json
}
else {
Write-Host 'Done - No config active'
exit
Write-Host 'Done - No config active'
exit
}

$Settings = $Config.psobject.properties.name
$logdate = (Get-Date).ToString('ddMMyyyy')
$Currentlog = Get-Content "Logs\$($logdate).log" | ConvertFrom-Csv -Header 'DateTime', 'Tenant', 'API', 'Message', 'User', 'Severity' -Delimiter '|' | Where-Object { [datetime]$_.Datetime -gt (Get-Date).AddMinutes(-31) -and $_.api -in $Settings -and $_.Severity -ne 'debug' }
$Currentlog = Get-Content "Logs\$($logdate).log" | ConvertFrom-Csv -Header 'DateTime', 'Tenant', 'API', 'Message', 'User', 'Severity' -Delimiter '|' | Where-Object { [datetime]$_.Datetime -gt (Get-Date).AddMinutes(-16) -and $_.api -in $Settings -and $_.Severity -ne 'debug' }
Write-Host "Current log: $CurrentLog"
Write-Host $Config
if ($Config.email -ne '' -and $null -ne $CurrentLog) {
$HTMLLog = ($CurrentLog | ConvertTo-Html -frag) -replace '<table>', '<table class=blueTable>' | Out-String
$JSONBody = @"
$HTMLLog = ($CurrentLog | ConvertTo-Html -frag) -replace '<table>', '<table class=blueTable>' | Out-String
$JSONBody = @"
{
"message": {
"subject": "CIPP Alert: Alerts found starting at $((Get-Date).AddMinutes(-31))",
"subject": "CIPP Alert: Alerts found starting at $((Get-Date).AddMinutes(-16))",
"body": {
"contentType": "HTML",
"content": "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>
Expand All @@ -43,35 +42,35 @@ if ($Config.email -ne '' -and $null -ne $CurrentLog) {
"saveToSentItems": "false"
}
"@
New-GraphPostRequest -uri 'https://graph.microsoft.com/v1.0/me/sendMail' -tenantid $env:TenantID -type POST -body ($JSONBody)
New-GraphPostRequest -uri 'https://graph.microsoft.com/v1.0/me/sendMail' -tenantid $env:TenantID -type POST -body ($JSONBody)
}



if ($Config.webhook -ne '' -and $null -ne $CurrentLog) {
switch -wildcard ($config.Webhook) {
switch -wildcard ($config.Webhook) {

'*webhook.office.com*' {
$Log = $Currentlog | ConvertTo-Html -frag | Out-String
$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>$Log`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}
'*webhook.office.com*' {
$Log = $Currentlog | ConvertTo-Html -frag | Out-String
$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>$Log`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}

'*slack.com*' {
$Log = $Currentlog | ForEach-Object {
$JSonBody = @"
'*slack.com*' {
$Log = $Currentlog | ForEach-Object {
$JSonBody = @"
{"blocks":[{"type":"header","text":{"type":"plain_text","text":"New Alert from CIPP","emoji":true}},{"type":"section","fields":[{"type":"mrkdwn","text":"*DateTime:*\n$($_.DateTime)"},{"type":"mrkdwn","text":"*Tenant:*\n$($_.Tenant)"},{"type":"mrkdwn","text":"*API:*\n$($_.API)"},{"type":"mrkdwn","text":"*User:*\n$($_.User)."}]},{"type":"section","text":{"type":"mrkdwn","text":"*Message:*\n$($_.message)"}}]}
"@
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}
}
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}
}

'*discord.com*' {
$Log = $Currentlog | ConvertTo-Html -frag | Out-String
$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. $Log`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
'*discord.com*' {
$Log = $Currentlog | ConvertTo-Html -frag | Out-String
$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. $Log`"}"
Invoke-RestMethod -Uri $config.webhook -Method POST -ContentType 'Application/json' -Body $JSONBody
}
}
}

}

Expand Down
9 changes: 9 additions & 0 deletions Scheduler_GetQueue/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bindings": [
{
"name": "name",
"type": "activityTrigger",
"direction": "in"
}
]
}
25 changes: 25 additions & 0 deletions Scheduler_GetQueue/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
param($name)

$Tenants = Get-ChildItem "Cache_Scheduler\*.json"

$object = foreach ($Tenant in $tenants) {
$TypeFile = Get-Content "$($tenant)" | ConvertFrom-Json
if ($Typefile.Tenant -ne "AllTenants") {
[pscustomobject]@{
Tenant = $Typefile.Tenant
Type = $Typefile.Type
}
}
else {
Write-Host "All tenants, doing them all"
get-tenants | ForEach-Object {
[pscustomobject]@{
Tenant = $_.defaultDomainName
Type = $Typefile.Type
}
}
}
}


$object
9 changes: 9 additions & 0 deletions Scheduler_Orchestration/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"bindings": [
{
"name": "Context",
"type": "orchestrationTrigger",
"direction": "in"
}
]
}
15 changes: 15 additions & 0 deletions Scheduler_Orchestration/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
param($Context)

New-Item "Cache_Scheduler" -ItemType Directory -ErrorAction SilentlyContinue
New-Item "Cache_Scheduler\CurrentlyRunning.txt" -ItemType File -Force


$Batch = (Invoke-DurableActivity -FunctionName 'Scheduler_GetQueue' -Input 'LetsGo')
$ParallelTasks = foreach ($Item in $Batch) {
Invoke-DurableActivity -FunctionName "Scheduler_$($item['Type'])" -Input $item['Tenant'] -NoWait
}

$Outputs = Wait-ActivityFunction -Task $ParallelTasks
Write-Host $Outputs
Remove-Item "Cache_Scheduler\CurrentlyRunning.txt" -Force
Log-request -API "Scheduler" -tenant $tenant -message "Scheduler Ran." -sev Info
15 changes: 15 additions & 0 deletions Scheduler_Timer/function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"bindings": [
{
"name": "Timer",
"schedule": "0 */15 * * * *",
"direction": "in",
"type": "timerTrigger"
},
{
"name": "starter",
"type": "durableClient",
"direction": "in"
}
]
}
8 changes: 8 additions & 0 deletions Scheduler_Timer/run.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using namespace System.Net

param($Timer)

$InstanceId = Start-NewOrchestration -FunctionName 'Scheduler_Orchestration'
Write-Host "Started orchestration with ID = '$InstanceId'"
New-OrchestrationCheckStatusResponse -Request $timer -InstanceId $InstanceId

10 changes: 0 additions & 10 deletions SendNotifications/function.json

This file was deleted.

0 comments on commit f140018

Please sign in to comment.