EN RU

Get Windows Security Events By IP

Оглавление
  1. 1. Introduction
  2. 2. Section for Regular Users
  3. 3. Section for Developer
  4. 4. Section for Administrator
  5. 5. Glossary of Terms

1. Introduction

1.1. Document Purpose

This guide provides comprehensive information about the Get-Windows-Security-Events-By-IP PowerShell script, designed for analyzing Windows security events by IP addresses. The document is divided into three target audiences with appropriate complexity levels.

1.2. Target Audiences

  • Regular Users — Basic usage for personal needs
  • Developers — Integration and functionality extension
  • Administrators — Enterprise deployment

1.3. Document Structure

Each section contains gradual immersion into the topic, starting from basics and ending with expert methodologies. All sections are numbered for easy navigation and cross-referencing.


2. Section for Regular Users

2.1. Basic Concepts and Terminology

2.1.1. What are Windows Security Events?

Windows Security Events are records in the system log that capture various actions occurring in the operating system. Each event contains information about what happened, when it occurred, and what credentials were used.

2.1.2. Why Analyze Events by IP?

Analyzing events by IP addresses allows you to:

  • Detect unauthorized access attempts
  • Track suspicious network activity
  • Build evidence base for provider complaints
  • Understand threat sources for your system

2.1.3. Main Types of Security Events

  • 4624 — Successful logon
  • 4625 — Failed logon attempt
  • 4648 — Logon with explicit credentials
  • 4672 — Special privileges assigned

2.2. Installation and Setup

2.2.1. System Requirements

# System compatibility check
$systemInfo = Get-ComputerInfo
$requiredPSVersion = "5.1"
$currentPSVersion = $PSVersionTable.PSVersion

Write-Host "Current PowerShell version: $currentPSVersion"
Write-Host "Required version: $requiredPSVersion"

2.2.2. Downloading the Script

# Method 1: Direct download
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/paulmann/Get-Windows-Security-Events-By-IP/main/Get-SecurityEventsByIP.ps1" -OutFile "Get-SecurityEventsByIP.ps1"

# Method 2: Repository cloning
git clone https://github.com/paulmann/Get-Windows-Security-Events-By-IP.git
cd Get-Windows-Security-Events-By-IP

2.2.3. Execution Policy Configuration

# Check current policy
Get-ExecutionPolicy

# Temporary execution permission
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process

# Or permanent change (requires admin rights)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

2.3. Basic Usage

2.3.1. First Script Run

# Simplest call for single IP address
.\Get-SecurityEventsByIP.ps1 -IPAddress "192.168.1.100"

# Example output
# TimeCreated     : 2024-01-15 14:30:22
# EventID        : 4625
# IPAddress      : 192.168.1.100
# Computer       : DESKTOP-USER123
# Message        : Failed logon attempt

2.3.2. Understanding Output Data

The script returns a table with the following columns:

  • TimeCreated — Event creation time
  • EventID — Event identifier
  • IPAddress — Source IP address
  • Computer — Computer name
  • Message — Event message text

2.3.3. Time Filtering

# Search events from last 24 hours
.\Get-SecurityEventsByIP.ps1 -IPAddress "10.0.0.5" -LastHours 24

# Search for specific period
.\Get-SecurityEventsByIP.ps1 -IPAddress "10.0.0.5" -StartTime "2024-01-01" -EndTime "2024-01-15"

2.4. Practical Usage Scenarios

2.4.1. Monitoring Suspicious IP Addresses

# Daily check of known suspicious IPs
$suspiciousIPs = @("203.0.113.45", "198.51.100.23", "192.0.2.156")
foreach ($ip in $suspiciousIPs) {
    .\Get-SecurityEventsByIP.ps1 -IPAddress $ip -LastHours 24
}

2.4.2. Creating Simple Reports

# Export results to CSV
.\Get-SecurityEventsByIP.ps1 -IPAddress "192.168.1.100" -LastDays 7 -OutputFormat CSV -OutputPath "C:\Reports\security_report.csv"

# View report
Import-Csv "C:\Reports\security_report.csv" | Format-Table

2.4.3. Automating Regular Checks

