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:
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user