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

SecurityAccess Protocol (SID 0x27)

Csecurity_access.c
/* UDS 0x27: SecurityAccess — 4-step seed-key protocol */
/* Level 1: workshop access (sub-functions 0x01/0x02) */
/* Level 2: reprogramming access (sub-functions 0x03/0x04) */

#include 
#include "Rng.h"
#include "Hsm.h"

typedef struct {
    uint32_t seed;          /* last generated seed */
    uint8_t  fail_count;    /* consecutive wrong-key count */
    uint32_t lockout_timer; /* ticks remaining in lockout */
    boolean  seed_valid;    /* seed was generated and not yet used */
} SecurityState_t;

static SecurityState_t g_sec_state[2];  /* index 0=Level1, index 1=Level2 */

Std_ReturnType SA_RequestSeed(uint8_t level_idx, uint8_t *seed_out, uint16_t *seed_len)
{
    SecurityState_t *state = &g_sec_state[level_idx];

    /* Check: not in lockout */
    if (state->lockout_timer > 0u) {
        return E_NOT_OK;  /* NRC 0x37: requiredTimeDelayNotExpired */
    }

    /* Already unlocked at this level? Return all zeros (seed = 0 means already unlocked) */
    if (Dcm_GetSecurityLevel() >= (level_idx + 1u)) {
        seed_out[0]=0; seed_out[1]=0; seed_out[2]=0; seed_out[3]=0;
        *seed_len = 4u;
        return E_OK;
    }

    /* Generate random seed via TRNG (hardware random number generator) */
    state->seed = Rng_GetRandom32();
    state->seed_valid = TRUE;

    seed_out[0] = (uint8_t)(state->seed >> 24u);
    seed_out[1] = (uint8_t)(state->seed >> 16u);
    seed_out[2] = (uint8_t)(state->seed >>  8u);
    seed_out[3] = (uint8_t)(state->seed);
    *seed_len = 4u;
    return E_OK;
}

Std_ReturnType SA_VerifyKey(uint8_t level_idx, const uint8_t *key_in, uint16_t key_len)
{
    SecurityState_t *state = &g_sec_state[level_idx];

    if (!state->seed_valid || key_len != 4u) {
        return E_NOT_OK;  /* NRC 0x24: requestSequenceError */
    }
    state->seed_valid = FALSE;

    /* Compute expected key from seed */
    uint32_t expected_key = SA_ComputeKey(state->seed, level_idx);
    uint32_t received_key = ((uint32_t)key_in[0] << 24u) | ((uint32_t)key_in[1] << 16u)
                           | ((uint32_t)key_in[2] <<  8u) |  (uint32_t)key_in[3];

    if (received_key != expected_key) {
        state->fail_count++;
        if (state->fail_count >= 5u) {
            state->lockout_timer = LOCKOUT_10MIN_TICKS;  /* NRC 0x37 for 10 min */
            state->fail_count = 0u;
        }
        return E_NOT_OK;  /* NRC 0x35: invalidKey */
    }

    state->fail_count = 0u;
    Dcm_SetSecurityLevel(level_idx + 1u);
    return E_OK;
}

Key Computation: HMAC-SHA256 (Production)

Ckey_algorithm.c
/* Production key algorithm: HMAC-SHA256 with HSM-stored secret */
/* NEVER use XOR or simple arithmetic in production — trivially reverse-engineered */

#include "Hsm.h"

/* Key derivation: HMAC-SHA256(secret_key, seed || ECU_serial || session_level) */
/* secret_key stored in HSM OTP — never accessible to software */

uint32_t SA_ComputeKey(uint32_t seed, uint8_t level)
{
    uint8_t input[9];
    input[0] = (uint8_t)(seed >> 24u);
    input[1] = (uint8_t)(seed >> 16u);
    input[2] = (uint8_t)(seed >>  8u);
    input[3] = (uint8_t) seed;
    input[4] = (uint8_t)(ECU_SERIAL >> 24u);
    input[5] = (uint8_t)(ECU_SERIAL >> 16u);
    input[6] = (uint8_t)(ECU_SERIAL >>  8u);
    input[7] = (uint8_t) ECU_SERIAL;
    input[8] = level;

    uint8_t hmac[32];  /* 256-bit HMAC output */
    Hsm_ComputeHmacSha256(HSM_KEY_SLOT_SA_LEVEL1 + level,
                           input, sizeof(input),
                           hmac);

    /* Truncate to 4 bytes (32 bits) for wire format */
    return ((uint32_t)hmac[0] << 24u) | ((uint32_t)hmac[1] << 16u)
           | ((uint32_t)hmac[2] <<  8u) |  (uint32_t)hmac[3];
}

/* Development alternative (NEVER production): simple XOR for lab testing */
uint32_t SA_ComputeKey_Dev(uint32_t seed, uint8_t level)
{
    (void)level;
    return seed ^ 0xDEADC0DEu;  /* trivially broken — for lab only */
}

/* Workshop tester: runs same HMAC algorithm on PC */
/* OEM distributes key DLL/library to authorised workshop tools */
/* Seed → key computation happens on tester side, not shared as algorithm 

Failed Attempt Lockout (NRC 0x36 and 0x37)

AttemptNRC ReturnedState Change
Attempt 1–4 (wrong key)0x35 invalidKeyfail_count incremented
Attempt 5 (wrong key)0x36 exceededNumberOfAttemptsfail_count=5; lockout_timer = 10 min
Any request during lockout0x37 requiredTimeDelayNotExpiredlockout_timer decremented each second
After lockout expires0x27 0x01 seed available againfail_count reset to 0
ECU reset during lockoutLockout MUST persist (stored in NvM)fail_count + lockout_timer written to NvM before reset

Summary

SecurityAccess is the primary barrier preventing unauthorised ECU reprogramming. HMAC-SHA256 with HSM-stored secret is mandatory for production — the secret key never leaves the HSM, and the key computation is performed inside the hardware security boundary. The tester-side key computation uses the same HMAC algorithm with the same secret (distributed to authorised tools via OEM key DLL), which means the security level is only as strong as the key distribution control. Lockout persistence across resets (NvM storage) is a mandatory requirement — without it, an attacker can simply reset the ECU after every 5 failed attempts to reset the counter.

🔬 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.

← PreviousDiagnosticSessionControl & ECUResetNext →RequestDownload & TransferData