CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-mitreattack-python

MITRE ATT&CK python library for accessing, querying, and manipulating ATT&CK threat intelligence data.

Pending
Overview
Eval results
Files

navigation-layers.mddocs/

ATT&CK Navigator Layers

Create, manipulate, and export ATT&CK Navigator layer files for data visualization. This module provides comprehensive tools for generating layer files that can be imported into the MITRE ATT&CK Navigator for visual analysis, including programmatic layer creation, SVG export, Excel export, and advanced layer manipulation operations.

Capabilities

Core Layer Management

Main classes for creating and managing ATT&CK Navigator layers.

class Layer:
    def __init__(self, init_data=None, name=None, domain=None, strict=True):
        """
        Create a new ATT&CK Navigator layer.
        
        Args:
            init_data: Optional base Layer JSON or string data on initialization
            name (str, optional): Layer name for display
            domain (str, optional): ATT&CK domain ("enterprise-attack", "mobile-attack", "ics-attack")
            strict (bool): Whether to use strict validation. Defaults to True.
        """
    
    def from_file(self, filepath: str) -> None:
        """
        Load layer from JSON file.
        
        Args:
            filepath (str): Path to layer JSON file
        """
    
    def to_file(self, filepath: str) -> None:
        """
        Save layer to JSON file.
        
        Args:
            filepath (str): Output file path
        """
    
    def to_excel(self, path: str, **kwargs) -> None:
        """
        Export layer to Excel format.
        
        Args:
            path (str): Output Excel file path
            **kwargs: Additional export options
        """
    
    def to_svg(self, path: str, **kwargs) -> None:
        """
        Export layer to SVG format.
        
        Args:
            path (str): Output SVG file path
            **kwargs: SVG formatting options
        """

Layer Component Classes

Classes representing different components of a Navigator layer.

class Technique:
    def __init__(self, techniqueID: str = "", color: str = "", comment: str = "", 
                 enabled: bool = True, score: int = None):
        """
        Individual technique representation in a layer.
        
        Args:
            techniqueID (str): ATT&CK technique ID (e.g., "T1055")
            color (str): Hex color code for visualization
            comment (str): Comment or note for the technique
            enabled (bool): Whether technique is enabled in the layer
            score (int): Numeric score for the technique
        """

class Metadata:
    def __init__(self, name: str = "", value: str = ""):
        """
        Layer metadata key-value pair.
        
        Args:
            name (str): Metadata field name
            value (str): Metadata field value
        """

class Filter:
    def __init__(self, platforms: List[str] = None, stages: List[str] = None):
        """
        Layer filtering options.
        
        Args:
            platforms (List[str]): Platforms to include in layer
            stages (List[str]): Kill chain stages to include
        """

class Gradient:
    def __init__(self, colors: List[str] = None, minValue: float = 0, maxValue: float = 100):
        """
        Color gradient for score-based visualization.
        
        Args:
            colors (List[str]): List of hex color codes
            minValue (float): Minimum score value
            maxValue (float): Maximum score value
        """

class Layout:
    def __init__(self, layout: str = "side", showID: bool = False, showName: bool = True):
        """
        Layer display layout configuration.
        
        Args:
            layout (str): Layout type ("side", "flat", "mini")
            showID (bool): Whether to show technique IDs
            showName (bool): Whether to show technique names
        """

class LegendItem:
    def __init__(self, label: str = "", color: str = ""):
        """
        Legend item for layer visualization.
        
        Args:
            label (str): Legend item label
            color (str): Hex color code
        """

class Link:
    def __init__(self, label: str = "", url: str = ""):
        """
        External link associated with layer.
        
        Args:
            label (str): Link display text
            url (str): Target URL
        """

class Versions:
    def __init__(self, attack: str = "", navigator: str = "", layer: str = ""):
        """
        Version information for layer compatibility.
        
        Args:
            attack (str): ATT&CK version
            navigator (str): Navigator version
            layer (str): Layer format version
        """

Layer Generators

Automated layer generation based on ATT&CK data analysis.

class OverviewLayerGenerator:
    def __init__(self, data: 'MitreAttackData'):
        """
        Generate overview layers showing object type distributions.
        
        Args:
            data (MitreAttackData): ATT&CK data source
        """
    
    def generate_overview_layers(self) -> Dict[str, Layer]:
        """
        Generate overview layers for different object types.
        
        Returns:
            Dict[str, Layer]: Dictionary mapping layer names to Layer objects
        """

class UsageLayerGenerator:
    def __init__(self, data: 'MitreAttackData'):
        """
        Generate layers showing technique usage patterns.
        
        Args:
            data (MitreAttackData): ATT&CK data source
        """
    
    def generate_usage_layers(self, group_filter: List[str] = None) -> Dict[str, Layer]:
        """
        Generate usage-based layers highlighting technique adoption.
        
        Args:
            group_filter (List[str], optional): Filter to specific group IDs
            
        Returns:
            Dict[str, Layer]: Dictionary mapping layer names to Layer objects
        """

