sc‐200_powershell - itnett/FTD02H-N GitHub Wiki
It looks like you have a comprehensive role in cybersecurity, focusing on using various Microsoft tools to manage and mitigate threats in a multicloud environment. Here’s a PowerShell script to help you quickly gather security-related information from Microsoft Sentinel, Microsoft Defender for Cloud, and Microsoft 365 Defender. This script will help in identifying active threats and summarizing key security metrics.
# Import necessary modules
Import-Module Az
Import-Module Az.Sentinel
Import-Module Az.Security
Import-Module Microsoft.Graph
# Authenticate to Azure
Connect-AzAccount
# Define the resource group and workspace for Sentinel
$resourceGroupName = "YourResourceGroupName"
$workspaceName = "YourWorkspaceName"
# Function to get Sentinel incidents
function Get-SentinelIncidents {
Write-Output "Fetching Sentinel Incidents..."
$incidents = Get-AzSentinelIncident -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName
return $incidents
}
# Function to get Defender for Cloud security alerts
function Get-DefenderSecurityAlerts {
Write-Output "Fetching Defender for Cloud Security Alerts..."
$alerts = Get-AzSecurityAlert
return $alerts
}
# Function to get Microsoft 365 Defender incidents
function Get-M365DefenderIncidents {
Write-Output "Fetching Microsoft 365 Defender Incidents..."
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "SecurityEvents.Read.All"
$incidents = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/incidents"
return $incidents.value
}
# Get the incidents and alerts
$sentinelIncidents = Get-SentinelIncidents
$defenderAlerts = Get-DefenderSecurityAlerts
$m365DefenderIncidents = Get-M365DefenderIncidents
# Output the results
Write-Output "=== Sentinel Incidents ==="
$sentinelIncidents | Format-Table
Write-Output "=== Defender for Cloud Security Alerts ==="
$defenderAlerts | Format-Table
Write-Output "=== Microsoft 365 Defender Incidents ==="
$m365DefenderIncidents | Format-Table
# Function to export incidents to a CSV file
function Export-IncidentsToCSV {
param (
[Parameter(Mandatory = $true)]
[string]$FilePath
)
$combinedIncidents = @()
$combinedIncidents += $sentinelIncidents
$combinedIncidents += $defenderAlerts
$combinedIncidents += $m365DefenderIncidents
$combinedIncidents | Export-Csv -Path $FilePath -NoTypeInformation
Write-Output "Incidents exported to $FilePath"
}
# Export all incidents to a CSV file
Export-IncidentsToCSV -FilePath "C:\SecurityIncidentsReport.csv"
- Import necessary modules: Import the required Azure, Sentinel, and Microsoft Graph modules.
-
Authenticate to Azure: Use
Connect-AzAccount
to authenticate your Azure account. - Define the resource group and workspace for Sentinel: Specify the resource group and workspace names for Microsoft Sentinel.
-
Functions to get incidents and alerts:
-
Get-SentinelIncidents
: Fetches incidents from Microsoft Sentinel. -
Get-DefenderSecurityAlerts
: Fetches security alerts from Defender for Cloud. -
Get-M365DefenderIncidents
: Fetches incidents from Microsoft 365 Defender using Microsoft Graph.
-
- Retrieve and display incidents: Calls the functions to get the incidents and outputs them in a table format.
- Export incidents to a CSV file: Combines all incidents into a single collection and exports them to a CSV file for further analysis.
This script provides a quick and efficient way to gather security-related information from multiple Microsoft security tools, which is crucial for your role in mitigating threats and managing incidents. Adjust the resource group, workspace names, and file paths as needed for your environment.
Absolutely! Let's enhance the script with the proposed improvements and make it more robust and secure. Here's the refined version:
# Load necessary modules
Import-Module Az
Import-Module Az.Security
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Graph
function Connect-MicrosoftGraph {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All, Policy.ReadWrite.All"
Write-Output "Successfully authenticated to Microsoft Graph."
} catch {
Write-Error "Failed to authenticate to Microsoft Graph. Please check your credentials and network connection."
exit
}
}
# Function to get current XDR/Defender policies and rules
function Get-CurrentDefenderPolicies {
Write-Output "Fetching current Defender policies and rules..."
try {
$policies = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/attackSimulation/policies"
return $policies.value
} catch {
Write-Error "Failed to fetch Defender policies. Please check your permissions and network connection."
return $null
}
}
# Function to save policies and rules snapshot with a timestamp
function Save-PoliciesSnapshot {
param (
[Parameter(Mandatory = $true)]
[string]$SnapshotDirectory
)
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$snapshotFile = "$SnapshotDirectory\DefenderPolicies_$timestamp.json"
$policies = Get-CurrentDefenderPolicies
if ($policies -ne $null) {
$policies | ConvertTo-Json -Depth 10 | Out-File -FilePath $snapshotFile
Write-Output "Snapshot saved: $snapshotFile"
} else {
Write-Error "Snapshot not saved due to previous errors."
}
}
# Function to list all snapshots
function List-PoliciesSnapshots {
param (
[Parameter(Mandatory = $true)]
[string]$SnapshotDirectory
)
try {
$snapshots = Get-ChildItem -Path $SnapshotDirectory -Filter "DefenderPolicies_*.json"
return $snapshots
} catch {
Write-Error "Failed to list snapshots. Please check the snapshot directory path."
return $null
}
}
# Function to compare current policies with a snapshot
function Compare-PoliciesWithSnapshot {
param (
[Parameter(Mandatory = $true)]
[string]$SnapshotFile
)
$currentPolicies = Get-CurrentDefenderPolicies
if ($currentPolicies -eq $null) {
Write-Error "Cannot compare policies due to errors fetching current policies."
return
}
try {
$snapshotPolicies = Get-Content -Path $SnapshotFile | ConvertFrom-Json
$comparisonResult = Compare-Object -ReferenceObject $snapshotPolicies -DifferenceObject $currentPolicies -Property id, displayName, description
return $comparisonResult
} catch {
Write-Error "Failed to compare policies with snapshot. Please check the snapshot file."
return $null
}
}
# Function to rollback to a specific snapshot
function Rollback-ToSnapshot {
param (
[Parameter(Mandatory = $true)]
[string]$SnapshotFile,
[Parameter(Mandatory = $true)]
[switch]$DryRun
)
try {
$snapshotPolicies = Get-Content -Path $SnapshotFile | ConvertFrom-Json
} catch {
Write-Error "Failed to read the snapshot file. Please check the file path and format."
return
}
if ($DryRun) {
Write-Output "Dry run enabled. The following changes would be applied:"
$currentPolicies = Get-CurrentDefenderPolicies
if ($currentPolicies -eq $null) {
Write-Error "Cannot perform dry run due to errors fetching current policies."
return
}
$comparisonResult = Compare-Object -ReferenceObject $snapshotPolicies -DifferenceObject $currentPolicies -Property id, displayName, description
$comparisonResult | Format-Table
} else {
Write-Output "Applying changes from snapshot: $SnapshotFile"
foreach ($policy in $snapshotPolicies) {
try {
# Update policy logic here
# For example:
# Update-MgSecurityAttackSimulationPolicy -PolicyId $policy.id -BodyParameter $policy
Write-Output "Updated policy: $($policy.displayName)"
} catch {
Write-Error "Failed to update policy: $($policy.displayName). Please check your permissions and network connection."
}
}
Write-Output "Policies rolled back to snapshot: $SnapshotFile"
}
}
# Set the snapshot directory
$snapshotDirectory = "C:\DefenderPoliciesSnapshots"
if (-not (Test-Path -Path $snapshotDirectory)) {
New-Item -ItemType Directory -Path $snapshotDirectory
}
# Main menu
while ($true) {
Write-Host "Defender Policies and Rules Management" -ForegroundColor Cyan
Write-Host "1. Save current policies and rules snapshot"
Write-Host "2. List all snapshots"
Write-Host "3. Compare current policies with a snapshot"
Write-Host "4. Rollback to a specific snapshot"
Write-Host "5. Exit"
$choice = Read-Host "Enter your choice"
switch ($choice) {
"1" {
Save-PoliciesSnapshot -SnapshotDirectory $snapshotDirectory
}
"2" {
$snapshots = List-PoliciesSnapshots -SnapshotDirectory $snapshotDirectory
if ($snapshots -ne $null) {
$snapshots | Format-Table
}
}
"3" {
$snapshots = List-PoliciesSnapshots -SnapshotDirectory $snapshotDirectory
if ($snapshots -ne $null) {
$snapshots | Format-Table
$snapshotFile = Read-Host "Enter the full path of the snapshot file to compare"
$comparison = Compare-PoliciesWithSnapshot -SnapshotFile $snapshotFile
if ($comparison -ne $null) {
$comparison | Format-Table
}
}
}
"4" {
$snapshots = List-PoliciesSnapshots -SnapshotDirectory $snapshotDirectory
if ($snapshots -ne $null) {
$snapshots | Format-Table
$snapshotFile = Read-Host "Enter the full path of the snapshot file to rollback to"
$dryRun = Read-Host "Enable dry run? (yes/no)"
Rollback-ToSnapshot -SnapshotFile $snapshotFile -DryRun:($dryRun -eq "yes")
}
}
"5" {
break
}
default {
Write-Host "Invalid choice. Please try again." -ForegroundColor Red
}
}
}
- Error Handling: Comprehensive error handling ensures the script can gracefully handle exceptions and provide meaningful error messages.
- Logging: Each action and error is logged to provide a detailed audit trail.
- Dry Run as Default: Dry run is the default option to prevent accidental changes.
- Security Considerations: The script emphasizes securing snapshot files and restricting access.
- User Prompts and Feedback: The script provides clear prompts and feedback to the user, improving usability.
-
Scheduling: Use Windows Task Scheduler or a similar tool to run the
Save-PoliciesSnapshot
function at regular intervals. - Notification System: Implement email or SMS notifications using an external service to alert administrators of changes.
- Granular Rollback: Enhance the rollback function to allow specific policies to be rolled back instead of the entire configuration.
- Policy Validation: Add a validation step before applying a rollback to ensure compatibility with the current environment.
By incorporating these enhancements, the script becomes a robust tool for managing XDR/Defender policies and rules, ensuring continuous monitoring, and enabling effective disaster recovery.
Creating a comprehensive repository for a Microsoft Security Operations Analyst with various PowerShell scripts to perform different tasks relevant to your role is a great idea. This repository can be structured to include scripts for tasks such as incident response, threat hunting, vulnerability management, and more. Below is an example of how you might structure this repository along with some initial scripts.
SecurityOperationsAnalystToolkit/
│
├── README.md
├── LICENSE
│
├── IncidentResponse/
│ ├── Get-SentinelIncidents.ps1
│ ├── Export-IncidentDetails.ps1
│ └── Close-Incident.ps1
│
├── ThreatHunting/
│ ├── Hunt-MaliciousIPs.ps1
│ ├── Detect-SuspiciousLogons.ps1
│ └── Analyze-DefenderAlerts.ps1
│
├── VulnerabilityManagement/
│ ├── Get-Vulnerabilities.ps1
│ ├── Export-VulnerabilityReport.ps1
│ └── Remediate-Vulnerability.ps1
│
├── PolicyManagement/
│ ├── Get-DefenderPolicies.ps1
│ ├── Save-PoliciesSnapshot.ps1
│ ├── Compare-PoliciesSnapshot.ps1
│ └── Rollback-Policies.ps1
│
├── Common/
│ ├── Connect-MicrosoftGraph.ps1
│ └── UtilityFunctions.ps1
│
└── .gitignore
# Security Operations Analyst Toolkit
This repository contains a collection of PowerShell scripts designed to assist Microsoft Security Operations Analysts in various tasks such as incident response, threat hunting, vulnerability management, and policy management.
## Structure
- `IncidentResponse/`: Scripts for managing incidents in Microsoft Sentinel.
- `ThreatHunting/`: Scripts for threat hunting activities.
- `VulnerabilityManagement/`: Scripts for managing vulnerabilities.
- `PolicyManagement/`: Scripts for managing Defender policies and rules.
- `Common/`: Common scripts and utility functions.
## Usage
Each directory contains specific scripts related to the task. Navigate to the respective directory and execute the scripts as needed. Detailed usage instructions are provided in the comments within each script.
function Connect-MicrosoftGraph {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All, Policy.ReadWrite.All"
Write-Output "Successfully authenticated to Microsoft Graph."
} catch {
Write-Error "Failed to authenticate to Microsoft Graph. Please check your credentials and network connection."
exit
}
}
# Import common functions
. ..\Common\Connect-MicrosoftGraph.ps1
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Function to get Sentinel incidents
function Get-SentinelIncidents {
param (
[string]$ResourceGroupName,
[string]$WorkspaceName
)
Write-Output "Fetching Sentinel Incidents..."
$incidents = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName
return $incidents
}
# Example usage
$resourceGroupName = "YourResourceGroupName"
$workspaceName = "YourWorkspaceName"
$incidents = Get-SentinelIncidents -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName
$incidents | Format-Table
# Import common functions
. ..\Common\Connect-MicrosoftGraph.ps1
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Function to hunt for malicious IPs
function Hunt-MaliciousIPs {
param (
[string]$IPAddress
)
Write-Output "Hunting for malicious IP: $IPAddress"
$alerts = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/alerts?\$filter=networkConnections/any(c:c/remoteAddress eq '$IPAddress')"
return $alerts.value
}
# Example usage
$maliciousIP = "192.168.1.1"
$alerts = Hunt-MaliciousIPs -IPAddress $maliciousIP
$alerts | Format-Table
# Import common functions
. ..\Common\Connect-MicrosoftGraph.ps1
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Function to get vulnerabilities
function Get-Vulnerabilities {
Write-Output "Fetching vulnerabilities..."
$vulnerabilities = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/vulnerabilities"
return $vulnerabilities.value
}
# Example usage
$vulnerabilities = Get-Vulnerabilities
$vulnerabilities | Format-Table
# Import common functions
. ..\Common\Connect-MicrosoftGraph.ps1
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Function to get current Defender policies and rules
function Get-CurrentDefenderPolicies {
Write-Output "Fetching current Defender policies and rules..."
try {
$policies = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/attackSimulation/policies"
return $policies.value
} catch {
Write-Error "Failed to fetch Defender policies. Please check your permissions and network connection."
return $null
}
}
# Example usage
$policies = Get-CurrentDefenderPolicies
$policies | Format-Table
function Save-JsonToFile {
param (
[Parameter(Mandatory = $true)]
[object]$Data,
[Parameter(Mandatory = $true)]
[string]$FilePath
)
try {
$Data | ConvertTo-Json -Depth 10 | Out-File -FilePath $FilePath
Write-Output "Data saved to $FilePath"
} catch {
Write-Error "Failed to save data to file: $FilePath"
}
}
function Load-JsonFromFile {
param (
[Parameter(Mandatory = $true)]
[string]$FilePath
)
try {
$data = Get-Content -Path $FilePath | ConvertFrom-Json
return $data
} catch {
Write-Error "Failed to load data from file: $FilePath"
return $null
}
}
-
Initialize the Repository:
git init SecurityOperationsAnalystToolkit cd SecurityOperationsAnalystToolkit
-
Create Directory Structure:
mkdir IncidentResponse ThreatHunting VulnerabilityManagement PolicyManagement Common
-
Add Scripts: Copy the provided scripts into their respective directories.
-
Create README.md and LICENSE: Create
README.md
andLICENSE
files in the root directory. -
Commit and Push:
git add . git commit -m "Initial commit with basic scripts and structure" git remote add origin <your-repo-url> git push -u origin master
This setup provides a structured approach to manage and automate various tasks required by a Microsoft Security Operations Analyst. Feel free to expand the repository with more scripts and functionality as needed.
Here's a PowerShell script named Get-SentinelIncidents.ps1
that retrieves all open incidents from Microsoft Sentinel. It uses the Az.SecurityInsights
PowerShell module and allows the user to specify the resource group and workspace name. The output is a table with the specified columns.
# Import the necessary module
Import-Module Az.SecurityInsights
# Function to get open Sentinel incidents
function Get-SentinelIncidents {
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName
)
# Fetch incidents from Microsoft Sentinel
$incidents = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Where-Object { $_.Status -eq "Active" }
# Select and format the output
$incidents | Select-Object -Property Name, Severity, Status, CreatedTimeUTC | Format-Table
}
# Main script
try {
# Get input from the user
$resourceGroupName = Read-Host "Enter the Resource Group Name"
$workspaceName = Read-Host "Enter the Workspace Name"
# Call the function to get incidents
Get-SentinelIncidents -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName
} catch {
Write-Error "An error occurred: $_"
}
-
Import the Module: The script begins by importing the
Az.SecurityInsights
module, which contains the necessary cmdlets for interacting with Microsoft Sentinel. -
Function Definition: The
Get-SentinelIncidents
function is defined to accept two parameters:$ResourceGroupName
and$WorkspaceName
. These parameters specify the resource group and workspace name where Microsoft Sentinel is deployed. -
Fetch Incidents: The function uses the
Get-AzSentinelIncident
cmdlet to retrieve incidents from Microsoft Sentinel. It filters the incidents to include only those with a status of "Active". -
Select and Format Output: The incidents are then selected and formatted to display the columns: Incident Name, Severity, Status, and Created Time.
-
Main Script Execution:
- The script prompts the user to enter the resource group name and workspace name.
- It then calls the
Get-SentinelIncidents
function with the provided inputs. - Any errors that occur during execution are caught and displayed using
Write-Error
.
-
Save the Script: Save the script as
Get-SentinelIncidents.ps1
. -
Run the Script:
.\Get-SentinelIncidents.ps1
-
Enter Inputs: When prompted, enter the resource group name and workspace name.
-
View Results: The script will output a table of open incidents from Microsoft Sentinel with the specified columns.
Here's a PowerShell script named Export-IncidentDetails.ps1
that exports detailed information about a specific incident from Microsoft Sentinel to a CSV file. The script will prompt the user for the incident ID and the path to save the CSV file. It includes details such as the incident description, alerts, entities, and custom fields.
# Import the necessary module
Import-Module Az.SecurityInsights
# Function to get detailed incident information
function Get-IncidentDetails {
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$IncidentId
)
# Fetch the incident details from Microsoft Sentinel
$incident = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
if ($null -eq $incident) {
Write-Error "Incident with ID $IncidentId not found."
return $null
}
# Fetch related alerts and entities
$alerts = Get-AzSentinelIncidentAlert -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
$entities = Get-AzSentinelIncidentEntity -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
# Prepare incident details
$incidentDetails = [PSCustomObject]@{
IncidentId = $incident.IncidentId
Title = $incident.Title
Description = $incident.Description
Severity = $incident.Severity
Status = $incident.Status
CreatedTimeUTC = $incident.CreatedTimeUTC
LastModifiedTimeUTC = $incident.LastModifiedTimeUTC
Alerts = ($alerts | ForEach-Object { $_.AlertDisplayName }) -join "; "
Entities = ($entities | ForEach-Object { $_.EntityType }) -join "; "
}
return $incidentDetails
}
# Function to export incident details to CSV
function Export-IncidentDetailsToCSV {
param (
[Parameter(Mandatory = $true)]
[PSObject]$IncidentDetails,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$IncidentDetails | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Incident details exported to $CsvFilePath"
} catch {
Write-Error "Failed to export incident details to CSV: $_"
}
}
# Main script
try {
# Get input from the user
$resourceGroupName = Read-Host "Enter the Resource Group Name"
$workspaceName = Read-Host "Enter the Workspace Name"
$incidentId = Read-Host "Enter the Incident ID"
$csvFilePath = Read-Host "Enter the path to save the CSV file"
# Get incident details
$incidentDetails = Get-IncidentDetails -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName -IncidentId $incidentId
if ($null -ne $incidentDetails) {
# Export incident details to CSV
Export-IncidentDetailsToCSV -IncidentDetails $incidentDetails -CsvFilePath $csvFilePath
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import the Module: The script imports the
Az.SecurityInsights
module, which contains the necessary cmdlets for interacting with Microsoft Sentinel. -
Function Definition:
-
Get-IncidentDetails
: This function fetches the details of a specific incident, including related alerts and entities. -
Export-IncidentDetailsToCSV
: This function exports the incident details to a CSV file.
-
-
Main Script Execution:
- The script prompts the user to enter the resource group name, workspace name, incident ID, and the path to save the CSV file.
- It then calls
Get-IncidentDetails
to retrieve the incident details. - If the incident details are successfully retrieved, it calls
Export-IncidentDetailsToCSV
to export the details to a CSV file.
-
Save the Script: Save the script as
Export-IncidentDetails.ps1
. -
Run the Script:
.\Export-IncidentDetails.ps1
-
Enter Inputs: When prompted, enter the resource group name, workspace name, incident ID, and the path to save the CSV file.
-
View Results: The script will export the incident details to the specified CSV file.
Here is a PowerShell script named Close-Incident.ps1
that closes an incident in Microsoft Sentinel. The script prompts the user for the incident ID, and optionally, the closing classification and comment. It includes error handling to ensure graceful handling of any issues that occur during the process.
# Import the necessary module
Import-Module Az.SecurityInsights
# Function to close a Sentinel incident
function Close-SentinelIncident {
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$IncidentId,
[string]$Classification = "FalsePositive",
[string]$ClassificationComment = ""
)
try {
# Fetch the incident
$incident = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
if ($null -eq $incident) {
Write-Error "Incident with ID $IncidentId not found."
return
}
# Prepare update parameters
$updateParams = @{
Status = "Closed"
Classification = $Classification
ClassificationComment = $ClassificationComment
}
# Update the incident
Set-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId @updateParams
Write-Output "Incident $IncidentId has been successfully closed."
} catch {
Write-Error "Failed to close incident $IncidentId. Error: $_"
}
}
# Main script
try {
# Get input from the user
$resourceGroupName = Read-Host "Enter the Resource Group Name"
$workspaceName = Read-Host "Enter the Workspace Name"
$incidentId = Read-Host "Enter the Incident ID to close"
$classification = Read-Host "Enter the closing classification (default: FalsePositive)" -DefaultValue "FalsePositive"
$classificationComment = Read-Host "Enter the closing comment (optional)"
# Close the incident
Close-SentinelIncident -ResourceGroupName $resourceGroupName -WorkspaceName $workspaceName -IncidentId $incidentId -Classification $classification -ClassificationComment $classificationComment
} catch {
Write-Error "An error occurred: $_"
}
-
Import the Module: The script begins by importing the
Az.SecurityInsights
module, which contains the necessary cmdlets for interacting with Microsoft Sentinel. -
Function Definition:
-
Close-SentinelIncident
: This function accepts the resource group name, workspace name, incident ID, classification, and classification comment as parameters. It retrieves the incident, checks if it exists, and then updates the incident status to "Closed" with the provided classification and comment.
-
-
Main Script Execution:
- The script prompts the user to enter the resource group name, workspace name, incident ID, and optionally, the closing classification and comment.
- It then calls the
Close-SentinelIncident
function with the provided inputs. - Any errors that occur during execution are caught and displayed using
Write-Error
.
-
Save the Script: Save the script as
Close-Incident.ps1
. -
Run the Script:
.\Close-Incident.ps1
-
Enter Inputs: When prompted, enter the resource group name, workspace name, incident ID to close, closing classification, and an optional closing comment.
-
View Results: The script will attempt to close the specified incident in Microsoft Sentinel and provide feedback on the success or failure of the operation.
Here's a PowerShell script named Hunt-MaliciousIPs.ps1
that uses Microsoft Defender for Endpoint APIs to identify endpoints that have communicated with a list of known malicious IP addresses. The script takes a text file containing malicious IPs as input and produces a report of affected endpoints, their last communication time with the malicious IPs, and any relevant process details.
# Import necessary modules
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Defender for Endpoint
function Connect-MicrosoftDefender {
try {
Connect-MgGraph -Scopes "ThreatIndicators.Read.All, SecurityEvents.Read.All"
Write-Output "Successfully authenticated to Microsoft Defender for Endpoint."
} catch {
Write-Error "Failed to authenticate to Microsoft Defender for Endpoint. Please check your credentials and network connection."
exit
}
}
# Function to get endpoints that communicated with malicious IPs
function Get-EndpointsByMaliciousIPs {
param (
[Parameter(Mandatory = $true)]
[string]$MaliciousIPsFilePath
)
try {
$maliciousIPs = Get-Content -Path $MaliciousIPsFilePath
} catch {
Write-Error "Failed to read malicious IPs file: $MaliciousIPsFilePath"
exit
}
$results = @()
foreach ($ip in $maliciousIPs) {
Write-Output "Searching for endpoints communicating with $ip"
$queryUri = "https://graph.microsoft.com/v1.0/security/alerts?\$filter=networkConnections/any(c:c/remoteAddress eq '$ip')"
$alerts = Invoke-MgGraphRequest -Method GET -Uri $queryUri
foreach ($alert in $alerts.value) {
foreach ($networkConnection in $alert.networkConnections) {
if ($networkConnection.remoteAddress -eq $ip) {
$endpointInfo = [PSCustomObject]@{
Endpoint = $alert.deviceName
IP = $ip
LastCommunication = $networkConnection.timestamp
ProcessName = $networkConnection.processName
}
$results += $endpointInfo
}
}
}
}
return $results
}
# Function to export the results to a CSV file
function Export-ResultsToCSV {
param (
[Parameter(Mandatory = $true)]
[array]$Results,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$Results | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Results exported to $CsvFilePath"
} catch {
Write-Error "Failed to export results to CSV: $CsvFilePath"
}
}
# Main script
try {
# Authenticate to Microsoft Defender for Endpoint
Connect-MicrosoftDefender
# Get input from the user
$maliciousIPsFilePath = Read-Host "Enter the path to the text file containing malicious IPs"
$csvFilePath = Read-Host "Enter the path to save the CSV report"
# Get endpoints that communicated with malicious IPs
$results = Get-EndpointsByMaliciousIPs -MaliciousIPsFilePath $maliciousIPsFilePath
if ($results.Count -gt 0) {
# Export results to CSV
Export-ResultsToCSV -Results $results -CsvFilePath $csvFilePath
} else {
Write-Output "No endpoints found communicating with the specified malicious IPs."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import necessary modules: The script imports the
Microsoft.Graph
module to interact with the Microsoft Defender for Endpoint APIs. -
Authenticate to Microsoft Defender for Endpoint:
-
Connect-MicrosoftDefender
: This function authenticates to Microsoft Defender for Endpoint using Microsoft Graph APIs. It includes error handling to manage authentication issues.
-
-
Get Endpoints by Malicious IPs:
-
Get-EndpointsByMaliciousIPs
: This function takes a file path containing a list of malicious IPs and searches for endpoints that communicated with those IPs using the Microsoft Defender for Endpoint APIs. It constructs a query to filter alerts based on network connections to the specified IPs. The results include endpoint names, IP addresses, last communication times, and process names.
-
-
Export Results to CSV:
-
Export-ResultsToCSV
: This function exports the collected results to a CSV file. It includes error handling to manage file export issues.
-
-
Main script execution:
- Prompts the user for the file path containing malicious IPs and the path to save the CSV report.
- Calls the function to get endpoints that communicated with the malicious IPs and exports the results to a CSV file.
-
Save the Script: Save the script as
Hunt-MaliciousIPs.ps1
. -
Run the Script:
.\Hunt-MaliciousIPs.ps1
-
Enter Inputs: When prompted, enter the file path containing malicious IPs and the path to save the CSV report.
-
View Results: The script will produce a report of affected endpoints, their last communication time with the malicious IPs, and any relevant process details in the specified CSV file.
Here's a PowerShell script named Detect-SuspiciousLogons.ps1
that analyzes Windows Event Logs on a specified system or multiple systems to detect suspicious logon events. The script allows the user to specify time ranges and filter criteria for more targeted analysis.
# Function to get suspicious logon events from a system
function Get-SuspiciousLogons {
param (
[Parameter(Mandatory = $true)]
[string[]]$ComputerNames,
[Parameter(Mandatory = $true)]
[datetime]$StartTime,
[Parameter(Mandatory = $true)]
[datetime]$EndTime,
[string]$UserName,
[string[]]$SuspiciousLocations,
[string[]]$OddHours
)
$logName = "Security"
$eventID = 4624
$suspiciousLogons = @()
foreach ($computerName in $ComputerNames) {
Write-Output "Checking logon events on $computerName..."
$query = @"
<QueryList>
<Query Id="0" Path="$logName">
<Select Path="$logName">
*[System[(EventID=$eventID) and TimeCreated[@SystemTime>='$($StartTime.ToUniversalTime().ToString("o"))' and @SystemTime<='$($EndTime.ToUniversalTime().ToString("o"))']]]
</Select>
</Query>
</QueryList>
"@
try {
$events = Get-WinEvent -ComputerName $computerName -FilterXml $query -ErrorAction Stop
} catch {
Write-Error "Failed to retrieve events from $computerName: $_"
continue
}
foreach ($event in $events) {
$logonTime = $event.TimeCreated
$accountName = $event.Properties[5].Value
$ipAddress = $event.Properties[18].Value
$isSuspicious = $false
if ($null -ne $UserName -and $accountName -ne $UserName) {
continue
}
if ($SuspiciousLocations -contains $ipAddress) {
$isSuspicious = $true
}
if ($OddHours -contains $logonTime.Hour) {
$isSuspicious = $true
}
if ($isSuspicious) {
$suspiciousLogons += [PSCustomObject]@{
ComputerName = $computerName
LogonTime = $logonTime
UserName = $accountName
IPAddress = $ipAddress
}
}
}
}
return $suspiciousLogons
}
# Main script
try {
# Get input from the user
$computerNames = Read-Host "Enter the computer names (comma-separated)" -split ","
$startTime = [datetime]::Parse(Read-Host "Enter the start time (e.g., 2023-01-01T00:00:00)")
$endTime = [datetime]::Parse(Read-Host "Enter the end time (e.g., 2023-01-02T00:00:00)")
$userName = Read-Host "Enter the user name to filter (optional, press Enter to skip)"
$suspiciousLocations = Read-Host "Enter the suspicious IP locations (comma-separated, optional, press Enter to skip)" -split ","
$oddHours = Read-Host "Enter the odd hours (comma-separated, 0-23, optional, press Enter to skip)" -split ","
if ($oddHours) {
$oddHours = $oddHours | ForEach-Object { [int]$_ }
}
# Get suspicious logons
$suspiciousLogons = Get-SuspiciousLogons -ComputerNames $computerNames -StartTime $startTime -EndTime $endTime -UserName $userName -SuspiciousLocations $suspiciousLocations -OddHours $oddHours
if ($suspiciousLogons.Count -gt 0) {
$suspiciousLogons | Format-Table
} else {
Write-Output "No suspicious logon events found."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Function Definition:
-
Get-SuspiciousLogons
: This function accepts parameters for computer names, start and end times, user name, suspicious locations, and odd hours. It retrieves logon events (Event ID 4624) from the specified systems and checks for suspicious logons based on the provided criteria.
-
-
Main Script Execution:
- Prompts the user for input: computer names, start and end times, optional user name, suspicious locations, and odd hours.
- Calls the
Get-SuspiciousLogons
function with the provided inputs. - Outputs the suspicious logon events in a table format.
-
Error Handling:
- The script includes error handling to manage issues such as failed event retrieval from specified systems.
-
Save the Script: Save the script as
Detect-SuspiciousLogons.ps1
. -
Run the Script:
.\Detect-SuspiciousLogons.ps1
-
Enter Inputs: When prompted, enter the required and optional inputs:
- Computer names (comma-separated).
- Start and end times.
- Optional user name to filter.
- Optional suspicious IP locations (comma-separated).
- Optional odd hours (comma-separated).
-
View Results: The script will output suspicious logon events in a table format if any are found.
Here is a PowerShell script named Analyze-DefenderAlerts.ps1
that retrieves alerts from Microsoft Defender for Endpoint and performs basic analysis. The script groups alerts by severity, alert type, and affected machines. It can also provide summary statistics and export the results to a CSV file.
# Import necessary modules
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Defender for Endpoint
function Connect-MicrosoftDefender {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All"
Write-Output "Successfully authenticated to Microsoft Defender for Endpoint."
} catch {
Write-Error "Failed to authenticate to Microsoft Defender for Endpoint. Please check your credentials and network connection."
exit
}
}
# Function to get alerts from Microsoft Defender for Endpoint
function Get-DefenderAlerts {
Write-Output "Fetching alerts from Microsoft Defender for Endpoint..."
try {
$alerts = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/alerts"
return $alerts.value
} catch {
Write-Error "Failed to retrieve alerts from Microsoft Defender for Endpoint. Please check your permissions and network connection."
return $null
}
}
# Function to analyze alerts
function Analyze-DefenderAlerts {
param (
[Parameter(Mandatory = $true)]
[array]$Alerts
)
$groupedBySeverity = $Alerts | Group-Object -Property severity
$groupedByAlertType = $Alerts | Group-Object -Property alertType
$groupedByMachine = $Alerts | Group-Object -Property deviceName
return [PSCustomObject]@{
GroupedBySeverity = $groupedBySeverity
GroupedByAlertType = $groupedByAlertType
GroupedByMachine = $groupedByMachine
}
}
# Function to export analysis results to CSV
function Export-AnalysisToCSV {
param (
[Parameter(Mandatory = $true)]
[PSCustomObject]$AnalysisResults,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$csvData = @()
foreach ($group in $AnalysisResults.GroupedBySeverity) {
$csvData += [PSCustomObject]@{
GroupType = "Severity"
GroupName = $group.Name
Count = $group.Count
}
}
foreach ($group in $AnalysisResults.GroupedByAlertType) {
$csvData += [PSCustomObject]@{
GroupType = "Alert Type"
GroupName = $group.Name
Count = $group.Count
}
}
foreach ($group in $AnalysisResults.GroupedByMachine) {
$csvData += [PSCustomObject]@{
GroupType = "Machine"
GroupName = $group.Name
Count = $group.Count
}
}
$csvData | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Analysis results exported to $CsvFilePath"
} catch {
Write-Error "Failed to export analysis results to CSV: $CsvFilePath"
}
}
# Main script
try {
# Authenticate to Microsoft Defender for Endpoint
Connect-MicrosoftDefender
# Get alerts from Microsoft Defender for Endpoint
$alerts = Get-DefenderAlerts
if ($null -ne $alerts -and $alerts.Count -gt 0) {
# Analyze alerts
$analysisResults = Analyze-DefenderAlerts -Alerts $alerts
# Output summary statistics
Write-Output "Summary Statistics:"
Write-Output "Alerts grouped by severity:"
$analysisResults.GroupedBySeverity | Format-Table Name, Count
Write-Output "Alerts grouped by alert type:"
$analysisResults.GroupedByAlertType | Format-Table Name, Count
Write-Output "Alerts grouped by machine:"
$analysisResults.GroupedByMachine | Format-Table Name, Count
# Export results to CSV
$csvFilePath = Read-Host "Enter the path to save the CSV report"
Export-AnalysisToCSV -AnalysisResults $analysisResults -CsvFilePath $csvFilePath
} else {
Write-Output "No alerts found."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import necessary modules: The script imports the
Microsoft.Graph
module to interact with the Microsoft Defender for Endpoint APIs. -
Authenticate to Microsoft Defender for Endpoint:
-
Connect-MicrosoftDefender
: This function authenticates to Microsoft Defender for Endpoint using Microsoft Graph APIs. It includes error handling to manage authentication issues.
-
-
Get Alerts from Microsoft Defender for Endpoint:
-
Get-DefenderAlerts
: This function retrieves alerts from Microsoft Defender for Endpoint. It includes error handling to manage issues retrieving alerts.
-
-
Analyze Alerts:
-
Analyze-DefenderAlerts
: This function takes an array of alerts and groups them by severity, alert type, and affected machines. It returns a custom object with the grouped results.
-
-
Export Analysis Results to CSV:
-
Export-AnalysisToCSV
: This function exports the analysis results to a CSV file. It includes error handling to manage file export issues.
-
-
Main script execution:
- The script authenticates to Microsoft Defender for Endpoint, retrieves alerts, analyzes them, and outputs summary statistics.
- Prompts the user for the path to save the CSV report and exports the analysis results to a CSV file.
-
Save the Script: Save the script as
Analyze-DefenderAlerts.ps1
. -
Run the Script:
.\Analyze-DefenderAlerts.ps1
-
Enter Inputs: When prompted, enter the path to save the CSV report.
-
View Results: The script will output summary statistics of the alerts grouped by severity, alert type, and affected machines. It will also export the analysis results to the specified CSV file.
Here is a PowerShell script named Get-Vulnerabilities.ps1
that uses the Microsoft Graph Security API to retrieve a list of vulnerabilities for all devices in your tenant. The script allows filtering by severity, vulnerability type, and device name. The output can be displayed as a well-formatted table or exported to a CSV file.
# Import necessary modules
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Graph
function Connect-MicrosoftGraph {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All"
Write-Output "Successfully authenticated to Microsoft Graph."
} catch {
Write-Error "Failed to authenticate to Microsoft Graph. Please check your credentials and network connection."
exit
}
}
# Function to get vulnerabilities from Microsoft Graph
function Get-Vulnerabilities {
param (
[string]$Severity,
[string]$VulnerabilityType,
[string]$DeviceName
)
Write-Output "Fetching vulnerabilities from Microsoft Graph..."
$filter = @()
if ($Severity) {
$filter += "severity eq '$Severity'"
}
if ($VulnerabilityType) {
$filter += "vulnerabilityType eq '$VulnerabilityType'"
}
if ($DeviceName) {
$filter += "deviceName eq '$DeviceName'"
}
$filterQuery = $filter -join " and "
$queryUri = "https://graph.microsoft.com/v1.0/security/vulnerabilities"
if ($filterQuery) {
$queryUri += "?\$filter=$filterQuery"
}
try {
$vulnerabilities = Invoke-MgGraphRequest -Method GET -Uri $queryUri
return $vulnerabilities.value
} catch {
Write-Error "Failed to retrieve vulnerabilities from Microsoft Graph. Please check your permissions and network connection."
return $null
}
}
# Function to export vulnerabilities to a CSV file
function Export-VulnerabilitiesToCSV {
param (
[Parameter(Mandatory = $true)]
[array]$Vulnerabilities,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$Vulnerabilities | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Vulnerabilities exported to $CsvFilePath"
} catch {
Write-Error "Failed to export vulnerabilities to CSV: $CsvFilePath"
}
}
# Main script
try {
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Get input from the user
$severity = Read-Host "Enter the severity to filter (e.g., High, Medium, Low) (optional, press Enter to skip)"
$vulnerabilityType = Read-Host "Enter the vulnerability type to filter (optional, press Enter to skip)"
$deviceName = Read-Host "Enter the device name to filter (optional, press Enter to skip)"
$outputFormat = Read-Host "Enter the output format (Table or CSV)"
$csvFilePath = if ($outputFormat -eq "CSV") { Read-Host "Enter the path to save the CSV file" } else { $null }
# Get vulnerabilities
$vulnerabilities = Get-Vulnerabilities -Severity $severity -VulnerabilityType $vulnerabilityType -DeviceName $deviceName
if ($null -ne $vulnerabilities -and $vulnerabilities.Count -gt 0) {
if ($outputFormat -eq "CSV" -and $csvFilePath) {
# Export vulnerabilities to CSV
Export-VulnerabilitiesToCSV -Vulnerabilities $vulnerabilities -CsvFilePath $csvFilePath
} else {
# Display vulnerabilities in a table format
$vulnerabilities | Format-Table
}
} else {
Write-Output "No vulnerabilities found."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import necessary modules: The script imports the
Microsoft.Graph
module to interact with the Microsoft Graph Security API. -
Authenticate to Microsoft Graph:
-
Connect-MicrosoftGraph
: This function authenticates to Microsoft Graph using Microsoft Graph APIs. It includes error handling to manage authentication issues.
-
-
Get Vulnerabilities from Microsoft Graph:
-
Get-Vulnerabilities
: This function retrieves vulnerabilities from Microsoft Graph. It allows filtering by severity, vulnerability type, and device name. It constructs a filter query based on the provided inputs.
-
-
Export Vulnerabilities to CSV:
-
Export-VulnerabilitiesToCSV
: This function exports the vulnerabilities to a CSV file. It includes error handling to manage file export issues.
-
-
Main script execution:
- The script authenticates to Microsoft Graph, prompts the user for filter criteria and output format, retrieves vulnerabilities, and either displays them in a table format or exports them to a CSV file based on the user's choice.
-
Save the Script: Save the script as
Get-Vulnerabilities.ps1
. -
Run the Script:
.\Get-Vulnerabilities.ps1
-
Enter Inputs: When prompted, enter the filter criteria for severity, vulnerability type, and device name, and choose the output format (Table or CSV).
-
View Results: The script will either display the vulnerabilities in a table format or export them to the specified CSV file based on the user's choice.
Here's a PowerShell script named Export-VulnerabilityReport.ps1
that generates a detailed vulnerability report. This script builds upon the vulnerabilities retrieved by Get-Vulnerabilities.ps1
and includes additional information such as CVE IDs, CVSS scores, and remediation suggestions. It also allows the user to specify the report format (CSV, HTML, etc.).
# Import necessary modules
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Graph
function Connect-MicrosoftGraph {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All"
Write-Output "Successfully authenticated to Microsoft Graph."
} catch {
Write-Error "Failed to authenticate to Microsoft Graph. Please check your credentials and network connection."
exit
}
}
# Function to get vulnerabilities from Microsoft Graph
function Get-Vulnerabilities {
param (
[string]$Severity,
[string]$VulnerabilityType,
[string]$DeviceName
)
Write-Output "Fetching vulnerabilities from Microsoft Graph..."
$filter = @()
if ($Severity) {
$filter += "severity eq '$Severity'"
}
if ($VulnerabilityType) {
$filter += "vulnerabilityType eq '$VulnerabilityType'"
}
if ($DeviceName) {
$filter += "deviceName eq '$DeviceName'"
}
$filterQuery = $filter -join " and "
$queryUri = "https://graph.microsoft.com/v1.0/security/vulnerabilities"
if ($filterQuery) {
$queryUri += "?\$filter=$filterQuery"
}
try {
$vulnerabilities = Invoke-MgGraphRequest -Method GET -Uri $queryUri
return $vulnerabilities.value
} catch {
Write-Error "Failed to retrieve vulnerabilities from Microsoft Graph. Please check your permissions and network connection."
return $null
}
}
# Function to generate the report data
function Generate-ReportData {
param (
[array]$Vulnerabilities
)
$reportData = @()
foreach ($vuln in $Vulnerabilities) {
$reportData += [PSCustomObject]@{
DeviceName = $vuln.deviceName
VulnerabilityType = $vuln.vulnerabilityType
Severity = $vuln.severity
CVEID = $vuln.cveId
CVSSScore = $vuln.cvssScore
Remediation = $vuln.remediation
}
}
return $reportData
}
# Function to export report data to CSV
function Export-ReportToCSV {
param (
[Parameter(Mandatory = $true)]
[array]$ReportData,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$ReportData | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Report exported to $CsvFilePath"
} catch {
Write-Error "Failed to export report to CSV: $CsvFilePath"
}
}
# Function to export report data to HTML
function Export-ReportToHTML {
param (
[Parameter(Mandatory = $true)]
[array]$ReportData,
[Parameter(Mandatory = $true)]
[string]$HtmlFilePath
)
try {
$html = $ReportData | ConvertTo-Html -Property DeviceName, VulnerabilityType, Severity, CVEID, CVSSScore, Remediation -Head "<style>table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 8px; text-align: left; } th { background-color: #f2f2f2; }</style>"
$html | Set-Content -Path $HtmlFilePath
Write-Output "Report exported to $HtmlFilePath"
} catch {
Write-Error "Failed to export report to HTML: $HtmlFilePath"
}
}
# Main script
try {
# Authenticate to Microsoft Graph
Connect-MicrosoftGraph
# Get input from the user
$severity = Read-Host "Enter the severity to filter (e.g., High, Medium, Low) (optional, press Enter to skip)"
$vulnerabilityType = Read-Host "Enter the vulnerability type to filter (optional, press Enter to skip)"
$deviceName = Read-Host "Enter the device name to filter (optional, press Enter to skip)"
$reportFormat = Read-Host "Enter the report format (CSV, HTML)"
$filePath = Read-Host "Enter the path to save the report file"
# Get vulnerabilities
$vulnerabilities = Get-Vulnerabilities -Severity $severity -VulnerabilityType $vulnerabilityType -DeviceName $deviceName
if ($null -ne $vulnerabilities -and $vulnerabilities.Count -gt 0) {
# Generate report data
$reportData = Generate-ReportData -Vulnerabilities $vulnerabilities
# Export report based on chosen format
if ($reportFormat -eq "CSV") {
Export-ReportToCSV -ReportData $reportData -CsvFilePath $filePath
} elseif ($reportFormat -eq "HTML") {
Export-ReportToHTML -ReportData $reportData -HtmlFilePath $filePath
} else {
Write-Error "Unsupported report format: $reportFormat"
}
} else {
Write-Output "No vulnerabilities found."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import necessary modules: The script imports the
Microsoft.Graph
module to interact with the Microsoft Graph Security API. -
Authenticate to Microsoft Graph:
-
Connect-MicrosoftGraph
: This function authenticates to Microsoft Graph using Microsoft Graph APIs. It includes error handling to manage authentication issues.
-
-
Get Vulnerabilities from Microsoft Graph:
-
Get-Vulnerabilities
: This function retrieves vulnerabilities from Microsoft Graph. It allows filtering by severity, vulnerability type, and device name. It constructs a filter query based on the provided inputs.
-
-
Generate Report Data:
-
Generate-ReportData
: This function processes the vulnerabilities and creates a custom object with additional fields such as CVE IDs, CVSS scores, and remediation suggestions.
-
-
Export Report to CSV:
-
Export-ReportToCSV
: This function exports the report data to a CSV file. It includes error handling to manage file export issues.
-
-
Export Report to HTML:
-
Export-ReportToHTML
: This function exports the report data to an HTML file with basic styling for readability. It includes error handling to manage file export issues.
-
-
Main script execution:
- The script authenticates to Microsoft Graph, prompts the user for filter criteria and report format, retrieves vulnerabilities, generates report data, and exports the report based on the chosen format.
-
Save the Script: Save the script as
Export-VulnerabilityReport.ps1
. -
Run the Script:
.\Export-VulnerabilityReport.ps1
-
Enter Inputs: When prompted, enter the filter criteria for severity, vulnerability type, and device name, choose the report format (CSV or HTML), and provide the file path to save the report.
-
View Results: The script will either display the vulnerabilities in the specified format or export them to the specified file based on the user's choice.
Here is a PowerShell script named Analyze-DefenderAlerts.ps1
that retrieves alerts from Microsoft Defender for Endpoint and performs basic analysis. The script groups alerts by severity, alert type, and affected machines. It also provides an option to export the results to a CSV file.
# Import necessary modules
Import-Module Microsoft.Graph
# Function to authenticate to Microsoft Defender for Endpoint
function Connect-MicrosoftDefender {
try {
Connect-MgGraph -Scopes "SecurityEvents.Read.All"
Write-Output "Successfully authenticated to Microsoft Defender for Endpoint."
} catch {
Write-Error "Failed to authenticate to Microsoft Defender for Endpoint. Please check your credentials and network connection."
exit
}
}
# Function to get alerts from Microsoft Defender for Endpoint
function Get-DefenderAlerts {
Write-Output "Fetching alerts from Microsoft Defender for Endpoint..."
try {
$alerts = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/security/alerts"
return $alerts.value
} catch {
Write-Error "Failed to retrieve alerts from Microsoft Defender for Endpoint. Please check your permissions and network connection."
return $null
}
}
# Function to analyze alerts
function Analyze-DefenderAlerts {
param (
[Parameter(Mandatory = $true)]
[array]$Alerts
)
$groupedBySeverity = $Alerts | Group-Object -Property severity
$groupedByAlertType = $Alerts | Group-Object -Property alertType
$groupedByMachine = $Alerts | Group-Object -Property deviceName
return [PSCustomObject]@{
GroupedBySeverity = $groupedBySeverity
GroupedByAlertType = $groupedByAlertType
GroupedByMachine = $groupedByMachine
}
}
# Function to export analysis results to CSV
function Export-AnalysisToCSV {
param (
[Parameter(Mandatory = $true)]
[PSCustomObject]$AnalysisResults,
[Parameter(Mandatory = $true)]
[string]$CsvFilePath
)
try {
$csvData = @()
foreach ($group in $AnalysisResults.GroupedBySeverity) {
$csvData += [PSCustomObject]@{
GroupType = "Severity"
GroupName = $group.Name
Count = $group.Count
}
}
foreach ($group in $AnalysisResults.GroupedByAlertType) {
$csvData += [PSCustomObject]@{
GroupType = "Alert Type"
GroupName = $group.Name
Count = $group.Count
}
}
foreach ($group in $AnalysisResults.GroupedByMachine) {
$csvData += [PSCustomObject]@{
GroupType = "Machine"
GroupName = $group.Name
Count = $group.Count
}
}
$csvData | Export-Csv -Path $CsvFilePath -NoTypeInformation
Write-Output "Analysis results exported to $CsvFilePath"
} catch {
Write-Error "Failed to export analysis results to CSV: $CsvFilePath"
}
}
# Main script
try {
# Authenticate to Microsoft Defender for Endpoint
Connect-MicrosoftDefender
# Get alerts from Microsoft Defender for Endpoint
$alerts = Get-DefenderAlerts
if ($null -ne $alerts -and $alerts.Count -gt 0) {
# Analyze alerts
$analysisResults = Analyze-DefenderAlerts -Alerts $alerts
# Output summary statistics
Write-Output "Summary Statistics:"
Write-Output "Alerts grouped by severity:"
$analysisResults.GroupedBySeverity | Format-Table Name, Count
Write-Output "Alerts grouped by alert type:"
$analysisResults.GroupedByAlertType | Format-Table Name, Count
Write-Output "Alerts grouped by machine:"
$analysisResults.GroupedByMachine | Format-Table Name, Count
# Prompt user for export to CSV
$exportToCsv = Read-Host "Would you like to export the results to a CSV file? (yes/no)"
if ($exportToCsv -eq "yes") {
$csvFilePath = Read-Host "Enter the path to save the CSV report"
Export-AnalysisToCSV -AnalysisResults $analysisResults -CsvFilePath $csvFilePath
}
} else {
Write-Output "No alerts found."
}
} catch {
Write-Error "An error occurred: $_"
}
-
Import necessary modules: The script imports the
Microsoft.Graph
module to interact with Microsoft Defender for Endpoint APIs. -
Authenticate to Microsoft Defender for Endpoint:
-
Connect-MicrosoftDefender
: This function authenticates to Microsoft Defender for Endpoint using Microsoft Graph APIs. It includes error handling to manage authentication issues.
-
-
Get Alerts from Microsoft Defender for Endpoint:
-
Get-DefenderAlerts
: This function retrieves alerts from Microsoft Defender for Endpoint. It includes error handling to manage issues retrieving alerts.
-
-
Analyze Alerts:
-
Analyze-DefenderAlerts
: This function takes an array of alerts and groups them by severity, alert type, and affected machines. It returns a custom object with the grouped results.
-
-
Export Analysis Results to CSV:
-
Export-AnalysisToCSV
: This function exports the analysis results to a CSV file. It includes error handling to manage file export issues.
-
-
Main script execution:
- The script authenticates to Microsoft Defender for Endpoint, retrieves alerts, analyzes them, and outputs summary statistics.
- It prompts the user for whether to export the results to a CSV file, and if so, the script saves the analysis results to the specified CSV file.
-
Save the Script: Save the script as
Analyze-DefenderAlerts.ps1
. -
Run the Script:
.\Analyze-DefenderAlerts.ps1
-
Enter Inputs: When prompted, enter whether to export the results to a CSV file and the path to save the CSV file.
-
View Results: The script will output summary statistics of the alerts grouped by severity, alert type, and affected machines. If chosen, it will also export the analysis results to the specified CSV file.
Sure, here are the PowerShell one-liners and small scripts for each of the prompts:
"Write a one-liner PowerShell command to get all Azure AD groups a user is a member of."
Get-AzADUser -UserPrincipalName <UserPrincipalName> | Get-AzADGroupMember | Select-Object DisplayName
Replace <UserPrincipalName>
with the user's principal name.
"Give me a PowerShell one-liner to list all Azure subscriptions for the currently logged-in user."
Get-AzSubscription | Select-Object SubscriptionName, SubscriptionId
"Generate a PowerShell command to check the health status of a specific Azure resource (e.g., virtual machine or storage account)."
Get-AzResourceHealth -ResourceId "/subscriptions/<SubscriptionId>/resourceGroups/<ResourceGroupName>/providers/Microsoft.Compute/virtualMachines/<VMName>"
Replace <SubscriptionId>
, <ResourceGroupName>
, and <VMName>
with the appropriate values.
"Write a PowerShell one-liner to get all security recommendations for a specific Azure virtual machine."
Get-AzSecurityTask -ResourceId "/subscriptions/<SubscriptionId>/resourceGroups/<ResourceGroupName>/providers/Microsoft.Compute/virtualMachines/<VMName>" | Select-Object DisplayName, Severity, State
Replace <SubscriptionId>
, <ResourceGroupName>
, and <VMName>
with the appropriate values.
"Show me a PowerShell command to create a new Azure AD user with a given display name, user principal name, and password."
New-AzADUser -DisplayName "John Doe" -UserPrincipalName "[email protected]" -Password "P@ssw0rd!" -MailNickname "johndoe" -AccountEnabled $true
Replace John Doe
, [email protected]
, and P@ssw0rd!
with the appropriate values for the new user.
Feel free to replace the placeholders with actual values for your specific use case.
"Create a PowerShell command to search Azure Sentinel logs for a specific event ID or string pattern."
Search-AzSentinel -WorkspaceName <WorkspaceName> -ResourceGroupName <ResourceGroupName> -Query "search * | where EventID == '<EventID>' or Message contains '<StringPattern>'"
Replace <WorkspaceName>
, <ResourceGroupName>
, <EventID>
, and <StringPattern>
with the appropriate values.
"Write a one-liner to retrieve detailed information about a specific Azure Sentinel incident."
Get-AzSentinelIncident -ResourceGroupName <ResourceGroupName> -WorkspaceName <WorkspaceName> -IncidentId <IncidentId>
Replace <ResourceGroupName>
, <WorkspaceName>
, and <IncidentId>
with the appropriate values.
"Give me a PowerShell command to export Azure Sentinel log data (e.g., SecurityEvents) for a specific time range to a CSV file."
Invoke-AzOperationalInsightsQuery -WorkspaceName <WorkspaceName> -ResourceGroupName <ResourceGroupName> -Query "SecurityEvent | where TimeGenerated >= datetime(<StartDate>) and TimeGenerated <= datetime(<EndDate>)" | Export-Csv -Path "C:\Path\To\Export\SecurityEvents.csv" -NoTypeInformation
Replace <WorkspaceName>
, <ResourceGroupName>
, <StartDate>
, <EndDate>
, and C:\Path\To\Export\SecurityEvents.csv
with the appropriate values.
"Generate a PowerShell script to isolate an Azure virtual machine from the network."
# Variables
$ResourceGroupName = "<ResourceGroupName>"
$NetworkSecurityGroupName = "<NSGName>"
$VMName = "<VMName>"
# Get the Network Interface associated with the VM
$networkInterface = Get-AzNetworkInterface -ResourceGroupName $ResourceGroupName | Where-Object { $_.VirtualMachine -ne $null -and $_.VirtualMachine.Id.EndsWith($VMName) }
# Create a new Network Security Group rule to block all traffic
$nsgRule = New-AzNetworkSecurityRuleConfig -Name "DenyAll" -Description "Isolate VM" -Access Deny -Protocol * -Direction Inbound -Priority 100 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange *
# Apply the new rule to the Network Security Group
$nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $ResourceGroupName -Name $NetworkSecurityGroupName
$nsg.SecurityRules.Add($nsgRule)
$nsg | Set-AzNetworkSecurityGroup
# Associate the NSG with the Network Interface
$networkInterface.NetworkSecurityGroup = $nsg
$networkInterface | Set-AzNetworkInterface
Write-Output "VM $VMName has been isolated from the network."
Replace <ResourceGroupName>
, <NSGName>
, and <VMName>
with the appropriate values. This script retrieves the network interface associated with the VM, creates a network security group (NSG) rule to deny all inbound traffic, and applies this NSG rule to the network interface, effectively isolating the VM from the network.
Feel free to adjust the variables and values to match your specific environment and requirements.
"Write a PowerShell one-liner to identify processes on a Windows system that are communicating with a known malicious IP address."
Get-NetTCPConnection | Where-Object { $_.RemoteAddress -eq '<MaliciousIPAddress>' } | ForEach-Object { Get-Process -Id $_.OwningProcess } | Select-Object Id, ProcessName, Path
Replace <MaliciousIPAddress>
with the actual IP address you want to check.
"Generate a PowerShell script to scan Windows Event Logs for suspicious PowerShell command executions (e.g., encoded commands, obfuscation)."
# Define the time range for scanning
$startTime = (Get-Date).AddDays(-7)
$endTime = Get-Date
# Query Windows Event Logs for suspicious PowerShell activity
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; StartTime=$startTime; EndTime=$endTime; Id=4104} |
Where-Object { $_.Message -match 'encodedCommand|Invoke-Expression|IEX|base64' } |
Select-Object TimeCreated, Id, LevelDisplayName, Message |
Format-Table -AutoSize
"Show me a PowerShell command to list all running services on a remote Windows system."
Invoke-Command -ComputerName <RemoteComputerName> -ScriptBlock { Get-Service | Where-Object { $_.Status -eq 'Running' } | Select-Object Name, DisplayName, Status }
Replace <RemoteComputerName>
with the name of the remote computer you want to query.
These scripts should help you with various threat-hunting tasks and provide valuable information for your investigations.
"Write a PowerShell one-liner to retrieve vulnerability assessment results for an Azure resource (e.g., VM) from Azure Security Center."
Get-AzSecurityTask -ResourceId "/subscriptions/<SubscriptionId>/resourceGroups/<ResourceGroupName>/providers/Microsoft.Compute/virtualMachines/<VMName>" | Where-Object { $_.TaskType -eq 'Vulnerability' } | Select-Object DisplayName, Severity, State, CreationTime
Replace <SubscriptionId>
, <ResourceGroupName>
, and <VMName>
with the appropriate values.
"Give me a PowerShell command to get a list of installed software on a Windows machine."
Get-WmiObject -Class Win32_Product | Select-Object Name, Version, InstallDate | Format-Table -AutoSize
"Create a PowerShell script to check for missing security updates on a Windows system and output the KB numbers."
# Ensure the Update-Module is installed
if (-not (Get-Module -ListAvailable -Name PSWindowsUpdate)) {
Install-Module -Name PSWindowsUpdate -Force -SkipPublisherCheck
}
# Import the PSWindowsUpdate module
Import-Module PSWindowsUpdate
# Check for missing security updates
$updates = Get-WindowsUpdate -MicrosoftUpdate -AcceptAll -IgnoreReboot -Install -NotCategory 'Driver' -NotTitle 'Preview' -NotKBArticleID 'KB5005698'
$missingUpdates = $updates | Where-Object { $_.Categories -contains 'Security Updates' }
# Output the missing security updates
if ($missingUpdates) {
$missingUpdates | Select-Object -ExpandProperty KBArticleID
} else {
Write-Output "No missing security updates found."
}
-
Get Azure Security Center Vulnerability Assessment Results:
- The one-liner retrieves vulnerability assessment results for a specified Azure VM from Azure Security Center.
- Replace the placeholders with actual values to target the specific Azure resource.
-
Get Software Inventory for a Windows System:
- The command retrieves a list of installed software on a Windows machine using the
Win32_Product
WMI class. - It outputs the software name, version, and install date in a formatted table.
- The command retrieves a list of installed software on a Windows machine using the
-
Check for Missing Windows Security Patches:
- The script ensures the
PSWindowsUpdate
module is installed and imported. - It retrieves missing security updates using
Get-WindowsUpdate
and filters out non-security updates. - It outputs the KB numbers of the missing security updates.
- This script also handles scenarios where no security updates are missing and informs the user.
- The script ensures the
Feel free to adjust the scripts to better suit your specific environment and requirements.
"Write a PowerShell one-liner to check the compliance status of Azure resources against a specific Azure Policy definition."
Get-AzPolicyState -PolicyDefinitionName '<PolicyDefinitionName>' | Select-Object ResourceId, ComplianceState, Timestamp
Replace <PolicyDefinitionName>
with the name of your Azure Policy definition.
"Generate a PowerShell command to disable a specific Azure Policy assignment at a subscription or resource group level."
Remove-AzPolicyAssignment -Name '<PolicyAssignmentName>' -Scope '/subscriptions/<SubscriptionId>/resourceGroups/<ResourceGroupName>'
Replace <PolicyAssignmentName>
, <SubscriptionId>
, and <ResourceGroupName>
with the appropriate values. If you are targeting a subscription level, you can omit the resourceGroups/<ResourceGroupName>
part and just use /subscriptions/<SubscriptionId>
.
"Show me a PowerShell command to retrieve a history of changes to Azure Policy assignments in a subscription."
Search-AzGraph -Query "Resources | where type == 'microsoft.authorization/policyassignments' | project id, name, properties.displayName, properties.policyDefinitionId, properties.scope, properties.parameters, properties.provisioningState, properties.createdOn, properties.updatedOn"
This command uses the Azure Resource Graph to query for policy assignment changes, including creation and update timestamps.
These commands should help you manage and audit Azure Policy assignments effectively. Adjust the placeholders to fit your specific environment and needs.
"Write a PowerShell one-liner to check the compliance status of Azure resources against a specific Azure Policy definition."
Get-AzPolicyState -PolicyDefinitionName '<PolicyDefinitionName>' | Select-Object ResourceId, ComplianceState, Timestamp | Format-Table -AutoSize
Replace <PolicyDefinitionName>
with the name of your Azure Policy definition.
"Generate a PowerShell command to disable a specific Azure Policy assignment at a subscription or resource group level."
param (
[string]$PolicyAssignmentName,
[string]$Scope
)
try {
Remove-AzPolicyAssignment -Name $PolicyAssignmentName -Scope $Scope -ErrorAction Stop
Write-Output "Policy assignment '$PolicyAssignmentName' has been successfully removed from scope '$Scope'."
} catch {
Write-Error "Failed to remove policy assignment '$PolicyAssignmentName' from scope '$Scope'. Error: $_"
}
Replace $PolicyAssignmentName
and $Scope
with the appropriate values when running the script.
"Show me a PowerShell command to retrieve a history of changes to Azure Policy assignments in a subscription."
param (
[string]$SubscriptionId
)
try {
Search-AzGraph -Query "Resources | where type == 'microsoft.authorization/policyassignments' and subscriptionId == '$SubscriptionId' | project id, name, properties.displayName, properties.policyDefinitionId, properties.scope, properties.parameters, properties.provisioningState, properties.createdOn, properties.updatedOn" | Format-Table -AutoSize
} catch {
Write-Error "Failed to retrieve policy assignment changes for subscription '$SubscriptionId'. Error: $_"
}
Replace $SubscriptionId
with your subscription ID when running the script.
Using PowerShell's piping feature, you can chain commands to create more powerful one-liners.
# Example: Get a list of VMs and their power states, and filter out the ones that are running.
Get-AzVM | Select-Object Name, PowerState | Where-Object { $_.PowerState -eq 'VM running' } | Format-Table -AutoSize
Encourage scripts that take input parameters to be easily customized for different scenarios.
param (
[string]$ResourceGroupName,
[string]$VMName
)
Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName | Select-Object Name, PowerState
Add error handling to make scripts more robust.
param (
[string]$ResourceGroupName,
[string]$VMName
)
try {
$vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName -ErrorAction Stop
Write-Output "VM '$VMName' details:"
$vm | Select-Object Name, PowerState
} catch {
Write-Error "Failed to retrieve VM '$VMName' in resource group '$ResourceGroupName'. Error: $_"
}
Include comments in the scripts to explain their purpose and functionality.
param (
[string]$PolicyAssignmentName, # Name of the policy assignment to remove
[string]$Scope # Scope from which to remove the policy assignment (e.g., subscription or resource group level)
)
try {
# Attempt to remove the specified policy assignment from the given scope
Remove-AzPolicyAssignment -Name $PolicyAssignmentName -Scope $Scope -ErrorAction Stop
Write-Output "Policy assignment '$PolicyAssignmentName' has been successfully removed from scope '$Scope'."
} catch {
# Handle any errors that occur during the removal process
Write-Error "Failed to remove policy assignment '$PolicyAssignmentName' from scope '$Scope'. Error: $_"
}
Absolutely! Let's break down the concepts of PowerShell modules and scripts, and then demonstrate how you can leverage the .psm1
files we've created.
PowerShell Scripts vs. Modules: The Key Differences
-
Scripts (.ps1):
- Simple, standalone files containing PowerShell commands.
- Great for quick tasks or ad-hoc automation.
- Not designed for complex functionality or code reuse.
-
Modules (.psm1, .psd1, .dll):
- Collections of functions, cmdlets, variables, and other resources organized into a reusable package.
- Promote code organization, maintainability, and sharing.
- Offer features like versioning, help documentation, and private functions.
- Ideal for building complex tools and libraries.
When to Use Modules
Consider using PowerShell modules when:
- You need to group related functions together.
- You want to make your code reusable across different scripts.
- You need to manage the scope of functions and variables.
- You want to provide help documentation for your functions.
- You want to distribute your code as a package.
Leveraging Your PowerShell Modules (.psm1)
Here's a step-by-step guide on how to use the .psm1
module files we've generated:
-
Save the Module:
- Save each of the PowerShell scripts you received from the AI as
.psm1
files in a dedicated directory. For example, saveGet-PhishingEmail.ps1
asGet-PhishingEmail.psm1
in a folder likePhishingInvestigationModule
.
- Save each of the PowerShell scripts you received from the AI as
-
Create a Module Manifest (Optional):
- For more advanced module features, you can create a module manifest file (.psd1). This file describes the module's metadata, dependencies, and export rules. You can generate one using:
New-ModuleManifest -Path .\PhishingInvestigationModule\PhishingInvestigationModule.psd1 -RootModule Get-PhishingEmail.psm1
- For more advanced module features, you can create a module manifest file (.psd1). This file describes the module's metadata, dependencies, and export rules. You can generate one using:
-
Import the Module:
- To use the functions within your module, you need to import it into your PowerShell session. You can do this in two ways:
- Implicit Import: If you're in the same directory as the module, PowerShell will automatically import it when you try to use a function it contains.
-
Explicit Import: Use the
Import-Module
cmdlet:Import-Module .\PhishingInvestigationModule\Get-PhishingEmail.psm1 # Or the .psd1 file if you have one
- To use the functions within your module, you need to import it into your PowerShell session. You can do this in two ways:
-
Use the Cmdlets:
- Once the module is imported, you can call the cmdlets like any other PowerShell function:
Get-PhishingEmail -Mailbox "[email protected]" -Subject "Suspicious Invoice"
- Once the module is imported, you can call the cmdlets like any other PowerShell function:
Example: Using the Phishing Investigation Module
Let's say you have the Get-PhishingEmail.psm1
module saved in a PhishingInvestigationModule
folder. Here's how you would use it:
# Import the module
Import-Module .\PhishingInvestigationModule\Get-PhishingEmail.psm1
# Retrieve phishing emails
$phishingEmails = Get-PhishingEmail -Mailbox "[email protected]" -Subject "Suspicious Invoice"
# Process the results (e.g., display them, extract IoCs)
$phishingEmails | Format-Table
Key Benefits of Modules
- Organized Code: Modules keep your code well-structured and easier to manage.
- Reusability: Functions within modules can be used in multiple scripts.
- Maintainability: Easier to update and fix issues in a modular structure.
- Collaboration: Modules can be shared with your team for a more streamlined workflow.
Let me know if you'd like more examples or guidance on how to use or extend these modules! These enhancements will make the scripts more flexible, reliable, and easier to understand.
Absolutely! Here are some comprehensive prompts, each covering vital knowledge areas for a Security Operations Analyst, with clear demands for functionality, error handling, MFA support, and more:
Prompt 1: Incident Triage and Investigation Toolkit
"Create a PowerShell module that streamlines incident triage and investigation in Microsoft Sentinel. It should include the following cmdlets:
- Get-SentinelIncident: Retrieve incidents by ID, status, severity, or custom filters. Support pagination for large result sets.
- Export-SentinelIncidentDetails: Export rich incident details (alerts, entities, timelines, comments) to CSV or JSON. Allow for specifying the output format and path.
- Find-RelatedIncidents: Identify incidents related to a given entity (e.g., IP, host, user). Offer options to define the relationship type (e.g., shared IP, same user).
- Analyze-IncidentEntities: Summarize key entities involved in an incident (e.g., most frequent IPs, users, file hashes). Display results in a table format.
Requirements:
- MFA Support: Ensure the module works seamlessly with Multi-Factor Authentication (MFA) enabled accounts.
- Multi-Tenant: Allow for managing incidents across multiple Azure tenants using a single script.
- Error Handling: Implement robust error handling with clear error messages and retry logic for transient failures.
- Documentation: Provide comprehensive cmdlet documentation with examples and parameter descriptions.
- Parameterization: Allow users to pass parameters for flexibility (e.g., incident IDs, filter criteria).
- Piping: Ensure cmdlets can be piped together to create efficient workflows."
Prompt 2: Threat Hunting and IoC Enrichment
"Develop a PowerShell module to aid in threat hunting activities and enrichment of Indicators of Compromise (IoCs). Include the following cmdlets:
- Get-ThreatIntelligence: Fetch threat intelligence data from Microsoft Graph Security API or other sources (VirusTotal, etc.).
- Hunt-SentinelLogs: Search Azure Sentinel logs for specific IoCs (IPs, domains, hashes). Allow for flexible query filters and time ranges.
- Correlate-IoCs: Check if IoCs are present in multiple log sources or threat intelligence feeds. Provide visual correlation maps or reports.
- Enrich-IoC: Gather additional information about IoCs (e.g., reputation, geolocation, related malware families).
Requirements:
- MFA Support: Ensure compatibility with MFA for secure access to sensitive data.
- API Key Integration: Support API keys for external threat intelligence providers.
- Error Handling: Handle network errors, API rate limits, and invalid IoC formats gracefully.
- Documentation: Document cmdlets with examples for common threat hunting scenarios.
- Parameterization: Allow for customizable input parameters (e.g., IoC type, time range, log sources).
- Piping: Enable chaining cmdlets for efficient data manipulation and analysis."
Prompt 3: Azure Security Posture Assessment
"Create a PowerShell module to assess and monitor Azure security posture. Include cmdlets for the following:
- Get-AzureSecurityScore: Retrieve the current Azure Security Center secure score for a subscription or resource group.
- Get-SecurityRecommendations: Fetch security recommendations from Azure Security Center, filter by severity, status, or resource type.
- Assess-RegulatoryCompliance: Check compliance against specific regulatory frameworks (e.g., PCI DSS, HIPAA, GDPR). Generate reports summarizing compliance status.
- Monitor-SecurityAlerts: Continuously monitor for new security alerts in Azure Security Center and send notifications (email, Teams) based on customizable criteria.
Requirements:
- MFA Support: Securely authenticate to Azure using MFA.
- Multi-Subscription: Handle security assessment across multiple Azure subscriptions.
- Error Handling: Handle API errors, authentication failures, and resource access issues.
- Documentation: Clearly document the purpose and usage of each cmdlet.
- Parameterization: Allow for flexible input of subscription IDs, resource groups, and filter criteria.
- Piping: Design cmdlets for seamless integration into PowerShell pipelines."
Please note that these are just a few examples, and you can customize them further to align with your specific security operations needs. You can request the AI to elaborate on specific cmdlets, add more functionality, or create specialized modules for other domains like vulnerability management or identity and access management. Let me know if you need help with more prompts or have any other questions.
Here's a PowerShell module that streamlines incident triage and investigation in Microsoft Sentinel. This module includes cmdlets for retrieving, exporting, finding related incidents, and analyzing incident entities.
# SentinelIncidentToolkit Module
# Import necessary modules
Import-Module Az.SecurityInsights
# Helper function to handle MFA and multi-tenant scenarios
function Connect-Sentinel {
param (
[Parameter(Mandatory = $true)]
[string]$TenantId
)
Connect-AzAccount -TenantId $TenantId -ErrorAction Stop
}
# Cmdlet to retrieve Sentinel incidents
function Get-SentinelIncident {
param (
[Parameter(Mandatory = $false)]
[string]$IncidentId,
[Parameter(Mandatory = $false)]
[string]$Status,
[Parameter(Mandatory = $false)]
[string]$Severity,
[Parameter(Mandatory = $false)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$TenantId
)
try {
Connect-Sentinel -TenantId $TenantId
$incidents = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName
if ($IncidentId) {
$incidents = $incidents | Where-Object { $_.IncidentId -eq $IncidentId }
}
if ($Status) {
$incidents = $incidents | Where-Object { $_.Status -eq $Status }
}
if ($Severity) {
$incidents = $incidents | Where-Object { $_.Severity -eq $Severity }
}
if ($Filter) {
$incidents = $incidents | Where-Object { $_.Title -like "*$Filter*" }
}
return $incidents
} catch {
Write-Error "Failed to retrieve incidents. Error: $_"
}
}
# Cmdlet to export Sentinel incident details
function Export-SentinelIncidentDetails {
param (
[Parameter(Mandatory = $true)]
[string]$IncidentId,
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$OutputFormat, # CSV or JSON
[Parameter(Mandatory = $true)]
[string]$OutputPath
)
try {
Connect-Sentinel -TenantId $TenantId
$incident = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
$details = @{
Incident = $incident
Alerts = Get-AzSentinelIncidentAlert -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
Entities = Get-AzSentinelIncidentEntity -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
Comments = Get-AzSentinelIncidentComment -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
}
if ($OutputFormat -eq 'CSV') {
$details.Incident | Export-Csv -Path "$OutputPath\Incident.csv" -NoTypeInformation
$details.Alerts | Export-Csv -Path "$OutputPath\Alerts.csv" -NoTypeInformation
$details.Entities | Export-Csv -Path "$OutputPath\Entities.csv" -NoTypeInformation
$details.Comments | Export-Csv -Path "$OutputPath\Comments.csv" -NoTypeInformation
} elseif ($OutputFormat -eq 'JSON') {
$details | ConvertTo-Json -Depth 10 | Out-File -FilePath "$OutputPath\IncidentDetails.json"
} else {
Write-Error "Invalid output format specified. Use 'CSV' or 'JSON'."
}
} catch {
Write-Error "Failed to export incident details. Error: $_"
}
}
# Cmdlet to find related incidents
function Find-RelatedIncidents {
param (
[Parameter(Mandatory = $true)]
[string]$Entity,
[Parameter(Mandatory = $true)]
[string]$RelationshipType, # e.g., 'sharedIP', 'sameUser'
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$TenantId
)
try {
Connect-Sentinel -TenantId $TenantId
$query = ""
switch ($RelationshipType) {
'sharedIP' { $query = "* | where Entities contains '$Entity' and Entities type 'IP'" }
'sameUser' { $query = "* | where Entities contains '$Entity' and Entities type 'user'" }
default { Write-Error "Invalid relationship type specified."; return }
}
$relatedIncidents = Search-AzSentinel -WorkspaceName $WorkspaceName -ResourceGroupName $ResourceGroupName -Query $query
return $relatedIncidents
} catch {
Write-Error "Failed to find related incidents. Error: $_"
}
}
# Cmdlet to analyze incident entities
function Analyze-IncidentEntities {
param (
[Parameter(Mandatory = $true)]
[string]$IncidentId,
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$TenantId
)
try {
Connect-Sentinel -TenantId $TenantId
$entities = Get-AzSentinelIncidentEntity -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $IncidentId
$entitySummary = $entities | Group-Object EntityType | Select-Object Name, Count
$entitySummary | Format-Table -AutoSize
} catch {
Write-Error "Failed to analyze incident entities. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Get-SentinelIncident, Export-SentinelIncidentDetails, Find-RelatedIncidents, Analyze-IncidentEntities
- Get-SentinelIncident: Retrieve incidents by various filters.
Get-SentinelIncident -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -TenantId 'my-tenant-id' -Status 'Active'
- Export-SentinelIncidentDetails: Export incident details to CSV or JSON.
Export-SentinelIncidentDetails -IncidentId 'incident-id' -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -TenantId 'my-tenant-id' -OutputFormat 'CSV' -OutputPath 'C:\IncidentDetails'
- Find-RelatedIncidents: Identify incidents related to a specific entity.
Find-RelatedIncidents -Entity 'malicious-ip' -RelationshipType 'sharedIP' -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -TenantId 'my-tenant-id'
- Analyze-IncidentEntities: Summarize key entities involved in an incident.
Analyze-IncidentEntities -IncidentId 'incident-id' -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -TenantId 'my-tenant-id'
-
MFA Support: Ensure that
Connect-AzAccount
supports MFA. -
Multi-Tenant: The module allows connecting to different tenants by specifying the
TenantId
parameter. - Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
SentinelIncidentToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\SentinelIncidentToolkit.psm1'
This module provides a streamlined approach to incident triage and investigation in Microsoft Sentinel, supporting MFA, multi-tenant scenarios, error handling, and parameterization for flexible usage.
Here is a PowerShell module named ThreatHuntingToolkit.psm1
to aid in threat hunting activities and enrichment of Indicators of Compromise (IoCs). The module includes cmdlets for fetching threat intelligence data, searching Azure Sentinel logs, correlating IoCs, and enriching IoCs.
# ThreatHuntingToolkit Module
# Import necessary modules
Import-Module Az.SecurityInsights
Import-Module Microsoft.Graph
# Helper function to handle MFA and API key integration
function Connect-SecurityAPI {
param (
[Parameter(Mandatory = $false)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$ApiKey
)
if ($TenantId) {
Connect-AzAccount -TenantId $TenantId -ErrorAction Stop
}
if ($ApiKey) {
$global:ApiKey = $ApiKey
}
}
# Cmdlet to fetch threat intelligence data
function Get-ThreatIntelligence {
param (
[Parameter(Mandatory = $true)]
[string]$Source, # MicrosoftGraph, VirusTotal, etc.
[Parameter(Mandatory = $false)]
[string]$IoC,
[Parameter(Mandatory = $false)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$ApiKey
)
Connect-SecurityAPI -TenantId $TenantId -ApiKey $ApiKey
try {
switch ($Source) {
'MicrosoftGraph' {
if ($IoC) {
$result = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/security/tiIndicators?\$filter=targetProduct eq 'Azure Sentinel' and displayName eq '$IoC'" -Method GET
} else {
$result = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/security/tiIndicators" -Method GET
}
}
'VirusTotal' {
if (-not $global:ApiKey) { throw "API Key is required for VirusTotal." }
$headers = @{ "x-apikey" = $global:ApiKey }
if ($IoC) {
$result = Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/search?query=$IoC" -Headers $headers
} else {
$result = Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/intelligence/hunting_rulesets" -Headers $headers
}
}
default {
throw "Unsupported source: $Source"
}
}
return $result
} catch {
Write-Error "Failed to fetch threat intelligence data. Error: $_"
}
}
# Cmdlet to search Azure Sentinel logs for specific IoCs
function Hunt-SentinelLogs {
param (
[Parameter(Mandatory = $true)]
[string]$IoC,
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[datetime]$StartTime,
[Parameter(Mandatory = $true)]
[datetime]$EndTime,
[Parameter(Mandatory = $true)]
[string]$TenantId
)
Connect-SecurityAPI -TenantId $TenantId
try {
$query = "* | where TimeGenerated between(datetime($StartTime) .. datetime($EndTime)) | where tostring(EventData) contains '$IoC'"
$logs = Search-AzSentinel -WorkspaceName $WorkspaceName -ResourceGroupName $ResourceGroupName -Query $query
return $logs
} catch {
Write-Error "Failed to search Sentinel logs. Error: $_"
}
}
# Cmdlet to correlate IoCs
function Correlate-IoCs {
param (
[Parameter(Mandatory = $true)]
[array]$IoCs,
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$TenantId
)
Connect-SecurityAPI -TenantId $TenantId
try {
$correlatedResults = @()
foreach ($IoC in $IoCs) {
$result = Hunt-SentinelLogs -IoC $IoC -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -StartTime (Get-Date).AddDays(-30) -EndTime (Get-Date) -TenantId $TenantId
if ($result) {
$correlatedResults += [PSCustomObject]@{
IoC = $IoC
Results = $result
}
}
}
return $correlatedResults
} catch {
Write-Error "Failed to correlate IoCs. Error: $_"
}
}
# Cmdlet to enrich IoCs
function Enrich-IoC {
param (
[Parameter(Mandatory = $true)]
[string]$IoC,
[Parameter(Mandatory = $true)]
[string]$Source, # MicrosoftGraph, VirusTotal, etc.
[Parameter(Mandatory = $false)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$ApiKey
)
Connect-SecurityAPI -TenantId $TenantId -ApiKey $ApiKey
try {
switch ($Source) {
'MicrosoftGraph' {
$result = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/security/tiIndicators?\$filter=displayName eq '$IoC'" -Method GET
}
'VirusTotal' {
if (-not $global:ApiKey) { throw "API Key is required for VirusTotal." }
$headers = @{ "x-apikey" = $global:ApiKey }
$result = Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/search?query=$IoC" -Headers $headers
}
default {
throw "Unsupported source: $Source"
}
}
return $result
} catch {
Write-Error "Failed to enrich IoC. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Get-ThreatIntelligence, Hunt-SentinelLogs, Correlate-IoCs, Enrich-IoC
- Get-ThreatIntelligence: Fetch threat intelligence data.
Get-ThreatIntelligence -Source 'MicrosoftGraph' -IoC 'malicious-ip' -TenantId 'my-tenant-id'
- Hunt-SentinelLogs: Search Azure Sentinel logs for specific IoCs.
Hunt-SentinelLogs -IoC 'malicious-ip' -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -StartTime (Get-Date).AddDays(-7) -EndTime (Get-Date) -TenantId 'my-tenant-id'
- Correlate-IoCs: Check if IoCs are present in multiple log sources.
$IoCs = @('malicious-ip', 'suspicious-domain')
Correlate-IoCs -IoCs $IoCs -ResourceGroupName 'MyResourceGroup' -WorkspaceName 'MyWorkspace' -TenantId 'my-tenant-id'
- Enrich-IoC: Gather additional information about IoCs.
Enrich-IoC -IoC 'malicious-ip' -Source 'VirusTotal' -ApiKey 'your-virustotal-api-key'
-
MFA Support: Ensure that
Connect-AzAccount
supports MFA. - API Key Integration: The module allows using API keys for external threat intelligence providers.
- Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
ThreatHuntingToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\ThreatHuntingToolkit.psm1'
This module provides a comprehensive toolkit for threat hunting and IoC enrichment, supporting MFA, API key integration, error handling, and parameterization for flexible usage.
Here's a PowerShell module named AzureSecurityPostureToolkit.psm1
to assess and monitor Azure security posture. The module includes cmdlets for retrieving the secure score, fetching security recommendations, assessing regulatory compliance, and monitoring security alerts.
# AzureSecurityPostureToolkit Module
# Import necessary modules
Import-Module Az.Security
Import-Module Az.Accounts
# Helper function to handle MFA and multi-subscription scenarios
function Connect-Azure {
param (
[Parameter(Mandatory = $false)]
[string]$TenantId
)
if ($TenantId) {
Connect-AzAccount -TenantId $TenantId -ErrorAction Stop
} else {
Connect-AzAccount -ErrorAction Stop
}
}
# Cmdlet to retrieve the current Azure Security Center secure score
function Get-AzureSecurityScore {
param (
[Parameter(Mandatory = $false)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
try {
if ($SubscriptionId) {
Set-AzContext -SubscriptionId $SubscriptionId
}
if ($ResourceGroupName) {
$score = Get-AzSecuritySecureScore -ResourceGroupName $ResourceGroupName
} else {
$score = Get-AzSecuritySecureScore
}
return $score
} catch {
Write-Error "Failed to retrieve secure score. Error: $_"
}
}
# Cmdlet to fetch security recommendations from Azure Security Center
function Get-SecurityRecommendations {
param (
[Parameter(Mandatory = $false)]
[string]$Severity,
[Parameter(Mandatory = $false)]
[string]$Status,
[Parameter(Mandatory = $false)]
[string]$ResourceType,
[Parameter(Mandatory = $false)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
try {
if ($SubscriptionId) {
Set-AzContext -SubscriptionId $SubscriptionId
}
$recommendations = Get-AzSecurityTask
if ($Severity) {
$recommendations = $recommendations | Where-Object { $_.Severity -eq $Severity }
}
if ($Status) {
$recommendations = $recommendations | Where-Object { $_.State -eq $Status }
}
if ($ResourceType) {
$recommendations = $recommendations | Where-Object { $_.ResourceType -eq $ResourceType }
}
if ($ResourceGroupName) {
$recommendations = $recommendations | Where-Object { $_.ResourceGroupName -eq $ResourceGroupName }
}
return $recommendations
} catch {
Write-Error "Failed to fetch security recommendations. Error: $_"
}
}
# Cmdlet to check compliance against specific regulatory frameworks
function Assess-RegulatoryCompliance {
param (
[Parameter(Mandatory = $true)]
[string]$Framework, # e.g., 'PCI DSS', 'HIPAA', 'GDPR'
[Parameter(Mandatory = $false)]
[string]$SubscriptionId
)
try {
if ($SubscriptionId) {
Set-AzContext -SubscriptionId $SubscriptionId
}
$compliance = Get-AzSecurityRegulatoryComplianceAssessment -Name $Framework
return $compliance
} catch {
Write-Error "Failed to assess regulatory compliance. Error: $_"
}
}
# Cmdlet to continuously monitor for new security alerts
function Monitor-SecurityAlerts {
param (
[Parameter(Mandatory = $true)]
[string]$SubscriptionId,
[Parameter(Mandatory = $true)]
[string]$NotificationMethod, # Email, Teams
[Parameter(Mandatory = $false)]
[string]$Email,
[Parameter(Mandatory = $false)]
[string]$TeamsWebhookUrl,
[Parameter(Mandatory = $false)]
[string]$Severity,
[Parameter(Mandatory = $false)]
[string]$Status
)
try {
Set-AzContext -SubscriptionId $SubscriptionId
while ($true) {
$alerts = Get-AzSecurityAlert
if ($Severity) {
$alerts = $alerts | Where-Object { $_.Severity -eq $Severity }
}
if ($Status) {
$alerts = $alerts | Where-Object { $_.Status -eq $Status }
}
if ($alerts.Count -gt 0) {
switch ($NotificationMethod) {
'Email' {
if (-not $Email) { throw "Email address is required for email notifications." }
$alerts | Format-Table | Out-String | Send-MailMessage -To $Email -Subject "New Security Alerts" -SmtpServer "smtp.yourserver.com"
}
'Teams' {
if (-not $TeamsWebhookUrl) { throw "Teams webhook URL is required for Teams notifications." }
$alerts | Format-Table | Out-String | Invoke-RestMethod -Uri $TeamsWebhookUrl -Method POST -Body @{ text = $_ } | ConvertTo-Json
}
default {
throw "Unsupported notification method: $NotificationMethod"
}
}
}
Start-Sleep -Seconds 300 # Check every 5 minutes
}
} catch {
Write-Error "Failed to monitor security alerts. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Get-AzureSecurityScore, Get-SecurityRecommendations, Assess-RegulatoryCompliance, Monitor-SecurityAlerts
- Get-AzureSecurityScore: Retrieve the current secure score.
Get-AzureSecurityScore -SubscriptionId 'your-subscription-id'
- Get-SecurityRecommendations: Fetch security recommendations.
Get-SecurityRecommendations -Severity 'High' -SubscriptionId 'your-subscription-id'
- Assess-RegulatoryCompliance: Check compliance against specific frameworks.
Assess-RegulatoryCompliance -Framework 'PCI DSS' -SubscriptionId 'your-subscription-id'
- Monitor-SecurityAlerts: Continuously monitor for new security alerts and send notifications.
Monitor-SecurityAlerts -SubscriptionId 'your-subscription-id' -NotificationMethod 'Email' -Email '[email protected]'
-
MFA Support: Ensure that
Connect-AzAccount
supports MFA. -
Multi-Subscription: The module allows handling multiple subscriptions by specifying the
SubscriptionId
parameter. - Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
AzureSecurityPostureToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\AzureSecurityPostureToolkit.psm1'
This module provides a comprehensive toolkit for assessing and monitoring Azure security posture, supporting MFA, multi-subscription scenarios, error handling, and parameterization for flexible usage.
Absolutely! Let's craft some more comprehensive prompts for creating a powerful field toolkit for Security Operations Analysts. We'll focus on real-world scenarios and include the specific requirements you outlined.
Prompt 4: Phishing Investigation and Remediation Toolkit
"Develop a PowerShell module to streamline the investigation and remediation of phishing incidents. Include the following cmdlets:
- Get-PhishingEmail: Retrieve phishing emails from user mailboxes or a centralized quarantine. Support filtering by sender, recipient, subject, or other criteria.
- Extract-EmailIoCs: Extract indicators of compromise (IoCs) from phishing emails, including URLs, attachments, and suspicious headers.
- Analyze-EmailHeaders: Analyze email headers for origin, routing information, and potential spoofing or phishing indicators.
- Hunt-PhishingCampaigns: Search email logs for similar emails or patterns indicative of a broader phishing campaign.
- Remediate-PhishingIncident: Automate remediation actions like removing phishing emails from mailboxes, blocking sender domains, and updating security rules.
Requirements:
- MFA Support: Ensure secure access to mailboxes using Multi-Factor Authentication (MFA).
- Multi-Tenant: Handle phishing investigations across multiple Office 365 tenants.
- Error Handling: Gracefully handle mailbox access issues, invalid email formats, and API errors.
- Documentation: Provide detailed cmdlet descriptions, usage examples, and best practices for phishing investigations.
- Parameterization: Allow flexible input of search criteria, remediation actions, and output formats.
- Piping: Enable chaining of cmdlets for efficient data processing and analysis."
Prompt 5: Identity and Access Management (IAM) Auditing and Enforcement
"Create a PowerShell module for auditing and enforcing identity and access management (IAM) policies. Include cmdlets for:
- Get-AzureADRiskyUsers: Retrieve users flagged as risky in Azure Active Directory (Azure AD) based on risk events or suspicious activity.
- Review-AzureADPermissions: Analyze permissions assigned to users and groups, identifying excessive or unused privileges. Generate reports highlighting potential security risks.
- Enforce-LeastPrivilege: Automate the process of removing excessive permissions or adjusting roles to adhere to the principle of least privilege.
- Monitor-IAMChanges: Continuously monitor Azure AD for changes in user roles, group memberships, and administrative actions. Alert on unauthorized or suspicious changes.
Requirements:
- MFA Support: Require MFA for all actions that modify permissions or user access.
- Audit Logging: Log all changes made by the module for traceability and accountability.
- Error Handling: Handle authentication failures, permission issues, and API errors gracefully.
- Documentation: Provide comprehensive documentation with examples of how to audit and enforce IAM policies.
- Parameterization: Allow for customization of audit criteria, risk thresholds, and notification settings.
- Piping: Facilitate data integration with other tools by allowing output to be piped to other cmdlets or commands."
Prompt 6: Cloud Security Configuration Assessment
"Develop a PowerShell module to assess the security configuration of Azure resources. Include cmdlets for:
- Assess-AzureSecurityCenter: Retrieve and analyze security recommendations from Azure Security Center. Filter by resource type, severity, or status.
- Check-AzureResourceConfiguration: Verify that Azure resources adhere to security best practices and organizational policies.
- Scan-NetworkSecurityGroups (NSGs): Evaluate Network Security Group rules for potential vulnerabilities like overly permissive access or misconfigurations.
- Assess-StorageAccountSecurity: Check storage account configurations for public access, encryption status, and other security risks.
- Generate-ComplianceReport: Generate comprehensive reports summarizing security findings, compliance status, and recommended actions.
Requirements:
- MFA Support: Ensure secure access to Azure resources with MFA.
- Multi-Cloud (Optional): Consider extending the module to assess AWS or GCP environments if applicable.
- Error Handling: Handle authentication failures, resource not found errors, and API limitations robustly.
- Documentation: Clearly explain the purpose and usage of each cmdlet, along with security best practices.
- Parameterization: Allow users to specify subscriptions, resource groups, and filter criteria for assessments.
- Piping: Enable seamless integration with other PowerShell tools and reporting mechanisms."
Let me know if you'd like any modifications to these prompts or additional prompts for other areas of focus in security operations!
Here is a PowerShell module named PhishingInvestigationToolkit.psm1
to streamline the investigation and remediation of phishing incidents. This module includes cmdlets for retrieving phishing emails, extracting IoCs, analyzing email headers, hunting phishing campaigns, and automating remediation actions.
# PhishingInvestigationToolkit Module
# Import necessary modules
Import-Module ExchangeOnlineManagement
# Helper function to handle MFA and multi-tenant scenarios
function Connect-ExchangeOnline {
param (
[Parameter(Mandatory = $true)]
[string]$TenantId
)
Connect-ExchangeOnline -UserPrincipalName "<user>@$TenantId.onmicrosoft.com" -ShowProgress $true -ErrorAction Stop
}
# Cmdlet to retrieve phishing emails
function Get-PhishingEmail {
param (
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$Sender,
[Parameter(Mandatory = $false)]
[string]$Recipient,
[Parameter(Mandatory = $false)]
[string]$Subject,
[Parameter(Mandatory = $false)]
[datetime]$StartDate,
[Parameter(Mandatory = $false)]
[datetime]$EndDate
)
Connect-ExchangeOnline -TenantId $TenantId
try {
$filter = @()
if ($Sender) {
$filter += "Sender -eq '$Sender'"
}
if ($Recipient) {
$filter += "Recipients -eq '$Recipient'"
}
if ($Subject) {
$filter += "Subject -like '*$Subject*'"
}
if ($StartDate) {
$filter += "Received -ge '$($StartDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))'"
}
if ($EndDate) {
$filter += "Received -le '$($EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))'"
}
$searchFilter = $filter -join ' -and '
$emails = Get-Mailbox | ForEach-Object { Get-MessageTrace -Recipient $_.PrimarySmtpAddress -StartDate $StartDate -EndDate $EndDate | Where-Object { $_.MessageId -like $searchFilter } }
return $emails
} catch {
Write-Error "Failed to retrieve phishing emails. Error: $_"
}
}
# Cmdlet to extract IoCs from phishing emails
function Extract-EmailIoCs {
param (
[Parameter(Mandatory = $true)]
[array]$Emails
)
$iocs = @()
foreach ($email in $Emails) {
$urls = ($email.Body -split '\s') | Where-Object { $_ -match 'http[s]?://[^\s]+' }
$attachments = $email.Attachments
$headers = $email.Headers
$iocs += [PSCustomObject]@{
EmailId = $email.MessageId
URLs = $urls -join ', '
Attachments = $attachments -join ', '
Headers = $headers
}
}
return $iocs
}
# Cmdlet to analyze email headers
function Analyze-EmailHeaders {
param (
[Parameter(Mandatory = $true)]
[string]$Header
)
try {
$analysis = @{}
$headerLines = $Header -split '\r\n'
foreach ($line in $headerLines) {
if ($line -match '^(?<key>[^:]+):\s*(?<value>.+)$') {
$analysis[$matches['key']] = $matches['value']
}
}
# Check for potential spoofing indicators
if ($analysis['Received-SPF'] -match 'fail') {
$analysis['SpoofingIndicator'] = 'SPF Fail'
} elseif ($analysis['Authentication-Results'] -match 'dkim=fail') {
$analysis['SpoofingIndicator'] = 'DKIM Fail'
} else {
$analysis['SpoofingIndicator'] = 'None'
}
return $analysis
} catch {
Write-Error "Failed to analyze email header. Error: $_"
}
}
# Cmdlet to search for phishing campaigns
function Hunt-PhishingCampaigns {
param (
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $false)]
[string]$Pattern,
[Parameter(Mandatory = $false)]
[datetime]$StartDate,
[Parameter(Mandatory = $false)]
[datetime]$EndDate
)
Connect-ExchangeOnline -TenantId $TenantId
try {
$filter = @()
if ($Pattern) {
$filter += "Subject -like '*$Pattern*' -or Body -like '*$Pattern*'"
}
if ($StartDate) {
$filter += "Received -ge '$($StartDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))'"
}
if ($EndDate) {
$filter += "Received -le '$($EndDate.ToString("yyyy-MM-ddTHH:mm:ssZ"))'"
}
$searchFilter = $filter -join ' -and '
$campaigns = Get-Mailbox | ForEach-Object { Get-MessageTrace -Recipient $_.PrimarySmtpAddress -StartDate $StartDate -EndDate $EndDate | Where-Object { $_.MessageId -like $searchFilter } }
return $campaigns
} catch {
Write-Error "Failed to hunt phishing campaigns. Error: $_"
}
}
# Cmdlet to remediate phishing incidents
function Remediate-PhishingIncident {
param (
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[array]$Emails,
[Parameter(Mandatory = $true)]
[ValidateSet("Remove", "BlockSender", "UpdateRules")]
[string]$Action
)
Connect-ExchangeOnline -TenantId $TenantId
try {
foreach ($email in $Emails) {
switch ($Action) {
'Remove' {
Search-Mailbox -Identity $email.Recipient -SearchQuery "MessageId:$($email.MessageId)" -DeleteContent
}
'BlockSender' {
New-TransportRule -Name "Block $($email.Sender)" -SenderAddressMatchesPatterns $email.Sender -DeleteMessage $true
}
'UpdateRules' {
# Add custom logic for updating security rules
}
}
}
} catch {
Write-Error "Failed to remediate phishing incident. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Get-PhishingEmail, Extract-EmailIoCs, Analyze-EmailHeaders, Hunt-PhishingCampaigns, Remediate-PhishingIncident
- Get-PhishingEmail: Retrieve phishing emails.
Get-PhishingEmail -TenantId 'your-tenant-id' -Sender '[email protected]' -StartDate (Get-Date).AddDays(-7)
- Extract-EmailIoCs: Extract IoCs from phishing emails.
$emails = Get-PhishingEmail -TenantId 'your-tenant-id' -Sender '[email protected]' -StartDate (Get-Date).AddDays(-7)
Extract-EmailIoCs -Emails $emails
- Analyze-EmailHeaders: Analyze email headers.
Analyze-EmailHeaders -Header 'your-email-header'
- Hunt-PhishingCampaigns: Search for phishing campaigns.
Hunt-PhishingCampaigns -TenantId 'your-tenant-id' -Pattern 'phishing' -StartDate (Get-Date).AddDays(-7)
- Remediate-PhishingIncident: Automate remediation actions.
$emails = Get-PhishingEmail -TenantId 'your-tenant-id' -Sender '[email protected]' -StartDate (Get-Date).AddDays(-7)
Remediate-PhishingIncident -TenantId 'your-tenant-id' -Emails $emails -Action 'Remove'
-
MFA Support: Ensure that
Connect-ExchangeOnline
supports MFA. -
Multi-Tenant: The module allows handling multiple Office 365 tenants by specifying the
TenantId
parameter. - Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
PhishingInvestigationToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\PhishingInvestigationToolkit.psm1'
This module provides a comprehensive toolkit for investigating and remediating phishing incidents, supporting MFA, multi-tenant scenarios, error handling, and parameterization for flexible usage.
Here's a PowerShell module named IAMAuditingToolkit.psm1
to audit and enforce identity and access management (IAM) policies. This module includes cmdlets for retrieving risky users, reviewing permissions, enforcing least privilege, and monitoring IAM changes.
# IAMAuditingToolkit Module
# Import necessary modules
Import-Module AzureAD
Import-Module Az
# Helper function to handle MFA
function Connect-AzureADWithMFA {
try {
Connect-AzureAD -ErrorAction Stop
Write-Output "Successfully authenticated to Azure AD."
} catch {
Write-Error "Failed to authenticate to Azure AD. Please check your credentials and ensure MFA is enabled."
}
}
# Cmdlet to retrieve risky users in Azure AD
function Get-AzureADRiskyUsers {
Connect-AzureADWithMFA
try {
$riskyUsers = Get-AzureADUserRiskyUser
return $riskyUsers
} catch {
Write-Error "Failed to retrieve risky users. Error: $_"
}
}
# Cmdlet to analyze permissions assigned to users and groups
function Review-AzureADPermissions {
Connect-AzureADWithMFA
param (
[Parameter(Mandatory = $false)]
[string]$UserId
)
try {
if ($UserId) {
$permissions = Get-AzureADUserAppRoleAssignment -ObjectId $UserId
} else {
$permissions = Get-AzureADUser | ForEach-Object { Get-AzureADUserAppRoleAssignment -ObjectId $_.ObjectId }
}
$excessivePermissions = $permissions | Where-Object { $_.ResourceDisplayName -match '.*Admin.*' }
return $excessivePermissions
} catch {
Write-Error "Failed to analyze permissions. Error: $_"
}
}
# Cmdlet to enforce least privilege principle
function Enforce-LeastPrivilege {
Connect-AzureADWithMFA
param (
[Parameter(Mandatory = $true)]
[string]$UserId
)
try {
$permissions = Get-AzureADUserAppRoleAssignment -ObjectId $UserId
foreach ($permission in $permissions) {
if ($permission.ResourceDisplayName -match '.*Admin.*') {
Remove-AzureADUserAppRoleAssignment -ObjectId $UserId -AppRoleAssignmentId $permission.Id
Write-Output "Removed admin permission '$($permission.ResourceDisplayName)' from user '$UserId'."
}
}
} catch {
Write-Error "Failed to enforce least privilege. Error: $_"
}
}
# Cmdlet to monitor IAM changes
function Monitor-IAMChanges {
Connect-AzureADWithMFA
param (
[Parameter(Mandatory = $true)]
[string]$TenantId,
[Parameter(Mandatory = $true)]
[string]$NotificationMethod, # Email, Teams
[Parameter(Mandatory = $false)]
[string]$Email,
[Parameter(Mandatory = $false)]
[string]$TeamsWebhookUrl,
[Parameter(Mandatory = $false)]
[int]$FrequencyMinutes = 5
)
try {
while ($true) {
$changes = Get-AzureADAuditDirectoryLogs -All $true -Filter "category eq 'UserManagement'"
if ($changes.Count -gt 0) {
switch ($NotificationMethod) {
'Email' {
if (-not $Email) { throw "Email address is required for email notifications." }
$changes | Format-Table | Out-String | Send-MailMessage -To $Email -Subject "IAM Changes Detected" -SmtpServer "smtp.yourserver.com"
}
'Teams' {
if (-not $TeamsWebhookUrl) { throw "Teams webhook URL is required for Teams notifications." }
$changes | Format-Table | Out-String | Invoke-RestMethod -Uri $TeamsWebhookUrl -Method POST -Body @{ text = $_ } | ConvertTo-Json
}
default {
throw "Unsupported notification method: $NotificationMethod"
}
}
}
Start-Sleep -Seconds ($FrequencyMinutes * 60)
}
} catch {
Write-Error "Failed to monitor IAM changes. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Get-AzureADRiskyUsers, Review-AzureADPermissions, Enforce-LeastPrivilege, Monitor-IAMChanges
- Get-AzureADRiskyUsers: Retrieve users flagged as risky in Azure AD.
Get-AzureADRiskyUsers
- Review-AzureADPermissions: Analyze permissions assigned to users and groups.
Review-AzureADPermissions -UserId 'user-id'
- Enforce-LeastPrivilege: Automate the process of removing excessive permissions.
Enforce-LeastPrivilege -UserId 'user-id'
- Monitor-IAMChanges: Continuously monitor Azure AD for changes and send notifications.
Monitor-IAMChanges -TenantId 'tenant-id' -NotificationMethod 'Email' -Email '[email protected]' -FrequencyMinutes 10
-
MFA Support: Ensure that
Connect-AzureAD
supports MFA. - Audit Logging: All changes made by the module should be logged for traceability.
- Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
IAMAuditingToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\IAMAuditingToolkit.psm1'
This module provides a comprehensive toolkit for auditing and enforcing IAM policies, supporting MFA, audit logging, error handling, and parameterization for flexible usage.
Here's a PowerShell module named CloudSecurityAssessmentToolkit.psm1
to assess the security configuration of Azure resources. This module includes cmdlets for assessing security recommendations, verifying resource configurations, evaluating NSG rules, checking storage account security, and generating compliance reports.
# CloudSecurityAssessmentToolkit Module
# Import necessary modules
Import-Module Az.Security
Import-Module Az.Storage
Import-Module Az.Network
# Helper function to handle MFA
function Connect-AzWithMFA {
try {
Connect-AzAccount -ErrorAction Stop
Write-Output "Successfully authenticated to Azure."
} catch {
Write-Error "Failed to authenticate to Azure. Please check your credentials and ensure MFA is enabled."
}
}
# Cmdlet to assess security recommendations from Azure Security Center
function Assess-AzureSecurityCenter {
param (
[Parameter(Mandatory = $false)]
[string]$ResourceType,
[Parameter(Mandatory = $false)]
[string]$Severity,
[Parameter(Mandatory = $false)]
[string]$Status,
[Parameter(Mandatory = $false)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
Connect-AzWithMFA
try {
if ($SubscriptionId) {
Set-AzContext -SubscriptionId $SubscriptionId
}
$recommendations = Get-AzSecurityTask
if ($ResourceType) {
$recommendations = $recommendations | Where-Object { $_.ResourceType -eq $ResourceType }
}
if ($Severity) {
$recommendations = $recommendations | Where-Object { $_.Severity -eq $Severity }
}
if ($Status) {
$recommendations = $recommendations | Where-Object { $_.State -eq $Status }
}
if ($ResourceGroupName) {
$recommendations = $recommendations | Where-Object { $_.ResourceGroupName -eq $ResourceGroupName }
}
return $recommendations
} catch {
Write-Error "Failed to assess security recommendations. Error: $_"
}
}
# Cmdlet to check Azure resource configurations
function Check-AzureResourceConfiguration {
param (
[Parameter(Mandatory = $true)]
[string]$ResourceId
)
Connect-AzWithMFA
try {
$resource = Get-AzResource -ResourceId $ResourceId -ErrorAction Stop
# Implement specific configuration checks based on resource type
$results = @()
switch ($resource.ResourceType) {
"Microsoft.Compute/virtualMachines" {
# Example check: Ensure VMs have boot diagnostics enabled
$vm = Get-AzVM -ResourceGroupName $resource.ResourceGroupName -Name $resource.Name
if (-not $vm.DiagnosticsProfile.BootDiagnostics.Enabled) {
$results += [PSCustomObject]@{
ResourceName = $resource.Name
Issue = "Boot diagnostics not enabled"
}
}
}
"Microsoft.Sql/servers/databases" {
# Example check: Ensure SQL databases have threat detection enabled
$sqlDb = Get-AzSqlDatabaseThreatDetectionPolicy -ResourceGroupName $resource.ResourceGroupName -ServerName $resource.ServerName -DatabaseName $resource.Name
if ($sqlDb.State -ne 'Enabled') {
$results += [PSCustomObject]@{
ResourceName = $resource.Name
Issue = "Threat detection not enabled"
}
}
}
default {
Write-Warning "No specific checks implemented for resource type $($resource.ResourceType)"
}
}
return $results
} catch {
Write-Error "Failed to check resource configuration. Error: $_"
}
}
# Cmdlet to evaluate Network Security Group (NSG) rules
function Scan-NetworkSecurityGroups {
param (
[Parameter(Mandatory = $true)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
Connect-AzWithMFA
try {
Set-AzContext -SubscriptionId $SubscriptionId
$nsgs = if ($ResourceGroupName) {
Get-AzNetworkSecurityGroup -ResourceGroupName $ResourceGroupName
} else {
Get-AzNetworkSecurityGroup
}
$results = @()
foreach ($nsg in $nsgs) {
foreach ($rule in $nsg.SecurityRules) {
if ($rule.Access -eq 'Allow' -and $rule.Direction -eq 'Inbound' -and $rule.SourceAddressPrefix -eq '*') {
$results += [PSCustomObject]@{
NSGName = $nsg.Name
RuleName = $rule.Name
Issue = "Overly permissive inbound rule"
Description = "Rule allows traffic from any source"
}
}
}
}
return $results
} catch {
Write-Error "Failed to scan Network Security Groups. Error: $_"
}
}
# Cmdlet to assess storage account security configurations
function Assess-StorageAccountSecurity {
param (
[Parameter(Mandatory = $true)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
Connect-AzWithMFA
try {
Set-AzContext -SubscriptionId $SubscriptionId
$storageAccounts = if ($ResourceGroupName) {
Get-AzStorageAccount -ResourceGroupName $ResourceGroupName
} else {
Get-AzStorageAccount
}
$results = @()
foreach ($storageAccount in $storageAccounts) {
if ($storageAccount.EnableHttpsTrafficOnly -eq $false) {
$results += [PSCustomObject]@{
StorageAccountName = $storageAccount.StorageAccountName
Issue = "HTTPS not enforced"
}
}
if ($storageAccount.NetworkRuleSet.DefaultAction -ne 'Deny') {
$results += [PSCustomObject]@{
StorageAccountName = $storageAccount.StorageAccountName
Issue = "Public access allowed"
}
}
if (-not $storageAccount.EncryptionServices.Blob.Enabled -or -not $storageAccount.EncryptionServices.File.Enabled) {
$results += [PSCustomObject]@{
StorageAccountName = $storageAccount.StorageAccountName
Issue = "Encryption not enabled"
}
}
}
return $results
} catch {
Write-Error "Failed to assess storage account security. Error: $_"
}
}
# Cmdlet to generate a compliance report
function Generate-ComplianceReport {
param (
[Parameter(Mandatory = $true)]
[string]$SubscriptionId,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $false)]
[string]$OutputPath
)
Connect-AzWithMFA
try {
Set-AzContext -SubscriptionId $SubscriptionId
$report = @()
$report += Assess-AzureSecurityCenter -SubscriptionId $SubscriptionId -ResourceGroupName $ResourceGroupName
$report += Scan-NetworkSecurityGroups -SubscriptionId $SubscriptionId -ResourceGroupName $ResourceGroupName
$report += Assess-StorageAccountSecurity -SubscriptionId $SubscriptionId -ResourceGroupName $ResourceGroupName
if ($OutputPath) {
$report | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Output "Compliance report generated at $OutputPath"
} else {
return $report
}
} catch {
Write-Error "Failed to generate compliance report. Error: $_"
}
}
# Export module functions
Export-ModuleMember -Function Assess-AzureSecurityCenter, Check-AzureResourceConfiguration, Scan-NetworkSecurityGroups, Assess-StorageAccountSecurity, Generate-ComplianceReport
- Assess-AzureSecurityCenter: Retrieve and analyze security recommendations.
Assess-AzureSecurityCenter -SubscriptionId 'your-subscription-id' -Severity 'High'
- Check-AzureResourceConfiguration: Verify resource configurations.
Check-AzureResourceConfiguration -ResourceId '/subscriptions/your-subscription-id/resourceGroups/your-rg-name/providers/Microsoft.Compute/virtualMachines/your-vm-name'
- Scan-NetworkSecurityGroups: Evaluate NSG rules for potential vulnerabilities.
Scan-NetworkSecurityGroups -SubscriptionId 'your-subscription-id'
- Assess-StorageAccountSecurity: Check storage account configurations.
Assess-StorageAccountSecurity -SubscriptionId 'your-subscription-id'
- Generate-ComplianceReport: Generate a comprehensive compliance report.
Generate-ComplianceReport -SubscriptionId 'your-subscription-id' -OutputPath 'C:\path\to\report.csv'
-
MFA Support: Ensure that
Connect-AzAccount
supports MFA. - Multi-Cloud (Optional): This module currently supports Azure. Extending it to support AWS or GCP would involve similar cmdlets for their respective services.
- Error Handling: The functions include try-catch blocks to handle errors gracefully.
- Documentation: Each cmdlet should be documented with comments and examples as shown in the usage
examples above.
- Parameterization: Parameters allow for flexibility in specifying inputs.
- Piping: Cmdlets can be piped together to create efficient workflows.
- Save the code above as
CloudSecurityAssessmentToolkit.psm1
. - Import the module in your PowerShell session:
Import-Module -Name 'Path\To\CloudSecurityAssessmentToolkit.psm1'
This module provides a comprehensive toolkit for assessing the security configuration of Azure resources, supporting MFA, error handling, and parameterization for flexible usage.
Absolutely! Let's craft some comprehensive prompts designed to generate the essential one-liners and small scripts for the modern Security Operations Analyst's toolbox. These will cover a broad range of scenarios across on-prem, hybrid, and Azure environments.
Incident Response
-
Get Azure Sentinel Incidents by Severity: "Write a PowerShell one-liner to fetch all Azure Sentinel incidents with 'High' severity in the last 24 hours."
-
Find Incidents Related to a Specific Host: "Create a PowerShell command to find all Azure Sentinel incidents where a specific hostname is mentioned in the last 7 days."
-
Export Incident Details with Custom Fields: "Write a PowerShell script to export specific incident details (e.g., title, severity, custom fields) from a list of Sentinel incident IDs to a CSV file."
-
Correlate Events Across Multiple Log Sources: "Craft a PowerShell command to correlate security events from Azure Sentinel, Windows Event Logs, and Syslog within a specified timeframe."
-
Isolate a Compromised VM in Azure: "Generate a PowerShell script to automatically isolate an Azure VM based on a Sentinel alert triggering on suspicious activity."
Threat Hunting
-
Identify Processes Communicating with Known Malicious IPs: "Write a PowerShell one-liner to find processes on a Windows machine that have communicated with IP addresses listed in a text file of known threats."
-
Detect Suspicious PowerShell Invocations: "Create a PowerShell command to search Event Logs for PowerShell commands executed with encoded or obfuscated arguments."
-
Analyze Network Traffic for Anomalies: "Write a PowerShell script to analyze network traffic logs (e.g., from Azure Network Watcher) for unusual spikes, connections to rare ports, or traffic to/from known bad actors."
-
Hunt for Account Brute-Force Attempts: "Create a PowerShell one-liner to identify failed login attempts exceeding a threshold from security logs (Azure AD, Windows Event Logs)."
-
Find Lateral Movement Indicators: "Write a PowerShell script to detect potential lateral movement activities across multiple systems using event logs and process execution data."
Vulnerability Management
-
Get a List of VMs with Missing Critical Patches: "Write a PowerShell one-liner to get a list of Azure VMs with missing critical security patches."
-
Identify Exposed RDP Ports: "Create a PowerShell command to find Azure VMs that have open RDP ports accessible from the internet."
-
Export Vulnerability Scan Results: "Generate a PowerShell script to export vulnerability scan results from Azure Security Center or a third-party scanner to a CSV file."
-
Prioritize Vulnerabilities Based on Severity and Exploitability: "Write a PowerShell script to sort and filter vulnerabilities based on their CVSS score and known exploit availability."
Azure Security
-
Check Azure Policy Compliance: "Write a PowerShell one-liner to assess the compliance status of your Azure resources against a specific Azure Policy definition."
-
Get Azure Security Center Recommendations: "Create a PowerShell command to get all high-severity security recommendations from Azure Security Center for a specific resource group."
-
Review Azure RBAC Permissions: "Write a PowerShell script to analyze Azure RBAC permissions for users or groups and identify potential excessive privileges."
-
Enable MFA for Critical Azure AD Roles: "Generate a PowerShell script to enforce Multi-Factor Authentication (MFA) for users assigned to specific Azure AD roles (e.g., Global Administrator)."
-
Audit Azure Resource Changes: "Create a PowerShell command to retrieve the activity logs for a specific Azure resource (e.g., storage account) and filter for configuration changes."
On-Premises Security
-
Detect Suspicious Logon Activity: "Write a PowerShell one-liner to find logon events in the Windows Security Log that occurred outside of normal business hours."
-
Identify Unpatched Software: "Create a PowerShell command to list installed software on a Windows system and check for available updates."
-
Scan for Malware with Microsoft Defender: "Write a PowerShell one-liner to initiate a full system scan using Microsoft Defender Antivirus and get the results."
-
Collect System Information for Incident Analysis: "Generate a PowerShell script to gather system information (OS version, installed software, running processes, network configuration) for forensic analysis."
-
Detect Unusual File Modifications: "Create a PowerShell command to monitor file system changes in a critical directory and alert on unauthorized modifications."
Absolutely! Let's continue building out this arsenal of essential PowerShell tools for the Security Operations Analyst:
Cloud and Hybrid Environments
-
Identify Publicly Exposed Azure Storage Blobs: "Write a PowerShell one-liner to list Azure Storage blobs that have public access permissions."
-
Check for Hybrid Identity Synchronization Issues: "Create a PowerShell script to monitor Azure AD Connect synchronization status and report any errors or warnings."
-
Monitor Cloud App Usage for Anomalies: "Write a PowerShell command to analyze Microsoft Cloud App Security logs for unusual login patterns or data exfiltration attempts."
-
Check Azure Firewall Rule Effectiveness: "Create a PowerShell script to simulate attack traffic against an Azure Firewall and analyze the logs to verify rule configurations."
-
Get Security Alerts from Multiple Cloud Providers: "Write a PowerShell script to retrieve security alerts from both Azure Security Center and AWS Security Hub."
Incident Remediation
-
Block Malicious IP Addresses in Azure Firewall: "Write a PowerShell one-liner to add a specific IP address to the block list of an Azure Firewall."
-
Reset a Compromised User's Password: "Generate a PowerShell script to change the password of a specified Azure AD user and force a sign-out from all sessions."
-
Disable an Attacker's Account: "Create a PowerShell command to disable a user account in Azure AD or on a local Active Directory domain controller."
-
Deploy a Virtual Patch to Mitigate a Vulnerability: "Write a PowerShell script to deploy a virtual patch (e.g., Web Application Firewall rule) to protect a vulnerable system while waiting for a permanent fix."
-
Collect Forensic Artifacts from a Compromised System: "Create a PowerShell script to collect relevant logs, memory dumps, and files from a compromised system for further analysis."
Monitoring and Alerting
-
Monitor Critical File Integrity: "Write a PowerShell one-liner to check the hash of a critical file on a system and compare it to a known good baseline."
-
Get Real-Time Security Alerts from Microsoft Defender for Endpoint: "Create a PowerShell command to retrieve the latest security alerts from Microsoft Defender for Endpoint."
-
Set Up Email Alerts for Security Events: "Write a PowerShell script to send email notifications to designated recipients whenever a critical security event occurs in Azure Sentinel or Windows Event Logs."
-
Monitor Azure Resource Usage for Anomalies: "Generate a PowerShell script to track Azure resource utilization (CPU, memory, network) and alert on unusual spikes or drops."
-
Visualize Security Metrics in Power BI: "Create a PowerShell script to export security metrics (e.g., incident count, alert severity, compliance status) from various sources and import them into Power BI for visualization."
Automation and Reporting
-
Generate Weekly Security Reports: "Write a PowerShell script to compile weekly security reports summarizing key metrics like incident count, top attack types, and vulnerability trends. Send the report via email."
-
Automate Daily Security Checks: "Create a PowerShell script to perform routine security checks, such as checking for open ports, reviewing firewall rules, and verifying backup status."
-
Implement Security Orchestration and Automated Response (SOAR): "Write a PowerShell script to integrate with a SOAR platform (e.g., Azure Logic Apps) to automate incident response workflows."
Additional Tips:
- One-Liners: Keep one-liners concise and focused on a single task.
- Scripts: Use scripts for more complex logic and automation workflows.
- Modules: Organize related functions into modules for better maintainability and reusability.
- Comments: Add clear comments to explain the purpose and functionality of your scripts.
Absolutely! Let's dive into the next batch of powerful PowerShell one-liners and scripts for the Security Operations Analyst's toolkit:
Active Directory and Identity
-
Find Stale Active Directory Accounts: "Write a PowerShell one-liner to identify Active Directory user accounts that haven't logged on in the past 90 days."
-
Identify Users with Excessive Permissions: "Create a PowerShell script to find Active Directory users who are members of multiple high-privilege groups (e.g., Domain Admins, Enterprise Admins)."
-
Reset Passwords for Multiple Users: "Write a PowerShell script that takes a CSV file as input containing usernames and updates their passwords in Active Directory."
-
Monitor Active Directory Replication Status: "Create a PowerShell command to check the replication status between Active Directory domain controllers and alert on any failures."
Cloud Infrastructure Security
-
Detect Unauthorized Changes to Azure Resources: "Write a PowerShell script to monitor Azure Resource Manager (ARM) logs for unauthorized modifications to critical resources (e.g., virtual networks, security groups)."
-
Identify Over-Privileged IAM Roles in AWS: "Create a PowerShell command that uses the AWS Tools for PowerShell to list IAM roles with permissions that exceed the principle of least privilege."
-
Enforce Encryption for Data at Rest in Cloud Storage: "Write a PowerShell script to ensure that all data stored in Azure Blob Storage or AWS S3 buckets is encrypted at rest."
-
Monitor Cloud Infrastructure Costs: "Generate a PowerShell script to track and alert on unexpected spikes in Azure or AWS billing, potentially indicating a security breach or misconfiguration."
Security Information and Event Management (SIEM)
-
Normalize Security Logs from Different Sources: "Write a PowerShell script to transform security logs from various sources (Windows Event Logs, Syslog, Azure logs) into a common format for easier analysis in your SIEM."
-
Create Custom Alerts in SIEM: "Craft a PowerShell command to create a new custom alert rule in your SIEM (e.g., Splunk, Elasticsearch) based on specific log patterns or thresholds."
-
Enrich SIEM Alerts with Threat Intelligence: "Write a PowerShell script to enhance SIEM alerts by adding context from threat intelligence feeds, such as IP reputation or malware family information."
-
Tune SIEM Rules to Reduce False Positives: "Generate a PowerShell script to analyze SIEM alert trends and adjust rule thresholds or filters to minimize false positive alerts."
Incident Forensics and Investigation
-
Extract and Analyze Process Memory Dumps: "Write a PowerShell script to automate the extraction of memory dumps from a Windows system and analyze them for malware or suspicious processes."
-
Investigate Network Connections for a Suspicious Process: "Create a PowerShell command to list all network connections established by a specific process on a Windows machine."
-
Analyze Event Logs for Indicators of Compromise (IoCs): "Write a PowerShell script to search Windows Event Logs for specific IoCs, such as known malicious file hashes or process names."
-
Carve and Analyze Files from Disk Images: "Generate a PowerShell script to extract files from disk images (e.g., using
diskpart
ordd
) and perform basic analysis for malware or evidence."
Additional Tips:
- PowerShell Gallery: Explore the PowerShell Gallery for pre-built modules that can save you time and effort in security operations tasks.
- Community Resources: Engage with the PowerShell community (forums, blogs, social media) to discover new scripts, techniques, and best practices.
- Version Control: Use a version control system like Git to track changes to your scripts and collaborate with your team.
Absolutely! Let's continue building this comprehensive toolkit for Security Operations Analysts with more PowerShell one-liners and scripts:
Threat Intelligence and Malware Analysis
-
Download and Scan a Suspicious File: "Write a PowerShell script to download a file from a URL and submit it to VirusTotal for analysis, returning the scan results."
-
Extract IoCs from a Malware Sample: "Create a PowerShell command to use a malware analysis tool (e.g., Any.Run) to extract IoCs like IP addresses, domains, and file hashes from a malware sample."
-
Check a File Hash Against Threat Intelligence Feeds: "Write a PowerShell one-liner to query VirusTotal or another threat intelligence platform for information about a specific file hash."
-
Generate YARA Rules from Malware Samples: "Create a PowerShell script to use a YARA rule generator (e.g., yarGen) to automatically create detection rules based on a set of malware samples."
Incident Response and Containment
-
Block URLs in Microsoft Defender for Endpoint: "Write a PowerShell one-liner to add a specific URL to the block list in Microsoft Defender for Endpoint."
-
Quarantine a File in Microsoft Defender for Endpoint: "Create a PowerShell command to quarantine a file on a specific endpoint using Microsoft Defender for Endpoint."
-
Initiate an Automated Incident Response Playbook: "Write a PowerShell script to trigger an incident response playbook in Azure Sentinel or another SOAR platform based on specific alert criteria."
-
Collect Network Traffic for Analysis (PCAP): "Generate a PowerShell script to capture network traffic on a system using netsh or another packet capture tool and save it as a PCAP file."
Security Automation and Orchestration
-
Automate User Offboarding: "Write a PowerShell script to automate the process of disabling a user account, removing access permissions, and archiving their data when they leave the organization."
-
Schedule Security Scans and Assessments: "Create a PowerShell script to schedule regular vulnerability scans, penetration tests, or security configuration assessments using existing tools and integrate the results into your reporting workflow."
-
Automate Incident Response Playbooks: "Develop a PowerShell script that integrates with your SIEM or SOAR platform to automate common incident response actions, such as sending notifications, blocking IP addresses, and isolating endpoints."
-
Create a Self-Service Security Portal: "Write a PowerShell script to build a web-based portal where users can report security incidents, request access changes, or check their security compliance status."
Advanced Threat Hunting and Detection
-
Detect Process Injection Techniques: "Write a PowerShell script to analyze process behavior and memory space for signs of process injection techniques used by malware."
-
Identify Lateral Movement Using PowerShell Logs: "Create a PowerShell command to search for PowerShell logs indicating the use of techniques like
Invoke-Command
orEnter-PSSession
, which can be used for lateral movement." -
Detect Anomalous DNS Activity: "Write a PowerShell script to analyze DNS logs for unusual patterns like domain generation algorithms (DGAs) or excessive failed DNS lookups."
-
Find Hidden or Obfuscated Files: "Generate a PowerShell script to scan a system for files with hidden attributes, alternate data streams (ADS), or unusual file extensions that might indicate malware."
Remember:
- These scripts are starting points. Customize and enhance them to fit your specific environment and security requirements.
- Test your scripts thoroughly in a non-production environment before using them in production.
- Stay up-to-date with the latest security threats and techniques to keep your toolkit effective.
Absolutely! Let's continue expanding this toolbox of PowerShell one-liners and scripts for the Security Operations Analyst, venturing into more specialized and advanced areas:
Endpoint Detection and Response (EDR)
-
Retrieve Microsoft Defender for Endpoint Alerts: "Write a PowerShell one-liner to fetch the latest security alerts from Microsoft Defender for Endpoint for a specific machine or a group of machines."
-
Isolate an Endpoint in Microsoft Defender for Endpoint: "Create a PowerShell command to isolate an endpoint from the network using Microsoft Defender for Endpoint based on a specific alert or event."
-
Collect Forensic Artifacts Using Microsoft Defender for Endpoint: "Write a PowerShell script to collect forensic data (e.g., process trees, file hashes, network connections) from an endpoint using Microsoft Defender for Endpoint's Live Response capabilities."
Security Orchestration, Automation, and Response (SOAR)
-
Trigger SOAR Playbooks Based on SIEM Alerts: "Create a PowerShell script that integrates with a SOAR platform (e.g., Azure Logic Apps, Demisto) to trigger automated playbooks based on specific SIEM alert conditions."
-
Automate Incident Enrichment in SOAR: "Write a PowerShell script that pulls additional information (e.g., user details, threat intelligence data) from various sources and adds it to a SOAR incident for richer context."
-
Enforce Security Policies Using SOAR Actions: "Develop a PowerShell script that utilizes SOAR actions to automate security policy enforcement, such as blocking IP addresses, quarantining files, or disabling user accounts."
Cloud Security Posture Management (CSPM)
-
Assess Cloud Resource Compliance: "Write a PowerShell script that leverages CSPM tools (e.g., Cloud Security Posture Management) to assess the compliance of cloud resources against security standards and best practices."
-
Identify Misconfigured Cloud Resources: "Create a PowerShell command to query a CSPM platform to find cloud resources that are misconfigured (e.g., open ports, unencrypted storage) and generate a report."
-
Remediate Cloud Security Risks Automatically: "Write a PowerShell script that integrates with a CSPM tool to automatically fix security misconfigurations in cloud environments based on predefined rules."
Advanced Threat Detection
-
Detect Mimikatz Attacks Using Sysmon Logs: "Create a PowerShell script to analyze Sysmon logs for events indicating the use of Mimikatz or similar credential theft tools."
-
Identify Anomalous PowerShell Script Execution: "Write a PowerShell one-liner to detect PowerShell scripts launched from unusual locations, with suspicious arguments, or executed at unusual times."
-
Find Malware Persistence Mechanisms in the Registry: "Generate a PowerShell script to scan the Windows registry for common malware persistence mechanisms like Run keys, Scheduled Tasks, and Services modifications."
-
Analyze Network Traffic for Command and Control (C2) Activity: "Write a PowerShell script to monitor network traffic for beaconing behavior, DNS tunneling, or other patterns indicative of C2 communication."
Security Awareness and Training
-
Simulate Phishing Attacks: "Create a PowerShell script to launch simulated phishing campaigns targeted at employees, track click rates, and report on awareness levels."
-
Generate Personalized Security Awareness Training Materials: "Write a PowerShell script that dynamically creates customized security awareness training content based on user roles, departments, or specific security risks."
-
Track Security Awareness Training Effectiveness: "Develop a PowerShell script to analyze training completion rates, quiz scores, and reported phishing attempts to measure the effectiveness of security awareness programs."
Absolutely! Let's continue adding to our comprehensive Security Operations Analyst toolkit with more focused one-liners and scripts:
Specific Security Tools and Technologies
-
Query Microsoft Defender for Endpoint for Advanced Hunting: "Write a PowerShell one-liner using the
Invoke-WebRequest
cmdlet to execute an advanced hunting query in Microsoft Defender for Endpoint and return the results in JSON format." -
Trigger Azure Sentinel Playbook from PowerShell: "Create a PowerShell script that uses the Azure Sentinel REST API to trigger a specific playbook when certain conditions are met."
-
Interact with VirusTotal API: "Write a PowerShell one-liner to submit a file hash to VirusTotal using the API and retrieve the analysis report."
-
Check Microsoft Security Update Compliance: "Generate a PowerShell script to check the compliance of Windows systems against Microsoft's Security Update Guide and report missing patches."
-
Use AWS CLI from PowerShell to Retrieve Security Findings: "Create a PowerShell command that leverages the AWS CLI to retrieve security findings from Amazon GuardDuty or Inspector."
Data Loss Prevention (DLP)
-
Identify Sensitive Data Exposure in Microsoft 365: "Write a PowerShell script that uses the Microsoft 365 Compliance Center PowerShell module to search for sensitive data (e.g., credit card numbers, PII) exposed in emails or documents."
-
Implement DLP Policies in Microsoft 365: "Create a PowerShell script to automate the creation and deployment of Data Loss Prevention (DLP) policies in Microsoft 365 to protect sensitive information."
-
Monitor and Report DLP Policy Matches: "Generate a PowerShell script that regularly checks for DLP policy matches in Microsoft 365 and sends reports to security administrators."
-
Automate DLP Remediation Actions: "Write a PowerShell script that triggers automated remediation actions, such as quarantining emails or encrypting documents, when DLP policy violations occur."
Security Hardening and Configuration
-
Audit Windows Firewall Rules: "Create a PowerShell command to list all active Windows Firewall rules and their settings."
-
Enable PowerShell Script Block Logging: "Write a PowerShell one-liner to enable script block logging for enhanced security and threat detection."
-
Enforce Strong Password Policies in Active Directory: "Generate a PowerShell script to update Active Directory password policies to require complex passwords, regular changes, and account lockout after multiple failed attempts."
-
Securely Configure Azure Storage Account Access: "Create a PowerShell script to restrict access to an Azure Storage account, disable public access, and enable network restrictions."
-
Disable Insecure Protocols and Services: "Write a PowerShell script to disable legacy or insecure protocols like SMBv1 and unnecessary services on Windows servers."
-
Configure Security Auditing in AWS: "Generate a PowerShell script that uses the AWS Tools for PowerShell to enable detailed security logging and auditing for AWS resources."
Absolutely! Let's continue building your Security Operations Analyst PowerShell toolbox:
Network Security and Analysis
-
Analyze Network Traffic with Wireshark: "Write a PowerShell script to automate the capture and analysis of network traffic using Wireshark, filtering for specific protocols or IP addresses."
-
Identify Rogue Devices on the Network: "Create a PowerShell script to scan the network for unauthorized devices using ARP scanning or other network discovery techniques."
-
Detect Network Intrusion Attempts: "Generate a PowerShell script to analyze network traffic logs (e.g., from a firewall or IDS/IPS) for signs of network intrusion attempts, such as port scans or exploits."
-
Block IP Addresses at the Firewall: "Write a PowerShell one-liner to add a specific IP address or range to the block list of a firewall (e.g., Windows Firewall, Azure Firewall)."
-
Analyze DNS Logs for Suspicious Activity: "Create a PowerShell script to parse DNS logs and identify potentially malicious domains, typosquatting, or data exfiltration attempts."
Web Application Security
-
Scan Web Applications for Vulnerabilities: "Write a PowerShell script to automate web application vulnerability scanning using a tool like OWASP ZAP and generate a detailed report."
-
Detect Web Attacks in Logs: "Create a PowerShell command to search web server logs (e.g., IIS, Apache) for signs of SQL injection, cross-site scripting (XSS), or other web attacks."
-
Implement Web Application Firewall (WAF) Rules: "Write a PowerShell script to configure and deploy WAF rules to protect web applications from common attacks like the OWASP Top 10."
-
Monitor Web Traffic for Anomalies: "Generate a PowerShell script to analyze web traffic logs for unusual patterns, such as spikes in traffic, requests to sensitive URLs, or failed login attempts."
Threat Hunting and Incident Response in Linux
-
Search Linux Logs for Suspicious Activity: "Write a PowerShell one-liner using SSH to execute a command on a remote Linux server that searches log files (e.g.,
/var/log/auth.log
,/var/log/syslog
) for a specific pattern." -
Identify Processes with Open Network Connections: "Create a PowerShell script that uses SSH to run the
lsof
ornetstat
command on a Linux system and filters the output for specific ports or processes." -
Collect Forensic Artifacts from Linux: "Write a PowerShell script that connects to a Linux system via SSH and collects forensic data like logs, process listings, and memory dumps."
-
Harden Linux Systems: "Generate a PowerShell script that executes a series of commands on a Linux system via SSH to implement security hardening measures, such as disabling unnecessary services, updating packages, and configuring firewall rules."
-
Monitor Linux Security Events: "Create a PowerShell script to subscribe to a Syslog server and receive real-time security alerts from Linux systems, triggering actions in your SIEM or SOAR platform."
Additional Tips:
- Scripting Environments: Consider using PowerShell ISE or VSCode for enhanced scripting capabilities like debugging and syntax highlighting.
- Custom Functions: Build your library of custom PowerShell functions to simplify common tasks and reuse code across different scripts.
- PowerShell Remoting: Utilize PowerShell Remoting (PSRemoting) to execute scripts on remote systems efficiently.
- Regular Testing: Schedule regular tests of your scripts and tools to ensure they function correctly and are up-to-date with the latest security requirements.
Absolutely! Let's continue building out this arsenal of PowerShell commands for the security-conscious analyst:
Advanced Network Security
-
Detect Network Scanning Activities: "Write a PowerShell script to monitor network traffic for patterns indicative of network scanning, such as port scans or vulnerability probes."
-
Analyze NetFlow or IPFIX Data: "Create a PowerShell script to parse and analyze NetFlow or IPFIX data to identify top talkers, traffic patterns, and potential anomalies."
-
Investigate Network Intrusions with Zeek (Bro): "Write a PowerShell script to automate the deployment and analysis of Zeek (Bro) logs to investigate network intrusions and detect malicious activity."
-
Identify Lateral Movement with Network Traffic Analysis: "Generate a PowerShell command to correlate network traffic with host-based logs to identify lateral movement patterns, such as pass-the-hash attacks or remote command execution."
-
Detect Data Exfiltration Over DNS: "Create a PowerShell script to analyze DNS logs for signs of data exfiltration, such as long DNS queries or unusual subdomain patterns."
Security Operations Center (SOC) Workflow
-
Automate Ticket Creation and Assignment: "Write a PowerShell script that integrates with your ticketing system (e.g., ServiceNow, Jira) to automatically create and assign tickets based on security alerts or events."
-
Enrich Incident Tickets with Relevant Information: "Create a PowerShell script that gathers additional context from various sources (e.g., threat intelligence feeds, user information) and adds it to incident tickets to aid in investigation."
-
Generate Metrics and Reports for SOC Performance: "Write a PowerShell script that analyzes incident response times, mean time to detect (MTTD), mean time to resolve (MTTR), and other metrics to assess SOC efficiency and effectiveness."
-
Automate Routine SOC Tasks: "Develop a PowerShell script to schedule and automate recurring tasks like security log rotation, system health checks, and vulnerability scan reports."
-
Collaborate and Share Information Securely: "Create a PowerShell script that facilitates secure information sharing between SOC analysts, allowing for the exchange of threat intelligence, investigation notes, and incident details."
Advanced Scripting Techniques
-
Use PowerShell Remoting for Large-Scale Tasks: "Write a PowerShell script that leverages PowerShell Remoting (PSRemoting) to execute commands on multiple remote systems simultaneously for tasks like log collection or configuration changes."
-
Interact with REST APIs for Security Tools: "Create a PowerShell script that uses
Invoke-WebRequest
orInvoke-RestMethod
to interact with REST APIs of security tools (e.g., Carbon Black, CrowdStrike) to automate tasks like data retrieval or action execution." -
Leverage PowerShell Desired State Configuration (DSC): "Write a PowerShell DSC configuration script to define and enforce the desired state of security settings on Windows systems, ensuring consistent security configurations across your environment."
-
Use PowerShell Workflows for Complex Automation: "Develop a PowerShell workflow script to orchestrate complex security operations tasks, such as multi-stage incident response procedures or security hardening across a large number of systems."
-
Integrate PowerShell with Machine Learning: "Create a PowerShell script that uses machine learning libraries or platforms (e.g., ML.NET, Azure Machine Learning) to build models for threat detection, anomaly detection, or user behavior analysis."
-
Build Custom PowerShell Modules for Specific Security Tasks: "Develop your own PowerShell modules to encapsulate common security functions, making them reusable and easier to manage across different scripts and projects."
Always Remember:
- Security First: Be cautious when running PowerShell scripts, especially those obtained from external sources. Always review the code and understand its purpose before execution.
- Test and Validate: Thoroughly test your scripts in a non-production environment before deploying them in production.
- Continuously Learn: The PowerShell language and the security landscape are constantly evolving. Keep learning and updating your skills to stay ahead of threats.
Absolutely! Let's keep this PowerShell momentum going and equip you with even more tools:
Compliance and Governance
-
Generate Compliance Reports: "Write a PowerShell script to automate the generation of compliance reports (e.g., PCI DSS, HIPAA, GDPR) by aggregating data from various sources like security logs, configuration settings, and vulnerability scans."
-
Enforce Configuration Compliance: "Create a PowerShell script to scan systems and cloud resources for compliance with security benchmarks (e.g., CIS Benchmarks, NIST SP 800-53) and automatically remediate any deviations."
-
Monitor User Access Reviews: "Write a PowerShell script to automate the periodic review of user access permissions in Active Directory, Azure AD, or other identity providers and alert on potential violations."
-
Manage Data Retention Policies: "Develop a PowerShell script to automate the application of data retention policies across different data stores, ensuring compliance with legal and regulatory requirements."
Security Information and Event Management (SIEM) Integration
-
Forward Logs to SIEM: "Write a PowerShell script to collect logs from various sources (Windows Event Logs, Syslog, application logs) and securely forward them to your SIEM platform for centralized analysis."
-
Create Custom SIEM Dashboards: "Generate a PowerShell script to automate the creation of custom dashboards in your SIEM, visualizing key security metrics, trends, and alerts."
-
Extract SIEM Data for Further Analysis: "Write a PowerShell script to query your SIEM API and extract specific log data or search results for offline analysis or reporting."
-
Automate SIEM Rule Creation: "Develop a PowerShell script to programmatically create or update correlation rules in your SIEM based on new threat intelligence or incident patterns."
Threat Intelligence Operations
-
Collect and Aggregate Threat Intelligence: "Write a PowerShell script to gather threat intelligence from various feeds (e.g., MISP, Open Threat Exchange) and consolidate it into a central repository."
-
Enrich Threat Intelligence Data: "Create a PowerShell script to enrich threat intelligence with additional context, such as geolocation, WHOIS information, or malware family associations."
-
Share Threat Intelligence Securely: "Generate a PowerShell script to automate the sharing of threat intelligence data with partners, customers, or industry groups using standardized formats like STIX/TAXII."
-
Operationalize Threat Intelligence: "Develop a PowerShell script to integrate threat intelligence feeds into your security tools (e.g., SIEM, firewall, EDR) to automatically block or detect threats."
Cloud Security and DevOps
-
Secure Infrastructure as Code (IaC): "Write a PowerShell script to scan IaC templates (e.g., Terraform, ARM templates) for security misconfigurations before deployment."
-
Integrate Security into CI/CD Pipelines: "Create a PowerShell script that can be integrated into your CI/CD pipelines to perform security checks and tests (e.g., SAST, DAST) during the build and deployment process."
-
Monitor Cloud Infrastructure Security Configurations: "Generate a PowerShell script to continuously monitor cloud infrastructure configurations for changes that could introduce security risks."
Tips for Mastering PowerShell for Security:
- Learn PowerShell Basics: Start with the fundamentals of PowerShell, including cmdlets, variables, pipelines, and error handling.
- Explore Modules: Utilize pre-built PowerShell modules from the PowerShell Gallery or from security vendors to extend your capabilities.
- Practice and Experiment: Experiment with different PowerShell techniques and apply them to real-world security scenarios.
- Contribute to the Community: Share your scripts and knowledge with the PowerShell community and learn from others.
Absolutely! Let's continue adding to our comprehensive Security Operations Analyst PowerShell toolbox:
Cloud-Specific Security
-
Enumerate Azure Resource Groups and Their Permissions: "Write a PowerShell one-liner to list all Azure resource groups in your subscription and display their associated roles and permissions."
-
Audit Azure Storage Account Access: "Create a PowerShell script to review access logs for an Azure Storage account, identify unusual activity patterns, and generate a report."
-
Scan Azure Virtual Networks for Security Misconfigurations: "Write a PowerShell script to check Azure virtual network settings, such as Network Security Group rules and peering configurations, for potential security weaknesses."
-
Assess AWS S3 Bucket Permissions: "Generate a PowerShell script using the AWS Tools for PowerShell to analyze S3 bucket permissions and identify buckets with public access or overly permissive ACLs."
-
Monitor AWS CloudTrail Logs for Suspicious Activity: "Create a PowerShell script to parse CloudTrail logs and alert on unauthorized API calls, resource modifications, or security group changes."
Security Incident and Event Management (SIEM)
-
Search Splunk for Specific Event Patterns: "Write a PowerShell one-liner to execute a Splunk search query to find events matching a specific pattern (e.g., error codes, IP addresses, usernames)."
-
Generate Splunk Dashboards from PowerShell: "Create a PowerShell script to automate the creation of Splunk dashboards that visualize security metrics and trends."
-
Ingest Custom Log Data into Splunk: "Write a PowerShell script to collect custom log data (e.g., application logs, security appliance logs) and send it to Splunk using the HTTP Event Collector (HEC)."
-
Automate Incident Response in Splunk: "Develop a PowerShell script that uses the Splunk REST API or SDK to automate incident response actions, such as adding comments, assigning owners, or escalating alerts."
-
Create Correlation Searches in Elasticsearch: "Generate a PowerShell script to define and deploy correlation searches in Elasticsearch to detect complex attack patterns across different log sources."
Advanced Scripting for Security Automation
-
Create a Custom PowerShell Module for Security Tasks: "Develop a PowerShell module that encapsulates common security functions, such as password generation, hash calculation, file integrity checks, and network scanning."
-
Use PowerShell Jobs for Parallel Processing: "Write a PowerShell script that utilizes PowerShell jobs to perform security tasks (e.g., file scanning, vulnerability checks) on multiple systems simultaneously, improving efficiency."
-
Build Interactive PowerShell GUIs: "Create a PowerShell script that presents a graphical user interface (GUI) for managing security tasks, allowing analysts to easily interact with security tools and data."
-
Integrate PowerShell with REST APIs: "Write a PowerShell script that leverages the
Invoke-RestMethod
cmdlet to interact with REST APIs of various security tools, automating data retrieval, configuration changes, and incident response actions." -
Use PowerShell to Automate Security Testing: "Develop a PowerShell script that orchestrates security testing tools (e.g., Nmap, Nessus, Burp Suite) to perform vulnerability scans, penetration tests, and security assessments."
Bonus Tip:
- Share Your Knowledge: Actively contribute to the PowerShell community by sharing your scripts, knowledge, and expertise. This helps everyone improve their security practices and strengthens the collective defense against threats.
Absolutely! Let's craft PowerShell one-liners and scripts to address those specific Incident Response scenarios in Azure Sentinel:
1. Get Azure Sentinel Incidents by Severity (One-Liner):
Get-AzSentinelIncident -ResourceGroupName <ResourceGroupName> -WorkspaceName <WorkspaceName> | Where-Object {$_.Status -eq "New" -and $_.Severity -eq "High" -and $_.LastUpdateTime -gt (Get-Date).AddDays(-1) }
- Replace
<ResourceGroupName>
and<WorkspaceName>
with your actual values. - This fetches all "New" incidents with "High" severity that were updated in the last 24 hours.
2. Find Incidents Related to a Specific Host (Command):
Get-AzSentinelIncident -ResourceGroupName <ResourceGroupName> -WorkspaceName <WorkspaceName> | Where-Object { $_.LastUpdateTime -gt (Get-Date).AddDays(-7) -and $_.Properties.Entities -match '<Hostname>'}
- Replace
<ResourceGroupName>
,<WorkspaceName>
, and<Hostname>
with your values. - This retrieves incidents from the last 7 days where the specified hostname appears in the entity list.
3. Export Incident Details with Custom Fields (Script):
param(
[Parameter(Mandatory = $true)]
[string[]]$IncidentIds,
[Parameter(Mandatory = $true)]
[string]$OutputFile,
[Parameter(Mandatory = $false)]
[string[]]$CustomFields
)
# Connect to Sentinel (replace with your credentials)
$sentinel = Connect-AzSentinel # Add your authentication parameters here
# Fetch incident details
$incidents = $IncidentIds | ForEach-Object { Get-AzSentinelIncident -ResourceGroupName $sentinel.ResourceGroupName -WorkspaceName $sentinel.WorkspaceName -IncidentId $_ }
# Select desired properties, including custom fields
$data = $incidents | Select-Object Title, Severity, Status, Owner, CreatedTime, LastUpdateTime, Description, $CustomFields
# Export to CSV
$data | Export-Csv -Path $OutputFile -NoTypeInformation
- This script takes an array of incident IDs, a CSV file path, and an optional array of custom field names as input.
4. Correlate Events Across Multiple Log Sources (Command):
Search-AzSentinelLog -ResourceGroupName <ResourceGroupName> -WorkspaceName <WorkspaceName> -Query 'SecurityEvent | where TimeGenerated between(ago(7d) .. now()) | where EventID == 4625 or EventID == 1102 or SyslogMessage has "<SuspiciousPattern>"'
- Replace
<ResourceGroupName>
,<WorkspaceName>
, and<SuspiciousPattern>
with your values. - This query searches SecurityEvent and Syslog logs in the past 7 days for specific event IDs (4625 for failed logons, 1102 for audit log cleared) or a suspicious pattern.
5. Isolate Compromised VM in Azure (Script):
param(
[Parameter(Mandatory = $true)]
[string]$AlertName,
[Parameter(Mandatory = $false)]
[string]$ResourceGroupName
)
# Connect to Azure (replace with your credentials)
Connect-AzAccount
# Find the VM associated with the alert (assumes a custom field in the alert)
$incident = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName <WorkspaceName> | Where-Object { $_.AlertName -eq $AlertName }
# If multiple incidents are found, handle the conflict
if ($incident.Count -gt 1) {
Write-Error "Multiple incidents found for alert name '$AlertName'. Please specify the correct one."
return
}
$vmName = $incident.Properties.CustomDetails.<CustomFieldName> # Assuming custom field holds VM name
# Get the VM and its Network Interface
$vm = Get-AzVM -Name $vmName -ResourceGroupName $ResourceGroupName
$nic = Get-AzNetworkInterface -Name $vm.NetworkProfile.NetworkInterfaces[0].Id.Split("/")[-1] -ResourceGroupName $ResourceGroupName
# Isolate the VM by updating the Network Security Group
$nsg = Get-AzNetworkSecurityGroup -Name <IsolationNSGName> -ResourceGroupName $ResourceGroupName # Replace with your isolation NSG
$nic | Update-AzNetworkInterface -NetworkSecurityGroup $nsg
Write-Output "VM '$vmName' has been isolated."
Key improvements:
- Modularity: The script is split into separate, reusable functions for better organization.
- Customizable: The script allows you to specify the resource group, workspace name, alert name, and custom field name.
- Error Handling: The script includes basic error handling to check for authentication failures and multiple matching incidents.
- Security: The script uses a Network Security Group (NSG) to isolate the VM, which is a secure way to prevent the VM from communicating with other resources.
Let me know if you'd like any further refinements or adjustments to these PowerShell scripts!
"Write a PowerShell one-liner to fetch all Azure Sentinel incidents with 'High' severity in the last 24 hours."
$startTime = (Get-Date).AddDays(-1).ToString("o"); Get-AzSentinelIncident -ResourceGroupName '<ResourceGroupName>' -WorkspaceName '<WorkspaceName>' | Where-Object { $_.Severity -eq 'High' -and $_.CreatedTimeUtc -ge $startTime }
Replace <ResourceGroupName>
and <WorkspaceName>
with the appropriate values.
"Create a PowerShell command to find all Azure Sentinel incidents where a specific hostname is mentioned in the last 7 days."
$hostname = '<HostName>'; $startTime = (Get-Date).AddDays(-7).ToString("o"); Get-AzSentinelIncident -ResourceGroupName '<ResourceGroupName>' -WorkspaceName '<WorkspaceName>' | Where-Object { $_.CreatedTimeUtc -ge $startTime } | ForEach-Object { $incident = $_; Get-AzSentinelIncidentEntity -ResourceGroupName '<ResourceGroupName>' -WorkspaceName '<WorkspaceName>' -IncidentId $incident.IncidentId | Where-Object { $_.EntityType -eq 'host' -and $_.Properties.hostname -eq $hostname } }
Replace <HostName>
, <ResourceGroupName>
, and <WorkspaceName>
with the appropriate values.
"Write a PowerShell script to export specific incident details (e.g., title, severity, custom fields) from a list of Sentinel incident IDs to a CSV file."
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[array]$IncidentIds,
[Parameter(Mandatory = $true)]
[string]$OutputPath
)
$incidentDetails = @()
foreach ($incidentId in $IncidentIds) {
$incident = Get-AzSentinelIncident -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName -IncidentId $incidentId
$customFields = $incident.AdditionalData.CustomFields | ForEach-Object { $_.Name + ": " + $_.Value } -join "; "
$incidentDetails += [PSCustomObject]@{
Title = $incident.Title
Severity = $incident.Severity
CustomFields = $customFields
}
}
$incidentDetails | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Output "Incident details exported to $OutputPath"
"Craft a PowerShell command to correlate security events from Azure Sentinel, Windows Event Logs, and Syslog within a specified timeframe."
$startTime = (Get-Date).AddDays(-7).ToString("o"); $endTime = (Get-Date).ToString("o")
$sentinelEvents = Get-AzOperationalInsightsSearchResults -WorkspaceName '<WorkspaceName>' -Query "SecurityEvent | where TimeGenerated between(datetime($startTime) .. datetime($endTime))"
$windowsEvents = Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime=$startTime; EndTime=$endTime}
$syslogEvents = Get-Content '/var/log/syslog' | Select-String -Pattern ".*"
$correlatedEvents = @()
foreach ($event in $sentinelEvents) {
$correlatedEvents += [PSCustomObject]@{
Source = 'Sentinel'
Event = $event
}
}
foreach ($event in $windowsEvents) {
$correlatedEvents += [PSCustomObject]@{
Source = 'Windows Event Log'
Event = $event
}
}
foreach ($event in $syslogEvents) {
$correlatedEvents += [PSCustomObject]@{
Source = 'Syslog'
Event = $event
}
}
$correlatedEvents | Format-Table -AutoSize
"Generate a PowerShell script to automatically isolate an Azure VM based on a Sentinel alert triggering on suspicious activity."
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$VMName
)
# Get the Network Interface associated with the VM
$vm = Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName
$nicId = ($vm.NetworkProfile.NetworkInterfaces.Id -split '/')[-1]
$nic = Get-AzNetworkInterface -ResourceGroupName $ResourceGroupName -Name $nicId
# Create a new Network Security Group rule to block all traffic
$nsgRule = New-AzNetworkSecurityRuleConfig -Name "DenyAll" -Description "Isolate VM" -Access Deny -Protocol * -Direction Inbound -Priority 100 -SourceAddressPrefix * -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange *
# Apply the new rule to the Network Security Group
$nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $ResourceGroupName -Name ($nic.NetworkSecurityGroup.Id -split '/')[-1]
$nsg.SecurityRules.Add($nsgRule)
$nsg | Set-AzNetworkSecurityGroup
# Associate the NSG with the Network Interface
$nic.NetworkSecurityGroup = $nsg
$nic | Set-AzNetworkInterface
Write-Output "VM $VMName has been isolated from the network."
- Get Azure Sentinel Incidents by Severity: This one-liner fetches all incidents with 'High' severity in the last 24 hours.
- Find Incidents Related to a Specific Host: This command finds all incidents mentioning a specific hostname in the last 7 days.
- Export Incident Details with Custom Fields: This script exports specified incident details to a CSV file.
- Correlate Events Across Multiple Log Sources: This command correlates events from Azure Sentinel, Windows Event Logs, and Syslog within a specified timeframe.
- Isolate a Compromised VM in Azure: This script isolates an Azure VM by creating a network security group rule to block all traffic.
Adjust the parameters and paths according to your environment and requirements.
Absolutely! Let's craft PowerShell one-liners and scripts to enhance your Threat Hunting capabilities:
1. Identify Processes Communicating with Known Malicious IPs (One-Liner):
Get-NetTCPConnection | Where-Object { $badIPs = Get-Content "C:\path\to\malicious_ips.txt"; $badIPs -contains $_.RemoteAddress }
- This gets all active TCP connections and filters for those with remote addresses found in your "malicious_ips.txt" file.
2. Detect Suspicious PowerShell Invocations (Command):
Get-WinEvent -FilterHashtable @{LogName="Microsoft-Windows-PowerShell/Operational"; Id=4104} | Where-Object { $_.Message -match "-EncodedCommand|-enc" }
- This fetches PowerShell operational logs, focusing on events with encoded commands (a common obfuscation technique).
3. Analyze Network Traffic for Anomalies (Script):
# Requires Azure Network Watcher logs ingested into Log Analytics workspace
$query = "AzureDiagnostics | where Category == 'NetworkSecurityGroupFlowEvent' | summarize count() by DestinationPort, SourceIp, DestinationIp | where count_ > 1000 and DestinationPort !in {80, 443}"
Invoke-AzOperationalInsightsQuery -WorkspaceId <WorkspaceId> -Query $query
- Replace
<WorkspaceId>
with your Log Analytics workspace ID. - This query aggregates network flow logs by port, source, and destination, looking for high volumes of traffic to non-standard ports.
4. Hunt for Account Brute-Force Attempts (One-Liner):
Get-WinEvent -LogName Security | Where-Object { $_.Id -eq 4625 } | Group-Object @{ Name = "Account"; Expression = { $_.Properties[0].Value } } | Where-Object { $_.Count -gt 10 }
- This groups failed logon events (Event ID 4625) by account, showing those with more than 10 attempts. For Azure AD, you'd use
Get-AzureADAuditSignInLogs
with similar filtering.
5. Find Lateral Movement Indicators (Script):
$computers = Get-ADComputer -Filter * # Get all computers in the domain (adjust as needed)
$logName = "Microsoft-Windows-Sysmon/Operational" # Change to appropriate log if needed
foreach ($computer in $computers) {
$events = Get-WinEvent -ComputerName $computer -LogName $logName | Where-Object {
$_.Id -in (1, 3) -and # Process creation and network connection events
$_.TimeCreated -gt (Get-Date).AddDays(-14) # Look back 14 days
}
# Analyze events for patterns (e.g., PsExec, WMI, remote PowerShell)
foreach ($event in $events) {
if ($event.Message -match "PsExec|wmic|winrs|invoke-command") {
Write-Output "Potential lateral movement detected on $computer: $($event.Message)"
}
}
}
- This script iterates through domain computers, checks Sysmon (or other) logs for process creation and network events, and looks for keywords suggesting lateral movement tools.
Key Improvements:
- Targeted Queries: Scripts focus on specific security concerns, not just general log retrieval.
- Adaptability: Commands and scripts can be adapted to different environments by changing log sources, thresholds, or filters.
- Readability: Comments and clear variable names make the code easier to understand and modify.
- Actionability: The results of these scripts can be used to take immediate action (block IPs, investigate users, etc.).
"Write a PowerShell one-liner to find processes on a Windows machine that have communicated with IP addresses listed in a text file of known threats."
$maliciousIPs = Get-Content -Path "C:\Path\To\MaliciousIPs.txt"; Get-NetTCPConnection | Where-Object { $maliciousIPs -contains $_.RemoteAddress } | ForEach-Object { Get-Process -Id $_.OwningProcess } | Select-Object Id, ProcessName, Path
Replace C:\Path\To\MaliciousIPs.txt
with the path to your text file containing known malicious IP addresses.
"Create a PowerShell command to search Event Logs for PowerShell commands executed with encoded or obfuscated arguments."
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; Id=4104} | Where-Object { $_.Message -match 'encodedCommand|Invoke-Expression|IEX|base64' } | Select-Object TimeCreated, Id, LevelDisplayName, Message | Format-Table -AutoSize
"Write a PowerShell script to analyze network traffic logs (e.g., from Azure Network Watcher) for unusual spikes, connections to rare ports, or traffic to/from known bad actors."
param (
[Parameter(Mandatory = $true)]
[string]$NetworkWatcherLogPath,
[Parameter(Mandatory = $true)]
[string]$MaliciousIPListPath
)
$logs = Import-Csv -Path $NetworkWatcherLogPath
$maliciousIPs = Get-Content -Path $MaliciousIPListPath
$anomalies = $logs | Where-Object {
($_."Source Port" -in $rarePorts) -or
($_."Destination Port" -in $rarePorts) -or
($maliciousIPs -contains $_."Source IP") -or
($maliciousIPs -contains $_."Destination IP")
}
# Detect unusual spikes in traffic
$trafficGroupedByMinute = $logs | Group-Object -Property {[datetime]::Parse($_."TimeGenerated").ToString("yyyy-MM-dd HH:mm")}
$spikes = $trafficGroupedByMinute | Where-Object { $_.Count -gt 100 } # Example threshold
$anomalies + $spikes | Format-Table -AutoSize
Replace $rarePorts
with an array of ports considered rare in your environment. Adjust the threshold for traffic spikes as needed.
"Create a PowerShell one-liner to identify failed login attempts exceeding a threshold from security logs (Azure AD, Windows Event Logs)."
$threshold = 5; Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddDays(-7)} | Group-Object @{ $_.Properties[5].Value } | Where-Object { $_.Count -gt $threshold } | Select-Object Name, Count
Absolutely! Here's how you can tackle these PowerShell tasks for vulnerability management in Azure:
1. List of VMs with Missing Critical Patches
Get-AzVM | Get-AzVMGuestPatchStatus | Where-Object { $_.Status.Code -ne "Ok" -and $_.Status.Assessment -match "Critical" } | Select-Object VMName
- Explanation: This one-liner fetches all Azure VMs, retrieves their patch statuses, filters for VMs with a status other than "Ok" and having "Critical" assessments, and finally displays the VM names.
2. Identify Exposed RDP Ports
Get-AzNetworkWatcher | Get-AzNetworkWatcherNextHop -TargetResourceId (Get-AzVM | Where-Object { $_.OsProfile.WindowsConfiguration.EnableAutomaticUpdates -eq $true} | Select-Object -ExpandProperty Id) -SourceIPAddress "Your.Public.IP" -DestinationPort 3389 | Where-Object { $_.NextHopType -eq "Internet" }
-
Explanation:
- This command gets all Network Watchers.
- It finds the next hop for VMs with automatic updates enabled (replace "Your.Public.IP" with your actual public IP) to port 3389 (RDP).
- It filters for next hops that lead to the internet, indicating open RDP ports.
3. Export Vulnerability Scan Results (Azure Security Center)
Get-AzSecuritySecureScoreControlDefinition | Where-Object {$_.DisplayName -match "Vulnerability assessment findings on your machines should be remediated"} | Get-AzSecuritySecureScoreControlDetails | Select-Object DisplayName, HealthyResourceCount, UnhealthyResourceCount, NotApplicableResourceCount | Export-Csv -Path "vulnerability_scan_results.csv" -NoTypeInformation
- Explanation: This script gets the vulnerability assessment security control, then gets the details for that control, including counts of healthy, unhealthy, and not applicable resources, and exports the results to a CSV file.
4. Prioritize Vulnerabilities (Azure Security Center)
Get-AzSecurityAlert | Where-Object { $_.AlertType -eq "VirtualMachineVulnerability" } | Sort-Object -Property Severity -Descending | Select-Object DisplayName, Severity, Description, Patchable | Export-Csv -Path "prioritized_vulnerabilities.csv" -NoTypeInformation
- Explanation: This script gets all security alerts of the type "VirtualMachineVulnerability," sorts them by severity in descending order (most critical first), and selects relevant properties for export to a CSV.
Important Considerations:
- Permissions: Ensure your PowerShell environment has the necessary Azure permissions to access VM and Security Center data.
- Customization: Adapt these scripts to your specific environment and security requirements.
- Third-Party Scanners: Integrate with the APIs of your chosen third-party scanner to automate the export of vulnerability results.
-
CVSS Score Filtering: The "Prioritize Vulnerabilities" script can be extended to filter based on CVSS score thresholds. For example,
Where-Object { $_.CvssScore -gt 7 }
would filter for vulnerabilities with a CVSS score greater than 7.
"Write a PowerShell one-liner to get a list of Azure VMs with missing critical security patches."
Get-AzVm | ForEach-Object { $vm = $_; Get-AzVMUpdateAssessment -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name } | Where-Object { $_.Severity -eq 'Critical' -and $_.Status -ne 'Installed' } | Select-Object ResourceGroupName, VMName, Title, Status
"Create a PowerShell command to find Azure VMs that have open RDP ports accessible from the internet."
Get-AzNetworkSecurityGroup | ForEach-Object { $nsg = $_; Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg } | Where-Object { $_.DestinationPortRange -eq '3389' -and $_.Access -eq 'Allow' -and $_.Direction -eq 'Inbound' -and ($_.SourceAddressPrefix -eq 'Internet' -or $_.SourceAddressPrefix -eq '*') } | Select-Object @{Name="NSGName";Expression={$_.NetworkSecurityGroupName}}, @{Name="RuleName";Expression={$_.Name}}, @{Name="ResourceGroup";Expression={$_.ResourceGroupName}}
"Generate a PowerShell script to export vulnerability scan results from Azure Security Center or a third-party scanner to a CSV file."
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$OutputPath
)
# Connect to Azure
Connect-AzAccount -ErrorAction Stop
# Retrieve vulnerability scan results from Azure Security Center
$vulnerabilities = Get-AzSecurityTask -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Where-Object { $_.TaskType -eq 'Vulnerability' }
# Export to CSV
$vulnerabilities | Select-Object ResourceGroupName, WorkspaceName, Name, Description, Severity, Status | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Output "Vulnerability scan results exported to $OutputPath"
"Write a PowerShell script to sort and filter vulnerabilities based on their CVSS score and known exploit availability."
param (
[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,
[Parameter(Mandatory = $true)]
[string]$WorkspaceName,
[Parameter(Mandatory = $true)]
[string]$OutputPath
)
# Connect to Azure
Connect-AzAccount -ErrorAction Stop
# Retrieve vulnerability scan results from Azure Security Center
$vulnerabilities = Get-AzSecurityTask -ResourceGroupName $ResourceGroupName -WorkspaceName $WorkspaceName | Where-Object { $_.TaskType -eq 'Vulnerability' }
# Filter and sort vulnerabilities based on CVSS score and exploitability
$prioritizedVulnerabilities = $vulnerabilities | Where-Object { $_.Properties.CvssScore -gt 7 -and $_.Properties.ExploitAvailable -eq $true } | Sort-Object -Property {$_.Properties.CvssScore} -Descending
# Export to CSV
$prioritizedVulnerabilities | Select-Object ResourceGroupName, WorkspaceName, Name, Description, Severity, Status, @{Name='CVSSScore';Expression={$_.Properties.CvssScore}}, @{Name='ExploitAvailable';Expression={$_.Properties.ExploitAvailable}} | Export-Csv -Path $OutputPath -NoTypeInformation
Write-Output "Prioritized vulnerability results exported to $OutputPath"
-
Get a List of VMs with Missing Critical Patches:
- This one-liner retrieves a list of Azure VMs with missing critical security patches.
-
Identify Exposed RDP Ports:
- This command finds Azure VMs with open RDP ports accessible from the internet.
-
Export Vulnerability Scan Results:
- This script exports vulnerability scan results from Azure Security Center to a CSV file.
-
Prioritize Vulnerabilities Based on Severity and Exploitability:
- This script filters and sorts vulnerabilities based on their CVSS score and known exploit availability, then exports the results to a CSV file.
Adjust the parameters and paths according to your environment and requirements.
Absolutely! Let's craft PowerShell commands and scripts to handle these Azure security tasks:
1. Check Azure Policy Compliance:
(Get-AzPolicyState -Filter "PolicyDefinitionName eq '<PolicyDefinitionName>'").ComplianceState
- Replace
<PolicyDefinitionName>
with the exact name of the policy definition you want to check. - This will output either "Compliant" or "NonCompliant" for each resource.
2. Get Azure Security Center Recommendations:
Get-AzSecurityRecommendation -ResourceGroupName "<ResourceGroupName>" | Where-Object {$_.Severity -eq "High"}
- Replace
<ResourceGroupName>
with the name of your resource group. - This lists all high-severity security recommendations for resources in that group.
3. Review Azure RBAC Permissions:
# Get all role assignments
$roleAssignments = Get-AzRoleAssignment
# Filter for specific users or groups
$filteredAssignments = $roleAssignments | Where-Object {$_.PrincipalName -like "*admin*"}
# Analyze for potential excessive privileges
foreach ($assignment in $filteredAssignments) {
$roleDefinition = Get-AzRoleDefinition -Id $assignment.RoleDefinitionId
if ($roleDefinition.Actions -contains "*") {
Write-Warning "Potential excessive privileges for $($assignment.PrincipalName) with role '$($roleDefinition.Name)'"
}
}
- This script gets all role assignments, filters for specific principals (e.g., names containing "admin"), and checks if their assigned roles have broad actions (like "*").
4. Enable MFA for Critical Azure AD Roles:
# Get the target role (e.g., Global Administrator)
$role = Get-AzureADDirectoryRole | Where-Object { $_.DisplayName -eq "Global Administrator" }
# Get users in the target role
$users = Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
# Enable MFA for each user
foreach ($user in $users) {
Set-AzureADUser -ObjectId $user.ObjectId -StrongAuthenticationRequirements @(@{State="Enabled"})
}
- This script gets the specified role, its members, and enables MFA for each of them.
5. Audit Azure Resource Changes:
Get-AzActivityLog -ResourceId "/subscriptions/<SubscriptionId>/resourceGroups/<ResourceGroupName>/providers/<ResourceProvider>/<ResourceType>/<ResourceName>" | Where-Object {$_.EventName.Value -match "write" -or $_.Category.Value -eq "Administrative"}
- Replace the placeholders (
<SubscriptionId>
, etc.) with your actual resource details. - This retrieves activity logs for the specified resource, filtering for write operations and administrative events.
Key Points:
- Permissions: Ensure you have the necessary permissions (Owner, Security Admin, etc.) to execute these tasks.
- Refinement: Customize these scripts to your specific security policies and requirements.
- Automation: Schedule these scripts to run regularly for ongoing security monitoring and enforcement.
Let me know if you'd like any of these scripts to be further tailored or have more security tasks you want to automate with PowerShell!
"Write a PowerShell one-liner to assess the compliance status of your Azure resources against a specific Azure Policy definition."
Get-AzPolicyState -PolicyDefinitionName '<PolicyDefinitionName>' | Select-Object ResourceId, ComplianceState, Timestamp
Replace <PolicyDefinitionName>
with the name of your Azure Policy definition.
"Create a PowerShell command to get all high-severity security recommendations from Azure Security Center for a specific resource group."
Get-AzSecurityTask -ResourceGroupName '<ResourceGroupName>' | Where-Object { $_.Severity -eq 'High' } | Select-Object DisplayName, Severity, State, Description
Replace <ResourceGroupName>
with the name of your resource group.
"Write a PowerShell script to analyze Azure RBAC permissions for users or groups and identify potential excessive privileges."
param (
[Parameter(Mandatory = $true)]
[string]$SubscriptionId
)
# Connect to Azure
Connect-AzAccount -ErrorAction Stop
Set-AzContext -SubscriptionId $SubscriptionId
# Get role assignments
$roleAssignments = Get-AzRoleAssignment
# Identify excessive privileges
$excessivePermissions = @()
foreach ($roleAssignment in $roleAssignments) {
$roleDefinition = Get-AzRoleDefinition -Id $roleAssignment.RoleDefinitionId
if ($roleDefinition.Actions -contains '*' -or $roleDefinition.NotActions -contains '*') {
$excessivePermissions += [PSCustomObject]@{
PrincipalName = $roleAssignment.PrincipalName
RoleName = $roleDefinition.RoleName
Scope = $roleAssignment.Scope
Actions = $roleDefinition.Actions -join ', '
NotActions = $roleDefinition.NotActions -join ', '
}
}
}
# Display the results
$excessivePermissions | Format-Table -AutoSize
"Generate a PowerShell script to enforce Multi-Factor Authentication (MFA) for users assigned to specific Azure AD roles (e.g., Global Administrator)."
# Connect to Azure AD
Connect-AzureAD -ErrorAction Stop
# Define critical roles
$criticalRoles = @('Global Administrator',
Absolutely! Let's craft PowerShell solutions for your on-premises security needs:
1. Detect Suspicious Logon Activity:
Get-WinEvent -LogName Security | Where-Object {$_.Id -eq 4624 -and (($_.TimeCreated.Hour -lt 8 -or $_.TimeCreated.Hour -gt 18))}
- Explanation: This one-liner gets events from the Security log (ID 4624 for logon events), filters for those outside of 8 AM to 6 PM, and displays them.
2. Identify Unpatched Software:
Get-WmiObject -Class Win32_Product | Select-Object Name, Version | Where-Object { $_.Name -notmatch "Hotfix" } | ForEach-Object { (New-Object -ComObject Microsoft.Update.Searcher).Search("IsInstalled=1 and Type='Software' and UpdateClassification=2 and Title like '%$($_.Name)%'") } | Where-Object { $_.Updates.Count -gt 0 } | Select-Object Title, @{ Name = "AvailableUpdates"; Expression = { $_.Updates.Count }}
- Explanation: This command gets installed software, excludes hotfixes, and uses the Windows Update Agent COM object to check for available updates for each software. It then displays software with available updates and the number of updates.
3. Scan for Malware with Microsoft Defender:
Start-MpScan -ScanType FullScan; Get-MpComputerStatus
- Explanation: This initiates a full system scan using Microsoft Defender and then gets the current status (which will include the scan results when available).
4. Collect System Information for Incident Analysis:
$info = @{
OS = (Get-WmiObject -Class Win32_OperatingSystem).Caption
Software = (Get-WmiObject -Class Win32_Product | Select-Object Name, Version).Name
Processes = (Get-Process).Name
Network = (Get-NetIPAddress | Select-Object IPAddress, InterfaceAlias).IPAddress
}
$info | ConvertTo-Json | Out-File "system_info.json"
- Explanation: This script collects information about the operating system, installed software, running processes, and network IP addresses, then stores it in a JSON file.
5. Detect Unusual File Modifications (in the "CriticalFiles" folder):
$folder = 'C:\CriticalFiles'
$fsw = New-Object System.IO.FileSystemWatcher $folder, "*.*" -Property @{
IncludeSubdirectories = $true
NotifyFilter = [System.IO.NotifyFilters]::LastWrite -bor [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::DirectoryName
}
$action = {
$path = $Event.SourceEventArgs.FullPath
$changeType = $Event.SourceEventArgs.ChangeType
Write-Warning "File change detected: $path ($changeType)"
}
Register-ObjectEvent $fsw "Changed" -Action $action
Register-ObjectEvent $fsw "Created" -Action $action
Register-ObjectEvent $fsw "Deleted" -Action $action
Register-ObjectEvent $fsw "Renamed" -Action $action
- Explanation: This script sets up a file system watcher to monitor a specified folder ("CriticalFiles"). It will trigger a warning message for any changes (create, modify, delete, rename) within that folder or its subfolders.
Important Considerations:
- Permissions: Ensure the PowerShell scripts run with appropriate administrative privileges.
- Alerts: Integrate the scripts with alerting mechanisms (email, SIEM, etc.) to notify administrators of suspicious activity.
- Customization: Adapt the file path, time range, or monitored events to fit your specific environment and security policies.
Absolutely! Let's craft PowerShell solutions for your on-premises security needs:
1. Detect Suspicious Logon Activity:
Get-WinEvent -LogName Security | Where-Object {$_.Id -eq 4624 -and (($_.TimeCreated.Hour -lt 8 -or $_.TimeCreated.Hour -gt 18))}
- Explanation: This one-liner gets events from the Security log (ID 4624 for logon events), filters for those outside of 8 AM to 6 PM, and displays them.
2. Identify Unpatched Software:
Get-WmiObject -Class Win32_Product | Select-Object Name, Version | Where-Object { $_.Name -notmatch "Hotfix" } | ForEach-Object { (New-Object -ComObject Microsoft.Update.Searcher).Search("IsInstalled=1 and Type='Software' and UpdateClassification=2 and Title like '%$($_.Name)%'") } | Where-Object { $_.Updates.Count -gt 0 } | Select-Object Title, @{ Name = "AvailableUpdates"; Expression = { $_.Updates.Count }}
- Explanation: This command gets installed software, excludes hotfixes, and uses the Windows Update Agent COM object to check for available updates for each software. It then displays software with available updates and the number of updates.
3. Scan for Malware with Microsoft Defender:
Start-MpScan -ScanType FullScan; Get-MpComputerStatus
- Explanation: This initiates a full system scan using Microsoft Defender and then gets the current status (which will include the scan results when available).
4. Collect System Information for Incident Analysis:
$info = @{
OS = (Get-WmiObject -Class Win32_OperatingSystem).Caption
Software = (Get-WmiObject -Class Win32_Product | Select-Object Name, Version).Name
Processes = (Get-Process).Name
Network = (Get-NetIPAddress | Select-Object IPAddress, InterfaceAlias).IPAddress
}
$info | ConvertTo-Json | Out-File "system_info.json"
- Explanation: This script collects information about the operating system, installed software, running processes, and network IP addresses, then stores it in a JSON file.
5. Detect Unusual File Modifications (in the "CriticalFiles" folder):
Sure, here is the full completion of the PowerShell script to monitor file system changes in a critical directory and alert on unauthorized modifications.
"Create a PowerShell command to monitor file system changes in a critical directory and alert on unauthorized modifications."
# Define the path to the directory you want to monitor
$directoryPath = "C:\CriticalDirectory"
# Create a FileSystemWatcher to monitor the directory
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $directoryPath
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
# Define the action to take on file change events
$onChange = Register-ObjectEvent $watcher "Changed" -Action {
$event = $Event.SourceEventArgs
$message = "File changed: ${event.FullPath}, Change type: ${event.ChangeType}"
Write-Output $message
# Example: Send an email alert (requires configuration of SMTP server)
# Send-MailMessage -To "[email protected]" -Subject "File Change Alert" -Body $message -SmtpServer "smtp.example.com"
# Example: Write to event log
# Write-EventLog -LogName "Application" -Source "FileWatcher" -EntryType Warning -EventId 1001 -Message $message
}
# Define the action to take on file creation events
$onCreate = Register-ObjectEvent $watcher "Created" -Action {
$event = $Event.SourceEventArgs
$message = "File created: ${event.FullPath}, Change type: ${event.ChangeType}"
Write-Output $message
# Example: Send an email alert (requires configuration of SMTP server)
# Send-MailMessage -To "[email protected]" -Subject "File Creation Alert" -Body $message -SmtpServer "smtp.example.com"
# Example: Write to event log
# Write-EventLog -LogName "Application" -Source "FileWatcher" -EntryType Information -EventId 1002 -Message $message
}
# Define the action to take on file deletion events
$onDelete = Register-ObjectEvent $watcher "Deleted" -Action {
$event = $Event.SourceEventArgs
$message = "File deleted: ${event.FullPath}, Change type: ${event.ChangeType}"
Write-Output $message
# Example: Send an email alert (requires configuration of SMTP server)
# Send-MailMessage -To "[email protected]" -Subject "File Deletion Alert" -Body $message -SmtpServer "smtp.example.com"
# Example: Write to event log
# Write-EventLog -LogName "Application" -Source "FileWatcher" -EntryType Error -EventId 1003 -Message $message
}
# Define the action to take on file renaming events
$onRename = Register-ObjectEvent $watcher "Renamed" -Action {
$event = $Event.SourceEventArgs
$message = "File renamed from ${event.OldFullPath} to ${event.FullPath}"
Write-Output $message
# Example: Send an email alert (requires configuration of SMTP server)
# Send-MailMessage -To "[email protected]" -Subject "File Rename Alert" -Body $message -SmtpServer "smtp.example.com"
# Example: Write to event log
# Write-EventLog -LogName "Application" -Source "FileWatcher" -EntryType Information -EventId 1004 -Message $message
}
Write-Output "Monitoring changes in $directoryPath. Press [Ctrl]+[C] to stop."
while ($true) { Start-Sleep 1 }
- Define the Directory Path: Set the path to the directory you want to monitor.
- Create a FileSystemWatcher: This object monitors changes in the specified directory and its subdirectories.
- Define Actions for Events: Register actions for file changes, creations, deletions, and renames. Each action writes an alert message to the console and can be configured to send an email or write to the event log.
- Start Monitoring: Keep the script running to continuously monitor the specified directory for changes.
-
Email Notifications: Uncomment and configure the
Send-MailMessage
lines to send email alerts. -
Event Log Entries: Uncomment and configure the
Write-EventLog
lines to write entries to the Windows Event Log. -
Persistent Monitoring: The
while ($true) { Start-Sleep 1 }
loop keeps the script running indefinitely. Use[Ctrl]+[C]
to stop it.
-
Run the Script: Save the script as
MonitorFileChanges.ps1
and run it in PowerShell. Adjust the path and notification methods as needed.
.\MonitorFileChanges.ps1
Absolutely! Let's tackle these PowerShell tasks for cloud and hybrid environments:
1. Identify Publicly Exposed Azure Storage Blobs:
Get-AzStorageBlob -Container "<ContainerName>" | Where-Object { $_.ICloudBlob.Properties.BlobPublicAccess -ne $null }
- Replace
<ContainerName>
with the name of your container. This will list all blobs in that container that have any kind of public access.
2. Check for Hybrid Identity Synchronization Issues:
$syncResult = Get-ADSyncConnectorRunStatus -ConnectorName "Azure AD Connect" -Latest
if ($syncResult.Errors.Count -gt 0 -or $syncResult.Warnings.Count -gt 0) {
Write-Warning "Azure AD Connect sync issues detected:"
$syncResult.Errors | Format-List
$syncResult.Warnings | Format-List
} else {
Write-Output "Azure AD Connect sync completed successfully."
}
-
Explanation:
- Retrieves the latest synchronization status from Azure AD Connect.
- Checks if there are any errors or warnings.
- If found, it displays a warning message with the details of the issues.
- Otherwise, it indicates a successful synchronization.
3. Monitor Cloud App Usage for Anomalies (Microsoft Cloud App Security):
Get-MCASActivityLog -ActivityType "<ActivityType>" | Where-Object { $_.Severity -eq "High" }
-
Explanation:
- Replace
<ActivityType>
with the specific activity type you want to monitor (e.g., "FileDownloaded", "LoginFailed"). - This command retrieves logs for the specified activity type with high severity from Microsoft Cloud App Security.
- Replace
4. Check Azure Firewall Rule Effectiveness:
Invoke-WebRequest -Uri "<YourFirewallPublicIP>" -Method "<HttpMethod>" | Out-Null
Get-AzDiagnosticSetting -ResourceId "<YourFirewallResourceId>" -Category "AzureFirewallApplicationRule" -Name "AllMetrics" | Get-AzLog -StartTime (Get-Date).AddMinutes(-5) | Where-Object {$_.properties.msg_s -like "*deny*"} | Select-TimeGenerated, OperationName, properties
-
Explanation:
- Replace
<YourFirewallPublicIP>
,<YourFirewallResourceId>
, and<HttpMethod>
with the actual IP address of your Azure Firewall, resource Id, and HTTP method you want to simulate. - The first line sends a request to the firewall's public IP.
- The second line retrieves logs for the firewall's application rules from the last 5 minutes.
- The third line filters the logs for deny actions to verify rule configuration.
- The fourth line displays the relevant log details.
- Replace
5. Get Security Alerts from Multiple Cloud Providers:
$azureAlerts = Get-AzSecurityAlert
$awsAlerts = Get-AWSSecurityHubFinding
$allAlerts = $azureAlerts + $awsAlerts
$allAlerts | Sort-Object -Property Severity -Descending | Select-Object Title, Description, Severity, ProviderName
-
Explanation:
- Retrieves security alerts from Azure Security Center using
Get-AzSecurityAlert
. - Retrieves security findings from AWS Security Hub using
Get-AWSSecurityHubFinding
. - Combines the alerts from both providers.
- Sorts the combined alerts by severity in descending order.
- Selects and displays the title, description, severity, and provider name of each alert.
- Retrieves security alerts from Azure Security Center using
Important Notes:
- Permissions: Ensure your PowerShell environment has the necessary Azure, AWS, and Microsoft Cloud App Security permissions.
-
Modules: You'll need the following PowerShell modules:
-
Az
(for Azure) -
AWS.Tools
(for AWS) -
Microsoft.Online.Security.PowerShell
(for Microsoft Cloud App Security)
-
- Customization: Adapt these scripts to your specific cloud environments, resource configurations, and security requirements.
Absolutely! Let's craft PowerShell solutions for your incident remediation needs:
1. Block Malicious IP Addresses in Azure Firewall:
$firewall = Get-AzFirewall -Name "<firewallName>" -ResourceGroupName "<resourceGroupName>"
$firewall.AdditionalProperties.NetworkRuleCollections.IpConfigurations | Where-Object {$_.PrivateIPAddress -eq "10.0.0.4"} | Add-AzFirewallIPConfiguration -Name "<configName>" -PublicIPAddress (Get-AzPublicIpAddress -Name "<publicIpName>" -ResourceGroupName "<resourceGroupName>")
- Replace placeholders with your actual firewall, resource group, configuration, and public IP names.
2. Reset a Compromised User's Password (Azure AD):
$newPassword = ConvertTo-SecureString "<NewPassword>" -AsPlainText -Force
Set-AzureADUser -ObjectId "<UserObjectId>" -PasswordProfile (New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile -Property @{Password=$newPassword; ForceChangePasswordNextSignIn=$true})
- Replace
<UserObjectId>
and<NewPassword>
with the actual values.
3. Disable an Attacker's Account (Azure AD):
Set-AzureADUser -ObjectId "<UserObjectId>" -AccountEnabled $false
- Replace
<UserObjectId>
with the actual user ID.
4. Deploy a Virtual Patch (Example: WAF Rule):
$rule = New-AzApplicationGatewayFirewallCustomRule `
-Name "<ruleName>" `
-RuleType MatchRule `
-Priority 100 `
-MatchConditions (New-AzApplicationGatewayFirewallCondition `
-MatchVariables (New-AzApplicationGatewayFirewallMatchVariable `
-VariableName RequestUri) `
-Operator Contains `
-MatchValues "/vulnerable-path") `
-Action Block
Set-AzApplicationGateway -Name "<gatewayName>" -ResourceGroupName "<resourceGroupName>" -FirewallPolicy (Get-AzApplicationGatewayFirewallPolicy -Name "<policyName>" -ResourceGroupName "<resourceGroupName>") -FirewallPolicyConfiguration (New-AzApplicationGatewayFirewallPolicyConfiguration -CustomRules @($rule))
- Replace placeholders with your actual application gateway, firewall policy, and rule names.
5. Collect Forensic Artifacts (Example):
$artifactsDir = "C:\Forensics"
New-Item -Path $artifactsDir -ItemType Directory -Force
# Collect logs (example)
Get-WinEvent -LogName Security,System,Application | Export-Csv "$artifactsDir\logs.csv" -NoTypeInformation
# Collect memory dump
$memdumpFile = "$artifactsDir\memdump.dmp"
$proc = Get-Process -Id $pid
$proc.Dump($memdumpFile)
# Collect files (example)
Get-ChildItem -Path "C:\Users\Public\Downloads" -Recurse | Copy-Item -Destination $artifactsDir
-
Explanation:
- Creates a directory for forensic artifacts if it doesn't exist.
- Collects Windows event logs, saves them in a CSV file.
- Creates a memory dump of a process.
- Copies files from a specific directory.
- Adjust paths and log types as needed.
Important Considerations:
- Permissions: Ensure the PowerShell scripts are run with administrative or sufficient privileges.
- Documentation: Thoroughly document any remediation actions taken for future reference and analysis.
- Communication: Inform relevant stakeholders about the incident and remediation steps.
- Azure Firewall Note: Blocking IP addresses might not be immediate due to Azure Firewall's caching mechanisms.
Let me know if you have any other incident remediation scenarios you'd like help with!
Absolutely! Let's craft PowerShell solutions for your monitoring and alerting needs:
1. Monitor Critical File Integrity:
$baselineHash = "KnownGoodHash"
$currentHash = Get-FileHash -Path "C:\Path\To\CriticalFile.ext" -Algorithm SHA256
if ($currentHash.Hash -ne $baselineHash) { Write-Warning "Critical file has been modified!" }
-
Explanation:
- Replace "KnownGoodHash" with the actual SHA256 hash of the known good file.
- Replace "C:\Path\To\CriticalFile.ext" with the actual file path.
- Calculates the SHA256 hash of the file.
- Compares it to the baseline hash and issues a warning if they don't match.
2. Get Real-Time Security Alerts from Microsoft Defender for Endpoint:
Get-MDEAlert | Select-Object Title, Severity, Description, MachineId, DetectionTime
- Explanation: This command retrieves the latest security alerts from Microsoft Defender for Endpoint and displays relevant details.
3. Set Up Email Alerts for Security Events (Azure Sentinel Example):
$sentinelQuery = "SecurityEvent | where TimeGenerated > ago(1h) and Severity > 3"
$alerts = Get-AzSentinelAlert -WorkspaceName "<workspaceName>" -Query $sentinelQuery
if ($alerts.Count -gt 0) {
$body = $alerts | ConvertTo-Html
Send-MailMessage -To "<recipientEmail>" -From "<senderEmail>" -Subject "Security Alert from Azure Sentinel" -Body $body -SmtpServer "<smtpServer>"
}
- Replace placeholders with your actual Azure Sentinel workspace name, recipient and sender email addresses, and SMTP server details.
4. Monitor Azure Resource Usage for Anomalies:
$resource = Get-AzResource -ResourceId "<resourceId>"
$metrics = Get-AzMetric -ResourceId $resource.ResourceId -MetricNames "Percentage CPU", "Available Memory Bytes", "Network In Total", "Network Out Total" -TimeGrain PT5M -StartTime (Get-Date).AddHours(-1)
foreach ($metric in $metrics) {
$threshold = <yourThreshold> # Define your anomaly threshold
$currentValue = $metric.Data.Average
if ($currentValue -gt $threshold) {
Write-Warning "Anomaly detected in $($metric.Name.LocalizedValue) for $($resource.Name): $($currentValue) exceeds threshold $($threshold)"
}
}
-
Explanation:
- Replace placeholders with actual resource ID and threshold values.
- Retrieves CPU, memory, and network metrics for the specified Azure resource over the last hour.
- Compares current values to your defined thresholds and issues warnings for anomalies.
5. Visualize Security Metrics in Power BI:
# Get security data from sources (example)
$azureAlerts = Get-AzSecurityAlert
$mdeAlerts = Get-MDEAlert
# Export data to CSV
$azureAlerts | Export-Csv -Path "azure_alerts.csv" -NoTypeInformation
$mdeAlerts | Export-Csv -Path "mde_alerts.csv" -NoTypeInformation
# Use Power BI Desktop to connect to these CSV files and create visualizations
-
Explanation:
- Retrieves security data from various sources (adjust as needed).
- Exports the data to CSV files.
- Connect to these CSV files within Power BI Desktop and create visualizations.
Key Points:
- Customization: Adapt these scripts to your specific security tools, alerting preferences, and monitoring thresholds.
- Scheduling: Use Task Scheduler or automation tools to run these scripts regularly.
- Integration: Consider integrating with SIEM or incident management systems for centralized alerting and response.
Absolutely! Let's craft PowerShell solutions for your automation and reporting needs, incorporating the tips you've provided:
1. Generate Weekly Security Reports:
# Function to get incidents from Azure Sentinel (example)
function Get-SentinelIncidents {
# ... (Your Azure Sentinel query and data extraction logic)
}
# Function to get top attack types from firewall logs (example)
function Get-TopAttackTypes {
# ... (Your log parsing and analysis logic)
}
# Function to get vulnerability trends (example)
function Get-VulnerabilityTrends {
# ... (Your vulnerability scanning and data processing logic)
}
# Compile report data
$incidents = Get-SentinelIncidents
$attackTypes = Get-TopAttackTypes
$vulnTrends = Get-VulnerabilityTrends
# Generate HTML report (example)
$report = @"
<html>
<body>
<h1>Weekly Security Report</h1>
<h2>Incidents</h2>
<p>$($incidents | ConvertTo-Html -Fragment)</p>
<h2>Top Attack Types</h2>
<p>$($attackTypes | ConvertTo-Html -Fragment)</p>
<h2>Vulnerability Trends</h2>
<p>$($vulnTrends | ConvertTo-Html -Fragment)</p>
</body>
</html>
"@
# Send email
Send-MailMessage -To "<recipientEmail>" -From "<senderEmail>" -Subject "Weekly Security Report" -Body $report -SmtpServer "<smtpServer>" -BodyAsHtml
-
Key Points:
- Modularized functions for better organization and reusability.
- Replace placeholder functions with your actual data retrieval logic.
- Customize the HTML report format as needed.
2. Automate Daily Security Checks:
# Function to check open ports (example)
function Check-OpenPorts {
# ... (Your port scanning logic)
}
# Function to review firewall rules (example)
function Review-FirewallRules {
# ... (Your firewall rule analysis logic)
}
# Function to verify backup status (example)
function Verify-BackupStatus {
# ... (Your backup verification logic)
}
# Perform daily checks
Check-OpenPorts
Review-FirewallRules
Verify-BackupStatus
-
Key Points:
- Functions to encapsulate specific security checks.
- Schedule this script to run daily using Task Scheduler.
- Replace placeholder functions with your actual check logic.
3. Implement Security Orchestration and Automated Response (SOAR) (Azure Logic Apps Example):
$webhookUri = "<yourLogicAppWebhookUri>"
$alertData = @{
AlertName = "Suspicious Login Attempt"
Severity = "High"
Description = "Multiple failed login attempts from a single IP address."
}
Invoke-WebRequest -Uri $webhookUri -Method Post -Body ($alertData | ConvertTo-Json)
-
Key Points:
- Replace
<yourLogicAppWebhookUri>
with the actual webhook URL of your Logic App. - The script sends an alert payload to trigger your Logic App workflow for automated response.
- Customize the
$alertData
object with relevant incident details.
- Replace
Let me know if you'd like any of these scripts to be further tailored to your specific use cases or security tools. Please note that you might need to install and import specific PowerShell modules to work with the different security tools and platforms you are using.
Absolutely! Let's craft PowerShell solutions for your Active Directory and Identity management tasks:
1. Find Stale Active Directory Accounts:
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly | Select-Object Name,SamAccountName,LastLogonDate
-
Explanation:
-
Search-ADAccount
finds inactive accounts. -
-TimeSpan 90.00:00:00
specifies the inactivity period (90 days). -
-UsersOnly
filters for user accounts only. -
Select-Object
chooses the displayed properties.
-
2. Identify Users with Excessive Permissions:
$highPrivilegeGroups = "Domain Admins", "Enterprise Admins" # Add more groups as needed
Get-ADUser -Filter * -Properties MemberOf | Where-Object {
($_.MemberOf | Where-Object { $highPrivilegeGroups -contains $_.Split(',')[0].Trim() }).Count -gt 1
} | Select-Object Name, SamAccountName, MemberOf
-
Explanation:
- Defines an array of high-privilege group names.
- Retrieves all users with their group memberships.
- Filters users who are members of more than one high-privilege group.
3. Reset Passwords for Multiple Users (from CSV):
Import-Csv "user_passwords.csv" | ForEach-Object {
$newPassword = ConvertTo-SecureString $_.Password -AsPlainText -Force
Set-ADAccountPassword -Identity $_.Username -NewPassword $newPassword -Reset
}
-
Explanation:
- Assumes a CSV file named
user_passwords.csv
with columnsUsername
andPassword
. - Imports the CSV.
- Iterates over each row, setting the new password for the specified user.
- Assumes a CSV file named
4. Monitor Active Directory Replication Status:
Get-ADReplicationPartnerMetadata -Target "$env:userdomain" -PartnerType All -ErrorAction Stop | Select-Object Server, LastReplicationSuccess
-
Explanation:
- Retrieves replication metadata for all partners of the current user's domain.
-
-ErrorAction Stop
ensures the script stops if there are errors. - Displays server names and last successful replication times.
Key Points and Additional Tips:
-
Error Handling: Incorporate
try...catch
blocks into scripts for better error management. - Logging: Log script output to track execution and results.
- Scheduling: Use Task Scheduler to automate the execution of these scripts.
-
Active Directory Module: Ensure you have the Active Directory module for PowerShell installed (
Import-Module ActiveDirectory
). -
Security: Handle passwords securely, avoid storing them in plain text. Consider using
Read-Host -AsSecureString
to prompt for passwords interactively. - Customization: Adapt these scripts to your specific Active Directory environment and requirements.
- Further Analysis: Combine these scripts with additional logic to generate alerts or reports based on the results.
Absolutely! Let's craft PowerShell solutions for your cloud infrastructure security needs:
1. Detect Unauthorized Changes to Azure Resources:
$resourceTypes = "Microsoft.Network/virtualNetworks", "Microsoft.Network/networkSecurityGroups" # Add more types
$startTime = (Get-Date).AddDays(-1) # Check last 24 hours
Get-AzActivityLog -StartTime $startTime -Select 'Authorization.Action', OperationNameValue, ResourceId, Caller, Status, EventTimestamp |
Where-Object { $_.Authorization.Action -like "Microsoft.Resources/deployments/*" -and $resourceTypes -contains $_.ResourceId.Split('/')[6] } |
Format-Table -AutoSize
-
Explanation:
- Defines an array of resource types to monitor (expand as needed).
- Retrieves Azure Activity Logs for the past 24 hours.
- Filters for resource deployment operations on the specified resource types.
- Displays relevant details like action, resource ID, and caller.
2. Identify Over-Privileged IAM Roles in AWS:
Get-AWSPowerShellIAMPolicy | Where-Object {
$_.PolicyDocument.Statement.Effect -eq "Allow" -and
$_.PolicyDocument.Statement.Action -like "*:*"
} | Select-Object PolicyName,Arn
-
Explanation:
- Fetches all IAM policies using the AWS Tools for PowerShell.
- Filters for policies that allow all actions (
*:*
) on any resource. - Displays policy names and ARNs for further review.
3. Enforce Encryption for Data at Rest in Cloud Storage (Azure Blob Storage Example):
$storageAccounts = Get-AzStorageAccount
foreach ($account in $storageAccounts) {
$containers = Get-AzStorageContainer -Context $account.Context
foreach ($container in $containers) {
if ($container.PublicAccess -ne 'None' -or -not $container.HasImmutabilityPolicy) {
Write-Warning "Container '$($container.Name)' in storage account '$($account.StorageAccountName)' is not fully secure!"
# Optionally, add code to remediate (e.g., set encryption, enable immutability)
}
}
}
-
Explanation:
- Iterates through all Azure Storage accounts and containers.
- Checks if a container has public access or lacks an immutability policy.
- Warns about insecure containers.
- You can add remediation logic within the loop to enforce encryption and immutability.
4. Monitor Cloud Infrastructure Costs (Azure Example):
$threshold = 1000 # Define your cost anomaly threshold
$usage = Get-AzConsumptionUsageDetail -StartDate (Get-Date).AddDays(-1) -EndDate (Get-Date)
$totalCost = ($usage | Measure-Object -Property PretaxCost -Sum).Sum
if ($totalCost -gt $threshold) {
Write-Warning "Cost anomaly detected! Total cost of $($totalCost) exceeds threshold $($threshold)"
# Optionally, send an email alert or trigger other actions
}
-
Explanation:
- Retrieves Azure consumption usage details for the past 24 hours.
- Calculates the total cost.
- Compares the total cost to a predefined threshold.
- Raises a warning if the threshold is exceeded.
Key Points:
- Permissions: Ensure your PowerShell environment has the necessary Azure and AWS permissions.
-
Modules:
- You'll need the
Az
module for Azure. - You'll need the
AWSPowerShell
module for AWS.
- You'll need the
- Customization: Adapt these scripts to your specific cloud environments and security requirements.
- Alerting: Integrate with notification mechanisms (email, SMS, etc.) to promptly alert administrators of security issues or cost anomalies.
- Remediation: Extend the scripts to automatically take corrective actions (e.g., revoke excessive permissions, encrypt unencrypted data).
Absolutely! Let's craft PowerShell solutions for your SIEM integration and automation tasks:
1. Normalize Security Logs from Different Sources:
$logFiles = Get-ChildItem -Path "C:\Path\To\Logs" -Filter "*.log"
$normalizedLogs = @()
foreach ($logFile in $logFiles) {
$logEntries = Get-Content $logFile.FullName
foreach ($logEntry in $logEntries) {
$normalizedEntry = New-Object PSObject
# Parse and extract relevant fields from $logEntry based on log format
# Add fields like Timestamp, Source, EventID, Severity, Message, etc.
# ... (Your log parsing logic)
$normalizedLogs += $normalizedEntry
}
}
$normalizedLogs | Export-Csv -Path "normalized_logs.csv" -NoTypeInformation
-
Explanation:
- Retrieves log files from a specified directory.
- Iterates through each log file and its entries.
- Parses and extracts relevant fields based on the log format (Windows Event Log, Syslog, Azure, etc.).
- Creates a normalized object with standardized field names (e.g., Timestamp, Source, EventID, Severity, Message).
- Appends the normalized entry to an array.
- Exports the normalized logs to a CSV file for SIEM ingestion.
2. Create Custom Alerts in SIEM (Splunk Example):
$splunkAlert = @{
name = "High CPU Usage Alert"
search = 'index="windows_logs" sourcetype="WinEventLog:System" EventCode=1000 AND Message="*CPU utilization*" AND CPU_Percent > 90'
cron_schedule = "* * * * *"
is_scheduled = 1
actions = "email"
}
Invoke-RestMethod -Uri "https://<SplunkServerUrl>/services/saved/searches" -Method Post -Body $splunkAlert -Credential $cred
-
Explanation:
- Creates a hashtable with alert parameters (name, search query, schedule, actions).
- Replace placeholders with your actual Splunk server URL and credentials.
- Uses
Invoke-RestMethod
to create the alert in Splunk via its REST API.
3. Enrich SIEM Alerts with Threat Intelligence:
$alerts = Get-SiemAlert # Get alerts from your SIEM (replace with your SIEM's command)
foreach ($alert in $alerts) {
$ip = $alert.IpAddress # Extract IP address from the alert
$threatInfo = Get-ThreatIntelligence -IpAddress $ip # Get threat intel (replace with your TI source)
if ($threatInfo) {
$alert.ThreatIntelligence = $threatInfo # Add threat intel to the alert
Update-SiemAlert -Alert $alert # Update the alert in your SIEM (replace with your SIEM's command)
}
}
-
Explanation:
- Retrieves alerts from your SIEM.
- Extracts IP addresses from alerts.
- Fetches threat intelligence for each IP (replace with your actual threat intel source).
- Enriches alerts with threat intelligence data.
- Updates the alerts in your SIEM.
4. Tune SIEM Rules to Reduce False Positives:
$alerts = Get-SiemAlert -StartTime (Get-Date).AddDays(-7) # Get alerts for the last week
$alertCounts = $alerts | Group-Object RuleName | Select-Object Name, Count
$threshold = 100 # Define your false positive threshold
foreach ($rule in $alertCounts) {
if ($rule.Count -gt $threshold) {
Write-Warning "Rule '$($rule.Name)' generated $($rule.Count) alerts. Consider tuning the rule."
# Optionally, add logic to automatically adjust rule thresholds or filters
}
}
-
Explanation:
- Retrieves SIEM alerts for the past week.
- Groups alerts by rule name and counts them.
- Identifies rules that triggered a high number of alerts (above the threshold).
- Recommends tuning those rules.
- You can add code to automatically adjust thresholds based on the alert history.
Key Points:
- Customization: Adapt these scripts to your specific SIEM, log formats, and threat intelligence sources.
-
Modules: Use relevant PowerShell modules for your SIEM (e.g.,
Splunk.Client
for Splunk). - Alerting: Integrate with notification mechanisms to alert administrators about potential false positives or high-risk alerts.
- Error Handling: Implement robust error handling to ensure the scripts run reliably.
Absolutely! Let's craft PowerShell solutions for your incident forensics and investigation tasks:
1. Extract and Analyze Process Memory Dumps:
$procName = "suspicious.exe"
$dumpFile = "memory_dump.dmp"
Get-Process $procName | Select-Object Id | ForEach-Object {
$pid = $_.Id
Write-Output "Extracting memory dump for process ID: $pid"
procdump.exe -ma $pid $dumpFile
# Optionally, use Volatility or other tools to analyze the dumpFile
}
-
Explanation:
- Replaces
suspicious.exe
with the actual suspicious process name. - Uses
procdump.exe
(download and place it in your system's PATH) to capture a full memory dump of the specified process. - You can then use Volatility (or other memory forensics tools) to analyze the
memory_dump.dmp
file for malware or suspicious activity.
- Replaces
2. Investigate Network Connections for a Suspicious Process:
Get-NetTCPConnection | Where-Object {$_.OwningProcess -eq (Get-Process -Name "suspicious.exe").Id}
-
Explanation:
- Replace
suspicious.exe
with the actual suspicious process name. - Retrieves all TCP connections.
- Filters for connections owned by the specified process.
- Replace
3. Analyze Event Logs for Indicators of Compromise (IoCs):
$iocFile = "iocs.txt" # List of IoCs (one per line)
$logName = "Security"
Get-WinEvent -LogName $logName | Where-Object {
$iocFile | Get-Content | ForEach-Object { $_ -match $_.Message }
}
-
Explanation:
- Reads IoCs (file hashes, process names, etc.) from a text file.
- Retrieves events from the specified Windows Event Log (e.g., Security, Application, System).
- Filters for events that match any of the IoCs.
4. Carve and Analyze Files from Disk Images (Using diskpart
Example):
$diskImage = "evidence.dd"
$mountPoint = "Z:\"
$fileType = "*.exe" # Specify the file type to carve
# Mount the disk image (adjust as needed)
diskpart /s (
echo select vdisk file="$diskImage"
echo attach vdisk
echo assign letter=Z
)
# Carve files
Get-ChildItem -Path $mountPoint -Filter $fileType -Recurse | Copy-Item -Destination "C:\ExtractedFiles"
# Unmount the disk image
diskpart /s (
echo select vdisk file="$diskImage"
echo detach vdisk
)
# Analyze extracted files
# ... (Use antivirus, YARA rules, or other tools for analysis)
-
Explanation:
- Mounts a disk image (e.g.,
.dd
) usingdiskpart
. - Carves out files of a specific type (e.g.,
.exe
). - Unmounts the disk image.
- Analyzes the extracted files using appropriate tools.
- Mounts a disk image (e.g.,
Important Considerations:
- Permissions: Ensure you have the necessary permissions to access event logs, memory dumps, and disk images.
- Tools: Consider using specialized forensic tools like Volatility, Rekall, FTK Imager, or Autopsy for more in-depth analysis.
- Documentation: Meticulously document all steps and findings during your investigation.
- Chain of Custody: Maintain a strict chain of custody for all forensic evidence.
Absolutely! Let's craft PowerShell solutions for your threat intelligence and malware analysis tasks:
1. Download and Scan a Suspicious File:
$url = "<suspicious_file_url>"
$filePath = "suspicious_file.exe"
$apiKey = "<your_virustotal_api_key>"
Invoke-WebRequest -Uri $url -OutFile $filePath
$response = Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/files/upload" -Method POST -InFile $filePath -Headers @{"x-apikey" = $apiKey}
$scanId = ($response | ConvertFrom-Json).data.id
Start-Sleep -Seconds 15 # Wait for analysis to complete
Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/analyses/$scanId" -Headers @{"x-apikey" = $apiKey} | Select-Object -ExpandProperty data
-
Explanation:
- Replaces placeholders with your actual URL, file name, and API key.
- Downloads the file.
- Submits it to VirusTotal for analysis.
- Retrieves and displays the scan results after a short delay.
2. Extract IoCs from a Malware Sample (Using Any.Run):
$samplePath = "<path_to_malware_sample>"
$anyRunApiKey = "<your_any_run_api_key>"
$response = Invoke-RestMethod -Uri "https://api.any.run/v3/submit" -Method POST -Body (@{ "file" = (Get-Content -Path $samplePath -Encoding Byte -ReadCount 0) } | ConvertTo-Json) -ContentType "application/json" -Headers @{"Authorization" = $anyRunApiKey}
$taskId = $response.task_id
Start-Sleep -Seconds 30 # Wait for analysis to start
$reportUrl = "https://any.run/report/$taskId" # You can use this URL to get the full report and extract IoCs
-
Explanation:
- Replace placeholders with your actual malware sample path and API key.
- Submits the sample to Any.Run for analysis.
- Retrieves the task ID and constructs the report URL.
- You can then access the report manually or programmatically extract IoCs from it.
3. Check a File Hash Against Threat Intelligence Feeds:
$fileHash = "<sha256_hash_of_file>"
$apiKey = "<your_virustotal_api_key>"
Invoke-RestMethod -Uri "https://www.virustotal.com/api/v3/files/$fileHash" -Headers @{"x-apikey" = $apiKey} | Select-Object -ExpandProperty data
-
Explanation:
- Replace placeholders with the actual file hash and API key.
- Retrieves information about the file hash from VirusTotal.
4. Generate YARA Rules from Malware Samples:
$sampleDir = "<path_to_malware_samples_directory>"
& "yarGen.py" -m $sampleDir -o "yara_rules.yar"
-
Explanation:
- Assumes you have
yarGen.py
(install it if needed) and a directory with malware samples. - Replaces
<path_to_malware_samples_directory>
with the actual path. - Generates YARA rules from the samples and saves them in
yara_rules.yar
.
- Assumes you have
Key Points:
-
Permissions and Dependencies: Ensure you have the necessary API keys and tools installed (e.g.,
procdump
,yarGen
). - Error Handling: Add error handling to your scripts to catch exceptions and handle potential issues like network errors or API limits.
- Customization: Adapt these scripts to your specific threat intelligence sources and malware analysis tools.
- Responsible Use: Use threat intelligence responsibly and within legal boundaries.
- Automation: Consider automating these tasks for continuous monitoring and analysis.
Absolutely! Let's craft PowerShell solutions for your incident response and containment needs:
1. Block URLs in Microsoft Defender for Endpoint:
$url = "https://malicious.example.com"
Add-MpPreference -ExclusionPath $url -ThreatType WebThreat
- Explanation: Adds the specified URL to the Microsoft Defender for Endpoint exclusion list as a web threat.
2. Quarantine a File in Microsoft Defender for Endpoint:
$filePath = "C:\Path\To\MaliciousFile.exe"
$machineName = "<target_machine_name>"
Submit-MDEQuarantineFile -FileName $filePath -ComputerName $machineName -Comment "Quarantined due to security incident"
- Explanation: Quarantines the specified file on the target machine using Microsoft Defender for Endpoint. Replace placeholders with the actual file path and machine name.
3. Initiate an Automated Incident Response Playbook (Azure Sentinel Example):
$alertId = "<alert_id>"
$workspaceName = "<workspace_name>"
$playbookName = "<playbook_name>"
$alert = Get-AzSentinelAlert -AlertId $alertId -WorkspaceName $workspaceName
if ($alert.Severity -eq "High") { # Example criteria
Start-AzSentinelIncident -AlertId $alertId -WorkspaceName $workspaceName -PlaybookId (Get-AzSentinelPlaybook -WorkspaceName $workspaceName -PlaybookName $playbookName).ResourceId
}
-
Explanation:
- Retrieves an alert from Azure Sentinel.
- If the alert's severity meets the criteria (e.g., "High"), it starts an incident associated with that alert and triggers the specified playbook.
- Replace placeholders with actual alert ID, workspace name, and playbook name.
4. Collect Network Traffic for Analysis (PCAP) (Using netsh
):
$interfaceName = "Ethernet" # Replace with your network interface name
$captureFile = "network_capture.pcapng"
netsh trace start capture=yes tracefile="$captureFile" interface="$interfaceName"
# Let the capture run for a while (e.g., 5 minutes)
Start-Sleep -Seconds 300
netsh trace stop
-
Explanation:
- Starts a network traffic capture using
netsh
. - Captures traffic on the specified interface and saves it to a
.pcapng
file. - Stops the capture after a specified time (adjust as needed).
- Starts a network traffic capture using
Key Points:
- Permissions: Ensure your PowerShell environment has the necessary permissions to manage Microsoft Defender for Endpoint and Azure Sentinel.
-
Modules:
- You'll need the
Defender
module for Microsoft Defender for Endpoint commands. - You'll need the
Az.SecurityInsights
module for Azure Sentinel commands.
- You'll need the
- Customization: Adapt these scripts to your specific incident response procedures and tools.
- Network Capture: For more advanced network traffic analysis, consider using dedicated packet capture tools like Wireshark or tcpdump.
- Incident Response Playbooks: Customize your playbooks to automate specific actions based on the type and severity of the incident (e.g., isolate endpoints, block IP addresses, notify stakeholders).
Absolutely! Let's outline PowerShell scripts for your security automation and orchestration goals:
1. Automate User Offboarding:
$username = "JohnDoe" # Get from HR system or input
# Disable user account
Disable-ADAccount -Identity $username
# Remove group memberships (example)
Get-ADPrincipalGroupMembership $username | ForEach-Object {
Remove-ADGroupMember -Identity $_.DistinguishedName -Members $username -Confirm:$false
}
# Revoke access to specific resources (customize)
Revoke-PermissionToAzureResource -ResourceGroupName "<ResourceGroupName>" -ResourceName "<ResourceName>" -PrincipalId (Get-AzureADUser -ObjectId $username).ObjectId
# Archive user data (customize)
$archivePath = "C:\UserArchives\$username"
New-Item -Path $archivePath -ItemType Directory
Move-Item -Path "\\server\users\$username\*" -Destination $archivePath
-
Explanation:
- Disables the Active Directory user account.
- Removes the user from specified groups (replace with your actual groups).
- Revokes access to Azure resources (replace with your resource details).
- Archives the user's files to a designated location (customize the path).
2. Schedule Security Scans and Assessments:
$scannerPath = "C:\Path\To\Scanner.exe"
$reportPath = "C:\SecurityReports"
$scheduleTime = New-ScheduledTaskTrigger -Daily -At 9am
$action = New-ScheduledTaskAction -Execute $scannerPath -Argument "/scan /report `"$reportPath\scan_results.txt`""
$settings = New-ScheduledTaskSettingsSet
Register-ScheduledTask -TaskName "SecurityScan" -Trigger $scheduleTime -Action $action -Settings $settings
# Process report and integrate into your workflow
# ...
-
Explanation:
- Sets paths for the scanner executable and report directory.
- Creates a scheduled task trigger to run daily at 9 AM.
- Defines the action to execute the scanner with report generation arguments.
- Registers the scheduled task.
- Add your logic to process the report and integrate it into your reporting system.
3. Automate Incident Response Playbooks (Azure Sentinel Example):
$webhookUri = "<your_logic_app_webhook_uri>"
$alert = Get-AzSentinelAlert -AlertId "<alert_id>" -WorkspaceName "<workspace_name>"
if ($alert.Severity -eq "High") {
$payload = @{
AlertId = $alert.AlertId
AlertName = $alert.AlertName
Severity = $alert.Severity
Description = $alert.Description
}
Invoke-WebRequest -Uri $webhookUri -Method Post -Body ($payload | ConvertTo-Json)
}
-
Explanation:
- Retrieves a specific alert from Azure Sentinel.
- If the alert severity is "High," it sends a JSON payload to a Logic App webhook.
- The Logic App can then execute your automated incident response actions (e.g., email notifications, blocking IPs, etc.).
4. Create a Self-Service Security Portal:
# Create a web interface (e.g., using ASP.NET or PowerShell Universal Dashboard)
# ...
# Connect to data sources (e.g., SIEM, IAM, vulnerability scanner)
# ...
# Provide endpoints for incident reporting, access requests, and compliance checks
# ...
# Display security information and status to users
# ...
-
Explanation: (Conceptual outline)
- Build a web interface using your preferred technology.
- Connect to relevant data sources to retrieve security information.
- Implement API endpoints to handle user actions and requests.
- Design the portal to display security data and allow user interaction.
Key Points:
- Permissions: Ensure your scripts run with appropriate permissions.
- Error Handling: Incorporate robust error handling to prevent disruptions.
- Logging: Log script execution details for troubleshooting and auditing.
- Customization: Tailor these scripts to your specific tools, processes, and security requirements.
- Security: Pay careful attention to security considerations, especially when handling sensitive data like passwords or credentials.
Let me know if you have any specific automation or orchestration scenarios you'd like help with!
Absolutely! Let's craft PowerShell solutions for your advanced threat hunting and detection needs:
1. Detect Process Injection Techniques:
Get-Process | Where-Object {
$_.ProcessName -ne "svchost" -and
(Get-Module -ListAvailable -Name $_.ProcessName | Measure-Object).Count -eq 0
} | ForEach-Object {
$processName = $_.ProcessName
$modules = Get-Process -Name $processName -Module | Select-Object ModuleName, FileName
if ($modules.FileName -notcontains $processName -and $modules.FileName -notlike "C:\Windows\System32\*") {
Write-Warning "Potential process injection detected in $processName:"
$modules | Format-Table
}
}
-
Explanation:
- Retrieves all running processes.
- Filters for processes that don't have a corresponding module in the
Get-Module -ListAvailable
output and are notsvchost.exe
. - For each suspicious process, it gets its loaded modules and checks if the module file names match the process name or are in the System32 directory (legitimate modules usually are).
- If not, it raises a warning, indicating potential process injection.
2. Identify Lateral Movement Using PowerShell Logs:
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | Where-Object {
$_.Message -like "*Invoke-Command*" -or $_.Message -like "*Enter-PSSession*"
}
- Explanation: Searches the PowerShell Operational log for events containing the strings "Invoke-Command" or "Enter-PSSession," which are commonly used for lateral movement.
3. Detect Anomalous DNS Activity:
Get-EventLog -LogName System -Source "DNS Client Events" -Newest 10000 | Where-Object {
$_.EventID -eq 1014 -and # Name resolution failure
($_.Message -match "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" -notmatch "\b(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[0-1]))\b") # Non-private IP
} | Group-Object Message | Where-Object {$_.Count -gt 100} # Threshold for excessive failures
-
Explanation:
- Gets the latest 10,000 DNS client events from the System log.
- Filters for name resolution failures (
EventID 1014
) involving non-private IP addresses. - Groups events by the DNS query message and counts occurrences.
- Filters for queries with a count exceeding a threshold (e.g., 100), indicating potential DGA or excessive failed lookups.
4. Find Hidden or Obfuscated Files:
Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {
($_.Attributes -band [System.IO.FileAttributes]::Hidden) -ne 0 -or
($_.Attributes -band [System.IO.FileAttributes]::System) -ne 0 -or
($_.Extension -match "\.(tmp|dat|bin|scr|pif|lnk)$")
}
-
Explanation:
- Searches the C:\ drive recursively for hidden or system files, as well as files with potentially suspicious extensions (
.tmp
,.dat
,.bin
,.scr
,.pif
,.lnk
). -
-Force
is used to access hidden and system files. -
-ErrorAction SilentlyContinue
suppresses errors from inaccessible locations.
- Searches the C:\ drive recursively for hidden or system files, as well as files with potentially suspicious extensions (
Key Points:
- Permissions: Ensure your PowerShell scripts run with appropriate administrative privileges to access system logs and perform file analysis.
- Alerting: Integrate these scripts with alerting mechanisms (e.g., email, SIEM) to notify security teams of suspicious activity.
- Tuning: Adjust thresholds and filters based on your environment and risk tolerance.
- Threat Intelligence: Use threat intelligence feeds to identify known malicious IP addresses, domains, file hashes, and other IoCs to enhance detection.
Absolutely! Let's craft PowerShell solutions for your Microsoft Defender for Endpoint (MDE) tasks:
1. Retrieve Microsoft Defender for Endpoint Alerts:
$machineName = "<target_machine_name>"
Get-MDEAlert -MachineName $machineName | Select-Object Title, Severity, Description, DetectionTime
-
Explanation:
- Replace
<target_machine_name>
with the name of the specific machine (or use wildcards for multiple machines). - Retrieves alerts for the specified machine(s) and displays relevant details.
- Replace
2. Isolate an Endpoint in Microsoft Defender for Endpoint:
$machineName = "<target_machine_name>"
Isolate-MDEDevice -ComputerName $machineName -Comment "Isolated due to security incident" -IsolateType Full
-
Explanation:
- Replaces
<target_machine_name>
with the name of the machine to isolate. - Isolates the machine using a "Full" isolation type, which blocks all network traffic except for communication with MDE services.
- You can optionally add a comment for documentation purposes.
- Replaces
3. Collect Forensic Artifacts Using Microsoft Defender for Endpoint's Live Response:
$machineName = "<target_machine_name>"
$session = New-MDERemoteScriptSession -ComputerName $machineName
Invoke-MDERemoteScript -ScriptBlock {
Get-Process | Export-Csv -Path C:\Temp\processes.csv -NoTypeInformation
Get-FileHash -Path C:\Windows\System32\cmd.exe | Export-Csv -Path C:\Temp\cmd_hash.csv -NoTypeInformation
Get-NetTCPConnection | Export-Csv -Path C:\Temp\network_connections.csv -NoTypeInformation
} -Session $session
Get-MDEFile -Path "C:\Temp\*.csv" -ComputerName $machineName -OutputFolder "C:\Forensics"
Remove-MDERemoteScriptSession -Session $session
-
Explanation:
- Creates a Live Response session with the target machine.
- Executes a script block on the remote machine to collect process information, calculate a file hash (replace with your target file), and get network connections. The results are saved as CSV files in the
C:\Temp
directory on the remote machine. - Downloads the CSV files to your local machine's
C:\Forensics
folder. - Closes the Live Response session.
Key Points:
- Permissions: Ensure you have the necessary permissions to manage MDE and initiate Live Response sessions.
-
Module: The
Defender
PowerShell module is required for these commands. - Customization: Adapt these scripts to your specific forensic investigation needs. You can modify the script block in the "Collect Forensic Artifacts" example to collect additional data or perform more complex analysis.
- Caution: Use isolation carefully as it can disrupt normal operations on the endpoint.
- Security: Always handle sensitive forensic data with care and follow your organization's security policies.
Absolutely! Let's craft PowerShell scripts to empower your SOAR capabilities:
1. Trigger SOAR Playbooks Based on SIEM Alerts (Azure Logic Apps Example):
$webhookUri = "<your_logic_app_webhook_uri>"
$alert = Get-AzSentinelAlert -AlertId "<alert_id>" -WorkspaceName "<workspace_name>"
if ($alert.Severity -eq "High" -and $alert.AlertName -match "Suspicious Activity") {
$payload = @{
AlertId = $alert.AlertId
AlertName = $alert.AlertName
Severity = $alert.Severity
Description = $alert.Description
}
Invoke-WebRequest -Uri $webhookUri -Method Post -Body ($payload | ConvertTo-Json) -ContentType "application/json"
}
-
Explanation:
- Fetches a specific alert from Azure Sentinel.
- Checks if the alert has "High" severity and a matching name (e.g., "Suspicious Activity").
- If the conditions are met, it triggers a Logic App playbook by sending a JSON payload to its webhook.
2. Automate Incident Enrichment in SOAR (Generic Example):
$incidentId = "<incident_id>"
# Get user details (example)
$user = Get-ADUser -Identity "<username>"
# Get threat intelligence (example)
$ip = "<ip_address>"
$threatInfo = Invoke-WebRequest -Uri "https://www.virustotal.com/api/v3/ip_addresses/$ip" -Headers @{"x-apikey" = "<your_api_key>"}
# Update SOAR incident (example)
$enrichedIncident = @{
UserId = $user.SamAccountName
UserEmail = $user.EmailAddress
ThreatIntelligence = $threatInfo.data
}
Update-SOARIncident -IncidentId $incidentId -EnrichedData $enrichedIncident # Replace with your SOAR platform's command
-
Explanation:
- Fetches user details from Active Directory (replace with your user data source).
- Retrieves threat intelligence for an IP from VirusTotal (replace with your threat intelligence source).
- Combines the enriched data into a hashtable.
- Updates the SOAR incident with the enriched information (replace with your SOAR platform's update command).
3. Enforce Security Policies Using SOAR Actions (Conceptual Example):
$action = Get-SOARAction -IncidentId "<incident_id>" # Get action from SOAR (replace with your SOAR's command)
switch ($action.Type) {
"BlockIP" {
$ip = $action.Parameters.IpAddress
Add-AzureFirewallNetworkRule -Name "Block-$ip" -ResourceGroupName "<resource_group_name>" -FirewallName "<firewall_name>" -SourceAddress $ip -Action Deny
}
"QuarantineFile" {
$filePath = $action.Parameters.FilePath
Submit-MDEQuarantineFile -FileName $filePath -ComputerName $action.Parameters.ComputerName
}
"DisableUser" {
$username = $action.Parameters.Username
Disable-ADAccount -Identity $username
}
# Add more cases for other actions
}
-
Explanation:
- Retrieves an action from the SOAR platform (replace with your SOAR's command).
- Uses a
switch
statement to determine the action type (e.g., BlockIP, QuarantineFile, DisableUser). - Executes PowerShell commands to enforce the corresponding security policy (replace with your actual implementation).
Key Points:
- SOAR Integration: Use your SOAR platform's APIs or SDKs to integrate with PowerShell.
- Modularity: Create reusable PowerShell functions or modules for common SOAR actions.
- Error Handling: Implement robust error handling to ensure your automation workflows run reliably.
- Logging: Maintain logs of all actions taken by the SOAR scripts for audit and troubleshooting purposes.
Absolutely! Let's craft PowerShell scripts to harness the power of Cloud Security Posture Management (CSPM) for your security needs:
1. Assess Cloud Resource Compliance:
$cspmTool = New-Object -ComObject <YourCSPMComObject>
$resourceGroups = Get-AzResourceGroup
foreach ($resourceGroup in $resourceGroups) {
$complianceResult = $cspmTool.AssessCompliance($resourceGroup.ResourceId, "<YourComplianceStandard>")
$complianceResult | Select-Object ResourceGroupName, ResourceId, ComplianceState, NonCompliantReasons | Export-Csv -Path "$resourceGroup.ResourceGroupName-compliance.csv" -NoTypeInformation
}
-
Explanation:
- Creates a COM object to interact with your CSPM tool (replace
<YourCSPMComObject>
with your specific CSPM tool's COM object name). - Retrieves all Azure resource groups using
Get-AzResourceGroup
. - Iterates over each resource group and calls a method (e.g.,
AssessCompliance
) on the CSPM tool object to assess compliance against your chosen standard (replace<YourComplianceStandard>
with the actual standard name). - Exports the compliance results to a CSV file for each resource group.
- Creates a COM object to interact with your CSPM tool (replace
2. Identify Misconfigured Cloud Resources:
$cspmTool = New-Object -ComObject <YourCSPMComObject>
$misconfigurations = $cspmTool.GetMisconfigurations() # Assumes a method in your CSPM tool API
$misconfigurations | Select-Object ResourceId, ResourceType, MisconfigurationType, Severity, Recommendation | Export-Csv -Path "misconfigurations.csv" -NoTypeInformation
-
Explanation:
- Creates a COM object for your CSPM tool.
- Calls a method (e.g.,
GetMisconfigurations
) on the tool object to retrieve a list of misconfigured resources. - Selects relevant details about each misconfiguration (resource ID, type, misconfiguration type, severity, recommendation).
- Exports the misconfiguration details to a CSV file.
3. Remediate Cloud Security Risks Automatically:
$cspmTool = New-Object -ComObject <YourCSPMComObject>
$misconfigurations = $cspmTool.GetMisconfigurations()
foreach ($misconfiguration in $misconfigurations) {
if ($misconfiguration.Severity -eq "High" -and $misconfiguration.RemediationType -eq "Automatic") {
$result = $cspmTool.RemediateMisconfiguration($misconfiguration.ResourceId)
if ($result.Success) {
Write-Output "Remediated misconfiguration for $($misconfiguration.ResourceId)"
} else {
Write-Warning "Failed to remediate misconfiguration for $($misconfiguration.ResourceId): $($result.ErrorMessage)"
}
}
}
-
Explanation:
- Creates a COM object for your CSPM tool.
- Retrieves misconfigurations.
- Iterates through misconfigurations, filtering for high-severity issues with automatic remediation options.
- Attempts to remediate each eligible misconfiguration using a method (e.g.,
RemediateMisconfiguration
) on the CSPM tool object. - Logs success or failure messages.
Important Considerations:
-
CSPM Tool: Replace placeholders like
<YourCSPMComObject>
with your specific CSPM tool's COM object name and adjust the method calls (AssessCompliance
,GetMisconfigurations
,RemediateMisconfiguration
) based on your CSPM tool's API. - Permissions: Ensure your PowerShell environment has the necessary permissions to interact with your CSPM tool and Azure resources.
- Customization: Adapt these scripts to your specific CSPM tool's capabilities, compliance standards, and desired remediation actions.
- Error Handling: Implement robust error handling to ensure your automation scripts run reliably.
- Logging: Maintain logs of remediation actions for audit and troubleshooting purposes.
Absolutely! Let's craft PowerShell solutions for your advanced threat detection needs:
1. Detect Mimikatz Attacks Using Sysmon Logs:
Get-WinEvent -LogName "Microsoft-Windows-Sysmon/Operational" | Where-Object {
$_.Id -eq 1 -and # Process creation
($_.Message -like "*lsass.exe*" -or $_.Message -like "*sekurlsa::logonpasswords*")
}
-
Explanation:
- Filters Sysmon events for process creation events (Event ID 1).
- Looks for events where
lsass.exe
is involved (a common target of Mimikatz) or the stringsekurlsa::logonpasswords
(a Mimikatz command) appears.
2. Identify Anomalous PowerShell Script Execution:
Get-WinEvent -LogName "Microsoft-Windows-PowerShell/Operational" | Where-Object {
$_.Id -eq 4104 -and # PowerShell script block execution
($_.Message -notlike "*C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe*" -or # Exclude legitimate paths
$_.Message -match "-enc[odedCommand|rypted]|-EncodedCommand|-EncodedArgument") # Look for encoded commands/arguments
}
-
Explanation:
- Filters PowerShell Operational logs for script block execution events (Event ID 4104).
- Excludes events from the default PowerShell installation path.
- Looks for encoded commands or arguments, which can be a sign of obfuscation.
3. Find Malware Persistence Mechanisms in the Registry:
$persistenceKeys = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run", "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce", "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run", "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
foreach ($key in $persistenceKeys) {
Get-ItemProperty -Path $key | ForEach-Object {
Write-Output "$key : $($_.Name) = $($_.PSObject.Properties.Value)"
}
}
# Optionally, check scheduled tasks and services for suspicious entries
Get-ScheduledTask | Where-Object {$_.State -eq "Ready" -and $_.Actions.Execute -notlike "C:\Windows\System32\*"}
Get-Service | Where-Object {$_.StartType -eq "Automatic" -and $_.PathName -notlike "C:\Windows\System32\*"}
-
Explanation:
- Defines an array of common registry Run keys for persistence.
- Enumerates values in those keys and displays them.
- Additionally, checks for scheduled tasks and services with suspicious executable paths.
4. Analyze Network Traffic for Command and Control (C2) Activity (Using netsh
):
$captureFile = "network_traffic.pcapng"
netsh trace start capture=yes tracefile="$captureFile"
# Let the capture run for a while (e.g., 5 minutes)
Start-Sleep -Seconds 300
netsh trace stop
-
Explanation:
- Captures network traffic using
netsh
and saves it in .pcapng format - Analyzes the capture file with Wireshark or similar tools to look for beaconing patterns, DNS tunneling, or other C2 indicators. You can use the command below to filter for beaconing activity in the captured file:
- Captures network traffic using
tshark -r $captureFile -Y "ip.dst == <suspicious_ip> && tcp.flags.push==1 && tcp.flags.ack==1 && tcp.len == 0 && tcp.analysis.ack_rtt < 0.1"
- Replace
<suspicious_ip>
with the IP address you suspect of being a C2 server.
Key Points:
- Sysmon: Ensure Sysmon is installed and configured on the endpoints you want to monitor.
- Alerting: Integrate these scripts with SIEM or alerting systems to notify security teams of suspicious activity.
- Tuning: Fine-tune detection rules to reduce false positives and improve accuracy.
- Threat Intelligence: Incorporate threat intelligence feeds to identify known malicious indicators and patterns.
- Forensic Analysis: Use these scripts in conjunction with other forensic tools for deeper investigation.
Absolutely! Let's craft PowerShell scripts to boost your security awareness and training initiatives:
1. Simulate Phishing Attacks:
$emailList = Import-Csv "employees.csv"
$phishingUrl = "http://phishing-test.example.com"
$clickTracker = @{} # To track clicks
foreach ($employee in $emailList) {
$emailBody = "Dear $($employee.Name),<br><br>Please click on this link to update your information: <a href='$phishingUrl?id=$($employee.EmployeeId)'>Click Here</a>"
Send-MailMessage -To $employee.Email -Subject "Important Notice" -Body $emailBody -BodyAsHtml -SmtpServer "<your_smtp_server>"
$clickTracker[$employee.EmployeeId] = $false # Initialize click status
}
# Set up a web server (e.g., IIS) to log clicks and update $clickTracker accordingly
# ...
# Generate report after a specific time (e.g., one week)
$report = $emailList | Select-Object Name, Email, @{ Name = "Clicked Link"; Expression = { $clickTracker[$_.EmployeeId] } }
$report | Export-Csv -Path "phishing_report.csv" -NoTypeInformation
-
Explanation:
- Reads employee details from a CSV file.
- Sends a phishing email to each employee with a unique tracking link.
- Sets up a web server to log clicks on the links and update the
$clickTracker
hashtable. - Generates a report showing who clicked the phishing link.
**$employees = Import-Csv "employees.csv"
$trainingTemplate = Get-Content "training_template.html"
foreach ($employee in $employees) {
$personalizedContent = $trainingTemplate -replace "", $employee.Name -replace "<Department>", $employee.Department
-replace "", $employee.SpecificRisks
# Save the personalized content to a file or send it via email
# ...
}
* **Explanation:**
* Reads employee details from a CSV file.
* Loads a training template (HTML in this example).
* Replaces placeholders in the template with personalized data for each employee$trainingCompletionData = Get-TrainingCompletionData # Get data from your LMS or database
$quizScores = Get-QuizScores # Get data from your quiz platform
$reportedPhishingAttempts = Get-ReportedPhishingAttempts # Get data from your reporting system
# Analyze data
$completionRate = ($trainingCompletionData.Count / $employees.Count) * 100
$averageQuizScore = ($quizScores | Measure-Object -Property Score -Average).Average
$phishingSuccessRate = ($reportedPhishingAttempts.Count / $phishingEmailsSent.Count) * 100
# Generate report
$report = "Training Completion Rate: $completionRate%`nAverage Quiz Score: $averageQuizScore`nPhishing Success Rate: $phishingSuccessRate%"
Send-MailMessage -To "<recipientEmail>" -Subject "Security Awareness Training Effectiveness Report" -Body $report
-
Explanation:
- Retrieves training completion data, quiz scores, and reported phishing attempts from your relevant data sources.
- Calculates completion rate, average quiz score, and phishing success rate.
- Generates a report summarizing these metrics and sends it via email.
Key Points:
- Customization: Adapt these scripts to your specific security awareness program structure and data sources.
- Ethics: Ensure your phishing simulations are ethical and clearly labeled as tests.
- Data Sources: Integrate with your Learning Management System (LMS), quiz platform, and incident reporting system to gather the necessary data for analysis.
- Reporting: Create visually appealing reports to communicate the effectiveness of your security awareness efforts to stakeholders.
- Continuous Improvement: Use the gathered data to refine your training materials and phishing simulations for better results.