# Create task scheduler for daily checks
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File `"C:\Scripts\Get-SecurityEventsByIP.ps1`" -IPAddress `"192.168.1.0/24`" -OutputPath `"C:\Reports\DailyCheck.csv`""
$Trigger = New-ScheduledTaskTrigger -Daily -At "08:00"
Register-ScheduledTask -TaskName "Daily Security Check" -Action $Action -Trigger $Trigger

2.5. Troubleshooting Common Issues

2.5.1. Access Errors

# Check administrator rights
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Host "Run script as administrator" -ForegroundColor Red
    exit
}

2.5.2. Output Issues

# Enable verbose output for diagnostics
.\Get-SecurityEventsByIP.ps1 -IPAddress "192.168.1.100" -Verbose

# Save execution log
Start-Transcript -Path "C:\Logs\script_log.txt"
.\Get-SecurityEventsByIP.ps1 -IPAddress "192.168.1.100"
Stop-Transcript

3. Section for Developer

3.1. Script Architecture

3.1.1. Code Structure Overview

# Main functional blocks of the script
# 1. Parameters and validation block
# 2. Logging and error handling functions
# 3. Main event query logic
# 4. Output formatting functions
# 5. Utility functions

3.1.2. Key Functions and Modules

  • Get-SecurityEvents — Main event query function
  • ConvertTo-ReportFormat — Conversion to various formats
  • Send-AbuseReport — Sending abuse reports
  • New-EventFilter — Creating event filters

3.2. Functionality Extension

3.2.1. Adding New Output Formats

