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:
Ashin Walpola
2026-11-11 00:13:57 +01:00
parent 1c3a66e4da
commit 50bbf6552d
10307 changed files with 53622 additions and 850451 deletions
@@ -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
@@ -0,0 +1,122 @@
#pragma once
#include <vanetza/common/byte_buffer.hpp>
#include <vanetza/net/mac_address.hpp>
#include <cstdint>
#include <memory>
#include <optional>
#if V2X_NETWORK
#include <vanetza/common/runtime.hpp>
#include <vanetza/dcc/channel_load.hpp>
#endif
namespace microbu_v2x {
// Implementation result, NOT an additional ETSI AL-DATA.confirm primitive.
enum class Result { accepted, invalid_argument, unsupported, wrong_entry_point,
security_unavailable, resource_limit, rejected, time_regression,
identity_change_pending /*< TS 102 723-8 clause 6.3.1.3: between PREPARE and COMMIT */ };
// Named PHY modes avoid confusing legacy OFDM coding schemes with the SDK's
// rate indices or HT/NGV MCS indices. EN 303 797 clauses 4.3.1 and 4.3.2.
enum class OfdmMcs : std::uint8_t {
bpsk_1_2, bpsk_3_4, qpsk_1_2, qpsk_3_4,
qam16_1_2, qam16_3_4, qam64_2_3, qam64_3_4
};
/** Technology-specific AL_DATA.request: EN 303 797 V2.1.1, Annex B.2.
* 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.
* 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.
*/
struct AlDataRequest {
vanetza::MacAddress source;
vanetza::MacAddress destination;
std::uint8_t priority = 0; // IEEE 802.1D user priority 0..7, not EDCA ordinal
double transmit_power_dbm = 0.0;
OfdmMcs mcs = OfdmMcs::qpsk_1_2; // 6 Mbit/s at 10 MHz
std::uint16_t bandwidth_mhz = 10;
std::uint16_t channel_number = 180;
std::uint8_t transceiver_id = 0;
std::optional<std::uint8_t> transceiver_mode;
std::optional<std::uint32_t> datastream_id;
vanetza::ByteBuffer data;
};
/** AL_DATA.indication, EN 303 797 V2.1.1 Annex B.2.
* Optional radio measurements are absent when the backend cannot measure them;
* zero must never stand for a made-up measurement.
*/
struct AlDataIndication {
vanetza::MacAddress source;
vanetza::MacAddress destination;
std::optional<double> channel_busy_ratio;
std::optional<double> received_power_dbm;
std::uint16_t channel_number = 180;
std::uint8_t receiver_id = 0;
std::optional<std::uint8_t> receiver_mode;
vanetza::ByteBuffer data;
};
/** Device-independent access adapter. Backend must reject unsupported controls,
* apply DCC when allocated to access, and report reception via Stack::indicate.
* request takes ownership even on failure. No callback from an interrupt.
*/
class Access {
public:
virtual Result request(AlDataRequest) = 0;
virtual ~Access() = default;
};
Result validate(const AlDataRequest&, std::size_t maximum_gnpdu);
/** Access profile has no BTP/GN state and preserves the AL_DATA parameters.
*
* 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.
* Disabled by default so existing callers (host tests, other
* applications) are unaffected; the ESP32-C5 firmware enables it once it has a real CBR
* source. The DCC methods below do not exist on an access-only build (no
* V2X_NETWORK): the Adaptive approach lives in vanetza/dcc, which that configuration does
* not compile, matching the documented access-only deployment (docs/conformance.md).
*/
class AccessStack {
public:
explicit AccessStack(Access& access, std::size_t maximum_gnpdu = 4096);
~AccessStack();
AccessStack(const AccessStack&) = delete;
AccessStack& operator=(const AccessStack&) = delete;
#if V2X_NETWORK
/** Enable the Adaptive DCC_ACC gate. cbr_target defaults to TS 103 836-4-2's
* itsGNCBRTarget = 0.62
* (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
* periodic advance()/trigger() (e.g. the Stack's ManualRuntime), since the Adaptive approach
* reschedules itself every 200 ms of that runtime's own clock.
* Call once, before the first request().
*/
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):
* local LCBR, or CBR_G when a Release-2 DCC_NET has one available. No-op unless
* enable_dcc was called.
*/
void report_channel_load(vanetza::dcc::ChannelLoad);
/** Permitted duty cycle (delta) from the last periodic Adaptive-approach update.
* Returns UnitInterval(1.0) (unrestricted) when DCC is not enabled.
*/
vanetza::UnitInterval permitted_duty_cycle() const;
#endif
Result request(AlDataRequest);
private:
#if V2X_NETWORK
class Dcc;
std::unique_ptr<Dcc> dcc_;
#endif
Access& access_;
std::size_t maximum_gnpdu_;
};
}
@@ -0,0 +1,63 @@
#pragma once
#include <microbu_v2x/security_module.hpp>
#include <vanetza/security/backend.hpp>
#include <memory>
namespace microbu_v2x {
/** vanetza::security::Backend on the PSA Crypto API of mbedTLS.
*
* ESP-IDF 6.0.2 ships mbedTLS 4.1.0 (TF-PSA-Crypto), where the classic
* ecp/ecdsa/bignum headers are private; the PSA API (psa/crypto.h) is the only
* public cryptography interface and is also present in mbedTLS 3.6 (ESP-IDF 5.x).
*
* Algorithms are those TS 103 097 V2.2.1 clause 5.2 selects through IEEE Std
* 1609.2: ECDSA over NIST P-256, brainpoolP256r1 (SHA-256) and brainpoolP384r1
* (SHA-384), clauses 5.3.1, 5.3.3, 6.3.38/6.3.39. ECDSA is randomized
* (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
* verification; IEEE Std 1609.2 does not require RFC 6979). Compressed points
* are recovered by microbu_v2x::ecc, since PSA imports Weierstrass public keys
* only in SEC 1 uncompressed form.
*
* 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
* failure raises std::runtime_error or returns false; nothing is faked.
*/
class BackendMbedTls : public vanetza::security::Backend, public security::KeyGenerator {
public:
static constexpr auto backend_name = "mbedTLS-PSA";
BackendMbedTls();
~BackendMbedTls() override;
BackendMbedTls(const BackendMbedTls&) = delete;
BackendMbedTls& operator=(const BackendMbedTls&) = delete;
/// Legacy NIST P-256 + SHA-256 signature of data (TS 103 097 v1.x, IEEE 1609.2 5.3.1)
vanetza::security::EcdsaSignature sign_data(const vanetza::security::ecdsa256::PrivateKey&,
const vanetza::ByteBuffer& data) override;
/// ECDSA over a precomputed digest; curve follows the key type
vanetza::security::Signature sign_digest(const vanetza::security::PrivateKey&,
const vanetza::ByteBuffer& digest) override;
bool verify_data(const vanetza::security::ecdsa256::PublicKey&, const vanetza::ByteBuffer& data,
const vanetza::security::EcdsaSignature&) override;
bool verify_digest(const vanetza::security::PublicKey&, const vanetza::ByteBuffer& digest,
const vanetza::security::Signature&) override;
/// NIST P-256 only, matching the upstream OpenSSL backend (EccPoint carries no curve)
boost::optional<vanetza::security::Uncompressed> decompress_point(const vanetza::security::EccPoint&) override;
vanetza::ByteBuffer calculate_hash(vanetza::security::HashAlgorithm, const vanetza::ByteBuffer&) override;
/// Fresh NIST P-256 key pair from the PSA random generator
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:
* the current and next authorization tickets plus enrolment material). */
void set_key_cache_size(std::size_t);
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace microbu_v2x
@@ -0,0 +1,45 @@
#pragma once
#include <sdkconfig.h>
#if !defined(CONFIG_IDF_TARGET_ESP32C5) || !defined(CONFIG_MICROBU_V2X_RADIO_C5)
#error "C5Radio requires ESP32-C5 and CONFIG_MICROBU_V2X_RADIO_C5"
#endif
#include <microbu_v2x/access.hpp>
#include <esp_err.h>
#include <functional>
#include <memory>
namespace microbu_v2x {
struct C5RadioConfig {
std::uint16_t channel_number = 180;
double transmit_power_dbm = 10.0;
unsigned receive_queue_length = 8;
// Explicit laboratory mode until real CBR/DCC enforcement is integrated.
// The default supports a receive-only second C5 without any packet TX.
bool laboratory_transmission = false;
};
/** ITS-G5 AL_DATA device binding, EN 303 797 Annex B.2.
* This adapter owns the Wi-Fi driver while started. Invoke start/stop/request/
* poll in one application task. Radio callbacks only copy into a bounded queue.
* No MQTT, Ethernet, storage, facilities service or test runtime is included.
*/
class C5Radio final : public Access {
public:
using Receive = std::function<void(AlDataIndication)>;
using Capture = std::function<void(const vanetza::ByteBuffer&, int, std::uint32_t)>;
explicit C5Radio(C5RadioConfig = {});
~C5Radio();
C5Radio(const C5Radio&) = delete;
C5Radio& operator=(const C5Radio&) = delete;
esp_err_t start();
void stop();
Result request(AlDataRequest) override;
// Dispatch reception in the owning task. Capture contains the original
// MPDU including FCS, before LLC/MAC removal; timestamp is radio-local us.
void poll(const Receive&, const Capture& = {});
std::uint32_t dropped_frames() const;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
}
@@ -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
@@ -0,0 +1,39 @@
#pragma once
#include <vanetza/common/byte_buffer.hpp>
#include <vanetza/security/ecc_point.hpp>
#include <vanetza/security/key_type.hpp>
#include <boost/optional/optional.hpp>
#include <cstddef>
namespace microbu_v2x::ecc {
/** 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
* clause 3.4/3.6): the three curves TS 103 097 V2.2.1 clause 6 admits for
* verification keys (IEEE Std 1609.2 clause 6.4.36 PublicVerificationKey).
* All three primes satisfy p = 3 (mod 4).
*/
struct CurveParameters {
vanetza::security::KeyType type;
std::size_t octets; // field element length
const char* p;
const char* a;
const char* b;
};
/** Domain parameters for a key type, nullptr for KeyType::Unspecified. */
const CurveParameters* curve(vanetza::security::KeyType);
/** Recover an affine point from its x coordinate and the parity of y.
* IEEE Std 1609.2 clause 6.3.23 EccP256CurvePoint / 6.3.24 EccP384CurvePoint
* compressed-y-0 / compressed-y-1 forms (SEC 1 clause 2.3.4). Pure integer
* arithmetic (Boost.Multiprecision), so it is independent of the crypto backend.
* \return uncompressed point, or none if x has the wrong length or is not on the curve
*/
boost::optional<vanetza::security::Uncompressed>
decompress(vanetza::security::KeyType, const vanetza::ByteBuffer& x, bool y_odd);
/** SEC 1 clause 2.3.3 octet-string point encoding 0x04 || X || Y. */
vanetza::ByteBuffer encode_uncompressed(const vanetza::security::Uncompressed&);
} // namespace microbu_v2x::ecc
@@ -0,0 +1,23 @@
#pragma once
#include <microbu_v2x/pki.hpp>
namespace microbu_v2x::pki {
/** 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
* coordinate, psa_mac_compute(PSA_ALG_HMAC(SHA-256)), psa_generate_random and
* psa_aead_encrypt/decrypt(PSA_ALG_CCM) with a 16-octet tag. */
class EciesMbedTls : public EciesBackend {
public:
EciesMbedTls(); // psa_crypto_init, throws on failure
KeyPair generate_key(KeyType) override;
std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) override;
ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) override;
ByteBuffer random(std::size_t octets) override;
bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) override;
bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
};
} // namespace microbu_v2x::pki
@@ -0,0 +1,19 @@
#pragma once
#include <microbu_v2x/pki.hpp>
namespace microbu_v2x::pki {
/// EciesBackend on OpenSSL (host builds only): ECDH via EC_KEY, HMAC-SHA256, RAND_bytes, EVP AES-128-CCM.
class EciesOpenSsl : public EciesBackend {
public:
KeyPair generate_key(KeyType) override;
std::optional<ByteBuffer> ecdh_x(const PrivateKey& own, const PublicKey& peer) override;
ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) override;
ByteBuffer random(std::size_t octets) override;
bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) override;
bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) override;
};
} // namespace microbu_v2x::pki
@@ -0,0 +1,80 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <vanetza/asn1/asn1c_wrapper.hpp>
#include <vanetza/asn1/support/uper_decoder.h>
#if V2X_CAM
#include <vanetza/asn1/its/r2/CAM.h>
#endif
#if V2X_DENM
#include <vanetza/asn1/its/r2/DENM.h>
#endif
#if V2X_VAM
#include <vanetza/asn1/its/r2/VAM.h>
#endif
namespace microbu_v2x::facilities {
template<class T>
struct CompletePerMessage : vanetza::asn1::asn1c_per_wrapper<T> {
using vanetza::asn1::asn1c_per_wrapper<T>::asn1c_per_wrapper;
bool decode_exact(const vanetza::ByteBuffer& bytes) {
if (bytes.empty()) return false;
// X.691 complete encoding: consume the PDU and only its zero padding.
// Comparing a re-encoding would incorrectly reject unknown extensions
// which an extensible ASN.1 decoder is permitted to skip.
void* decoded = nullptr;
asn_codec_ctx_t context{};
context.max_stack_size = 16384;
const auto result = uper_decode(&context, this->m_type, &decoded,
bytes.data(), bytes.size(), 0, 0);
const bool complete = result.code == RC_OK && result.consumed > 0 &&
(result.consumed + 7) / 8 == bytes.size();
const unsigned padding = complete ? (8 - result.consumed % 8) % 8 : 0;
if (!complete || (bytes.back() & ((1u << padding) - 1u))) {
vanetza::asn1::free(*this->m_type, decoded);
return false;
}
vanetza::asn1::free(*this->m_type, this->m_struct);
this->m_struct = static_cast<T*>(decoded);
return true;
}
};
// Explicit R2 aliases avoid Vanetza's backwards-compatible R1 Cam/Denm aliases.
// 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.
#if V2X_CAM
struct Cam : CompletePerMessage<Vanetza_ITS2_CAM_t> {
Cam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_CAM) {}
};
#endif
#if V2X_DENM
struct Denm : CompletePerMessage<Vanetza_ITS2_DENM_t> {
Denm() : CompletePerMessage(asn_DEF_Vanetza_ITS2_DENM) {}
};
#endif
#if V2X_VAM
struct Vam : CompletePerMessage<Vanetza_ITS2_VAM_t> {
Vam() : CompletePerMessage(asn_DEF_Vanetza_ITS2_VAM) {}
};
#endif
enum class Kind { cam, denm, vam };
struct Descriptor { std::uint16_t port; unsigned message_id; unsigned protocol_version; };
Descriptor descriptor(Kind);
/** Decode + constraints + identity + exact UPER consumption.
* This boundary validates an encoded PDU. It is NOT a complete CA, DEN or VRU
* Basic Service: generation rules/lifecycle/SSP decisions belong to that service.
*/
Result validate_pdu(Kind, const vanetza::ByteBuffer&, std::size_t maximum = 1394);
/** Application owns generation and lifecycle; this function selects the standard
* BTP port and validates the Release 2 PDU before entering the NF-SAP.
*/
#if V2X_NETWORK
}
#include <microbu_v2x/stack.hpp>
namespace microbu_v2x::facilities {
Result send(Stack&, Kind, vanetza::ByteBuffer, BtpRequest transport);
#endif
}
@@ -0,0 +1,87 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <vanetza/common/byte_buffer.hpp>
#include <vanetza/security/hashed_id.hpp>
#include <cstdint>
#include <functional>
#include <memory>
namespace microbu_v2x::security {
/** Identifier-change service of the security entity.
*
* TS 102 723-8 V2.0.0 clause 5 incorporates V1.1.1: clauses 5.2.5 to 5.2.10
* (SN-IDCHANGE-SUBSCRIBE/-EVENT/-UNSUBSCRIBE/-TRIGGER, SN-ID-LOCK/-UNLOCK) and
* clause 6.3 (ID management: hook function, two-phase commit, lock, trigger).
* TS 102 723-9 V1.1.1 clauses 5.2.5 to 5.2.10 define the identical SF-SAP
* primitives (Tables 10 to 21 carry the same names and ranges), and clause
* 4.1.5 allows one security entity to serve several layers, so one service
* instance is exposed through both sn_sap.hpp and sf_sap.hpp. TS 102 940
* V2.1.1 clause 6.5 requires every layer holding an identifier to subscribe
* and derive its identifier from the HashedId8 given in the event.
*
* A subscriber may live in the same task, another task or process, or another
* device: the hook is an ordinary callback and the response object may be used
* inside the callback or later. The library defines no transport for that.
*/
/// SN-IDCHANGE-EVENT.indication command (TS 102 723-8 V1.1.1 Table 12; clause 6.3.1.2 a-d)
enum class IdChangeCommand : std::uint8_t { PREPARE, COMMIT, ABORT, DEREG };
/// Table 11 / Table 14 subscription: INTEGER 0 to 2^64-1
using SubscriptionHandle = std::uint64_t;
/// Table 19 / Table 20 lock_handle: INTEGER 0 to 2^64-1
using LockHandle = std::uint64_t;
/// Table 12 id: OCTET STRING of 8 octets, the HashedId8 of the authorization ticket (TS 102 940 clause 6.5)
using Identifier = vanetza::security::HashedId8;
/** SN-IDCHANGE-EVENT.response (Table 13 return_code).
* Hand the object back within the hook call for a local subscriber, or keep it
* and respond once the remote party has answered. Responding twice, or after
* the phase finished (timeout, abort, unsubscribe), is ignored.
*/
class IdChangeResponder {
public:
virtual void respond(bool return_code) = 0;
virtual ~IdChangeResponder() = default;
};
/** Hook function (clause 6.3.1.2): command, id to be set and the subscriber_data
* given at subscription (Table 12). For PREPARE and COMMIT the service waits
* for the response; ABORT and DEREG expect no response (responder is null). */
using IdChangeHook = std::function<void(IdChangeCommand, const Identifier&, const vanetza::ByteBuffer& subscriber_data,
std::shared_ptr<IdChangeResponder>)>;
/** The identifier-change service of the security entity (TS 102 723-8 V1.1.1 clause 6.3
* "ID management"): SN-IDCHANGE-SUBSCRIBE/-UNSUBSCRIBE/-TRIGGER and SN-ID-LOCK/-UNLOCK
* (clauses 5.2.5, 5.2.7 to 5.2.10) as virtual calls; the same instance serves the
* SF-SAP (TS 102 723-9 V1.1.1 clauses 5.2.5 to 5.2.10). */
class IdChangeService {
public:
virtual ~IdChangeService() = default;
/// SN-IDCHANGE-SUBSCRIBE.request (Table 10) -> .confirm subscription (Table 11)
virtual SubscriptionHandle subscribe(IdChangeHook idchange_event_hook, vanetza::ByteBuffer subscriber_data = {}) = 0;
/// SN-IDCHANGE-UNSUBSCRIBE.request (Table 14); .confirm carries no parameter (Table 15)
virtual Result unsubscribe(SubscriptionHandle subscription) = 0;
/** SN-IDCHANGE-TRIGGER.request (Table 16). Queues an identifier change; clause 6.3.3 NOTE:
* this does not lead to an immediate change, the two-phase commit is invoked, after any
* lock is released. Result::rejected when no other valid authorization ticket exists. */
virtual Result trigger() = 0;
/// SN-ID-LOCK.request Duration 0..255 seconds (Table 18) -> lock_handle (Table 19); clause 6.3.2
virtual LockHandle lock(std::uint8_t duration_seconds) = 0;
/// SN-ID-UNLOCK.request (Table 20); .confirm carries no parameter (Table 21)
virtual Result unlock(LockHandle lock_handle) = 0;
/// HashedId8 of the authorization ticket currently in use (TS 102 940 clause 6.5)
virtual Identifier current_identifier() const = 0;
/// true while PREPARE has been issued and COMMIT/ABORT is outstanding (clause 6.3.1.3 item 2)
virtual bool change_pending() const = 0;
};
} // namespace microbu_v2x::security
@@ -0,0 +1,16 @@
#pragma once
#include <microbu_v2x/access.hpp>
namespace microbu_v2x::its_g5 {
// 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.
constexpr std::size_t maximum_gnpdu = 2296;
Result encode_frame(const AlDataRequest&, std::uint16_t sequence, vanetza::ByteBuffer&);
// Caller declares FCS presence; this function never guesses from payload bytes.
// Receive PHY/FCS status must be checked by the radio before calling this:
// on ESP32-C5, any frame reaching the promiscuous callback has already passed
// a real hardware FCS check (WIFI_PROMIS_FILTER_MASK_FCSFAIL is never set),
// and the 4 trailing bytes this flag strips are not a software-recoverable
// copy of that FCS -- see c5_radio.cpp's receive() for the measured evidence.
Result decode_frame(const std::uint8_t*, std::size_t, bool includes_fcs, AlDataIndication&);
}
@@ -0,0 +1,81 @@
#pragma once
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
/** ITS time base: TAI microseconds since the ITS epoch 2004-01-01T00:00:00.000 UTC.
*
* TS 102 894-2 V2.4.1 DE_TimestampIts: "elapsed milliseconds since the ITS epoch
* ... TAI is a continuous time scale. UTC has discontinuities, as it is occasionally
* adjusted by leap seconds. As of 1 January, 2022, TimestampIts is 5 seconds ahead
* of UTC" (example: 2007-01-01T00:00:00.000Z is 94 694 401 000 ms, one leap second
* since the epoch). IEEE Std 1609.2 Time64 is the same scale in microseconds and
* Time32 in seconds ("the number of (TAI) microseconds/seconds since 00:00:00 UTC,
* 1 January, 2004", Ieee1609Dot2BaseTypes ASN.1 module as published by ETSI);
* TS 103 097 V2.2.1 generationTime and certificate validityPeriod use them. vanetza::Clock::time_point counts these
* microseconds; upstream's Clock::at(posix_time) subtracts the epoch in UTC without
* leap seconds and is therefore 5 s behind since 2017: convert wall-clock time with
* this header.
*
* Leap seconds are announced by the IERS at most six months ahead; the table ends
* 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).
*/
namespace microbu_v2x::its_time {
/// Unix time (seconds since 1970-01-01T00:00:00Z, no leap seconds) of the ITS epoch.
constexpr std::int64_t epoch_unix_seconds = 1072915200;
/// Unix instants at which UTC gained a leap second after the ITS epoch: 2006-01-01,
/// 2009-01-01, 2012-07-01, 2015-07-01, 2017-01-01 (each 00:00:00Z, the first second
/// after the inserted 23:59:60). TAI-UTC was 32 s at the epoch and is 37 s since 2017.
constexpr std::array<std::int64_t, 5> leap_second_unix_seconds = {
1136073600, 1230768000, 1341100800, 1435708800, 1483228800};
/// Number of leap seconds inserted between the ITS epoch and the given Unix instant.
constexpr int leap_seconds_since_epoch(std::int64_t unix_seconds) {
int count = 0;
for (auto at : leap_second_unix_seconds) if (unix_seconds >= at) ++count;
return count;
}
/// TAI microseconds since the ITS epoch for a Unix instant given as seconds and an
/// additional sub-second part in microseconds.
constexpr std::int64_t microseconds_since_epoch(std::int64_t unix_seconds, std::int64_t sub_second_microseconds = 0) {
return (unix_seconds - epoch_unix_seconds + leap_seconds_since_epoch(unix_seconds)) * 1000000 + sub_second_microseconds;
}
/// The same for a std::chrono system clock instant (Unix time on every platform this library targets).
inline std::chrono::microseconds since_epoch(std::chrono::system_clock::time_point at) {
// ("unix" itself is a predefined macro on GNU/Linux)
const auto unix_us = std::chrono::duration_cast<std::chrono::microseconds>(at.time_since_epoch()).count();
const std::int64_t seconds = unix_us >= 0 ? unix_us / 1000000 : -((-unix_us + 999999) / 1000000);
return std::chrono::microseconds(microseconds_since_epoch(seconds, unix_us - seconds * 1000000));
}
/// TS 102 894-2 TimestampIts (milliseconds) for a system clock instant.
inline std::uint64_t timestamp_its(std::chrono::system_clock::time_point at) {
return static_cast<std::uint64_t>(since_epoch(at).count() / 1000);
}
/// IEEE Std 1609.2 Time32 (seconds) for a system clock instant.
inline std::uint32_t time32(std::chrono::system_clock::time_point at) {
return static_cast<std::uint32_t>(since_epoch(at).count() / 1000000);
}
/// Inverse: Unix microseconds for TAI microseconds since the ITS epoch. An instant inside an
/// inserted leap second (UTC 23:59:60) has no Unix second of its own and maps onto the
/// following 00:00:00.
constexpr std::int64_t unix_microseconds(std::int64_t microseconds_since_its_epoch) {
const std::int64_t tai_seconds = microseconds_since_its_epoch / 1000000;
int inserted = 0;
for (std::size_t i = 0; i < leap_second_unix_seconds.size(); ++i) {
// TAI value (since the ITS epoch) of the first second after the i-th insertion
const std::int64_t tai_of_leap = leap_second_unix_seconds[i] - epoch_unix_seconds + static_cast<std::int64_t>(i + 1);
if (tai_seconds >= tai_of_leap) ++inserted;
}
return (tai_seconds + epoch_unix_seconds - inserted) * 1000000 + microseconds_since_its_epoch % 1000000;
}
} // namespace microbu_v2x::its_time
@@ -0,0 +1,66 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <microbu_v2x/mn_sap.hpp>
#include <cstdint>
#include <vector>
/** MF-SAP language binding: management entity -> facilities layer.
*
* - TS 102 723-5 V2.0.0 clause 5 incorporates V1.1.1 altogether, which (like
* TS 102 723-4 for MN) provides MF-COMMAND and MF-REQUEST with the generic
* envelope of TS 102 723-1: entity identifier, CommandRef, command/request
* number and value, ErrStatus in the confirm.
* - TS 103 175 V1.1.1 clause 8.4: MF-SET.request/.confirm (Tables 11/12) with
* the DCC F-Params of Table 13, i.e. the channel-load feedback the DCC
* management entity gives the facilities layer (clause 6.5 DCC_CROSS_Facilities).
* The facilities layer implements FacilitiesParameterSink; it may live in
* another task, process or device, the library defines no transport.
*/
namespace microbu_v2x::MF_SAP {
using MN_SAP::ErrStatus;
/// TS 103 175 V1.1.1 Table 13: F-Param.No for the DCC interface at the MF-SAP
enum class F_Param_No : std::uint8_t {
CHANNEL_NUMBER = 0, // R/W, 1 octet 1..7 (selects the channel for consecutive reads/writes)
AVAILABLE_RESOURCE = 1, // R/W, 2 octets, reciprocal value of CBRa on the selected channel
};
struct F_Param { F_Param_No no; std::uint32_t value; };
struct F_Error { F_Param_No f_param_no; ErrStatus err_status; };
/// Table 11: MF-SET.request
struct MF_SET_request { std::uint32_t fac_id; std::uint8_t command_ref; std::vector<F_Param> f_param; };
/// Table 12: MF-SET.confirm (Errors optional)
struct MF_SET_confirm { std::uint32_t fac_id; std::uint8_t command_ref; std::vector<F_Error> errors; };
/// TS 102 723-1 envelope (through TS 102 723-5): MF-COMMAND.request/.confirm, MF-REQUEST.request/.confirm.
/// Command and request numbers are entity specific (annexes of the respective part); opaque here.
struct MF_COMMAND_request { std::uint32_t fac_id; std::uint8_t command_ref; std::uint32_t command_no; vanetza::ByteBuffer value; };
struct MF_COMMAND_confirm { std::uint32_t fac_id; std::uint8_t command_ref; ErrStatus err_status; };
struct MF_REQUEST_request { std::uint32_t fac_id; std::uint8_t command_ref; std::uint32_t request_no; vanetza::ByteBuffer value; };
struct MF_REQUEST_confirm { std::uint32_t fac_id; std::uint8_t command_ref; ErrStatus err_status; vanetza::ByteBuffer value; };
/** Implemented by the facilities layer (e.g. the message generation services that
* adapt their rate to the available resource). */
class FacilitiesParameterSink {
public:
virtual ~FacilitiesParameterSink() = default;
virtual ErrStatus set(F_Param_No, std::uint32_t value) = 0;
/// MF-COMMAND / MF-REQUEST are delivered unchanged; a sink that knows no such number
/// answers INVALID_COMMAND_REQUEST_NUMBER (TS 102 723-3 clause 5.2.3 wording).
virtual MF_COMMAND_confirm command(const MF_COMMAND_request& request) {
return {request.fac_id, request.command_ref, ErrStatus::INVALID_COMMAND_REQUEST_NUMBER};
}
virtual MF_REQUEST_confirm request(const MF_REQUEST_request& request) {
return {request.fac_id, request.command_ref, ErrStatus::INVALID_COMMAND_REQUEST_NUMBER, {}};
}
};
bool f_param_value_in_format(F_Param_No, std::uint32_t value);
/** MF-SET over a sink; format checked first (Table 13), a null sink answers UNSUPPORTED. */
MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink*, const MF_SET_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&);
} // namespace microbu_v2x::MF_SAP
@@ -0,0 +1,56 @@
#pragma once
#include <microbu_v2x/mn_sap.hpp>
#include <cstdint>
#include <vector>
/** MI-SAP language binding: management entity <-> access layer, DCC subset.
*
* - TS 102 723-3 V1.1.1 clauses 7 and 8: MI-SET.request/.confirm (Tables 5/6)
* and MI-GET.request/.confirm (Tables 7/8) with MAC-ID, CommandRef and a
* sequence of I-Param; clause 5.2.3: an undefined command is acknowledged
* with ErrStatus 5 "INVALID COMMAND/REQUEST NUMBER".
* - TS 103 175 V1.1.1 clause 8.2: the DCC I-Params of Table 5 (clauses 6.2 and
* 6.3 DCC_CROSS_Access).
* Binding only: the access adapter of the application may implement
* AccessParameterProvider; the library reads channel load and transmit
* timing from nowhere else and invents no values.
*/
namespace microbu_v2x::MI_SAP {
using MN_SAP::ErrStatus;
/// TS 103 175 V1.1.1 Table 5: I-Param.No for the DCC interface at the MI-SAP
enum class I_Param_No : std::uint8_t {
CHANNEL_NUMBER = 52, // R/W, 1 octet 1..7
LOCAL_CBR = 53, // R, 1 octet 0..100 (CL measurement of TS 102 687)
MESSAGE_LENGTH = 54, // R, 1 octet, granularity 1 OFDM symbol = 8 us (air time Ton)
LAST_TRANSMIT_TIME = 55, // R, 4 octets, granularity 1 OFDM symbol = 8 us
IDLE_TIME = 56, // R/W, 2 octets in ms (Toff)
TX_POWER_LEVEL_LIMIT = 57, // R/W, 1 octet, bits 0..4 EIRP 0..31 dBm, bits 5..7 reserved
};
struct I_Param { I_Param_No no; std::uint32_t value; };
struct I_Error { I_Param_No i_param_no; ErrStatus err_status; };
/// TS 102 723-3 Table 7 / TS 103 175 Table 1: MI-GET.request (MAC-ID structure of TS 102 723-1 reduced to an id)
struct MI_GET_request { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param_No> i_param_no; };
/// TS 102 723-3 Table 8 / TS 103 175 Table 2: MI-GET.confirm
struct MI_GET_confirm { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param> i_param; std::vector<I_Error> errors; };
/// TS 102 723-3 Table 5 / TS 103 175 Table 3: MI-SET.request
struct MI_SET_request { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Param> i_param; };
/// TS 102 723-3 Table 6 / TS 103 175 Table 4: MI-SET.confirm (Errors optional)
struct MI_SET_confirm { std::uint32_t mac_id; std::uint8_t command_ref; std::vector<I_Error> errors; };
class AccessParameterProvider {
public:
virtual ~AccessParameterProvider() = default;
virtual ErrStatus get(I_Param_No, std::uint32_t& value) = 0;
virtual ErrStatus set(I_Param_No, std::uint32_t value) = 0;
};
bool i_param_value_in_format(I_Param_No, std::uint32_t value);
bool i_param_writable(I_Param_No);
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider*, const MI_GET_request&);
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider*, const MI_SET_request&);
} // namespace microbu_v2x::MI_SAP
@@ -0,0 +1,101 @@
#pragma once
#include <microbu_v2x/stack.hpp>
#include <vanetza/common/clock.hpp>
#include <vanetza/common/position_fix.hpp>
#include <vanetza/geonet/address.hpp>
#include <cstdint>
#include <optional>
#include <vector>
/** MN-SAP language binding: management entity <-> networking & transport layer.
*
* - TS 102 723-4 V1.1.1 clause 5: the MN-SAP provides MN-COMMAND and MN-REQUEST
* whose primitives are specified in TS 102 723-1 (not reproduced here; the
* generic envelope is the one of TS 102 723-3 Tables 1 to 4: id, CommandRef,
* command/request number and value, ErrStatus).
* - TS 103 836-4-1 V2.2.1 Annex K: CORE_MMT.request/.response carry time, the
* local position vector, the GeoNetworking address and the TC mapping from
* the N&T management entity to the GN core; EN 302 890-2 V2.1.1 clause
* 5.5.2 names the PoTi minimum data set (timestamp, latitude, longitude,
* horizontal confidence) a networking function receives.
* - TS 103 175 V1.1.1 clause 8.3: MN-GET/MN-SET for the DCC N-Params of
* Table 10, served by the access/DCC adapter of the application.
* 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.
*/
namespace microbu_v2x::MN_SAP {
/// 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 };
struct CORE_MMT_request { RequestCause request_cause; };
/// Clause K.3: CORE_MMT.response, all parameters optional, at least one present
struct CORE_MMT_response {
std::optional<vanetza::Clock::time_point> time; // reference time for freshness of received packets
std::optional<vanetza::PositionFix> local_position_vector; // position, speed, heading, timestamp, accuracy
std::optional<vanetza::geonet::Address> geonetworking_address;
std::optional<std::vector<std::uint8_t>> tc_mapping; // Annex G traffic class parameters (opaque here)
};
/** Apply a CORE_MMT.response to the GN core. Time -> Stack::advance, position ->
* Stack::update_position. The GeoNetworking address is accepted only with
* itsGnLocalAddrConfMethod == Managed (clause 10.2.1.3.3: the GN core updates the
* MID with an unsolicited CORE_MMT.response); with Auto (10.2.1.2: the address is
* not changed) or Anonymous (10.2.1.4: the security entity owns the identifier) it
* is refused with Result::unsupported. TC mapping is refused as unsupported: the
* port uses the fixed TS 102 687 profile-to-access-category mapping. An empty
* response is Result::invalid_argument; the first failing parameter stops. */
Result CORE_MMT_response_apply(Stack&, const CORE_MMT_response&);
/// TS 102 723-3 V1.1.1 Table 2 ErrStatus is "specified in TS 102 723-1"; that text is not
/// available to this library, so only the values named in TS 102 723-3 clause 5.2.3
/// (5 = INVALID COMMAND/REQUEST NUMBER) and this library's outcomes are enumerated.
enum class ErrStatus : std::uint8_t {
SUCCESS = 0,
INVALID_COMMAND_REQUEST_NUMBER = 5,
UNSUPPORTED = 250, // library: no provider for this parameter
READ_ONLY = 251, // library: TS 103 175 Table 10 access R
INVALID_VALUE = 252, // library: outside the Table 10 format
FAILED = 253 // library: provider reported a failure
};
/// TS 103 175 V1.1.1 Table 10: N-Param.No for the DCC interface at the MN-SAP
enum class N_Param_No : std::uint8_t {
GLOBAL_CBR = 0, // R, 1 octet 0..100 (TS 102 636-4-2 global CBR of the selected channel)
CHANNEL_NUMBER = 1, // R/W, 1 octet 1..7 (selects the channel for consecutive reads/writes)
LOCAL_CBR = 2, // R, 1 octet 0..100 (from the MI-SAP for the selected channel)
AVAILABLE_RESOURCE = 3, // R, 2 octets, reciprocal value of CBRa
LAST_TRANSMIT_TIME = 4, // R, 4 octets, granularity 1 OFDM symbol = 8 us
IDLE_TIME = 5, // R/W, 2 octets in ms (Toff per radio channel)
TX_POWER_LEVEL_LIMIT = 6, // R/W, 1 octet, bits 0..4 EIRP 0..31 dBm, bits 5..7 reserved
};
struct N_Param { N_Param_No no; std::uint32_t value; };
struct N_Error { N_Param_No n_param_no; ErrStatus err_status; };
/// Table 6: MN-GET.request
struct MN_GET_request { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param_No> n_param_no; };
/// Table 7: MN-GET.confirm
struct MN_GET_confirm { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param> n_param; std::vector<N_Error> errors; };
/// Table 8: MN-SET.request
struct MN_SET_request { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Param> n_param; };
/// Table 9: MN-SET.confirm (Errors optional)
struct MN_SET_confirm { std::uint32_t nt_id; std::uint8_t command_ref; std::vector<N_Error> errors; };
/** Implemented by the access/DCC adapter of the application: the only source of
* channel load, transmit times and power limits. The stack never invents these. */
class NetworkParameterProvider {
public:
virtual ~NetworkParameterProvider() = default;
virtual ErrStatus get(N_Param_No, std::uint32_t& value) = 0;
virtual ErrStatus set(N_Param_No, std::uint32_t value) = 0;
};
/// Format limits of Table 10; a value outside is INVALID_VALUE before the provider sees it
bool n_param_value_in_format(N_Param_No, std::uint32_t value);
bool n_param_writable(N_Param_No);
/** MN-GET/MN-SET over a provider; a null provider answers UNSUPPORTED for every parameter. */
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider*, const MN_GET_request&);
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider*, const MN_SET_request&);
} // namespace microbu_v2x::MN_SAP
@@ -0,0 +1,89 @@
#pragma once
#include <microbu_v2x/stack.hpp>
#include <utility>
namespace microbu_v2x::NF_SAP {
enum class SecurityProfile { UNSECURED, SECURED };
/** BTP-DATA.request language binding.
* TS 102 723-11 V2.0.0 clause 5 incorporates V1.1.1; the complete BTP
* parameter contract is TS 103 836-5-1 V2.1.1 Annex A.2.
* '-' and '.' in primitive names become '_' in C++ identifiers.
* Parameters retain the extracted snake_case names. length counts octets;
* gn_maximum_packet_lifetime uses the GN lifetime value, not an unlabelled int.
*/
struct BTP_DATA_request {
vanetza::ByteBuffer fl_sdu;
std::size_t length = 0;
BtpType btp_type = BtpType::b;
std::uint16_t destination_port = 0;
std::optional<std::uint16_t> destination_port_info;
std::optional<std::uint16_t> source_port;
vanetza::geonet::TransportType gn_packet_transport_type = vanetza::geonet::TransportType::SHB;
vanetza::geonet::CommunicationProfile gn_communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
std::optional<SecurityProfile> gn_security_profile;
vanetza::geonet::TrafficClass gn_traffic_class;
std::optional<vanetza::geonet::Lifetime> gn_maximum_packet_lifetime;
vanetza::geonet::DestinationVariant gn_destination_address = nullptr;
std::optional<unsigned> gn_maximum_hop_limit;
std::optional<vanetza::geonet::DataRequest::Repetition> gn_repetition;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
// SN-ENCAP context_information (TS 102 723-8 V1.1.1 Table 24), forwarded by GN
// as the TRANSP_CORE.request Security context information (TS 103 836-4-1 Annex J.2)
vanetza::ByteBuffer context_information;
};
/** BTP-DATA.indication, TS 103 836-5-1 V2.1.1 Annex A.3.
* received_fl_sdu is the facilities payload; gn preserves the complete
* router indication, including source position and security report metadata.
*/
struct BTP_DATA_indication {
vanetza::ByteBuffer received_fl_sdu;
std::size_t length;
BtpType btp_type;
std::uint16_t destination_port;
std::optional<std::uint16_t> destination_port_info;
std::optional<std::uint16_t> source_port;
vanetza::geonet::DataIndication gn;
std::optional<vanetza::ByteBuffer> certificate_id;
};
inline BTP_DATA_indication BTP_DATA_indication_from(BtpIndication indication) {
const auto length = indication.data.size();
return {std::move(indication.data), length, indication.type,
indication.destination_port, indication.destination_port_info,
indication.source_port, std::move(indication.gn),
std::move(indication.certificate_id)};
}
inline Result BTP_DATA_request_submit(Stack& stack, BTP_DATA_request primitive) {
if (primitive.length != primitive.fl_sdu.size()) return Result::invalid_argument;
if (primitive.gn_security_profile) {
if (*primitive.gn_security_profile != SecurityProfile::SECURED &&
*primitive.gn_security_profile != SecurityProfile::UNSECURED)
return Result::invalid_argument;
const bool secured = *primitive.gn_security_profile == SecurityProfile::SECURED;
// A per-request profile cannot silently change station security policy.
if (secured != stack.config().mib.itsGnSecurity) return Result::unsupported;
}
BtpRequest request;
request.type = primitive.btp_type;
request.source_port = primitive.source_port;
request.destination_port = primitive.destination_port;
request.destination_port_info = primitive.destination_port_info;
request.transport = primitive.gn_packet_transport_type;
request.communication_profile = primitive.gn_communication_profile;
request.traffic_class = primitive.gn_traffic_class;
request.maximum_lifetime = primitive.gn_maximum_packet_lifetime;
request.destination = primitive.gn_destination_address;
request.maximum_hop_limit = primitive.gn_maximum_hop_limit;
request.repetition = primitive.gn_repetition;
request.its_aid = primitive.its_aid;
request.permissions = std::move(primitive.permissions);
request.security_context = std::move(primitive.context_information);
request.data = std::move(primitive.fl_sdu);
return stack.request(std::move(request));
}
}
@@ -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
@@ -0,0 +1,293 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <microbu_v2x/security.hpp>
#include <vanetza/common/byte_buffer.hpp>
#include <vanetza/common/clock.hpp>
#include <vanetza/common/its_aid.hpp>
#include <vanetza/security/backend.hpp>
#include <vanetza/security/hash_algorithm.hpp>
#include <vanetza/security/hashed_id.hpp>
#include <vanetza/security/private_key.hpp>
#include <vanetza/security/public_key.hpp>
#include <vanetza/security/v3/certificate.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <utility>
#include <vector>
/** TS 102 941 V2.2.1 enrolment and authorization request/response core.
*
* Clause 6.2.3.2 (EnrolmentRequest/Response) and clause 6.2.3.3
* (AuthorizationRequest/Response with proof of possession), message formats
* of Annex A.2, signed structures per TS 103 097 V2.2.1 clause 5.2 with
* psid = secured certificate request (TS 102 965 V2.4.1 Table A.1, 623),
* encryption per TS 103 097 clause 5.3: ECIES (IEEE Std 1609.2 clause 5.3.5,
* KDF2 of IEEE Std 1363a, HMAC-SHA256 tag truncated to 128 bit, key
* derivation parameter = SHA-256 of the recipient certificate) and
* AES-128-CCM (IEEE Std 1609.2 clause 5.3.8: 12-octet nonce, 16-octet tag
* appended to the ciphertext).
*
* The library builds and parses the messages only. Transport to the EA/AA
* (TS 102 941 clause 6.1 reference points S3/S4, HTTP in practice) and the
* retrieval of CTL and CRL from a distribution centre (clause 6.3.5, Annex D:
* GET <dc>/getctl/<HashedId8>, GET <dc>/getcrl/<HashedId8>) are supplied by the
* application; the lists themselves are built, verified and read here (clause
* 6.3.2 to 6.3.6, formats of clause A.2.7 as compiled from the TS 102 941
* V1.3.1 module, unchanged for these types in V2.2.1); butterfly keys (clause
* 6.2.3.5) are not implemented.
*/
namespace microbu_v2x::pki {
using vanetza::ByteBuffer;
using vanetza::security::HashAlgorithm;
using vanetza::security::HashedId8;
using vanetza::security::KeyType;
using vanetza::security::PrivateKey;
using vanetza::security::PublicKey;
using vanetza::security::v3::Certificate;
/// A verification or encryption key pair (IEEE Std 1609.2 PublicVerificationKey /
/// BasePublicEncryptionKey, TS 103 097 V2.2.1 clause 6) outside a security module.
using KeyPair = security::KeyPair;
/// 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
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.
* Implemented on OpenSSL (host) and the PSA Crypto API (device). generate_key()
* (KeyGenerator) gives a fresh key pair on the given curve (NIST P-256 or
* brainpoolP256r1 for ECIES). */
class EciesBackend : public security::KeyGenerator {
public:
/// 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;
/// HMAC-SHA256 (FIPS PUB 198-1), full 32-octet tag
virtual ByteBuffer hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) = 0;
/// cryptographically strong random octets
virtual ByteBuffer random(std::size_t octets) = 0;
/// AES-128-CCM, 12-octet nonce, no associated data; output = ciphertext || 16-octet tag
virtual bool aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& plaintext, ByteBuffer& ciphertext_and_tag) = 0;
virtual bool aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& ciphertext_and_tag, ByteBuffer& plaintext) = 0;
};
/// IEEE 1609.2 clause 6.3.36 EciesP256EncryptedKey: ephemeral point v, wrapped key c, tag t
struct EncryptedKey {
PublicKey v;
std::array<std::uint8_t, 16> c;
std::array<std::uint8_t, 16> t;
};
/// KDF2 (IEEE 1363a-2004 clause 13.2 with SHA-256): counter starts at 1, big-endian
ByteBuffer kdf2_sha256(vanetza::security::Backend&, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length);
/// ECIES encryption of a 16-octet AES key for a recipient public key; p1 = key derivation parameter
std::optional<EncryptedKey> ecies_encrypt_key(vanetza::security::Backend&, EciesBackend&, const PublicKey& recipient,
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key);
/// ECIES decryption with the recipient private key; none when the tag does not verify
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(vanetza::security::Backend&, EciesBackend&,
const PrivateKey& recipient, const ByteBuffer& p1,
const EncryptedKey&);
/** 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
* 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 {
// 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> request_hash {};
};
/// requested appPermissions (IEEE Std 1609.2 SequenceOfPsidSsp: ITS-AID and opaque SSP),
/// 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>>;
/// 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
struct EnrolmentRequestParameters {
ByteBuffer its_id; // canonical identifier (initial) or HashedId8 of the current EC (re-enrolment)
SigningKey verification_key; // new key; its signature is the proof of possession
Permissions app_permissions; // requestedSubjectAttributes.appPermissions
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
HashAlgorithm hash = HashAlgorithm::SHA256;
};
/** Build the EtsiTs103097Data-Encrypted EnrolmentRequest for the EA whose certificate
* carries the encryption key. Result::invalid_argument for missing keys or an EA
* certificate without encryptionKey, security_unavailable on backend failure. */
Result build_enrolment_request(vanetza::security::Backend&, EciesBackend&, vanetza::Clock::time_point now,
const EnrolmentRequestParameters&, const Certificate& ea, ByteBuffer& encoded,
RequestContext&);
/// Clause 6.2.3.2.2 InnerEcResponse
struct EnrolmentResponse {
std::uint8_t response_code = 0; // EnrolmentResponseCode, 0 = ok
std::optional<Certificate> certificate;
};
/** Decrypt with the request context (pskRecipInfo must match), verify the EA signature
* (signer digest = HashedId8 of ea, psid 623), check the requestHash, decode. Result::rejected
* when any check fails; the response is never trusted on decoding alone. */
Result parse_enrolment_response(vanetza::security::Backend&, EciesBackend&, const RequestContext&, const Certificate& ea,
const ByteBuffer& encoded, EnrolmentResponse&);
/// Clause 6.2.3.3.1 inputs
struct AuthorizationRequestParameters {
SigningKey verification_key; // new AT key
std::optional<PublicKey> encryption_key; // optional AT encryption key
Permissions app_permissions; // shall be present
std::optional<std::pair<vanetza::Clock::time_point, std::uint16_t>> validity_period; // start, hours
const Certificate* ec = nullptr; // enrolment credential signing SharedAtRequest
Signer ec_signer; // with the EC's key
bool privacy = true; // [Itss_WithPrivacy]: EC signature encrypted for the EA
bool include_pop = true; // AuthorizationRequestMessageWithPop
HashAlgorithm hash = HashAlgorithm::SHA256;
};
Result build_authorization_request(vanetza::security::Backend&, EciesBackend&, vanetza::Clock::time_point now,
const AuthorizationRequestParameters&, const Certificate& ea, const Certificate& aa,
ByteBuffer& encoded, RequestContext&);
/// Clause 6.2.3.3.2 InnerAtResponse
struct AuthorizationResponse {
std::uint8_t response_code = 0; // AuthorizationResponseCode, 0 = ok
std::optional<Certificate> certificate;
};
Result parse_authorization_response(vanetza::security::Backend&, EciesBackend&, const RequestContext&, const Certificate& aa,
const ByteBuffer& encoded, AuthorizationResponse&);
// ---- Building blocks shared with tests and authority-side tooling ---------------------
/// 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,
const ByteBuffer& payload, const Signer&, const Certificate* signer_cert);
/// EtsiTs103097Data-SignedExternalPayload: extDataHash = SHA-256 of external_payload
std::optional<ByteBuffer> sign_external(vanetza::security::Backend&, vanetza::Clock::time_point now,
const ByteBuffer& external_payload, const Signer&,
const Certificate& signer_cert);
/// EtsiTs103097Data-Encrypted for one certificate recipient; aes_key/nonce generated, key returned
std::optional<ByteBuffer> encrypt_for(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key);
/// EtsiTs103097Data-Encrypted with pskRecipInfo for a known symmetric key
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend&, const std::array<std::uint8_t, 16>& aes_key, const ByteBuffer& plaintext);
/// Decrypt an EtsiTs103097Data-Encrypted addressed to a certificate (certRecipInfo) with its private encryption key
std::optional<ByteBuffer> decrypt_as_recipient(vanetza::security::Backend&, EciesBackend&, const Certificate& recipient,
const PrivateKey& encryption_key, const ByteBuffer& encoded,
std::array<std::uint8_t, 16>* aes_key = nullptr);
/// Decrypt an EtsiTs103097Data-Encrypted whose pskRecipInfo matches aes_key
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend&, const std::array<std::uint8_t, 16>& aes_key, const ByteBuffer& encoded);
/// Verify an EtsiTs103097Data-Signed: self-signed with public_key, or by signer_cert when given; returns the payload
std::optional<ByteBuffer> verify_signed(vanetza::security::Backend&, const ByteBuffer& encoded, const PublicKey* self_key,
const Certificate* signer_cert, vanetza::ItsAid expected_psid);
// ---- TS 102 941 V2.2.1 clause 6.3: trust list and revocation list of a root CA ----------
//
// RcaCertificateTrustListMessage (clause 6.3.2, 6.3.4, A.2.7): EtsiTs103097Data-Signed over an
// EtsiTs102941Data{certificateTrustListRca ToBeSignedRcaCtl}, signed with the RCA's key, the
// signer carrying the RCA certificate, psid = CTL service (TS 102 965 Table A.1, 624), the RCA
// certificate holding the CTL appPermissions (TS 102 941 Table B.3: 0138 for a root CTL).
// CertificateRevocationListMessage (clause 6.3.3): the same over
// EtsiTs102941Data{certificateRevocationList ToBeSignedCrl}, psid = CRL service (622).
// Clause 6.3.6: an ITS-S accepts either only when it verifies as signed by its RCA; it then
// takes the EA/AA entries as trusted issuers and the CRL entries as revoked.
using Time32 = std::uint32_t; // IEEE Std 1609.2 Time32, seconds since 2004-01-01 00:00:00 TAI
struct TrustListEntries {
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
std::vector<Authority> ea, aa;
std::vector<DistributionCentre> dc;
};
/// FullCtl (isFullCtl true, ctlCommands add only) of an RCA, version 1; ctl_sequence 0..255
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,
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
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,
Time32 next_update);
struct RcaTrustList {
std::uint8_t sequence = 0;
Time32 next_update = 0;
bool full = true;
std::vector<Certificate> ea, aa; // added entries (issuer of each: the RCA, checked)
std::vector<TrustListEntries::DistributionCentre> dc;
std::vector<HashedId8> deleted; // DeltaCtl delete commands (certificates)
std::vector<std::string> deleted_dc;
};
/// Clause 6.3.6: the message verifies as signed by rca (signer certificate equal to rca,
/// psid 624, rca permitted for the CTL service), decodes as an RCA CTL of version 1 and every
/// 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);
// 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 {
Time32 this_update = 0, next_update = 0;
std::vector<HashedId8> revoked;
};
/// the same for a CRL (psid 622, rca permitted for the CRL service)
std::optional<RevocationList> parse_crl(vanetza::security::Backend&, const ByteBuffer& message, const Certificate& rca);
/// Clause 6.3.6: the EA/AA entries become trusted issuers (TrustConfiguration::add_authority);
/// returns the number added (entries already known are not counted)
std::size_t apply(const RcaTrustList&, microbu_v2x::security::TrustConfiguration&);
/// 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
std::size_t apply(const RevocationList&, const Certificate& rca, microbu_v2x::security::TrustConfiguration&);
} // 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
@@ -0,0 +1,164 @@
#pragma once
#include <microbu_v2x/security.hpp>
#include <vanetza/common/its_aid.hpp>
#include <optional>
#include <utility>
#include <vector>
/** SF-SAP language binding: TS 102 723-9 V1.1.1 (interface between the
* security entity and the facilities layer). Tables 10 to 21 carry the same
* parameters as the SN-SAP identifier-change primitives of TS 102 723-8, and
* clause 4.1.5 allows one security entity to serve several layers: the SF
* primitives below are served by the same IdChangeService instance the GN
* core subscribes to. TS 103 300-3 V2.3.1 clause 5.3.5 requires the VRU
* basic service to subscribe, stop generating VAMs on PREPARE, resume after
* COMMIT with a new StationId, and to use the lock for elevated-hazard
* situations. The facilities-side subscriber may run in the same task, in
* another task or process, or on another device; the library defines no
* transport, only these bindings.
*
* SF-SIGN/-VERIFY/-ENCRYPT/-DECRYPT/-ENCAP/-DECAP (Tables 2 to 9, 24 to 27)
* are declared as parameter types only: for messages carried over BTP and
* GeoNetworking the security envelope is applied at the GeoNetworking layer
* (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.
*/
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:
// one security entity serves several layers), under the SF-SAP names.
using security::Identifier;
using security::IdChangeCommand;
using security::LockHandle;
using security::SubscriptionHandle;
/// Table 10: SF-IDCHANGE-SUBSCRIBE.request
struct SF_IDCHANGE_SUBSCRIBE_request {
security::IdChangeHook idchange_event_hook; // Mandatory, signature of clause 5.2.6
vanetza::ByteBuffer subscriber_data; // Optional
};
/// Table 11: SF-IDCHANGE-SUBSCRIBE.confirm
struct SF_IDCHANGE_SUBSCRIBE_confirm { SubscriptionHandle subscription; };
/// Table 12: SF-IDCHANGE-EVENT.indication (the hook arguments)
struct SF_IDCHANGE_EVENT_indication {
IdChangeCommand command;
Identifier id;
vanetza::ByteBuffer subscriber_data;
};
/// Table 13: SF-IDCHANGE-EVENT.response
struct SF_IDCHANGE_EVENT_response { bool return_code; };
/// Table 14: SF-IDCHANGE-UNSUBSCRIBE.request; Table 15 confirm carries no parameter
struct SF_IDCHANGE_UNSUBSCRIBE_request { SubscriptionHandle subscription; };
/// Tables 16/17: SF-IDCHANGE-TRIGGER.request/.confirm carry no parameter
struct SF_IDCHANGE_TRIGGER_request {};
/// Table 18: SF-ID-LOCK.request
struct SF_ID_LOCK_request { std::uint8_t Duration; };
/// Table 19: SF-ID-LOCK.confirm
struct SF_ID_LOCK_confirm { LockHandle lock_handle; };
/// Table 20: SF-ID-UNLOCK.request; Table 21 confirm carries no parameter
struct SF_ID_UNLOCK_request { LockHandle lock_handle; };
/// Clause 5.2.11 / Table 22 (message example): SF-LOG-SECURITY-EVENT.request
using SF_LOG_SECURITY_EVENT_request = security::SecurityEvent;
/// TS 102 723-9 V1.1.1 clause 5.2.5: SF-IDCHANGE-SUBSCRIBE (Tables 10/11)
inline SF_IDCHANGE_SUBSCRIBE_confirm SF_IDCHANGE_SUBSCRIBE_request_submit(security::IdChangeService& service,
SF_IDCHANGE_SUBSCRIBE_request primitive) {
return {service.subscribe(std::move(primitive.idchange_event_hook), std::move(primitive.subscriber_data))};
}
/// Clause 5.2.7: SF-IDCHANGE-UNSUBSCRIBE (Tables 14/15)
inline Result SF_IDCHANGE_UNSUBSCRIBE_request_submit(security::IdChangeService& service,
SF_IDCHANGE_UNSUBSCRIBE_request primitive) {
return service.unsubscribe(primitive.subscription);
}
/// Clause 5.2.8: SF-IDCHANGE-TRIGGER (Tables 16/17)
inline Result SF_IDCHANGE_TRIGGER_request_submit(security::IdChangeService& service, SF_IDCHANGE_TRIGGER_request) {
return service.trigger();
}
/// Clause 5.2.9: SF-ID-LOCK (Tables 18/19), Duration in seconds 0..255
inline SF_ID_LOCK_confirm SF_ID_LOCK_request_submit(security::IdChangeService& service, SF_ID_LOCK_request primitive) {
return {service.lock(primitive.Duration)};
}
/// Clause 5.2.10: SF-ID-UNLOCK (Tables 20/21)
inline Result SF_ID_UNLOCK_request_submit(security::IdChangeService& service, SF_ID_UNLOCK_request primitive) {
return service.unlock(primitive.lock_handle);
}
/// Clause 5.2.11: SF-LOG-SECURITY-EVENT (Tables 22/23)
inline void SF_LOG_SECURITY_EVENT_request_submit(security::SecurityEntity& entity,
SF_LOG_SECURITY_EVENT_request primitive) {
entity.log_security_event(std::move(primitive));
}
// ---- Parameter types only (see the header comment) -------------------------
/// Table 2: SF-SIGN.request
struct SF_SIGN_request {
std::size_t tbs_message_length = 0;
vanetza::ByteBuffer tbs_message;
vanetza::ItsAid its_aid = 0;
std::size_t permissions_length = 0;
vanetza::ByteBuffer Permissions; // <= 31 octets, SSP of the ITS-AID
vanetza::ByteBuffer context_information; // Optional
std::optional<std::uint64_t> key_handle; // Optional
};
/// Table 3: SF-SIGN.confirm
struct SF_SIGN_confirm { std::size_t sec_message_length = 0; vanetza::ByteBuffer sec_message; };
/// Table 4: SF-VERIFY.request
struct SF_VERIFY_request {
std::size_t sec_header_length = 0;
vanetza::ByteBuffer sec_header;
std::size_t message_length = 0;
vanetza::ByteBuffer message;
};
/// Table 5: SF-VERIFY.confirm (report values of TS 102 723-8 Table 27 / vanetza::security::VerificationReport)
struct SF_VERIFY_confirm {
vanetza::security::VerificationReport report;
std::optional<security::HashedId8> certificate_id;
std::size_t its_aid_length = 0;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
};
/// Table 6: SF-ENCRYPT.request
struct SF_ENCRYPT_request {
std::size_t tbe_payload_length = 0;
vanetza::ByteBuffer tbe_payload;
std::size_t target_id_list_length = 0;
std::vector<security::HashedId8> target_id_list;
vanetza::ByteBuffer context_information; // Optional
};
/// Table 7: SF-ENCRYPT.confirm
struct SF_ENCRYPT_confirm { std::size_t encrypted_message_length = 0; vanetza::ByteBuffer encrypted_message; };
/// Table 8: SF-DECRYPT.request
struct SF_DECRYPT_request { std::size_t encrypted_message_length = 0; vanetza::ByteBuffer encrypted_message; };
/// Table 9: SF-DECRYPT.confirm
struct SF_DECRYPT_confirm {
enum class Report : std::uint8_t { SUCCESS, UNENCRYPTED_MESSAGE, DECRYPTION_ERROR, INCOMPATIBLE_PROTOCOL };
std::size_t plaintext_message_length = 0;
vanetza::ByteBuffer plaintext_message;
Report report;
};
/// Table 24: SF-ENCAP.request (identical parameters to SN-ENCAP.request)
struct SF_ENCAP_request {
std::size_t tbe_packet_length = 0;
vanetza::ByteBuffer tbe_packet;
std::optional<std::uint16_t> sec_services;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
vanetza::ByteBuffer context_information;
std::vector<security::HashedId8> target_id_list;
};
/// Table 25: SF-ENCAP.confirm
struct SF_ENCAP_confirm { std::size_t sec_packet_length = 0; vanetza::ByteBuffer sec_packet; };
/// Table 26: SF-DECAP.request
struct SF_DECAP_request { std::size_t sec_packet_length = 0; vanetza::ByteBuffer sec_packet; };
/// Table 27: SF-DECAP.confirm
struct SF_DECAP_confirm {
std::size_t plaintext_packet_length = 0;
vanetza::ByteBuffer plaintext_packet;
vanetza::security::VerificationReport report;
std::optional<security::HashedId8> certificate_id;
std::size_t its_aid_length = 0;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
};
} // namespace microbu_v2x::SF_SAP
@@ -0,0 +1,189 @@
#pragma once
#include <microbu_v2x/security.hpp>
#include <vanetza/common/byte_buffer_sink.hpp>
#include <vanetza/net/osi_layer.hpp>
#include <vanetza/net/packet.hpp>
#include <vanetza/security/secured_message.hpp>
#include <boost/iostreams/stream.hpp>
#include <optional>
#include <utility>
#include <vector>
/** SN-SAP language binding: TS 102 723-8 V2.0.0 clause 5 incorporates V1.1.1,
* whose Tables 10 to 27 define the primitives below. '-' and '.' in primitive
* names become '_'; parameters keep the tables' names in snake_case. The
* *_submit functions are thin calls into the security entity, like
* NF_SAP::BTP_DATA_request_submit. Inside the stack the GeoNetworking router
* calls the same entity directly (vanetza::security::SecurityEntity), so
* these bindings serve a caller in another task, process or device and the
* test adapters; the library defines no transport for that.
*/
namespace microbu_v2x::SN_SAP {
// 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.
using security::Identifier;
using security::IdChangeCommand;
using security::LockHandle;
using security::SubscriptionHandle;
/// TS 102 723-8 V1.1.1 Table 10: SN-IDCHANGE-SUBSCRIBE.request
struct SN_IDCHANGE_SUBSCRIBE_request {
security::IdChangeHook idchange_event_hook; // Mandatory: hook function, signature of clause 5.2.6
vanetza::ByteBuffer subscriber_data; // Optional: passed back on every hook call
};
/// Table 11: SN-IDCHANGE-SUBSCRIBE.confirm
struct SN_IDCHANGE_SUBSCRIBE_confirm {
SubscriptionHandle subscription; // INTEGER 0 to 2^64-1
};
/// Table 12: SN-IDCHANGE-EVENT.indication (the arguments of the hook function)
struct SN_IDCHANGE_EVENT_indication {
IdChangeCommand command; // PREPARE, COMMIT, ABORT, DEREG (clause 6.3)
Identifier id; // OCTET STRING, 8 octets: id to be set
vanetza::ByteBuffer subscriber_data; // Optional
};
/// Table 13: SN-IDCHANGE-EVENT.response
struct SN_IDCHANGE_EVENT_response {
bool return_code; // acknowledgement to the given command
};
/// Table 14: SN-IDCHANGE-UNSUBSCRIBE.request; Table 15 confirm carries no parameter
struct SN_IDCHANGE_UNSUBSCRIBE_request {
SubscriptionHandle subscription;
};
/// Table 16/17: SN-IDCHANGE-TRIGGER.request/.confirm carry no parameter
struct SN_IDCHANGE_TRIGGER_request {};
/// Table 18: SN-ID-LOCK.request
struct SN_ID_LOCK_request {
std::uint8_t Duration; // INTEGER 0 to 2^8-1: number of seconds to lock
};
/// Table 19: SN-ID-LOCK.confirm
struct SN_ID_LOCK_confirm {
LockHandle lock_handle; // INTEGER 0 to 2^64-1: handle to unlock manually
};
/// Table 20: SN-ID-UNLOCK.request; Table 21 confirm carries no parameter
struct SN_ID_UNLOCK_request {
LockHandle lock_handle;
};
/// Table 22: SN-LOG-SECURITY-EVENT.request; Table 23 confirm carries no parameter
using SN_LOG_SECURITY_EVENT_request = security::SecurityEvent;
/// Table 24: SN-ENCAP.request (the GeoNetworking source fills it per TS 103 836-4-1 V2.2.1 Table 34)
struct SN_ENCAP_request {
std::size_t tbe_packet_length = 0; // Mandatory: length of tbe_packet
vanetza::ByteBuffer tbe_packet; // Mandatory: packet to encapsulate (Common Header onwards)
std::optional<std::uint16_t> sec_services; // Optional: security service(s) to invoke
vanetza::ItsAid its_aid = 0; // Mandatory: ITS-AID selecting the security profile
vanetza::ByteBuffer permissions; // Mandatory: SSP associated with the ITS-AID (<= 31 octets)
vanetza::ByteBuffer context_information; // Optional: opaque, see security::context
std::vector<security::HashedId8> target_id_list; // Optional: recipients (encryption is not implemented)
};
/// Table 25: SN-ENCAP.confirm
struct SN_ENCAP_confirm {
std::size_t sec_packet_length = 0;
vanetza::ByteBuffer sec_packet; // the Secured Packet, EtsiTs103097Data (COER)
};
/// Table 26: SN-DECAP.request
struct SN_DECAP_request {
std::size_t sec_packet_length = 0;
vanetza::ByteBuffer sec_packet; // EtsiTs103097Data (COER), without the GN basic header
};
/// TS 102 723-8 Table 27: SN-DECAP.confirm carries the verification outcome.
/// Callers enforce their receive policy using report and the signer permissions.
/// Verification requires V2X_SECURITY_VERIFY. Builds without it report
/// CONFIGURATION_PROBLEM for signed messages and UNSIGNED_MESSAGE otherwise.
struct SN_DECAP_confirm {
std::size_t plaintext_packet_length = 0;
vanetza::ByteBuffer plaintext_packet;
vanetza::security::VerificationReport report = vanetza::security::VerificationReport::Configuration_Problem;
std::optional<security::HashedId8> certificate_id;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
};
/// TS 102 723-8 V1.1.1 clause 5.2.5: SN-IDCHANGE-SUBSCRIBE (Tables 10/11)
inline SN_IDCHANGE_SUBSCRIBE_confirm SN_IDCHANGE_SUBSCRIBE_request_submit(security::IdChangeService& service,
SN_IDCHANGE_SUBSCRIBE_request primitive) {
return {service.subscribe(std::move(primitive.idchange_event_hook), std::move(primitive.subscriber_data))};
}
/// Clause 5.2.7: SN-IDCHANGE-UNSUBSCRIBE (Tables 14/15)
inline Result SN_IDCHANGE_UNSUBSCRIBE_request_submit(security::IdChangeService& service,
SN_IDCHANGE_UNSUBSCRIBE_request primitive) {
return service.unsubscribe(primitive.subscription);
}
/// Clause 5.2.8: SN-IDCHANGE-TRIGGER (Tables 16/17)
inline Result SN_IDCHANGE_TRIGGER_request_submit(security::IdChangeService& service, SN_IDCHANGE_TRIGGER_request) {
return service.trigger();
}
/// Clause 5.2.9: SN-ID-LOCK (Tables 18/19), Duration in seconds 0..255
inline SN_ID_LOCK_confirm SN_ID_LOCK_request_submit(security::IdChangeService& service, SN_ID_LOCK_request primitive) {
return {service.lock(primitive.Duration)};
}
/// Clause 5.2.10: SN-ID-UNLOCK (Tables 20/21)
inline Result SN_ID_UNLOCK_request_submit(security::IdChangeService& service, SN_ID_UNLOCK_request primitive) {
return service.unlock(primitive.lock_handle);
}
/// Clause 5.2.11: SN-LOG-SECURITY-EVENT (Tables 22/23)
inline void SN_LOG_SECURITY_EVENT_request_submit(security::SecurityEntity& entity,
SN_LOG_SECURITY_EVENT_request primitive) {
entity.log_security_event(std::move(primitive));
}
/** SN-ENCAP over raw octets. Result::invalid_argument on a length mismatch or a
* permissions field beyond 31 octets, Result::unsupported when sec_services or
* target_id_list request anything but signing, Result::security_unavailable
* when the entity refuses (no usable ticket, identifier change pending). */
/// Clause 5.2.12: SN-ENCAP (Tables 24/25); clause 5.2.13 SN-DECAP (Tables 26/27) below
inline Result SN_ENCAP_request_submit(vanetza::security::SecurityEntity& entity, SN_ENCAP_request primitive,
SN_ENCAP_confirm& confirm) {
if (primitive.tbe_packet_length != primitive.tbe_packet.size() || primitive.tbe_packet.empty() ||
primitive.permissions.size() > 31) return Result::invalid_argument;
if (primitive.sec_services || !primitive.target_id_list.empty()) return Result::unsupported;
vanetza::security::SignRequest request;
request.plain_message[vanetza::OsiLayer::Network] = std::move(primitive.tbe_packet);
request.its_aid = primitive.its_aid;
request.permissions = std::move(primitive.permissions);
request.context_information = std::move(primitive.context_information);
auto result = entity.encapsulate_packet(vanetza::security::EncapRequest {std::move(request)});
const auto* secured = result.secured_message();
if (!secured) return Result::security_unavailable;
confirm.sec_packet.clear();
vanetza::byte_buffer_sink sink(confirm.sec_packet);
boost::iostreams::stream_buffer<vanetza::byte_buffer_sink> stream(sink);
vanetza::OutputArchive archive(stream);
vanetza::security::serialize(archive, *secured);
stream.pubsync();
confirm.sec_packet_length = confirm.sec_packet.size();
return Result::accepted;
}
/** SN-DECAP over raw octets (clause 5.2.13). Result::invalid_argument on a length
* mismatch or when sec_packet is not a decodable EtsiTs103097Data; otherwise the
* confirm carries the entity's report (never Success, see SN_DECAP_confirm). */
inline Result SN_DECAP_request_submit(vanetza::security::SecurityEntity& entity, const SN_DECAP_request& primitive,
SN_DECAP_confirm& confirm) {
if (primitive.sec_packet_length != primitive.sec_packet.size() || primitive.sec_packet.empty())
return Result::invalid_argument;
vanetza::security::v3::SecuredMessage message;
if (!message.decode(primitive.sec_packet)) return Result::invalid_argument;
vanetza::security::SecuredMessage variant {std::move(message)};
auto result = entity.decapsulate_packet(vanetza::security::DecapRequest {vanetza::security::SecuredMessageView {variant}});
confirm = SN_DECAP_confirm {};
if (const auto* report = boost::get<vanetza::security::VerificationReport>(&result.report)) confirm.report = *report;
if (result.certificate_id) confirm.certificate_id = *result.certificate_id;
confirm.its_aid = result.its_aid;
confirm.permissions = std::move(result.permissions);
if (const auto* packet = boost::get<vanetza::CohesivePacket>(&result.plaintext_payload)) {
confirm.plaintext_packet.assign(packet->buffer().begin(), packet->buffer().end());
} else if (const auto* chunks = boost::get<vanetza::ChunkPacket>(&result.plaintext_payload)) {
for (auto layer : vanetza::osi_layer_range<vanetza::OsiLayer::Network, vanetza::OsiLayer::Application>()) {
const auto& part = (*chunks)[layer];
vanetza::ByteBuffer bytes;
part.convert(bytes);
confirm.plaintext_packet.insert(confirm.plaintext_packet.end(), bytes.begin(), bytes.end());
}
}
confirm.plaintext_packet_length = confirm.plaintext_packet.size();
return Result::accepted;
}
} // namespace microbu_v2x::SN_SAP
@@ -0,0 +1,174 @@
#pragma once
#include <microbu_v2x/access.hpp>
#include <microbu_v2x/id_change.hpp>
#include <vanetza/common/manual_runtime.hpp>
#include <vanetza/common/position_fix.hpp>
#include <vanetza/dcc/channel_load.hpp>
#include <vanetza/geonet/data_request.hpp>
#include <vanetza/geonet/data_indication.hpp>
#include <vanetza/geonet/data_confirm.hpp>
#include <vanetza/security/security_entity.hpp>
#include <functional>
#include <memory>
#include <optional>
namespace microbu_v2x {
enum class BtpType { a, b };
/** NF-SAP / BTP-DATA.request: TS 103 836-5-1 V2.1.1 Annex A.2
* 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.
* All port numbers are HOST order. data.size() is the Length parameter.
* Omitted GN parameters inherit the configured MIB. No magic sentinel values.
*/
struct BtpRequest {
BtpType type = BtpType::b;
std::optional<std::uint16_t> source_port;
std::uint16_t destination_port = 0;
std::optional<std::uint16_t> destination_port_info;
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
vanetza::geonet::DestinationVariant destination = nullptr;
vanetza::geonet::CommunicationProfile communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
// The selected security entity implements this profile; ITS-AID, SSP and
// context information are SN-ENCAP inputs (TS 102 723-8 V2.0.0 clause 5 /
// V1.1.1 Table 24) that GN forwards unchanged (TS 103 836-4-1 V2.2.1
// Table 34, Annex J.2 "Security context information").
std::optional<std::uint32_t> security_profile;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
vanetza::ByteBuffer security_context; // see security::context for the values this library defines
std::optional<vanetza::geonet::Lifetime> maximum_lifetime;
std::optional<vanetza::geonet::DataRequest::Repetition> repetition;
std::optional<unsigned> maximum_hop_limit;
vanetza::geonet::TrafficClass traffic_class;
vanetza::ByteBuffer data;
};
/** 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,
* traffic class, remaining lifetime and hop limit. Owns the received payload.
*/
struct BtpIndication {
BtpType type;
std::optional<std::uint16_t> source_port;
std::uint16_t destination_port;
std::optional<std::uint16_t> destination_port_info;
vanetza::geonet::DataIndication gn;
std::optional<vanetza::ByteBuffer> certificate_id;
vanetza::ByteBuffer data;
};
/** 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). Unlike BtpRequest, data is the raw SDU
* 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
* as Result::unsupported, matching Stack::request(BtpRequest).
*/
struct GnRequest {
vanetza::geonet::TransportType transport = vanetza::geonet::TransportType::SHB;
vanetza::geonet::DestinationVariant destination = nullptr; // Area for GBC, null for SHB
vanetza::geonet::CommunicationProfile communication_profile = vanetza::geonet::CommunicationProfile::ITS_G5;
vanetza::geonet::TrafficClass traffic_class;
std::optional<vanetza::geonet::Lifetime> maximum_lifetime;
std::optional<unsigned> maximum_hop_limit;
std::optional<vanetza::geonet::DataRequest::Repetition> repetition;
vanetza::ItsAid its_aid = 0;
vanetza::ByteBuffer permissions;
vanetza::ByteBuffer security_context; // TS 103 836-4-1 V2.2.1 Annex J.2 Security context information
vanetza::ByteBuffer data;
};
/** GN-DATA.indication for a packet whose Common Header next_header is "Any"
* (no upper protocol registered by BtpRequest's handler), TS 103 836-4-1
* V2.2.1 clause 9.3. gn retains the complete router indication.
*/
struct GnIndication {
vanetza::geonet::DataIndication gn;
vanetza::ByteBuffer data;
};
struct StackConfig {
vanetza::geonet::MIB mib;
std::size_t maximum_gnpdu = 4096;
std::uint32_t security_profile = 0;
AlDataRequest radio_parameters;
StackConfig();
};
/** Portable network/transport module for the NF-SAP entry point.
* The caller serializes all calls in ONE task/event loop, including reception,
* clock advancement and destruction. Access/SecurityEntity must outlive Stack.
* 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.
* 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
* configuration): with itsGnLocalAddrConfMethod == Anonymous and an
* IdChangeService, the GN core subscribes at construction and unsubscribes at
* destruction. On COMMIT the GN address MID becomes the 48 least significant
* bits of the new HashedId8 (TS 102 940 V2.1.1 clause 6.5), with the I/G bit
* cleared (a source address is individual) and the U/L bit set; the link-layer
* source follows because every request takes it from the GN address. Between
* PREPARE and COMMIT the forwarding buffers are flushed and request() returns
* Result::identity_change_pending (TS 102 723-8 clause 6.3.1.3). The access
* adapter is not notified by the stack: it may subscribe to the same service
* (TS 102 723-7 analogy for the IN-SAP side is not defined here).
*/
class Stack {
public:
using Receive = std::function<void(BtpIndication)>;
using ReceiveGn = std::function<void(GnIndication)>;
using Report = std::function<void(Result)>;
/** id_change may be omitted: when security is a microbu_v2x::security::SecurityEntity
* its own identifier-change service is used. */
Stack(StackConfig, vanetza::ManualRuntime&, Access&,
vanetza::security::SecurityEntity* security = nullptr,
security::IdChangeService* id_change = nullptr);
~Stack();
Stack(const Stack&) = delete;
Stack& operator=(const Stack&) = delete;
Result request(BtpRequest);
Result request(GnRequest);
Result indicate(AlDataIndication);
Result update_position(const vanetza::PositionFix&);
Result advance(vanetza::Clock::time_point);
void on_receive(Receive);
void on_receive_gn(ReceiveGn);
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;
/// the identifier-change service this stack subscribed to, nullptr without one
security::IdChangeService* id_change();
vanetza::security::SecurityEntity* security_entity();
/// true between PREPARE and COMMIT (or ABORT) of an identifier change
bool identity_change_pending() const;
/// GeoNetworking address currently in use (MID follows the identifier change)
const vanetza::geonet::Address& address() const;
/** Managed address configuration (TS 103 836-4-1 V2.2.1 clause 10.2.1.3.3): the N&T
* management entity updates the GN address with an unsolicited CORE_MMT.response
* (MN_SAP::CORE_MMT_response_apply). Result::unsupported with Auto (10.2.1.2) or
* Anonymous (10.2.1.4) configuration, identity_change_pending during a change. */
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).
* 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
* reserved zero field, and every received SHB packet's DCC-MCO updates LocTEX-G5
* (already unconditional in the upstream router once itsGnIfType is ITS_G5, which this
* 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
* the caller should feed with global_channel_busy_ratio() when available, else the same
* local measurement.
*/
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.
void report_tx_power(unsigned dbm);
/** CBR_G (TS 103 836-4-2 clause 5.3), once at least one 100 ms aggregation cycle has run;
* std::nullopt beforehand (no neighbour data collected yet). */
std::optional<vanetza::dcc::ChannelLoad> global_channel_busy_ratio() const;
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
}
@@ -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);
}
@@ -0,0 +1,27 @@
# Kconfig hides this backend on other SoCs; this independent guard also rejects
# forced/stale configurations. The private ABI is qualified per SDK version.
if(NOT IDF_TARGET STREQUAL "esp32c5")
message(FATAL_ERROR "Integrated ITS-G5 radio requires IDF_TARGET=esp32c5")
endif()
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")
endif()
set(_otm_source "${V2X_PORT}/third_party/otm/main/tx_custom.c")
if(NOT EXISTS "${_otm_source}")
message(FATAL_ERROR "Initialize the OpenTrafficMap submodule before selecting the C5 radio")
endif()
file(READ "${_otm_source}" _otm)
string(REPLACE "\r\n" "\n" _otm "${_otm}")
string(SHA256 _otm_hash "${_otm}")
if(NOT _otm_hash STREQUAL "cb1dccfef96912ca59275e8a9102f41f56925b94a19d4a4629082aaeb779be1b")
message(FATAL_ERROR "OpenTrafficMap transmitter differs from the reviewed source revision")
endif()
# Keep the upstream checkout immutable. The sole logic patch preserves the
# actual driver submission result, which upstream discarded. ESP_OK still
# means submission, not independent observation of transmission on air.
string(REPLACE " ieee80211_post_hmac_tx(eb);"
" result = ieee80211_post_hmac_tx(eb);" _otm "${_otm}")
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")
target_sources(${V2X_TARGET} PRIVATE "${V2X_PORT}/src/c5_radio.cpp" "${_otm_generated}")
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));
}
}
@@ -0,0 +1,246 @@
#include <microbu_v2x/backend_mbedtls.hpp>
#include <microbu_v2x/ecc.hpp>
#include <vanetza/security/sha.hpp>
#include <psa/crypto.h>
#include <algorithm>
#include <deque>
#include <stdexcept>
namespace microbu_v2x {
using namespace vanetza::security;
namespace {
psa_ecc_family_t family(KeyType type) {
switch (type) {
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
case KeyType::BrainpoolP256r1:
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
default: throw std::runtime_error("unsupported key type");
}
}
std::size_t curve_bits(KeyType type) { return key_length(type) * 8; }
struct ScopedKey {
mbedtls_svc_key_id_t id = 0;
~ScopedKey() { if (id) psa_destroy_key(id); }
};
// SEC 1 uncompressed encoding of a generic public key, recovering y when compressed.
vanetza::ByteBuffer public_key_octets(const PublicKey& key) {
Uncompressed point;
switch (key.compression) {
case KeyCompression::NoCompression:
point.x = key.x; point.y = key.y;
break;
case KeyCompression::Y0:
case KeyCompression::Y1: {
auto recovered = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
if (!recovered) throw std::runtime_error("public key is not on the curve");
point = std::move(*recovered);
break;
}
default: throw std::runtime_error("unsupported point compression");
}
if (point.x.size() != key_length(key.type) || point.y.size() != key_length(key.type))
throw std::runtime_error("public key coordinate length");
return ecc::encode_uncompressed(point);
}
// The digest handed in is the SHA-256/SHA-384 output IEEE Std 1609.2 clause 5.3.1 prescribes
// for the curve, so the operation names that hash: implementations that accelerate ECDSA
// (ESP-IDF's PSA driver for the ESP32-C5 ECDSA peripheral, CONFIG_MBEDTLS_HARDWARE_ECDSA_VERIFY)
// only take PSA_ALG_ECDSA(PSA_ALG_SHA_256/384), never PSA_ALG_ECDSA_ANY, which falls back to
// software. Keys are imported with the wildcard policy so either form is permitted.
psa_algorithm_t ecdsa_algorithm(std::size_t digest_octets) {
switch (digest_octets) {
case 32: return PSA_ALG_ECDSA(PSA_ALG_SHA_256);
case 48: return PSA_ALG_ECDSA(PSA_ALG_SHA_384);
default: return PSA_ALG_ECDSA_ANY;
}
}
mbedtls_svc_key_id_t import_public(KeyType type, const vanetza::ByteBuffer& sec1) {
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(family(type)));
psa_set_key_bits(&attributes, curve_bits(type));
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
mbedtls_svc_key_id_t id = 0;
if (psa_import_key(&attributes, sec1.data(), sec1.size(), &id) != PSA_SUCCESS)
throw std::runtime_error("PSA public key import failed");
return id;
}
vanetza::ByteBuffer raw_signature(mbedtls_svc_key_id_t key, KeyType type, const vanetza::ByteBuffer& digest) {
vanetza::ByteBuffer signature(2 * key_length(type));
std::size_t length = 0;
const auto status = psa_sign_hash(key, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
signature.data(), signature.size(), &length);
if (status != PSA_SUCCESS || length != signature.size()) throw std::runtime_error("PSA ECDSA signing failed");
return signature;
}
bool verify_raw(KeyType type, const vanetza::ByteBuffer& sec1, const vanetza::ByteBuffer& digest,
const vanetza::ByteBuffer& r, const vanetza::ByteBuffer& s) {
const auto n = key_length(type);
if (r.size() != n || s.size() != n) return false;
vanetza::ByteBuffer signature;
signature.reserve(2 * n);
signature.insert(signature.end(), r.begin(), r.end());
signature.insert(signature.end(), s.begin(), s.end());
ScopedKey key;
try { key.id = import_public(type, sec1); } catch (const std::runtime_error&) { return false; }
return psa_verify_hash(key.id, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
signature.data(), signature.size()) == PSA_SUCCESS;
}
} // namespace
class BackendMbedTls::Impl {
public:
struct Entry { KeyType type; vanetza::ByteBuffer secret; mbedtls_svc_key_id_t id; };
std::deque<Entry> cache;
std::size_t capacity = 4;
~Impl() { for (auto& entry : cache) psa_destroy_key(entry.id); }
mbedtls_svc_key_id_t signing_key(KeyType type, const vanetza::ByteBuffer& secret) {
if (secret.size() != key_length(type)) throw std::runtime_error("private key length");
for (auto it = cache.begin(); it != cache.end(); ++it) {
if (it->type == type && it->secret == secret) {
Entry hit = std::move(*it);
cache.erase(it);
cache.push_front(std::move(hit)); // most recently used first
return cache.front().id;
}
}
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
psa_set_key_bits(&attributes, curve_bits(type));
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
mbedtls_svc_key_id_t id = 0;
if (psa_import_key(&attributes, secret.data(), secret.size(), &id) != PSA_SUCCESS)
throw std::runtime_error("PSA private key import failed");
while (cache.size() >= capacity) {
psa_destroy_key(cache.back().id);
cache.pop_back();
}
cache.push_front(Entry {type, secret, id});
return id;
}
};
BackendMbedTls::BackendMbedTls() : impl_(std::make_unique<Impl>()) {
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
}
BackendMbedTls::~BackendMbedTls() = default;
void BackendMbedTls::set_key_cache_size(std::size_t size) { impl_->capacity = std::max<std::size_t>(1, size); }
EcdsaSignature BackendMbedTls::sign_data(const ecdsa256::PrivateKey& key, const vanetza::ByteBuffer& data) {
const auto digest = calculate_sha256_digest(data.data(), data.size());
const vanetza::ByteBuffer secret(key.key.begin(), key.key.end());
const auto id = impl_->signing_key(KeyType::NistP256, secret);
auto raw = raw_signature(id, KeyType::NistP256, vanetza::ByteBuffer(digest.begin(), digest.end()));
EcdsaSignature signature;
X_Coordinate_Only r;
r.x.assign(raw.begin(), raw.begin() + 32);
signature.R = std::move(r);
signature.s.assign(raw.begin() + 32, raw.end());
return signature;
}
Signature BackendMbedTls::sign_digest(const PrivateKey& key, const vanetza::ByteBuffer& digest) {
const auto id = impl_->signing_key(key.type, key.key);
auto raw = raw_signature(id, key.type, digest);
const auto n = key_length(key.type);
Signature signature;
signature.type = key.type;
signature.r.assign(raw.begin(), raw.begin() + n);
signature.s.assign(raw.begin() + n, raw.end());
return signature;
}
bool BackendMbedTls::verify_data(const ecdsa256::PublicKey& key, const vanetza::ByteBuffer& data,
const EcdsaSignature& signature) {
const auto digest = calculate_sha256_digest(data.data(), data.size());
Uncompressed point;
point.x.assign(key.x.begin(), key.x.end());
point.y.assign(key.y.begin(), key.y.end());
return verify_raw(KeyType::NistP256, ecc::encode_uncompressed(point),
vanetza::ByteBuffer(digest.begin(), digest.end()),
convert_for_signing(signature.R), signature.s);
}
bool BackendMbedTls::verify_digest(const PublicKey& key, const vanetza::ByteBuffer& digest, const Signature& signature) {
if (key.type != signature.type) return false;
try {
return verify_raw(key.type, public_key_octets(key), digest, signature.r, signature.s);
} catch (const std::runtime_error&) {
return false;
}
}
boost::optional<Uncompressed> BackendMbedTls::decompress_point(const EccPoint& ecc_point) {
struct Visitor : boost::static_visitor<boost::optional<Uncompressed>> {
boost::optional<Uncompressed> operator()(const X_Coordinate_Only&) const { return boost::none; }
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_0& p) const {
return ecc::decompress(KeyType::NistP256, p.x, false);
}
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_1& p) const {
return ecc::decompress(KeyType::NistP256, p.x, true);
}
boost::optional<Uncompressed> operator()(const Uncompressed& p) const { return p; }
};
Visitor visitor;
return boost::apply_visitor(visitor, ecc_point);
}
vanetza::ByteBuffer BackendMbedTls::calculate_hash(HashAlgorithm algorithm, const vanetza::ByteBuffer& data) {
psa_algorithm_t alg;
std::size_t size;
switch (algorithm) {
case HashAlgorithm::SHA256: alg = PSA_ALG_SHA_256; size = 32; break;
case HashAlgorithm::SHA384: alg = PSA_ALG_SHA_384; size = 48; break;
default: return {};
}
vanetza::ByteBuffer digest(size);
std::size_t written = 0;
if (psa_hash_compute(alg, data.data(), data.size(), digest.data(), digest.size(), &written) != PSA_SUCCESS ||
written != size) throw std::runtime_error("PSA hash failed");
return digest;
}
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_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
psa_set_key_bits(&attributes, n * 8);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA_ANY);
ScopedKey key;
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
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;
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
throw std::runtime_error("PSA private key export failed");
vanetza::ByteBuffer sec1(1 + 2 * n);
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");
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
return pair;
}
} // namespace microbu_v2x
@@ -0,0 +1,165 @@
#include <microbu_v2x/c5_radio.hpp>
#include <microbu_v2x/its_g5_frame.hpp>
#include <esp_event.h>
#include <esp_wifi.h>
#include <hal/modem_syscon_ll.h>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstring>
#include <mutex>
extern "C" {
void phy_11p_set(int, int);
void phy_change_channel(int, int, int, int);
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);
}
namespace microbu_v2x {
class C5Radio::Impl {
public:
struct Raw {
std::uint16_t length;
std::int8_t rssi;
std::uint32_t timestamp;
std::uint8_t bytes[2346];
};
C5RadioConfig config;
QueueHandle_t queue = nullptr;
bool initialized = false, started = false, own_event_loop = false;
std::uint16_t sequence = 0;
std::atomic<std::uint32_t> dropped {0};
static Impl* active;
static std::mutex callback_mutex;
explicit Impl(C5RadioConfig c) : config(c) {}
static void receive(void* buffer, wifi_promiscuous_pkt_type_t type) {
if (!buffer || type != WIFI_PKT_DATA) return;
const auto* packet = static_cast<const wifi_promiscuous_pkt_t*>(buffer);
if (packet->rx_ctrl.rx_state != 0) return;
// esp_wifi_he_types.h documents sig_len on this chip as "the length of the
// reception MPDU", not "MPDU + FCS" as older-chip ESP-IDF documentation
// states; measured on real hardware, it is consistently 4 bytes longer than
// the actual frame, and those 4 trailing bytes are a fixed, content-independent
// 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
// already passed a real hardware FCS check by the time it reaches this callback
// -- see components/microbu_v2x/tools/radio_pair.py's docstring for the full evidence.
const auto length = packet->rx_ctrl.sig_len;
std::lock_guard<std::mutex> lock(callback_mutex);
if (!active || !active->queue) return;
if (length < 38 || length > sizeof(Raw::bytes)) { ++active->dropped; return; }
Raw raw {};
raw.length = length; raw.rssi = packet->rx_ctrl.rssi;
raw.timestamp = packet->rx_ctrl.timestamp;
std::memcpy(raw.bytes, packet->payload, length);
if (xQueueSend(active->queue, &raw, 0) != pdTRUE) ++active->dropped;
}
};
C5Radio::Impl* C5Radio::Impl::active = nullptr;
std::mutex C5Radio::Impl::callback_mutex;
C5Radio::C5Radio(C5RadioConfig c) : impl_(std::make_unique<Impl>(c)) {}
C5Radio::~C5Radio() { stop(); }
esp_err_t C5Radio::start() {
auto& p = *impl_;
const auto& c = p.config;
if (p.initialized) return ESP_ERR_INVALID_STATE;
if (c.channel_number < 172 || c.channel_number > 184 || c.channel_number % 2 ||
!std::isfinite(c.transmit_power_dbm) || c.transmit_power_dbm < 2 || c.transmit_power_dbm > 20 ||
std::floor(c.transmit_power_dbm * 4) != c.transmit_power_dbm * 4 ||
c.receive_queue_length == 0 || c.receive_queue_length > 32) return ESP_ERR_INVALID_ARG;
{
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
if (Impl::active) return ESP_ERR_INVALID_STATE;
p.queue = xQueueCreate(c.receive_queue_length, sizeof(Impl::Raw));
if (!p.queue) return ESP_ERR_NO_MEM;
Impl::active = &p;
}
auto result = esp_event_loop_create_default();
p.own_event_loop = result == ESP_OK;
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { stop(); return result; }
// OpenTrafficMap main/main.c and cmd_sniffer.c establish the FE clock and
// NON_NGV_10 PHY mode. These private calls are SDK-specific, not ETSI SAPs.
modem_syscon_ll_enable_fe_40m_clock(&MODEM_SYSCON, true);
wifi_init_config_t wifi = WIFI_INIT_CONFIG_DEFAULT();
wifi.nvs_enable = 0;
result = esp_wifi_init(&wifi);
if (result != ESP_OK) { stop(); return result; }
p.initialized = true;
auto attempt = [&](esp_err_t r) { if (result == ESP_OK) result = r; };
attempt(esp_wifi_set_storage(WIFI_STORAGE_RAM));
attempt(esp_wifi_set_mode(WIFI_MODE_STA));
if (result == ESP_OK) { result = esp_wifi_start(); p.started = result == ESP_OK; }
if (result != ESP_OK) { stop(); return result; }
attempt(esp_wifi_set_band_mode(WIFI_BAND_MODE_5G_ONLY));
attempt(esp_wifi_set_ps(WIFI_PS_NONE));
attempt(esp_wifi_set_max_tx_power(static_cast<std::int8_t>(c.transmit_power_dbm * 4)));
wifi_promiscuous_filter_t filter {};
filter.filter_mask = WIFI_PROMIS_FILTER_MASK_DATA;
attempt(esp_wifi_set_promiscuous_filter(&filter));
attempt(esp_wifi_set_promiscuous_rx_cb(Impl::receive));
attempt(esp_wifi_set_promiscuous(true));
if (result != ESP_OK) { stop(); return result; }
phy_11p_set(1, 0); // 10 MHz; never infer PHY width from WIFI_BW20 below.
phy_change_channel(5000 + 5 * c.channel_number, 1, 0, 0);
return ESP_OK;
}
void C5Radio::stop() {
if (!impl_) return;
auto& p = *impl_;
if (p.started) esp_wifi_set_promiscuous(false);
{
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
if (Impl::active == &p) Impl::active = nullptr;
if (p.queue) { vQueueDelete(p.queue); p.queue = nullptr; }
}
if (p.started) esp_wifi_stop();
if (p.initialized) esp_wifi_deinit();
if (p.own_event_loop) esp_event_loop_delete_default();
p.started = p.initialized = p.own_event_loop = false;
}
Result C5Radio::request(AlDataRequest request) {
auto& p = *impl_;
if (!p.started) return Result::rejected;
if (!p.config.laboratory_transmission) return Result::unsupported;
// Reject controls this fixed-channel backend cannot honour. In particular,
// do not silently reinterpret an AL_DATA bandwidth or transceiver mode.
if (request.bandwidth_mhz != 10 || request.channel_number != p.config.channel_number ||
request.transceiver_id != 0 || request.transceiver_mode || request.datastream_id ||
request.transmit_power_dbm != p.config.transmit_power_dbm) return Result::unsupported;
constexpr wifi_phy_rate_t rates[] = {WIFI_PHY_RATE_6M, WIFI_PHY_RATE_9M, WIFI_PHY_RATE_12M,
WIFI_PHY_RATE_18M, WIFI_PHY_RATE_24M, WIFI_PHY_RATE_36M, WIFI_PHY_RATE_48M, WIFI_PHY_RATE_54M};
const auto index = static_cast<unsigned>(request.mcs);
if (index >= std::size(rates)) return Result::invalid_argument;
vanetza::ByteBuffer bytes;
const auto encoded = its_g5::encode_frame(request, p.sequence, bytes);
if (encoded != Result::accepted) return encoded;
p.sequence = (p.sequence + 1) & 4095;
wifi_tx_rate_config_t rate {};
rate.phymode = WIFI_PHY_MODE_11A; rate.rate = rates[index];
// Legacy OFDM rate identifiers are halved by the 10 MHz PHY mode.
// The driver consumes the frame synchronously into its own ebuf.
const auto result = esp_wifi_80211_tx_custom(WIFI_IF_STA, bytes.data(), bytes.size(), false,
&rate, WIFI_BAND_5G, WIFI_BW20);
return result == ESP_OK ? Result::accepted : result == ESP_ERR_NO_MEM ? Result::resource_limit : Result::rejected;
}
void C5Radio::poll(const Receive& receive, const Capture& capture) {
auto& p = *impl_;
if (!p.queue) return;
Impl::Raw raw {};
// Bound work per poll even if the radio continuously fills the queue.
for (unsigned i = 0; i < p.config.receive_queue_length && xQueueReceive(p.queue, &raw, 0) == pdTRUE; ++i) {
if (capture) capture(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.length), raw.rssi, raw.timestamp);
AlDataIndication ind;
if (its_g5::decode_frame(raw.bytes, raw.length, true, ind) != Result::accepted) continue;
ind.channel_number = p.config.channel_number;
ind.received_power_dbm = raw.rssi;
// The SDK does not provide channel-busy time here. CBR remains absent;
// counting received packets would not be a valid CBR measurement.
if (receive) receive(std::move(ind));
}
}
std::uint32_t C5Radio::dropped_frames() const { return impl_->dropped.load(); }
}
@@ -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
@@ -0,0 +1,82 @@
#include <microbu_v2x/ecc.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <algorithm>
#include <iterator>
namespace microbu_v2x::ecc {
using namespace vanetza::security;
namespace {
// Fixed width, no heap: a 384-bit product needs 768 bits before reduction.
using Int = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<
1024, 1024, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
// FIPS 186-4 D.1.2.3 (P-256), RFC 5639 3.4 (brainpoolP256r1) and 3.6 (brainpoolP384r1).
// The host regression compares every constant with OpenSSL's built-in groups.
constexpr CurveParameters curves[] = {
{KeyType::NistP256, 32,
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"},
{KeyType::BrainpoolP256r1, 32,
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377",
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9",
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6"},
{KeyType::BrainpoolP384r1, 48,
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53",
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826",
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11"},
};
Int from_hex(const char* hex) { return Int(std::string("0x") + hex); }
Int from_bytes(const vanetza::ByteBuffer& bytes) {
Int value;
boost::multiprecision::import_bits(value, bytes.begin(), bytes.end(), 8, true);
return value;
}
vanetza::ByteBuffer to_bytes(const Int& value, std::size_t octets) {
vanetza::ByteBuffer out;
boost::multiprecision::export_bits(value, std::back_inserter(out), 8, true);
if (out.size() > octets) return {};
out.insert(out.begin(), octets - out.size(), 0);
return out;
}
} // namespace
const CurveParameters* curve(KeyType type) {
for (const auto& c : curves) if (c.type == type) return &c;
return nullptr;
}
boost::optional<Uncompressed> decompress(KeyType type, const vanetza::ByteBuffer& x_bytes, bool y_odd) {
const auto* c = curve(type);
if (!c || x_bytes.size() != c->octets) return boost::none;
const Int p = from_hex(c->p), a = from_hex(c->a), b = from_hex(c->b);
const Int x = from_bytes(x_bytes);
if (x >= p) return boost::none;
// rhs = x^3 + a*x + b (mod p)
Int rhs = (x * x) % p;
rhs = (rhs * x) % p;
rhs = (rhs + (a * x) % p) % p;
rhs = (rhs + b) % p;
// p = 3 (mod 4): sqrt(n) = n^((p+1)/4) (mod p) when n is a quadratic residue.
Int y = boost::multiprecision::powm(rhs, (p + 1) / 4, p);
if ((y * y) % p != rhs) return boost::none; // x is not on the curve
if (static_cast<bool>(y & 1) != y_odd) y = p - y;
Uncompressed point;
point.x = x_bytes;
point.y = to_bytes(y, c->octets);
if (point.y.empty()) return boost::none;
return point;
}
vanetza::ByteBuffer encode_uncompressed(const Uncompressed& point) {
vanetza::ByteBuffer out;
out.reserve(1 + point.x.size() + point.y.size());
out.push_back(0x04);
out.insert(out.end(), point.x.begin(), point.x.end());
out.insert(out.end(), point.y.begin(), point.y.end());
return out;
}
} // namespace microbu_v2x::ecc
@@ -0,0 +1,135 @@
#include <microbu_v2x/ecies_mbedtls.hpp>
#include <microbu_v2x/ecc.hpp>
#include <psa/crypto.h>
#include <stdexcept>
namespace microbu_v2x::pki {
using namespace vanetza::security;
namespace {
psa_ecc_family_t family_of(KeyType type) {
switch (type) {
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
case KeyType::BrainpoolP256r1:
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
default: throw std::runtime_error("unsupported key type");
}
}
struct ScopedKey {
mbedtls_svc_key_id_t id = 0;
~ScopedKey() { if (id) psa_destroy_key(id); }
};
mbedtls_svc_key_id_t import_raw(psa_key_type_t type, std::size_t bits, psa_key_usage_t usage, psa_algorithm_t alg,
const std::uint8_t* data, std::size_t length) {
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, type);
if (bits) psa_set_key_bits(&attributes, bits);
psa_set_key_usage_flags(&attributes, usage);
psa_set_key_algorithm(&attributes, alg);
mbedtls_svc_key_id_t id = 0;
if (psa_import_key(&attributes, data, length, &id) != PSA_SUCCESS) throw std::runtime_error("PSA key import failed");
return id;
}
} // namespace
EciesMbedTls::EciesMbedTls() {
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
}
KeyPair EciesMbedTls::generate_key(KeyType type) {
const std::size_t n = key_length(type);
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(type)));
psa_set_key_bits(&attributes, n * 8);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDH);
ScopedKey key;
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
KeyPair pair;
pair.priv.type = type;
pair.priv.key.resize(n);
std::size_t length = 0;
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
throw std::runtime_error("PSA private key export failed");
ByteBuffer sec1(1 + 2 * n);
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");
pair.pub.type = type;
pair.pub.compression = KeyCompression::NoCompression;
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
return pair;
}
std::optional<ByteBuffer> EciesMbedTls::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
const std::size_t n = key_length(own.type);
if (own.key.size() != n || peer.x.size() != n || peer.y.size() != n) return std::nullopt;
try {
ScopedKey key;
key.id = import_raw(PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(own.type)), n * 8, PSA_KEY_USAGE_DERIVE, PSA_ALG_ECDH,
own.key.data(), own.key.size());
Uncompressed point;
point.x = peer.x; point.y = peer.y;
const ByteBuffer sec1 = ecc::encode_uncompressed(point);
ByteBuffer secret(n);
std::size_t length = 0;
// PSA raw ECDH output is the x coordinate of the shared point (PSA Crypto API 1.1, PSA_ALG_ECDH)
if (psa_raw_key_agreement(PSA_ALG_ECDH, key.id, sec1.data(), sec1.size(), secret.data(), secret.size(), &length) != PSA_SUCCESS ||
length != n) return std::nullopt;
return secret;
} catch (const std::exception&) {
return std::nullopt;
}
}
ByteBuffer EciesMbedTls::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
ScopedKey mac_key;
mac_key.id = import_raw(PSA_KEY_TYPE_HMAC, 0, PSA_KEY_USAGE_SIGN_MESSAGE, PSA_ALG_HMAC(PSA_ALG_SHA_256),
key.data(), key.size());
ByteBuffer out(32);
std::size_t length = 0;
if (psa_mac_compute(mac_key.id, PSA_ALG_HMAC(PSA_ALG_SHA_256), data.data(), data.size(), out.data(), out.size(), &length) != PSA_SUCCESS ||
length != 32) throw std::runtime_error("PSA HMAC failed");
return out;
}
ByteBuffer EciesMbedTls::random(std::size_t octets) {
ByteBuffer out(octets);
if (octets && psa_generate_random(out.data(), out.size()) != PSA_SUCCESS) throw std::runtime_error("PSA random failed");
return out;
}
bool EciesMbedTls::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& plaintext, ByteBuffer& out) {
try {
ScopedKey aes;
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_ENCRYPT, PSA_ALG_CCM, key.data(), key.size());
out.resize(plaintext.size() + 16);
std::size_t length = 0;
if (psa_aead_encrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, plaintext.data(), plaintext.size(),
out.data(), out.size(), &length) != PSA_SUCCESS || length != out.size()) { out.clear(); return false; }
return true;
} catch (const std::exception&) {
return false;
}
}
bool EciesMbedTls::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& in, ByteBuffer& plaintext) {
if (in.size() < 16) return false;
try {
ScopedKey aes;
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_DECRYPT, PSA_ALG_CCM, key.data(), key.size());
plaintext.resize(in.size() - 16);
std::size_t length = 0;
if (psa_aead_decrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, in.data(), in.size(),
plaintext.data(), plaintext.size(), &length) != PSA_SUCCESS || length != plaintext.size()) {
plaintext.clear();
return false;
}
return true;
} catch (const std::exception&) {
return false;
}
}
} // namespace microbu_v2x::pki
@@ -0,0 +1,121 @@
#include <microbu_v2x/ecies_openssl.hpp>
#include <microbu_v2x/ecc.hpp>
#include <vanetza/security/openssl_wrapper.hpp>
#include <openssl/ec.h>
#include <openssl/ecdh.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/obj_mac.h>
#include <openssl/rand.h>
#include <memory>
#include <stdexcept>
namespace microbu_v2x::pki {
using namespace vanetza::security;
namespace {
int nid_of(KeyType type) {
switch (type) {
case KeyType::NistP256: return NID_X9_62_prime256v1;
case KeyType::BrainpoolP256r1: return NID_brainpoolP256r1;
case KeyType::BrainpoolP384r1: return NID_brainpoolP384r1;
default: return NID_undef;
}
}
struct CipherContext {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
~CipherContext() { EVP_CIPHER_CTX_free(ctx); }
};
} // namespace
KeyPair EciesOpenSsl::generate_key(KeyType type) {
openssl::Key key(nid_of(type));
openssl::check(EC_KEY_generate_key(key));
const std::size_t n = key_length(type);
KeyPair pair;
pair.priv.type = type;
pair.priv.key.resize(n);
BN_bn2binpad(EC_KEY_get0_private_key(key), pair.priv.key.data(), n);
openssl::BigNumber x, y;
openssl::BigNumberContext ctx;
openssl::check(EC_POINT_get_affine_coordinates(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key), x, y, ctx));
pair.pub.type = type;
pair.pub.compression = KeyCompression::NoCompression;
pair.pub.x.resize(n); pair.pub.y.resize(n);
BN_bn2binpad(x, pair.pub.x.data(), n);
BN_bn2binpad(y, pair.pub.y.data(), n);
return pair;
}
std::optional<ByteBuffer> EciesOpenSsl::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
try {
openssl::Key key(nid_of(own.type));
openssl::BigNumber d(own.key);
openssl::check(EC_KEY_set_private_key(key, d));
openssl::Group group(nid_of(peer.type));
openssl::Point point(group);
openssl::BigNumberContext ctx;
openssl::check(EC_POINT_set_affine_coordinates(group, point, openssl::BigNumber(peer.x), openssl::BigNumber(peer.y), ctx));
openssl::check(EC_POINT_is_on_curve(group, point, ctx) == 1);
ByteBuffer secret(key_length(own.type));
// no KDF here: the raw x coordinate is the ECIES shared secret input to KDF2
const int written = ECDH_compute_key(secret.data(), secret.size(), point, key, nullptr);
if (written != static_cast<int>(secret.size())) return std::nullopt;
return secret;
} catch (const std::exception&) {
return std::nullopt;
}
}
ByteBuffer EciesOpenSsl::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
ByteBuffer out(32);
unsigned length = 0;
if (!HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()), data.data(), data.size(), out.data(), &length) ||
length != 32) throw std::runtime_error("HMAC-SHA256 failed");
return out;
}
ByteBuffer EciesOpenSsl::random(std::size_t octets) {
ByteBuffer out(octets);
if (octets && RAND_bytes(out.data(), static_cast<int>(octets)) != 1) throw std::runtime_error("RAND_bytes failed");
return out;
}
bool EciesOpenSsl::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& plaintext, ByteBuffer& out) {
CipherContext c;
if (!c.ctx) return false;
int length = 0;
if (EVP_EncryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, nullptr) != 1 ||
EVP_EncryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
EVP_EncryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(plaintext.size())) != 1) return false;
out.resize(plaintext.size() + 16);
if (EVP_EncryptUpdate(c.ctx, out.data(), &length, plaintext.data(), static_cast<int>(plaintext.size())) != 1 ||
length != static_cast<int>(plaintext.size())) return false;
int final_length = 0;
if (EVP_EncryptFinal_ex(c.ctx, out.data() + length, &final_length) != 1) return false;
if (EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_GET_TAG, 16, out.data() + plaintext.size()) != 1) return false;
return true;
}
bool EciesOpenSsl::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
const ByteBuffer& in, ByteBuffer& plaintext) {
if (in.size() < 16) return false;
const std::size_t payload = in.size() - 16;
CipherContext c;
if (!c.ctx) return false;
int length = 0;
if (EVP_DecryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, const_cast<std::uint8_t*>(in.data() + payload)) != 1 ||
EVP_DecryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
EVP_DecryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(payload)) != 1) return false;
plaintext.resize(payload);
// CCM verifies the tag inside this update; a mismatch returns 0
if (EVP_DecryptUpdate(c.ctx, plaintext.data(), &length, in.data(), static_cast<int>(payload)) != 1 ||
length != static_cast<int>(payload)) { plaintext.clear(); return false; }
return true;
}
} // namespace microbu_v2x::pki
@@ -0,0 +1,27 @@
// ESP32-C5 boot repair, linked into every application that uses this component on
// that target (the component's CMake forces the object in with "-u").
//
// ESP-IDF's esp_system/port/soc/esp32c5/system_internal.c documents that the C5
// ROM's UART initialisation misses the UART0 function clock enable
// (PCR_UART0_SCLK_EN, "does not reset with the UART module") and repairs it inside
// esp_restart(). A reset triggered over USB-Serial/JTAG or JTAG (esptool's
// DTR/RTS toggle, OpenOCD, a debugger) bypasses esp_restart(), so once an
// application has left the bit cleared the next boot's ROM stage waits forever
// for PCR_UART0_READY and the board stays unreachable until a power cycle.
// Setting the bit early in every boot keeps warm resets working regardless of what
// the application does with UART0; the cost is one register write.
#include "sdkconfig.h"
#if CONFIG_IDF_TARGET_ESP32C5
#include <esp_err.h>
#include <esp_private/startup_internal.h>
#include <soc/pcr_reg.h>
#include <soc/soc.h>
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);
return ESP_OK;
}
// Referenced through "-u" so the linker keeps this object and its init entry.
void v2x_esp32c5_rom_uart_clock_link(void) {}
#endif
@@ -0,0 +1,70 @@
#include <microbu_v2x/facilities.hpp>
#include <vanetza/common/its_aid.hpp>
#include <utility>
namespace microbu_v2x::facilities {
Descriptor descriptor(Kind kind) {
// TS 103 248 BTP well-known ports; CDD MessageId values. The service
// protocolVersion comes from each service ASN.1 definition: CAM/DENM 2,
// VAM 3 (TS 103 300-3 V2.3.1 ItsPduHeaderVam). Release != protocolVersion.
switch (kind) {
case Kind::cam: return {2001, 2, 2};
case Kind::denm: return {2002, 1, 2};
// TS 103 248 V2.4.1, Table 1: VA (VAM) is 2018; 2009 is CP (CPM).
case Kind::vam: return {2018, 16, 3};
}
return {0, 0, 0};
}
template<class Message>
Result check(Kind kind, const vanetza::ByteBuffer& data) {
Message message;
if (!message.decode_exact(data) || !message.validate()) return Result::invalid_argument;
const auto expected = descriptor(kind);
if (message->header.messageId != expected.message_id ||
message->header.protocolVersion != expected.protocol_version) return Result::invalid_argument;
return Result::accepted;
}
Result validate_pdu(Kind kind, const vanetza::ByteBuffer& data, std::size_t maximum) {
if (data.empty() || data.size() > maximum) return Result::invalid_argument;
try {
switch (kind) {
#if V2X_CAM
case Kind::cam: return check<Cam>(kind, data);
#endif
#if V2X_DENM
case Kind::denm: return check<Denm>(kind, data);
#endif
#if V2X_VAM
case Kind::vam: return check<Vam>(kind, data);
#endif
default: return Result::unsupported;
}
} catch (const std::bad_alloc&) { return Result::resource_limit; }
catch (const std::exception&) { return Result::invalid_argument; }
}
#if V2X_NETWORK
Result send(Stack& stack, Kind kind, vanetza::ByteBuffer bytes, BtpRequest req) {
auto result = validate_pdu(kind, bytes, stack.config().mib.itsGnMaxSduSize - 4u);
if (result != Result::accepted) return result;
req.type = BtpType::b;
req.source_port.reset();
req.destination_port = descriptor(kind).port;
req.destination_port_info = 0;
if (req.its_aid == 0) {
// SN-ENCAP its_aid selects the security profile: TS 102 965 V2.4.1 Table A.1
// (CA 36, DEN 37, VRU 638); TS 103 300-3 V2.3.1 clause 6.5.1 for VAMs.
switch (kind) {
case Kind::cam: req.its_aid = vanetza::aid::CA; break;
case Kind::denm: req.its_aid = vanetza::aid::DEN; break;
case Kind::vam: req.its_aid = vanetza::aid::VRU; break;
}
}
if (kind == Kind::vam && req.permissions.empty()) {
// TS 103 300-3 V2.3.1 clause 6.5.2: BitmapSsp whose first octet, value 1, is the SSP version.
req.permissions = {0x01};
}
req.data = std::move(bytes);
return stack.request(std::move(req));
}
#endif
}
@@ -0,0 +1,225 @@
// 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.
#include <microbu_v2x/security.hpp>
#include <chrono>
#include <map>
#include <memory>
#include <set>
#include <vector>
namespace microbu_v2x::security {
using namespace vanetza;
class IdentityManager::Impl : public std::enable_shared_from_this<IdentityManager::Impl> {
public:
struct Subscription { IdChangeHook hook; ByteBuffer data; };
struct Round {
std::uint64_t id;
IdChangeCommand phase; // PREPARE or COMMIT
Identifier new_identifier;
std::set<SubscriptionHandle> outstanding;
};
Runtime& runtime;
CertificatePool& pool;
std::map<SubscriptionHandle, Subscription> subscriptions;
SubscriptionHandle next_subscription = 1;
std::map<LockHandle, Clock::time_point> locks;
LockHandle next_lock = 1;
std::unique_ptr<Round> round;
std::uint64_t round_counter = 0;
bool pending_trigger = false;
Clock::duration response_timeout = std::chrono::milliseconds(500);
std::function<void(const Identifier&)> committed;
Statistics stats;
unsigned notify_depth = 0; // hooks run re-entrantly; phase changes wait until delivery completed
char round_timer_scope = 0;
char lock_timer_scope = 0;
Impl(Runtime& rt, CertificatePool& p) : runtime(rt), pool(p) {}
Identifier current() const {
const auto* ticket = pool.current();
return ticket ? ticket->digest : Identifier {};
}
bool locked() const { return !locks.empty(); }
// Table 13 return_code carrier handed to hooks for PREPARE and COMMIT.
class Responder : public IdChangeResponder {
public:
Responder(std::weak_ptr<Impl> owner, std::uint64_t round, SubscriptionHandle handle) :
owner_(std::move(owner)), round_(round), handle_(handle) {}
void respond(bool return_code) override {
if (auto impl = owner_.lock()) impl->handle_response(round_, handle_, return_code);
}
private:
std::weak_ptr<Impl> owner_;
std::uint64_t round_;
SubscriptionHandle handle_;
};
// Deliver a command to every current subscriber; hooks may respond, unsubscribe or
// subscribe re-entrantly, so iterate over a snapshot and re-check membership.
void notify(IdChangeCommand command, const Identifier& id, bool expect_response) {
std::vector<SubscriptionHandle> handles;
for (const auto& entry : subscriptions) handles.push_back(entry.first);
if (expect_response && round) round->outstanding.insert(handles.begin(), handles.end());
const auto round_id = round ? round->id : 0;
++notify_depth;
for (auto handle : handles) {
// An abort raised by an earlier hook ends this round: nobody else gets PREPARE/COMMIT.
if (expect_response && (!round || round->id != round_id)) break;
auto it = subscriptions.find(handle);
if (it == subscriptions.end()) {
if (round && round->id == round_id) round->outstanding.erase(handle);
continue;
}
std::shared_ptr<IdChangeResponder> responder;
if (expect_response) responder = std::make_shared<Responder>(weak_from_this(), round_id, handle);
IdChangeHook hook = it->second.hook;
ByteBuffer data = it->second.data;
hook(command, id, data, responder);
}
--notify_depth;
if (expect_response && notify_depth == 0 && round && round->id == round_id) {
if (round->outstanding.empty()) advance();
else arm_round_timer();
}
}
void arm_round_timer() {
runtime.cancel(&round_timer_scope);
runtime.schedule(response_timeout, [this](Clock::time_point) { on_round_timeout(); }, &round_timer_scope);
}
void try_start() {
if (!pending_trigger || locked() || round) return;
const auto* next = pool.next_valid(runtime.now());
pending_trigger = false;
if (!next) return; // nothing to change to; trigger() already reported this
round = std::make_unique<Round>(Round {++round_counter, IdChangeCommand::PREPARE, next->digest, {}});
notify(IdChangeCommand::PREPARE, round->new_identifier, true); // advances or arms the timer itself
}
void handle_response(std::uint64_t round_id, SubscriptionHandle handle, bool return_code) {
if (!round || round->id != round_id) return;
if (round->outstanding.erase(handle) == 0) return;
if (!return_code) {
if (round->phase == IdChangeCommand::PREPARE) { abort(); return; }
++stats.commit_failures; // COMMIT cannot be rolled back (Figure 11); recorded
}
if (round->outstanding.empty() && notify_depth == 0) advance();
}
void advance() {
runtime.cancel(&round_timer_scope);
if (round->phase == IdChangeCommand::PREPARE) {
round->phase = IdChangeCommand::COMMIT;
pool.select(round->new_identifier);
notify(IdChangeCommand::COMMIT, round->new_identifier, true); // finishes or arms the timer
} else {
finish();
}
}
void finish() {
runtime.cancel(&round_timer_scope);
const Identifier id = round->new_identifier;
round.reset();
++stats.committed;
if (committed) committed(id);
try_start(); // a trigger queued during this round
}
void abort() {
runtime.cancel(&round_timer_scope);
const Identifier id = round->new_identifier;
round.reset();
++stats.aborted;
notify(IdChangeCommand::ABORT, id, false); // Figures 12/13
}
void on_round_timeout() {
if (!round) return;
++stats.timed_out;
if (round->phase == IdChangeCommand::PREPARE) {
abort();
} else {
stats.commit_failures += static_cast<unsigned>(round->outstanding.size());
finish();
}
}
void arm_lock_timer() {
runtime.cancel(&lock_timer_scope);
if (locks.empty()) return;
Clock::time_point earliest = locks.begin()->second;
for (const auto& lock : locks) earliest = std::min(earliest, lock.second);
runtime.schedule(earliest, [this](Clock::time_point) { on_lock_timer(); }, &lock_timer_scope);
}
void on_lock_timer() {
const auto now = runtime.now();
for (auto it = locks.begin(); it != locks.end();) {
if (it->second <= now) it = locks.erase(it); else ++it;
}
arm_lock_timer();
try_start();
}
};
IdentityManager::IdentityManager(Runtime& rt, CertificatePool& pool) : impl_(std::make_shared<Impl>(rt, pool)) {}
IdentityManager::~IdentityManager() {
impl_->runtime.cancel(&impl_->round_timer_scope);
impl_->runtime.cancel(&impl_->lock_timer_scope);
impl_->round.reset();
impl_->notify(IdChangeCommand::DEREG, impl_->current(), false); // Figure 15
impl_->subscriptions.clear();
}
SubscriptionHandle IdentityManager::subscribe(IdChangeHook hook, ByteBuffer subscriber_data) {
const auto handle = impl_->next_subscription++;
impl_->subscriptions.emplace(handle, Impl::Subscription {std::move(hook), std::move(subscriber_data)});
return handle;
}
Result IdentityManager::unsubscribe(SubscriptionHandle handle) {
if (impl_->subscriptions.erase(handle) == 0) return Result::invalid_argument;
if (impl_->round && impl_->round->outstanding.erase(handle) && impl_->round->outstanding.empty() &&
impl_->notify_depth == 0)
impl_->advance();
return Result::accepted;
}
Result IdentityManager::trigger() {
if (!impl_->pool.next_valid(impl_->runtime.now())) return Result::rejected;
impl_->pending_trigger = true;
impl_->try_start();
return Result::accepted;
}
LockHandle IdentityManager::lock(std::uint8_t duration_seconds) {
const auto handle = impl_->next_lock++;
impl_->locks[handle] = impl_->runtime.now() + std::chrono::seconds(duration_seconds);
impl_->arm_lock_timer();
if (duration_seconds == 0) impl_->on_lock_timer(); // released at once
return handle;
}
Result IdentityManager::unlock(LockHandle handle) {
if (impl_->locks.erase(handle) == 0) return Result::invalid_argument;
impl_->arm_lock_timer();
impl_->try_start();
return Result::accepted;
}
Identifier IdentityManager::current_identifier() const { return impl_->current(); }
bool IdentityManager::change_pending() const { return static_cast<bool>(impl_->round); }
void IdentityManager::set_response_timeout(Clock::duration timeout) { impl_->response_timeout = timeout; }
void IdentityManager::on_committed(std::function<void(const Identifier&)> callback) { impl_->committed = std::move(callback); }
const IdentityManager::Statistics& IdentityManager::statistics() const { return impl_->stats; }
bool IdentityManager::locked() const { return impl_->locked(); }
} // namespace microbu_v2x::security
@@ -0,0 +1,37 @@
#include <microbu_v2x/its_g5_frame.hpp>
#include <algorithm>
namespace microbu_v2x::its_g5 {
namespace {
constexpr std::uint8_t snap[] = {0xaa, 0xaa, 0x03, 0, 0, 0, 0x89, 0x47};
}
Result encode_frame(const AlDataRequest& request, std::uint16_t sequence, vanetza::ByteBuffer& out) {
if (validate(request, maximum_gnpdu) != Result::accepted || sequence > 4095)
return Result::invalid_argument;
out.assign(34 + request.data.size(), 0);
out[0] = 0x88; // QoS Data; To DS=From DS=0 (OCB), no encryption at MAC.
std::copy(request.destination.octets.begin(), request.destination.octets.end(), out.begin() + 4);
std::copy(request.source.octets.begin(), request.source.octets.end(), out.begin() + 10);
std::fill(out.begin() + 16, out.begin() + 22, 0xff); // wildcard BSSID
out[22] = (sequence << 4) & 0xff; out[23] = sequence >> 4;
out[24] = request.priority; // TID carries IEEE 802.1D user priority.
std::copy(std::begin(snap), std::end(snap), out.begin() + 26);
std::copy(request.data.begin(), request.data.end(), out.begin() + 34);
return Result::accepted;
}
Result decode_frame(const std::uint8_t* data, std::size_t length, bool fcs, AlDataIndication& out) {
if (!data || length < 34 + (fcs ? 4u : 0u)) return Result::invalid_argument;
if (fcs) length -= 4;
// Only non-fragmented, unprotected QoS Data with the OCB three-address
// layout. Reject A-MSDU/HT-control rather than misinterpreting their offsets.
if (data[0] != 0x88 || (data[1] & 0xc7) || (data[22] & 0x0f) ||
(data[24] & 0x80) || !std::all_of(data + 16, data + 22, [](auto b) { return b == 0xff; }))
return Result::unsupported;
if (!std::equal(std::begin(snap), std::end(snap), data + 26)) return Result::unsupported;
if (length == 34 || length - 34 > maximum_gnpdu) return Result::invalid_argument;
std::copy(data + 4, data + 10, out.destination.octets.begin());
std::copy(data + 10, data + 16, out.source.octets.begin());
out.data.assign(data + 34, data + length);
return Result::accepted;
}
}
@@ -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
@@ -0,0 +1,137 @@
// Management-plane bindings: MN-SAP (TS 102 723-4, TS 103 836-4-1 Annex K,
// 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
// providers the application registers.
#include <microbu_v2x/mf_sap.hpp>
#include <microbu_v2x/mi_sap.hpp>
#include <microbu_v2x/mn_sap.hpp>
namespace microbu_v2x {
namespace {
// Shared GET/SET machinery: format check, access check, then the provider.
template<class No, class Param, class Error, class Provider>
void get_all(Provider* provider, const std::vector<No>& numbers, bool (*in_format)(No, std::uint32_t),
std::vector<Param>& out, std::vector<Error>& errors) {
for (auto no : numbers) {
std::uint32_t value = 0;
auto status = provider ? provider->get(no, value) : MN_SAP::ErrStatus::UNSUPPORTED;
if (status == MN_SAP::ErrStatus::SUCCESS && !in_format(no, value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
if (status == MN_SAP::ErrStatus::SUCCESS) out.push_back(Param {no, value});
else errors.push_back(Error {no, status});
}
}
template<class No, class Param, class Error, class Provider>
void set_all(Provider* provider, const std::vector<Param>& params, bool (*in_format)(No, std::uint32_t),
bool (*writable)(No), std::vector<Error>& errors) {
for (const auto& param : params) {
MN_SAP::ErrStatus status;
if (!writable(param.no)) status = MN_SAP::ErrStatus::READ_ONLY;
else if (!in_format(param.no, param.value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
else status = provider ? provider->set(param.no, param.value) : MN_SAP::ErrStatus::UNSUPPORTED;
if (status != MN_SAP::ErrStatus::SUCCESS) errors.push_back(Error {param.no, status});
}
}
} // namespace
namespace MN_SAP {
Result CORE_MMT_response_apply(Stack& stack, const CORE_MMT_response& response) {
if (!response.time && !response.local_position_vector && !response.geonetworking_address && !response.tc_mapping)
return Result::invalid_argument; // clause K.3: at least one parameter is present
if (response.time) {
const auto result = stack.advance(*response.time);
if (result != Result::accepted) return result;
}
if (response.local_position_vector) {
const auto result = stack.update_position(*response.local_position_vector);
if (result != Result::accepted) return result;
}
if (response.geonetworking_address) {
const auto result = stack.set_address(*response.geonetworking_address);
if (result != Result::accepted) return result;
}
if (response.tc_mapping) return Result::unsupported; // fixed TS 102 687 mapping in this port
return Result::accepted;
}
bool n_param_value_in_format(N_Param_No no, std::uint32_t value) {
switch (no) { // TS 103 175 Table 10 formats
case N_Param_No::GLOBAL_CBR:
case N_Param_No::LOCAL_CBR: return value <= 100;
case N_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
case N_Param_No::AVAILABLE_RESOURCE:
case N_Param_No::IDLE_TIME: return value <= 0xffff;
case N_Param_No::LAST_TRANSMIT_TIME: return true;
case N_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31; // bits 5..7 reserved
}
return false;
}
bool n_param_writable(N_Param_No no) {
return no == N_Param_No::CHANNEL_NUMBER || no == N_Param_No::IDLE_TIME || no == N_Param_No::TX_POWER_LEVEL_LIMIT;
}
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider* provider, const MN_GET_request& request) {
MN_GET_confirm confirm {request.nt_id, request.command_ref, {}, {}};
get_all<N_Param_No, N_Param, N_Error>(provider, request.n_param_no, n_param_value_in_format, confirm.n_param, confirm.errors);
return confirm;
}
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider* provider, const MN_SET_request& request) {
MN_SET_confirm confirm {request.nt_id, request.command_ref, {}};
set_all<N_Param_No, N_Param, N_Error>(provider, request.n_param, n_param_value_in_format, n_param_writable, confirm.errors);
return confirm;
}
} // namespace MN_SAP
namespace MF_SAP {
bool f_param_value_in_format(F_Param_No no, std::uint32_t value) {
switch (no) { // TS 103 175 Table 13 formats
case F_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
case F_Param_No::AVAILABLE_RESOURCE: return value <= 0xffff;
}
return false;
}
MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink* sink, const MF_SET_request& request) {
MF_SET_confirm confirm {request.fac_id, request.command_ref, {}};
for (const auto& param : request.f_param) {
ErrStatus status;
if (!f_param_value_in_format(param.no, param.value)) status = ErrStatus::INVALID_VALUE;
else status = sink ? sink->set(param.no, param.value) : ErrStatus::UNSUPPORTED;
if (status != ErrStatus::SUCCESS) confirm.errors.push_back(F_Error {param.no, status});
}
return confirm;
}
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink* sink, const MF_COMMAND_request& request) {
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED};
return sink->command(request);
}
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink* sink, const MF_REQUEST_request& request) {
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED, {}};
return sink->request(request);
}
} // namespace MF_SAP
namespace MI_SAP {
bool i_param_value_in_format(I_Param_No no, std::uint32_t value) {
switch (no) { // TS 103 175 Table 5 formats
case I_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
case I_Param_No::LOCAL_CBR: return value <= 100;
case I_Param_No::MESSAGE_LENGTH: return value <= 0xff;
case I_Param_No::LAST_TRANSMIT_TIME: return true;
case I_Param_No::IDLE_TIME: return value <= 0xffff;
case I_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31;
}
return false;
}
bool i_param_writable(I_Param_No no) {
return no == I_Param_No::CHANNEL_NUMBER || no == I_Param_No::IDLE_TIME || no == I_Param_No::TX_POWER_LEVEL_LIMIT;
}
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider* provider, const MI_GET_request& request) {
MI_GET_confirm confirm {request.mac_id, request.command_ref, {}, {}};
get_all<I_Param_No, I_Param, I_Error>(provider, request.i_param_no, i_param_value_in_format, confirm.i_param, confirm.errors);
return confirm;
}
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider* provider, const MI_SET_request& request) {
MI_SET_confirm confirm {request.mac_id, request.command_ref, {}};
set_all<I_Param_No, I_Param, I_Error>(provider, request.i_param, i_param_value_in_format, i_param_writable, confirm.errors);
return confirm;
}
} // namespace MI_SAP
} // namespace microbu_v2x
@@ -0,0 +1,50 @@
#include <microbu_v2x/nvs_credential_store.hpp>
#include <nvs.h>
namespace microbu_v2x::security {
namespace {
// nvs_open/nvs_close around one operation; NVS handles are cheap and the store is stateless
class Handle {
public:
Handle(const std::string& ns, nvs_open_mode_t mode) { error_ = nvs_open(ns.c_str(), mode, &handle_); }
~Handle() { if (error_ == ESP_OK) nvs_close(handle_); }
esp_err_t error() const { return error_; }
nvs_handle_t get() const { return handle_; }
private:
nvs_handle_t handle_ = 0;
esp_err_t error_ = ESP_FAIL;
};
} // namespace
Result NvsCredentialStore::save(const StoredCredentials& credentials) {
const ByteBuffer bundle = encode(credentials);
Handle nvs(namespace_, NVS_READWRITE);
if (nvs.error() != ESP_OK) return Result::rejected;
if (nvs_set_blob(nvs.get(), key_.c_str(), bundle.data(), bundle.size()) != ESP_OK) return Result::resource_limit;
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
}
Result NvsCredentialStore::load(StoredCredentials& credentials) {
Handle nvs(namespace_, NVS_READONLY);
if (nvs.error() != ESP_OK) return Result::rejected; // no such namespace yet: nothing stored
std::size_t size = 0;
const esp_err_t probe = nvs_get_blob(nvs.get(), key_.c_str(), nullptr, &size);
if (probe == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
if (probe != ESP_OK || size == 0) return Result::rejected;
ByteBuffer bundle(size);
if (nvs_get_blob(nvs.get(), key_.c_str(), bundle.data(), &size) != ESP_OK) return Result::rejected;
bundle.resize(size);
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
}
Result NvsCredentialStore::erase() {
Handle nvs(namespace_, NVS_READWRITE);
if (nvs.error() != ESP_OK) return Result::rejected;
const esp_err_t error = nvs_erase_key(nvs.get(), key_.c_str());
if (error == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
if (error != ESP_OK) return Result::rejected;
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
}
} // 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 = &target;
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
@@ -0,0 +1,163 @@
// 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.
#include <microbu_v2x/security.hpp>
#include <vanetza/common/position_fix.hpp>
#include <vanetza/security/peer_request_tracker.hpp>
#include <vanetza/security/sign_service.hpp>
#include <vanetza/security/v2/basic_elements.hpp>
#include <vanetza/security/v3/secured_message.hpp>
#include <chrono>
#include <map>
namespace vanetza::security::v3 {
// Defined in the upstream sign_header_policy.cpp translation unit (not declared in its header):
// ThreeDLocation from a PositionFix (IEEE 1609.2 clause 6.3.10 encoding).
asn1::ThreeDLocation build_location(const PositionFix& fix);
}
namespace microbu_v2x::security {
using namespace vanetza;
using namespace vanetza::security;
class Ts103097SignHeaderPolicy::Impl {
public:
const Runtime& runtime;
PositionProvider& positioning;
CertificatePool& pool;
const TrustConfiguration& trust;
// CAM, clause 7.1.1
boost::optional<Clock::time_point> cam_last_certificate;
bool cam_certificate_requested = false;
PeerRequestTracker incoming_requests; // inlineP2pcdRequest digests received from peers
PeerRequestTracker outgoing_requests; // certificates unknown to us
// VAM, TS 103 300-3 clause 6.5.3
boost::optional<Clock::time_point> vam_last_certificate;
bool new_cam_signer = false;
// generic profile: per ITS-AID
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) :
runtime(rt), positioning(pp), pool(certificates), trust(t) {}
static constexpr std::chrono::milliseconds one_second {1000};
static constexpr std::chrono::milliseconds half_second {500};
template<class Optional>
static bool elapsed(const Optional& last, Clock::time_point now, std::chrono::milliseconds interval) {
return !last || now - *last >= interval;
}
void cam(const SignRequest&, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
const auto digest = at.calculate_digest();
// Inline P2PCD request naming our own AT: include the certificate immediately.
if (digest && incoming_requests.is_pending(truncate(*digest))) {
cam_certificate_requested = true;
incoming_requests.discard_request(truncate(*digest));
}
bool full_certificate = cam_certificate_requested || elapsed(cam_last_certificate, now, one_second);
if (full_certificate) {
message.set_signer_identifier(at);
cam_last_certificate = now; // "the timer for the next inclusion ... shall be restarted"
cam_certificate_requested = false;
} else {
message.set_signer_identifier(*digest);
}
// Digests of certificates unknown to this station (clause 7.1.1, inlineP2pcdRequest).
message.set_inline_p2pcd_request(outgoing_requests.all());
// requestedCertificate: a known CA certificate that a peer asked for, only while our
// signer is the digest ("unless the component signer ... is of choice certificate").
if (!full_certificate) {
while (auto requested = incoming_requests.next_one()) {
if (const auto* authority = trust.authority(*requested)) {
message.set_requested_certificate(*authority);
return;
}
}
}
}
void denm(v3::SecuredMessage& message, const Certificate& at) {
message.set_signer_identifier(at);
message.set_generation_location(v3::build_location(positioning.position_fix()));
}
void vam(const SignRequest& request, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
const bool cluster = request.context_information == context::vam_cluster;
bool attach;
if (cluster) {
attach = elapsed(vam_last_certificate, now, half_second);
} else {
attach = new_cam_signer || elapsed(vam_last_certificate, now, one_second);
}
if (attach) {
message.set_signer_identifier(at);
vam_last_certificate = now;
new_cam_signer = false;
} else if (auto digest = at.calculate_digest()) {
message.set_signer_identifier(*digest);
} else {
message.set_signer_identifier(at);
}
}
void generic(ItsAid aid, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
auto it = generic_last_certificate.find(aid);
const auto digest = at.calculate_digest();
if (it == generic_last_certificate.end() || now - it->second >= one_second || !digest) {
message.set_signer_identifier(at);
generic_last_certificate[aid] = now;
} else {
message.set_signer_identifier(*digest);
}
}
};
Ts103097SignHeaderPolicy::Ts103097SignHeaderPolicy(const Runtime& rt, PositionProvider& pp, CertificatePool& pool,
const TrustConfiguration& trust) :
impl_(std::make_unique<Impl>(rt, pp, pool, trust)) {}
Ts103097SignHeaderPolicy::~Ts103097SignHeaderPolicy() = default;
void Ts103097SignHeaderPolicy::prepare_header(const SignRequest& request, v3::SecuredMessage& message) {
const auto now = impl_->runtime.now();
// Clause 5.2: psid and generationTime always present.
message.set_its_aid(request.its_aid);
message.set_generation_time(v2::convert_time64(now));
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) {
// TS 102 941 clause 6.2.3.2 inner enrolment structures are self-signed.
message.set_signer_identifier_self();
return;
}
switch (request.its_aid) {
case aid::CA: impl_->cam(request, message, at, now); break;
case aid::DEN: impl_->denm(message, at); break;
case aid::VRU: impl_->vam(request, message, at, now); break;
default: impl_->generic(request.its_aid, message, at, now); break;
}
}
void Ts103097SignHeaderPolicy::request_unrecognized_certificate(HashedId8 id) {
impl_->outgoing_requests.add_request(truncate(id));
}
void Ts103097SignHeaderPolicy::request_certificate() { impl_->cam_certificate_requested = true; }
void Ts103097SignHeaderPolicy::enqueue_p2p_request(HashedId3 id) { impl_->incoming_requests.add_request(id); }
void Ts103097SignHeaderPolicy::discard_p2p_request(HashedId3 id) { impl_->incoming_requests.discard_request(id); }
void Ts103097SignHeaderPolicy::report_new_cam_signer() { impl_->new_cam_signer = true; }
void Ts103097SignHeaderPolicy::reset_after_identifier_change() {
impl_->cam_last_certificate = boost::none;
impl_->cam_certificate_requested = false;
impl_->vam_last_certificate = boost::none;
impl_->generic_last_certificate.clear();
}
} // namespace microbu_v2x::security
@@ -0,0 +1,344 @@
#include <microbu_v2x/stack.hpp>
#if V2X_SECURITY
#include <microbu_v2x/security.hpp>
#endif
#include <vanetza/access/access_category.hpp>
#include <vanetza/btp/header.hpp>
#include <vanetza/btp/header_conversion.hpp>
#include <vanetza/dcc/interface.hpp>
#include <vanetza/dcc/mapping.hpp>
#include <vanetza/dcc/data_request.hpp>
#include <vanetza/geonet/dcc_information_sharing.hpp>
#include <vanetza/geonet/router.hpp>
#include <vanetza/geonet/transport_interface.hpp>
#include <vanetza/net/packet.hpp>
#include <vanetza/net/packet_variant.hpp>
#include <vanetza/common/byte_view.hpp>
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <utility>
namespace microbu_v2x {
namespace gn = vanetza::geonet;
using namespace vanetza;
StackConfig::StackConfig() {
// Explicit ITS-G5 subset. Defaults are upstream MIB, not R2 certification.
mib.itsGnIfType = gn::InterfaceType::ITS_G5;
mib.itsGnSnDecapResultHandling = gn::SecurityDecapHandling::Strict;
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 {
public:
StackConfig cfg;
ManualRuntime& runtime;
Access& access;
vanetza::security::SecurityEntity* security;
security::IdChangeService* id_change;
gn::Router router;
// 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.
gn::DccInformationSharing dcc_information_sharing;
std::optional<dcc::ChannelLoad> global_cbr;
Receive receive;
ReceiveGn receive_gn;
Report report;
bool position_valid = false;
bool change_pending = false;
std::optional<security::SubscriptionHandle> subscription;
Impl(StackConfig c, ManualRuntime& rt, Access& al, vanetza::security::SecurityEntity* sec,
security::IdChangeService* ids) :
cfg(std::move(c)), runtime(rt), access(al), security(sec), id_change(ids), router(rt, cfg.mib),
// TS 103 836-4-2 clause 5.3: "all ITS-S shall start with a random time offset" so that
// stations do not all recompute CBR_G in lockstep. No RNG dependency (host and ESP-IDF
// newlib without configured hardware entropy behave differently): the station's own
// startup time already differs from its neighbours', so its microsecond-level position
// within the 100 ms trigger interval (itsGNCBRGTriggerInterval) serves as that offset.
dcc_information_sharing(rt, router.get_location_table(), dcc::ChannelLoad(0.62),
UnitInterval(double(rt.now().time_since_epoch().count() % 100000) / 100000.0)) {
router.set_access_interface(this);
router.set_security_entity(sec);
router.set_dcc_field_generator(&dcc_information_sharing);
dcc_information_sharing.on_global_cbr_update = [this](const gn::CbrAggregator& agg) {
global_cbr = agg.get_global_cbr();
};
// MIB.itsGnLocalGnAddr is otherwise inert: Router::update_position only
// touches timestamp/latitude/longitude/speed/heading, never the address,
// and the router's own m_local_position_vector.gn_addr starts at
// vanetza::geonet::Address()'s default (all-zero mid, not manually
// configured) until this is called. Every GN packet's source position
// vector carries that address, so leaving this out silently transmits
// the wrong (default) station address regardless of what the caller
// configured -- undetected by BTP's official ATS, which never checks
// the source GN address, but not so for GeoNetworking's.
router.set_address(cfg.mib.itsGnLocalGnAddr);
router.set_transport_handler(gn::UpperProtocol::BTP_A, this);
router.set_transport_handler(gn::UpperProtocol::BTP_B, this);
router.set_transport_handler(gn::UpperProtocol::Unknown, this);
// TS 103 836-4-1 V2.2.1 clause 10.2.1.4: the GN core of an anonymously addressed
// station subscribes to the identifier-change service at startup (SN-IDCHANGE-SUBSCRIBE)
// and derives its MID from the identifier of the security entity (TS 102 940 clause 6.5).
if (cfg.mib.itsGnLocalAddrConfMethod == gn::AddrConfMethod::Anonymous && id_change) {
subscription = id_change->subscribe(
[this](security::IdChangeCommand command, const security::Identifier& id, const ByteBuffer&,
std::shared_ptr<security::IdChangeResponder> responder) { on_id_change(command, id, responder); });
const auto current = id_change->current_identifier();
if (current != security::Identifier {}) apply_identifier(current);
}
}
~Impl() override {
// clause 10.2.1.4: unsubscribe when the router shuts down (SN-IDCHANGE-UNSUBSCRIBE)
if (subscription && id_change) id_change->unsubscribe(*subscription);
}
// TS 102 940 V2.1.1 clause 6.5: the 48 least significant bits of the HashedId8 become the
// MAC-layer / GN MID identifier. A source address must be individual (IEEE Std 802 clause
// 8.2.2, I/G bit 0) and this one is not OUI-assigned (U/L bit 1).
void apply_identifier(const security::Identifier& id) {
MacAddress mid;
std::copy(id.begin() + 2, id.end(), mid.octets.begin());
mid.octets[0] = (mid.octets[0] & 0xfe) | 0x02;
cfg.mib.itsGnLocalGnAddr.mid(mid);
router.set_address(cfg.mib.itsGnLocalGnAddr);
}
// TS 102 723-8 V1.1.1 clauses 6.3.1.2 and 6.3.1.3: hook function of the GN core.
void on_id_change(security::IdChangeCommand command, const security::Identifier& id,
const std::shared_ptr<security::IdChangeResponder>& responder) {
switch (command) {
case security::IdChangeCommand::PREPARE:
change_pending = true;
router.flush_forwarding_buffers(); // caches shall be flushed
if (responder) responder->respond(true);
break;
case security::IdChangeCommand::COMMIT:
apply_identifier(id);
change_pending = false;
if (responder) responder->respond(true);
break;
case security::IdChangeCommand::ABORT:
change_pending = false;
break;
case security::IdChangeCommand::DEREG:
change_pending = false;
subscription.reset();
break;
}
}
void request(const dcc::DataRequest& req, std::unique_ptr<ChunkPacket> packet) override {
auto out = cfg.radio_parameters;
out.source = req.source;
out.destination = req.destination;
// DCC profile to IEEE 802.1D priority: upstream TS 102 687 mapping.
// DCC enforcement belongs to the injected Access adapter; no fake CBR.
out.priority = access::user_priority(dcc::map_profile_onto_ac(req.dcc_profile));
const auto view = create_byte_view(*packet, OsiLayer::Network, max_osi_layer());
out.data.assign(view.begin(), view.end());
auto result = validate(out, cfg.maximum_gnpdu);
if (result == Result::accepted) result = access.request(std::move(out));
if (report) report(result);
}
void indicate(const gn::DataIndication& ind, std::unique_ptr<UpPacket> packet) override {
if (ind.upper_protocol == gn::UpperProtocol::Unknown) {
// GN-DATA.indication for a packet with no registered upper protocol
// (Common Header next_header "Any"): the raw SDU, no BTP header to strip.
if (!receive_gn) return;
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
receive_gn(GnIndication {ind, ByteBuffer(view.begin(), view.end())});
return;
}
// validate length BEFORE parsing; upstream header parsing
// 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());
if (view.size() < 4 || !receive) return;
BtpIndication out {};
out.type = ind.upper_protocol == gn::UpperProtocol::BTP_A ? BtpType::a : BtpType::b;
out.destination_port = (std::uint16_t(view[0]) << 8) | view[1];
const std::uint16_t second = (std::uint16_t(view[2]) << 8) | view[3];
if (out.type == BtpType::a) out.source_port = second;
else out.destination_port_info = second;
out.gn = ind;
// SN-DECAP.confirm -> NF-SAP: TS 102 723-8 V2.0.0 clause 5 /
// V1.1.1 Table 27 and TS 103 836-5-1 Annex A.3.
if (ind.certificate_id)
out.certificate_id = ByteBuffer(ind.certificate_id->begin(), ind.certificate_id->end());
out.data.assign(view.begin() + 4, view.end());
receive(std::move(out));
}
};
Stack::Stack(StackConfig config, ManualRuntime& runtime, Access& access,
vanetza::security::SecurityEntity* security, security::IdChangeService* id_change) {
if (config.mib.itsGnMaxSduSize < 4 || config.mib.itsGnMaxSduSize > 65535 ||
config.maximum_gnpdu < config.mib.itsGnMaxSduSize ||
config.mib.itsGnIfType != gn::InterfaceType::ITS_G5 ||
config.mib.itsGnSnDecapResultHandling != gn::SecurityDecapHandling::Strict)
throw std::invalid_argument("Invalid ITS-G5 stack configuration");
#if V2X_SECURITY
if (!id_change) {
if (auto* own = dynamic_cast<security::SecurityEntity*>(security)) id_change = &own->id_change();
}
#endif
impl_ = std::make_unique<Impl>(std::move(config), runtime, access, security, id_change);
}
Stack::~Stack() = default;
const StackConfig& Stack::config() const { return impl_->cfg; }
security::IdChangeService* Stack::id_change() { return impl_->subscription ? impl_->id_change : nullptr; }
vanetza::security::SecurityEntity* Stack::security_entity() { return impl_->security; }
bool Stack::identity_change_pending() const { return impl_->change_pending; }
// 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) {
if (impl_->cfg.mib.itsGnLocalAddrConfMethod != gn::AddrConfMethod::Managed) return Result::unsupported;
if (impl_->change_pending) return Result::identity_change_pending;
impl_->cfg.mib.itsGnLocalGnAddr = address;
impl_->router.set_address(address);
return Result::accepted;
}
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_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_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; }
Result Stack::advance(Clock::time_point time) {
if (time < impl_->runtime.now()) return Result::time_regression;
impl_->runtime.trigger(time);
return Result::accepted;
}
Result Stack::update_position(const PositionFix& fix) {
if (!has_horizontal_position(fix) || fix.latitude.value() < -90 || fix.latitude.value() > 90 ||
fix.longitude.value() < -180 || fix.longitude.value() > 180 ||
fix.timestamp > impl_->runtime.now()) return Result::invalid_argument;
impl_->router.update_position(fix);
impl_->position_valid = true;
return Result::accepted;
}
Result Stack::indicate(AlDataIndication ind) {
if (ind.data.empty() || ind.data.size() > impl_->cfg.maximum_gnpdu) return Result::invalid_argument;
try {
auto packet = std::make_unique<UpPacket>(CohesivePacket(std::move(ind.data), OsiLayer::Network));
impl_->router.indicate(std::move(packet), ind.source, ind.destination);
return Result::accepted; // submitted for processing, NOT a receive verdict
} catch (const std::bad_alloc&) { return Result::resource_limit; }
catch (const std::exception&) { return Result::rejected; }
}
Result Stack::request(BtpRequest req) {
// mutually exclusive BTP header variants and conditional fields.
if ((req.type != BtpType::a && req.type != BtpType::b) ||
(req.type == BtpType::a && (!req.source_port || req.destination_port_info)) ||
(req.type == BtpType::b && req.source_port)) return Result::invalid_argument;
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize - 4u) return Result::resource_limit;
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
if (req.security_profile && *req.security_profile != impl_->cfg.security_profile) return Result::unsupported;
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
if (impl_->change_pending) return Result::identity_change_pending;
if (!impl_->position_valid) return Result::rejected;
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
return Result::invalid_argument;
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
return Result::invalid_argument;
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
return Result::invalid_argument;
try {
auto packet = std::make_unique<DownPacket>();
// TS 103 836-5-1 clauses 7 and 8.2: both headers occupy four octets.
if (req.type == BtpType::a) {
btp::HeaderA header { host_cast(req.destination_port), host_cast(*req.source_port) };
(*packet)[OsiLayer::Transport] = header;
} else {
btp::HeaderB header { host_cast(req.destination_port), host_cast(req.destination_port_info.value_or(0)) };
(*packet)[OsiLayer::Transport] = header;
}
(*packet)[OsiLayer::Application] = std::move(req.data);
auto apply = [&](gn::DataRequest& gn_req) {
gn_req.upper_protocol = req.type == BtpType::a ? gn::UpperProtocol::BTP_A : gn::UpperProtocol::BTP_B;
gn_req.communication_profile = req.communication_profile;
gn_req.its_aid = req.its_aid;
gn_req.permissions = std::move(req.permissions);
gn_req.security_context = std::move(req.security_context);
gn_req.traffic_class = req.traffic_class;
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
if (req.repetition) gn_req.repetition = *req.repetition;
};
gn::DataConfirm confirm;
if (req.transport == gn::TransportType::SHB) {
gn::ShbDataRequest gn_req(impl_->cfg.mib);
apply(gn_req);
confirm = impl_->router.request(gn_req, std::move(packet));
} else {
gn::GbcDataRequest gn_req(impl_->cfg.mib);
apply(gn_req);
gn_req.destination = boost::get<gn::Area>(req.destination);
confirm = impl_->router.request(gn_req, std::move(packet));
}
return confirm.accepted() ? Result::accepted : Result::rejected;
} catch (const std::bad_alloc&) { return Result::resource_limit; }
catch (const std::exception&) { return Result::rejected; }
}
Result Stack::request(GnRequest req) {
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize) return Result::resource_limit;
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
if (impl_->change_pending) return Result::identity_change_pending;
if (!impl_->position_valid) return Result::rejected;
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
return Result::invalid_argument;
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
return Result::invalid_argument;
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
return Result::invalid_argument;
try {
auto packet = std::make_unique<DownPacket>();
(*packet)[OsiLayer::Application] = std::move(req.data);
auto apply = [&](gn::DataRequest& gn_req) {
gn_req.upper_protocol = gn::UpperProtocol::Unknown;
gn_req.communication_profile = req.communication_profile;
gn_req.its_aid = req.its_aid;
gn_req.permissions = std::move(req.permissions);
gn_req.security_context = std::move(req.security_context);
gn_req.traffic_class = req.traffic_class;
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
if (req.repetition) gn_req.repetition = *req.repetition;
};
gn::DataConfirm confirm;
if (req.transport == gn::TransportType::SHB) {
gn::ShbDataRequest gn_req(impl_->cfg.mib);
apply(gn_req);
confirm = impl_->router.request(gn_req, std::move(packet));
} else {
gn::GbcDataRequest gn_req(impl_->cfg.mib);
apply(gn_req);
gn_req.destination = boost::get<gn::Area>(req.destination);
confirm = impl_->router.request(gn_req, std::move(packet));
}
return confirm.accepted() ? Result::accepted : Result::rejected;
} catch (const std::bad_alloc&) { return Result::resource_limit; }
catch (const std::exception&) { return Result::rejected; }
}
}
@@ -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,159 @@
#include "esp_private/wifi_os_adapter.h"
#include "esp_wifi.h"
#include "tx_custom.h"
esp_err_t ieee80211_raw_frame_sanity_check(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq);
esp_err_t ieee80211_post_hmac_tx(void *ebuf);
void *ic_ebuf_alloc(const void *packet, uint32_t unknown, uint32_t len);
void *ic_get_default_sched(void);
extern wifi_osi_funcs_t *g_osi_funcs_p;
extern void *g_wifi_global_lock;
typedef struct x_eb_txdesc
{
uint32_t flags;
uint32_t field_4;
uint32_t field_8;
uint8_t rate;
uint8_t field_d;
uint8_t field_e;
uint8_t field_f;
uint32_t field_10;
uint32_t field_14;
uint32_t timestamp;
void* sched;
uint32_t field_20;
uint32_t field_24;
uint32_t field_28;
union {
uint32_t field_2c_32;
struct {
uint8_t field_2c;
uint8_t field_2d;
uint8_t field_2e;
uint8_t field_2f;
};
};
union {
uint32_t field_30_32;
struct {
uint8_t field_30;
uint8_t field_31;
uint8_t field_32;
uint8_t field_33;
};
};
uint32_t field_34;
uint32_t field_38;
uint32_t field_3c;
uint32_t field_40;
uint32_t field_44;
} x_eb_txdesc_t;
static_assert(sizeof(x_eb_txdesc_t) == 0x48);
typedef struct x_middle_data
{
uint32_t field_40;
uint8_t* buf;
uint32_t field_48;
uint32_t field_4c;
} x_middle_data_t;
static_assert(sizeof(x_middle_data_t) == 0x10);
typedef struct x_ebuf
{
uint32_t field_0;
x_middle_data_t* ds_head;
x_middle_data_t* ds_tail;
uint16_t field_c;
uint16_t field_e;
uint32_t extra_data_start;
uint16_t header_length;
uint32_t data_length;
uint16_t field_1c;
uint8_t alloc_type;
uint8_t field_1f;
uint32_t field_20;
uint8_t field_24;
uint8_t field_25;
uint8_t field_26;
uint8_t field_27;
uint32_t field_28;
uint8_t field_2c;
uint32_t field_30;
uint32_t next_free;
x_eb_txdesc_t* txdesc;
uint16_t field_3c;
uint8_t field_3e;
uint8_t field_3f;
} x_ebuf_t;
static_assert(sizeof(x_ebuf_t) == 0x40);
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw)
{
esp_err_t result = 0;//ieee80211_raw_frame_sanity_check(ifx, buffer, len, en_sys_seq);
if (!result)
{
g_osi_funcs_p->_mutex_lock(g_wifi_global_lock);
x_ebuf_t* eb = ic_ebuf_alloc(buffer, 1, len);
if (eb)
{
//eb->data_length = len - 0x1a;
eb->data_length = 0;
x_eb_txdesc_t *txdesc_1 = eb->txdesc;
//eb->header_length = 0x1a;
eb->header_length = len;
txdesc_1->flags |= 0x4000;
txdesc_1->sched = ic_get_default_sched();
wifi_phy_rate_t rate = tx_rate_config->rate;
x_eb_txdesc_t *txdesc = eb->txdesc;
if (rate)
txdesc->rate = (char)rate;
else if (band != WIFI_BAND_5G)
txdesc->rate = 0;
else
txdesc->rate = (char)WIFI_PHY_RATE_6M;
wifi_phy_mode_t phymode = tx_rate_config->phymode;
if (phymode == WIFI_PHY_MODE_HE20)
{
txdesc->flags |= 0x80000000;
txdesc->field_2f =
(char)((((uint32_t)tx_rate_config->ersu + 6) & 0xf) << 3)
| (txdesc->field_2f & 0x87);
if ((uint32_t)tx_rate_config->dcm)
txdesc->field_31 |= 0x80;
}
else if (phymode == WIFI_PHY_MODE_VHT20)
txdesc->flags |= 0x1000000;
// No idea if this is correct, but this is what the original code does...
uint32_t bw_is_bw40 = bw == WIFI_BW40;
txdesc->field_8 = (bw_is_bw40 << 0xf) | (txdesc->field_8 & 0xffff7fff);
if (en_sys_seq)
txdesc->flags |= 1;
txdesc->field_10 =
(txdesc->field_10 & 0xfff3ffff) | ((ifx & WIFI_IF_MAX) << 0x12);
txdesc->field_14 = 0x100;
ieee80211_post_hmac_tx(eb);
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
}
else
{
result = ESP_ERR_NO_MEM;
g_osi_funcs_p->_mutex_unlock(g_wifi_global_lock);
}
}
return result;
}
@@ -0,0 +1,13 @@
#pragma once
#include "esp_wifi.h"
#ifdef __cplusplus
extern "C" {
#endif
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t ifx, const void *buffer, int32_t len, bool en_sys_seq, wifi_tx_rate_config_t *tx_rate_config, wifi_band_t band, wifi_bandwidth_t bw);
#ifdef __cplusplus
}
#endif