recon 2.0

recon.ps1
# Define a function to sanitize file names
function Sanitize-FileName {
    param(
        [string]$FileName
    )
    # Remove invalid characters
    $InvalidChars = [System.IO.Path]::GetInvalidFileNameChars()
    foreach ($Char in $InvalidChars) {
        $FileName = $FileName -replace [Regex]::Escape($Char), ''
    }
    # Optionally, replace spaces with underscores (if desired)
    # $FileName = $FileName -replace ' ', '_'
    return $FileName
}

# Ensure the recon_file directory exists
$OutputDir = "C:\temp\recon_file\"

Write-Output "Checking for directory: $OutputDir"
if (-not (Test-Path $OutputDir)) {
    Write-Output "Directory does not exist. Creating directory: $OutputDir"
    New-Item -Path $OutputDir -ItemType Directory | Out-Null
} else {
    Write-Output "Directory already exists: $OutputDir"
}

# Function to execute command and write output in Markdown format to a specific file
function Write-MarkdownSection {
    param (
        [string]$Title,
        [string[]]$Commands,
        [string]$OutputFile
    )

    Write-Output "Scanning $Title..."

    # If the file doesn't exist, create it and write the heading along with the hint
    if (-not (Test-Path $OutputFile)) {
        # Write the hint markdown at the top
        '{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
        "This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
        '{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        "" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
        "# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8
    }

    foreach ($Command in $Commands) {
        # Write command in code block
        '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        $Command | Out-File -Append -FilePath $OutputFile -Encoding utf8
        '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

        # Execute command and capture output
        Try {
            $Output = Invoke-Expression $Command
        } Catch {
            $Output = ("Error executing command: {0}" -f $_)
        }

        # Write output in code block
        '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        $Output | Out-File -Append -FilePath $OutputFile -Encoding utf8
        '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
    }

    Write-Output "$Title completed"
}

# Command History (Place this at the beginning to avoid logging script commands)
$Title = "Command History"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))

Write-Output "Fetching $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 1: Fetch history from `Get-History`
$HistoryCommand1 = "Get-History"
Write-Output "Fetching PowerShell session history..."
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$HistoryCommand1 | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute and capture output
$HistoryOutput1 = Try {
    Invoke-Expression $HistoryCommand1
} Catch {
    ("Error executing Get-History: {0}" -f $_)
}

# Write output in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$HistoryOutput1 | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 2: Fetch history from PSReadline
$HistoryCommand2 = "(Get-PSReadlineOption).HistorySavePath"
Write-Output "Fetching PSReadline history file path..."
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$HistoryCommand2 | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute and capture output
$HistoryFilePath = Try {
    Invoke-Expression $HistoryCommand2
} Catch {
    ("Error executing PSReadline history path retrieval: {0}" -f $_)
}

# Write the history file path in the Markdown file
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$HistoryFilePath | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 3: Read the content of the PSReadline history file
if (Test-Path $HistoryFilePath) {
    $HistoryCommand3 = "Get-Content `"$HistoryFilePath`""
    Write-Output "Fetching PSReadline history content..."
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $HistoryCommand3 | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute and capture output
    $HistoryOutput3 = Try {
        Get-Content $HistoryFilePath
    } Catch {
        ("Error reading PSReadline history file: {0}" -f $_)
    }

    # Write history content in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $HistoryOutput3 | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
} else {
    Write-Output "PSReadline history file not found."
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    "PSReadline history file not found." | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
}

Write-Output "$Title completed"

# Hostname and Username (Updated to include 'whoami /priv')
$Title = "Hostname and Username"
$Commands = @("whoami", "whoami /priv")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# User Groups
$Title = "User Groups"
$Commands = @("whoami /groups")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Existing Users List
$Title = "Existing Users List"
$Commands = @("Get-LocalUser")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Include details for each user in the Existing Users List.md
Write-Output "Retrieving details for each user..."
$Users = Get-LocalUser | Select-Object -ExpandProperty Name
foreach ($User in $Users) {
    $UserTitle = "Details for User: $User"
    $UserCommand = "net user `"$User`""
    Write-Output "Scanning $UserTitle..."

    # Write expandable section start
    '<details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    "<summary>$UserTitle</summary>" | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '' | Out-File -Append -FilePath $OutputFile -Encoding utf8  # Empty line for Markdown formatting

    # Write command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $UserCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute command and capture output
    $UserOutput = Try {
        net user $User
    } Catch {
        ("Error executing net user for ${User}: {0}" -f $_)
    }

    # Write output in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $UserOutput | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Write expandable section end
    '</details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    Add-Content -Path $OutputFile -Value "`n" -Encoding utf8

    Write-Output "$UserTitle completed"
}
Write-Output "User details retrieval completed"

