#include #include "station.hpp" #include "raw_capture_policy.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "c5_radio.hpp" extern "C" { #include "geonet.h" #include "gn_unwrap.h" } #include "v2x_rx.hpp" #include #include #include "cca_window.hpp" #include "heap_diagnostics.hpp" #include "radio_policy.hpp" #include "simple_ble.hpp" #include "tx_policy.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace microbu { using namespace microbu_v2x; using vanetza::ByteBuffer; using vanetza::security::PublicKey; namespace gn = vanetza::geonet; namespace { const char* TAG = "station"; bool pki_load(const char*, vanetza::ByteBuffer&); link::Code code(Result result) { return static_cast(result); } // Numbering of the link's "Packet transport type" field matches the TRANSP_CORE.request/.indication // service primitive parameter of ETSI TS 103 836-4-1 annex J.2/J.4 (0 GUC, 1 SHB, 2 TSB, 3 GBC, // 4 GAC); it does not reuse the HT wire encoding of clause 9.7.4 table 9, which numbers these // differently (GEOUNICAST=2, GEOANYCAST=3, GEOBROADCAST=4, TSB=5, no separate SHB value there). std::uint8_t transport_number(gn::TransportType t) { switch (t) { case gn::TransportType::GUC: return 0; case gn::TransportType::SHB: return 1; case gn::TransportType::TSB: return 2; case gn::TransportType::GBC: return 3; case gn::TransportType::GAC: return 4; } return 0; } std::optional transport_from(std::uint8_t n) { switch (n) { case 0: return gn::TransportType::GUC; case 1: return gn::TransportType::SHB; case 2: return gn::TransportType::TSB; case 3: return gn::TransportType::GBC; case 4: return gn::TransportType::GAC; } return std::nullopt; } // Wire DestinationArea -> vanetza gn::Area (GBC destination). gn::Area area_from(const link::DestinationArea& a) { gn::Area area; switch (a.shape) { case 0: { gn::Circle c; c.r = double(a.distance_a) * vanetza::units::si::meter; area.shape = c; break; } case 1: { gn::Rectangle r; r.a = double(a.distance_a) * vanetza::units::si::meter; r.b = double(a.distance_b) * vanetza::units::si::meter; area.shape = r; break; } default: { gn::Ellipse e; e.a = double(a.distance_a) * vanetza::units::si::meter; e.b = double(a.distance_b) * vanetza::units::si::meter; area.shape = e; break; } } area.position = gn::GeodeticPosition(a.latitude / 1.0e7 * vanetza::units::degree, a.longitude / 1.0e7 * vanetza::units::degree); area.angle = vanetza::units::Angle(double(a.angle) * vanetza::units::degree); return area; } // gn::Area -> wire DestinationArea (the inverse of area_from). struct AreaToLink : boost::static_visitor { const gn::Area& area; explicit AreaToLink(const gn::Area& a) : area(a) {} link::DestinationArea common() const { link::DestinationArea out; out.latitude = static_cast(area.position.latitude.value() * 1.0e7); out.longitude = static_cast(area.position.longitude.value() * 1.0e7); out.angle = static_cast(area.angle.value()); return out; } link::DestinationArea operator()(const gn::Circle& c) const { auto o = common(); o.shape = 0; o.distance_a = c.r.value(); return o; } link::DestinationArea operator()(const gn::Rectangle& r) const { auto o = common(); o.shape = 1; o.distance_a = r.a.value(); o.distance_b = r.b.value(); return o; } link::DestinationArea operator()(const gn::Ellipse& e) const { auto o = common(); o.shape = 2; o.distance_a = e.a.value(); o.distance_b = e.b.value(); return o; } }; // 0 unsecured (no security envelope), 1 + VerificationReport ordinal otherwise struct ReportToLink : boost::static_visitor { ReportToLink() = default; std::uint8_t operator()(boost::blank) const { return 0; } std::uint8_t operator()(vanetza::security::VerificationReport r) const { return 1 + static_cast(r); } }; } // Backend for public data, trust configuration, ticket pool (keys in the station's security module) and the // entity built on them. struct Station::Security { explicit Security(security::SecurityModule& module) : pool(module) {} std::unique_ptr owned_backend = make_security_backend(); vanetza::security::Backend& backend = *owned_backend; security::TrustConfiguration trust; security::CertificatePool pool; std::unique_ptr entity; bool loaded = false; security::ApplyReport report; }; // An outstanding TS 102 941 request: the context that decrypts its response and the key the security module // generated for it. The key is destroyed with the request unless the issued certificate was installed. struct Station::PkiPending { PkiPending(security::SecurityModule& m, security::KeyId k, PublicKey p) : module(m), key(k), public_key(std::move(p)) {} ~PkiPending() { if (key) module.destroy_key(key); } PkiPending(const PkiPending&) = delete; PkiPending& operator=(const PkiPending&) = delete; /// the certificate for the key is installed: the key now belongs to it security::KeyId release() { return std::exchange(key, security::KeyId {}); } security::SecurityModule& module; security::KeyId key; PublicKey public_key; pki::RequestContext context; pki::RetrySchedule retry; ByteBuffer request; std::uint64_t created_ms = 0; pki::Permissions permissions; security::HashedId8 ea {}; security::HashedId8 aa {}; }; // A validated BTP-DATA.request waiting for signing and submission (reply before transmission). struct Station::Pending { NF_SAP::BTP_DATA_request request; std::uint32_t its_aid = 0; }; namespace { constexpr std::int64_t packet_lifetime_us = 1000000; // VAM maximum packet lifetime (TS 103 300-3 Table 4) // ETSI TS 103 836-4-1 packet buffer policy: at most one pending VAM; a newer VAM replaces an older unsent one (latest state only). constexpr std::size_t max_pending_vams = 1; // Bound for all requests waiting between their CONFIRM and their submission (CAM, DENM and the VAM). constexpr std::size_t max_pending = 8; gn::CommunicationProfile communication_profile(std::uint8_t n, bool& valid) { valid = n <= 2; switch (n) { case 1: return gn::CommunicationProfile::ITS_G5; case 2: return gn::CommunicationProfile::LTE_V2X; default: return gn::CommunicationProfile::Unspecified; } } gn::DataRequest::Repetition repetition_from(std::uint16_t interval_ms, std::uint16_t maximum_ms) { gn::DataRequest::Repetition repetition; repetition.interval = (interval_ms / 1000.0) * vanetza::units::si::seconds; repetition.maximum = (maximum_ms / 1000.0) * vanetza::units::si::seconds; return repetition; } // Link BTP-DATA.request -> NF-SAP BTP-DATA.request (TS 103 300-3 Table 4 PCI). Every transmission is signed: // an unsecured request is refused. Returns the refusal code, or accepted with `out` filled. link::Code to_nf_request(const link::BtpDataRequest& q, gn::TrafficClass default_traffic_class, NF_SAP::BTP_DATA_request& out) { const auto transport = transport_from(q.gn_packet_transport_type); bool profile_valid = false; const auto profile = communication_profile(q.gn_communication_profile, profile_valid); if (!transport || !profile_valid) return link::Code::invalid_argument; if (q.gn_security_profile == 1) return link::Code::rejected; if (q.gn_security_profile != 0 && q.gn_security_profile != 2) return link::Code::invalid_argument; if (*transport == gn::TransportType::GBC && !q.area) return link::Code::invalid_argument; out.fl_sdu = q.fl_sdu; out.length = q.fl_sdu.size(); out.btp_type = q.btp_type == 0 ? BtpType::a : BtpType::b; out.destination_port = q.destination_port; if (out.btp_type == BtpType::a) out.source_port = q.destination_port_info; else out.destination_port_info = q.destination_port_info; out.gn_packet_transport_type = *transport; out.gn_communication_profile = profile; out.gn_security_profile = NF_SAP::SecurityProfile::SECURED; out.gn_traffic_class = q.gn_traffic_class == 0xFF ? default_traffic_class : gn::TrafficClass(q.gn_traffic_class); if (q.gn_maximum_packet_lifetime != 0xFF) { gn::Lifetime l; l.raw(q.gn_maximum_packet_lifetime); out.gn_maximum_packet_lifetime = l; } if (q.gn_maximum_hop_limit) out.gn_maximum_hop_limit = q.gn_maximum_hop_limit; if (q.gn_repetition_interval_ms) out.gn_repetition = repetition_from(q.gn_repetition_interval_ms, q.gn_repetition_maximum_ms); if (*transport == gn::TransportType::GBC) out.gn_destination_address = area_from(*q.area); out.its_aid = q.its_aid; out.permissions = q.permissions; out.context_information = q.context; return link::Code::accepted; } // PoTi update (EN 302 890-2 minimum data set, link units) -> vanetza position fix at `timestamp`. vanetza::PositionFix position_fix_from(const link::PotiUpdate& p, vanetza::Clock::time_point timestamp) { vanetza::PositionFix fix; fix.timestamp = timestamp; fix.latitude = p.latitude / 1.0e7 * vanetza::units::degree; fix.longitude = p.longitude / 1.0e7 * vanetza::units::degree; fix.confidence.semi_major = p.semi_major_cm / 100.0 * vanetza::units::si::meter; fix.confidence.semi_minor = p.semi_minor_cm / 100.0 * vanetza::units::si::meter; fix.confidence.orientation = p.orientation_deci_degree / 10.0 * vanetza::units::true_north_degrees; fix.speed = (p.has_speed() ? p.speed_cm_s / 100.0 : 0.0) * vanetza::units::si::meters_per_second; fix.course = (p.has_heading() ? p.heading_deci_degree / 10.0 : 0.0) * vanetza::units::true_north_degrees; if (p.has_altitude()) fix.altitude = vanetza::ConfidentQuantity(p.altitude_cm / 100.0 * vanetza::units::si::meter); return fix; } bool valid_position(const link::PotiUpdate& p) { return p.latitude >= -900000000 && p.latitude <= 900000000 && p.longitude >= -1800000000 && p.longitude <= 1800000000; } // NF-SAP BTP-DATA.indication -> link BTP_DATA_INDICATION (TS 103 836-4-1 annex J.4 parameters). link::BtpDataIndication to_link_indication(NF_SAP::BTP_DATA_indication& indication) { link::BtpDataIndication out; out.btp_type = indication.btp_type == BtpType::b ? 1 : 0; out.destination_port = indication.destination_port; out.destination_port_info = indication.source_port.value_or(indication.destination_port_info.value_or(0)); out.gn_packet_transport_type = transport_number(indication.gn.transport_type); out.gn_traffic_class = indication.gn.traffic_class.raw(); out.gn_remaining_packet_lifetime = indication.gn.remaining_packet_lifetime ? indication.gn.remaining_packet_lifetime->raw() : 0xFF; out.gn_remaining_hop_limit = indication.gn.remaining_hop_limit ? static_cast(std::min(*indication.gn.remaining_hop_limit, 254u)) : 0xFF; ByteBuffer address; gn::serialize_into_buffer(indication.gn.source_position.gn_addr, address); std::copy_n(address.begin(), std::min(address.size(), 8), out.source_gn_address); out.source_timestamp = indication.gn.source_position.timestamp.raw(); out.source_latitude = indication.gn.source_position.latitude.value(); out.source_longitude = indication.gn.source_position.longitude.value(); out.security_report = boost::apply_visitor(ReportToLink {}, indication.gn.security_report); out.its_aid = indication.gn.its_aid.value_or(0); if (indication.gn.permissions) out.permissions = *indication.gn.permissions; if (indication.gn.certificate_id) { out.certificate_present = true; std::copy(indication.gn.certificate_id->begin(), indication.gn.certificate_id->end(), out.certificate_id); } if (const auto* area = boost::get(&indication.gn.destination)) out.area = boost::apply_visitor(AreaToLink {*area}, area->shape); out.received_fl_sdu = std::move(indication.received_fl_sdu); return out; } } std::int64_t Station::Clock::now_us() const { const std::int64_t elapsed = esp_timer_get_time() - base_esp_us; return base_its_us + elapsed - its_clock::slew_applied_us(slew_us, elapsed); } std::int64_t Station::Clock::remaining_slew_us() const { return slew_us - its_clock::slew_applied_us(slew_us, esp_timer_get_time() - base_esp_us); } Station::Station() = default; Station::~Station() { teardown(); } void Station::teardown() { if (!pending_.empty()) ESP_LOGW(TAG, "station rebuilt: %u pending requests dropped", unsigned(pending_.size())); pending_.clear(); // prepared for the old stack and identity rebuilding_ = true; // the DEREG of TS 102 723-8 Figure 15 is ours, not the phone's stack_.reset(); // router timers before the runtime // AccessStack::Dcc's Limeric holds a reference to *runtime_ and calls into it from its // destructor (Runtime::cancel): it must be destroyed before runtime_ is. access_stack_.reset(); // The security entity holds the runtime too; the trust set and ticket pool stay (decoding them again on // every build cost a 40-60 kB heap peak and ended in out-of-memory resets). if (security_) security_->entity.reset(); runtime_.reset(); dcc_cca_last_.reset(); dcc_last_sample_its_us_ = 0; pending_responders_.clear(); rebuilding_ = false; } // TS 102 894-2 station config -> the GeoNetworking MIB (TS 103 836-4-1). void Station::apply_mib(StackConfig& config, const link::StationConfigure& c) const { config.mib.itsGnLocalGnAddr.mid(vanetza::MacAddress {c.mid[0], c.mid[1], c.mid[2], c.mid[3], c.mid[4], c.mid[5]}); config.mib.itsGnLocalGnAddr.station_type(static_cast(c.station_type & 0x1F)); config.mib.itsGnLocalGnAddr.is_manually_configured(c.address_configuration == 0); config.mib.itsGnLocalAddrConfMethod = c.address_configuration == 1 ? gn::AddrConfMethod::Anonymous : gn::AddrConfMethod::Auto; config.mib.itsGnSecurity = c.security == 1; config.mib.vanetzaDisableBeaconing = c.beaconing == 0; config.mib.itsGnDefaultTrafficClass = gn::TrafficClass(c.default_traffic_class); gn::Lifetime lifetime; lifetime.raw(c.default_lifetime); config.mib.itsGnDefaultPacketLifetime = lifetime; config.mib.itsGnMaxPacketLifetime = lifetime < config.mib.itsGnMaxPacketLifetime ? config.mib.itsGnMaxPacketLifetime : lifetime; config.radio_parameters.channel_number = c.channel_number; config.radio_parameters.transmit_power_dbm = c.transmit_power_dbm; } // Carry the phone's SF-SAP pseudonym-change subscriptions (TS 102 723-8 clause 6.3) // over to the identity manager of a freshly rebuilt security entity. void Station::resubscribe_id_change() { std::map renewed; for (const auto& [handle, old_service] : link_subscriptions_) { (void)old_service; renewed[handle] = subscribe_id_change(handle, {}); } link_subscriptions_ = renewed; } std::uint64_t Station::subscribe_id_change(std::uint64_t handle, const link::Bytes& subscriber_data) { return security_->entity->id_change().subscribe( [this, handle](security::IdChangeCommand command, const security::Identifier& id, const ByteBuffer& data, std::shared_ptr responder) { link::IdChangeEvent event; event.subscription = handle; event.command = static_cast(command); std::copy(id.begin(), id.end(), event.id); event.subscriber_data = data; if (responder) pending_responders_[handle] = responder; if (id_event_ && !rebuilding_) id_event_(event); }, subscriber_data); } namespace { // free heap and the largest block one allocation can get, at each stage of a station build (one line per // build): a falling largest block with a flat free heap is fragmentation, a falling free heap a leak. void log_heap_stage(const char* stage) { ESP_LOGI(TAG, "build heap %s: free=%lu largest=%lu dma_largest=%lu", stage, (unsigned long)esp_get_free_heap_size(), (unsigned long)heap_caps_get_largest_free_block(MALLOC_CAP_DEFAULT), (unsigned long)heap_caps_get_largest_free_block(MALLOC_CAP_DMA)); } } security::SecurityModule* Station::module() { if (module_) return module_.get(); try { module_ = make_security_module(); ESP_LOGI(TAG, "security module: %s", security_module_name()); } catch (const std::exception& e) { ESP_LOGE(TAG, "security module unavailable (%s): secured requests and TS 102 941 refused", e.what()); } return module_.get(); } void Station::new_entity() { security_->entity = std::make_unique(*runtime_, *this, security_->backend, security_->pool, security_->trust); resubscribe_id_change(); } bool Station::load_security() { if (security_ && !credentials_stale_) { // the same credentials as at the last build: keep the decoded set, only the entity is new new_entity(); return true; } security_.reset(); // the old set goes before the new one is decoded (never two sets at once) auto* keys = module(); if (!keys) return false; security_ = std::make_unique(*keys); credentials_stale_ = false; security::StoredCredentials credentials; security::NvsCredentialStore store; auto load = store.load(credentials); ByteBuffer trust_bytes; pki::TrustSnapshot managed; const bool has_managed = pki_load("trust_snapshot", trust_bytes); managed_trust_deadline_ = 0; managed_trust_expired_ = false; if (has_managed) { if (!clock_.synchronised) credentials_stale_ = true; const auto seconds = clock_.now_us() / 1000000; if (!pki::decode_snapshot(trust_bytes, managed) || !clock_.synchronised || seconds >= managed.deadline || !pki::snapshot_credentials(security_->backend, managed, credentials, &security_->trust)) { credentials = {}; managed_trust_expired_ = true; } else load = Result::accepted; managed_trust_deadline_ = managed.deadline; } log_heap_stage("after NVS load"); if (load == Result::accepted) { const auto failed_before = heap_diagnostics::failed_allocations(); try { security_->report = security::apply(credentials, security_->trust, security_->pool); } catch (const std::exception& e) { // a stored certificate the codec cannot read must not take the station down: run without credentials ESP_LOGE(TAG, "stored credentials unusable (%s)", e.what()); security_->report = {}; security_->report.result = Result::invalid_argument; } const auto failed = heap_diagnostics::failed_allocations() - failed_before; if (security_->report.result != Result::accepted) { // Out of memory shows up as an ASN.1 decoding failure (asn1c gets NULL from malloc): say which it was, // and release the partly decoded set (it held about 44 kB of nothing usable). if (failed) ESP_LOGE(TAG, "not enough heap for the stored credentials: %u allocation(s) failed while " "decoding them; secured requests refused until provisioned", unsigned(failed)); const auto report = security_->report; security_ = std::make_unique(*keys); security_->report = report; credentials_stale_ = true; // try again at the next build (e.g. with the radio off there may be room) } credentials = {}; // the parsed NVS copy is not needed any more log_heap_stage("after credential apply"); security_->loaded = security_->report.result == Result::accepted && !security_->pool.empty(); ESP_LOGI(TAG, "credentials from NVS: %u roots, %u authorities, %u tickets (result %d)", unsigned(security_->report.roots), unsigned(security_->report.authorities), unsigned(security_->report.tickets), int(security_->report.result)); } else if (load == Result::rejected) { ESP_LOGW(TAG, "no credentials in NVS: secured requests will be refused until provisioned"); } else { ESP_LOGE(TAG, "stored credentials do not decode (result %d)", int(load)); } new_entity(); return true; } // (Re)build stack and security entity from config_, the stored credentials and the current clock. link::Code Station::build() { teardown(); log_heap_stage("after teardown"); runtime_ = std::make_unique(vanetza::Clock::time_point(std::chrono::microseconds(clock_.synchronised ? clock_.now_us() : 0))); StackConfig config; apply_mib(config, *config_); radio_parameters_ = config.radio_parameters; if (config.mib.itsGnSecurity) { if (!load_security()) return link::Code::security_unavailable; // never a secured configuration without keys } else { security_.reset(); // an unsecured configuration needs no trust set: its heap goes back } log_heap_stage("after security"); vanetza::security::SecurityEntity* entity = security_ ? security_->entity.get() : nullptr; stack_ = std::make_unique(config, *runtime_, *this, entity); log_heap_stage("after stack"); stack_->on_receive([this](BtpIndication indication) { deliver(std::move(indication)); }); stack_->on_access_result([](Result) { /* counted in Station::request, the adapter itself */ }); // DCC_ACC gate in front of whatever radio_ currently is (rebuilt here rather than in // Station::configure() because it must reference the fresh runtime_, not a torn-down one -- // see the destruction-order comment in Station::teardown()). if (radio_) { access_stack_ = std::make_unique(*radio_); access_stack_->enable_dcc(*runtime_); stack_->report_tx_power(static_cast(std::lround(radio_parameters_.transmit_power_dbm))); } dcc_cca_last_.reset(); dcc_last_sample_its_us_ = clock_.synchronised ? clock_.now_us() : 0; if (have_fix_) apply_position(); return link::Code::accepted; } link::Code Station::configure(const link::StationConfigure& c, link::Bytes& detail) { // Transmit only on declared operating points , receive on any ITS-G5 carrier; refused // before anything is torn down, so a bad request leaves the running configuration untouched. const bool radio_ok = c.radio == 0 || (c.radio == 2 ? radio_policy::operating_point_allowed(c.channel_number, c.transmit_power_dbm) : radio_policy::receive_channel_allowed(c.channel_number)); if (!radio_ok) { ESP_LOGW(TAG, "channel %u at %u dBm is not a declared operating point", unsigned(c.channel_number), unsigned(c.transmit_power_dbm)); return link::Code::invalid_argument; } const bool radio_changed = !config_ || config_->radio != c.radio || config_->channel_number != c.channel_number || config_->transmit_power_dbm != c.transmit_power_dbm; if (radio_changed) { // The stack (with its AccessStack reference to *radio_ and the security entity) goes before the radio is // replaced: no dangling reference, and esp_wifi_init() gets the heap the old stack held. Starting the // Wi-Fi driver while both were alive failed with ESP_ERR_NO_MEM after a signing session (2026-09-29). teardown(); const auto started = start_radio(c); if (started != link::Code::accepted) { if (config_) build(); // the previous configuration, now without a radio return started; } } config_ = c; // MicrOBU: a fresh locally administered unicast MAC for unsecured frames on every configuration, // so a station that does not sign does not keep one link-layer identity either. esp_fill_random(unsecured_mid_, sizeof unsecured_mid_); unsecured_mid_[0] = static_cast((unsecured_mid_[0] & 0xFC) | 0x02); link_subscriptions_.clear(); // a configuration starts a phone session: earlier subscriptions are void counters_ = link::Status {}; // and the session's counters start at zero const auto result = build(); if (result != link::Code::accepted) return result; detail = configuration_detail(); counters_.configured = 1; return link::Code::accepted; } link::Code Station::start_radio(const link::StationConfigure& c) { radio_.reset(); if (c.radio == 0) { raw_mode_ = 0; return link::Code::accepted; } // no radio, nothing to capture C5RadioConfig rc; rc.channel_number = c.channel_number; rc.transmit_power_dbm = c.transmit_power_dbm; rc.laboratory_transmission = c.radio == 2; radio_ = std::make_unique(rc); const auto error = radio_->start(); if (error != ESP_OK) { ESP_LOGE(TAG, "radio start failed: %s", esp_err_to_name(error)); radio_.reset(); return link::Code::rejected; } ESP_LOGI(TAG, "radio on channel %u, %s", unsigned(c.channel_number), c.radio == 2 ? "transmit and receive" : "receive only"); radio_->on_transmitted([this](const std::uint8_t* data, std::size_t size) { emit_raw(data, size, 0, static_cast(esp_timer_get_time()), true); }); radio_->set_capture(raw_mode_); // a rebuilt radio keeps the phone's capture setting return link::Code::accepted; } link::Bytes Station::configuration_detail() const { link::Writer w; ByteBuffer address; gn::serialize_into_buffer(stack_->address(), address); w.bytes(address); security::Identifier identifier {}; if (security_ && security_->entity) identifier = security_->entity->id_change().current_identifier(); w.bytes(identifier.data(), 8); w.u8(security_ && security_->loaded ? 1 : 0); w.u8(security_ ? static_cast(std::min(security_->pool.size(), 255)) : 0); return w.out; } void Station::apply_position() { if (!stack_ || !have_fix_) return; // never ahead of the station clock (Stack::update_position rejects that) const auto now = runtime_->now(); if (fix_.timestamp > now) fix_.timestamp = now; const auto result = stack_->update_position(fix_); if (result != Result::accepted) ESP_LOGW(TAG, "position rejected: %d", int(result)); } link::Code Station::poti(const link::PotiUpdate& p) { if (!valid_position(p)) return link::Code::invalid_argument; const std::int64_t its_us = static_cast(p.timestamp_ms) * 1000; const auto step = apply_time_reference(its_us); // A stale update, delivered late by the link, keeps the clock and must not apply its old position either. if (step == its_clock::Step::refuse_stale) return link::Code::time_regression; fix_ = position_fix_from(p, vanetza::Clock::time_point(std::chrono::microseconds(std::min(its_us, clock_.now_us())))); have_fix_ = true; last_poti_ = p; ++counters_.poti_updates; tick(); apply_position(); return step == its_clock::Step::restart ? link::Code::time_regression : link::Code::accepted; } // ITS clock: the phone's PoTi time is the reference; the local esp_timer runs between updates (its_clock). its_clock::Step Station::apply_time_reference(std::int64_t its_us) { const std::int64_t esp_us = esp_timer_get_time(); const std::int64_t drift = clock_.synchronised ? its_us - clock_.now_us() : 0; // Behind the clock but ahead of where a pending slew takes it: judged against the slewed clock, so one // offset is not corrected twice; never a forward step from it (that would move the clock back). const std::int64_t judged = drift >= 0 ? drift : std::min(drift + clock_.remaining_slew_us(), -1); const auto step = its_clock::next_step(clock_.synchronised, judged, esp_us, regression_, lag_); switch (step) { case its_clock::Step::start: clock_ = Clock {true, its_us, esp_us, 0}; if (config_) build(); // the runtime started at 0: restart it at real time break; case its_clock::Step::forward: clock_.base_its_us = its_us; clock_.base_esp_us = esp_us; clock_.slew_us = 0; break; case its_clock::Step::slew_back: { const std::int64_t now = clock_.now_us(); // rebase at the current reading: monotonic from here on clock_.slew_us = clock_.remaining_slew_us() + lag_.slew_us; clock_.base_its_us = now; clock_.base_esp_us = esp_us; ESP_LOGW(TAG, "station clock ahead of the freshest PoTi reference by %lld ms: slewing back at %lld %%", static_cast(lag_.slew_us / 1000), static_cast(100 / its_clock::slew_divisor)); lag_ = {}; break; } case its_clock::Step::hold: break; // the local clock catches up with the next updates case its_clock::Step::refuse_stale: ESP_LOGW(TAG, "stale PoTi update refused: %lld ms behind the station clock", static_cast(-drift / 1000)); break; case its_clock::Step::restart: ESP_LOGW(TAG, "ITS time moved back by %lld ms (consistent over several updates), restarting the station", static_cast(-drift / 1000)); clock_ = Clock {true, its_us, esp_us}; if (config_) build(); break; } return step; } link::Code Station::btp_request(const link::BtpDataRequest& q) { if (!stack_) return link::Code::not_configured; if (!clock_.synchronised || !have_fix_) { ++counters_.requests_refused; return link::Code::rejected; } // MicrOBU: Niklas Dathe's station signs everything. Here the phone's "Sign outgoing messages" // setting decides per request; 0 means the station's configuration. if (q.gn_security_profile == 1 || (q.gn_security_profile == 0 && config_ && config_->security == 0)) return unsecured_request(q); auto pending = std::make_unique(); const auto mapped = to_nf_request(q, stack_->config().mib.itsGnDefaultTrafficClass, pending->request); if (mapped != link::Code::accepted) { ++counters_.requests_refused; return mapped; } const auto now_us = clock_.now_us(); if (q.generated_at_ms && tx_policy::is_stale(static_cast(*q.generated_at_ms) * 1000, now_us, packet_lifetime_us)) { ESP_LOGW(TAG, "request generated %lld ms ago: stale request refused", static_cast(now_us / 1000 - static_cast(*q.generated_at_ms))); ++counters_.requests_refused; return link::Code::rejected; } if (q.its_aid == 638) { // ETSI TS 103 836-4-1 packet buffer policy: outdated VAM state is never transmitted after its replacement const auto vams = std::count_if(pending_.begin(), pending_.end(), [](const auto& p) { return p->its_aid == 638; }); if (static_cast(vams) >= max_pending_vams) { const auto older = std::find_if(pending_.begin(), pending_.end(), [](const auto& p) { return p->its_aid == 638; }); ESP_LOGI(TAG, "unsent VAM replaced by a newer one"); ++counters_.requests_refused; // the replaced request never goes on air pending_.erase(older); } } if (pending_.size() >= max_pending) { ++counters_.requests_refused; return link::Code::resource_limit; } pending->its_aid = q.its_aid; pending_.push_back(std::move(pending)); return link::Code::accepted; // validated and queued; signing refusals show in the STATUS counters } void Station::forward_raw(const ByteBuffer& frame, int rssi) { if (!raw_its_) return; // Most captured frames are not ITS traffic this handles; false is the common case, not an error. gn_rx_t rx; if (!gn_unwrap_its(frame.data(), static_cast(frame.size()), &rx)) return; const bool fits = link::v2x_rx_fits(rx); if (!fits) { ++raw_oversize_; static std::int64_t last_report = 0; // one line per 10 s at most, the counter has the rest const auto now = esp_timer_get_time(); if (now - last_report > 10000000) { last_report = now; ESP_LOGW(TAG, "V2X_RX: port %u message of %d bytes does not fit a link message (%lu dropped so far)", unsigned(rx.btp_dest_port), rx.payload_len, (unsigned long)raw_oversize_); } return; } ++raw_forwarded_; raw_its_(link::encode_v2x_rx(rx, rssi)); } link::Code Station::unsecured_request(const link::BtpDataRequest& q) { if (!stack_ || !config_) return link::Code::not_configured; if (!clock_.synchronised || !have_fix_) { ++counters_.requests_refused; return link::Code::rejected; } // geonet.c builds exactly one packet shape: BTP-B inside a GN single-hop broadcast. That is // what CAM and VAM are; anything else still needs the stack, which here only signs. if (q.btp_type != 1 || q.gn_packet_transport_type != 1) { ++counters_.requests_refused; return link::Code::unsupported; } gn_lpv_t lpv {}; std::copy(std::begin(unsecured_mid_), std::end(unsecured_mid_), lpv.mac); lpv.station_type = config_->station_type; lpv.pai = last_poti_.pai(); lpv.tst_ms = static_cast(last_poti_.timestamp_ms); // TimestampIts mod 2^32 lpv.lat_tenmicrodeg = last_poti_.latitude; lpv.lon_tenmicrodeg = last_poti_.longitude; lpv.speed_cms = static_cast(last_poti_.has_speed() ? std::min(last_poti_.speed_cm_s, 16383) : 0); lpv.heading_decideg = last_poti_.has_heading() ? last_poti_.heading_deci_degree : 0; ByteBuffer pdu(q.fl_sdu.size() + 64); const int length = geonet_wrap_shb(q.fl_sdu.data(), static_cast(q.fl_sdu.size()), &lpv, q.destination_port, pdu.data(), pdu.size()); if (length <= 0) { ++counters_.requests_refused; return link::Code::invalid_argument; } pdu.resize(static_cast(length)); AlDataRequest frame = radio_parameters_; frame.source = vanetza::MacAddress {lpv.mac[0], lpv.mac[1], lpv.mac[2], lpv.mac[3], lpv.mac[4], lpv.mac[5]}; frame.destination = vanetza::cBroadcastMacAddress; frame.data = std::move(pdu); const auto result = request(std::move(frame)); if (result == Result::accepted) ++counters_.requests_accepted; else ++counters_.requests_refused; return code(result); } void Station::submit_pending() { while (!pending_.empty()) { auto pending = std::move(pending_.front()); pending_.pop_front(); submit(*pending); } } void Station::submit(Pending& pending) { vam_pending_ = pending.its_aid == 638; // VRU basic service: its frame airtime feeds T_GenVam_DCC tick(); // the packet carries the current time and position ESP_LOGI(TAG, "heap before sign: free=%lu min=%lu largest=%lu dma=%lu dma_largest=%lu stack_hwm=%u", (unsigned long)esp_get_free_heap_size(), (unsigned long)esp_get_minimum_free_heap_size(), (unsigned long)heap_caps_get_largest_free_block(MALLOC_CAP_DEFAULT), (unsigned long)heap_caps_get_free_size(MALLOC_CAP_DMA), (unsigned long)heap_caps_get_largest_free_block(MALLOC_CAP_DMA), (unsigned)uxTaskGetStackHighWaterMark(nullptr)); try { const auto result = NF_SAP::BTP_DATA_request_submit(*stack_, std::move(pending.request)); if (result == Result::accepted) ++counters_.requests_accepted; else ++counters_.requests_refused; } catch (const std::exception& e) { ESP_LOGE(TAG, "BTP_DATA_request_submit exception: %s", e.what()); ++counters_.requests_refused; } vam_pending_ = false; } void Station::deliver(BtpIndication received) { auto indication = NF_SAP::BTP_DATA_indication_from(std::move(received)); ++counters_.indications; if (indication_) indication_(to_link_indication(indication)); } namespace { // Keys of stored tickets that a new set no longer references. std::vector dropped_keys(const security::StoredCredentials& before, const security::StoredCredentials& after) { std::vector dropped; for (const auto& old : before.tickets) { const bool kept = std::any_of(after.tickets.begin(), after.tickets.end(), [&](const auto& t) { return t.key == old.key; }); if (!kept) dropped.push_back(old.key); } return dropped; } } // namespace // The stored set becomes `next`; ticket keys only the old set referenced are destroyed in the module. Result Station::store_credentials(const security::StoredCredentials& next) { security::NvsCredentialStore store; security::StoredCredentials before; const bool had = store.load(before) == Result::accepted; const auto saved = next.empty() ? store.erase() : store.save(next); if (saved != Result::accepted && !(next.empty() && saved == Result::rejected)) return saved; if (had) for (const auto key : dropped_keys(before, next)) module_->destroy_key(key); credentials_stale_ = true; // the next build decodes the new set return Result::accepted; } link::Code Station::provision(const link::Bytes& bundle, link::ApplyReport& report) { try { security::Credentials credentials; // Tickets are optional: the phone's TS 102 941 flow provisions the public trust (root, EA, AA) // first and adds the authorization ticket from the AA response afterwards. if (!security::decode(bundle, credentials) || credentials.roots.empty()) { return link::Code::invalid_argument; } auto* keys = module(); if (!keys) return link::Code::security_unavailable; auto stored = security::import_keys(credentials, *keys); for (auto& ticket : credentials.tickets) pki::erase_secret(ticket.key.key.data(), ticket.key.key.size()); if (!stored) return link::Code::invalid_argument; // a ticket key that does not belong to its certificate const auto saved = store_credentials(*stored); if (saved != Result::accepted) { for (const auto& ticket : stored->tickets) keys->destroy_key(ticket.key); return code(saved); } const auto parsed = link::ApplyReport {static_cast(stored->roots.size()), static_cast(stored->authorities.size()), static_cast(stored->tickets.size())}; stored.reset(); // not held while the station decodes the stored set credentials = {}; if (config_ && config_->security) { const auto result = build(); if (result != link::Code::accepted) return result; if (security_) { report.roots = security_->report.roots; report.authorities = security_->report.authorities; report.tickets = security_->report.tickets; ESP_LOGI(TAG, "credentials provisioned: %u roots, %u authorities, %u tickets", unsigned(report.roots), unsigned(report.authorities), unsigned(report.tickets)); } return link::Code::accepted; } report = parsed; return link::Code::accepted; } catch (const std::bad_alloc&) { ESP_LOGE(TAG, "out of memory provisioning credentials"); return link::Code::resource_limit; } catch (const std::exception& e) { ESP_LOGE(TAG, "failed provisioning credentials: %s", e.what()); return link::Code::invalid_argument; } } link::Code Station::erase_credentials() { if (!module()) return link::Code::security_unavailable; const auto erased = store_credentials({}); if (erased != Result::accepted) return code(erased); if (config_ && config_->security) return build(); return link::Code::accepted; } link::Code Station::subscribe(const link::Bytes& subscriber_data, std::uint64_t& subscription) { if (!security_ || !security_->entity) return link::Code::security_unavailable; static std::uint64_t next_handle = 1; const auto handle = next_handle++; link_subscriptions_[handle] = subscribe_id_change(handle, subscriber_data); subscription = handle; return link::Code::accepted; } link::Code Station::unsubscribe(std::uint64_t subscription) { const auto it = link_subscriptions_.find(subscription); if (it == link_subscriptions_.end()) return link::Code::invalid_argument; Result result = Result::accepted; if (security_ && security_->entity) result = security_->entity->id_change().unsubscribe(it->second); link_subscriptions_.erase(it); pending_responders_.erase(subscription); return code(result); } link::Code Station::event_response(std::uint64_t subscription, bool return_code) { const auto it = pending_responders_.find(subscription); if (it == pending_responders_.end()) return link::Code::invalid_argument; it->second->respond(return_code); pending_responders_.erase(it); return link::Code::accepted; } link::Code Station::trigger() { if (!security_ || !security_->entity) return link::Code::security_unavailable; return code(security_->entity->id_change().trigger()); } link::Code Station::lock(std::uint8_t seconds, std::uint64_t& handle) { if (!security_ || !security_->entity) return link::Code::security_unavailable; handle = security_->entity->id_change().lock(seconds); return link::Code::accepted; } link::Code Station::unlock(std::uint64_t handle) { if (!security_ || !security_->entity) return link::Code::security_unavailable; return code(security_->entity->id_change().unlock(handle)); } void Station::tick() { const auto monotonic_ms = static_cast(esp_timer_get_time() / 1000); for (unsigned index = 0; index < 2; ++index) { auto& pending = pki_pending_[index]; if (pending && (index == 0 ? !pending->retry.poll(monotonic_ms) : monotonic_ms - pending->created_ms >= 60000)) pending.reset(); } if (managed_trust_deadline_ && !managed_trust_expired_ && clock_.synchronised && clock_.now_us() / 1000000 >= managed_trust_deadline_) { credentials_stale_ = true; pki_pending_[0].reset(); pki_pending_[1].reset(); if (config_ && config_->security) build(); } const bool running = stack_ && clock_.synchronised; if (running) { const auto now = vanetza::Clock::time_point(std::chrono::microseconds(clock_.now_us())); if (now > runtime_->now()) stack_->advance(now); } // The raw capture runs without a synchronised clock too, as the OTM receiver does; the stack // only receives frames once PoTi has set the ITS clock. // MicrOBU: the radio queue (16 frames) is drained and raw frames forwarded from the moment the // station has a radio, PoTi or not; without a synchronised clock the stack just gets nothing. if (radio_) { C5Radio::Receive receive; if (running) { receive = [this](AlDataIndication indication) { ++counters_.radio_received; if (received_) received_(); if (stack_) stack_->indicate(std::move(indication)); }; } C5Radio::Capture capture; if (raw_mode_ & C5Radio::capture_on) { capture = [this](const vanetza::ByteBuffer& frame, int rssi, std::uint32_t local_us) { emit_raw(frame.data(), frame.size(), rssi, local_us, false); }; } radio_->poll(receive, capture, [this](const vanetza::ByteBuffer& frame, int rssi) { forward_raw(frame, rssi); }); counters_.radio_dropped = radio_->dropped_frames(); } if (running) sample_dcc_channel_load(); } link::Code Station::raw_capture(std::uint8_t mode) { if (!capture_policy::valid_mode(mode)) return link::Code::invalid_argument; mode = capture_policy::effective_mode(mode); if ((mode & C5Radio::capture_on) && !radio_) return link::Code::not_configured; // configure radio rx or txrx first if ((mode & C5Radio::capture_on) && !(raw_mode_ & C5Radio::capture_on)) raw_counter_ = 0; raw_mode_ = mode; if (radio_) radio_->set_capture(mode); return link::Code::accepted; } void Station::emit_raw(const std::uint8_t* data, std::size_t size, int rssi, std::uint32_t local_us, bool own_tx) { if (!raw_frame_ || !(raw_mode_ & C5Radio::capture_on)) return; // ITS5 record time (V2X2Map bridge format: u32 seconds, u32 microseconds). The OTM receiver uses // rx_ctrl.timestamp, i.e. time since boot; once PoTi has synchronised the ITS clock the record // carries UTC instead: TimestampIts (TAI ms since 2004-01-01T00:00:00Z) minus the 5 leap // seconds since 2004, plus the Unix time of the ITS epoch (1072915200 s). std::uint8_t flags = own_tx ? 0x01 : 0x00; std::int64_t record_us = local_us; if (clock_.synchronised) { const std::uint32_t age_us = static_cast(esp_timer_get_time()) - local_us; // wraps like rx_ctrl const std::int64_t its_us = clock_.now_us() - (age_us < 10000000u ? age_us : 0u); record_us = its_us + (1072915200LL - 5LL) * 1000000LL; flags |= 0x02; } link::Writer w; w.u32(++raw_counter_); w.u8(flags); w.u8(static_cast(static_cast(rssi))); static constexpr std::uint8_t magic[4] = {'I', 'T', 'S', '5'}; w.bytes(magic, 4); w.u32(static_cast(record_us / 1000000)); w.u32(static_cast(record_us % 1000000)); w.u16(static_cast(size)); w.bytes(data, size); raw_frame_(w.out); } // Sample the hardware LCBR counters at the T_Cbr cadence (TS 102 687 clause 5.4 / // TS 103 836-4-2 clause 5.2, both 100 ms) and feed both DCC entities. The first sample after // (re)build only establishes the baseline counter snapshot -- a CBR delta needs two samples. void Station::sample_dcc_channel_load() { if (!radio_ || !access_stack_) return; const auto its_us = clock_.now_us(); if (its_us - dcc_last_sample_its_us_ < 100000) return; const auto counters = radio_->read_cca_counters(); const auto mono_us = esp_timer_get_time(); // A window read at or beyond one counter wrap (3.36 s, a delayed task), with no elapsed cycle, or across a counter // restart (every 3.36 s) cannot be measured: the reading becomes the next baseline instead of a wrong CBR // (cca_window.hpp). const auto cbr = dcc_cca_last_ && !counters.restarted ? cca::window_cbr(counters.total_cycles, counters.busy_cycles, dcc_cca_last_->total_cycles, dcc_cca_last_->busy_cycles, mono_us - dcc_last_sample_mono_us_) : std::nullopt; if (dcc_cca_last_ && !counters.restarted && !cbr && (dcc_invalid_windows_++ % 100) == 0) { ESP_LOGW(TAG, "DCC: CBR window skipped (%lld us since the last read, %u skipped so far)", static_cast(mono_us - dcc_last_sample_mono_us_), static_cast(dcc_invalid_windows_)); } if (cbr) { const vanetza::dcc::ChannelLoad local_cbr(*cbr); stack_->report_local_channel_load(local_cbr); const auto global_cbr = stack_->global_channel_busy_ratio(); // Consume Release-2 CBR_G for DCC_ACC when available, else LCBR. access_stack_->report_channel_load(global_cbr ? *global_cbr : local_cbr); cbr_local_ = local_cbr.value(); cbr_global_ = global_cbr ? std::optional(global_cbr->value()) : std::nullopt; update_t_gen_vam(its_us); } if (counters.restarted) dcc_cca_last_.reset(); // the restart may have cleared the counters: no baseline yet else dcc_cca_last_ = counters; dcc_last_sample_its_us_ = its_us; dcc_last_sample_mono_us_ = mono_us; } namespace { // Airtime of a frame with `octets` MPDU octets at the request's MCS (same formula as the DCC_ACC gate // in microbu_v2x access.cpp: vanetza's TransmissionLite channel occupancy with the G5 rate table). std::uint32_t airtime_us(std::size_t octets, microbu_v2x::OfdmMcs mcs) { static constexpr std::array rates { &vanetza::access::G5_3Mbps, &vanetza::access::G5_4dot5Mbps, &vanetza::access::G5_6Mbps, &vanetza::access::G5_9Mbps, &vanetza::access::G5_12Mbps, &vanetza::access::G5_18bps, &vanetza::access::G5_24Mbps, &vanetza::access::G5_27Mbps, }; vanetza::dcc::TransmissionLite transmission(vanetza::dcc::Profile::DP2, octets); const auto index = static_cast(mcs); transmission.m_data_rate = index < rates.size() ? rates[index] : rates[2]; return static_cast(std::chrono::duration_cast(transmission.channel_occupancy()).count()); } } // namespace // TS 103 300-3 V2.3.1 clause 6.2: for ITS-G5, T_GenVam is managed according to DCC and provided by // the management entity. Project realisation: the Adaptive approach's permitted duty cycle delta and // the gate keeper of TS 102 687 V1.2.1 Annex B, equation (B.1): a packet of airtime Ton_pp may follow // the previous one after min(max(Ton_pp / delta, 25 ms), 1 s). With the airtime of the station's own // VAM frame this is the shortest VAM interval DCC_ACC admits; the VBS clamps it to // [T_GenVamMin, T_GenVamMax] itself. void Station::update_t_gen_vam(std::int64_t its_us) { const double delta = access_stack_->permitted_duty_cycle().value(); const std::uint32_t ton_us = vam_ton_us_ ? vam_ton_us_ : airtime_us(300, radio_parameters_.mcs); // before the first VAM double interval_ms = delta > 0.0 ? ton_us / delta / 1000.0 : 1000.0; interval_ms = std::min(std::max(interval_ms, 25.0), 1000.0); t_gen_vam_ms_ = static_cast(std::lround(interval_ms)); const bool changed = t_gen_vam_sent_ms_ == 0 || std::abs(int(t_gen_vam_ms_) - int(t_gen_vam_sent_ms_)) * 10 > int(t_gen_vam_sent_ms_); // > 10 % if (!dcc_update_ || (!changed && its_us - t_gen_vam_sent_us_ < 1000000)) return; link::Writer w; w.u16(t_gen_vam_ms_); w.u16(static_cast(std::lround(delta * 10000))); const double cbr = cbr_global_ ? *cbr_global_ : cbr_local_.value_or(0.0); w.u16(static_cast(std::lround(cbr * 10000))); w.u16(static_cast(std::min(ton_us, 0xFFFF))); dcc_update_(w.out); t_gen_vam_sent_ms_ = t_gen_vam_ms_; t_gen_vam_sent_us_ = its_us; } link::Status Station::status() { link::Status s = counters_; s.uptime_ms = static_cast(esp_timer_get_time() / 1000); s.configured = stack_ ? 1 : 0; if (stack_) { ByteBuffer address; gn::serialize_into_buffer(stack_->address(), address); std::copy_n(address.begin(), std::min(address.size(), 8), s.gn_address); s.change_pending = stack_->identity_change_pending() ? 1 : 0; } if (security_ && security_->entity) { const auto id = security_->entity->id_change().current_identifier(); std::copy(id.begin(), id.end(), s.identifier); s.tickets = static_cast(std::min(security_->pool.size(), 255)); const auto& st = security_->entity->statistics(); s.signed_messages = st.signed_messages; s.refused_no_ticket = st.refused_no_ticket; s.refused_change_pending = st.refused_change_pending; s.refused_permission = st.refused_permission; s.sign_failed = st.failed; s.verified = st.verified; s.rejected = st.rejected_profile + st.rejected_signer + st.rejected_certificate + st.rejected_signature + st.rejected_time + st.replayed; } s.its_time_ms = clock_.synchronised ? static_cast(clock_.now_us() / 1000) : 0; auto ratio = [](std::optional v) { return v ? static_cast(std::lround(std::min(std::max(*v, 0.0), 1.0) * 10000)) : std::uint16_t(0xFFFF); }; s.cbr_local = ratio(cbr_local_); s.cbr_global = ratio(cbr_global_); s.dcc_delta = access_stack_ ? ratio(access_stack_->permitted_duty_cycle().value()) : std::uint16_t(0xFFFF); s.t_gen_vam_dcc_ms = t_gen_vam_ms_; s.heap_free = esp_get_free_heap_size(); s.heap_minimum_free = esp_get_minimum_free_heap_size(); s.heap_largest_block = heap_caps_get_largest_free_block(MALLOC_CAP_DEFAULT); s.dma_largest_block = heap_caps_get_largest_free_block(MALLOC_CAP_DMA); return s; } Result Station::request(AlDataRequest request) { if (vam_pending_) vam_ton_us_ = airtime_us(request.data.size(), request.mcs); // same size basis as the DCC_ACC gate if (!radio_) { ++counters_.radio_failed; return Result::unsupported; // no radio configured and nothing diverting: the request has nowhere to go } #if CONFIG_MICROBU_TX_BLE_GUARD hold_for_ble_guard(); #endif // Adaptive DCC_ACC gates here when access_stack_ has it enabled (build()); it falls // through to radio_->request() unchanged otherwise. const auto result = access_stack_ ? access_stack_->request(std::move(request)) : radio_->request(std::move(request)); count_radio_result(result); return result; } // Shared radio scheduling: the C5 shares its RF between BLE and ITS-G5; a broadcast frame handed to the driver // while a BLE connection event is due is accepted but never transmitted (and never retried). The lossy phase // windows after the last BLE write (the host's view of the connection-event anchor) are calibrated per // connection interval (tx_policy); a frame due inside one waits for its end (at most 3.5 ms). std::int64_t Station::hold_for_ble_guard() const { const auto anchor = ble::last_write_us(); if (!anchor) return 0; const auto interval = static_cast(ble::connection_interval_us()); static std::int64_t warned_interval = 0; // one warning per uncalibrated interval the link switches to if (tx_policy::guard_windows(interval).empty() && interval != warned_interval) { warned_interval = interval; ESP_LOGW(TAG, "BLE interval %lld us has no calibrated TX guard: frames may be lost", static_cast(interval)); } const auto delay = tx_policy::guard_delay_us(esp_timer_get_time() - anchor, interval); if (delay > 0) esp_rom_delay_us(static_cast(delay)); return delay; } void Station::count_radio_result(Result result) { if (result == Result::accepted) { ++counters_.radio_submitted; if (disseminated_) disseminated_(); return; } ++counters_.radio_failed; static std::int64_t last_report = 0; // one line per second, the counter has the rest const auto now = esp_timer_get_time(); if (now - last_report > 1000000) { last_report = now; ESP_LOGW(TAG, "radio refused a frame: result %d", int(result)); } } // ---- TS 102 941 V2.2.1 on the device ---------------------------------------------------------------- using vanetza::security::KeyType; using Certificate = vanetza::security::v3::Certificate; namespace { constexpr const char* kPkiNamespace = "pki"; bool pki_load(const char* key, ByteBuffer& out) { nvs_handle_t handle; if (nvs_open(kPkiNamespace, NVS_READONLY, &handle) != ESP_OK) return false; std::size_t size = 0; bool ok = nvs_get_blob(handle, key, nullptr, &size) == ESP_OK && size > 0; if (ok) { out.resize(size); ok = nvs_get_blob(handle, key, out.data(), &size) == ESP_OK; } nvs_close(handle); return ok; } bool pki_store(const char* key, const ByteBuffer& data) { nvs_handle_t handle; if (nvs_open(kPkiNamespace, NVS_READWRITE, &handle) != ESP_OK) return false; const bool ok = nvs_set_blob(handle, key, data.data(), data.size()) == ESP_OK && nvs_commit(handle) == ESP_OK; nvs_close(handle); return ok; } // TS 102 941 clause 6.2.3.2.1: the canonical identifier the EA registered for this ITS-S. Stable per device. ByteBuffer canonical_identifier() { std::uint8_t mac[6] = {}; esp_read_mac(mac, ESP_MAC_WIFI_STA); char text[24]; std::snprintf(text, sizeof(text), "micrOBU-%02X%02X%02X%02X%02X%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); return ByteBuffer(text, text + std::strlen(text)); } ByteBuffer point(const PublicKey& key) { // uncompressed SEC1 point 04 || x || y ByteBuffer out {0x04}; out.insert(out.end(), key.x.begin(), key.x.end()); out.insert(out.end(), key.y.begin(), key.y.end()); return out; } ByteBuffer encode_key_id(security::KeyId key) { return {static_cast(key.value >> 24), static_cast(key.value >> 16), static_cast(key.value >> 8), static_cast(key.value)}; } // A KeyId kept under an NVS key of the pki namespace (4 octets, big-endian). std::optional load_key_id(const char* name) { ByteBuffer stored; if (!pki_load(name, stored) || stored.size() != 4) return std::nullopt; const security::KeyId key {std::uint32_t(stored[0]) << 24 | std::uint32_t(stored[1]) << 16 | std::uint32_t(stored[2]) << 8 | stored[3]}; if (!key) return std::nullopt; return key; } } // namespace // The canonical key: generated in the security module the first time it is needed; NVS keeps its KeyId. std::optional Station::canonical_key() { auto* keys = module(); if (!keys) return std::nullopt; if (const auto stored = load_key_id("canonical")) { if (keys->public_key(*stored)) return stored; ESP_LOGE(TAG, "the security module lost the canonical key: the EA registration is void"); return std::nullopt; } const auto key = keys->generate_key(KeyType::NistP256); if (!pki_store("canonical", encode_key_id(key))) { keys->destroy_key(key); throw std::runtime_error("canonical key not stored"); } ESP_LOGI(TAG, "canonical key generated in the security module"); return key; } // The enrolment credential: certificate and the KeyId of its key, both in NVS. std::optional> Station::enrolment_credential() { ByteBuffer encoded; Certificate ec; const auto key = load_key_id("ec_key"); if (!module() || !key || !pki_load("ec_cert", encoded) || !ec.decode(encoded)) return std::nullopt; return std::make_pair(std::move(ec), *key); } link::Code Station::pki_identity(link::Bytes& detail) { const auto key = canonical_key(); const auto pub = key ? module_->public_key(*key) : std::nullopt; if (!pub) return link::Code::security_unavailable; const auto id = canonical_identifier(); link::Writer w; w.u8(static_cast(id.size())); w.bytes(id); w.bytes(point(*pub)); detail = w.out; return link::Code::accepted; } link::Code Station::pki_trust_bootstrap(const link::Bytes& bytes) { // TS 102 941 clause 6.1.2: initial TLM trust is an independent provisioning input. if (bytes.size() < 9) return link::Code::invalid_argument; const ByteBuffer encoded(bytes.begin() + 8, bytes.end()); Certificate tlm; if (!tlm.decode(encoded) || tlm.encode() != encoded) return link::Code::invalid_argument; const auto digest = tlm.calculate_digest(); if (!digest || !std::equal(digest->begin(), digest->end(), bytes.begin())) return link::Code::rejected; ByteBuffer previous; if (pki_load("tlm_pin", previous)) return previous == encoded ? link::Code::accepted : link::Code::rejected; return pki_store("tlm_pin", encoded) ? link::Code::accepted : link::Code::resource_limit; } link::Code Station::pki_trust_update(const link::Bytes& bytes) { if (!clock_.synchronised || !security_ || !runtime_) return link::Code::not_configured; pki::TrustSnapshot proposed, previous, accepted; ByteBuffer stored, pin; const bool existing = pki_load("trust_snapshot", stored); if (!pki::decode_snapshot(bytes, proposed) || (existing && !pki::decode_snapshot(stored, previous)) || !pki_load("tlm_pin", pin)) return link::Code::rejected; if (!pki::validate_update(security_->backend, runtime_->now(), pin, existing ? &previous : nullptr, proposed, accepted)) return link::Code::rejected; const auto encoded = pki::encode_snapshot(accepted); if (encoded.empty() || !pki_store("trust_snapshot", encoded)) return link::Code::resource_limit; // One NVS blob commits all signed objects and replay state before activation. pki_pending_[0].reset(); pki_pending_[1].reset(); credentials_stale_ = true; return config_ && config_->security ? build() : link::Code::accepted; } // ETSI TS 102 941 clauses 6.1.3 and 6.1.5: expose validity, never private keys. link::Code Station::pki_status(link::Bytes& detail) { if (!clock_.synchronised || !security_ || !runtime_) return link::Code::not_configured; const auto now = runtime_->now(); auto end = [](const Certificate& cert) { return microbu_v2x::security::validity_bounds(cert).end_validity; }; std::uint32_t ec_end = 0, vam_end = 0, cam_end = 0; if (const auto credential = enrolment_credential()) { const auto& ec = credential->first; const auto ec_key = module_->public_key(credential->second); const auto issuer = ec.issuer_digest(); const auto* ea = issuer ? security_->trust.issuers().find_issuer(*issuer) : nullptr; const auto root = ea ? ea->issuer_digest() : boost::optional(); const bool revoked = root && (security_->trust.revocations().is_revoked(*root, *issuer) || security_->trust.revocations().is_revoked(*root, *root)); if (ea && ec_key && !revoked && pki::validate_issued_certificate(security_->backend, ec, *ea, *ec_key, now, {{vanetza::aid::SCR, {1, 0xc0}}}, true)) ec_end = end(ec); } for (const auto& ticket : security_->pool.tickets()) { if (!ticket.certificate.valid_at_timepoint(now)) continue; const auto issuer = ticket.certificate.issuer_digest(); const auto* aa = issuer ? security_->trust.issuers().find_issuer(*issuer) : nullptr; if (!aa || !aa->valid_at_timepoint(now)) continue; const auto root = aa->issuer_digest(); if (!root || security_->trust.revocations().is_revoked(*root, *issuer) || security_->trust.revocations().is_revoked(*root, *root)) continue; if (ticket.certificate.valid_for_application(vanetza::aid::VRU)) vam_end = std::max(vam_end, end(ticket.certificate)); if (ticket.certificate.valid_for_application(vanetza::aid::CA)) cam_end = std::max(cam_end, end(ticket.certificate)); } link::Writer writer; writer.u8(1); writer.u32(static_cast(std::chrono::duration_cast(now.time_since_epoch()).count())); writer.u32(ec_end); writer.u32(vam_end); writer.u32(cam_end); writer.u32(managed_trust_deadline_); writer.u8((pki_pending_[0] ? 1 : 0) | (pki_pending_[1] ? 2 : 0)); detail = std::move(writer.out); return link::Code::accepted; } link::Code Station::pki_request(std::uint8_t kind, const link::Bytes& body, link::Bytes& request) { if (kind != 1 && kind != 2) return link::Code::invalid_argument; if (pki_pending_[kind - 1]) return link::Code::busy; if (!security_ || !runtime_) return link::Code::not_configured; // needs the trust set and the station clock if (!clock_.synchronised) return link::Code::rejected; // generationTime of the request link::Reader r(body); security::HashedId8 ea {}, aa {}; r.bytes(ea.data(), ea.size()); if (kind == 2) r.bytes(aa.data(), aa.size()); const auto application = kind == 2 && body.size() == 17 ? r.u8() : 0; if (application > 1) return link::Code::invalid_argument; const auto renewal = kind == 1 && body.size() == 9 ? r.u8() : 0; if (renewal > 1) return link::Code::invalid_argument; if (!r.done()) return link::Code::malformed; const Certificate* ea_cert = security_->trust.issuers().find_issuer(ea); const Certificate* aa_cert = kind == 2 ? security_->trust.issuers().find_issuer(aa) : nullptr; const auto usable_authority = [&](const Certificate* cert) { if (!cert || !cert->valid_at_timepoint(runtime_->now())) return false; const auto issuer = cert->issuer_digest(), digest = cert->calculate_digest(); const auto* root = issuer ? security_->trust.issuers().find_issuer(*issuer) : nullptr; return root && root->issuer_is_self() && root->valid_at_timepoint(runtime_->now()) && digest && !security_->trust.revocations().is_revoked(*issuer, *digest) && !security_->trust.revocations().is_revoked(*issuer, *issuer); }; if (!usable_authority(ea_cert) || (kind == 2 && !usable_authority(aa_cert))) return link::Code::no_credentials; auto* keys = module(); if (!keys) return link::Code::security_unavailable; pki::EciesMbedTls ecies; // the new EC or AT key, generated in the security module const auto new_key = keys->generate_key(KeyType::NistP256); auto pending = std::make_unique(*keys, new_key, *keys->public_key(new_key)); pending->ea = ea; pending->aa = aa; const pki::SigningKey verification_key {pending->public_key, pki::module_signer(*keys, new_key)}; Result built; if (kind == 1) { pki::EnrolmentRequestParameters params; params.its_id = canonical_identifier(); params.verification_key = verification_key; params.app_permissions = {{vanetza::aid::SCR, {0x01, 0xc0}}}; pending->permissions = params.app_permissions; const auto canonical = canonical_key(); if (!canonical) return link::Code::security_unavailable; params.outer_signer = pki::module_signer(*keys, *canonical); // initial enrolment: canonical key std::optional> current; if (renewal == 1) { current = enrolment_credential(); const auto current_key = current ? keys->public_key(current->second) : std::nullopt; if (!current_key) return link::Code::no_credentials; if (!pki::validate_issued_certificate(security_->backend, current->first, *ea_cert, *current_key, runtime_->now(), params.app_permissions, true)) return link::Code::rejected; const auto id = current->first.calculate_digest(); if (!id) return link::Code::rejected; params.its_id.assign(id->begin(), id->end()); params.current_ec = ¤t->first; params.outer_signer = pki::module_signer(*keys, current->second); // re-enrolment: current EC key } built = pki::build_enrolment_request(security_->backend, ecies, runtime_->now(), params, *ea_cert, request, pending->context); } else { const auto ec = enrolment_credential(); if (!ec) return link::Code::no_credentials; pki::AuthorizationRequestParameters params; params.verification_key = verification_key; // ETSI TS 103 300-3 V2.3.1 clause 6.5.2: VAM service permission. params.app_permissions = application == 1 ? pki::Permissions {{vanetza::aid::CA, {0x01, 0x00, 0x00}}} : pki::Permissions {{vanetza::aid::VRU, {0x01}}}; pending->permissions = params.app_permissions; params.ec = &ec->first; params.ec_signer = pki::module_signer(*keys, ec->second); built = pki::build_authorization_request(security_->backend, ecies, runtime_->now(), params, *ea_cert, *aa_cert, request, pending->context); } if (built != Result::accepted) return code(built); pending->created_ms = static_cast(esp_timer_get_time() / 1000); if (kind == 1) { pending->request = request; if (!pending->retry.begin(pending->created_ms)) return link::Code::invalid_argument; } pki_pending_[kind - 1] = std::move(pending); ESP_LOGI(TAG, "%s request built on the device (%u octets)", kind == 1 ? "enrolment" : "authorization", unsigned(request.size())); return link::Code::accepted; } // ETSI TS 103 601 clause 5.1.2 repeats the same serialized enrolment request. link::Code Station::pki_retry(std::uint8_t kind, link::Bytes& request) { if (kind != 1) return kind == 2 ? link::Code::unsupported : link::Code::invalid_argument; auto& pending = pki_pending_[0]; if (!pending) return link::Code::rejected; const auto now = static_cast(esp_timer_get_time() / 1000); if (!pending->retry.repeat(now)) { if (!pending->retry.active()) { pending.reset(); return link::Code::rejected; } return link::Code::busy; } request = pending->request; return link::Code::accepted; } link::Code Station::pki_cancel(std::uint8_t kind) { if (kind != 1 && kind != 2) return link::Code::invalid_argument; pki_pending_[kind - 1].reset(); return link::Code::accepted; } link::Code Station::pki_response(std::uint8_t kind, const link::Bytes& response, link::Bytes& detail) { if (kind != 1 && kind != 2) return link::Code::invalid_argument; auto& pending = pki_pending_[kind - 1]; if (!pending || !security_) return link::Code::rejected; // no outstanding request pki::EciesMbedTls ecies; const Certificate* ea_cert = security_->trust.issuers().find_issuer(pending->ea); const Certificate* aa_cert = kind == 2 ? security_->trust.issuers().find_issuer(pending->aa) : nullptr; if (!ea_cert || (kind == 2 && !aa_cert)) return link::Code::no_credentials; std::uint8_t response_code = 0xFF; std::optional certificate; Result parsed; if (kind == 1) { pki::EnrolmentResponse r; parsed = pki::parse_enrolment_response(security_->backend, ecies, pending->context, *ea_cert, response, r); response_code = r.response_code; certificate = std::move(r.certificate); } else { pki::AuthorizationResponse r; parsed = pki::parse_authorization_response(security_->backend, ecies, pending->context, *aa_cert, response, r); response_code = r.response_code; certificate = std::move(r.certificate); } if (parsed != Result::accepted) { // A forged or unrelated response does not terminate the valid transaction. detail = {0xff}; return code(parsed); } if (response_code != 0 || !certificate) { ESP_LOGW(TAG, "%s response refused (result %d, response code %u)", kind == 1 ? "enrolment" : "authorization", int(parsed), unsigned(response_code)); pending.reset(); detail = {response_code}; return parsed != Result::accepted ? code(parsed) : link::Code::rejected; } const auto* issuer = kind == 1 ? ea_cert : aa_cert; if (!pki::validate_issued_certificate(security_->backend, *certificate, *issuer, pending->public_key, runtime_->now(), pending->permissions, kind == 1)) { pending.reset(); detail = {0xff}; return link::Code::rejected; } const auto digest = certificate->calculate_digest(); if (kind == 1) { const auto previous = load_key_id("ec_key"); if (!pki_store("ec_cert", certificate->encode()) || !pki_store("ec_key", encode_key_id(pending->key))) return link::Code::resource_limit; const auto installed = pending->release(); if (previous && *previous != installed) module_->destroy_key(*previous); // the replaced EC's key ESP_LOGI(TAG, "enrolment credential stored on the device"); } else { // the new ticket joins the stored credentials with the key generated for it here security::StoredCredentials credentials; security::NvsCredentialStore store; if (store.load(credentials) != Result::accepted) return link::Code::no_credentials; // TS 102 941 clause 6.2.3.3.2: install the newly granted AT for subsequent use. credentials.tickets.insert(credentials.tickets.begin(), {certificate->encode(), pending->key}); const auto saved = store.save(credentials); if (saved != Result::accepted) return code(saved); pending->release(); credentials_stale_ = true; ESP_LOGI(TAG, "authorization ticket stored on the device (%u tickets)", unsigned(credentials.tickets.size())); } pending.reset(); link::Writer w; w.u8(response_code); if (digest) w.bytes(digest->data(), digest->size()); else w.bytes(security::HashedId8 {}.data(), 8); detail = w.out; if (kind == 2 && config_ && config_->security) return build(); // the pool now holds the new ticket return link::Code::accepted; } } // namespace microbu