StingarCM.psm1
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 |
#Region './_PrefixCode.ps1' 0 # Code in here will be prepended to top of the psm1-file. Set-StrictMode -Version Latest #EndRegion './_PrefixCode.ps1' 3 #Region './Classes/Helper/HelperLog.Class.ps1' 0 class HelperLog { HelperLog() { } static [string] FormatLogMessage([string]$Message) { $timestampRoundTrip = Get-Date -Format 'o' $callerName = (Get-PSCallStack)[1].Command return "$timestampRoundTrip [$callerName] $Message" } } #EndRegion './Classes/Helper/HelperLog.Class.ps1' 11 #Region './Private/App/Clear-IpBlockListFiles.ps1' 0 function Clear-IpBlockListFiles { $blockListWildCardFilePath = Join-Path -Path $Script:AppConfig.Config.BlockListPath -ChildPath ([string]::Format($Script:AppConfig.Config.BlockListFileNameFormat, '*')) Get-ChildItem -Path $blockListWildCardFilePath -ErrorAction Stop | ForEach-Object { '' | Out-File -Path $_.FullName -NoNewline -Encoding ascii } } #EndRegion './Private/App/Clear-IpBlockListFiles.ps1' 6 #Region './Private/App/Convert-CsvColumnToArrayList.ps1' 0 function Convert-CsvColumnToArrayList ([System.Collections.ArrayList]$ArrayList, [string]$FilePath, [string]$ColumnName) { Write-Verbose -Message ([HelperLog]::FormatLogMessage("Processing CSV: $FilePath")) Import-Csv -Path $FilePath | ForEach-Object { try { $csvColumnData = $_."$ColumnName" if ($ArrayList.Contains($csvColumnData) -eq $false) { $ArrayList.Add($csvColumnData) | Out-Null } } catch [Exception] { Write-Warning -Message ([HelperLog]::FormatLogMessage("Error while trying to add item from column: $ColumnName")) } } } #EndRegion './Private/App/Convert-CsvColumnToArrayList.ps1' 14 #Region './Private/App/Export-Configuration.ps1' 0 function Export-Configuration { $jsonConfig = $Script:AppConfig.Config | ConvertTo-Json $jsonConfig | Out-File -FilePath (Get-ConfigurationFilePath -ConfigurationName $Script:AppConfig.Config.ConfigurationName) } #EndRegion './Private/App/Export-Configuration.ps1' 4 #Region './Private/App/Export-IpBlockListFiles.ps1' 0 function Export-IpBlockListFiles ([Collections.ArrayList]$IpBlockList) { if ($null -eq $IpBlockList -or ($null -ne $IpBlockList -and $null -ne $IpBlockList.Count -and $IpBlockList.Count -eq 0)) { Write-Verbose -Message ([HelperLog]::FormatLogMessage('No attack IPs to import.')) return } Write-Verbose -Message ([HelperLog]::FormatLogMessage("IPs added: $($IpBlockList.Count)")) if ($IpBlockList.Count -le $Script:AppConfig.Config.MaxIpPerBlockList) { Export-IpBlockListToSingleFile -IpBlockList $IpBlockList } else { Export-IpBlockListToMultipleFiles -IpBlockList $IpBlockList } } #EndRegion './Private/App/Export-IpBlockListFiles.ps1' 14 #Region './Private/App/Export-IpBlockListToMultipleFiles.ps1' 0 function Export-IpBlockListToMultipleFiles ([Collections.ArrayList]$IpBlockList) { $blockListFileIndex = 0 for ($ipBlockListIndex = 0; $ipBlockListIndex -lt $IpBlockList.Count; $ipBlockListIndex++) { if ($ipBlockListIndex % $Script:AppConfig.Config.MaxIpPerBlockList -eq 0) { $blockListFileIndex = $blockListFileIndex + 1 $blockListFilePath = Join-Path -Path $Script:AppConfig.Config.BlockListPath -ChildPath ([string]::Format($Script:AppConfig.Config.BlockListFileNameFormat, $blockListFileIndex)) Write-Verbose -Message ([HelperLog]::FormatLogMessage("Creating multiple external block list file: $blockListFilePath")) $IpBlockList[$ipBlockListIndex] | Out-File -FilePath $blockListFilePath -Encoding ascii } else { $IpBlockList[$ipBlockListIndex] | Out-File -FilePath $blockListFilePath -Encoding ascii -Append } } } #EndRegion './Private/App/Export-IpBlockListToMultipleFiles.ps1' 15 #Region './Private/App/Export-IpBlockListToSingleFile.ps1' 0 function Export-IpBlockListToSingleFile ([Collections.ArrayList]$IpBlockList) { $blockListFilePath = Join-Path -Path $Script:AppConfig.Config.BlockListPath -ChildPath ([string]::Format($Script:AppConfig.Config.BlockListFileNameFormat, '1')) Write-Verbose -Message ([HelperLog]::FormatLogMessage("Creating single external block list file: $blockListFilePath")) $IpBlockList | Out-File -FilePath $blockListFilePath -Encoding ascii } #EndRegion './Private/App/Export-IpBlockListToSingleFile.ps1' 7 #Region './Private/App/Export-RawAttackDataToCsv.ps1' 0 function Export-RawAttackDataToCsv { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases', '')] [CmdletBinding()] param ( [string]$Path, [Int32]$MaxIndicatorReturnSize, [Int32]$AttackAgeInDays, [bool]$Append=$false, [string]$LastAttackerDataFetchTimestamp ) process { # Determine how old the attack data should be. $reportTimeRange = (Get-Date).AddDays(-1 * $AttackAgeInDays).ToUniversalTime() if ([string]::IsNullOrEmpty($LastAttackerDataFetchTimestamp) -eq $false) { $reportTimeRange = $LastAttackerDataFetchTimestamp } $reportTime = Get-Date -Format 'yyyy-MM-ddTHH:mm:ssZ' -Date $reportTimeRange Write-Verbose -Message ([HelperLog]::FormatLogMessage("Get attacks from $reportTime")) $indicatorRaw = Get-CifIndicator -limit $MaxIndicatorReturnSize -reporttime $reportTime if ($null -ne $indicatorRaw -and $null -ne $indicatorRaw.Data -and $null -ne $indicatorRaw.Data.Count -and $indicatorRaw.Data.Count -gt 0) { # Determine the oldest attack and how many days have passed. $indicatorSortByOldest = $indicatorRaw.Data | Sort-Object -Property reporttime $oldestIndicator = $indicatorSortByOldest | Select-Object -First 1 -ExpandProperty reporttime $newestIndicator = $indicatorSortByOldest | Select-Object -Last 1 -ExpandProperty reporttime $firstAttackAgeInDays = [Math]::Ceiling(((Get-Date) - (Get-Date -Date $oldestIndicator)).TotalDays) # Build columns to convert everything to joined strings otherwise # output will list arrays as Object[] instead of actual data. $mergedColumnDataProperty = Merge-ColumnDataArrayToString -InputObject $indicatorSortByOldest[0] # Export all attack data based on the time it occurred. for ($dayIndex = 0; $dayIndex -le $firstAttackAgeInDays; $dayIndex++) { $currentIndicatorTimestamp = (Get-Date).AddDays(-1 * $dayIndex) $indicatorReportTime = Get-Date -Format 'yyyyMMdd' -Date $currentIndicatorTimestamp $indicatorReportTimeFileFormat = Get-Date -Format $Script:AppConfig.Config.AttackerDataFileNameDateFormat -Date $currentIndicatorTimestamp $csvFilePath = Join-Path -Path $Path -ChildPath ([string]::Format($Script:AppConfig.Config.AttackerDataFileNameFormat, $indicatorReportTimeFileFormat)) if (((Test-Path -Path $csvFilePath) -eq $false) -or $PSBoundParameters.ContainsKey('Force') -or $Append -eq $true) { $currentIndicator = $indicatorSortByOldest | Where-Object { (Get-Date -Format 'yyyyMMdd' -Date $_.reporttime) -eq $indicatorReportTime } if ($currentIndicator) { $paramExport = @{ Path = $csvFilePath Append = $Append } $currentIndicator | Select-Object -Property $mergedColumnDataProperty | Export-Csv @paramExport Write-Verbose -Message ([HelperLog]::FormatLogMessage("Export attacker IP data to CSV: $csvFilePath")) Write-Verbose -Message ([HelperLog]::FormatLogMessage("Attacker IP count: $($currentIndicator.Count)")) $Script:AppConfig.Config.LastAttackerDataFetchTimestamp = $newestIndicator } } } } } } #EndRegion './Private/App/Export-RawAttackDataToCsv.ps1' 59 #Region './Private/App/Get-Configuration.ps1' 0 function Get-Configuration ([string]$ConfigurationName) { $configFilePath = Get-ConfigurationFilePath -ConfigurationName $ConfigurationName if (Test-Path -Path $configFilePath) { Write-Verbose -Message ([HelperLog]::FormatLogMessage("Read existing config file: $configFilePath")) Get-Content -Path $configFilePath -Raw | ConvertFrom-Json } else { Write-Verbose -Message ([HelperLog]::FormatLogMessage("Create new config: $ConfigurationName")) New-Configuration -ConfigurationName $ConfigurationName } } #EndRegion './Private/App/Get-Configuration.ps1' 13 #Region './Private/App/Get-ConfigurationFilePath.ps1' 0 function Get-ConfigurationFilePath ([string]$ConfigurationName) { Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/config/config.json" } #EndRegion './Private/App/Get-ConfigurationFilePath.ps1' 3 #Region './Private/App/Get-EnvHome.ps1' 0 function Get-EnvHome { $Env:HOME } #EndRegion './Private/App/Get-EnvHome.ps1' 3 #Region './Private/App/Get-RootPath.ps1' 0 function Get-RootPath ([string]$Path) { if ([string]::IsNullOrEmpty($Path)) { $Path = Get-EnvHome } if ([string]::IsNullOrEmpty($Path)) { $Path = $Env:HOMEDRIVE + $Env:HOMEPATH } if ([string]::IsNullOrEmpty($Path)) { $Path = $Env:USERPROFILE } if ([string]::IsNullOrEmpty($Path)) { throw 'The Path parameter should be set to a valid home path. By default, the environment variable $Env:HOME is used, then $Env:HOMEDRIVE + $Env:HOMEPATH, and finally $Env:USERPROFILE.' } Join-Path -Path $Path -ChildPath '.stingarcm' } #EndRegion './Private/App/Get-RootPath.ps1' 19 #Region './Private/App/Import-AttackDataCsvToIpBlockList.ps1' 0 function Import-AttackDataCsvToIpBlockList ([Collections.ArrayList]$IpBlockList) { # Import attack IPs from the past few days. for ($currentDay = 0; $currentDay -le $Script:AppConfig.Config.DaysToBlockIp; $currentDay++) { $indicatorReportTimeFileFormat = Get-Date -Format $Script:AppConfig.Config.AttackerDataFileNameDateFormat -Date (Get-Date).AddDays(-1 * $currentDay) $currentDayCsvFilePath = Join-Path -Path $Script:AppConfig.Config.AttackerDataPath -ChildPath ([string]::Format($Script:AppConfig.Config.AttackerDataFileNameFormat, $indicatorReportTimeFileFormat)) if (Test-Path -Path $currentDayCsvFilePath) { Convert-CsvColumnToArrayList -ArrayList $IpBlockList -FilePath $currentDayCsvFilePath -ColumnName 'indicator' } } # Import manual ban IP list. if (Test-Path -Path $Script:AppConfig.Config.ManualIpBlockListFilePath) { Convert-CsvColumnToArrayList -ArrayList $IpBlockList -FilePath $Script:AppConfig.Config.ManualIpBlockListFilePath -ColumnName 'indicator' } } #EndRegion './Private/App/Import-AttackDataCsvToIpBlockList.ps1' 16 #Region './Private/App/Initialize-Configuration.ps1' 0 function Initialize-Configuration ([string]$ConfigurationName, [string]$Path) { $Script:AppConfig = @{ Config = @{} CifApiTokenPlainText = '' AppPath = '' } Initialize-RootPath -ConfigurationName $ConfigurationName -Path $Path $Script:AppConfig.Config = Get-Configuration -ConfigurationName $ConfigurationName $Script:AppConfig.CifApiTokenPlainText = (New-Object -TypeName System.Net.NetworkCredential('', (ConvertTo-SecureString -String $Script:AppConfig.Config.CifApiToken))).Password } #EndRegion './Private/App/Initialize-Configuration.ps1' 13 #Region './Private/App/Initialize-RootPath.ps1' 0 function Initialize-RootPath ([string]$ConfigurationName, [string]$Path) { $Script:AppConfig.AppPath = Get-RootPath -Path $Path Write-Verbose -Message ([HelperLog]::FormatLogMessage("Setting Script:AppConfig.AppPath to [$($Script:AppConfig.AppPath)]")) New-Item -Path $Script:AppConfig.AppPath -ItemType Directory -Force | Out-Null if (-not (Test-Path -Path $Script:AppConfig.AppPath)) { throw "Unable to access app path [$($Script:AppConfig.AppPath)]" } $configPath = Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/config" New-Item -Path $configPath -ItemType Directory -Force | Out-Null if (-not (Test-Path -Path $configPath)) { throw "Unable to access config path [$configPath]" } $logPath = Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/log" New-Item -Path $logPath -ItemType Directory -Force | Out-Null if (-not (Test-Path -Path $logPath)) { throw "Unable to access log path [$logPath]" } $dataPath = Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/data" New-Item -Path $dataPath -ItemType Directory -Force | Out-Null if (-not (Test-Path -Path $dataPath)) { throw "Unable to access data path [$dataPath]" } } #EndRegion './Private/App/Initialize-RootPath.ps1' 27 #Region './Private/App/Merge-ColumnDataArrayToString.ps1' 0 function Merge-ColumnDataArrayToString { [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '')] [CmdletBinding()] Param ( $InputObject ) $newColumnCollection = [System.Collections.ArrayList]@() $InputObject | Get-Member -MemberType Property,NoteProperty -ErrorAction SilentlyContinue | ForEach-Object { $originalColumnName = $_.Name $newColumnExpression = Invoke-Expression -Command "@{Name='$originalColumnName'; Expression={`$_.$originalColumnName -join ';'}}" $newColumnCollection.Add($newColumnExpression) | Out-Null } return $newColumnCollection } #EndRegion './Private/App/Merge-ColumnDataArrayToString.ps1' 16 #Region './Private/App/New-Configuration.ps1' 0 function New-Configuration { [CmdletBinding(SupportsShouldProcess=$true)] Param ( [string]$ConfigurationName ) process { if ($pscmdlet.ShouldProcess('Create new configuration file')) { $defaultAttackerDataPath = Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/data" $defaultBlockListPath = Join-Path -Path $Script:AppConfig.AppPath -ChildPath "$ConfigurationName/blocklist" $cifApiUri = Read-HostForce -Prompt 'What is the CIFv3 URI?' -Default 'https://v3.cif.localhost' -ValidatePattern '^https?:\/\/.+$' $cifApiToken = Read-Host -Prompt 'What is your CIFv3 read-only token?' -AsSecureString $daysToBlockIp = Read-HostForce -Prompt 'How many days do you want to block an IP?' -Default '4' -ValidatePattern '^\d+$' $maxIndicatorReturnSize = Read-HostForce -Prompt 'What is the maximum number of attacker IPs to fetch?' -Default '1000' -ValidatePattern '^\d+$' $safeIpList = (Read-Host -Prompt 'What IPv4 addresses should be on your safe list? (supports regex, separate by comma)').Split(',') | ForEach-Object { $_.Trim() } $manualIpBlockListFilePath = Read-Host -Prompt 'Enter a file path that contains a CSV of IPs to block' $maxIpPerBlockList = Read-HostForce -Prompt 'What is the maximum number of IPs each block list can hold?' -Default '39700' -ValidatePattern '^\d+$' $attackerDataFileNameDateFormat = Read-HostForce -Prompt 'What date format should the attack data CSV files use?' -Default 'yyyyMMdd' -ValidatePattern '.*' $attackerDataFileNameFormat = Read-HostForce -Prompt 'What file name format should the attack data CSV files use?' -Default 'cif-attack-data-{0}.csv' -ValidatePattern '.*' $blockListFileNameFormat = Read-HostForce -Prompt 'What file name format should the IP block list use?' -Default 'cif-attack-ip-blocklist-{0}.txt' -ValidatePattern '.*' do { $attackerDataPath = Read-HostForce -Prompt 'What folder should raw attack data be saved to?' -Default $defaultAttackerDataPath -ValidatePattern '.*' New-Item -Path $attackerDataPath -ItemType Directory -Force | Out-Null } while ((Test-Path -Path $attackerDataPath) -eq $false) do { $blockListPath = Read-HostForce -Prompt 'What folder should block lists be saved to?' -Default $defaultBlockListPath -ValidatePattern '.*' New-Item -Path $blockListPath -ItemType Directory -Force | Out-Null } while ((Test-Path -Path $blockListPath) -eq $false) # Create block list template if none was specified. if ((Test-Path -Path $manualIpBlockListFilePath) -eq $false) { $manualIpBlockListFilePath = Join-Path -Path $attackerDataPath -ChildPath 'manual-ip-blocklist.csv' 'indicator' | Out-File -FilePath $manualIpBlockListFilePath -Encoding utf8 -Force -ErrorAction SilentlyContinue } $config = @{ 'ConfigurationName' = $ConfigurationName 'CifApiUri' = $cifApiUri 'CifApiToken' = ConvertFrom-SecureString -SecureString $cifApiToken 'DaysToBlockIp' = [Int32]$daysToBlockIp 'MaxIndicatorReturnSize' = [Int32]$maxIndicatorReturnSize 'SafeIpList' = [Array]$safeIpList 'MaxIpPerBlockList' = [Int32]$maxIpPerBlockList 'AttackerDataPath' = $attackerDataPath 'BlockListPath' = $blockListPath 'ManualIpBlockListFilePath' = $manualIpBlockListFilePath 'LastAttackerDataFetchTimestamp' = '' 'AttackerDataFileNameDateFormat' = $attackerDataFileNameDateFormat 'AttackerDataFileNameFormat' = $attackerDataFileNameFormat 'BlockListFileNameFormat' = $blockListFileNameFormat } $json = $config | ConvertTo-Json $json | Out-File -FilePath (Get-ConfigurationFilePath -ConfigurationName $ConfigurationName) $json | ConvertFrom-Json } } } #EndRegion './Private/App/New-Configuration.ps1' 61 #Region './Private/App/Optimize-IpBlockList.ps1' 0 function Optimize-IpBlockList ([Collections.ArrayList]$IpBlockList) { # Indicators and type from honeypots can be incorrect, so remove non-IPv4 addresses # and remove anything matching our safe lists. Write-Verbose -Message ([HelperLog]::FormatLogMessage('Filter out non-IPv4 or safe-list IPs')) $IpBlockList | Remove-NonIpV4Entry | Remove-MatchingSafeIp -SafeIp $Script:AppConfig.Config.SafeIpList | Sort-Object } #EndRegion './Private/App/Optimize-IpBlockList.ps1' 8 #Region './Private/App/Read-HostForce.ps1' 0 function Read-HostForce ([string]$Prompt, [string]$Default, [string]$ValidatePattern) { do { $userProvidedAnswer = Read-Host -Prompt "$Prompt [$Default]" if ([string]::IsNullOrEmpty($userProvidedAnswer)) { $userProvidedAnswer = $Default } } while ($userProvidedAnswer -inotmatch $ValidatePattern) $userProvidedAnswer } #EndRegion './Private/App/Read-HostForce.ps1' 11 #Region './Private/App/Remove-MatchingSafeIp.ps1' 0 function Remove-MatchingSafeIp { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([string])] Param ( # An IP to perform matching against. [Parameter(ValueFromPipeline = $true)] [string]$Data, # A collection of strings that should be removed from Data if found. [Parameter()] [string[]]$SafeIp ) process { if ($pscmdlet.ShouldProcess('Pipeline', 'Remove IP')) { $ipToCheck = $Data.Trim() $SafeIp | ForEach-Object { if (($Data -imatch $_)) { Write-Verbose -Message ([HelperLog]::FormatLogMessage("Excluding $ipToCheck, matches safe list $_")) break } } $ipToCheck } } } #EndRegion './Private/App/Remove-MatchingSafeIp.ps1' 28 #Region './Private/App/Remove-NonIpV4Entry.ps1' 0 function Remove-NonIpV4Entry { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([string])] Param ( # String to check IPv4 address format against. [Parameter(ValueFromPipeline = $true)] [string]$Data ) Process { if ($pscmdlet.ShouldProcess('Pipeline', 'Remove IP')) { $ipToCheck = $Data.Trim() $isIpV4 = $ipToCheck -match '^\d+\.\d+\.\d+\.\d+$' if ($isIpV4 -and $Matches.Count -eq 1) { $ipToCheck } else { Write-Verbose -Message ([HelperLog]::FormatLogMessage("Excluding $ipToCheck, not IPv4")) } } } } #EndRegion './Private/App/Remove-NonIpV4Entry.ps1' 21 #Region './Public/App/Invoke-ExportAttackData.ps1' 0 function Invoke-ExportAttackData { <# .SYNOPSIS Export recent attack data to one or more CSV files. .DESCRIPTION Connects to a CIF server to save recent attack data to one or more CSV files using settings stored in a configuration file. .PARAMETER Confirm Prompts you for confirmation before running the cmdlet. .PARAMETER WhatIf Shows what would happen if Invoke-ExportAttackData runs. The cmdlet isn't run. .EXAMPLE Invoke-ExportAttackData -ConfigurationName 'contoso' This will export attacker data to CSV files using the config associated with contoso. File names are based on the date an attack occurred, such as: cif-attack-data-20190131.csv. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingCmdletAliases', '')] [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([string])] param ( # A short name to identify your configuration. Used in file and path names. [Parameter(Mandatory=$true)] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [string] $ConfigurationName, # The root path that will contain .stingarcm configuration and data files. [Parameter()] [string] $Path ) begin { if ($ConfigurationName -cnotmatch '^[A-Za-z0-9\-_]+$') { throw 'ConfigurationName can only contain the following characters: A-Z, a-z, 0-9, -, _' } } process { if ($pscmdlet.ShouldProcess('CIF server', 'Export attacker IP data')) { try { Initialize-Configuration -ConfigurationName $ConfigurationName -Path $Path Connect-CifService -ApiUri $Script:AppConfig.Config.CifApiUri -ApiToken $Script:AppConfig.CifApiTokenPlainText Export-RawAttackDataToCsv -Path $Script:AppConfig.Config.AttackerDataPath -AttackAgeInDays $Script:AppConfig.Config.DaysToBlockIp -MaxIndicatorReturnSize $Script:AppConfig.Config.MaxIndicatorReturnSize -LastAttackerDataFetchTimestamp $Script:AppConfig.Config.LastAttackerDataFetchTimestamp -Append $true Export-Configuration } catch { Write-Error -Message ([HelperLog]::FormatLogMessage(($_ | Out-String))) } } } } #EndRegion './Public/App/Invoke-ExportAttackData.ps1' 63 #Region './Public/App/Invoke-NewBlockList.ps1' 0 function Invoke-NewBlockList { <# .SYNOPSIS Export attacker IP to a TXT file. .DESCRIPTION Using data collected by Invoke-ExportAttackData, this will export just the attacker IP address based on the config DaysToBlockIp to a text file. The generated text file can then be imported directly or served to your firewall if it supports external block lists. .PARAMETER Confirm Prompts you for confirmation before running the cmdlet. .PARAMETER WhatIf Shows what would happen if Invoke-NewBlockList runs. The cmdlet isn't run. .EXAMPLE Invoke-NewBlockList -ConfigurationName 'contoso' Create block list text files containing IP addresses using attacker data collected by Invoke-ExportAttackData. Settings will be associated with the configuration contoso. #> [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([string])] param ( # A short name to identify your configuration. Used in file and path names. [Parameter(Mandatory=$true)] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [string] $ConfigurationName, # The root path that will contain .stingarcm configuration and data files. [Parameter()] [string] $Path ) begin { if ($ConfigurationName -cnotmatch '^[A-Za-z0-9\-_]+$') { throw 'ConfigurationName can only contain the following characters: A-Z, a-z, 0-9, -, _' } } process { if ($pscmdlet.ShouldProcess('Export attacker IP only and apply safe list')) { try { Initialize-Configuration -ConfigurationName $ConfigurationName -Path $Path $ipToBlock = [Collections.ArrayList] @() Import-AttackDataCsvToIpBlockList -IpBlockList $ipToBlock $filteredIpToBlock = Optimize-IpBlockList -IpBlockList $ipToBlock Clear-IpBlockListFiles Export-IpBlockListFiles -IpBlockList $filteredIpToBlock } catch { Write-Error -Message ([HelperLog]::FormatLogMessage(($_ | Out-String))) } } } } #EndRegion './Public/App/Invoke-NewBlockList.ps1' 68 #Region './_SuffixCode.ps1' 0 # Code in here will be appended to bottom of the psm1-file. #EndRegion './_SuffixCode.ps1' 1 |