6.2: SEC.2 Cybersecurity Implementation


Process Definition

Standards Note: SEC.2 in ASPICE CS-PAM is "Cybersecurity Implementation" - refining design to implement cybersecurity requirements. The TARA methodology covered later in this chapter aligns with ISO/SAE 21434 Clause 8 (Threat Analysis and Risk Assessment), which provides inputs to SEC.2 implementation activities.

Purpose

SEC.2 Purpose: To refine the design of the system, software, and hardware consistent with the cybersecurity requirements and ensure they are implemented.

Outcomes

Outcome Description
O1 Architecture is refined to address cybersecurity requirements
O2 Consistency and traceability established between requirements and architecture
O3 Appropriate cybersecurity controls are selected
O4 Architecture weaknesses are analyzed
O5 Detailed design is refined for cybersecurity
O6 Consistency and traceability established between architecture and detailed design
O7 Agreed cybersecurity implementation is communicated

Base Practices with AI Integration

BP Base Practice AI Level AI Application
BP1 Refine architecture details L1-L2 Architecture pattern suggestions
BP2 Ensure consistency and traceability (requirements) L2 Trace link generation
BP3 Select cybersecurity controls L1-L2 Control recommendation
BP4 Analyze architecture for weaknesses L2 Vulnerability detection
BP5 Refine detailed design L2 Secure design patterns
BP6 Ensure consistency and traceability (design) L2 Design trace generation
BP7 Communicate implementation results L2 Report generation

TARA Methodology (ISO/SAE 21434 Input)

Note: TARA (Threat Analysis and Risk Assessment) per ISO/SAE 21434 Clause 8 provides essential inputs for SEC.2 implementation decisions. The risk treatment decisions from TARA inform which cybersecurity controls to implement.


TARA Methodology

The diagram below illustrates the Threat Analysis and Risk Assessment (TARA) methodology per ISO/SAE 21434, showing the flow from asset identification through threat scenarios, attack feasibility, risk determination, and treatment decisions.

TARA Methodology


AI-Powered Attack Tree Generation

Attack Tree Analyzer

"""
AI-assisted attack tree generation for automotive systems.
"""

from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
from enum import Enum

class NodeType(Enum):
    AND = "AND"
    OR = "OR"
    LEAF = "LEAF"

class AttackFeasibility(Enum):
    HIGH = 4      # Easy for average attacker
    MEDIUM = 3    # Requires some expertise
    LOW = 2       # Requires significant expertise
    VERY_LOW = 1  # Requires expert knowledge + special equipment

@dataclass
class AttackTreeNode:
    """Node in an attack tree."""
    id: str
    name: str
    node_type: NodeType
    description: str
    children: List['AttackTreeNode'] = field(default_factory=list)

    # For leaf nodes
    elapsed_time: Optional[str] = None
    expertise: Optional[str] = None
    knowledge: Optional[str] = None
    equipment: Optional[str] = None
    window: Optional[str] = None
    feasibility: Optional[AttackFeasibility] = None

@dataclass
class AttackPath:
    """Complete attack path from root to leaf."""
    path_id: str
    nodes: List[str]
    total_feasibility: AttackFeasibility
    impact: str
    risk_level: str


