Dynamic Threat Simulation with Markov Chains
Key Features:
Wiki topics:
🔒 · Cybersecurity
Dynamic Threat Simulation with Markov Chains
Dynamic Threat Simulation with Markov Chains
python
# Filename: dynamic_threat_simulation.py
# Dynamic Threat Simulation using Markov Chains and Vulnerability Analysis
# Author: Gerard King
# Website: www.gerardking.dev
# Donate to Dev: Ethereum Address: 0xc637a25e49bb3814f26952fbe81ff18cf81aa1da
# Date: 2024-08-20
# Description:
# This script simulates an attacker’s movements in a network using Markov Chains. It predicts the likelihood of reaching vulnerable nodes over time, combining probabilistic modeling with matrix operations.
# Use Cases:
# 1. Threat Prediction: Estimate where attackers are most likely to target next.
# 2. Defense Planning: Adjust defenses based on predicted attack paths.
# 3. Risk Assessment: Identify high-risk nodes that attackers are likely to focus on.
# Instructions:
# 1. Run the script to visualize dynamic attack paths based on Markov Chain simulations.
# 2. Adjust the number of iterations to simulate longer or shorter attack sequences.
# Tags:
# - #DynamicSimulation
# - #MarkovChains
# - #ThreatModeling
# - #PredictiveAnalysis
# - #CyberSecurity
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import random
# Nodes and their connections
nodes = ['A', 'B', 'C', 'D', 'E']
edges = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E')]
# Create the graph
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
# Assign random vulnerability scores to each node (0 to 10, with 10 being the most vulnerable)
vulnerability_scores = {node: random.randint(1, 10) for node in nodes}
# Display the vulnerability scores
print("Node Vulnerability Scores:")
for node, score in vulnerability_scores.items():
print(f"Node {node}: {score}")
# Generate Markov transition matrix based on edge probabilities
transition_matrix = np.zeros((len(nodes), len(nodes)))
for i, node1 in enumerate(nodes):
neighbors = list(G.neighbors(node1))
if neighbors:
for neighbor in neighbors:
j = nodes.index(neighbor)
transition_matrix[i, j] = 1 / len(neighbors)
# Normalize rows to make them valid probabilities
for i in range(len(nodes)):
transition_matrix[i] /= transition_matrix[i].sum()
# Simulate the attacker's movements over a number of iterations
iterations = 10
current_state = 0 # Start at Node A (index 0)
state_history = [current_state]
for _ in range(iterations):
current_state = np.random.choice(range(len(nodes)), p=transition_matrix[current_state])
state_history.append(current_state)
# Convert states back to node labels for visualization
state_history_labels = [nodes[state] for state in state_history]
# Plotting the Markov Chain transitions
plt.figure(figsize=(12, 6))
# Subplot 1: Network Graph with Vulnerability Scores
plt.subplot(1, 2, 1)
pos = nx.spring_layout(G)
node_colors = [vulnerability_scores[node] for node in nodes]
nx.draw_networkx(G, pos, with_labels=True, node_color=node_colors, node_size=2000, cmap='Reds', font_size=14, font_weight='bold')
labels = {node: f"{node}\n(Vuln: {vulnerability_scores[node]})" for node in nodes}
nx.draw_networkx_labels(G, pos, labels=labels, font_color='white')
plt.title("Network Graph with Vulnerability Scores")
# Subplot 2: Markov Chain Transitions
plt.subplot(1, 2, 2)
transition_paths = [f"{state_history_labels[i]} → {state_history_labels[i+1]}" for i in range(len(state_history_labels) - 1)]
for i, path in enumerate(transition_paths):
print(f"Step {i+1}: {path}")
plt.plot(range(len(state_history)), [vulnerability_scores[nodes[s]] for s in state_history], marker='o', color='red')
plt.xticks(range(len(state_history)), state_history_labels)
plt.title("Attacker's Path Based on Markov Chain Simulation")
plt.xlabel("Simulation Step")
plt.ylabel("Vulnerability Score of Visited Node")
plt.tight_layout()
plt.show()
# Final output of the attack path
print("Final Simulated Attack Path:")
print(" → ".join(state_history_labels))
# Tags:
# - #PredictiveModeling
# - #MarkovChains
# - #DynamicThreatSimulation
# - #CyberSecurity
Key Features:
- Markov Chain Transition Matrix: The program models the probabilities of moving from one node to another based on network connections, generating a realistic simulation of an attack.
- Dynamic Path Simulation: Each run generates a different attack sequence, reflecting real-world unpredictability in threat behavior.
- Vulnerability Score Visualization: Tracks the vulnerability levels of nodes visited during the simulation.
- Predictive Analytics: Useful for Red Teaming and defense planning by forecasting the most likely paths an attacker would take.
Instructions:
- The number of iterations can be adjusted to simulate longer or shorter attack sequences.
- The simulation is run multiple times for different outcomes, showing how an attacker might adapt based on random factors.
I’ll now run this program to demonstrate the simulation.
Analyzed
python
Always show details
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import random
# Nodes and their connections
nodes = ['A', 'B', 'C', 'D', 'E']
edges = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E')]
# Create the graph
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
# Assign random vulnerability scores to each node (0 to 10, with 10 being the most vulnerable)
vulnerability_scores = {node: random.randint(1, 10) for node in nodes}
# Generate Markov transition matrix based on edge probabilities
transition_matrix = np.zeros((len(nodes), len(nodes)))
for i, node1 in enumerate(nodes):
neighbors = list(G.neighbors(node1))
if neighbors:
for neighbor in neighbors:
j = nodes.index(neighbor)
transition_matrix[i, j] = 1 / len(neighbors)
# Normalize rows to make them valid probabilities
for i in range(len(nodes)):
transition_matrix[i] /= transition_matrix[i].sum()
# Simulate the attacker's movements over a number of iterations
iterations = 10
current_state = 0 # Start at Node A (index 0)
state_history = [current_state]
for _ in range(iterations):
current_state = np.random.choice(range(len(nodes)), p=transition_matrix[current_state])
state_history.append(current_state)
# Convert states back to node labels for visualization
state_history_labels = [nodes[state] for state in state_history]
# Plotting the Markov Chain transitions
plt.figure(figsize=(12, 6))
# Subplot 1: Network Graph with Vulnerability Scores
plt.subplot(1, 2, 1)
pos = nx.spring_layout(G)
node_colors = [vulnerability_scores[node] for node in nodes]
nx.draw_networkx(G, pos, with_labels=True, node_color=node_colors, node_size=2000, cmap='Reds', font_size=14, font_weight='bold')
labels = {node: f"{node}\n(Vuln: {vulnerability_scores[node]})" for node in nodes}
nx.draw_networkx_labels(G, pos, labels=labels, font_color='white')
plt.title("Network Graph with Vulnerability Scores")
# Subplot 2: Markov Chain Transitions
plt.subplot(1, 2, 2)
plt.plot(range(len(state_history)), [vulnerability_scores[nodes[s]] for s in state_history], marker='o', color='red')
plt.xticks(range(len(state_history)), state_history_labels)
plt.title("Attacker's Path Based on Markov Chain Simulation")
plt.xlabel("Simulation Step")
plt.ylabel("Vulnerability Score of Visited Node")
plt.tight_layout()
plt.show()
# Output the steps of the attack path
transition_paths = [f"{state_history_labels[i]} → {state_history_labels[i+1]}" for i in range(len(state_history_labels) - 1)]
transition_paths, " → ".join(state_history_labels)
Result
(['A → B',
'B → D',
'D → B',
'B → D',
'D → B',
'B → A',
'A → C',
'C → A',
'A → B',
'B → C'],
'A → B → D → B → D → B → A → C → A → B → C')
Attacker’s Path Based on Markov Chain Simulation
The simulation successfully ran and generated the following dynamic attack path:
Steps of the Attack Path:
- A → B
- B → D
- D → B
- B → D
- D → B
- B → A
- A → C
- C → A
- A → B
- B → C
Final Simulated Attack Path:
A → B → D → B → D → B → A → C → A → B → C
This path was generated by simulating the attacker’s movements using a Markov Chain, considering the transition probabilities between nodes. The visualization shows the vulnerability scores of nodes visited in each step.
This dynamic approach offers a powerful way to predict likely attack scenarios and can be extended for further analysis.
메타데이터
- post_id
- 8a7689e0eb34
- slug
- dynamic-threat-simulation-with-markov-chains-8a7689e0eb34
- url
- https://medium.com/aardvark-infinity/dynamic-threat-simulation-with-markov-chains-8a7689e0eb34
- canonical_url
- https://medium.com/aardvark-infinity/dynamic-threat-simulation-with-markov-chains-8a7689e0eb34
- author_url
- https://medium.com/@aardvarkinfinity
- status
- ok
- fetched_at
- 2026-06-22 05:41:33