惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
爱范儿
爱范儿
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
雷峰网
雷峰网
WordPress大学
WordPress大学
L
LangChain Blog
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
腾讯CDC
GbyAI
GbyAI
罗磊的独立博客
Blog — PlanetScale
Blog — PlanetScale
月光博客
月光博客
F
Fortinet All Blogs
Y
Y Combinator Blog
V
V2EX
A
About on SuperTechFans

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Implementing Robust UDS Diagnostics and Secure ECU Flashing
beefed.ai · 2026-04-27 · via DEV Community
  • Which UDS services should be in your toolkit?
  • Designing DTCs and diagnostic coverage that scales
  • How to implement robust seed-and-key and authenticated sessions
  • Safe ECU flashing: bootloaders, signatures, atomic updates and rollback
  • Practical Application — checklists and step-by-step protocols

UDS is the vehicle's diagnostic lingua franca: if you don't build the diagnostic stack the way the vehicle, service network, and regulators expect, you'll either blind your technicians or hand attackers privileged paths into ECU reprogramming. Get the DTC model, secure sessions (seed-and-key / PKI), and the flashing state machine right up front and you stop field failures from becoming recalls.

The problem in the field shows as three repeating symptoms: incomplete or misleading DTCs that waste diagnostic time; reflash sequences that fail or time out and brick hardware; and security models that either lock out independent service or are trivially spoofed. Those symptoms come from weak DTC discipline, ad-hoc security-access implementations, and bootloaders that were never designed for atomic, authenticated updates. You see this as long service times at dealerships, high warranty returns for “software issues”, and an inability to scale OTA or third‑party workshop reprogramming without breaking type‑approval evidence.

Which UDS services should be in your toolkit?

UDS is a toolbox, not a checklist. Pick the minimal set you need for the role the ECU plays, then add services for development, manufacturing and service. The canonical standard is ISO 14229; AUTOSAR maps those services into the DCM/DEM flow used in production ECUs.

SID (hex) Name When to require it (practical)
0x10 Diagnostic Session Control Always—support default + programming/non-default sessions for flashing or secured access.
0x11 ECU Reset Required for state transitions after flashing or configuration changes.
0x3E Tester Present Keep long operations alive (use during transfers).
0x27 Security Access Seed/key challenge-response for unlocking secured services.
0x29 Authentication PKI and certificate verification (ISO 14229 enhancement—preferred for backend/OTA).
0x34/0x36/0x37 RequestDownload / TransferData / RequestTransferExit The standard UDS flash/download sequence—used for ECU reprogramming.
0x19 ReadDTCInformation Essential for diagnostics and remote telematics.
0x14 ClearDiagnosticInformation Restrict to service level and log action.
0x22/0x2E Read/Write Data by Identifier (DID) Telemetry, calibration, and configuration – gate by security level.

Important: Positive UDS responses are the request SID + 0x40 (e.g., 0x10 -> 0x50), and 0x7F is the standard negative-response wrapper—use these to build parsers and error flows that detect service-specific NRCs instead of guessing.

Example: the reprogramming flow people rely on is:

1) Tester -> ECU: DiagnosticSessionControl (0x10) : enter programming session
2) Tester -> ECU: SecurityAccess (0x27) : RequestSeed / SendKey sequence
3) Tester -> ECU: RequestDownload (0x34) : declare image size & address
4) Tester -> ECU: TransferData (0x36) : send blocks with blockSequenceCounter
5) Tester -> ECU: RequestTransferExit (0x37) : finalize
6) Tester -> ECU: RoutineControl (0x31) or ECUReset (0x11) : trigger boot to new image

Enter fullscreen mode Exit fullscreen mode

This sequence is normative in most OEM flows and implemented in AUTOSAR DCM/bootloader callouts.

Designing DTCs and diagnostic coverage that scales