class AttackTreeGenerator:
    """AI-assisted attack tree generation.

    Note: Attack patterns database should be updated regularly;
    consider integration with MITRE ATT&CK automotive framework.
    """

    def __init__(self):
        self.attack_patterns = self._load_attack_patterns()

    def _load_attack_patterns(self) -> Dict:
        """Load automotive attack patterns database."""
        return {
            'can_injection': {
                'root': "Inject malicious CAN message",
                'sub_goals': [
                    {
                        'type': NodeType.OR,
                        'name': "Gain CAN bus access",
                        'children': [
                            {'name': "Physical OBD-II access", 'feasibility': AttackFeasibility.HIGH},
                            {'name': "Compromise gateway ECU", 'feasibility': AttackFeasibility.LOW},
                            {'name': "Through infotainment system", 'feasibility': AttackFeasibility.MEDIUM}
                        ]
                    },
                    {
                        'type': NodeType.OR,
                        'name': "Craft valid message",
                        'children': [
                            {'name': "Reverse engineer protocol", 'feasibility': AttackFeasibility.MEDIUM},
                            {'name': "Obtain DBC file", 'feasibility': AttackFeasibility.MEDIUM},
                            {'name': "Replay captured message", 'feasibility': AttackFeasibility.HIGH}
                        ]
                    }
                ]
            },
            'key_extraction': {
                'root': "Extract cryptographic key",
                'sub_goals': [
                    {
                        'type': NodeType.OR,
                        'name': "Access key storage",
                        'children': [
                            {'name': "Dump firmware via JTAG", 'feasibility': AttackFeasibility.LOW},
                            {'name': "Side-channel attack on HSM", 'feasibility': AttackFeasibility.VERY_LOW},
                            {'name': "Exploit software vulnerability", 'feasibility': AttackFeasibility.MEDIUM}
                        ]
                    }
                ]
            },
            'denial_of_service': {
                'root': "Cause denial of service",
                'sub_goals': [
                    {
                        'type': NodeType.OR,
                        'name': "Disable ECU function",
                        'children': [
                            {'name': "CAN bus flooding", 'feasibility': AttackFeasibility.HIGH},
                            {'name': "Trigger bus-off condition", 'feasibility': AttackFeasibility.MEDIUM},
                            {'name': "Exhaust resources", 'feasibility': AttackFeasibility.MEDIUM}
                        ]
                    }
                ]
            }
        }

    def generate_attack_tree(self, threat_scenario: str, asset: str) -> AttackTreeNode:
        """Generate attack tree for a threat scenario."""

        # Map threat to attack pattern
        pattern = self._select_pattern(threat_scenario)

        # Build tree structure
        root = AttackTreeNode(
            id="AT-ROOT",
            name=pattern['root'],
            node_type=NodeType.AND,
            description=f"Attack goal: {threat_scenario} on {asset}"
        )

        # Add sub-goals
        for i, sub_goal in enumerate(pattern['sub_goals']):
            sub_node = AttackTreeNode(
                id=f"AT-{i+1}",
                name=sub_goal['name'],
                node_type=sub_goal['type'],
                description=f"Sub-goal {i+1}"
            )

            # Add leaf nodes
            for j, child in enumerate(sub_goal['children']):
                leaf = AttackTreeNode(
                    id=f"AT-{i+1}-{j+1}",
                    name=child['name'],
                    node_type=NodeType.LEAF,
                    description=f"Attack step",
                    feasibility=child['feasibility'],
                    expertise=self._map_expertise(child['feasibility']),
                    equipment=self._map_equipment(child['feasibility'])
                )
                sub_node.children.append(leaf)

            root.children.append(sub_node)

        return root

    def _select_pattern(self, threat_scenario: str) -> Dict:
        """Select appropriate attack pattern."""
        scenario_lower = threat_scenario.lower()

        if 'inject' in scenario_lower or 'forge' in scenario_lower:
            return self.attack_patterns['can_injection']
        elif 'key' in scenario_lower or 'crypto' in scenario_lower:
            return self.attack_patterns['key_extraction']
        elif 'denial' in scenario_lower or 'dos' in scenario_lower:
            return self.attack_patterns['denial_of_service']
        else:
            return self.attack_patterns['can_injection']

    def _map_expertise(self, feasibility: AttackFeasibility) -> str:
        """Map feasibility to required expertise."""
        mapping = {
            AttackFeasibility.HIGH: "Layman",
            AttackFeasibility.MEDIUM: "Proficient",
            AttackFeasibility.LOW: "Expert",
            AttackFeasibility.VERY_LOW: "Multiple experts"
        }
        return mapping[feasibility]

    def _map_equipment(self, feasibility: AttackFeasibility) -> str:
        """Map feasibility to required equipment."""
        mapping = {
            AttackFeasibility.HIGH: "Standard",
            AttackFeasibility.MEDIUM: "Specialized",
            AttackFeasibility.LOW: "Bespoke",
            AttackFeasibility.VERY_LOW: "Multiple bespoke"
        }
        return mapping[feasibility]

    def calculate_path_feasibility(self, path: List[AttackTreeNode]) -> AttackFeasibility:
        """Calculate overall feasibility for an attack path."""

        # For AND nodes, use minimum feasibility (hardest step)
        # For OR nodes, use maximum feasibility (easiest path)
        feasibilities = [node.feasibility.value for node in path
                        if node.feasibility is not None]

        if not feasibilities:
            return AttackFeasibility.MEDIUM

        # Simplified: return minimum (most difficult step determines path difficulty)
        min_val = min(feasibilities)
        return AttackFeasibility(min_val)

    def enumerate_attack_paths(self, root: AttackTreeNode) -> List[AttackPath]:
        """Enumerate all attack paths in tree."""

        paths = []

        def traverse(node: AttackTreeNode, current_path: List[str]):
            current_path.append(node.id)

            if node.node_type == NodeType.LEAF:
                paths.append(current_path.copy())
            else:
                if node.node_type == NodeType.AND:
                    # Must traverse all children
                    for child in node.children:
                        traverse(child, current_path.copy())
                else:  # OR
                    # Each child is a separate path
                    for child in node.children:
                        traverse(child, current_path.copy())

            current_path.pop()

        traverse(root, [])

        return [AttackPath(
            path_id=f"PATH-{i+1:03d}",
            nodes=path,
            total_feasibility=AttackFeasibility.MEDIUM,  # Simplified
            impact="TBD",
            risk_level="TBD"
        ) for i, path in enumerate(paths)]


