Files
MicrOBU/obu-firmware/components/microbu_v2x/include/microbu_v2x/security.hpp
T
Ashin Walpola 50bbf6552d 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.
2026-11-11 00:13:57 +01:00

383 lines
21 KiB
C++

#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