Home Learning Paths ECU Lab Assessments Interview Preparation Arena Pricing Log In Sign Up

Lab Setup

ComponentDetail
ECUAUTOSAR DCM with SecurityAccess Level 1 (0x01/0x02) and Level 2 (0x03/0x04) configured
AlgorithmHMAC-SHA256 truncated to 4 bytes (HSM-backed in real ECU; SW implementation for lab)
Test toolPython + udsoncan; or CANoe CAPL
Lab secret0x01 0x23 0x45 0x67 0x89 0xAB 0xCD 0xEF (lab only; never production!)

Exercise 1: Implement Complete Seed-Key Exchange

Pythonlab_security_access.py
#!/usr/bin/env python3
# SecurityAccess Level 1: seed-key exchange implementation
import udsoncan, hashlib, hmac, struct
from udsoncan.client import Client

LAB_SECRET = bytes.fromhex("0123456789ABCDEF")  # lab only!

def compute_key(seed: bytes) -> bytes:
    # HMAC-SHA256 truncated to 4 bytes
    h = hmac.new(LAB_SECRET, seed, hashlib.sha256)
    return h.digest()[:4]

def do_security_access_level1(client) -> bool:
    # Step 1: request seed (subFunction 0x01)
    resp = client.request_seed(0x01)
    if not resp.positive:
        print(f"RequestSeed failed: NRC 0x{resp.code:02X}"); return False

    seed = resp.service_data.security_seed
    print(f"Seed received: {seed.hex()}")

    # Step 2: compute key
    key = compute_key(seed)
    print(f"Computed key:  {key.hex()}")

    # Step 3: send key (subFunction 0x02)
    resp = client.send_key(0x02, key)
    if resp.positive:
        print("SecurityAccess Level 1: UNLOCKED")
        return True
    else:
        print(f"SendKey failed: NRC 0x{resp.code:02X}")
        return False

# Usage:
# client.change_session(udsoncan.services.DiagnosticSessionControl.Session.extendedDiagnosticSession)
# success = do_security_access_level1(client)
# if success: client.write_data_by_identifier(0x0101, bytes([0x05]))

Exercise 2: Verify Lockout Behaviour

Pythonlab_lockout.py
#!/usr/bin/env python3
# Verify lockout: 5 wrong keys → NRC 0x36; then NRC 0x37 during delay
import udsoncan, time
from udsoncan.client import Client

def test_lockout_behaviour(client):
    client.change_session(udsoncan.services.DiagnosticSessionControl.Session.extendedDiagnosticSession)

    # Attempt 1–5: send wrong key each time
    for attempt in range(1, 6):
        resp = client.request_seed(0x01)
        seed = resp.service_data.security_seed
        wrong_key = bytes([0xFF, 0xFF, 0xFF, 0xFF])  # deliberately wrong

        resp = client.send_key(0x02, wrong_key)
        print(f"Attempt {attempt}: NRC 0x{resp.code:02X} ", end="")
        if resp.code == 0x35:
            print("(invalidKey - expected)")
        elif resp.code == 0x36:
            print("(exceededNumberOfAttempts - LOCKOUT TRIGGERED)")
            break

    # Attempt during lockout: expect NRC 0x37
    try:
        resp = client.request_seed(0x01)
        if resp.code == 0x37:
            print("During lockout: NRC 0x37 (requiredTimeDelayNotExpired) - CORRECT")
        else:
            print(f"FAIL: expected NRC 0x37 during lockout, got 0x{resp.code:02X}")
    except Exception as e:
        print(f"Exception during lockout test: {e}")

    # Verify lockout persists after ECU reset
    client.ecu_reset(0x01)  # soft reset
    time.sleep(2)
    client.change_session(udsoncan.services.DiagnosticSessionControl.Session.extendedDiagnosticSession)
    resp = client.request_seed(0x01)
    if resp.code == 0x37:
        print("PASS: lockout persists after ECU reset (NvM-stored lockout counter)")
    else:
        print("FAIL: lockout should persist after reset")

Exercise 3: Security Level Boundary Tests

Pythonlab_security_boundaries.py
#!/usr/bin/env python3
# Verify service access requires correct security level
import udsoncan
from udsoncan.client import Client

