CyHelper.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
<#
    Helper function.
 
    Converts a given string or byte array to Base64 "urlencoding" format (= replace certain special characters from the Base64 alphabet with URL safe chars)
#>

function ConvertTo-Base64UrlEncoding {
    Param(
        [parameter(Mandatory=$true)]
        [Object]$s
    )
    if ($s -is [String]) {
        $s = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($s)) # convert to base64
    } elseif ($s -is [byte[]]) {
        $s = [Convert]::ToBase64String($s)
    }
    $s.Split("=")[0].Replace("+", "-").Replace("/", "_") # alphabet replacement from regular base64 to base64urlencoded
}

<#
    Helper function.
 
    Converts a given string from Base64 "urlencoding" format (= replace certain special characters from the Base64 alphabet with URL safe chars) to a string
#>

function ConvertFrom-Base64UrlEncoding {
    Param(
        [parameter(Mandatory=$true)]
        [String]$s
    )
    $s = $s.Replace("-", "+").Replace("_", "/") # alphabet replacement from base64urlencoded to regular
    while ($s.Length % 4 -ne 0) { $s += "=" }   # padding
    [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s))
}


<#
.SYNOPSIS
    Converts the named "date" fields from CSV data (in "M/d/yyyy h:mm:ss tt" format) into datetime objects so that they can be exported to Excel.
 
.DESCRIPTION
    All date/time data is treated as UTC.
 
    Format defaults to "M/d/yyyy h:mm:ss tt"
 
#>

function Convert-FromCSVDate {
    Param (
        [parameter(Mandatory=$True)]
        [PSObject]$Data,
        [Parameter(Mandatory=$True)]
        [Array]$Fields,
        [Parameter(Mandatory=$False)]
        [Array]$Format = "M/d/yyyy h:mm:ss tt"
    )
    $Data | ForEach-Object {
        # each row
        ForEach ($field in $Fields) {
            if (![string]::IsNullOrWhiteSpace($_.$field)) {
                try {
                    $t = $_.$field
                    $_.$field = [datetime]::ParseExact($_.$field, $Format, [cultureinfo]::InvariantCulture)
                } catch {
                    Write-Error "Could not convert date: $($t), exception: $($_.Exception.ItemName)"
                }
            }
        }
        $_
    }
}

<#
.SYNOPSIS
    Returns a hash map with the consoles configuration list for API and TDR modules
 
.DESCRIPTION
    Reads "consoles.json" from $HOME\ as a short-hand way to reference the credentials and settings
    to access one or more Cylance consoles.
#>