DTCs are your contract with service, telematics, and regulators—design them intentionally.

  • DTC format and status: UDS reports DTCs as 3‑byte codes with an 8‑bit status byte that carries the pending/confirmed/MIL state and other flags; ReadDTCInformation (0x19) exposes subfunctions for status‑filtered queries, snapshots and supported DTC lists. That format is the basis for both workshop tools and remote diagnostics.
  • Coverage strategy by fault mode: map faults to three buckets—safety-critical, emissions-critical, operational/comfort. Assign a maximum number of DTCs per bucket and per ECU to avoid flooding NVM during cascades (e.g., max 32 active per ECU, archive 128 historic). Use severity masks to prioritize telematics upload.
  • DTC lifecycle rules (implementation checklist):
    • Define clear semantics: which service or event clears a DTC (0x14), and what happens to snapshots.
    • Capture freeze-frame for first occurrence and rolling snapshots for intermittent issues.
    • Instrument counting and aging rules—how many cycles until a pending DTC becomes confirmed.
    • Gate DTC generation by safety states to avoid spurious flags during calibration or manufacturing modes.
  • One-truth event manager: centralize DTC sinks in a DEM-like module; DCM should call into DEM for selection/clear/read operations so diagnostic behavior is consistent across sessions and power cycles.

Concrete example: use ReadDTCInformation(0x19, 0x02 reportDTCByStatusMask) to let a telematics agent ask “which DTCs currently request MIL on?” and only upload high-severity items to backend channels to preserve bandwidth and privacy.

How to implement robust seed-and-key and authenticated sessions

The worst security implementations are either trivial static keys or black‑box OEM schemes that become single points of failure. Make the security model auditable, provable and rooted in hardware.

  • Two maturity paths:
    1. Seed-and-key (UDS 0x27) — challenge/response derived keys using a secret held in an HSM or secure element. Implement time delays, attempt counters, and per‑level unlock timeouts as in the standard. Never store raw master keys in plaintext in MCU flash.
    2. PKI-based Authentication (0x29, ISO 14229 additions) — preferred for OTA/back-end tooling: client certificates, CRLs or OCSP-like revocation, and mutual verification. This scales for fleet and backend-driven updates.
  • Concrete crypto pattern for seed→key (recommended):
    • Device provisioned with a unique secret key K_device stored in an HSM.
    • ECU returns a cryptographic seed = nonce || challenge_data.
    • Tester computes key = Truncate(HMAC‑SHA256(K_device, seed || level || context)).
    • ECU verifies the HMAC using its internal K_device via HSM. Do not expose K_device. Use an authenticated KDF (NIST SP 800‑108 / HKDF patterns).
  • Policies to put in place:
    • Lockout policy: after N invalid sendKey attempts, return NRC 0x36 (exceeded attempts) and enable a configurable time delay; clear on successful authentication. This behavior is specified by ISO 14229 and must be enforced to defend brute force.
    • Ephemeral unlocking: unlock for the minimal necessary subset of services and for the shortest time window; revert to locked state on power cycle or explicit deAuthenticate.
    • Use HSMs: put keys and monotonic counters in a secure element (SHE/SHA/HSM). An MCU‑only implementation without protected keys invites cloning or key extraction. AUTOSAR Crypto/HSM integration is the production pattern.
  • Audit & forensics: log secure‑access attempts, success/failure, and tie them to tool credentials/serial numbers. Keep logs locally and send telemetry of anomalous patterns to a centralized SOC when possible. UNECE/SUMS expectations for traceability make this mandatory in regulated regions.

Sample pseudocode (key derivation, high level):

