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,97 @@
|
||||
#include <microbu_v2x/access.hpp>
|
||||
#include <cmath>
|
||||
#include <utility>
|
||||
#if V2X_NETWORK
|
||||
#include <vanetza/access/data_rates.hpp>
|
||||
#include <vanetza/dcc/limeric.hpp>
|
||||
#include <vanetza/dcc/limeric_budget.hpp>
|
||||
#include <vanetza/dcc/profile.hpp>
|
||||
#include <vanetza/dcc/transmission.hpp>
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#endif
|
||||
|
||||
namespace microbu_v2x {
|
||||
Result validate(const AlDataRequest& request, std::size_t maximum) {
|
||||
if (request.data.empty() || request.data.size() > maximum || request.priority > 7 ||
|
||||
!std::isfinite(request.transmit_power_dbm) || request.bandwidth_mhz == 0)
|
||||
return Result::invalid_argument;
|
||||
return Result::accepted;
|
||||
}
|
||||
#if V2X_NETWORK
|
||||
namespace {
|
||||
// EN 303 797 V2.1.1 clause 4.6.2's Ton limit; a single
|
||||
// frame at or below this duration also cannot alone exceed the 3 % duty cycle at Toff>=25 ms.
|
||||
constexpr vanetza::Clock::duration max_ton = std::chrono::milliseconds(4);
|
||||
// Index by OfdmMcs; mirrors the rate table in C5Radio::request/transmit_burst.
|
||||
constexpr std::array<const vanetza::access::DataRateG5*, 8> g5_rates {
|
||||
&vanetza::access::G5_3Mbps, &vanetza::access::G5_4dot5Mbps, &vanetza::access::G5_6Mbps,
|
||||
&vanetza::access::G5_9Mbps, &vanetza::access::G5_12Mbps, &vanetza::access::G5_18bps,
|
||||
&vanetza::access::G5_24Mbps, &vanetza::access::G5_27Mbps,
|
||||
};
|
||||
// Airtime-only use of Transmission::channel_occupancy(); profile is immaterial here since no
|
||||
// FlowControl queueing is involved, only the data-rate/length formula.
|
||||
vanetza::Clock::duration request_airtime(const AlDataRequest& request) {
|
||||
vanetza::dcc::TransmissionLite transmission(vanetza::dcc::Profile::DP2, request.data.size());
|
||||
const auto index = static_cast<unsigned>(request.mcs);
|
||||
transmission.m_data_rate = index < g5_rates.size() ? g5_rates[index] : nullptr;
|
||||
return transmission.channel_occupancy();
|
||||
}
|
||||
// TS 102 687 V1.2.1 Table 3 defaults, with cbr_target overridden to the project's Release-2
|
||||
// value.
|
||||
vanetza::dcc::Limeric::Parameters limeric_parameters(vanetza::dcc::ChannelLoad cbr_target) {
|
||||
vanetza::dcc::Limeric::Parameters parameters;
|
||||
parameters.cbr_target = cbr_target;
|
||||
return parameters;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class AccessStack::Dcc {
|
||||
public:
|
||||
Dcc(vanetza::Runtime& rt, vanetza::dcc::ChannelLoad target) :
|
||||
limeric(rt, limeric_parameters(target)),
|
||||
budget(limeric, rt)
|
||||
{
|
||||
// TS 102 687 V1.2.1 Annex B: the gate-opening time depends on the current permitted
|
||||
// duty cycle, so it must be recalculated whenever the Adaptive approach updates delta.
|
||||
limeric.on_duty_cycle_change = [this](const vanetza::dcc::Limeric*, vanetza::Clock::time_point) {
|
||||
budget.update();
|
||||
};
|
||||
}
|
||||
vanetza::dcc::Limeric limeric;
|
||||
vanetza::dcc::LimericBudget budget;
|
||||
};
|
||||
|
||||
void AccessStack::enable_dcc(vanetza::Runtime& runtime, vanetza::dcc::ChannelLoad cbr_target) {
|
||||
dcc_ = std::make_unique<Dcc>(runtime, cbr_target);
|
||||
}
|
||||
|
||||
void AccessStack::report_channel_load(vanetza::dcc::ChannelLoad load) {
|
||||
if (dcc_) dcc_->limeric.update_cbr(load);
|
||||
}
|
||||
|
||||
vanetza::UnitInterval AccessStack::permitted_duty_cycle() const {
|
||||
return dcc_ ? dcc_->limeric.permitted_duty_cycle() : vanetza::UnitInterval(1.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
AccessStack::AccessStack(Access& access, std::size_t maximum) :
|
||||
access_(access), maximum_gnpdu_(maximum) {}
|
||||
AccessStack::~AccessStack() = default;
|
||||
|
||||
Result AccessStack::request(AlDataRequest request) {
|
||||
auto result = validate(request, maximum_gnpdu_);
|
||||
if (result != Result::accepted) return result;
|
||||
#if V2X_NETWORK
|
||||
if (dcc_) {
|
||||
const auto ton = request_airtime(request);
|
||||
if (ton <= vanetza::Clock::duration::zero() || ton > max_ton) return Result::invalid_argument;
|
||||
if (dcc_->budget.delay() > vanetza::Clock::duration::zero()) return Result::resource_limit;
|
||||
result = access_.request(std::move(request));
|
||||
if (result == Result::accepted) dcc_->budget.notify(ton);
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
return access_.request(std::move(request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/sha.hpp>
|
||||
#include <psa/crypto.h>
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
|
||||
psa_ecc_family_t family(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
|
||||
case KeyType::BrainpoolP256r1:
|
||||
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
|
||||
default: throw std::runtime_error("unsupported key type");
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t curve_bits(KeyType type) { return key_length(type) * 8; }
|
||||
|
||||
struct ScopedKey {
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
~ScopedKey() { if (id) psa_destroy_key(id); }
|
||||
};
|
||||
|
||||
// SEC 1 uncompressed encoding of a generic public key, recovering y when compressed.
|
||||
vanetza::ByteBuffer public_key_octets(const PublicKey& key) {
|
||||
Uncompressed point;
|
||||
switch (key.compression) {
|
||||
case KeyCompression::NoCompression:
|
||||
point.x = key.x; point.y = key.y;
|
||||
break;
|
||||
case KeyCompression::Y0:
|
||||
case KeyCompression::Y1: {
|
||||
auto recovered = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
|
||||
if (!recovered) throw std::runtime_error("public key is not on the curve");
|
||||
point = std::move(*recovered);
|
||||
break;
|
||||
}
|
||||
default: throw std::runtime_error("unsupported point compression");
|
||||
}
|
||||
if (point.x.size() != key_length(key.type) || point.y.size() != key_length(key.type))
|
||||
throw std::runtime_error("public key coordinate length");
|
||||
return ecc::encode_uncompressed(point);
|
||||
}
|
||||
|
||||
// The digest handed in is the SHA-256/SHA-384 output IEEE Std 1609.2 clause 5.3.1 prescribes
|
||||
// for the curve, so the operation names that hash: implementations that accelerate ECDSA
|
||||
// (ESP-IDF's PSA driver for the ESP32-C5 ECDSA peripheral, CONFIG_MBEDTLS_HARDWARE_ECDSA_VERIFY)
|
||||
// only take PSA_ALG_ECDSA(PSA_ALG_SHA_256/384), never PSA_ALG_ECDSA_ANY, which falls back to
|
||||
// software. Keys are imported with the wildcard policy so either form is permitted.
|
||||
psa_algorithm_t ecdsa_algorithm(std::size_t digest_octets) {
|
||||
switch (digest_octets) {
|
||||
case 32: return PSA_ALG_ECDSA(PSA_ALG_SHA_256);
|
||||
case 48: return PSA_ALG_ECDSA(PSA_ALG_SHA_384);
|
||||
default: return PSA_ALG_ECDSA_ANY;
|
||||
}
|
||||
}
|
||||
|
||||
mbedtls_svc_key_id_t import_public(KeyType type, const vanetza::ByteBuffer& sec1) {
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(family(type)));
|
||||
psa_set_key_bits(&attributes, curve_bits(type));
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, sec1.data(), sec1.size(), &id) != PSA_SUCCESS)
|
||||
throw std::runtime_error("PSA public key import failed");
|
||||
return id;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer raw_signature(mbedtls_svc_key_id_t key, KeyType type, const vanetza::ByteBuffer& digest) {
|
||||
vanetza::ByteBuffer signature(2 * key_length(type));
|
||||
std::size_t length = 0;
|
||||
const auto status = psa_sign_hash(key, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
|
||||
signature.data(), signature.size(), &length);
|
||||
if (status != PSA_SUCCESS || length != signature.size()) throw std::runtime_error("PSA ECDSA signing failed");
|
||||
return signature;
|
||||
}
|
||||
|
||||
bool verify_raw(KeyType type, const vanetza::ByteBuffer& sec1, const vanetza::ByteBuffer& digest,
|
||||
const vanetza::ByteBuffer& r, const vanetza::ByteBuffer& s) {
|
||||
const auto n = key_length(type);
|
||||
if (r.size() != n || s.size() != n) return false;
|
||||
vanetza::ByteBuffer signature;
|
||||
signature.reserve(2 * n);
|
||||
signature.insert(signature.end(), r.begin(), r.end());
|
||||
signature.insert(signature.end(), s.begin(), s.end());
|
||||
ScopedKey key;
|
||||
try { key.id = import_public(type, sec1); } catch (const std::runtime_error&) { return false; }
|
||||
return psa_verify_hash(key.id, ecdsa_algorithm(digest.size()), digest.data(), digest.size(),
|
||||
signature.data(), signature.size()) == PSA_SUCCESS;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
class BackendMbedTls::Impl {
|
||||
public:
|
||||
struct Entry { KeyType type; vanetza::ByteBuffer secret; mbedtls_svc_key_id_t id; };
|
||||
std::deque<Entry> cache;
|
||||
std::size_t capacity = 4;
|
||||
|
||||
~Impl() { for (auto& entry : cache) psa_destroy_key(entry.id); }
|
||||
|
||||
mbedtls_svc_key_id_t signing_key(KeyType type, const vanetza::ByteBuffer& secret) {
|
||||
if (secret.size() != key_length(type)) throw std::runtime_error("private key length");
|
||||
for (auto it = cache.begin(); it != cache.end(); ++it) {
|
||||
if (it->type == type && it->secret == secret) {
|
||||
Entry hit = std::move(*it);
|
||||
cache.erase(it);
|
||||
cache.push_front(std::move(hit)); // most recently used first
|
||||
return cache.front().id;
|
||||
}
|
||||
}
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
|
||||
psa_set_key_bits(&attributes, curve_bits(type));
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_ANY_HASH));
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, secret.data(), secret.size(), &id) != PSA_SUCCESS)
|
||||
throw std::runtime_error("PSA private key import failed");
|
||||
while (cache.size() >= capacity) {
|
||||
psa_destroy_key(cache.back().id);
|
||||
cache.pop_back();
|
||||
}
|
||||
cache.push_front(Entry {type, secret, id});
|
||||
return id;
|
||||
}
|
||||
};
|
||||
|
||||
BackendMbedTls::BackendMbedTls() : impl_(std::make_unique<Impl>()) {
|
||||
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
|
||||
}
|
||||
BackendMbedTls::~BackendMbedTls() = default;
|
||||
void BackendMbedTls::set_key_cache_size(std::size_t size) { impl_->capacity = std::max<std::size_t>(1, size); }
|
||||
|
||||
EcdsaSignature BackendMbedTls::sign_data(const ecdsa256::PrivateKey& key, const vanetza::ByteBuffer& data) {
|
||||
const auto digest = calculate_sha256_digest(data.data(), data.size());
|
||||
const vanetza::ByteBuffer secret(key.key.begin(), key.key.end());
|
||||
const auto id = impl_->signing_key(KeyType::NistP256, secret);
|
||||
auto raw = raw_signature(id, KeyType::NistP256, vanetza::ByteBuffer(digest.begin(), digest.end()));
|
||||
EcdsaSignature signature;
|
||||
X_Coordinate_Only r;
|
||||
r.x.assign(raw.begin(), raw.begin() + 32);
|
||||
signature.R = std::move(r);
|
||||
signature.s.assign(raw.begin() + 32, raw.end());
|
||||
return signature;
|
||||
}
|
||||
|
||||
Signature BackendMbedTls::sign_digest(const PrivateKey& key, const vanetza::ByteBuffer& digest) {
|
||||
const auto id = impl_->signing_key(key.type, key.key);
|
||||
auto raw = raw_signature(id, key.type, digest);
|
||||
const auto n = key_length(key.type);
|
||||
Signature signature;
|
||||
signature.type = key.type;
|
||||
signature.r.assign(raw.begin(), raw.begin() + n);
|
||||
signature.s.assign(raw.begin() + n, raw.end());
|
||||
return signature;
|
||||
}
|
||||
|
||||
bool BackendMbedTls::verify_data(const ecdsa256::PublicKey& key, const vanetza::ByteBuffer& data,
|
||||
const EcdsaSignature& signature) {
|
||||
const auto digest = calculate_sha256_digest(data.data(), data.size());
|
||||
Uncompressed point;
|
||||
point.x.assign(key.x.begin(), key.x.end());
|
||||
point.y.assign(key.y.begin(), key.y.end());
|
||||
return verify_raw(KeyType::NistP256, ecc::encode_uncompressed(point),
|
||||
vanetza::ByteBuffer(digest.begin(), digest.end()),
|
||||
convert_for_signing(signature.R), signature.s);
|
||||
}
|
||||
|
||||
bool BackendMbedTls::verify_digest(const PublicKey& key, const vanetza::ByteBuffer& digest, const Signature& signature) {
|
||||
if (key.type != signature.type) return false;
|
||||
try {
|
||||
return verify_raw(key.type, public_key_octets(key), digest, signature.r, signature.s);
|
||||
} catch (const std::runtime_error&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<Uncompressed> BackendMbedTls::decompress_point(const EccPoint& ecc_point) {
|
||||
struct Visitor : boost::static_visitor<boost::optional<Uncompressed>> {
|
||||
boost::optional<Uncompressed> operator()(const X_Coordinate_Only&) const { return boost::none; }
|
||||
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_0& p) const {
|
||||
return ecc::decompress(KeyType::NistP256, p.x, false);
|
||||
}
|
||||
boost::optional<Uncompressed> operator()(const Compressed_Lsb_Y_1& p) const {
|
||||
return ecc::decompress(KeyType::NistP256, p.x, true);
|
||||
}
|
||||
boost::optional<Uncompressed> operator()(const Uncompressed& p) const { return p; }
|
||||
};
|
||||
Visitor visitor;
|
||||
return boost::apply_visitor(visitor, ecc_point);
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer BackendMbedTls::calculate_hash(HashAlgorithm algorithm, const vanetza::ByteBuffer& data) {
|
||||
psa_algorithm_t alg;
|
||||
std::size_t size;
|
||||
switch (algorithm) {
|
||||
case HashAlgorithm::SHA256: alg = PSA_ALG_SHA_256; size = 32; break;
|
||||
case HashAlgorithm::SHA384: alg = PSA_ALG_SHA_384; size = 48; break;
|
||||
default: return {};
|
||||
}
|
||||
vanetza::ByteBuffer digest(size);
|
||||
std::size_t written = 0;
|
||||
if (psa_hash_compute(alg, data.data(), data.size(), digest.data(), digest.size(), &written) != PSA_SUCCESS ||
|
||||
written != size) throw std::runtime_error("PSA hash failed");
|
||||
return digest;
|
||||
}
|
||||
|
||||
ecdsa256::KeyPair BackendMbedTls::generate_key_pair() {
|
||||
const auto generated = generate_key(KeyType::NistP256);
|
||||
ecdsa256::KeyPair pair;
|
||||
std::copy(generated.priv.key.begin(), generated.priv.key.end(), pair.private_key.key.begin());
|
||||
std::copy(generated.pub.x.begin(), generated.pub.x.end(), pair.public_key.x.begin());
|
||||
std::copy(generated.pub.y.begin(), generated.pub.y.end(), pair.public_key.y.begin());
|
||||
return pair;
|
||||
}
|
||||
|
||||
security::KeyPair BackendMbedTls::generate_key(KeyType type) {
|
||||
const std::size_t n = key_length(type);
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family(type)));
|
||||
psa_set_key_bits(&attributes, n * 8);
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA_ANY);
|
||||
ScopedKey key;
|
||||
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
||||
security::KeyPair pair;
|
||||
pair.priv.type = pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.priv.key.resize(n);
|
||||
std::size_t length = 0;
|
||||
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
|
||||
throw std::runtime_error("PSA private key export failed");
|
||||
vanetza::ByteBuffer sec1(1 + 2 * n);
|
||||
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() ||
|
||||
sec1[0] != 0x04) throw std::runtime_error("PSA public key export failed");
|
||||
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
|
||||
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
|
||||
return pair;
|
||||
}
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,165 @@
|
||||
#include <microbu_v2x/c5_radio.hpp>
|
||||
#include <microbu_v2x/its_g5_frame.hpp>
|
||||
#include <esp_event.h>
|
||||
#include <esp_wifi.h>
|
||||
#include <hal/modem_syscon_ll.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/queue.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
|
||||
extern "C" {
|
||||
void phy_11p_set(int, int);
|
||||
void phy_change_channel(int, int, int, int);
|
||||
esp_err_t esp_wifi_80211_tx_custom(wifi_interface_t, const void*, int32_t, bool,
|
||||
wifi_tx_rate_config_t*, wifi_band_t, wifi_bandwidth_t);
|
||||
}
|
||||
|
||||
namespace microbu_v2x {
|
||||
class C5Radio::Impl {
|
||||
public:
|
||||
struct Raw {
|
||||
std::uint16_t length;
|
||||
std::int8_t rssi;
|
||||
std::uint32_t timestamp;
|
||||
std::uint8_t bytes[2346];
|
||||
};
|
||||
C5RadioConfig config;
|
||||
QueueHandle_t queue = nullptr;
|
||||
bool initialized = false, started = false, own_event_loop = false;
|
||||
std::uint16_t sequence = 0;
|
||||
std::atomic<std::uint32_t> dropped {0};
|
||||
static Impl* active;
|
||||
static std::mutex callback_mutex;
|
||||
explicit Impl(C5RadioConfig c) : config(c) {}
|
||||
static void receive(void* buffer, wifi_promiscuous_pkt_type_t type) {
|
||||
if (!buffer || type != WIFI_PKT_DATA) return;
|
||||
const auto* packet = static_cast<const wifi_promiscuous_pkt_t*>(buffer);
|
||||
if (packet->rx_ctrl.rx_state != 0) return;
|
||||
// esp_wifi_he_types.h documents sig_len on this chip as "the length of the
|
||||
// reception MPDU", not "MPDU + FCS" as older-chip ESP-IDF documentation
|
||||
// states; measured on real hardware, it is consistently 4 bytes longer than
|
||||
// the actual frame, and those 4 trailing bytes are a fixed, content-independent
|
||||
// value (00 00 99 00), not a real, software-recoverable FCS. This promiscuous
|
||||
// filter never sets WIFI_PROMIS_FILTER_MASK_FCSFAIL, so the frame itself has
|
||||
// already passed a real hardware FCS check by the time it reaches this callback
|
||||
// -- see components/microbu_v2x/tools/radio_pair.py's docstring for the full evidence.
|
||||
const auto length = packet->rx_ctrl.sig_len;
|
||||
std::lock_guard<std::mutex> lock(callback_mutex);
|
||||
if (!active || !active->queue) return;
|
||||
if (length < 38 || length > sizeof(Raw::bytes)) { ++active->dropped; return; }
|
||||
Raw raw {};
|
||||
raw.length = length; raw.rssi = packet->rx_ctrl.rssi;
|
||||
raw.timestamp = packet->rx_ctrl.timestamp;
|
||||
std::memcpy(raw.bytes, packet->payload, length);
|
||||
if (xQueueSend(active->queue, &raw, 0) != pdTRUE) ++active->dropped;
|
||||
}
|
||||
};
|
||||
C5Radio::Impl* C5Radio::Impl::active = nullptr;
|
||||
std::mutex C5Radio::Impl::callback_mutex;
|
||||
C5Radio::C5Radio(C5RadioConfig c) : impl_(std::make_unique<Impl>(c)) {}
|
||||
C5Radio::~C5Radio() { stop(); }
|
||||
esp_err_t C5Radio::start() {
|
||||
auto& p = *impl_;
|
||||
const auto& c = p.config;
|
||||
if (p.initialized) return ESP_ERR_INVALID_STATE;
|
||||
if (c.channel_number < 172 || c.channel_number > 184 || c.channel_number % 2 ||
|
||||
!std::isfinite(c.transmit_power_dbm) || c.transmit_power_dbm < 2 || c.transmit_power_dbm > 20 ||
|
||||
std::floor(c.transmit_power_dbm * 4) != c.transmit_power_dbm * 4 ||
|
||||
c.receive_queue_length == 0 || c.receive_queue_length > 32) return ESP_ERR_INVALID_ARG;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
|
||||
if (Impl::active) return ESP_ERR_INVALID_STATE;
|
||||
p.queue = xQueueCreate(c.receive_queue_length, sizeof(Impl::Raw));
|
||||
if (!p.queue) return ESP_ERR_NO_MEM;
|
||||
Impl::active = &p;
|
||||
}
|
||||
auto result = esp_event_loop_create_default();
|
||||
p.own_event_loop = result == ESP_OK;
|
||||
if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { stop(); return result; }
|
||||
// OpenTrafficMap main/main.c and cmd_sniffer.c establish the FE clock and
|
||||
// NON_NGV_10 PHY mode. These private calls are SDK-specific, not ETSI SAPs.
|
||||
modem_syscon_ll_enable_fe_40m_clock(&MODEM_SYSCON, true);
|
||||
wifi_init_config_t wifi = WIFI_INIT_CONFIG_DEFAULT();
|
||||
wifi.nvs_enable = 0;
|
||||
result = esp_wifi_init(&wifi);
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
p.initialized = true;
|
||||
auto attempt = [&](esp_err_t r) { if (result == ESP_OK) result = r; };
|
||||
attempt(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
attempt(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
if (result == ESP_OK) { result = esp_wifi_start(); p.started = result == ESP_OK; }
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
attempt(esp_wifi_set_band_mode(WIFI_BAND_MODE_5G_ONLY));
|
||||
attempt(esp_wifi_set_ps(WIFI_PS_NONE));
|
||||
attempt(esp_wifi_set_max_tx_power(static_cast<std::int8_t>(c.transmit_power_dbm * 4)));
|
||||
wifi_promiscuous_filter_t filter {};
|
||||
filter.filter_mask = WIFI_PROMIS_FILTER_MASK_DATA;
|
||||
attempt(esp_wifi_set_promiscuous_filter(&filter));
|
||||
attempt(esp_wifi_set_promiscuous_rx_cb(Impl::receive));
|
||||
attempt(esp_wifi_set_promiscuous(true));
|
||||
if (result != ESP_OK) { stop(); return result; }
|
||||
phy_11p_set(1, 0); // 10 MHz; never infer PHY width from WIFI_BW20 below.
|
||||
phy_change_channel(5000 + 5 * c.channel_number, 1, 0, 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
void C5Radio::stop() {
|
||||
if (!impl_) return;
|
||||
auto& p = *impl_;
|
||||
if (p.started) esp_wifi_set_promiscuous(false);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(Impl::callback_mutex);
|
||||
if (Impl::active == &p) Impl::active = nullptr;
|
||||
if (p.queue) { vQueueDelete(p.queue); p.queue = nullptr; }
|
||||
}
|
||||
if (p.started) esp_wifi_stop();
|
||||
if (p.initialized) esp_wifi_deinit();
|
||||
if (p.own_event_loop) esp_event_loop_delete_default();
|
||||
p.started = p.initialized = p.own_event_loop = false;
|
||||
}
|
||||
Result C5Radio::request(AlDataRequest request) {
|
||||
auto& p = *impl_;
|
||||
if (!p.started) return Result::rejected;
|
||||
if (!p.config.laboratory_transmission) return Result::unsupported;
|
||||
// Reject controls this fixed-channel backend cannot honour. In particular,
|
||||
// do not silently reinterpret an AL_DATA bandwidth or transceiver mode.
|
||||
if (request.bandwidth_mhz != 10 || request.channel_number != p.config.channel_number ||
|
||||
request.transceiver_id != 0 || request.transceiver_mode || request.datastream_id ||
|
||||
request.transmit_power_dbm != p.config.transmit_power_dbm) return Result::unsupported;
|
||||
constexpr wifi_phy_rate_t rates[] = {WIFI_PHY_RATE_6M, WIFI_PHY_RATE_9M, WIFI_PHY_RATE_12M,
|
||||
WIFI_PHY_RATE_18M, WIFI_PHY_RATE_24M, WIFI_PHY_RATE_36M, WIFI_PHY_RATE_48M, WIFI_PHY_RATE_54M};
|
||||
const auto index = static_cast<unsigned>(request.mcs);
|
||||
if (index >= std::size(rates)) return Result::invalid_argument;
|
||||
vanetza::ByteBuffer bytes;
|
||||
const auto encoded = its_g5::encode_frame(request, p.sequence, bytes);
|
||||
if (encoded != Result::accepted) return encoded;
|
||||
p.sequence = (p.sequence + 1) & 4095;
|
||||
wifi_tx_rate_config_t rate {};
|
||||
rate.phymode = WIFI_PHY_MODE_11A; rate.rate = rates[index];
|
||||
// Legacy OFDM rate identifiers are halved by the 10 MHz PHY mode.
|
||||
// The driver consumes the frame synchronously into its own ebuf.
|
||||
const auto result = esp_wifi_80211_tx_custom(WIFI_IF_STA, bytes.data(), bytes.size(), false,
|
||||
&rate, WIFI_BAND_5G, WIFI_BW20);
|
||||
return result == ESP_OK ? Result::accepted : result == ESP_ERR_NO_MEM ? Result::resource_limit : Result::rejected;
|
||||
}
|
||||
void C5Radio::poll(const Receive& receive, const Capture& capture) {
|
||||
auto& p = *impl_;
|
||||
if (!p.queue) return;
|
||||
Impl::Raw raw {};
|
||||
// Bound work per poll even if the radio continuously fills the queue.
|
||||
for (unsigned i = 0; i < p.config.receive_queue_length && xQueueReceive(p.queue, &raw, 0) == pdTRUE; ++i) {
|
||||
if (capture) capture(vanetza::ByteBuffer(raw.bytes, raw.bytes + raw.length), raw.rssi, raw.timestamp);
|
||||
AlDataIndication ind;
|
||||
if (its_g5::decode_frame(raw.bytes, raw.length, true, ind) != Result::accepted) continue;
|
||||
ind.channel_number = p.config.channel_number;
|
||||
ind.received_power_dbm = raw.rssi;
|
||||
// The SDK does not provide channel-busy time here. CBR remains absent;
|
||||
// counting received packets would not be a valid CBR measurement.
|
||||
if (receive) receive(std::move(ind));
|
||||
}
|
||||
}
|
||||
std::uint32_t C5Radio::dropped_frames() const { return impl_->dropped.load(); }
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
#include <microbu_v2x/credentials.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using vanetza::security::KeyType;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint8_t bundle_magic[4] = {'V', 'C', 'R', '1'};
|
||||
constexpr std::uint8_t stored_magic[4] = {'V', 'C', 'S', '1'};
|
||||
enum Record : std::uint8_t { root = 1, authority = 2, ticket = 3, ticket_key = 4, ticket_key_id = 5 };
|
||||
|
||||
std::uint8_t curve_code(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return 1;
|
||||
case KeyType::BrainpoolP256r1: return 2;
|
||||
case KeyType::BrainpoolP384r1: return 3;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
KeyType curve_type(std::uint8_t code) {
|
||||
switch (code) {
|
||||
case 1: return KeyType::NistP256;
|
||||
case 2: return KeyType::BrainpoolP256r1;
|
||||
case 3: return KeyType::BrainpoolP384r1;
|
||||
default: return KeyType::Unspecified;
|
||||
}
|
||||
}
|
||||
void put(ByteBuffer& out, std::uint8_t type, const ByteBuffer& payload) {
|
||||
out.push_back(type);
|
||||
out.push_back(static_cast<std::uint8_t>(payload.size() >> 8));
|
||||
out.push_back(static_cast<std::uint8_t>(payload.size()));
|
||||
out.insert(out.end(), payload.begin(), payload.end());
|
||||
}
|
||||
|
||||
ByteBuffer key_record(const PrivateKey& key) {
|
||||
ByteBuffer out {curve_code(key.type)};
|
||||
out.insert(out.end(), key.key.begin(), key.key.end());
|
||||
return out;
|
||||
}
|
||||
ByteBuffer key_record(KeyId key) {
|
||||
return {static_cast<std::uint8_t>(key.value >> 24), static_cast<std::uint8_t>(key.value >> 16),
|
||||
static_cast<std::uint8_t>(key.value >> 8), static_cast<std::uint8_t>(key.value)};
|
||||
}
|
||||
|
||||
bool read_key(const ByteBuffer& payload, PrivateKey& key) {
|
||||
const KeyType curve = curve_type(payload[0]);
|
||||
if (curve == KeyType::Unspecified || payload.size() - 1 != vanetza::security::key_length(curve)) return false;
|
||||
key.type = curve;
|
||||
key.key.assign(payload.begin() + 1, payload.end());
|
||||
return true;
|
||||
}
|
||||
bool read_key(const ByteBuffer& payload, KeyId& key) {
|
||||
if (payload.size() != 4) return false;
|
||||
key.value = std::uint32_t(payload[0]) << 24 | std::uint32_t(payload[1]) << 16 | std::uint32_t(payload[2]) << 8 | payload[3];
|
||||
return bool(key);
|
||||
}
|
||||
|
||||
/// Both formats: magic, then roots, authorities and tickets, each ticket certificate followed by its key record.
|
||||
template <class Set>
|
||||
ByteBuffer encode_set(const Set& set, const std::uint8_t (&magic)[4], std::uint8_t key_type) {
|
||||
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||
for (const auto& coer : set.roots) put(out, Record::root, coer);
|
||||
for (const auto& coer : set.authorities) put(out, Record::authority, coer);
|
||||
for (const auto& t : set.tickets) {
|
||||
put(out, Record::ticket, t.certificate);
|
||||
put(out, key_type, key_record(t.key));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
template <class Set>
|
||||
bool decode_set(const ByteBuffer& bundle, const std::uint8_t (&magic)[4], std::uint8_t key_type, Set& out) {
|
||||
if (bundle.size() < sizeof(magic) || !std::equal(std::begin(magic), std::end(magic), bundle.begin())) return false;
|
||||
Set parsed;
|
||||
bool key_pending = false; // a ticket certificate awaits its key record
|
||||
std::size_t at = sizeof(magic);
|
||||
while (at < bundle.size()) {
|
||||
if (bundle.size() - at < 3) return false;
|
||||
const std::uint8_t type = bundle[at];
|
||||
const std::size_t length = (static_cast<std::size_t>(bundle[at + 1]) << 8) | bundle[at + 2];
|
||||
at += 3;
|
||||
if (bundle.size() - at < length || length == 0) return false;
|
||||
ByteBuffer payload(bundle.begin() + at, bundle.begin() + at + length);
|
||||
at += length;
|
||||
if (key_pending != (type == key_type)) return false;
|
||||
if (type == Record::root) {
|
||||
parsed.roots.push_back(std::move(payload));
|
||||
} else if (type == Record::authority) {
|
||||
parsed.authorities.push_back(std::move(payload));
|
||||
} else if (type == Record::ticket) {
|
||||
parsed.tickets.push_back({std::move(payload), {}});
|
||||
key_pending = true;
|
||||
} else if (type == key_type) {
|
||||
if (!read_key(payload, parsed.tickets.back().key)) return false;
|
||||
key_pending = false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (key_pending) return false;
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ByteBuffer encode(const Credentials& credentials) { return encode_set(credentials, bundle_magic, Record::ticket_key); }
|
||||
ByteBuffer encode(const StoredCredentials& credentials) {
|
||||
return encode_set(credentials, stored_magic, Record::ticket_key_id);
|
||||
}
|
||||
|
||||
bool decode(const ByteBuffer& bundle, Credentials& out) {
|
||||
return decode_set(bundle, bundle_magic, Record::ticket_key, out);
|
||||
}
|
||||
bool decode(const ByteBuffer& bundle, StoredCredentials& out) {
|
||||
return decode_set(bundle, stored_magic, Record::ticket_key_id, out);
|
||||
}
|
||||
|
||||
std::optional<StoredCredentials> import_keys(const Credentials& credentials, SecurityModule& module) {
|
||||
StoredCredentials stored {credentials.roots, credentials.authorities, {}};
|
||||
const auto undo = [&]() -> std::optional<StoredCredentials> {
|
||||
for (const auto& t : stored.tickets) module.destroy_key(t.key);
|
||||
return std::nullopt;
|
||||
};
|
||||
for (const auto& t : credentials.tickets) {
|
||||
vanetza::security::v3::Certificate certificate;
|
||||
if (!certificate.decode(t.certificate)) return undo();
|
||||
const auto verification_key = vanetza::security::v3::get_public_key(*certificate.content());
|
||||
if (!verification_key) return undo();
|
||||
const auto key = module.import_key(KeyPair {t.key, *verification_key});
|
||||
if (!key) return undo();
|
||||
stored.tickets.push_back({t.certificate, *key});
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
ApplyReport apply(const StoredCredentials& credentials, TrustConfiguration& trust, CertificatePool& pool) {
|
||||
ApplyReport report;
|
||||
for (const auto& coer : credentials.roots) {
|
||||
if ((report.result = trust.add_root(coer)) != Result::accepted) return report;
|
||||
++report.roots;
|
||||
}
|
||||
for (const auto& coer : credentials.authorities) {
|
||||
if ((report.result = trust.add_authority(coer)) != Result::accepted) return report;
|
||||
++report.authorities;
|
||||
}
|
||||
for (const auto& t : credentials.tickets) {
|
||||
if ((report.result = pool.add(t.certificate, t.key)) != Result::accepted) return report;
|
||||
++report.tickets;
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::save(const StoredCredentials& credentials) {
|
||||
const ByteBuffer bundle = encode(credentials);
|
||||
std::ofstream out(path_, std::ios::binary | std::ios::trunc);
|
||||
out.write(reinterpret_cast<const char*>(bundle.data()), bundle.size());
|
||||
return out ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::load(StoredCredentials& credentials) {
|
||||
std::ifstream in(path_, std::ios::binary);
|
||||
if (!in) return Result::rejected;
|
||||
const ByteBuffer bundle(std::istreambuf_iterator<char>(in), {});
|
||||
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
|
||||
}
|
||||
|
||||
Result FileCredentialStore::erase() {
|
||||
return std::remove(path_.c_str()) == 0 ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,82 @@
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <boost/multiprecision/cpp_int.hpp>
|
||||
#include <algorithm>
|
||||
#include <iterator>
|
||||
|
||||
namespace microbu_v2x::ecc {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
// Fixed width, no heap: a 384-bit product needs 768 bits before reduction.
|
||||
using Int = boost::multiprecision::number<boost::multiprecision::cpp_int_backend<
|
||||
1024, 1024, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>;
|
||||
|
||||
// FIPS 186-4 D.1.2.3 (P-256), RFC 5639 3.4 (brainpoolP256r1) and 3.6 (brainpoolP384r1).
|
||||
// The host regression compares every constant with OpenSSL's built-in groups.
|
||||
constexpr CurveParameters curves[] = {
|
||||
{KeyType::NistP256, 32,
|
||||
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF",
|
||||
"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC",
|
||||
"5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"},
|
||||
{KeyType::BrainpoolP256r1, 32,
|
||||
"A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377",
|
||||
"7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9",
|
||||
"26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6"},
|
||||
{KeyType::BrainpoolP384r1, 48,
|
||||
"8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53",
|
||||
"7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826",
|
||||
"04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11"},
|
||||
};
|
||||
|
||||
Int from_hex(const char* hex) { return Int(std::string("0x") + hex); }
|
||||
|
||||
Int from_bytes(const vanetza::ByteBuffer& bytes) {
|
||||
Int value;
|
||||
boost::multiprecision::import_bits(value, bytes.begin(), bytes.end(), 8, true);
|
||||
return value;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer to_bytes(const Int& value, std::size_t octets) {
|
||||
vanetza::ByteBuffer out;
|
||||
boost::multiprecision::export_bits(value, std::back_inserter(out), 8, true);
|
||||
if (out.size() > octets) return {};
|
||||
out.insert(out.begin(), octets - out.size(), 0);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
const CurveParameters* curve(KeyType type) {
|
||||
for (const auto& c : curves) if (c.type == type) return &c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
boost::optional<Uncompressed> decompress(KeyType type, const vanetza::ByteBuffer& x_bytes, bool y_odd) {
|
||||
const auto* c = curve(type);
|
||||
if (!c || x_bytes.size() != c->octets) return boost::none;
|
||||
const Int p = from_hex(c->p), a = from_hex(c->a), b = from_hex(c->b);
|
||||
const Int x = from_bytes(x_bytes);
|
||||
if (x >= p) return boost::none;
|
||||
// rhs = x^3 + a*x + b (mod p)
|
||||
Int rhs = (x * x) % p;
|
||||
rhs = (rhs * x) % p;
|
||||
rhs = (rhs + (a * x) % p) % p;
|
||||
rhs = (rhs + b) % p;
|
||||
// p = 3 (mod 4): sqrt(n) = n^((p+1)/4) (mod p) when n is a quadratic residue.
|
||||
Int y = boost::multiprecision::powm(rhs, (p + 1) / 4, p);
|
||||
if ((y * y) % p != rhs) return boost::none; // x is not on the curve
|
||||
if (static_cast<bool>(y & 1) != y_odd) y = p - y;
|
||||
Uncompressed point;
|
||||
point.x = x_bytes;
|
||||
point.y = to_bytes(y, c->octets);
|
||||
if (point.y.empty()) return boost::none;
|
||||
return point;
|
||||
}
|
||||
|
||||
vanetza::ByteBuffer encode_uncompressed(const Uncompressed& point) {
|
||||
vanetza::ByteBuffer out;
|
||||
out.reserve(1 + point.x.size() + point.y.size());
|
||||
out.push_back(0x04);
|
||||
out.insert(out.end(), point.x.begin(), point.x.end());
|
||||
out.insert(out.end(), point.y.begin(), point.y.end());
|
||||
return out;
|
||||
}
|
||||
} // namespace microbu_v2x::ecc
|
||||
@@ -0,0 +1,135 @@
|
||||
#include <microbu_v2x/ecies_mbedtls.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <psa/crypto.h>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
psa_ecc_family_t family_of(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return PSA_ECC_FAMILY_SECP_R1;
|
||||
case KeyType::BrainpoolP256r1:
|
||||
case KeyType::BrainpoolP384r1: return PSA_ECC_FAMILY_BRAINPOOL_P_R1;
|
||||
default: throw std::runtime_error("unsupported key type");
|
||||
}
|
||||
}
|
||||
struct ScopedKey {
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
~ScopedKey() { if (id) psa_destroy_key(id); }
|
||||
};
|
||||
mbedtls_svc_key_id_t import_raw(psa_key_type_t type, std::size_t bits, psa_key_usage_t usage, psa_algorithm_t alg,
|
||||
const std::uint8_t* data, std::size_t length) {
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, type);
|
||||
if (bits) psa_set_key_bits(&attributes, bits);
|
||||
psa_set_key_usage_flags(&attributes, usage);
|
||||
psa_set_key_algorithm(&attributes, alg);
|
||||
mbedtls_svc_key_id_t id = 0;
|
||||
if (psa_import_key(&attributes, data, length, &id) != PSA_SUCCESS) throw std::runtime_error("PSA key import failed");
|
||||
return id;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
EciesMbedTls::EciesMbedTls() {
|
||||
if (psa_crypto_init() != PSA_SUCCESS) throw std::runtime_error("PSA crypto initialisation failed");
|
||||
}
|
||||
|
||||
KeyPair EciesMbedTls::generate_key(KeyType type) {
|
||||
const std::size_t n = key_length(type);
|
||||
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
|
||||
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(type)));
|
||||
psa_set_key_bits(&attributes, n * 8);
|
||||
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
|
||||
psa_set_key_algorithm(&attributes, PSA_ALG_ECDH);
|
||||
ScopedKey key;
|
||||
if (psa_generate_key(&attributes, &key.id) != PSA_SUCCESS) throw std::runtime_error("PSA key generation failed");
|
||||
KeyPair pair;
|
||||
pair.priv.type = type;
|
||||
pair.priv.key.resize(n);
|
||||
std::size_t length = 0;
|
||||
if (psa_export_key(key.id, pair.priv.key.data(), n, &length) != PSA_SUCCESS || length != n)
|
||||
throw std::runtime_error("PSA private key export failed");
|
||||
ByteBuffer sec1(1 + 2 * n);
|
||||
if (psa_export_public_key(key.id, sec1.data(), sec1.size(), &length) != PSA_SUCCESS || length != sec1.size() || sec1[0] != 0x04)
|
||||
throw std::runtime_error("PSA public key export failed");
|
||||
pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.pub.x.assign(sec1.begin() + 1, sec1.begin() + 1 + n);
|
||||
pair.pub.y.assign(sec1.begin() + 1 + n, sec1.end());
|
||||
return pair;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> EciesMbedTls::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
|
||||
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
|
||||
const std::size_t n = key_length(own.type);
|
||||
if (own.key.size() != n || peer.x.size() != n || peer.y.size() != n) return std::nullopt;
|
||||
try {
|
||||
ScopedKey key;
|
||||
key.id = import_raw(PSA_KEY_TYPE_ECC_KEY_PAIR(family_of(own.type)), n * 8, PSA_KEY_USAGE_DERIVE, PSA_ALG_ECDH,
|
||||
own.key.data(), own.key.size());
|
||||
Uncompressed point;
|
||||
point.x = peer.x; point.y = peer.y;
|
||||
const ByteBuffer sec1 = ecc::encode_uncompressed(point);
|
||||
ByteBuffer secret(n);
|
||||
std::size_t length = 0;
|
||||
// PSA raw ECDH output is the x coordinate of the shared point (PSA Crypto API 1.1, PSA_ALG_ECDH)
|
||||
if (psa_raw_key_agreement(PSA_ALG_ECDH, key.id, sec1.data(), sec1.size(), secret.data(), secret.size(), &length) != PSA_SUCCESS ||
|
||||
length != n) return std::nullopt;
|
||||
return secret;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer EciesMbedTls::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
|
||||
ScopedKey mac_key;
|
||||
mac_key.id = import_raw(PSA_KEY_TYPE_HMAC, 0, PSA_KEY_USAGE_SIGN_MESSAGE, PSA_ALG_HMAC(PSA_ALG_SHA_256),
|
||||
key.data(), key.size());
|
||||
ByteBuffer out(32);
|
||||
std::size_t length = 0;
|
||||
if (psa_mac_compute(mac_key.id, PSA_ALG_HMAC(PSA_ALG_SHA_256), data.data(), data.size(), out.data(), out.size(), &length) != PSA_SUCCESS ||
|
||||
length != 32) throw std::runtime_error("PSA HMAC failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
ByteBuffer EciesMbedTls::random(std::size_t octets) {
|
||||
ByteBuffer out(octets);
|
||||
if (octets && psa_generate_random(out.data(), out.size()) != PSA_SUCCESS) throw std::runtime_error("PSA random failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
bool EciesMbedTls::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& out) {
|
||||
try {
|
||||
ScopedKey aes;
|
||||
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_ENCRYPT, PSA_ALG_CCM, key.data(), key.size());
|
||||
out.resize(plaintext.size() + 16);
|
||||
std::size_t length = 0;
|
||||
if (psa_aead_encrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, plaintext.data(), plaintext.size(),
|
||||
out.data(), out.size(), &length) != PSA_SUCCESS || length != out.size()) { out.clear(); return false; }
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool EciesMbedTls::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& in, ByteBuffer& plaintext) {
|
||||
if (in.size() < 16) return false;
|
||||
try {
|
||||
ScopedKey aes;
|
||||
aes.id = import_raw(PSA_KEY_TYPE_AES, 128, PSA_KEY_USAGE_DECRYPT, PSA_ALG_CCM, key.data(), key.size());
|
||||
plaintext.resize(in.size() - 16);
|
||||
std::size_t length = 0;
|
||||
if (psa_aead_decrypt(aes.id, PSA_ALG_CCM, nonce.data(), nonce.size(), nullptr, 0, in.data(), in.size(),
|
||||
plaintext.data(), plaintext.size(), &length) != PSA_SUCCESS || length != plaintext.size()) {
|
||||
plaintext.clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,121 @@
|
||||
#include <microbu_v2x/ecies_openssl.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/openssl_wrapper.hpp>
|
||||
#include <openssl/ec.h>
|
||||
#include <openssl/ecdh.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/hmac.h>
|
||||
#include <openssl/obj_mac.h>
|
||||
#include <openssl/rand.h>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza::security;
|
||||
namespace {
|
||||
int nid_of(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return NID_X9_62_prime256v1;
|
||||
case KeyType::BrainpoolP256r1: return NID_brainpoolP256r1;
|
||||
case KeyType::BrainpoolP384r1: return NID_brainpoolP384r1;
|
||||
default: return NID_undef;
|
||||
}
|
||||
}
|
||||
struct CipherContext {
|
||||
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
|
||||
~CipherContext() { EVP_CIPHER_CTX_free(ctx); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
KeyPair EciesOpenSsl::generate_key(KeyType type) {
|
||||
openssl::Key key(nid_of(type));
|
||||
openssl::check(EC_KEY_generate_key(key));
|
||||
const std::size_t n = key_length(type);
|
||||
KeyPair pair;
|
||||
pair.priv.type = type;
|
||||
pair.priv.key.resize(n);
|
||||
BN_bn2binpad(EC_KEY_get0_private_key(key), pair.priv.key.data(), n);
|
||||
openssl::BigNumber x, y;
|
||||
openssl::BigNumberContext ctx;
|
||||
openssl::check(EC_POINT_get_affine_coordinates(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key), x, y, ctx));
|
||||
pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.pub.x.resize(n); pair.pub.y.resize(n);
|
||||
BN_bn2binpad(x, pair.pub.x.data(), n);
|
||||
BN_bn2binpad(y, pair.pub.y.data(), n);
|
||||
return pair;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> EciesOpenSsl::ecdh_x(const PrivateKey& own, const PublicKey& peer) {
|
||||
if (own.type != peer.type || peer.compression != KeyCompression::NoCompression) return std::nullopt;
|
||||
try {
|
||||
openssl::Key key(nid_of(own.type));
|
||||
openssl::BigNumber d(own.key);
|
||||
openssl::check(EC_KEY_set_private_key(key, d));
|
||||
openssl::Group group(nid_of(peer.type));
|
||||
openssl::Point point(group);
|
||||
openssl::BigNumberContext ctx;
|
||||
openssl::check(EC_POINT_set_affine_coordinates(group, point, openssl::BigNumber(peer.x), openssl::BigNumber(peer.y), ctx));
|
||||
openssl::check(EC_POINT_is_on_curve(group, point, ctx) == 1);
|
||||
ByteBuffer secret(key_length(own.type));
|
||||
// no KDF here: the raw x coordinate is the ECIES shared secret input to KDF2
|
||||
const int written = ECDH_compute_key(secret.data(), secret.size(), point, key, nullptr);
|
||||
if (written != static_cast<int>(secret.size())) return std::nullopt;
|
||||
return secret;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer EciesOpenSsl::hmac_sha256(const ByteBuffer& key, const ByteBuffer& data) {
|
||||
ByteBuffer out(32);
|
||||
unsigned length = 0;
|
||||
if (!HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()), data.data(), data.size(), out.data(), &length) ||
|
||||
length != 32) throw std::runtime_error("HMAC-SHA256 failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
ByteBuffer EciesOpenSsl::random(std::size_t octets) {
|
||||
ByteBuffer out(octets);
|
||||
if (octets && RAND_bytes(out.data(), static_cast<int>(octets)) != 1) throw std::runtime_error("RAND_bytes failed");
|
||||
return out;
|
||||
}
|
||||
|
||||
bool EciesOpenSsl::aes_ccm_encrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& plaintext, ByteBuffer& out) {
|
||||
CipherContext c;
|
||||
if (!c.ctx) return false;
|
||||
int length = 0;
|
||||
if (EVP_EncryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, nullptr) != 1 ||
|
||||
EVP_EncryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
|
||||
EVP_EncryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(plaintext.size())) != 1) return false;
|
||||
out.resize(plaintext.size() + 16);
|
||||
if (EVP_EncryptUpdate(c.ctx, out.data(), &length, plaintext.data(), static_cast<int>(plaintext.size())) != 1 ||
|
||||
length != static_cast<int>(plaintext.size())) return false;
|
||||
int final_length = 0;
|
||||
if (EVP_EncryptFinal_ex(c.ctx, out.data() + length, &final_length) != 1) return false;
|
||||
if (EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_GET_TAG, 16, out.data() + plaintext.size()) != 1) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool EciesOpenSsl::aes_ccm_decrypt(const std::array<std::uint8_t, 16>& key, const std::array<std::uint8_t, 12>& nonce,
|
||||
const ByteBuffer& in, ByteBuffer& plaintext) {
|
||||
if (in.size() < 16) return false;
|
||||
const std::size_t payload = in.size() - 16;
|
||||
CipherContext c;
|
||||
if (!c.ctx) return false;
|
||||
int length = 0;
|
||||
if (EVP_DecryptInit_ex(c.ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_IVLEN, static_cast<int>(nonce.size()), nullptr) != 1 ||
|
||||
EVP_CIPHER_CTX_ctrl(c.ctx, EVP_CTRL_CCM_SET_TAG, 16, const_cast<std::uint8_t*>(in.data() + payload)) != 1 ||
|
||||
EVP_DecryptInit_ex(c.ctx, nullptr, nullptr, key.data(), nonce.data()) != 1 ||
|
||||
EVP_DecryptUpdate(c.ctx, nullptr, &length, nullptr, static_cast<int>(payload)) != 1) return false;
|
||||
plaintext.resize(payload);
|
||||
// CCM verifies the tag inside this update; a mismatch returns 0
|
||||
if (EVP_DecryptUpdate(c.ctx, plaintext.data(), &length, in.data(), static_cast<int>(payload)) != 1 ||
|
||||
length != static_cast<int>(payload)) { plaintext.clear(); return false; }
|
||||
return true;
|
||||
}
|
||||
} // namespace microbu_v2x::pki
|
||||
@@ -0,0 +1,27 @@
|
||||
// ESP32-C5 boot repair, linked into every application that uses this component on
|
||||
// that target (the component's CMake forces the object in with "-u").
|
||||
//
|
||||
// ESP-IDF's esp_system/port/soc/esp32c5/system_internal.c documents that the C5
|
||||
// ROM's UART initialisation misses the UART0 function clock enable
|
||||
// (PCR_UART0_SCLK_EN, "does not reset with the UART module") and repairs it inside
|
||||
// esp_restart(). A reset triggered over USB-Serial/JTAG or JTAG (esptool's
|
||||
// DTR/RTS toggle, OpenOCD, a debugger) bypasses esp_restart(), so once an
|
||||
// application has left the bit cleared the next boot's ROM stage waits forever
|
||||
// for PCR_UART0_READY and the board stays unreachable until a power cycle.
|
||||
// Setting the bit early in every boot keeps warm resets working regardless of what
|
||||
// the application does with UART0; the cost is one register write.
|
||||
#include "sdkconfig.h"
|
||||
#if CONFIG_IDF_TARGET_ESP32C5
|
||||
#include <esp_err.h>
|
||||
#include <esp_private/startup_internal.h>
|
||||
#include <soc/pcr_reg.h>
|
||||
#include <soc/soc.h>
|
||||
|
||||
ESP_SYSTEM_INIT_FN(v2x_esp32c5_rom_uart_clock, CORE, BIT(0), 120) {
|
||||
REG_SET_BIT(PCR_UART0_SCLK_CONF_REG, PCR_UART0_SCLK_EN);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// Referenced through "-u" so the linker keeps this object and its init entry.
|
||||
void v2x_esp32c5_rom_uart_clock_link(void) {}
|
||||
#endif
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <microbu_v2x/facilities.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace microbu_v2x::facilities {
|
||||
Descriptor descriptor(Kind kind) {
|
||||
// TS 103 248 BTP well-known ports; CDD MessageId values. The service
|
||||
// protocolVersion comes from each service ASN.1 definition: CAM/DENM 2,
|
||||
// VAM 3 (TS 103 300-3 V2.3.1 ItsPduHeaderVam). Release != protocolVersion.
|
||||
switch (kind) {
|
||||
case Kind::cam: return {2001, 2, 2};
|
||||
case Kind::denm: return {2002, 1, 2};
|
||||
// TS 103 248 V2.4.1, Table 1: VA (VAM) is 2018; 2009 is CP (CPM).
|
||||
case Kind::vam: return {2018, 16, 3};
|
||||
}
|
||||
return {0, 0, 0};
|
||||
}
|
||||
template<class Message>
|
||||
Result check(Kind kind, const vanetza::ByteBuffer& data) {
|
||||
Message message;
|
||||
if (!message.decode_exact(data) || !message.validate()) return Result::invalid_argument;
|
||||
const auto expected = descriptor(kind);
|
||||
if (message->header.messageId != expected.message_id ||
|
||||
message->header.protocolVersion != expected.protocol_version) return Result::invalid_argument;
|
||||
return Result::accepted;
|
||||
}
|
||||
Result validate_pdu(Kind kind, const vanetza::ByteBuffer& data, std::size_t maximum) {
|
||||
if (data.empty() || data.size() > maximum) return Result::invalid_argument;
|
||||
try {
|
||||
switch (kind) {
|
||||
#if V2X_CAM
|
||||
case Kind::cam: return check<Cam>(kind, data);
|
||||
#endif
|
||||
#if V2X_DENM
|
||||
case Kind::denm: return check<Denm>(kind, data);
|
||||
#endif
|
||||
#if V2X_VAM
|
||||
case Kind::vam: return check<Vam>(kind, data);
|
||||
#endif
|
||||
default: return Result::unsupported;
|
||||
}
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::invalid_argument; }
|
||||
}
|
||||
#if V2X_NETWORK
|
||||
Result send(Stack& stack, Kind kind, vanetza::ByteBuffer bytes, BtpRequest req) {
|
||||
auto result = validate_pdu(kind, bytes, stack.config().mib.itsGnMaxSduSize - 4u);
|
||||
if (result != Result::accepted) return result;
|
||||
req.type = BtpType::b;
|
||||
req.source_port.reset();
|
||||
req.destination_port = descriptor(kind).port;
|
||||
req.destination_port_info = 0;
|
||||
if (req.its_aid == 0) {
|
||||
// SN-ENCAP its_aid selects the security profile: TS 102 965 V2.4.1 Table A.1
|
||||
// (CA 36, DEN 37, VRU 638); TS 103 300-3 V2.3.1 clause 6.5.1 for VAMs.
|
||||
switch (kind) {
|
||||
case Kind::cam: req.its_aid = vanetza::aid::CA; break;
|
||||
case Kind::denm: req.its_aid = vanetza::aid::DEN; break;
|
||||
case Kind::vam: req.its_aid = vanetza::aid::VRU; break;
|
||||
}
|
||||
}
|
||||
if (kind == Kind::vam && req.permissions.empty()) {
|
||||
// TS 103 300-3 V2.3.1 clause 6.5.2: BitmapSsp whose first octet, value 1, is the SSP version.
|
||||
req.permissions = {0x01};
|
||||
}
|
||||
req.data = std::move(bytes);
|
||||
return stack.request(std::move(req));
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
// TS 102 723-8 V1.1.1 clause 6.3 identifier-change procedures over one pool of
|
||||
// authorization tickets. See id_change.hpp and security.hpp for the contracts.
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using namespace vanetza;
|
||||
|
||||
class IdentityManager::Impl : public std::enable_shared_from_this<IdentityManager::Impl> {
|
||||
public:
|
||||
struct Subscription { IdChangeHook hook; ByteBuffer data; };
|
||||
struct Round {
|
||||
std::uint64_t id;
|
||||
IdChangeCommand phase; // PREPARE or COMMIT
|
||||
Identifier new_identifier;
|
||||
std::set<SubscriptionHandle> outstanding;
|
||||
};
|
||||
|
||||
Runtime& runtime;
|
||||
CertificatePool& pool;
|
||||
std::map<SubscriptionHandle, Subscription> subscriptions;
|
||||
SubscriptionHandle next_subscription = 1;
|
||||
std::map<LockHandle, Clock::time_point> locks;
|
||||
LockHandle next_lock = 1;
|
||||
std::unique_ptr<Round> round;
|
||||
std::uint64_t round_counter = 0;
|
||||
bool pending_trigger = false;
|
||||
Clock::duration response_timeout = std::chrono::milliseconds(500);
|
||||
std::function<void(const Identifier&)> committed;
|
||||
Statistics stats;
|
||||
unsigned notify_depth = 0; // hooks run re-entrantly; phase changes wait until delivery completed
|
||||
char round_timer_scope = 0;
|
||||
char lock_timer_scope = 0;
|
||||
|
||||
Impl(Runtime& rt, CertificatePool& p) : runtime(rt), pool(p) {}
|
||||
|
||||
Identifier current() const {
|
||||
const auto* ticket = pool.current();
|
||||
return ticket ? ticket->digest : Identifier {};
|
||||
}
|
||||
|
||||
bool locked() const { return !locks.empty(); }
|
||||
|
||||
// Table 13 return_code carrier handed to hooks for PREPARE and COMMIT.
|
||||
class Responder : public IdChangeResponder {
|
||||
public:
|
||||
Responder(std::weak_ptr<Impl> owner, std::uint64_t round, SubscriptionHandle handle) :
|
||||
owner_(std::move(owner)), round_(round), handle_(handle) {}
|
||||
void respond(bool return_code) override {
|
||||
if (auto impl = owner_.lock()) impl->handle_response(round_, handle_, return_code);
|
||||
}
|
||||
private:
|
||||
std::weak_ptr<Impl> owner_;
|
||||
std::uint64_t round_;
|
||||
SubscriptionHandle handle_;
|
||||
};
|
||||
|
||||
// Deliver a command to every current subscriber; hooks may respond, unsubscribe or
|
||||
// subscribe re-entrantly, so iterate over a snapshot and re-check membership.
|
||||
void notify(IdChangeCommand command, const Identifier& id, bool expect_response) {
|
||||
std::vector<SubscriptionHandle> handles;
|
||||
for (const auto& entry : subscriptions) handles.push_back(entry.first);
|
||||
if (expect_response && round) round->outstanding.insert(handles.begin(), handles.end());
|
||||
const auto round_id = round ? round->id : 0;
|
||||
++notify_depth;
|
||||
for (auto handle : handles) {
|
||||
// An abort raised by an earlier hook ends this round: nobody else gets PREPARE/COMMIT.
|
||||
if (expect_response && (!round || round->id != round_id)) break;
|
||||
auto it = subscriptions.find(handle);
|
||||
if (it == subscriptions.end()) {
|
||||
if (round && round->id == round_id) round->outstanding.erase(handle);
|
||||
continue;
|
||||
}
|
||||
std::shared_ptr<IdChangeResponder> responder;
|
||||
if (expect_response) responder = std::make_shared<Responder>(weak_from_this(), round_id, handle);
|
||||
IdChangeHook hook = it->second.hook;
|
||||
ByteBuffer data = it->second.data;
|
||||
hook(command, id, data, responder);
|
||||
}
|
||||
--notify_depth;
|
||||
if (expect_response && notify_depth == 0 && round && round->id == round_id) {
|
||||
if (round->outstanding.empty()) advance();
|
||||
else arm_round_timer();
|
||||
}
|
||||
}
|
||||
|
||||
void arm_round_timer() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
runtime.schedule(response_timeout, [this](Clock::time_point) { on_round_timeout(); }, &round_timer_scope);
|
||||
}
|
||||
|
||||
void try_start() {
|
||||
if (!pending_trigger || locked() || round) return;
|
||||
const auto* next = pool.next_valid(runtime.now());
|
||||
pending_trigger = false;
|
||||
if (!next) return; // nothing to change to; trigger() already reported this
|
||||
round = std::make_unique<Round>(Round {++round_counter, IdChangeCommand::PREPARE, next->digest, {}});
|
||||
notify(IdChangeCommand::PREPARE, round->new_identifier, true); // advances or arms the timer itself
|
||||
}
|
||||
|
||||
void handle_response(std::uint64_t round_id, SubscriptionHandle handle, bool return_code) {
|
||||
if (!round || round->id != round_id) return;
|
||||
if (round->outstanding.erase(handle) == 0) return;
|
||||
if (!return_code) {
|
||||
if (round->phase == IdChangeCommand::PREPARE) { abort(); return; }
|
||||
++stats.commit_failures; // COMMIT cannot be rolled back (Figure 11); recorded
|
||||
}
|
||||
if (round->outstanding.empty() && notify_depth == 0) advance();
|
||||
}
|
||||
|
||||
void advance() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
if (round->phase == IdChangeCommand::PREPARE) {
|
||||
round->phase = IdChangeCommand::COMMIT;
|
||||
pool.select(round->new_identifier);
|
||||
notify(IdChangeCommand::COMMIT, round->new_identifier, true); // finishes or arms the timer
|
||||
} else {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
void finish() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
const Identifier id = round->new_identifier;
|
||||
round.reset();
|
||||
++stats.committed;
|
||||
if (committed) committed(id);
|
||||
try_start(); // a trigger queued during this round
|
||||
}
|
||||
|
||||
void abort() {
|
||||
runtime.cancel(&round_timer_scope);
|
||||
const Identifier id = round->new_identifier;
|
||||
round.reset();
|
||||
++stats.aborted;
|
||||
notify(IdChangeCommand::ABORT, id, false); // Figures 12/13
|
||||
}
|
||||
|
||||
void on_round_timeout() {
|
||||
if (!round) return;
|
||||
++stats.timed_out;
|
||||
if (round->phase == IdChangeCommand::PREPARE) {
|
||||
abort();
|
||||
} else {
|
||||
stats.commit_failures += static_cast<unsigned>(round->outstanding.size());
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
void arm_lock_timer() {
|
||||
runtime.cancel(&lock_timer_scope);
|
||||
if (locks.empty()) return;
|
||||
Clock::time_point earliest = locks.begin()->second;
|
||||
for (const auto& lock : locks) earliest = std::min(earliest, lock.second);
|
||||
runtime.schedule(earliest, [this](Clock::time_point) { on_lock_timer(); }, &lock_timer_scope);
|
||||
}
|
||||
|
||||
void on_lock_timer() {
|
||||
const auto now = runtime.now();
|
||||
for (auto it = locks.begin(); it != locks.end();) {
|
||||
if (it->second <= now) it = locks.erase(it); else ++it;
|
||||
}
|
||||
arm_lock_timer();
|
||||
try_start();
|
||||
}
|
||||
};
|
||||
|
||||
IdentityManager::IdentityManager(Runtime& rt, CertificatePool& pool) : impl_(std::make_shared<Impl>(rt, pool)) {}
|
||||
|
||||
IdentityManager::~IdentityManager() {
|
||||
impl_->runtime.cancel(&impl_->round_timer_scope);
|
||||
impl_->runtime.cancel(&impl_->lock_timer_scope);
|
||||
impl_->round.reset();
|
||||
impl_->notify(IdChangeCommand::DEREG, impl_->current(), false); // Figure 15
|
||||
impl_->subscriptions.clear();
|
||||
}
|
||||
|
||||
SubscriptionHandle IdentityManager::subscribe(IdChangeHook hook, ByteBuffer subscriber_data) {
|
||||
const auto handle = impl_->next_subscription++;
|
||||
impl_->subscriptions.emplace(handle, Impl::Subscription {std::move(hook), std::move(subscriber_data)});
|
||||
return handle;
|
||||
}
|
||||
|
||||
Result IdentityManager::unsubscribe(SubscriptionHandle handle) {
|
||||
if (impl_->subscriptions.erase(handle) == 0) return Result::invalid_argument;
|
||||
if (impl_->round && impl_->round->outstanding.erase(handle) && impl_->round->outstanding.empty() &&
|
||||
impl_->notify_depth == 0)
|
||||
impl_->advance();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result IdentityManager::trigger() {
|
||||
if (!impl_->pool.next_valid(impl_->runtime.now())) return Result::rejected;
|
||||
impl_->pending_trigger = true;
|
||||
impl_->try_start();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
LockHandle IdentityManager::lock(std::uint8_t duration_seconds) {
|
||||
const auto handle = impl_->next_lock++;
|
||||
impl_->locks[handle] = impl_->runtime.now() + std::chrono::seconds(duration_seconds);
|
||||
impl_->arm_lock_timer();
|
||||
if (duration_seconds == 0) impl_->on_lock_timer(); // released at once
|
||||
return handle;
|
||||
}
|
||||
|
||||
Result IdentityManager::unlock(LockHandle handle) {
|
||||
if (impl_->locks.erase(handle) == 0) return Result::invalid_argument;
|
||||
impl_->arm_lock_timer();
|
||||
impl_->try_start();
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Identifier IdentityManager::current_identifier() const { return impl_->current(); }
|
||||
bool IdentityManager::change_pending() const { return static_cast<bool>(impl_->round); }
|
||||
void IdentityManager::set_response_timeout(Clock::duration timeout) { impl_->response_timeout = timeout; }
|
||||
void IdentityManager::on_committed(std::function<void(const Identifier&)> callback) { impl_->committed = std::move(callback); }
|
||||
const IdentityManager::Statistics& IdentityManager::statistics() const { return impl_->stats; }
|
||||
bool IdentityManager::locked() const { return impl_->locked(); }
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <microbu_v2x/its_g5_frame.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
namespace microbu_v2x::its_g5 {
|
||||
namespace {
|
||||
constexpr std::uint8_t snap[] = {0xaa, 0xaa, 0x03, 0, 0, 0, 0x89, 0x47};
|
||||
}
|
||||
Result encode_frame(const AlDataRequest& request, std::uint16_t sequence, vanetza::ByteBuffer& out) {
|
||||
if (validate(request, maximum_gnpdu) != Result::accepted || sequence > 4095)
|
||||
return Result::invalid_argument;
|
||||
out.assign(34 + request.data.size(), 0);
|
||||
out[0] = 0x88; // QoS Data; To DS=From DS=0 (OCB), no encryption at MAC.
|
||||
std::copy(request.destination.octets.begin(), request.destination.octets.end(), out.begin() + 4);
|
||||
std::copy(request.source.octets.begin(), request.source.octets.end(), out.begin() + 10);
|
||||
std::fill(out.begin() + 16, out.begin() + 22, 0xff); // wildcard BSSID
|
||||
out[22] = (sequence << 4) & 0xff; out[23] = sequence >> 4;
|
||||
out[24] = request.priority; // TID carries IEEE 802.1D user priority.
|
||||
std::copy(std::begin(snap), std::end(snap), out.begin() + 26);
|
||||
std::copy(request.data.begin(), request.data.end(), out.begin() + 34);
|
||||
return Result::accepted;
|
||||
}
|
||||
Result decode_frame(const std::uint8_t* data, std::size_t length, bool fcs, AlDataIndication& out) {
|
||||
if (!data || length < 34 + (fcs ? 4u : 0u)) return Result::invalid_argument;
|
||||
if (fcs) length -= 4;
|
||||
// Only non-fragmented, unprotected QoS Data with the OCB three-address
|
||||
// layout. Reject A-MSDU/HT-control rather than misinterpreting their offsets.
|
||||
if (data[0] != 0x88 || (data[1] & 0xc7) || (data[22] & 0x0f) ||
|
||||
(data[24] & 0x80) || !std::all_of(data + 16, data + 22, [](auto b) { return b == 0xff; }))
|
||||
return Result::unsupported;
|
||||
if (!std::equal(std::begin(snap), std::end(snap), data + 26)) return Result::unsupported;
|
||||
if (length == 34 || length - 34 > maximum_gnpdu) return Result::invalid_argument;
|
||||
std::copy(data + 4, data + 10, out.destination.octets.begin());
|
||||
std::copy(data + 10, data + 16, out.source.octets.begin());
|
||||
out.data.assign(data + 34, data + length);
|
||||
return Result::accepted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "local_security.hpp"
|
||||
#include <microbu_v2x/backend_mbedtls.hpp>
|
||||
#include <microbu_v2x/security_backend.hpp>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
|
||||
/// One NVS blob for the keys of the local software module.
|
||||
class NvsKeyStorage final : public security::KeyStorage {
|
||||
public:
|
||||
bool load(vanetza::ByteBuffer& out) override {
|
||||
nvs_handle_t handle;
|
||||
if (nvs_open(local_key_namespace, NVS_READONLY, &handle) != ESP_OK) return false;
|
||||
std::size_t size = 0;
|
||||
bool ok = nvs_get_blob(handle, local_key_name, nullptr, &size) == ESP_OK && size > 0;
|
||||
if (ok) {
|
||||
out.resize(size);
|
||||
ok = nvs_get_blob(handle, local_key_name, out.data(), &size) == ESP_OK;
|
||||
}
|
||||
nvs_close(handle);
|
||||
return ok;
|
||||
}
|
||||
bool save(const vanetza::ByteBuffer& blob) override {
|
||||
nvs_handle_t handle;
|
||||
if (nvs_open(local_key_namespace, NVS_READWRITE, &handle) != ESP_OK) return false;
|
||||
const bool ok = nvs_set_blob(handle, local_key_name, blob.data(), blob.size()) == ESP_OK &&
|
||||
nvs_commit(handle) == ESP_OK;
|
||||
nvs_close(handle);
|
||||
return ok;
|
||||
}
|
||||
};
|
||||
|
||||
/// The SE051's role in software on the ESP32-C5: keys in NVS, signatures through PSA.
|
||||
class LocalSecurityModule final : public security::SecurityModule {
|
||||
public:
|
||||
security::KeyId generate_key(security::KeyType type) override { return module_.generate_key(type); }
|
||||
std::optional<security::KeyId> import_key(const security::KeyPair& pair) override { return module_.import_key(pair); }
|
||||
std::optional<security::PublicKey> public_key(security::KeyId id) const override { return module_.public_key(id); }
|
||||
security::Signature sign_digest(security::KeyId id, const vanetza::ByteBuffer& digest) override {
|
||||
return module_.sign_digest(id, digest);
|
||||
}
|
||||
bool destroy_key(security::KeyId id) override { return module_.destroy_key(id); }
|
||||
|
||||
private:
|
||||
BackendMbedTls psa_;
|
||||
NvsKeyStorage storage_;
|
||||
security::SoftwareSecurityModule module_ {psa_, psa_, storage_};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<vanetza::security::Backend> make_local_security_backend() { return std::make_unique<BackendMbedTls>(); }
|
||||
|
||||
std::unique_ptr<security::SecurityModule> make_local_security_module() { return std::make_unique<LocalSecurityModule>(); }
|
||||
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <memory>
|
||||
|
||||
// The implementations on the ESP32 itself (local_security.cpp): PSA crypto for the public operations, and the
|
||||
// software security module with its keys in NVS.
|
||||
namespace microbu_v2x {
|
||||
std::unique_ptr<vanetza::security::Backend> make_local_security_backend();
|
||||
std::unique_ptr<security::SecurityModule> make_local_security_module();
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,137 @@
|
||||
// Management-plane bindings: MN-SAP (TS 102 723-4, TS 103 836-4-1 Annex K,
|
||||
// TS 103 175 clause 8.3), MF-SAP (TS 102 723-5, TS 103 175 clause 8.4) and
|
||||
// MI-SAP (TS 102 723-3, TS 103 175 clause 8.2). Values only ever come from the
|
||||
// providers the application registers.
|
||||
#include <microbu_v2x/mf_sap.hpp>
|
||||
#include <microbu_v2x/mi_sap.hpp>
|
||||
#include <microbu_v2x/mn_sap.hpp>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
// Shared GET/SET machinery: format check, access check, then the provider.
|
||||
template<class No, class Param, class Error, class Provider>
|
||||
void get_all(Provider* provider, const std::vector<No>& numbers, bool (*in_format)(No, std::uint32_t),
|
||||
std::vector<Param>& out, std::vector<Error>& errors) {
|
||||
for (auto no : numbers) {
|
||||
std::uint32_t value = 0;
|
||||
auto status = provider ? provider->get(no, value) : MN_SAP::ErrStatus::UNSUPPORTED;
|
||||
if (status == MN_SAP::ErrStatus::SUCCESS && !in_format(no, value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
|
||||
if (status == MN_SAP::ErrStatus::SUCCESS) out.push_back(Param {no, value});
|
||||
else errors.push_back(Error {no, status});
|
||||
}
|
||||
}
|
||||
template<class No, class Param, class Error, class Provider>
|
||||
void set_all(Provider* provider, const std::vector<Param>& params, bool (*in_format)(No, std::uint32_t),
|
||||
bool (*writable)(No), std::vector<Error>& errors) {
|
||||
for (const auto& param : params) {
|
||||
MN_SAP::ErrStatus status;
|
||||
if (!writable(param.no)) status = MN_SAP::ErrStatus::READ_ONLY;
|
||||
else if (!in_format(param.no, param.value)) status = MN_SAP::ErrStatus::INVALID_VALUE;
|
||||
else status = provider ? provider->set(param.no, param.value) : MN_SAP::ErrStatus::UNSUPPORTED;
|
||||
if (status != MN_SAP::ErrStatus::SUCCESS) errors.push_back(Error {param.no, status});
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
namespace MN_SAP {
|
||||
Result CORE_MMT_response_apply(Stack& stack, const CORE_MMT_response& response) {
|
||||
if (!response.time && !response.local_position_vector && !response.geonetworking_address && !response.tc_mapping)
|
||||
return Result::invalid_argument; // clause K.3: at least one parameter is present
|
||||
if (response.time) {
|
||||
const auto result = stack.advance(*response.time);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.local_position_vector) {
|
||||
const auto result = stack.update_position(*response.local_position_vector);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.geonetworking_address) {
|
||||
const auto result = stack.set_address(*response.geonetworking_address);
|
||||
if (result != Result::accepted) return result;
|
||||
}
|
||||
if (response.tc_mapping) return Result::unsupported; // fixed TS 102 687 mapping in this port
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
bool n_param_value_in_format(N_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 10 formats
|
||||
case N_Param_No::GLOBAL_CBR:
|
||||
case N_Param_No::LOCAL_CBR: return value <= 100;
|
||||
case N_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case N_Param_No::AVAILABLE_RESOURCE:
|
||||
case N_Param_No::IDLE_TIME: return value <= 0xffff;
|
||||
case N_Param_No::LAST_TRANSMIT_TIME: return true;
|
||||
case N_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31; // bits 5..7 reserved
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool n_param_writable(N_Param_No no) {
|
||||
return no == N_Param_No::CHANNEL_NUMBER || no == N_Param_No::IDLE_TIME || no == N_Param_No::TX_POWER_LEVEL_LIMIT;
|
||||
}
|
||||
MN_GET_confirm MN_GET_request_submit(NetworkParameterProvider* provider, const MN_GET_request& request) {
|
||||
MN_GET_confirm confirm {request.nt_id, request.command_ref, {}, {}};
|
||||
get_all<N_Param_No, N_Param, N_Error>(provider, request.n_param_no, n_param_value_in_format, confirm.n_param, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
MN_SET_confirm MN_SET_request_submit(NetworkParameterProvider* provider, const MN_SET_request& request) {
|
||||
MN_SET_confirm confirm {request.nt_id, request.command_ref, {}};
|
||||
set_all<N_Param_No, N_Param, N_Error>(provider, request.n_param, n_param_value_in_format, n_param_writable, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
} // namespace MN_SAP
|
||||
|
||||
namespace MF_SAP {
|
||||
bool f_param_value_in_format(F_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 13 formats
|
||||
case F_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case F_Param_No::AVAILABLE_RESOURCE: return value <= 0xffff;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
MF_SET_confirm MF_SET_request_submit(FacilitiesParameterSink* sink, const MF_SET_request& request) {
|
||||
MF_SET_confirm confirm {request.fac_id, request.command_ref, {}};
|
||||
for (const auto& param : request.f_param) {
|
||||
ErrStatus status;
|
||||
if (!f_param_value_in_format(param.no, param.value)) status = ErrStatus::INVALID_VALUE;
|
||||
else status = sink ? sink->set(param.no, param.value) : ErrStatus::UNSUPPORTED;
|
||||
if (status != ErrStatus::SUCCESS) confirm.errors.push_back(F_Error {param.no, status});
|
||||
}
|
||||
return confirm;
|
||||
}
|
||||
MF_COMMAND_confirm MF_COMMAND_request_submit(FacilitiesParameterSink* sink, const MF_COMMAND_request& request) {
|
||||
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED};
|
||||
return sink->command(request);
|
||||
}
|
||||
MF_REQUEST_confirm MF_REQUEST_request_submit(FacilitiesParameterSink* sink, const MF_REQUEST_request& request) {
|
||||
if (!sink) return {request.fac_id, request.command_ref, ErrStatus::UNSUPPORTED, {}};
|
||||
return sink->request(request);
|
||||
}
|
||||
} // namespace MF_SAP
|
||||
|
||||
namespace MI_SAP {
|
||||
bool i_param_value_in_format(I_Param_No no, std::uint32_t value) {
|
||||
switch (no) { // TS 103 175 Table 5 formats
|
||||
case I_Param_No::CHANNEL_NUMBER: return value >= 1 && value <= 7;
|
||||
case I_Param_No::LOCAL_CBR: return value <= 100;
|
||||
case I_Param_No::MESSAGE_LENGTH: return value <= 0xff;
|
||||
case I_Param_No::LAST_TRANSMIT_TIME: return true;
|
||||
case I_Param_No::IDLE_TIME: return value <= 0xffff;
|
||||
case I_Param_No::TX_POWER_LEVEL_LIMIT: return value <= 31;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool i_param_writable(I_Param_No no) {
|
||||
return no == I_Param_No::CHANNEL_NUMBER || no == I_Param_No::IDLE_TIME || no == I_Param_No::TX_POWER_LEVEL_LIMIT;
|
||||
}
|
||||
MI_GET_confirm MI_GET_request_submit(AccessParameterProvider* provider, const MI_GET_request& request) {
|
||||
MI_GET_confirm confirm {request.mac_id, request.command_ref, {}, {}};
|
||||
get_all<I_Param_No, I_Param, I_Error>(provider, request.i_param_no, i_param_value_in_format, confirm.i_param, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
MI_SET_confirm MI_SET_request_submit(AccessParameterProvider* provider, const MI_SET_request& request) {
|
||||
MI_SET_confirm confirm {request.mac_id, request.command_ref, {}};
|
||||
set_all<I_Param_No, I_Param, I_Error>(provider, request.i_param, i_param_value_in_format, i_param_writable, confirm.errors);
|
||||
return confirm;
|
||||
}
|
||||
} // namespace MI_SAP
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,50 @@
|
||||
#include <microbu_v2x/nvs_credential_store.hpp>
|
||||
#include <nvs.h>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
|
||||
namespace {
|
||||
// nvs_open/nvs_close around one operation; NVS handles are cheap and the store is stateless
|
||||
class Handle {
|
||||
public:
|
||||
Handle(const std::string& ns, nvs_open_mode_t mode) { error_ = nvs_open(ns.c_str(), mode, &handle_); }
|
||||
~Handle() { if (error_ == ESP_OK) nvs_close(handle_); }
|
||||
esp_err_t error() const { return error_; }
|
||||
nvs_handle_t get() const { return handle_; }
|
||||
private:
|
||||
nvs_handle_t handle_ = 0;
|
||||
esp_err_t error_ = ESP_FAIL;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Result NvsCredentialStore::save(const StoredCredentials& credentials) {
|
||||
const ByteBuffer bundle = encode(credentials);
|
||||
Handle nvs(namespace_, NVS_READWRITE);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected;
|
||||
if (nvs_set_blob(nvs.get(), key_.c_str(), bundle.data(), bundle.size()) != ESP_OK) return Result::resource_limit;
|
||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
Result NvsCredentialStore::load(StoredCredentials& credentials) {
|
||||
Handle nvs(namespace_, NVS_READONLY);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected; // no such namespace yet: nothing stored
|
||||
std::size_t size = 0;
|
||||
const esp_err_t probe = nvs_get_blob(nvs.get(), key_.c_str(), nullptr, &size);
|
||||
if (probe == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
|
||||
if (probe != ESP_OK || size == 0) return Result::rejected;
|
||||
ByteBuffer bundle(size);
|
||||
if (nvs_get_blob(nvs.get(), key_.c_str(), bundle.data(), &size) != ESP_OK) return Result::rejected;
|
||||
bundle.resize(size);
|
||||
return decode(bundle, credentials) ? Result::accepted : Result::invalid_argument;
|
||||
}
|
||||
|
||||
Result NvsCredentialStore::erase() {
|
||||
Handle nvs(namespace_, NVS_READWRITE);
|
||||
if (nvs.error() != ESP_OK) return Result::rejected;
|
||||
const esp_err_t error = nvs_erase_key(nvs.get(), key_.c_str());
|
||||
if (error == ESP_ERR_NVS_NOT_FOUND) return Result::rejected;
|
||||
if (error != ESP_OK) return Result::rejected;
|
||||
return nvs_commit(nvs.get()) == ESP_OK ? Result::accepted : Result::rejected;
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,996 @@
|
||||
// TS 102 941 V2.2.1 enrolment/authorization messages on the upstream
|
||||
// EtsiTs103097Data wrapper. See pki.hpp for the clause map.
|
||||
#include <microbu_v2x/pki.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/asn1/security/CtlCommand.h>
|
||||
#include <vanetza/asn1/security/CtlEntry.h>
|
||||
#include <vanetza/asn1/security/EtsiTs103097Certificate.h>
|
||||
#include <vanetza/asn1/security/InnerAtRequest.h>
|
||||
#include <vanetza/asn1/security/InnerEcRequest.h>
|
||||
#include <vanetza/asn1/security/PublicEncryptionKey.h>
|
||||
#include <vanetza/asn1/security/PublicVerificationKey.h>
|
||||
#include <vanetza/asn1/security/SharedAtRequest.h>
|
||||
#include <vanetza/asn1/security/ValidityPeriod.h>
|
||||
#include <vanetza/security/sha.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/asn1_conversions.hpp>
|
||||
#include <vanetza/security/v3/hash.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
using SecuredData = v3::SecuredMessage; // EtsiTs103097Data wrapper
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t aes_key_length = 16;
|
||||
constexpr std::size_t nonce_length = 12;
|
||||
constexpr std::size_t tag_length = 16;
|
||||
|
||||
ByteBuffer octets(const OCTET_STRING_t& s) { return ByteBuffer(s.buf, s.buf + s.size); }
|
||||
|
||||
// EccP256CurvePoint -> PublicKey (x-only points carry no usable y and are refused)
|
||||
std::optional<PublicKey> point_to_key(const Vanetza_Security_EccP256CurvePoint& point, KeyType type) {
|
||||
PublicKey key;
|
||||
key.type = type;
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||
key.compression = KeyCompression::Y0; key.x = octets(point.choice.compressed_y_0); break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||
key.compression = KeyCompression::Y1; key.x = octets(point.choice.compressed_y_1); break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
|
||||
key.compression = KeyCompression::NoCompression;
|
||||
key.x = octets(point.choice.uncompressedP256.x); key.y = octets(point.choice.uncompressedP256.y); break;
|
||||
default: return std::nullopt;
|
||||
}
|
||||
if (key.x.size() != 32) return std::nullopt;
|
||||
return key;
|
||||
}
|
||||
|
||||
// uncompressed form for backends that need y (ECDH peer key)
|
||||
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||
if (key.compression == KeyCompression::NoCompression) return key;
|
||||
auto point = ecc::decompress(key.type, key.x, key.compression == KeyCompression::Y1);
|
||||
if (!point) return std::nullopt;
|
||||
PublicKey out = key;
|
||||
out.compression = KeyCompression::NoCompression;
|
||||
out.y = point->y;
|
||||
return out;
|
||||
}
|
||||
|
||||
PublicKey compressed(const PublicKey& key) {
|
||||
if (key.compression != KeyCompression::NoCompression || key.y.empty()) return key;
|
||||
PublicKey out = key;
|
||||
out.compression = (key.y.back() & 1) ? KeyCompression::Y1 : KeyCompression::Y0;
|
||||
out.y.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
void fill_point(Vanetza_Security_EccP256CurvePoint& point, const PublicKey& key) {
|
||||
point = v3::to_asn1(make_ecc_point(compressed(key)));
|
||||
}
|
||||
|
||||
void fill_verification_key(Vanetza_Security_PublicVerificationKey& out, const PublicKey& key) {
|
||||
if (key.type == KeyType::BrainpoolP256r1) {
|
||||
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1;
|
||||
fill_point(out.choice.ecdsaBrainpoolP256r1, key);
|
||||
} else {
|
||||
out.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256;
|
||||
fill_point(out.choice.ecdsaNistP256, key);
|
||||
}
|
||||
}
|
||||
|
||||
void fill_encryption_key(Vanetza_Security_PublicEncryptionKey& out, const PublicKey& key) {
|
||||
out.supportedSymmAlg = Vanetza_Security_SymmAlgorithm_aes128Ccm;
|
||||
if (key.type == KeyType::BrainpoolP256r1) {
|
||||
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesBrainpoolP256r1;
|
||||
fill_point(out.publicKey.choice.eciesBrainpoolP256r1, key);
|
||||
} else {
|
||||
out.publicKey.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256;
|
||||
fill_point(out.publicKey.choice.eciesNistP256, key);
|
||||
}
|
||||
}
|
||||
|
||||
void fill_permissions(Vanetza_Security_CertificateSubjectAttributes& attributes, const Permissions& permissions) {
|
||||
if (permissions.empty()) return;
|
||||
attributes.appPermissions = v3::asn1::allocate<Vanetza_Security_SequenceOfPsidSsp>();
|
||||
for (const auto& permission : permissions) {
|
||||
auto* entry = v3::asn1::allocate<Vanetza_Security_PsidSsp>();
|
||||
entry->psid = permission.first;
|
||||
if (!permission.second.empty()) {
|
||||
entry->ssp = v3::asn1::allocate<Vanetza_Security_ServiceSpecificPermissions>();
|
||||
entry->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
|
||||
v3::assign(&entry->ssp->choice.bitmapSsp, permission.second);
|
||||
}
|
||||
ASN_SEQUENCE_ADD(attributes.appPermissions, entry);
|
||||
}
|
||||
}
|
||||
|
||||
// IEEE 1609.2 clause 5.3.1: Hash(Hash(tbsData) || Hash(signer certificate or empty string))
|
||||
ByteBuffer message_digest(Backend& backend, HashAlgorithm hash, const ByteBuffer& tbs, const Certificate* signer) {
|
||||
if (signer) return v3::calculate_message_hash(backend, hash, tbs, *signer);
|
||||
ByteBuffer concat = backend.calculate_hash(hash, tbs);
|
||||
const ByteBuffer empty = backend.calculate_hash(hash, ByteBuffer {});
|
||||
concat.insert(concat.end(), empty.begin(), empty.end());
|
||||
return backend.calculate_hash(hash, concat);
|
||||
}
|
||||
|
||||
// Fill the common header of a signed structure (TS 102 941: psid 623, generationTime only).
|
||||
void prepare_signed(SecuredData& data, HashAlgorithm hash, Clock::time_point now, const Certificate* signer) {
|
||||
data.set_hash_id(hash);
|
||||
data.set_its_aid(aid::SCR);
|
||||
data.set_generation_time(v2::convert_time64(now));
|
||||
if (signer) {
|
||||
const auto digest = signer->calculate_digest();
|
||||
if (digest) data.set_signer_identifier(*digest); else data.set_signer_identifier_self();
|
||||
} else {
|
||||
data.set_signer_identifier_self();
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> finish_signed(Backend& backend, SecuredData& data, HashAlgorithm hash, const Signer& sign,
|
||||
const Certificate* signer) {
|
||||
try {
|
||||
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||
data.set_signature(sign(digest));
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer psk_id_input(const std::array<std::uint8_t, aes_key_length>& key) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_SymmetricEncryptionKey> wrapper(asn_DEF_Vanetza_Security_SymmetricEncryptionKey);
|
||||
wrapper->present = Vanetza_Security_SymmetricEncryptionKey_PR_aes128Ccm;
|
||||
OCTET_STRING_fromBuf(&wrapper->choice.aes128Ccm, reinterpret_cast<const char*>(key.data()), key.size());
|
||||
return wrapper.encode();
|
||||
}
|
||||
|
||||
std::array<std::uint8_t, 16> left16(const ByteBuffer& in) {
|
||||
std::array<std::uint8_t, 16> out {};
|
||||
std::copy_n(in.begin(), std::min<std::size_t>(16, in.size()), out.begin());
|
||||
return out;
|
||||
}
|
||||
|
||||
// InnerEcResponse / InnerAtResponse share the layout: requestHash, responseCode, certificate OPTIONAL
|
||||
template<class Inner>
|
||||
Result read_inner_response(const Inner& inner, const RequestContext& context, std::uint8_t& code,
|
||||
std::optional<Certificate>& certificate) {
|
||||
certificate.reset();
|
||||
if (inner.requestHash.size != 16 || std::memcmp(inner.requestHash.buf, context.request_hash.data(), 16) != 0)
|
||||
return Result::rejected; // the response answers another request
|
||||
code = static_cast<std::uint8_t>(inner.responseCode);
|
||||
if (inner.certificate) {
|
||||
// asn1c forward-declares a distinct struct tag for this member; the object it points to is
|
||||
// decoded with asn_DEF_Vanetza_Security_EtsiTs103097Certificate, i.e. an EtsiTs103097Certificate_t.
|
||||
Certificate cert(*reinterpret_cast<const Vanetza_Security_EtsiTs103097Certificate_t*>(inner.certificate));
|
||||
if (!cert.validate()) return Result::rejected;
|
||||
certificate = std::move(cert);
|
||||
} else if (code == 0) {
|
||||
return Result::rejected; // clause 6.2.3.2.2: a positive response returns a certificate
|
||||
}
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
// Decrypt, verify the authority signature and hand back the EtsiTs102941Data
|
||||
std::optional<ByteBuffer> open_response(Backend& backend, EciesBackend& ecies, const RequestContext& context,
|
||||
const Certificate& authority, const ByteBuffer& encoded) {
|
||||
auto signed_bytes = decrypt_with_psk(ecies, context.aes_key, encoded);
|
||||
if (!signed_bytes) return std::nullopt;
|
||||
return verify_signed(backend, *signed_bytes, nullptr, &authority, aid::SCR);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
ByteBuffer kdf2_sha256(Backend& backend, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t length) {
|
||||
ByteBuffer derived;
|
||||
for (std::uint32_t counter = 1; derived.size() < length; ++counter) {
|
||||
ByteBuffer input = shared_secret;
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 24));
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 16));
|
||||
input.push_back(static_cast<std::uint8_t>(counter >> 8));
|
||||
input.push_back(static_cast<std::uint8_t>(counter));
|
||||
input.insert(input.end(), kdp.begin(), kdp.end());
|
||||
const auto block = backend.calculate_hash(HashAlgorithm::SHA256, input);
|
||||
derived.insert(derived.end(), block.begin(), block.end());
|
||||
}
|
||||
derived.resize(length);
|
||||
return derived;
|
||||
}
|
||||
|
||||
std::optional<EncryptedKey> ecies_encrypt_key(Backend& backend, EciesBackend& ecies, const PublicKey& recipient,
|
||||
const ByteBuffer& p1, const std::array<std::uint8_t, 16>& aes_key) {
|
||||
const auto peer = uncompressed(recipient);
|
||||
if (!peer || (peer->type != KeyType::NistP256 && peer->type != KeyType::BrainpoolP256r1)) return std::nullopt;
|
||||
try {
|
||||
const KeyPair ephemeral = ecies.generate_key(peer->type);
|
||||
const auto secret = ecies.ecdh_x(ephemeral.priv, *peer);
|
||||
if (!secret) return std::nullopt;
|
||||
// K1 (16 octets, key encryption) || K2 (32 octets, MAC key)
|
||||
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||
EncryptedKey out;
|
||||
out.v = ephemeral.pub;
|
||||
ByteBuffer c(aes_key_length);
|
||||
for (std::size_t i = 0; i < aes_key_length; ++i) c[i] = k[i] ^ aes_key[i];
|
||||
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||
if (tag.size() < tag_length) return std::nullopt;
|
||||
out.c = left16(c);
|
||||
out.t = left16(tag);
|
||||
return out;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<std::array<std::uint8_t, 16>> ecies_decrypt_key(Backend& backend, EciesBackend& ecies,
|
||||
const PrivateKey& recipient, const ByteBuffer& p1,
|
||||
const EncryptedKey& encrypted) {
|
||||
const auto peer = uncompressed(encrypted.v);
|
||||
if (!peer) return std::nullopt;
|
||||
try {
|
||||
const auto secret = ecies.ecdh_x(recipient, *peer);
|
||||
if (!secret) return std::nullopt;
|
||||
const ByteBuffer k = kdf2_sha256(backend, *secret, p1, aes_key_length + 32);
|
||||
const ByteBuffer c(encrypted.c.begin(), encrypted.c.end());
|
||||
const ByteBuffer k2(k.begin() + aes_key_length, k.end());
|
||||
const ByteBuffer tag = ecies.hmac_sha256(k2, c);
|
||||
if (tag.size() < tag_length) return std::nullopt;
|
||||
// constant-time comparison of the truncated tag
|
||||
unsigned diff = 0;
|
||||
for (std::size_t i = 0; i < tag_length; ++i) diff |= tag[i] ^ encrypted.t[i];
|
||||
if (diff != 0) return std::nullopt;
|
||||
std::array<std::uint8_t, 16> key {};
|
||||
for (std::size_t i = 0; i < aes_key_length; ++i) key[i] = k[i] ^ encrypted.c[i];
|
||||
return key;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- building blocks -------------------------------------------------------
|
||||
|
||||
Signer module_signer(security::SecurityModule& module, security::KeyId key) {
|
||||
return [&module, key](const ByteBuffer& digest) { return module.sign_digest(key, digest); };
|
||||
}
|
||||
|
||||
Signer key_signer(Backend& backend, PrivateKey key) {
|
||||
return [&backend, key = std::move(key)](const ByteBuffer& digest) { return backend.sign_digest(key, digest); };
|
||||
}
|
||||
|
||||
SigningKey signing_key(Backend& backend, const KeyPair& pair) { return {pair.pub, key_signer(backend, pair.priv)}; }
|
||||
|
||||
std::optional<ByteBuffer> sign_data(Backend& backend, Clock::time_point now, HashAlgorithm hash, const ByteBuffer& payload,
|
||||
const Signer& sign, const Certificate* signer) {
|
||||
SecuredData data = SecuredData::with_signed_data();
|
||||
prepare_signed(data, hash, now, signer);
|
||||
data.set_payload(payload);
|
||||
return finish_signed(backend, data, hash, sign, signer);
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> sign_external(Backend& backend, Clock::time_point now, const ByteBuffer& external_payload,
|
||||
const Signer& sign, const Certificate& signer) {
|
||||
SecuredData data = SecuredData::with_signed_data_hash();
|
||||
prepare_signed(data, HashAlgorithm::SHA256, now, &signer);
|
||||
data.set_external_payload_hash(calculate_sha256_digest(external_payload.data(), external_payload.size()));
|
||||
return finish_signed(backend, data, HashAlgorithm::SHA256, sign, &signer);
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> encrypt_for(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||
const ByteBuffer& plaintext, std::array<std::uint8_t, 16>& aes_key) {
|
||||
const auto encryption_key = v3::get_public_encryption_key(*recipient.content());
|
||||
const auto recipient_id = recipient.calculate_digest();
|
||||
if (!encryption_key || !recipient_id) return std::nullopt;
|
||||
try {
|
||||
const ByteBuffer random = ecies.random(aes_key_length + nonce_length);
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
std::copy_n(random.begin(), aes_key_length, aes_key.begin());
|
||||
std::copy_n(random.begin() + aes_key_length, nonce_length, nonce.begin());
|
||||
ByteBuffer ciphertext;
|
||||
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||
// P1 = SHA-256 of the recipient certificate (IEEE 1609.2 clause 5.3.5, certRecipInfo)
|
||||
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||
const auto wrapped = ecies_encrypt_key(backend, ecies, *encryption_key, p1, aes_key);
|
||||
if (!wrapped) return std::nullopt;
|
||||
SecuredData data = SecuredData::with_encrypted_data();
|
||||
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
data.set_cert_recip_info(*recipient_id, wrapped->c, wrapped->t, compressed(wrapped->v));
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> encrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||
const ByteBuffer& plaintext) {
|
||||
try {
|
||||
const ByteBuffer random = ecies.random(nonce_length);
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
std::copy_n(random.begin(), nonce_length, nonce.begin());
|
||||
ByteBuffer ciphertext;
|
||||
if (!ecies.aes_ccm_encrypt(aes_key, nonce, plaintext, ciphertext)) return std::nullopt;
|
||||
SecuredData data = SecuredData::with_encrypted_data();
|
||||
data.set_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
// pskRecipInfo = HashedId8 of the COER SymmetricEncryptionKey (IEEE 1609.2 clause 6.3.43)
|
||||
const ByteBuffer key_encoding = psk_id_input(aes_key);
|
||||
const HashedId8 psk_id = create_hashed_id8(calculate_sha256_digest(key_encoding.data(), key_encoding.size()));
|
||||
auto* recipient = v3::asn1::allocate<Vanetza_Security_RecipientInfo>();
|
||||
recipient->present = Vanetza_Security_RecipientInfo_PR_pskRecipInfo;
|
||||
OCTET_STRING_fromBuf(&recipient->choice.pskRecipInfo, reinterpret_cast<const char*>(psk_id.data()), psk_id.size());
|
||||
ASN_SEQUENCE_ADD(&data->content->choice.encryptedData.recipients.list, recipient);
|
||||
return data.encode();
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> decrypt_as_recipient(Backend& backend, EciesBackend& ecies, const Certificate& recipient,
|
||||
const PrivateKey& encryption_key, const ByteBuffer& encoded,
|
||||
std::array<std::uint8_t, 16>* aes_key_out) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||
const auto own_id = recipient.calculate_digest();
|
||||
if (!own_id) return std::nullopt;
|
||||
const auto& recipients = data->content->choice.encryptedData.recipients.list;
|
||||
for (int i = 0; i < recipients.count; ++i) {
|
||||
const auto* info = recipients.array[i];
|
||||
if (!info || info->present != Vanetza_Security_RecipientInfo_PR_certRecipInfo) continue;
|
||||
const auto& cert_info = info->choice.certRecipInfo;
|
||||
if (cert_info.recipientId.size != 8 || std::memcmp(cert_info.recipientId.buf, own_id->data(), 8) != 0) continue;
|
||||
const Vanetza_Security_EciesP256EncryptedKey* ecies_key = nullptr;
|
||||
KeyType type = KeyType::NistP256;
|
||||
if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesNistP256) {
|
||||
ecies_key = &cert_info.encKey.choice.eciesNistP256;
|
||||
} else if (cert_info.encKey.present == Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesBrainpoolP256r1) {
|
||||
ecies_key = &cert_info.encKey.choice.eciesBrainpoolP256r1;
|
||||
type = KeyType::BrainpoolP256r1;
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (ecies_key->c.size != 16 || ecies_key->t.size != 16) continue;
|
||||
EncryptedKey wrapped;
|
||||
auto v = point_to_key(ecies_key->v, type);
|
||||
if (!v) continue;
|
||||
wrapped.v = *v;
|
||||
std::copy_n(ecies_key->c.buf, 16, wrapped.c.begin());
|
||||
std::copy_n(ecies_key->t.buf, 16, wrapped.t.begin());
|
||||
const ByteBuffer p1 = backend.calculate_hash(HashAlgorithm::SHA256, recipient.encode());
|
||||
const auto aes_key = ecies_decrypt_key(backend, ecies, encryption_key, p1, wrapped);
|
||||
if (!aes_key) return std::nullopt;
|
||||
ByteBuffer ciphertext;
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
ByteBuffer plaintext;
|
||||
if (!ecies.aes_ccm_decrypt(*aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||
if (aes_key_out) *aes_key_out = *aes_key;
|
||||
return plaintext;
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> decrypt_with_psk(EciesBackend& ecies, const std::array<std::uint8_t, 16>& aes_key,
|
||||
const ByteBuffer& encoded) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_encrypted()) return std::nullopt;
|
||||
if (!data.check_psk_match(aes_key)) return std::nullopt; // response is not for this request
|
||||
ByteBuffer ciphertext;
|
||||
std::array<std::uint8_t, nonce_length> nonce {};
|
||||
data.get_aes_ccm_ciphertext(ciphertext, nonce);
|
||||
ByteBuffer plaintext;
|
||||
if (!ecies.aes_ccm_decrypt(aes_key, nonce, ciphertext, plaintext)) return std::nullopt;
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> verify_signed(Backend& backend, const ByteBuffer& encoded, const PublicKey* self_key,
|
||||
const Certificate* signer, ItsAid expected_psid) {
|
||||
SecuredData data;
|
||||
if (!data.decode(encoded) || data.encode() != encoded || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||
if (data.its_aid() != expected_psid || !data.generation_time()) return std::nullopt;
|
||||
const auto hash = data.hash_id();
|
||||
const auto signature = data.signature();
|
||||
if (hash == HashAlgorithm::Unspecified || !signature) return std::nullopt;
|
||||
const auto* signed_data = data->content->choice.signedData;
|
||||
// TS 102 941 V2.2.1 clause 6.2: management messages use only PSID and generationTime.
|
||||
const auto& header = signed_data->tbsData->headerInfo;
|
||||
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions)
|
||||
return std::nullopt;
|
||||
PublicKey key;
|
||||
if (signer) {
|
||||
const auto digest = signer->calculate_digest();
|
||||
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_digest || !digest ||
|
||||
signed_data->signer.choice.digest.size != 8 ||
|
||||
std::memcmp(signed_data->signer.choice.digest.buf, digest->data(), 8) != 0) return std::nullopt;
|
||||
const auto signer_key = v3::get_public_key(*signer->content());
|
||||
if (!signer_key) return std::nullopt;
|
||||
key = *signer_key;
|
||||
} else {
|
||||
if (signed_data->signer.present != Vanetza_Security_SignerIdentifier_PR_self || !self_key) return std::nullopt;
|
||||
key = *self_key;
|
||||
}
|
||||
const auto digest = message_digest(backend, hash, data.signing_payload(), signer);
|
||||
if (!backend.verify_digest(key, digest, *signature)) return std::nullopt;
|
||||
auto payload = data.payload();
|
||||
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||
return ByteBuffer(view.begin(), view.end());
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.2.3.2 --------------------------------------------------
|
||||
|
||||
bool validate_issued_certificate(Backend& backend, const Certificate& certificate, const Certificate& issuer,
|
||||
const PublicKey& requested_key, Clock::time_point now, const Permissions& expected,
|
||||
bool enrolment) {
|
||||
try {
|
||||
if (certificate->version != 3 || certificate->type != Vanetza_Security_CertificateType_explicit ||
|
||||
certificate->toBeSigned.certIssuePermissions || !certificate->toBeSigned.appPermissions ||
|
||||
!certificate.valid_at_timepoint(now) || !issuer.valid_at_timepoint(now)) return false;
|
||||
const auto id = certificate->toBeSigned.id.present;
|
||||
if ((enrolment && id != Vanetza_Security_CertificateId_PR_name) ||
|
||||
(!enrolment && id != Vanetza_Security_CertificateId_PR_none)) return false;
|
||||
const auto digest = issuer.calculate_digest();
|
||||
const auto referenced = certificate.issuer_digest();
|
||||
if (!digest || !referenced || *digest != *referenced ||
|
||||
!security::verify_certificate_signature(backend, certificate, &issuer) ||
|
||||
!security::chain_permissions_consistent({&certificate, &issuer}) ||
|
||||
!security::region_within(certificate, issuer, true)) return false;
|
||||
const auto subject_time = microbu_v2x::security::validity_bounds(certificate);
|
||||
const auto assurance = certificate.assurance_level();
|
||||
const auto issuer_assurance = issuer.assurance_level();
|
||||
if (assurance) {
|
||||
if (!issuer_assurance) return false;
|
||||
const auto level = (*assurance >> 5) & 7;
|
||||
const auto issuer_level = (*issuer_assurance >> 5) & 7;
|
||||
if (level > issuer_level || (level == issuer_level &&
|
||||
((*assurance >> 2) & 7) > ((*issuer_assurance >> 2) & 7))) return false;
|
||||
}
|
||||
const auto issuer_time = microbu_v2x::security::validity_bounds(issuer);
|
||||
if (subject_time.start_validity < issuer_time.start_validity || subject_time.end_validity > issuer_time.end_validity)
|
||||
return false;
|
||||
if (certificate->toBeSigned.appPermissions->list.count != static_cast<int>(expected.size())) return false;
|
||||
for (const auto& permission : expected) {
|
||||
if (!certificate.valid_for_application(permission.first) ||
|
||||
v3::get_app_permissions(*certificate.content(), permission.first) != permission.second) return false;
|
||||
}
|
||||
const auto public_key = v3::get_public_key(*certificate.content());
|
||||
return public_key && security::same_public_key(*public_key, requested_key);
|
||||
} catch (const std::exception&) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Result build_enrolment_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||
const EnrolmentRequestParameters& params, const Certificate& ea, ByteBuffer& encoded,
|
||||
RequestContext& context) {
|
||||
if (params.its_id.empty() || !params.verification_key.sign || !params.outer_signer) return Result::invalid_argument;
|
||||
if (!v3::get_public_encryption_key(*ea.content())) return Result::invalid_argument;
|
||||
// 1. InnerEcRequest (certificateFormat ts103097v131 = 1)
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest> inner(asn_DEF_Vanetza_Security_InnerEcRequest);
|
||||
v3::assign(&inner->itsId, params.its_id);
|
||||
inner->certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
fill_verification_key(inner->publicKeys.verificationKey, params.verification_key.pub);
|
||||
fill_permissions(inner->requestedSubjectAttributes, params.app_permissions);
|
||||
if (!inner.validate()) return Result::invalid_argument;
|
||||
// 2. InnerEcRequestSignedForPop: self-signed with the new verification key
|
||||
auto pop = sign_data(backend, now, params.hash, inner.encode(), params.verification_key.sign, nullptr);
|
||||
if (!pop) return Result::security_unavailable;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentRequest;
|
||||
void* target = &mgmt->content.choice.enrolmentRequest;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *pop)) return Result::security_unavailable;
|
||||
// 3. Outer EtsiTs103097Data-Signed: self (canonical key) or digest of the current EC
|
||||
auto outer = sign_data(backend, now, params.hash, mgmt.encode(), params.outer_signer, params.current_ec);
|
||||
if (!outer) return Result::security_unavailable;
|
||||
// 4. EtsiTs103097Data-Encrypted for the EA
|
||||
auto encrypted = encrypt_for(backend, ecies, ea, *outer, context.aes_key);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
encoded = std::move(*encrypted);
|
||||
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result parse_enrolment_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& ea,
|
||||
const ByteBuffer& encoded, EnrolmentResponse& out) {
|
||||
auto mgmt_bytes = open_response(backend, ecies, context, ea, encoded);
|
||||
if (!mgmt_bytes) return Result::rejected;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentResponse) return Result::rejected;
|
||||
return read_inner_response(mgmt->content.choice.enrolmentResponse, context, out.response_code, out.certificate);
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.2.3.3 --------------------------------------------------
|
||||
|
||||
Result build_authorization_request(Backend& backend, EciesBackend& ecies, Clock::time_point now,
|
||||
const AuthorizationRequestParameters& params, const Certificate& ea,
|
||||
const Certificate& aa, ByteBuffer& encoded, RequestContext& context) {
|
||||
if (!params.ec || !params.ec_signer || !params.verification_key.sign || params.app_permissions.empty())
|
||||
return Result::invalid_argument;
|
||||
if (params.hash != HashAlgorithm::SHA256) return Result::unsupported; // extDataHash carries sha256HashedData
|
||||
if (!v3::get_public_encryption_key(*aa.content()) || (params.privacy && !v3::get_public_encryption_key(*ea.content())))
|
||||
return Result::invalid_argument;
|
||||
const auto ea_id = ea.calculate_digest();
|
||||
if (!ea_id) return Result::invalid_argument;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_authorizationRequest;
|
||||
auto& inner = mgmt->content.choice.authorizationRequest;
|
||||
// publicKeys: new verification key and optional encryption key
|
||||
fill_verification_key(inner.publicKeys.verificationKey, params.verification_key.pub);
|
||||
if (params.encryption_key) {
|
||||
inner.publicKeys.encryptionKey = v3::asn1::allocate<Vanetza_Security_PublicEncryptionKey>();
|
||||
fill_encryption_key(*inner.publicKeys.encryptionKey, *params.encryption_key);
|
||||
}
|
||||
// hmacKey: 32 random octets; keyTag = leftmost 16 octets of HMAC-SHA256(hmacKey, OER(publicKeys))
|
||||
ByteBuffer hmac_key;
|
||||
try { hmac_key = ecies.random(32); } catch (const std::exception&) { return Result::security_unavailable; }
|
||||
if (hmac_key.size() != 32) return Result::security_unavailable;
|
||||
v3::assign(&inner.hmacKey, hmac_key);
|
||||
ByteBuffer tag_input = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicVerificationKey, &inner.publicKeys.verificationKey);
|
||||
if (inner.publicKeys.encryptionKey) {
|
||||
const auto enc = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_PublicEncryptionKey, inner.publicKeys.encryptionKey);
|
||||
tag_input.insert(tag_input.end(), enc.begin(), enc.end());
|
||||
}
|
||||
const auto key_tag = ecies.hmac_sha256(hmac_key, tag_input);
|
||||
if (key_tag.size() < 16) return Result::security_unavailable;
|
||||
// SharedAtRequest
|
||||
auto& shared = inner.sharedAtRequest;
|
||||
OCTET_STRING_fromBuf(&shared.eaId, reinterpret_cast<const char*>(ea_id->data()), ea_id->size());
|
||||
OCTET_STRING_fromBuf(&shared.keyTag, reinterpret_cast<const char*>(key_tag.data()), 16);
|
||||
shared.certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
fill_permissions(shared.requestedSubjectAttributes, params.app_permissions);
|
||||
if (params.validity_period) {
|
||||
shared.requestedSubjectAttributes.validityPeriod = v3::asn1::allocate<Vanetza_Security_ValidityPeriod>();
|
||||
shared.requestedSubjectAttributes.validityPeriod->start = v2::convert_time32(params.validity_period->first);
|
||||
shared.requestedSubjectAttributes.validityPeriod->duration.present = Vanetza_Security_Duration_PR_hours;
|
||||
shared.requestedSubjectAttributes.validityPeriod->duration.choice.hours = params.validity_period->second;
|
||||
}
|
||||
// EC signature over the SharedAtRequest (external payload), signer = digest of the EC
|
||||
const ByteBuffer shared_encoded = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_SharedAtRequest, &shared);
|
||||
auto ec_signed = sign_external(backend, now, shared_encoded, params.ec_signer, *params.ec);
|
||||
if (!ec_signed) return Result::security_unavailable;
|
||||
ByteBuffer ec_signature_bytes;
|
||||
if (params.privacy) {
|
||||
std::array<std::uint8_t, 16> throwaway {};
|
||||
auto encrypted = encrypt_for(backend, ecies, ea, *ec_signed, throwaway);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_encryptedEcSignature;
|
||||
void* target = &inner.ecSignature.choice.encryptedEcSignature;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *encrypted)) return Result::security_unavailable;
|
||||
} else {
|
||||
inner.ecSignature.present = Vanetza_Security_EcSignature_PR_ecSignature;
|
||||
void* target = &inner.ecSignature.choice.ecSignature;
|
||||
if (!vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Data, &target, *ec_signed)) return Result::security_unavailable;
|
||||
}
|
||||
if (!mgmt.validate()) return Result::security_unavailable;
|
||||
ByteBuffer plaintext = mgmt.encode();
|
||||
if (params.include_pop) {
|
||||
auto pop = sign_data(backend, now, params.hash, plaintext, params.verification_key.sign, nullptr);
|
||||
if (!pop) return Result::security_unavailable;
|
||||
plaintext = std::move(*pop);
|
||||
} else {
|
||||
// EtsiTs103097Data unsecured envelope around the EtsiTs102941Data
|
||||
SecuredData envelope;
|
||||
envelope->protocolVersion = 3;
|
||||
envelope->content = v3::asn1::allocate<Vanetza_Security_Ieee1609Dot2Content>();
|
||||
envelope->content->present = Vanetza_Security_Ieee1609Dot2Content_PR_unsecuredData;
|
||||
v3::assign(&envelope->content->choice.unsecuredData, plaintext);
|
||||
plaintext = envelope.encode();
|
||||
}
|
||||
auto encrypted = encrypt_for(backend, ecies, aa, plaintext, context.aes_key);
|
||||
if (!encrypted) return Result::security_unavailable;
|
||||
encoded = std::move(*encrypted);
|
||||
context.request_hash = left16(backend.calculate_hash(HashAlgorithm::SHA256, encoded));
|
||||
return Result::accepted;
|
||||
}
|
||||
|
||||
Result parse_authorization_response(Backend& backend, EciesBackend& ecies, const RequestContext& context, const Certificate& aa,
|
||||
const ByteBuffer& encoded, AuthorizationResponse& out) {
|
||||
auto mgmt_bytes = open_response(backend, ecies, context, aa, encoded);
|
||||
if (!mgmt_bytes) return Result::rejected;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_authorizationResponse) return Result::rejected;
|
||||
return read_inner_response(mgmt->content.choice.authorizationResponse, context, out.response_code, out.certificate);
|
||||
}
|
||||
|
||||
// ---- TS 102 941 clause 6.3: RCA trust list and revocation list -----------------------
|
||||
|
||||
namespace {
|
||||
void set_url(Vanetza_Security_Url_t& url, const std::string& text) {
|
||||
OCTET_STRING_fromBuf(&url, text.data(), text.size());
|
||||
}
|
||||
std::string get_url(const Vanetza_Security_Url_t& url) {
|
||||
return std::string(reinterpret_cast<const char*>(url.buf), url.size);
|
||||
}
|
||||
void set_hashed_id8(Vanetza_Security_HashedId8_t& target, const HashedId8& id) {
|
||||
OCTET_STRING_fromBuf(&target, reinterpret_cast<const char*>(id.data()), id.size());
|
||||
}
|
||||
std::optional<HashedId8> get_hashed_id8(const Vanetza_Security_HashedId8_t& source) {
|
||||
if (source.size != 8) return std::nullopt;
|
||||
HashedId8 id;
|
||||
std::copy_n(source.buf, 8, id.begin());
|
||||
return id;
|
||||
}
|
||||
// the certificate structure of an entry, decoded from COER into the inline member
|
||||
bool put_certificate(Vanetza_Security_EtsiTs103097Certificate_t& target, const ByteBuffer& coer) {
|
||||
void* into = ⌖
|
||||
return vanetza::asn1::decode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &into, coer);
|
||||
}
|
||||
|
||||
// TS 102 941 clauses 6.3.3 and 6.3.4. CTLs carry the issuer certificate.
|
||||
std::optional<ByteBuffer> sign_list(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
ItsAid psid, const ByteBuffer& mgmt) {
|
||||
if (!rca.valid_for_application(psid)) return std::nullopt; // TS 103 097 clause 7.2.3: CRL/CTL appPermissions
|
||||
SecuredData data = SecuredData::with_signed_data();
|
||||
const auto hash = rca->issuer.present == Vanetza_Security_IssuerIdentifier_PR_self &&
|
||||
rca->issuer.choice.self == Vanetza_Security_HashAlgorithm_sha384 ? HashAlgorithm::SHA384 : HashAlgorithm::SHA256;
|
||||
data.set_hash_id(hash);
|
||||
data.set_its_aid(psid);
|
||||
data.set_generation_time(v2::convert_time64(now));
|
||||
if (psid == aid::CRL) {
|
||||
const auto id = rca.calculate_digest();
|
||||
if (!id) return std::nullopt;
|
||||
data.set_signer_identifier(*id);
|
||||
} else data.set_signer_identifier(rca);
|
||||
data.set_payload(mgmt);
|
||||
return finish_signed(backend, data, hash, key_signer(backend, rca_key), &rca);
|
||||
}
|
||||
|
||||
// the EtsiTs102941Data of a list message that verifies as signed by rca with the given psid
|
||||
std::optional<ByteBuffer> open_list(Backend& backend, const ByteBuffer& message, const Certificate& rca, ItsAid psid) {
|
||||
SecuredData data;
|
||||
if (!data.decode(message) || data.encode() != message || !data.is_signed() || data.protocol_version() != 3) return std::nullopt;
|
||||
if (data.its_aid() != psid || !data.generation_time() ||
|
||||
(data.hash_id() != HashAlgorithm::SHA256 && data.hash_id() != HashAlgorithm::SHA384)) return std::nullopt;
|
||||
if (!rca.valid_for_application(psid)) return std::nullopt;
|
||||
const auto* signed_data = data->content->choice.signedData;
|
||||
const auto& header = signed_data->tbsData->headerInfo;
|
||||
if (header.expiryTime || header.generationLocation || header.p2pcdLearningRequest ||
|
||||
header.missingCrlIdentifier || header.encryptionKey || header.inlineP2pcdRequest ||
|
||||
header.requestedCertificate || header.pduFunctionalType || header.contributedExtensions) return std::nullopt;
|
||||
const auto& signer = signed_data->signer;
|
||||
if (signer.present == Vanetza_Security_SignerIdentifier_PR_certificate) {
|
||||
if (signer.choice.certificate.list.count != 1) return std::nullopt;
|
||||
const ByteBuffer inline_cert = vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_EtsiTs103097Certificate,
|
||||
signer.choice.certificate.list.array[0]);
|
||||
if (inline_cert != rca.encode()) return std::nullopt;
|
||||
} else if (psid == aid::CRL && signer.present == Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||
const auto id = rca.calculate_digest();
|
||||
if (!id || signer.choice.digest.size != id->size() ||
|
||||
!std::equal(id->begin(), id->end(), signer.choice.digest.buf)) return std::nullopt;
|
||||
} else return std::nullopt;
|
||||
const auto signature = data.signature();
|
||||
const auto key = v3::get_public_key(*rca.content());
|
||||
if (!signature || !key) return std::nullopt;
|
||||
const auto digest = message_digest(backend, data.hash_id(), data.signing_payload(), &rca);
|
||||
try {
|
||||
if (!backend.verify_digest(*key, digest, *signature)) return std::nullopt;
|
||||
} catch (const std::exception&) {
|
||||
return std::nullopt;
|
||||
}
|
||||
auto payload = data.payload();
|
||||
const auto& packet = boost::get<CohesivePacket>(payload);
|
||||
const auto view = create_byte_view(packet, OsiLayer::Network, max_osi_layer());
|
||||
return ByteBuffer(view.begin(), view.end());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::optional<ByteBuffer> build_rca_ctl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
const TrustListEntries& entries, Time32 next_update, std::uint8_t ctl_sequence) {
|
||||
if (entries.dc.empty()) return std::nullopt;
|
||||
for (const auto& dc : entries.dc) if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||
auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||
ctl.version = 1; // clause 6.3.4: CtlFormat version 1
|
||||
ctl.nextUpdate = next_update;
|
||||
ctl.isFullCtl = 1;
|
||||
ctl.ctlSequence = ctl_sequence;
|
||||
const auto add = [&](Vanetza_Security_CtlEntry_PR kind) -> Vanetza_Security_CtlEntry_t& {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = kind;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
return command->choice.add;
|
||||
};
|
||||
for (const auto& ea : entries.ea) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_ea).choice.ea;
|
||||
if (!put_certificate(entry.eaCertificate, ea.certificate)) return std::nullopt;
|
||||
set_url(entry.aaAccessPoint, ea.access_point);
|
||||
if (!ea.its_access_point.empty()) {
|
||||
entry.itsAccessPoint = vanetza::asn1::allocate<Vanetza_Security_Url_t>();
|
||||
set_url(*entry.itsAccessPoint, ea.its_access_point);
|
||||
}
|
||||
}
|
||||
for (const auto& aa : entries.aa) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_aa).choice.aa;
|
||||
if (!put_certificate(entry.aaCertificate, aa.certificate)) return std::nullopt;
|
||||
set_url(entry.accessPoint, aa.access_point);
|
||||
}
|
||||
for (const auto& dc : entries.dc) {
|
||||
auto& entry = add(Vanetza_Security_CtlEntry_PR_dc).choice.dc;
|
||||
set_url(entry.url, dc.url);
|
||||
for (const auto& id : dc.certificates) {
|
||||
auto* item = vanetza::asn1::allocate<Vanetza_Security_HashedId8_t>();
|
||||
set_hashed_id8(*item, id);
|
||||
ASN_SEQUENCE_ADD(&entry.cert, item);
|
||||
}
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, rca, rca_key, aid::CTL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<RcaTrustListUpdate> build_rca_ctl_update(Backend& backend, Clock::time_point now,
|
||||
const Certificate& rca, const PrivateKey& key, const ByteBuffer& previous_full,
|
||||
const TrustListEntries& entries, Time32 next_update) {
|
||||
const auto previous = parse_rca_ctl(backend, previous_full, rca);
|
||||
if (!previous || !previous->full || next_update <= v2::convert_time32(now)) return std::nullopt;
|
||||
const auto sequence = static_cast<std::uint8_t>(previous->sequence + 1);
|
||||
const auto full = build_rca_ctl(backend, now, rca, key, entries, next_update, sequence);
|
||||
if (!full || !parse_rca_ctl(backend, *full, rca)) return std::nullopt;
|
||||
const auto old_payload = open_list(backend, previous_full, rca, aid::CTL);
|
||||
const auto new_payload = open_list(backend, *full, rca, aid::CTL);
|
||||
if (!old_payload || !new_payload) return std::nullopt;
|
||||
using Management = vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data>;
|
||||
Management old_list(asn_DEF_Vanetza_Security_EtsiTs102941Data), new_list(asn_DEF_Vanetza_Security_EtsiTs102941Data),
|
||||
delta(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!old_list.decode(*old_payload) || !new_list.decode(*new_payload)) return std::nullopt;
|
||||
delta->version = Vanetza_Security_Version_v1;
|
||||
delta->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca;
|
||||
auto& out = delta->content.choice.certificateTrustListRca;
|
||||
out.version = 1; out.nextUpdate = next_update; out.isFullCtl = 0; out.ctlSequence = sequence;
|
||||
// A certificate entry is identified by HashedId8. A DC entry is identified by URL.
|
||||
auto entry_key = [](const Vanetza_Security_CtlEntry_t& entry) -> ByteBuffer {
|
||||
Certificate certificate;
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_ea: certificate = Certificate(entry.choice.ea.eaCertificate); break;
|
||||
case Vanetza_Security_CtlEntry_PR_aa: certificate = Certificate(entry.choice.aa.aaCertificate); break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||
const auto url = get_url(entry.choice.dc.url);
|
||||
ByteBuffer result {1}; result.insert(result.end(), url.begin(), url.end()); return result;
|
||||
}
|
||||
default: return {};
|
||||
}
|
||||
const auto id = certificate.calculate_digest();
|
||||
if (!id) return {};
|
||||
ByteBuffer result {0}; result.insert(result.end(), id->begin(), id->end()); return result;
|
||||
};
|
||||
using Commands = std::map<ByteBuffer, const Vanetza_Security_CtlCommand_t*>;
|
||||
Commands old_entries, new_entries;
|
||||
auto collect = [&](const Vanetza_Security_CtlFormat_t& list, Commands& result) {
|
||||
for (int i = 0; i < list.ctlCommands.list.count; ++i) {
|
||||
const auto* command = list.ctlCommands.list.array[i];
|
||||
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return false;
|
||||
const auto id = entry_key(command->choice.add);
|
||||
if (id.empty() || !result.emplace(id, command).second) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
if (!collect(old_list->content.choice.certificateTrustListRca, old_entries) ||
|
||||
!collect(new_list->content.choice.certificateTrustListRca, new_entries)) return std::nullopt;
|
||||
for (const auto& item : new_entries) {
|
||||
const auto found = old_entries.find(item.first);
|
||||
if (found != old_entries.end() && vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &found->second->choice.add) ==
|
||||
vanetza::asn1::encode_oer(asn_DEF_Vanetza_Security_CtlEntry, &item.second->choice.add)) continue;
|
||||
auto* command = static_cast<Vanetza_Security_CtlCommand_t*>(vanetza::asn1::copy(asn_DEF_Vanetza_Security_CtlCommand, item.second));
|
||||
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||
}
|
||||
for (const auto& item : old_entries) {
|
||||
if (new_entries.count(item.first)) continue;
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
ASN_SEQUENCE_ADD(&out.ctlCommands, command);
|
||||
command->present = Vanetza_Security_CtlCommand_PR_delete;
|
||||
auto& removed = command->choice.Delete;
|
||||
if (item.first[0] == 0) {
|
||||
removed.present = Vanetza_Security_CtlDelete_PR_cert;
|
||||
HashedId8 id; std::copy(item.first.begin() + 1, item.first.end(), id.begin());
|
||||
set_hashed_id8(removed.choice.cert, id);
|
||||
} else {
|
||||
removed.present = Vanetza_Security_CtlDelete_PR_dc;
|
||||
set_url(removed.choice.dc, std::string(item.first.begin() + 1, item.first.end()));
|
||||
}
|
||||
}
|
||||
if (!delta.validate()) return std::nullopt;
|
||||
const auto signed_delta = sign_list(backend, now, rca, key, aid::CTL, delta.encode());
|
||||
if (!signed_delta || !parse_rca_ctl(backend, *signed_delta, rca)) return std::nullopt;
|
||||
return RcaTrustListUpdate {*full, *signed_delta, sequence};
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> build_crl(Backend& backend, Clock::time_point now, const Certificate& rca, const PrivateKey& rca_key,
|
||||
const std::vector<HashedId8>& revoked, Time32 this_update, Time32 next_update) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList;
|
||||
auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||
crl.version = 1;
|
||||
crl.thisUpdate = this_update;
|
||||
crl.nextUpdate = next_update;
|
||||
for (const auto& id : revoked) {
|
||||
auto* entry = vanetza::asn1::allocate<Vanetza_Security_CrlEntry_t>();
|
||||
set_hashed_id8(*entry, id);
|
||||
ASN_SEQUENCE_ADD(&crl.entries, entry);
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, rca, rca_key, aid::CRL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<RcaTrustList> parse_rca_ctl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||
if (v3::get_app_permissions(*rca.content(), aid::CTL) != ByteBuffer({1, 0x38})) return std::nullopt;
|
||||
const auto mgmt_bytes = open_list(backend, message, rca, aid::CTL);
|
||||
if (!mgmt_bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca) return std::nullopt;
|
||||
const auto& ctl = mgmt->content.choice.certificateTrustListRca;
|
||||
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||
RcaTrustList list;
|
||||
list.sequence = static_cast<std::uint8_t>(ctl.ctlSequence);
|
||||
list.next_update = static_cast<Time32>(ctl.nextUpdate);
|
||||
list.full = ctl.isFullCtl != 0;
|
||||
const auto rca_digest = rca.calculate_digest();
|
||||
if (!rca_digest) return std::nullopt;
|
||||
const auto issued_by_rca = [&](const Vanetza_Security_EtsiTs103097Certificate_t& raw, Certificate& out) {
|
||||
out = Certificate(raw);
|
||||
const auto issuer = out.issuer_digest();
|
||||
return issuer && *issuer == *rca_digest && out.is_ca_certificate() &&
|
||||
microbu_v2x::security::verify_certificate_signature(backend, out, &rca);
|
||||
};
|
||||
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||
const auto* command = ctl.ctlCommands.list.array[i];
|
||||
if (!command) return std::nullopt;
|
||||
if (command->present == Vanetza_Security_CtlCommand_PR_add) {
|
||||
const auto& entry = command->choice.add;
|
||||
Certificate certificate;
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_ea:
|
||||
if (!issued_by_rca(entry.choice.ea.eaCertificate, certificate)) return std::nullopt;
|
||||
list.ea.push_back(std::move(certificate));
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_aa:
|
||||
if (!issued_by_rca(entry.choice.aa.aaCertificate, certificate)) return std::nullopt;
|
||||
list.aa.push_back(std::move(certificate));
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc: {
|
||||
TrustListEntries::DistributionCentre dc;
|
||||
dc.url = get_url(entry.choice.dc.url);
|
||||
for (int k = 0; k < entry.choice.dc.cert.list.count; ++k) {
|
||||
const auto id = entry.choice.dc.cert.list.array[k] ? get_hashed_id8(*entry.choice.dc.cert.list.array[k]) : std::nullopt;
|
||||
if (!id) return std::nullopt;
|
||||
dc.certificates.push_back(*id);
|
||||
}
|
||||
if (dc.url.empty() || dc.certificates.empty()) return std::nullopt;
|
||||
list.dc.push_back(std::move(dc));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return std::nullopt; // clause 6.3.2: an RCA CTL carries no RCA or TLM entries
|
||||
}
|
||||
} else if (command->present == Vanetza_Security_CtlCommand_PR_delete) {
|
||||
if (list.full) return std::nullopt; // clause 6.3.4: a FullCtl has add commands only
|
||||
const auto& del = command->choice.Delete;
|
||||
if (del.present == Vanetza_Security_CtlDelete_PR_cert) {
|
||||
const auto id = get_hashed_id8(del.choice.cert);
|
||||
if (!id) return std::nullopt;
|
||||
list.deleted.push_back(*id);
|
||||
} else if (del.present == Vanetza_Security_CtlDelete_PR_dc) {
|
||||
list.deleted_dc.push_back(get_url(del.choice.dc));
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
} else {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
if (list.full && list.dc.empty()) return std::nullopt;
|
||||
return list;
|
||||
}
|
||||
|
||||
std::optional<ByteBuffer> build_tlm_ctl(Backend& backend, Clock::time_point now,
|
||||
const Certificate& tlm, const PrivateKey& key, const std::vector<Certificate>& roots,
|
||||
const std::vector<Certificate>& successors, Time32 next_update, std::uint8_t sequence) {
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm;
|
||||
auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||
ctl.version = 1; ctl.nextUpdate = next_update; ctl.isFullCtl = 1; ctl.ctlSequence = sequence;
|
||||
for (const auto& cert : roots) {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = Vanetza_Security_CtlEntry_PR_rca;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
if (!put_certificate(command->choice.add.choice.rca.selfsignedRootCa, cert.encode())) return std::nullopt;
|
||||
}
|
||||
for (const auto& cert : successors) {
|
||||
auto* command = vanetza::asn1::allocate<Vanetza_Security_CtlCommand_t>();
|
||||
command->present = Vanetza_Security_CtlCommand_PR_add;
|
||||
command->choice.add.present = Vanetza_Security_CtlEntry_PR_tlm;
|
||||
ASN_SEQUENCE_ADD(&ctl.ctlCommands, command);
|
||||
auto& entry = command->choice.add.choice.tlm;
|
||||
if (!put_certificate(entry.selfSignedTLMCertificate, cert.encode())) return std::nullopt;
|
||||
set_url(entry.accessPoint, "https://cpoc.example.test/L0");
|
||||
}
|
||||
if (!mgmt.validate()) return std::nullopt;
|
||||
return sign_list(backend, now, tlm, key, aid::CTL, mgmt.encode());
|
||||
}
|
||||
|
||||
std::optional<TlmTrustList> parse_tlm_ctl(Backend& backend, const ByteBuffer& message, const Certificate& tlm) {
|
||||
const auto permissions = v3::get_app_permissions(*tlm.content(), aid::CTL);
|
||||
if (permissions.size() != 2 || permissions[0] != 1 || permissions[1] != 0xc8 ||
|
||||
!microbu_v2x::security::verify_certificate_signature(backend, tlm, nullptr)) return std::nullopt;
|
||||
const auto bytes = open_list(backend, message, tlm, aid::CTL);
|
||||
if (!bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*bytes) || mgmt.encode() != *bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm) return std::nullopt;
|
||||
const auto& ctl = mgmt->content.choice.certificateTrustListTlm;
|
||||
if (ctl.version != 1 || ctl.ctlSequence < 0 || ctl.ctlSequence > 255) return std::nullopt;
|
||||
TlmTrustList result;
|
||||
result.sequence = ctl.ctlSequence; result.next_update = ctl.nextUpdate; result.full = ctl.isFullCtl;
|
||||
for (int i = 0; i < ctl.ctlCommands.list.count; ++i) {
|
||||
const auto* command = ctl.ctlCommands.list.array[i];
|
||||
// This client requests full lists. Never apply a delta without its complete base.
|
||||
if (!command || command->present != Vanetza_Security_CtlCommand_PR_add) return std::nullopt;
|
||||
const auto& entry = command->choice.add;
|
||||
if (entry.present == Vanetza_Security_CtlEntry_PR_rca) {
|
||||
Certificate cert(entry.choice.rca.selfsignedRootCa);
|
||||
if ((cert->issuer.present != Vanetza_Security_IssuerIdentifier_PR_self || !cert.is_ca_certificate()) || !microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||
result.roots.push_back(std::move(cert));
|
||||
} else if (entry.present == Vanetza_Security_CtlEntry_PR_tlm) {
|
||||
Certificate cert(entry.choice.tlm.selfSignedTLMCertificate);
|
||||
const auto p = v3::get_app_permissions(*cert.content(), aid::CTL);
|
||||
if (p.size() != 2 || p[0] != 1 || p[1] != 0xc8 ||
|
||||
!microbu_v2x::security::verify_certificate_signature(backend, cert, nullptr)) return std::nullopt;
|
||||
result.tlms.push_back(std::move(cert));
|
||||
} else if (entry.present != Vanetza_Security_CtlEntry_PR_dc) return std::nullopt;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::optional<RevocationList> parse_crl(Backend& backend, const ByteBuffer& message, const Certificate& rca) {
|
||||
if (v3::get_app_permissions(*rca.content(), aid::CRL) != ByteBuffer({1})) return std::nullopt;
|
||||
const auto mgmt_bytes = open_list(backend, message, rca, aid::CRL);
|
||||
if (!mgmt_bytes) return std::nullopt;
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
if (!mgmt.decode(*mgmt_bytes) || mgmt.encode() != *mgmt_bytes || mgmt->version != Vanetza_Security_Version_v1 ||
|
||||
mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList) return std::nullopt;
|
||||
const auto& crl = mgmt->content.choice.certificateRevocationList;
|
||||
if (crl.version != 1) return std::nullopt;
|
||||
RevocationList list;
|
||||
list.this_update = static_cast<Time32>(crl.thisUpdate);
|
||||
list.next_update = static_cast<Time32>(crl.nextUpdate);
|
||||
for (int i = 0; i < crl.entries.list.count; ++i) {
|
||||
const auto id = crl.entries.list.array[i] ? get_hashed_id8(*crl.entries.list.array[i]) : std::nullopt;
|
||||
if (!id) return std::nullopt;
|
||||
list.revoked.push_back(*id);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
std::size_t apply(const RcaTrustList& list, microbu_v2x::security::TrustConfiguration& trust) {
|
||||
std::size_t added = 0;
|
||||
for (const auto* entries : {&list.ea, &list.aa}) {
|
||||
for (const auto& certificate : *entries) {
|
||||
if (trust.add_authority(certificate) == Result::accepted) ++added;
|
||||
}
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
std::size_t apply(const RevocationList& list, const Certificate& rca, microbu_v2x::security::TrustConfiguration& trust) {
|
||||
const auto issuer = rca.calculate_digest();
|
||||
if (!issuer) return 0;
|
||||
trust.clear_revocations(*issuer);
|
||||
for (const auto& id : list.revoked) trust.revoke(*issuer, id);
|
||||
return list.revoked.size();
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::pki
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
#include <microbu_v2x/security_backend.hpp>
|
||||
#include "local_security.hpp"
|
||||
#include <sdkconfig.h>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace {
|
||||
template <class T>
|
||||
std::unique_ptr<T> required(std::unique_ptr<T> made, const char* what) {
|
||||
if (!made) throw std::runtime_error(what);
|
||||
return made;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<vanetza::security::Backend> make_security_backend() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return required(make_external_security_backend(), "security adapter returned no backend");
|
||||
#else
|
||||
return make_local_security_backend();
|
||||
#endif
|
||||
}
|
||||
|
||||
std::unique_ptr<security::SecurityModule> make_security_module() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_SE051 || CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return required(make_external_security_module(), "security adapter returned no security module");
|
||||
#else
|
||||
return make_local_security_module();
|
||||
#endif
|
||||
}
|
||||
|
||||
const char* security_module_name() {
|
||||
#if CONFIG_MICROBU_V2X_CRYPTO_SE051
|
||||
return "se051";
|
||||
#elif CONFIG_MICROBU_V2X_CRYPTO_V2X_HSM
|
||||
return "v2x-hsm";
|
||||
#else
|
||||
return "esp32-software";
|
||||
#endif
|
||||
}
|
||||
} // namespace microbu_v2x
|
||||
@@ -0,0 +1,205 @@
|
||||
#include <microbu_v2x/security_module.hpp>
|
||||
#include <microbu_v2x/ecc.hpp>
|
||||
#include <vanetza/security/v3/hash.hpp>
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using vanetza::security::KeyCompression;
|
||||
using vanetza::security::key_length;
|
||||
|
||||
namespace {
|
||||
constexpr std::uint8_t magic[4] = {'M', 'S', 'M', '1'};
|
||||
|
||||
void wipe(ByteBuffer& secret) {
|
||||
volatile std::uint8_t* target = secret.data();
|
||||
for (std::size_t n = secret.size(); n--;) *target++ = 0;
|
||||
secret.clear();
|
||||
}
|
||||
|
||||
std::uint8_t curve_code(KeyType type) {
|
||||
switch (type) {
|
||||
case KeyType::NistP256: return 1;
|
||||
case KeyType::BrainpoolP256r1: return 2;
|
||||
case KeyType::BrainpoolP384r1: return 3;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
KeyType curve_type(std::uint8_t code) {
|
||||
switch (code) {
|
||||
case 1: return KeyType::NistP256;
|
||||
case 2: return KeyType::BrainpoolP256r1;
|
||||
case 3: return KeyType::BrainpoolP384r1;
|
||||
default: return KeyType::Unspecified;
|
||||
}
|
||||
}
|
||||
|
||||
void put_u32(ByteBuffer& out, std::uint32_t value) {
|
||||
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||
}
|
||||
|
||||
std::uint32_t get_u32(const ByteBuffer& in, std::size_t at) {
|
||||
return std::uint32_t(in[at]) << 24 | std::uint32_t(in[at + 1]) << 16 | std::uint32_t(in[at + 2]) << 8 | in[at + 3];
|
||||
}
|
||||
|
||||
bool well_formed(const KeyPair& pair) {
|
||||
const auto type = pair.priv.type;
|
||||
const auto n = key_length(type);
|
||||
return curve_code(type) != 0 && pair.pub.type == type && pair.priv.key.size() == n &&
|
||||
pair.pub.compression == KeyCompression::NoCompression && pair.pub.x.size() == n && pair.pub.y.size() == n;
|
||||
}
|
||||
|
||||
/// The two halves belong together when a signature with the private key verifies with the public key.
|
||||
bool halves_match(vanetza::security::Backend& backend, const KeyPair& pair) {
|
||||
const ByteBuffer probe = backend.calculate_hash(vanetza::security::v3::specified_hash_algorithm(pair.priv.type),
|
||||
pair.pub.x);
|
||||
return backend.verify_digest(pair.pub, probe, backend.sign_digest(pair.priv, probe));
|
||||
}
|
||||
|
||||
ByteBuffer encode_keys(std::uint32_t next, const std::map<KeyId, KeyPair>& keys) {
|
||||
ByteBuffer out(std::begin(magic), std::end(magic));
|
||||
put_u32(out, next);
|
||||
for (const auto& [id, pair] : keys) {
|
||||
put_u32(out, id.value);
|
||||
out.push_back(curve_code(pair.priv.type));
|
||||
for (const auto* part : {&pair.priv.key, &pair.pub.x, &pair.pub.y}) out.insert(out.end(), part->begin(), part->end());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool decode_keys(const ByteBuffer& in, std::uint32_t& next, std::map<KeyId, KeyPair>& keys) {
|
||||
if (in.size() < 8 || !std::equal(std::begin(magic), std::end(magic), in.begin())) return false;
|
||||
next = get_u32(in, 4);
|
||||
for (std::size_t at = 8; at < in.size();) {
|
||||
if (in.size() - at < 5) return false;
|
||||
const KeyId id {get_u32(in, at)};
|
||||
const KeyType type = curve_type(in[at + 4]);
|
||||
at += 5;
|
||||
const auto n = key_length(type);
|
||||
if (!id || id.value >= next || type == KeyType::Unspecified || in.size() - at < 3 * n || keys.count(id)) return false;
|
||||
KeyPair pair;
|
||||
pair.priv.type = pair.pub.type = type;
|
||||
pair.pub.compression = KeyCompression::NoCompression;
|
||||
pair.priv.key.assign(in.begin() + at, in.begin() + at + n);
|
||||
pair.pub.x.assign(in.begin() + at + n, in.begin() + at + 2 * n);
|
||||
pair.pub.y.assign(in.begin() + at + 2 * n, in.begin() + at + 3 * n);
|
||||
at += 3 * n;
|
||||
keys.emplace(id, std::move(pair));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// x and y of a public key in uncompressed form, none when a compressed point is not on its curve.
|
||||
std::optional<PublicKey> uncompressed(const PublicKey& key) {
|
||||
if (key.compression == KeyCompression::NoCompression) return key;
|
||||
const bool odd = key.compression == KeyCompression::Y1;
|
||||
if (!odd && key.compression != KeyCompression::Y0) return std::nullopt;
|
||||
const auto point = ecc::decompress(key.type, key.x, odd);
|
||||
if (!point) return std::nullopt;
|
||||
PublicKey out;
|
||||
out.type = key.type;
|
||||
out.compression = KeyCompression::NoCompression;
|
||||
out.x = point->x;
|
||||
out.y = point->y;
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool same_public_key(const PublicKey& a, const PublicKey& b) {
|
||||
if (a.type != b.type || a.type == KeyType::Unspecified) return false;
|
||||
const auto ua = uncompressed(a), ub = uncompressed(b);
|
||||
return ua && ub && ua->x == ub->x && ua->y == ub->y;
|
||||
}
|
||||
|
||||
bool MemoryKeyStorage::load(ByteBuffer& out) {
|
||||
if (blob_.empty()) return false;
|
||||
out = blob_;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MemoryKeyStorage::save(const ByteBuffer& blob) {
|
||||
wipe(blob_);
|
||||
blob_ = blob;
|
||||
return true;
|
||||
}
|
||||
|
||||
SoftwareSecurityModule::SoftwareSecurityModule(vanetza::security::Backend& backend, KeyGenerator& generator,
|
||||
KeyStorage& storage) :
|
||||
backend_(backend), generator_(generator), storage_(storage) {
|
||||
ByteBuffer stored;
|
||||
if (!storage_.load(stored)) return;
|
||||
const bool decoded = decode_keys(stored, next_, keys_);
|
||||
wipe(stored);
|
||||
if (!decoded) throw std::runtime_error("stored security module keys do not decode");
|
||||
}
|
||||
|
||||
SoftwareSecurityModule::~SoftwareSecurityModule() {
|
||||
for (auto& entry : keys_) wipe(entry.second.priv.key);
|
||||
}
|
||||
|
||||
KeyId SoftwareSecurityModule::generate_key(KeyType type) {
|
||||
KeyPair pair = generator_.generate_key(type);
|
||||
if (!well_formed(pair)) throw std::runtime_error("key generation returned no usable key pair");
|
||||
return keep(std::move(pair));
|
||||
}
|
||||
|
||||
std::optional<KeyId> SoftwareSecurityModule::import_key(const KeyPair& pair) {
|
||||
const auto pub = uncompressed(pair.pub);
|
||||
if (!pub) return std::nullopt;
|
||||
KeyPair copy {pair.priv, *pub};
|
||||
try {
|
||||
if (!well_formed(copy) || !halves_match(backend_, copy)) {
|
||||
wipe(copy.priv.key);
|
||||
return std::nullopt;
|
||||
}
|
||||
} catch (const std::exception&) {
|
||||
wipe(copy.priv.key);
|
||||
return std::nullopt;
|
||||
}
|
||||
return keep(std::move(copy));
|
||||
}
|
||||
|
||||
std::optional<PublicKey> SoftwareSecurityModule::public_key(KeyId id) const {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) return std::nullopt;
|
||||
return found->second.pub;
|
||||
}
|
||||
|
||||
Signature SoftwareSecurityModule::sign_digest(KeyId id, const ByteBuffer& digest) {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) throw std::runtime_error("security module holds no such key");
|
||||
return backend_.sign_digest(found->second.priv, digest);
|
||||
}
|
||||
|
||||
bool SoftwareSecurityModule::destroy_key(KeyId id) {
|
||||
const auto found = keys_.find(id);
|
||||
if (found == keys_.end()) return false;
|
||||
wipe(found->second.priv.key);
|
||||
keys_.erase(found);
|
||||
persist();
|
||||
return true;
|
||||
}
|
||||
|
||||
KeyId SoftwareSecurityModule::keep(KeyPair pair) {
|
||||
if (next_ == 0) throw std::runtime_error("security module key identifiers exhausted");
|
||||
const KeyId id {next_++};
|
||||
keys_.emplace(id, std::move(pair));
|
||||
try {
|
||||
persist();
|
||||
} catch (...) {
|
||||
wipe(keys_[id].priv.key);
|
||||
keys_.erase(id);
|
||||
throw;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
void SoftwareSecurityModule::persist() {
|
||||
ByteBuffer blob = encode_keys(next_, keys_);
|
||||
const bool saved = storage_.save(blob);
|
||||
wipe(blob);
|
||||
if (!saved) throw std::runtime_error("security module keys not stored");
|
||||
}
|
||||
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,163 @@
|
||||
// Signer identifier and header selection per TS 103 097 V2.2.1 clause 7.1 and
|
||||
// TS 103 300-3 V2.3.1 clause 6.5.3. See the class comment in security.hpp.
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <vanetza/common/position_fix.hpp>
|
||||
#include <vanetza/security/peer_request_tracker.hpp>
|
||||
#include <vanetza/security/sign_service.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <chrono>
|
||||
#include <map>
|
||||
|
||||
namespace vanetza::security::v3 {
|
||||
// Defined in the upstream sign_header_policy.cpp translation unit (not declared in its header):
|
||||
// ThreeDLocation from a PositionFix (IEEE 1609.2 clause 6.3.10 encoding).
|
||||
asn1::ThreeDLocation build_location(const PositionFix& fix);
|
||||
}
|
||||
|
||||
namespace microbu_v2x::security {
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
|
||||
class Ts103097SignHeaderPolicy::Impl {
|
||||
public:
|
||||
const Runtime& runtime;
|
||||
PositionProvider& positioning;
|
||||
CertificatePool& pool;
|
||||
const TrustConfiguration& trust;
|
||||
// CAM, clause 7.1.1
|
||||
boost::optional<Clock::time_point> cam_last_certificate;
|
||||
bool cam_certificate_requested = false;
|
||||
PeerRequestTracker incoming_requests; // inlineP2pcdRequest digests received from peers
|
||||
PeerRequestTracker outgoing_requests; // certificates unknown to us
|
||||
// VAM, TS 103 300-3 clause 6.5.3
|
||||
boost::optional<Clock::time_point> vam_last_certificate;
|
||||
bool new_cam_signer = false;
|
||||
// generic profile: per ITS-AID
|
||||
std::map<ItsAid, Clock::time_point> generic_last_certificate;
|
||||
// the own certificate the timers above refer to
|
||||
boost::optional<HashedId8> signer_digest;
|
||||
|
||||
Impl(const Runtime& rt, PositionProvider& pp, CertificatePool& certificates, const TrustConfiguration& t) :
|
||||
runtime(rt), positioning(pp), pool(certificates), trust(t) {}
|
||||
|
||||
static constexpr std::chrono::milliseconds one_second {1000};
|
||||
static constexpr std::chrono::milliseconds half_second {500};
|
||||
|
||||
template<class Optional>
|
||||
static bool elapsed(const Optional& last, Clock::time_point now, std::chrono::milliseconds interval) {
|
||||
return !last || now - *last >= interval;
|
||||
}
|
||||
|
||||
void cam(const SignRequest&, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
const auto digest = at.calculate_digest();
|
||||
// Inline P2PCD request naming our own AT: include the certificate immediately.
|
||||
if (digest && incoming_requests.is_pending(truncate(*digest))) {
|
||||
cam_certificate_requested = true;
|
||||
incoming_requests.discard_request(truncate(*digest));
|
||||
}
|
||||
bool full_certificate = cam_certificate_requested || elapsed(cam_last_certificate, now, one_second);
|
||||
if (full_certificate) {
|
||||
message.set_signer_identifier(at);
|
||||
cam_last_certificate = now; // "the timer for the next inclusion ... shall be restarted"
|
||||
cam_certificate_requested = false;
|
||||
} else {
|
||||
message.set_signer_identifier(*digest);
|
||||
}
|
||||
// Digests of certificates unknown to this station (clause 7.1.1, inlineP2pcdRequest).
|
||||
message.set_inline_p2pcd_request(outgoing_requests.all());
|
||||
// requestedCertificate: a known CA certificate that a peer asked for, only while our
|
||||
// signer is the digest ("unless the component signer ... is of choice certificate").
|
||||
if (!full_certificate) {
|
||||
while (auto requested = incoming_requests.next_one()) {
|
||||
if (const auto* authority = trust.authority(*requested)) {
|
||||
message.set_requested_certificate(*authority);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void denm(v3::SecuredMessage& message, const Certificate& at) {
|
||||
message.set_signer_identifier(at);
|
||||
message.set_generation_location(v3::build_location(positioning.position_fix()));
|
||||
}
|
||||
|
||||
void vam(const SignRequest& request, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
const bool cluster = request.context_information == context::vam_cluster;
|
||||
bool attach;
|
||||
if (cluster) {
|
||||
attach = elapsed(vam_last_certificate, now, half_second);
|
||||
} else {
|
||||
attach = new_cam_signer || elapsed(vam_last_certificate, now, one_second);
|
||||
}
|
||||
if (attach) {
|
||||
message.set_signer_identifier(at);
|
||||
vam_last_certificate = now;
|
||||
new_cam_signer = false;
|
||||
} else if (auto digest = at.calculate_digest()) {
|
||||
message.set_signer_identifier(*digest);
|
||||
} else {
|
||||
message.set_signer_identifier(at);
|
||||
}
|
||||
}
|
||||
|
||||
void generic(ItsAid aid, v3::SecuredMessage& message, const Certificate& at, Clock::time_point now) {
|
||||
auto it = generic_last_certificate.find(aid);
|
||||
const auto digest = at.calculate_digest();
|
||||
if (it == generic_last_certificate.end() || now - it->second >= one_second || !digest) {
|
||||
message.set_signer_identifier(at);
|
||||
generic_last_certificate[aid] = now;
|
||||
} else {
|
||||
message.set_signer_identifier(*digest);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ts103097SignHeaderPolicy::Ts103097SignHeaderPolicy(const Runtime& rt, PositionProvider& pp, CertificatePool& pool,
|
||||
const TrustConfiguration& trust) :
|
||||
impl_(std::make_unique<Impl>(rt, pp, pool, trust)) {}
|
||||
Ts103097SignHeaderPolicy::~Ts103097SignHeaderPolicy() = default;
|
||||
|
||||
void Ts103097SignHeaderPolicy::prepare_header(const SignRequest& request, v3::SecuredMessage& message) {
|
||||
const auto now = impl_->runtime.now();
|
||||
// Clause 5.2: psid and generationTime always present.
|
||||
message.set_its_aid(request.its_aid);
|
||||
message.set_generation_time(v2::convert_time64(now));
|
||||
const Certificate& at = impl_->pool.own_certificate();
|
||||
// A different own certificate (a newly provisioned ticket, or a ticket switch outside
|
||||
// reset_after_identifier_change) has never been sent in full: restart the inclusion timers so the
|
||||
// first message signed with it carries the certificate. Receivers cannot resolve the digest of a
|
||||
// certificate they have not seen (2026-09-29: 9 digest-signed VAMs after re-provisioning).
|
||||
const auto signer = at.calculate_digest();
|
||||
if (signer != impl_->signer_digest) {
|
||||
reset_after_identifier_change();
|
||||
impl_->signer_digest = signer;
|
||||
}
|
||||
if (request.self_signed) {
|
||||
// TS 102 941 clause 6.2.3.2 inner enrolment structures are self-signed.
|
||||
message.set_signer_identifier_self();
|
||||
return;
|
||||
}
|
||||
switch (request.its_aid) {
|
||||
case aid::CA: impl_->cam(request, message, at, now); break;
|
||||
case aid::DEN: impl_->denm(message, at); break;
|
||||
case aid::VRU: impl_->vam(request, message, at, now); break;
|
||||
default: impl_->generic(request.its_aid, message, at, now); break;
|
||||
}
|
||||
}
|
||||
|
||||
void Ts103097SignHeaderPolicy::request_unrecognized_certificate(HashedId8 id) {
|
||||
impl_->outgoing_requests.add_request(truncate(id));
|
||||
}
|
||||
void Ts103097SignHeaderPolicy::request_certificate() { impl_->cam_certificate_requested = true; }
|
||||
void Ts103097SignHeaderPolicy::enqueue_p2p_request(HashedId3 id) { impl_->incoming_requests.add_request(id); }
|
||||
void Ts103097SignHeaderPolicy::discard_p2p_request(HashedId3 id) { impl_->incoming_requests.discard_request(id); }
|
||||
void Ts103097SignHeaderPolicy::report_new_cam_signer() { impl_->new_cam_signer = true; }
|
||||
void Ts103097SignHeaderPolicy::reset_after_identifier_change() {
|
||||
impl_->cam_last_certificate = boost::none;
|
||||
impl_->cam_certificate_requested = false;
|
||||
impl_->vam_last_certificate = boost::none;
|
||||
impl_->generic_last_certificate.clear();
|
||||
}
|
||||
} // namespace microbu_v2x::security
|
||||
@@ -0,0 +1,344 @@
|
||||
#include <microbu_v2x/stack.hpp>
|
||||
#if V2X_SECURITY
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#endif
|
||||
#include <vanetza/access/access_category.hpp>
|
||||
#include <vanetza/btp/header.hpp>
|
||||
#include <vanetza/btp/header_conversion.hpp>
|
||||
#include <vanetza/dcc/interface.hpp>
|
||||
#include <vanetza/dcc/mapping.hpp>
|
||||
#include <vanetza/dcc/data_request.hpp>
|
||||
#include <vanetza/geonet/dcc_information_sharing.hpp>
|
||||
#include <vanetza/geonet/router.hpp>
|
||||
#include <vanetza/geonet/transport_interface.hpp>
|
||||
#include <vanetza/net/packet.hpp>
|
||||
#include <vanetza/net/packet_variant.hpp>
|
||||
#include <vanetza/common/byte_view.hpp>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace microbu_v2x {
|
||||
namespace gn = vanetza::geonet;
|
||||
using namespace vanetza;
|
||||
|
||||
StackConfig::StackConfig() {
|
||||
// Explicit ITS-G5 subset. Defaults are upstream MIB, not R2 certification.
|
||||
mib.itsGnIfType = gn::InterfaceType::ITS_G5;
|
||||
mib.itsGnSnDecapResultHandling = gn::SecurityDecapHandling::Strict;
|
||||
mib.itsGnSecurity = true;
|
||||
// A GBC received again (CBF relies on duplicates, TS 103 836-4-1 V2.2.1 clause 10.3.11.3 step 3 and Annex F.3)
|
||||
// is handled by the forwarding algorithm and never passed up a second time; the upstream default (0) passes
|
||||
// every copy up. Found by TC_GEONW_PON_GBC_AREA_ALL_BO_08.
|
||||
mib.vanetzaGbcMemoryCapacity = 128;
|
||||
}
|
||||
|
||||
class Stack::Impl : public dcc::RequestInterface, public gn::TransportInterface {
|
||||
public:
|
||||
StackConfig cfg;
|
||||
ManualRuntime& runtime;
|
||||
Access& access;
|
||||
vanetza::security::SecurityEntity* security;
|
||||
security::IdChangeService* id_change;
|
||||
gn::Router router;
|
||||
// TS 103 836-4-2 Release-2 DCC_NET. Declared after router: it holds a
|
||||
// reference to router's location table, which must already be constructed.
|
||||
gn::DccInformationSharing dcc_information_sharing;
|
||||
std::optional<dcc::ChannelLoad> global_cbr;
|
||||
Receive receive;
|
||||
ReceiveGn receive_gn;
|
||||
Report report;
|
||||
bool position_valid = false;
|
||||
bool change_pending = false;
|
||||
std::optional<security::SubscriptionHandle> subscription;
|
||||
|
||||
Impl(StackConfig c, ManualRuntime& rt, Access& al, vanetza::security::SecurityEntity* sec,
|
||||
security::IdChangeService* ids) :
|
||||
cfg(std::move(c)), runtime(rt), access(al), security(sec), id_change(ids), router(rt, cfg.mib),
|
||||
// TS 103 836-4-2 clause 5.3: "all ITS-S shall start with a random time offset" so that
|
||||
// stations do not all recompute CBR_G in lockstep. No RNG dependency (host and ESP-IDF
|
||||
// newlib without configured hardware entropy behave differently): the station's own
|
||||
// startup time already differs from its neighbours', so its microsecond-level position
|
||||
// within the 100 ms trigger interval (itsGNCBRGTriggerInterval) serves as that offset.
|
||||
dcc_information_sharing(rt, router.get_location_table(), dcc::ChannelLoad(0.62),
|
||||
UnitInterval(double(rt.now().time_since_epoch().count() % 100000) / 100000.0)) {
|
||||
router.set_access_interface(this);
|
||||
router.set_security_entity(sec);
|
||||
router.set_dcc_field_generator(&dcc_information_sharing);
|
||||
dcc_information_sharing.on_global_cbr_update = [this](const gn::CbrAggregator& agg) {
|
||||
global_cbr = agg.get_global_cbr();
|
||||
};
|
||||
// MIB.itsGnLocalGnAddr is otherwise inert: Router::update_position only
|
||||
// touches timestamp/latitude/longitude/speed/heading, never the address,
|
||||
// and the router's own m_local_position_vector.gn_addr starts at
|
||||
// vanetza::geonet::Address()'s default (all-zero mid, not manually
|
||||
// configured) until this is called. Every GN packet's source position
|
||||
// vector carries that address, so leaving this out silently transmits
|
||||
// the wrong (default) station address regardless of what the caller
|
||||
// configured -- undetected by BTP's official ATS, which never checks
|
||||
// the source GN address, but not so for GeoNetworking's.
|
||||
router.set_address(cfg.mib.itsGnLocalGnAddr);
|
||||
router.set_transport_handler(gn::UpperProtocol::BTP_A, this);
|
||||
router.set_transport_handler(gn::UpperProtocol::BTP_B, this);
|
||||
router.set_transport_handler(gn::UpperProtocol::Unknown, this);
|
||||
// TS 103 836-4-1 V2.2.1 clause 10.2.1.4: the GN core of an anonymously addressed
|
||||
// station subscribes to the identifier-change service at startup (SN-IDCHANGE-SUBSCRIBE)
|
||||
// and derives its MID from the identifier of the security entity (TS 102 940 clause 6.5).
|
||||
if (cfg.mib.itsGnLocalAddrConfMethod == gn::AddrConfMethod::Anonymous && id_change) {
|
||||
subscription = id_change->subscribe(
|
||||
[this](security::IdChangeCommand command, const security::Identifier& id, const ByteBuffer&,
|
||||
std::shared_ptr<security::IdChangeResponder> responder) { on_id_change(command, id, responder); });
|
||||
const auto current = id_change->current_identifier();
|
||||
if (current != security::Identifier {}) apply_identifier(current);
|
||||
}
|
||||
}
|
||||
|
||||
~Impl() override {
|
||||
// clause 10.2.1.4: unsubscribe when the router shuts down (SN-IDCHANGE-UNSUBSCRIBE)
|
||||
if (subscription && id_change) id_change->unsubscribe(*subscription);
|
||||
}
|
||||
|
||||
// TS 102 940 V2.1.1 clause 6.5: the 48 least significant bits of the HashedId8 become the
|
||||
// MAC-layer / GN MID identifier. A source address must be individual (IEEE Std 802 clause
|
||||
// 8.2.2, I/G bit 0) and this one is not OUI-assigned (U/L bit 1).
|
||||
void apply_identifier(const security::Identifier& id) {
|
||||
MacAddress mid;
|
||||
std::copy(id.begin() + 2, id.end(), mid.octets.begin());
|
||||
mid.octets[0] = (mid.octets[0] & 0xfe) | 0x02;
|
||||
cfg.mib.itsGnLocalGnAddr.mid(mid);
|
||||
router.set_address(cfg.mib.itsGnLocalGnAddr);
|
||||
}
|
||||
|
||||
// TS 102 723-8 V1.1.1 clauses 6.3.1.2 and 6.3.1.3: hook function of the GN core.
|
||||
void on_id_change(security::IdChangeCommand command, const security::Identifier& id,
|
||||
const std::shared_ptr<security::IdChangeResponder>& responder) {
|
||||
switch (command) {
|
||||
case security::IdChangeCommand::PREPARE:
|
||||
change_pending = true;
|
||||
router.flush_forwarding_buffers(); // caches shall be flushed
|
||||
if (responder) responder->respond(true);
|
||||
break;
|
||||
case security::IdChangeCommand::COMMIT:
|
||||
apply_identifier(id);
|
||||
change_pending = false;
|
||||
if (responder) responder->respond(true);
|
||||
break;
|
||||
case security::IdChangeCommand::ABORT:
|
||||
change_pending = false;
|
||||
break;
|
||||
case security::IdChangeCommand::DEREG:
|
||||
change_pending = false;
|
||||
subscription.reset();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void request(const dcc::DataRequest& req, std::unique_ptr<ChunkPacket> packet) override {
|
||||
auto out = cfg.radio_parameters;
|
||||
out.source = req.source;
|
||||
out.destination = req.destination;
|
||||
// DCC profile to IEEE 802.1D priority: upstream TS 102 687 mapping.
|
||||
// DCC enforcement belongs to the injected Access adapter; no fake CBR.
|
||||
out.priority = access::user_priority(dcc::map_profile_onto_ac(req.dcc_profile));
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Network, max_osi_layer());
|
||||
out.data.assign(view.begin(), view.end());
|
||||
auto result = validate(out, cfg.maximum_gnpdu);
|
||||
if (result == Result::accepted) result = access.request(std::move(out));
|
||||
if (report) report(result);
|
||||
}
|
||||
|
||||
void indicate(const gn::DataIndication& ind, std::unique_ptr<UpPacket> packet) override {
|
||||
if (ind.upper_protocol == gn::UpperProtocol::Unknown) {
|
||||
// GN-DATA.indication for a packet with no registered upper protocol
|
||||
// (Common Header next_header "Any"): the raw SDU, no BTP header to strip.
|
||||
if (!receive_gn) return;
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
||||
receive_gn(GnIndication {ind, ByteBuffer(view.begin(), view.end())});
|
||||
return;
|
||||
}
|
||||
// validate length BEFORE parsing; upstream header parsing
|
||||
// alone does not reject a short BTP PDU. Never read an incomplete port.
|
||||
const auto view = create_byte_view(*packet, OsiLayer::Transport, max_osi_layer());
|
||||
if (view.size() < 4 || !receive) return;
|
||||
BtpIndication out {};
|
||||
out.type = ind.upper_protocol == gn::UpperProtocol::BTP_A ? BtpType::a : BtpType::b;
|
||||
out.destination_port = (std::uint16_t(view[0]) << 8) | view[1];
|
||||
const std::uint16_t second = (std::uint16_t(view[2]) << 8) | view[3];
|
||||
if (out.type == BtpType::a) out.source_port = second;
|
||||
else out.destination_port_info = second;
|
||||
out.gn = ind;
|
||||
// SN-DECAP.confirm -> NF-SAP: TS 102 723-8 V2.0.0 clause 5 /
|
||||
// V1.1.1 Table 27 and TS 103 836-5-1 Annex A.3.
|
||||
if (ind.certificate_id)
|
||||
out.certificate_id = ByteBuffer(ind.certificate_id->begin(), ind.certificate_id->end());
|
||||
out.data.assign(view.begin() + 4, view.end());
|
||||
receive(std::move(out));
|
||||
}
|
||||
};
|
||||
|
||||
Stack::Stack(StackConfig config, ManualRuntime& runtime, Access& access,
|
||||
vanetza::security::SecurityEntity* security, security::IdChangeService* id_change) {
|
||||
if (config.mib.itsGnMaxSduSize < 4 || config.mib.itsGnMaxSduSize > 65535 ||
|
||||
config.maximum_gnpdu < config.mib.itsGnMaxSduSize ||
|
||||
config.mib.itsGnIfType != gn::InterfaceType::ITS_G5 ||
|
||||
config.mib.itsGnSnDecapResultHandling != gn::SecurityDecapHandling::Strict)
|
||||
throw std::invalid_argument("Invalid ITS-G5 stack configuration");
|
||||
#if V2X_SECURITY
|
||||
if (!id_change) {
|
||||
if (auto* own = dynamic_cast<security::SecurityEntity*>(security)) id_change = &own->id_change();
|
||||
}
|
||||
#endif
|
||||
impl_ = std::make_unique<Impl>(std::move(config), runtime, access, security, id_change);
|
||||
}
|
||||
Stack::~Stack() = default;
|
||||
const StackConfig& Stack::config() const { return impl_->cfg; }
|
||||
security::IdChangeService* Stack::id_change() { return impl_->subscription ? impl_->id_change : nullptr; }
|
||||
vanetza::security::SecurityEntity* Stack::security_entity() { return impl_->security; }
|
||||
bool Stack::identity_change_pending() const { return impl_->change_pending; }
|
||||
// The address the router uses now: DAD (clause 10.2.1.5) and identifier changes move it away from the
|
||||
// configured MIB value, and the station must report what it actually transmits.
|
||||
const gn::Address& Stack::address() const { return impl_->router.get_local_position_vector().gn_addr; }
|
||||
Result Stack::set_address(const gn::Address& address) {
|
||||
if (impl_->cfg.mib.itsGnLocalAddrConfMethod != gn::AddrConfMethod::Managed) return Result::unsupported;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
impl_->cfg.mib.itsGnLocalGnAddr = address;
|
||||
impl_->router.set_address(address);
|
||||
return Result::accepted;
|
||||
}
|
||||
void Stack::on_receive(Receive receive) { impl_->receive = std::move(receive); }
|
||||
void Stack::on_receive_gn(ReceiveGn receive) { impl_->receive_gn = std::move(receive); }
|
||||
void Stack::on_access_result(Report report) { impl_->report = std::move(report); }
|
||||
void Stack::on_packet_drop(std::function<void(const std::string&)> report) {
|
||||
impl_->router.packet_dropped = [report = std::move(report)](gn::Router::PacketDropReason reason) {
|
||||
if (report) report(gn::stringify(reason));
|
||||
};
|
||||
}
|
||||
void Stack::report_local_channel_load(dcc::ChannelLoad load) { impl_->dcc_information_sharing.update_local_cbr(load); }
|
||||
void Stack::report_tx_power(unsigned dbm) { impl_->dcc_information_sharing.set_tx_power(dbm); }
|
||||
std::optional<dcc::ChannelLoad> Stack::global_channel_busy_ratio() const { return impl_->global_cbr; }
|
||||
|
||||
Result Stack::advance(Clock::time_point time) {
|
||||
if (time < impl_->runtime.now()) return Result::time_regression;
|
||||
impl_->runtime.trigger(time);
|
||||
return Result::accepted;
|
||||
}
|
||||
Result Stack::update_position(const PositionFix& fix) {
|
||||
if (!has_horizontal_position(fix) || fix.latitude.value() < -90 || fix.latitude.value() > 90 ||
|
||||
fix.longitude.value() < -180 || fix.longitude.value() > 180 ||
|
||||
fix.timestamp > impl_->runtime.now()) return Result::invalid_argument;
|
||||
impl_->router.update_position(fix);
|
||||
impl_->position_valid = true;
|
||||
return Result::accepted;
|
||||
}
|
||||
Result Stack::indicate(AlDataIndication ind) {
|
||||
if (ind.data.empty() || ind.data.size() > impl_->cfg.maximum_gnpdu) return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<UpPacket>(CohesivePacket(std::move(ind.data), OsiLayer::Network));
|
||||
impl_->router.indicate(std::move(packet), ind.source, ind.destination);
|
||||
return Result::accepted; // submitted for processing, NOT a receive verdict
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
Result Stack::request(BtpRequest req) {
|
||||
// mutually exclusive BTP header variants and conditional fields.
|
||||
if ((req.type != BtpType::a && req.type != BtpType::b) ||
|
||||
(req.type == BtpType::a && (!req.source_port || req.destination_port_info)) ||
|
||||
(req.type == BtpType::b && req.source_port)) return Result::invalid_argument;
|
||||
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize - 4u) return Result::resource_limit;
|
||||
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
|
||||
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
|
||||
if (req.security_profile && *req.security_profile != impl_->cfg.security_profile) return Result::unsupported;
|
||||
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
if (!impl_->position_valid) return Result::rejected;
|
||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<DownPacket>();
|
||||
// TS 103 836-5-1 clauses 7 and 8.2: both headers occupy four octets.
|
||||
if (req.type == BtpType::a) {
|
||||
btp::HeaderA header { host_cast(req.destination_port), host_cast(*req.source_port) };
|
||||
(*packet)[OsiLayer::Transport] = header;
|
||||
} else {
|
||||
btp::HeaderB header { host_cast(req.destination_port), host_cast(req.destination_port_info.value_or(0)) };
|
||||
(*packet)[OsiLayer::Transport] = header;
|
||||
}
|
||||
(*packet)[OsiLayer::Application] = std::move(req.data);
|
||||
auto apply = [&](gn::DataRequest& gn_req) {
|
||||
gn_req.upper_protocol = req.type == BtpType::a ? gn::UpperProtocol::BTP_A : gn::UpperProtocol::BTP_B;
|
||||
gn_req.communication_profile = req.communication_profile;
|
||||
gn_req.its_aid = req.its_aid;
|
||||
gn_req.permissions = std::move(req.permissions);
|
||||
gn_req.security_context = std::move(req.security_context);
|
||||
gn_req.traffic_class = req.traffic_class;
|
||||
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
|
||||
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
|
||||
if (req.repetition) gn_req.repetition = *req.repetition;
|
||||
};
|
||||
gn::DataConfirm confirm;
|
||||
if (req.transport == gn::TransportType::SHB) {
|
||||
gn::ShbDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
} else {
|
||||
gn::GbcDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
gn_req.destination = boost::get<gn::Area>(req.destination);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
}
|
||||
return confirm.accepted() ? Result::accepted : Result::rejected;
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
Result Stack::request(GnRequest req) {
|
||||
if (req.data.size() > impl_->cfg.mib.itsGnMaxSduSize) return Result::resource_limit;
|
||||
if (req.communication_profile != gn::CommunicationProfile::ITS_G5 &&
|
||||
req.communication_profile != gn::CommunicationProfile::Unspecified) return Result::unsupported;
|
||||
if (impl_->cfg.mib.itsGnSecurity && !impl_->security) return Result::security_unavailable;
|
||||
if (impl_->change_pending) return Result::identity_change_pending;
|
||||
if (!impl_->position_valid) return Result::rejected;
|
||||
if (req.maximum_hop_limit && (*req.maximum_hop_limit == 0 || *req.maximum_hop_limit > 255))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport != gn::TransportType::SHB && req.transport != gn::TransportType::GBC)
|
||||
return Result::unsupported; // Upstream GUC, GAC, TSB are unimplemented.
|
||||
if (req.transport == gn::TransportType::GBC && !boost::get<gn::Area>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
if (req.transport == gn::TransportType::SHB && !boost::get<std::nullptr_t>(&req.destination))
|
||||
return Result::invalid_argument;
|
||||
try {
|
||||
auto packet = std::make_unique<DownPacket>();
|
||||
(*packet)[OsiLayer::Application] = std::move(req.data);
|
||||
auto apply = [&](gn::DataRequest& gn_req) {
|
||||
gn_req.upper_protocol = gn::UpperProtocol::Unknown;
|
||||
gn_req.communication_profile = req.communication_profile;
|
||||
gn_req.its_aid = req.its_aid;
|
||||
gn_req.permissions = std::move(req.permissions);
|
||||
gn_req.security_context = std::move(req.security_context);
|
||||
gn_req.traffic_class = req.traffic_class;
|
||||
if (req.maximum_lifetime) gn_req.maximum_lifetime = *req.maximum_lifetime;
|
||||
if (req.maximum_hop_limit) gn_req.max_hop_limit = *req.maximum_hop_limit;
|
||||
if (req.repetition) gn_req.repetition = *req.repetition;
|
||||
};
|
||||
gn::DataConfirm confirm;
|
||||
if (req.transport == gn::TransportType::SHB) {
|
||||
gn::ShbDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
} else {
|
||||
gn::GbcDataRequest gn_req(impl_->cfg.mib);
|
||||
apply(gn_req);
|
||||
gn_req.destination = boost::get<gn::Area>(req.destination);
|
||||
confirm = impl_->router.request(gn_req, std::move(packet));
|
||||
}
|
||||
return confirm.accepted() ? Result::accepted : Result::rejected;
|
||||
} catch (const std::bad_alloc&) { return Result::resource_limit; }
|
||||
catch (const std::exception&) { return Result::rejected; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
#include <microbu_v2x/security.hpp>
|
||||
#include <microbu_v2x/trust_update.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/secured_message.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
namespace microbu_v2x::pki {
|
||||
namespace {
|
||||
bool same_or_newer(unsigned old_seq, unsigned next_seq, const ByteBuffer& old, const ByteBuffer& next) {
|
||||
if (next_seq == old_seq) return old == next;
|
||||
auto generation_time = [](const ByteBuffer& bytes) {
|
||||
vanetza::security::v3::SecuredMessage message;
|
||||
if (!message.decode(bytes)) return decltype(message.generation_time()) {};
|
||||
return message.generation_time();
|
||||
};
|
||||
const auto old_time = generation_time(old);
|
||||
const auto next_time = generation_time(next);
|
||||
if (!old_time || !next_time || *next_time < *old_time) return false;
|
||||
// TS 102 941 clause 6.3.4 wraps ctlSequence at 255. Authenticated time
|
||||
// distinguishes a wrapped full list from replay of an earlier cycle.
|
||||
return next_seq > old_seq || *next_time > *old_time;
|
||||
}
|
||||
bool decode_certificate(const ByteBuffer& bytes, Certificate& cert) {
|
||||
return cert.decode(bytes) && cert.encode() == bytes;
|
||||
}
|
||||
}
|
||||
ByteBuffer encode_snapshot(const TrustSnapshot& snapshot) {
|
||||
ByteBuffer bytes {'T', 'S', 'N', 1};
|
||||
for (const auto* blob : {&snapshot.tlm, &snapshot.rca, &snapshot.ectl, &snapshot.ctl, &snapshot.crl}) {
|
||||
if (blob->empty() || blob->size() > 32768) return {};
|
||||
bytes.push_back(blob->size() >> 8); bytes.push_back(blob->size() & 255);
|
||||
bytes.insert(bytes.end(), blob->begin(), blob->end());
|
||||
}
|
||||
for (int shift = 24; shift >= 0; shift -= 8) bytes.push_back(snapshot.deadline >> shift);
|
||||
return bytes.size() <= 60000 ? bytes : ByteBuffer {};
|
||||
}
|
||||
bool decode_snapshot(const ByteBuffer& bytes, TrustSnapshot& out) {
|
||||
if (bytes.size() < 8 || bytes.size() > 60000 || !std::equal(bytes.begin(), bytes.begin() + 4, ByteBuffer {'T','S','N',1}.begin())) return false;
|
||||
TrustSnapshot parsed;
|
||||
std::size_t pos = 4;
|
||||
for (auto* blob : {&parsed.tlm, &parsed.rca, &parsed.ectl, &parsed.ctl, &parsed.crl}) {
|
||||
if (pos + 2 > bytes.size()) return false;
|
||||
const std::size_t length = (bytes[pos] << 8) | bytes[pos + 1]; pos += 2;
|
||||
if (!length || length > 32768 || length > bytes.size() - pos) return false;
|
||||
blob->assign(bytes.begin() + pos, bytes.begin() + pos + length); pos += length;
|
||||
}
|
||||
if (pos + 4 != bytes.size()) return false;
|
||||
for (int i = 0; i < 4; ++i) parsed.deadline = (parsed.deadline << 8) | bytes[pos++];
|
||||
out = std::move(parsed);
|
||||
return true;
|
||||
}
|
||||
bool validate_update(vanetza::security::Backend& backend, vanetza::Clock::time_point now,
|
||||
const ByteBuffer& pinned_tlm, const TrustSnapshot* previous,
|
||||
const TrustSnapshot& proposed, TrustSnapshot& accepted) {
|
||||
Certificate tlm, rca;
|
||||
if (!decode_certificate(proposed.tlm, tlm) || !decode_certificate(proposed.rca, rca) ||
|
||||
!tlm.valid_at_timepoint(now) || !rca.valid_at_timepoint(now)) return false;
|
||||
const auto time = vanetza::security::v2::convert_time32(now);
|
||||
for (const auto* wire : {&proposed.ectl, &proposed.ctl, &proposed.crl}) {
|
||||
vanetza::security::v3::SecuredMessage msg;
|
||||
if (!msg.decode(*wire) || !msg.generation_time() ||
|
||||
*msg.generation_time() > vanetza::security::v2::convert_time64(now)) return false;
|
||||
}
|
||||
// TS 102 941 clause 6.3.6: authenticate every object, releasing decoded
|
||||
// certificate graphs between lists so live reception can continue during updates.
|
||||
std::optional<unsigned> old_ectl_sequence, old_ctl_sequence;
|
||||
std::optional<RevocationList> old_crl;
|
||||
std::vector<std::pair<HashedId8, Time32>> old_authorities;
|
||||
if (previous) {
|
||||
{
|
||||
Certificate old_tlm;
|
||||
if (!decode_certificate(previous->tlm, old_tlm)) return false;
|
||||
const auto old_ectl = parse_tlm_ctl(backend, previous->ectl, old_tlm);
|
||||
if (!old_ectl) return false;
|
||||
old_ectl_sequence = old_ectl->sequence;
|
||||
if (proposed.tlm != previous->tlm &&
|
||||
std::none_of(old_ectl->tlms.begin(), old_ectl->tlms.end(),
|
||||
[&](const auto& c) { return c.encode() == proposed.tlm; })) return false;
|
||||
}
|
||||
Certificate old_rca;
|
||||
if (!decode_certificate(previous->rca, old_rca)) return false;
|
||||
{
|
||||
const auto old_ctl = parse_rca_ctl(backend, previous->ctl, old_rca);
|
||||
if (!old_ctl) return false;
|
||||
old_ctl_sequence = old_ctl->sequence;
|
||||
for (const auto* list : {&old_ctl->ea, &old_ctl->aa}) for (const auto& cert : *list) {
|
||||
const auto id = cert.calculate_digest();
|
||||
if (!id) return false;
|
||||
old_authorities.emplace_back(*id, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||
}
|
||||
}
|
||||
old_crl = parse_crl(backend, previous->crl, old_rca);
|
||||
if (!old_crl) return false;
|
||||
} else if (pinned_tlm.empty() || proposed.tlm != pinned_tlm) return false;
|
||||
Time32 deadline = std::min(microbu_v2x::security::validity_bounds(tlm).end_validity,
|
||||
microbu_v2x::security::validity_bounds(rca).end_validity);
|
||||
{
|
||||
const auto ectl = parse_tlm_ctl(backend, proposed.ectl, tlm);
|
||||
if (!ectl || !ectl->full || ectl->next_update <= time ||
|
||||
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||
[&](const auto& c) { return c.encode() == proposed.rca; })) return false;
|
||||
deadline = std::min(deadline, ectl->next_update);
|
||||
if (previous && proposed.tlm == previous->tlm &&
|
||||
!same_or_newer(*old_ectl_sequence, ectl->sequence, previous->ectl, proposed.ectl)) return false;
|
||||
}
|
||||
{
|
||||
const auto ctl = parse_rca_ctl(backend, proposed.ctl, rca);
|
||||
if (!ctl || !ctl->full || ctl->next_update <= time) return false;
|
||||
deadline = std::min(deadline, ctl->next_update);
|
||||
if (previous && proposed.rca == previous->rca &&
|
||||
!same_or_newer(*old_ctl_sequence, ctl->sequence, previous->ctl, proposed.ctl)) return false;
|
||||
for (const auto* list : {&ctl->ea, &ctl->aa}) for (const auto& cert : *list) {
|
||||
if (!cert.valid_at_timepoint(now)) return false;
|
||||
deadline = std::min(deadline, microbu_v2x::security::validity_bounds(cert).end_validity);
|
||||
}
|
||||
}
|
||||
const auto crl = parse_crl(backend, proposed.crl, rca);
|
||||
if (!crl || crl->next_update <= time || crl->this_update > time ||
|
||||
crl->next_update <= crl->this_update) return false;
|
||||
deadline = std::min(deadline, crl->next_update);
|
||||
if (previous && proposed.rca == previous->rca) {
|
||||
if (crl->this_update < old_crl->this_update ||
|
||||
(crl->this_update == old_crl->this_update && proposed.crl != previous->crl)) return false;
|
||||
// Revocation is permanent until the known certificate expires.
|
||||
// Unknown removed entries cannot be proven expired and fail closed.
|
||||
for (const auto& id : old_crl->revoked) {
|
||||
if (std::find(crl->revoked.begin(), crl->revoked.end(), id) != crl->revoked.end()) continue;
|
||||
const auto known = std::find_if(old_authorities.begin(), old_authorities.end(),
|
||||
[&](const auto& item) { return item.first == id; });
|
||||
if (known == old_authorities.end() || known->second > time) return false;
|
||||
}
|
||||
}
|
||||
accepted = proposed; accepted.deadline = deadline;
|
||||
return true;
|
||||
}
|
||||
bool snapshot_credentials(vanetza::security::Backend& backend, const TrustSnapshot& state,
|
||||
microbu_v2x::security::StoredCredentials& credentials, microbu_v2x::security::TrustConfiguration* trust) {
|
||||
Certificate tlm, rca;
|
||||
if (!decode_certificate(state.tlm, tlm) || !decode_certificate(state.rca, rca)) return false;
|
||||
const auto crl = parse_crl(backend, state.crl, rca);
|
||||
if (!crl) return false;
|
||||
// TS 102 941 clauses 6.3.1 and 6.3.6: ECTL anchors apply to reception.
|
||||
// The selected home RCA determines credential management and its CTL.
|
||||
std::vector<ByteBuffer> roots, authorities;
|
||||
{
|
||||
const auto ectl = parse_tlm_ctl(backend, state.ectl, tlm);
|
||||
if (!ectl || !ectl->full ||
|
||||
std::none_of(ectl->roots.begin(), ectl->roots.end(),
|
||||
[&](const auto& c) { return c.encode() == state.rca; })) return false;
|
||||
for (const auto& cert : ectl->roots) roots.push_back(cert.encode());
|
||||
}
|
||||
{
|
||||
const auto ctl = parse_rca_ctl(backend, state.ctl, rca);
|
||||
if (!ctl || !ctl->full) return false;
|
||||
for (const auto* list : {&ctl->ea, &ctl->aa})
|
||||
for (const auto& cert : *list) authorities.push_back(cert.encode());
|
||||
}
|
||||
credentials.roots = std::move(roots);
|
||||
credentials.authorities = std::move(authorities);
|
||||
if (trust) apply(*crl, rca, *trust);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user