def generate_attack_tree_diagram(root: AttackTreeNode) -> str:
    """Generate text-based attack tree diagram."""

    lines = []
    lines.append(f"Attack Tree: {root.name}")
    lines.append("=" * 60)

    def render_node(node: AttackTreeNode, indent: int = 0):
        prefix = "  " * indent
        type_symbol = {"AND": "∧", "OR": "∨", "LEAF": "●"}[node.node_type.value]

        line = f"{prefix}{type_symbol} {node.name}"
        if node.feasibility:
            line += f" [Feasibility: {node.feasibility.name}]"
        lines.append(line)

        for child in node.children:
            render_node(child, indent + 1)

    render_node(root)

    return "\n".join(lines)

Risk Assessment Matrix

ISO 21434 Risk Matrix

The following diagram visualizes the cybersecurity risk matrix, mapping attack feasibility against impact severity to determine the resulting risk level and corresponding Cybersecurity Assurance Level (CAL).

Cybersecurity Risk Matrix

Risk Matrix:

Impact High Feas. Medium Feas. Low Feas. Very Low Feas.
Severe R5 (CAL 4) R4 (CAL 4) R3 (CAL 3) R2 (CAL 3)
Major R4 (CAL 4) R3 (CAL 3) R2 (CAL 2) R1 (CAL 2)
Moderate R3 (CAL 3) R2 (CAL 2) R1 (CAL 1) R1 (CAL 1)
Minor R2 (CAL 2) R1 (CAL 1) R1 (CAL 1) R1 (CAL 1)
Negligible R1 (CAL 1) R1 (CAL 1) R1 (CAL 1) R1 (CAL 1)

Risk Treatment Record

Treatment Template

Note: Dates shown are illustrative; actual records use project-specific dates.

