-
Notifications
You must be signed in to change notification settings - Fork 13
/
CxHealthMonitor.ps1
1813 lines (1508 loc) · 69.5 KB
/
CxHealthMonitor.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
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
Checkmarx CxSAST Health Monitoring System
Version 1.0
Gem Immauel (gem.immanuel@checkmarx.com)
Checkmarx Professional Services
Usage: .\CxHealthMonitor.ps1 [-cxUser cxaccount] [-cxPass cxpassword] [-audit] [-dbUser dbaccount] [-dbPass dbpassword]
The command line parameters will override the values read from the
configuration file (cx_health_mon.config.json)
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[String]
$cxUser = "",
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[String]
$cxPass = "",
[switch]
$audit,
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[String]
$dbUser = "",
[Parameter(Mandatory = $False)]
[ValidateNotNullOrEmpty()]
[String]
$dbPass = ""
)
# ----------------------- Module imports ------------------------ #
if ($audit) {
if(-not(Get-InstalledModule Invoke-SqlCmd2 -ErrorAction silentlycontinue))
{
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module Invoke-SqlCmd2 -Confirm:$False -Force
}
Import-Module "Invoke-SqlCmd2" -DisableNameChecking
}
if(-not(Get-InstalledModule CredentialManager -ErrorAction silentlycontinue))
{ #Module is imported automatically, if any cmdlets are used.
Set-PSRepository PSGallery -InstallationPolicy Trusted
Install-Module CredentialManager -Confirm:$False -Force
}
# CxSAST REST API auth values
[String] $CX_REST_GRANT_TYPE = "password"
[String] $CX_REST_SCOPE = "sast_rest_api"
[String] $CX_REST_CLIENT_ID = "resource_owner_client"
[String] $CX_REST_CLIENT_SECRET = "014DF517-39D1-4453-B7B3-9930C563627C"
# -----------------------------------------------------------------
# Input/Output Utility
# -----------------------------------------------------------------
Class IO {
# General logging
static [String] $LOG_FILE = "cx_health_mon.log"
# Event logging
static [String] $EVENT_FILE = "cx_health_mon_events.log"
hidden [DateTimeUtil] $dateUtil = [DateTimeUtil]::new()
# Files for JSON output
static [String] $FILE_SUFFIX_TIMESTAMP_FORMAT = "yyyyMMdd_hhmmssfff"
# Logs given message to configured log file
Log ([String] $message) {
# Write to log file
$this.WriteToFile($message, [IO]::LOG_FILE)
# Also write to console
$this.Console($message)
}
# Writes given message to configured events file
LogEvent ([String] $message) {
# Write to event file
$this.WriteToFile($message, [IO]::EVENT_FILE)
# Also write to log, console
$this.Log($message)
}
# Write given string to host console
Console ([String] $message) {
Write-Host $this.AddTimestamp($message)
}
# Write to JSON file
WriteJSON([AlertType] $jsonFile, [PSCustomObject] $object) {
# Ensure folder exists
[String] $jsonOutDir = $script:config.log.jsonDirectory
If (!(Test-Path $jsonOutDir)) {
New-Item -ItemType Directory -Force -Path $jsonOutDir
}
$jsonOutDir = (Get-Item -Path $jsonOutDir).FullName
# Create timestamp
[DateTime] $timestamp = $this.dateUtil.NowUTC()
[String] $fileSuffix = $timestamp.ToString([IO]::FILE_SUFFIX_TIMESTAMP_FORMAT)
if(((Get-Item -Path $jsonOutDir).LastWriteTime.DayOfYear) -lt ((Get-Date).DayOfYear))
{ #Zip the current json folder
[String] $ZIPPED_LOGS = "zipped_logs"
if(!(Get-Item $ZIPPED_LOGS -ErrorAction SilentlyContinue))
{
New-Item -ItemType Directory -Name $ZIPPED_LOGS -Force
}
[String] $jsonFolderName = (Get-Item -Path $jsonOutDir).Name
[String] $newFolderName = $jsonFolderName + "_$fileSuffix.zip"
Compress-Archive -Path $jsonFolderName -DestinationPath "$ZIPPED_LOGS\$newFolderName" -CompressionLevel Fastest
Remove-Item -Path "$jsonFolderName\*" -Force -Recurse
}
# Update JSON blob with timestamp
$object.EventDate = $this.dateUtil.Format($timestamp)
# Create file name
[String] $fileName = $jsonFile.ToString().ToLower() + "_$fileSuffix.json"
[String] $jsonFilePath = Join-Path -Path "$jsonOutDir" -ChildPath $fileName
# Write to file
Add-content $jsonFilePath -Value ($object | ConvertTo-Json)
}
# Write a pretty header output
WriteHeader() {
Write-Host "-----------------------------------------" -ForegroundColor Green
Write-Host "Checkmarx Health Monitor" -ForegroundColor Green
Write-Host "Checkmarx CxSAST: $($script:config.cx.host)"
if ($script:audit) {
Write-Host "Checkmarx Database: $($script:config.cx.db.instance)"
}
Write-Host "Poll interval (seconds): $($script:config.monitor.pollIntervalSeconds)"
Write-Host "Default scan rate (LOC / Hour): $($script:config.monitor.thresholds.scanRateAsLOCPerHour)"
Write-Host "Threshold for number of scans in the queued state: $($script:config.monitor.thresholds.queuedScansThreshold)"
Write-Host "Threshold for time spent in the queued state: $($script:config.monitor.thresholds.queuedTimeThresholdMinutes) minute(s)"
Write-Host "Scan duration threshold margin: $($script:config.monitor.thresholds.scanDurationThresholdMarginPercent)%"
Write-Host "Alerting Systems: [$($script:alertService.alertSystems.name)]"
Write-Host "-----------------------------------------" -ForegroundColor Green
}
# Utility that writes to given file
hidden WriteToFile([String] $message, [String] $file) {
$existingFile = Get-Item $file -ErrorAction SilentlyContinue
if ($existingFile) {
if(($existingFile.LastWriteTime.DayOfYear) -lt ((Get-Date).DayOfYear))
{
#Zip the current file
[DateTime] $timestamp = $this.dateUtil.NowUTC()
[String] $fileSuffix = $timestamp.ToString([IO]::FILE_SUFFIX_TIMESTAMP_FORMAT)
[String] $newFileName = $file + "_$fileSuffix"
[String] $newZipFileName = $file + "_$fileSuffix.zip"
[String] $ZIPPED_LOGS = "zipped_logs"
if(!(Get-Item $ZIPPED_LOGS -ErrorAction SilentlyContinue))
{
New-Item -ItemType Directory -Name $ZIPPED_LOGS -Force
}
Rename-Item $existingFile.Name -NewName $newFileName
Compress-Archive -Path $newFileName -DestinationPath "$ZIPPED_LOGS\$newZipFileName"
Remove-Item $newFileName -Force
}
}
Add-content $file -Value $this.AddTimestamp($message)
}
hidden [String] AddTimestamp ([String] $message) {
return $this.dateUtil.NowUTCFormatted() + ": " + $message
}
}
# -----------------------------------------------------------------
# Abstract Alert System
# -----------------------------------------------------------------
Class AlertSystem {
[String] $name = "Unknown Name. Alert System Name not explicitly set."
[String] $systemType = "Unknown system type. Alert System Type not explicitly set."
[IO] $io = [IO]::new()
[DateTimeUtil] $dateUtil = [DateTimeUtil]::new()
# Abstract constructor
AlertSystem () {
$type = $this.GetType()
if ($type -eq [AlertSystem]) {
throw("Class $type must be overridden by an alerting system implementation")
}
}
# Sends an alert for given scan
Send([String] $message) {
# Force implementation by a concrete algo
throw("Method is abstract. Needs to be overriden by an alerting system implementation.")
}
[String] GetSystemType() {
return $this.systemType
}
# By default, alert systems do not batch(combine) alert messages.
# Some systems, by design, can (ex. email systems)
# If a system can batch messages, override this to return true
[Bool] IsBatchMessages() {
return $False
}
}
# -----------------------------------------------------------------
# Standard Syslog Severities
# -----------------------------------------------------------------
Enum SyslogSeverity {
EMERGENCY = 0
ALERT = 1
CRITICAL = 2
ERROR = 3
WARNING = 4
NOTICE = 5
INFO = 6
DEBUG = 7
}
# -----------------------------------------------------------------
# Support for alerting over the Syslog protocol
# -----------------------------------------------------------------
Class SyslogAlertSystem : AlertSystem {
hidden [String] $syslogServer
hidden [int] $syslogPort
hidden [SyslogSeverity] $severity = [SyslogSeverity]::ALERT
# Constructs a syslog alerting system object
SyslogAlertSystem([String] $systemType, [String] $name, [String] $syslogServer, [int] $syslogPort) {
$this.systemType = $systemType
$this.name = $name
$this.syslogServer = $syslogServer
$this.syslogPort = $syslogPort
}
# Sends given message over UDP to configured syslog server/port
Send([String] $message) {
# If there is no message, not much to do
if (!$message) { return }
# Prepend 'Checkmarx' as marker
$message = "Checkmarx: $message"
# Syslog Facility 1 : User-level message
[int] $facility = 1
[String] $hostname = $env:computername
# Calculate the priority
[int] $priority = ([int] $facility * 8) + [int] $this.severity.value__
# "MMM dd HH:mm:ss" or "yyyy:MM:dd:-HH:mm:ss zzz"
[String] $timestamp = ($this.dateUtil.NowUTC()).ToString("MMM dd HH:mm:ss")
# Syslog packet format
[String] $syslogMessage = "<{0}>{1} {2} {3}" -f $priority, $timestamp, $hostname, $message
# Create encoded syslog packet
$encoder = [System.Text.Encoding]::ASCII
$encodedPacket = $encoder.GetBytes($syslogMessage)
# Connect to the syslog server and send packet over UDP
$udpClient = New-Object System.Net.Sockets.UdpClient
$udpClient.Connect($this.syslogServer, $this.syslogPort)
$udpClient.Send($encodedPacket, $encodedPacket.Length)
$this.io.Log("Sent syslog message to [$($this.name) : $($this.syslogServer)]")
}
}
# -----------------------------------------------------------------
# Email Alert System
# -----------------------------------------------------------------
Class EmailAlertSystem : AlertSystem {
hidden [IO] $io
hidden [String] $smtpHost
hidden [int] $smtpPort
hidden [pscredential] $smtpCredentials
hidden [String] $subject
hidden [String] $smtpSender
hidden [String[]] $recipients
hidden [Boolean] $useSsl
# Constructs the email alert system object
EmailAlertSystem ([String] $systemType, [String] $name, [String] $smtpHost, [int] $smtpPort, [String] $smtpUsername, [String] $smtpPassword, [String] $smtpSender, [String[]] $recipients, [String] $subject, [Boolean] $useSsl) {
$this.io = [IO]::new()
$this.systemType = $systemType
$this.name = $name
$this.smtpHost = $smtpHost
$this.smtpPort = $smtpPort
$this.smtpSender = $smtpSender
$this.recipients = $recipients
$this.subject = $subject
$this.useSsl = $useSsl
# Support anonymous authenticated smtp scenario
if ($smtpUsername.Length -gt 0 -and $smtpPassword.Length -gt 0) {
[CredentialsUtil] $credUtil = [CredentialsUtil]::new()
$this.smtpCredentials = $credUtil.GetPSCredential($smtpUsername, $smtpPassword)
}
}
# Override default behavior
# Indicate that this system will batch messages.
[Bool] IsBatchMessages() {
return $True
}
# Sends an email with message
Send([String] $message) {
# No-frills implementation
try {
$this.io.Log("Sending email alert to [$($this.name) : $($this.recipients)]")
$mailargs = @{
From = $this.smtpSender
Body = $message
Subject = $this.subject
To = $this.recipients
Priority = "High"
SmtpServer = $this.smtpHost
Port = $this.smtpPort
}
# If credentials are not provided then we will use anonymous smtp
if ($this.smtpCredentials) {
$mailargs.Add("Credential", $this.smtpCredentials)
}
if ($this.useSsl) {
$mailargs.Add("UseSsl", $True)
}
Send-MailMessage @mailargs
}
catch {
$this.io.Log("ERROR: [$($_.Exception.Message)] Could not send email alert. Verify email configuration.")
}
}
}
# -----------------------------------------------------------------
# Webhooks Alert System
# -----------------------------------------------------------------
Class WebhooksAlertSystem : AlertSystem {
hidden [IO] $io
hidden [String] $systemType
hidden [String] $name
hidden [String] $hook
# Constructs the email alert system object
WebhooksAlertSystem ([String] $systemType, [String] $name, [String] $hook) {
$this.io = [IO]::new()
$this.systemType = $systemType
$this.name = $name
$this.hook = $hook
}
# Sends a Webhooks with message
Send([String] $message) {
# No-frills implementation
try {
$this.io.Log("Sending alert to [$($this.name)]")
$body = @{
text = $message
}
$body = $body | ConvertTo-Json
$response = Invoke-RestMethod -Uri $this.hook -Method Post -Body $body -ContentType 'application/json'
}
catch {
$this.io.Log("ERROR: [$($_.Exception.Message)] Could not send Webhooks [$($this.systemType)] alert. Verify Webhooks [$($this.systemType)] configuration.")
}
}
}
# Enumerates types of alerts that we send
# Helps keep track of which type of alert
# was sent when and for which scan/project.
Enum AlertType {
SCAN_FAILED
SCAN_SLOW
QUEUE_SCAN_TIME_EXCEEDED
QUEUE_SCAN_EXCESS
ENGINE_OFFLINE
ENGINE_RESPONSE_SLOW
ENGINE_IDLE
ENGINE_ERROR
PORTAL_SLOW
AUDIT
}
# -----------------------------------------------------------------
# Alert Service
# -----------------------------------------------------------------
Class AlertService {
hidden [IO] $io
hidden [System.Collections.ArrayList] $alerts = @()
hidden [System.Collections.ArrayList] $alertSystems = @()
# Key = scanId_projectName_scanType_AlertType
# Value = TimeSent
hidden [Hashtable] $sent = @{ }
# Number of minutes to wait before sending an
# alert for the same scan and/or condition
hidden [TimeSpan] $waitBetweenAlerts
AlertService () {
$this.io = [IO]::new()
$this.waitBetweenAlerts = [TimeSpan]::FromMinutes($script:config.alerts.waitingPeriodBetweenAlertsMinutes)
$this.RegisterAlertSystems()
}
# Register configured alert systems
RegisterAlertSystems() {
# Register alerting systems specified in configuration file
foreach ($alertingSystem in $script:config.alertingSystems) {
# For now, we register each type of alerting systems separately.
# Enhancement would be to have configuration self-declare system type
# and have a factory create the system for you :)
# Register SMTP systems, if configured
if ($alertingSystem.smtp) {
foreach ($smtpSystem in $alertingSystem.smtp) {
$EMAIL_CREDENTIALS = "CxOverwatch.EmailAlert"
$emailCredentials = Get-StoredCredential -Target $EMAIL_CREDENTIALS #Get from Windows Credential Manager
$emailUsername = ""
$emailPassword = ""
if ($emailCredentials) {
Write-Host "Found Email credentials."
$emailUsername = $emailCredentials.UserName
$emailPassword = $emailCredentials.GetNetworkCredential().Password
}
[AlertSystem] $emailAlertSystem = [EmailAlertSystem]::new($smtpSystem.systemType, $smtpSystem.name, $smtpSystem.host, $smtpSystem.port, $emailUsername, $emailPassword, $smtpSystem.sender, $smtpSystem.recipients, $smtpSystem.subject, $smtpSystem.useSsl)
$this.AddAlertSystem($emailAlertSystem);
}
}
# Register Syslog systems, if configured
if ($alertingSystem.syslog) {
foreach ($syslogSystem in $alertingSystem.syslog) {
[AlertSystem] $syslogAlertSystem = [SyslogAlertSystem]::new($syslogSystem.systemType, $syslogSystem.name, $syslogSystem.host, $syslogSystem.port)
$this.AddAlertSystem($syslogAlertSystem);
}
}
# Register webhooks, if configured
if ($alertingSystem.webhooks) {
foreach ($webhookSystem in $alertingSystem.webhooks) {
[AlertSystem] $webhookAlertSystem = [WebhooksAlertSystem]::new($webhookSystem.systemType, $webhookSystem.name, $webhookSystem.hook)
$this.AddAlertSystem($webhookAlertSystem);
}
}
}
}
# Add an AlertSystem to the Alert Service
# This enables multiple AlertSystem implementations
# Ex. Email, Syslog, SMNP etc.
AddAlertSystem ([AlertSystem] $alertSystem) {
$this.alertSystems.Add($alertSystem)
$this.io.Log("Config: Added Alert System [$($alertSystem.name)]")
}
# Track an alert : Type and current timestamp
Track ([String] $scanKey, [AlertType] $alertType) {
$timestamp = Get-Date
[String] $alertKey = $scanKey + "_" + $alertType
if ($this.sent.ContainsKey($alertKey)) {
# Update with current timestamp
$this.sent[$alertKey] = $timestamp
}
else {
$this.sent.Add($alertKey, $timestamp)
}
}
# Should the alert be sent?
# We determine if an alert should be sent again by:
# checking if an alert had been previously sent for (scanId + projectName + scanType + alertType)
# and we're past the waiting period between alerts
[Bool] ShouldSend([String] $scanKey, [AlertType] $alertType) {
[Bool] $goForIt = $True
[String] $alertKey = $scanKey + "_" + $alertType
if ($this.sent.containsKey($alertKey)) {
[datetime] $now = Get-Date
[datetime] $lastSent = $this.sent[$alertKey]
# If we're still within (lastSent + waitingPeriod) don't send alert just yet
if ($now -lt $lastSent.Add($this.waitBetweenAlerts)) {
# $this.io.Console("Alert [$alertKey] still within waiting period between alerts.")
$goForIt = $False
}
}
return $goForIt
}
# Add an alert message to a list that will be sent as a batch on Send()
AddAlert ([AlertType] $alertType, [String] $message, [String] $scanKey) {
$this.io.LogEvent("$alertType : $message")
# Add only if given message should be sent
if ($this.ShouldSend($scanKey, $alertType)) {
$this.alerts.Add("$alertType : $message")
$this.Track($scanKey, $alertType)
}
}
# Sends out alert message
# via all registered alerting systems
Send () {
# If we don't have any alerts to send, return
if ($this.alerts.Count -eq 0) { return }
# Otherwise, send them out to every registered alerting system
foreach ($alertSystem in $this.alertSystems) {
# Batch(combine) messages is required:
# Email systems, for instance.
if ($alertSystem.IsBatchMessages()) {
[String] $batchMessage = ""
foreach ($message in $this.alerts) {
if ($message -notmatch $script:config.alerts.suppressionRegex -Or [String]::IsNullOrWhiteSpace($script:config.alerts.suppressionRegex)) {
$batchMessage += "$message`n"
} else {
Write-Host Alert [$message] suppressed due to matching suppressionRegex -ForegroundColor DarkRed
}
}
if (![string]::IsNullOrEmpty($batchMessage)) {
$alertSystem.Send($batchMessage)
}
}
else {
foreach ($message in $this.alerts) {
if ($message -notmatch $script:config.alerts.suppressionRegex -Or [String]::IsNullOrWhiteSpace($script:config.alerts.suppressionRegex)) {
$alertSystem.Send($message)
} else {
Write-Host Alert [$message] suppressed due to matching suppressionRegex -ForegroundColor DarkRed
}
}
}
}
$this.alerts.Clear()
}
}
# -----------------------------------------------------------------
# Credentials Utility
# -----------------------------------------------------------------
Class CredentialsUtil {
# Returns a PSCredential object from given plaintext username/password
[PSCredential] GetPSCredential ([String] $username, [String] $plainTextPassword) {
[SecureString] $secPassword = ConvertTo-SecureString $plainTextPassword -AsPlainText -Force
return New-Object System.Management.Automation.PSCredential ($username, $secPassword)
}
}
# -----------------------------------------------------------------
# DateTime Utility
# -----------------------------------------------------------------
Class DateTimeUtil {
# Gets timestamp in UTC in configured format
[String] NowUTCFormatted() {
return $this.Format($this.NowUTC())
}
# Gets timestamp in UTC
[DateTime] NowUTC() {
return (Get-Date).ToUniversalTime()
}
# Converts to UTC and formats
[String] ToUTCAndFormat([DateTime] $dateTime) {
return $this.Format($dateTime.ToUniversalTime())
}
# Formats time based on configured format
[String] Format([DateTime] $dateTime) {
return $dateTime.ToString($script:config.monitor.timeFormat)
}
}
# -----------------------------------------------------------------
# Simple fixed-size list
# -----------------------------------------------------------------
Class FixedSizeList {
hidden $data
hidden [int] $size
# Constructs a fixed size list
# This is a simple implementation based on a LinkedList :)
# Until CX requirements dictate a more complex impl, this'll do nicely.
FixedSizeList ([int] $size) {
$this.size = $size
$this.data = New-Object Collections.Generic.LinkedList[Object]
}
# Add data item to the list
Add([Object] $item) {
# Maintain a max of {size} items
if ($this.data.Count -eq $this.size) {
$this.data.RemoveLast()
}
$this.data.AddFirst($item)
}
# Get internal data
# Tsk,tsk..
[Array] GetData() {
return $this.data
}
}
# -----------------------------------------------------------------
# Abstract Scan Time Estimation algo
# -----------------------------------------------------------------
Class ScanTimeAlgo {
# Margin (%) to add to scan duration threshold
[double] $thresholdMargin
# Abstract constructor
ScanTimeAlgo () {
$type = $this.GetType()
if ($type -eq [ScanTimeAlgo]) {
throw("Class $type must be implemented")
}
}
# Calculates expected scan duration
[double] Estimate ([Object] $scan) {
# Force implementation by a concrete algo
throw("Method is abstract. Needs to be overriden by implementation.")
}
# Calculates elapsed time for a scan (in minutes)
[double] GetScanDuration ([Object] $scan) {
[double] $elapsedTime = 0.0
[String] $scanStart = $scan.engineStartedOn
if ($scanStart) {
[String] $scanEnd = $scan.completedOn
# Calculate scan duration
$startTime = [Xml.XmlConvert]::ToDateTime($scanStart)
if (!$scanEnd) {
$scanEnd = Get-Date
if ($script:config.monitor.useUTCTimeOnClient -eq "true") {
$scanEnd = (Get-Date).ToUniversalTime()
}
}
$diff = New-TimeSpan -Start $startTime -End $scanEnd
$elapsedTime = $diff.TotalMinutes
}
return $elapsedTime
}
}
# -----------------------------------------------------------------
# Default Scan Time Estimation algo
# -----------------------------------------------------------------
Class DefaultScanTimeAlgo : ScanTimeAlgo {
hidden [IO] $io
hidden [Hashtable] $scanHistory
# Default scan rate: LOC / hour
hidden [int] $scanRateLOCPerHour
DefaultScanTimeAlgo () {
$this.io = [IO]::new()
$this.scanHistory = [Hashtable]::new()
# Sets margin for threshold
# Threshold is calculated as (scan time + margin %)
$this.thresholdMargin = $script:config.monitor.thresholds.scanDurationThresholdMarginPercent
$this.scanRateLOCPerHour = $script:config.monitor.thresholds.scanRateAsLOCPerHour
}
# Default scan time estimation algo implementation
# Simply maintain last scan duration and use (that+%margin) as benchmark
[double] Estimate ([Object] $scan) {
[double] $scanDuration = 0.0
# If we have prior scans from this project
[String] $key = $this.GetKey($scan)
if ($this.scanHistory.Count -gt 0 -and $this.scanHistory.containsKey($key)) {
# Fetch previously completed scan
[Object] $priorScan = $this.scanHistory[$key]
$scanDuration = $this.GetScanDuration($priorScan)
}
else {
# Simple formula : LOC / scan rate and converted to minutes
$scanDuration = ($scan.loc / $this.scanRateLOCPerHour) * 60.0
# $this.io.Console("Based on simple calculation: $($scan.loc) / $($this.scanRateLOCPerHour) * 60 = $scanDuration")
}
# Margin is a percentage added on top of expected scan duration
$margin = ($scanDuration * ($this.thresholdMargin / 100.0))
return $scanDuration + $margin
}
# Returns a machine readable Scan key
[String] GetKey([Object] $scan) {
[String] $scanType = if ($scan.isIncremental -eq $True) { "I" } else { "F" }
return "$($scan.id)_$($scan.project.Name)_$scanType"
}
# Saves a finished scan's duration to scan history
StoreScanDuration ($scan) {
# Guard for case when engineStartedOn is not available which
# happens when no source code changes were detected.
if ([string]::IsNullOrEmpty($scan.engineStartedOn)) {
return
}
[String] $key = $this.GetKey($scan)
# Add scan if no prior scans exist for given key
if (!$this.scanHistory.containsKey($key)) {
# TODO: This table will need to be flushed either on a timely basis, or some other criteria
# Store data only if the scan actually was underway
if ($scan.engineStartedOn) {
$this.scanHistory.Add($key, $scan)
}
}
else {
$priorScan = $this.scanHistory[$key]
[DateTime] $priorScanStart = [Xml.XmlConvert]::ToDateTime($priorScan.engineStartedOn)
[DateTime] $currentScanStart = [Xml.XmlConvert]::ToDateTime($scan.engineStartedOn)
# Replace old scan with new scan if scan is newer
if ($priorScan.id -ne $scan.id -and $currentScanStart -gt $priorScanStart) {
# $this.io.Console("Replacing prior scan. Old scanId $($priorScan.id) Current ScanId $($scan.id)")
$this.scanHistory[$key] = $scan
}
}
}
}
# -----------------------------------------------------------------
# Reads Configuration from JSON file
# -----------------------------------------------------------------
Class Config {
hidden [IO] $io
hidden $config
static [String] $CONFIG_FILE = ".\cx_health_mon_config.json"
# Constructs and loads configuration from given path
Config () {
$this.io = [IO]::new()
$this.LoadConfig()
}
# Loads configuration from configured path
LoadConfig () {
try {
$cp = [Config]::CONFIG_FILE
$configFilePath = (Get-Item -Path $cp).FullName
$this.io.Log("Loading configuration from $configFilePath")
$this.config = Get-Content -Path $configFilePath -Raw | ConvertFrom-Json
}
catch {
$this.io.Log("Provided configuration file at [" + [Config]::CONFIG_FILE + "] is missing / corrupt.")
}
}
[PsCustomObject] GetConfig() {
return $this.config
}
}
# -----------------------------------------------------------------
# REST request methods
# -----------------------------------------------------------------
Enum RESTMethod {
GET
POST
}
# -----------------------------------------------------------------
# REST request body
# -----------------------------------------------------------------
Class RESTBody {
[String] $grantType
[String] $scope
[String] $clientId
[String] $clientSecret
RESTBody(
[String] $grantType,
[String] $scope,
[String] $clientId,
[String] $clientSecret
) {
$this.grantType = $grantType
$this.scope = $scope
$this.clientId = $clientId
$this.clientSecret = $clientSecret
}
}
# -----------------------------------------------------------------
# REST Client
# -----------------------------------------------------------------
Class RESTClient {
[String] $baseUrl
[RESTBody] $restBody
hidden [String] $token
hidden [IO] $io = [IO]::new()
# Constructs a RESTClient based on given base URL and body
RESTClient ([String] $cxHost, [RESTBody] $restBody) {
$this.baseUrl = $cxHost + "/cxrestapi"
$this.restBody = $restBody
}
<#
# returns CxSAST version
#>
[String] version () {
try {
$versionUrl = $this.baseUrl + "/system/version"
$response = Invoke-RestMethod -uri $versionUrl -method GET -TimeoutSec $script:config.monitor.apiResponseTimeoutSeconds
$cxVersion = $response.version + " HF" + $response.hotFix
}
catch {
$this.io.Log("Could not retrieve version CxSAST. Most probably using a version below 9.0. Reason: HTTP [$($_.Exception.Response.StatusCode.value__)] - $($_.Exception.Response.StatusDescription).")
$cxVersion = "below 9.0 version"
}
return $cxVersion
}
<#
# Logins to the CxSAST REST API
# and returns an API token
#>
[bool] login ([String] $username, [String] $password) {
[bool] $isLoginSuccessful = $False
$body = @{
username = $username
password = $password
grant_type = $this.restBody.grantType
scope = $this.restBody.scope
client_id = $this.restBody.clientId
client_secret = $this.restBody.clientSecret
}
[psobject] $response = $null
try {
$loginUrl = $this.baseUrl + "/auth/identity/connect/token"
$response = Invoke-RestMethod -uri $loginUrl -method POST -body $body -contenttype 'application/x-www-form-urlencoded' -TimeoutSec $script:config.monitor.apiResponseTimeoutSeconds
} catch {
$this.io.Log("Could not authenticate against Checkmarx REST API. Reason: HTTP [$($_.Exception.Response.StatusCode.value__)] - $($_.Exception.Response.StatusDescription).")
}
if ($response -and $response.access_token) {
$isLoginSuccessful = $True
# Track token internally
$this.token = $response.token_type + " " + $response.access_token
}
return $isLoginSuccessful
}
<#
# Invokes a given REST API
#>
[Object] invokeAPI ([String] $requestUri, [RESTMethod] $method, [Object] $body, [int] $apiResponseTimeoutSeconds) {
# Sanity : If not logged in, do not proceed
if ( ! $this.token) {
throw "Must execute login() first, prior to other API calls."
}
$headers = @{
"Authorization" = $this.token
"Accept" = "application/json"
}
$response = $null
try {
$uri = $this.baseUrl + $requestUri
if ($method -ieq "GET") {
$response = Invoke-RestMethod -Uri $uri -Method $method -Headers $headers -TimeoutSec $apiResponseTimeoutSeconds
}
else {
$response = Invoke-RestMethod -Uri $uri -Method $method.ToString() -Headers $headers -Body $body -TimeoutSec $apiResponseTimeoutSeconds
}
Write-Debug "ID: $($response.id)"
Write-Debug "Key: $($response.key)"
Write-Debug "Self: $($response.self)"
}
catch {
$exception = $_.Exception
$this.io.Log("REST API call failed : [$($exception.Message)]")
$this.io.Log("Status Code: $($exception.Response.StatusCode)")
if ($exception.Response.StatusCode -eq "BadRequest") {
$respstream = $exception.Response.GetResponseStream()
$sr = new-object System.IO.StreamReader $respstream
$ErrorResult = $sr.ReadToEnd()
$this.io.Log($ErrorResult)
}
}
return $response
}
}
# -----------------------------------------------------------------
# Database Client
# -----------------------------------------------------------------
Class DBClient {
hidden [IO] $io = [IO]::new()
hidden [PSCredential] $sqlAuthCreds
hidden [String] $serverInstance
# Constructs a DBClient based on given server and creds
DBClient ([String] $serverInstance, [String]$dbUser, [String] $dbPass) {
$this.serverInstance = $serverInstance
if ($dbUser -and $dbPass) {
$this.sqlAuthCreds = [CredentialsUtil]::new().GetPSCredential($dbUser, $dbPass)
}
}
# Executes given SQL using either SQLServer authentication or Windows, depending on given PSCredential object
[PSObject] ExecSQL ([String] $sql, [Hashtable] $parameters) {
# $this.io.Console("Executing $sql")
try {
if ($this.sqlAuthCreds.UserName) {
$cred = $this.sqlAuthCreds
return Invoke-Sqlcmd2 -ServerInstance $this.serverInstance -Credential @cred -Query $sql -SqlParameters $parameters
}
else {
return Invoke-Sqlcmd2 -ServerInstance $this.serverInstance -Query $sql -SqlParameters $parameters
}
}
catch {
$this.io.Log("Database execution error. $($_.Exception.GetType().FullName), $($_.Exception.Message)")
# Force exit during dev run - runtime savior
Exit
}
}
}
# -----------------------------------------------------------------
# Engine(s) Monitor
# -----------------------------------------------------------------
Class EngineMonitor {
hidden [IO] $io
hidden [AlertService] $alertService
hidden [RESTClient] $cxSastRestClient
hidden [DateTimeUtil] $dateUtil
hidden [String] $cxVersion