# All Group Names (Modified to exclude empty groups)
$Title = "All Group Names"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}
Write-Output "Scanning $Title..."

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Get all local groups
$Groups = Get-LocalGroup

foreach ($Group in $Groups) {
    $GroupName = $Group.Name
    $GroupCommand = "Get-LocalGroupMember -Group `"$GroupName`""

    # Execute the command to get group members
    Try {
        $GroupMembers = Get-LocalGroupMember -Group $GroupName
    } Catch {
        Write-Output ("Error retrieving members for group: {0} - {1}" -f $GroupName, $_)
        Continue
    }

    # Skip the group if it has no members
    if ($GroupMembers.Count -eq 0) {
        Write-Output "Skipping empty group: $GroupName"
        Continue
    }

    Write-Output "Processing group: $GroupName..."

    # Write expandable section start
    '<details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    "<summary>Group: $GroupName</summary>" | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '' | Out-File -Append -FilePath $OutputFile -Encoding utf8  # Empty line for Markdown formatting

    # Write the command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $GroupCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Write the group members in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $GroupMembers | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Write expandable section end
    '</details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
}

Write-Output "$Title completed"

# Environment Variables
$Title = "Environment Variables"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-Output "Scanning $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Define the commands to retrieve environment variables
$Commands = @(
    "Get-ChildItem Env:",
    'cmd /c "set"'
)

# Iterate over each command
foreach ($Command in $Commands) {
    # Write command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $Command | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute command and capture output
    Try {
        $Output = Invoke-Expression $Command
    } Catch {
        $Output = ("Error executing command: {0}" -f $_)
    }

    # Write the output in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $Output | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
}

Write-Output "$Title completed"

# System Information
$Title = "System Information"
$Commands = @("systeminfo")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Network Information
$Title = "Network Information"
$Commands = @("ipconfig /all")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# ARP Table
$Title = "ARP Table"
$Commands = @("arp -a")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Routing Information
$Title = "Routing Information"
$Commands = @("route print")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Active Network Connections
$Title = "Active Network Connections"
$Commands = @("netstat -ano")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Installed Software (32-bit)
$Title = "Installed Software (32-bit)"
$Commands = @('Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | Where-Object { $_.DisplayName } | Select-Object -ExpandProperty DisplayName')
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Installed Software (64-bit)
$Title = "Installed Software (64-bit)"
$Commands = @('Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Where-Object { $_.DisplayName } | Select-Object -ExpandProperty DisplayName')
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Running Processes
$Title = "Running Processes"
$Commands = @("Get-Process")
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-MarkdownSection -Title $Title -Commands $Commands -OutputFile $OutputFile

# Running Services (Modified to include both commands)
$Title = "Running Services"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))

Write-Output "Scanning $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Define both commands
$Commands = @(
    'Get-CimInstance -ClassName win32_service | Select Name, State, PathName, StartMode | Where-Object { $_.State -like "Running" }',
    'Get-CimInstance -ClassName win32_service | Select Name, State, StartMode | Where-Object { $_.State -like "Running" }'
)

foreach ($Command in $Commands) {
    # Write command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $Command | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute command and capture output
    Try {
        $Output = Invoke-Expression $Command
    } Catch {
        $Output = ("Error executing command: {0}" -f $_)
    }

    # Write output in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $Output | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
}

Write-Output "$Title completed"

# Folder Permissions in C (Updated to include directory listing)
$Title = "Folder Permissions in C"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
Write-Output "Scanning $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 1: List contents of C:\ directory
$LsCommand = "ls C:\"
Write-Output "Listing contents of C:\..."

# Write the ls command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$LsCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute ls command and capture output
Try {
    $LsOutput = Invoke-Expression $LsCommand
} Catch {
    $LsOutput = ("Error executing ls command: {0}" -f $_)
}

# Write the output of ls command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$LsOutput | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
Add-Content -Path $OutputFile -Value "`n" -Encoding utf8

Write-Output "C:\ directory contents listed successfully."

# Step 2: Scan folder permissions
Write-Output "Scanning folder permissions in C:\..."

# Define folders to skip
$FoldersToSkip = @(
    'Windows',
    'Program Files',
    'Program Files (x86)',
    'Users',
    '$Recycle.Bin',
    'System Volume Information',
    'PerfLogs',
    'Recovery',
    'Documents and Settings'
)

# Get all directories in C:\ and skip specified folders
Try {
    $Folders = Get-ChildItem -Path 'C:\' -Directory -Force | Where-Object { $FoldersToSkip -notcontains $_.Name }
} Catch {
    Write-Output ("Error retrieving directories in C:\: {0}" -f $_)
    $Folders = @()
}

foreach ($Folder in $Folders) {
    $FolderPath = $Folder.FullName
    $FolderName = $Folder.Name
    $Command = "icacls `"$FolderPath`""

    # Write expandable section start
    '<details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    "<summary>Permissions for Folder: $FolderName</summary>" | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '' | Out-File -Append -FilePath $OutputFile -Encoding utf8  # Empty line for Markdown formatting

    # Write command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $Command | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute command and capture output
    Try {
        $IcaclsOutput = Try {
            icacls "$FolderPath" 2>&1
        } Catch {
            ("Failed to get permissions for {0}: {1}" -f $FolderPath, $_)
        }
    } Catch {
        $IcaclsOutput = ("Error executing icacls for {0}: {1}" -f $FolderPath, $_)
    }

    # Write output in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $IcaclsOutput | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Write expandable section end
    '</details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
}
Write-Output "Folder permissions scan completed."

# Script Block Logging
$Title = "Script Block Logging"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))
$CsvFile = Join-Path -Path $OutputDir -ChildPath "script_block_logs.csv"

Write-Output "Scanning $Title..."

# Remove the Markdown file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 1: Export Script Block Logs to CSV
$ScriptBlockCommand = "Get-WinEvent -LogName 'Microsoft-Windows-PowerShell/Operational' | Where-Object { `$_.Id -eq 4104 } | Export-Csv -Path '$CsvFile' -NoTypeInformation"
Write-Output "Exporting script block logs to CSV..."

# Write the export command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$ScriptBlockCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute the export command

Invoke-Expression $ScriptBlockCommand
Write-Output "Script block logs exported to $CsvFile"
# Add-Content -Path $OutputFile -Value "Script block logs exported to `$CsvFile.`" -Encoding utf8

# Step 2: Search for sensitive information in the exported CSV
if (Test-Path $CsvFile) {
    $SensitivePatterns = "password|username|api_key|secret|GetBytes|ToBase64String|Credential"
    $SearchCommand = "Get-Content '$CsvFile' | Select-String -Pattern '$SensitivePatterns'"
    Write-Output "Searching for sensitive information in script block logs..."

    # Write the search command in code block
    '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    $SearchCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
    '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

    # Execute the search command
    Try {
        $SensitiveData = Get-Content $CsvFile | Select-String -Pattern $SensitivePatterns

        # Write findings to Markdown file
        '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        if ($SensitiveData) {
            $SensitiveData | Out-File -Append -FilePath $OutputFile -Encoding utf8
        } else {
            "No sensitive information found in the logs." | Out-File -Append -FilePath $OutputFile -Encoding utf8
        }
        '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
    } Catch {
        Write-Output ("Failed to search for sensitive information: {0}" -f $_)
        Add-Content -Path $OutputFile -Value ("Failed to search for sensitive information: {0}" -f $_) -Encoding utf8
    }
} Else {
    Write-Output "Script block logs CSV file not found."
    Add-Content -Path $OutputFile -Value "Script block logs CSV file not found." -Encoding utf8
}