# Risk Treatment Record (illustrative example)
risk_treatment:
  id: RT-BCM-001
  threat_scenario: THR-CAN-001
  asset: Door Lock Control
  date: (assessment date)

  risk_assessment:
    attack_path: "OBD-II → CAN injection → Door unlock"
    attack_feasibility: high
    impact_rating: major
    impact_justification: |
      Unauthorized vehicle access could lead to:
      - Theft of vehicle contents
      - Vehicle theft (if combined with immobilizer bypass)
      - Privacy violation
    risk_level: R4
    cal_assignment: CAL 4

  treatment_decision:
    option: mitigate
    rationale: |
      Risk level R4 is above acceptance threshold (R2).
      Mitigation is feasible with SecOC implementation.

  treatment_measures:
    measure_1:
      id: TM-001
      description: "Implement SecOC message authentication"
      cybersecurity_goal: CSG-001
      reduces: attack_feasibility
      residual_feasibility: low
      implementation:
        requirement: CSR-BCM-001
        component: BCM_Security_Module

    measure_2:
      id: TM-002
      description: "Implement message freshness counter"
      cybersecurity_goal: CSG-001
      reduces: attack_feasibility
      residual_feasibility: low
      implementation:
        requirement: CSR-BCM-002
        component: BCM_Security_Module

    measure_3:
      id: TM-003
      description: "Rate limit diagnostic access"
      cybersecurity_goal: CSG-003
      reduces: attack_feasibility
      residual_feasibility: medium
      implementation:
        requirement: CSR-BCM-006
        component: BCM_Diagnostics

  residual_risk:
    residual_feasibility: low
    residual_impact: major  # unchanged
    residual_risk_level: R2
    residual_cal: CAL 2
    acceptance_status: accepted
    accepted_by: "Security Architect"
    acceptance_date: 2025-01-20
    justification: |
      Residual risk R2 is within acceptable threshold.
      Remaining attack vectors require significant expertise
      and specialized equipment.

  verification:
    verification_method: penetration_test
    test_reference: SEC-PT-001
    verification_status: pass
    verification_date: 2025-02-01

AI Risk Analysis Dashboard

The diagram below presents the AI-powered cybersecurity risk dashboard, aggregating threat status, risk levels, treatment progress, and vulnerability trends into a single view for security management.

Cybersecurity Risk Dashboard


CVSS Scoring Automation

Automated Vulnerability Scoring

The CVSS calculator implementation is presented in logical sections below:

Step 1: Enumerations and Data Classes

"""
CVSS v3.1 scoring automation for cybersecurity risk assessment.
"""

from dataclasses import dataclass
from enum import Enum
from typing import Dict, Tuple

class AttackVector(Enum):
    NETWORK = 0.85
    ADJACENT = 0.62
    LOCAL = 0.55
    PHYSICAL = 0.2

class AttackComplexity(Enum):
    LOW = 0.77
    HIGH = 0.44

class PrivilegesRequired(Enum):
    NONE = 0.85
    LOW = 0.62
    HIGH = 0.27

class UserInteraction(Enum):
    NONE = 0.85
    REQUIRED = 0.62

class Impact(Enum):
    HIGH = 0.56
    LOW = 0.22
    NONE = 0.0

@dataclass
class CVSSMetrics:
    """CVSS v3.1 base metrics."""
    attack_vector: AttackVector
    attack_complexity: AttackComplexity
    privileges_required: PrivilegesRequired
    user_interaction: UserInteraction
    scope_changed: bool
    confidentiality_impact: Impact
    integrity_impact: Impact
    availability_impact: Impact

Step 2: CVSS Calculator Class