function Export-ToHTML {
    param(
        [Parameter(Mandatory=$true)]
        [PSCustomObject[]]$Events,

        [Parameter(Mandatory=$true)]
        [string]$OutputPath
    )

    $htmlHeader = @"
<!DOCTYPE html>
<html>
<head>
    <title>Security Events Report</title>
    <style>
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        tr:nth-child(even) { background-color: #f9f9f9; }
    </style>
</head>
<body>
    <h1>Security Events Report</h1>
    <table>
        <tr>
            <th>Time</th>
            <th>Event ID</th>
            <th>IP Address</th>
            <th>Computer</th>
            <th>Message</th>
        </tr>
"@

    $htmlRows = $Events | ForEach-Object {
        @"
        <tr>
            <td>$($_.TimeCreated)</td>
            <td>$($_.EventID)</td>
            <td>$($_.IPAddress)</td>
            <td>$($_.Computer)</td>
            <td>$($_.Message)</td>
        </tr>
"@
    }

    $htmlFooter = @"
    </table>
    <p>Report generated on: $(Get-Date)</p>
</body>
</html>
"@

    $htmlHeader + ($htmlRows -join "`n") + $htmlFooter | Out-File -FilePath $OutputPath -Encoding UTF8
}

3.2.2. Integration with External APIs

# Integration with VirusTotal for IP checking
function Get-VirusTotalIPReport {
    param([string]$IPAddress, [string]$ApiKey)

    $uri = "https://www.virustotal.com/api/v3/ip_addresses/$IPAddress"
    $headers = @{ "x-apikey" = $ApiKey }

    try {
        $response = Invoke-RestMethod -Uri $uri -Headers $headers
        return [PSCustomObject]@{
            IPAddress = $IPAddress
            Malicious = $response.data.attributes.last_analysis_stats.malicious
            Suspicious = $response.data.attributes.last_analysis_stats.suspicious
            Reputation = $response.data.attributes.reputation
        }
    }
    catch {
        Write-Warning "VirusTotal query error: $($_.Exception.Message)"
        return $null
    }
}

# Usage in main script
$events = .\Get-SecurityEventsByIP.ps1 -IPAddress "192.168.1.100" -LastHours 24
$vtReport = Get-VirusTotalIPReport -IPAddress "192.168.1.100" -ApiKey $env:VT_API_KEY

3.2.3. Creating Custom Filters

# Advanced filter for brute force attack detection
function Get-BruteForceAttempts {
    param(
        [string]$IPAddress,
        [int]$FailedAttemptThreshold = 10,
        [int]$TimeWindowMinutes = 60
    )

    $startTime = (Get-Date).AddMinutes(-$TimeWindowMinutes)

    $events = Get-SecurityEventsByIP -IPAddress $IPAddress -StartTime $startTime

    $failedLogons = $events | Where-Object { 
        $_.EventID -eq 4625 -and 
        $_.LogonType -in @(2, 3, 10)  # Interactive, Network, RemoteInteractive
    }

    if ($failedLogons.Count -ge $FailedAttemptThreshold) {
        return [PSCustomObject]@{
            IPAddress = $IPAddress
            FailedAttempts = $failedLogons.Count
            TimeWindow = "$TimeWindowMinutes minutes"
            FirstAttempt = ($failedLogons | Sort-Object TimeCreated | Select-Object -First 1).TimeCreated
            LastAttempt = ($failedLogons | Sort-Object TimeCreated | Select-Object -Last 1).TimeCreated
            Status = "BRUTE_FORCE_DETECTED"
        }
    }

    return $null
}

3.3. Testing and Debugging

3.3.1. Creating Unit Tests

# Pester tests for script functions
Describe "Get-SecurityEventsByIP Unit Tests" {
    BeforeAll {
        . .\Get-SecurityEventsByIP.ps1
    }

    It "Should validate IP address format" {
        { Get-SecurityEventsByIP -IPAddress "invalid" } | Should -Throw
    }

    It "Should accept valid IP addresses" {
        { Get-SecurityEventsByIP -IPAddress "192.168.1.1" } | Should -Not -Throw
    }

    It "Should process CIDR notation" {
        $results = Get-SecurityEventsByIP -IPAddress "192.168.1.0/30" -WhatIf
        $results | Should -Not -BeNullOrEmpty
    }
}

3.3.2. Performance Profiling

# Measuring execution time of various operations
function Measure-ScriptPerformance {
    param([string]$IPAddress)

    $timeMeasurements = @()

    # Basic query test
    $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
    $events = Get-SecurityEventsByIP -IPAddress $IPAddress -LastHours 1
    $stopwatch.Stop()
    $timeMeasurements += [PSCustomObject]@{
        Operation = "BasicQuery-1h"
        Duration = $stopwatch.Elapsed
        EventsCount = $events.Count
    }

    # Extended query test
    $stopwatch.Restart()
    $events = Get-SecurityEventsByIP -IPAddress $IPAddress -LastDays 7 -Detailed
    $stopwatch.Stop()
    $timeMeasurements += [PSCustomObject]@{
        Operation = "DetailedQuery-7d"
        Duration = $stopwatch.Elapsed
        EventsCount = $events.Count
    }

    return $timeMeasurements
}

3.4. Integration with Other Systems

3.4.1. REST API Interface

# Creating simple REST API for the script
function Start-SecurityEventsAPI {
    param([int]$Port = 8080)

    $listener = New-Object System.Net.HttpListener
    $listener.Prefixes.Add("http://localhost:$Port/")
    $listener.Start()

    Write-Host "Security Events API listening on port $Port"

    while ($listener.IsListening) {
        $context = $listener.GetContext()
        $request = $context.Request
        $response = $context.Response

        try {
            if ($request.HttpMethod -eq "GET" -and $request.Url.LocalPath -eq "/events") {
                $ip = $request.QueryString["ip"]
                $hours = [int]($request.QueryString["hours"] ?? "24")

                $events = Get-SecurityEventsByIP -IPAddress $ip -LastHours $hours -OutputFormat JSON

                $buffer = [System.Text.Encoding]::UTF8.GetBytes($events)
                $response.ContentLength64 = $buffer.Length
                $response.OutputStream.Write($buffer, 0, $buffer.Length)
            }
        }
        catch {
            $errorBuffer = [System.Text.Encoding]::UTF8.GetBytes("{ 'error': '$($_.Exception.Message)' }")
            $response.ContentLength64 = $errorBuffer.Length
            $response.OutputStream.Write($errorBuffer, 0, $errorBuffer.Length)
        }
        finally {
            $response.Close()
        }
    }
}

3.4.2. Database for Storing Results

# Saving results to SQLite database
function Save-EventsToDatabase {
    param(
        [PSCustomObject[]]$Events,
        [string]$DatabasePath = "C:\Data\SecurityEvents.db"
    )

    # Create SQLite connection
    Add-Type -Path "System.Data.SQLite.dll"
    $connection = New-Object System.Data.SQLite.SQLiteConnection("Data Source=$DatabasePath")
    $connection.Open()

    # Create table if not exists
    $createTableCommand = $connection.CreateCommand()
    $createTableCommand.CommandText = @"
CREATE TABLE IF NOT EXISTS SecurityEvents (
    Id INTEGER PRIMARY KEY AUTOINCREMENT,
    TimeCreated DATETIME,
    EventID INTEGER,
    IPAddress TEXT,
    ComputerName TEXT,
    LogonType INTEGER,
    SubjectUserName TEXT,
    CreatedAt DATETIME DEFAULT CURRENT_TIMESTAMP
)
"@
    $createTableCommand.ExecuteNonQuery()

    # Insert events
    foreach ($event in $Events) {
        $insertCommand = $connection.CreateCommand()
        $insertCommand.CommandText = @"
INSERT INTO SecurityEvents (TimeCreated, EventID, IPAddress, ComputerName, LogonType, SubjectUserName)
VALUES (@time, @eventId, @ip, @computer, @logonType, @user)
"@
        $insertCommand.Parameters.AddWithValue("@time", $event.TimeCreated)
        $insertCommand.Parameters.AddWithValue("@eventId", $event.EventID)
        $insertCommand.Parameters.AddWithValue("@ip", $event.IPAddress)
        $insertCommand.Parameters.AddWithValue("@computer", $event.Computer)
        $insertCommand.Parameters.AddWithValue("@logonType", $event.LogonType)
        $insertCommand.Parameters.AddWithValue("@user", $event.SubjectUserName)

        $insertCommand.ExecuteNonQuery()
    }

    $connection.Close()
}

4. Section for Administrator

4.1. Enterprise Deployment

4.1.1. Infrastructure Requirements

# Enterprise system requirements check script
function Test-EnterpriseRequirements {
    $requirements = @()

    # Check PowerShell version
    $psVersion = $PSVersionTable.PSVersion
    $requirements += [PSCustomObject]@{
        Component = "PowerShell"
        Required = "5.1+"
        Current = $psVersion.ToString()
        Status = if ($psVersion -ge [version]"5.1") { "PASS" } else { "FAIL" }
    }

    # Check event logs availability
    $eventLogs = Get-WinEvent -ListLog "Security" -ErrorAction SilentlyContinue
    $requirements += [PSCustomObject]@{
        Component = "Security Event Log"
        Required = "Available"
        Current = if ($eventLogs) { "Available" } else { "Not Available" }
        Status = if ($eventLogs) { "PASS" } else { "FAIL" }
    }

    # Check administrator rights
    $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
    $requirements += [PSCustomObject]@{
        Component = "Administrator Rights"
        Required = "True"
        Current = $isAdmin.ToString()
        Status = if ($isAdmin) { "PASS" } else { "FAIL" }
    }

    return $requirements
}

4.1.2. Mass Deployment via Group Policy

# Domain environment deployment script
function Deploy-SecurityScriptViaGPO {
    param(
        [string[]]$ComputerNames,
        [string]$ScriptSourcePath,
        [string]$DomainController = "DC01"
    )

    $deploymentResults = @()

    foreach ($computer in $ComputerNames) {
        try {
            # Check computer availability
            if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
                # Copy script to shared network folder
                $destPath = "\\$computer\C$\Program Files\SecurityTools\"
                New-Item -Path $destPath -ItemType Directory -Force | Out-Null
                Copy-Item -Path $ScriptSourcePath -Destination $destPath -Force

                # Create scheduled task
                $schTaskScript = @"
schtasks /create /tn "Enterprise Security Scan" /tr "powershell.exe -File `"C:\Program Files\SecurityTools\Get-SecurityEventsByIP.ps1`" -IPAddress `"10.0.0.0/8`" -OutputPath `"C:\Reports\SecurityScan.csv`"" /sc daily /st 02:00 /ru "SYSTEM" /f
"@
                Invoke-Command -ComputerName $computer -ScriptBlock {
                    param($TaskScript)
                    cmd.exe /c $TaskScript
                } -ArgumentList $schTaskScript

                $deploymentResults += [PSCustomObject]@{
                    Computer = $computer
                    Status = "SUCCESS"
                    Message = "Script deployed successfully"
                }
            }
            else {
                $deploymentResults += [PSCustomObject]@{
                    Computer = $computer
                    Status = "FAILED"
                    Message = "Computer unreachable"
                }
            }
        }
        catch {
            $deploymentResults += [PSCustomObject]@{
                Computer = $computer
                Status = "FAILED"
                Message = $_.Exception.Message
            }
        }
    }

    return $deploymentResults
}