Write-Output "$Title completed"

# Scheduled Tasks Analysis
$Title = "Scheduled Tasks Analysis -self"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))

Write-Output "Scanning $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 1: Query all scheduled tasks
$SchtasksCommand = 'schtasks /query /fo LIST /v'
Write-Output "Querying scheduled tasks..."

# Write the command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
# $SchtasksCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute the command and capture output
Try {
    $TasksOutput = schtasks /query /fo LIST /v
} Catch {
    $TasksOutput = ("Error executing schtasks command: {0}" -f $_)
}

# Write the entire tasks output to the Markdown file (optional)
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
# $TasksOutput | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8
Add-Content -Path $OutputFile -Value "`n" -Encoding utf8

# Step 2: Analyze the tasks for potential privilege escalation
Write-Output "Analyzing scheduled tasks for potential privilege escalation..."

# Initialize an array to hold tasks of interest
$TasksOfInterest = @()

# Split the output into individual tasks based on double newlines
$Tasks = ($TasksOutput -join "`n") -split "\n\s*\n"

foreach ($Task in $Tasks) {
    # Extract "Task Name", "Task To Run", and "Next Run Time"
    if ($Task -match "Task Name:\s*(.*)") {
        $TaskName = $Matches[1].Trim()
    } else {
        $TaskName = ""
    }

    if ($Task -match "Task To Run:\s*(.*)") {
        $TaskToRun = $Matches[1].Trim()
    } else {
        $TaskToRun = ""
    }

    if ($Task -match "Next Run Time:\s*(.*)") {
        $NextRunTime = $Matches[1].Trim()
    } else {
        $NextRunTime = ""
    }

    # Check if "Task To Run" does not contain "system32" and "Next Run Time" is not "N/A"
    if ($TaskToRun -and $TaskToRun -notmatch "\\system32\\" -and $NextRunTime -notmatch "N/A") {
        # Sanitize $TaskToRun by removing any embedded quotes
        $TaskToRun = $TaskToRun.Trim('"')

        # Check if the sanitized path is valid
        if (Test-Path $TaskToRun) {
            Try {
                $Access = (Get-Acl $TaskToRun).Access | Where-Object { 
                    $_.IdentityReference -like "$env:USERNAME*" -and $_.FileSystemRights -match "Write" 
                }
                if ($Access) {
                    # Add to tasks of interest
                    $TasksOfInterest += @{
                        TaskName = $TaskName
                        TaskToRun = $TaskToRun
                        NextRunTime = $NextRunTime
                        Details = $Task
                    }
                }
            } Catch {
                # Handle access errors
                Write-Output ("Error accessing {0}: {1}" -f $TaskToRun, $_)
            }
        } else {
            Write-Output ("Task To Run path does not exist or is invalid: {0}" -f $TaskToRun)
        }
    }
}