Layer Export Classes

Export layers to different formats with customization options.

class ToExcel:
    def __init__(self, layer: Layer, template: str = "default"):
        """
        Excel export functionality for layers.
        
        Args:
            layer (Layer): Layer to export
            template (str): Excel template to use
        """
    
    def export(self, filepath: str, **kwargs) -> None:
        """
        Export layer to Excel file.
        
        Args:
            filepath (str): Output Excel file path
            **kwargs: Additional formatting options
        """

class ToSvg:
    def __init__(self, layer: Layer, config: 'SVGConfig' = None):
        """
        SVG export functionality for layers.
        
        Args:
            layer (Layer): Layer to export
            config (SVGConfig, optional): SVG rendering configuration
        """
    
    def export(self, filepath: str) -> None:
        """
        Export layer to SVG file.
        
        Args:
            filepath (str): Output SVG file path
        """

class SVGConfig:
    def __init__(self, width: int = 1200, height: int = 800, font_size: int = 12):
        """
        Configuration for SVG export formatting.
        
        Args:
            width (int): SVG width in pixels
            height (int): SVG height in pixels
            font_size (int): Text font size
        """

Layer Manipulation

Advanced operations for modifying and combining layers.

class LayerOps:
    @staticmethod
    def merge_layers(layers: List[Layer], merge_technique_scores: str = "max") -> Layer:
        """
        Merge multiple layers into one.
        
        Args:
            layers (List[Layer]): Layers to merge
            merge_technique_scores (str): How to handle score conflicts ("max", "min", "avg")
            
        Returns:
            Layer: Merged layer
        """
    
    @staticmethod
    def filter_layer_by_platforms(layer: Layer, platforms: List[str]) -> Layer:
        """
        Filter layer to show only specified platforms.
        
        Args:
            layer (Layer): Source layer
            platforms (List[str]): Platforms to include
            
        Returns:
            Layer: Filtered layer
        """
    
    @staticmethod
    def apply_colormap(layer: Layer, colormap: Dict[str, str]) -> Layer:
        """
        Apply color mapping to layer techniques.
        
        Args:
            layer (Layer): Layer to colorize
            colormap (Dict[str, str]): Mapping of technique IDs to colors
            
        Returns:
            Layer: Colorized layer
        """

Generator Helper Functions

Utility functions for layer generation workflows.

def remove_revoked_depreciated(stix_objects: List[dict]) -> List[dict]:
    """
    Filter out revoked and deprecated STIX objects.
    
    Args:
        stix_objects (List[dict]): List of STIX objects
        
    Returns:
        List[dict]: Filtered objects
    """

def construct_relationship_mapping(data: 'MitreAttackData', source_type: str, 
                                 target_type: str, relationship_type: str) -> Dict[str, List[str]]:
    """
    Build relationship mapping between ATT&CK objects.
    
    Args:
        data (MitreAttackData): ATT&CK data source
        source_type (str): Source object type
        target_type (str): Target object type  
        relationship_type (str): Relationship type to map
        
    Returns:
        Dict[str, List[str]]: Mapping of source IDs to target ID lists
    """

def get_attack_id(stix_object: dict) -> str:
    """
    Extract ATT&CK ID from STIX object.
    
    Args:
        stix_object (dict): STIX object
        
    Returns:
        str: ATT&CK ID (e.g., "T1055")
    """

def build_data_strings(stix_objects: List[dict], field_name: str) -> List[str]:
    """
    Extract specific field values from STIX objects.
    
    Args:
        stix_objects (List[dict]): List of STIX objects
        field_name (str): Field name to extract
        
    Returns:
        List[str]: List of field values
    """

Exception Classes

Exception types for layer operations and validation.

class InvalidFormat(Exception):
    """Raised when layer format is invalid."""

class BadLambda(Exception):
    """Raised when lambda expression is malformed."""

class MismatchedDomain(Exception):
    """Raised when layer domain doesn't match data domain."""

class BadInput(Exception):
    """Raised when input parameters are invalid."""

class BadType(Exception):
    """Raised when object type is incorrect."""

class UninitializedLayer(Exception):
    """Raised when layer is not properly initialized."""

class UnknownLayerProperty(Exception):
    """Raised when accessing undefined layer property."""

class UnknownTechniqueProperty(Exception):
    """Raised when accessing undefined technique property."""

class MissingParameters(Exception):
    """Raised when required parameters are missing."""

Utility Constants and Functions

UNSETVALUE = "UNSET_VALUE"  # Constant for unset layer values

def handler(exception_type: Exception, message: str) -> None:
    """
    Centralized exception handling.
    
    Args:
        exception_type (Exception): Exception type to raise
        message (str): Error message
    """

def typeChecker(value: object, expected_type: type, field_name: str) -> None:
    """
    Validate object type with descriptive error messages.
    
    Args:
        value (object): Value to check
        expected_type (type): Expected type
        field_name (str): Field name for error context
    """