4.2. Monitoring and Reporting

4.2.1. Integration with SIEM Systems

# Export events to Splunk-compatible format
function Export-ToSplunk {
    param(
        [PSCustomObject[]]$Events,
        [string]$SplunkHost,
        [int]$SplunkPort = 8088,
        [string]$Token
    )

    $splunkEvents = $Events | ForEach-Object {
        @{
            time = [math]::Round((Get-Date $_.TimeCreated -UFormat %s) * 1000)
            host = $_.Computer
            source = "Get-SecurityEventsByIP"
            sourcetype = "windows:security:events"
            event = $_
        }
    }

    $uri = "https://$SplunkHost`:$SplunkPort/services/collector"
    $headers = @{
        "Authorization" = "Splunk $Token"
        "Content-Type" = "application/json"
    }

    # Send in batches of 100 events
    for ($i = 0; $i -lt $splunkEvents.Count; $i += 100) {
        $batch = $splunkEvents[$i..($i + 99)] | Where-Object { $_ }
        $body = ($batch | ForEach-Object { @{ event = $_ } | ConvertTo-Json -Depth 5 }) -join "`n"

        try {
            Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body
            Write-Host "Sent batch $($i/100 + 1) of $( [math]::Ceiling($splunkEvents.Count/100) )" -ForegroundColor Green
        }
        catch {
            Write-Error "Failed to send batch: $($_.Exception.Message)"
        }
    }
}