function Get-CyConsoleConfig {
    @("$($HOME)\TDRs\", "$($HOME)" ) | 
        ForEach-Object {
            if (Test-Path -Path "$($_)\consoles.json" -PathType Leaf) {
                # PowerShell parser chokes on JS comments... pffft
                $script:ConsolesJsonPath = "$($_)\consoles.json"
                Write-Verbose "consoles.json path used: $($script:ConsolesJsonPath)"
                Get-Content "$($_)\consoles.json" | Select-String -NotMatch -Pattern "^[\s]*//.*$" | ConvertFrom-Json
                return
            }
        }
    @()
}

<#
.SYNOPSIS
    Adds a console entry to the consoles.json file.
 
.PARAMETER Console
    Mandatory. The console ID you will use to refer to this console entry in your consoles.json file. See the README for CyCLI module.
 
.PARAMETER Id
    Mandatory. API ID
 
.PARAMETER Secret
    Mandatory. API Secret
 
.PARAMETER TenantId
    Mandatory. API Tenant ID
 
.PARAMETER Uri
    Optional. URI to obtain API token, e.g. "https://protectapi<-region>.cylance.com/auth/v2/token". Defaults to EUC1 region.
 
.PARAMETER Token
    Optional. If you would like to use TDR access as well, specify TDR token for console.
 
#>

function New-CyConsoleConfig {
    Param (
        [parameter(Mandatory=$true)]
        [String]$Console,
        [parameter(Mandatory=$true)]
        [String]$APIId,
        [parameter(Mandatory=$true)]
        [SecureString]$APISecret,
        [parameter(Mandatory=$true)]
        [String]$APITenantId,
        [parameter(Mandatory=$false)]
        [String]$Token,
        [parameter(Mandatory=$false)]
        [String]$TDRUrl = "https://protect-euc1.cylance.com/Reports/ThreatDataReportV1/",
        [parameter(Mandatory=$false)]
        [String]$APIAuthUrl = "https://protectapi-euc1.cylance.com/auth/v2/token"
        )
        $Consoles = Get-CyConsoleConfig
        if ($script:ConsolesJsonPath -eq $null) {
            $script:ConsolesJsonPath = "$($HOME)\consoles.json"
        }
        try {
            # was: $APISecret = Read-Host -AsSecureString
            $DPAPISecret = ConvertFrom-SecureString -SecureString $APISecret
            $handle = CyAPIHandle -APIId $id -APISecret $Secret -APITenantId $APITenantId -APIAuthUrl $APIAuthUrl -Scope None
            # https://social.technet.microsoft.com/wiki/contents/articles/4546.working-with-passwords-secure-strings-and-credentials-in-windows-powershell.aspx
            $NewConsole = @{
                    ConsoleId = $Console
                    AutoRetrieve = $true
                    APIId = $APIId
                    APISecret = $DPAPISecret
                    APITenantId = $APITenantId
                    APIUrl = $APIAuthUrl
                    Token = $Token
                    TDRUrl = $TDRUrl
                }
            if ($Consoles -eq $null) {
                $Consoles = @( $NewConsole )
            } else {
                $Consoles += $NewConsole
            }
            Copy-Item $script:ConsolesJsonPath "$($script:ConsolesJsonPath).bak" -Force
            ConvertTo-Json $Consoles | Out-File -FilePath $script:ConsolesJsonPath -Force
        } catch {
            $_.Exception
            return
        }
}

<#
.SYNOPSIS
    Removes a console configuration entry from consoles.json
 
#>

function Remove-CyConsoleConfig {
    [CmdletBinding()]
    Param()
    DynamicParam {
        Get-CyConsoleArgumentAutoCompleter -Mandatory -ParameterName "Console"
    }

    Begin {
    }

    Process {
        $Consoles = (Get-CyConsoleConfig) | Where-Object ConsoleId -ne $PSBoundParameters.Console
        ConvertTo-Json $Consoles | Out-File -FilePath $script:ConsolesJsonPath -Force
    }
}

<#
.SYNOPSIS
    Gets a DynamicParam definition that enables auto-completion to specify a single or multiple
    console IDs as an argument.
 
.PARAMETER Mandatory
    Makes the dynamic parameter mandatory.
 
.PARAMETER AllowMultiple
    Allows specification of multiple comma-separated consoles arguments
 
.PARAMETER ParameterName
    The name of the dynamic parameter (typically "Console" or "Consoles")
 
#>

function Get-CyConsoleArgumentAutoCompleter {
    [CmdletBinding()]
    Param (
        [parameter(Mandatory=$False)]
        [Switch]$AllowMultiple = $False,
        [parameter(Mandatory=$False)]
        [Switch]$Mandatory,
        [parameter(Mandatory=$True)]
        [String]$ParameterName,
        [parameter(Mandatory=$False)]
        [String]$ParameterSetName
    )
    
    $consolesAttributes = new-object -Type System.Collections.ObjectModel.Collection[System.Attribute]
    $consolesParam = new-object System.Management.Automation.ParameterAttribute
    $consolesParam.Mandatory = $Mandatory
    $consolesParam.HelpMessage = "Enter one or more console IDs, separated by commas"
    if ([String]::Empty -ne $ParameterSetName) { $consolesParam.ParameterSetName = $ParameterSetName }
    $consolesAttributes.Add($consolesParam)    
    $consoleIds = (Get-CyConsoleConfig).ConsoleId
    $consoleIdsValidateSetAttribute = New-Object -type System.Management.Automation.ValidateSetAttribute($consoleIds)
    $consolesAttributes.Add($consoleIdsValidateSetAttribute)
    if ($AllowMultiple) { 
        $consoleIdsRuntimeDefinedParam = new-object -Type System.Management.Automation.RuntimeDefinedParameter("$($ParameterName)", [String[]], $consolesAttributes)
    } else { 
        $consoleIdsRuntimeDefinedParam = new-object -Type System.Management.Automation.RuntimeDefinedParameter("$($ParameterName)", [String], $consolesAttributes)
    }
    $paramDictionary = new-object -Type System.Management.Automation.RuntimeDefinedParameterDictionary
    $paramDictionary.Add("$($ParameterName)", $consoleIdsRuntimeDefinedParam)
    return $paramDictionary
}