def categoryChecker(value: str, valid_categories: List[str], field_name: str) -> None:
    """
    Validate value against allowed categories.
    
    Args:
        value (str): Value to check
        valid_categories (List[str]): List of valid values
        field_name (str): Field name for error context
    """

Usage Examples

Basic Layer Creation and Export

from mitreattack.navlayers import Layer, Technique
from mitreattack.stix20 import MitreAttackData

# Create a new layer
layer = Layer(name="Threat Group Analysis", domain="enterprise-attack")

# Add techniques with scores and colors
layer.techniques = [
    Technique(techniqueID="T1055", score=85, color="#ff6b6b", comment="Process Injection"),
    Technique(techniqueID="T1059", score=92, color="#ff8e53", comment="Command and Scripting"),
    Technique(techniqueID="T1083", score=78, color="#ffab00", comment="File Discovery")
]

# Configure layer display
layer.layout.showName = True
layer.layout.showID = True

# Save layer file
layer.to_file("apt29_techniques.json")

# Export to SVG
layer.to_svg("apt29_techniques.svg")

Automated Layer Generation

from mitreattack.navlayers.generators import OverviewLayerGenerator, UsageLayerGenerator
from mitreattack.stix20 import MitreAttackData

# Load ATT&CK data
attack_data = MitreAttackData("enterprise-attack")

# Generate overview layers
overview_gen = OverviewLayerGenerator(attack_data)
overview_layers = overview_gen.generate_overview_layers()

# Save overview layers
for layer_name, layer_obj in overview_layers.items():
    layer_obj.to_file(f"overview_{layer_name}.json")

# Generate usage layers for specific groups
usage_gen = UsageLayerGenerator(attack_data)
usage_layers = usage_gen.generate_usage_layers(group_filter=["G0016", "G0028"])  # APT29, Lazarus

for layer_name, layer_obj in usage_layers.items():
    layer_obj.to_file(f"usage_{layer_name}.json")

Layer Manipulation and Analysis

from mitreattack.navlayers.manipulators import LayerOps
from mitreattack.navlayers import Layer

# Load multiple layers
layer1 = Layer()
layer1.from_file("apt29_layer.json")

layer2 = Layer()  
layer2.from_file("lazarus_layer.json")

# Merge layers
merged_layer = LayerOps.merge_layers([layer1, layer2], merge_technique_scores="max")
merged_layer.name = "Combined Threat Analysis"
merged_layer.to_file("combined_threats.json")

# Filter by platform
windows_layer = LayerOps.filter_layer_by_platforms(merged_layer, ["Windows"])
windows_layer.to_file("windows_threats.json")

# Apply custom color scheme
color_mapping = {
    "T1055": "#ff0000",  # High priority - red
    "T1059": "#ff8800",  # Medium priority - orange  
    "T1083": "#ffff00"   # Low priority - yellow
}
colored_layer = LayerOps.apply_colormap(merged_layer, color_mapping)
colored_layer.to_file("prioritized_threats.json")

CLI Layer Tools

# Generate layers from ATT&CK data
layerGenerator_cli --data-source enterprise-attack --output ./layers/ --type overview

# Generate usage layers for specific groups
layerGenerator_cli --data-source enterprise-attack --groups G0016,G0028 --output ./usage-layers/

# Export layer to different formats  
layerExporter_cli --input my_layer.json --format svg --output my_layer.svg
layerExporter_cli --input my_layer.json --format excel --output my_layer.xlsx

Advanced Layer Customization

from mitreattack.navlayers import Layer, Gradient, Filter, LegendItem

# Create layer with advanced configuration
layer = Layer(name="Detection Coverage Analysis", domain="enterprise-attack")

# Set up color gradient for coverage scores
layer.gradient = Gradient(
    colors=["#ffffff", "#73c6b6", "#2e8b57"],  # White to green gradient
    minValue=0,
    maxValue=100
)

# Configure filtering
layer.filters = Filter(
    platforms=["Windows", "Linux", "macOS"],
    stages=["initial-access", "execution", "persistence"]
)

# Add legend
layer.legendItems = [
    LegendItem(label="High Coverage", color="#2e8b57"),
    LegendItem(label="Medium Coverage", color="#73c6b6"), 
    LegendItem(label="Low Coverage", color="#ffffff")
]

# Set techniques with coverage scores
coverage_data = [
    ("T1055", 85), ("T1059", 92), ("T1083", 45), ("T1105", 78)
]

layer.techniques = [
    Technique(techniqueID=tid, score=score, enabled=True)
    for tid, score in coverage_data
]

layer.to_file("detection_coverage.json")

Install with Tessl CLI

npx tessl i tessl/pypi-mitreattack-python

docs

cli-tools.md

collections.md

excel-export.md

index.md

navigation-layers.md

stix20-data-access.md

version-comparison.md

version-management.md

tile.json