sc‐200_Python - itnett/FTD02H-N GitHub Wiki
[python]
For the SC-200 exam, which focuses on Microsoft Security, Compliance, and Identity Fundamentals, I'll create a Python script relevant to cybersecurity. Let's consider a script that can help with basic log analysis, a common task in security operations.
The script will:
- Parse a simple log file.
- Extract key information such as timestamps, IP addresses, and event types.
- Perform basic analysis, like counting occurrences of different event types or detecting suspicious IP addresses.
Here's the Python script:
import re
from collections import Counter
# Function to parse log file
def parse_log(file_path):
with open(file_path, 'r') as file:
logs = file.readlines()
log_data = []
for line in logs:
# Regex to extract timestamp, IP, and event type from log line
match = re.search(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}), (\d+\.\d+\.\d+\.\d+), (.+)', line)
if match:
timestamp, ip_address, event_type = match.groups()
log_data.append((timestamp, ip_address, event_type))
return log_data
# Function to analyze log data
def analyze_logs(log_data):
event_counter = Counter()
ip_counter = Counter()
for timestamp, ip_address, event_type in log_data:
event_counter[event_type] += 1
ip_counter[ip_address] += 1
return event_counter, ip_counter
# Function to detect suspicious IP addresses
def detect_suspicious_ips(ip_counter, threshold=10):
suspicious_ips = [ip for ip, count in ip_counter.items() if count > threshold]
return suspicious_ips
# Example usage
if __name__ == "__main__":
log_file_path = 'path_to_your_log_file.log'
# Parse the log file
logs = parse_log(log_file_path)
# Analyze the logs
event_counts, ip_counts = analyze_logs(logs)
# Detect suspicious IP addresses
suspicious_ips = detect_suspicious_ips(ip_counts)
# Output results
print("Event Counts:")
for event, count in event_counts.items():
print(f"{event}: {count}")
print("\nSuspicious IP Addresses:")
for ip in suspicious_ips:
print(ip)
Explanation:
- parse_log: Reads the log file and extracts the timestamp, IP address, and event type using regular expressions.
- analyze_logs: Analyzes the parsed log data to count the occurrences of each event type and IP address.
- detect_suspicious_ips: Identifies IP addresses with a high number of log entries, which might indicate suspicious activity.
- Example usage: Demonstrates how to use the above functions to parse, analyze, and detect suspicious IPs from a log file.
How to use:
- Replace
'path_to_your_log_file.log'
with the path to your log file. - Run the script to see the counts of different event types and any suspicious IP addresses.
This script provides a foundation for log analysis and can be extended with more sophisticated techniques as needed.
[python]
Given your role as a Microsoft security operations analyst and the need to mitigate threats using various Microsoft Defender products, I will expand the previous script to include integration with Microsoft Sentinel. The script will now query Microsoft Sentinel for security incidents, analyze them, and provide insights that can be used for triage, incident response, and threat hunting.
To achieve this, we will use the Microsoft Sentinel API. Please ensure you have the necessary permissions and API keys configured for accessing Microsoft Sentinel.
Script Overview:
- Authenticate with Microsoft Sentinel: Using Azure AD for secure access.
- Fetch Security Incidents: Query Microsoft Sentinel for recent security incidents.
- Analyze Incidents: Perform basic analysis on the incidents to identify patterns or trends.
- Generate Report: Provide a summary report of the findings.
Here is the enhanced Python script:
import requests
import json
from collections import Counter
# Function to authenticate with Microsoft Sentinel using Azure AD
def authenticate(client_id, client_secret, tenant_id):
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://management.azure.com/.default'
}
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
return response.json()['access_token']
# Function to fetch incidents from Microsoft Sentinel
def fetch_incidents(access_token, subscription_id, resource_group_name, workspace_name):
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.OperationalInsights/workspaces/{workspace_name}/providers/Microsoft.SecurityInsights/incidents?api-version=2020-01-01"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()['value']
# Function to analyze incidents
def analyze_incidents(incidents):
severity_counter = Counter()
status_counter = Counter()
tactics_counter = Counter()
for incident in incidents:
severity_counter[incident['properties']['severity']] += 1
status_counter[incident['properties']['status']] += 1
if 'tactics' in incident['properties']:
for tactic in incident['properties']['tactics']:
tactics_counter[tactic] += 1
return severity_counter, status_counter, tactics_counter
# Example usage
if __name__ == "__main__":
# Replace these values with your Azure AD and Microsoft Sentinel information
CLIENT_ID = 'your_client_id'
CLIENT_SECRET = 'your_client_secret'
TENANT_ID = 'your_tenant_id'
SUBSCRIPTION_ID = 'your_subscription_id'
RESOURCE_GROUP_NAME = 'your_resource_group_name'
WORKSPACE_NAME = 'your_workspace_name'
# Authenticate with Azure AD
access_token = authenticate(CLIENT_ID, CLIENT_SECRET, TENANT_ID)
# Fetch incidents from Microsoft Sentinel
incidents = fetch_incidents(access_token, SUBSCRIPTION_ID, RESOURCE_GROUP_NAME, WORKSPACE_NAME)
# Analyze the incidents
severity_counts, status_counts, tactics_counts = analyze_incidents(incidents)
# Output results
print("Incident Severity Counts:")
for severity, count in severity_counts.items():
print(f"{severity}: {count}")
print("\nIncident Status Counts:")
for status, count in status_counts.items():
print(f"{status}: {count}")
print("\nIncident Tactics Counts:")
for tactic, count in tactics_counts.items():
print(f"{tactic}: {count}")
Explanation:
- authenticate: Authenticates with Azure AD using the provided client ID, client secret, and tenant ID to obtain an access token.
- fetch_incidents: Uses the access token to fetch security incidents from Microsoft Sentinel for the specified subscription, resource group, and workspace.
- analyze_incidents: Analyzes the fetched incidents, counting occurrences by severity, status, and tactics.
- Example usage: Demonstrates how to authenticate, fetch, and analyze incidents from Microsoft Sentinel. Replace the placeholder values with your actual Azure AD and Sentinel details.
Prerequisites:
- Azure AD application with necessary API permissions.
- Microsoft Sentinel workspace configured.
- Python packages:
requests
(install usingpip install requests
).
This script provides a foundational tool for integrating Microsoft Sentinel into your security operations workflow, enabling you to monitor, analyze, and respond to threats more effectively.