// Pseudocode: compute key on tester side
uint8_t compute_key(const uint8_t *seed, size_t seed_len,
                    const uint8_t *level, size_t level_len,
                    const uint8_t *device_secret, size_t secret_len,
                    uint8_t *out_key, size_t out_len) {
    // Use HMAC-SHA256 then truncate
    uint8_t mac;
    HMAC_SHA256(device_secret, secret_len, seed, seed_len + level_len, mac);
    memcpy(out_key, mac, out_len); // e.g., 16 bytes
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

Do not implement your own crypto primitives; use approved algorithms and KDF profiles (see NIST guidance).

Safe ECU flashing: bootloaders, signatures, atomic updates and rollback

Flashing is the highest‑risk functionality you expose to a vehicle. Treat it like surgery: deterministic, auditable and reversible.

Key technical pillars

  • Authenticated images: always sign images with OEM private keys and verify signatures in a verified bootloader before any write to persistent program partitions. If you use encryption for IP protection, separate the encryption key (for confidentiality) from the signing key (for integrity/authorization). NIST & platform RoT guidance emphasize this chain-of-trust logic.
  • Atomic update strategy: use A/B partitions or a staging partition + golden image. Write the new image to an inactive partition, verify the signature/hash, then update a secure metadata flag and reboot to the new image. Only mark the image committed after a full validated boot. If validation fails, boot the golden image.
  • Anti‑rollback: store monotonic counters or version monotonic values inside an HSM or secure monotonic storage; refuse images with lower version numbers than the stored monotonic value. This prevents downgrades to vulnerable releases.
  • UDS transfer discipline: implement RequestDownload (0x34) with correct AddressAndLengthFormatIdentifier, TransferData (0x36) with verified blockSequenceCounter, and RequestTransferExit (0x37). Use TesterPresent (0x3E) or 0x78 ResponsePending to avoid timing out long operations.
  • Power and time resilience: require minimum battery voltage for field flashing, or use a local supercap/aux power to ensure flash completes. Always design a recovery button/serial JTAG fallback for service centers—bricked hardware without a recovery path costs replacement.

Bootloader state machine (recommended minimal):

  1. IDLE — normal runtime.
  2. DOWNLOAD_IN_PROGRESS — receiving blocks; use TransferData counters and temporary storage with checksums.
  3. VALIDATE — run signature verification and integrity checks.
  4. APPLY — write to inactive partition (atomically switch pointers when done).
  5. TRY_BOOT — reboot to new image; start verification timers.
  6. COMMIT — if startup checks pass (self-tests, watchdog), set committed=true; else ROLLBACK to previous partition.

Example bootloader verification pseudocode:

if (download_complete) {
  if (!verify_signature(image, cert_public_key)) {
    report_error(NRC_0x72); // generalProgrammingFailure
    abort_update();
  }
  write_to_inactive_partition(image);
  set_pending_boot();
  system_reset();
}
on_boot {
  if (pending_boot) {
     if (self_tests_pass()) {
         set_committed(); // mark new image as active
     } else {
         rollback_to_previous();
     }
  }
}

Enter fullscreen mode Exit fullscreen mode

Regulatory & operational context: UNECE R156 demands auditable SUMS processes: software identification (e.g., RXSWIN), staged rollouts, and the ability to restore to previously approved software. That influences build pipelines, cryptographic key handling and logging.

Field reprogramming & workshop patterns

  • For workshop/tool-based reprogramming, industry uses SAE J2534 / Pass‑Thru interfaces (or OEM equivalents) to standardize the VCI/PC interface for reprogramming—design your toolchain to interoperate with pass‑thru APIs if you support independent workshops.
  • For OTA, pair signed artifact delivery with rollout gating and health telemetry—don’t release a full fleet update globally without staged canary and automatic rollback on regression metrics.

Practical Application — checklists and step-by-step protocols

Below are immediately actionable artifacts you can drop into design and verification.

Pre‑deployment checklist (design & architecture)

  • [ ] Map required UDS services per ECU and document which session and security level needed for each.
  • [ ] Define DTC taxonomy (ID ranges, severity mapping, max per ECU) and storage quotas.
  • [ ] Select crypto primitives and KDFs (HMAC‑SHA256/HKDF or NIST‑approved KDF) and plan HSM integration.
  • [ ] Design bootloader partitioning (A/B, golden image) and monotonic counter storage (HSM or secure NV).
  • [ ] Define SUMS requirements: RXSWIN support, evidence of signing, rollback policy and logs (UNECE R156 alignment).

UDS / DCM configuration quick protocol (implementation detail)

  1. Implement 0x10 sessions: default, extended, programming — configure allowed services per session.
  2. Gate 0x34/0x36/0x37 and 0x3D behind 0x27 SecurityAccess or 0x29 Authentication.
  3. During TransferData (0x36): verify blockSequenceCounter, calculate block hash and accumulate overall image hash. Return 0x76 positive responses with echoed blockSequenceCounter.
  4. Use TesterPresent (0x3E) from the tool with interval < session timeout to maintain session during long transfer.

Flashing protocol (step-by-step)

  • Step 0: Ensure vehicle power > threshold; disable sleeping modes and notify customer of required downtime.
  • Step 1: Enter programming session (0x10: subfunction=programming), request and pass security (0x27 / 0x29).
  • Step 2: RequestDownload (0x34) with container MemoryId and AddressAndLengthFormatIdentifier. ECU responds with accepted block size.
  • Step 3: Send TransferData (0x36) blocks; monitor blockSequenceCounter, retry failed blocks, log NRCs.
  • Step 4: RequestTransferExit (0x37) — ECU validates payload and returns success/failure.
  • Step 5: Invoke RoutineControl (0x31) to start bootload validation or call ECUReset (0x11) to reboot. Verify boot and commit.

Testing & validation checklist (integration)

  • [ ] Unit tests for each UDS service; cover NRCs including 0x22 0x31 and 0x36 edge cases.
  • [ ] Fuzz test UDS parser and overflow/sequence errors.
  • [ ] Security verification: attempt seed/key brute force with proper lockout timers and ensure delays and NRCs match spec.
  • [ ] Update testing: simulate interrupted download, partial writes, and verify automatic rollback behavior.
  • [ ] SUMS compliance tests: verify RXSWIN can be read and update traceability logs are generated for each vehicle.

Operational controls (production & field)

  • Keep a signed manifest and image metadata (version, build id, RXSWIN) in the release bundle—verify before flashing.
  • Maintain an HSM‑backed code‑signing process; restrict signing keys to a limited security role (no developer laptops).
  • Stage OTA rollouts: 1% canary → 10% regional → global; automatically halt & rollback on health regressions.

Important: A single engineering misstep—unsigned images, no anti-rollback, or storing master keys in plaintext—makes secure flashing and diagnostics moot. Protect the root of trust first; everything else follows.

Sources:
ISO 14229-1:2020 — Road vehicles — Unified diagnostic services (UDS) — Part 1: Application layer - Official ISO standard describing UDS services, session semantics, SecurityAccess rules and DTC/ReadDTCInformation behaviors used for service selection and negative response codes.

AUTOSAR SWS DiagnosticCommunicationManager (excerpt) - AUTOSAR Diagnostic Communication Manager specification (DCM) describing UDS integration into BSW, session/security handling and callouts for request/download and DTC management.

py-uds / UDS Knowledge Base — Diagnostic services and TransferData details - Practical service descriptions and formats for ReadDTCInformation (0x19), TransferData (0x36), RequestDownload (0x34), and Authentication (0x29) used for implementation examples.

NIST SP 800-193 Platform Firmware Resiliency Guidelines - Guidance on Root of Trust, authenticated firmware update mechanisms, detection and recovery practices; basis for secure boot, anti‑rollback and atomic update design.

Software Update Management Systems according to UNECE R156 (overview) - Practical guidance on SUMS requirements, RXSWIN identification and the regulatory expectations for update traceability and rollback processes under UN R156.

PASS‑THRU / J2534 explanation (TEXA) - Explanation of Pass‑Thru J2534 / ISO 22900 reprogramming interfaces for workshop-level ECU reprogramming and the role of standardized VCIs in dealer and independent-shop flows.