# Write tasks of interest to the Markdown file
if ($TasksOfInterest.Count -gt 0) {
    foreach ($TaskInfo in $TasksOfInterest) {
        # Write expandable section start
        '<details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        "<summary>Potential Privilege Escalation Task: $($TaskInfo.TaskName)</summary>" | Out-File -Append -FilePath $OutputFile -Encoding utf8
        '' | Out-File -Append -FilePath $OutputFile -Encoding utf8  # Empty line for Markdown formatting

        # Write task details in code block
        '```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        $TaskInfo.Details | Out-File -Append -FilePath $OutputFile -Encoding utf8
        '```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

        # Write expandable section end
        '</details>' | Out-File -Append -FilePath $OutputFile -Encoding utf8
        Add-Content -Path $OutputFile -Value "`n" -Encoding utf8
    }
} else {
    Add-Content -Path $OutputFile -Value "No potential privilege escalation tasks found." -Encoding utf8
}

Write-Output "$Title completed"

# Kernel Exploits Analysis
$Title = "Kernel Exploits Analysis"
$OutputFile = Join-Path -Path $OutputDir -ChildPath (Sanitize-FileName("$Title.md"))

Write-Output "Scanning $Title..."

# Remove the file if it exists to start fresh
if (Test-Path $OutputFile) {
    Remove-Item $OutputFile
}

# Write heading with hint
'{% hint style="info" %}' | Out-File -FilePath $OutputFile -Encoding utf8
"This section provides detailed information about $Title." | Out-File -Append -FilePath $OutputFile -Encoding utf8
'{% endhint %}' | Out-File -Append -FilePath $OutputFile -Encoding utf8
"" | Out-File -Append -FilePath $OutputFile -Encoding utf8 # Add an empty line for formatting
"# $Title" | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 1: Get OS Version and Build Information
$OSCommand = "systeminfo"
Write-Output "Fetching OS version and build information..."

# Write the command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$OSCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute the command and capture output
Try {
    $OSInfo = Invoke-Expression $OSCommand
} Catch {
    $OSInfo = ("Error executing systeminfo: {0}" -f $_)
}

# Write output in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$OSInfo | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 2: Get Installed Security Updates
$PatchCommand = "Get-CimInstance -Class win32_quickfixengineering | Where-Object { `$_.Description -eq 'Security Update' }"
Write-Output "Fetching installed security patches..."

# Write the command in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$PatchCommand | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Execute the command and capture output
Try {
    $PatchInfo = Invoke-Expression $PatchCommand
} Catch {
    $PatchInfo = ("Error fetching security patches: {0}" -f $_)
}

# Write output in code block
'```powershell' | Out-File -Append -FilePath $OutputFile -Encoding utf8
$PatchInfo | Format-Table -AutoSize | Out-String | Out-File -Append -FilePath $OutputFile -Encoding utf8
'```' | Out-File -Append -FilePath $OutputFile -Encoding utf8

# Step 3: Note CVE Reference for Kernel Exploit
Write-Output "Adding details for kernel exploits (CVE-2023-29360)..."
Add-Content -Path $OutputFile -Value "`n## CVE Reference" -Encoding utf8
Add-Content -Path $OutputFile -Value "This section includes references to kernel exploits for further investigation." -Encoding utf8
Add-Content -Path $OutputFile -Value "- [CVE-2023-29360 Details and Exploit](https://www.example.com)" -Encoding utf8
Add-Content -Path $OutputFile -Value "- Ensure you validate the environment and test appropriately before using public exploits." -Encoding utf8
# code
Write-Output "$Title completed"

Write-Output "System information has been saved to individual Markdown files in $OutputDir."

Last updated