class CVSSCalculator:
    """Calculate CVSS v3.1 base scores.

    Note: This calculates base score only; temporal and environmental
    scores require additional context-specific metrics.
    """

    def calculate_base_score(self, metrics: CVSSMetrics) -> Tuple[float, str]:
        """Calculate CVSS base score and severity."""

        # Exploitability sub-score
        exploitability = 8.22 * metrics.attack_vector.value * \
                        metrics.attack_complexity.value * \
                        metrics.privileges_required.value * \
                        metrics.user_interaction.value

        # Impact sub-score
        isc_base = 1 - (1 - metrics.confidentiality_impact.value) * \
                       (1 - metrics.integrity_impact.value) * \
                       (1 - metrics.availability_impact.value)

        if metrics.scope_changed:
            impact = 7.52 * (isc_base - 0.029) - \
                    3.25 * pow(isc_base - 0.02, 15)
        else:
            impact = 6.42 * isc_base

        # Base score
        if impact <= 0:
            base_score = 0.0
        elif metrics.scope_changed:
            base_score = min(1.08 * (impact + exploitability), 10.0)
        else:
            base_score = min(impact + exploitability, 10.0)

        # Round up to 1 decimal
        base_score = round(base_score * 10) / 10

        # Severity rating
        if base_score == 0.0:
            severity = "None"
        elif base_score < 4.0:
            severity = "Low"
        elif base_score < 7.0:
            severity = "Medium"
        elif base_score < 9.0:
            severity = "High"
        else:
            severity = "Critical"

        return base_score, severity

    def analyze_automotive_threat(self, threat_description: str) -> CVSSMetrics:
        """AI-assisted CVSS metric derivation from threat description."""

        # Simplified pattern matching (in production, use NLP/LLM)
        desc_lower = threat_description.lower()

        # Determine attack vector
        if 'remote' in desc_lower or 'network' in desc_lower:
            av = AttackVector.NETWORK
        elif 'adjacent' in desc_lower or 'wireless' in desc_lower:
            av = AttackVector.ADJACENT
        elif 'local' in desc_lower or 'obd' in desc_lower:
            av = AttackVector.LOCAL
        else:
            av = AttackVector.PHYSICAL

        # Determine attack complexity
        if 'easy' in desc_lower or 'simple' in desc_lower:
            ac = AttackComplexity.LOW
        else:
            ac = AttackComplexity.HIGH

        # Determine privileges required
        if 'authenticated' in desc_lower or 'authorized' in desc_lower:
            pr = PrivilegesRequired.LOW
        elif 'admin' in desc_lower or 'privileged' in desc_lower:
            pr = PrivilegesRequired.HIGH
        else:
            pr = PrivilegesRequired.NONE

        # Determine user interaction
        if 'user' in desc_lower and 'click' in desc_lower:
            ui = UserInteraction.REQUIRED
        else:
            ui = UserInteraction.NONE

        # Determine impacts (automotive-specific)
        if 'safety' in desc_lower or 'control' in desc_lower:
            ci = Impact.HIGH
            ii = Impact.HIGH
            ai = Impact.HIGH
            scope_changed = True
        elif 'data' in desc_lower or 'privacy' in desc_lower:
            ci = Impact.HIGH
            ii = Impact.LOW
            ai = Impact.NONE
            scope_changed = False
        else:
            ci = Impact.LOW
            ii = Impact.LOW
            ai = Impact.LOW
            scope_changed = False

        return CVSSMetrics(
            attack_vector=av,
            attack_complexity=ac,
            privileges_required=pr,
            user_interaction=ui,
            scope_changed=scope_changed,
            confidentiality_impact=ci,
            integrity_impact=ii,
            availability_impact=ai
        )

Step 3: Example Usage Function

# Example usage
def score_threat(description: str) -> Dict:
    """Score a threat scenario using CVSS."""

    calc = CVSSCalculator()
    metrics = calc.analyze_automotive_threat(description)
    score, severity = calc.calculate_base_score(metrics)

    return {
        'description': description,
        'cvss_score': score,
        'severity': severity,
        'vector_string': f"AV:{metrics.attack_vector.name[0]}/"
                        f"AC:{metrics.attack_complexity.name[0]}/"
                        f"PR:{metrics.privileges_required.name[0]}/"
                        f"UI:{metrics.user_interaction.name[0]}/"
                        f"S:{'C' if metrics.scope_changed else 'U'}/"
                        f"C:{metrics.confidentiality_impact.name[0]}/"
                        f"I:{metrics.integrity_impact.name[0]}/"
                        f"A:{metrics.availability_impact.name[0]}"
    }

Work Products

WP ID Work Product AI Role
08-52 Threat analysis report Attack tree generation
08-53 Risk treatment plan Treatment recommendations
08-55 Attack feasibility rating CVSS automation
13-53 Risk assessment record Analysis documentation

Summary

SEC.2 Cybersecurity Risk Treatment:

  • AI Level: L1-L2 (AI generates, human decides)
  • Primary AI Value: Attack tree generation, CVSS scoring
  • Human Essential: Risk acceptance, treatment decisions
  • Key Outputs: TARA report, risk treatment records
  • ISO 21434 Alignment: Clause 8 & 9 requirements