StingarCM.psm1

#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