-
Notifications
You must be signed in to change notification settings - Fork 18
/
PingCastle-Notify.ps1
465 lines (424 loc) · 19.5 KB
/
PingCastle-Notify.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<#
author: Martial Puygrenier - @mpgn_x64
original work from Romain Tiennot at ManoMano - aikiox
original gist from aikiox: https://gist.github.com/aikiox/98f97ccc092557acc1ea958d65f8f361#file-send-pingcastlereport-ps1
change:
- slack integration
- rule diff between two pingcastle scan
- teams integration
- scan log integration
- option $print_current_result to add all flaged rules
date: 14/09/2022
version: 1.1
change:
- better slack integration with color
date: 22/02/2024
version: 1.2
#>
### EDIT THIS PARAMETERS ###
$slackChannel = "#pingcastle-scan"
$slackToken="xoxb-xxxxx-xxxxx-xxxxx-xxxxx"
$slack = 1
$teams = 0
$teamsUri = "https://xxxxxxxxx.office.com/webhookb2/xxxxxxxxxxxxx/IncomingWebhook/xxxxxxxxx/xxxxxxxxx"
$print_current_result = 1
### END ###
$ErrorActionPreference = 'Stop'
$InformationPreference = 'Continue'
#region Variable
$ApplicationName = 'PingCastle'
$PingCastle = [pscustomobject]@{
Name = $ApplicationName
ProgramPath = Join-Path $PSScriptRoot $ApplicationName
ProgramName = '{0}.exe' -f $ApplicationName
Arguments = '--healthcheck --level Full'
ReportFileName = 'ad_hc_{0}' -f ($env:USERDNSDOMAIN).ToLower()
ReportFolder = "Reports"
ProgramUpdate = '{0}AutoUpdater.exe' -f $ApplicationName
ArgumentsUpdate = '--wait-for-days 30'
}
$pingCastleFullpath = Join-Path $PingCastle.ProgramPath $PingCastle.ProgramName
$pingCastleUpdateFullpath = Join-Path $PingCastle.ProgramPath $PingCastle.ProgramUpdate
$pingCastleReportLogs = Join-Path $PingCastle.ProgramPath $PingCastle.ReportFolder
$pingCastleReportFullpath = Join-Path $PingCastle.ProgramPath ('{0}.html' -f $PingCastle.ReportFileName)
$pingCastleReportXMLFullpath = Join-Path $PingCastle.ProgramPath ('{0}.xml' -f $PingCastle.ReportFileName)
$pingCastleReportDate = Get-Date -UFormat %Y%m%d_%H%M%S
$pingCastleReportFileNameDate = ('{0}_{1}' -f $pingCastleReportDate, ('{0}.html' -f $PingCastle.ReportFileName))
$pingCastleReportFileNameDateXML = ('{0}_{1}' -f $pingCastleReportDate, ('{0}.xml' -f $PingCastle.ReportFileName))
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$headers = @{
Authorization="Bearer $slackToken"
}
$sentNotification = $false
$splatProcess = @{
WindowStyle = 'Hidden'
Wait = $true
}
$BodySlack = @{
channel = $slackChannel;
attachments = @(
@{
"mrkdwn_in" = @("text")
"color" = ""
"text" = ""
"fields" = @(
@{
"value" = ""
"short" = "True"
},
@{
"value" = ""
"short" = "True"
},
@{
"value" = ""
"short" = "True"
},
@{
"value" = ""
"short" = "True"
},
@{
"value" = ""
"short" = $False
}
)
"footer" = "<https://github.com/LuccaSA/PingCastle-Notify|Pingcastle-Notify> v1.2"
"footer_icon" = "https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png"
}
);
icon_emoji = ":ghost:";
username = "PingCastle Automatic run";
}
$BodyTeams = @"
{
text:'Domain *domain_env* - date_scan - *Global Score abc* :
- Score: *[cbd Trusts | def Stale Object | asx Privileged Group | dse Anomalies]*
- add_new_vuln
"@
# Function update slack color
Function updateSlackColor($body, $point) {
if ($point -ge 75) {
$body['attachments'][0]['color'] = "#f12828"
} elseIf ($point -ge 50 -and $point -lt 75) {
$body['attachments'][0]['color'] = "#ff6a00"
} elseIf ($point -ge 25 -and $point -lt 50) {
$body['attachments'][0]['color'] = "#ffd800"
} elseIf ($point -ge 0 -and $point -lt 25) {
$body['attachments'][0]['color'] = "#83e043"
} else {
$body['attachments'][0]['color'] = "#83e043"
}
return $body
}
# function send to slack
Function Send_WebHook($body, $connector) {
if ($slack -and $connector -eq "slack") {
$BodySlackJson = $body | ConvertTo-Json -Depth 5
Write-Host $BodySlackJson
Write-Host "Sending to slack"
return Invoke-RestMethod -Uri https://slack.com/api/chat.postMessage -Headers $headers -Body $BodySlackJson -Method Post -ContentType 'application/json'
}
if ($teams -and $connector -eq "teams") {
Write-Host "Sending to teams"
return Invoke-RestMethod -Method post -ContentType 'application/Json' -Body $body -Uri $teamsUri
}
}
# function update body
Function Update_Body($body, $connector) {
if ($connector -eq "slack") {
$body['attachments'][0]['text'] = "Domain *" + $domainName + "* - " + $dateScan.ToString("dd/MM/yyyy") + " - *Global Score " + [string]$total_point + "* : "
$body['attachments'][0]['fields'][0]['value'] = $str_trusts.Split(" ")[1].Trim() + " Trusts: " + $str_trusts.Split(" ")[0].Trim()
$body['attachments'][0]['fields'][1]['value'] = $str_staleObject.Split(" ")[1].Trim() + " Stale Object: " + $str_staleObject.Split(" ")[0].Trim()
$body['attachments'][0]['fields'][2]['value'] = $str_privilegeAccount.Split(" ")[1].Trim() + " Privileged Group: " + $str_privilegeAccount.Split(" ")[0].Trim()
$body['attachments'][0]['fields'][3]['value'] = $str_anomalies.Split(" ")[1].Trim() + " Anomalies: " + $str_anomalies.Split(" ")[0].Trim()
return $body
}
if ($connector -eq "teams") {
return $body.Replace("abc",$str_total_point).Replace("cbd", $str_trusts).Replace("def", $str_staleObject).Replace("asx", $str_privilegeAccount).Replace("dse", $str_anomalies).Replace("domain_env", $domainName).Replace("date_scan", $dateScan.ToString("dd/MM/yyyy"))
}
}
# function to deal with slack color
Function Add_Color($p){
if ($p -is [ValueType]) {
$point = $p
} else {
$p1 = $p | Measure-Object -Sum Points
$point = $p1.Sum
}
if ($point -ge 75) {
return [string]$point + " :red_circle:"
} elseIf ($point -ge 50 -and $point -lt 75) {
return [string]$point + " :large_orange_circle:"
} elseIf ($point -ge 25 -and $point -lt 50) {
return [string]$point + " :large_yellow_circle:"
} elseIf ($point -ge 0 -and $point -lt 25) {
return [string]$point + " :large_green_circle:"
} else {
return [string]$point + " :large_green_circle:"
}
}
# function extract HealthcheckRiskRule data
Function ExtractXML($xml,$category) {
$value = $xml.HealthcheckRiskRule | Select-Object Category, Points, Rationale, RiskId | Where-Object Category -eq $category
if ($value -eq $null)
{
$value = New-Object psobject -Property @{
Category = $category
Points = 0
}
}
return $value
}
# function to calc sum from xml
Function CaclSumGroup($a,$b,$c,$d) {
$a1 = $a | Measure-Object -Sum Points
$b1 = $b | Measure-Object -Sum Points
$c1 = $c | Measure-Object -Sum Points
$d1 = $d | Measure-Object -Sum Points
return $a1.Sum + $b1.Sum + $c1.Sum + $d1.Sum
}
# function to calc sum from one source
Function IsEqual($a,$b) {
[int]$a1 = $a | Measure-Object -Sum Points | Select-Object -Expand Sum
[int]$b1 = $b | Measure-Object -Sum Points | Select-Object -Expand Sum
if($a1 -eq $b1) {
return 1
}
return 0
}
# function to get diff between two reports
Function DiffReport($xml1,$xml2,$action) {
$result = ""
Foreach ($rule in $xml1) {
$found = 0
Foreach ($rule2 in $xml2) {
if ($rule.RiskId -and $rule2.RiskId) {
# if not warning and ...
if ($action -ne ":arrow_forward:" -and ($rule2.RiskId -eq $rule.RiskId)) {
$found = 1
break
# else if warning and
} elseIf ($action -eq ":arrow_forward:" -and ($rule2.RiskId -eq $rule.RiskId) -and ($rule2.Rationale -ne $rule.Rationale)) {
Write-Host $action + " *+" + $rule.Points + "* - " + $rule.Rationale $rule2.Rationale
$found = 2
break
}
}
}
if ($found -eq 0 -and $rule.Rationale -and $action -ne ":arrow_forward:") {
Write-Host $action + " *+" + $rule.Points + "* - " + $rule.Rationale $rule2.RiskId $rule.RiskId
If ($action -eq ":heavy_exclamation_mark:") {
$result = $result + $action + " *+" + $rule.Points + "* - " + $rule.Rationale + "`n"
} else {
$result = $result + $action + " *-" + $rule.Points + "* - " + $rule.Rationale + "`n"
}
} elseIf ($found -eq 2 -and $rule.Rationale) {
$result = $result + $action + " *" + $rule.Points + "* - " + $rule.Rationale + "`n"
}
}
return $result
}
# Check if program exist
if (-not(Test-Path $pingCastleFullpath)) {
Write-Error -Message ("Path not found {0}" -f $pingCastleFullpath)
}
# Check if log directory exist. If not, create it
if (-not (Test-Path $pingCastleReportLogs)) {
try {
$null = New-Item -Path $pingCastleReportLogs -ItemType directory
}
Catch {
Write-Error -Message ("Error for create directory {0}" -f $pingCastleReportLogs)
}
}
# Try to start program and catch any error
try {
Set-Location -Path $PingCastle.ProgramPath
Start-Process -FilePath $pingCastleFullpath -ArgumentList $PingCastle.Arguments @splatProcess
}
Catch {
Write-Error -Message ("Error for execute {0}" -f $pingCastleFullpath)
}
# Check if report exist after execution
foreach ($pingCastleTestFile in ($pingCastleReportFullpath, $pingCastleReportXMLFullpath)) {
if (-not (Test-Path $pingCastleTestFile)) {
Write-Error -Message ("Report file not found {0}" -f $pingCastleTestFile)
}
}
# Get content on XML file
try {
$contentPingCastleReportXML = $null
$contentPingCastleReportXML = (Select-Xml -Path $pingCastleReportXMLFullpath -XPath "/HealthcheckData/RiskRules").node
$domainName = (Select-Xml -Path $pingCastleReportXMLFullpath -XPath "/HealthcheckData/DomainFQDN").node.InnerXML
$dateScan = [datetime](Select-Xml -Path $pingCastleReportXMLFullpath -XPath "/HealthcheckData/GenerationDate").node.InnerXML
# get metrics
$Anomalies = ExtractXML $contentPingCastleReportXML "Anomalies"
$PrivilegedAccounts = ExtractXML $contentPingCastleReportXML "PrivilegedAccounts"
$StaleObjects = ExtractXML $contentPingCastleReportXML "StaleObjects"
$Trusts = ExtractXML $contentPingCastleReportXML "Trusts"
$total_point = CaclSumGroup $Trusts $StaleObjects $PrivilegedAccounts $Anomalies
}
catch {
Write-Error -Message ("Unable to read the content of the xml file {0}" -f $pingCastleReportXMLFullpath)
}
$str_total_point = Add_Color $total_point
$str_trusts = Add_Color $Trusts
$str_staleObject = Add_Color $StaleObjects
$str_privilegeAccount = Add_Color $PrivilegedAccounts
$str_anomalies = Add_Color $Anomalies
$BodySlack = updateSlackColor $BodySlack $total_point
$BodySlack = Update_Body $BodySlack "slack"
$BodyTeams = Update_Body $BodyTeams "teams"
$old_report = (Get-ChildItem -Path "Reports" -Filter "*.xml" -Attributes !Directory | Sort-Object -Descending -Property LastWriteTime | select -First 1)
$old_report.FullName
$current_scan = ""
$final_thread = ""
# Check if PingCastle previous score file exist
if (-not ($old_report.FullName)) {
# if don't exist, sent report
$sentNotification = $true
Write-Host "First time run"
$BodySlack['attachments'][0]['fields'][4]['value'] = "First PingCastle scan ! :tada:"
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "First PingCastle scan ! 🥳 `n`n ")
$newCategoryContent = $Anomalies + $PrivilegedAccounts + $StaleObjects + $Trusts
$result = ""
Foreach ($rule in $newCategoryContent) {
$action = ":heavy_exclamation_mark: *+"
if ($rule.RiskId) {
$result = $result + $action + $rule.Points + "* - " + $rule.Rationale + "`n"
}
}
$final_thread = $result
} else {
$newCategoryContent = $Anomalies + $PrivilegedAccounts + $StaleObjects + $Trusts
Foreach ($rule in $newCategoryContent) {
$action = ":heavy_exclamation_mark: *+"
if ($rule.RiskId) {
$current_scan = $current_scan + $action + $rule.Points + "* - " + $rule.Rationale + "`n"
}
}
$current_scan = "`n`---`n" + $current_scan
# Get content of previous PingCastle score
try {
$pingCastleOldReportXMLFullpath = $old_report.FullName
$contentOldPingCastleReportXML = (Select-Xml -Path $pingCastleOldReportXMLFullpath -XPath "/HealthcheckData/RiskRules").node
$Anomalies_old = ExtractXML $contentOldPingCastleReportXML "Anomalies"
$PrivilegedAccounts_old = ExtractXML $contentOldPingCastleReportXML "PrivilegedAccounts"
$StaleObjects_old = ExtractXML $contentOldPingCastleReportXML "StaleObjects"
$Trusts_old = ExtractXML $contentOldPingCastleReportXML "Trusts"
$previous_score = CaclSumGroup $Trusts_old $StaleObjects_old $PrivilegedAccounts_old $Anomalies_old
Write-Host "Previous score " $previous_score
Write-Host "Current score " $total_point
}
catch {
Write-Error -Message ("Unable to read the content of the xml file {0}" -f $old_report)
}
$newCategoryContent = $Anomalies + $PrivilegedAccounts + $StaleObjects + $Trusts
$oldCategoryContent = $Anomalies_old + $PrivilegedAccounts_old + $StaleObjects_old + $Trusts_old
$addedVuln = DiffReport $newCategoryContent $oldCategoryContent ":heavy_exclamation_mark:"
$removedVuln = DiffReport $oldCategoryContent $newCategoryContent ":white_check_mark:"
$warningVuln = DiffReport $newCategoryContent $oldCategoryContent ":arrow_forward:"
# write message regarding previous score
if ([int]$previous_score -eq [int]$total_point -and (IsEqual $StaleObjects_old $StaleObjects) -and (IsEqual $PrivilegedAccounts_old $PrivilegedAccounts) -and (IsEqual $Anomalies_old $Anomalies) -and (IsEqual $Trusts_old $Trusts)) {
if ($addedVuln -or $removedVuln -or $warningVuln) {
$sentNotification = $True
$BodySlack['attachments'][0]['fields'][4]['value'] = "There is no new vulnerability yet some rules have changed !"
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "There is no new vulnerability yet some rules have changed !")
} else {
$sentNotification = $False
$BodySlack['attachments'][0]['fields'][4]['value'] = "There is no new vulnerability ! :tada:"
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "There is no new vulnerability ! 🥳")
}
} elseIf ([int]$previous_score -lt [int]$total_point) {
Write-Host "rage"
$sentNotification = $true
$BodySlack['attachments'][0]['fields'][4]['value'] = "New rules flagged *+" + [string]([int]$total_point-[int]$previous_score) + " points* :rage: "
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "New rules flagged **+" + [string]([int]$total_point-[int]$previous_score) + " points** 😠 `n`n")
} elseIf ([int]$previous_score -gt [int]$total_point) {
Write-Host "no rage"
$sentNotification = $true
$BodySlack['attachments'][0]['fields'][4]['value'] = "Yeah, some improvement have been made *-" + [string]([int]$previous_score-[int]$total_point) + " points* :smile: "
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "Yeah, some improvement have been made *-" + [string]([int]$previous_score-[int]$total_point) + " points* 😄 `n`n")
} else {
Write-Host "same global score but different score in categories"
$sentNotification = $true
$BodySlack['attachments'][0]['fields'][4]['value'] = "New rules flagged but also some fix, yet same score than previous scan"
$BodyTeams = $BodyTeams.Replace("add_new_vuln", "New rules flagged but also some fix, yet same score than previous scan `n`n")
}
$final_thread = $addedVuln + $removedVuln + $warningVuln
}
$logreport = $PingCastle.ReportFolder + "\\scan.log"
# If content is same, don't sent report
if ($sentNotification -eq $false) {
Remove-Item ("{0}.{1}" -f (Join-Path $PingCastle.ProgramPath $PingCastle.ReportFileName), '*')
Write-Information "Same value on PingCastle report. Report deleted."
"Last scan " + $dateScan | out-file -append $logreport
exit
}
# Move report to logs directory
try {
Write-Information "Sending information by email, webhook, etc..."
if ($slack) {
$r = Send_WebHook $BodySlack "slack"
if ($final_thread) {
$BodySlack2 = @{
channel = $r.channel;
thread_ts = $r.ts
text = $final_thread;
icon_emoji = ":ghost:"
username = "PingCastle Automatic run"
}
Send_WebHook $BodySlack2 "slack"
}
if ($print_current_result) {
$BodySlack3 = @{
channel = $r.channel;
thread_ts = $r.ts
text = $current_scan;
icon_emoji = ":ghost:"
username = "PingCastle Automatic run"
}
Send_WebHook $BodySlack3 "slack"
}
}
if ($teams) {
$current_scan = $current_scan.replace("'", "\'")
$final_thread = $final_thread.replace("'", "\'")
if ($print_current_result) {
$BodyTeams = $BodyTeams + $final_thread + $current_scan + "'}"
}
else {
$BodyTeams = $BodyTeams + $final_thread + "'}"
}
$BodyTeams = $BodyTeams.Replace("*","**").Replace("`n","`n`n")
$BodyTeams = $BodyTeams.Replace(":red_circle:","🔴").Replace(":large_orange_circle:","🟠").Replace(":large_yellow_circle:","🟡").Replace(":large_green_circle:","🟢")
$BodyTeams = $BodyTeams.Replace(":heavy_exclamation_mark:", "❗").Replace(":white_check_mark:", "✅").Replace(":arrow_forward:", "🔸")
$r = Send_WebHook $BodyTeams "teams"
}
# write log report
"Last scan " + $dateScan | out-file -append $logreport
$log = $BodyTeams
$log = $log + $final_thread
$log = $log.Replace("*","").Replace(":large_green_circle:","").Replace(":large_orange_circle:","").Replace(":large_yellow_circle:","").Replace(":red_circle:","").Replace(":heavy_exclamation_mark:","!").Replace(":white_check_mark:","-").Replace(":arrow_forward:",">").Replace(":tada:","")
$log = $log.Replace("{","").Replace(" text:'","").Replace("🥳","")
$log | out-file -append $logreport
$log
$pingCastleMoveFile = (Join-Path $pingCastleReportLogs $pingCastleReportFileNameDate)
Move-Item -Path $pingCastleReportFullpath -Destination $pingCastleMoveFile
$pingCastleMoveFile = (Join-Path $pingCastleReportLogs $pingCastleReportFileNameDateXML)
Move-Item -Path $pingCastleReportXMLFullpath -Destination $pingCastleMoveFile
Remove-Item ("{0}.{1}" -f (Join-Path $PingCastle.ProgramPath $PingCastle.ReportFileName), '*')
}
catch {
Write-Error -Message ("Error for move report file to logs directory {0}" -f $pingCastleReportFullpath)
}
# Try to start update program and catch any error
try {
Write-Information "Trying to update"
Start-Process -FilePath $pingCastleUpdateFullpath -ArgumentList $PingCastle.ArgumentsUpdate @splatProcess
Write-Information "Update completed"
}
Catch {
Write-Error -Message ("Error for execute update program {0}" -f $pingCastleUpdateFullpath)
}