def run_boundary_tests(client):
    results = []

    # Test 1: Write DID without SecurityAccess → NRC 0x33
    client.change_session(udsoncan.services.DiagnosticSessionControl.Session.extendedDiagnosticSession)
    try:
        client.write_data_by_identifier(0x0101, bytes([0x05]))
        results.append(("FAIL", "Write without security should return NRC 0x33"))
    except udsoncan.exceptions.NegativeResponseException as e:
        results.append(("PASS" if e.response.code == 0x33 else "FAIL",
                        f"WriteDID without security → NRC 0x{e.response.code:02X}"))

    # Test 2: Level 2 service (RoutineControl EraseMemory) with only Level 1 → NRC 0x33
    # (After doing Level 1 SecurityAccess)
    # do_security_access_level1(client)
    # try:
    #     client.routine_control(...)  # Level 2 routine
    # except NegativeResponseException as e:
    #     results.append(("PASS" if e.response.code == 0x33 else "FAIL",
    #                     "Level 2 routine with Level 1 access"))

    # Test 3: RequestDownload in ExtendedDiag (wrong session) → NRC 0x25
    try:
        client.request_download(0x00, bytes([0x80, 0x00, 0x00, 0x00]), bytes([0x00, 0x01, 0x00, 0x00]))
        results.append(("FAIL", "RequestDownload in Extended should return NRC 0x25"))
    except udsoncan.exceptions.NegativeResponseException as e:
        results.append(("PASS" if e.response.code == 0x25 else "FAIL",
                        f"RequestDownload in ExtDiag → NRC 0x{e.response.code:02X}"))

    for status, desc in results:
        print(f"[{status}] {desc}")

Summary

The seed-key exchange implementation in Exercise 1 demonstrates the exact protocol flow that a production workshop tool follows. The lockout test in Exercise 2 is critical for UNECE R155 compliance — an ECU without brute-force protection on SecurityAccess is a cybersecurity finding. The boundary matrix tests in Exercise 3 create a reusable security regression suite: any change to DCM ARXML security configuration should be retested against this boundary matrix to catch regressions where a service accidentally becomes accessible at a lower security level than intended.

🔬 Deep Dive — Core Concepts Expanded

This section builds on the foundational concepts covered above with additional technical depth, edge cases, and configuration nuances that separate competent engineers from experts. When working on production ECU projects, the details covered here are the ones most commonly responsible for integration delays and late-phase defects.

Key principles to reinforce:

  • Configuration over coding: In AUTOSAR and automotive middleware environments, correctness is largely determined by ARXML configuration, not application code. A correctly implemented algorithm can produce wrong results due to a single misconfigured parameter.
  • Traceability as a first-class concern: Every configuration decision should be traceable to a requirement, safety goal, or architecture decision. Undocumented configuration choices are a common source of regression defects when ECUs are updated.
  • Cross-module dependencies: In tightly integrated automotive software stacks, changing one module's configuration often requires corresponding updates in dependent modules. Always perform a dependency impact analysis before submitting configuration changes.

🏭 How This Topic Appears in Production Projects

  • Project integration phase: The concepts covered in this lesson are most commonly encountered during ECU integration testing — when multiple software components from different teams are combined for the first time. Issues that were invisible in unit tests frequently surface at this stage.
  • Supplier/OEM interface: This is a topic that frequently appears in technical discussions between Tier-1 ECU suppliers and OEM system integrators. Engineers who can speak fluently about these details earn credibility and are often brought into critical design review meetings.
  • Automotive tool ecosystem: Vector CANoe/CANalyzer, dSPACE tools, and ETAS INCA are the standard tools used to validate and measure the correct behaviour of the systems described in this lesson. Familiarity with these tools alongside the conceptual knowledge dramatically accelerates debugging in real projects.

⚠️ Common Mistakes and How to Avoid Them

  1. Assuming default configuration is correct: Automotive software tools ship with default configurations that are designed to compile and link, not to meet project-specific requirements. Every configuration parameter needs to be consciously set. 'It compiled' is not the same as 'it is correctly configured'.
  2. Skipping documentation of configuration rationale: In a 3-year ECU project with team turnover, undocumented configuration choices become tribal knowledge that disappears when engineers leave. Document why a parameter is set to a specific value, not just what it is set to.
  3. Testing only the happy path: Automotive ECUs must behave correctly under fault conditions, voltage variations, and communication errors. Always test the error handling paths as rigorously as the nominal operation. Many production escapes originate in untested error branches.
  4. Version mismatches between teams: In a multi-team project, the BSW team, SWC team, and system integration team may use different versions of the same ARXML file. Version management of all ARXML files in a shared repository is mandatory, not optional.

📊 Industry Note

Engineers who master both the theoretical concepts and the practical toolchain skills covered in this course are among the most sought-after professionals in the automotive software industry. The combination of AUTOSAR standards knowledge, safety engineering understanding, and hands-on configuration experience commands premium salaries at OEMs and Tier-1 suppliers globally.

← PreviousSecurity Levels & Access RightsNext →Reprogramming Sequence Overview