4.2.2. Creating Monitoring Dashboards

# Generate HTML dashboard with security statistics
function New-SecurityDashboard {
    param(
        [string[]]$IPAddresses,
        [int]$Days = 30,
        [string]$OutputPath = "C:\Dashboards\SecurityDashboard.html"
    )

    $events = @()
    foreach ($ip in $IPAddresses) {
        $events += Get-SecurityEventsByIP -IPAddress $ip -LastDays $Days
    }

    # Statistics by event types
    $eventStats = $events | Group-Object EventID | ForEach-Object {
        [PSCustomObject]@{
            EventID = $_.Name
            Count = $_.Count
            Description = (Get-EventDescription -EventID $_.Name)
        }
    }

    # Statistics by IP addresses
    $ipStats = $events | Group-Object IPAddress | ForEach-Object {
        [PSCustomObject]@{
            IPAddress = $_.Name
            EventCount = $_.Count
            FirstSeen = ($_.Group | Sort-Object TimeCreated | Select-Object -First 1).TimeCreated
            LastSeen = ($_.Group | Sort-Object TimeCreated | Select-Object -Last 1).TimeCreated
        }
    }

    # HTML generation
    $dashboardHTML = @"
<!DOCTYPE html>
<html>
<head>
    <title>Enterprise Security Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .dashboard { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .card { border: 1px solid #ddd; padding: 15px; border-radius: 5px; }
        .critical { border-left: 5px solid #dc3545; }
        .warning { border-left: 5px solid #ffc107; }
    </style>
</head>
<body>
    <h1>Security Events Dashboard</h1>
    <div class="dashboard">
        <div class="card">
            <h3>Event Statistics</h3>
            <canvas id="eventChart" width="400" height="200"></canvas>
        </div>
        <div class="card">
            <h3>Top IP Addresses</h3>
            <canvas id="ipChart" width="400" height="200"></canvas>
        </div>
    </div>

    <script>
        const eventCtx = document.getElementById('eventChart').getContext('2d');
        new Chart(eventCtx, {
            type: 'pie',
            data: {
                labels: [$(($eventStats | ForEach-Object { "'$($_.EventID): $($_.Description)'" }) -join ',')],
                datasets: [{
                    data: [$(($eventStats | ForEach-Object { $_.Count }) -join ',')],
                    backgroundColor: ['#ff6384', '#36a2eb', '#cc65fe', '#ffce56']
                }]
            }
        });
    </script>
</body>
</html>
"@

    $dashboardHTML | Out-File -FilePath $OutputPath -Encoding UTF8
    Write-Host "Dashboard generated: $OutputPath"
}

4.3. Security and Compliance

4.3.1. Audit Configuration According to Standards

# Audit policy configuration for NIST/ISO 27001 compliance
function Set-NISTComplianceAuditing {
    # Enable required audit subcategories
    $auditSubcategories = @(
        "Audit Logon",
        "Audit Logoff", 
        "Audit Account Lockout",
        "Audit IPsec Extended Mode",
        "Audit IPsec Main Mode",
        "Audit Other Logon/Logoff Events",
        "Audit Special Logon"
    )

    foreach ($subcategory in $auditSubcategories) {
        try {
            auditpol /set /subcategory:"$subcategory" /success:enable /failure:enable
            Write-Host "Enabled auditing for: $subcategory" -ForegroundColor Green
        }
        catch {
            Write-Warning "Failed to enable auditing for: $subcategory"
        }
    }

    # Check current settings
    $currentAuditSettings = auditpol /get /category:* | Out-String
    return $currentAuditSettings
}

4.3.2. Creating Compliance Reports

# Generate reports for PCI-DSS, SOX, GDPR
function New-ComplianceReport {
    param(
        [string]$ComplianceStandard,
        [datetime]$StartDate,
        [datetime]$EndDate
    )

    switch ($ComplianceStandard) {
        "PCI-DSS" {
            # Requirement 10: Track and monitor access
            $events = Get-SecurityEventsByIP -StartTime $StartDate -EndTime $EndDate -EventID @(4624, 4625, 4634, 4647)
            $report = [PSCustomObject]@{
                Standard = "PCI-DSS"
                Requirement = "10.2.1"
                Description = "Audit trails for all system components"
                EventsAnalyzed = $events.Count
                UniqueIPs = ($events | Group-Object IPAddress).Count
                FailedLogons = ($events | Where-Object EventID -eq 4625).Count
                ComplianceStatus = if ($events.Count -gt 0) { "COMPLIANT" } else { "NON-COMPLIANT" }
            }
        }
        "GDPR" {
            # Article 32: Security of processing
            $events = Get-SecurityEventsByIP -StartTime $StartDate -EndTime $EndDate -EventID @(4625, 4672, 4720, 4732)
            $report = [PSCustomObject]@{
                Standard = "GDPR"
                Article = "32"
                Description = "Security of processing"
                UnauthorizedAccessAttempts = ($events | Where-Object EventID -eq 4625).Count
                PrivilegeChanges = ($events | Where-Object EventID -in @(4672, 4720, 4732)).Count
                ComplianceStatus = "REVIEW_REQUIRED"
            }
        }
    }

    return $report
}

4.4. Advanced Incident Response Scenarios

4.4.1. Automatic IP Blocking

# Integration with Windows Firewall for automatic blocking
function Add-FirewallBlock {
    param(
        [string[]]$IPAddresses,
        [string]$RuleName = "AutoBlocked_$(Get-Date -Format 'yyyyMMdd_HHmmss')",
        [string]$Duration = "24:00:00"  # 24 hours
    )

    foreach ($ip in $IPAddresses) {
        # Create inbound blocking rule
        $blockRule = @"
netsh advfirewall firewall add rule name="$RuleName" dir=in action=block remoteip="$ip" protocol=any enable=yes
"@
        Invoke-Expression $blockRule

        # Scheduled rule removal after specified time
        $removeScript = @"
Remove-NetFirewallRule -Name "$RuleName" -ErrorAction SilentlyContinue
"@
        $removeScript | Out-File "C:\Scripts\RemoveBlock_$RuleName.ps1"

        $triggerTime = (Get-Date).AddHours(24)
        Register-ScheduledTask -TaskName "RemoveBlock_$RuleName" `
            -Action (New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File `"C:\Scripts\RemoveBlock_$RuleName.ps1`"") `
            -Trigger (New-ScheduledTaskTrigger -Once -At $triggerTime) `
            -RunLevel Highest
    }

    Write-Host "Blocked $($IPAddresses.Count) IP addresses for $Duration" -ForegroundColor Yellow
}

4.4.2. Creating Incident Playbooks

# Automated incident response playbook
function Start-IncidentResponsePlaybook {
    param(
        [string]$IncidentIP,
        [string]$Severity = "Medium"
    )

    Write-Host "Starting incident response for IP: $IncidentIP" -ForegroundColor Red

    # Phase 1: Information gathering
    $events = Get-SecurityEventsByIP -IPAddress $IncidentIP -LastDays 7 -Detailed
    $affectedSystems = $events | Group-Object Computer | Select-Object -ExpandProperty Name

    # Phase 2: Containment
    if ($Severity -in @("High", "Critical")) {
        Add-FirewallBlock -IPAddresses @($IncidentIP) -Duration "168:00:00"  # 1 week
    }

    # Phase 3: Analysis
    $analysisReport = [PSCustomObject]@{
        IncidentIP = $IncidentIP
        FirstSeen = ($events | Sort-Object TimeCreated | Select-Object -First 1).TimeCreated
        LastSeen = ($events | Sort-Object TimeCreated | Select-Object -Last 1).TimeCreated
        TotalEvents = $events.Count
        AffectedSystems = $affectedSystems
        EventTypes = ($events | Group-Object EventID | ForEach-Object { "$($_.Name) ($($_.Count))" }) -join ", "
        RecommendedActions = @()
    }

    # Determine recommended actions based on attack patterns
    if (($events | Where-Object EventID -eq 4625).Count -gt 10) {
        $analysisReport.RecommendedActions += "Reset passwords for accounts targeted by brute force"
    }

    if ($events | Where-Object EventID -in @(4720, 4722, 4728)) {
        $analysisReport.RecommendedActions += "Review account and group membership changes"
    }

    return $analysisReport
}

5. Glossary of Terms

5.1. Security Terms

Event ID
A unique numeric identifier assigned to each event in the Windows log. For example, Event ID 4625 indicates a failed logon attempt.

IP Address
A unique numeric identifier for a device in a computer network. In security context, used to track the source of suspicious activity.

Brute Force Attack
A brute force attack where an attacker attempts to guess credentials through multiple login attempts.

SIEM
(Security Information and Event Management) — a system for collecting, analyzing, and correlating security events from various sources in an organization.

5.2. Technical Terms

PowerShell Cmdlet
A special command in PowerShell that performs a specific function. Cmdlets follow the «Verb-Noun» naming convention.

WinRM
(Windows Remote Management) — a management protocol that allows executing PowerShell commands on remote systems.

XPath Filter
A query language for selecting nodes from XML documents. Used in Windows for filtering events in the log.

CIDR Notation
(Classless Inter-Domain Routing) — a method for specifying IP addresses and their subnets. For example, 192.168.1.0/24 represents a range of 256 addresses.

5.3. Compliance Terms

PCI DSS
(Payment Card Industry Data Security Standard) — payment card industry data security standard requiring strict access control and monitoring.

GDPR
(General Data Protection Regulation) — general data protection regulation governing personal data processing in the EU.

NIST Framework
The US National Institute of Standards and Technology cybersecurity framework providing best practices for cyber risk management.

Compliance Audit
The process of verifying a system or organization’s compliance with established standards and regulatory requirements.


Document last updated: 20 October 2024
Document version: 3.0

Добавить комментарий

Разработка и продвижение сайтов webseed.ru
Прокрутить вверх