Rebuild obu-firmware on Niklas Dathe's microbu-firmware
Replace the vanetza-idf port with his current station firmware (microbu-firmware e4e4bd8: main/, components/microbu_v2x, components/vanetza, external/vanetza) and re-apply the MicrOBU additions, each marked "MicrOBU:" in the sources: - V2X_RX (opcode 0x90): every received ITS message, signed or not, through gn_unwrap.c, because the stack drops unsigned and foreign-root traffic. 0x85 is the spec's RAW_FRAME and 0x86 is reserved. The body is built in v2x_rx.hpp. - Unsigned transmission (geonet.c) for security profile 1 or station security 0, from a random MAC per configuration. - Radio polled from STATION_CONFIGURE on; manual country policy, TX power read-back, static RX buffer, short frames ignored. - Battery guard (battery_policy.hpp): deep sleep below 3.30 V with no phone on USB. - No USB writes without a host; last_frame_ms() for the guard. - 80 KB NVS with the app at 0x20000, 8 MB flash, XIAO ESP32-C5 board, 20 dBm. Remove the old C firmware, the bench listener and the old vanetza-idf copy. Add docs/station-link.tex as revision 2 of the interface reference (V2X_RX, unsigned sending, battery rule, revision history). Add 39 host unit tests (make firmware in test/host) next to the existing chain, replay, fuzz and battery tests, and point tools/station_status_watch.py at the new CONFIRM-based status.
This commit is contained in:
+18
-41
@@ -1,64 +1,41 @@
|
|||||||
cmake_minimum_required(VERSION 3.22)
|
cmake_minimum_required(VERSION 3.22)
|
||||||
# obu-firmware: the ESP32-C5 half of the MicrOBU station, on the vanetza-idf C-ITS stack.
|
# ESP32-C5 station on the microbu_v2x and Vanetza components.
|
||||||
#
|
# Verify the vendored radio source before configuration.
|
||||||
# Since 2026-09-23 this is a port of the colleague's standalone VRU station
|
set(_otm_upstream "${CMAKE_CURRENT_LIST_DIR}/components/microbu_v2x/third_party/otm/main/tx_custom.c")
|
||||||
# (microbu-esp32c5/firmware, in their own repository, not part of this one). From it:
|
|
||||||
# BTP/GeoNetworking and the TS 103 097 security entity (vanetza-idf), the station-link message
|
|
||||||
# layer over native USB Serial/JTAG and BLE GATT, the NVS credential store, and the C5 radio adapter.
|
|
||||||
# Added here for this project: the raw receive path of the previous firmware (gn_unwrap.c, forwarded
|
|
||||||
# as link opcode V2X_RX) so unsigned and non-demo-signed traffic still reaches the phone, the
|
|
||||||
# unsigned transmit path of the previous firmware (geonet.c), and BLE pausing while USB is in use.
|
|
||||||
# See NOTES.md.
|
|
||||||
#
|
|
||||||
# ESP-IDF 6.0.2 exactly: the C5 radio's private Wi-Fi driver ABI (otm_tx_custom.c) is pinned to it
|
|
||||||
# by vanetza-idf's radio_c5.cmake and has only been validated there. The previous C firmware was
|
|
||||||
# built with IDF 6.1; see FLASHING.md for the export script of each.
|
|
||||||
#
|
|
||||||
# vanetza-idf lives in external/vanetza-idf, copied from the colleague's repository (their
|
|
||||||
# external/vanetza-idf at commit cf4b99f, unchanged; see its PROVENANCE.md). Override with
|
|
||||||
# -DVANETZA_IDF_DIR=... to build against another checkout.
|
|
||||||
if(NOT VANETZA_IDF_DIR)
|
|
||||||
set(VANETZA_IDF_DIR "${CMAKE_CURRENT_LIST_DIR}/external/vanetza-idf")
|
|
||||||
endif()
|
|
||||||
if(NOT EXISTS "${VANETZA_IDF_DIR}/idf_component.yml")
|
|
||||||
message(FATAL_ERROR "vanetza-idf not found at ${VANETZA_IDF_DIR}: obu-firmware/external/vanetza-idf "
|
|
||||||
"is part of this repository; check it is complete, or pass "
|
|
||||||
"-DVANETZA_IDF_DIR=<path to a vanetza-idf checkout>")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
# Provenance guard for main/otm_tx_custom.c, copied unchanged from microbu-esp32c5/firmware/CMakeLists.txt:
|
|
||||||
# this checked-in copy is what microbu::C5Radio::request() links against for every transmission.
|
|
||||||
# Fail configure if either the pinned upstream or this file drifts from the reviewed revision.
|
|
||||||
set(_otm_upstream "${VANETZA_IDF_DIR}/ports/esp_idf/third_party/otm/main/tx_custom.c")
|
|
||||||
if(EXISTS "${_otm_upstream}")
|
if(EXISTS "${_otm_upstream}")
|
||||||
file(READ "${_otm_upstream}" _otm_upstream_text)
|
file(READ "${_otm_upstream}" _otm_upstream_text)
|
||||||
string(REPLACE "\r\n" "\n" _otm_upstream_text "${_otm_upstream_text}")
|
string(REPLACE "\r\n" "\n" _otm_upstream_text "${_otm_upstream_text}")
|
||||||
string(SHA256 _otm_upstream_hash "${_otm_upstream_text}")
|
string(SHA256 _otm_upstream_hash "${_otm_upstream_text}")
|
||||||
if(NOT _otm_upstream_hash STREQUAL "cb1dccfef96912ca59275e8a9102f41f56925b94a19d4a4629082aaeb779be1b")
|
if(NOT _otm_upstream_hash STREQUAL "cb1dccfef96912ca59275e8a9102f41f56925b94a19d4a4629082aaeb779be1b")
|
||||||
message(FATAL_ERROR "OpenTrafficMap upstream tx_custom.c differs from the reviewed source revision (674e3412) -- review before updating main/otm_tx_custom.c and this hash")
|
message(FATAL_ERROR "The vendored OpenTrafficMap radio source differs from its pinned SHA256")
|
||||||
endif()
|
endif()
|
||||||
endif()
|
endif()
|
||||||
set(_otm_checked_in "${CMAKE_CURRENT_LIST_DIR}/main/otm_tx_custom.c")
|
set(_otm_checked_in "${CMAKE_CURRENT_LIST_DIR}/main/otm_tx_custom.c")
|
||||||
file(READ "${_otm_checked_in}" _otm_checked_in_text)
|
file(READ "${_otm_checked_in}" _otm_checked_in_text)
|
||||||
string(REPLACE "\r\n" "\n" _otm_checked_in_text "${_otm_checked_in_text}")
|
string(REPLACE "\r\n" "\n" _otm_checked_in_text "${_otm_checked_in_text}")
|
||||||
string(SHA256 _otm_checked_in_hash "${_otm_checked_in_text}")
|
string(SHA256 _otm_checked_in_hash "${_otm_checked_in_text}")
|
||||||
if(NOT _otm_checked_in_hash STREQUAL "114693af99ce3866cfc767066d484e45822eaf15335d94a03626b60ac5777277")
|
if(NOT _otm_checked_in_hash STREQUAL "db32dd6e2a50decf7add4fc09ea14ee1f060bf07a047c5c7bd3cdc2b1190b019")
|
||||||
message(FATAL_ERROR "main/otm_tx_custom.c differs from the reviewed copy -- review the change, then update this hash")
|
message(FATAL_ERROR "The application radio source differs from its pinned SHA256")
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
list(APPEND EXTRA_COMPONENT_DIRS "${VANETZA_IDF_DIR}")
|
|
||||||
set(SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
|
set(SDKCONFIG_DEFAULTS "${CMAKE_CURRENT_LIST_DIR}/sdkconfig.defaults")
|
||||||
set(COMPONENTS main)
|
set(COMPONENTS main)
|
||||||
|
set(MICROBU_CRYPTO_ADAPTER_COMPONENT "" CACHE STRING
|
||||||
|
"Optional ESP IDF component implementing the selected external Vanetza crypto backend")
|
||||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
project(obu_firmware)
|
project(microbu_firmware)
|
||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/cmake/no_efuse_writes.cmake")
|
||||||
add_compile_options(-Wno-error -Wno-cpp -Wno-error=implicit-function-declaration)
|
add_compile_options(-Wno-error -Wno-cpp -Wno-error=implicit-function-declaration)
|
||||||
idf_component_get_property(vanetza_lib vanetza-idf COMPONENT_LIB)
|
foreach(_stack vanetza microbu_v2x)
|
||||||
if(vanetza_lib)
|
idf_component_get_property(_stack_lib ${_stack} COMPONENT_LIB)
|
||||||
target_compile_options(${vanetza_lib} PRIVATE -Wno-error=implicit-function-declaration -Wno-error=cpp)
|
if(_stack_lib)
|
||||||
endif()
|
target_compile_options(${_stack_lib} PRIVATE -Wno-error=implicit-function-declaration -Wno-error=cpp)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
# GCC 15's stricter -Warray-bounds false-positives on NimBLE's fixed-size bond-store arrays
|
# GCC 15's stricter -Warray-bounds false-positives on NimBLE's fixed-size bond-store arrays
|
||||||
# (upstream Apache Mynewt code); demote to a warning so the component still builds.
|
# (upstream Apache Mynewt code, not ours); demote to a warning so the component still builds.
|
||||||
idf_component_get_property(bt_lib bt COMPONENT_LIB)
|
idf_component_get_property(bt_lib bt COMPONENT_LIB)
|
||||||
if(bt_lib)
|
if(bt_lib)
|
||||||
target_compile_options(${bt_lib} PRIVATE -Wno-error=array-bounds)
|
target_compile_options(${bt_lib} PRIVATE -Wno-error=array-bounds)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|||||||
+87
-208
@@ -1,247 +1,126 @@
|
|||||||
# obu-firmware — setup & flashing notes
|
# obu-firmware: build and flash
|
||||||
|
|
||||||
**Board (since 2026-10-05): Seeed XIAO ESP32-C5.** One USB-C port, which is the chip's native USB
|
**Board: Seeed XIAO ESP32-C5.** One USB-C port, the chip's native USB Serial/JTAG (VID/PID
|
||||||
Serial/JTAG (VID/PID 0x303A/0x1001); no UART bridge, no second port. 8 MB flash (`esptool flash-id`),
|
0x303A/0x1001); no UART bridge. 8 MB flash. The same port flashes the board, carries the phone's
|
||||||
so `sdkconfig.defaults` sets `FLASHSIZE_8MB` (the earlier CH343 bench board had 16 MB). The same
|
station link and carries the log (as LOG frames, type 0x7F), so the PC and the phone take turns on
|
||||||
port flashes the board *and* carries the phone's station link, so the PC and the phone take turns on
|
it. Over BLE the phone does not need the cable.
|
||||||
it. Pin map and what is wired: "Battery and pins" below. The sections that still say "UART-bridge
|
|
||||||
port" or "COM3" describe the earlier two-port bench board.
|
|
||||||
|
|
||||||
## Two toolchains - use a dedicated terminal for each
|
## Toolchain
|
||||||
|
|
||||||
Since 2026-09-23 this project builds against ESP-IDF **6.0.2** exactly
|
ESP-IDF **6.0.2** exactly (`C:\Espressif\frameworks\esp-idf-v6.0.2`): `components/microbu_v2x`
|
||||||
(`C:\Espressif\frameworks\esp-idf-v6.0.2`): it is the vanetza-idf port (see
|
pins the C5 radio's private Wi-Fi driver ABI to it. Not the receiver firmware's 6.1, not
|
||||||
NOTES.md), and vanetza-idf's `radio_c5.cmake` refuses any other version because
|
`obu-cam-transmistter`'s 5.5.4. Exporting two IDFs in one PowerShell window fails; open a fresh
|
||||||
the raw TX path pokes private Wi-Fi driver structures only validated there. The
|
window, or clear `$env:IDF_PYTHON_ENV_PATH` and `$env:IDF_PATH` first.
|
||||||
previous C firmware used the receiver firmware's IDF **6.1**; the separate
|
|
||||||
`obu-cam-transmistter` project builds against the global ESP-IDF **5.5.4**.
|
|
||||||
Exporting two of them in one PowerShell window fails: the second export
|
|
||||||
inherits the first's `IDF_PYTHON_ENV_PATH` and reports every Python dependency
|
|
||||||
as unmet. Don't run `install.bat` to "fix" that - open a fresh terminal, or
|
|
||||||
clear the state with `$env:IDF_PYTHON_ENV_PATH = $null; $env:IDF_PATH = $null`.
|
|
||||||
|
|
||||||
The build is self-contained: the C-ITS library comes from
|
|
||||||
`obu-firmware/external/vanetza-idf`, a copy of `external/vanetza-idf` from the
|
|
||||||
colleague's microbu-esp32c5 repository (their commit cf4b99f, unchanged). Pass
|
|
||||||
`-DVANETZA_IDF_DIR=<path>` to `idf.py` to build against another checkout. The
|
|
||||||
first build downloads `espressif/esp-boost` into `managed_components/`.
|
|
||||||
|
|
||||||
Nothing is fetched from or pushed to the colleague's repository (HAW GitLab,
|
|
||||||
urban-mobility-lab/microbu/microbu-esp32c5). To take a newer vanetza-idf from
|
|
||||||
it, copy their `external/vanetza-idf` over this folder, rebuild and test, and
|
|
||||||
commit it here. The rest of their tree (their own VAM firmware, PKI tooling,
|
|
||||||
station-link Python tools, the V2X2MAP bridge) is not part of this repository.
|
|
||||||
|
|
||||||
## Every new PowerShell session
|
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
|
||||||
$env:IDF_TOOLS_PATH = "C:\Espressif"
|
$env:IDF_TOOLS_PATH = "C:\Espressif"
|
||||||
C:\Espressif\frameworks\esp-idf-v6.0.2\export.ps1
|
C:\Espressif\frameworks\esp-idf-v6.0.2\export.ps1
|
||||||
idf.py --version # v6.0.2
|
|
||||||
```
|
|
||||||
|
|
||||||
## Build & flash
|
|
||||||
|
|
||||||
The XIAO flashes over its one USB-C port (COM10 on the bench; Device Manager → Ports shows it as
|
|
||||||
"USB Serial Device"). esptool resets it into the bootloader by itself; no BOOT button is needed
|
|
||||||
unless the running firmware has crashed the USB peripheral, then hold BOOT while plugging in.
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
|
cd C:\Users\Ashin\AndroidStudioProjects\MicrOBU\obu-firmware
|
||||||
idf.py set-target esp32c5 # only needed once per clean build folder
|
idf.py set-target esp32c5 # once per clean build folder
|
||||||
idf.py build
|
idf.py build # first build ~20 min; downloads espressif/esp-boost into managed_components/
|
||||||
idf.py -p COM10 -b 921600 flash
|
|
||||||
```
|
```
|
||||||
|
|
||||||
There is **no console on this port**: ESP_LOG stays on UART0 (GPIO11/GPIO12 = pads D6/D7), which a
|
## Flash
|
||||||
bare XIAO does not route to USB, and `idf.py monitor` would only see the link frames. To read the
|
|
||||||
log, put a 3.3 V USB-UART adapter on D6 (TX) / D7 (RX), or set `CONFIG_MICROBU_LOG_OVER_LINK=y`
|
|
||||||
(LOG frames of type 0x7F on the link; the Android app has not been checked against them). To read
|
|
||||||
what the board says over the link, use `tools/station_status_watch.py COM10`.
|
|
||||||
|
|
||||||
The earlier two-port board flashed through its CH343 bridge port (COM3) with
|
Use a full `flash` (bootloader + partition table + app), never `app-flash`: the partition table is
|
||||||
`idf.py -p COM3 -b 921600 flash monitor`; its console was on that port.
|
not Niklas Dathe's (80 KB NVS, app at 0x20000).
|
||||||
Use `flash` (bootloader + partition table + app), not `app-flash`, whenever the
|
|
||||||
partition table may differ from what the board has.
|
|
||||||
|
|
||||||
### First flash onto a board with the previous firmware
|
|
||||||
|
|
||||||
The partition table changed with the port (NVS 24 KB → 80 KB, app 0x10000 →
|
|
||||||
0x20000), and the old NVS is full of Wi-Fi settings the previous firmware left
|
|
||||||
behind. Erase the whole new NVS range once, then do a full flash:
|
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python -m esptool --chip esp32c5 -p COM10 -b 921600 erase-region 0x9000 0x15000
|
idf.py -p COM6 flash
|
||||||
idf.py -p COM10 -b 921600 flash
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Without the erase, the board cannot store the BLE bond and the phone has to pair
|
**If the running firmware has taken the USB port down** (or the board holds an unrelated image),
|
||||||
on every connection (2026-09-23). After it:
|
auto-reset fails with "No serial data received". Unplug, hold BOOT, plug in, release. If the flasher
|
||||||
|
stub then fails to start (seen 2026-11-10 with esptool 5.4 on this board), flash without it, from
|
||||||
|
`build/`:
|
||||||
|
|
||||||
- the boot log shows `0 bonded phone(s) in NVS`, `BLE advertising started as
|
```powershell
|
||||||
'micrOBU-XXXX'` and `station task ready`; the radio stays off until the app
|
python -m esptool --chip esp32c5 -p COM6 --no-stub --before=no-reset --after=hard-reset write-flash "@flash_args"
|
||||||
connects;
|
```
|
||||||
- on the first Connect the app provisions the demo credentials once (the card
|
|
||||||
says "Provisioning the demo credentials"); they stay in NVS from then on;
|
|
||||||
- a phone that was paired with the board before must forget `micrOBU-XXXX` in
|
|
||||||
Android's Bluetooth settings and pair again (passkey 123456).
|
|
||||||
|
|
||||||
Erasing NVS later (e.g. after a partition change) has the same effects.
|
A board left in download mode comes back after unplugging and replugging without BOOT.
|
||||||
|
|
||||||
## Going back to the previous firmware
|
**Before flashing a board you did not flash yourself, read its app descriptor**
|
||||||
|
(`esptool read-flash 0x10000 0x100`; `esp_app_desc_t` starts at 0x20): project name `microbu_firmware`
|
||||||
|
is this firmware, `obu_firmware` an older MicrOBU one, `arduino-lib-builder` an Arduino sketch.
|
||||||
|
Back the flash up first to `firmware-backups/` (gitignored).
|
||||||
|
|
||||||
The previous, unsigned C firmware (frame types 0x01-0x05, CAM over USB only)
|
### First flash onto a board with other firmware
|
||||||
can come back two ways. The app detects it and falls back to its protocol.
|
|
||||||
|
|
||||||
- **Image:** `firmware-backups/` in the repository root (gitignored, on the lab
|
Erase the NVS range once, so no old Wi-Fi or BLE data sits in the new 80 KB NVS:
|
||||||
laptop only) holds a full-flash image of the COM3 board as it was before the
|
|
||||||
port, with the esptool command in its README.txt. It restores the old
|
|
||||||
partition table and NVS too.
|
|
||||||
- **Source:** commit `7285fa1` is the last one before the port. Check it out in
|
|
||||||
a separate worktree and build it with the receiver firmware's IDF 6.1
|
|
||||||
(`its-g5-receiver-firmware\esp-idf\export.ps1`). Erase the NVS range as above
|
|
||||||
first, then `flash` (full, since the partition table differs); erasing after
|
|
||||||
flashing would wipe the start of the old app, which sits at 0x10000.
|
|
||||||
|
|
||||||
## If the build fails
|
```powershell
|
||||||
|
python -m esptool --chip esp32c5 -p COM6 erase-region 0x9000 0x15000
|
||||||
|
```
|
||||||
|
|
||||||
- **"includes X.h, provided by Y component(s)... not in the requirements
|
Then: the boot log shows `BLE advertising started as 'micrOBU-XXXX'` and `station task ready`; the
|
||||||
list"** — IDF 5.x split the old monolithic `driver` component apart
|
radio stays off until the app (or `tools/station_status_watch.py --configure`) sends
|
||||||
(`esp_driver_gpio`, `esp_driver_uart`, etc.). Add the named component to
|
STATION_CONFIGURE; the app provisions the demo credentials on the first Connect. A phone that was
|
||||||
`REQUIRES` in `main/CMakeLists.txt` and rebuild. Already fixed once for
|
paired before must forget `micrOBU-XXXX` in Android's Bluetooth settings and pair again (passkey
|
||||||
`esp_driver_gpio` + `esp_driver_uart` — if a new header comes up, same fix.
|
123456, `CONFIG_MICROBU_BLE_PASSKEY`).
|
||||||
- Otherwise, start clean before re-building:
|
|
||||||
```powershell
|
|
||||||
idf.py fullclean
|
|
||||||
idf.py build
|
|
||||||
```
|
|
||||||
|
|
||||||
## Connecting the phone (XIAO ESP32-C5)
|
## Look at the board from the PC
|
||||||
|
|
||||||
The XIAO has a single USB-C port, the native USB Serial/JTAG one: the phone plugs into it via
|
```powershell
|
||||||
USB-OTG, the station link runs over it (below), and unplugging the phone and plugging the PC in
|
py -3.11 tools/station_status_watch.py COM6 30 --configure --rx
|
||||||
is how it is flashed. Over BLE the phone does not need the cable at all (the board runs on its cell).
|
```
|
||||||
|
|
||||||
The rest of this section describes the earlier **ESP32-C5-WIFI6-KIT** bench board with two USB-C
|
prints the log, the STATUS snapshot once a second (uptime, signing and radio counters, heap,
|
||||||
ports — use the right one:
|
battery) and the first V2X_RX messages heard on air. DTR/RTS stay low in the script because toggling
|
||||||
|
them resets the board.
|
||||||
|
|
||||||
- **Native USB-C port** (labeled for JTAG/native USB, up to 12 Mbps) — this
|
## Production OBU checklist (board with the cell connected)
|
||||||
is where the phone plugs in via USB-OTG. The station link
|
|
||||||
(`serial_link.cpp`: station-link messages as frame type 0x10 in the 0xAA55
|
|
||||||
framing) runs over the ESP32-C5's native USB Serial/JTAG peripheral on this port, enumerating as a CDC-ACM device under Espressif's
|
|
||||||
VID/PID (0x303A/0x1001).
|
|
||||||
- **UART-bridge port** (labeled for flashing) — this is what you use for
|
|
||||||
`idf.py flash monitor` from your PC. Leave the phone unplugged from this
|
|
||||||
one; it only carries `idf.py`'s flashing protocol and the ESP_LOG console.
|
|
||||||
|
|
||||||
The app recognizes the ESP32-C5's VID/PID via a custom probe table in
|
1. **Before touching the board:** read its app descriptor and back its flash up (see above). Check the
|
||||||
`UsbSerialTransport.kt` (the default `usb-serial-for-android` prober doesn't
|
cell polarity with a multimeter before it goes on the BAT pads; the slide switch can stay off while
|
||||||
know Espressif's device IDs). If the phone doesn't detect anything when
|
flashing, USB powers the board.
|
||||||
plugged into the native port, first confirm with a tool like "USB Device
|
2. Erase the NVS range, then a full `idf.py -p COMx flash` (or the `--no-stub` recipe if the stub
|
||||||
Info" (or `adb shell dumpsys usb` from a PC) that Android sees a USB device
|
fails). Unplug and replug the cable **without** BOOT afterwards.
|
||||||
at all — that isolates a bad/charge-only OTG cable from an app-side issue.
|
3. `py -3.11 tools/station_status_watch.py COMx 20 --configure --rx`: expect `BLE advertising started as
|
||||||
|
'micrOBU-XXXX'`, a STATUS line every second, `configured=1` after the configure, and `battery=` close
|
||||||
## Bring-up checklist (phone <-> ESP32-C5 link)
|
to the multimeter reading on the cell. The firmware has no calibration trim any more: if the two differ
|
||||||
|
by more than about 50 mV, note both values (a `CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` option of the
|
||||||
Work down this list — each step isolates the layer below it.
|
earlier port can be added back).
|
||||||
|
4. Switch the cell on, unplug USB, check the board keeps running (LED pulses on RX, the phone connects
|
||||||
1. **Flash and install together.** The app detects the firmware generation by
|
over BLE). Then work down `TODO.md` ("obu-firmware on Niklas Dathe's microbu-firmware").
|
||||||
its heartbeat and speaks either protocol, but only an app from 2026-09-23 on
|
5. **Know the shutdown rule before leaving it unattended:** with the cell below 3.30 V, no phone on USB
|
||||||
knows the station-link protocol; messages are at most 512 octets on both
|
and more than 60 s after boot, the board deep-sleeps and only wakes every 5 minutes to check; it runs
|
||||||
sides.
|
again from 3.60 V (charge it over USB). A board that "went dead" on a flat cell is this, not a crash.
|
||||||
2. **Does Android see the device at all?** Plug the phone into the **native**
|
6. Install the app built from this commit on the phone: the app and firmware of 2026-11-10 only talk
|
||||||
USB-C port, hit Connect, and read logcat for `UsbSerialTransport`. It logs
|
to each other (CONFIRM/STATUS_REQUEST, V2X_RX 0x90). The phone must forget an old `micrOBU-XXXX`
|
||||||
every attached device *and* each device's interfaces. Empty list = cable /
|
bond and pair again (passkey 123456), because the NVS was erased.
|
||||||
OTG / wrong port, below the app entirely.
|
|
||||||
3. **Did the right interface get claimed?** The C5's USB Serial/JTAG is a
|
|
||||||
composite device — expect CDC control (class 2) + CDC data (class 10) +
|
|
||||||
vendor-specific JTAG (class 255) in that dump. Compare against the `ports=`
|
|
||||||
count on the `matched device` line.
|
|
||||||
4. **Is the link alive?** The firmware sends a STATUS at 1 Hz regardless of
|
|
||||||
radio traffic, and the app marks the link ERROR after ~3.5 s of silence.
|
|
||||||
Connected-and-staying-connected means device→host actually works. The board
|
|
||||||
starts its radio only after the app's STATION_CONFIGURE, so nothing is
|
|
||||||
received before Connect.
|
|
||||||
5. **If it connects but no V2X_RX ever arrives** — suspect DTR. The app now
|
|
||||||
asserts DTR/RTS on open (`openDevice()` in `UsbSerialTransport.kt`), because
|
|
||||||
`CdcAcmSerialDriver` doesn't do it by default and the ESP32's USB Serial/JTAG
|
|
||||||
endpoint may gate TX on the host opening the CDC line. **This is still
|
|
||||||
unverified on real hardware** — test it both ways (with the `setDTR(true)`
|
|
||||||
call and with it commented out) and record the answer in `serial_link.h`
|
|
||||||
next to the VID/PID note, so nobody has to guess again.
|
|
||||||
6. **Watch the counters, not just "Sent: N".** The CAM Pinger card shows
|
|
||||||
consecutive write failures (phone side) and the firmware's tx-failure /
|
|
||||||
RX-queue-drop / CRC-error totals from the heartbeat; the connection card
|
|
||||||
shows tickets, signed and refused counts. A rising `tx fail` means messages
|
|
||||||
reach the ESP32 but the radio refuses them — a radio problem, not a link
|
|
||||||
problem. A rising `refused` with signing on usually means no ticket (NVS
|
|
||||||
erased: reconnect so the app provisions again).
|
|
||||||
|
|
||||||
## Connecting over Bluetooth instead
|
|
||||||
|
|
||||||
Settings > Connection > ESP32-C5 > link: Bluetooth, then Connect. The board
|
|
||||||
advertises as `micrOBU-XXXX` (last two bytes of its BT MAC; `micrOBU-4AFA` on
|
|
||||||
COM3), but only while nothing uses its native USB port. Android asks to pair
|
|
||||||
the first time: passkey **123456** (fixed in `simple_ble.cpp`). The bond is kept
|
|
||||||
on both sides; the board keeps one bond, so pairing a second phone or a PC
|
|
||||||
replaces the first. Log lines on the console start with `cits_ble:`.
|
|
||||||
|
|
||||||
## Battery and pins (XIAO ESP32-C5)
|
## Battery and pins (XIAO ESP32-C5)
|
||||||
|
|
||||||
The prototype runs on the 3.7 V LiPo of an Intenso XS5000 power bank (5000 mAh), on the XIAO's BAT
|
The prototype runs on a 3.7 V LiPo on the BAT pads (cell `+` through a slide switch to **BAT+**,
|
||||||
pads: cell `+` through a slide switch to **BAT+**, cell `−` to **BAT−**. The board's SGM40567 charger
|
`−` to **BAT−**); the board's charger charges it from USB. Check the polarity with a multimeter
|
||||||
charges it from USB (the phone, or the PC). Check the polarity with a multimeter before connecting:
|
first: reversed, it destroys the board. **The cell has no protection board**, so only the firmware
|
||||||
reversed, the cell destroys the board. **The cell has no protection board** (the power bank's own
|
stops an over-discharge, and nothing stops a short.
|
||||||
circuit board did that job), so nothing but the firmware stops an over-discharge, and nothing at all
|
|
||||||
stops a short.
|
|
||||||
|
|
||||||
| Pin | GPIO | Used for |
|
| Pin | GPIO | Used for |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| (back pad) | GPIO6 | `BAT_VOLT_PIN`: the cell through two 100 kΩ resistors (ADC1) |
|
| on-board | GPIO6 | `BAT_VOLT_PIN`: BAT+ through the board's own 100 kΩ / 100 kΩ divider (ADC1); nothing to wire |
|
||||||
| (back pad) | GPIO26 | `BAT_VOLT_PIN_EN`: load switch that powers that divider, high only while measuring |
|
| on-board | GPIO26 | `BAT_VOLT_PIN_EN`: load switch for that divider, high only while measuring; nothing to wire |
|
||||||
| D6 / D7 | GPIO11 / GPIO12 | UART0 (console) |
|
| native USB | GPIO13 / GPIO14 | USB D− / D+ |
|
||||||
| native USB | GPIO13 / GPIO14 | USB D− / D+ (the phone link) |
|
| (user LED) | GPIO27 | yellow LED, active low: pulses on TX/RX (`CONFIG_MICROBU_STATUS_LED`) |
|
||||||
| — | GPIO27 | the yellow user LED, active low; `CONFIG_MICROBU_TX_LED_GPIO=27` turns the activity LED on |
|
|
||||||
|
|
||||||
(Pin names from Seeed's XIAO ESP32-C5 wiki; GPIO13/14 and the LED are the chip's defaults, not
|
Only the cell's `+` and `−` go to the BAT pads; the cell's two extra wires (temperature / ID) stay unconnected, the firmware does not use them. The voltage measurement needs no further wiring. `BatteryMonitor` (`battery_monitor.cpp`) reports the calibrated cell voltage as `battery_mv` in
|
||||||
re-checked against the schematic.) The cell's two extra wires (temperature / ID) are not used.
|
STATUS (octets 129-130, 0 = no cell or no sensor). `BatteryPolicy` (`battery_policy.hpp`, host-tested
|
||||||
|
in `test/host`) adds the protection, every 5 s: the smoothed voltage below 3.30 V for 30 s, more than
|
||||||
|
60 s after boot and with **no frame from a phone on USB in the last 5 s**, puts the board into deep
|
||||||
|
sleep; it wakes every 300 s, measures, and runs again from 3.60 V. A phone on USB powers the board,
|
||||||
|
so no shutdown happens then. Thresholds: `menuconfig -> micrOBU firmware`. The app shows
|
||||||
|
low/critical from the same voltage and its own thresholds.
|
||||||
|
|
||||||
What the firmware does with it (`battery.cpp`, `battery_monitor.hpp`):
|
## If the build fails
|
||||||
|
|
||||||
- Every 5 s it enables the divider, takes the median of 16 samples, disables it, and smooths the
|
`idf.py fullclean`, then build again. A "provided by component(s) ... not in the requirements list"
|
||||||
result. The cell voltage (twice the pin voltage) goes into the STATUS message the board sends
|
error means a header moved to another IDF component: add it to `REQUIRES` in `main/CMakeLists.txt`.
|
||||||
every second over USB and BLE: `battery_mv` u16 at octet 103 (0: no cell or no sensor) and
|
|
||||||
`battery_flags` u8 at 105 (bit 0 low, bit 1 critical). STATUS grew from 103 to 106 octets; the
|
|
||||||
app and the firmware both accept 103 (older board) or 106 and more. The colleague's Python
|
|
||||||
`Status.decode` requires exactly 103, so their `phone_emulator` rejects this board's STATUS.
|
|
||||||
- **Low** below 3.50 V (cleared at 3.60 V): the app shows an amber battery icon in the top bar and a
|
|
||||||
warning on the ESP32-C5 card. **Critical** below 3.30 V: red.
|
|
||||||
- **Shutdown:** when the smoothed voltage has stayed below 3.30 V for 30 s (6 samples), more than
|
|
||||||
60 s after boot, and **no phone has sent a frame over USB in the last 10 s**, the board sends a
|
|
||||||
last STATUS with the critical flag and goes into deep sleep. A phone on USB powers the board, so
|
|
||||||
the cell is not the reason it would stop and no shutdown happens. In deep sleep the board wakes
|
|
||||||
every 300 s, measures, and sleeps again until the cell reads 3.60 V (charged over USB); a reset
|
|
||||||
or power-cycle starts it normally and the rule applies again.
|
|
||||||
- The battery percentage in the app is a LiPo open-circuit-voltage table (`StationStatus.lipoPercent`):
|
|
||||||
an indicator, not a fuel gauge. It sags under TX and rises while charging.
|
|
||||||
|
|
||||||
All thresholds are `CONFIG_MICROBU_BATTERY_*` in `main/Kconfig.projbuild`. If the app's voltage
|
## Going back
|
||||||
differs from a multimeter on the cell, set `CONFIG_MICROBU_BATTERY_SCALE_PERMILLE` to
|
|
||||||
1000 × multimeter ÷ reading. Check it with `py -3.11 tools/station_status_watch.py COM10`: it
|
|
||||||
requests STATUS once a second and prints the battery fields.
|
|
||||||
|
|
||||||
Not measured yet: the charge current of the XIAO's charger (the wiki does not give it; a 5000 mAh
|
`firmware-backups/` (gitignored, on the lab laptop) holds full or 4 MB images of the boards as they
|
||||||
cell on a trickle charge takes days), whether the ADC reading is disturbed while the radio is
|
were before they were reflashed. Restore with
|
||||||
transmitting, and the board's own idle current from the cell. See TODO.md.
|
`python -m esptool --chip esp32c5 -p COM<N> write-flash 0 <image>`. The previous C firmware is in
|
||||||
|
git history (last commit before the port: `7285fa1`; the vanetza-idf port: `1c3a66e`).
|
||||||
## Notes
|
|
||||||
|
|
||||||
- No `git submodule update` needed here — obu-firmware has no pinned
|
|
||||||
submodule of its own, unlike its-g5-receiver-firmware.
|
|
||||||
- Don't use the global "ESP-IDF 5.5 PowerShell" shortcut or the receiver
|
|
||||||
firmware's 6.1 checkout — export from `esp-idf-v6.0.2`, the version the
|
|
||||||
vanetza-idf radio's undocumented driver internals were verified against.
|
|
||||||
- The console (ESP_LOG, boot messages, panics) stays on the UART-bridge port.
|
|
||||||
Opening it resets the board; do that only while nothing else depends on the
|
|
||||||
session.
|
|
||||||
|
|||||||
+69
-74
@@ -1,88 +1,83 @@
|
|||||||
# obu-firmware
|
# obu-firmware
|
||||||
|
|
||||||
## Since 2026-09-23: signed ITS on vanetza-idf
|
The production OBU firmware: the ESP32-C5 half of the MicrOBU station (Seeed XIAO ESP32-C5).
|
||||||
|
|
||||||
This firmware is a port of the colleague's standalone ESP32-C5 VRU station
|
## Since 2026-11-10: Niklas Dathe's microbu-firmware architecture
|
||||||
(`microbu-esp32c5/firmware`, in their own repository; only its `external/vanetza-idf` is copied
|
|
||||||
here, to `obu-firmware/external/vanetza-idf`).
|
|
||||||
From it: the vanetza-idf C-ITS stack (BTP, GeoNetworking, the TS 103 097 security entity with
|
|
||||||
credentials in NVS), the station-link protocol v1 (`link_protocol.*`, `link_service.*`) over the
|
|
||||||
native USB port (`serial_link.*`, frame type 0x10 in the same 0xAA55 framing as before) and over BLE
|
|
||||||
GATT (`simple_ble.*`), and the radio adapter (`c5_radio.*`, `otm_tx_custom.c`). Build with ESP-IDF
|
|
||||||
**6.0.2**; see FLASHING.md.
|
|
||||||
|
|
||||||
The phone builds CAM or VAM, configures the station, provisions credentials, sends PoTi and hands
|
This tree is the current station firmware written by Niklas Dathe (`microbu-firmware`, HAW GitLab
|
||||||
each message over as a BTP-DATA.request; the firmware adds GN/BTP, signs with the authorization
|
urban-mobility-lab/microbu/microbu-firmware, commit e4e4bd8) with the MicrOBU additions below. The
|
||||||
ticket, and transmits. The phone side is `Esp32Link.kt` in the app.
|
earlier port of their older `microbu-esp32c5` (vanetza-idf, 2026-09-23) is gone.
|
||||||
|
|
||||||
Changed or added for this project (search for `MicrOBU:` in the sources):
|
Layout:
|
||||||
|
|
||||||
- **Reception stays as it was.** vanetza-idf decapsulates with `itsGnSnDecapResultHandling =
|
| Path | What |
|
||||||
STRICT`, so it drops unsigned traffic (the bench sim car) and everything signed under a root other
|
| --- | --- |
|
||||||
than the provisioned demo root (every RSU). Every captured frame therefore also goes through the
|
| `main/` | station and link service: `station.cpp`, `link_*`, `serial_link.cpp`, `simple_ble.cpp`, `c5_radio.cpp`, board controls, battery |
|
||||||
previous firmware's `gn_unwrap.c` and reaches the phone as link opcode `V2X_RX` (0x85), whose body
|
| `components/microbu_v2x/` | station wrapper, security entity, device PKI client (unchanged from Niklas Dathe's firmware) |
|
||||||
is exactly the old `SERIAL_MSG_V2X_RX` payload (`Station::forward_raw`). The app's receive side is
|
| `components/vanetza/` | ESP-IDF component around Vanetza (unchanged) |
|
||||||
unchanged. Signed or not, BTP ports 2001 CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM and 2018 VAM
|
| `external/vanetza/` | patched upstream Vanetza source (unchanged, see its `UPSTREAM`) |
|
||||||
pass (MAPEM and VAM since 2026-10-28); a message over 494 bytes does not fit a 512-octet link
|
| `docs/station-link.tex` | the link interface reference this firmware and the app implement: **revision 2**, Niklas Dathe's revision 1 plus our extensions (the original PDF is `microbu-firmware/docs/station-link.pdf`; build ours with `pdflatex`, no LaTeX is installed on the lab laptop) |
|
||||||
message and is dropped and counted, not fragmented.
|
| `cmake/no_efuse_writes.cmake` | build guard: nothing in this firmware may program eFuses |
|
||||||
- **Bench listener** (`CONFIG_MICROBU_BENCH_LISTEN`, off in `sdkconfig`): for a board whose only PC
|
| `test/host/` | PC tests (`make` in that folder): the MicrOBU C code (`gn_unwrap.c`, `geonet.c`), the battery policy and, with `make firmware`, 39 unit tests of the link codec, V2X_RX and the policies |
|
||||||
connection is the UART0 console. It configures itself receive-only at boot and logs every V2X_RX;
|
|
||||||
`tools/bench_listen_watch.py COMx` tallies the log. Build it from a copy of `sdkconfig` with the
|
|
||||||
option on and `CONFIG_MICROBU_BATTERY_ADC_GPIO=-1` (on a board without the XIAO's cell divider,
|
|
||||||
GPIO6 floats and can read like a flat cell, which deep-sleeps the board), e.g. `idf.py -B build-bench -DSDKCONFIG=<copy> build`.
|
|
||||||
- **Unsigned transmission is still possible.** The colleague's station refuses unsecured requests.
|
|
||||||
Here a request with GN security profile 1 goes out with the previous firmware's `geonet.c` header
|
|
||||||
and the position of the last PoTi (`Station::unsecured_request`); the app's "Sign outgoing
|
|
||||||
messages" setting decides per message.
|
|
||||||
- **Console on UART0.** ESP_LOG stays on UART0 (GPIO11/12, pads D6/D7 on the XIAO); the native port
|
|
||||||
carries only link frames. The earlier bench board had a CH343 bridge on UART0 (COM3); the XIAO has
|
|
||||||
none, so its log is invisible unless a UART adapter is attached. The colleague's single-port board
|
|
||||||
routes the log into LOG frames on the native port (`CONFIG_MICROBU_LOG_OVER_LINK`, off here).
|
|
||||||
- **BLE pauses while USB is in use** (`CONFIG_MICROBU_BLE_USB_IDLE_MS`, 3 s): BLE and ITS-G5 share
|
|
||||||
the C5's one RF front end. Whether a live BLE connection disturbs 5.9 GHz is still unmeasured
|
|
||||||
(TODO.md).
|
|
||||||
- A serial write no longer stalls the station task when no USB host is present (BLE-only use).
|
|
||||||
- A notification longer than the ATT MTU is dropped instead of silently truncated.
|
|
||||||
- The Wi-Fi RX callback's 2.4 KB capture buffer is static rather than on the driver task's stack
|
|
||||||
(the previous firmware's commit 04b0076 fixed the same risk).
|
|
||||||
- Manual country policy and the TX-power read-back from the previous firmware's radio bring-up.
|
|
||||||
- The activity LED (GPIO27 on the XIAO) is off unless configured (`CONFIG_MICROBU_TX_LED_GPIO`).
|
|
||||||
- **Production board is the XIAO ESP32-C5 (2026-10-05):** 8 MB flash, one native USB-C port, flashed
|
|
||||||
on COM10 on the bench. Battery: STATUS carries `battery_mv`/`battery_flags` (octets 103-105, a
|
|
||||||
MicrOBU extension; decoders accept 103 or >= 106 octets) and the board deep-sleeps below 3.30 V
|
|
||||||
when no phone is on USB, to protect a cell with no protection board. Details and thresholds:
|
|
||||||
FLASHING.md, "Battery and pins".
|
|
||||||
|
|
||||||
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain generated 2026-09-23 with the
|
Take a newer release from Niklas Dathe by copying `firmware/{main,components,cmake}` and
|
||||||
colleague's `vidf_issue` (root `6E7D0374FB021901`, AA `B3312F29844299E0`, AT `B80B49387A4C12EB`
|
`external/vanetza` over these folders and re-applying the `MicrOBU:` changes (search the sources
|
||||||
valid two years, permissions psid 36 SSP `010000` and psid 638 SSP `01`). The colleague's own demo
|
for that word). Nothing is fetched from or pushed to their repository.
|
||||||
chain only grants psid 638 and so cannot sign CAMs. Not EU-registered: receivers that verify against
|
|
||||||
the EU trust list drop what it signs.
|
|
||||||
|
|
||||||
Time: the signature's generationTime comes from the PoTi timestamp, which follows the app's
|
Board: `CONFIG_MICROBU_BOARD_XIAO_C5` (sdkconfig.defaults). Their default is `mainboard-v5`, the
|
||||||
`ItsTime`: TimestampIts counts TAI milliseconds since 2004 (TS 102 894-2 V2.5.1), so it includes the
|
custom PCB; pick it in `menuconfig -> micrOBU firmware -> Board`.
|
||||||
5 leap seconds inserted since then, as the colleague's VBS does. Until 2026-10 the app left them out:
|
|
||||||
its PoTi set the micrOBU's clock 5 s behind, which made it reject other stations' messages as
|
|
||||||
Invalid_Timestamp and restart its stack whenever a correctly timed source had set the clock before.
|
|
||||||
|
|
||||||
## Earlier notes (Phase 2, superseded)
|
### MicrOBU additions (search for `MicrOBU`)
|
||||||
|
|
||||||
### OBU transmit firmware - Phase 2 (in progress: HLN-SV DENM beacon)
|
- **Reception of everything on air: `V2X_RX`, opcode `0x90`.** The stack decapsulates strictly, so it
|
||||||
|
drops unsigned traffic (the bench sim car) and everything signed under a root other than the
|
||||||
|
provisioned one (every RSU). Every received data frame therefore also goes through `gn_unwrap.c`
|
||||||
|
(`Station::forward_raw`) and reaches the phone as `V2X_RX`. Body: `u16 port, i8 rssi, u8 flags
|
||||||
|
(bit0 GBC area, bit1 signed), i32 lat, i32 lon, u16 distance_a, ITS payload`. `0x85` is the spec's
|
||||||
|
`RAW_FRAME` debug capture and `0x86` is reserved by Niklas Dathe, hence `0x90`. BTP ports 2001
|
||||||
|
CAM, 2002 DENM, 2003 MAPEM, 2004 SPATEM, 2018 VAM pass; a message over 494 bytes does not fit a
|
||||||
|
512-octet link message and is dropped and counted (not fragmented).
|
||||||
|
- **Unsigned transmission.** Niklas Dathe's station signs everything. A request with GN security
|
||||||
|
profile 1 (or 0 while the station is configured `security = 0`) goes out unsigned with
|
||||||
|
`geonet.c`'s header and the position of the last PoTi (`Station::unsecured_request`), from a
|
||||||
|
random locally administered MAC drawn at every STATION_CONFIGURE. The app's "Sign outgoing
|
||||||
|
messages" setting decides per message. It bypasses the BLE collision guard's queue but not the
|
||||||
|
guard itself.
|
||||||
|
- **Radio polled from configure on**, not from the first PoTi, so the 16-frame queue never overflows
|
||||||
|
while the phone has not sent a fix yet.
|
||||||
|
- **Radio bring-up** from the previous C firmware: manual country policy (5 GHz channels on), TX
|
||||||
|
power read-back logged, 2.4 KB receive buffer static instead of on the Wi-Fi task's stack, frames
|
||||||
|
too short to be GN packets ignored rather than counted as lost.
|
||||||
|
- **Battery guard.** Niklas Dathe's firmware only reports `battery_mv` in STATUS. A XIAO cell has no
|
||||||
|
protection board, so `battery_policy.hpp` (smoothing, warning hysteresis, shutdown) deep-sleeps the
|
||||||
|
board below 3.30 V for 30 s when no phone is on USB, re-checks every 5 min, and runs again from
|
||||||
|
3.60 V. Thresholds: `menuconfig -> micrOBU firmware`.
|
||||||
|
- **Serial link**: no write attempt while no USB host is connected; `last_frame_ms()` tells the battery
|
||||||
|
guard whether a phone is powering the board.
|
||||||
|
- **Partition table**: 80 KB NVS (Niklas Dathe's 24 KB filled up and BLE bonds stopped persisting),
|
||||||
|
app at `0x20000`. A plain app-only flash of an older layout is wrong: flash everything.
|
||||||
|
- **Flash size 8 MB** (XIAO), TX power ceiling 20 dBm (`radio_policy.hpp` admits 20 dBm on channel 180).
|
||||||
|
|
||||||
Started. See `docs/04-transmit-setup.md` in the project root for build/flash
|
### Link spec revision 2
|
||||||
steps and how to validate this against your own sniffer.
|
|
||||||
|
|
||||||
Implements one profile so far: **HLN-SV** (aftermarket stationary recovery
|
`docs/station-link.tex` is revision 2 of the interface reference: Niklas Dathe's revision 1 (microbu-firmware
|
||||||
vehicle), causeCode 94 (stationaryVehicle), subCauseCode 0, active while the
|
e4e4bd8, kept unchanged as `microbu-firmware/docs/station-link.pdf`) plus a section "MicrOBU extensions": `V2X_RX`
|
||||||
hazard-light GPIO is grounded. No location/alacarte containers.
|
(0x90), unsigned transmission (security profile 0x01, or 0x00 with `security` 0; random MAC per configure),
|
||||||
|
the battery shutdown rule, no USB writes without a host, and a revision history. The wire format of
|
||||||
|
revision 1 is unchanged, so a revision 1 host still works. No LaTeX is installed on the lab laptop: build
|
||||||
|
the PDF with `pdflatex station-link.tex` (twice) elsewhere.
|
||||||
|
|
||||||
- `main/main.c` - entry point, the `phy_11p_set`/`phy_change_channel(5900,...)`
|
### What the new firmware changes for the phone
|
||||||
register hack, GPIO polling, TX loop
|
|
||||||
- `main/denm.c` / `.h` - ASN.1 UPER encoding of a minimal DENM
|
|
||||||
- `main/geonet.c` / `.h` - GeoNetworking Basic/Common/SHB headers + BTP-B
|
|
||||||
- `main/dot11p.c` / `.h` - 802.11 OCB (QoS Data, broadcast) frame + LLC/SNAP
|
|
||||||
|
|
||||||
Known gaps, tracked as TODOs in the source: no real GNSS (lat/long hardcoded
|
See `docs/station-link.tex` (revision history at its end). In short: `RESULT`/`STATUS` became `CONFIRM` (0x80) with the 131-octet
|
||||||
0), no real time source (detectionTime/referenceTime hardcoded 0, decodes as
|
status in `CONFIRM.detail` of `STATUS_REQUEST`; STATION_CONFIGURE is 6 octets (type, channel, power,
|
||||||
2004-01-01), fixed (non-rotating) pseudonym MAC, SHB instead of GeoBroadcast
|
security, beaconing; no MAC, the address derives from the ticket); BTP-DATA.request carries
|
||||||
(no multi-hop forwarding), unsecured (no IEEE 1609.2 signing).
|
`generated_at_ms` (requests older than 1 s are refused); request bodies up to 1536 and indications up
|
||||||
|
to 65535 octets are fragmented; logs travel as LOG frames (0x7F) on the USB link, so a XIAO needs no
|
||||||
|
UART adapter any more.
|
||||||
|
|
||||||
|
Credentials: the app ships `assets/demo-chain.vcr`, a throwaway chain with psid 36 (CAM) and 638 (VAM).
|
||||||
|
Not EU-registered: receivers that verify against the EU trust list drop what it signs.
|
||||||
|
|
||||||
|
Time: TimestampIts counts TAI milliseconds since 2004 (TS 102 894-2), 5 leap seconds ahead of UTC;
|
||||||
|
the app's `ItsTime` follows that.
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Reject SDK features that can program permanent chip state or auto-create hardware keys.
|
||||||
|
foreach(_microbu_option
|
||||||
|
CONFIG_SECURE_BOOT
|
||||||
|
CONFIG_SECURE_FLASH_ENC_ENABLED
|
||||||
|
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK
|
||||||
|
CONFIG_BOOTLOADER_ANTI_ROLLBACK_ENABLE
|
||||||
|
CONFIG_SECURE_DISABLE_ROM_DL_MODE
|
||||||
|
CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE
|
||||||
|
CONFIG_NVS_ENCRYPTION
|
||||||
|
CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC
|
||||||
|
CONFIG_ESP_TEE)
|
||||||
|
if(${_microbu_option})
|
||||||
|
message(FATAL_ERROR "${_microbu_option} is forbidden: this firmware must not program eFuses or auto-provision hardware keys")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
# micrOBU V2X runtime on the Vanetza component (LGPL-3.0-or-later).
|
||||||
|
cmake_minimum_required(VERSION 3.22)
|
||||||
|
set(V2X_PORT "${CMAKE_CURRENT_LIST_DIR}")
|
||||||
|
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
# IDF dependency discovery evaluates this file before Kconfig is available.
|
||||||
|
idf_component_register(SRCS "${V2X_PORT}/src/access.cpp"
|
||||||
|
INCLUDE_DIRS "${V2X_PORT}/include"
|
||||||
|
REQUIRES vanetza mbedtls ${MICROBU_CRYPTO_ADAPTER_COMPONENT}
|
||||||
|
PRIV_REQUIRES esp_wifi esp_phy esp_event nvs_flash)
|
||||||
|
if(CMAKE_BUILD_EARLY_EXPANSION)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
if(NOT CONFIG_COMPILER_CXX_EXCEPTIONS OR NOT CONFIG_COMPILER_CXX_RTTI)
|
||||||
|
message(FATAL_ERROR "microbu_v2x requires CONFIG_COMPILER_CXX_EXCEPTIONS=y and CONFIG_COMPILER_CXX_RTTI=y")
|
||||||
|
endif()
|
||||||
|
set(V2X_TARGET ${COMPONENT_LIB})
|
||||||
|
set(V2X_NETWORK ${CONFIG_MICROBU_V2X_NETWORK})
|
||||||
|
set(V2X_CAM ${CONFIG_MICROBU_V2X_CAM})
|
||||||
|
set(V2X_DENM ${CONFIG_MICROBU_V2X_DENM})
|
||||||
|
set(V2X_VAM ${CONFIG_MICROBU_V2X_VAM})
|
||||||
|
set(V2X_HIL ${CONFIG_MICROBU_V2X_HIL})
|
||||||
|
set(V2X_SECURITY ${CONFIG_MICROBU_V2X_SECURITY})
|
||||||
|
set(V2X_SECURITY_VERIFY ${CONFIG_MICROBU_V2X_SECURITY_VERIFY})
|
||||||
|
set(V2X_PKI ${CONFIG_MICROBU_V2X_PKI})
|
||||||
|
set(V2X_NVS_CREDENTIALS ${CONFIG_MICROBU_V2X_NVS_CREDENTIALS})
|
||||||
|
else()
|
||||||
|
project(microbu_v2x LANGUAGES C CXX)
|
||||||
|
option(V2X_NETWORK "GeoNetworking router, BTP and DCC" ON)
|
||||||
|
option(V2X_CAM "Release 2 CAM codec/endpoint" ON)
|
||||||
|
option(V2X_DENM "Release 2 DENM codec/endpoint" ON)
|
||||||
|
option(V2X_VAM "Release 2 VAM codec/endpoint" ON)
|
||||||
|
set(V2X_HIL OFF)
|
||||||
|
option(V2X_SECURITY "TS 103 097 signing security entity and TS 102 723-8 identifier-change service" ON)
|
||||||
|
option(V2X_SECURITY_VERIFY "SN-DECAP verification of received secured packets (IEEE 1609.2 clause 5.2, TS 103 097 clause 7.1)" ON)
|
||||||
|
option(V2X_PKI "TS 102 941 enrolment/authorization request-response core" OFF)
|
||||||
|
set(V2X_MBEDTLS_ROOT "" CACHE PATH
|
||||||
|
"Host only: mbedTLS (>= 3.6 or 4.x/TF-PSA-Crypto) source tree; builds the PSA backend for testing against OpenSSL")
|
||||||
|
set(VANETZA_SOURCE_DIR "" CACHE PATH
|
||||||
|
"Host only: an already patched Vanetza tree (default: build it from external/vanetza and ../vanetza/patches)")
|
||||||
|
add_subdirectory("${V2X_PORT}/../vanetza" "${CMAKE_BINARY_DIR}/vanetza")
|
||||||
|
add_library(microbu_v2x STATIC src/access.cpp)
|
||||||
|
add_library(Microbu::v2x ALIAS microbu_v2x)
|
||||||
|
set(V2X_TARGET microbu_v2x)
|
||||||
|
target_include_directories(${V2X_TARGET} PUBLIC include)
|
||||||
|
target_link_libraries(${V2X_TARGET} PUBLIC vanetza)
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_features(${V2X_TARGET} PUBLIC cxx_std_17)
|
||||||
|
set_target_properties(${V2X_TARGET} PROPERTIES C_STANDARD 11 CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
|
||||||
|
if(V2X_SECURITY AND NOT V2X_NETWORK)
|
||||||
|
message(FATAL_ERROR "The security entity serves the GeoNetworking layer: V2X_SECURITY requires V2X_NETWORK")
|
||||||
|
endif()
|
||||||
|
if(V2X_SECURITY_VERIFY AND NOT V2X_SECURITY)
|
||||||
|
message(FATAL_ERROR "V2X_SECURITY_VERIFY requires V2X_SECURITY")
|
||||||
|
endif()
|
||||||
|
if(V2X_PKI AND NOT V2X_SECURITY)
|
||||||
|
message(FATAL_ERROR "V2X_PKI requires V2X_SECURITY")
|
||||||
|
endif()
|
||||||
|
target_compile_definitions(${V2X_TARGET} PUBLIC
|
||||||
|
V2X_NETWORK=$<BOOL:${V2X_NETWORK}> V2X_CAM=$<BOOL:${V2X_CAM}>
|
||||||
|
V2X_DENM=$<BOOL:${V2X_DENM}> V2X_VAM=$<BOOL:${V2X_VAM}> V2X_HIL=$<BOOL:${V2X_HIL}>
|
||||||
|
V2X_SECURITY=$<BOOL:${V2X_SECURITY}> V2X_SECURITY_VERIFY=$<BOOL:${V2X_SECURITY_VERIFY}>
|
||||||
|
V2X_PKI=$<BOOL:${V2X_PKI}>)
|
||||||
|
set(_sources "${V2X_PORT}/src/its_g5_frame.cpp")
|
||||||
|
if(V2X_NETWORK)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/stack.cpp" "${V2X_PORT}/src/management.cpp")
|
||||||
|
if(NOT ESP_PLATFORM)
|
||||||
|
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
|
||||||
|
target_link_libraries(${V2X_TARGET} PRIVATE OpenSSL::Crypto)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
if(V2X_CAM OR V2X_DENM OR V2X_VAM)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/facilities.cpp")
|
||||||
|
endif()
|
||||||
|
if(V2X_HIL)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/hil.cpp")
|
||||||
|
endif()
|
||||||
|
if(V2X_SECURITY)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/ecc.cpp" "${V2X_PORT}/src/security_module.cpp"
|
||||||
|
"${V2X_PORT}/src/security.cpp" "${V2X_PORT}/src/identity_manager.cpp"
|
||||||
|
"${V2X_PORT}/src/sign_header_policy.cpp" "${V2X_PORT}/src/credentials.cpp")
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp" "${V2X_PORT}/src/security_backend.cpp"
|
||||||
|
"${V2X_PORT}/src/local_security.cpp")
|
||||||
|
if(CONFIG_MICROBU_V2X_CRYPTO_SE051 OR CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM)
|
||||||
|
if(NOT MICROBU_CRYPTO_ADAPTER_COMPONENT)
|
||||||
|
message(FATAL_ERROR "External security module selected: set MICROBU_CRYPTO_ADAPTER_COMPONENT to a real adapter component")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
|
||||||
|
if(V2X_NVS_CREDENTIALS)
|
||||||
|
# CredentialStore on nvs_flash (credentials.hpp); the application initialises NVS
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/nvs_credential_store.cpp")
|
||||||
|
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_NVS_CREDENTIALS=1)
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_OPENSSL=1)
|
||||||
|
target_compile_definitions(${V2X_TARGET} PRIVATE OPENSSL_API_COMPAT=0x10101000L)
|
||||||
|
if(V2X_MBEDTLS_ROOT)
|
||||||
|
set(ENABLE_PROGRAMS OFF CACHE BOOL "" FORCE)
|
||||||
|
set(ENABLE_TESTING OFF CACHE BOOL "" FORCE)
|
||||||
|
set(MBEDTLS_FATAL_WARNINGS OFF CACHE BOOL "" FORCE)
|
||||||
|
set(GEN_FILES OFF CACHE BOOL "" FORCE)
|
||||||
|
# ESP-IDF's mbedTLS fork includes "mbedtls/bignum.h"/"mbedtls/ecp.h" wrappers that only
|
||||||
|
# its own port directory provides (they wrap the TF-PSA-Crypto private headers and add
|
||||||
|
# hardware-acceleration hooks). Recreate the plain wrappers so the same tree builds here.
|
||||||
|
set(_v2x_mbedtls_shim "${CMAKE_BINARY_DIR}/mbedtls-shim/mbedtls")
|
||||||
|
foreach(_hdr bignum ecp)
|
||||||
|
if(EXISTS "${V2X_MBEDTLS_ROOT}/tf-psa-crypto/drivers/builtin/include/mbedtls/private/${_hdr}.h"
|
||||||
|
AND NOT EXISTS "${V2X_MBEDTLS_ROOT}/include/mbedtls/${_hdr}.h")
|
||||||
|
file(WRITE "${_v2x_mbedtls_shim}/${_hdr}.h"
|
||||||
|
"#pragma once
|
||||||
|
#define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
|
||||||
|
#include \"mbedtls/private/${_hdr}.h\"
|
||||||
|
")
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
if(EXISTS "${_v2x_mbedtls_shim}")
|
||||||
|
file(WRITE "${CMAKE_BINARY_DIR}/mbedtls-shim/sdkconfig.h" "#pragma once
|
||||||
|
")
|
||||||
|
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -I${CMAKE_BINARY_DIR}/mbedtls-shim")
|
||||||
|
endif()
|
||||||
|
add_subdirectory("${V2X_MBEDTLS_ROOT}" "${CMAKE_BINARY_DIR}/mbedtls" EXCLUDE_FROM_ALL)
|
||||||
|
if(TARGET tfpsacrypto)
|
||||||
|
set(_v2x_psa tfpsacrypto) # mbedTLS 4.x
|
||||||
|
else()
|
||||||
|
set(_v2x_psa mbedcrypto) # mbedTLS 3.x
|
||||||
|
endif()
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/backend_mbedtls.cpp")
|
||||||
|
target_link_libraries(${V2X_TARGET} PUBLIC ${_v2x_psa})
|
||||||
|
target_compile_definitions(${V2X_TARGET} PUBLIC V2X_BACKEND_MBEDTLS=1)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
if(V2X_PKI)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/pki.cpp" "${V2X_PORT}/src/trust_update.cpp")
|
||||||
|
if(ESP_PLATFORM OR V2X_MBEDTLS_ROOT)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/ecies_mbedtls.cpp")
|
||||||
|
endif()
|
||||||
|
if(NOT ESP_PLATFORM)
|
||||||
|
list(APPEND _sources "${V2X_PORT}/src/ecies_openssl.cpp")
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
list(REMOVE_DUPLICATES _sources)
|
||||||
|
target_sources(${V2X_TARGET} PRIVATE ${_sources})
|
||||||
|
if(ESP_PLATFORM AND CONFIG_MICROBU_V2X_RADIO_C5)
|
||||||
|
include("${V2X_PORT}/radio_c5.cmake")
|
||||||
|
endif()
|
||||||
|
if(ESP_PLATFORM AND CONFIG_IDF_TARGET_ESP32C5)
|
||||||
|
# ROM UART0 clock repair for warm resets (see the source); kept by an undefined-symbol reference.
|
||||||
|
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/esp32c5_rom_uart_clock.c")
|
||||||
|
target_link_libraries(${V2X_TARGET} INTERFACE "-u v2x_esp32c5_rom_uart_clock_link")
|
||||||
|
endif()
|
||||||
|
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||||
|
target_compile_options(${V2X_TARGET} PRIVATE -ffunction-sections -fdata-sections
|
||||||
|
-Wno-error=deprecated-declarations)
|
||||||
|
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15)
|
||||||
|
target_compile_options(${V2X_TARGET} PRIVATE -Wno-error=deprecated-variadic-comma-omission)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
target_compile_options(${V2X_TARGET} PRIVATE
|
||||||
|
$<$<COMPILE_LANGUAGE:C>:-Wno-error=unused-function>
|
||||||
|
$<$<COMPILE_LANGUAGE:C>:-Wno-error=maybe-uninitialized>)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
menu "micrOBU V2X stack (Vanetza)"
|
||||||
|
choice MICROBU_V2X_PROFILE
|
||||||
|
prompt "Stack entry point"
|
||||||
|
default MICROBU_V2X_PROFILE_NETWORK
|
||||||
|
config MICROBU_V2X_PROFILE_ACCESS
|
||||||
|
bool "Access: AL_DATA / IN-SAP"
|
||||||
|
config MICROBU_V2X_PROFILE_NETWORK
|
||||||
|
bool "Network: BTP-DATA / NF-SAP"
|
||||||
|
config MICROBU_V2X_PROFILE_FACILITIES
|
||||||
|
bool "Facilities endpoints (CAM, DENM, VAM)"
|
||||||
|
endchoice
|
||||||
|
config MICROBU_V2X_NETWORK
|
||||||
|
bool
|
||||||
|
default y if !MICROBU_V2X_PROFILE_ACCESS
|
||||||
|
config MICROBU_V2X_CAM
|
||||||
|
bool "Release 2 CAM codec and endpoint"
|
||||||
|
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||||
|
depends on MICROBU_V2X_NETWORK
|
||||||
|
config MICROBU_V2X_DENM
|
||||||
|
bool "Release 2 DENM codec and endpoint"
|
||||||
|
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||||
|
depends on MICROBU_V2X_NETWORK
|
||||||
|
config MICROBU_V2X_VAM
|
||||||
|
bool "Release 2 VAM codec and endpoint"
|
||||||
|
default y if MICROBU_V2X_PROFILE_FACILITIES
|
||||||
|
depends on MICROBU_V2X_NETWORK
|
||||||
|
config MICROBU_V2X_SECURITY
|
||||||
|
bool "TS 103 097 signing security entity and identifier-change service"
|
||||||
|
default y
|
||||||
|
depends on MICROBU_V2X_NETWORK
|
||||||
|
help
|
||||||
|
SN-SAP security entity: signs outgoing GeoNetworking packets with
|
||||||
|
authorization tickets the application provisions (TS 103 097
|
||||||
|
V2.2.1, IEEE Std 1609.2) on the mbedTLS PSA backend and runs the
|
||||||
|
TS 102 723-8 clause 6.3 identifier-change two-phase commit that
|
||||||
|
the GN core, access adapter and facilities subscribe to. Without
|
||||||
|
it a stack with itsGnSecurity enabled fails closed.
|
||||||
|
choice MICROBU_V2X_CRYPTO
|
||||||
|
prompt "Security module"
|
||||||
|
depends on MICROBU_V2X_SECURITY
|
||||||
|
default MICROBU_V2X_CRYPTO_ESP32
|
||||||
|
help
|
||||||
|
Where the station's private keys live and are used
|
||||||
|
(security_module.hpp). Hashing, verification and point
|
||||||
|
decompression run on the ESP32 PSA backend unless the V2X HSM
|
||||||
|
takes them as well.
|
||||||
|
config MICROBU_V2X_CRYPTO_ESP32
|
||||||
|
bool "Software on the ESP32 (keys in NVS, PSA crypto)"
|
||||||
|
config MICROBU_V2X_CRYPTO_SE051
|
||||||
|
bool "SE051 over I2C (requires an adapter component)"
|
||||||
|
config MICROBU_V2X_CRYPTO_V2X_HSM
|
||||||
|
bool "V2X HSM for keys and public operations (requires an adapter component)"
|
||||||
|
endchoice
|
||||||
|
config MICROBU_V2X_SECURITY_VERIFY
|
||||||
|
bool "SN-DECAP verification of received secured packets"
|
||||||
|
default y
|
||||||
|
depends on MICROBU_V2X_SECURITY
|
||||||
|
help
|
||||||
|
Verify received EtsiTs103097Data-Signed packets (IEEE 1609.2
|
||||||
|
clause 5.2 with the TS 103 097 clause 7.1 profile checks, the
|
||||||
|
certificate chain to the provisioned trust anchors, generation
|
||||||
|
time plausibility and replay detection). Without it SN-DECAP
|
||||||
|
reports Configuration_Problem and a strict GeoNetworking receiver
|
||||||
|
drops every secured packet.
|
||||||
|
config MICROBU_V2X_NVS_CREDENTIALS
|
||||||
|
bool "Credential store on NVS"
|
||||||
|
default y
|
||||||
|
depends on MICROBU_V2X_SECURITY
|
||||||
|
help
|
||||||
|
NvsCredentialStore keeps the station's provisioned credentials
|
||||||
|
(root and CA certificates, authorization tickets with their
|
||||||
|
private keys, credentials.hpp bundle) as one blob in the
|
||||||
|
nvs_flash component's storage. The application initialises NVS
|
||||||
|
and decides on NVS encryption; without this option the
|
||||||
|
application supplies its own CredentialStore.
|
||||||
|
config MICROBU_V2X_PKI
|
||||||
|
bool "TS 102 941 enrolment and authorization request-response core"
|
||||||
|
default n
|
||||||
|
depends on MICROBU_V2X_SECURITY
|
||||||
|
help
|
||||||
|
Builds and parses EtsiTs102941Data enrolment/authorization
|
||||||
|
requests and responses (TS 102 941 V2.2.1 clause 6.2.3). The
|
||||||
|
transport to the EA/AA and credential storage are supplied by the
|
||||||
|
application.
|
||||||
|
choice MICROBU_V2X_RADIO
|
||||||
|
prompt "Access adapter"
|
||||||
|
default MICROBU_V2X_RADIO_EXTERNAL
|
||||||
|
config MICROBU_V2X_RADIO_EXTERNAL
|
||||||
|
bool "Application-provided access adapter"
|
||||||
|
config MICROBU_V2X_RADIO_C5
|
||||||
|
bool "Experimental integrated ESP32-C5 ITS-G5 radio"
|
||||||
|
depends on IDF_TARGET_ESP32C5
|
||||||
|
help
|
||||||
|
Uses OpenTrafficMap's private driver transmit path. Only the
|
||||||
|
pinned ESP-IDF version is accepted. Hardware/RF and DCC
|
||||||
|
qualification remain separate acceptance requirements.
|
||||||
|
endchoice
|
||||||
|
endmenu
|
||||||
+14
-15
@@ -4,12 +4,12 @@
|
|||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#if VIDF_NETWORK
|
#if V2X_NETWORK
|
||||||
#include <vanetza/common/runtime.hpp>
|
#include <vanetza/common/runtime.hpp>
|
||||||
#include <vanetza/dcc/channel_load.hpp>
|
#include <vanetza/dcc/channel_load.hpp>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
|
|
||||||
// Implementation result, NOT an additional ETSI AL-DATA.confirm primitive.
|
// Implementation result, NOT an additional ETSI AL-DATA.confirm primitive.
|
||||||
enum class Result { accepted, invalid_argument, unsupported, wrong_entry_point,
|
enum class Result { accepted, invalid_argument, unsupported, wrong_entry_point,
|
||||||
@@ -24,7 +24,7 @@ enum class OfdmMcs : std::uint8_t {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** Technology-specific AL_DATA.request: EN 303 797 V2.1.1, Annex B.2.
|
/** Technology-specific AL_DATA.request: EN 303 797 V2.1.1, Annex B.2.
|
||||||
* See docs/idf/standards.md (IF-IN-001). This is the AL_DATA binding,
|
* See EN 303 797 V2.1.1 Annex B. This is the AL_DATA binding,
|
||||||
* not the separate IN-UNITDATA interface of TS 102 723-10.
|
* not the separate IN-UNITDATA interface of TS 102 723-10.
|
||||||
* This C++ binding is local: the standard does not prescribe a C++/BLE ABI.
|
* This C++ binding is local: the standard does not prescribe a C++/BLE ABI.
|
||||||
* Owns the GNPDU bytes; they exclude LLC, MAC and PHY headers.
|
* Owns the GNPDU bytes; they exclude LLC, MAC and PHY headers.
|
||||||
@@ -43,7 +43,7 @@ struct AlDataRequest {
|
|||||||
vanetza::ByteBuffer data;
|
vanetza::ByteBuffer data;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** AL_DATA.indication, EN 303 797 V2.1.1 Annex B.2 (IF-IN-002).
|
/** AL_DATA.indication, EN 303 797 V2.1.1 Annex B.2.
|
||||||
* Optional radio measurements are absent when the backend cannot measure them;
|
* Optional radio measurements are absent when the backend cannot measure them;
|
||||||
* zero must never stand for a made-up measurement.
|
* zero must never stand for a made-up measurement.
|
||||||
*/
|
*/
|
||||||
@@ -72,13 +72,13 @@ Result validate(const AlDataRequest&, std::size_t maximum_gnpdu);
|
|||||||
|
|
||||||
/** Access profile has no BTP/GN state and preserves the AL_DATA parameters.
|
/** Access profile has no BTP/GN state and preserves the AL_DATA parameters.
|
||||||
*
|
*
|
||||||
* On a VIDF_NETWORK build, optionally runs DCC_ACC (TS 102 687 V1.2.1 clause 5.4 Adaptive
|
* On a V2X_NETWORK build, optionally runs DCC_ACC (TS 102 687 V1.2.1 clause 5.4 Adaptive
|
||||||
* approach, gated by the Annex B budget/gate-keeper) in front of the backend, per
|
* approach, gated by the Annex B budget/gate-keeper) in front of the backend.
|
||||||
* SYS-DCC-001/GAP-DCC-001. Disabled by default so existing callers (host tests, other
|
* Disabled by default so existing callers (host tests, other
|
||||||
* applications) are unaffected; the ESP32-C5 firmware enables it once it has a real CBR
|
* applications) are unaffected; the ESP32-C5 firmware enables it once it has a real CBR
|
||||||
* source (SYS-DCC-002). The DCC methods below do not exist on an access-only build (no
|
* source. The DCC methods below do not exist on an access-only build (no
|
||||||
* VIDF_NETWORK): the Adaptive approach lives in vanetza/dcc, which that configuration does
|
* V2X_NETWORK): the Adaptive approach lives in vanetza/dcc, which that configuration does
|
||||||
* not compile, matching the documented access-only deployment (docs/idf/conformance.md).
|
* not compile, matching the documented access-only deployment (docs/conformance.md).
|
||||||
*/
|
*/
|
||||||
class AccessStack {
|
class AccessStack {
|
||||||
public:
|
public:
|
||||||
@@ -87,9 +87,9 @@ public:
|
|||||||
AccessStack(const AccessStack&) = delete;
|
AccessStack(const AccessStack&) = delete;
|
||||||
AccessStack& operator=(const AccessStack&) = delete;
|
AccessStack& operator=(const AccessStack&) = delete;
|
||||||
|
|
||||||
#if VIDF_NETWORK
|
#if V2X_NETWORK
|
||||||
/** Enable the Adaptive DCC_ACC gate. cbr_target defaults to TS 103 836-4-2's
|
/** Enable the Adaptive DCC_ACC gate. cbr_target defaults to TS 103 836-4-2's
|
||||||
* itsGNCBRTarget = 0.62, the value the project's SYS-DCC-001/002/003 use consistently
|
* itsGNCBRTarget = 0.62
|
||||||
* (not TS 102 687 Table 3's older, superseded 0.68 default).
|
* (not TS 102 687 Table 3's older, superseded 0.68 default).
|
||||||
* runtime must outlive this AccessStack and must be the same Runtime driving the caller's
|
* runtime must outlive this AccessStack and must be the same Runtime driving the caller's
|
||||||
* periodic advance()/trigger() (e.g. the Stack's ManualRuntime), since the Adaptive approach
|
* periodic advance()/trigger() (e.g. the Stack's ManualRuntime), since the Adaptive approach
|
||||||
@@ -99,8 +99,7 @@ public:
|
|||||||
void enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target = vanetza::dcc::ChannelLoad(0.62));
|
void enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target = vanetza::dcc::ChannelLoad(0.62));
|
||||||
|
|
||||||
/** Feed the latest channel-busy-ratio measurement at roughly the T_Cbr cadence (100 ms):
|
/** Feed the latest channel-busy-ratio measurement at roughly the T_Cbr cadence (100 ms):
|
||||||
* local LCBR (SYS-DCC-002), or CBR_G when a Release-2 DCC_NET has one available
|
* local LCBR, or CBR_G when a Release-2 DCC_NET has one available. No-op unless
|
||||||
* (SYS-DCC-001: "consume Release-2 CBR_G when available, otherwise LCBR"). No-op unless
|
|
||||||
* enable_dcc was called.
|
* enable_dcc was called.
|
||||||
*/
|
*/
|
||||||
void report_channel_load(vanetza::dcc::ChannelLoad);
|
void report_channel_load(vanetza::dcc::ChannelLoad);
|
||||||
@@ -113,7 +112,7 @@ public:
|
|||||||
|
|
||||||
Result request(AlDataRequest);
|
Result request(AlDataRequest);
|
||||||
private:
|
private:
|
||||||
#if VIDF_NETWORK
|
#if V2X_NETWORK
|
||||||
class Dcc;
|
class Dcc;
|
||||||
std::unique_ptr<Dcc> dcc_;
|
std::unique_ptr<Dcc> dcc_;
|
||||||
#endif
|
#endif
|
||||||
+7
-4
@@ -1,8 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <microbu_v2x/security_module.hpp>
|
||||||
#include <vanetza/security/backend.hpp>
|
#include <vanetza/security/backend.hpp>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
|
|
||||||
/** vanetza::security::Backend on the PSA Crypto API of mbedTLS.
|
/** vanetza::security::Backend on the PSA Crypto API of mbedTLS.
|
||||||
*
|
*
|
||||||
@@ -16,14 +17,14 @@ namespace vanetza_idf {
|
|||||||
* (PSA_ALG_ECDSA(SHA-256/SHA-384) over the caller-supplied digest of that
|
* (PSA_ALG_ECDSA(SHA-256/SHA-384) over the caller-supplied digest of that
|
||||||
* length, which lets ESP-IDF's PSA driver use the ESP32-C5 ECDSA peripheral for
|
* length, which lets ESP-IDF's PSA driver use the ESP32-C5 ECDSA peripheral for
|
||||||
* verification; IEEE Std 1609.2 does not require RFC 6979). Compressed points
|
* verification; IEEE Std 1609.2 does not require RFC 6979). Compressed points
|
||||||
* are recovered by vanetza_idf::ecc, since PSA imports Weierstrass public keys
|
* are recovered by microbu_v2x::ecc, since PSA imports Weierstrass public keys
|
||||||
* only in SEC 1 uncompressed form.
|
* only in SEC 1 uncompressed form.
|
||||||
*
|
*
|
||||||
* Private keys are imported as volatile PSA keys the first time they are used
|
* Private keys are imported as volatile PSA keys the first time they are used
|
||||||
* and kept in a small bounded cache until the backend is destroyed. Every
|
* and kept in a small bounded cache until the backend is destroyed. Every
|
||||||
* failure raises std::runtime_error or returns false; nothing is faked.
|
* failure raises std::runtime_error or returns false; nothing is faked.
|
||||||
*/
|
*/
|
||||||
class BackendMbedTls : public vanetza::security::Backend {
|
class BackendMbedTls : public vanetza::security::Backend, public security::KeyGenerator {
|
||||||
public:
|
public:
|
||||||
static constexpr auto backend_name = "mbedTLS-PSA";
|
static constexpr auto backend_name = "mbedTLS-PSA";
|
||||||
|
|
||||||
@@ -47,6 +48,8 @@ public:
|
|||||||
vanetza::ByteBuffer calculate_hash(vanetza::security::HashAlgorithm, const vanetza::ByteBuffer&) override;
|
vanetza::ByteBuffer calculate_hash(vanetza::security::HashAlgorithm, const vanetza::ByteBuffer&) override;
|
||||||
/// Fresh NIST P-256 key pair from the PSA random generator
|
/// Fresh NIST P-256 key pair from the PSA random generator
|
||||||
vanetza::security::ecdsa256::KeyPair generate_key_pair() override;
|
vanetza::security::ecdsa256::KeyPair generate_key_pair() override;
|
||||||
|
/// Fresh ECDSA key pair on any TS 103 097 curve from the PSA random generator (SoftwareSecurityModule)
|
||||||
|
security::KeyPair generate_key(vanetza::security::KeyType) override;
|
||||||
|
|
||||||
/** Maximum number of imported private keys kept resident (default 4:
|
/** Maximum number of imported private keys kept resident (default 4:
|
||||||
* the current and next authorization tickets plus enrolment material). */
|
* the current and next authorization tickets plus enrolment material). */
|
||||||
@@ -57,4 +60,4 @@ private:
|
|||||||
std::unique_ptr<Impl> impl_;
|
std::unique_ptr<Impl> impl_;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vanetza_idf
|
} // namespace microbu_v2x
|
||||||
+4
-4
@@ -1,14 +1,14 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <sdkconfig.h>
|
#include <sdkconfig.h>
|
||||||
#if !defined(CONFIG_IDF_TARGET_ESP32C5) || !defined(CONFIG_VANETZA_IDF_RADIO_C5)
|
#if !defined(CONFIG_IDF_TARGET_ESP32C5) || !defined(CONFIG_MICROBU_V2X_RADIO_C5)
|
||||||
#error "C5Radio requires ESP32-C5 and CONFIG_VANETZA_IDF_RADIO_C5"
|
#error "C5Radio requires ESP32-C5 and CONFIG_MICROBU_V2X_RADIO_C5"
|
||||||
#endif
|
#endif
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <esp_err.h>
|
#include <esp_err.h>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
struct C5RadioConfig {
|
struct C5RadioConfig {
|
||||||
std::uint16_t channel_number = 180;
|
std::uint16_t channel_number = 180;
|
||||||
double transmit_power_dbm = 10.0;
|
double transmit_power_dbm = 10.0;
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/security.hpp>
|
||||||
|
#include <optional>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/** A station's provisioned credentials and how they are kept.
|
||||||
|
*
|
||||||
|
* TS 102 940 V2.1.1 clause 6 (trust model: root CA, EA/AA, tickets) and TS 102 941
|
||||||
|
* V2.2.1 (credential life cycle) leave the obtaining and keeping of certificates to
|
||||||
|
* the station; TS 102 723-8 has no primitive for it. The security entity takes
|
||||||
|
* them as a TrustConfiguration and a CertificatePool (security.hpp). This header
|
||||||
|
* fixes the octets in between. Certificates are COER EtsiTs103097Certificate
|
||||||
|
* values (TS 103 097 V2.2.1 clause 6).
|
||||||
|
*
|
||||||
|
* Credentials is the laboratory provisioning bundle, which carries the private
|
||||||
|
* scalar of each ticket's verification key (IEEE Std 1609.2 clause 6.4.36 curves).
|
||||||
|
* Format (this library's definition, version 1): the ASCII magic "VCR1" followed
|
||||||
|
* by records [type: 1 octet][length: 2 octets, big-endian][payload]. Types: 1 root
|
||||||
|
* CA certificate, 2 subordinate CA certificate (AA/EA), 3 ticket certificate, 4
|
||||||
|
* ticket private key ([curve: 1 octet, 1 = NIST P-256, 2 = brainpoolP256r1, 3 =
|
||||||
|
* brainpoolP384r1][scalar]) which follows its ticket certificate. The keys travel
|
||||||
|
* in the clear, so the transport must be a trusted one. import_keys() moves them
|
||||||
|
* into the security module.
|
||||||
|
*
|
||||||
|
* StoredCredentials is what the station keeps: the same certificates, and for each
|
||||||
|
* ticket the KeyId of its key in the security module instead of the key. Format
|
||||||
|
* "VCS1" with the record types 1 to 3 above and 5, the KeyId (4 octets, big-endian),
|
||||||
|
* which follows its ticket certificate. Decoding fails closed on any deviation.
|
||||||
|
*/
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
|
struct Credentials {
|
||||||
|
struct Ticket {
|
||||||
|
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
|
||||||
|
PrivateKey key; // private scalar of verifyKeyIndicator
|
||||||
|
};
|
||||||
|
std::vector<ByteBuffer> roots; // clause 7.2.3, self-signed
|
||||||
|
std::vector<ByteBuffer> authorities; // clause 7.2.4, issued by a root or another CA
|
||||||
|
std::vector<Ticket> tickets; // clause 7.2.1, with keys
|
||||||
|
|
||||||
|
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
struct StoredCredentials {
|
||||||
|
struct Ticket {
|
||||||
|
ByteBuffer certificate; // COER, TS 103 097 clause 7.2.1 profile
|
||||||
|
KeyId key; // the verification key in the security module
|
||||||
|
};
|
||||||
|
std::vector<ByteBuffer> roots;
|
||||||
|
std::vector<ByteBuffer> authorities;
|
||||||
|
std::vector<Ticket> tickets;
|
||||||
|
|
||||||
|
bool empty() const { return roots.empty() && authorities.empty() && tickets.empty(); }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// bundle octets of the credentials (formats above)
|
||||||
|
ByteBuffer encode(const Credentials&);
|
||||||
|
ByteBuffer encode(const StoredCredentials&);
|
||||||
|
/// parse a bundle; false (and an untouched output) when the octets are not a well-formed bundle
|
||||||
|
bool decode(const ByteBuffer& bundle, Credentials& out);
|
||||||
|
bool decode(const ByteBuffer& bundle, StoredCredentials& out);
|
||||||
|
|
||||||
|
/** Import every ticket key of a provisioning bundle into the module, paired with the verification key of its
|
||||||
|
* certificate. None, with every key of this call destroyed again, when a ticket certificate does not decode or
|
||||||
|
* its key does not belong to it. Throws what the module throws. */
|
||||||
|
std::optional<StoredCredentials> import_keys(const Credentials&, SecurityModule&);
|
||||||
|
|
||||||
|
/** Result of feeding credentials into the trust configuration and the pool: how many
|
||||||
|
* of each were accepted and the first refusal (Result::accepted when everything was). */
|
||||||
|
struct ApplyReport {
|
||||||
|
std::size_t roots = 0, authorities = 0, tickets = 0;
|
||||||
|
Result result = Result::accepted;
|
||||||
|
};
|
||||||
|
/** Add every root, then every authority, then every ticket, each through the checks of
|
||||||
|
* TrustConfiguration::add_* and CertificatePool::add (TS 103 097 profiles, key/certificate
|
||||||
|
* match); stops at the first refusal so that a broken item is not silently skipped. */
|
||||||
|
ApplyReport apply(const StoredCredentials&, TrustConfiguration&, CertificatePool&);
|
||||||
|
|
||||||
|
/** Storage the application chooses: keeps one set. load() returns Result::rejected
|
||||||
|
* when nothing is stored and Result::invalid_argument when the stored octets do not
|
||||||
|
* decode; save() replaces what was there; erase() removes it. */
|
||||||
|
class CredentialStore {
|
||||||
|
public:
|
||||||
|
virtual ~CredentialStore() = default;
|
||||||
|
virtual Result save(const StoredCredentials&) = 0;
|
||||||
|
virtual Result load(StoredCredentials&) = 0;
|
||||||
|
virtual Result erase() = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// a bundle in one file (hosts, or an ESP-IDF VFS the application mounted)
|
||||||
|
class FileCredentialStore final : public CredentialStore {
|
||||||
|
public:
|
||||||
|
explicit FileCredentialStore(std::string path) : path_(std::move(path)) {}
|
||||||
|
Result save(const StoredCredentials&) override;
|
||||||
|
Result load(StoredCredentials&) override;
|
||||||
|
Result erase() override;
|
||||||
|
private:
|
||||||
|
std::string path_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
+2
-2
@@ -5,7 +5,7 @@
|
|||||||
#include <boost/optional/optional.hpp>
|
#include <boost/optional/optional.hpp>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
|
|
||||||
namespace vanetza_idf::ecc {
|
namespace microbu_v2x::ecc {
|
||||||
|
|
||||||
/** Short Weierstrass domain parameters y^2 = x^3 + a*x + b (mod p), big-endian octets.
|
/** Short Weierstrass domain parameters y^2 = x^3 + a*x + b (mod p), big-endian octets.
|
||||||
* NIST P-256 (FIPS 186-4 D.1.2.3), brainpoolP256r1 and brainpoolP384r1 (RFC 5639
|
* NIST P-256 (FIPS 186-4 D.1.2.3), brainpoolP256r1 and brainpoolP384r1 (RFC 5639
|
||||||
@@ -36,4 +36,4 @@ decompress(vanetza::security::KeyType, const vanetza::ByteBuffer& x, bool y_odd)
|
|||||||
/** SEC 1 clause 2.3.3 octet-string point encoding 0x04 || X || Y. */
|
/** SEC 1 clause 2.3.3 octet-string point encoding 0x04 || X || Y. */
|
||||||
vanetza::ByteBuffer encode_uncompressed(const vanetza::security::Uncompressed&);
|
vanetza::ByteBuffer encode_uncompressed(const vanetza::security::Uncompressed&);
|
||||||
|
|
||||||
} // namespace vanetza_idf::ecc
|
} // namespace microbu_v2x::ecc
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/pki.hpp>
|
#include <microbu_v2x/pki.hpp>
|
||||||
|
|
||||||
namespace vanetza_idf::pki {
|
namespace microbu_v2x::pki {
|
||||||
|
|
||||||
/** EciesBackend on the PSA Crypto API of mbedTLS (see backend_mbedtls.hpp for the
|
/** EciesBackend on the PSA Crypto API of mbedTLS (see backend_mbedtls.hpp for the
|
||||||
* version rationale): psa_raw_key_agreement(PSA_ALG_ECDH) for the shared x
|
* version rationale): psa_raw_key_agreement(PSA_ALG_ECDH) for the shared x
|
||||||
@@ -20,4 +20,4 @@ public:
|
|||||||
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vanetza_idf::pki
|
} // namespace microbu_v2x::pki
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/pki.hpp>
|
#include <microbu_v2x/pki.hpp>
|
||||||
|
|
||||||
namespace vanetza_idf::pki {
|
namespace microbu_v2x::pki {
|
||||||
|
|
||||||
/// EciesBackend on OpenSSL (host builds only): ECDH via EC_KEY, HMAC-SHA256, RAND_bytes, EVP AES-128-CCM.
|
/// EciesBackend on OpenSSL (host builds only): ECDH via EC_KEY, HMAC-SHA256, RAND_bytes, EVP AES-128-CCM.
|
||||||
class EciesOpenSsl : public EciesBackend {
|
class EciesOpenSsl : public EciesBackend {
|
||||||
@@ -16,4 +16,4 @@ public:
|
|||||||
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vanetza_idf::pki
|
} // namespace microbu_v2x::pki
|
||||||
+15
-15
@@ -1,18 +1,18 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||||
#include <vanetza/asn1/support/uper_decoder.h>
|
#include <vanetza/asn1/support/uper_decoder.h>
|
||||||
#if VIDF_CAM
|
#if V2X_CAM
|
||||||
#include <vanetza/asn1/its/r2/CAM.h>
|
#include <vanetza/asn1/its/r2/CAM.h>
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_DENM
|
#if V2X_DENM
|
||||||
#include <vanetza/asn1/its/r2/DENM.h>
|
#include <vanetza/asn1/its/r2/DENM.h>
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_VAM
|
#if V2X_VAM
|
||||||
#include <vanetza/asn1/its/r2/VAM.h>
|
#include <vanetza/asn1/its/r2/VAM.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace vanetza_idf::facilities {
|
namespace microbu_v2x::facilities {
|
||||||
template<class T>
|
template<class T>
|
||||||
struct CompletePerMessage : vanetza::asn1::asn1c_per_wrapper<T> {
|
struct CompletePerMessage : vanetza::asn1::asn1c_per_wrapper<T> {
|
||||||
using vanetza::asn1::asn1c_per_wrapper<T>::asn1c_per_wrapper;
|
using vanetza::asn1::asn1c_per_wrapper<T>::asn1c_per_wrapper;
|
||||||
@@ -25,34 +25,34 @@ struct CompletePerMessage : vanetza::asn1::asn1c_per_wrapper<T> {
|
|||||||
void* decoded = nullptr;
|
void* decoded = nullptr;
|
||||||
asn_codec_ctx_t context{};
|
asn_codec_ctx_t context{};
|
||||||
context.max_stack_size = 16384;
|
context.max_stack_size = 16384;
|
||||||
const auto result = uper_decode(&context, &this->m_type, &decoded,
|
const auto result = uper_decode(&context, this->m_type, &decoded,
|
||||||
bytes.data(), bytes.size(), 0, 0);
|
bytes.data(), bytes.size(), 0, 0);
|
||||||
const bool complete = result.code == RC_OK && result.consumed > 0 &&
|
const bool complete = result.code == RC_OK && result.consumed > 0 &&
|
||||||
(result.consumed + 7) / 8 == bytes.size();
|
(result.consumed + 7) / 8 == bytes.size();
|
||||||
const unsigned padding = complete ? (8 - result.consumed % 8) % 8 : 0;
|
const unsigned padding = complete ? (8 - result.consumed % 8) % 8 : 0;
|
||||||
if (!complete || (bytes.back() & ((1u << padding) - 1u))) {
|
if (!complete || (bytes.back() & ((1u << padding) - 1u))) {
|
||||||
vanetza::asn1::free(this->m_type, decoded);
|
vanetza::asn1::free(*this->m_type, decoded);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
vanetza::asn1::free(this->m_type, this->m_struct);
|
vanetza::asn1::free(*this->m_type, this->m_struct);
|
||||||
this->m_struct = static_cast<T*>(decoded);
|
this->m_struct = static_cast<T*>(decoded);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// Explicit R2 aliases avoid Vanetza's backwards-compatible R1 Cam/Denm aliases.
|
// Explicit R2 aliases avoid Vanetza's backwards-compatible R1 Cam/Denm aliases.
|
||||||
// IF-FAC-001: TS 103 900 V2.3.1, TS 103 831 V2.3.1,
|
// TS 103 900 V2.3.1, TS 103 831 V2.3.1,
|
||||||
// TS 103 300-3 V2.3.1 ASN.1; CDD TS 102 894-2 V2.4.1.
|
// TS 103 300-3 V2.3.1 ASN.1; CDD TS 102 894-2 V2.4.1.
|
||||||
#if VIDF_CAM
|
#if V2X_CAM
|
||||||
struct Cam : CompletePerMessage<Vanetza_ITS2_CAM_t> {
|
struct Cam : CompletePerMessage<Vanetza_ITS2_CAM_t> {
|
||||||
Cam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_CAM) {}
|
Cam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_CAM) {}
|
||||||
};
|
};
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_DENM
|
#if V2X_DENM
|
||||||
struct Denm : CompletePerMessage<Vanetza_ITS2_DENM_t> {
|
struct Denm : CompletePerMessage<Vanetza_ITS2_DENM_t> {
|
||||||
Denm() : CompletePerMessage(asn_DEF_Vanetza_ITS2_DENM) {}
|
Denm() : CompletePerMessage(asn_DEF_Vanetza_ITS2_DENM) {}
|
||||||
};
|
};
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_VAM
|
#if V2X_VAM
|
||||||
struct Vam : CompletePerMessage<Vanetza_ITS2_VAM_t> {
|
struct Vam : CompletePerMessage<Vanetza_ITS2_VAM_t> {
|
||||||
Vam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_VAM) {}
|
Vam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_VAM) {}
|
||||||
};
|
};
|
||||||
@@ -71,10 +71,10 @@ Result validate_pdu(Kind, const vanetza::ByteBuffer&, std::size_t maximum = 1394
|
|||||||
/** Application owns generation and lifecycle; this function selects the standard
|
/** Application owns generation and lifecycle; this function selects the standard
|
||||||
* BTP port and validates the Release 2 PDU before entering the NF-SAP.
|
* BTP port and validates the Release 2 PDU before entering the NF-SAP.
|
||||||
*/
|
*/
|
||||||
#if VIDF_NETWORK
|
#if V2X_NETWORK
|
||||||
}
|
}
|
||||||
#include <vanetza_idf/stack.hpp>
|
#include <microbu_v2x/stack.hpp>
|
||||||
namespace vanetza_idf::facilities {
|
namespace microbu_v2x::facilities {
|
||||||
Result send(Stack&, Kind, vanetza::ByteBuffer, BtpRequest transport);
|
Result send(Stack&, Kind, vanetza::ByteBuffer, BtpRequest transport);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <vanetza/common/byte_buffer.hpp>
|
#include <vanetza/common/byte_buffer.hpp>
|
||||||
#include <vanetza/security/hashed_id.hpp>
|
#include <vanetza/security/hashed_id.hpp>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
namespace vanetza_idf::security {
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
/** Identifier-change service of the security entity.
|
/** Identifier-change service of the security entity.
|
||||||
*
|
*
|
||||||
@@ -84,4 +84,4 @@ public:
|
|||||||
virtual bool change_pending() const = 0;
|
virtual bool change_pending() const = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vanetza_idf::security
|
} // namespace microbu_v2x::security
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
|
|
||||||
namespace vanetza_idf::its_g5 {
|
namespace microbu_v2x::its_g5 {
|
||||||
// IEEE 802.11 QoS Data header (26 octets) and IEEE 802 LLC/SNAP (8 octets).
|
// IEEE 802.11 QoS Data header (26 octets) and IEEE 802 LLC/SNAP (8 octets).
|
||||||
// EN 303 797 clauses 4.4/4.5 and Annex B.2; GeoNetworking EtherType 0x8947.
|
// EN 303 797 clauses 4.4/4.5 and Annex B.2; GeoNetworking EtherType 0x8947.
|
||||||
constexpr std::size_t maximum_gnpdu = 2296;
|
constexpr std::size_t maximum_gnpdu = 2296;
|
||||||
+2
-2
@@ -22,7 +22,7 @@
|
|||||||
* with the insertion of 2016-12-31 (Bulletin C 52). It must be extended when a new
|
* with the insertion of 2016-12-31 (Bulletin C 52). It must be extended when a new
|
||||||
* one is announced, the same as any TAI-UTC table (tzdata leap-seconds.list).
|
* one is announced, the same as any TAI-UTC table (tzdata leap-seconds.list).
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::its_time {
|
namespace microbu_v2x::its_time {
|
||||||
|
|
||||||
/// Unix time (seconds since 1970-01-01T00:00:00Z, no leap seconds) of the ITS epoch.
|
/// Unix time (seconds since 1970-01-01T00:00:00Z, no leap seconds) of the ITS epoch.
|
||||||
constexpr std::int64_t epoch_unix_seconds = 1072915200;
|
constexpr std::int64_t epoch_unix_seconds = 1072915200;
|
||||||
@@ -78,4 +78,4 @@ constexpr std::int64_t unix_microseconds(std::int64_t microseconds_since_its_epo
|
|||||||
return (tai_seconds + epoch_unix_seconds - inserted) * 1000000 + microseconds_since_its_epoch % 1000000;
|
return (tai_seconds + epoch_unix_seconds - inserted) * 1000000 + microseconds_since_its_epoch % 1000000;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vanetza_idf::its_time
|
} // namespace microbu_v2x::its_time
|
||||||
+4
-4
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <vanetza_idf/mn_sap.hpp>
|
#include <microbu_v2x/mn_sap.hpp>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* The facilities layer implements FacilitiesParameterSink; it may live in
|
* The facilities layer implements FacilitiesParameterSink; it may live in
|
||||||
* another task, process or device, the library defines no transport.
|
* another task, process or device, the library defines no transport.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::MF_SAP {
|
namespace microbu_v2x::MF_SAP {
|
||||||
|
|
||||||
using MN_SAP::ErrStatus;
|
using MN_SAP::ErrStatus;
|
||||||
|
|
||||||
@@ -63,4 +63,4 @@ MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink*, const MF_SET_requ
|
|||||||
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink*, const MF_COMMAND_request&);
|
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink*, const MF_COMMAND_request&);
|
||||||
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink*, const MF_REQUEST_request&);
|
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink*, const MF_REQUEST_request&);
|
||||||
|
|
||||||
} // namespace vanetza_idf::MF_SAP
|
} // namespace microbu_v2x::MF_SAP
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/mn_sap.hpp>
|
#include <microbu_v2x/mn_sap.hpp>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
* AccessParameterProvider; the library reads channel load and transmit
|
* AccessParameterProvider; the library reads channel load and transmit
|
||||||
* timing from nowhere else and invents no values.
|
* timing from nowhere else and invents no values.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::MI_SAP {
|
namespace microbu_v2x::MI_SAP {
|
||||||
|
|
||||||
using MN_SAP::ErrStatus;
|
using MN_SAP::ErrStatus;
|
||||||
|
|
||||||
@@ -53,4 +53,4 @@ bool i_param_writable(I_Param_No);
|
|||||||
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider*, const MI_GET_request&);
|
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider*, const MI_GET_request&);
|
||||||
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider*, const MI_SET_request&);
|
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider*, const MI_SET_request&);
|
||||||
|
|
||||||
} // namespace vanetza_idf::MI_SAP
|
} // namespace microbu_v2x::MI_SAP
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/stack.hpp>
|
#include <microbu_v2x/stack.hpp>
|
||||||
#include <vanetza/common/clock.hpp>
|
#include <vanetza/common/clock.hpp>
|
||||||
#include <vanetza/common/position_fix.hpp>
|
#include <vanetza/common/position_fix.hpp>
|
||||||
#include <vanetza/geonet/address.hpp>
|
#include <vanetza/geonet/address.hpp>
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
* The management entity may run in the same task or elsewhere; the library
|
* The management entity may run in the same task or elsewhere; the library
|
||||||
* only applies what it receives and forwards what it cannot answer itself.
|
* only applies what it receives and forwards what it cannot answer itself.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::MN_SAP {
|
namespace microbu_v2x::MN_SAP {
|
||||||
|
|
||||||
/// TS 103 836-4-1 V2.2.1 clause K.2: CORE_MMT.request Request cause
|
/// TS 103 836-4-1 V2.2.1 clause K.2: CORE_MMT.request Request cause
|
||||||
enum class RequestCause : std::uint8_t { TIME, POSITION_VECTOR, GN_ADDRESS_INITIAL, GN_ADDRESS_DAD, TC_MAPPING };
|
enum class RequestCause : std::uint8_t { TIME, POSITION_VECTOR, GN_ADDRESS_INITIAL, GN_ADDRESS_DAD, TC_MAPPING };
|
||||||
@@ -98,4 +98,4 @@ bool n_param_writable(N_Param_No);
|
|||||||
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider*, const MN_GET_request&);
|
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider*, const MN_GET_request&);
|
||||||
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider*, const MN_SET_request&);
|
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider*, const MN_SET_request&);
|
||||||
|
|
||||||
} // namespace vanetza_idf::MN_SAP
|
} // namespace microbu_v2x::MN_SAP
|
||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/stack.hpp>
|
#include <microbu_v2x/stack.hpp>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
namespace vanetza_idf::NF_SAP {
|
namespace microbu_v2x::NF_SAP {
|
||||||
|
|
||||||
enum class SecurityProfile { UNSECURED, SECURED };
|
enum class SecurityProfile { UNSECURED, SECURED };
|
||||||
|
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/credentials.hpp>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
/** CredentialStore on ESP-IDF non-volatile storage (the nvs_flash component).
|
||||||
|
*
|
||||||
|
* The stored credentials (credentials.hpp: certificates and KeyIds, no private
|
||||||
|
* keys) as one NVS blob under a namespace and key of the application's choosing.
|
||||||
|
* The application initialises NVS itself (nvs_flash_init or nvs_flash_secure_init)
|
||||||
|
* before using the store. Built with
|
||||||
|
* CONFIG_MICROBU_V2X_NVS_CREDENTIALS (default on with the security entity).
|
||||||
|
*/
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
|
class NvsCredentialStore final : public CredentialStore {
|
||||||
|
public:
|
||||||
|
/// namespace_name up to 15 characters, key up to 15 characters (NVS limits)
|
||||||
|
explicit NvsCredentialStore(std::string namespace_name = "microbu_v2x", std::string key = "credentials") :
|
||||||
|
namespace_(std::move(namespace_name)), key_(std::move(key)) {}
|
||||||
|
Result save(const StoredCredentials&) override;
|
||||||
|
Result load(StoredCredentials&) override;
|
||||||
|
Result erase() override;
|
||||||
|
private:
|
||||||
|
std::string namespace_;
|
||||||
|
std::string key_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
+71
-23
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#include <vanetza/common/byte_buffer.hpp>
|
#include <vanetza/common/byte_buffer.hpp>
|
||||||
#include <vanetza/common/clock.hpp>
|
#include <vanetza/common/clock.hpp>
|
||||||
#include <vanetza/common/its_aid.hpp>
|
#include <vanetza/common/its_aid.hpp>
|
||||||
@@ -11,7 +11,9 @@
|
|||||||
#include <vanetza/security/public_key.hpp>
|
#include <vanetza/security/public_key.hpp>
|
||||||
#include <vanetza/security/v3/certificate.hpp>
|
#include <vanetza/security/v3/certificate.hpp>
|
||||||
#include <array>
|
#include <array>
|
||||||
|
#include <cstddef>
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -38,7 +40,7 @@
|
|||||||
* V1.3.1 module, unchanged for these types in V2.2.1); butterfly keys (clause
|
* V1.3.1 module, unchanged for these types in V2.2.1); butterfly keys (clause
|
||||||
* 6.2.3.5) are not implemented.
|
* 6.2.3.5) are not implemented.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::pki {
|
namespace microbu_v2x::pki {
|
||||||
|
|
||||||
using vanetza::ByteBuffer;
|
using vanetza::ByteBuffer;
|
||||||
using vanetza::security::HashAlgorithm;
|
using vanetza::security::HashAlgorithm;
|
||||||
@@ -49,20 +51,30 @@ using vanetza::security::PublicKey;
|
|||||||
using vanetza::security::v3::Certificate;
|
using vanetza::security::v3::Certificate;
|
||||||
|
|
||||||
/// A verification or encryption key pair (IEEE Std 1609.2 PublicVerificationKey /
|
/// A verification or encryption key pair (IEEE Std 1609.2 PublicVerificationKey /
|
||||||
/// BasePublicEncryptionKey, TS 103 097 V2.2.1 clause 6): private scalar and the
|
/// BasePublicEncryptionKey, TS 103 097 V2.2.1 clause 6) outside a security module.
|
||||||
/// uncompressed public point of the same curve.
|
using KeyPair = security::KeyPair;
|
||||||
struct KeyPair {
|
|
||||||
PrivateKey priv;
|
/// ECDSA signature over a digest with a key the caller holds (IEEE Std 1609.2 clause 5.3.1); throws on failure.
|
||||||
|
using Signer = std::function<vanetza::security::Signature(const ByteBuffer& digest)>;
|
||||||
|
/// a key of the station's security module (the station's TS 102 941 client)
|
||||||
|
Signer module_signer(security::SecurityModule&, security::KeyId);
|
||||||
|
/// a private key at hand (authorities in the issuing tools, tests)
|
||||||
|
Signer key_signer(vanetza::security::Backend&, PrivateKey);
|
||||||
|
|
||||||
|
/// The public key a request names and the signature with its private key.
|
||||||
|
struct SigningKey {
|
||||||
PublicKey pub; // uncompressed
|
PublicKey pub; // uncompressed
|
||||||
|
Signer sign;
|
||||||
};
|
};
|
||||||
|
/// a key pair at hand (tests and tools that act as a station)
|
||||||
|
SigningKey signing_key(vanetza::security::Backend&, const KeyPair&);
|
||||||
|
|
||||||
/** Primitives beyond vanetza::security::Backend that ECIES and AES-CCM need.
|
/** Primitives beyond vanetza::security::Backend that ECIES and AES-CCM need.
|
||||||
* Implemented on OpenSSL (host) and the PSA Crypto API (device). */
|
* Implemented on OpenSSL (host) and the PSA Crypto API (device). generate_key()
|
||||||
class EciesBackend {
|
* (KeyGenerator) gives a fresh key pair on the given curve (NIST P-256 or
|
||||||
|
* brainpoolP256r1 for ECIES). */
|
||||||
|
class EciesBackend : public security::KeyGenerator {
|
||||||
public:
|
public:
|
||||||
virtual ~EciesBackend() = default;
|
|
||||||
/// fresh key pair on the given curve (NIST P-256 or brainpoolP256r1 for ECIES)
|
|
||||||
virtual KeyPair generate_key(KeyType) = 0;
|
|
||||||
/// x coordinate of the ECDH shared point (IEEE 1609.2 5.3.5: the shared secret value)
|
/// x coordinate of the ECDH shared point (IEEE 1609.2 5.3.5: the shared secret value)
|
||||||
virtual std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) = 0;
|
virtual std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) = 0;
|
||||||
/// HMAC-SHA256 (FIPS PUB 198-1), full 32-octet tag
|
/// HMAC-SHA256 (FIPS PUB 198-1), full 32-octet tag
|
||||||
@@ -97,7 +109,18 @@ std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(vanetza::security:
|
|||||||
/** State kept from a request for reading its response: the AES key (the response is
|
/** State kept from a request for reading its response: the AES key (the response is
|
||||||
* encrypted with it, referenced by pskRecipInfo) and the request hash the response
|
* encrypted with it, referenced by pskRecipInfo) and the request hash the response
|
||||||
* must echo (left-most 16 octets of SHA-256 of the encrypted request). */
|
* must echo (left-most 16 octets of SHA-256 of the encrypted request). */
|
||||||
|
inline void erase_secret(std::uint8_t* data, std::size_t length) {
|
||||||
|
volatile std::uint8_t* target = data;
|
||||||
|
while (length--) *target++ = 0;
|
||||||
|
}
|
||||||
|
|
||||||
struct RequestContext {
|
struct RequestContext {
|
||||||
|
// TS 103 601 clause 5.1.2: erase the retained session key on termination.
|
||||||
|
void clear() {
|
||||||
|
erase_secret(aes_key.data(), aes_key.size());
|
||||||
|
request_hash.fill(0);
|
||||||
|
}
|
||||||
|
~RequestContext() { clear(); }
|
||||||
std::array<std::uint8_t, 16> aes_key {};
|
std::array<std::uint8_t, 16> aes_key {};
|
||||||
std::array<std::uint8_t, 16> request_hash {};
|
std::array<std::uint8_t, 16> request_hash {};
|
||||||
};
|
};
|
||||||
@@ -106,12 +129,19 @@ struct RequestContext {
|
|||||||
/// TS 102 941 V2.2.1 clause 6.2.3.2/6.2.3.3 request parameters
|
/// TS 102 941 V2.2.1 clause 6.2.3.2/6.2.3.3 request parameters
|
||||||
using Permissions = std::vector<std::pair<vanetza::ItsAid, ByteBuffer>>;
|
using Permissions = std::vector<std::pair<vanetza::ItsAid, ByteBuffer>>;
|
||||||
|
|
||||||
|
/// TS 102 941 clauses 6.2.3.2.2/6.2.3.3.2: validate an issued credential before installation.
|
||||||
|
/// Check its issuer signature, profile, interval, granted permissions and that its verification key is the
|
||||||
|
/// requested one.
|
||||||
|
bool validate_issued_certificate(vanetza::security::Backend&, const Certificate&, const Certificate& issuer,
|
||||||
|
const PublicKey& requested_key, vanetza::Clock::time_point,
|
||||||
|
const Permissions&, bool enrolment);
|
||||||
|
|
||||||
/// Clause 6.2.3.2.1 inputs
|
/// Clause 6.2.3.2.1 inputs
|
||||||
struct EnrolmentRequestParameters {
|
struct EnrolmentRequestParameters {
|
||||||
ByteBuffer its_id; // canonical identifier (initial) or HashedId8 of the current EC (re-enrolment)
|
ByteBuffer its_id; // canonical identifier (initial) or HashedId8 of the current EC (re-enrolment)
|
||||||
KeyPair verification_key; // new key pair; the private key signs the proof of possession
|
SigningKey verification_key; // new key; its signature is the proof of possession
|
||||||
Permissions app_permissions; // requestedSubjectAttributes.appPermissions
|
Permissions app_permissions; // requestedSubjectAttributes.appPermissions
|
||||||
PrivateKey outer_signer_key; // canonical private key (initial) or current EC private key
|
Signer outer_signer; // canonical key (initial) or current EC key
|
||||||
const Certificate* current_ec = nullptr; // set for re-enrolment: outer signer = digest of the EC
|
const Certificate* current_ec = nullptr; // set for re-enrolment: outer signer = digest of the EC
|
||||||
HashAlgorithm hash = HashAlgorithm::SHA256;
|
HashAlgorithm hash = HashAlgorithm::SHA256;
|
||||||
};
|
};
|
||||||
@@ -137,12 +167,12 @@ Result parse_enrolment_response(vanetza::security::Backend&, EciesBackend&, cons
|
|||||||
|
|
||||||
/// Clause 6.2.3.3.1 inputs
|
/// Clause 6.2.3.3.1 inputs
|
||||||
struct AuthorizationRequestParameters {
|
struct AuthorizationRequestParameters {
|
||||||
KeyPair verification_key; // new AT key pair
|
SigningKey verification_key; // new AT key
|
||||||
std::optional<KeyPair> encryption_key; // optional AT encryption key
|
std::optional<PublicKey> encryption_key; // optional AT encryption key
|
||||||
Permissions app_permissions; // shall be present
|
Permissions app_permissions; // shall be present
|
||||||
std::optional<std::pair<vanetza::Clock::time_point, std::uint16_t>> validity_period; // start, hours
|
std::optional<std::pair<vanetza::Clock::time_point, std::uint16_t>> validity_period; // start, hours
|
||||||
const Certificate* ec = nullptr; // enrolment credential signing SharedAtRequest
|
const Certificate* ec = nullptr; // enrolment credential signing SharedAtRequest
|
||||||
PrivateKey ec_key;
|
Signer ec_signer; // with the EC's key
|
||||||
bool privacy = true; // [Itss_WithPrivacy]: EC signature encrypted for the EA
|
bool privacy = true; // [Itss_WithPrivacy]: EC signature encrypted for the EA
|
||||||
bool include_pop = true; // AuthorizationRequestMessageWithPop
|
bool include_pop = true; // AuthorizationRequestMessageWithPop
|
||||||
HashAlgorithm hash = HashAlgorithm::SHA256;
|
HashAlgorithm hash = HashAlgorithm::SHA256;
|
||||||
@@ -165,10 +195,10 @@ Result parse_authorization_response(vanetza::security::Backend&, EciesBackend&,
|
|||||||
|
|
||||||
/// EtsiTs103097Data-Signed over a payload: signer self (signer_cert null) or digest of signer_cert
|
/// EtsiTs103097Data-Signed over a payload: signer self (signer_cert null) or digest of signer_cert
|
||||||
std::optional<ByteBuffer> sign_data(vanetza::security::Backend&, vanetza::Clock::time_point now, HashAlgorithm,
|
std::optional<ByteBuffer> sign_data(vanetza::security::Backend&, vanetza::Clock::time_point now, HashAlgorithm,
|
||||||
const ByteBuffer& payload, const PrivateKey& key, const Certificate* signer_cert);
|
const ByteBuffer& payload, const Signer&, const Certificate* signer_cert);
|
||||||
/// EtsiTs103097Data-SignedExternalPayload: extDataHash = SHA-256 of external_payload
|
/// EtsiTs103097Data-SignedExternalPayload: extDataHash = SHA-256 of external_payload
|
||||||
std::optional<ByteBuffer> sign_external(vanetza::security::Backend&, vanetza::Clock::time_point now,
|
std::optional<ByteBuffer> sign_external(vanetza::security::Backend&, vanetza::Clock::time_point now,
|
||||||
const ByteBuffer& external_payload, const PrivateKey& key,
|
const ByteBuffer& external_payload, const Signer&,
|
||||||
const Certificate& signer_cert);
|
const Certificate& signer_cert);
|
||||||
/// EtsiTs103097Data-Encrypted for one certificate recipient; aes_key/nonce generated, key returned
|
/// EtsiTs103097Data-Encrypted for one certificate recipient; aes_key/nonce generated, key returned
|
||||||
std::optional<ByteBuffer> encrypt_for(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
|
std::optional<ByteBuffer> encrypt_for(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
|
||||||
@@ -199,7 +229,7 @@ std::optional<ByteBuffer> verify_signed(vanetza::security::Backend&, const ByteB
|
|||||||
using Time32 = std::uint32_t; // IEEE Std 1609.2 Time32, seconds since 2004-01-01 00:00:00 TAI
|
using Time32 = std::uint32_t; // IEEE Std 1609.2 Time32, seconds since 2004-01-01 00:00:00 TAI
|
||||||
|
|
||||||
struct TrustListEntries {
|
struct TrustListEntries {
|
||||||
struct Authority { ByteBuffer certificate; std::string access_point; }; // EaEntry / AaEntry
|
struct Authority { ByteBuffer certificate; std::string access_point; std::string its_access_point {}; }; // EaEntry / AaEntry
|
||||||
struct DistributionCentre { std::string url; std::vector<HashedId8> certificates; }; // DcEntry
|
struct DistributionCentre { std::string url; std::vector<HashedId8> certificates; }; // DcEntry
|
||||||
std::vector<Authority> ea, aa;
|
std::vector<Authority> ea, aa;
|
||||||
std::vector<DistributionCentre> dc;
|
std::vector<DistributionCentre> dc;
|
||||||
@@ -209,6 +239,12 @@ struct TrustListEntries {
|
|||||||
std::optional<ByteBuffer> build_rca_ctl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
std::optional<ByteBuffer> build_rca_ctl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
||||||
const PrivateKey& rca_key, const TrustListEntries&, Time32 next_update,
|
const PrivateKey& rca_key, const TrustListEntries&, Time32 next_update,
|
||||||
std::uint8_t ctl_sequence);
|
std::uint8_t ctl_sequence);
|
||||||
|
// TS 102 941 clauses 6.3.2 and 6.3.4: one full and delta pair per update.
|
||||||
|
struct RcaTrustListUpdate { ByteBuffer full, delta; std::uint8_t sequence = 0; };
|
||||||
|
std::optional<RcaTrustListUpdate> build_rca_ctl_update(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||||
|
const Certificate& rca, const PrivateKey&, const ByteBuffer& previous_full,
|
||||||
|
const TrustListEntries&, Time32 next_update);
|
||||||
|
|
||||||
/// CRL of an RCA, version 1
|
/// CRL of an RCA, version 1
|
||||||
std::optional<ByteBuffer> build_crl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
std::optional<ByteBuffer> build_crl(vanetza::security::Backend&, vanetza::Clock::time_point now, const Certificate& rca,
|
||||||
const PrivateKey& rca_key, const std::vector<HashedId8>& revoked, Time32 this_update,
|
const PrivateKey& rca_key, const std::vector<HashedId8>& revoked, Time32 this_update,
|
||||||
@@ -228,6 +264,18 @@ struct RcaTrustList {
|
|||||||
/// EA/AA entry is issued by rca with a verifying signature (IEEE Std 1609.2 clause 5.3.1).
|
/// EA/AA entry is issued by rca with a verifying signature (IEEE Std 1609.2 clause 5.3.1).
|
||||||
std::optional<RcaTrustList> parse_rca_ctl(vanetza::security::Backend&, const ByteBuffer& message, const Certificate& rca);
|
std::optional<RcaTrustList> parse_rca_ctl(vanetza::security::Backend&, const ByteBuffer& message, const Certificate& rca);
|
||||||
|
|
||||||
|
// TS 102 941 clauses 6.3.1 and 6.3.4. Full ECTLs authenticate root and successor TLM certificates.
|
||||||
|
struct TlmTrustList {
|
||||||
|
std::uint8_t sequence = 0;
|
||||||
|
Time32 next_update = 0;
|
||||||
|
bool full = true;
|
||||||
|
std::vector<Certificate> roots, tlms;
|
||||||
|
};
|
||||||
|
std::optional<TlmTrustList> parse_tlm_ctl(vanetza::security::Backend&, const ByteBuffer&, const Certificate& tlm);
|
||||||
|
std::optional<ByteBuffer> build_tlm_ctl(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||||
|
const Certificate& tlm, const PrivateKey&, const std::vector<Certificate>& roots,
|
||||||
|
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence);
|
||||||
|
|
||||||
struct RevocationList {
|
struct RevocationList {
|
||||||
Time32 this_update = 0, next_update = 0;
|
Time32 this_update = 0, next_update = 0;
|
||||||
std::vector<HashedId8> revoked;
|
std::vector<HashedId8> revoked;
|
||||||
@@ -237,9 +285,9 @@ std::optional<RevocationList> parse_crl(vanetza::security::Backend&, const ByteB
|
|||||||
|
|
||||||
/// Clause 6.3.6: the EA/AA entries become trusted issuers (TrustConfiguration::add_authority);
|
/// Clause 6.3.6: the EA/AA entries become trusted issuers (TrustConfiguration::add_authority);
|
||||||
/// returns the number added (entries already known are not counted)
|
/// returns the number added (entries already known are not counted)
|
||||||
std::size_t apply(const RcaTrustList&, vanetza_idf::security::TrustConfiguration&);
|
std::size_t apply(const RcaTrustList&, microbu_v2x::security::TrustConfiguration&);
|
||||||
/// Clause 6.3.6: the CRL entries become revocations by the RCA (TrustConfiguration::revoke),
|
/// Clause 6.3.6: the CRL entries become revocations by the RCA (TrustConfiguration::revoke),
|
||||||
/// replacing the RCA's earlier list; returns the number of entries
|
/// replacing the RCA's earlier list; returns the number of entries
|
||||||
std::size_t apply(const RevocationList&, const Certificate& rca, vanetza_idf::security::TrustConfiguration&);
|
std::size_t apply(const RevocationList&, const Certificate& rca, microbu_v2x::security::TrustConfiguration&);
|
||||||
|
|
||||||
} // namespace vanetza_idf::pki
|
} // namespace microbu_v2x::pki
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace microbu_v2x::pki {
|
||||||
|
|
||||||
|
// ETSI TS 103 601 V2.1.1 clauses 5.1.2 and 5.1.4.
|
||||||
|
// Times use a monotonic millisecond clock. N1 includes the initial attempt.
|
||||||
|
struct RetryPolicy {
|
||||||
|
std::uint64_t interval_ms = 60000;
|
||||||
|
std::uint64_t lifetime_ms = 190000;
|
||||||
|
std::uint32_t attempts = 3;
|
||||||
|
std::uint64_t minimum_response_ms = 55000;
|
||||||
|
std::uint64_t authority_context_ms = 3600000;
|
||||||
|
|
||||||
|
bool valid() const {
|
||||||
|
return attempts && interval_ms >= minimum_response_ms && interval_ms && lifetime_ms &&
|
||||||
|
(lifetime_ms - 1) / attempts >= interval_ms && authority_context_ms >= lifetime_ms;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class RetrySchedule {
|
||||||
|
public:
|
||||||
|
bool begin(std::uint64_t now, RetryPolicy policy = {}) {
|
||||||
|
stop();
|
||||||
|
if (!policy.valid()) return false;
|
||||||
|
policy_ = policy;
|
||||||
|
start_ = last_ = now;
|
||||||
|
attempts_ = 1;
|
||||||
|
active_ = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool poll(std::uint64_t now) {
|
||||||
|
if (active_ && (now < last_ || now - start_ >= policy_.lifetime_ms ||
|
||||||
|
(attempts_ == policy_.attempts && now - last_ >= policy_.interval_ms))) stop();
|
||||||
|
return active_;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool repeat(std::uint64_t now) {
|
||||||
|
if (!poll(now) || now - last_ < policy_.interval_ms || attempts_ >= policy_.attempts) return false;
|
||||||
|
last_ = now;
|
||||||
|
++attempts_;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void stop() { active_ = false; }
|
||||||
|
bool active() const { return active_; }
|
||||||
|
std::uint32_t attempts() const { return attempts_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
RetryPolicy policy_;
|
||||||
|
std::uint64_t start_ = 0;
|
||||||
|
std::uint64_t last_ = 0;
|
||||||
|
std::uint32_t attempts_ = 0;
|
||||||
|
bool active_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::pki
|
||||||
@@ -0,0 +1,382 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/access.hpp>
|
||||||
|
#include <microbu_v2x/id_change.hpp>
|
||||||
|
#include <microbu_v2x/security_module.hpp>
|
||||||
|
#include <vanetza/common/clock.hpp>
|
||||||
|
#include <vanetza/common/its_aid.hpp>
|
||||||
|
#include <vanetza/common/position_provider.hpp>
|
||||||
|
#include <vanetza/common/runtime.hpp>
|
||||||
|
#include <vanetza/security/backend.hpp>
|
||||||
|
#include <vanetza/security/hashed_id.hpp>
|
||||||
|
#include <vanetza/security/security_entity.hpp>
|
||||||
|
#include <vanetza/security/v3/certificate.hpp>
|
||||||
|
#include <vanetza/security/v3/certificate_provider.hpp>
|
||||||
|
#include <vanetza/security/v3/certificate_validator.hpp>
|
||||||
|
#include <vanetza/security/v3/issuer_memory_lookup.hpp>
|
||||||
|
#include <vanetza/security/v3/location_checker.hpp>
|
||||||
|
#include <vanetza/security/v3/revocation_lookup.hpp>
|
||||||
|
#include <vanetza/security/v3/sign_header_policy.hpp>
|
||||||
|
#include <vanetza/security/v3/trust_store.hpp>
|
||||||
|
#include <chrono>
|
||||||
|
#include <deque>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/** Signing security entity for the SN-SAP.
|
||||||
|
*
|
||||||
|
* Standards: TS 103 097 V2.2.1 (secured message and certificate formats,
|
||||||
|
* clause 5.2 SignedData constraints, clause 7 profiles), IEEE Std 1609.2
|
||||||
|
* (hashing and ECDSA, clause 5.3), TS 102 940 V2.1.1 (trust model: root CA ->
|
||||||
|
* AA -> authorization ticket, clause 6.5 identity management), TS 102 941
|
||||||
|
* V2.2.1 (credential life cycle), TS 102 723-8 V2.0.0/V1.1.1 (SN-SAP
|
||||||
|
* primitives), TS 103 300-3 V2.3.1 clause 6.5 (VAM signing and certificate
|
||||||
|
* attachment). Verification of received messages (SN-DECAP) follows IEEE Std
|
||||||
|
* 1609.2 clause 5.2 as TS 103 097 clause 5.2 requires, with the profile checks of
|
||||||
|
* clause 7.1 and the chain checks of TS 102 940 clause 6; it is built when
|
||||||
|
* V2X_SECURITY_VERIFY is set (default with the security feature), otherwise
|
||||||
|
* SN-DECAP reports Configuration_Problem.
|
||||||
|
*/
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
|
using vanetza::ByteBuffer;
|
||||||
|
using vanetza::security::HashedId8;
|
||||||
|
using vanetza::security::PrivateKey;
|
||||||
|
using vanetza::security::v3::Certificate;
|
||||||
|
|
||||||
|
// IEEE Std 1609.2 Duration: a year is 31556952 seconds.
|
||||||
|
// Bounds outside Time32 are invalid rather than wrapping into the past.
|
||||||
|
vanetza::security::v3::StartAndEndValidity validity_bounds(const Certificate&);
|
||||||
|
|
||||||
|
|
||||||
|
/** SN-ENCAP.request context_information values understood by this entity
|
||||||
|
* (TS 102 723-8 V1.1.1 Table 24: opaque octets "used in selecting properties
|
||||||
|
* of the underlying security protocol"; the standard leaves the content to the
|
||||||
|
* implementation, these values are this library's definition). */
|
||||||
|
namespace context {
|
||||||
|
/// VAM generated for a VRU cluster: TS 103 300-3 V2.3.1 clause 6.5.3 500 ms certificate cadence
|
||||||
|
inline const ByteBuffer vam_cluster {0x01};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Authorization tickets owned by this station, each with the KeyId of its private key in the security module.
|
||||||
|
*
|
||||||
|
* TS 103 097 V2.2.1 clause 7.2.1 (AT profile), TS 102 940 V2.1.1 clause 6.5
|
||||||
|
* ("multiple authorization tickets ... to be used ... over its life time").
|
||||||
|
* Tickets come from the station's TS 102 941 client (key generated in the
|
||||||
|
* module) or from laboratory provisioning (key imported into the module,
|
||||||
|
* credentials.hpp). The pool never holds a private key: own_private_key() of
|
||||||
|
* the upstream CertificateProvider contract throws, and SN-ENCAP signs through
|
||||||
|
* SecurityModule::sign_digest with own_key().
|
||||||
|
*/
|
||||||
|
class CertificatePool : public vanetza::security::v3::BaseCertificateProvider {
|
||||||
|
public:
|
||||||
|
/// An authorization ticket (TS 103 097 V2.2.1 clause 7.2.1 profile) and the module key of its verifyKeyIndicator.
|
||||||
|
struct Ticket {
|
||||||
|
Certificate certificate;
|
||||||
|
KeyId key;
|
||||||
|
HashedId8 digest; // HashedId8 per TS 103 097 clause 6 / IEEE 1609.2 clause 6.4.3
|
||||||
|
};
|
||||||
|
|
||||||
|
explicit CertificatePool(SecurityModule&);
|
||||||
|
|
||||||
|
/** Add a ticket. Fails closed (Result::invalid_argument) when the certificate
|
||||||
|
* does not decode, is not an authorization ticket (clause 7.2.1: issuer
|
||||||
|
* sha256AndDigest/sha384AndDigest, appPermissions present, no
|
||||||
|
* certIssuePermissions), or the module holds no key with the certificate's
|
||||||
|
* verification key. Duplicate digests are rejected. */
|
||||||
|
Result add(const ByteBuffer& coer_certificate, KeyId);
|
||||||
|
Result add(Certificate, KeyId);
|
||||||
|
|
||||||
|
/// pool bookkeeping for the application's provisioning and persistence
|
||||||
|
std::size_t size() const { return tickets_.size(); }
|
||||||
|
bool empty() const { return tickets_.empty(); }
|
||||||
|
const std::vector<Ticket>& tickets() const { return tickets_; }
|
||||||
|
/// currently selected ticket, nullptr when the pool is empty
|
||||||
|
const Ticket* current() const;
|
||||||
|
/// next different ticket valid at now (round robin), nullptr when none
|
||||||
|
const Ticket* next_valid(vanetza::Clock::time_point now) const;
|
||||||
|
/// make the ticket with this digest current (identifier change COMMIT)
|
||||||
|
Result select(const HashedId8&);
|
||||||
|
/// drop tickets whose validity ended before now, never the current one; returns count
|
||||||
|
std::size_t prune(vanetza::Clock::time_point now);
|
||||||
|
|
||||||
|
/// the module that holds the ticket keys
|
||||||
|
SecurityModule& module() { return module_; }
|
||||||
|
/// module key of the current ticket; std::logic_error when empty
|
||||||
|
KeyId own_key() const;
|
||||||
|
|
||||||
|
// v3::CertificateProvider: the current ticket; std::logic_error when empty
|
||||||
|
const Certificate& own_certificate() override;
|
||||||
|
/// std::logic_error: private keys stay in the security module
|
||||||
|
const PrivateKey& own_private_key() override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
SecurityModule& module_;
|
||||||
|
std::vector<Ticket> tickets_;
|
||||||
|
std::size_t current_ = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Trust anchors and issuing authorities supplied by the application.
|
||||||
|
* TS 102 940 V2.1.1 clause 6.1 (root CA, AA), TS 103 097 clauses 7.2.3/7.2.4;
|
||||||
|
* TS 102 941 V2.2.1 clause 6.3 CTL/CRL retrieval is not part of this library. */
|
||||||
|
class TrustConfiguration {
|
||||||
|
public:
|
||||||
|
/// self-signed root CA certificate (clause 7.2.3) -> trust store and issuer lookup
|
||||||
|
Result add_root(const ByteBuffer& coer_certificate);
|
||||||
|
Result add_root(const Certificate&);
|
||||||
|
/// AA or other subordinate CA certificate (clause 7.2.4) -> issuer lookup; a certificate
|
||||||
|
/// already known is Result::rejected (nothing changes), a non-CA one invalid_argument
|
||||||
|
Result add_authority(const ByteBuffer& coer_certificate);
|
||||||
|
Result add_authority(const Certificate&);
|
||||||
|
|
||||||
|
const vanetza::security::v3::TrustStore& roots() const { return roots_; }
|
||||||
|
const vanetza::security::v3::IssuerMemoryLookup& issuers() const { return issuers_; }
|
||||||
|
/// every CA certificate added, in the order added (views into the issuer lookup, which holds the one copy)
|
||||||
|
std::vector<const Certificate*> authorities() const;
|
||||||
|
/// the CA certificate whose digest ends in this HashedId3 (P2P certificate distribution), or nullptr
|
||||||
|
const Certificate* authority(const vanetza::security::HashedId3& id) const;
|
||||||
|
|
||||||
|
/** TS 102 941 V2.2.1 clause 6.3.3/6.3.6: a certificate the named issuer has revoked
|
||||||
|
* (the RCA's CRL lists the CA certificates it no longer trusts). The validator walks
|
||||||
|
* every chain link against this list (IEEE Std 1609.2 clause 5.2: a revoked
|
||||||
|
* certificate anywhere in the chain invalidates it), so a revoked AA takes all its
|
||||||
|
* tickets with it; the station's own tickets included (it stops signing). */
|
||||||
|
void revoke(const HashedId8& issuer, const HashedId8& certificate);
|
||||||
|
/// forget every revocation recorded for this issuer (a fresh CRL replaces the old one)
|
||||||
|
void clear_revocations(const HashedId8& issuer);
|
||||||
|
const vanetza::security::v3::RevocationLookup& revocations() const { return revocations_; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
vanetza::security::v3::TrustStore roots_;
|
||||||
|
vanetza::security::v3::IssuerMemoryLookup issuers_;
|
||||||
|
// Digests only : a decoded certificate costs about 3.5 kB of heap on the ESP32-C5, and a second copy
|
||||||
|
// of every CA certificate here left the Wi-Fi driver without TX buffers. issuers_ holds the certificate.
|
||||||
|
std::vector<HashedId8> authority_digests_;
|
||||||
|
vanetza::security::v3::RevocationMemoryLookup revocations_;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** IEEE Std 1609.2 clause 5.3.1 certificate signature: Hash(Hash(toBeSigned) || Hash(issuer
|
||||||
|
* certificate)) with the hash algorithm of the IssuerIdentifier choice (sha256AndDigest /
|
||||||
|
* sha384AndDigest, or the algorithm named in the self choice with the empty string as
|
||||||
|
* issuer hash), verified with the issuer's verification key; issuer == nullptr means
|
||||||
|
* self-signed. TS 103 097 V2.2.1 clause 6 admits NIST P-256, brainpoolP256r1 (SHA-256)
|
||||||
|
* and brainpoolP384r1 (SHA-384). */
|
||||||
|
bool verify_certificate_signature(vanetza::security::Backend&, const Certificate& subject, const Certificate* issuer);
|
||||||
|
|
||||||
|
/** IEEE Std 1609.2-2025 clause 5.1.2 permission consistency of a certificate chain, chain[0]
|
||||||
|
* the end entity and the last element the anchor: every appPermissions entry of the end
|
||||||
|
* entity is covered by a PsidGroupPermissions group of each ancestor whose chain-length
|
||||||
|
* window (6.4.28) reaches down to the end entity and whose eeType admits it, the SSP
|
||||||
|
* inside the group's range (6.4.29/6.4.30 SspRange, BitmapSspRange: a 1 bit of the mask
|
||||||
|
* fixes the subordinate's bit; an omitted SSP needs "all"); every subordinate CA's ranges
|
||||||
|
* nest inside its issuer's. Unknown CHOICE alternatives are critical (5.2.6): false.
|
||||||
|
* Used by the receive-side chain validator and by the issuing tools before they write. */
|
||||||
|
bool chain_permissions_consistent(const std::vector<const Certificate*>& chain);
|
||||||
|
|
||||||
|
/** IEEE Std 1609.2-2025 clause 6.4.17: no part of the subject's region may lie outside the
|
||||||
|
* issuer's. No issuer region: true; issuer region but none on the subject: false;
|
||||||
|
* geometric issuer regions by the upstream geometry; identifiedRegion issuer (6.4.21 to
|
||||||
|
* 6.4.24): identifier containment for an identifiedRegion subject, the
|
||||||
|
* permissive_identified_region policy for a geometric subject (no border database). */
|
||||||
|
bool region_within(const Certificate& subject, const Certificate& issuer, bool permissive_identified_region);
|
||||||
|
|
||||||
|
/** Receive-side parameters that TS 103 097 leaves to the station. generationTime
|
||||||
|
* plausibility: IEEE Std 1609.2 clause 5.2.3.2 lists it among the relevance checks
|
||||||
|
* without fixing values; the defaults are a 3 s clock tolerance into the future and the
|
||||||
|
* 5 min window the TS 103 096-2 test purposes apply to generation times (the CAM/DENM
|
||||||
|
* services apply their own, tighter freshness rules on top). Replay: a message whose
|
||||||
|
* (signer digest, generationTime) pair was already accepted is DUPLICATE_MESSAGE
|
||||||
|
* (TS 102 723-8 Table 27 report). */
|
||||||
|
struct VerificationPolicy {
|
||||||
|
std::chrono::seconds generation_time_future_tolerance {3};
|
||||||
|
std::chrono::seconds generation_time_max_age {300};
|
||||||
|
std::size_t replay_window = 256; // remembered accepted (signer, time) pairs, 0 disables
|
||||||
|
std::size_t verified_chain_cache = 64; // authorization tickets whose chain signature was verified
|
||||||
|
std::size_t certificate_cache_limit = 32; // learned certificates kept (the cache is emptied beyond it)
|
||||||
|
std::size_t learned_authority_limit = 8; // AA certificates learned through P2P distribution
|
||||||
|
bool permissive_identified_region = true; // identifiedRegion without a country database: accept (see docs)
|
||||||
|
};
|
||||||
|
|
||||||
|
/** TS 103 097 V2.2.1 clause 5.2 and 7.1.1 to 7.1.3 structural checks of a received
|
||||||
|
* signed message, before any cryptography: protocolVersion 3 on both levels, hashId
|
||||||
|
* consistent with the signature choice, generationTime present, p2pcdLearningRequest and
|
||||||
|
* missingCrlIdentifier absent, per ITS-AID: CAM without expiryTime, generationLocation
|
||||||
|
* and encryptionKey; DENM with generationLocation and with a certificate as signer,
|
||||||
|
* without expiryTime and encryptionKey; signer digest or certificate (not self).
|
||||||
|
* Returns Success when the structure is admissible, otherwise the report to give. */
|
||||||
|
vanetza::security::VerificationReport check_profile(const vanetza::security::v3::SecuredMessage&);
|
||||||
|
|
||||||
|
/** Header fields and signer identifier per message profile.
|
||||||
|
*
|
||||||
|
* TS 103 097 V2.2.1 clause 5.2: psid and generationTime always present,
|
||||||
|
* p2pcdLearningRequest and missingCrlIdentifier always absent.
|
||||||
|
* - CAM (ITS-AID 36, TS 102 965 Table A.1): clause 7.1.1 - digest by default,
|
||||||
|
* certificate once one second after its last inclusion, immediately after a
|
||||||
|
* CAM from an unknown AT (request_certificate) or an inline P2PCD request for
|
||||||
|
* our AT, inlineP2pcdRequest for unknown certificates, requestedCertificate
|
||||||
|
* for known CA certificates; no other header fields.
|
||||||
|
* - DENM (37): clause 7.1.2 - certificate always, generationLocation present.
|
||||||
|
* - VAM (638): TS 103 300-3 V2.3.1 clause 6.5.3 - individual VAM: certificate
|
||||||
|
* if >= 1 s since the last certificate attached to a VAM or a new CAM signer
|
||||||
|
* was observed (report_new_cam_signer), else digest; cluster VAM (SN-ENCAP
|
||||||
|
* context_information == context::vam_cluster): certificate if >= 500 ms,
|
||||||
|
* else digest.
|
||||||
|
* - other ITS-AIDs, including GN-MGMT beacons (141): clause 7.1.3 generic
|
||||||
|
* profile, which constrains only clause 5.2; this library includes the
|
||||||
|
* certificate once per second per ITS-AID and the digest otherwise.
|
||||||
|
*/
|
||||||
|
class Ts103097SignHeaderPolicy : public vanetza::security::v3::SignHeaderPolicy {
|
||||||
|
public:
|
||||||
|
Ts103097SignHeaderPolicy(const vanetza::Runtime&, vanetza::PositionProvider&, CertificatePool&,
|
||||||
|
const TrustConfiguration&);
|
||||||
|
~Ts103097SignHeaderPolicy() override;
|
||||||
|
void prepare_header(const vanetza::security::SignRequest&, vanetza::security::v3::SecuredMessage&) override;
|
||||||
|
void request_unrecognized_certificate(HashedId8) override;
|
||||||
|
void request_certificate() override;
|
||||||
|
void enqueue_p2p_request(vanetza::security::HashedId3) override;
|
||||||
|
void discard_p2p_request(vanetza::security::HashedId3) override;
|
||||||
|
/// TS 103 300-3 clause 6.5.3 item 2: a CAM was received from a not previously seen signer
|
||||||
|
void report_new_cam_signer();
|
||||||
|
/// after an identifier change the new ticket has never been announced: attach it next
|
||||||
|
void reset_after_identifier_change();
|
||||||
|
|
||||||
|
private:
|
||||||
|
class Impl;
|
||||||
|
std::unique_ptr<Impl> impl_;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** SN-LOG-SECURITY-EVENT.request (TS 102 723-8 V1.1.1 Table 22). Events are
|
||||||
|
* kept in a bounded log the application can drain for misbehaviour reporting. */
|
||||||
|
struct SecurityEvent {
|
||||||
|
enum class Type : std::uint8_t {
|
||||||
|
TIME_CONSISTENCY_FAILED, LOCATION_CONSISTENCY_FAILED, ID_CONSISTENCY_FAILED,
|
||||||
|
DISALLOWED_MESSAGE_CONTENT, DISALLOWED_MESSAGE_FREQUENCY, REPLAY_DETECTION_TIME,
|
||||||
|
REPLAY_DETECTION_LOCATION, MOVEMENT_PLAUSIBILITY, APPEARANCE_PLAUSIBILITY,
|
||||||
|
LOCATION_PLAUSIBILITY_SENSOR, LOCATION_PLAUSIBILITY_MAP, LOCATION_PLAUSIBILITY_CONTRADICTION,
|
||||||
|
APPLICATION_SPECIFIC
|
||||||
|
};
|
||||||
|
struct Location { std::int32_t latitude; std::int32_t longitude; };
|
||||||
|
struct Evidence { std::uint8_t type; ByteBuffer content; }; // event_evidence_type/content
|
||||||
|
Type event_type;
|
||||||
|
std::vector<HashedId8> neighbour_id_list;
|
||||||
|
std::uint32_t event_time; // INTEGER 0..2^32-1, shall be in the past
|
||||||
|
std::optional<Location> event_location;
|
||||||
|
std::vector<Evidence> event_evidence_list;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The steps of the signature in SN-ENCAP, reported to a SignObserver.
|
||||||
|
enum class SignStep : std::uint8_t {
|
||||||
|
header, ///< header fields and signer choice (Ts103097SignHeaderPolicy::prepare_header)
|
||||||
|
ticket, ///< the current ticket is valid for signing this ITS-AID (validity, permissions, region)
|
||||||
|
digest, ///< IEEE Std 1609.2 clause 5.3.1 hash of the to-be-signed data and the signer
|
||||||
|
signature, ///< ECDSA signature in the security module
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Instrumentation of SN-ENCAP (power markers): begin() and end() bracket each SignStep in order.
|
||||||
|
class SignObserver {
|
||||||
|
public:
|
||||||
|
virtual ~SignObserver() = default;
|
||||||
|
virtual void begin(SignStep) = 0;
|
||||||
|
virtual void end(SignStep) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class IdentityManager;
|
||||||
|
|
||||||
|
/** The security entity: SN-ENCAP/SN-DECAP plus the identifier-change service.
|
||||||
|
* Runtime, position provider, backend, pool and trust configuration are
|
||||||
|
* owned by the application and must outlive the entity. SN-ENCAP signs with
|
||||||
|
* the pool's security module; the backend serves hashing, verification and
|
||||||
|
* point decompression. All calls come from the one task that also drives the
|
||||||
|
* stack. */
|
||||||
|
class SecurityEntity : public vanetza::security::SecurityEntity {
|
||||||
|
public:
|
||||||
|
SecurityEntity(vanetza::Runtime&, vanetza::PositionProvider&, vanetza::security::Backend&, CertificatePool&,
|
||||||
|
const TrustConfiguration&);
|
||||||
|
~SecurityEntity() override;
|
||||||
|
|
||||||
|
/** SN-ENCAP.request/.confirm (TS 102 723-8 V1.1.1 Tables 24/25; TS 103 836-4-1 V2.2.1
|
||||||
|
* Table 34). Refused (SignConfirmError::No_Certificate) when the pool is empty, the current
|
||||||
|
* ticket is not valid for the ITS-AID, or an identifier change is between PREPARE and COMMIT
|
||||||
|
* (clause 6.3.1.3: messages with old identifiers shall be avoided). */
|
||||||
|
vanetza::security::EncapConfirm encapsulate_packet(vanetza::security::EncapRequest&&) override;
|
||||||
|
|
||||||
|
/** SN-DECAP.request/.confirm (Tables 26/27). With V2X_SECURITY_VERIFY: check_profile(),
|
||||||
|
* then IEEE Std 1609.2 clause 5.2 verification (signer lookup in the learned-certificate
|
||||||
|
* cache or the inline certificate, authorization ticket validity, permissions for the
|
||||||
|
* ITS-AID, chain to a trust anchor with verified certificate signatures, region, message
|
||||||
|
* signature), generationTime plausibility and replay detection per VerificationPolicy;
|
||||||
|
* a CAM/DENM from an unknown station or with an unknown AA drives the P2P certificate
|
||||||
|
* distribution of TS 103 097 clause 7.1.1 through the header policy, and an AA carried
|
||||||
|
* in requestedCertificate is learned once its signature chains to a trust anchor.
|
||||||
|
* Without V2X_SECURITY_VERIFY: unsigned messages report UNSIGNED_MESSAGE, signed ones
|
||||||
|
* Configuration_Problem, never success; a receiver with
|
||||||
|
* itsGnSnDecapResultHandling = STRICT drops them either way. */
|
||||||
|
vanetza::security::DecapConfirm decapsulate_packet(vanetza::security::DecapRequest&&) override;
|
||||||
|
void set_verification_policy(const VerificationPolicy&);
|
||||||
|
/// report the signing steps of SN-ENCAP to the observer (nullptr: none); it must outlive the entity
|
||||||
|
void observe_signing(SignObserver*);
|
||||||
|
const VerificationPolicy& verification_policy() const;
|
||||||
|
/// authorities learned through P2P certificate distribution (requestedCertificate), verified
|
||||||
|
const std::deque<Certificate>& learned_authorities() const;
|
||||||
|
|
||||||
|
/// SN-LOG-SECURITY-EVENT.request (Table 22); .confirm has no parameters (Table 23)
|
||||||
|
void log_security_event(SecurityEvent);
|
||||||
|
/// take all logged events, oldest first
|
||||||
|
std::deque<SecurityEvent> drain_security_events();
|
||||||
|
void set_security_event_capacity(std::size_t);
|
||||||
|
|
||||||
|
/** Outcome counters. The GN router reports GN-DATA.confirm before SN-ENCAP runs
|
||||||
|
* (TS 103 836-4-1 clause 10.3.10.2 step 2 happens at transmission), so a refused
|
||||||
|
* encapsulation is visible here and in the absence of a packet, not in Stack::request. */
|
||||||
|
struct Statistics { unsigned signed_messages = 0, refused_no_ticket = 0, refused_change_pending = 0,
|
||||||
|
refused_permission = 0, failed = 0;
|
||||||
|
// SN-DECAP outcomes (V2X_SECURITY_VERIFY)
|
||||||
|
unsigned verified = 0, rejected_profile = 0, rejected_signer = 0, rejected_certificate = 0,
|
||||||
|
rejected_signature = 0, rejected_time = 0, replayed = 0, learned_authorities = 0; };
|
||||||
|
const Statistics& statistics() const;
|
||||||
|
|
||||||
|
IdChangeService& id_change();
|
||||||
|
const IdChangeService& id_change() const;
|
||||||
|
IdentityManager& identity_manager();
|
||||||
|
Ts103097SignHeaderPolicy& header_policy();
|
||||||
|
vanetza::security::v3::DefaultCertificateValidator& validator();
|
||||||
|
CertificatePool& certificates();
|
||||||
|
|
||||||
|
private:
|
||||||
|
class Impl;
|
||||||
|
std::unique_ptr<Impl> impl_;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** TS 102 723-8 V1.1.1 clause 6.3 implementation: subscriptions, the two-phase commit
|
||||||
|
* (clause 6.3.1.3, Figures 11 to 13), locks with automatic release (clause 6.3.2,
|
||||||
|
* Table 18) and deferred triggers (clause 6.3.3). New identifier = HashedId8 of the
|
||||||
|
* next authorization ticket in the pool (TS 102 940 V2.1.1 clause 6.5). */
|
||||||
|
class IdentityManager : public IdChangeService {
|
||||||
|
public:
|
||||||
|
IdentityManager(vanetza::Runtime&, CertificatePool&);
|
||||||
|
~IdentityManager() override; // DEREG to every subscriber (Figure 15)
|
||||||
|
|
||||||
|
SubscriptionHandle subscribe(IdChangeHook, ByteBuffer subscriber_data = {}) override;
|
||||||
|
Result unsubscribe(SubscriptionHandle) override;
|
||||||
|
Result trigger() override;
|
||||||
|
LockHandle lock(std::uint8_t duration_seconds) override;
|
||||||
|
Result unlock(LockHandle) override;
|
||||||
|
Identifier current_identifier() const override;
|
||||||
|
bool change_pending() const override;
|
||||||
|
|
||||||
|
/** Time allowed for all PREPARE (or COMMIT) responses before the change is aborted
|
||||||
|
* (or the COMMIT is closed). Not specified by TS 102 723-8; library default 500 ms. */
|
||||||
|
void set_response_timeout(vanetza::Clock::duration);
|
||||||
|
/// invoked after a successful COMMIT with the new identifier
|
||||||
|
void on_committed(std::function<void(const Identifier&)>);
|
||||||
|
|
||||||
|
struct Statistics { unsigned committed = 0, aborted = 0, timed_out = 0, commit_failures = 0; };
|
||||||
|
const Statistics& statistics() const;
|
||||||
|
bool locked() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
class Impl;
|
||||||
|
std::shared_ptr<Impl> impl_; // responders keep a weak reference across the manager's lifetime
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/security_module.hpp>
|
||||||
|
#include <vanetza/security/backend.hpp>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
// The station's cryptography behind two interfaces, chosen at build time (Kconfig "Security module"):
|
||||||
|
// SecurityModule (security_module.hpp) every private key and the signatures made with it
|
||||||
|
// vanetza::security::Backend hashing, verification and point decompression of public data
|
||||||
|
// The station never sees which implementation is behind either.
|
||||||
|
namespace microbu_v2x {
|
||||||
|
|
||||||
|
std::unique_ptr<vanetza::security::Backend> make_security_backend();
|
||||||
|
std::unique_ptr<security::SecurityModule> make_security_module();
|
||||||
|
const char* security_module_name();
|
||||||
|
|
||||||
|
// An external adapter component implements these factories. Each must return a working implementation or throw;
|
||||||
|
// a missing adapter never falls back to software. make_external_security_backend() is needed only when the
|
||||||
|
// adapter takes the public operations as well (V2X HSM).
|
||||||
|
std::unique_ptr<security::SecurityModule> make_external_security_module();
|
||||||
|
std::unique_ptr<vanetza::security::Backend> make_external_security_backend();
|
||||||
|
|
||||||
|
/// NVS location of the keys of the local software module (the station's credential checkpoint copies it).
|
||||||
|
constexpr const char* local_key_namespace = "v2x_keys";
|
||||||
|
constexpr const char* local_key_name = "keys";
|
||||||
|
|
||||||
|
} // namespace microbu_v2x
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <vanetza/common/byte_buffer.hpp>
|
||||||
|
#include <vanetza/security/backend.hpp>
|
||||||
|
#include <vanetza/security/key_type.hpp>
|
||||||
|
#include <vanetza/security/private_key.hpp>
|
||||||
|
#include <vanetza/security/public_key.hpp>
|
||||||
|
#include <vanetza/security/signature.hpp>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <map>
|
||||||
|
#include <optional>
|
||||||
|
|
||||||
|
/** The station's security module: the only place that holds private keys.
|
||||||
|
*
|
||||||
|
* Everything that the micrOBU hardware puts into its secure element (SE051 on the
|
||||||
|
* prototype mainboard) or a later V2X HSM is behind SecurityModule: generation
|
||||||
|
* and import of key pairs, keeping them across resets, and the ECDSA signature
|
||||||
|
* over a digest (IEEE Std 1609.2 clause 5.3.1). Callers hold a KeyId, never a
|
||||||
|
* private key value; the operations follow the key management and asymmetric
|
||||||
|
* signature functions of the PSA Certified Crypto API (psa_generate_key,
|
||||||
|
* psa_import_key, psa_export_public_key, psa_sign_hash, psa_destroy_key), which
|
||||||
|
* a secure element integrates as an opaque key location.
|
||||||
|
*
|
||||||
|
* Operations on public data stay with vanetza::security::Backend on the
|
||||||
|
* application processor: hashing, verification and point decompression.
|
||||||
|
* Ephemeral ECIES keys and the AES-CCM session key of a TS 102 941 request
|
||||||
|
* (pki.hpp) are short-lived and stay there too.
|
||||||
|
*/
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
|
using vanetza::ByteBuffer;
|
||||||
|
using vanetza::security::KeyType;
|
||||||
|
using vanetza::security::PrivateKey;
|
||||||
|
using vanetza::security::PublicKey;
|
||||||
|
using vanetza::security::Signature;
|
||||||
|
|
||||||
|
/// A key held by a SecurityModule. A stored KeyId stays valid across resets until the key is destroyed.
|
||||||
|
struct KeyId {
|
||||||
|
std::uint32_t value = 0; // 0 is no key
|
||||||
|
explicit operator bool() const { return value != 0; }
|
||||||
|
friend bool operator==(KeyId a, KeyId b) { return a.value == b.value; }
|
||||||
|
friend bool operator!=(KeyId a, KeyId b) { return a.value != b.value; }
|
||||||
|
friend bool operator<(KeyId a, KeyId b) { return a.value < b.value; }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A key pair outside a security module: an authority's key in the issuing tools, an ephemeral ECIES key, or a
|
||||||
|
/// laboratory ticket key on its way into the module. Public key uncompressed.
|
||||||
|
struct KeyPair {
|
||||||
|
PrivateKey priv;
|
||||||
|
PublicKey pub;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SecurityModule {
|
||||||
|
public:
|
||||||
|
virtual ~SecurityModule() = default;
|
||||||
|
/// New key pair on the curve, kept in the module; throws std::runtime_error when the module cannot create it.
|
||||||
|
virtual KeyId generate_key(KeyType) = 0;
|
||||||
|
/// Laboratory provisioning of a key pair created outside the station (VCR1 bundle, issuing tools). None when
|
||||||
|
/// the two halves do not belong together; throws std::runtime_error when the module cannot store the key.
|
||||||
|
virtual std::optional<KeyId> import_key(const KeyPair&) = 0;
|
||||||
|
/// The public half (uncompressed), none for a KeyId the module does not hold.
|
||||||
|
virtual std::optional<PublicKey> public_key(KeyId) const = 0;
|
||||||
|
/// ECDSA with the curve of the key over a digest of the curve's length; throws std::runtime_error for a KeyId
|
||||||
|
/// the module does not hold or a failed operation.
|
||||||
|
virtual Signature sign_digest(KeyId, const ByteBuffer& digest) = 0;
|
||||||
|
/// Removes the key for good; false when the module holds no such key.
|
||||||
|
virtual bool destroy_key(KeyId) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// True when both keys are the same point on the same curve, in compressed or uncompressed form.
|
||||||
|
bool same_public_key(const PublicKey&, const PublicKey&);
|
||||||
|
|
||||||
|
/// Creates key pairs for SoftwareSecurityModule (the platform's random generator).
|
||||||
|
class KeyGenerator {
|
||||||
|
public:
|
||||||
|
virtual ~KeyGenerator() = default;
|
||||||
|
virtual KeyPair generate_key(KeyType) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Where SoftwareSecurityModule keeps its keys between resets: one blob, written as a whole.
|
||||||
|
class KeyStorage {
|
||||||
|
public:
|
||||||
|
virtual ~KeyStorage() = default;
|
||||||
|
/// false when nothing is stored
|
||||||
|
virtual bool load(ByteBuffer&) = 0;
|
||||||
|
virtual bool save(const ByteBuffer&) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
class MemoryKeyStorage final : public KeyStorage {
|
||||||
|
public:
|
||||||
|
bool load(ByteBuffer& out) override;
|
||||||
|
bool save(const ByteBuffer& blob) override;
|
||||||
|
private:
|
||||||
|
ByteBuffer blob_;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** SecurityModule in software on the application processor: the stand-in for the SE051 until its adapter
|
||||||
|
* exists. Signs through a Backend and keeps the keys in a KeyStorage, whose protection at rest is the
|
||||||
|
* platform's (NVS encryption on the ESP32-C5). Storage format: "MSM1", next KeyId (4 octets), then per key
|
||||||
|
* [KeyId: 4][curve: 1][private scalar][public x][public y], all big-endian. */
|
||||||
|
class SoftwareSecurityModule final : public SecurityModule {
|
||||||
|
public:
|
||||||
|
/// Loads the stored keys; throws std::runtime_error when the stored blob does not decode.
|
||||||
|
SoftwareSecurityModule(vanetza::security::Backend&, KeyGenerator&, KeyStorage&);
|
||||||
|
~SoftwareSecurityModule() override;
|
||||||
|
SoftwareSecurityModule(const SoftwareSecurityModule&) = delete;
|
||||||
|
SoftwareSecurityModule& operator=(const SoftwareSecurityModule&) = delete;
|
||||||
|
|
||||||
|
KeyId generate_key(KeyType) override;
|
||||||
|
std::optional<KeyId> import_key(const KeyPair&) override;
|
||||||
|
std::optional<PublicKey> public_key(KeyId) const override;
|
||||||
|
Signature sign_digest(KeyId, const ByteBuffer& digest) override;
|
||||||
|
bool destroy_key(KeyId) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
KeyId keep(KeyPair);
|
||||||
|
void persist();
|
||||||
|
|
||||||
|
vanetza::security::Backend& backend_;
|
||||||
|
KeyGenerator& generator_;
|
||||||
|
KeyStorage& storage_;
|
||||||
|
std::map<KeyId, KeyPair> keys_;
|
||||||
|
std::uint32_t next_ = 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#include <vanetza/common/its_aid.hpp>
|
#include <vanetza/common/its_aid.hpp>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
* (TS 103 300-3 clause 6.5.1; TS 103 836-4-1 clause 10.3.10.2 SN-ENCAP), so
|
* (TS 103 300-3 clause 6.5.1; TS 103 836-4-1 clause 10.3.10.2 SN-ENCAP), so
|
||||||
* this library provides no facilities-level signing service.
|
* this library provides no facilities-level signing service.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::SF_SAP {
|
namespace microbu_v2x::SF_SAP {
|
||||||
|
|
||||||
// The same identifier-change service types as sn_sap.hpp (TS 102 723-9 V1.1.1 clause 4.1.5:
|
// The same identifier-change service types as sn_sap.hpp (TS 102 723-9 V1.1.1 clause 4.1.5:
|
||||||
// one security entity serves several layers), under the SF-SAP names.
|
// one security entity serves several layers), under the SF-SAP names.
|
||||||
@@ -161,4 +161,4 @@ struct SF_DECAP_confirm {
|
|||||||
vanetza::ByteBuffer permissions;
|
vanetza::ByteBuffer permissions;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace vanetza_idf::SF_SAP
|
} // namespace microbu_v2x::SF_SAP
|
||||||
+7
-7
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#include <vanetza/common/byte_buffer_sink.hpp>
|
#include <vanetza/common/byte_buffer_sink.hpp>
|
||||||
#include <vanetza/net/osi_layer.hpp>
|
#include <vanetza/net/osi_layer.hpp>
|
||||||
#include <vanetza/net/packet.hpp>
|
#include <vanetza/net/packet.hpp>
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
* these bindings serve a caller in another task, process or device and the
|
* these bindings serve a caller in another task, process or device and the
|
||||||
* test adapters; the library defines no transport for that.
|
* test adapters; the library defines no transport for that.
|
||||||
*/
|
*/
|
||||||
namespace vanetza_idf::SN_SAP {
|
namespace microbu_v2x::SN_SAP {
|
||||||
|
|
||||||
// Types of the identifier-change service (id_change.hpp: TS 102 723-8 V1.1.1 clause 6.3,
|
// Types of the identifier-change service (id_change.hpp: TS 102 723-8 V1.1.1 clause 6.3,
|
||||||
// identifier = HashedId8 per TS 102 940 V2.1.1 clause 6.5) under the SN-SAP names.
|
// identifier = HashedId8 per TS 102 940 V2.1.1 clause 6.5) under the SN-SAP names.
|
||||||
@@ -87,10 +87,10 @@ struct SN_DECAP_request {
|
|||||||
std::size_t sec_packet_length = 0;
|
std::size_t sec_packet_length = 0;
|
||||||
vanetza::ByteBuffer sec_packet; // EtsiTs103097Data (COER), without the GN basic header
|
vanetza::ByteBuffer sec_packet; // EtsiTs103097Data (COER), without the GN basic header
|
||||||
};
|
};
|
||||||
/// Table 27: SN-DECAP.confirm. report never reads SUCCESS from this library: verification
|
/// TS 102 723-8 Table 27: SN-DECAP.confirm carries the verification outcome.
|
||||||
/// is not implemented (docs/idf/conformance.md GAP-SEC-001), the entity answers
|
/// Callers enforce their receive policy using report and the signer permissions.
|
||||||
/// CONFIGURATION_PROBLEM (signed) or UNSIGNED_MESSAGE; the ITS-AID and permissions are
|
/// Verification requires V2X_SECURITY_VERIFY. Builds without it report
|
||||||
/// those the packet claims, forwarded for the caller's own policy, not verified.
|
/// CONFIGURATION_PROBLEM for signed messages and UNSIGNED_MESSAGE otherwise.
|
||||||
struct SN_DECAP_confirm {
|
struct SN_DECAP_confirm {
|
||||||
std::size_t plaintext_packet_length = 0;
|
std::size_t plaintext_packet_length = 0;
|
||||||
vanetza::ByteBuffer plaintext_packet;
|
vanetza::ByteBuffer plaintext_packet;
|
||||||
@@ -186,4 +186,4 @@ inline Result SN_DECAP_request_submit(vanetza::security::SecurityEntity& entity,
|
|||||||
return Result::accepted;
|
return Result::accepted;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vanetza_idf::SN_SAP
|
} // namespace microbu_v2x::SN_SAP
|
||||||
+13
-12
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <vanetza_idf/access.hpp>
|
#include <microbu_v2x/access.hpp>
|
||||||
#include <vanetza_idf/id_change.hpp>
|
#include <microbu_v2x/id_change.hpp>
|
||||||
#include <vanetza/common/manual_runtime.hpp>
|
#include <vanetza/common/manual_runtime.hpp>
|
||||||
#include <vanetza/common/position_fix.hpp>
|
#include <vanetza/common/position_fix.hpp>
|
||||||
#include <vanetza/dcc/channel_load.hpp>
|
#include <vanetza/dcc/channel_load.hpp>
|
||||||
@@ -12,11 +12,11 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <optional>
|
#include <optional>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
enum class BtpType { a, b };
|
enum class BtpType { a, b };
|
||||||
|
|
||||||
/** NF-SAP / BTP-DATA.request: TS 103 836-5-1 V2.1.1 Annex A.2
|
/** NF-SAP / BTP-DATA.request: TS 103 836-5-1 V2.1.1 Annex A.2
|
||||||
* and clauses 7, 8.2 (IF-NF-001); TS 102 723-11 V2.0.0 clause 5
|
* and clauses 7, 8.2; TS 102 723-11 V2.0.0 clause 5
|
||||||
* incorporates V1.1.1, including its clause 5.1 GeoAware SAP.
|
* incorporates V1.1.1, including its clause 5.1 GeoAware SAP.
|
||||||
* All port numbers are HOST order. data.size() is the Length parameter.
|
* All port numbers are HOST order. data.size() is the Length parameter.
|
||||||
* Omitted GN parameters inherit the configured MIB. No magic sentinel values.
|
* Omitted GN parameters inherit the configured MIB. No magic sentinel values.
|
||||||
@@ -44,7 +44,7 @@ struct BtpRequest {
|
|||||||
vanetza::ByteBuffer data;
|
vanetza::ByteBuffer data;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** BTP-DATA.indication: TS 103 836-5-1 V2.1.1 Annex A.3/8.3 (IF-NF-002).
|
/** BTP-DATA.indication: TS 103 836-5-1 V2.1.1 Annex A.3/8.3.
|
||||||
* gn retains the transport, destination, source vector, report, permissions,
|
* gn retains the transport, destination, source vector, report, permissions,
|
||||||
* traffic class, remaining lifetime and hop limit. Owns the received payload.
|
* traffic class, remaining lifetime and hop limit. Owns the received payload.
|
||||||
*/
|
*/
|
||||||
@@ -59,10 +59,10 @@ struct BtpIndication {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** GN-DATA.request: TS 103 836-4-1 V2.2.1 clause 9.3 N-SAP (EN 302 636-4-1
|
/** GN-DATA.request: TS 103 836-4-1 V2.2.1 clause 9.3 N-SAP (EN 302 636-4-1
|
||||||
* clause 9.3 heritage), IF-GN-001. Unlike BtpRequest, data is the raw SDU
|
* clause 9.3 heritage). Unlike BtpRequest, data is the raw SDU
|
||||||
* with no assumed upper-layer header; the Common Header next_header is
|
* with no assumed upper-layer header; the Common Header next_header is
|
||||||
* "Any". Only SHB and GBC are implemented; GUC, GAC and TSB are rejected
|
* "Any". Only SHB and GBC are implemented; GUC, GAC and TSB are rejected
|
||||||
* as Result::unsupported (GAP-GN-001), matching Stack::request(BtpRequest).
|
* as Result::unsupported, matching Stack::request(BtpRequest).
|
||||||
*/
|
*/
|
||||||
struct GnRequest {
|
struct GnRequest {
|
||||||
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
|
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
|
||||||
@@ -100,7 +100,7 @@ struct StackConfig {
|
|||||||
* clock advancement and destruction. Access/SecurityEntity must outlive Stack.
|
* clock advancement and destruction. Access/SecurityEntity must outlive Stack.
|
||||||
* Timer source is injectable for host tests, HIL and ESP-IDF esp_timer.
|
* Timer source is injectable for host tests, HIL and ESP-IDF esp_timer.
|
||||||
* No FreeRTOS task, radio, BLE link, socket or filesystem is opened internally.
|
* No FreeRTOS task, radio, BLE link, socket or filesystem is opened internally.
|
||||||
* This is a port of the upstream router; see docs/idf/conformance.md for R2 gaps.
|
* This is a port of the upstream router; see docs/conformance.md for R2 gaps.
|
||||||
*
|
*
|
||||||
* Identifier change (TS 103 836-4-1 V2.2.1 clause 10.2.1.4, anonymous address
|
* Identifier change (TS 103 836-4-1 V2.2.1 clause 10.2.1.4, anonymous address
|
||||||
* configuration): with itsGnLocalAddrConfMethod == Anonymous and an
|
* configuration): with itsGnLocalAddrConfMethod == Anonymous and an
|
||||||
@@ -119,7 +119,7 @@ public:
|
|||||||
using Receive = std::function<void(BtpIndication)>;
|
using Receive = std::function<void(BtpIndication)>;
|
||||||
using ReceiveGn = std::function<void(GnIndication)>;
|
using ReceiveGn = std::function<void(GnIndication)>;
|
||||||
using Report = std::function<void(Result)>;
|
using Report = std::function<void(Result)>;
|
||||||
/** id_change may be omitted: when security is a vanetza_idf::security::SecurityEntity
|
/** id_change may be omitted: when security is a microbu_v2x::security::SecurityEntity
|
||||||
* its own identifier-change service is used. */
|
* its own identifier-change service is used. */
|
||||||
Stack(StackConfig, vanetza::ManualRuntime&, Access&,
|
Stack(StackConfig, vanetza::ManualRuntime&, Access&,
|
||||||
vanetza::security::SecurityEntity* security = nullptr,
|
vanetza::security::SecurityEntity* security = nullptr,
|
||||||
@@ -135,6 +135,8 @@ public:
|
|||||||
void on_receive(Receive);
|
void on_receive(Receive);
|
||||||
void on_receive_gn(ReceiveGn);
|
void on_receive_gn(ReceiveGn);
|
||||||
void on_access_result(Report);
|
void on_access_result(Report);
|
||||||
|
/// Observe the native Vanetza packet drop reason without changing its decision.
|
||||||
|
void on_packet_drop(std::function<void(const std::string&)>);
|
||||||
const StackConfig& config() const;
|
const StackConfig& config() const;
|
||||||
/// the identifier-change service this stack subscribed to, nullptr without one
|
/// the identifier-change service this stack subscribed to, nullptr without one
|
||||||
security::IdChangeService* id_change();
|
security::IdChangeService* id_change();
|
||||||
@@ -149,7 +151,7 @@ public:
|
|||||||
* Anonymous (10.2.1.4) configuration, identity_change_pending during a change. */
|
* Anonymous (10.2.1.4) configuration, identity_change_pending during a change. */
|
||||||
Result set_address(const vanetza::geonet::Address&);
|
Result set_address(const vanetza::geonet::Address&);
|
||||||
|
|
||||||
/** Release-2 DCC_NET (TS 103 836-4-2 V2.1.1 clauses 5, 6.2, 6.3.3, 7.2; SYS-DCC-003).
|
/** Release-2 DCC_NET (TS 103 836-4-2 V2.1.1 clauses 5, 6.2, 6.3.3, 7.2).
|
||||||
* Always active for this ITS-G5-only Stack: outgoing SHB packets carry a real DCC-MCO
|
* Always active for this ITS-G5-only Stack: outgoing SHB packets carry a real DCC-MCO
|
||||||
* field (local/one-hop CBR, TX power) instead of the upstream NullDccFieldGenerator's
|
* field (local/one-hop CBR, TX power) instead of the upstream NullDccFieldGenerator's
|
||||||
* reserved zero field, and every received SHB packet's DCC-MCO updates LocTEX-G5
|
* reserved zero field, and every received SHB packet's DCC-MCO updates LocTEX-G5
|
||||||
@@ -157,8 +159,7 @@ public:
|
|||||||
* Stack requires). report_local_channel_load feeds DCC_NET's own CBR_G calculation
|
* Stack requires). report_local_channel_load feeds DCC_NET's own CBR_G calculation
|
||||||
* (clause 5.3); it is independent of AccessStack::report_channel_load (DCC_ACC), which
|
* (clause 5.3); it is independent of AccessStack::report_channel_load (DCC_ACC), which
|
||||||
* the caller should feed with global_channel_busy_ratio() when available, else the same
|
* the caller should feed with global_channel_busy_ratio() when available, else the same
|
||||||
* local measurement (SYS-DCC-001: "consume Release-2 CBR_G when available, otherwise
|
* local measurement.
|
||||||
* LCBR").
|
|
||||||
*/
|
*/
|
||||||
void report_local_channel_load(vanetza::dcc::ChannelLoad);
|
void report_local_channel_load(vanetza::dcc::ChannelLoad);
|
||||||
/// EIRP of the station's own transmissions, for the outgoing DCC-MCO field's TX-power octet.
|
/// EIRP of the station's own transmissions, for the outgoing DCC-MCO field's TX-power octet.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/pki.hpp>
|
||||||
|
#include <microbu_v2x/credentials.hpp>
|
||||||
|
|
||||||
|
namespace microbu_v2x::pki {
|
||||||
|
// TS 102 941 clauses 6.3.1 to 6.3.6. One complete authenticated transaction.
|
||||||
|
struct TrustSnapshot {
|
||||||
|
ByteBuffer tlm, rca, ectl, ctl, crl;
|
||||||
|
Time32 deadline = 0;
|
||||||
|
};
|
||||||
|
ByteBuffer encode_snapshot(const TrustSnapshot&);
|
||||||
|
bool decode_snapshot(const ByteBuffer&, TrustSnapshot&);
|
||||||
|
// Initial bootstrap requires the independently pinned TLM. Later TLM changes
|
||||||
|
// require a successor authenticated by the previously accepted ECTL.
|
||||||
|
bool validate_update(vanetza::security::Backend&, vanetza::Clock::time_point,
|
||||||
|
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
|
||||||
|
const TrustSnapshot& proposed, TrustSnapshot& accepted);
|
||||||
|
bool snapshot_credentials(vanetza::security::Backend&, const TrustSnapshot&,
|
||||||
|
microbu_v2x::security::StoredCredentials&, microbu_v2x::security::TrustConfiguration* = nullptr);
|
||||||
|
}
|
||||||
+3
-3
@@ -6,7 +6,7 @@ endif()
|
|||||||
if(NOT IDF_VERSION_MAJOR EQUAL 6 OR NOT IDF_VERSION_MINOR EQUAL 0 OR NOT IDF_VERSION_PATCH EQUAL 2)
|
if(NOT IDF_VERSION_MAJOR EQUAL 6 OR NOT IDF_VERSION_MINOR EQUAL 0 OR NOT IDF_VERSION_PATCH EQUAL 2)
|
||||||
message(FATAL_ERROR "C5 private radio ABI is pinned to ESP-IDF 6.0.2")
|
message(FATAL_ERROR "C5 private radio ABI is pinned to ESP-IDF 6.0.2")
|
||||||
endif()
|
endif()
|
||||||
set(_otm_source "${VIDF_PORT}/third_party/otm/main/tx_custom.c")
|
set(_otm_source "${V2X_PORT}/third_party/otm/main/tx_custom.c")
|
||||||
if(NOT EXISTS "${_otm_source}")
|
if(NOT EXISTS "${_otm_source}")
|
||||||
message(FATAL_ERROR "Initialize the OpenTrafficMap submodule before selecting the C5 radio")
|
message(FATAL_ERROR "Initialize the OpenTrafficMap submodule before selecting the C5 radio")
|
||||||
endif()
|
endif()
|
||||||
@@ -23,5 +23,5 @@ string(REPLACE " ieee80211_post_hmac_tx(eb);"
|
|||||||
" result = ieee80211_post_hmac_tx(eb);" _otm "${_otm}")
|
" result = ieee80211_post_hmac_tx(eb);" _otm "${_otm}")
|
||||||
set(_otm_generated "${CMAKE_CURRENT_BINARY_DIR}/otm_tx_custom.c")
|
set(_otm_generated "${CMAKE_CURRENT_BINARY_DIR}/otm_tx_custom.c")
|
||||||
file(WRITE "${_otm_generated}" "#include <assert.h>\n#include <stddef.h>\n${_otm}\n_Static_assert(offsetof(x_ebuf_t, txdesc) == 0x38, \"ebuf txdesc offset\");\n_Static_assert(offsetof(x_eb_txdesc_t, rate) == 0x0c, \"txdesc rate offset\");\n")
|
file(WRITE "${_otm_generated}" "#include <assert.h>\n#include <stddef.h>\n${_otm}\n_Static_assert(offsetof(x_ebuf_t, txdesc) == 0x38, \"ebuf txdesc offset\");\n_Static_assert(offsetof(x_eb_txdesc_t, rate) == 0x0c, \"txdesc rate offset\");\n")
|
||||||
target_sources(${VIDF_TARGET} PRIVATE "${VIDF_PORT}/src/c5_radio.cpp" "${_otm_generated}")
|
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/c5_radio.cpp" "${_otm_generated}")
|
||||||
target_include_directories(${VIDF_TARGET} PRIVATE "${VIDF_PORT}/third_party/otm/main")
|
target_include_directories(${V2X_TARGET} PRIVATE "${V2X_PORT}/third_party/otm/main")
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#include <microbu_v2x/access.hpp>
|
||||||
|
#include <cmath>
|
||||||
|
#include <utility>
|
||||||
|
#if V2X_NETWORK
|
||||||
|
#include <vanetza/access/data_rates.hpp>
|
||||||
|
#include <vanetza/dcc/limeric.hpp>
|
||||||
|
#include <vanetza/dcc/limeric_budget.hpp>
|
||||||
|
#include <vanetza/dcc/profile.hpp>
|
||||||
|
#include <vanetza/dcc/transmission.hpp>
|
||||||
|
#include <array>
|
||||||
|
#include <chrono>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace microbu_v2x {
|
||||||
|
Result validate(const AlDataRequest& request, std::size_t maximum) {
|
||||||
|
if (request.data.empty() || request.data.size() > maximum || request.priority > 7 ||
|
||||||
|
!std::isfinite(request.transmit_power_dbm) || request.bandwidth_mhz == 0)
|
||||||
|
return Result::invalid_argument;
|
||||||
|
return Result::accepted;
|
||||||
|
}
|
||||||
|
#if V2X_NETWORK
|
||||||
|
namespace {
|
||||||
|
// EN 303 797 V2.1.1 clause 4.6.2's Ton limit; a single
|
||||||
|
// frame at or below this duration also cannot alone exceed the 3 % duty cycle at Toff>=25 ms.
|
||||||
|
constexpr vanetza::Clock::duration max_ton = std::chrono::milliseconds(4);
|
||||||
|
// Index by OfdmMcs; mirrors the rate table in C5Radio::request/transmit_burst.
|
||||||
|
constexpr std::array<const vanetza::access::DataRateG5*, 8> g5_rates {
|
||||||
|
&vanetza::access::G5_3Mbps, &vanetza::access::G5_4dot5Mbps, &vanetza::access::G5_6Mbps,
|
||||||
|
&vanetza::access::G5_9Mbps, &vanetza::access::G5_12Mbps, &vanetza::access::G5_18bps,
|
||||||
|
&vanetza::access::G5_24Mbps, &vanetza::access::G5_27Mbps,
|
||||||
|
};
|
||||||
|
// Airtime-only use of Transmission::channel_occupancy(); profile is immaterial here since no
|
||||||
|
// FlowControl queueing is involved, only the data-rate/length formula.
|
||||||
|
vanetza::Clock::duration request_airtime(const AlDataRequest& request) {
|
||||||
|
vanetza::dcc::TransmissionLite transmission(vanetza::dcc::Profile::DP2, request.data.size());
|
||||||
|
const auto index = static_cast<unsigned>(request.mcs);
|
||||||
|
transmission.m_data_rate = index < g5_rates.size() ? g5_rates[index] : nullptr;
|
||||||
|
return transmission.channel_occupancy();
|
||||||
|
}
|
||||||
|
// TS 102 687 V1.2.1 Table 3 defaults, with cbr_target overridden to the project's Release-2
|
||||||
|
// value.
|
||||||
|
vanetza::dcc::Limeric::Parameters limeric_parameters(vanetza::dcc::ChannelLoad cbr_target) {
|
||||||
|
vanetza::dcc::Limeric::Parameters parameters;
|
||||||
|
parameters.cbr_target = cbr_target;
|
||||||
|
return parameters;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
class AccessStack::Dcc {
|
||||||
|
public:
|
||||||
|
Dcc(vanetza::Runtime& rt, vanetza::dcc::ChannelLoad target) :
|
||||||
|
limeric(rt, limeric_parameters(target)),
|
||||||
|
budget(limeric, rt)
|
||||||
|
{
|
||||||
|
// TS 102 687 V1.2.1 Annex B: the gate-opening time depends on the current permitted
|
||||||
|
// duty cycle, so it must be recalculated whenever the Adaptive approach updates delta.
|
||||||
|
limeric.on_duty_cycle_change = [this](const vanetza::dcc::Limeric*, vanetza::Clock::time_point) {
|
||||||
|
budget.update();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
vanetza::dcc::Limeric limeric;
|
||||||
|
vanetza::dcc::LimericBudget budget;
|
||||||
|
};
|
||||||
|
|
||||||
|
void AccessStack::enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target) {
|
||||||
|
dcc_ = std::make_unique<Dcc>(runtime, cbr_target);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccessStack::report_channel_load(vanetza::dcc::ChannelLoad load) {
|
||||||
|
if (dcc_) dcc_->limeric.update_cbr(load);
|
||||||
|
}
|
||||||
|
|
||||||
|
vanetza::UnitInterval AccessStack::permitted_duty_cycle() const {
|
||||||
|
return dcc_ ? dcc_->limeric.permitted_duty_cycle() : vanetza::UnitInterval(1.0);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
AccessStack::AccessStack(Access& access, std::size_t maximum) :
|
||||||
|
access_(access), maximum_gnpdu_(maximum) {}
|
||||||
|
AccessStack::~AccessStack() = default;
|
||||||
|
|
||||||
|
Result AccessStack::request(AlDataRequest request) {
|
||||||
|
auto result = validate(request, maximum_gnpdu_);
|
||||||
|
if (result != Result::accepted) return result;
|
||||||
|
#if V2X_NETWORK
|
||||||
|
if (dcc_) {
|
||||||
|
const auto ton = request_airtime(request);
|
||||||
|
if (ton <= vanetza::Clock::duration::zero() || ton > max_ton) return Result::invalid_argument;
|
||||||
|
if (dcc_->budget.delay() > vanetza::Clock::duration::zero()) return Result::resource_limit;
|
||||||
|
result = access_.request(std::move(request));
|
||||||
|
if (result == Result::accepted) dcc_->budget.notify(ton);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
return access_.request(std::move(request));
|
||||||
|
}
|
||||||
|
}
|
||||||
+25
-12
@@ -1,12 +1,12 @@
|
|||||||
#include <vanetza_idf/backend_mbedtls.hpp>
|
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||||
#include <vanetza_idf/ecc.hpp>
|
#include <microbu_v2x/ecc.hpp>
|
||||||
#include <vanetza/security/sha.hpp>
|
#include <vanetza/security/sha.hpp>
|
||||||
#include <psa/crypto.h>
|
#include <psa/crypto.h>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <deque>
|
#include <deque>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
using namespace vanetza::security;
|
using namespace vanetza::security;
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
@@ -212,22 +212,35 @@ vanetza::ByteBuffer BackendMbedTls::calculate_hash(HashAlgorithm algorithm, cons
|
|||||||
}
|
}
|
||||||
|
|
||||||
ecdsa256::KeyPair BackendMbedTls::generate_key_pair() {
|
ecdsa256::KeyPair BackendMbedTls::generate_key_pair() {
|
||||||
|
const auto generated = generate_key(KeyType::NistP256);
|
||||||
|
ecdsa256::KeyPair pair;
|
||||||
|
std::copy(generated.priv.key.begin(), generated.priv.key.end(), pair.private_key.key.begin());
|
||||||
|
std::copy(generated.pub.x.begin(), generated.pub.x.end(), pair.public_key.x.begin());
|
||||||
|
std::copy(generated.pub.y.begin(), generated.pub.y.end(), pair.public_key.y.begin());
|
||||||
|
return pair;
|
||||||
|
}
|
||||||
|
|
||||||
|
security::KeyPair BackendMbedTls::generate_key(KeyType type) {
|
||||||
|
const std::size_t n = key_length(type);
|
||||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
|
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
|
||||||
psa_set_key_bits(&attributes, 256);
|
psa_set_key_bits(&attributes, n * 8);
|
||||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
||||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA_ANY);
|
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA_ANY);
|
||||||
ScopedKey key;
|
ScopedKey key;
|
||||||
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
||||||
ecdsa256::KeyPair pair;
|
security::KeyPair pair;
|
||||||
|
pair.priv.type = pair.pub.type = type;
|
||||||
|
pair.pub.compression = KeyCompression::NoCompression;
|
||||||
|
pair.priv.key.resize(n);
|
||||||
std::size_t length = 0;
|
std::size_t length = 0;
|
||||||
if (psa_export_key(key.id, pair.private_key.key.data(), pair.private_key.key.size(), &length) != PSA_SUCCESS ||
|
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
|
||||||
length != pair.private_key.key.size()) throw std::runtime_error("PSA private key export failed");
|
throw std::runtime_error("PSA private key export failed");
|
||||||
std::array<std::uint8_t, 65> sec1 {};
|
vanetza::ByteBuffer sec1(1 + 2 * n);
|
||||||
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() ||
|
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() ||
|
||||||
sec1[0] != 0x04) throw std::runtime_error("PSA public key export failed");
|
sec1[0] != 0x04) throw std::runtime_error("PSA public key export failed");
|
||||||
std::copy(sec1.begin() + 1, sec1.begin() + 33, pair.public_key.x.begin());
|
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
|
||||||
std::copy(sec1.begin() + 33, sec1.end(), pair.public_key.y.begin());
|
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
|
||||||
return pair;
|
return pair;
|
||||||
}
|
}
|
||||||
} // namespace vanetza_idf
|
} // namespace microbu_v2x
|
||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
#include <vanetza_idf/c5_radio.hpp>
|
#include <microbu_v2x/c5_radio.hpp>
|
||||||
#include <vanetza_idf/its_g5_frame.hpp>
|
#include <microbu_v2x/its_g5_frame.hpp>
|
||||||
#include <esp_event.h>
|
#include <esp_event.h>
|
||||||
#include <esp_wifi.h>
|
#include <esp_wifi.h>
|
||||||
#include <hal/modem_syscon_ll.h>
|
#include <hal/modem_syscon_ll.h>
|
||||||
@@ -18,7 +18,7 @@ esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t, const void*, int32_t, bool,
|
|||||||
wifi_tx_rate_config_t*, wifi_band_t, wifi_bandwidth_t);
|
wifi_tx_rate_config_t*, wifi_band_t, wifi_bandwidth_t);
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
class C5Radio::Impl {
|
class C5Radio::Impl {
|
||||||
public:
|
public:
|
||||||
struct Raw {
|
struct Raw {
|
||||||
@@ -46,7 +46,7 @@ public:
|
|||||||
// value (00 00 99 00), not a real, software-recoverable FCS. This promiscuous
|
// value (00 00 99 00), not a real, software-recoverable FCS. This promiscuous
|
||||||
// filter never sets WIFI_PROMIS_FILTER_MASK_FCSFAIL, so the frame itself has
|
// filter never sets WIFI_PROMIS_FILTER_MASK_FCSFAIL, so the frame itself has
|
||||||
// already passed a real hardware FCS check by the time it reaches this callback
|
// already passed a real hardware FCS check by the time it reaches this callback
|
||||||
// -- see ports/esp_idf/tools/radio_pair.py's docstring for the full evidence.
|
// -- see components/microbu_v2x/tools/radio_pair.py's docstring for the full evidence.
|
||||||
const auto length = packet->rx_ctrl.sig_len;
|
const auto length = packet->rx_ctrl.sig_len;
|
||||||
std::lock_guard<std::mutex> lock(callback_mutex);
|
std::lock_guard<std::mutex> lock(callback_mutex);
|
||||||
if (!active || !active->queue) return;
|
if (!active || !active->queue) return;
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
#include <microbu_v2x/credentials.hpp>
|
||||||
|
#include <vanetza/security/v3/certificate.hpp>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iterator>
|
||||||
|
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
using vanetza::security::KeyType;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::uint8_t bundle_magic[4] = {'V', 'C', 'R', '1'};
|
||||||
|
constexpr std::uint8_t stored_magic[4] = {'V', 'C', 'S', '1'};
|
||||||
|
enum Record : std::uint8_t { root = 1, authority = 2, ticket = 3, ticket_key = 4, ticket_key_id = 5 };
|
||||||
|
|
||||||
|
std::uint8_t curve_code(KeyType type) {
|
||||||
|
switch (type) {
|
||||||
|
case KeyType::NistP256: return 1;
|
||||||
|
case KeyType::BrainpoolP256r1: return 2;
|
||||||
|
case KeyType::BrainpoolP384r1: return 3;
|
||||||
|
default: return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
KeyType curve_type(std::uint8_t code) {
|
||||||
|
switch (code) {
|
||||||
|
case 1: return KeyType::NistP256;
|
||||||
|
case 2: return KeyType::BrainpoolP256r1;
|
||||||
|
case 3: return KeyType::BrainpoolP384r1;
|
||||||
|
default: return KeyType::Unspecified;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
void put(ByteBuffer& out, std::uint8_t type, const ByteBuffer& payload) {
|
||||||
|
out.push_back(type);
|
||||||
|
out.push_back(static_cast<std::uint8_t>(payload.size() >> 8));
|
||||||
|
out.push_back(static_cast<std::uint8_t>(payload.size()));
|
||||||
|
out.insert(out.end(), payload.begin(), payload.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteBuffer key_record(const PrivateKey& key) {
|
||||||
|
ByteBuffer out {curve_code(key.type)};
|
||||||
|
out.insert(out.end(), key.key.begin(), key.key.end());
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
ByteBuffer key_record(KeyId key) {
|
||||||
|
return {static_cast<std::uint8_t>(key.value >> 24), static_cast<std::uint8_t>(key.value >> 16),
|
||||||
|
static_cast<std::uint8_t>(key.value >> 8), static_cast<std::uint8_t>(key.value)};
|
||||||
|
}
|
||||||
|
|
||||||
|
bool read_key(const ByteBuffer& payload, PrivateKey& key) {
|
||||||
|
const KeyType curve = curve_type(payload[0]);
|
||||||
|
if (curve == KeyType::Unspecified || payload.size() - 1 != vanetza::security::key_length(curve)) return false;
|
||||||
|
key.type = curve;
|
||||||
|
key.key.assign(payload.begin() + 1, payload.end());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool read_key(const ByteBuffer& payload, KeyId& key) {
|
||||||
|
if (payload.size() != 4) return false;
|
||||||
|
key.value = std::uint32_t(payload[0]) << 24 | std::uint32_t(payload[1]) << 16 | std::uint32_t(payload[2]) << 8 | payload[3];
|
||||||
|
return bool(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Both formats: magic, then roots, authorities and tickets, each ticket certificate followed by its key record.
|
||||||
|
template <class Set>
|
||||||
|
ByteBuffer encode_set(const Set& set, const std::uint8_t (&magic)[4], std::uint8_t key_type) {
|
||||||
|
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||||
|
for (const auto& coer : set.roots) put(out, Record::root, coer);
|
||||||
|
for (const auto& coer : set.authorities) put(out, Record::authority, coer);
|
||||||
|
for (const auto& t : set.tickets) {
|
||||||
|
put(out, Record::ticket, t.certificate);
|
||||||
|
put(out, key_type, key_record(t.key));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class Set>
|
||||||
|
bool decode_set(const ByteBuffer& bundle, const std::uint8_t (&magic)[4], std::uint8_t key_type, Set& out) {
|
||||||
|
if (bundle.size() < sizeof(magic) || !std::equal(std::begin(magic), std::end(magic), bundle.begin())) return false;
|
||||||
|
Set parsed;
|
||||||
|
bool key_pending = false; // a ticket certificate awaits its key record
|
||||||
|
std::size_t at = sizeof(magic);
|
||||||
|
while (at < bundle.size()) {
|
||||||
|
if (bundle.size() - at < 3) return false;
|
||||||
|
const std::uint8_t type = bundle[at];
|
||||||
|
const std::size_t length = (static_cast<std::size_t>(bundle[at + 1]) << 8) | bundle[at + 2];
|
||||||
|
at += 3;
|
||||||
|
if (bundle.size() - at < length || length == 0) return false;
|
||||||
|
ByteBuffer payload(bundle.begin() + at, bundle.begin() + at + length);
|
||||||
|
at += length;
|
||||||
|
if (key_pending != (type == key_type)) return false;
|
||||||
|
if (type == Record::root) {
|
||||||
|
parsed.roots.push_back(std::move(payload));
|
||||||
|
} else if (type == Record::authority) {
|
||||||
|
parsed.authorities.push_back(std::move(payload));
|
||||||
|
} else if (type == Record::ticket) {
|
||||||
|
parsed.tickets.push_back({std::move(payload), {}});
|
||||||
|
key_pending = true;
|
||||||
|
} else if (type == key_type) {
|
||||||
|
if (!read_key(payload, parsed.tickets.back().key)) return false;
|
||||||
|
key_pending = false;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (key_pending) return false;
|
||||||
|
out = std::move(parsed);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
ByteBuffer encode(const Credentials& credentials) { return encode_set(credentials, bundle_magic, Record::ticket_key); }
|
||||||
|
ByteBuffer encode(const StoredCredentials& credentials) {
|
||||||
|
return encode_set(credentials, stored_magic, Record::ticket_key_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool decode(const ByteBuffer& bundle, Credentials& out) {
|
||||||
|
return decode_set(bundle, bundle_magic, Record::ticket_key, out);
|
||||||
|
}
|
||||||
|
bool decode(const ByteBuffer& bundle, StoredCredentials& out) {
|
||||||
|
return decode_set(bundle, stored_magic, Record::ticket_key_id, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<StoredCredentials> import_keys(const Credentials& credentials, SecurityModule& module) {
|
||||||
|
StoredCredentials stored {credentials.roots, credentials.authorities, {}};
|
||||||
|
const auto undo = [&]() -> std::optional<StoredCredentials> {
|
||||||
|
for (const auto& t : stored.tickets) module.destroy_key(t.key);
|
||||||
|
return std::nullopt;
|
||||||
|
};
|
||||||
|
for (const auto& t : credentials.tickets) {
|
||||||
|
vanetza::security::v3::Certificate certificate;
|
||||||
|
if (!certificate.decode(t.certificate)) return undo();
|
||||||
|
const auto verification_key = vanetza::security::v3::get_public_key(*certificate.content());
|
||||||
|
if (!verification_key) return undo();
|
||||||
|
const auto key = module.import_key(KeyPair {t.key, *verification_key});
|
||||||
|
if (!key) return undo();
|
||||||
|
stored.tickets.push_back({t.certificate, *key});
|
||||||
|
}
|
||||||
|
return stored;
|
||||||
|
}
|
||||||
|
|
||||||
|
ApplyReport apply(const StoredCredentials& credentials, TrustConfiguration& trust, CertificatePool& pool) {
|
||||||
|
ApplyReport report;
|
||||||
|
for (const auto& coer : credentials.roots) {
|
||||||
|
if ((report.result = trust.add_root(coer)) != Result::accepted) return report;
|
||||||
|
++report.roots;
|
||||||
|
}
|
||||||
|
for (const auto& coer : credentials.authorities) {
|
||||||
|
if ((report.result = trust.add_authority(coer)) != Result::accepted) return report;
|
||||||
|
++report.authorities;
|
||||||
|
}
|
||||||
|
for (const auto& t : credentials.tickets) {
|
||||||
|
if ((report.result = pool.add(t.certificate, t.key)) != Result::accepted) return report;
|
||||||
|
++report.tickets;
|
||||||
|
}
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result FileCredentialStore::save(const StoredCredentials& credentials) {
|
||||||
|
const ByteBuffer bundle = encode(credentials);
|
||||||
|
std::ofstream out(path_, std::ios::binary | std::ios::trunc);
|
||||||
|
out.write(reinterpret_cast<const char*>(bundle.data()), bundle.size());
|
||||||
|
return out ? Result::accepted : Result::rejected;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result FileCredentialStore::load(StoredCredentials& credentials) {
|
||||||
|
std::ifstream in(path_, std::ios::binary);
|
||||||
|
if (!in) return Result::rejected;
|
||||||
|
const ByteBuffer bundle(std::istreambuf_iterator<char>(in), {});
|
||||||
|
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result FileCredentialStore::erase() {
|
||||||
|
return std::remove(path_.c_str()) == 0 ? Result::accepted : Result::rejected;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
#include <vanetza_idf/ecc.hpp>
|
#include <microbu_v2x/ecc.hpp>
|
||||||
#include <boost/multiprecision/cpp_int.hpp>
|
#include <boost/multiprecision/cpp_int.hpp>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <iterator>
|
#include <iterator>
|
||||||
|
|
||||||
namespace vanetza_idf::ecc {
|
namespace microbu_v2x::ecc {
|
||||||
using namespace vanetza::security;
|
using namespace vanetza::security;
|
||||||
namespace {
|
namespace {
|
||||||
// Fixed width, no heap: a 384-bit product needs 768 bits before reduction.
|
// Fixed width, no heap: a 384-bit product needs 768 bits before reduction.
|
||||||
@@ -79,4 +79,4 @@ vanetza::ByteBuffer encode_uncompressed(const Uncompressed& point) {
|
|||||||
out.insert(out.end(), point.y.begin(), point.y.end());
|
out.insert(out.end(), point.y.begin(), point.y.end());
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
} // namespace vanetza_idf::ecc
|
} // namespace microbu_v2x::ecc
|
||||||
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
#include <vanetza_idf/ecies_mbedtls.hpp>
|
#include <microbu_v2x/ecies_mbedtls.hpp>
|
||||||
#include <vanetza_idf/ecc.hpp>
|
#include <microbu_v2x/ecc.hpp>
|
||||||
#include <psa/crypto.h>
|
#include <psa/crypto.h>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
namespace vanetza_idf::pki {
|
namespace microbu_v2x::pki {
|
||||||
using namespace vanetza::security;
|
using namespace vanetza::security;
|
||||||
namespace {
|
namespace {
|
||||||
psa_ecc_family_t family_of(KeyType type) {
|
psa_ecc_family_t family_of(KeyType type) {
|
||||||
@@ -132,4 +132,4 @@ bool EciesMbedTls::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, cons
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} // namespace vanetza_idf::pki
|
} // namespace microbu_v2x::pki
|
||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
#include <vanetza_idf/ecies_openssl.hpp>
|
#include <microbu_v2x/ecies_openssl.hpp>
|
||||||
#include <vanetza_idf/ecc.hpp>
|
#include <microbu_v2x/ecc.hpp>
|
||||||
#include <vanetza/security/openssl_wrapper.hpp>
|
#include <vanetza/security/openssl_wrapper.hpp>
|
||||||
#include <openssl/ec.h>
|
#include <openssl/ec.h>
|
||||||
#include <openssl/ecdh.h>
|
#include <openssl/ecdh.h>
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
|
|
||||||
namespace vanetza_idf::pki {
|
namespace microbu_v2x::pki {
|
||||||
using namespace vanetza::security;
|
using namespace vanetza::security;
|
||||||
namespace {
|
namespace {
|
||||||
int nid_of(KeyType type) {
|
int nid_of(KeyType type) {
|
||||||
@@ -118,4 +118,4 @@ bool EciesOpenSsl::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, cons
|
|||||||
length != static_cast<int>(payload)) { plaintext.clear(); return false; }
|
length != static_cast<int>(payload)) { plaintext.clear(); return false; }
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} // namespace vanetza_idf::pki
|
} // namespace microbu_v2x::pki
|
||||||
+2
-2
@@ -17,11 +17,11 @@
|
|||||||
#include <soc/pcr_reg.h>
|
#include <soc/pcr_reg.h>
|
||||||
#include <soc/soc.h>
|
#include <soc/soc.h>
|
||||||
|
|
||||||
ESP_SYSTEM_INIT_FN(vidf_esp32c5_rom_uart_clock, CORE, BIT(0), 120) {
|
ESP_SYSTEM_INIT_FN(v2x_esp32c5_rom_uart_clock, CORE, BIT(0), 120) {
|
||||||
REG_SET_BIT(PCR_UART0_SCLK_CONF_REG, PCR_UART0_SCLK_EN);
|
REG_SET_BIT(PCR_UART0_SCLK_CONF_REG, PCR_UART0_SCLK_EN);
|
||||||
return ESP_OK;
|
return ESP_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Referenced through "-u" so the linker keeps this object and its init entry.
|
// Referenced through "-u" so the linker keeps this object and its init entry.
|
||||||
void vidf_esp32c5_rom_uart_clock_link(void) {}
|
void v2x_esp32c5_rom_uart_clock_link(void) {}
|
||||||
#endif
|
#endif
|
||||||
+6
-6
@@ -1,8 +1,8 @@
|
|||||||
#include <vanetza_idf/facilities.hpp>
|
#include <microbu_v2x/facilities.hpp>
|
||||||
#include <vanetza/common/its_aid.hpp>
|
#include <vanetza/common/its_aid.hpp>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
namespace vanetza_idf::facilities {
|
namespace microbu_v2x::facilities {
|
||||||
Descriptor descriptor(Kind kind) {
|
Descriptor descriptor(Kind kind) {
|
||||||
// TS 103 248 BTP well-known ports; CDD MessageId values. The service
|
// TS 103 248 BTP well-known ports; CDD MessageId values. The service
|
||||||
// protocolVersion comes from each service ASN.1 definition: CAM/DENM 2,
|
// protocolVersion comes from each service ASN.1 definition: CAM/DENM 2,
|
||||||
@@ -28,13 +28,13 @@ Result validate_pdu(Kind kind, const vanetza::ByteBuffer& data, std::size_t maxi
|
|||||||
if (data.empty() || data.size() > maximum) return Result::invalid_argument;
|
if (data.empty() || data.size() > maximum) return Result::invalid_argument;
|
||||||
try {
|
try {
|
||||||
switch (kind) {
|
switch (kind) {
|
||||||
#if VIDF_CAM
|
#if V2X_CAM
|
||||||
case Kind::cam: return check<Cam>(kind, data);
|
case Kind::cam: return check<Cam>(kind, data);
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_DENM
|
#if V2X_DENM
|
||||||
case Kind::denm: return check<Denm>(kind, data);
|
case Kind::denm: return check<Denm>(kind, data);
|
||||||
#endif
|
#endif
|
||||||
#if VIDF_VAM
|
#if V2X_VAM
|
||||||
case Kind::vam: return check<Vam>(kind, data);
|
case Kind::vam: return check<Vam>(kind, data);
|
||||||
#endif
|
#endif
|
||||||
default: return Result::unsupported;
|
default: return Result::unsupported;
|
||||||
@@ -42,7 +42,7 @@ Result validate_pdu(Kind kind, const vanetza::ByteBuffer& data, std::size_t maxi
|
|||||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||||
catch (const std::exception&) { return Result::invalid_argument; }
|
catch (const std::exception&) { return Result::invalid_argument; }
|
||||||
}
|
}
|
||||||
#if VIDF_NETWORK
|
#if V2X_NETWORK
|
||||||
Result send(Stack& stack, Kind kind, vanetza::ByteBuffer bytes, BtpRequest req) {
|
Result send(Stack& stack, Kind kind, vanetza::ByteBuffer bytes, BtpRequest req) {
|
||||||
auto result = validate_pdu(kind, bytes, stack.config().mib.itsGnMaxSduSize - 4u);
|
auto result = validate_pdu(kind, bytes, stack.config().mib.itsGnMaxSduSize - 4u);
|
||||||
if (result != Result::accepted) return result;
|
if (result != Result::accepted) return result;
|
||||||
+3
-3
@@ -1,13 +1,13 @@
|
|||||||
// TS 102 723-8 V1.1.1 clause 6.3 identifier-change procedures over one pool of
|
// TS 102 723-8 V1.1.1 clause 6.3 identifier-change procedures over one pool of
|
||||||
// authorization tickets. See id_change.hpp and security.hpp for the contracts.
|
// authorization tickets. See id_change.hpp and security.hpp for the contracts.
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace vanetza_idf::security {
|
namespace microbu_v2x::security {
|
||||||
using namespace vanetza;
|
using namespace vanetza;
|
||||||
|
|
||||||
class IdentityManager::Impl : public std::enable_shared_from_this<IdentityManager::Impl> {
|
class IdentityManager::Impl : public std::enable_shared_from_this<IdentityManager::Impl> {
|
||||||
@@ -222,4 +222,4 @@ void IdentityManager::on_committed(std::function<void(const Identifier&)> callba
|
|||||||
const IdentityManager::Statistics& IdentityManager::statistics() const { return impl_->stats; }
|
const IdentityManager::Statistics& IdentityManager::statistics() const { return impl_->stats; }
|
||||||
bool IdentityManager::locked() const { return impl_->locked(); }
|
bool IdentityManager::locked() const { return impl_->locked(); }
|
||||||
|
|
||||||
} // namespace vanetza_idf::security
|
} // namespace microbu_v2x::security
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
#include <vanetza_idf/its_g5_frame.hpp>
|
#include <microbu_v2x/its_g5_frame.hpp>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
namespace vanetza_idf::its_g5 {
|
namespace microbu_v2x::its_g5 {
|
||||||
namespace {
|
namespace {
|
||||||
constexpr std::uint8_t snap[] = {0xaa, 0xaa, 0x03, 0, 0, 0, 0x89, 0x47};
|
constexpr std::uint8_t snap[] = {0xaa, 0xaa, 0x03, 0, 0, 0, 0x89, 0x47};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#include "local_security.hpp"
|
||||||
|
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||||
|
#include <microbu_v2x/security_backend.hpp>
|
||||||
|
#include <nvs.h>
|
||||||
|
|
||||||
|
namespace microbu_v2x {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
/// One NVS blob for the keys of the local software module.
|
||||||
|
class NvsKeyStorage final : public security::KeyStorage {
|
||||||
|
public:
|
||||||
|
bool load(vanetza::ByteBuffer& out) override {
|
||||||
|
nvs_handle_t handle;
|
||||||
|
if (nvs_open(local_key_namespace, NVS_READONLY, &handle) != ESP_OK) return false;
|
||||||
|
std::size_t size = 0;
|
||||||
|
bool ok = nvs_get_blob(handle, local_key_name, nullptr, &size) == ESP_OK && size > 0;
|
||||||
|
if (ok) {
|
||||||
|
out.resize(size);
|
||||||
|
ok = nvs_get_blob(handle, local_key_name, out.data(), &size) == ESP_OK;
|
||||||
|
}
|
||||||
|
nvs_close(handle);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
bool save(const vanetza::ByteBuffer& blob) override {
|
||||||
|
nvs_handle_t handle;
|
||||||
|
if (nvs_open(local_key_namespace, NVS_READWRITE, &handle) != ESP_OK) return false;
|
||||||
|
const bool ok = nvs_set_blob(handle, local_key_name, blob.data(), blob.size()) == ESP_OK &&
|
||||||
|
nvs_commit(handle) == ESP_OK;
|
||||||
|
nvs_close(handle);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The SE051's role in software on the ESP32-C5: keys in NVS, signatures through PSA.
|
||||||
|
class LocalSecurityModule final : public security::SecurityModule {
|
||||||
|
public:
|
||||||
|
security::KeyId generate_key(security::KeyType type) override { return module_.generate_key(type); }
|
||||||
|
std::optional<security::KeyId> import_key(const security::KeyPair& pair) override { return module_.import_key(pair); }
|
||||||
|
std::optional<security::PublicKey> public_key(security::KeyId id) const override { return module_.public_key(id); }
|
||||||
|
security::Signature sign_digest(security::KeyId id, const vanetza::ByteBuffer& digest) override {
|
||||||
|
return module_.sign_digest(id, digest);
|
||||||
|
}
|
||||||
|
bool destroy_key(security::KeyId id) override { return module_.destroy_key(id); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
BackendMbedTls psa_;
|
||||||
|
NvsKeyStorage storage_;
|
||||||
|
security::SoftwareSecurityModule module_ {psa_, psa_, storage_};
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::unique_ptr<vanetza::security::Backend> make_local_security_backend() { return std::make_unique<BackendMbedTls>(); }
|
||||||
|
|
||||||
|
std::unique_ptr<security::SecurityModule> make_local_security_module() { return std::make_unique<LocalSecurityModule>(); }
|
||||||
|
|
||||||
|
} // namespace microbu_v2x
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <microbu_v2x/security_module.hpp>
|
||||||
|
#include <vanetza/security/backend.hpp>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
// The implementations on the ESP32 itself (local_security.cpp): PSA crypto for the public operations, and the
|
||||||
|
// software security module with its keys in NVS.
|
||||||
|
namespace microbu_v2x {
|
||||||
|
std::unique_ptr<vanetza::security::Backend> make_local_security_backend();
|
||||||
|
std::unique_ptr<security::SecurityModule> make_local_security_module();
|
||||||
|
} // namespace microbu_v2x
|
||||||
+5
-5
@@ -2,11 +2,11 @@
|
|||||||
// TS 103 175 clause 8.3), MF-SAP (TS 102 723-5, TS 103 175 clause 8.4) and
|
// TS 103 175 clause 8.3), MF-SAP (TS 102 723-5, TS 103 175 clause 8.4) and
|
||||||
// MI-SAP (TS 102 723-3, TS 103 175 clause 8.2). Values only ever come from the
|
// MI-SAP (TS 102 723-3, TS 103 175 clause 8.2). Values only ever come from the
|
||||||
// providers the application registers.
|
// providers the application registers.
|
||||||
#include <vanetza_idf/mf_sap.hpp>
|
#include <microbu_v2x/mf_sap.hpp>
|
||||||
#include <vanetza_idf/mi_sap.hpp>
|
#include <microbu_v2x/mi_sap.hpp>
|
||||||
#include <vanetza_idf/mn_sap.hpp>
|
#include <microbu_v2x/mn_sap.hpp>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
namespace {
|
namespace {
|
||||||
// Shared GET/SET machinery: format check, access check, then the provider.
|
// Shared GET/SET machinery: format check, access check, then the provider.
|
||||||
template<class No, class Param, class Error, class Provider>
|
template<class No, class Param, class Error, class Provider>
|
||||||
@@ -134,4 +134,4 @@ MI_SET_confirm MI_SET_request_submit(AccessParameterProvider* provider, const MI
|
|||||||
return confirm;
|
return confirm;
|
||||||
}
|
}
|
||||||
} // namespace MI_SAP
|
} // namespace MI_SAP
|
||||||
} // namespace vanetza_idf
|
} // namespace microbu_v2x
|
||||||
+5
-5
@@ -1,7 +1,7 @@
|
|||||||
#include <vanetza_idf/nvs_credential_store.hpp>
|
#include <microbu_v2x/nvs_credential_store.hpp>
|
||||||
#include <nvs.h>
|
#include <nvs.h>
|
||||||
|
|
||||||
namespace vanetza_idf::security {
|
namespace microbu_v2x::security {
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
// nvs_open/nvs_close around one operation; NVS handles are cheap and the store is stateless
|
// nvs_open/nvs_close around one operation; NVS handles are cheap and the store is stateless
|
||||||
@@ -17,7 +17,7 @@ private:
|
|||||||
};
|
};
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
Result NvsCredentialStore::save(const Credentials& credentials) {
|
Result NvsCredentialStore::save(const StoredCredentials& credentials) {
|
||||||
const ByteBuffer bundle = encode(credentials);
|
const ByteBuffer bundle = encode(credentials);
|
||||||
Handle nvs(namespace_, NVS_READWRITE);
|
Handle nvs(namespace_, NVS_READWRITE);
|
||||||
if (nvs.error() != ESP_OK) return Result::rejected;
|
if (nvs.error() != ESP_OK) return Result::rejected;
|
||||||
@@ -25,7 +25,7 @@ Result NvsCredentialStore::save(const Credentials& credentials) {
|
|||||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||||
}
|
}
|
||||||
|
|
||||||
Result NvsCredentialStore::load(Credentials& credentials) {
|
Result NvsCredentialStore::load(StoredCredentials& credentials) {
|
||||||
Handle nvs(namespace_, NVS_READONLY);
|
Handle nvs(namespace_, NVS_READONLY);
|
||||||
if (nvs.error() != ESP_OK) return Result::rejected; // no such namespace yet: nothing stored
|
if (nvs.error() != ESP_OK) return Result::rejected; // no such namespace yet: nothing stored
|
||||||
std::size_t size = 0;
|
std::size_t size = 0;
|
||||||
@@ -47,4 +47,4 @@ Result NvsCredentialStore::erase() {
|
|||||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace vanetza_idf::security
|
} // namespace microbu_v2x::security
|
||||||
@@ -0,0 +1,996 @@
|
|||||||
|
// TS 102 941 V2.2.1 enrolment/authorization messages on the upstream
|
||||||
|
// EtsiTs103097Data wrapper. See pki.hpp for the clause map.
|
||||||
|
#include <microbu_v2x/pki.hpp>
|
||||||
|
#include <microbu_v2x/ecc.hpp>
|
||||||
|
#include <microbu_v2x/security.hpp>
|
||||||
|
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||||
|
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||||
|
#include <vanetza/asn1/security/CtlCommand.h>
|
||||||
|
#include <vanetza/asn1/security/CtlEntry.h>
|
||||||
|
#include <vanetza/asn1/security/EtsiTs103097Certificate.h>
|
||||||
|
#include <vanetza/asn1/security/InnerAtRequest.h>
|
||||||
|
#include <vanetza/asn1/security/InnerEcRequest.h>
|
||||||
|
#include <vanetza/asn1/security/PublicEncryptionKey.h>
|
||||||
|
#include <vanetza/asn1/security/PublicVerificationKey.h>
|
||||||
|
#include <vanetza/asn1/security/SharedAtRequest.h>
|
||||||
|
#include <vanetza/asn1/security/ValidityPeriod.h>
|
||||||
|
#include <vanetza/security/sha.hpp>
|
||||||
|
#include <vanetza/security/v2/basic_elements.hpp>
|
||||||
|
#include <vanetza/security/v3/asn1_conversions.hpp>
|
||||||
|
#include <vanetza/security/v3/hash.hpp>
|
||||||
|
#include <vanetza/security/v3/secured_message.hpp>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
#include <map>
|
||||||
|
|
||||||
|
namespace microbu_v2x::pki {
|
||||||
|
using namespace vanetza;
|
||||||
|
using namespace vanetza::security;
|
||||||
|
using SecuredData = v3::SecuredMessage; // EtsiTs103097Data wrapper
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr std::size_t aes_key_length = 16;
|
||||||
|
constexpr std::size_t nonce_length = 12;
|
||||||
|
constexpr std::size_t tag_length = 16;
|
||||||
|
|
||||||
|
ByteBuffer octets(const OCTET_STRING_t& s) { return ByteBuffer(s.buf, s.buf + s.size); }
|
||||||
|
|
||||||
|
// EccP256CurvePoint -> PublicKey (x-only points carry no usable y and are refused)
|
||||||
|
std::optional<PublicKey> point_to_key(const Vanetza_Security_EccP256CurvePoint& point, KeyType type) {
|
||||||
|
PublicKey key;
|
||||||
|
key.type = type;
|
||||||
|
switch (point.present) {
|
||||||
|
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||||
|
key.compression = KeyCompression::Y0; key.x = octets(point.choice.compressed_y_0); break;
|
||||||
|
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||||
|
key.compression = KeyCompression::Y1; key.x = octets(point.choice.compressed_y_1); break;
|
||||||
|
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
|
||||||
|
key.compression = KeyCompression::NoCompression;
|
||||||
|
key.x = octets(point.choice.uncompressedP256.x); key.y = octets(point.choice.uncompressedP256.y); break;
|
||||||
|
default: return std::nullopt;
|
||||||
|
}
|
||||||
|
if (key.x.size() != 32) return std::nullopt;
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
|
// uncompressed form for backends that need y (ECDH peer key)
|
||||||
|
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||||
|
if (key.compression == KeyCompression::NoCompression) return key;
|
||||||
|
auto point = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
|
||||||
|
if (!point) return std::nullopt;
|
||||||
|
PublicKey out = key;
|
||||||
|
out.compression = KeyCompression::NoCompression;
|
||||||
|
out.y = point->y;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
PublicKey compressed(const PublicKey& key) {
|
||||||
|
if (key.compression != KeyCompression::NoCompression || key.y.empty()) return key;
|
||||||
|
PublicKey out = key;
|
||||||
|
out.compression = (key.y.back() & 1) ? KeyCompression::Y1 : KeyCompression::Y0;
|
||||||
|
out.y.clear();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill_point(Vanetza_Security_EccP256CurvePoint& point, const PublicKey& key) {
|
||||||
|
point = v3::to_asn1(make_ecc_point(compressed(key)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill_verification_key(Vanetza_Security_PublicVerificationKey& out, const PublicKey& key) {
|
||||||
|
if (key.type == KeyType::BrainpoolP256r1) {
|
||||||
|
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1;
|
||||||
|
fill_point(out.choice.ecdsaBrainpoolP256r1, key);
|
||||||
|
} else {
|
||||||
|
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256;
|
||||||
|
fill_point(out.choice.ecdsaNistP256, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill_encryption_key(Vanetza_Security_PublicEncryptionKey& out, const PublicKey& key) {
|
||||||
|
out.supportedSymmAlg = Vanetza_Security_SymmAlgorithm_aes128Ccm;
|
||||||
|
if (key.type == KeyType::BrainpoolP256r1) {
|
||||||
|
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesBrainpoolP256r1;
|
||||||
|
fill_point(out.publicKey.choice.eciesBrainpoolP256r1, key);
|
||||||
|
} else {
|
||||||
|
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256;
|
||||||
|
fill_point(out.publicKey.choice.eciesNistP256, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void fill_permissions(Vanetza_Security_CertificateSubjectAttributes& attributes, const Permissions& permissions) {
|
||||||
|
if (permissions.empty()) return;
|
||||||
|
attributes.appPermissions = v3::asn1::allocate<Vanetza_Security_SequenceOfPsidSsp>();
|
||||||
|
for (const auto& permission : permissions) {
|
||||||
|
auto* entry = v3::asn1::allocate<Vanetza_Security_PsidSsp>();
|
||||||
|
entry->psid = permission.first;
|
||||||
|
if (!permission.second.empty()) {
|
||||||
|
entry->ssp = v3::asn1::allocate<Vanetza_Security_ServiceSpecificPermissions>();
|
||||||
|
entry->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
|
||||||
|
v3::assign(&entry->ssp->choice.bitmapSsp, permission.second);
|
||||||
|
}
|
||||||
|
ASN_SEQUENCE_ADD(attributes.appPermissions, entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IEEE 1609.2 clause 5.3.1: Hash(Hash(tbsData) || Hash(signer certificate or empty string))
|
||||||
|
ByteBuffer message_digest(Backend& backend, HashAlgorithm hash, const ByteBuffer& tbs, const Certificate* signer) {
|
||||||
|
if (signer) return v3::calculate_message_hash(backend, hash, tbs, *signer);
|
||||||
|
ByteBuffer concat = backend.calculate_hash(hash, tbs);
|
||||||
|
const ByteBuffer empty = backend.calculate_hash(hash, ByteBuffer {});
|
||||||
|
concat.insert(concat.end(), empty.begin(), empty.end());
|
||||||
|
return backend.calculate_hash(hash, concat);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill the common header of a signed structure (TS 102 941: psid 623, generationTime only).
|
||||||
|
void prepare_signed(SecuredData& data, HashAlgorithm hash, Clock::time_point now, const Certificate* signer) {
|
||||||
|
data.set_hash_id(hash);
|
||||||
|
data.set_its_aid(aid::SCR);
|
||||||
|
data.set_generation_time(v2::convert_time64(now));
|
||||||
|
if (signer) {
|
||||||
|
const auto digest = signer->calculate_digest();
|
||||||
|
if (digest) data.set_signer_identifier(*digest); else data.set_signer_identifier_self();
|
||||||
|
} else {
|
||||||
|
data.set_signer_identifier_self();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> finish_signed(Backend& backend, SecuredData& data, HashAlgorithm hash, const Signer& sign,
|
||||||
|
const Certificate* signer) {
|
||||||
|
try {
|
||||||
|
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||||
|
data.set_signature(sign(digest));
|
||||||
|
return data.encode();
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteBuffer psk_id_input(const std::array<std::uint8_t, aes_key_length>& key) {
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_SymmetricEncryptionKey> wrapper(asn_DEF_Vanetza_Security_SymmetricEncryptionKey);
|
||||||
|
wrapper->present = Vanetza_Security_SymmetricEncryptionKey_PR_aes128Ccm;
|
||||||
|
OCTET_STRING_fromBuf(&wrapper->choice.aes128Ccm, reinterpret_cast<const char*>(key.data()), key.size());
|
||||||
|
return wrapper.encode();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<std::uint8_t, 16> left16(const ByteBuffer& in) {
|
||||||
|
std::array<std::uint8_t, 16> out {};
|
||||||
|
std::copy_n(in.begin(), std::min<std::size_t>(16, in.size()), out.begin());
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// InnerEcResponse / InnerAtResponse share the layout: requestHash, responseCode, certificate OPTIONAL
|
||||||
|
template<class Inner>
|
||||||
|
Result read_inner_response(const Inner& inner, const RequestContext& context, std::uint8_t& code,
|
||||||
|
std::optional<Certificate>& certificate) {
|
||||||
|
certificate.reset();
|
||||||
|
if (inner.requestHash.size != 16 || std::memcmp(inner.requestHash.buf, context.request_hash.data(), 16) != 0)
|
||||||
|
return Result::rejected; // the response answers another request
|
||||||
|
code = static_cast<std::uint8_t>(inner.responseCode);
|
||||||
|
if (inner.certificate) {
|
||||||
|
// asn1c forward-declares a distinct struct tag for this member; the object it points to is
|
||||||
|
// decoded with asn_DEF_Vanetza_Security_EtsiTs103097Certificate, i.e. an EtsiTs103097Certificate_t.
|
||||||
|
Certificate cert(*reinterpret_cast<const Vanetza_Security_EtsiTs103097Certificate_t*>(inner.certificate));
|
||||||
|
if (!cert.validate()) return Result::rejected;
|
||||||
|
certificate = std::move(cert);
|
||||||
|
} else if (code == 0) {
|
||||||
|
return Result::rejected; // clause 6.2.3.2.2: a positive response returns a certificate
|
||||||
|
}
|
||||||
|
return Result::accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt, verify the authority signature and hand back the EtsiTs102941Data
|
||||||
|
std::optional<ByteBuffer> open_response(Backend& backend, EciesBackend& ecies, const RequestContext& context,
|
||||||
|
const Certificate& authority, const ByteBuffer& encoded) {
|
||||||
|
auto signed_bytes = decrypt_with_psk(ecies, context.aes_key, encoded);
|
||||||
|
if (!signed_bytes) return std::nullopt;
|
||||||
|
return verify_signed(backend, *signed_bytes, nullptr, &authority, aid::SCR);
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
ByteBuffer kdf2_sha256(Backend& backend, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length) {
|
||||||
|
ByteBuffer derived;
|
||||||
|
for (std::uint32_t counter = 1; derived.size() < length; ++counter) {
|
||||||
|
ByteBuffer input = shared_secret;
|
||||||
|
input.push_back(static_cast<std::uint8_t>(counter >> 24));
|
||||||
|
input.push_back(static_cast<std::uint8_t>(counter >> 16));
|
||||||
|
input.push_back(static_cast<std::uint8_t>(counter >> 8));
|
||||||
|
input.push_back(static_cast<std::uint8_t>(counter));
|
||||||
|
input.insert(input.end(), kdp.begin(), kdp.end());
|
||||||
|
const auto block = backend.calculate_hash(HashAlgorithm::SHA256, input);
|
||||||
|
derived.insert(derived.end(), block.begin(), block.end());
|
||||||
|
}
|
||||||
|
derived.resize(length);
|
||||||
|
return derived;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<EncryptedKey> ecies_encrypt_key(Backend& backend, EciesBackend& ecies, const PublicKey& recipient,
|
||||||
|
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key) {
|
||||||
|
const auto peer = uncompressed(recipient);
|
||||||
|
if (!peer || (peer->type != KeyType::NistP256 && peer->type != KeyType::BrainpoolP256r1)) return std::nullopt;
|
||||||
|
try {
|
||||||
|
const KeyPair ephemeral = ecies.generate_key(peer->type);
|
||||||
|
const auto secret = ecies.ecdh_x(ephemeral.priv, *peer);
|
||||||
|
if (!secret) return std::nullopt;
|
||||||
|
// K1 (16 octets, key encryption) || K2 (32 octets, MAC key)
|
||||||
|
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||||
|
EncryptedKey out;
|
||||||
|
out.v = ephemeral.pub;
|
||||||
|
ByteBuffer c(aes_key_length);
|
||||||
|
for (std::size_t i = 0; i < aes_key_length; ++i) c[i] = k[i] ^ aes_key[i];
|
||||||
|
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||||
|
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||||
|
if (tag.size() < tag_length) return std::nullopt;
|
||||||
|
out.c = left16(c);
|
||||||
|
out.t = left16(tag);
|
||||||
|
return out;
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(Backend& backend, EciesBackend& ecies,
|
||||||
|
const PrivateKey& recipient, const ByteBuffer& p1,
|
||||||
|
const EncryptedKey& encrypted) {
|
||||||
|
const auto peer = uncompressed(encrypted.v);
|
||||||
|
if (!peer) return std::nullopt;
|
||||||
|
try {
|
||||||
|
const auto secret = ecies.ecdh_x(recipient, *peer);
|
||||||
|
if (!secret) return std::nullopt;
|
||||||
|
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||||
|
const ByteBuffer c(encrypted.c.begin(), encrypted.c.end());
|
||||||
|
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||||
|
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||||
|
if (tag.size() < tag_length) return std::nullopt;
|
||||||
|
// constant-time comparison of the truncated tag
|
||||||
|
unsigned diff = 0;
|
||||||
|
for (std::size_t i = 0; i < tag_length; ++i) diff |= tag[i] ^ encrypted.t[i];
|
||||||
|
if (diff != 0) return std::nullopt;
|
||||||
|
std::array<std::uint8_t, 16> key {};
|
||||||
|
for (std::size_t i = 0; i < aes_key_length; ++i) key[i] = k[i] ^ encrypted.c[i];
|
||||||
|
return key;
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- building blocks -------------------------------------------------------
|
||||||
|
|
||||||
|
Signer module_signer(security::SecurityModule& module, security::KeyId key) {
|
||||||
|
return [&module, key](const ByteBuffer& digest) { return module.sign_digest(key, digest); };
|
||||||
|
}
|
||||||
|
|
||||||
|
Signer key_signer(Backend& backend, PrivateKey key) {
|
||||||
|
return [&backend, key = std::move(key)](const ByteBuffer& digest) { return backend.sign_digest(key, digest); };
|
||||||
|
}
|
||||||
|
|
||||||
|
SigningKey signing_key(Backend& backend, const KeyPair& pair) { return {pair.pub, key_signer(backend, pair.priv)}; }
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> sign_data(Backend& backend, Clock::time_point now, HashAlgorithm hash, const ByteBuffer& payload,
|
||||||
|
const Signer& sign, const Certificate* signer) {
|
||||||
|
SecuredData data = SecuredData::with_signed_data();
|
||||||
|
prepare_signed(data, hash, now, signer);
|
||||||
|
data.set_payload(payload);
|
||||||
|
return finish_signed(backend, data, hash, sign, signer);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> sign_external(Backend& backend, Clock::time_point now, const ByteBuffer& external_payload,
|
||||||
|
const Signer& sign, const Certificate& signer) {
|
||||||
|
SecuredData data = SecuredData::with_signed_data_hash();
|
||||||
|
prepare_signed(data, HashAlgorithm::SHA256, now, &signer);
|
||||||
|
data.set_external_payload_hash(calculate_sha256_digest(external_payload.data(), external_payload.size()));
|
||||||
|
return finish_signed(backend, data, HashAlgorithm::SHA256, sign, &signer);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> encrypt_for(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||||
|
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key) {
|
||||||
|
const auto encryption_key = v3::get_public_encryption_key(*recipient.content());
|
||||||
|
const auto recipient_id = recipient.calculate_digest();
|
||||||
|
if (!encryption_key || !recipient_id) return std::nullopt;
|
||||||
|
try {
|
||||||
|
const ByteBuffer random = ecies.random(aes_key_length + nonce_length);
|
||||||
|
std::array<std::uint8_t, nonce_length> nonce {};
|
||||||
|
std::copy_n(random.begin(), aes_key_length, aes_key.begin());
|
||||||
|
std::copy_n(random.begin() + aes_key_length, nonce_length, nonce.begin());
|
||||||
|
ByteBuffer ciphertext;
|
||||||
|
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||||
|
// P1 = SHA-256 of the recipient certificate (IEEE 1609.2 clause 5.3.5, certRecipInfo)
|
||||||
|
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||||
|
const auto wrapped = ecies_encrypt_key(backend, ecies, *encryption_key, p1, aes_key);
|
||||||
|
if (!wrapped) return std::nullopt;
|
||||||
|
SecuredData data = SecuredData::with_encrypted_data();
|
||||||
|
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||||
|
data.set_cert_recip_info(*recipient_id, wrapped->c, wrapped->t, compressed(wrapped->v));
|
||||||
|
return data.encode();
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||||
|
const ByteBuffer& plaintext) {
|
||||||
|
try {
|
||||||
|
const ByteBuffer random = ecies.random(nonce_length);
|
||||||
|
std::array<std::uint8_t, nonce_length> nonce {};
|
||||||
|
std::copy_n(random.begin(), nonce_length, nonce.begin());
|
||||||
|
ByteBuffer ciphertext;
|
||||||
|
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||||
|
SecuredData data = SecuredData::with_encrypted_data();
|
||||||
|
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||||
|
// pskRecipInfo = HashedId8 of the COER SymmetricEncryptionKey (IEEE 1609.2 clause 6.3.43)
|
||||||
|
const ByteBuffer key_encoding = psk_id_input(aes_key);
|
||||||
|
const HashedId8 psk_id = create_hashed_id8(calculate_sha256_digest(key_encoding.data(), key_encoding.size()));
|
||||||
|
auto* recipient = v3::asn1::allocate<Vanetza_Security_RecipientInfo>();
|
||||||
|
recipient->present = Vanetza_Security_RecipientInfo_PR_pskRecipInfo;
|
||||||
|
OCTET_STRING_fromBuf(&recipient->choice.pskRecipInfo, reinterpret_cast<const char*>(psk_id.data()), psk_id.size());
|
||||||
|
ASN_SEQUENCE_ADD(&data->content->choice.encryptedData.recipients.list, recipient);
|
||||||
|
return data.encode();
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> decrypt_as_recipient(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||||
|
const PrivateKey& encryption_key, const ByteBuffer& encoded,
|
||||||
|
std::array<std::uint8_t, 16>* aes_key_out) {
|
||||||
|
SecuredData data;
|
||||||
|
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||||
|
const auto own_id = recipient.calculate_digest();
|
||||||
|
if (!own_id) return std::nullopt;
|
||||||
|
const auto& recipients = data->content->choice.encryptedData.recipients.list;
|
||||||
|
for (int i = 0; i < recipients.count; ++i) {
|
||||||
|
const auto* info = recipients.array[i];
|
||||||
|
if (!info || info->present != Vanetza_Security_RecipientInfo_PR_certRecipInfo) continue;
|
||||||
|
const auto& cert_info = info->choice.certRecipInfo;
|
||||||
|
if (cert_info.recipientId.size != 8 || std::memcmp(cert_info.recipientId.buf, own_id->data(), 8) != 0) continue;
|
||||||
|
const Vanetza_Security_EciesP256EncryptedKey* ecies_key = nullptr;
|
||||||
|
KeyType type = KeyType::NistP256;
|
||||||
|
if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesNistP256) {
|
||||||
|
ecies_key = &cert_info.encKey.choice.eciesNistP256;
|
||||||
|
} else if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesBrainpoolP256r1) {
|
||||||
|
ecies_key = &cert_info.encKey.choice.eciesBrainpoolP256r1;
|
||||||
|
type = KeyType::BrainpoolP256r1;
|
||||||
|
} else {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ecies_key->c.size != 16 || ecies_key->t.size != 16) continue;
|
||||||
|
EncryptedKey wrapped;
|
||||||
|
auto v = point_to_key(ecies_key->v, type);
|
||||||
|
if (!v) continue;
|
||||||
|
wrapped.v = *v;
|
||||||
|
std::copy_n(ecies_key->c.buf, 16, wrapped.c.begin());
|
||||||
|
std::copy_n(ecies_key->t.buf, 16, wrapped.t.begin());
|
||||||
|
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||||
|
const auto aes_key = ecies_decrypt_key(backend, ecies, encryption_key, p1, wrapped);
|
||||||
|
if (!aes_key) return std::nullopt;
|
||||||
|
ByteBuffer ciphertext;
|
||||||
|
std::array<std::uint8_t, nonce_length> nonce {};
|
||||||
|
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||||
|
ByteBuffer plaintext;
|
||||||
|
if (!ecies.aes_ccm_decrypt(*aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||||
|
if (aes_key_out) *aes_key_out = *aes_key;
|
||||||
|
return plaintext;
|
||||||
|
}
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||||
|
const ByteBuffer& encoded) {
|
||||||
|
SecuredData data;
|
||||||
|
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||||
|
if (!data.check_psk_match(aes_key)) return std::nullopt; // response is not for this request
|
||||||
|
ByteBuffer ciphertext;
|
||||||
|
std::array<std::uint8_t, nonce_length> nonce {};
|
||||||
|
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||||
|
ByteBuffer plaintext;
|
||||||
|
if (!ecies.aes_ccm_decrypt(aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||||
|
return plaintext;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> verify_signed(Backend& backend, const ByteBuffer& encoded, const PublicKey* self_key,
|
||||||
|
const Certificate* signer, ItsAid expected_psid) {
|
||||||
|
SecuredData data;
|
||||||
|
if (!data.decode(encoded) || data.encode() != encoded || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||||
|
if (data.its_aid() != expected_psid || !data.generation_time()) return std::nullopt;
|
||||||
|
const auto hash = data.hash_id();
|
||||||
|
const auto signature = data.signature();
|
||||||
|
if (hash == HashAlgorithm::Unspecified || !signature) return std::nullopt;
|
||||||
|
const auto* signed_data = data->content->choice.signedData;
|
||||||
|
// TS 102 941 V2.2.1 clause 6.2: management messages use only PSID and generationTime.
|
||||||
|
const auto& header = signed_data->tbsData->headerInfo;
|
||||||
|
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||||
|
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||||
|
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions)
|
||||||
|
return std::nullopt;
|
||||||
|
PublicKey key;
|
||||||
|
if (signer) {
|
||||||
|
const auto digest = signer->calculate_digest();
|
||||||
|
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_digest || !digest ||
|
||||||
|
signed_data->signer.choice.digest.size != 8 ||
|
||||||
|
std::memcmp(signed_data->signer.choice.digest.buf, digest->data(), 8) != 0) return std::nullopt;
|
||||||
|
const auto signer_key = v3::get_public_key(*signer->content());
|
||||||
|
if (!signer_key) return std::nullopt;
|
||||||
|
key = *signer_key;
|
||||||
|
} else {
|
||||||
|
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_self || !self_key) return std::nullopt;
|
||||||
|
key = *self_key;
|
||||||
|
}
|
||||||
|
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||||
|
if (!backend.verify_digest(key, digest, *signature)) return std::nullopt;
|
||||||
|
auto payload = data.payload();
|
||||||
|
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||||
|
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||||
|
return ByteBuffer(view.begin(), view.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- TS 102 941 clause 6.2.3.2 --------------------------------------------------
|
||||||
|
|
||||||
|
bool validate_issued_certificate(Backend& backend, const Certificate& certificate, const Certificate& issuer,
|
||||||
|
const PublicKey& requested_key, Clock::time_point now, const Permissions& expected,
|
||||||
|
bool enrolment) {
|
||||||
|
try {
|
||||||
|
if (certificate->version != 3 || certificate->type != Vanetza_Security_CertificateType_explicit ||
|
||||||
|
certificate->toBeSigned.certIssuePermissions || !certificate->toBeSigned.appPermissions ||
|
||||||
|
!certificate.valid_at_timepoint(now) || !issuer.valid_at_timepoint(now)) return false;
|
||||||
|
const auto id = certificate->toBeSigned.id.present;
|
||||||
|
if ((enrolment && id != Vanetza_Security_CertificateId_PR_name) ||
|
||||||
|
(!enrolment && id != Vanetza_Security_CertificateId_PR_none)) return false;
|
||||||
|
const auto digest = issuer.calculate_digest();
|
||||||
|
const auto referenced = certificate.issuer_digest();
|
||||||
|
if (!digest || !referenced || *digest != *referenced ||
|
||||||
|
!security::verify_certificate_signature(backend, certificate, &issuer) ||
|
||||||
|
!security::chain_permissions_consistent({&certificate, &issuer}) ||
|
||||||
|
!security::region_within(certificate, issuer, true)) return false;
|
||||||
|
const auto subject_time = microbu_v2x::security::validity_bounds(certificate);
|
||||||
|
const auto assurance = certificate.assurance_level();
|
||||||
|
const auto issuer_assurance = issuer.assurance_level();
|
||||||
|
if (assurance) {
|
||||||
|
if (!issuer_assurance) return false;
|
||||||
|
const auto level = (*assurance >> 5) & 7;
|
||||||
|
const auto issuer_level = (*issuer_assurance >> 5) & 7;
|
||||||
|
if (level > issuer_level || (level == issuer_level &&
|
||||||
|
((*assurance >> 2) & 7) > ((*issuer_assurance >> 2) & 7))) return false;
|
||||||
|
}
|
||||||
|
const auto issuer_time = microbu_v2x::security::validity_bounds(issuer);
|
||||||
|
if (subject_time.start_validity < issuer_time.start_validity || subject_time.end_validity > issuer_time.end_validity)
|
||||||
|
return false;
|
||||||
|
if (certificate->toBeSigned.appPermissions->list.count != static_cast<int>(expected.size())) return false;
|
||||||
|
for (const auto& permission : expected) {
|
||||||
|
if (!certificate.valid_for_application(permission.first) ||
|
||||||
|
v3::get_app_permissions(*certificate.content(), permission.first) != permission.second) return false;
|
||||||
|
}
|
||||||
|
const auto public_key = v3::get_public_key(*certificate.content());
|
||||||
|
return public_key && security::same_public_key(*public_key, requested_key);
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Result build_enrolment_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||||
|
const EnrolmentRequestParameters& params, const Certificate& ea, ByteBuffer& encoded,
|
||||||
|
RequestContext& context) {
|
||||||
|
if (params.its_id.empty() || !params.verification_key.sign || !params.outer_signer) return Result::invalid_argument;
|
||||||
|
if (!v3::get_public_encryption_key(*ea.content())) return Result::invalid_argument;
|
||||||
|
// 1. InnerEcRequest (certificateFormat ts103097v131 = 1)
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest> inner(asn_DEF_Vanetza_Security_InnerEcRequest);
|
||||||
|
v3::assign(&inner->itsId, params.its_id);
|
||||||
|
inner->certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||||
|
fill_verification_key(inner->publicKeys.verificationKey, params.verification_key.pub);
|
||||||
|
fill_permissions(inner->requestedSubjectAttributes, params.app_permissions);
|
||||||
|
if (!inner.validate()) return Result::invalid_argument;
|
||||||
|
// 2. InnerEcRequestSignedForPop: self-signed with the new verification key
|
||||||
|
auto pop = sign_data(backend, now, params.hash, inner.encode(), params.verification_key.sign, nullptr);
|
||||||
|
if (!pop) return Result::security_unavailable;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
mgmt->version = Vanetza_Security_Version_v1;
|
||||||
|
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentRequest;
|
||||||
|
void* target = &mgmt->content.choice.enrolmentRequest;
|
||||||
|
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *pop)) return Result::security_unavailable;
|
||||||
|
// 3. Outer EtsiTs103097Data-Signed: self (canonical key) or digest of the current EC
|
||||||
|
auto outer = sign_data(backend, now, params.hash, mgmt.encode(), params.outer_signer, params.current_ec);
|
||||||
|
if (!outer) return Result::security_unavailable;
|
||||||
|
// 4. EtsiTs103097Data-Encrypted for the EA
|
||||||
|
auto encrypted = encrypt_for(backend, ecies, ea, *outer, context.aes_key);
|
||||||
|
if (!encrypted) return Result::security_unavailable;
|
||||||
|
encoded = std::move(*encrypted);
|
||||||
|
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||||
|
return Result::accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result parse_enrolment_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& ea,
|
||||||
|
const ByteBuffer& encoded, EnrolmentResponse& out) {
|
||||||
|
auto mgmt_bytes = open_response(backend, ecies, context, ea, encoded);
|
||||||
|
if (!mgmt_bytes) return Result::rejected;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||||
|
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentResponse) return Result::rejected;
|
||||||
|
return read_inner_response(mgmt->content.choice.enrolmentResponse, context, out.response_code, out.certificate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- TS 102 941 clause 6.2.3.3 --------------------------------------------------
|
||||||
|
|
||||||
|
Result build_authorization_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||||
|
const AuthorizationRequestParameters& params, const Certificate& ea,
|
||||||
|
const Certificate& aa, ByteBuffer& encoded, RequestContext& context) {
|
||||||
|
if (!params.ec || !params.ec_signer || !params.verification_key.sign || params.app_permissions.empty())
|
||||||
|
return Result::invalid_argument;
|
||||||
|
if (params.hash != HashAlgorithm::SHA256) return Result::unsupported; // extDataHash carries sha256HashedData
|
||||||
|
if (!v3::get_public_encryption_key(*aa.content()) || (params.privacy && !v3::get_public_encryption_key(*ea.content())))
|
||||||
|
return Result::invalid_argument;
|
||||||
|
const auto ea_id = ea.calculate_digest();
|
||||||
|
if (!ea_id) return Result::invalid_argument;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
mgmt->version = Vanetza_Security_Version_v1;
|
||||||
|
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_authorizationRequest;
|
||||||
|
auto& inner = mgmt->content.choice.authorizationRequest;
|
||||||
|
// publicKeys: new verification key and optional encryption key
|
||||||
|
fill_verification_key(inner.publicKeys.verificationKey, params.verification_key.pub);
|
||||||
|
if (params.encryption_key) {
|
||||||
|
inner.publicKeys.encryptionKey = v3::asn1::allocate<Vanetza_Security_PublicEncryptionKey>();
|
||||||
|
fill_encryption_key(*inner.publicKeys.encryptionKey, *params.encryption_key);
|
||||||
|
}
|
||||||
|
// hmacKey: 32 random octets; keyTag = leftmost 16 octets of HMAC-SHA256(hmacKey, OER(publicKeys))
|
||||||
|
ByteBuffer hmac_key;
|
||||||
|
try { hmac_key = ecies.random(32); } catch (const std::exception&) { return Result::security_unavailable; }
|
||||||
|
if (hmac_key.size() != 32) return Result::security_unavailable;
|
||||||
|
v3::assign(&inner.hmacKey, hmac_key);
|
||||||
|
ByteBuffer tag_input = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicVerificationKey, &inner.publicKeys.verificationKey);
|
||||||
|
if (inner.publicKeys.encryptionKey) {
|
||||||
|
const auto enc = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicEncryptionKey, inner.publicKeys.encryptionKey);
|
||||||
|
tag_input.insert(tag_input.end(), enc.begin(), enc.end());
|
||||||
|
}
|
||||||
|
const auto key_tag = ecies.hmac_sha256(hmac_key, tag_input);
|
||||||
|
if (key_tag.size() < 16) return Result::security_unavailable;
|
||||||
|
// SharedAtRequest
|
||||||
|
auto& shared = inner.sharedAtRequest;
|
||||||
|
OCTET_STRING_fromBuf(&shared.eaId, reinterpret_cast<const char*>(ea_id->data()), ea_id->size());
|
||||||
|
OCTET_STRING_fromBuf(&shared.keyTag, reinterpret_cast<const char*>(key_tag.data()), 16);
|
||||||
|
shared.certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||||
|
fill_permissions(shared.requestedSubjectAttributes, params.app_permissions);
|
||||||
|
if (params.validity_period) {
|
||||||
|
shared.requestedSubjectAttributes.validityPeriod = v3::asn1::allocate<Vanetza_Security_ValidityPeriod>();
|
||||||
|
shared.requestedSubjectAttributes.validityPeriod->start = v2::convert_time32(params.validity_period->first);
|
||||||
|
shared.requestedSubjectAttributes.validityPeriod->duration.present = Vanetza_Security_Duration_PR_hours;
|
||||||
|
shared.requestedSubjectAttributes.validityPeriod->duration.choice.hours = params.validity_period->second;
|
||||||
|
}
|
||||||
|
// EC signature over the SharedAtRequest (external payload), signer = digest of the EC
|
||||||
|
const ByteBuffer shared_encoded = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_SharedAtRequest, &shared);
|
||||||
|
auto ec_signed = sign_external(backend, now, shared_encoded, params.ec_signer, *params.ec);
|
||||||
|
if (!ec_signed) return Result::security_unavailable;
|
||||||
|
ByteBuffer ec_signature_bytes;
|
||||||
|
if (params.privacy) {
|
||||||
|
std::array<std::uint8_t, 16> throwaway {};
|
||||||
|
auto encrypted = encrypt_for(backend, ecies, ea, *ec_signed, throwaway);
|
||||||
|
if (!encrypted) return Result::security_unavailable;
|
||||||
|
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_encryptedEcSignature;
|
||||||
|
void* target = &inner.ecSignature.choice.encryptedEcSignature;
|
||||||
|
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *encrypted)) return Result::security_unavailable;
|
||||||
|
} else {
|
||||||
|
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_ecSignature;
|
||||||
|
void* target = &inner.ecSignature.choice.ecSignature;
|
||||||
|
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *ec_signed)) return Result::security_unavailable;
|
||||||
|
}
|
||||||
|
if (!mgmt.validate()) return Result::security_unavailable;
|
||||||
|
ByteBuffer plaintext = mgmt.encode();
|
||||||
|
if (params.include_pop) {
|
||||||
|
auto pop = sign_data(backend, now, params.hash, plaintext, params.verification_key.sign, nullptr);
|
||||||
|
if (!pop) return Result::security_unavailable;
|
||||||
|
plaintext = std::move(*pop);
|
||||||
|
} else {
|
||||||
|
// EtsiTs103097Data unsecured envelope around the EtsiTs102941Data
|
||||||
|
SecuredData envelope;
|
||||||
|
envelope->protocolVersion = 3;
|
||||||
|
envelope->content = v3::asn1::allocate<Vanetza_Security_Ieee1609Dot2Content>();
|
||||||
|
envelope->content->present = Vanetza_Security_Ieee1609Dot2Content_PR_unsecuredData;
|
||||||
|
v3::assign(&envelope->content->choice.unsecuredData, plaintext);
|
||||||
|
plaintext = envelope.encode();
|
||||||
|
}
|
||||||
|
auto encrypted = encrypt_for(backend, ecies, aa, plaintext, context.aes_key);
|
||||||
|
if (!encrypted) return Result::security_unavailable;
|
||||||
|
encoded = std::move(*encrypted);
|
||||||
|
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||||
|
return Result::accepted;
|
||||||
|
}
|
||||||
|
|
||||||
|
Result parse_authorization_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& aa,
|
||||||
|
const ByteBuffer& encoded, AuthorizationResponse& out) {
|
||||||
|
auto mgmt_bytes = open_response(backend, ecies, context, aa, encoded);
|
||||||
|
if (!mgmt_bytes) return Result::rejected;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||||
|
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_authorizationResponse) return Result::rejected;
|
||||||
|
return read_inner_response(mgmt->content.choice.authorizationResponse, context, out.response_code, out.certificate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- TS 102 941 clause 6.3: RCA trust list and revocation list -----------------------
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
void set_url(Vanetza_Security_Url_t& url, const std::string& text) {
|
||||||
|
OCTET_STRING_fromBuf(&url, text.data(), text.size());
|
||||||
|
}
|
||||||
|
std::string get_url(const Vanetza_Security_Url_t& url) {
|
||||||
|
return std::string(reinterpret_cast<const char*>(url.buf), url.size);
|
||||||
|
}
|
||||||
|
void set_hashed_id8(Vanetza_Security_HashedId8_t& target, const HashedId8& id) {
|
||||||
|
OCTET_STRING_fromBuf(&target, reinterpret_cast<const char*>(id.data()), id.size());
|
||||||
|
}
|
||||||
|
std::optional<HashedId8> get_hashed_id8(const Vanetza_Security_HashedId8_t& source) {
|
||||||
|
if (source.size != 8) return std::nullopt;
|
||||||
|
HashedId8 id;
|
||||||
|
std::copy_n(source.buf, 8, id.begin());
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
// the certificate structure of an entry, decoded from COER into the inline member
|
||||||
|
bool put_certificate(Vanetza_Security_EtsiTs103097Certificate_t& target, const ByteBuffer& coer) {
|
||||||
|
void* into = ⌖
|
||||||
|
return vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &into, coer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TS 102 941 clauses 6.3.3 and 6.3.4. CTLs carry the issuer certificate.
|
||||||
|
std::optional<ByteBuffer> sign_list(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||||
|
ItsAid psid, const ByteBuffer& mgmt) {
|
||||||
|
if (!rca.valid_for_application(psid)) return std::nullopt; // TS 103 097 clause 7.2.3: CRL/CTL appPermissions
|
||||||
|
SecuredData data = SecuredData::with_signed_data();
|
||||||
|
const auto hash = rca->issuer.present == Vanetza_Security_IssuerIdentifier_PR_self &&
|
||||||
|
rca->issuer.choice.self == Vanetza_Security_HashAlgorithm_sha384 ? HashAlgorithm::SHA384 : HashAlgorithm::SHA256;
|
||||||
|
data.set_hash_id(hash);
|
||||||
|
data.set_its_aid(psid);
|
||||||
|
data.set_generation_time(v2::convert_time64(now));
|
||||||
|
if (psid == aid::CRL) {
|
||||||
|
const auto id = rca.calculate_digest();
|
||||||
|
if (!id) return std::nullopt;
|
||||||
|
data.set_signer_identifier(*id);
|
||||||
|
} else data.set_signer_identifier(rca);
|
||||||
|
data.set_payload(mgmt);
|
||||||
|
return finish_signed(backend, data, hash, key_signer(backend, rca_key), &rca);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the EtsiTs102941Data of a list message that verifies as signed by rca with the given psid
|
||||||
|
std::optional<ByteBuffer> open_list(Backend& backend, const ByteBuffer& message, const Certificate& rca, ItsAid psid) {
|
||||||
|
SecuredData data;
|
||||||
|
if (!data.decode(message) || data.encode() != message || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||||
|
if (data.its_aid() != psid || !data.generation_time() ||
|
||||||
|
(data.hash_id() != HashAlgorithm::SHA256 && data.hash_id() != HashAlgorithm::SHA384)) return std::nullopt;
|
||||||
|
if (!rca.valid_for_application(psid)) return std::nullopt;
|
||||||
|
const auto* signed_data = data->content->choice.signedData;
|
||||||
|
const auto& header = signed_data->tbsData->headerInfo;
|
||||||
|
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||||
|
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||||
|
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions) return std::nullopt;
|
||||||
|
const auto& signer = signed_data->signer;
|
||||||
|
if (signer.present == Vanetza_Security_SignerIdentifier_PR_certificate) {
|
||||||
|
if (signer.choice.certificate.list.count != 1) return std::nullopt;
|
||||||
|
const ByteBuffer inline_cert = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate,
|
||||||
|
signer.choice.certificate.list.array[0]);
|
||||||
|
if (inline_cert != rca.encode()) return std::nullopt;
|
||||||
|
} else if (psid == aid::CRL && signer.present == Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||||
|
const auto id = rca.calculate_digest();
|
||||||
|
if (!id || signer.choice.digest.size != id->size() ||
|
||||||
|
!std::equal(id->begin(), id->end(), signer.choice.digest.buf)) return std::nullopt;
|
||||||
|
} else return std::nullopt;
|
||||||
|
const auto signature = data.signature();
|
||||||
|
const auto key = v3::get_public_key(*rca.content());
|
||||||
|
if (!signature || !key) return std::nullopt;
|
||||||
|
const auto digest = message_digest(backend, data.hash_id(), data.signing_payload(), &rca);
|
||||||
|
try {
|
||||||
|
if (!backend.verify_digest(*key, digest, *signature)) return std::nullopt;
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
auto payload = data.payload();
|
||||||
|
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||||
|
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||||
|
return ByteBuffer(view.begin(), view.end());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> build_rca_ctl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||||
|
const TrustListEntries& entries, Time32 next_update, std::uint8_t ctl_sequence) {
|
||||||
|
if (entries.dc.empty()) return std::nullopt;
|
||||||
|
for (const auto& dc : entries.dc) if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
mgmt->version = Vanetza_Security_Version_v1;
|
||||||
|
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||||
|
auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||||
|
ctl.version = 1; // clause 6.3.4: CtlFormat version 1
|
||||||
|
ctl.nextUpdate = next_update;
|
||||||
|
ctl.isFullCtl = 1;
|
||||||
|
ctl.ctlSequence = ctl_sequence;
|
||||||
|
const auto add = [&](Vanetza_Security_CtlEntry_PR kind) -> Vanetza_Security_CtlEntry_t& {
|
||||||
|
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||||
|
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||||
|
command->choice.add.present = kind;
|
||||||
|
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||||
|
return command->choice.add;
|
||||||
|
};
|
||||||
|
for (const auto& ea : entries.ea) {
|
||||||
|
auto& entry = add(Vanetza_Security_CtlEntry_PR_ea).choice.ea;
|
||||||
|
if (!put_certificate(entry.eaCertificate, ea.certificate)) return std::nullopt;
|
||||||
|
set_url(entry.aaAccessPoint, ea.access_point);
|
||||||
|
if (!ea.its_access_point.empty()) {
|
||||||
|
entry.itsAccessPoint = vanetza::asn1::allocate<Vanetza_Security_Url_t>();
|
||||||
|
set_url(*entry.itsAccessPoint, ea.its_access_point);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const auto& aa : entries.aa) {
|
||||||
|
auto& entry = add(Vanetza_Security_CtlEntry_PR_aa).choice.aa;
|
||||||
|
if (!put_certificate(entry.aaCertificate, aa.certificate)) return std::nullopt;
|
||||||
|
set_url(entry.accessPoint, aa.access_point);
|
||||||
|
}
|
||||||
|
for (const auto& dc : entries.dc) {
|
||||||
|
auto& entry = add(Vanetza_Security_CtlEntry_PR_dc).choice.dc;
|
||||||
|
set_url(entry.url, dc.url);
|
||||||
|
for (const auto& id : dc.certificates) {
|
||||||
|
auto* item = vanetza::asn1::allocate<Vanetza_Security_HashedId8_t>();
|
||||||
|
set_hashed_id8(*item, id);
|
||||||
|
ASN_SEQUENCE_ADD(&entry.cert, item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!mgmt.validate()) return std::nullopt;
|
||||||
|
return sign_list(backend, now, rca, rca_key, aid::CTL, mgmt.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<RcaTrustListUpdate> build_rca_ctl_update(Backend& backend, Clock::time_point now,
|
||||||
|
const Certificate& rca, const PrivateKey& key, const ByteBuffer& previous_full,
|
||||||
|
const TrustListEntries& entries, Time32 next_update) {
|
||||||
|
const auto previous = parse_rca_ctl(backend, previous_full, rca);
|
||||||
|
if (!previous || !previous->full || next_update <= v2::convert_time32(now)) return std::nullopt;
|
||||||
|
const auto sequence = static_cast<std::uint8_t>(previous->sequence + 1);
|
||||||
|
const auto full = build_rca_ctl(backend, now, rca, key, entries, next_update, sequence);
|
||||||
|
if (!full || !parse_rca_ctl(backend, *full, rca)) return std::nullopt;
|
||||||
|
const auto old_payload = open_list(backend, previous_full, rca, aid::CTL);
|
||||||
|
const auto new_payload = open_list(backend, *full, rca, aid::CTL);
|
||||||
|
if (!old_payload || !new_payload) return std::nullopt;
|
||||||
|
using Management = vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data>;
|
||||||
|
Management old_list(asn_DEF_Vanetza_Security_EtsiTs102941Data), new_list(asn_DEF_Vanetza_Security_EtsiTs102941Data),
|
||||||
|
delta(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!old_list.decode(*old_payload) || !new_list.decode(*new_payload)) return std::nullopt;
|
||||||
|
delta->version = Vanetza_Security_Version_v1;
|
||||||
|
delta->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||||
|
auto& out = delta->content.choice.certificateTrustListRca;
|
||||||
|
out.version = 1; out.nextUpdate = next_update; out.isFullCtl = 0; out.ctlSequence = sequence;
|
||||||
|
// A certificate entry is identified by HashedId8. A DC entry is identified by URL.
|
||||||
|
auto entry_key = [](const Vanetza_Security_CtlEntry_t& entry) -> ByteBuffer {
|
||||||
|
Certificate certificate;
|
||||||
|
switch (entry.present) {
|
||||||
|
case Vanetza_Security_CtlEntry_PR_ea: certificate = Certificate(entry.choice.ea.eaCertificate); break;
|
||||||
|
case Vanetza_Security_CtlEntry_PR_aa: certificate = Certificate(entry.choice.aa.aaCertificate); break;
|
||||||
|
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||||
|
const auto url = get_url(entry.choice.dc.url);
|
||||||
|
ByteBuffer result {1}; result.insert(result.end(), url.begin(), url.end()); return result;
|
||||||
|
}
|
||||||
|
default: return {};
|
||||||
|
}
|
||||||
|
const auto id = certificate.calculate_digest();
|
||||||
|
if (!id) return {};
|
||||||
|
ByteBuffer result {0}; result.insert(result.end(), id->begin(), id->end()); return result;
|
||||||
|
};
|
||||||
|
using Commands = std::map<ByteBuffer, const Vanetza_Security_CtlCommand_t*>;
|
||||||
|
Commands old_entries, new_entries;
|
||||||
|
auto collect = [&](const Vanetza_Security_CtlFormat_t& list, Commands& result) {
|
||||||
|
for (int i = 0; i < list.ctlCommands.list.count; ++i) {
|
||||||
|
const auto* command = list.ctlCommands.list.array[i];
|
||||||
|
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return false;
|
||||||
|
const auto id = entry_key(command->choice.add);
|
||||||
|
if (id.empty() || !result.emplace(id, command).second) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
if (!collect(old_list->content.choice.certificateTrustListRca, old_entries) ||
|
||||||
|
!collect(new_list->content.choice.certificateTrustListRca, new_entries)) return std::nullopt;
|
||||||
|
for (const auto& item : new_entries) {
|
||||||
|
const auto found = old_entries.find(item.first);
|
||||||
|
if (found != old_entries.end() && vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &found->second->choice.add) ==
|
||||||
|
vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &item.second->choice.add)) continue;
|
||||||
|
auto* command = static_cast<Vanetza_Security_CtlCommand_t*>(vanetza::asn1::copy(asn_DEF_Vanetza_Security_CtlCommand, item.second));
|
||||||
|
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||||
|
}
|
||||||
|
for (const auto& item : old_entries) {
|
||||||
|
if (new_entries.count(item.first)) continue;
|
||||||
|
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||||
|
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||||
|
command->present = Vanetza_Security_CtlCommand_PR_delete;
|
||||||
|
auto& removed = command->choice.Delete;
|
||||||
|
if (item.first[0] == 0) {
|
||||||
|
removed.present = Vanetza_Security_CtlDelete_PR_cert;
|
||||||
|
HashedId8 id; std::copy(item.first.begin() + 1, item.first.end(), id.begin());
|
||||||
|
set_hashed_id8(removed.choice.cert, id);
|
||||||
|
} else {
|
||||||
|
removed.present = Vanetza_Security_CtlDelete_PR_dc;
|
||||||
|
set_url(removed.choice.dc, std::string(item.first.begin() + 1, item.first.end()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!delta.validate()) return std::nullopt;
|
||||||
|
const auto signed_delta = sign_list(backend, now, rca, key, aid::CTL, delta.encode());
|
||||||
|
if (!signed_delta || !parse_rca_ctl(backend, *signed_delta, rca)) return std::nullopt;
|
||||||
|
return RcaTrustListUpdate {*full, *signed_delta, sequence};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> build_crl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||||
|
const std::vector<HashedId8>& revoked, Time32 this_update, Time32 next_update) {
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
mgmt->version = Vanetza_Security_Version_v1;
|
||||||
|
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList;
|
||||||
|
auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||||
|
crl.version = 1;
|
||||||
|
crl.thisUpdate = this_update;
|
||||||
|
crl.nextUpdate = next_update;
|
||||||
|
for (const auto& id : revoked) {
|
||||||
|
auto* entry = vanetza::asn1::allocate<Vanetza_Security_CrlEntry_t>();
|
||||||
|
set_hashed_id8(*entry, id);
|
||||||
|
ASN_SEQUENCE_ADD(&crl.entries, entry);
|
||||||
|
}
|
||||||
|
if (!mgmt.validate()) return std::nullopt;
|
||||||
|
return sign_list(backend, now, rca, rca_key, aid::CRL, mgmt.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<RcaTrustList> parse_rca_ctl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||||
|
if (v3::get_app_permissions(*rca.content(), aid::CTL) != ByteBuffer({1, 0x38})) return std::nullopt;
|
||||||
|
const auto mgmt_bytes = open_list(backend, message, rca, aid::CTL);
|
||||||
|
if (!mgmt_bytes) return std::nullopt;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||||
|
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca) return std::nullopt;
|
||||||
|
const auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||||
|
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||||
|
RcaTrustList list;
|
||||||
|
list.sequence = static_cast<std::uint8_t>(ctl.ctlSequence);
|
||||||
|
list.next_update = static_cast<Time32>(ctl.nextUpdate);
|
||||||
|
list.full = ctl.isFullCtl != 0;
|
||||||
|
const auto rca_digest = rca.calculate_digest();
|
||||||
|
if (!rca_digest) return std::nullopt;
|
||||||
|
const auto issued_by_rca = [&](const Vanetza_Security_EtsiTs103097Certificate_t& raw, Certificate& out) {
|
||||||
|
out = Certificate(raw);
|
||||||
|
const auto issuer = out.issuer_digest();
|
||||||
|
return issuer && *issuer == *rca_digest && out.is_ca_certificate() &&
|
||||||
|
microbu_v2x::security::verify_certificate_signature(backend, out, &rca);
|
||||||
|
};
|
||||||
|
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||||
|
const auto* command = ctl.ctlCommands.list.array[i];
|
||||||
|
if (!command) return std::nullopt;
|
||||||
|
if (command->present == Vanetza_Security_CtlCommand_PR_add) {
|
||||||
|
const auto& entry = command->choice.add;
|
||||||
|
Certificate certificate;
|
||||||
|
switch (entry.present) {
|
||||||
|
case Vanetza_Security_CtlEntry_PR_ea:
|
||||||
|
if (!issued_by_rca(entry.choice.ea.eaCertificate, certificate)) return std::nullopt;
|
||||||
|
list.ea.push_back(std::move(certificate));
|
||||||
|
break;
|
||||||
|
case Vanetza_Security_CtlEntry_PR_aa:
|
||||||
|
if (!issued_by_rca(entry.choice.aa.aaCertificate, certificate)) return std::nullopt;
|
||||||
|
list.aa.push_back(std::move(certificate));
|
||||||
|
break;
|
||||||
|
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||||
|
TrustListEntries::DistributionCentre dc;
|
||||||
|
dc.url = get_url(entry.choice.dc.url);
|
||||||
|
for (int k = 0; k < entry.choice.dc.cert.list.count; ++k) {
|
||||||
|
const auto id = entry.choice.dc.cert.list.array[k] ? get_hashed_id8(*entry.choice.dc.cert.list.array[k]) : std::nullopt;
|
||||||
|
if (!id) return std::nullopt;
|
||||||
|
dc.certificates.push_back(*id);
|
||||||
|
}
|
||||||
|
if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||||
|
list.dc.push_back(std::move(dc));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return std::nullopt; // clause 6.3.2: an RCA CTL carries no RCA or TLM entries
|
||||||
|
}
|
||||||
|
} else if (command->present == Vanetza_Security_CtlCommand_PR_delete) {
|
||||||
|
if (list.full) return std::nullopt; // clause 6.3.4: a FullCtl has add commands only
|
||||||
|
const auto& del = command->choice.Delete;
|
||||||
|
if (del.present == Vanetza_Security_CtlDelete_PR_cert) {
|
||||||
|
const auto id = get_hashed_id8(del.choice.cert);
|
||||||
|
if (!id) return std::nullopt;
|
||||||
|
list.deleted.push_back(*id);
|
||||||
|
} else if (del.present == Vanetza_Security_CtlDelete_PR_dc) {
|
||||||
|
list.deleted_dc.push_back(get_url(del.choice.dc));
|
||||||
|
} else {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (list.full && list.dc.empty()) return std::nullopt;
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<ByteBuffer> build_tlm_ctl(Backend& backend, Clock::time_point now,
|
||||||
|
const Certificate& tlm, const PrivateKey& key, const std::vector<Certificate>& roots,
|
||||||
|
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence) {
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
mgmt->version = Vanetza_Security_Version_v1;
|
||||||
|
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm;
|
||||||
|
auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||||
|
ctl.version = 1; ctl.nextUpdate = next_update; ctl.isFullCtl = 1; ctl.ctlSequence = sequence;
|
||||||
|
for (const auto& cert : roots) {
|
||||||
|
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||||
|
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||||
|
command->choice.add.present = Vanetza_Security_CtlEntry_PR_rca;
|
||||||
|
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||||
|
if (!put_certificate(command->choice.add.choice.rca.selfsignedRootCa, cert.encode())) return std::nullopt;
|
||||||
|
}
|
||||||
|
for (const auto& cert : successors) {
|
||||||
|
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||||
|
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||||
|
command->choice.add.present = Vanetza_Security_CtlEntry_PR_tlm;
|
||||||
|
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||||
|
auto& entry = command->choice.add.choice.tlm;
|
||||||
|
if (!put_certificate(entry.selfSignedTLMCertificate, cert.encode())) return std::nullopt;
|
||||||
|
set_url(entry.accessPoint, "https://cpoc.example.test/L0");
|
||||||
|
}
|
||||||
|
if (!mgmt.validate()) return std::nullopt;
|
||||||
|
return sign_list(backend, now, tlm, key, aid::CTL, mgmt.encode());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<TlmTrustList> parse_tlm_ctl(Backend& backend, const ByteBuffer& message, const Certificate& tlm) {
|
||||||
|
const auto permissions = v3::get_app_permissions(*tlm.content(), aid::CTL);
|
||||||
|
if (permissions.size() != 2 || permissions[0] != 1 || permissions[1] != 0xc8 ||
|
||||||
|
!microbu_v2x::security::verify_certificate_signature(backend, tlm, nullptr)) return std::nullopt;
|
||||||
|
const auto bytes = open_list(backend, message, tlm, aid::CTL);
|
||||||
|
if (!bytes) return std::nullopt;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!mgmt.decode(*bytes) || mgmt.encode() != *bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||||
|
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm) return std::nullopt;
|
||||||
|
const auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||||
|
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||||
|
TlmTrustList result;
|
||||||
|
result.sequence = ctl.ctlSequence; result.next_update = ctl.nextUpdate; result.full = ctl.isFullCtl;
|
||||||
|
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||||
|
const auto* command = ctl.ctlCommands.list.array[i];
|
||||||
|
// This client requests full lists. Never apply a delta without its complete base.
|
||||||
|
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return std::nullopt;
|
||||||
|
const auto& entry = command->choice.add;
|
||||||
|
if (entry.present == Vanetza_Security_CtlEntry_PR_rca) {
|
||||||
|
Certificate cert(entry.choice.rca.selfsignedRootCa);
|
||||||
|
if ((cert->issuer.present != Vanetza_Security_IssuerIdentifier_PR_self || !cert.is_ca_certificate()) || !microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||||
|
result.roots.push_back(std::move(cert));
|
||||||
|
} else if (entry.present == Vanetza_Security_CtlEntry_PR_tlm) {
|
||||||
|
Certificate cert(entry.choice.tlm.selfSignedTLMCertificate);
|
||||||
|
const auto p = v3::get_app_permissions(*cert.content(), aid::CTL);
|
||||||
|
if (p.size() != 2 || p[0] != 1 || p[1] != 0xc8 ||
|
||||||
|
!microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||||
|
result.tlms.push_back(std::move(cert));
|
||||||
|
} else if (entry.present != Vanetza_Security_CtlEntry_PR_dc) return std::nullopt;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<RevocationList> parse_crl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||||
|
if (v3::get_app_permissions(*rca.content(), aid::CRL) != ByteBuffer({1})) return std::nullopt;
|
||||||
|
const auto mgmt_bytes = open_list(backend, message, rca, aid::CRL);
|
||||||
|
if (!mgmt_bytes) return std::nullopt;
|
||||||
|
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||||
|
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||||
|
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList) return std::nullopt;
|
||||||
|
const auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||||
|
if (crl.version != 1) return std::nullopt;
|
||||||
|
RevocationList list;
|
||||||
|
list.this_update = static_cast<Time32>(crl.thisUpdate);
|
||||||
|
list.next_update = static_cast<Time32>(crl.nextUpdate);
|
||||||
|
for (int i = 0; i < crl.entries.list.count; ++i) {
|
||||||
|
const auto id = crl.entries.list.array[i] ? get_hashed_id8(*crl.entries.list.array[i]) : std::nullopt;
|
||||||
|
if (!id) return std::nullopt;
|
||||||
|
list.revoked.push_back(*id);
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t apply(const RcaTrustList& list, microbu_v2x::security::TrustConfiguration& trust) {
|
||||||
|
std::size_t added = 0;
|
||||||
|
for (const auto* entries : {&list.ea, &list.aa}) {
|
||||||
|
for (const auto& certificate : *entries) {
|
||||||
|
if (trust.add_authority(certificate) == Result::accepted) ++added;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t apply(const RevocationList& list, const Certificate& rca, microbu_v2x::security::TrustConfiguration& trust) {
|
||||||
|
const auto issuer = rca.calculate_digest();
|
||||||
|
if (!issuer) return 0;
|
||||||
|
trust.clear_revocations(*issuer);
|
||||||
|
for (const auto& id : list.revoked) trust.revoke(*issuer, id);
|
||||||
|
return list.revoked.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::pki
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
|||||||
|
#include <microbu_v2x/security_backend.hpp>
|
||||||
|
#include "local_security.hpp"
|
||||||
|
#include <sdkconfig.h>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
|
namespace microbu_v2x {
|
||||||
|
namespace {
|
||||||
|
template <class T>
|
||||||
|
std::unique_ptr<T> required(std::unique_ptr<T> made, const char* what) {
|
||||||
|
if (!made) throw std::runtime_error(what);
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::unique_ptr<vanetza::security::Backend> make_security_backend() {
|
||||||
|
#if CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||||
|
return required(make_external_security_backend(), "security adapter returned no backend");
|
||||||
|
#else
|
||||||
|
return make_local_security_backend();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<security::SecurityModule> make_security_module() {
|
||||||
|
#if CONFIG_MICROBU_V2X_CRYPTO_SE051 || CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||||
|
return required(make_external_security_module(), "security adapter returned no security module");
|
||||||
|
#else
|
||||||
|
return make_local_security_module();
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* security_module_name() {
|
||||||
|
#if CONFIG_MICROBU_V2X_CRYPTO_SE051
|
||||||
|
return "se051";
|
||||||
|
#elif CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||||
|
return "v2x-hsm";
|
||||||
|
#else
|
||||||
|
return "esp32-software";
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
} // namespace microbu_v2x
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
#include <microbu_v2x/security_module.hpp>
|
||||||
|
#include <microbu_v2x/ecc.hpp>
|
||||||
|
#include <vanetza/security/v3/hash.hpp>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
|
namespace microbu_v2x::security {
|
||||||
|
using vanetza::security::KeyCompression;
|
||||||
|
using vanetza::security::key_length;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr std::uint8_t magic[4] = {'M', 'S', 'M', '1'};
|
||||||
|
|
||||||
|
void wipe(ByteBuffer& secret) {
|
||||||
|
volatile std::uint8_t* target = secret.data();
|
||||||
|
for (std::size_t n = secret.size(); n--;) *target++ = 0;
|
||||||
|
secret.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint8_t curve_code(KeyType type) {
|
||||||
|
switch (type) {
|
||||||
|
case KeyType::NistP256: return 1;
|
||||||
|
case KeyType::BrainpoolP256r1: return 2;
|
||||||
|
case KeyType::BrainpoolP384r1: return 3;
|
||||||
|
default: return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyType curve_type(std::uint8_t code) {
|
||||||
|
switch (code) {
|
||||||
|
case 1: return KeyType::NistP256;
|
||||||
|
case 2: return KeyType::BrainpoolP256r1;
|
||||||
|
case 3: return KeyType::BrainpoolP384r1;
|
||||||
|
default: return KeyType::Unspecified;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void put_u32(ByteBuffer& out, std::uint32_t value) {
|
||||||
|
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::uint32_t get_u32(const ByteBuffer& in, std::size_t at) {
|
||||||
|
return std::uint32_t(in[at]) << 24 | std::uint32_t(in[at + 1]) << 16 | std::uint32_t(in[at + 2]) << 8 | in[at + 3];
|
||||||
|
}
|
||||||
|
|
||||||
|
bool well_formed(const KeyPair& pair) {
|
||||||
|
const auto type = pair.priv.type;
|
||||||
|
const auto n = key_length(type);
|
||||||
|
return curve_code(type) != 0 && pair.pub.type == type && pair.priv.key.size() == n &&
|
||||||
|
pair.pub.compression == KeyCompression::NoCompression && pair.pub.x.size() == n && pair.pub.y.size() == n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two halves belong together when a signature with the private key verifies with the public key.
|
||||||
|
bool halves_match(vanetza::security::Backend& backend, const KeyPair& pair) {
|
||||||
|
const ByteBuffer probe = backend.calculate_hash(vanetza::security::v3::specified_hash_algorithm(pair.priv.type),
|
||||||
|
pair.pub.x);
|
||||||
|
return backend.verify_digest(pair.pub, probe, backend.sign_digest(pair.priv, probe));
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteBuffer encode_keys(std::uint32_t next, const std::map<KeyId, KeyPair>& keys) {
|
||||||
|
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||||
|
put_u32(out, next);
|
||||||
|
for (const auto& [id, pair] : keys) {
|
||||||
|
put_u32(out, id.value);
|
||||||
|
out.push_back(curve_code(pair.priv.type));
|
||||||
|
for (const auto* part : {&pair.priv.key, &pair.pub.x, &pair.pub.y}) out.insert(out.end(), part->begin(), part->end());
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool decode_keys(const ByteBuffer& in, std::uint32_t& next, std::map<KeyId, KeyPair>& keys) {
|
||||||
|
if (in.size() < 8 || !std::equal(std::begin(magic), std::end(magic), in.begin())) return false;
|
||||||
|
next = get_u32(in, 4);
|
||||||
|
for (std::size_t at = 8; at < in.size();) {
|
||||||
|
if (in.size() - at < 5) return false;
|
||||||
|
const KeyId id {get_u32(in, at)};
|
||||||
|
const KeyType type = curve_type(in[at + 4]);
|
||||||
|
at += 5;
|
||||||
|
const auto n = key_length(type);
|
||||||
|
if (!id || id.value >= next || type == KeyType::Unspecified || in.size() - at < 3 * n || keys.count(id)) return false;
|
||||||
|
KeyPair pair;
|
||||||
|
pair.priv.type = pair.pub.type = type;
|
||||||
|
pair.pub.compression = KeyCompression::NoCompression;
|
||||||
|
pair.priv.key.assign(in.begin() + at, in.begin() + at + n);
|
||||||
|
pair.pub.x.assign(in.begin() + at + n, in.begin() + at + 2 * n);
|
||||||
|
pair.pub.y.assign(in.begin() + at + 2 * n, in.begin() + at + 3 * n);
|
||||||
|
at += 3 * n;
|
||||||
|
keys.emplace(id, std::move(pair));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// x and y of a public key in uncompressed form, none when a compressed point is not on its curve.
|
||||||
|
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||||
|
if (key.compression == KeyCompression::NoCompression) return key;
|
||||||
|
const bool odd = key.compression == KeyCompression::Y1;
|
||||||
|
if (!odd && key.compression != KeyCompression::Y0) return std::nullopt;
|
||||||
|
const auto point = ecc::decompress(key.type, key.x, odd);
|
||||||
|
if (!point) return std::nullopt;
|
||||||
|
PublicKey out;
|
||||||
|
out.type = key.type;
|
||||||
|
out.compression = KeyCompression::NoCompression;
|
||||||
|
out.x = point->x;
|
||||||
|
out.y = point->y;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool same_public_key(const PublicKey& a, const PublicKey& b) {
|
||||||
|
if (a.type != b.type || a.type == KeyType::Unspecified) return false;
|
||||||
|
const auto ua = uncompressed(a), ub = uncompressed(b);
|
||||||
|
return ua && ub && ua->x == ub->x && ua->y == ub->y;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MemoryKeyStorage::load(ByteBuffer& out) {
|
||||||
|
if (blob_.empty()) return false;
|
||||||
|
out = blob_;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool MemoryKeyStorage::save(const ByteBuffer& blob) {
|
||||||
|
wipe(blob_);
|
||||||
|
blob_ = blob;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
SoftwareSecurityModule::SoftwareSecurityModule(vanetza::security::Backend& backend, KeyGenerator& generator,
|
||||||
|
KeyStorage& storage) :
|
||||||
|
backend_(backend), generator_(generator), storage_(storage) {
|
||||||
|
ByteBuffer stored;
|
||||||
|
if (!storage_.load(stored)) return;
|
||||||
|
const bool decoded = decode_keys(stored, next_, keys_);
|
||||||
|
wipe(stored);
|
||||||
|
if (!decoded) throw std::runtime_error("stored security module keys do not decode");
|
||||||
|
}
|
||||||
|
|
||||||
|
SoftwareSecurityModule::~SoftwareSecurityModule() {
|
||||||
|
for (auto& entry : keys_) wipe(entry.second.priv.key);
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyId SoftwareSecurityModule::generate_key(KeyType type) {
|
||||||
|
KeyPair pair = generator_.generate_key(type);
|
||||||
|
if (!well_formed(pair)) throw std::runtime_error("key generation returned no usable key pair");
|
||||||
|
return keep(std::move(pair));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<KeyId> SoftwareSecurityModule::import_key(const KeyPair& pair) {
|
||||||
|
const auto pub = uncompressed(pair.pub);
|
||||||
|
if (!pub) return std::nullopt;
|
||||||
|
KeyPair copy {pair.priv, *pub};
|
||||||
|
try {
|
||||||
|
if (!well_formed(copy) || !halves_match(backend_, copy)) {
|
||||||
|
wipe(copy.priv.key);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
} catch (const std::exception&) {
|
||||||
|
wipe(copy.priv.key);
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return keep(std::move(copy));
|
||||||
|
}
|
||||||
|
|
||||||
|
std::optional<PublicKey> SoftwareSecurityModule::public_key(KeyId id) const {
|
||||||
|
const auto found = keys_.find(id);
|
||||||
|
if (found == keys_.end()) return std::nullopt;
|
||||||
|
return found->second.pub;
|
||||||
|
}
|
||||||
|
|
||||||
|
Signature SoftwareSecurityModule::sign_digest(KeyId id, const ByteBuffer& digest) {
|
||||||
|
const auto found = keys_.find(id);
|
||||||
|
if (found == keys_.end()) throw std::runtime_error("security module holds no such key");
|
||||||
|
return backend_.sign_digest(found->second.priv, digest);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool SoftwareSecurityModule::destroy_key(KeyId id) {
|
||||||
|
const auto found = keys_.find(id);
|
||||||
|
if (found == keys_.end()) return false;
|
||||||
|
wipe(found->second.priv.key);
|
||||||
|
keys_.erase(found);
|
||||||
|
persist();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyId SoftwareSecurityModule::keep(KeyPair pair) {
|
||||||
|
if (next_ == 0) throw std::runtime_error("security module key identifiers exhausted");
|
||||||
|
const KeyId id {next_++};
|
||||||
|
keys_.emplace(id, std::move(pair));
|
||||||
|
try {
|
||||||
|
persist();
|
||||||
|
} catch (...) {
|
||||||
|
wipe(keys_[id].priv.key);
|
||||||
|
keys_.erase(id);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SoftwareSecurityModule::persist() {
|
||||||
|
ByteBuffer blob = encode_keys(next_, keys_);
|
||||||
|
const bool saved = storage_.save(blob);
|
||||||
|
wipe(blob);
|
||||||
|
if (!saved) throw std::runtime_error("security module keys not stored");
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace microbu_v2x::security
|
||||||
+17
-9
@@ -1,6 +1,6 @@
|
|||||||
// Signer identifier and header selection per TS 103 097 V2.2.1 clause 7.1 and
|
// Signer identifier and header selection per TS 103 097 V2.2.1 clause 7.1 and
|
||||||
// TS 103 300-3 V2.3.1 clause 6.5.3. See the class comment in security.hpp.
|
// TS 103 300-3 V2.3.1 clause 6.5.3. See the class comment in security.hpp.
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#include <vanetza/common/position_fix.hpp>
|
#include <vanetza/common/position_fix.hpp>
|
||||||
#include <vanetza/security/peer_request_tracker.hpp>
|
#include <vanetza/security/peer_request_tracker.hpp>
|
||||||
#include <vanetza/security/sign_service.hpp>
|
#include <vanetza/security/sign_service.hpp>
|
||||||
@@ -15,7 +15,7 @@ namespace vanetza::security::v3 {
|
|||||||
asn1::ThreeDLocation build_location(const PositionFix& fix);
|
asn1::ThreeDLocation build_location(const PositionFix& fix);
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace vanetza_idf::security {
|
namespace microbu_v2x::security {
|
||||||
using namespace vanetza;
|
using namespace vanetza;
|
||||||
using namespace vanetza::security;
|
using namespace vanetza::security;
|
||||||
|
|
||||||
@@ -35,6 +35,8 @@ public:
|
|||||||
bool new_cam_signer = false;
|
bool new_cam_signer = false;
|
||||||
// generic profile: per ITS-AID
|
// generic profile: per ITS-AID
|
||||||
std::map<ItsAid, Clock::time_point> generic_last_certificate;
|
std::map<ItsAid, Clock::time_point> generic_last_certificate;
|
||||||
|
// the own certificate the timers above refer to
|
||||||
|
boost::optional<HashedId8> signer_digest;
|
||||||
|
|
||||||
Impl(const Runtime& rt, PositionProvider& pp, CertificatePool& certificates, const TrustConfiguration& t) :
|
Impl(const Runtime& rt, PositionProvider& pp, CertificatePool& certificates, const TrustConfiguration& t) :
|
||||||
runtime(rt), positioning(pp), pool(certificates), trust(t) {}
|
runtime(rt), positioning(pp), pool(certificates), trust(t) {}
|
||||||
@@ -68,12 +70,9 @@ public:
|
|||||||
// signer is the digest ("unless the component signer ... is of choice certificate").
|
// signer is the digest ("unless the component signer ... is of choice certificate").
|
||||||
if (!full_certificate) {
|
if (!full_certificate) {
|
||||||
while (auto requested = incoming_requests.next_one()) {
|
while (auto requested = incoming_requests.next_one()) {
|
||||||
for (const auto& authority : trust.authorities()) {
|
if (const auto* authority = trust.authority(*requested)) {
|
||||||
const auto authority_digest = authority.calculate_digest();
|
message.set_requested_certificate(*authority);
|
||||||
if (authority_digest && truncate(*authority_digest) == *requested) {
|
return;
|
||||||
message.set_requested_certificate(authority);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,6 +125,15 @@ void Ts103097SignHeaderPolicy::prepare_header(const SignRequest& request, v3::Se
|
|||||||
message.set_its_aid(request.its_aid);
|
message.set_its_aid(request.its_aid);
|
||||||
message.set_generation_time(v2::convert_time64(now));
|
message.set_generation_time(v2::convert_time64(now));
|
||||||
const Certificate& at = impl_->pool.own_certificate();
|
const Certificate& at = impl_->pool.own_certificate();
|
||||||
|
// A different own certificate (a newly provisioned ticket, or a ticket switch outside
|
||||||
|
// reset_after_identifier_change) has never been sent in full: restart the inclusion timers so the
|
||||||
|
// first message signed with it carries the certificate. Receivers cannot resolve the digest of a
|
||||||
|
// certificate they have not seen (2026-09-29: 9 digest-signed VAMs after re-provisioning).
|
||||||
|
const auto signer = at.calculate_digest();
|
||||||
|
if (signer != impl_->signer_digest) {
|
||||||
|
reset_after_identifier_change();
|
||||||
|
impl_->signer_digest = signer;
|
||||||
|
}
|
||||||
if (request.self_signed) {
|
if (request.self_signed) {
|
||||||
// TS 102 941 clause 6.2.3.2 inner enrolment structures are self-signed.
|
// TS 102 941 clause 6.2.3.2 inner enrolment structures are self-signed.
|
||||||
message.set_signer_identifier_self();
|
message.set_signer_identifier_self();
|
||||||
@@ -152,4 +160,4 @@ void Ts103097SignHeaderPolicy::reset_after_identifier_change() {
|
|||||||
impl_->vam_last_certificate = boost::none;
|
impl_->vam_last_certificate = boost::none;
|
||||||
impl_->generic_last_certificate.clear();
|
impl_->generic_last_certificate.clear();
|
||||||
}
|
}
|
||||||
} // namespace vanetza_idf::security
|
} // namespace microbu_v2x::security
|
||||||
+22
-11
@@ -1,6 +1,6 @@
|
|||||||
#include <vanetza_idf/stack.hpp>
|
#include <microbu_v2x/stack.hpp>
|
||||||
#if VIDF_SECURITY
|
#if V2X_SECURITY
|
||||||
#include <vanetza_idf/security.hpp>
|
#include <microbu_v2x/security.hpp>
|
||||||
#endif
|
#endif
|
||||||
#include <vanetza/access/access_category.hpp>
|
#include <vanetza/access/access_category.hpp>
|
||||||
#include <vanetza/btp/header.hpp>
|
#include <vanetza/btp/header.hpp>
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
#include <stdexcept>
|
#include <stdexcept>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
namespace vanetza_idf {
|
namespace microbu_v2x {
|
||||||
namespace gn = vanetza::geonet;
|
namespace gn = vanetza::geonet;
|
||||||
using namespace vanetza;
|
using namespace vanetza;
|
||||||
|
|
||||||
@@ -28,6 +28,10 @@ StackConfig::StackConfig() {
|
|||||||
mib.itsGnIfType = gn::InterfaceType::ITS_G5;
|
mib.itsGnIfType = gn::InterfaceType::ITS_G5;
|
||||||
mib.itsGnSnDecapResultHandling = gn::SecurityDecapHandling::Strict;
|
mib.itsGnSnDecapResultHandling = gn::SecurityDecapHandling::Strict;
|
||||||
mib.itsGnSecurity = true;
|
mib.itsGnSecurity = true;
|
||||||
|
// A GBC received again (CBF relies on duplicates, TS 103 836-4-1 V2.2.1 clause 10.3.11.3 step 3 and Annex F.3)
|
||||||
|
// is handled by the forwarding algorithm and never passed up a second time; the upstream default (0) passes
|
||||||
|
// every copy up. Found by TC_GEONW_PON_GBC_AREA_ALL_BO_08.
|
||||||
|
mib.vanetzaGbcMemoryCapacity = 128;
|
||||||
}
|
}
|
||||||
|
|
||||||
class Stack::Impl : public dcc::RequestInterface, public gn::TransportInterface {
|
class Stack::Impl : public dcc::RequestInterface, public gn::TransportInterface {
|
||||||
@@ -38,7 +42,7 @@ public:
|
|||||||
vanetza::security::SecurityEntity* security;
|
vanetza::security::SecurityEntity* security;
|
||||||
security::IdChangeService* id_change;
|
security::IdChangeService* id_change;
|
||||||
gn::Router router;
|
gn::Router router;
|
||||||
// SYS-DCC-003 / GAP-DCC-001: Release-2 DCC_NET. Declared after router: it holds a
|
// TS 103 836-4-2 Release-2 DCC_NET. Declared after router: it holds a
|
||||||
// reference to router's location table, which must already be constructed.
|
// reference to router's location table, which must already be constructed.
|
||||||
gn::DccInformationSharing dcc_information_sharing;
|
gn::DccInformationSharing dcc_information_sharing;
|
||||||
std::optional<dcc::ChannelLoad> global_cbr;
|
std::optional<dcc::ChannelLoad> global_cbr;
|
||||||
@@ -153,7 +157,7 @@ public:
|
|||||||
receive_gn(GnIndication {ind, ByteBuffer(view.begin(), view.end())});
|
receive_gn(GnIndication {ind, ByteBuffer(view.begin(), view.end())});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// IF-NF-002: validate length BEFORE parsing; upstream header parsing
|
// validate length BEFORE parsing; upstream header parsing
|
||||||
// alone does not reject a short BTP PDU. Never read an incomplete port.
|
// alone does not reject a short BTP PDU. Never read an incomplete port.
|
||||||
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
||||||
if (view.size() < 4 || !receive) return;
|
if (view.size() < 4 || !receive) return;
|
||||||
@@ -180,7 +184,7 @@ Stack::Stack(StackConfig config, ManualRuntime& runtime, Access& access,
|
|||||||
config.mib.itsGnIfType != gn::InterfaceType::ITS_G5 ||
|
config.mib.itsGnIfType != gn::InterfaceType::ITS_G5 ||
|
||||||
config.mib.itsGnSnDecapResultHandling != gn::SecurityDecapHandling::Strict)
|
config.mib.itsGnSnDecapResultHandling != gn::SecurityDecapHandling::Strict)
|
||||||
throw std::invalid_argument("Invalid ITS-G5 stack configuration");
|
throw std::invalid_argument("Invalid ITS-G5 stack configuration");
|
||||||
#if VIDF_SECURITY
|
#if V2X_SECURITY
|
||||||
if (!id_change) {
|
if (!id_change) {
|
||||||
if (auto* own = dynamic_cast<security::SecurityEntity*>(security)) id_change = &own->id_change();
|
if (auto* own = dynamic_cast<security::SecurityEntity*>(security)) id_change = &own->id_change();
|
||||||
}
|
}
|
||||||
@@ -192,7 +196,9 @@ const StackConfig& Stack::config() const { return impl_->cfg; }
|
|||||||
security::IdChangeService* Stack::id_change() { return impl_->subscription ? impl_->id_change : nullptr; }
|
security::IdChangeService* Stack::id_change() { return impl_->subscription ? impl_->id_change : nullptr; }
|
||||||
vanetza::security::SecurityEntity* Stack::security_entity() { return impl_->security; }
|
vanetza::security::SecurityEntity* Stack::security_entity() { return impl_->security; }
|
||||||
bool Stack::identity_change_pending() const { return impl_->change_pending; }
|
bool Stack::identity_change_pending() const { return impl_->change_pending; }
|
||||||
const gn::Address& Stack::address() const { return impl_->cfg.mib.itsGnLocalGnAddr; }
|
// The address the router uses now: DAD (clause 10.2.1.5) and identifier changes move it away from the
|
||||||
|
// configured MIB value, and the station must report what it actually transmits.
|
||||||
|
const gn::Address& Stack::address() const { return impl_->router.get_local_position_vector().gn_addr; }
|
||||||
Result Stack::set_address(const gn::Address& address) {
|
Result Stack::set_address(const gn::Address& address) {
|
||||||
if (impl_->cfg.mib.itsGnLocalAddrConfMethod != gn::AddrConfMethod::Managed) return Result::unsupported;
|
if (impl_->cfg.mib.itsGnLocalAddrConfMethod != gn::AddrConfMethod::Managed) return Result::unsupported;
|
||||||
if (impl_->change_pending) return Result::identity_change_pending;
|
if (impl_->change_pending) return Result::identity_change_pending;
|
||||||
@@ -203,6 +209,11 @@ Result Stack::set_address(const gn::Address& address) {
|
|||||||
void Stack::on_receive(Receive receive) { impl_->receive = std::move(receive); }
|
void Stack::on_receive(Receive receive) { impl_->receive = std::move(receive); }
|
||||||
void Stack::on_receive_gn(ReceiveGn receive) { impl_->receive_gn = std::move(receive); }
|
void Stack::on_receive_gn(ReceiveGn receive) { impl_->receive_gn = std::move(receive); }
|
||||||
void Stack::on_access_result(Report report) { impl_->report = std::move(report); }
|
void Stack::on_access_result(Report report) { impl_->report = std::move(report); }
|
||||||
|
void Stack::on_packet_drop(std::function<void(const std::string&)> report) {
|
||||||
|
impl_->router.packet_dropped = [report = std::move(report)](gn::Router::PacketDropReason reason) {
|
||||||
|
if (report) report(gn::stringify(reason));
|
||||||
|
};
|
||||||
|
}
|
||||||
void Stack::report_local_channel_load(dcc::ChannelLoad load) { impl_->dcc_information_sharing.update_local_cbr(load); }
|
void Stack::report_local_channel_load(dcc::ChannelLoad load) { impl_->dcc_information_sharing.update_local_cbr(load); }
|
||||||
void Stack::report_tx_power(unsigned dbm) { impl_->dcc_information_sharing.set_tx_power(dbm); }
|
void Stack::report_tx_power(unsigned dbm) { impl_->dcc_information_sharing.set_tx_power(dbm); }
|
||||||
std::optional<dcc::ChannelLoad> Stack::global_channel_busy_ratio() const { return impl_->global_cbr; }
|
std::optional<dcc::ChannelLoad> Stack::global_channel_busy_ratio() const { return impl_->global_cbr; }
|
||||||
@@ -230,7 +241,7 @@ Result Stack::indicate(AlDataIndication ind) {
|
|||||||
catch (const std::exception&) { return Result::rejected; }
|
catch (const std::exception&) { return Result::rejected; }
|
||||||
}
|
}
|
||||||
Result Stack::request(BtpRequest req) {
|
Result Stack::request(BtpRequest req) {
|
||||||
// IF-NF-001: mutually exclusive BTP header variants and conditional fields.
|
// mutually exclusive BTP header variants and conditional fields.
|
||||||
if ((req.type != BtpType::a && req.type != BtpType::b) ||
|
if ((req.type != BtpType::a && req.type != BtpType::b) ||
|
||||||
(req.type == BtpType::a && (!req.source_port || req.destination_port_info)) ||
|
(req.type == BtpType::a && (!req.source_port || req.destination_port_info)) ||
|
||||||
(req.type == BtpType::b && req.source_port)) return Result::invalid_argument;
|
(req.type == BtpType::b && req.source_port)) return Result::invalid_argument;
|
||||||
@@ -244,7 +255,7 @@ Result Stack::request(BtpRequest req) {
|
|||||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||||
return Result::invalid_argument;
|
return Result::invalid_argument;
|
||||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented: GAP-GN-001.
|
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||||
return Result::invalid_argument;
|
return Result::invalid_argument;
|
||||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||||
@@ -296,7 +307,7 @@ Result Stack::request(GnRequest req) {
|
|||||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||||
return Result::invalid_argument;
|
return Result::invalid_argument;
|
||||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented: GAP-GN-001.
|
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||||
return Result::invalid_argument;
|
return Result::invalid_argument;
|
||||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
#include <microbu_v2x/security.hpp>
|
||||||
|
#include <microbu_v2x/trust_update.hpp>
|
||||||
|
#include <vanetza/security/v2/basic_elements.hpp>
|
||||||
|
#include <vanetza/security/v3/secured_message.hpp>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
namespace microbu_v2x::pki {
|
||||||
|
namespace {
|
||||||
|
bool same_or_newer(unsigned old_seq, unsigned next_seq, const ByteBuffer& old, const ByteBuffer& next) {
|
||||||
|
if (next_seq == old_seq) return old == next;
|
||||||
|
auto generation_time = [](const ByteBuffer& bytes) {
|
||||||
|
vanetza::security::v3::SecuredMessage message;
|
||||||
|
if (!message.decode(bytes)) return decltype(message.generation_time()) {};
|
||||||
|
return message.generation_time();
|
||||||
|
};
|
||||||
|
const auto old_time = generation_time(old);
|
||||||
|
const auto next_time = generation_time(next);
|
||||||
|
if (!old_time || !next_time || *next_time < *old_time) return false;
|
||||||
|
// TS 102 941 clause 6.3.4 wraps ctlSequence at 255. Authenticated time
|
||||||
|
// distinguishes a wrapped full list from replay of an earlier cycle.
|
||||||
|
return next_seq > old_seq || *next_time > *old_time;
|
||||||
|
}
|
||||||
|
bool decode_certificate(const ByteBuffer& bytes, Certificate& cert) {
|
||||||
|
return cert.decode(bytes) && cert.encode() == bytes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ByteBuffer encode_snapshot(const TrustSnapshot& snapshot) {
|
||||||
|
ByteBuffer bytes {'T', 'S', 'N', 1};
|
||||||
|
for (const auto* blob : {&snapshot.tlm, &snapshot.rca, &snapshot.ectl, &snapshot.ctl, &snapshot.crl}) {
|
||||||
|
if (blob->empty() || blob->size() > 32768) return {};
|
||||||
|
bytes.push_back(blob->size() >> 8); bytes.push_back(blob->size() & 255);
|
||||||
|
bytes.insert(bytes.end(), blob->begin(), blob->end());
|
||||||
|
}
|
||||||
|
for (int shift = 24; shift >= 0; shift -= 8) bytes.push_back(snapshot.deadline >> shift);
|
||||||
|
return bytes.size() <= 60000 ? bytes : ByteBuffer {};
|
||||||
|
}
|
||||||
|
bool decode_snapshot(const ByteBuffer& bytes, TrustSnapshot& out) {
|
||||||
|
if (bytes.size() < 8 || bytes.size() > 60000 || !std::equal(bytes.begin(), bytes.begin() + 4, ByteBuffer {'T','S','N',1}.begin())) return false;
|
||||||
|
TrustSnapshot parsed;
|
||||||
|
std::size_t pos = 4;
|
||||||
|
for (auto* blob : {&parsed.tlm, &parsed.rca, &parsed.ectl, &parsed.ctl, &parsed.crl}) {
|
||||||
|
if (pos + 2 > bytes.size()) return false;
|
||||||
|
const std::size_t length = (bytes[pos] << 8) | bytes[pos + 1]; pos += 2;
|
||||||
|
if (!length || length > 32768 || length > bytes.size() - pos) return false;
|
||||||
|
blob->assign(bytes.begin() + pos, bytes.begin() + pos + length); pos += length;
|
||||||
|
}
|
||||||
|
if (pos + 4 != bytes.size()) return false;
|
||||||
|
for (int i = 0; i < 4; ++i) parsed.deadline = (parsed.deadline << 8) | bytes[pos++];
|
||||||
|
out = std::move(parsed);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool validate_update(vanetza::security::Backend& backend, vanetza::Clock::time_point now,
|
||||||
|
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
|
||||||
|
const TrustSnapshot& proposed, TrustSnapshot& accepted) {
|
||||||
|
Certificate tlm, rca;
|
||||||
|
if (!decode_certificate(proposed.tlm, tlm) || !decode_certificate(proposed.rca, rca) ||
|
||||||
|
!tlm.valid_at_timepoint(now) || !rca.valid_at_timepoint(now)) return false;
|
||||||
|
const auto time = vanetza::security::v2::convert_time32(now);
|
||||||
|
for (const auto* wire : {&proposed.ectl, &proposed.ctl, &proposed.crl}) {
|
||||||
|
vanetza::security::v3::SecuredMessage msg;
|
||||||
|
if (!msg.decode(*wire) || !msg.generation_time() ||
|
||||||
|
*msg.generation_time() > vanetza::security::v2::convert_time64(now)) return false;
|
||||||
|
}
|
||||||
|
// TS 102 941 clause 6.3.6: authenticate every object, releasing decoded
|
||||||
|
// certificate graphs between lists so live reception can continue during updates.
|
||||||
|
std::optional<unsigned> old_ectl_sequence, old_ctl_sequence;
|
||||||
|
std::optional<RevocationList> old_crl;
|
||||||
|
std::vector<std::pair<HashedId8, Time32>> old_authorities;
|
||||||
|
if (previous) {
|
||||||
|
{
|
||||||
|
Certificate old_tlm;
|
||||||
|
if (!decode_certificate(previous->tlm, old_tlm)) return false;
|
||||||
|
const auto old_ectl = parse_tlm_ctl(backend, previous->ectl, old_tlm);
|
||||||
|
if (!old_ectl) return false;
|
||||||
|
old_ectl_sequence = old_ectl->sequence;
|
||||||
|
if (proposed.tlm != previous->tlm &&
|
||||||
|
std::none_of(old_ectl->tlms.begin(), old_ectl->tlms.end(),
|
||||||
|
[&](const auto& c) { return c.encode() == proposed.tlm; })) return false;
|
||||||
|
}
|
||||||
|
Certificate old_rca;
|
||||||
|
if (!decode_certificate(previous->rca, old_rca)) return false;
|
||||||
|
{
|
||||||
|
const auto old_ctl = parse_rca_ctl(backend, previous->ctl, old_rca);
|
||||||
|
if (!old_ctl) return false;
|
||||||
|
old_ctl_sequence = old_ctl->sequence;
|
||||||
|
for (const auto* list : {&old_ctl->ea, &old_ctl->aa}) for (const auto& cert : *list) {
|
||||||
|
const auto id = cert.calculate_digest();
|
||||||
|
if (!id) return false;
|
||||||
|
old_authorities.emplace_back(*id, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
old_crl = parse_crl(backend, previous->crl, old_rca);
|
||||||
|
if (!old_crl) return false;
|
||||||
|
} else if (pinned_tlm.empty() || proposed.tlm != pinned_tlm) return false;
|
||||||
|
Time32 deadline = std::min(microbu_v2x::security::validity_bounds(tlm).end_validity,
|
||||||
|
microbu_v2x::security::validity_bounds(rca).end_validity);
|
||||||
|
{
|
||||||
|
const auto ectl = parse_tlm_ctl(backend, proposed.ectl, tlm);
|
||||||
|
if (!ectl || !ectl->full || ectl->next_update <= time ||
|
||||||
|
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||||
|
[&](const auto& c) { return c.encode() == proposed.rca; })) return false;
|
||||||
|
deadline = std::min(deadline, ectl->next_update);
|
||||||
|
if (previous && proposed.tlm == previous->tlm &&
|
||||||
|
!same_or_newer(*old_ectl_sequence, ectl->sequence, previous->ectl, proposed.ectl)) return false;
|
||||||
|
}
|
||||||
|
{
|
||||||
|
const auto ctl = parse_rca_ctl(backend, proposed.ctl, rca);
|
||||||
|
if (!ctl || !ctl->full || ctl->next_update <= time) return false;
|
||||||
|
deadline = std::min(deadline, ctl->next_update);
|
||||||
|
if (previous && proposed.rca == previous->rca &&
|
||||||
|
!same_or_newer(*old_ctl_sequence, ctl->sequence, previous->ctl, proposed.ctl)) return false;
|
||||||
|
for (const auto* list : {&ctl->ea, &ctl->aa}) for (const auto& cert : *list) {
|
||||||
|
if (!cert.valid_at_timepoint(now)) return false;
|
||||||
|
deadline = std::min(deadline, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const auto crl = parse_crl(backend, proposed.crl, rca);
|
||||||
|
if (!crl || crl->next_update <= time || crl->this_update > time ||
|
||||||
|
crl->next_update <= crl->this_update) return false;
|
||||||
|
deadline = std::min(deadline, crl->next_update);
|
||||||
|
if (previous && proposed.rca == previous->rca) {
|
||||||
|
if (crl->this_update < old_crl->this_update ||
|
||||||
|
(crl->this_update == old_crl->this_update && proposed.crl != previous->crl)) return false;
|
||||||
|
// Revocation is permanent until the known certificate expires.
|
||||||
|
// Unknown removed entries cannot be proven expired and fail closed.
|
||||||
|
for (const auto& id : old_crl->revoked) {
|
||||||
|
if (std::find(crl->revoked.begin(), crl->revoked.end(), id) != crl->revoked.end()) continue;
|
||||||
|
const auto known = std::find_if(old_authorities.begin(), old_authorities.end(),
|
||||||
|
[&](const auto& item) { return item.first == id; });
|
||||||
|
if (known == old_authorities.end() || known->second > time) return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
accepted = proposed; accepted.deadline = deadline;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
bool snapshot_credentials(vanetza::security::Backend& backend, const TrustSnapshot& state,
|
||||||
|
microbu_v2x::security::StoredCredentials& credentials, microbu_v2x::security::TrustConfiguration* trust) {
|
||||||
|
Certificate tlm, rca;
|
||||||
|
if (!decode_certificate(state.tlm, tlm) || !decode_certificate(state.rca, rca)) return false;
|
||||||
|
const auto crl = parse_crl(backend, state.crl, rca);
|
||||||
|
if (!crl) return false;
|
||||||
|
// TS 102 941 clauses 6.3.1 and 6.3.6: ECTL anchors apply to reception.
|
||||||
|
// The selected home RCA determines credential management and its CTL.
|
||||||
|
std::vector<ByteBuffer> roots, authorities;
|
||||||
|
{
|
||||||
|
const auto ectl = parse_tlm_ctl(backend, state.ectl, tlm);
|
||||||
|
if (!ectl || !ectl->full ||
|
||||||
|
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||||
|
[&](const auto& c) { return c.encode() == state.rca; })) return false;
|
||||||
|
for (const auto& cert : ectl->roots) roots.push_back(cert.encode());
|
||||||
|
}
|
||||||
|
{
|
||||||
|
const auto ctl = parse_rca_ctl(backend, state.ctl, rca);
|
||||||
|
if (!ctl || !ctl->full) return false;
|
||||||
|
for (const auto* list : {&ctl->ea, &ctl->aa})
|
||||||
|
for (const auto& cert : *list) authorities.push_back(cert.encode());
|
||||||
|
}
|
||||||
|
credentials.roots = std::move(roots);
|
||||||
|
credentials.authorities = std::move(authorities);
|
||||||
|
if (trust) apply(*crl, rca, *trust);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# Vanetza (LGPL-3.0-or-later): upstream riebl/vanetza at the pinned commit plus patches/
|
||||||
|
# (series.cmake), as an ESP-IDF component or, on the host, as the static library `vanetza`.
|
||||||
|
# Only the sources listed in sources.cmake are compiled; the manifest fixes the compiled source set.
|
||||||
|
#
|
||||||
|
# Feature selection follows microbu_v2x: CONFIG_MICROBU_V2X_* on ESP-IDF, V2X_* on the host.
|
||||||
|
cmake_minimum_required(VERSION 3.22)
|
||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/series.cmake")
|
||||||
|
vanetza_series_prepare(VANETZA_ROOT)
|
||||||
|
include("${CMAKE_CURRENT_LIST_DIR}/sources.cmake")
|
||||||
|
set(_vanetza_dir "${CMAKE_CURRENT_LIST_DIR}")
|
||||||
|
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
idf_component_register(SRCS "src/sha.cpp"
|
||||||
|
INCLUDE_DIRS "${VANETZA_ROOT}" "${VANETZA_ROOT}/vanetza/asn1/support"
|
||||||
|
REQUIRES esp-boost
|
||||||
|
PRIV_REQUIRES mbedtls)
|
||||||
|
if(CMAKE_BUILD_EARLY_EXPANSION)
|
||||||
|
return()
|
||||||
|
endif()
|
||||||
|
set(VANETZA_TARGET ${COMPONENT_LIB})
|
||||||
|
foreach(_feature NETWORK CAM DENM VAM SECURITY PKI)
|
||||||
|
set(V2X_${_feature} ${CONFIG_MICROBU_V2X_${_feature}})
|
||||||
|
endforeach()
|
||||||
|
else()
|
||||||
|
foreach(_feature NETWORK CAM DENM VAM SECURITY)
|
||||||
|
if(NOT DEFINED V2X_${_feature})
|
||||||
|
set(V2X_${_feature} ON)
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
add_library(vanetza STATIC "${_vanetza_dir}/src/sha.cpp")
|
||||||
|
add_library(Vanetza::vanetza ALIAS vanetza)
|
||||||
|
set(VANETZA_TARGET vanetza)
|
||||||
|
target_include_directories(vanetza PUBLIC "${VANETZA_ROOT}" "${VANETZA_ROOT}/vanetza/asn1/support")
|
||||||
|
if(V2X_BOOST_ROOT)
|
||||||
|
target_include_directories(vanetza SYSTEM PUBLIC "${V2X_BOOST_ROOT}")
|
||||||
|
if(WIN32)
|
||||||
|
target_compile_definitions(vanetza PUBLIC BOOST_NO_USER_CONFIG
|
||||||
|
BOOST_PLATFORM_CONFIG="boost/config/platform/win32.hpp")
|
||||||
|
endif()
|
||||||
|
else()
|
||||||
|
find_package(Boost 1.70 REQUIRED)
|
||||||
|
target_include_directories(vanetza SYSTEM PUBLIC ${Boost_INCLUDE_DIRS})
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_compile_features(${VANETZA_TARGET} PUBLIC cxx_std_17)
|
||||||
|
set_target_properties(${VANETZA_TARGET} PROPERTIES C_STANDARD 11 CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
|
||||||
|
|
||||||
|
set(_sources ${V2X_BASE_SOURCES})
|
||||||
|
if(V2X_NETWORK)
|
||||||
|
list(APPEND _sources ${V2X_NETWORK_SOURCES} ${V2X_SECURITY_ASN_SOURCES})
|
||||||
|
endif()
|
||||||
|
if(NOT ESP_PLATFORM)
|
||||||
|
# src/sha.cpp: OpenSSL digests on the host, PSA Crypto on the device
|
||||||
|
find_package(OpenSSL REQUIRED COMPONENTS Crypto)
|
||||||
|
target_link_libraries(${VANETZA_TARGET} PRIVATE OpenSSL::Crypto)
|
||||||
|
endif()
|
||||||
|
if(V2X_NETWORK OR V2X_CAM OR V2X_DENM OR V2X_VAM)
|
||||||
|
list(APPEND _sources ${V2X_ASN_SUPPORT_SOURCES})
|
||||||
|
endif()
|
||||||
|
foreach(_service CAM DENM VAM)
|
||||||
|
if(V2X_${_service})
|
||||||
|
list(APPEND _sources ${V2X_${_service}_SOURCES})
|
||||||
|
endif()
|
||||||
|
endforeach()
|
||||||
|
if(V2X_SECURITY)
|
||||||
|
list(APPEND _sources ${V2X_SECURITY_PROVIDER_SOURCES})
|
||||||
|
if(NOT ESP_PLATFORM)
|
||||||
|
# persistence.hpp declares the OpenSSL loaders under this define: keep it PUBLIC.
|
||||||
|
list(APPEND _sources ${V2X_SECURITY_HOST_SOURCES})
|
||||||
|
target_compile_definitions(${VANETZA_TARGET} PUBLIC VANETZA_WITH_OPENSSL)
|
||||||
|
target_compile_definitions(${VANETZA_TARGET} PRIVATE OPENSSL_API_COMPAT=0x10101000L)
|
||||||
|
endif()
|
||||||
|
if(V2X_PKI)
|
||||||
|
list(APPEND _sources ${V2X_PKI_ASN_SOURCES})
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
list(REMOVE_DUPLICATES _sources)
|
||||||
|
target_sources(${VANETZA_TARGET} PRIVATE ${_sources})
|
||||||
|
|
||||||
|
if(V2X_NETWORK)
|
||||||
|
foreach(_module circular_buffer geometry heap rational multiprecision)
|
||||||
|
if(NOT EXISTS "${_vanetza_dir}/third_party/${_module}/include/boost")
|
||||||
|
message(FATAL_ERROR "Missing Boost.${_module}; run git submodule update --init --recursive")
|
||||||
|
endif()
|
||||||
|
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/third_party/${_module}/include")
|
||||||
|
endforeach()
|
||||||
|
# Last-resort fallback headers for older system Boost releases; searched after every real Boost include root.
|
||||||
|
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/compat/include")
|
||||||
|
endif()
|
||||||
|
# Iostreams stream devices are header-only here; esp-boost omits these headers.
|
||||||
|
if(V2X_IOSTREAMS_ROOT)
|
||||||
|
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${V2X_IOSTREAMS_ROOT}")
|
||||||
|
elseif(EXISTS "${_vanetza_dir}/third_party/iostreams/include/boost/iostreams/stream.hpp")
|
||||||
|
target_include_directories(${VANETZA_TARGET} SYSTEM PUBLIC "${_vanetza_dir}/third_party/iostreams/include")
|
||||||
|
elseif(ESP_PLATFORM)
|
||||||
|
message(FATAL_ERROR "Missing Boost.Iostreams. Run git submodule update --init --recursive or set V2X_IOSTREAMS_ROOT.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
|
||||||
|
target_compile_options(${VANETZA_TARGET} PRIVATE -ffunction-sections -fdata-sections
|
||||||
|
-Wno-error=deprecated-declarations)
|
||||||
|
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15)
|
||||||
|
target_compile_options(${VANETZA_TARGET} PRIVATE -Wno-error=deprecated-variadic-comma-omission)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
target_compile_definitions(${VANETZA_TARGET} PUBLIC HAVE_NETINET_IN_H)
|
||||||
|
# The generated IOC table intentionally zero-initializes trailing fields.
|
||||||
|
set_source_files_properties("${VANETZA_ROOT}/vanetza/asn1/its/r2/WrappedExtensionContainer.c"
|
||||||
|
PROPERTIES COMPILE_OPTIONS -Wno-error=missing-field-initializers)
|
||||||
|
# Same for the IOC tables behind HeaderInfo's contributedExtensions; some generated object sets
|
||||||
|
# are referenced by no constraint in this closure.
|
||||||
|
set_source_files_properties(
|
||||||
|
"${VANETZA_ROOT}/vanetza/asn1/security/AppExtension.c"
|
||||||
|
"${VANETZA_ROOT}/vanetza/asn1/security/CertIssueExtension.c"
|
||||||
|
"${VANETZA_ROOT}/vanetza/asn1/security/CertRequestExtension.c"
|
||||||
|
"${VANETZA_ROOT}/vanetza/asn1/security/ContributedExtensionBlock.c"
|
||||||
|
"${VANETZA_ROOT}/vanetza/asn1/security/IeeeExtension.c"
|
||||||
|
PROPERTIES COMPILE_OPTIONS "-Wno-error=missing-field-initializers;-Wno-error=unused-const-variable")
|
||||||
|
# ESP-IDF 6 uses picolibc's native timegm, without a tm_gmtoff member.
|
||||||
|
# Do not confuse the missing struct member with timezone-mutating emulation.
|
||||||
|
if(IDF_VERSION_MAJOR GREATER_EQUAL 6)
|
||||||
|
set_source_files_properties("${VANETZA_ROOT}/vanetza/asn1/support/GeneralizedTime.c"
|
||||||
|
PROPERTIES COMPILE_DEFINITIONS HAVE_TIMEGM)
|
||||||
|
endif()
|
||||||
|
target_compile_options(${VANETZA_TARGET} PRIVATE
|
||||||
|
$<$<COMPILE_LANGUAGE:C>:-Wno-error=unused-function>
|
||||||
|
$<$<COMPILE_LANGUAGE:C>:-Wno-error=maybe-uninitialized>)
|
||||||
|
endif()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
version: "0.1.0"
|
||||||
|
description: "Modular Vanetza library for ESP-IDF (conformance work in progress)"
|
||||||
|
url: https://github.com/riebl/vanetza
|
||||||
|
repository: https://github.com/riebl/vanetza.git
|
||||||
|
dependencies:
|
||||||
|
idf: ">=5.3"
|
||||||
|
espressif/esp-boost:
|
||||||
|
version: "0.4.1"
|
||||||
|
public: true
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
function(vanetza_series_prepare out)
|
||||||
|
if(VANETZA_SOURCE_DIR)
|
||||||
|
set(${out} "${VANETZA_SOURCE_DIR}" PARENT_SCOPE)
|
||||||
|
else()
|
||||||
|
get_filename_component(_root "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../external/vanetza" ABSOLUTE)
|
||||||
|
if(NOT EXISTS "${_root}/vanetza/common/clock.hpp")
|
||||||
|
message(FATAL_ERROR "Missing vendored Vanetza source at ${_root}")
|
||||||
|
endif()
|
||||||
|
set(${out} "${_root}" PARENT_SCOPE)
|
||||||
|
endif()
|
||||||
|
endfunction()
|
||||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user