forked from demisto/content-ci-cd-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommonServerPowerShell.ps1
739 lines (646 loc) · 21.8 KB
/
CommonServerPowerShell.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
. $PSScriptRoot\demistomock.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Scope = "", Justification = "Use of globals set by the Demisto Server")]
# Silence Progress STDOUT (e.g. long http request download progress)
$progressPreference = 'silentlyContinue'
enum ServerLogLevel {
debug
info
error
}
enum EntryTypes {
note = 1
downloadAgent = 2
file = 3
error = 4
pinned = 5
userManagement = 6
image = 7
playgroundError = 8
entryInfoFile = 9
warning = 11
map = 15
widget = 17
}
enum EntryFormats {
html
table
json
text
dbotResponse
markdown
}
# Demist Object Class for communicating with the Demisto Server
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Justification = 'use of global:DemistoServerRequest')]
class DemistoObject {
hidden [hashtable] $ServerEntry
hidden [bool] $IsDebug
hidden [bool] $IsIntegration
hidden [hashtable] $ContextArgs
DemistoObject () {
if($global:InnerContext.GetType().Name -eq 'String') {
$context = $global:InnerContext | ConvertFrom-Json -AsHashtable
}
else {
$context = $global:InnerContext
}
$this.ServerEntry = $context
$this.ContextArgs = $context.args
$this.IsDebug = $context.IsDebug
if ($this.IsDebug) {
$this.ContextArgs.Remove("debug-mode")
}
$this.IsIntegration = $context.integration
}
[hashtable] Args () {
return $this.ContextArgs
}
[hashtable] Params () {
return $this.ServerEntry.params
}
[string] GetCommand () {
return $this.ServerEntry.command
}
[hashtable] Investigation () {
return $this.ServerEntry.context.Inv
}
[hashtable] GetContext () {
return $this.ServerEntry.context.ExecutionContext
}
Log ($Entry) {
$Command = @{ type = "entryLog"; args = @{ message = $Entry } } | ConvertTo-Json -Compress -Depth 20
$global:DemistoOutputStream.WriteLine($Command)
}
Results ($EntryRaw) {
$Entry = $this.ConvertToEntry($EntryRaw)
$Command = @{ type = "result"; results = $Entry } | ConvertTo-Json -Compress -Depth 20
$global:DemistoOutputStream.WriteLine($Command)
}
[array] ConvertToEntry ($EntryRaw) {
$Entry = ""
$EntryType = $EntryRaw.GetType().name
switch ($EntryType) {
"Hashtable" {
if ($EntryRaw.ContainsKey("Contents") -and $EntryRaw.ContainsKey("ContentsFormat")) {
$Entry = @($EntryRaw)
}
else {
$Entry = @(@{Type = 1; Contents = $EntryRaw; ContentsFormat = "json" })
}
; Break
}
"Object[]" {
foreach ($EntryObj in $EntryRaw) {
if (!$Entry) {
$Entry = $this.ConvertToEntry($EntryObj)
}
else {
$Entry += $this.ConvertToEntry($EntryObj)[0]
}
}
; Break
}
"PSCustomObject" {
if ($EntryRaw.Contents -and $EntryRaw.ContentsFormat) {
$Entry = @($EntryRaw)
}
else {
$Entry = @(@{Type = 1; Contents = $EntryRaw; ContentsFormat = "json" })
}
; Break
}
default {
$EntryContent = [string]$EntryRaw
$Entry = @(@{Type = 1; Contents = $EntryContent; ContentsFormat = "text" })
; Break
}
}
return $entry
}
[array] ServerRequest ($Cmd) {
return global:DemistoServerRequest $cmd
}
[array] DT ($Value, $Name) {
return $this.ServerRequest(@{type = "dt"; name = $Name; value = $Value }).result
}
[array] GetFilePath ($ID) {
return $this.ServerRequest(@{type = "getFileByEntryID"; command = "getFilePath"; args = @{id = $ID } })
}
[array] DemistoUrls () {
return $this.ServerRequest(@{type = "demistoUrls" })
}
[array] DemistoVersion () {
return $this.ServerRequest(@{type = "demistoVersion" })
}
[string] UniqueFile () {
return New-Guid
}
[hashtable] ParentEntry () {
return $this.ServerEntry.context.ParentEntry
}
[string] GetLicenseID () {
return $this.ServerRequest(@{type = "executeCommand"; command = "getLicenseID"; args = @{ } }).id
}
Info ($Log) {
DemistoServerLog ([ServerLogLevel]::info) $Log
}
Debug ($Log) {
DemistoServerLog ([ServerLogLevel]::debug) $Log # disable-secrets-detection
}
Error ($Log) {
DemistoServerLog ([ServerLogLevel]::error) $Log
}
[array] GetIncidents () {
return $this.ServerEntry.context.Incidents
}
[array] Incidents () {
return $this.GetIncidents()
}
[hashtable] Incident () {
return $this.GetIncidents()[0]
}
# Script Functions
[array] ExecuteCommand ($Command, $CmdArgs) {
if ( $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerRequest(@{type = "executeCommand"; command = $Command; args = $CmdArgs })
}
[array] Execute ($Module, $Command, $CmdArgs) {
if ( $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerRequest(@{type = "execute"; module = $Module; command = $Command; args = $CmdArgs })
}
[array] GetAllSupportedCommands () {
if ( $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerRequest(@{type = "getAllModulesSupportedCmds" })
}
SetContext ($Name, $Value) {
if ( $this.IsIntegration ) {
throw "Method not supported"
}
$this.ServerRequest(@{type = "setContext"; name = $Name; value = $Value })
}
[Object[]] GetModules () {
if ( $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerRequest(@{type = "getAllModules" })
}
# Integration Functions
[string] IntegrationInstance () {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerEntry.context.IntegrationInstance
}
[array] Incidents ($Incidents) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$Incidents = $Incidents | ConvertTo-Json -Depth 6
return $this.Results(@{Type = 1; Contents = $Incidents; ContentsFormat = "json" })
}
[array] Credentials ($Crds) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$Credentials = $Crds | ConvertTo-Json -Depth 6
return $this.Results(@{Type = 1; Contents = $Credentials; ContentsFormat = "json" })
}
[Object[]] GetLastRun () {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
return $this.ServerRequest(@{type = "executeCommand"; command = "getLastRun"; args = @{ } })
}
SetLastRun ($Value) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$this.ServerRequest(@{type = "executeCommand"; command = "setLastRun"; args = @{ value = $Value } })
}
[Object[]] GetIntegrationContext () {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$integration_context = $this.ServerRequest(@{type = "executeCommand"; command = "getIntegrationContext"; args = @{ } })
# When Demisto Version is greater equal then "6.0.0". integration_context will be under "context" attribute.
if (DemistoVersionGreaterEqualThen -version "6.0.0") {
$integration_context = $integration_context.context
}
return $integration_context
}
SetIntegrationContext ($Value) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$this.ServerRequest(@{type = "executeCommand"; command = "setIntegrationContext"; args = @{
value = $Value
version = @{
"version" = -1
"sequenceNumber" = -1
"primaryTerm" = -1
} } })
}
[Object[]] GetIntegrationContextVersioned ($Refresh) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$integration_context = $this.ServerRequest(@{type = "executeCommand"; command = "getIntegrationContext"; args = @{ refresh = $Refresh } })
return $integration_context
}
SetIntegrationContextVersioned ($Value, $Version, $Sync) {
if ( -not $this.IsIntegration ) {
throw "Method not supported"
}
$this.ServerRequest(@{type = "executeCommand"; command = "setIntegrationContext"; args = @{value = $Value; version = $Version; sync = $Sync} })
}
}
[DemistoObject]$demisto = [DemistoObject]::New()
function global:Write-HostToLog($UserInput) { $demisto.Log($UserInput) | Out-Null }
# we override Write-Host with a function which writes to the demisto.Log.
# Incase there is need to undo this Alias, the integration/script can run the following command
# Remove-Item 'Alias:Write-Host' -Force
Set-Alias -Name 'Write-Host' -Value 'Write-HostToLog' -Scope Global
# -----------------------------------------------------------------------
# Utility Functions
# -----------------------------------------------------------------------
<#
.DESCRIPTION
Converts a string representation of args to a list
.PARAMETER Arg
The argument to convert
.PARAMETER Seperator
The seperator to use (default ',')
.OUTPUTS
Object[]. Returns an array of the arguments
#>
function ArgToList($Arg, [string]$Seperator = ",") {
if (! $Arg) {
$r = @()
}
elseif ($Arg.GetType().IsArray) {
$r = $Arg
}
elseif ($Arg[0] -eq "[" -and $Arg[-1] -eq "]") {
# json string
$r = $Arg | ConvertFrom-Json -AsHashtable
}
else {
$r = $Arg.Split($Seperator)
}
# we want to return an array and avoid one-at-a-time processing
# see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_return?view=powershell-6#return-values-and-the-pipeline
return @(, $r)
}
<#
.DESCRIPTION
Return an Error entry back to the Server
.PARAMETER Message
Messsage to display in the error entry
.PARAMETER Err
Error to log (optional)
.PARAMETER Outputs
The outputs that will be returned to playbook/investigation context (optional)
.OUTPUTS
The error entry object returned to the server
#>
function ReturnError([string]$Message, $Err, [hashtable]$Outputs) {
$demisto.Error("$Message")
if ($Err) {
$errMsg = $Err | Out-String
$demisto.Error($errMsg)
}
$entry = @{Type = [EntryTypes]::error; ContentsFormat = [EntryFormats]::text.ToString(); Contents = $message; EntryContext = $Outputs }
$demisto.Results($entry) | Out-Null
return $entry
}
<#
.DESCRIPTION
This function wraps the $demisto.results(), makes the usage of returning results to the user more intuitively.
.PARAMETER ReadableOutput
Markdown string that will be presented in the warroom, should be human readable
.PARAMETER Outputs
The outputs that will be returned to playbook/investigation context (optional)
.PARAMETER RawResponse
If not provided then will be equal to outputs. usually is the original
raw response from the 3rd party service (optional)
.OUTPUTS
The entry object returned to the server
#>
function ReturnOutputs([string]$ReadableOutput, [object]$Outputs, [object]$RawResponse) {
$entry = @{
Type = [EntryTypes]::note;
ContentsFormat = [EntryFormats]::json.ToString();
HumanReadable = $ReadableOutput;
Contents = $RawResponse;
EntryContext = $Outputs
}
# Return 'readable_output' only if needed
if ($ReadableOutput -and -not $outputs -and -not $RawResponse) {
$entry.Contents = $ReadableOutput
$entry.ContentsFormat = [EntryFormats]::text.ToString();
}
elseif ($Outputs -and -not $RawResponse) {
# if RawResponse was not provided but outputs were provided then set Contents as outputs
$entry.Contents = $Outputs
}
$demisto.Results($entry) | Out-Null
return $entry
}
<#
.DESCRIPTION
This function Gets a string and escape all special characters in it so that it can be in correct markdown format
.PARAMETER data
The string that needs to be escaped
.OUTPUTS
A string in which all special characters are escaped
#>
Function stringEscapeMD(){
[OutputType([string])]
Param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true)]
[AllowEmptyString()]
[String]$data
)
begin{
$markdown_chars = @('\', '`','*', '_', '{', '}', '[',']', '(', ')', '#', '+','-', '|', '!')
}
process {
$result = $data.Replace("`r`n", "<br>").Replace("`r", "<br>").Replace("`n", "<br>")
foreach ($char in $markdown_chars){
$result = $result.Replace("$char", "\$char")
}
$result
}
}
<#
.DESCRIPTION
This function Converts a hashtable object into an ordered dictionary object
.PARAMETER hashTable
The hash-table that needs to be converted
.OUTPUTS
Ordered dict with the same keys and values as the hashTable's
#>
Function ConvertTo-OrderedDict {
[CmdletBinding()]
[OutputType([System.Collections.Specialized.OrderedDictionary])]
Param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true)]
[AllowEmptyCollection()]
[HashTable]$hashTable
)
Process {
$OrderedDictionary = [ordered]@{ }
foreach ($Element in ($hashTable.GetEnumerator() | Sort-Object -Property Key))
{
$OrderedDictionary[$Element.Key] = $Element.Value
}
return $OrderedDictionary
}
}
<#
.DESCRIPTION
This function Gets a list of PSObjects and convert it to a markdown table
.PARAMETER collection
The list of PSObjects that will should be converted to markdown format
.PARAMETER name
The name of the markdown table. when given this name will be the title of the table
.OUTPUTS
The markdown table string representation
#>
Function TableToMarkdown{
[CmdletBinding()]
[OutputType([string])]
Param (
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true)]
[AllowEmptyCollection()]
[Object]$collection,
[Parameter(Mandatory = $false,Position = 1)]
[String]$name
)
Begin {
# Initializing $result
$result = ''
if ($name) {
$result += "### $name`n"
}
# Initializing $items
$items = @()
# Initializing $headers
$headers = @()
}
Process {
# proccessing items and headers
ForEach ($item in $collection)
{
if ($item -Is [HashTable])
{
# Need to convert hashtables to ordered dicts so that the keys/values will be in the same order
$item = $item | ConvertTo-OrderedDict
}
elseif ($item -Is [PsCustomObject]){
$newItem = @{}
$item.PSObject.Properties | ForEach-Object { $newItem[$_.Name] = $_.Value }
$item = $newItem | ConvertTo-OrderedDict
}
$items += $item
}
}
End {
if ($items)
{
if ($items[0] -is [System.Collections.IDictionary]){
$headers = $items[0].keys
}
else
{
$headers = $item[0].PSObject.Properties| ForEach-Object {$_.Name}
}
# Writing the headers line
$result += '| ' + ($headers -join ' | ')
$result += "`n"
# Writing the separator line
$separator = @()
ForEach ($key in $headers)
{
$separator += '---'
}
$result += '| ' + ($separator -join ' | ')
$result += "`n"
# Writing the values
ForEach ($item in $items)
{
$values = @()
if ($items[0] -is [System.Collections.IDictionary])
{
$raw_values = $item.values
}
else
{
$raw_values = $item[0].PSObject.Properties| ForEach-Object { $_.Value }
}
foreach ($raw_value in $raw_values)
{
if ($null -ne $raw_value)
{ try{
<# PWSH Type Code of numbers are 5 to 15. So we will handle them with ToString
and the rest are Json Serializble #>
$typeValue = $raw_value.getTypeCode().value__
$is_number = ($typeValue -ge 5 -and $typeValue -le 15)
} catch { $is_number = $false}
if ($raw_value -is [string] -or $is_number)
{
$value = $raw_value.ToString()
}
else
{
$value = $raw_value | ConvertTo-Json -Compress -Depth 5
}
}
else
{
$value = ""
}
$values += $value | stringEscapeMD
}
$result += '| ' + ($values -join ' | ')
$result += "`n"
}
}
else
{
$result += "**No entries.**`n"
}
return $result
}
}
Set-Alias -Name ConvertTo-Markdown -Value TableToMarkdown
function ConvertTo-Boolean
{
param
(
[Parameter(Mandatory=$false)][string] $value
)
switch ($value)
{
"y" { return $true; }
"yes" { return $true; }
"true" { return $true; }
"t" { return $true; }
1 { return $true; }
"n" { return $false; }
"no" { return $false; }
"false" { return $false; }
"f" { return $false; }
0 { return $false; }
}
}
<#
.DESCRIPTION
Creates a file from the given string data.
.PARAMETER file_name
The file name to use for the file in then entry result
.PARAMETER data
String data to use for the file
.PARAMETER is_file_info
If true will return an entry of type: [EntryTypes]::entryInfoFile
.OUTPUTS
Entry object to return to the server. Use $demisto.Results(obj) to actually send the entry to the server.
#>
function FileResult([string]$file_name, [string]$data, [bool]$is_file_info) {
$file_type = [EntryTypes]::file
if ($is_file_info) {
$file_type = [EntryTypes]::entryInfoFile
}
$temp = $demisto.UniqueFile()
Out-File -FilePath "$($demisto.Investigation().id)_$temp" -Encoding "utf8" -InputObject $data
return @{
"Contents" = ''
"ContentsFormat" = [EntryFormats]::text.ToString()
"Type" = $file_type
"File" = $file_name
"FileID" = $temp
}
}
function DemistoVersionGreaterEqualThen([string]$version) {
$demisto_version = $demisto.DemistoVersion().version
$version_pattern = "\d{1,2}\.\d{1,2}\.\d{1,2}"
$demisto_version = (Select-string -Pattern $version_pattern -InputObject $demisto_version).Matches[0].Value
$version = (Select-string -Pattern $version_pattern -InputObject $version).Matches[0].Value
return [version]::Parse($demisto_version) -ge [version]::Parse($version)
}
function ParseDateRange{
[CmdletBinding()]
[OutputType([System.Object[]])]
Param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$date_str
)
$now = $date = Get-Date
$number, $unit_name = $date_str.Split()
try{
$number = -([int]$number)
} catch [System.Management.Automation.RuntimeException]{
throw "No number given in '$date_str'"
}
if ($null -eq $unit_name){
throw "Time unit not given in '$date_str'"
}
if (!($unit_name.GetType() -eq [String])) {
throw "Too many arguemnts in '$date_str'"
}
if ($unit_name.Contains("minute")){
$date = $date.AddMinutes($number)
} elseif ($unit_name.Contains("hour")) {
$date = $date.AddHours($number)
} elseif ($unit_name.Contains("day")){
$date = $date.AddDays($number)
} elseif ($unit_name.Contains("week")) {
$date = $date.AddDays($number * 7)
} elseif ($unit_name.Contains("month")) {
$date = $date.AddMonths($number)
} elseif ($unit_name.Contains("year")) {
$date = $date.AddYears($number)
} else {
throw "Could not process time unit '$unit_name'. Available are: minute, hour, day, week, month, year."
}
return $date, $now
<#
.DESCRIPTION
Gets a string represents a date range ("3 day", "2 years" etc) and return the time on the past according to
the date range.
.PARAMETER date_str
a date string in a human readable format as "3 days", "5 years".
Available units: minute, hour, day, week, month, year.
.EXAMPLE
ParseDateRange("3 days") (current date it 04/01/21)
Date(01/01/21)
#>
}
function GetIntegrationContext {
[CmdletBinding()]
param (
[bool]$refresh = $true,
[bool]$withVersion = $false
)
if (DemistoVersionGreaterEqualThen -version "6.0.0") {
$integration_context = $demisto.getIntegrationContextVersioned($refresh)
if ($withVersion -eq $true) {
return $integration_context
}
return $integration_context.context
}
return $demisto.GetIntegrationContext()
}
function SetIntegrationContext ([object]$context, $version = -1, [bool]$sync = $true) {
if (DemistoVersionGreaterEqualThen -version "6.0.0") {
return $demisto.setIntegrationContextVersioned($context, $version, $sync)
}
return $demisto.SetIntegrationContext($context)
}