UDS: sessions, seed and key, and a protected write
A tester opens an extended session, unlocks an ECU with security access (seed and key), and writes a protected value, with the ECU refusing a wrong key and…
Communication · Advanced
In a real product: End-of-line ECU programming station (Automotive): A station on the assembly line unlocks each ECU and writes its configuration and programming date.
Reading a fault code is harmless, but writing a calibration or reflashing an ECU is not. So UDS guards those services twice. They only work in a non-default session, which falls back to the default one when the tester goes quiet. And they need security access: the ECU sends a random seed, and only a tester that knows the secret algorithm can compute the right key.
The tester on the left unlocks the ECU on the right and writes its programming date (DID F199). The ECU lights LD2 while it is unlocked.
What you'll learn
- Diagnostic Session Control (
10): the default (01) and extended (03) sessions, and the P2 / P2* times in the reply - Security Access (
27): request seed (odd sub-function), send key (the next even one), and the NRCs on the way:24sequence error,35invalid key,36too many attempts,37time delay not expired - Why a protected write is refused with
33(security access denied) until the ECU is unlocked - Tester Present (
3E 80) with the "suppress positive response" bit, and the S3 timer that ends an idle session
How it works
The tester runs through the steps once:
10 03: the ECU enters the extended session and replies50 03 00 32 01 F4. That is P2 = 50 ms, the time it may take to answer, and P2* = 0x01F4 × 10 ms = 5 s, the limit after a "response pending" message.2E F1 99 …: refused with7F 2E 33, because the ECU is still locked.27 01: the ECU answers67 01and a 4-byte random seed.27 02with a wrong key:7F 27 35. The ECU counts the failure and forgets the seed.27 01again for a fresh seed, then27 02with the right key:67 02, unlocked, and LD2 lights.2E F1 99 20 26 11 18: written,6E F1 99. Then22 F1 99reads it back.
The key is seed rotated left by 7 bits, XORed with a secret constant, plus 0x1234. A real ECU uses a much stronger algorithm, often AES with a key from a secure store, but the exchange is the same. After three wrong keys the ECU answers 36 and refuses every seed request with 37 for 10 s, so the key can't be found by trying every value.
Every second the tester sends 3E 80. Bit 7 of the sub-function means "don't reply", so it costs the bus one frame. Without it the ECU's S3 timer runs out after 5 s of silence: it drops back to the default session and locks itself again.
Try this
- Stop the tester present messages (comment out the line in the loop). About 5 s later the ECU prints that the session timed out, and LD2 goes off.
- Make the tester send a wrong key three times: the third answer is
7F 27 36, and the next seed request gets37. - Send
27 02without asking for a seed first and see7F 27 24, request sequence error. - Change
SECRETin only one of the two programs: the keys no longer match.
main.c
// Bare-metal C on the Nucleo-F446RE: no Arduino core and no HAL. CMSIS names every register.
// The TESTER: extended session, security access (seed and key), a protected write and read-back, then tester present.
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"
#define TX_ID 0x7E0
#define RX_ID 0x7E8
#define SECRET 0x5EC12E7Au // shared with the ECU: the "algorithm" behind the key
static volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
static void delay_ms(uint32_t t) { uint32_t s = ms; while (ms - s < t) {} }
int __io_putchar(int ch) {
while (!(USART2->SR & USART_SR_TXE)) {}
USART2->DR = ch;
return ch;
}
// ---- CAN: bxCAN CAN1 on PA11 (RX) and PA12 (TX), 500 kbit/s, polled -------------------------------------------
static int can_init(void) {
CAN1->MCR = CAN_MCR_INRQ;
while (!(CAN1->MSR & CAN_MSR_INAK)) {}
CAN1->BTR = (1u << CAN_BTR_TS2_Pos) | (12u << CAN_BTR_TS1_Pos) | (1u << CAN_BTR_BRP_Pos); // 16 MHz / 32
CAN1->FMR = (14u << CAN_FMR_CAN2SB_Pos) | CAN_FMR_FINIT;
CAN1->FA1R &= ~1u;
CAN1->FS1R |= 1u;
CAN1->FM1R |= 1u; // list mode: only RX_ID passes
CAN1->FFA1R &= ~1u;
CAN1->sFilterRegister[0].FR1 = RX_ID << 21;
CAN1->sFilterRegister[0].FR2 = RX_ID << 21;
CAN1->FA1R |= 1u;
CAN1->FMR &= ~CAN_FMR_FINIT;
CAN1->MCR &= ~CAN_MCR_INRQ;
uint32_t start = ms;
while (CAN1->MSR & CAN_MSR_INAK) if (ms - start > 50) return 0;
return 1;
}
static int can_send(const uint8_t *data, int len) { // 8 bytes, padded with AA
uint8_t f[8];
memset(f, 0xAA, 8);
memcpy(f, data, len);
uint32_t start = ms;
while (!(CAN1->TSR & CAN_TSR_TME0)) {
if (ms - start > 10) { CAN1->TSR = CAN_TSR_ABRQ0; return 0; }
}
CAN_TxMailBox_TypeDef *box = &CAN1->sTxMailBox[0];
box->TIR = TX_ID << CAN_TI0R_STID_Pos;
box->TDTR = 8;
box->TDLR = f[0] | f[1] << 8 | f[2] << 16 | (uint32_t)f[3] << 24;
box->TDHR = f[4] | f[5] << 8 | f[6] << 16 | (uint32_t)f[7] << 24;
box->TIR |= CAN_TI0R_TXRQ;
return 1;
}
static int can_receive(uint8_t *f, uint32_t timeout) {
uint32_t start = ms;
while (!(CAN1->RF0R & CAN_RF0R_FMP0)) if (ms - start >= timeout) return 0;
uint32_t lo = CAN1->sFIFOMailBox[0].RDLR, hi = CAN1->sFIFOMailBox[0].RDHR;
for (int i = 0; i < 4; i++) { f[i] = lo >> (8 * i); f[4 + i] = hi >> (8 * i); }
CAN1->RF0R = CAN_RF0R_RFOM0;
return 1;
}
// ---- ISO-TP (ISO 15765-2): one message each way, as in the ISO-TP project ---------------------------------------
static int isotp_send(const uint8_t *msg, uint16_t len) {
uint8_t f[8];
if (len <= 7) { f[0] = len; memcpy(f + 1, msg, len); return can_send(f, len + 1); }
f[0] = 0x10 | (len >> 8);
f[1] = len & 0xFF;
memcpy(f + 2, msg, 6);
if (!can_send(f, 8)) return 0;
uint16_t sent = 6;
uint8_t sn = 1;
while (sent < len) {
uint8_t fc[8];
do { if (!can_receive(fc, 1000)) return 0; } while ((fc[0] & 0xF0) != 0x30 || (fc[0] & 0x0F) == 1);
if ((fc[0] & 0x0F) != 0) return 0; // overflow
uint32_t stmin = fc[2] <= 0x7F ? fc[2] : 1;
for (uint8_t n = 0; sent < len && (fc[1] == 0 || n < fc[1]); n++) {
if (n) delay_ms(stmin);
uint16_t chunk = len - sent > 7 ? 7 : len - sent;
f[0] = 0x20 | (sn++ & 0x0F);
memcpy(f + 1, msg + sent, chunk);
if (!can_send(f, chunk + 1)) return 0;
sent += chunk;
}
}
return 1;
}
// Waits up to timeout ms for a message; returns its length, or -1.
static int isotp_receive(uint8_t *buf, uint16_t cap, uint32_t timeout) {
uint8_t f[8];
uint32_t start = ms;
for (;;) {
uint32_t spent = ms - start;
if (spent >= timeout || !can_receive(f, timeout - spent)) return -1;
if ((f[0] >> 4) == 0 && (f[0] & 0x0F) && (f[0] & 0x0F) <= 7) {
memcpy(buf, f + 1, f[0] & 0x0F);
return f[0] & 0x0F;
}
if ((f[0] >> 4) != 1) continue;
uint16_t len = (f[0] & 0x0F) << 8 | f[1];
uint8_t fc[3] = { len > cap ? 0x32 : 0x30, 0, 0 }; // block size 0: send it all
can_send(fc, 3);
if (len > cap) return -1;
memcpy(buf, f + 2, 6);
uint16_t got = 6;
uint8_t sn = 1;
while (got < len) {
if (!can_receive(f, 1000) || (f[0] >> 4) != 2 || (f[0] & 0x0F) != (sn++ & 0x0F)) return -1;
uint16_t chunk = len - got > 7 ? 7 : len - got;
memcpy(buf + got, f + 1, chunk);
got += chunk;
}
return len;
}
}
static void setup_board(void) {
SysTick_Config(SystemCoreClock / 1000);
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_CAN1EN;
// PA2, PA3: AF7 (USART2); PA11, PA12: AF9 (CAN1); PA5 (LD2) an output.
GPIOA->MODER = (GPIOA->MODER & ~(0xFu << 4 | 0xFu << 22 | 3u << 10)) | (0xAu << 4) | (0xAu << 22) | (1u << 10);
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFFu << 8)) | (0x77u << 8);
GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(0xFFu << 12)) | (0x99u << 12);
USART2->BRR = SystemCoreClock / 115200;
USART2->CR1 = USART_CR1_TE | USART_CR1_UE;
}
static uint8_t resp[64];
static int request(const uint8_t *req, uint16_t len) {
printf("->");
for (int i = 0; i < len; i++) printf(" %02X", req[i]);
printf("\r\n");
if (!isotp_send(req, len)) { printf(" not sent\r\n"); return -1; }
int n = isotp_receive(resp, sizeof resp, 200);
if (n < 0) { printf(" no response\r\n"); return -1; }
printf("<-");
for (int i = 0; i < n; i++) printf(" %02X", resp[i]);
printf("\r\n");
return n;
}
static uint32_t key_for(uint32_t seed) { return ((seed << 7 | seed >> 25) ^ SECRET) + 0x1234; }
// Asks for a seed and sends the key computed from it, plus a mistake (0 for none).
static int unlock(uint32_t mistake) {
static const uint8_t seed_req[] = { 0x27, 0x01 };
if (request(seed_req, 2) != 6 || resp[0] != 0x67) return 0;
uint32_t seed = (uint32_t)resp[2] << 24 | resp[3] << 16 | resp[4] << 8 | resp[5];
uint32_t key = key_for(seed) + mistake;
uint8_t key_req[6] = { 0x27, 0x02, key >> 24, key >> 16, key >> 8, key };
return request(key_req, 6) == 2 && resp[0] == 0x67;
}
int main(void) {
setup_board();
printf("Tester: %s\r\n", can_init() ? "on the bus" : "no CAN bus");
delay_ms(20);
static const uint8_t extended[] = { 0x10, 0x03 }, read_date[] = { 0x22, 0xF1, 0x99 }, present[] = { 0x3E, 0x80 };
static const uint8_t write_date[] = { 0x2E, 0xF1, 0x99, 0x20, 0x26, 0x11, 0x18 }; // 2026-11-18, in BCD
printf("\r\n1. Extended session\r\n");
request(extended, sizeof extended);
printf("\r\n2. Write the programming date while locked\r\n");
request(write_date, sizeof write_date);
printf("\r\n3. Seed, and a wrong key\r\n");
printf(" %s\r\n", unlock(1) ? "unlocked" : "still locked");
printf("\r\n4. A new seed, and the right key\r\n");
printf(" %s\r\n", unlock(0) ? "unlocked" : "still locked");
printf("\r\n5. Write the date and read it back\r\n");
request(write_date, sizeof write_date);
if (request(read_date, sizeof read_date) == 7 && resp[0] == 0x62) {
printf(" programmed on %02X%02X-%02X-%02X\r\n", resp[3], resp[4], resp[5], resp[6]);
}
printf("\r\nTester present every second\r\n");
for (;;) {
delay_ms(1000);
isotp_send(present, sizeof present); // 3E 80: no reply wanted
}
}ecu.c
// Bare-metal C on the Nucleo-F446RE: no Arduino core and no HAL. CMSIS names every register.
// The ECU: sessions (10), security access (27), write and read a protected DID (2E, 22), tester present (3E), and
// the S3 timer that ends an idle session. LD2 (PA5) is lit while it is unlocked.
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"
#define TX_ID 0x7E8
#define RX_ID 0x7E0
#define SECRET 0x5EC12E7Au
#define S3_MS 5000 // an idle non-default session ends after this
#define MAX_ATTEMPTS 3
#define LOCKOUT_MS 10000
static volatile uint32_t ms;
void SysTick_Handler(void) { ms++; }
static void delay_ms(uint32_t t) { uint32_t s = ms; while (ms - s < t) {} }
int __io_putchar(int ch) {
while (!(USART2->SR & USART_SR_TXE)) {}
USART2->DR = ch;
return ch;
}
// ---- CAN: bxCAN CAN1 on PA11 (RX) and PA12 (TX), 500 kbit/s, polled -------------------------------------------
static int can_init(void) {
CAN1->MCR = CAN_MCR_INRQ;
while (!(CAN1->MSR & CAN_MSR_INAK)) {}
CAN1->BTR = (1u << CAN_BTR_TS2_Pos) | (12u << CAN_BTR_TS1_Pos) | (1u << CAN_BTR_BRP_Pos); // 16 MHz / 32
CAN1->FMR = (14u << CAN_FMR_CAN2SB_Pos) | CAN_FMR_FINIT;
CAN1->FA1R &= ~1u;
CAN1->FS1R |= 1u;
CAN1->FM1R |= 1u; // list mode: only RX_ID passes
CAN1->FFA1R &= ~1u;
CAN1->sFilterRegister[0].FR1 = RX_ID << 21;
CAN1->sFilterRegister[0].FR2 = RX_ID << 21;
CAN1->FA1R |= 1u;
CAN1->FMR &= ~CAN_FMR_FINIT;
CAN1->MCR &= ~CAN_MCR_INRQ;
uint32_t start = ms;
while (CAN1->MSR & CAN_MSR_INAK) if (ms - start > 50) return 0;
return 1;
}
static int can_send(const uint8_t *data, int len) { // 8 bytes, padded with AA
uint8_t f[8];
memset(f, 0xAA, 8);
memcpy(f, data, len);
uint32_t start = ms;
while (!(CAN1->TSR & CAN_TSR_TME0)) {
if (ms - start > 10) { CAN1->TSR = CAN_TSR_ABRQ0; return 0; }
}
CAN_TxMailBox_TypeDef *box = &CAN1->sTxMailBox[0];
box->TIR = TX_ID << CAN_TI0R_STID_Pos;
box->TDTR = 8;
box->TDLR = f[0] | f[1] << 8 | f[2] << 16 | (uint32_t)f[3] << 24;
box->TDHR = f[4] | f[5] << 8 | f[6] << 16 | (uint32_t)f[7] << 24;
box->TIR |= CAN_TI0R_TXRQ;
return 1;
}
static int can_receive(uint8_t *f, uint32_t timeout) {
uint32_t start = ms;
while (!(CAN1->RF0R & CAN_RF0R_FMP0)) if (ms - start >= timeout) return 0;
uint32_t lo = CAN1->sFIFOMailBox[0].RDLR, hi = CAN1->sFIFOMailBox[0].RDHR;
for (int i = 0; i < 4; i++) { f[i] = lo >> (8 * i); f[4 + i] = hi >> (8 * i); }
CAN1->RF0R = CAN_RF0R_RFOM0;
return 1;
}
// ---- ISO-TP (ISO 15765-2): one message each way, as in the ISO-TP project ---------------------------------------
static int isotp_send(const uint8_t *msg, uint16_t len) {
uint8_t f[8];
if (len <= 7) { f[0] = len; memcpy(f + 1, msg, len); return can_send(f, len + 1); }
f[0] = 0x10 | (len >> 8);
f[1] = len & 0xFF;
memcpy(f + 2, msg, 6);
if (!can_send(f, 8)) return 0;
uint16_t sent = 6;
uint8_t sn = 1;
while (sent < len) {
uint8_t fc[8];
do { if (!can_receive(fc, 1000)) return 0; } while ((fc[0] & 0xF0) != 0x30 || (fc[0] & 0x0F) == 1);
if ((fc[0] & 0x0F) != 0) return 0; // overflow
uint32_t stmin = fc[2] <= 0x7F ? fc[2] : 1;
for (uint8_t n = 0; sent < len && (fc[1] == 0 || n < fc[1]); n++) {
if (n) delay_ms(stmin);
uint16_t chunk = len - sent > 7 ? 7 : len - sent;
f[0] = 0x20 | (sn++ & 0x0F);
memcpy(f + 1, msg + sent, chunk);
if (!can_send(f, chunk + 1)) return 0;
sent += chunk;
}
}
return 1;
}
// Waits up to timeout ms for a message; returns its length, or -1.
static int isotp_receive(uint8_t *buf, uint16_t cap, uint32_t timeout) {
uint8_t f[8];
uint32_t start = ms;
for (;;) {
uint32_t spent = ms - start;
if (spent >= timeout || !can_receive(f, timeout - spent)) return -1;
if ((f[0] >> 4) == 0 && (f[0] & 0x0F) && (f[0] & 0x0F) <= 7) {
memcpy(buf, f + 1, f[0] & 0x0F);
return f[0] & 0x0F;
}
if ((f[0] >> 4) != 1) continue;
uint16_t len = (f[0] & 0x0F) << 8 | f[1];
uint8_t fc[3] = { len > cap ? 0x32 : 0x30, 0, 0 }; // block size 0: send it all
can_send(fc, 3);
if (len > cap) return -1;
memcpy(buf, f + 2, 6);
uint16_t got = 6;
uint8_t sn = 1;
while (got < len) {
if (!can_receive(f, 1000) || (f[0] >> 4) != 2 || (f[0] & 0x0F) != (sn++ & 0x0F)) return -1;
uint16_t chunk = len - got > 7 ? 7 : len - got;
memcpy(buf + got, f + 1, chunk);
got += chunk;
}
return len;
}
}
static void setup_board(void) {
SysTick_Config(SystemCoreClock / 1000);
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_CAN1EN;
// PA2, PA3: AF7 (USART2); PA11, PA12: AF9 (CAN1); PA5 (LD2) an output.
GPIOA->MODER = (GPIOA->MODER & ~(0xFu << 4 | 0xFu << 22 | 3u << 10)) | (0xAu << 4) | (0xAu << 22) | (1u << 10);
GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFFu << 8)) | (0x77u << 8);
GPIOA->AFR[1] = (GPIOA->AFR[1] & ~(0xFFu << 12)) | (0x99u << 12);
USART2->BRR = SystemCoreClock / 115200;
USART2->CR1 = USART_CR1_TE | USART_CR1_UE;
}
static uint8_t session = 0x01; // 01 default, 03 extended
static int unlocked, seed_sent, attempts;
static uint32_t seed, last_request, lockout_until;
static uint8_t date[4] = { 0x20, 0x25, 0x01, 0x01 }; // DID F199, programming date (BCD)
static uint8_t req[32], res[64];
static int negative(uint8_t nrc) { res[0] = 0x7F; res[1] = req[0]; res[2] = nrc; return 3; }
static void lock(void) { unlocked = 0; seed_sent = 0; GPIOA->BSRR = GPIO_BSRR_BR5; }
static uint32_t random32(void) { // xorshift, stirred with the time: good enough for a demo, not for a car
static uint32_t x = 2463534242u;
x ^= ms + SysTick->VAL;
x ^= x << 13; x ^= x >> 17; x ^= x << 5;
return x;
}
static int session_control(int n) {
if (n != 2) return negative(0x13);
uint8_t s = req[1] & 0x7F;
if (s != 0x01 && s != 0x03) return negative(0x12);
session = s;
lock(); // every session change locks the ECU again
res[0] = 0x50; res[1] = s;
res[2] = 0x00; res[3] = 0x32; // P2 = 50 ms
res[4] = 0x01; res[5] = 0xF4; // P2* = 500 x 10 ms
return 6;
}
static int security_access(int n) {
if (session == 0x01) return negative(0x7F); // not in the default session
if (n < 2) return negative(0x13);
if (req[1] == 0x01) { // request seed
if (n != 2) return negative(0x13);
if ((int32_t)(ms - lockout_until) < 0) return negative(0x37);
seed = unlocked ? 0 : random32(); // a zero seed: already unlocked
seed_sent = !unlocked;
res[0] = 0x67; res[1] = 0x01;
res[2] = seed >> 24; res[3] = seed >> 16; res[4] = seed >> 8; res[5] = seed;
return 6;
}
if (req[1] == 0x02) { // send key
if (n != 6) return negative(0x13);
if (!seed_sent) return negative(0x24);
seed_sent = 0;
uint32_t key = (uint32_t)req[2] << 24 | req[3] << 16 | req[4] << 8 | req[5];
if (key != ((seed << 7 | seed >> 25) ^ SECRET) + 0x1234) {
if (++attempts >= MAX_ATTEMPTS) { attempts = 0; lockout_until = ms + LOCKOUT_MS; return negative(0x36); }
return negative(0x35);
}
attempts = 0;
unlocked = 1;
GPIOA->BSRR = GPIO_BSRR_BS5;
res[0] = 0x67; res[1] = 0x02;
return 2;
}
return negative(0x12);
}
static int write_data(int n) {
if (n < 3) return negative(0x13);
if ((req[1] << 8 | req[2]) != 0xF199) return negative(0x31);
if (n != 7) return negative(0x13);
if (session == 0x01) return negative(0x7F);
if (!unlocked) return negative(0x33);
memcpy(date, req + 3, 4);
res[0] = 0x6E; res[1] = 0xF1; res[2] = 0x99;
return 3;
}
static int read_data(int n) {
if (n != 3) return negative(0x13);
if ((req[1] << 8 | req[2]) != 0xF199) return negative(0x31);
res[0] = 0x62; res[1] = 0xF1; res[2] = 0x99;
memcpy(res + 3, date, 4);
return 7;
}
static int tester_present(int n) {
if (n != 2) return negative(0x13);
if ((req[1] & 0x7F) != 0) return negative(0x12);
res[0] = 0x7E; res[1] = req[1] & 0x7F;
return 2;
}
int main(void) {
setup_board();
printf("ECU: %s, default session, locked\r\n", can_init() ? "on the bus" : "no CAN bus");
for (;;) {
if (session != 0x01 && ms - last_request > S3_MS) {
session = 0x01;
lock();
printf("S3 timeout: back to the default session, locked\r\n");
}
int n = isotp_receive(req, sizeof req, 20);
if (n <= 0) continue;
last_request = ms;
int len;
switch (req[0]) {
case 0x10: len = session_control(n); break;
case 0x27: len = security_access(n); break;
case 0x2E: len = write_data(n); break;
case 0x22: len = read_data(n); break;
case 0x3E: len = tester_present(n); break;
default: len = negative(0x11); break;
}
// Bit 7 of the sub-function: suppress a positive response (never a negative one).
int suppress = (req[0] == 0x10 || req[0] == 0x3E) && n >= 2 && (req[1] & 0x80) && res[0] != 0x7F;
if (!suppress) isotp_send(res, len);
if (req[0] != 0x3E) {
printf("Service %02X: %s", req[0], res[0] == 0x7F ? "refused, NRC " : "ok");
if (res[0] == 0x7F) printf("%02X", res[2]);
printf(" (session %02X, %s)\r\n", session, unlocked ? "unlocked" : "locked");
}
}
}