Keep the colleague's microbu-esp32c5 tree in this repository
obu-firmware builds against vanetza-idf from microbu-esp32c5/external, but that tree was gitignored, so a clone of this repository could not build the firmware it ships. It is now committed here as ordinary files in its own folder, microbu-esp32c5/: the colleague's commit cf4b99f plus the V2X2MAP bridge's signature verification (--trust) used on the bench. Nothing is fetched from or pushed to the colleague's repository; this repository and its remotes carry everything. The folder's own .gitignore keeps build output, downloaded components and private key material out, as it did there; the committed file set is identical to that repository's tracked files. The ESP32-C5 is still flashed from obu-firmware/, which only takes vanetza-idf from microbu-esp32c5/, so the two stay separate folders. FLASHING.md says how to take a newer version of the colleague's tree (copy it over the folder, rebuild, test, commit).
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
if(NOT TARGET Boost::program_options)
|
||||
message(STATUS "Skip build of benchmark because of missing Boost::program_options dependency")
|
||||
return()
|
||||
endif()
|
||||
|
||||
add_executable(benchmark
|
||||
cases/security/base.cpp
|
||||
cases/security/signing.cpp
|
||||
cases/security/validation.cpp
|
||||
main.cpp
|
||||
options.cpp
|
||||
)
|
||||
|
||||
target_include_directories(benchmark PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(benchmark Boost::program_options vanetza)
|
||||
@@ -0,0 +1 @@
|
||||
Content of this readme file has been moved to our [documentation](https://www.vanetza.org/tools/benchmark).
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef BENCHMARK_CASE_HPP
|
||||
#define BENCHMARK_CASE_HPP
|
||||
|
||||
#include <chrono>
|
||||
#include <type_traits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Case
|
||||
{
|
||||
public:
|
||||
virtual bool parse(const std::vector<std::string>&) = 0;
|
||||
virtual void prepare() = 0;
|
||||
virtual int execute() = 0;
|
||||
virtual ~Case() = default;
|
||||
};
|
||||
|
||||
#endif /* BENCHMARK_CASE_HPP */
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "base.hpp"
|
||||
#include "vanetza/security/v2/sign_service.hpp"
|
||||
#include "vanetza/security/straight_verify_service.hpp"
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <iostream>
|
||||
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
|
||||
SecurityBaseCase::SecurityBaseCase() :
|
||||
runtime(Clock::at(boost::posix_time::microsec_clock::universal_time())),
|
||||
crypto_backend(create_backend("default")),
|
||||
certificate_cache(runtime),
|
||||
certificate_provider(runtime),
|
||||
certificate_validator(*crypto_backend, certificate_cache, trust_store),
|
||||
sign_header_policy(runtime, positioning),
|
||||
security_entity(create_sign_service(), create_verify_service())
|
||||
{
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
void SecurityBaseCase::prepare()
|
||||
{
|
||||
PositionFix position;
|
||||
position.latitude = 49.014420 * units::degree;
|
||||
position.longitude = 8.404417 * units::degree;
|
||||
position.confidence.semi_major = 25.0 * units::si::meter;
|
||||
position.confidence.semi_minor = 25.0 * units::si::meter;
|
||||
assert(position.confidence);
|
||||
|
||||
positioning.position_fix(position);
|
||||
}
|
||||
|
||||
std::unique_ptr<SignService> SecurityBaseCase::create_sign_service()
|
||||
{
|
||||
return std::unique_ptr<SignService> {
|
||||
new v2::StraightSignService(certificate_provider, *crypto_backend, sign_header_policy)
|
||||
};
|
||||
}
|
||||
|
||||
std::unique_ptr<VerifyService> SecurityBaseCase::create_verify_service()
|
||||
{
|
||||
std::unique_ptr<StraightVerifyService> verify_service { new StraightVerifyService(runtime, *crypto_backend, positioning) };
|
||||
verify_service->use_certificate_cache(&certificate_cache);
|
||||
verify_service->use_certificate_provider(&certificate_provider);
|
||||
verify_service->use_certificate_validator(&certificate_validator);
|
||||
verify_service->use_sign_header_policy(&sign_header_policy);
|
||||
return verify_service;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#ifndef BENCHMARK_CASES_SECURITY_BASE_HPP
|
||||
#define BENCHMARK_CASES_SECURITY_BASE_HPP
|
||||
|
||||
#include "case.hpp"
|
||||
#include <vanetza/common/manual_runtime.hpp>
|
||||
#include <vanetza/common/stored_position_provider.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/delegating_security_entity.hpp>
|
||||
#include <vanetza/security/v2/certificate_cache.hpp>
|
||||
#include <vanetza/security/v2/default_certificate_validator.hpp>
|
||||
#include <vanetza/security/v2/naive_certificate_provider.hpp>
|
||||
#include <vanetza/security/v2/sign_header_policy.hpp>
|
||||
#include <vanetza/security/v2/trust_store.hpp>
|
||||
|
||||
class SecurityBaseCase : public Case
|
||||
{
|
||||
public:
|
||||
SecurityBaseCase();
|
||||
|
||||
void prepare() override;
|
||||
|
||||
protected:
|
||||
vanetza::ManualRuntime runtime;
|
||||
vanetza::StoredPositionProvider positioning;
|
||||
std::unique_ptr<vanetza::security::Backend> crypto_backend;
|
||||
vanetza::security::v2::TrustStore trust_store;
|
||||
vanetza::security::v2::CertificateCache certificate_cache;
|
||||
vanetza::security::v2::NaiveCertificateProvider certificate_provider;
|
||||
vanetza::security::v2::DefaultCertificateValidator certificate_validator;
|
||||
vanetza::security::v2::DefaultSignHeaderPolicy sign_header_policy;
|
||||
vanetza::security::DelegatingSecurityEntity security_entity;
|
||||
|
||||
std::unique_ptr<vanetza::security::SignService> create_sign_service();
|
||||
std::unique_ptr<vanetza::security::VerifyService> create_verify_service();
|
||||
};
|
||||
|
||||
#endif /* BENCHMARK_CASES_SECURITY_BASE_HPP */
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#include "signing.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
namespace po = boost::program_options;
|
||||
|
||||
bool SecuritySigningCase::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("messages", po::value<unsigned>(&messages)->default_value(10000), "Number of messages.")
|
||||
("signer", po::value<std::string>(&signer_info_type)->default_value("certificate"), "Signer embedded into the messages, may be 'certificate', 'hash' or 'chain'.")
|
||||
;
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
|
||||
if (signer_info_type != "certificate" && signer_info_type != "hash" && signer_info_type != "chain") {
|
||||
throw std::runtime_error("Invalid signer info type.");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int SecuritySigningCase::execute()
|
||||
{
|
||||
if (signer_info_type == "hash") {
|
||||
// Sign one message with CAM profile, so the next message only includes the certificate hash
|
||||
DownPacket packet;
|
||||
packet.layer(OsiLayer::Application) = ByteBuffer { 0xC0, 0xFF, 0xEE };
|
||||
|
||||
SignRequest initial_sign_request;
|
||||
initial_sign_request.plain_message = std::move(packet);
|
||||
initial_sign_request.its_aid = aid::CA;
|
||||
security_entity.encapsulate_packet(std::move(initial_sign_request));
|
||||
}
|
||||
|
||||
if (signer_info_type == "certificate") {
|
||||
sign_header_policy.request_certificate();
|
||||
} else if (signer_info_type == "chain") {
|
||||
sign_header_policy.request_certificate_chain();
|
||||
}
|
||||
|
||||
std::cout << "Starting benchmark for messages ... ";
|
||||
|
||||
for (unsigned i = 0; i < messages; i++) {
|
||||
DownPacket packet;
|
||||
packet.layer(OsiLayer::Application) = ByteBuffer { 0xC0, 0xFF, 0xEE };
|
||||
|
||||
SignRequest sign_request;
|
||||
sign_request.plain_message= std::move(packet);
|
||||
sign_request.its_aid = aid::CA;
|
||||
|
||||
EncapConfirm encap_confirm = security_entity.encapsulate_packet(std::move(sign_request));
|
||||
}
|
||||
|
||||
std::cout << "[Done]" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#ifndef BENCHMARK_CASES_SECURITY_SIGNING_HPP
|
||||
#define BENCHMARK_CASES_SECURITY_SIGNING_HPP
|
||||
|
||||
#include "base.hpp"
|
||||
|
||||
class SecuritySigningCase : public SecurityBaseCase
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
unsigned messages;
|
||||
std::string signer_info_type;
|
||||
};
|
||||
|
||||
#endif /* BENCHMARK_CASES_SECURITY_SIGNING_HPP */
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/security/delegating_security_entity.hpp>
|
||||
#include <vanetza/security/v2/secured_message.hpp>
|
||||
#include <vanetza/security/v2/sign_service.hpp>
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <random>
|
||||
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
namespace po = boost::program_options;
|
||||
|
||||
bool SecurityValidationCase::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("identities", po::value<unsigned>(&identities)->default_value(1), "Number of identities (certificates).")
|
||||
("messages", po::value<unsigned>(&messages)->default_value(10000), "Number of messages.")
|
||||
("signer", po::value<std::string>(&signer_info_type)->default_value("certificate"), "Signer embedded into the messages, may be 'certificate', 'hash' or 'chain'.")
|
||||
;
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
|
||||
if (signer_info_type != "certificate" && signer_info_type != "hash" && signer_info_type != "chain") {
|
||||
throw std::runtime_error("Invalid signer info type.");
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int SecurityValidationCase::execute()
|
||||
{
|
||||
DownPacket packet;
|
||||
packet.layer(OsiLayer::Application) = ByteBuffer { 0xC0, 0xFF, 0xEE };
|
||||
|
||||
certificate_cache.insert(certificate_provider.own_certificate());
|
||||
certificate_cache.insert(certificate_provider.aa_certificate());
|
||||
trust_store.insert(certificate_provider.root_certificate());
|
||||
|
||||
std::vector<std::unique_ptr<v2::CertificateProvider>> providers;
|
||||
std::vector<std::unique_ptr<SecurityEntity>> entities;
|
||||
std::vector<SecuredMessage> secured_messages(identities);
|
||||
|
||||
for (unsigned i = 0; i < identities; i++) {
|
||||
providers.emplace_back(new v2::NaiveCertificateProvider(runtime));
|
||||
entities.emplace_back(new DelegatingSecurityEntity { create_sign_service(), create_verify_service() });
|
||||
certificate_cache.insert(providers.back()->own_certificate());
|
||||
}
|
||||
|
||||
if (signer_info_type == "hash") {
|
||||
// Sign one message with CAM profile, so the next message only includes the certificate hash
|
||||
SignRequest initial_sign_request;
|
||||
initial_sign_request.plain_message = packet;
|
||||
initial_sign_request.its_aid = aid::CA;
|
||||
entities[0]->encapsulate_packet(std::move(initial_sign_request));
|
||||
}
|
||||
|
||||
for (unsigned i = 0; i < identities; i++) {
|
||||
if (signer_info_type == "certificate") {
|
||||
sign_header_policy.request_certificate();
|
||||
} else if (signer_info_type == "chain") {
|
||||
sign_header_policy.request_certificate_chain();
|
||||
}
|
||||
|
||||
SignRequest sign_request;
|
||||
sign_request.plain_message = packet;
|
||||
sign_request.its_aid = aid::CA;
|
||||
|
||||
EncapConfirm encap_confirm = entities[i]->encapsulate_packet(std::move(sign_request));
|
||||
auto secured_msg = encap_confirm.secured_message();
|
||||
if (!secured_msg) {
|
||||
std::cerr << "Failed to encapsulate packet." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
auto v2_sec_msg = boost::get<v2::SecuredMessage>(*secured_msg);
|
||||
auto signer_info = v2_sec_msg.header_field<v2::HeaderFieldType::Signer_Info>();
|
||||
|
||||
if (signer_info_type == "hash") {
|
||||
assert(signer_info && get_type(*signer_info) == v2::SignerInfoType::Certificate_Digest_With_SHA256);
|
||||
} else if (signer_info_type == "certificate") {
|
||||
assert(signer_info && get_type(*signer_info) == v2::SignerInfoType::Certificate);
|
||||
} else if (signer_info_type == "chain") {
|
||||
assert(signer_info && get_type(*signer_info) == v2::SignerInfoType::Certificate_Chain);
|
||||
}
|
||||
|
||||
secured_messages.push_back(v2_sec_msg);
|
||||
}
|
||||
|
||||
std::mt19937 gen(0);
|
||||
std::uniform_int_distribution<> dis(0, identities - 1);
|
||||
|
||||
std::cout << "Starting benchmark for messages ... ";
|
||||
|
||||
for (unsigned i = 0; i < messages; i++) {
|
||||
DecapRequest decap_request { SecuredMessageView { secured_messages[dis(gen)] }};
|
||||
auto decap_confirm = security_entity.decapsulate_packet(std::move(decap_request));
|
||||
assert(decap_confirm.report == VerificationReport::Success);
|
||||
}
|
||||
|
||||
std::cout << "[Done]" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#ifndef BENCHMARK_CASES_SECURITY_VALIDATION_HPP
|
||||
#define BENCHMARK_CASES_SECURITY_VALIDATION_HPP
|
||||
|
||||
#include "base.hpp"
|
||||
|
||||
class SecurityValidationCase : public SecurityBaseCase
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
unsigned identities;
|
||||
unsigned messages;
|
||||
std::string signer_info_type;
|
||||
};
|
||||
|
||||
#endif /* BENCHMARK_CASES_SECURITY_VALIDATION_HPP */
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "options.hpp"
|
||||
#include <iostream>
|
||||
|
||||
int main(int argc, const char** argv)
|
||||
{
|
||||
try {
|
||||
std::unique_ptr<Case> executable = parse_options(argc, argv);
|
||||
|
||||
if (!executable) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return executable->execute();
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#include "cases/security/signing.hpp"
|
||||
#include "cases/security/validation.hpp"
|
||||
#include "options.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
|
||||
std::unique_ptr<Case> parse_options(int argc, const char *argv[])
|
||||
{
|
||||
po::options_description global("Global options");
|
||||
global.add_options()
|
||||
("case", po::value<std::string>(), "Case to execute.")
|
||||
("subargs", po::value<std::vector<std::string>>(), "Arguments for case.");
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("case", 1);
|
||||
pos.add("subargs", -1);
|
||||
|
||||
po::variables_map vm;
|
||||
|
||||
po::parsed_options parsed = po::command_line_parser(argc, argv)
|
||||
.options(global)
|
||||
.positional(pos)
|
||||
.allow_unregistered()
|
||||
.run();
|
||||
|
||||
po::store(parsed, vm);
|
||||
po::notify(vm);
|
||||
|
||||
std::string available_commands = "Available cases: security-validation, security-signing";
|
||||
|
||||
if (!vm.count("case")) {
|
||||
std::cerr << global << std::endl;
|
||||
std::cerr << available_commands << std::endl;
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string name = vm["case"].as<std::string>();
|
||||
std::unique_ptr<Case> instance;
|
||||
|
||||
if (name == "--help") {
|
||||
std::cerr << global << std::endl;
|
||||
std::cerr << available_commands << std::endl;
|
||||
} else if (name == "security-signing") {
|
||||
instance.reset(new SecuritySigningCase());
|
||||
} else if (name == "security-validation") {
|
||||
instance.reset(new SecurityValidationCase());
|
||||
} else {
|
||||
throw std::runtime_error("Unknown benchmark case.");
|
||||
}
|
||||
|
||||
std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
|
||||
opts.erase(opts.begin());
|
||||
|
||||
if (!instance->parse(opts)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return instance;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef BENCHMARK_OPTIONS_HPP
|
||||
#define BENCHMARK_OPTIONS_HPP
|
||||
|
||||
#include "case.hpp"
|
||||
#include <memory>
|
||||
|
||||
std::unique_ptr<Case> parse_options(int argc, const char* argv[]);
|
||||
|
||||
#endif /* BENCHMARK_OPTIONS_HPP */
|
||||
@@ -0,0 +1,27 @@
|
||||
if(NOT TARGET Boost::program_options)
|
||||
message(STATUS "Skip build of certify-pqc because Boost::program_options is unavailable")
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(NOT TARGET CryptoPP::CryptoPP)
|
||||
message(STATUS "Skip build of certify-pqc because CryptoPP is unavailable")
|
||||
return()
|
||||
endif()
|
||||
|
||||
add_executable(certify-pqc
|
||||
certificate_builder.cpp
|
||||
files.cpp
|
||||
main.cpp
|
||||
)
|
||||
target_include_directories(certify-pqc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(certify-pqc PRIVATE Boost::program_options vanetza)
|
||||
install(TARGETS certify-pqc RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
if(BUILD_TESTS AND TARGET certify)
|
||||
add_test(NAME CertifyPqcWorkflow
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DCERTIFY=$<TARGET_FILE:certify>
|
||||
-DCERTIFY_PQC=$<TARGET_FILE:certify-pqc>
|
||||
-DWORK_DIRECTORY=${PROJECT_BINARY_DIR}/tests/certify-pqc-workflow
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/test_workflow.cmake)
|
||||
endif()
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
#include "certificate_builder.hpp"
|
||||
#include <vanetza/asn1/security_profile.hpp>
|
||||
#include VANETZA_ASN1_SECURITY_HEADER(Certificate.h)
|
||||
#include VANETZA_ASN1_SECURITY_HEADER(PsidGroupPermissions.h)
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/ecc_point.hpp>
|
||||
#include <vanetza/security/pqc/hybrid_certificate.hpp>
|
||||
#include <vanetza/security/private_key.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v3/asn1_conversions.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <array>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace security
|
||||
{
|
||||
namespace pqc
|
||||
{
|
||||
namespace certificate_builder
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
void assign_octets(OCTET_STRING_t& destination, const void* source, std::size_t size)
|
||||
{
|
||||
if (size > static_cast<std::size_t>(std::numeric_limits<int>::max()) ||
|
||||
OCTET_STRING_fromBuf(
|
||||
&destination, static_cast<const char*>(source), static_cast<int>(size)) != 0) {
|
||||
throw std::runtime_error("cannot allocate ASN.1 octet string");
|
||||
}
|
||||
}
|
||||
|
||||
::vanetza::security::PrivateKey convert_private_key(const ecdsa256::PrivateKey& input)
|
||||
{
|
||||
::vanetza::security::PrivateKey output;
|
||||
output.type = KeyType::NistP256;
|
||||
output.key.assign(input.key.begin(), input.key.end());
|
||||
return output;
|
||||
}
|
||||
|
||||
void set_verification_key(v3::Certificate& certificate, const ecdsa256::PublicKey& public_key)
|
||||
{
|
||||
auto& indicator = certificate->toBeSigned.verifyKeyIndicator;
|
||||
indicator.present = Vanetza_Security_VerificationKeyIndicator_PR_verificationKey;
|
||||
auto& verification_key = indicator.choice.verificationKey;
|
||||
verification_key.present = Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256;
|
||||
verification_key.choice.ecdsaNistP256 =
|
||||
v3::to_asn1(compress_public_key(public_key));
|
||||
}
|
||||
|
||||
void set_encryption_key(v3::Certificate& certificate, const ecdsa256::PublicKey& public_key)
|
||||
{
|
||||
certificate->toBeSigned.encryptionKey =
|
||||
vanetza::asn1::allocate<v3::asn1::PublicEncryptionKey>();
|
||||
auto& encryption_key = certificate->toBeSigned.encryptionKey->publicKey;
|
||||
encryption_key.present = Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256;
|
||||
encryption_key.choice.eciesNistP256 =
|
||||
v3::to_asn1(compress_public_key(public_key));
|
||||
}
|
||||
|
||||
void set_issuer(v3::Certificate& certificate, const v3::Certificate* issuer)
|
||||
{
|
||||
if (!issuer) {
|
||||
certificate->issuer.present = Vanetza_Security_IssuerIdentifier_PR_self;
|
||||
certificate->issuer.choice.self = Vanetza_Security_HashAlgorithm_sha256;
|
||||
return;
|
||||
}
|
||||
|
||||
const auto digest = issuer->calculate_digest();
|
||||
if (!digest) {
|
||||
throw std::invalid_argument("issuer certificate has no canonical digest");
|
||||
}
|
||||
certificate->issuer.present = Vanetza_Security_IssuerIdentifier_PR_sha256AndDigest;
|
||||
assign_octets(
|
||||
certificate->issuer.choice.sha256AndDigest,
|
||||
digest->data(), digest->size());
|
||||
}
|
||||
|
||||
void set_subject_name(v3::Certificate& certificate, const std::string& name)
|
||||
{
|
||||
if (name.empty()) {
|
||||
throw std::invalid_argument("CA subject name must not be empty");
|
||||
}
|
||||
certificate->toBeSigned.id.present = Vanetza_Security_CertificateId_PR_name;
|
||||
assign_octets(certificate->toBeSigned.id.choice.name, name.data(), name.size());
|
||||
}
|
||||
|
||||
void set_validity(
|
||||
v3::Certificate& certificate, Clock::time_point now, int validity_days)
|
||||
{
|
||||
constexpr int maximum_days = std::numeric_limits<unsigned short>::max() / 24;
|
||||
if (validity_days < 1 || validity_days > maximum_days) {
|
||||
throw std::invalid_argument("validity must be between 1 and 2730 days");
|
||||
}
|
||||
|
||||
certificate->toBeSigned.validityPeriod.start =
|
||||
v2::convert_time32(now - std::chrono::hours(1));
|
||||
certificate->toBeSigned.validityPeriod.duration.present =
|
||||
Vanetza_Security_Duration_PR_hours;
|
||||
certificate->toBeSigned.validityPeriod.duration.choice.hours = validity_days * 24;
|
||||
}
|
||||
|
||||
void initialize_certificate(
|
||||
v3::Certificate& certificate, const ecdsa256::PublicKey& subject_key,
|
||||
const v3::Certificate* issuer, int validity_days, Clock::time_point now)
|
||||
{
|
||||
certificate->version = 3;
|
||||
certificate->type = Vanetza_Security_CertificateType_explicit;
|
||||
set_issuer(certificate, issuer);
|
||||
|
||||
static const std::array<char, 3> craca_id {{ 0, 0, 0 }};
|
||||
assign_octets(certificate->toBeSigned.cracaId, craca_id.data(), craca_id.size());
|
||||
certificate->toBeSigned.crlSeries = 0;
|
||||
set_validity(certificate, now, validity_days);
|
||||
set_verification_key(certificate, subject_key);
|
||||
}
|
||||
|
||||
std::vector<ItsAid> effective_issue_aids(const std::vector<ItsAid>& aids)
|
||||
{
|
||||
if (!aids.empty()) {
|
||||
return aids;
|
||||
}
|
||||
return { aid::CA, aid::DEN, aid::CP, aid::GN_MGMT, aid::IPV6_ROUTING };
|
||||
}
|
||||
|
||||
std::vector<ItsAid> effective_application_aids(const std::vector<ItsAid>& aids)
|
||||
{
|
||||
return aids.empty() ? std::vector<ItsAid> { aid::CA, aid::DEN } : aids;
|
||||
}
|
||||
|
||||
void add_issue_permission_for_aid(
|
||||
v3::asn1::PsidGroupPermissions* group, ItsAid application_id)
|
||||
{
|
||||
switch (application_id) {
|
||||
case aid::CA:
|
||||
v3::add_psid_group_permission(
|
||||
group, application_id, { 0x01, 0xff, 0xfc }, { 0xff, 0x00, 0x03 });
|
||||
break;
|
||||
case aid::DEN:
|
||||
v3::add_psid_group_permission(
|
||||
group, application_id,
|
||||
{ 0x01, 0xff, 0xff, 0xff }, { 0xff, 0x00, 0x00, 0x00 });
|
||||
break;
|
||||
case aid::CP:
|
||||
v3::add_psid_group_permission(group, application_id, { 0x00 }, { 0xff });
|
||||
break;
|
||||
case aid::TLM:
|
||||
v3::add_psid_group_permission(group, application_id, { 0x01, 0xe0 }, { 0xff, 0x1f });
|
||||
break;
|
||||
case aid::RLT:
|
||||
v3::add_psid_group_permission(group, application_id, { 0x01, 0xc0 }, { 0xff, 0x3f });
|
||||
break;
|
||||
case aid::IVI:
|
||||
v3::add_psid_group_permission(
|
||||
group, application_id,
|
||||
{ 0x01, 0xff, 0xff, 0xff, 0xff, 0xf8 },
|
||||
{ 0xff, 0x00, 0x00, 0x00, 0x00, 0x07 });
|
||||
break;
|
||||
case aid::TLC_R:
|
||||
v3::add_psid_group_permission(
|
||||
group, application_id,
|
||||
{ 0x02, 0xff, 0xff, 0xe0 }, { 0xff, 0x00, 0x00, 0x1f });
|
||||
break;
|
||||
case aid::GN_MGMT:
|
||||
case aid::IPV6_ROUTING:
|
||||
default:
|
||||
v3::add_psid_group_permission(group, application_id, { 0x00 }, { 0xff });
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void add_issue_permissions(v3::Certificate& certificate, const std::vector<ItsAid>& aids)
|
||||
{
|
||||
auto* group = vanetza::asn1::allocate<v3::asn1::PsidGroupPermissions>();
|
||||
group->subjectPermissions.present = Vanetza_Security_SubjectPermissions_PR_explicit;
|
||||
for (ItsAid application_id : effective_issue_aids(aids)) {
|
||||
add_issue_permission_for_aid(group, application_id);
|
||||
}
|
||||
certificate.add_cert_issue_permission(group);
|
||||
}
|
||||
|
||||
void add_application_permissions(v3::Certificate& certificate, const std::vector<ItsAid>& aids)
|
||||
{
|
||||
for (ItsAid application_id : effective_application_aids(aids)) {
|
||||
if (application_id == aid::CA) {
|
||||
certificate.add_app_permission(application_id, ByteBuffer { 1, 0, 0 });
|
||||
} else if (application_id == aid::DEN) {
|
||||
certificate.add_app_permission(application_id, ByteBuffer { 1, 0, 0, 0 });
|
||||
} else {
|
||||
certificate.add_app_permission(application_id, {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
v3::Certificate canonical_certificate(v3::Certificate certificate)
|
||||
{
|
||||
auto canonical = certificate.canonicalize();
|
||||
if (!canonical) {
|
||||
throw std::runtime_error("generated certificate cannot be canonicalized");
|
||||
}
|
||||
std::string error;
|
||||
if (!canonical->validate(error)) {
|
||||
throw std::runtime_error("generated certificate violates ASN.1 constraints: " + error);
|
||||
}
|
||||
return std::move(*canonical);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
v3::Certificate build_ecc_root_certificate(
|
||||
::vanetza::security::Backend& ecc_backend, const ecdsa256::KeyPair& subject_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key.public_key, nullptr, parameters.validity_days, now);
|
||||
set_subject_name(certificate, parameters.subject_name);
|
||||
add_issue_permissions(certificate, parameters.application_ids);
|
||||
certificate.add_app_permission(aid::CRL, ByteBuffer { 1 });
|
||||
certificate.add_app_permission(aid::CTL, ByteBuffer { 0x18 });
|
||||
|
||||
sign_primary_certificate(
|
||||
certificate, nullptr, ecc_backend, convert_private_key(subject_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
v3::Certificate build_hybrid_root_certificate(
|
||||
::vanetza::security::Backend& ecc_backend, Backend& pqc_backend,
|
||||
const ecdsa256::KeyPair& subject_key, const KeyPair& subject_pqc_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key.public_key, nullptr, parameters.validity_days, now);
|
||||
set_subject_name(certificate, parameters.subject_name);
|
||||
add_issue_permissions(certificate, parameters.application_ids);
|
||||
certificate.add_app_permission(aid::CRL, ByteBuffer { 1 });
|
||||
certificate.add_app_permission(aid::CTL, ByteBuffer { 0x18 });
|
||||
|
||||
set_alternative_public_key(certificate, subject_pqc_key.public_key);
|
||||
sign_alternative_certificate(
|
||||
certificate, nullptr, ecc_backend, pqc_backend, subject_pqc_key.private_key);
|
||||
sign_primary_certificate(
|
||||
certificate, nullptr, ecc_backend, convert_private_key(subject_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
v3::Certificate build_ecc_authorization_authority_certificate(
|
||||
::vanetza::security::Backend& ecc_backend, const ecdsa256::KeyPair& issuer_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key, &issuer_certificate, parameters.validity_days, now);
|
||||
set_subject_name(certificate, parameters.subject_name);
|
||||
add_issue_permissions(certificate, parameters.application_ids);
|
||||
set_encryption_key(certificate, subject_key);
|
||||
|
||||
sign_primary_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend,
|
||||
convert_private_key(issuer_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
v3::Certificate build_hybrid_authorization_authority_certificate(
|
||||
::vanetza::security::Backend& ecc_backend, Backend& pqc_backend,
|
||||
const ecdsa256::KeyPair& issuer_key, const PrivateKey& issuer_pqc_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key, const PublicKey& subject_pqc_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key, &issuer_certificate, parameters.validity_days, now);
|
||||
set_subject_name(certificate, parameters.subject_name);
|
||||
add_issue_permissions(certificate, parameters.application_ids);
|
||||
set_encryption_key(certificate, subject_key);
|
||||
|
||||
set_alternative_public_key(certificate, subject_pqc_key);
|
||||
sign_alternative_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend, pqc_backend, issuer_pqc_key);
|
||||
sign_primary_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend,
|
||||
convert_private_key(issuer_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
v3::Certificate build_ecc_authorization_ticket(
|
||||
::vanetza::security::Backend& ecc_backend, const ecdsa256::KeyPair& issuer_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key, &issuer_certificate, parameters.validity_days, now);
|
||||
certificate->toBeSigned.id.present = Vanetza_Security_CertificateId_PR_none;
|
||||
add_application_permissions(certificate, parameters.application_ids);
|
||||
|
||||
sign_primary_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend,
|
||||
convert_private_key(issuer_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
v3::Certificate build_hybrid_authorization_ticket(
|
||||
::vanetza::security::Backend& ecc_backend, Backend& pqc_backend,
|
||||
const ecdsa256::KeyPair& issuer_key, const PrivateKey& issuer_pqc_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters& parameters, Clock::time_point now)
|
||||
{
|
||||
v3::Certificate certificate;
|
||||
initialize_certificate(
|
||||
certificate, subject_key, &issuer_certificate, parameters.validity_days, now);
|
||||
certificate->toBeSigned.id.present = Vanetza_Security_CertificateId_PR_none;
|
||||
add_application_permissions(certificate, parameters.application_ids);
|
||||
|
||||
sign_alternative_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend, pqc_backend, issuer_pqc_key);
|
||||
sign_primary_certificate(
|
||||
certificate, &issuer_certificate, ecc_backend,
|
||||
convert_private_key(issuer_key.private_key));
|
||||
return canonical_certificate(std::move(certificate));
|
||||
}
|
||||
|
||||
} // namespace certificate_builder
|
||||
} // namespace pqc
|
||||
} // namespace security
|
||||
} // namespace vanetza
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/ecdsa256.hpp>
|
||||
#include <vanetza/security/pqc/fndsa512.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace security
|
||||
{
|
||||
|
||||
class Backend;
|
||||
|
||||
namespace pqc
|
||||
{
|
||||
namespace certificate_builder
|
||||
{
|
||||
|
||||
struct CertificateParameters
|
||||
{
|
||||
std::string subject_name;
|
||||
int validity_days = 1;
|
||||
std::vector<ItsAid> application_ids;
|
||||
};
|
||||
|
||||
v3::Certificate build_ecc_root_certificate(
|
||||
::vanetza::security::Backend&, const ecdsa256::KeyPair&,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
v3::Certificate build_hybrid_root_certificate(
|
||||
::vanetza::security::Backend&, Backend&, const ecdsa256::KeyPair&, const KeyPair&,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
v3::Certificate build_ecc_authorization_authority_certificate(
|
||||
::vanetza::security::Backend&, const ecdsa256::KeyPair& issuer_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
v3::Certificate build_hybrid_authorization_authority_certificate(
|
||||
::vanetza::security::Backend&, Backend&,
|
||||
const ecdsa256::KeyPair& issuer_key, const PrivateKey& issuer_pqc_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key, const PublicKey& subject_pqc_key,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
v3::Certificate build_ecc_authorization_ticket(
|
||||
::vanetza::security::Backend&, const ecdsa256::KeyPair& issuer_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
v3::Certificate build_hybrid_authorization_ticket(
|
||||
::vanetza::security::Backend&, Backend&,
|
||||
const ecdsa256::KeyPair& issuer_key, const PrivateKey& issuer_pqc_key,
|
||||
const v3::Certificate& issuer_certificate,
|
||||
const ecdsa256::PublicKey& subject_key,
|
||||
const CertificateParameters&, Clock::time_point now);
|
||||
|
||||
} // namespace certificate_builder
|
||||
} // namespace pqc
|
||||
} // namespace security
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,103 @@
|
||||
#include "files.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using vanetza::ByteBuffer;
|
||||
|
||||
ByteBuffer read_file(const std::string& path)
|
||||
{
|
||||
std::ifstream stream(path, std::ios::binary);
|
||||
if (!stream) {
|
||||
throw std::runtime_error("cannot open file for reading: " + path);
|
||||
}
|
||||
return ByteBuffer(std::istreambuf_iterator<char>(stream), {});
|
||||
}
|
||||
|
||||
void write_file(const std::string& path, const ByteBuffer& data)
|
||||
{
|
||||
std::ofstream stream(path, std::ios::binary | std::ios::trunc);
|
||||
if (!stream || !stream.write(
|
||||
reinterpret_cast<const char*>(data.data()), data.size())) {
|
||||
throw std::runtime_error("cannot write file: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T load_exact(const std::string& path, std::size_t expected_size, const char* description)
|
||||
{
|
||||
T output { read_file(path) };
|
||||
if (output.bytes.size() != expected_size) {
|
||||
throw std::runtime_error(
|
||||
std::string(description) + " has an invalid size in: " + path);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
vanetza::security::ecdsa256::KeyPair load_ecc_key_pair(const std::string& path)
|
||||
{
|
||||
return vanetza::security::v2::load_private_key_from_file(path);
|
||||
}
|
||||
|
||||
vanetza::security::pqc::KeyPair load_pqc_key_pair(const std::string& base_path)
|
||||
{
|
||||
using namespace vanetza::security::pqc;
|
||||
KeyPair key_pair;
|
||||
key_pair.private_key = load_exact<PrivateKey>(
|
||||
base_path + ".pqc.key", fndsa512_private_key_size, "FN-DSA-512 private key");
|
||||
key_pair.public_key = load_exact<PublicKey>(
|
||||
base_path + ".pqc.pub", fndsa512_public_key_size, "FN-DSA-512 public key");
|
||||
return key_pair;
|
||||
}
|
||||
|
||||
vanetza::security::pqc::PrivateKey load_pqc_private_key(const std::string& base_path)
|
||||
{
|
||||
using namespace vanetza::security::pqc;
|
||||
return load_exact<PrivateKey>(
|
||||
base_path + ".pqc.key", fndsa512_private_key_size, "FN-DSA-512 private key");
|
||||
}
|
||||
|
||||
void save_pqc_key_pair(
|
||||
const std::string& base_path, const vanetza::security::pqc::KeyPair& key_pair)
|
||||
{
|
||||
using namespace vanetza::security::pqc;
|
||||
if (key_pair.private_key.bytes.size() != fndsa512_private_key_size ||
|
||||
key_pair.public_key.bytes.size() != fndsa512_public_key_size) {
|
||||
throw std::invalid_argument("cannot save malformed FN-DSA-512 key pair");
|
||||
}
|
||||
|
||||
const std::string private_path = base_path + ".pqc.key";
|
||||
write_file(private_path, key_pair.private_key.bytes);
|
||||
if (::chmod(private_path.c_str(), S_IRUSR | S_IWUSR) != 0) {
|
||||
throw std::runtime_error("cannot restrict private-key permissions: " + private_path);
|
||||
}
|
||||
write_file(base_path + ".pqc.pub", key_pair.public_key.bytes);
|
||||
}
|
||||
|
||||
vanetza::security::v3::Certificate load_v3_certificate(const std::string& path)
|
||||
{
|
||||
vanetza::security::v3::Certificate certificate;
|
||||
const auto encoded = read_file(path);
|
||||
if (encoded.empty() || !certificate.decode(encoded)) {
|
||||
throw std::runtime_error("cannot decode V3 certificate: " + path);
|
||||
}
|
||||
return certificate;
|
||||
}
|
||||
|
||||
void save_v3_certificate(
|
||||
const std::string& path, const vanetza::security::v3::Certificate& certificate)
|
||||
{
|
||||
std::string error;
|
||||
if (!certificate.validate(error)) {
|
||||
throw std::runtime_error("refusing to save invalid V3 certificate: " + error);
|
||||
}
|
||||
write_file(path, certificate.encode());
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include <vanetza/security/ecdsa256.hpp>
|
||||
#include <vanetza/security/pqc/fndsa512.hpp>
|
||||
#include <vanetza/security/v3/certificate.hpp>
|
||||
#include <string>
|
||||
|
||||
vanetza::security::ecdsa256::KeyPair load_ecc_key_pair(const std::string& path);
|
||||
vanetza::security::pqc::KeyPair load_pqc_key_pair(const std::string& base_path);
|
||||
vanetza::security::pqc::PrivateKey load_pqc_private_key(const std::string& base_path);
|
||||
|
||||
void save_pqc_key_pair(
|
||||
const std::string& base_path, const vanetza::security::pqc::KeyPair&);
|
||||
|
||||
vanetza::security::v3::Certificate load_v3_certificate(const std::string& path);
|
||||
void save_v3_certificate(
|
||||
const std::string& path, const vanetza::security::v3::Certificate&);
|
||||
@@ -0,0 +1,423 @@
|
||||
#include "certificate_builder.hpp"
|
||||
#include "files.hpp"
|
||||
#include <vanetza/common/manual_runtime.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/pqc/fndsa512.hpp>
|
||||
#include <vanetza/security/pqc/hybrid_certificate.hpp>
|
||||
#include <vanetza/security/pqc/hybrid_certificate_validator.hpp>
|
||||
#include <vanetza/security/v3/issuer_memory_lookup.hpp>
|
||||
#include <vanetza/security/v3/trust_store.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
using namespace vanetza::security::v3;
|
||||
namespace builder = vanetza::security::pqc::certificate_builder;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
enum class CertificateProfile
|
||||
{
|
||||
Ecc,
|
||||
Hybrid
|
||||
};
|
||||
|
||||
CertificateProfile parse_profile(const std::string& profile)
|
||||
{
|
||||
if (profile == "ecc") {
|
||||
return CertificateProfile::Ecc;
|
||||
}
|
||||
if (profile == "hybrid") {
|
||||
return CertificateProfile::Hybrid;
|
||||
}
|
||||
throw std::invalid_argument("unknown certificate profile: " + profile);
|
||||
}
|
||||
|
||||
void validate_pqc_argument(
|
||||
CertificateProfile profile, const std::string& value, const char* option)
|
||||
{
|
||||
if (profile == CertificateProfile::Hybrid && value.empty()) {
|
||||
throw std::invalid_argument(std::string(option) + " is required for the hybrid profile");
|
||||
}
|
||||
if (profile == CertificateProfile::Ecc && !value.empty()) {
|
||||
throw std::invalid_argument(std::string(option) + " is not valid for the ECC profile");
|
||||
}
|
||||
}
|
||||
|
||||
Clock::time_point now()
|
||||
{
|
||||
return Clock::at(boost::posix_time::microsec_clock::universal_time());
|
||||
}
|
||||
|
||||
std::vector<ItsAid> convert_aids(const std::vector<unsigned>& input)
|
||||
{
|
||||
return std::vector<ItsAid>(input.begin(), input.end());
|
||||
}
|
||||
|
||||
std::vector<std::string> command_arguments(int argc, const char* argv[])
|
||||
{
|
||||
return std::vector<std::string>(argv + 2, argv + argc);
|
||||
}
|
||||
|
||||
po::variables_map parse(
|
||||
const std::vector<std::string>& arguments, const po::options_description& options,
|
||||
const po::positional_options_description& positional = {})
|
||||
{
|
||||
po::variables_map variables;
|
||||
po::store(po::command_line_parser(arguments)
|
||||
.options(options).positional(positional).run(), variables);
|
||||
if (!variables.count("help")) {
|
||||
po::notify(variables);
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
int generate_key(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string output;
|
||||
po::options_description options("Generate an FN-DSA-512 key pair");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("output", po::value<std::string>(&output)->required(),
|
||||
"Output base path; .pqc.key and .pqc.pub are appended");
|
||||
po::positional_options_description positional;
|
||||
positional.add("output", 1);
|
||||
const auto variables = parse(arguments, options, positional);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
auto backend = pqc::create_fndsa512_backend();
|
||||
save_pqc_key_pair(output, backend->generate_key_pair());
|
||||
std::cout << "Wrote " << output << ".pqc.key and " << output << ".pqc.pub\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
builder::CertificateParameters certificate_parameters(
|
||||
const std::string& name, int days, const std::vector<unsigned>& aids)
|
||||
{
|
||||
builder::CertificateParameters parameters;
|
||||
parameters.subject_name = name;
|
||||
parameters.validity_days = days;
|
||||
parameters.application_ids = convert_aids(aids);
|
||||
return parameters;
|
||||
}
|
||||
|
||||
int generate_root(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string output;
|
||||
std::string subject_key;
|
||||
std::string subject_pqc_key;
|
||||
std::string profile_name = "hybrid";
|
||||
std::string subject_name = "Hello World Root-CA";
|
||||
int days = 365;
|
||||
std::vector<unsigned> aids;
|
||||
po::options_description options("Generate a V3 Root CA certificate");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("output,o", po::value<std::string>(&output)->required(), "Output certificate")
|
||||
("subject-key", po::value<std::string>(&subject_key)->required(), "ECC private key")
|
||||
("profile", po::value<std::string>(&profile_name)->default_value("hybrid"),
|
||||
"Certificate profile: ecc or hybrid")
|
||||
("subject-pqc-key", po::value<std::string>(&subject_pqc_key),
|
||||
"FN-DSA key base path")
|
||||
("subject-name", po::value<std::string>(&subject_name), "Certificate subject name")
|
||||
("days", po::value<int>(&days), "Validity in days")
|
||||
("aid", po::value<std::vector<unsigned>>(&aids)->multitoken(), "Permitted ITS-AIDs");
|
||||
const auto variables = parse(arguments, options);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto profile = parse_profile(profile_name);
|
||||
validate_pqc_argument(profile, subject_pqc_key, "--subject-pqc-key");
|
||||
auto ecc_backend = create_backend_or_throw("default");
|
||||
const auto subject_ecc = load_ecc_key_pair(subject_key);
|
||||
Certificate certificate;
|
||||
if (profile == CertificateProfile::Hybrid) {
|
||||
auto pqc_backend = pqc::create_fndsa512_backend();
|
||||
certificate = builder::build_hybrid_root_certificate(
|
||||
*ecc_backend, *pqc_backend, subject_ecc, load_pqc_key_pair(subject_pqc_key),
|
||||
certificate_parameters(subject_name, days, aids), now());
|
||||
} else {
|
||||
certificate = builder::build_ecc_root_certificate(
|
||||
*ecc_backend, subject_ecc,
|
||||
certificate_parameters(subject_name, days, aids), now());
|
||||
}
|
||||
save_v3_certificate(output, certificate);
|
||||
std::cout << "Wrote " << profile_name << " V3 Root CA certificate " << output << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
int generate_aa(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string output;
|
||||
std::string sign_key;
|
||||
std::string sign_cert;
|
||||
std::string sign_pqc_key;
|
||||
std::string subject_key;
|
||||
std::string subject_pqc_key;
|
||||
std::string profile_name = "hybrid";
|
||||
std::string subject_name = "Hello World Auth-CA";
|
||||
int days = 180;
|
||||
std::vector<unsigned> aids;
|
||||
po::options_description options("Generate a V3 Authorization Authority certificate");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("output,o", po::value<std::string>(&output)->required(), "Output certificate")
|
||||
("sign-key", po::value<std::string>(&sign_key)->required(), "Issuer ECC private key")
|
||||
("sign-cert", po::value<std::string>(&sign_cert)->required(), "Issuer certificate")
|
||||
("profile", po::value<std::string>(&profile_name)->default_value("hybrid"),
|
||||
"Certificate profile: ecc or hybrid")
|
||||
("sign-pqc-key", po::value<std::string>(&sign_pqc_key),
|
||||
"Issuer FN-DSA key base path")
|
||||
("subject-key", po::value<std::string>(&subject_key)->required(), "Subject ECC private key")
|
||||
("subject-pqc-key", po::value<std::string>(&subject_pqc_key),
|
||||
"Subject FN-DSA key base path")
|
||||
("subject-name", po::value<std::string>(&subject_name), "Certificate subject name")
|
||||
("days", po::value<int>(&days), "Validity in days")
|
||||
("aid", po::value<std::vector<unsigned>>(&aids)->multitoken(), "Permitted ITS-AIDs");
|
||||
const auto variables = parse(arguments, options);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto profile = parse_profile(profile_name);
|
||||
validate_pqc_argument(profile, sign_pqc_key, "--sign-pqc-key");
|
||||
validate_pqc_argument(profile, subject_pqc_key, "--subject-pqc-key");
|
||||
auto ecc_backend = create_backend_or_throw("default");
|
||||
const auto subject_ecc = load_ecc_key_pair(subject_key);
|
||||
const auto issuer_ecc = load_ecc_key_pair(sign_key);
|
||||
const auto issuer_certificate = load_v3_certificate(sign_cert);
|
||||
Certificate certificate;
|
||||
if (profile == CertificateProfile::Hybrid) {
|
||||
auto pqc_backend = pqc::create_fndsa512_backend();
|
||||
const auto subject_pqc = load_pqc_key_pair(subject_pqc_key);
|
||||
certificate = builder::build_hybrid_authorization_authority_certificate(
|
||||
*ecc_backend, *pqc_backend, issuer_ecc,
|
||||
load_pqc_private_key(sign_pqc_key), issuer_certificate,
|
||||
subject_ecc.public_key, subject_pqc.public_key,
|
||||
certificate_parameters(subject_name, days, aids), now());
|
||||
} else {
|
||||
certificate = builder::build_ecc_authorization_authority_certificate(
|
||||
*ecc_backend, issuer_ecc, issuer_certificate, subject_ecc.public_key,
|
||||
certificate_parameters(subject_name, days, aids), now());
|
||||
}
|
||||
save_v3_certificate(output, certificate);
|
||||
std::cout << "Wrote " << profile_name
|
||||
<< " V3 Authorization Authority certificate " << output << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
int generate_ticket(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string output;
|
||||
std::string sign_key;
|
||||
std::string sign_cert;
|
||||
std::string sign_pqc_key;
|
||||
std::string subject_key;
|
||||
std::string profile_name = "hybrid";
|
||||
int days = 7;
|
||||
std::vector<unsigned> aids;
|
||||
po::options_description options("Generate a V3 Authorization Ticket");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("output,o", po::value<std::string>(&output)->required(), "Output certificate")
|
||||
("sign-key", po::value<std::string>(&sign_key)->required(), "Issuer ECC private key")
|
||||
("sign-cert", po::value<std::string>(&sign_cert)->required(), "Issuer certificate")
|
||||
("profile", po::value<std::string>(&profile_name)->default_value("hybrid"),
|
||||
"Certificate profile: ecc or hybrid")
|
||||
("sign-pqc-key", po::value<std::string>(&sign_pqc_key),
|
||||
"Issuer FN-DSA key base path")
|
||||
("subject-key", po::value<std::string>(&subject_key)->required(), "Subject ECC private key")
|
||||
("days", po::value<int>(&days), "Validity in days")
|
||||
("aid", po::value<std::vector<unsigned>>(&aids)->multitoken(), "Permitted ITS-AIDs");
|
||||
const auto variables = parse(arguments, options);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto profile = parse_profile(profile_name);
|
||||
validate_pqc_argument(profile, sign_pqc_key, "--sign-pqc-key");
|
||||
auto ecc_backend = create_backend_or_throw("default");
|
||||
const auto issuer_ecc = load_ecc_key_pair(sign_key);
|
||||
const auto issuer_certificate = load_v3_certificate(sign_cert);
|
||||
const auto subject_ecc = load_ecc_key_pair(subject_key);
|
||||
Certificate certificate;
|
||||
if (profile == CertificateProfile::Hybrid) {
|
||||
auto pqc_backend = pqc::create_fndsa512_backend();
|
||||
certificate = builder::build_hybrid_authorization_ticket(
|
||||
*ecc_backend, *pqc_backend, issuer_ecc,
|
||||
load_pqc_private_key(sign_pqc_key), issuer_certificate,
|
||||
subject_ecc.public_key, certificate_parameters({}, days, aids), now());
|
||||
} else {
|
||||
certificate = builder::build_ecc_authorization_ticket(
|
||||
*ecc_backend, issuer_ecc, issuer_certificate, subject_ecc.public_key,
|
||||
certificate_parameters({}, days, aids), now());
|
||||
}
|
||||
save_v3_certificate(output, certificate);
|
||||
std::cout << "Wrote " << profile_name << " V3 Authorization Ticket " << output << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const char* material_state(pqc::MaterialState state)
|
||||
{
|
||||
switch (state) {
|
||||
case pqc::MaterialState::None: return "none";
|
||||
case pqc::MaterialState::Authority: return "authority (key + signature)";
|
||||
case pqc::MaterialState::EndEntity: return "end entity (signature only)";
|
||||
case pqc::MaterialState::Inconsistent: return "inconsistent";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
int show_certificate(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string input;
|
||||
po::options_description options("Show V3 certificate information");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("certificate", po::value<std::string>(&input)->required(), "Certificate file");
|
||||
po::positional_options_description positional;
|
||||
positional.add("certificate", 1);
|
||||
const auto variables = parse(arguments, options, positional);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto certificate = load_v3_certificate(input);
|
||||
const auto key = pqc::get_alternative_public_key(certificate);
|
||||
const auto signature = pqc::get_alternative_signature(certificate);
|
||||
std::cout << "Encoded size: " << certificate.encode().size() << " bytes\n"
|
||||
<< "Alternative material: "
|
||||
<< material_state(pqc::alternative_material_state(certificate)) << "\n"
|
||||
<< "FN-DSA-512 public key: " << (key ? key->bytes.size() : 0) << " bytes\n"
|
||||
<< "FN-DSA-512 signature: " << (signature ? signature->bytes.size() : 0)
|
||||
<< " bytes\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
int verify_chain(const std::vector<std::string>& arguments)
|
||||
{
|
||||
std::string root_path;
|
||||
std::string aa_path;
|
||||
std::string ticket_path;
|
||||
std::string profile_name = "hybrid";
|
||||
unsigned application_id = aid::CA;
|
||||
po::options_description options("Verify a V3 Root -> AA -> AT chain");
|
||||
options.add_options()
|
||||
("help,h", "Show this help")
|
||||
("root", po::value<std::string>(&root_path)->required(), "Trusted Root certificate")
|
||||
("aa", po::value<std::string>(&aa_path)->required(), "Authorization Authority certificate")
|
||||
("ticket", po::value<std::string>(&ticket_path)->required(), "Authorization Ticket certificate")
|
||||
("profile", po::value<std::string>(&profile_name)->default_value("hybrid"),
|
||||
"Expected profile: ecc or hybrid")
|
||||
("aid", po::value<unsigned>(&application_id), "ITS-AID to validate (default: 36)");
|
||||
const auto variables = parse(arguments, options);
|
||||
if (variables.count("help")) {
|
||||
std::cout << options << '\n';
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto root = load_v3_certificate(root_path);
|
||||
const auto aa = load_v3_certificate(aa_path);
|
||||
const auto ticket = load_v3_certificate(ticket_path);
|
||||
const auto profile = parse_profile(profile_name);
|
||||
if (profile == CertificateProfile::Ecc &&
|
||||
(pqc::alternative_material_state(root) != pqc::MaterialState::None ||
|
||||
pqc::alternative_material_state(aa) != pqc::MaterialState::None ||
|
||||
pqc::alternative_material_state(ticket) != pqc::MaterialState::None)) {
|
||||
throw std::invalid_argument("ECC profile chain contains alternative PQC material");
|
||||
}
|
||||
auto ecc_backend = create_backend_or_throw("default");
|
||||
auto pqc_backend = pqc::create_fndsa512_backend();
|
||||
|
||||
TrustStore trust_store;
|
||||
trust_store.insert(root);
|
||||
IssuerMemoryLookup issuer_lookup;
|
||||
if (!issuer_lookup.insert(root) || !issuer_lookup.insert(aa)) {
|
||||
throw std::runtime_error("Root or AA cannot be used as an issuer certificate");
|
||||
}
|
||||
|
||||
ManualRuntime runtime(now());
|
||||
pqc::HybridCertificateValidator validator;
|
||||
validator.use_runtime(&runtime);
|
||||
validator.disable_location_checks(true);
|
||||
validator.use_issuer_lookup(&issuer_lookup);
|
||||
validator.use_trust_store(&trust_store);
|
||||
validator.use_backends(ecc_backend.get(), pqc_backend.get());
|
||||
validator.use_verification_policy(profile == CertificateProfile::Hybrid ?
|
||||
pqc::HybridCertificateValidator::VerificationPolicy::HybridRequired :
|
||||
pqc::HybridCertificateValidator::VerificationPolicy::HybridIfPresent);
|
||||
|
||||
const auto verdict = validator.valid_for_signing(ticket, application_id);
|
||||
if (verdict != CertificateValidator::Verdict::Valid) {
|
||||
std::cerr << profile_name << " chain verification failed (verdict "
|
||||
<< static_cast<int>(verdict) << ")\n";
|
||||
return 1;
|
||||
}
|
||||
std::cout << profile_name << " V3 Root -> AA -> AT chain is valid\n";
|
||||
return 0;
|
||||
}
|
||||
|
||||
void print_usage(const char* executable)
|
||||
{
|
||||
std::cout << "Usage: " << executable << " COMMAND [OPTIONS]\n\n"
|
||||
<< "Commands:\n"
|
||||
<< " generate-key Generate an FN-DSA-512 key pair\n"
|
||||
<< " generate-root Generate a V3 Root CA\n"
|
||||
<< " generate-aa Generate a V3 Authorization Authority\n"
|
||||
<< " generate-ticket Generate a V3 Authorization Ticket\n"
|
||||
<< " show Show V3 certificate material\n"
|
||||
<< " verify-chain Verify a Root -> AA -> AT chain\n";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, const char* argv[])
|
||||
{
|
||||
try {
|
||||
if (argc < 2 || std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h") {
|
||||
print_usage(argv[0]);
|
||||
return argc < 2 ? 1 : 0;
|
||||
}
|
||||
|
||||
const std::string command = argv[1];
|
||||
const auto arguments = command_arguments(argc, argv);
|
||||
if (command == "generate-key") {
|
||||
return generate_key(arguments);
|
||||
}
|
||||
if (command == "generate-root") {
|
||||
return generate_root(arguments);
|
||||
}
|
||||
if (command == "generate-aa") {
|
||||
return generate_aa(arguments);
|
||||
}
|
||||
if (command == "generate-ticket") {
|
||||
return generate_ticket(arguments);
|
||||
}
|
||||
if (command == "show") {
|
||||
return show_certificate(arguments);
|
||||
}
|
||||
if (command == "verify-chain") {
|
||||
return verify_chain(arguments);
|
||||
}
|
||||
throw std::invalid_argument("unknown command: " + command);
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Error: " << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
if(NOT CERTIFY OR NOT CERTIFY_PQC OR NOT WORK_DIRECTORY)
|
||||
message(FATAL_ERROR "CERTIFY, CERTIFY_PQC and WORK_DIRECTORY are required")
|
||||
endif()
|
||||
|
||||
file(REMOVE_RECURSE "${WORK_DIRECTORY}")
|
||||
file(MAKE_DIRECTORY "${WORK_DIRECTORY}")
|
||||
|
||||
function(run)
|
||||
execute_process(
|
||||
COMMAND ${ARGV}
|
||||
WORKING_DIRECTORY "${WORK_DIRECTORY}"
|
||||
RESULT_VARIABLE result
|
||||
OUTPUT_VARIABLE output
|
||||
ERROR_VARIABLE error)
|
||||
if(NOT result EQUAL 0)
|
||||
string(JOIN " " command ${ARGV})
|
||||
message(FATAL_ERROR "Command failed (${result}): ${command}\n${output}${error}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(run_fails)
|
||||
execute_process(
|
||||
COMMAND ${ARGV}
|
||||
WORKING_DIRECTORY "${WORK_DIRECTORY}"
|
||||
RESULT_VARIABLE result
|
||||
OUTPUT_VARIABLE output
|
||||
ERROR_VARIABLE error)
|
||||
if(result EQUAL 0)
|
||||
string(JOIN " " command ${ARGV})
|
||||
message(FATAL_ERROR "Command unexpectedly succeeded: ${command}\n${output}${error}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(check_show certificate material public_key_size signature_size)
|
||||
execute_process(
|
||||
COMMAND "${CERTIFY_PQC}" show "${certificate}"
|
||||
WORKING_DIRECTORY "${WORK_DIRECTORY}"
|
||||
RESULT_VARIABLE result
|
||||
OUTPUT_VARIABLE output
|
||||
ERROR_VARIABLE error)
|
||||
if(NOT result EQUAL 0)
|
||||
message(FATAL_ERROR "Cannot inspect ${certificate}:\n${output}${error}")
|
||||
endif()
|
||||
|
||||
set(expectations
|
||||
"Alternative material: ${material}"
|
||||
"FN-DSA-512 public key: ${public_key_size} bytes"
|
||||
"FN-DSA-512 signature: ${signature_size} bytes")
|
||||
foreach(expectation IN LISTS expectations)
|
||||
string(FIND "${output}" "${expectation}" position)
|
||||
if(position EQUAL -1)
|
||||
message(FATAL_ERROR
|
||||
"Unexpected material in ${certificate}: missing '${expectation}'\n${output}")
|
||||
endif()
|
||||
endforeach()
|
||||
endfunction()
|
||||
|
||||
run("${CERTIFY}" generate-key root.key)
|
||||
run("${CERTIFY}" generate-key aa.key)
|
||||
run("${CERTIFY}" generate-key ticket.key)
|
||||
run("${CERTIFY_PQC}" generate-key root)
|
||||
run("${CERTIFY_PQC}" generate-key aa)
|
||||
|
||||
run("${CERTIFY_PQC}" generate-root
|
||||
--profile ecc --output ecc-root.cert --subject-key root.key --days 365
|
||||
--aid 36 141)
|
||||
run("${CERTIFY_PQC}" generate-aa
|
||||
--profile ecc --output ecc-aa.cert
|
||||
--sign-key root.key --sign-cert ecc-root.cert
|
||||
--subject-key aa.key --days 180
|
||||
--aid 36 141)
|
||||
run("${CERTIFY_PQC}" generate-ticket
|
||||
--profile ecc --output ecc-ticket.cert
|
||||
--sign-key aa.key --sign-cert ecc-aa.cert
|
||||
--subject-key ticket.key --days 7
|
||||
--aid 141)
|
||||
run("${CERTIFY_PQC}" verify-chain --profile ecc
|
||||
--root ecc-root.cert --aa ecc-aa.cert --ticket ecc-ticket.cert --aid 141)
|
||||
check_show(ecc-root.cert "none" 0 0)
|
||||
check_show(ecc-aa.cert "none" 0 0)
|
||||
check_show(ecc-ticket.cert "none" 0 0)
|
||||
|
||||
run("${CERTIFY_PQC}" generate-root
|
||||
--output root.cert --subject-key root.key --subject-pqc-key root --days 365
|
||||
--aid 36 141)
|
||||
run("${CERTIFY_PQC}" generate-aa
|
||||
--output aa.cert
|
||||
--sign-key root.key --sign-cert root.cert --sign-pqc-key root
|
||||
--subject-key aa.key --subject-pqc-key aa --days 180
|
||||
--aid 36 141)
|
||||
run("${CERTIFY_PQC}" generate-ticket
|
||||
--output ticket.cert
|
||||
--sign-key aa.key --sign-cert aa.cert --sign-pqc-key aa
|
||||
--subject-key ticket.key --days 7
|
||||
--aid 141)
|
||||
run("${CERTIFY_PQC}" verify-chain
|
||||
--root root.cert --aa aa.cert --ticket ticket.cert --aid 141)
|
||||
check_show(root.cert "authority (key + signature)" 897 666)
|
||||
check_show(aa.cert "authority (key + signature)" 897 666)
|
||||
check_show(ticket.cert "end entity (signature only)" 0 666)
|
||||
|
||||
run_fails("${CERTIFY_PQC}" verify-chain --profile hybrid
|
||||
--root ecc-root.cert --aa ecc-aa.cert --ticket ecc-ticket.cert --aid 141)
|
||||
run_fails("${CERTIFY_PQC}" verify-chain --profile ecc
|
||||
--root root.cert --aa aa.cert --ticket ticket.cert --aid 141)
|
||||
@@ -0,0 +1,24 @@
|
||||
if(NOT TARGET Boost::program_options)
|
||||
message(STATUS "Skip build of certify because of missing Boost::program_options dependency")
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(NOT TARGET CryptoPP::CryptoPP)
|
||||
message(STATUS "Skip build of certify because of missing CryptoPP dependency")
|
||||
return()
|
||||
endif()
|
||||
|
||||
add_executable(certify
|
||||
commands/extract-public-key.cpp
|
||||
commands/generate-aa.cpp
|
||||
commands/generate-key.cpp
|
||||
commands/generate-root.cpp
|
||||
commands/generate-ticket.cpp
|
||||
commands/show-certificate.cpp
|
||||
main.cpp
|
||||
options.cpp
|
||||
utils.cpp
|
||||
)
|
||||
|
||||
target_include_directories(certify PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(certify Boost::program_options vanetza)
|
||||
@@ -0,0 +1 @@
|
||||
Content of this readme file has been moved to our [documentation](https://www.vanetza.org/tools/certify).
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef CERTIFY_COMMAND_HPP
|
||||
#define CERTIFY_COMMAND_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Command
|
||||
{
|
||||
public:
|
||||
virtual int execute() = 0;
|
||||
virtual bool parse(const std::vector<std::string>&) = 0;
|
||||
virtual ~Command() = default;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMAND_HPP */
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#include "extract-public-key.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza::security;
|
||||
|
||||
bool ExtractPublicKeyCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("output", po::value<std::string>(&output)->required(), "Output file.")
|
||||
("certificate", po::value<std::string>(&certificate_path), "Certificate file to extract public key from.")
|
||||
("private-key", po::value<std::string>(&private_key_path), "Private key file to extract public key from.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("output", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
|
||||
if (!(vm.count("certificate") ^ vm.count("private-key"))) {
|
||||
std::cerr << "Error: One of certificate / private-key parameters must be present." << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int ExtractPublicKeyCommand::execute()
|
||||
{
|
||||
std::cout << "Loading key... ";
|
||||
|
||||
std::unique_ptr<Backend> backend = create_backend("default");
|
||||
ecdsa256::PublicKey public_key;
|
||||
if (certificate_path.length() > 0) {
|
||||
auto certificate = v2::load_certificate_from_file(certificate_path);
|
||||
auto certificate_key = get_public_key(certificate, *backend);
|
||||
|
||||
if (!certificate_key) {
|
||||
std::cerr << "Reading public key from certificate failed." << std::endl;
|
||||
}
|
||||
|
||||
public_key = *certificate_key;
|
||||
} else {
|
||||
auto private_key = v2::load_private_key_from_file(private_key_path);
|
||||
public_key = private_key.public_key;
|
||||
}
|
||||
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
Uncompressed coordinates;
|
||||
coordinates.x.assign(public_key.x.begin(), public_key.x.end());
|
||||
coordinates.y.assign(public_key.y.begin(), public_key.y.end());
|
||||
|
||||
v2::ecdsa_nistp256_with_sha256 public_key_etsi;
|
||||
public_key_etsi.public_key = coordinates;
|
||||
|
||||
std::cout << "Writing public key to '" << output << "'... ";
|
||||
v2::save_public_key_to_file(output, public_key_etsi);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
#ifndef CERTIFY_COMMANDS_EXTRACT_PUBLIC_KEY_HPP
|
||||
#define CERTIFY_COMMANDS_EXTRACT_PUBLIC_KEY_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class ExtractPublicKeyCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string output;
|
||||
std::string certificate_path;
|
||||
std::string private_key_path;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_EXTRACT_PUBLIC_KEY_HPP */
|
||||
@@ -0,0 +1,138 @@
|
||||
#include "generate-aa.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <boost/variant/get.hpp>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v2/certificate.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
#include <vanetza/security/v2/subject_attribute.hpp>
|
||||
#include <vanetza/security/v2/subject_info.hpp>
|
||||
|
||||
namespace aid = vanetza::aid;
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza::security;
|
||||
using namespace vanetza::security::v2;
|
||||
|
||||
bool GenerateAaCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("output", po::value<std::string>(&output)->required(), "Output file.")
|
||||
("sign-key", po::value<std::string>(&sign_key_path)->required(), "Private key file of the signer.")
|
||||
("sign-cert", po::value<std::string>(&sign_cert_path)->required(), "Private certificate file of the signer.")
|
||||
("subject-key", po::value<std::string>(&subject_key_path)->required(), "Private key file to issue the certificate for.")
|
||||
("subject-name", po::value<std::string>(&subject_name)->default_value("Hello World Auth-CA"), "Subject name.")
|
||||
("days", po::value<int>(&validity_days)->default_value(180), "Validity in days.")
|
||||
("aid", po::value<std::vector<unsigned> >(&aids)->multitoken(), "Allowed ITS-AIDs to restrict permissions, defaults to 36 (CA) and 37 (DEN) if empty.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("output", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int GenerateAaCommand::execute()
|
||||
{
|
||||
auto backend = create_backend_or_throw("default");
|
||||
|
||||
std::cout << "Loading keys... ";
|
||||
auto sign_key = v2::load_private_key_from_file(sign_key_path);
|
||||
ecdsa256::PublicKey subject_key;
|
||||
try {
|
||||
auto subject_private_key = v2::load_private_key_from_file(subject_key_path);
|
||||
subject_key = subject_private_key.public_key;
|
||||
} catch (std::exception& e) {
|
||||
auto subject_key_etsi = v2::load_public_key_from_file(subject_key_path);
|
||||
if (get_type(subject_key_etsi) != PublicKeyAlgorithm::ECDSA_NISTP256_With_SHA256) {
|
||||
std::cerr << "Wrong public key algorithm." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto subject_key_etsi_ecdsa = boost::get<ecdsa_nistp256_with_sha256>(subject_key_etsi);
|
||||
auto uncompressed_subject_ecc_point = backend->decompress_point(subject_key_etsi_ecdsa.public_key);
|
||||
if (!uncompressed_subject_ecc_point) {
|
||||
std::cerr << "Cannot get uncompressed ECC point from public key.";
|
||||
return 1;
|
||||
} else {
|
||||
subject_key = ecdsa256::create_public_key(*uncompressed_subject_ecc_point);
|
||||
}
|
||||
}
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
Certificate sign_cert = v2::load_certificate_from_file(sign_cert_path);
|
||||
|
||||
auto time_now = vanetza::Clock::at(boost::posix_time::microsec_clock::universal_time());
|
||||
|
||||
Certificate certificate;
|
||||
std::list<v2::IntX> certificate_aids;
|
||||
|
||||
if (aids.size()) {
|
||||
for (unsigned aid : aids) {
|
||||
certificate_aids.push_back(v2::IntX(aid));
|
||||
}
|
||||
} else {
|
||||
certificate_aids.push_back(v2::IntX(aid::CA));
|
||||
certificate_aids.push_back(v2::IntX(aid::DEN));
|
||||
}
|
||||
certificate.subject_attributes.push_back(certificate_aids);
|
||||
|
||||
certificate.signer_info = calculate_hash(sign_cert);
|
||||
|
||||
std::vector<unsigned char> subject(subject_name.begin(), subject_name.end());
|
||||
certificate.subject_info.subject_name = subject;
|
||||
certificate.subject_info.subject_type = SubjectType::Authorization_Authority;
|
||||
certificate.subject_attributes.push_back(SubjectAssurance(0x00));
|
||||
|
||||
Uncompressed coordinates;
|
||||
coordinates.x.assign(subject_key.x.begin(), subject_key.x.end());
|
||||
coordinates.y.assign(subject_key.y.begin(), subject_key.y.end());
|
||||
EccPoint ecc_point = coordinates;
|
||||
ecdsa_nistp256_with_sha256 ecdsa;
|
||||
ecdsa.public_key = ecc_point;
|
||||
VerificationKey verification_key;
|
||||
verification_key.key = ecdsa;
|
||||
certificate.subject_attributes.push_back(verification_key);
|
||||
|
||||
StartAndEndValidity start_and_end;
|
||||
start_and_end.start_validity = convert_time32(time_now - std::chrono::hours(1));
|
||||
start_and_end.end_validity = convert_time32(time_now + std::chrono::hours(24 * validity_days));
|
||||
certificate.validity_restriction.push_back(start_and_end);
|
||||
|
||||
std::cout << "Signing certificate... ";
|
||||
|
||||
sort(certificate);
|
||||
auto data_buffer = convert_for_signing(certificate);
|
||||
certificate.signature = backend->sign_data(sign_key.private_key, data_buffer);
|
||||
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
std::cout << "Writing certificate to '" << output << "'... ";
|
||||
save_certificate_to_file(output, certificate);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#ifndef CERTIFY_COMMANDS_GENERATE_AA_HPP
|
||||
#define CERTIFY_COMMANDS_GENERATE_AA_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class GenerateAaCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string output;
|
||||
std::string sign_key_path;
|
||||
std::string sign_cert_path;
|
||||
std::string subject_key_path;
|
||||
std::string subject_name;
|
||||
int validity_days;
|
||||
std::vector<unsigned> aids;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_GENERATE_AA_HPP */
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "generate-key.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vanetza/security/backend.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza::security;
|
||||
|
||||
bool GenerateKeyCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("output", po::value<std::string>(&output)->required(), "Output file.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("output", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int GenerateKeyCommand::execute()
|
||||
{
|
||||
auto backend = create_backend_or_throw("default");
|
||||
|
||||
std::cout << "Generating key... ";
|
||||
auto key_pair = backend->generate_key_pair();
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
std::cout << "Writing key to '" << output << "'... ";
|
||||
std::ofstream ofs(output, std::ios::binary);
|
||||
v2::save_private_key_pkcs8_der(ofs, key_pair);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#ifndef CERTIFY_COMMANDS_GENERATE_KEY_HPP
|
||||
#define CERTIFY_COMMANDS_GENERATE_KEY_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class GenerateKeyCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string output;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_GENERATE_KEY_HPP */
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
#include "generate-root.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/backend_cryptopp.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v2/certificate.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
#include <vanetza/security/v2/subject_attribute.hpp>
|
||||
#include <vanetza/security/v2/subject_info.hpp>
|
||||
|
||||
namespace aid = vanetza::aid;
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza::security;
|
||||
|
||||
bool GenerateRootCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("output", po::value<std::string>(&output)->required(), "Output file.")
|
||||
("subject-key", po::value<std::string>(&subject_key_path)->required(), "Private key file.")
|
||||
("subject-name", po::value<std::string>(&subject_name)->default_value("Hello World Root-CA"), "Subject name.")
|
||||
("days", po::value<int>(&validity_days)->default_value(365), "Validity in days.")
|
||||
("aid", po::value<std::vector<unsigned> >(&aids)->multitoken(), "Allowed ITS-AIDs to restrict permissions, defaults to 36 (CA) and 37 (DEN) if empty.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("output", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int GenerateRootCommand::execute()
|
||||
{
|
||||
auto backend = create_backend_or_throw("default");
|
||||
|
||||
std::cout << "Loading key... ";
|
||||
auto subject_key = v2::load_private_key_from_file(subject_key_path);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
auto time_now = vanetza::Clock::at(boost::posix_time::microsec_clock::universal_time());
|
||||
|
||||
// create certificate
|
||||
v2::Certificate certificate;
|
||||
std::list<v2::IntX> certificate_aids;
|
||||
|
||||
if (aids.size()) {
|
||||
for (unsigned aid : aids) {
|
||||
certificate_aids.push_back(v2::IntX(aid));
|
||||
}
|
||||
} else {
|
||||
certificate_aids.push_back(v2::IntX(aid::CA));
|
||||
certificate_aids.push_back(v2::IntX(aid::DEN));
|
||||
}
|
||||
certificate.subject_attributes.push_back(certificate_aids);
|
||||
|
||||
// section 6.1 in TS 103 097 v1.2.1
|
||||
certificate.signer_info = nullptr; /* self */
|
||||
|
||||
// section 6.3 in TS 103 097 v1.2.1
|
||||
certificate.subject_info.subject_type = v2::SubjectType::Root_CA;
|
||||
|
||||
// section 7.4.2 in TS 103 097 v1.2.1
|
||||
std::vector<unsigned char> subject(subject_name.begin(), subject_name.end());
|
||||
certificate.subject_info.subject_name = subject;
|
||||
|
||||
// section 6.6 in TS 103 097 v1.2.1 - levels currently undefined
|
||||
certificate.subject_attributes.push_back(v2::SubjectAssurance(0x00));
|
||||
|
||||
// section 7.4.1 in TS 103 097 v1.2.1
|
||||
// set subject attributes
|
||||
// set the verification_key
|
||||
Uncompressed coordinates;
|
||||
coordinates.x.assign(subject_key.public_key.x.begin(), subject_key.public_key.x.end());
|
||||
coordinates.y.assign(subject_key.public_key.y.begin(), subject_key.public_key.y.end());
|
||||
EccPoint ecc_point = coordinates;
|
||||
v2::ecdsa_nistp256_with_sha256 ecdsa;
|
||||
ecdsa.public_key = ecc_point;
|
||||
v2::VerificationKey verification_key;
|
||||
verification_key.key = ecdsa;
|
||||
certificate.subject_attributes.push_back(verification_key);
|
||||
|
||||
// section 6.7 in TS 103 097 v1.2.1
|
||||
// set validity restriction
|
||||
v2::StartAndEndValidity start_and_end;
|
||||
start_and_end.start_validity = v2::convert_time32(time_now - std::chrono::hours(1));
|
||||
start_and_end.end_validity = v2::convert_time32(time_now + std::chrono::hours(24 * validity_days));
|
||||
certificate.validity_restriction.push_back(start_and_end);
|
||||
|
||||
std::cout << "Signing certificate... ";
|
||||
|
||||
sort(certificate);
|
||||
vanetza::ByteBuffer data_buffer = convert_for_signing(certificate);
|
||||
certificate.signature = backend->sign_data(subject_key.private_key, data_buffer);
|
||||
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
std::cout << "Writing certificate to '" << output << "'... ";
|
||||
save_certificate_to_file(output, certificate);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#ifndef CERTIFY_COMMANDS_GENERATE_ROOT_HPP
|
||||
#define CERTIFY_COMMANDS_GENERATE_ROOT_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class GenerateRootCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string subject_key_path;
|
||||
std::string output;
|
||||
std::string subject_name;
|
||||
int validity_days;
|
||||
std::vector<unsigned> aids;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_GENERATE_ROOT_HPP */
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
#include "generate-ticket.hpp"
|
||||
#include "utils.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <boost/variant/get.hpp>
|
||||
#include <cryptopp/cryptlib.h>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/backend_cryptopp.hpp>
|
||||
#include <vanetza/security/v2/basic_elements.hpp>
|
||||
#include <vanetza/security/v2/certificate.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
#include <vanetza/security/v2/subject_attribute.hpp>
|
||||
#include <vanetza/security/v2/subject_info.hpp>
|
||||
|
||||
namespace aid = vanetza::aid;
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza::security;
|
||||
|
||||
bool GenerateTicketCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("output", po::value<std::string>(&output)->required(), "Output file.")
|
||||
("sign-key", po::value<std::string>(&sign_key_path)->required(), "Private key file of the signer.")
|
||||
("sign-cert", po::value<std::string>(&sign_cert_path)->required(), "Private certificate file of the signer.")
|
||||
("subject-key", po::value<std::string>(&subject_key_path)->required(), "Private key file to issue the certificate for.")
|
||||
("days", po::value<int>(&validity_days)->default_value(7), "Validity in days.")
|
||||
("cam-permissions", po::value<std::string>(&cam_permissions), "CAM permissions as binary string (e.g. '1111111111111100' to grant all SSPs)")
|
||||
("denm-permissions", po::value<std::string>(&denm_permissions), "DENM permissions as binary string (e.g. '000000000000000000000000' to grant no SSPs)")
|
||||
("permit-gn-mgmt", po::bool_switch(&permit_gn_mgmt), "Generated ticket can be used to sign GN-MGMT messages (e.g. beacons).")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("output", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int GenerateTicketCommand::execute()
|
||||
{
|
||||
auto backend = create_backend_or_throw("default");
|
||||
|
||||
std::cout << "Loading keys... ";
|
||||
auto sign_key = v2::load_private_key_from_file(sign_key_path);
|
||||
ecdsa256::PublicKey subject_key;
|
||||
try {
|
||||
auto subject_private_key = v2::load_private_key_from_file(subject_key_path);
|
||||
subject_key = subject_private_key.public_key;
|
||||
} catch (CryptoPP::BERDecodeErr& e) {
|
||||
auto subject_key_etsi = v2::load_public_key_from_file(subject_key_path);
|
||||
if (v2::get_type(subject_key_etsi) != v2::PublicKeyAlgorithm::ECDSA_NISTP256_With_SHA256) {
|
||||
std::cerr << "Wrong public key algorithm." << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto subject_key_etsi_ecdsa = boost::get<v2::ecdsa_nistp256_with_sha256>(subject_key_etsi);
|
||||
if (v2::get_type(subject_key_etsi_ecdsa.public_key) != v2::EccPointType::Uncompressed) {
|
||||
std::cerr << "Unsupported ECC point type, must be uncompressed.";
|
||||
return 1;
|
||||
}
|
||||
|
||||
subject_key = ecdsa256::create_public_key(boost::get<Uncompressed>(subject_key_etsi_ecdsa.public_key));
|
||||
}
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
auto sign_cert = v2::load_certificate_from_file(sign_cert_path);
|
||||
auto time_now = vanetza::Clock::at(boost::posix_time::microsec_clock::universal_time());
|
||||
|
||||
auto cam_ssps = vanetza::ByteBuffer({ 1, 0, 0 }); // no special permissions
|
||||
auto denm_ssps = vanetza::ByteBuffer({ 1, 0, 0, 0 }); // no special permissions
|
||||
|
||||
if (cam_permissions.size()) {
|
||||
permission_string_to_buffer(cam_permissions, cam_ssps);
|
||||
}
|
||||
|
||||
if (denm_permissions.size()) {
|
||||
permission_string_to_buffer(denm_permissions, denm_ssps);
|
||||
}
|
||||
|
||||
v2::Certificate certificate;
|
||||
std::list<v2::ItsAidSsp> certificate_ssp;
|
||||
|
||||
// see ETSI EN 302 637-2 V1.3.1 (2014-09)
|
||||
v2::ItsAidSsp certificate_ssp_ca;
|
||||
certificate_ssp_ca.its_aid = v2::IntX(aid::CA);
|
||||
certificate_ssp_ca.service_specific_permissions = cam_ssps;
|
||||
certificate_ssp.push_back(certificate_ssp_ca);
|
||||
|
||||
// see ETSI EN 302 637-3 V1.2.2 (2014-11)
|
||||
v2::ItsAidSsp certificate_ssp_den;
|
||||
certificate_ssp_den.its_aid = v2::IntX(aid::DEN);
|
||||
certificate_ssp_den.service_specific_permissions = denm_ssps;
|
||||
certificate_ssp.push_back(certificate_ssp_den);
|
||||
|
||||
if (permit_gn_mgmt) {
|
||||
certificate_ssp.push_back({v2::IntX(aid::GN_MGMT), vanetza::ByteBuffer{}});
|
||||
}
|
||||
|
||||
certificate.signer_info = calculate_hash(sign_cert);
|
||||
certificate.subject_info.subject_type = v2::SubjectType::Authorization_Ticket;
|
||||
certificate.subject_attributes.push_back(v2::SubjectAssurance(0x00));
|
||||
certificate.subject_attributes.push_back(certificate_ssp);
|
||||
|
||||
Uncompressed coordinates;
|
||||
coordinates.x.assign(subject_key.x.begin(), subject_key.x.end());
|
||||
coordinates.y.assign(subject_key.y.begin(), subject_key.y.end());
|
||||
EccPoint ecc_point = coordinates;
|
||||
v2::ecdsa_nistp256_with_sha256 ecdsa;
|
||||
ecdsa.public_key = ecc_point;
|
||||
v2::VerificationKey verification_key;
|
||||
verification_key.key = ecdsa;
|
||||
certificate.subject_attributes.push_back(verification_key);
|
||||
|
||||
v2::StartAndEndValidity start_and_end;
|
||||
start_and_end.start_validity = v2::convert_time32(time_now - std::chrono::hours(1));
|
||||
start_and_end.end_validity = v2::convert_time32(time_now + std::chrono::hours(24 * validity_days));
|
||||
certificate.validity_restriction.push_back(start_and_end);
|
||||
|
||||
std::cout << "Signing certificate... ";
|
||||
|
||||
sort(certificate);
|
||||
auto data_buffer = convert_for_signing(certificate);
|
||||
certificate.signature = backend->sign_data(sign_key.private_key, data_buffer);
|
||||
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
std::cout << "Writing certificate to '" << output << "'... ";
|
||||
save_certificate_to_file(output, certificate);
|
||||
std::cout << "OK" << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
#ifndef CERTIFY_COMMANDS_GENERATE_TICKET_HPP
|
||||
#define CERTIFY_COMMANDS_GENERATE_TICKET_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class GenerateTicketCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string output;
|
||||
std::string sign_key_path;
|
||||
std::string sign_cert_path;
|
||||
std::string subject_key_path;
|
||||
int validity_days;
|
||||
std::string cam_permissions;
|
||||
std::string denm_permissions;
|
||||
bool permit_gn_mgmt = false;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_GENERATE_TICKET_HPP */
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
#include "show-certificate.hpp"
|
||||
#include <boost/algorithm/hex.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/program_options.hpp>
|
||||
#include <boost/variant.hpp>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/cam_ssp.hpp>
|
||||
#include <vanetza/security/v2/certificate.hpp>
|
||||
#include <vanetza/security/v2/ecc_point.hpp>
|
||||
#include <vanetza/security/v2/persistence.hpp>
|
||||
#include <vanetza/security/v2/public_key.hpp>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
using namespace vanetza;
|
||||
using namespace vanetza::security;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string hex_buffer(const ByteBuffer& buffer)
|
||||
{
|
||||
std::string bytes(buffer.begin(), buffer.end());
|
||||
return boost::algorithm::hex(bytes);
|
||||
}
|
||||
|
||||
void print_ecc_point(const EccPoint& point, const std::string& indent)
|
||||
{
|
||||
switch (v2::get_type(point)) {
|
||||
case v2::EccPointType::X_Coordinate_Only:
|
||||
std::cout << indent << "X: " << hex_buffer(boost::get<X_Coordinate_Only>(point).x)
|
||||
<< " (x-coordinate only)" << std::endl;
|
||||
break;
|
||||
case v2::EccPointType::Compressed_Lsb_Y_0:
|
||||
std::cout << indent << "X: " << hex_buffer(boost::get<Compressed_Lsb_Y_0>(point).x)
|
||||
<< " (compressed, y LSB 0)" << std::endl;
|
||||
break;
|
||||
case v2::EccPointType::Compressed_Lsb_Y_1:
|
||||
std::cout << indent << "X: " << hex_buffer(boost::get<Compressed_Lsb_Y_1>(point).x)
|
||||
<< " (compressed, y LSB 1)" << std::endl;
|
||||
break;
|
||||
case v2::EccPointType::Uncompressed: {
|
||||
const Uncompressed& uncompressed = boost::get<Uncompressed>(point);
|
||||
std::cout << indent << "X: " << hex_buffer(uncompressed.x) << std::endl;
|
||||
std::cout << indent << "Y: " << hex_buffer(uncompressed.y) << " (uncompressed)" << std::endl;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void print_public_key(const v2::PublicKey& key, const std::string& indent)
|
||||
{
|
||||
switch (v2::get_type(key)) {
|
||||
case v2::PublicKeyAlgorithm::ECDSA_NISTP256_With_SHA256:
|
||||
std::cout << indent << "Algorithm: ECDSA NISTP256 with SHA-256" << std::endl;
|
||||
print_ecc_point(boost::get<v2::ecdsa_nistp256_with_sha256>(key).public_key, indent);
|
||||
break;
|
||||
case v2::PublicKeyAlgorithm::ECIES_NISTP256:
|
||||
std::cout << indent << "Algorithm: ECIES NISTP256" << std::endl;
|
||||
print_ecc_point(boost::get<v2::ecies_nistp256>(key).public_key, indent);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ShowCertificateCommand::parse(const std::vector<std::string>& opts)
|
||||
{
|
||||
po::options_description desc("Available options");
|
||||
desc.add_options()
|
||||
("help", "Print out available options.")
|
||||
("certificate", po::value<std::string>(&certificate_path)->required(), "Certificate to show.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("certificate", 1);
|
||||
|
||||
po::variables_map vm;
|
||||
po::store(po::command_line_parser(opts).options(desc).positional(pos).run(), vm);
|
||||
|
||||
if (vm.count("help")) {
|
||||
std::cerr << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
po::notify(vm);
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int ShowCertificateCommand::execute()
|
||||
{
|
||||
v2::Certificate cert = v2::load_certificate_from_file(certificate_path);
|
||||
|
||||
// subject info
|
||||
|
||||
std::cout << "Subject: ";
|
||||
|
||||
if (cert.subject_info.subject_type == v2::SubjectType::Enrollment_Credential) {
|
||||
std::cout << "Enrollment Credential";
|
||||
} else if (cert.subject_info.subject_type == v2::SubjectType::Authorization_Ticket) {
|
||||
std::cout << "Authorization Ticket";
|
||||
} else if (cert.subject_info.subject_type == v2::SubjectType::Authorization_Authority) {
|
||||
std::cout << "Authorization Authority";
|
||||
} else if (cert.subject_info.subject_type == v2::SubjectType::Enrollment_Authority) {
|
||||
std::cout << "Enrollment Authority";
|
||||
} else if (cert.subject_info.subject_type == v2::SubjectType::Root_CA) {
|
||||
std::cout << "Root Authority";
|
||||
} else if (cert.subject_info.subject_type == v2::SubjectType::CRL_Signer) {
|
||||
std::cout << "CRL Signer";
|
||||
}
|
||||
|
||||
if (cert.subject_info.subject_name.size() > 0) {
|
||||
std::string subject_name(reinterpret_cast<const char*>(&cert.subject_info.subject_name[0]), cert.subject_info.subject_name.size());
|
||||
std::cout << " (" << subject_name << ")";
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
{
|
||||
HashedId8 cert_id = calculate_hash(cert);
|
||||
std::string cert_id_string(reinterpret_cast<const char*>(&cert_id[0]), cert_id.size());
|
||||
std::cout << "Digest: " << boost::algorithm::hex(cert_id_string) << " (SHA-256)" << std::endl;
|
||||
}
|
||||
|
||||
// signer info
|
||||
|
||||
std::cout << "Signer: ";
|
||||
|
||||
v2::SignerInfoType signer_type = get_type(cert.signer_info);
|
||||
|
||||
if (signer_type == v2::SignerInfoType::Self) {
|
||||
std::cout << "Self-Signed";
|
||||
} else if (signer_type == v2::SignerInfoType::Certificate_Digest_With_SHA256) {
|
||||
HashedId8 signer = boost::get<HashedId8>(cert.signer_info);
|
||||
std::string signer_id(reinterpret_cast<const char*>(&signer[0]), signer.size());
|
||||
std::cout << boost::algorithm::hex(signer_id) << " (SHA-256)";
|
||||
} else {
|
||||
std::cout << "Unknown (" << static_cast<int>(signer_type) << ")";
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
// subject attributes
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
unsigned certificate_application_ids = 0;
|
||||
|
||||
for (auto& subject_attr : cert.subject_attributes) {
|
||||
v2::SubjectAttributeType attr_type = get_type(subject_attr);
|
||||
if (attr_type == v2::SubjectAttributeType::Verification_Key) {
|
||||
std::cout << "Verification Key:" << std::endl;
|
||||
print_public_key(boost::get<v2::VerificationKey>(subject_attr).key, " - ");
|
||||
std::cout << std::endl;
|
||||
} else if (attr_type == v2::SubjectAttributeType::Encryption_Key) {
|
||||
std::cout << "Encryption Key:" << std::endl;
|
||||
print_public_key(boost::get<v2::EncryptionKey>(subject_attr).key, " - ");
|
||||
std::cout << std::endl;
|
||||
} else if (attr_type == v2::SubjectAttributeType::Reconstruction_Value) {
|
||||
std::cout << "Reconstruction Value:" << std::endl;
|
||||
print_ecc_point(boost::get<EccPoint>(subject_attr), " - ");
|
||||
std::cout << std::endl;
|
||||
} else if (attr_type == v2::SubjectAttributeType::Assurance_Level) {
|
||||
v2::SubjectAssurance assurance = boost::get<v2::SubjectAssurance>(subject_attr);
|
||||
std::cout << "Assurance: " << (assurance.raw & assurance.assurance_mask);
|
||||
std::cout << " with a confidence of " << (assurance.raw & assurance.confidence_mask);
|
||||
std::cout << std::endl << std::endl;
|
||||
} else if (attr_type == v2::SubjectAttributeType::ITS_AID_List) {
|
||||
std::list<v2::IntX> its_application_ids = boost::get<std::list<v2::IntX>>(subject_attr);
|
||||
|
||||
std::cout << "ITS Application IDs:" << std::endl;
|
||||
if (its_application_ids.size() == 0) {
|
||||
std::cout << "None";
|
||||
} else {
|
||||
for (auto& its_application_id : its_application_ids) {
|
||||
certificate_application_ids++;
|
||||
|
||||
std::cout << " - ";
|
||||
if (its_application_id == aid::CA) {
|
||||
std::cout << "36 (CA-Basic service)";
|
||||
} else if (its_application_id == aid::DEN) {
|
||||
std::cout << "37 (DEN-Basic service)";
|
||||
} else {
|
||||
std::cout << its_application_id.get();
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
std::cout << std::endl;
|
||||
} else if (attr_type == v2::SubjectAttributeType::ITS_AID_SSP_List) {
|
||||
std::list<v2::ItsAidSsp> its_service_specific_permissions = boost::get<std::list<v2::ItsAidSsp>>(subject_attr);
|
||||
for (auto& its_ssp : its_service_specific_permissions) {
|
||||
if (its_ssp.its_aid == aid::CA) {
|
||||
std::cout << "CA - ITS Service Specific Permissions:" << std::endl;
|
||||
ByteBuffer& ssp = its_ssp.service_specific_permissions;
|
||||
|
||||
if (ssp.size() == 0) {
|
||||
std::cerr << "Invalid service specific permissions for CA" << std::endl;
|
||||
continue;
|
||||
}
|
||||
|
||||
// See final draft ETSI EN 302 637-2 V1.3.1 (2014-09)
|
||||
if (ssp[0] == 0) {
|
||||
if (ssp.size() != 1) {
|
||||
std::cout << " - Warning: Length of SSP is expected to be 1, but was " << ssp.size() << std::endl;
|
||||
} else {
|
||||
std::cout << " - No version, shall be used only for testing." << std::endl;
|
||||
}
|
||||
} else if (ssp[0] == 1) {
|
||||
if (ssp.size() != 3) {
|
||||
std::cout << " - Warning: Length of SSP is expected to be 3, but was " << ssp.size() << std::endl;
|
||||
} else {
|
||||
CamPermissions ssp_decoded = CamPermissions::decode(ssp);
|
||||
for (auto permission : ssp_decoded.permissions()) {
|
||||
std::cout << " - " << stringify(permission) << "\n";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::cout << " - Reserved for future usage and not implemented." << std::endl;
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (certificate_application_ids == 0) {
|
||||
std::cout << "Warning: Certificate doesn't contain any application IDs." << std::endl << std::endl;
|
||||
}
|
||||
|
||||
// validity restrictions
|
||||
|
||||
const boost::posix_time::ptime epoch {
|
||||
boost::gregorian::date(2004, 1, 1),
|
||||
boost::posix_time::milliseconds(0)
|
||||
};
|
||||
|
||||
unsigned certificate_time_constraints = 0;
|
||||
|
||||
for (auto& validity_restriction : cert.validity_restriction) {
|
||||
v2::ValidityRestrictionType restriction_type = get_type(validity_restriction);
|
||||
if (restriction_type == v2::ValidityRestrictionType::Time_End) {
|
||||
certificate_time_constraints++;
|
||||
|
||||
boost::posix_time::ptime time_end = epoch + boost::posix_time::seconds(boost::get<v2::EndValidity>(validity_restriction));
|
||||
std::cout << "Validity ends " << time_end << std::endl;
|
||||
} else if (restriction_type == v2::ValidityRestrictionType::Time_Start_And_End) {
|
||||
certificate_time_constraints++;
|
||||
|
||||
v2::StartAndEndValidity start_and_end = boost::get<v2::StartAndEndValidity>(validity_restriction);
|
||||
boost::posix_time::ptime time_start = epoch + boost::posix_time::seconds(start_and_end.start_validity);
|
||||
boost::posix_time::ptime time_end = epoch + boost::posix_time::seconds(start_and_end.end_validity);
|
||||
std::cout << "Validity starts " << time_start << " and ends " << time_end << std::endl;
|
||||
} else if (restriction_type == v2::ValidityRestrictionType::Time_Start_And_Duration) {
|
||||
certificate_time_constraints++;
|
||||
|
||||
v2::StartAndDurationValidity start_and_duration = boost::get<v2::StartAndDurationValidity>(validity_restriction);
|
||||
boost::posix_time::ptime time_start = epoch + boost::posix_time::seconds(start_and_duration.start_validity);
|
||||
boost::posix_time::ptime time_end = epoch + boost::posix_time::seconds(start_and_duration.duration.to_seconds().count());
|
||||
std::cout << "Validity starts " << time_start << " and ends " << time_end << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
if (certificate_time_constraints == 0) {
|
||||
std::cout << "Warning: Certificate doesn't have any time based validity restriction." << std::endl;
|
||||
} else if (certificate_time_constraints > 1) {
|
||||
std::cout << "Warning: Certificate has multiple time based validity restrictions." << std::endl;
|
||||
}
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
bool certificate_region_constraints = false;
|
||||
|
||||
for (auto& validity_restriction : cert.validity_restriction) {
|
||||
v2::ValidityRestrictionType restriction_type = get_type(validity_restriction);
|
||||
if (restriction_type == v2::ValidityRestrictionType::Region) {
|
||||
certificate_region_constraints = true;
|
||||
|
||||
v2::GeographicRegion region = boost::get<v2::GeographicRegion>(validity_restriction);
|
||||
|
||||
std::cout << "This certificate is regionally restricted by ";
|
||||
|
||||
v2::RegionType region_type = get_type(region);
|
||||
if (region_type == v2::RegionType::None) {
|
||||
std::cout << "nothing";
|
||||
} else if (region_type == v2::RegionType::Circle) {
|
||||
std::cout << "a circle";
|
||||
} else if (region_type == v2::RegionType::Rectangle) {
|
||||
std::cout << "a set of rectangles";
|
||||
} else if (region_type == v2::RegionType::Polygon) {
|
||||
std::cout << "a polygon";
|
||||
} else if (region_type == v2::RegionType::ID) {
|
||||
std::cout << "an identified region";
|
||||
}
|
||||
|
||||
std::cout << "." << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
if (!certificate_region_constraints) {
|
||||
std::cout << "This certificate doesn't have any regional restriction." << std::endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#ifndef CERTIFY_COMMANDS_SHOW_CERTIFICATE_HPP
|
||||
#define CERTIFY_COMMANDS_SHOW_CERTIFICATE_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
|
||||
class ShowCertificateCommand : public Command
|
||||
{
|
||||
public:
|
||||
bool parse(const std::vector<std::string>&) override;
|
||||
int execute() override;
|
||||
|
||||
private:
|
||||
std::string certificate_path;
|
||||
};
|
||||
|
||||
#endif /* CERTIFY_COMMANDS_SHOW_CERTIFICATE_HPP */
|
||||
@@ -0,0 +1,18 @@
|
||||
#include "options.hpp"
|
||||
#include <iostream>
|
||||
|
||||
int main(int argc, const char** argv)
|
||||
{
|
||||
try {
|
||||
std::unique_ptr<Command> command = parse_options(argc, argv);
|
||||
|
||||
if (!command) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return command->execute();
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << e.what() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#include "commands/extract-public-key.hpp"
|
||||
#include "commands/generate-aa.hpp"
|
||||
#include "commands/generate-key.hpp"
|
||||
#include "commands/generate-root.hpp"
|
||||
#include "commands/generate-ticket.hpp"
|
||||
#include "commands/show-certificate.hpp"
|
||||
#include "options.hpp"
|
||||
#include <boost/program_options.hpp>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
|
||||
namespace po = boost::program_options;
|
||||
|
||||
std::unique_ptr<Command> parse_options(int argc, const char *argv[])
|
||||
{
|
||||
po::options_description global("Global options");
|
||||
global.add_options()
|
||||
("command", po::value<std::string>(), "Command to execute.")
|
||||
("subargs", po::value<std::vector<std::string>>(), "Arguments for command.")
|
||||
;
|
||||
|
||||
po::positional_options_description pos;
|
||||
pos.add("command", 1);
|
||||
pos.add("subargs", -1);
|
||||
|
||||
po::variables_map vm;
|
||||
|
||||
po::parsed_options parsed = po::command_line_parser(argc, argv)
|
||||
.options(global)
|
||||
.positional(pos)
|
||||
.allow_unregistered()
|
||||
.run();
|
||||
|
||||
po::store(parsed, vm);
|
||||
po::notify(vm);
|
||||
|
||||
std::string available_commands = "Available commands: generate-key, extract-public-key, generate-root, generate-aa, generate-ticket, show-certificate";
|
||||
|
||||
if (!vm.count("command")) {
|
||||
std::cerr << global << std::endl;
|
||||
std::cerr << available_commands << std::endl;
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string cmd = vm["command"].as<std::string>();
|
||||
std::unique_ptr<Command> command;
|
||||
|
||||
if (cmd == "--help") {
|
||||
std::cerr << global << std::endl;
|
||||
std::cerr << available_commands << std::endl;
|
||||
} else if (cmd == "extract-public-key") {
|
||||
command.reset(new ExtractPublicKeyCommand());
|
||||
} else if (cmd == "generate-aa") {
|
||||
command.reset(new GenerateAaCommand());
|
||||
} else if (cmd == "generate-key") {
|
||||
command.reset(new GenerateKeyCommand());
|
||||
} else if (cmd == "generate-root") {
|
||||
command.reset(new GenerateRootCommand());
|
||||
} else if (cmd == "generate-ticket") {
|
||||
command.reset(new GenerateTicketCommand());
|
||||
} else if (cmd == "show-certificate") {
|
||||
command.reset(new ShowCertificateCommand());
|
||||
} else {
|
||||
// unrecognized command
|
||||
throw po::invalid_option_value(cmd);
|
||||
}
|
||||
|
||||
std::vector<std::string> opts = po::collect_unrecognized(parsed.options, po::include_positional);
|
||||
if (!opts.empty()) {
|
||||
opts.erase(opts.begin());
|
||||
}
|
||||
|
||||
if (!command->parse(opts)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return command;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef CERTIFY_OPTIONS_HPP
|
||||
#define CERTIFY_OPTIONS_HPP
|
||||
|
||||
#include "command.hpp"
|
||||
#include <memory>
|
||||
|
||||
std::unique_ptr<Command> parse_options(int argc, const char* argv[]);
|
||||
|
||||
#endif /* CERTIFY_OPTIONS_HPP */
|
||||
@@ -0,0 +1,35 @@
|
||||
#include "utils.hpp"
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
|
||||
void permission_string_to_buffer(const std::string& in, vanetza::ByteBuffer& out)
|
||||
{
|
||||
if (in.size() / 8 != out.size() - 1 /* version */) {
|
||||
std::stringstream ss;
|
||||
ss << "Size mismatch, expected " << (out.size() - 1) << " bytes encoded with one bit per byte.";
|
||||
throw std::runtime_error(ss.str());
|
||||
}
|
||||
|
||||
uint8_t byte = 0;
|
||||
int index = 0;
|
||||
|
||||
for (auto it = in.begin(); it < in.end(); ++it) {
|
||||
byte <<= 1;
|
||||
|
||||
if (*it == '0') {
|
||||
byte &= 0xFE; // clear last bit
|
||||
} else if (*it == '1') {
|
||||
byte |= 1; // set last bit
|
||||
} else {
|
||||
throw std::runtime_error("Unexpected character in permissions, expected only '0' and '1'.");
|
||||
}
|
||||
|
||||
if ((index + 1) % 8 == 0) {
|
||||
out.at(1 /* version */ + (index / 8)) = byte;
|
||||
byte = 0;
|
||||
}
|
||||
|
||||
++index;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef CERTIFY_UTILS_HPP
|
||||
#define CERTIFY_UTILS_HPP
|
||||
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <string>
|
||||
|
||||
void permission_string_to_buffer(const std::string&, vanetza::ByteBuffer&);
|
||||
|
||||
#endif /* CERTIFY_UTILS_HPP */
|
||||
@@ -0,0 +1 @@
|
||||
/cache
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.9"
|
||||
# dependencies = ["pyshp", "shapely"]
|
||||
# ///
|
||||
"""Convert Natural Earth shapefile to Vanetza country data binary format.
|
||||
|
||||
Downloads the Natural Earth admin-0 countries shapefile at the requested
|
||||
resolution, then converts it to a compact binary format.
|
||||
|
||||
Output format:
|
||||
version : uint16 (little-endian)
|
||||
followed by a sequence of entries, each:
|
||||
m49_code : uint16 (little-endian)
|
||||
wkb_size : uint32 (little-endian)
|
||||
wkb_data : bytes (OGC WKB MultiPolygon)
|
||||
"""
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import shapefile
|
||||
from shapely.geometry import MultiPolygon, Polygon, shape
|
||||
|
||||
RESOLUTIONS = ["110m", "50m", "10m"]
|
||||
FORMAT_VERSION = 1
|
||||
|
||||
|
||||
def download_shapefile(resolution: str, cache_dir: Path) -> Path:
|
||||
name = f"ne_{resolution}_admin_0_countries"
|
||||
shp_dir = cache_dir / name
|
||||
shp_path = shp_dir / f"{name}.shp"
|
||||
|
||||
if shp_path.exists():
|
||||
return shp_path
|
||||
|
||||
url = f"https://naciscdn.org/naturalearth/{resolution}/cultural/{name}.zip"
|
||||
print(f"Downloading {url} ...", file=sys.stderr)
|
||||
data, _ = urllib.request.urlretrieve(url)
|
||||
with zipfile.ZipFile(data) as zf:
|
||||
shp_dir.mkdir(parents=True, exist_ok=True)
|
||||
zf.extractall(shp_dir)
|
||||
|
||||
return shp_path
|
||||
|
||||
|
||||
def convert(shp_path: Path, output: Path):
|
||||
sf = shapefile.Reader(str(shp_path))
|
||||
fields = [f[0] for f in sf.fields[1:]] # skip DeletionFlag
|
||||
|
||||
if "ISO_N3_EH" not in fields:
|
||||
print("Error: shapefile missing ISO_N3_EH field", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
iso_n3_eh_idx = fields.index("ISO_N3_EH")
|
||||
count = 0
|
||||
skipped = 0
|
||||
|
||||
with open(output, "wb") as out:
|
||||
out.write(struct.pack("<H", FORMAT_VERSION))
|
||||
|
||||
for sr in sf.shapeRecords():
|
||||
iso_n3_eh = sr.record[iso_n3_eh_idx]
|
||||
|
||||
# Skip non-numeric codes (e.g., "-99" for disputed territories)
|
||||
try:
|
||||
m49 = int(iso_n3_eh)
|
||||
except (ValueError, TypeError):
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
if m49 < 0 or m49 > 65535:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
geom = shape(sr.shape.__geo_interface__)
|
||||
|
||||
# Normalize to MultiPolygon
|
||||
if isinstance(geom, Polygon):
|
||||
geom = MultiPolygon([geom])
|
||||
elif not isinstance(geom, MultiPolygon):
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
wkb = geom.wkb
|
||||
|
||||
out.write(struct.pack("<H", m49))
|
||||
out.write(struct.pack("<I", len(wkb)))
|
||||
out.write(wkb)
|
||||
count += 1
|
||||
|
||||
print(f"Wrote {count} countries, skipped {skipped} entries", file=sys.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Convert Natural Earth to country data binary")
|
||||
parser.add_argument("--output", required=True, type=Path, help="Path to output .bin file")
|
||||
parser.add_argument("--resolution", choices=RESOLUTIONS, default="50m",
|
||||
help="Natural Earth resolution (default: 50m)")
|
||||
parser.add_argument("--cache-dir", type=Path,
|
||||
default=Path(__file__).parent / "cache",
|
||||
help="Cache directory for downloaded shapefiles")
|
||||
args = parser.parse_args()
|
||||
|
||||
shp_path = download_shapefile(args.resolution, args.cache_dir)
|
||||
convert(shp_path, args.output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.9"
|
||||
# dependencies = []
|
||||
# ///
|
||||
"""Generate a C++ source file embedding a binary file as std::array."""
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Embed binary file as C++ std::array")
|
||||
parser.add_argument("--input", required=True, type=Path, help="Path to binary input file")
|
||||
parser.add_argument("--output", required=True, type=Path, help="Path to C++ output file")
|
||||
args = parser.parse_args()
|
||||
|
||||
data = args.input.read_bytes()
|
||||
|
||||
with open(args.output, "w") as out:
|
||||
out.write("#include <vanetza/common/byte_view.hpp>\n\n")
|
||||
out.write(f"static const std::array<uint8_t, {len(data)}> vanetza_country_data_storage = {{\n")
|
||||
for i in range(0, len(data), 16):
|
||||
chunk = data[i:i + 16]
|
||||
out.write(" " + ", ".join(f"0x{b:02x}" for b in chunk) + ",\n")
|
||||
out.write("};\n\n")
|
||||
out.write("namespace vanetza {\n")
|
||||
out.write("namespace geodesy {\n")
|
||||
out.write("namespace country {\n\n")
|
||||
out.write("byte_view_range embedded()\n")
|
||||
out.write("{\n")
|
||||
out.write(" byte_view_iterator begin(vanetza_country_data_storage.data());\n")
|
||||
out.write(" byte_view_iterator end(vanetza_country_data_storage.data() + vanetza_country_data_storage.size());\n")
|
||||
out.write(" return {begin, end};\n")
|
||||
out.write("}\n\n")
|
||||
out.write("} // namespace country\n")
|
||||
out.write("} // namespace geodesy\n")
|
||||
out.write("} // namespace vanetza\n")
|
||||
|
||||
print(f"Embedded {len(data)} bytes into {args.output.name}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.9"
|
||||
# dependencies = ["matplotlib", "shapely"]
|
||||
# ///
|
||||
"""Plot country polygons from a Vanetza country data binary file."""
|
||||
import argparse
|
||||
import colorsys
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
from shapely import wkb
|
||||
|
||||
EXPECTED_FORMAT_VERSION = 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Plot country polygons from .bin file")
|
||||
parser.add_argument("input", help="Path to country_data.bin")
|
||||
args = parser.parse_args()
|
||||
|
||||
fig, ax = plt.subplots(figsize=(16, 8))
|
||||
|
||||
with open(args.input, "rb") as f:
|
||||
data = f.read()
|
||||
|
||||
if len(data) < 2:
|
||||
print("Error: file too short to contain version header", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
version, = struct.unpack_from("<H", data, 0)
|
||||
if version != EXPECTED_FORMAT_VERSION:
|
||||
print(f"Error: unsupported country data format version {version}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
offset = 2
|
||||
while offset < len(data):
|
||||
m49, = struct.unpack_from("<H", data, offset)
|
||||
offset += 2
|
||||
wkb_size, = struct.unpack_from("<I", data, offset)
|
||||
offset += 4
|
||||
geom = wkb.loads(data[offset:offset + wkb_size])
|
||||
offset += wkb_size
|
||||
|
||||
h = (m49 * 0.618) % 1.0
|
||||
s = 0.5 + (hash(m49) % 50) / 100.0
|
||||
l = 0.4 + (hash(m49 * 7) % 30) / 100.0
|
||||
color = colorsys.hls_to_rgb(h, l, s)
|
||||
|
||||
for polygon in geom.geoms:
|
||||
x, y = polygon.exterior.xy
|
||||
ax.fill(x, y, alpha=0.4, edgecolor="black", linewidth=0.3, facecolor=color)
|
||||
if polygon.area > 1.0:
|
||||
centroid = polygon.centroid
|
||||
ax.text(centroid.x, centroid.y, str(m49),
|
||||
fontsize=5, ha="center", va="center")
|
||||
|
||||
ax.set_aspect("equal")
|
||||
ax.set_xlabel("Longitude")
|
||||
ax.set_ylabel("Latitude")
|
||||
ax.set_title("Country Polygons")
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
ARG DEBIAN_VERSION=stable
|
||||
ARG UBUNTU_VERSION=resolute
|
||||
|
||||
FROM debian:${DEBIAN_VERSION} AS debian
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
capnproto \
|
||||
clang \
|
||||
cmake \
|
||||
git \
|
||||
libboost-date-time-dev \
|
||||
libboost-program-options-dev \
|
||||
libboost-system-dev \
|
||||
libcapnp-dev \
|
||||
libcrypto++-dev \
|
||||
libgeographiclib-dev \
|
||||
libssl-dev \
|
||||
ninja-build \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY --chmod=755 build_and_run_tests.sh build_strict_cxx14.sh /usr/local/bin/
|
||||
RUN useradd -m build-user
|
||||
USER build-user
|
||||
WORKDIR /home/build-user
|
||||
ENTRYPOINT ["build_and_run_tests.sh"]
|
||||
CMD ["/home/build-user/workspace"]
|
||||
|
||||
FROM debian AS strict-cxx14
|
||||
ENTRYPOINT ["build_strict_cxx14.sh"]
|
||||
CMD ["/home/build-user/workspace"]
|
||||
|
||||
FROM ubuntu:${UBUNTU_VERSION} AS ubuntu
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
SHELL ["/bin/bash", "-c"]
|
||||
COPY --chmod=755 update_cmake.sh apt_pkg_name.sh /usr/local/bin/
|
||||
RUN update_cmake.sh && apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
ca-certificates \
|
||||
capnproto \
|
||||
cmake \
|
||||
git \
|
||||
libboost-date-time-dev \
|
||||
libboost-program-options-dev \
|
||||
libboost-system-dev \
|
||||
libcapnp-dev \
|
||||
libcrypto++-dev \
|
||||
$(apt_pkg_name.sh geographiclib) \
|
||||
libssl-dev \
|
||||
ninja-build \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
COPY build_and_run_tests.sh /usr/local/bin/build_and_run_tests.sh
|
||||
RUN useradd -m build-user
|
||||
USER build-user
|
||||
WORKDIR /home/build-user
|
||||
ENTRYPOINT ["build_and_run_tests.sh"]
|
||||
CMD ["/home/build-user/workspace"]
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
source /etc/os-release
|
||||
case $VERSION_CODENAME in
|
||||
bionic|focal|jammy)
|
||||
GEOGRAPHICLIB=libgeographic-dev
|
||||
;;
|
||||
noble|resolute)
|
||||
GEOGRAPHICLIB=libgeographiclib-dev
|
||||
;;
|
||||
*)
|
||||
echo "Unsupported Ubuntu version: $VERSION_CODENAME"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
case $1 in
|
||||
geographiclib)
|
||||
echo $GEOGRAPHICLIB
|
||||
;;
|
||||
*)
|
||||
echo "Unknown package name: $1"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
SCRIPT=$(readlink -f $0)
|
||||
SCRIPT_PATH=$(dirname $SCRIPT)
|
||||
ROOT=${1:-$SCRIPT_PATH/../..}
|
||||
ROOT_PATH=$(readlink -f ${ROOT})
|
||||
BUILD_DIR=${BUILD_DIR:-$PWD/build}
|
||||
|
||||
mkdir -p ${BUILD_DIR} && cd ${BUILD_DIR}
|
||||
cmake -G Ninja \
|
||||
-DVANETZA_WITH_CRYPTOPP=ON \
|
||||
-DVANETZA_WITH_OPENSSL=ON \
|
||||
-DBUILD_CERTIFY=ON \
|
||||
-DBUILD_PKI=ON \
|
||||
-DBUILD_SOCKTAP=ON \
|
||||
-DBUILD_TESTS=ON \
|
||||
-DGTest_BUILD_DIRECTORY_DOWNLOAD=ON \
|
||||
${ROOT_PATH}
|
||||
cmake --build .
|
||||
ctest --output-on-failure
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/bin/bash
|
||||
# Strict C++14 compile check for the Vanetza libraries.
|
||||
set -e
|
||||
|
||||
SCRIPT=$(readlink -f "$0")
|
||||
SCRIPT_PATH=$(dirname "$SCRIPT")
|
||||
ROOT=${1:-$SCRIPT_PATH/../..}
|
||||
ROOT_PATH=$(readlink -f "${ROOT}")
|
||||
BUILD_DIR=${BUILD_DIR:-$PWD/build}
|
||||
|
||||
mkdir -p "${BUILD_DIR}" && cd "${BUILD_DIR}"
|
||||
cmake -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
|
||||
-DCMAKE_CXX_STANDARD=14 \
|
||||
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
|
||||
-DCMAKE_CXX_EXTENSIONS=OFF \
|
||||
-DVANETZA_WITH_CRYPTOPP=ON \
|
||||
-DVANETZA_WITH_OPENSSL=ON \
|
||||
-DVANETZA_WITH_GEOGRAPHICLIB=ON \
|
||||
-DVANETZA_WITH_RPC=OFF \
|
||||
-DBUILD_TESTS=OFF \
|
||||
"${ROOT_PATH}"
|
||||
cmake --build .
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
: ${UBUNTU_VERSION:=resolute}
|
||||
SCRIPT_DIR=$(dirname ${BASH_SOURCE[0]})
|
||||
ROOT_DIR=$(readlink -m "${SCRIPT_DIR}/../..")
|
||||
|
||||
echo "Compiling Vanetza for Ubuntu ${UBUNTU_VERSION} and running tests..."
|
||||
docker build --build-arg UBUNTU_VERSION=${UBUNTU_VERSION} --tag vanetza/docker-ci:${UBUNTU_VERSION} ${SCRIPT_DIR}
|
||||
docker run --rm -it -v${ROOT_DIR}:/home/build-user/workspace:ro vanetza/docker-ci:${UBUNTU_VERSION}
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
source /etc/os-release
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
install_kitware_repo() {
|
||||
GPG_KEYFILE=/usr/share/keyrings/kitware-archive-keyring.gpg
|
||||
wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor > $GPG_KEYFILE
|
||||
echo "deb [signed-by=$GPG_KEYFILE] https://apt.kitware.com/ubuntu/ ${UBUNTU_CODENAME} main" > /etc/apt/sources.list.d/kitware.list
|
||||
echo "Added Kitware repository for Ubuntu $UBUNTU_CODENAME"
|
||||
}
|
||||
|
||||
if [[ "${UBUNTU_CODENAME}" == "xenial" ]]; then
|
||||
apt-get update && apt-get install -y apt-transport-https wget
|
||||
install_kitware_repo
|
||||
elif [[ "${UBUNTU_CODENAME}" == "bionic" ]]; then
|
||||
apt-get update && apt-get install -y gpg wget
|
||||
install_kitware_repo
|
||||
else
|
||||
# Ubuntu focal and later ship with a sufficiently new CMake version
|
||||
echo "No need to add Kitware repository for Ubuntu $UBUNTU_CODENAME"
|
||||
fi
|
||||
@@ -0,0 +1 @@
|
||||
output/
|
||||
@@ -0,0 +1,5 @@
|
||||
add_executable(fuzzing-persistent router_fuzzing_context.cpp persistent.cpp)
|
||||
target_link_libraries(fuzzing-persistent PUBLIC vanetza)
|
||||
|
||||
add_executable(fuzzing-run router_fuzzing_context.cpp run.cpp)
|
||||
target_link_libraries(fuzzing-run PUBLIC vanetza)
|
||||
@@ -0,0 +1,15 @@
|
||||
ARG VERSION=latest
|
||||
FROM aflplusplus/aflplusplus:${VERSION}
|
||||
|
||||
# install build dependencies for Vanetza
|
||||
RUN apt-get update && apt-get install --no-install-recommends -y \
|
||||
libboost-all-dev libcrypto++-dev libgeographic-dev libssl-dev
|
||||
|
||||
# install casr-afl tool
|
||||
RUN cargo install --root /usr/local casr
|
||||
|
||||
# set up "fuzz" user and mapping of host user
|
||||
RUN useradd -m -s /bin/bash fuzz
|
||||
RUN cp /root/.bashrc /home/fuzz/.bashrc && chown fuzz:fuzz /home/fuzz/.bashrc
|
||||
COPY docker-entrypoint.sh /docker-entrypoint.sh
|
||||
ENTRYPOINT ["/docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/bash
|
||||
set -eu
|
||||
|
||||
if [[ ! -d "/AFLplusplus" ]] ; then
|
||||
echo "This script shall be run inside the AFL++ container"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cd /home/fuzz
|
||||
|
||||
export CC=${CC:=afl-clang-lto}
|
||||
export CXX=${CXX:=afl-clang-lto++}
|
||||
|
||||
export AFL_LLVM_CMPLOG=1
|
||||
mkdir -p build/cmplog
|
||||
cmake -S source -B build/cmplog -G Ninja -DBUILD_FUZZ=ON
|
||||
cmake --build build/cmplog
|
||||
unset AFL_LLVM_CMPLOG
|
||||
|
||||
# see https://aflplus.plus/docs/env_variables/ for supported environment variables
|
||||
export AFL_USE_ASAN=1
|
||||
export AFL_USE_UBSAN=1
|
||||
mkdir -p build/asan
|
||||
cmake -S source -B build/asan -G Ninja -DBUILD_FUZZ=ON
|
||||
cmake --build build/asan
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/bash -eu
|
||||
afl-system-config
|
||||
|
||||
usermod -u ${HOST_USER_ID} -g ${HOST_GROUP_ID} fuzz
|
||||
ln -sf /source /home/fuzz/source
|
||||
ln -sf /input /home/fuzz/input
|
||||
ln -sf /output /home/fuzz/output
|
||||
ln -sf /source/tools/fuzz-harness/compile.sh /home/fuzz/compile.sh
|
||||
ln -sf /source/tools/fuzz-harness/fuzz.sh /home/fuzz/fuzz.sh
|
||||
cd /home/fuzz
|
||||
su fuzz
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/bash
|
||||
set -eu
|
||||
HARNESS_DIR=$(realpath $(dirname $0))
|
||||
SOURCE_DIR=$HARNESS_DIR/../..
|
||||
|
||||
docker build $HARNESS_DIR
|
||||
IMAGE=$(docker build -q $HARNESS_DIR)
|
||||
|
||||
mkdir -p $HARNESS_DIR/output
|
||||
docker run --rm -it \
|
||||
--security-opt seccomp=unconfined \
|
||||
-v$SOURCE_DIR:/source:ro \
|
||||
-v$HARNESS_DIR/input:/input:ro \
|
||||
-v$HARNESS_DIR/output:/output \
|
||||
-e HOST_USER_ID=$(id -u) -e HOST_GROUP_ID=$(id -g) \
|
||||
$IMAGE
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -eu
|
||||
: ${FUZZ_INPUT:="$HOME/input"}
|
||||
: ${FUZZ_OUTPUT:="$HOME/output"}
|
||||
: ${FUZZ_BUILD:="$HOME/build"}
|
||||
afl-fuzz -i $FUZZ_INPUT -o $FUZZ_OUTPUT -c $FUZZ_BUILD/cmplog/bin/fuzzing-persistent -m none -- $FUZZ_BUILD/asan/bin/fuzzing-persistent
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,34 @@
|
||||
#include "router_fuzzing_context.hpp"
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifndef __AFL_FUZZ_TESTCASE_LEN
|
||||
ssize_t fuzz_len;
|
||||
#define __AFL_FUZZ_TESTCASE_LEN fuzz_len
|
||||
unsigned char fuzz_buf[1024000];
|
||||
#define __AFL_FUZZ_TESTCASE_BUF fuzz_buf
|
||||
#define __AFL_FUZZ_INIT() void sync(void);
|
||||
#define __AFL_LOOP(x) ((fuzz_len = read(0, fuzz_buf, sizeof(fuzz_buf))) > 0 ? 1 : 0)
|
||||
#define __AFL_INIT() sync()
|
||||
#endif
|
||||
|
||||
__AFL_FUZZ_INIT();
|
||||
|
||||
int main()
|
||||
{
|
||||
#ifdef __AFL_HAVE_MANUAL_CONTROL
|
||||
__AFL_INIT();
|
||||
#endif
|
||||
|
||||
vanetza::RouterFuzzingContext context;
|
||||
|
||||
unsigned char *buf = __AFL_FUZZ_TESTCASE_BUF;
|
||||
while (__AFL_LOOP(10000)) {
|
||||
int len = __AFL_FUZZ_TESTCASE_LEN;
|
||||
vanetza::ByteBuffer buffer { buf, buf + len };
|
||||
context.initialize();
|
||||
context.indicate(std::move(buffer));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
#include "router_fuzzing_context.hpp"
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
|
||||
class FuzzingRequestInterface : public dcc::RequestInterface
|
||||
{
|
||||
void request(const dcc::DataRequest&, std::unique_ptr<ChunkPacket>) override {}
|
||||
};
|
||||
|
||||
class FuzzingTransportInterface : public geonet::TransportInterface
|
||||
{
|
||||
void indicate(const geonet::DataIndication&, std::unique_ptr<geonet::UpPacket>) override {}
|
||||
};
|
||||
|
||||
RouterFuzzingContext::RouterFuzzingContext() :
|
||||
runtime(vanetza::Clock::at("2010-12-23 18:29")),
|
||||
security(runtime),
|
||||
req_ifc(std::make_unique<FuzzingRequestInterface>()),
|
||||
ind_ifc(std::make_unique<FuzzingTransportInterface>())
|
||||
{
|
||||
initialize();
|
||||
}
|
||||
|
||||
void RouterFuzzingContext::initialize()
|
||||
{
|
||||
router = std::make_unique<geonet::Router>(runtime, mib);
|
||||
router->set_security_entity(&security.entity());
|
||||
router->set_access_interface(req_ifc.get());
|
||||
router->set_transport_handler(geonet::UpperProtocol::BTP_B, ind_ifc.get());
|
||||
|
||||
geonet::Address gn_addr;
|
||||
gn_addr.mid(MacAddress{0, 0, 0, 0, 0, 1});
|
||||
router->set_address(gn_addr);
|
||||
}
|
||||
|
||||
void RouterFuzzingContext::indicate(ByteBuffer&& buffer)
|
||||
{
|
||||
MacAddress source { 0, 0, 0, 0, 0, 2 };
|
||||
MacAddress destination { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
|
||||
auto packet = std::make_unique<geonet::UpPacket>(CohesivePacket { std::move(buffer), OsiLayer::Network });
|
||||
router->indicate(std::move(packet), source, destination);
|
||||
}
|
||||
|
||||
} // namespace vanetza
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
#ifndef VANETZA_ROUTER_FUZZING_CONTEXT_HPP
|
||||
#define VANETZA_ROUTER_FUZZING_CONTEXT_HPP
|
||||
|
||||
#include <vanetza/common/manual_runtime.hpp>
|
||||
#include <vanetza/dcc/interface.hpp>
|
||||
#include <vanetza/geonet/router.hpp>
|
||||
#include <vanetza/geonet/transport_interface.hpp>
|
||||
#include <vanetza/geonet/tests/security_context.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
|
||||
class RouterFuzzingContext {
|
||||
public:
|
||||
RouterFuzzingContext();
|
||||
void initialize();
|
||||
void indicate(ByteBuffer&& buffer);
|
||||
|
||||
private:
|
||||
ManualRuntime runtime;
|
||||
SecurityContext security;
|
||||
geonet::ManagementInformationBase mib;
|
||||
std::unique_ptr<geonet::Router> router;
|
||||
std::unique_ptr<dcc::RequestInterface> req_ifc;
|
||||
std::unique_ptr<geonet::TransportInterface> ind_ifc;
|
||||
};
|
||||
|
||||
} // namespace vanetza
|
||||
|
||||
#endif //VANETZA_ROUTER_FUZZING_CONTEXT_HPP
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "router_fuzzing_context.hpp"
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
|
||||
vanetza::ByteBuffer readFileIntoBuffer(const std::string &filename)
|
||||
{
|
||||
std::ifstream file(filename, std::ios::binary | std::ios::ate);
|
||||
if (!file.is_open()) {
|
||||
std::cerr << "Error opening file: " << filename << std::endl;
|
||||
return {};
|
||||
}
|
||||
|
||||
const std::streamsize size = file.tellg();
|
||||
file.seekg(0, std::ios::beg);
|
||||
|
||||
vanetza::ByteBuffer buffer(size);
|
||||
if (!file.read(reinterpret_cast<char *>(buffer.data()), size)) {
|
||||
std::cerr << "Error reading file: " << filename << std::endl;
|
||||
return {};
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
if (argc != 2) {
|
||||
std::cerr << "Usage: " << argv[0] << " <filepath>" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
const std::string filename = argv[1];
|
||||
vanetza::ByteBuffer buffer = readFileIntoBuffer(filename);
|
||||
|
||||
if (buffer.empty()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
vanetza::RouterFuzzingContext context;
|
||||
context.indicate(std::move(buffer));
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
GPSD_LOCAL_PORT=8051
|
||||
NMEA_REMOTE_PORT=8052
|
||||
NC_REMOTE_PID=0
|
||||
NC_LOCAL_PID=0
|
||||
FIFO=/tmp/gpsnc_fifo.$$
|
||||
|
||||
exit_handler()
|
||||
{
|
||||
kill $NC_REMOTE_PID 2>/dev/null
|
||||
kill $NC_LOCAL_PID 2>/dev/null
|
||||
rm -f $FIFO
|
||||
}
|
||||
|
||||
trap exit_handler SIGINT SIGTERM
|
||||
|
||||
mkfifo $FIFO
|
||||
nc -k -l ${NMEA_REMOTE_PORT} > $FIFO &
|
||||
NC_REMOTE_PID=$!
|
||||
nc -l ${GPSD_LOCAL_PORT} < $FIFO &
|
||||
NC_LOCAL_PID=$!
|
||||
|
||||
sleep 1 # wait for nc ports becoming available
|
||||
gpsd -n -N -D4 tcp://localhost:${GPSD_LOCAL_PORT}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
find_package(Boost REQUIRED)
|
||||
find_package(OpenSSL REQUIRED)
|
||||
find_package(Threads)
|
||||
|
||||
include(FetchContent)
|
||||
find_package(CLI11 2.6 QUIET)
|
||||
if(NOT CLI11_FOUND)
|
||||
set(CLI11_PRECOMPILED ON CACHE BOOL "Build CLI11 as a compiled library" FORCE)
|
||||
FetchContent_Declare(CLI11
|
||||
GIT_REPOSITORY https://github.com/CLIUtils/CLI11.git
|
||||
GIT_TAG v2.6.2
|
||||
GIT_SHALLOW TRUE)
|
||||
FetchContent_MakeAvailable(CLI11)
|
||||
endif()
|
||||
|
||||
add_library(pki_library STATIC
|
||||
asn1.cpp
|
||||
at_request.cpp
|
||||
at_response.cpp
|
||||
authorization.cpp
|
||||
certificate.cpp
|
||||
certificate_filesystem_storage.cpp
|
||||
certificate_revocation_list.cpp
|
||||
certificate_trust_list.cpp
|
||||
config.cpp
|
||||
credential_filesystem_storage.cpp
|
||||
crl_store.cpp
|
||||
dc_command.cpp
|
||||
distribution_centre.cpp
|
||||
ea_request.cpp
|
||||
ea_response.cpp
|
||||
ecies.cpp
|
||||
encrypted_data.cpp
|
||||
filesystem.cpp
|
||||
hashed_id8.cpp
|
||||
hexstring.cpp
|
||||
http.cpp
|
||||
key_command.cpp
|
||||
keys.cpp
|
||||
openssl.cpp
|
||||
openssl_security_module.cpp
|
||||
pem.cpp
|
||||
prune_command.cpp
|
||||
psid_ssp.cpp
|
||||
response_codes.cpp
|
||||
security_module.cpp
|
||||
signed_builder.cpp
|
||||
signed_data.cpp
|
||||
station_config_filesystem.cpp
|
||||
time.cpp
|
||||
trust_list_filesystem_storage.cpp
|
||||
validation.cpp
|
||||
xdg.cpp
|
||||
)
|
||||
target_link_libraries(pki_library PUBLIC
|
||||
OpenSSL::Crypto OpenSSL::SSL
|
||||
Boost::headers
|
||||
CLI11::CLI11
|
||||
asn1 common security)
|
||||
target_compile_definitions(pki_library PRIVATE OPENSSL_API_COMPAT=0x10101000L)
|
||||
target_compile_features(pki_library PUBLIC cxx_std_17)
|
||||
|
||||
add_executable(pki
|
||||
cpoc.cpp
|
||||
enrolment.cpp
|
||||
main.cpp
|
||||
printing.cpp
|
||||
station.cpp
|
||||
)
|
||||
target_link_libraries(pki PUBLIC pki_library)
|
||||
set_target_properties(pki PROPERTIES INSTALL_RPATH $ORIGIN/../${CMAKE_INSTALL_LIBDIR})
|
||||
install(TARGETS pki DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
|
||||
add_test_subdirectory(tests)
|
||||
@@ -0,0 +1,110 @@
|
||||
# Vanetza PKI Client
|
||||
|
||||
Our PKI client allows you to interact with any ETSI compliant C-ITS PKI provider.
|
||||
Ideally, your PKI provider is listed in the European Certificate Trust List (ECTL).
|
||||
|
||||
In the examples below we use Eviden's L0 PKI (c-its-pki.eu). However, this tool is not limited to any particular PKI provider!
|
||||
|
||||
|
||||
## Enrol at PKI included in ECTL
|
||||
|
||||
1. Fetch latest TLM from CPOC
|
||||
|
||||
`pki cpoc tlm fetch`
|
||||
|
||||
> Added TLM certificate "EU-TLM_L0" (8FFE810BDB0D71E6)
|
||||
|
||||
Writes ~/.local/share/vanetza/pki/certificates/8FFE810BDB0D71E6.tlm
|
||||
|
||||
|
||||
2. Fetch ECTL from CPOC
|
||||
|
||||
`pki cpoc ectl fetch`
|
||||
|
||||
> Stored ECTL
|
||||
|
||||
Writes ~/.local/share/vanetza/pki/ectl.ctl and populates certificates/*.rca with Root CA certificaties listed in ECTL.
|
||||
|
||||
|
||||
3. Select Root CA for your station
|
||||
|
||||
`pki station set-root-ca 1B5CB4BEBE6FE9E9`
|
||||
|
||||
> Found Root CA certificate in cache.
|
||||
|
||||
|
||||
4. Fetch CTL from Distribution Centre (DC) of your Root CA
|
||||
|
||||
`pki dc info`
|
||||
|
||||
> DC URL: https://0.eu-dc.l0.c-its-pki.eu/
|
||||
|
||||
Prints the DC URL as found in the ECTL for the previously selected Root CA.
|
||||
|
||||
`pki dc getctl --print`
|
||||
|
||||
> - EA: http://0.eu-ea.l0.c-its-pki.eu/ [AA] \
|
||||
> - AA: http://0.eu-aa.l0.c-its-pki.eu/ \
|
||||
> Fetched CTL matches Root CA digest \
|
||||
> CTL is valid. Added to local trust list storage.
|
||||
|
||||
Writes ~/.local/share/vanetza/pki/ctls/1B5CB4BEBE6FE9E9.ctl
|
||||
|
||||
|
||||
5. Perform initial enrolment at EA
|
||||
|
||||
Initial enrolment needs a canonical (bootstrap) key pair.
|
||||
In a real deployment this key is provisioned by the station manufacturer.
|
||||
For testing you can generate one:
|
||||
|
||||
`pki key generate --out ~/station_key.pem`
|
||||
|
||||
> Wrote /home/user/station_key.pem \
|
||||
> Key type: BrainpoolP256r1 \
|
||||
> Canonical public key: 021234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF
|
||||
|
||||
Use `--key-type` to pick a curve (`BrainpoolP256r1` (default), `NistP256`, `BrainpoolP384r1`) and `--force` to overwrite an existing file.
|
||||
|
||||
`pki enrol init --canonical-id station_name --canonical-keyfile ~/station_key.pem`
|
||||
|
||||
> Root CA 1B5CB4BEBE6FE9E9 \
|
||||
> Canonical identifier: station_name \
|
||||
> Canonical public key X=1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF \
|
||||
> Enroling against EA certificate: D07F4E6D4D1DFA70 \
|
||||
> Enroling at EA URL: http://0.eu-ea.l0.c-its-pki.eu/ \
|
||||
> Stored new EC with HashedId8 = 1234567890ABCDEF \
|
||||
> Station can sign with received EC
|
||||
|
||||
|
||||
6. Check your station's state
|
||||
|
||||
`pki station`
|
||||
|
||||
> Canonical identifier: station_name \
|
||||
> Enrolled: yes \
|
||||
> EC digest: 1234567890ABCDEF \
|
||||
> EC certificate: [available] \
|
||||
> Root CA: 1B5CB4BEBE6FE9E9 \
|
||||
> DC URL: https://0.eu-dc.l0.c-its-pki.eu/
|
||||
|
||||
|
||||
## Fetch Authorization Tickets (ATs) from PKI's AA
|
||||
|
||||
Your station needs to be enrolled with valid EC certificate before you can retrieve ATs.
|
||||
|
||||
The following command fetches a single AT with default settings.
|
||||
The command line option `--permission` is required at least once to determine the requested AT application permissions.
|
||||
However, it is more convenient to set these permissions in the local configuration file (`~/.config/vanetza/pki.cfg`):
|
||||
|
||||
```
|
||||
[authorization.request]
|
||||
permission = ["36:01FFFC", "37:01FFFFFF", "141"]
|
||||
```
|
||||
|
||||
`pki at request`
|
||||
|
||||
> Authorizing against AA AF65A276F2D4EBC9 at http://0.eu-aa.l0.c-its-pki.eu/ \
|
||||
> Stored new AT ABCDEF1234567890 \
|
||||
> ABCDEF1234567890 [valid now] \
|
||||
> valid: 2026-06-06 07:06:29 until 2026-06-13 07:06:29 \
|
||||
> permissions: 36:01FFFC 37:01FFFFFF 141
|
||||
@@ -0,0 +1,241 @@
|
||||
#include "asn1.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "keys.hpp"
|
||||
#include "sha.hpp"
|
||||
#include <vanetza/asn1/security/EtsiTs103097Data.h>
|
||||
#include <vanetza/asn1/support/OCTET_STRING.h>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
ByteBuffer copy(const OCTET_STRING_t& octets)
|
||||
{
|
||||
ByteBuffer buffer(octets.size);
|
||||
std::memcpy(buffer.data(), octets.buf, octets.size);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
const OCTET_STRING_t* get_signed_payload(const Vanetza_Security_Ieee1609Dot2Content_t* content)
|
||||
{
|
||||
const OCTET_STRING_t* payload = nullptr;
|
||||
if (content && content->present == Vanetza_Security_Ieee1609Dot2Content_PR_signedData) {
|
||||
const Vanetza_Security_SignedData_t* data = content->choice.signedData;
|
||||
if (data && data->tbsData && data->tbsData->payload) {
|
||||
const Vanetza_Security_SignedDataPayload_t& spayload = *data->tbsData->payload;
|
||||
if (spayload.data && spayload.data->content &&
|
||||
spayload.data->content->present == Vanetza_Security_Ieee1609Dot2Content_PR_unsecuredData) {
|
||||
payload = &spayload.data->content->choice.unsecuredData;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
bool MgmtData::decode(const Vanetza_Security_Opaque_t& opaque)
|
||||
{
|
||||
return wrapper::decode(opaque.buf, opaque.size);
|
||||
}
|
||||
|
||||
MgmtData MgmtData::decode_expecting(const void* buffer, std::size_t size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR expected)
|
||||
{
|
||||
MgmtData mgmt;
|
||||
if (!mgmt.decode(buffer, size)) {
|
||||
throw DecodingFailure("decoding management data failed");
|
||||
}
|
||||
if (mgmt->content.present != expected) {
|
||||
throw DecodingFailure("management data contains unexpected content");
|
||||
}
|
||||
return mgmt;
|
||||
}
|
||||
|
||||
MgmtData MgmtData::decode_expecting(const Vanetza_Security_Opaque_t& opaque,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR expected)
|
||||
{
|
||||
return decode_expecting(opaque.buf, opaque.size, expected);
|
||||
}
|
||||
|
||||
TlmCtlData TlmCtlData::from_buffer(const void* buffer, std::size_t size)
|
||||
{
|
||||
return TlmCtlData { decode_expecting(buffer, size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm) };
|
||||
}
|
||||
|
||||
TlmCtlData TlmCtlData::from_opaque(const Vanetza_Security_Opaque_t& opaque)
|
||||
{
|
||||
return from_buffer(opaque.buf, opaque.size);
|
||||
}
|
||||
|
||||
RcaCtlData RcaCtlData::from_buffer(const void* buffer, std::size_t size)
|
||||
{
|
||||
return RcaCtlData { decode_expecting(buffer, size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca) };
|
||||
}
|
||||
|
||||
RcaCtlData RcaCtlData::from_opaque(const Vanetza_Security_Opaque_t& opaque)
|
||||
{
|
||||
return from_buffer(opaque.buf, opaque.size);
|
||||
}
|
||||
|
||||
EnrolmentResponseData EnrolmentResponseData::from_buffer(const void* buffer, std::size_t size)
|
||||
{
|
||||
return EnrolmentResponseData { decode_expecting(buffer, size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentResponse) };
|
||||
}
|
||||
|
||||
EnrolmentResponseData EnrolmentResponseData::from_opaque(const Vanetza_Security_Opaque_t& opaque)
|
||||
{
|
||||
return from_buffer(opaque.buf, opaque.size);
|
||||
}
|
||||
|
||||
AuthorizationResponseData AuthorizationResponseData::from_buffer(const void* buffer, std::size_t size)
|
||||
{
|
||||
return AuthorizationResponseData { decode_expecting(buffer, size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR_authorizationResponse) };
|
||||
}
|
||||
|
||||
AuthorizationResponseData AuthorizationResponseData::from_opaque(const Vanetza_Security_Opaque_t& opaque)
|
||||
{
|
||||
return from_buffer(opaque.buf, opaque.size);
|
||||
}
|
||||
|
||||
void copy(const OCTET_STRING_t& src, ByteBuffer& dst)
|
||||
{
|
||||
static_assert(sizeof(ByteBuffer::value_type) == sizeof(char), "sizes do not match");
|
||||
|
||||
dst.resize(src.size);
|
||||
std::copy_n(src.buf, src.size, dst.data());
|
||||
}
|
||||
|
||||
void copy(const ByteBuffer& src, OCTET_STRING_t& dst)
|
||||
{
|
||||
static_assert(sizeof(ByteBuffer::value_type) == sizeof(char), "sizes do not match");
|
||||
|
||||
auto src_buf = reinterpret_cast<const char*>(src.data());
|
||||
if (OCTET_STRING_fromBuf(&dst, src_buf, src.size()) != 0) {
|
||||
throw std::runtime_error("copying buffer into OCTET_STRING failed");
|
||||
}
|
||||
}
|
||||
|
||||
void copy_left_padded(const ByteBuffer& src, OCTET_STRING_t& dst, std::size_t len)
|
||||
{
|
||||
static_assert(sizeof(ByteBuffer::value_type) == sizeof(char), "sizes do not match");
|
||||
|
||||
if (src.size() > len) {
|
||||
throw std::runtime_error("source bytes exceed desired length of destination buffer");
|
||||
} else if (src.size() == len) {
|
||||
copy(src, dst);
|
||||
assert(dst.size == len);
|
||||
} else {
|
||||
std::string tmp;
|
||||
tmp.assign(len, '\0');
|
||||
std::copy(src.begin(), src.end(), std::next(tmp.begin(), len - src.size()));
|
||||
if (OCTET_STRING_fromBuf(&dst, tmp.data(), tmp.size()) != 0) {
|
||||
throw std::runtime_error("copying buffer into OCTET_STRING failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void fill_curve_point(const PublicKey& key, Vanetza_Security_EccP256CurvePoint_t& point)
|
||||
{
|
||||
switch (key.compression) {
|
||||
case KeyCompression::NoCompression:
|
||||
point.present = Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256;
|
||||
copy_left_padded(key.x, point.choice.uncompressedP256.x, 32);
|
||||
copy_left_padded(key.y, point.choice.uncompressedP256.y, 32);
|
||||
break;
|
||||
case KeyCompression::Y0:
|
||||
point.present = Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0;
|
||||
copy_left_padded(key.x, point.choice.compressed_y_0, 32);
|
||||
break;
|
||||
case KeyCompression::Y1:
|
||||
point.present = Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1;
|
||||
copy_left_padded(key.x, point.choice.compressed_y_1, 32);
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("unknown key compression");
|
||||
}
|
||||
}
|
||||
|
||||
void fill_curve_point(const PublicKey& key, Vanetza_Security_EccP384CurvePoint_t& point)
|
||||
{
|
||||
switch (key.compression) {
|
||||
case KeyCompression::NoCompression:
|
||||
point.present = Vanetza_Security_EccP384CurvePoint_PR_uncompressedP384;
|
||||
copy_left_padded(key.x, point.choice.uncompressedP384.x, 48);
|
||||
copy_left_padded(key.y, point.choice.uncompressedP384.y, 48);
|
||||
break;
|
||||
case KeyCompression::Y0:
|
||||
point.present = Vanetza_Security_EccP384CurvePoint_PR_compressed_y_0;
|
||||
copy_left_padded(key.x, point.choice.compressed_y_0, 48);
|
||||
break;
|
||||
case KeyCompression::Y1:
|
||||
point.present = Vanetza_Security_EccP384CurvePoint_PR_compressed_y_1;
|
||||
copy_left_padded(key.x, point.choice.compressed_y_1, 48);
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("unknown key compression");
|
||||
}
|
||||
}
|
||||
|
||||
Vanetza_Security_HashAlgorithm_t convert(HashAlgorithm from)
|
||||
{
|
||||
switch (from) {
|
||||
case HashAlgorithm::SHA256:
|
||||
return Vanetza_Security_HashAlgorithm_sha256;
|
||||
break;
|
||||
case HashAlgorithm::SHA384:
|
||||
return Vanetza_Security_HashAlgorithm_sha384;
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("unknown hash algorithm");
|
||||
}
|
||||
}
|
||||
|
||||
ByteBuffer to_buffer(const OCTET_STRING_t& input)
|
||||
{
|
||||
return ByteBuffer { input.buf, input.buf + input.size };
|
||||
}
|
||||
|
||||
std::string to_string(const OCTET_STRING_t& input)
|
||||
{
|
||||
if (input.buf) {
|
||||
return std::string { reinterpret_cast<const char*>(input.buf), input.size };
|
||||
} else {
|
||||
return std::string {};
|
||||
}
|
||||
}
|
||||
|
||||
bool operator==(const OCTET_STRING_t& lhs, const ByteBuffer& rhs)
|
||||
{
|
||||
if (lhs.size == rhs.size()) {
|
||||
if (std::memcmp(lhs.buf, rhs.data(), lhs.size) == 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool operator!=(const OCTET_STRING_t& lhs, const ByteBuffer& rhs)
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
bool operator==(const ByteBuffer& lhs, const OCTET_STRING_t& rhs)
|
||||
{
|
||||
return rhs == lhs;
|
||||
}
|
||||
|
||||
bool operator!=(const ByteBuffer& lhs, const OCTET_STRING_t& rhs)
|
||||
{
|
||||
return !(rhs == lhs);
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,187 @@
|
||||
#pragma once
|
||||
|
||||
#include "keys.hpp"
|
||||
#include "sha.hpp"
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <cstring>
|
||||
|
||||
// forward declaration
|
||||
typedef struct OCTET_STRING OCTET_STRING_t;
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
ByteBuffer copy(const OCTET_STRING_t&);
|
||||
const OCTET_STRING_t* get_signed_payload(const Vanetza_Security_Ieee1609Dot2Content_t*);
|
||||
|
||||
class MgmtData : public asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data_t>
|
||||
{
|
||||
public:
|
||||
using wrapper = asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data_t>;
|
||||
|
||||
MgmtData() : asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data_t>(asn_DEF_Vanetza_Security_EtsiTs102941Data)
|
||||
{
|
||||
}
|
||||
|
||||
using wrapper::decode;
|
||||
bool decode(const Vanetza_Security_Opaque_t&);
|
||||
|
||||
protected:
|
||||
/**
|
||||
* Decode and assert the content variant matches `expected`.
|
||||
*
|
||||
* \throws DecodingFailure on decode failure or unexpected content variant
|
||||
*/
|
||||
static MgmtData decode_expecting(const void* buffer, std::size_t size,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR expected);
|
||||
static MgmtData decode_expecting(const Vanetza_Security_Opaque_t&,
|
||||
Vanetza_Security_EtsiTs102941DataContent_PR expected);
|
||||
};
|
||||
|
||||
// Management data known to carry a TLM certificate trust list.
|
||||
class TlmCtlData : public MgmtData
|
||||
{
|
||||
public:
|
||||
TlmCtlData() = default;
|
||||
|
||||
static TlmCtlData from_buffer(const void* buffer, std::size_t size);
|
||||
static TlmCtlData from_opaque(const Vanetza_Security_Opaque_t&);
|
||||
|
||||
private:
|
||||
explicit TlmCtlData(MgmtData&& base) : MgmtData(std::move(base))
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// Management data known to carry an RCA certificate trust list.
|
||||
class RcaCtlData : public MgmtData
|
||||
{
|
||||
public:
|
||||
RcaCtlData() = default;
|
||||
|
||||
static RcaCtlData from_buffer(const void* buffer, std::size_t size);
|
||||
static RcaCtlData from_opaque(const Vanetza_Security_Opaque_t&);
|
||||
|
||||
private:
|
||||
explicit RcaCtlData(MgmtData&& base) : MgmtData(std::move(base))
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// Management data known to carry an enrolment response.
|
||||
class EnrolmentResponseData : public MgmtData
|
||||
{
|
||||
public:
|
||||
EnrolmentResponseData() = default;
|
||||
|
||||
static EnrolmentResponseData from_buffer(const void* buffer, std::size_t size);
|
||||
static EnrolmentResponseData from_opaque(const Vanetza_Security_Opaque_t&);
|
||||
|
||||
private:
|
||||
explicit EnrolmentResponseData(MgmtData&& base) : MgmtData(std::move(base))
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// Management data known to carry an authorization response.
|
||||
class AuthorizationResponseData : public MgmtData
|
||||
{
|
||||
public:
|
||||
AuthorizationResponseData() = default;
|
||||
|
||||
static AuthorizationResponseData from_buffer(const void* buffer, std::size_t size);
|
||||
static AuthorizationResponseData from_opaque(const Vanetza_Security_Opaque_t&);
|
||||
|
||||
private:
|
||||
explicit AuthorizationResponseData(MgmtData&& base) : MgmtData(std::move(base))
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
void fill_curve_point(const PublicKey&, Vanetza_Security_EccP256CurvePoint_t&);
|
||||
void fill_curve_point(const PublicKey&, Vanetza_Security_EccP384CurvePoint_t&);
|
||||
|
||||
void copy(const OCTET_STRING_t& src, ByteBuffer& dst);
|
||||
void copy(const ByteBuffer& src, OCTET_STRING_t& dst);
|
||||
void copy_left_padded(const ByteBuffer& src, OCTET_STRING_t& dst, std::size_t len);
|
||||
|
||||
Vanetza_Security_HashAlgorithm_t convert(HashAlgorithm);
|
||||
ByteBuffer to_buffer(const OCTET_STRING_t&);
|
||||
|
||||
std::string to_string(const OCTET_STRING_t&);
|
||||
|
||||
/**
|
||||
* \brief strong-typed wrapper around asn1c-generated enum
|
||||
*
|
||||
* \tparam Tag generated C enum
|
||||
* \tparam T underlying type
|
||||
*/
|
||||
template<typename Tag, typename T = long> struct asn1c_enum
|
||||
{
|
||||
T value;
|
||||
constexpr explicit asn1c_enum(T v = T {}) : value(v)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator==(asn1c_enum<Tag, T> l, asn1c_enum<Tag, T> r)
|
||||
{
|
||||
return l.value == r.value;
|
||||
}
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator!=(asn1c_enum<Tag, T> l, asn1c_enum<Tag, T> r)
|
||||
{
|
||||
return l.value != r.value;
|
||||
}
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator==(asn1c_enum<Tag, T> l, Tag r)
|
||||
{
|
||||
return l.value == static_cast<T>(r);
|
||||
}
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator!=(asn1c_enum<Tag, T> l, Tag r)
|
||||
{
|
||||
return l.value != static_cast<T>(r);
|
||||
}
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator==(Tag l, asn1c_enum<Tag, T> r)
|
||||
{
|
||||
return static_cast<T>(l) == r.value;
|
||||
}
|
||||
|
||||
template<typename Tag, typename T> constexpr bool operator!=(Tag l, asn1c_enum<Tag, T> r)
|
||||
{
|
||||
return static_cast<T>(l) != r.value;
|
||||
}
|
||||
|
||||
bool operator==(const OCTET_STRING_t&, const ByteBuffer&);
|
||||
bool operator!=(const OCTET_STRING_t&, const ByteBuffer&);
|
||||
bool operator==(const ByteBuffer&, const OCTET_STRING_t&);
|
||||
bool operator!=(const ByteBuffer&, const OCTET_STRING_t&);
|
||||
|
||||
template<std::size_t N> bool operator==(const OCTET_STRING_t& lhs, const std::array<std::uint8_t, N>& rhs)
|
||||
{
|
||||
return lhs.size == N && std::memcmp(lhs.buf, rhs.data(), N) == 0;
|
||||
}
|
||||
|
||||
template<std::size_t N> bool operator!=(const OCTET_STRING_t& lhs, const std::array<std::uint8_t, N>& rhs)
|
||||
{
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
template<std::size_t N> bool operator==(const std::array<std::uint8_t, N>& lhs, const OCTET_STRING_t& rhs)
|
||||
{
|
||||
return rhs == lhs;
|
||||
}
|
||||
|
||||
template<std::size_t N> bool operator!=(const std::array<std::uint8_t, N>& lhs, const OCTET_STRING_t& rhs)
|
||||
{
|
||||
return !(rhs == lhs);
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,179 @@
|
||||
#include "at_request.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "encrypted_data.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "psid_ssp.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include "sha.hpp"
|
||||
#include "signed_builder.hpp"
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/asn1/security/InnerAtRequest.h>
|
||||
#include <vanetza/asn1/security/SharedAtRequest.h>
|
||||
#include <vanetza/asn1/security/ValidityPeriod.h>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <vanetza/security/v3/basic_elements.hpp>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
void add_app_permissions(Vanetza_Security_CertificateSubjectAttributes_t& csa, const std::list<PsidSsp>& permissions)
|
||||
{
|
||||
csa.appPermissions = asn1::allocate<Vanetza_Security_SequenceOfPsidSsp_t>();
|
||||
for (const auto& perm : permissions) {
|
||||
auto* psid_ssp = asn1::allocate<Vanetza_Security_PsidSsp_t>();
|
||||
psid_ssp->psid = perm.psid;
|
||||
if (!perm.ssp.empty()) {
|
||||
psid_ssp->ssp = asn1::allocate<Vanetza_Security_ServiceSpecificPermissions_t>();
|
||||
psid_ssp->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
|
||||
copy(perm.ssp, psid_ssp->ssp->choice.bitmapSsp);
|
||||
}
|
||||
if (asn_sequence_add(csa.appPermissions, psid_ssp) != 0) {
|
||||
throw std::runtime_error("adding app permission to InnerAtRequest failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Encrypt `plaintext` to `recipient_certificate` using a fresh ECIES context
|
||||
// and populate `dest` (an EtsiTs103097Data-Encrypted value member of a parent
|
||||
// struct) in place. Precondition: `dest` is zero-initialised.
|
||||
void encrypt_into(Vanetza_Security_EtsiTs103097Data_Encrypted_85P0_t& dest, SecurityModule& security,
|
||||
const ByteBuffer& plaintext, const Certificate& recipient_certificate)
|
||||
{
|
||||
boost::optional<PublicKey> enc_key = recipient_certificate.get_encryption_key();
|
||||
if (!enc_key) {
|
||||
throw DecodingFailure("recipient certificate has no encryption key");
|
||||
}
|
||||
Sha256Hash recipient_hash = calculate_sha256_hash(security, recipient_certificate);
|
||||
auto ecies = security.create_ecies_context(*enc_key, recipient_hash);
|
||||
|
||||
EncryptedData::init(dest);
|
||||
EncryptedData::set_aes_ccm_ciphertext(dest, *ecies, plaintext);
|
||||
EncryptedData::append_recipient_info(dest, *ecies, recipient_certificate.calculate_hashed_id8(security));
|
||||
}
|
||||
|
||||
void validate(const AuthorizationRequestParameters& p)
|
||||
{
|
||||
if (!p.ec) {
|
||||
throw std::invalid_argument("AuthorizationRequest: ec is required");
|
||||
}
|
||||
if (!p.ea_certificate) {
|
||||
throw std::invalid_argument("AuthorizationRequest: ea_certificate is required");
|
||||
}
|
||||
if (!p.aa_certificate) {
|
||||
throw std::invalid_argument("AuthorizationRequest: aa_certificate is required");
|
||||
}
|
||||
if (p.permissions.empty()) {
|
||||
throw std::invalid_argument("AuthorizationRequest: at least one permission must be requested");
|
||||
}
|
||||
if (p.hash_algo != HashAlgorithm::SHA256) {
|
||||
throw std::invalid_argument("AuthorizationRequest: only SHA-256 is supported");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ByteBuffer build_signed_authorization_request(SecurityModule& security, const AuthorizationRequestParameters& params)
|
||||
{
|
||||
validate(params);
|
||||
|
||||
// Outer EtsiTs102941Data{authorizationRequest = InnerAtRequest}.
|
||||
// We populate the InnerAtRequest fields in place inside the wrapper.
|
||||
asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs102941Data_t> mgmt(asn_DEF_Vanetza_Security_EtsiTs102941Data);
|
||||
mgmt->version = Vanetza_Security_Version_v1;
|
||||
mgmt->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_authorizationRequest;
|
||||
Vanetza_Security_InnerAtRequest_t& iar = mgmt->content.choice.authorizationRequest;
|
||||
|
||||
// 1. Public keys carried in the request
|
||||
// verificationKey is required and will be the new AT's verification key
|
||||
set_verification_key(iar.publicKeys.verificationKey, params.verification_key);
|
||||
// encryptionKey is optional for future encrypted communication
|
||||
if (params.at_encryption_key) {
|
||||
iar.publicKeys.encryptionKey = asn1::allocate<Vanetza_Security_PublicEncryptionKey_t>();
|
||||
set_encryption_key(*iar.publicKeys.encryptionKey, *params.at_encryption_key);
|
||||
}
|
||||
|
||||
// 2. Random 32-byte hmacKey
|
||||
ByteBuffer hmac_key = security.generate_nonce(32);
|
||||
OCTET_STRING_fromBuf(&iar.hmacKey, reinterpret_cast<const char*>(hmac_key.data()), hmac_key.size());
|
||||
|
||||
// 3. SharedAtRequest
|
||||
Vanetza_Security_SharedAtRequest_t& sar = iar.sharedAtRequest;
|
||||
HashedId8 ea_hid8 = params.ea_certificate->calculate_hashed_id8(security);
|
||||
OCTET_STRING_fromBuf(&sar.eaId, reinterpret_cast<const char*>(ea_hid8.octets.data()), ea_hid8.octets.size());
|
||||
sar.certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
add_app_permissions(sar.requestedSubjectAttributes, params.permissions);
|
||||
if (params.validity_period) {
|
||||
sar.requestedSubjectAttributes.validityPeriod = asn1::allocate<Vanetza_Security_ValidityPeriod_t>();
|
||||
auto* vp = sar.requestedSubjectAttributes.validityPeriod;
|
||||
vp->start = security::v3::convert_time32(params.validity_period->start);
|
||||
vp->duration.present = Vanetza_Security_Duration_PR_hours;
|
||||
vp->duration.choice.hours = params.validity_period->duration.count();
|
||||
}
|
||||
|
||||
// 4. keyTag = first 16 bytes of HMAC-SHA256(hmacKey, verifyKey [|| encKey])
|
||||
ByteBuffer verify_oer =
|
||||
asn1::encode_oer(asn_DEF_Vanetza_Security_PublicVerificationKey, &iar.publicKeys.verificationKey);
|
||||
ByteBuffer hmac_input = verify_oer;
|
||||
if (iar.publicKeys.encryptionKey) {
|
||||
ByteBuffer enc_oer =
|
||||
asn1::encode_oer(asn_DEF_Vanetza_Security_PublicEncryptionKey, iar.publicKeys.encryptionKey);
|
||||
hmac_input.insert(hmac_input.end(), enc_oer.begin(), enc_oer.end());
|
||||
}
|
||||
ByteBuffer full_tag = security.calculate_hmac_sha256(hmac_key, hmac_input);
|
||||
OCTET_STRING_fromBuf(&sar.keyTag, reinterpret_cast<const char*>(full_tag.data()), 16);
|
||||
|
||||
// 5. EC proof: external-payload signed data over SharedAtRequest, signed by EC.
|
||||
ByteBuffer sar_encoded = asn1::encode_oer(asn_DEF_Vanetza_Security_SharedAtRequest, &sar);
|
||||
SignedData ec_signed =
|
||||
create_external_signed(sar_encoded, security, params.ec->get_public_key(), params.hash_algo, params.ec);
|
||||
ByteBuffer ec_signed_encoded = ec_signed.encode();
|
||||
|
||||
// 6. Encrypt the EC proof to the EA → encryptedEcSignature
|
||||
iar.ecSignature.present = Vanetza_Security_EcSignature_PR_encryptedEcSignature;
|
||||
encrypt_into(iar.ecSignature.choice.encryptedEcSignature, security, ec_signed_encoded, *params.ea_certificate);
|
||||
|
||||
if (!mgmt.validate()) {
|
||||
throw std::runtime_error("AuthorizationRequest: constructed InnerAtRequest is invalid");
|
||||
}
|
||||
ByteBuffer mgmt_encoded = mgmt.encode();
|
||||
|
||||
if (!params.include_pop) {
|
||||
return mgmt_encoded;
|
||||
}
|
||||
|
||||
// 7. POP wrap: EtsiTs103097Data-Signed (signer = self) signed with the new AT verification key
|
||||
SignedData pop_signed = create_signed(mgmt_encoded, security, params.verification_key, params.hash_algo, nullptr);
|
||||
return pop_signed.encode();
|
||||
}
|
||||
|
||||
EncryptedData build_authorization_request(SecurityModule& security, const AuthorizationRequestParameters& params)
|
||||
{
|
||||
validate(params);
|
||||
|
||||
ByteBuffer plaintext = build_signed_authorization_request(security, params);
|
||||
|
||||
boost::optional<PublicKey> aa_enc_key = params.aa_certificate->get_encryption_key();
|
||||
if (!aa_enc_key) {
|
||||
throw DecodingFailure("AuthorizationRequest: AA certificate has no encryption key");
|
||||
}
|
||||
Sha256Hash aa_hash = calculate_sha256_hash(security, *params.aa_certificate);
|
||||
auto ecies_unique = security.create_ecies_context(*aa_enc_key, aa_hash);
|
||||
std::shared_ptr<SecurityModule::EciesContext> ecies { std::move(ecies_unique) };
|
||||
|
||||
EncryptedData encrypted { ecies };
|
||||
encrypted.generate_ciphertext(plaintext);
|
||||
encrypted.add_recipient_info(params.aa_certificate->calculate_hashed_id8(security));
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include "keys.hpp"
|
||||
#include "psid_ssp.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
#include <vanetza/security/hash_algorithm.hpp>
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <chrono>
|
||||
#include <list>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class Certificate;
|
||||
class EncryptedData;
|
||||
class SecurityModule;
|
||||
|
||||
using security::HashAlgorithm;
|
||||
|
||||
/**
|
||||
* \brief Hint for sharedAtRequest.requestedSubjectAttributes.validityPeriod.
|
||||
* \see IEEE 1609.2 Time32 / Duration::hours
|
||||
*/
|
||||
struct ValidityPeriodHint
|
||||
{
|
||||
Clock::time_point start;
|
||||
std::chrono::hours duration;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Parameters for an AuthorizationRequest (encryptedEcSignature variant).
|
||||
* \see TS 102 941 §6.2.3.3.1
|
||||
*/
|
||||
struct AuthorizationRequestParameters
|
||||
{
|
||||
const Certificate* ec = nullptr; // current EC, signs the inner EC proof; mandatory
|
||||
const Certificate* ea_certificate = nullptr; // recipient of encryptedEcSignature; mandatory
|
||||
const Certificate* aa_certificate = nullptr; // recipient of outer encryption; mandatory
|
||||
PublicKey verification_key; // fresh key to be certified; private key in SecurityModule; mandatory
|
||||
boost::optional<PublicKey> at_encryption_key; // optional encryption key embedded in the AT
|
||||
std::list<PsidSsp> permissions; // requested PSID/SSP set; must be non-empty
|
||||
HashAlgorithm hash_algo = HashAlgorithm::SHA256; // EC proof and extDataHash; SHA-256 only
|
||||
boost::optional<ValidityPeriodHint> validity_period; // optional; AA decides within CP §7.2.1 bounds
|
||||
bool include_pop = true; // send AuthorizationRequestMessageWithPop; required by deployed AAs
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Build the inner EtsiTs102941Data{authorizationRequest} plaintext.
|
||||
*
|
||||
* Exposed for testing; production code should call build_authorization_request().
|
||||
*/
|
||||
ByteBuffer build_signed_authorization_request(SecurityModule& security,
|
||||
const AuthorizationRequestParameters& parameters);
|
||||
|
||||
/**
|
||||
* \brief Build the AA-encrypted authorization request.
|
||||
*
|
||||
* Call .encode() on the result for the OER bytes to POST as `application/x-its-request`.
|
||||
*/
|
||||
EncryptedData build_authorization_request(SecurityModule& security, const AuthorizationRequestParameters& parameters);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "at_response.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include "signed_data.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/asn1/security/InnerAtResponse.h>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
AuthorizationResponse parse_authorization_response(SecurityModule& security, const ByteBuffer& decrypted,
|
||||
const Certificate& aa_certificate)
|
||||
{
|
||||
SignedData outer;
|
||||
if (!outer.decode(decrypted)) {
|
||||
throw DecodingFailure("decoding signed authorization response failed");
|
||||
}
|
||||
if (outer->content->present != Vanetza_Security_Ieee1609Dot2Content_PR_signedData) {
|
||||
throw DecodingFailure("authorization response content is not signedData");
|
||||
}
|
||||
const Vanetza_Security_SignedData_t& sd = *outer->content->choice.signedData;
|
||||
|
||||
// Per TS 102 941 §6.2.3.3.2 the AA signs with signer = digest(AA cert).
|
||||
const HashedId8 aa_hid8 = aa_certificate.calculate_hashed_id8(security);
|
||||
if (sd.signer.present != Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||
throw DecodingFailure("authorization response must have signer = digest");
|
||||
}
|
||||
if (sd.signer.choice.digest != aa_hid8.octets) {
|
||||
throw VerificationFailure("authorization response signer digest does not match AA certificate");
|
||||
}
|
||||
|
||||
if (sd.tbsData->headerInfo.psid != aid::SCR) {
|
||||
throw DecodingFailure("authorization response PSID is not SCR");
|
||||
}
|
||||
|
||||
if (!validate(security, sd, aa_certificate.raw())) {
|
||||
throw VerificationFailure("authorization response signature does not verify against AA certificate");
|
||||
}
|
||||
|
||||
const Vanetza_Security_Opaque_t* inner_opaque = get_signed_payload(outer->content);
|
||||
if (!inner_opaque) {
|
||||
throw DecodingFailure("authorization response carries no unsecured signed payload");
|
||||
}
|
||||
|
||||
AuthorizationResponseData inner = AuthorizationResponseData::from_opaque(*inner_opaque);
|
||||
if (inner->version != Vanetza_Security_Version_v1) {
|
||||
throw DecodingFailure("inner EtsiTs102941Data version is not v1");
|
||||
}
|
||||
|
||||
const Vanetza_Security_InnerAtResponse_t& at_resp = inner->content.choice.authorizationResponse;
|
||||
|
||||
AuthorizationResponse result;
|
||||
result.code = AuthorizationResponseCode { at_resp.responseCode };
|
||||
result.request_hash.assign(at_resp.requestHash.buf, at_resp.requestHash.buf + at_resp.requestHash.size);
|
||||
|
||||
if (at_resp.certificate) {
|
||||
result.certificate = Certificate(*at_resp.certificate);
|
||||
}
|
||||
|
||||
if (at_resp.responseCode == Vanetza_Security_AuthorizationResponseCode_ok && !result.certificate) {
|
||||
throw DecodingFailure("authorization response code is ok but no certificate is included");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate.hpp"
|
||||
#include "response_codes.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <boost/optional/optional.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class SecurityModule;
|
||||
|
||||
// Result of parsing a decrypted AuthorizationResponse payload as specified
|
||||
// in ETSI TS 102 941 §6.2.3.3.2.
|
||||
struct AuthorizationResponse
|
||||
{
|
||||
// Response code from InnerAtResponse. Parsing succeeds regardless of
|
||||
// the code value; the caller decides how to act on non-ok results.
|
||||
AuthorizationResponseCode code;
|
||||
|
||||
// requestHash from InnerAtResponse (SHA-256 prefix of the request).
|
||||
ByteBuffer request_hash;
|
||||
|
||||
// New Authorization Ticket returned by the AA. Present iff the parser
|
||||
// was able to decode a certificate; the caller must still check that
|
||||
// `code` is `ok` before relying on it.
|
||||
boost::optional<Certificate> certificate;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a decrypted AuthorizationResponse per TS 102 941 §6.2.3.3.2.
|
||||
*
|
||||
* Verifies:
|
||||
* - outer Ieee1609Dot2Data is signedData
|
||||
* - signer = digest, matching HashedId8(aa_certificate)
|
||||
* - tbsData.headerInfo.psid == aid::SCR
|
||||
* - outer signature verifies against aa_certificate
|
||||
* - inner EtsiTs102941Data.version == v1
|
||||
* - inner content variant is authorizationResponse
|
||||
*
|
||||
* If `code == ok` the message MUST carry a certificate per TS 102 941;
|
||||
* for non-ok codes the parser returns normally with whatever certificate
|
||||
* (if any) was provided.
|
||||
*
|
||||
* \throws DecodingFailure on structural failure or missing required certificate
|
||||
* \throws VerificationFailure on signer-digest or signature mismatch
|
||||
*/
|
||||
AuthorizationResponse parse_authorization_response(SecurityModule& security, const ByteBuffer& decrypted,
|
||||
const Certificate& aa_certificate);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,343 @@
|
||||
#include "authorization.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "at_request.hpp"
|
||||
#include "at_response.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "ea_request.hpp"
|
||||
#include "encrypted_data.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hexstring.hpp"
|
||||
#include "http.hpp"
|
||||
#include "prune_command.hpp"
|
||||
#include "psid_ssp.hpp"
|
||||
#include "response_codes.hpp"
|
||||
#include "time.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <CLI/CLI.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_io.hpp>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct Context
|
||||
{
|
||||
Context(const MainConfig& c) : cfg(c)
|
||||
{
|
||||
}
|
||||
|
||||
std::string url(const AuthorizationAuthority& aa) const
|
||||
{
|
||||
return resolve_url(aa.access_point, url_override);
|
||||
}
|
||||
|
||||
const MainConfig& cfg;
|
||||
std::string url_override;
|
||||
std::function<void()> action;
|
||||
|
||||
KeyType key_type = KeyType::BrainpoolP256r1;
|
||||
HashAlgorithm hash_algo = HashAlgorithm::SHA256;
|
||||
std::list<PsidSsp> permissions;
|
||||
unsigned count = 1;
|
||||
Clock::time_point validity_start = current_time();
|
||||
std::chrono::hours validity_duration { 24 * 7 }; // 1 week, the CP §7.2.1 max
|
||||
bool custom_validity = false; // true if user set --validity-start/-duration; else no hint, AA picks
|
||||
};
|
||||
|
||||
const std::map<std::string, KeyType> key_type_map = {
|
||||
{ "NistP256", KeyType::NistP256 },
|
||||
{ "BrainpoolP256r1", KeyType::BrainpoolP256r1 },
|
||||
{ "BrainpoolP384r1", KeyType::BrainpoolP384r1 },
|
||||
};
|
||||
|
||||
const std::map<std::string, HashAlgorithm> hash_algo_map = {
|
||||
{ "SHA256", HashAlgorithm::SHA256 },
|
||||
{ "SHA384", HashAlgorithm::SHA384 },
|
||||
};
|
||||
|
||||
void list_tickets(Context& ctx);
|
||||
void request_ticket(Context& ctx);
|
||||
|
||||
} // namespace
|
||||
|
||||
std::shared_ptr<CLI::App> build_authorization_command(const MainConfig& cfg)
|
||||
{
|
||||
auto ctx = std::make_shared<Context>(cfg);
|
||||
auto app = std::make_shared<CLI::App>("authorization tickets (AT)", "authorization");
|
||||
app->alias("auth");
|
||||
app->alias("at");
|
||||
app->add_option("--url", ctx->url_override, "override the Authorization Authority URL");
|
||||
|
||||
auto list = app->add_subcommand("list", "list stored authorization tickets");
|
||||
list->callback([ctx]() { ctx->action = [ctx]() { list_tickets(*ctx); }; });
|
||||
|
||||
auto request = app->add_subcommand("request", "request a new authorization ticket");
|
||||
request->fallthrough();
|
||||
request->add_option("--key-type", ctx->key_type, "type of generated verification key")
|
||||
->default_val(KeyType::BrainpoolP256r1)
|
||||
->capture_default_str()
|
||||
->transform(CLI::CheckedTransformer(key_type_map, CLI::ignore_case));
|
||||
request->add_option("--hash-algorithm", ctx->hash_algo, "hash algorithm for signing")
|
||||
->default_val(HashAlgorithm::SHA256)
|
||||
->capture_default_str()
|
||||
->transform(CLI::CheckedTransformer(hash_algo_map, CLI::ignore_case));
|
||||
request->add_option("--permission", ctx->permissions, "requested AT permission (PSID[:HEX_SSP]); repeatable")
|
||||
->required();
|
||||
request->add_option("--count", ctx->count, "number of ATs to request in this run")
|
||||
->default_val(1)
|
||||
->capture_default_str()
|
||||
->check(CLI::PositiveNumber);
|
||||
CLI::callback_t validity_start_cb = [ctx](const CLI::results_t& v) -> bool {
|
||||
if (v.size() != 1) {
|
||||
return false;
|
||||
}
|
||||
auto parsed = parse_validity_start(v[0]);
|
||||
if (!parsed) {
|
||||
return false;
|
||||
}
|
||||
ctx->validity_start = *parsed;
|
||||
ctx->custom_validity = true;
|
||||
return true;
|
||||
};
|
||||
CLI::callback_t validity_duration_cb = [ctx](const CLI::results_t& v) -> bool {
|
||||
if (v.size() != 1) {
|
||||
return false;
|
||||
}
|
||||
auto parsed = parse_duration_hours(v[0]);
|
||||
if (!parsed) {
|
||||
return false;
|
||||
}
|
||||
ctx->validity_duration = *parsed;
|
||||
ctx->custom_validity = true;
|
||||
return true;
|
||||
};
|
||||
request
|
||||
->add_option("--validity-start", validity_start_cb,
|
||||
"AT validity start: 'YYYY-MM-DD[THH:MM:SS]' or relative '+Nd/h/w'")
|
||||
->default_str("now");
|
||||
request->add_option("--validity-duration", validity_duration_cb, "AT validity duration: 'Nh', 'Nd', 'Nw'")
|
||||
->default_str("1w");
|
||||
request->callback([ctx]() { ctx->action = [ctx]() { request_ticket(*ctx); }; });
|
||||
|
||||
auto prune = app->add_subcommand("prune", "delete expired authorization tickets");
|
||||
auto prune_dry = prune->add_flag("--dry-run,-n", "list only; do not delete");
|
||||
prune->callback([ctx, prune_dry]() {
|
||||
const bool dry_run = prune_dry->as<bool>();
|
||||
ctx->action = [ctx, dry_run]() { prune_expired_tickets(ctx->cfg, current_time(), dry_run); };
|
||||
});
|
||||
|
||||
// Default when no subcommand is picked: list.
|
||||
app->final_callback([ctx]() {
|
||||
if (!ctx->action) {
|
||||
ctx->action = [ctx]() { list_tickets(*ctx); };
|
||||
}
|
||||
ctx->action();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct AuthoritiesFromCtl
|
||||
{
|
||||
EnrolmentAuthority ea;
|
||||
AuthorizationAuthority aa;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Look up the EA (encryptedEcSignature recipient) and AA (outer encryption)
|
||||
* from the current Root CA's stored CTL.
|
||||
* \throws if the CTL is missing, either authority is not listed, or encryption keys are missing
|
||||
*/
|
||||
AuthoritiesFromCtl lookup_authorities(Context& ctx)
|
||||
{
|
||||
auto processor = process_stored_ctl(*ctx.cfg.trust_lists, ctx.cfg.security, ctx.cfg.root_ca_hid8);
|
||||
return AuthoritiesFromCtl { require_enrolment_authority(processor, ctx.cfg.root_ca_hid8),
|
||||
require_authorization_authority(processor, ctx.cfg.root_ca_hid8) };
|
||||
}
|
||||
|
||||
/// \brief Format one appPermissions entry as 'PSID[:HEX_SSP]', mirroring --permission.
|
||||
std::string format_app_permission(const Vanetza_Security_PsidSsp_t& entry)
|
||||
{
|
||||
std::string out = std::to_string(entry.psid);
|
||||
if (entry.ssp) {
|
||||
const auto& ssp = *entry.ssp;
|
||||
const std::uint8_t* buf = nullptr;
|
||||
std::size_t len = 0;
|
||||
if (ssp.present == Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp) {
|
||||
buf = ssp.choice.bitmapSsp.buf;
|
||||
len = ssp.choice.bitmapSsp.size;
|
||||
} else if (ssp.present == Vanetza_Security_ServiceSpecificPermissions_PR_opaque) {
|
||||
buf = ssp.choice.opaque.buf;
|
||||
len = ssp.choice.opaque.size;
|
||||
}
|
||||
if (buf && len > 0) {
|
||||
out += ":";
|
||||
out += hexstring(buf, len);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// \brief Print one stored AT to stdout: header line, validity range, appPermissions.
|
||||
void describe_ticket(Context& ctx, const HashedId8& at_id, const Certificate& at)
|
||||
{
|
||||
Clock::time_point start = at.valid_since();
|
||||
Clock::time_point stop = at.valid_until();
|
||||
Clock::time_point now = current_time();
|
||||
const char* state = (now < start) ? "[not yet valid]" : (now > stop) ? "[expired]" : "[valid now]";
|
||||
std::cout << hexstring(at_id);
|
||||
auto name = at.get_name();
|
||||
if (!name.empty()) {
|
||||
std::cout << " " << name;
|
||||
}
|
||||
std::cout << " " << state << "\n";
|
||||
std::cout << " valid: " << Clock::at(start) << " until " << Clock::at(stop) << "\n";
|
||||
|
||||
const auto* ap = at.raw().toBeSigned.appPermissions;
|
||||
if (ap && ap->list.count > 0) {
|
||||
std::cout << " permissions:";
|
||||
for (int i = 0; i < ap->list.count; ++i) {
|
||||
if (ap->list.array[i]) {
|
||||
std::cout << " " << format_app_permission(*ap->list.array[i]);
|
||||
}
|
||||
}
|
||||
std::cout << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
/// \brief Print every stored AT plus a count line.
|
||||
void list_tickets(Context& ctx)
|
||||
{
|
||||
std::size_t count = 0;
|
||||
for (const auto& id : ctx.cfg.tickets->list()) {
|
||||
if (count == 0) {
|
||||
std::cout << "Stored authorization ticket(s):\n";
|
||||
}
|
||||
++count;
|
||||
auto at = ctx.cfg.tickets->fetch(id);
|
||||
if (!at) {
|
||||
std::cout << hexstring(id) << " [unreadable]\n";
|
||||
continue;
|
||||
}
|
||||
describe_ticket(ctx, id, *at);
|
||||
}
|
||||
if (count == 0) {
|
||||
std::cout << "No authorization tickets stored.\n";
|
||||
} else {
|
||||
std::cout << count << " authorization ticket(s) total.\n";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief One AA round-trip: fresh AT key, build, POST, decrypt, parse, store.
|
||||
*
|
||||
* EA/AA are looked up by the caller so they can be reused across a batch.
|
||||
* \throws on any failure
|
||||
*/
|
||||
void request_one_ticket(Context& ctx, const Certificate& ec, const AuthoritiesFromCtl& auth,
|
||||
const boost::optional<ValidityPeriodHint>& validity)
|
||||
{
|
||||
ScopedKeyPair scoped_at_key(*ctx.cfg.security, ctx.key_type);
|
||||
|
||||
AuthorizationRequestParameters params;
|
||||
params.ec = &ec;
|
||||
params.ea_certificate = &auth.ea.certificate;
|
||||
params.aa_certificate = &auth.aa.certificate;
|
||||
params.verification_key = scoped_at_key.public_key();
|
||||
params.permissions = ctx.permissions;
|
||||
params.hash_algo = ctx.hash_algo;
|
||||
params.validity_period = validity;
|
||||
|
||||
EncryptedData encrypted_data = build_authorization_request(*ctx.cfg.security, params);
|
||||
|
||||
auto query = HttpQuery::from_url(ctx.url(auth.aa));
|
||||
auto encoded = encrypted_data.encode();
|
||||
auto req_hash = ctx.cfg.security->calculate_sha256_hash(encoded.data(), encoded.size());
|
||||
auto response = http_post(query, "application/x-its-request", encoded);
|
||||
|
||||
if (response.result() != boost::beast::http::status::ok) {
|
||||
throw HttpException("AA returned an unexpected HTTP status for the authorization request",
|
||||
std::move(response));
|
||||
} else if (response[boost::beast::http::field::content_type] != "application/x-its-response") {
|
||||
throw HttpException("expected application/x-its-response");
|
||||
}
|
||||
|
||||
if (!encrypted_data.decode(response.body().data(), response.body().size())) {
|
||||
throw DecodingFailure("decoding encrypted AT response failed");
|
||||
}
|
||||
ByteBuffer dec_resp = encrypted_data.decrypt();
|
||||
|
||||
AuthorizationResponse at_resp = parse_authorization_response(*ctx.cfg.security, dec_resp, auth.aa.certificate);
|
||||
if (!check_request_hash(req_hash, at_resp.request_hash)) {
|
||||
throw VerificationFailure("mismatch between request and response hash");
|
||||
}
|
||||
if (at_resp.code != Vanetza_Security_AuthorizationResponseCode_ok) {
|
||||
throw std::runtime_error("AA response code: " + vanetza::pki::to_string(at_resp.code));
|
||||
}
|
||||
|
||||
Certificate& at = *at_resp.certificate;
|
||||
HashedId8 at_id = at.calculate_hashed_id8(*ctx.cfg.security);
|
||||
scoped_at_key.commit();
|
||||
ctx.cfg.tickets->store(at);
|
||||
std::cout << "Stored new AT " << hexstring(at_id) << "\n";
|
||||
describe_ticket(ctx, at_id, at);
|
||||
}
|
||||
|
||||
/// \brief Validate preconditions, look up the AA, then request `ctx.count` ATs in sequence.
|
||||
void request_ticket(Context& ctx)
|
||||
{
|
||||
if (ctx.permissions.empty()) {
|
||||
throw UsageError("at least one --permission must be specified");
|
||||
}
|
||||
|
||||
// Preconditions and authority lookup are shared across the whole batch.
|
||||
auto ec_id = ctx.cfg.station->get_ec_identifier();
|
||||
if (!ec_id) {
|
||||
throw UsageError("no EC available", "run 'enrolment initial' first");
|
||||
}
|
||||
auto ec = ctx.cfg.enrolment_credentials->fetch(*ec_id);
|
||||
if (!ec) {
|
||||
throw UsageError("EC certificate missing from storage", "re-run 'enrolment initial'");
|
||||
}
|
||||
if (!ctx.cfg.security->can_sign(ec->get_public_key())) {
|
||||
throw UsageError("no EC private key available", "re-run 'enrolment initial'");
|
||||
}
|
||||
|
||||
// Send a validityPeriod hint only when the user explicitly set --validity-start or --validity-duration.
|
||||
// Otherwise leave it out so the AA picks unilaterally.
|
||||
boost::optional<ValidityPeriodHint> validity;
|
||||
if (ctx.custom_validity) {
|
||||
validity = ValidityPeriodHint { ctx.validity_start, ctx.validity_duration };
|
||||
}
|
||||
|
||||
AuthoritiesFromCtl auth = lookup_authorities(ctx);
|
||||
HashedId8 aa_hid8 = auth.aa.certificate.calculate_hashed_id8(*ctx.cfg.security);
|
||||
std::cout << "Authorizing against AA " << hexstring(aa_hid8) << " at " << ctx.url(auth.aa) << "\n";
|
||||
|
||||
for (unsigned i = 1; i <= ctx.count; ++i) {
|
||||
if (ctx.count > 1) {
|
||||
std::cout << "--- AT " << i << " of " << ctx.count << " ---\n";
|
||||
}
|
||||
request_one_ticket(ctx, *ec, auth, validity);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "main.hpp"
|
||||
#include <CLI/App.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
std::shared_ptr<CLI::App> build_authorization_command(const MainConfig&);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,514 @@
|
||||
#include "certificate.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
bool is_compressed(const Vanetza_Security_EccP256CurvePoint& point)
|
||||
{
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool is_compressed(const Vanetza_Security_EccP384CurvePoint& point)
|
||||
{
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP384CurvePoint_PR_compressed_y_0:
|
||||
case Vanetza_Security_EccP384CurvePoint_PR_compressed_y_1:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool is_signature_x_only(const Vanetza_Security_Signature_t& sig)
|
||||
{
|
||||
switch (sig.present) {
|
||||
case Vanetza_Security_Signature_PR_ecdsaNistP256Signature:
|
||||
return sig.choice.ecdsaNistP256Signature.rSig.present == Vanetza_Security_EccP256CurvePoint_PR_x_only;
|
||||
case Vanetza_Security_Signature_PR_ecdsaBrainpoolP256r1Signature:
|
||||
return sig.choice.ecdsaBrainpoolP256r1Signature.rSig.present ==
|
||||
Vanetza_Security_EccP256CurvePoint_PR_x_only;
|
||||
case Vanetza_Security_Signature_PR_ecdsaBrainpoolP384r1Signature:
|
||||
return sig.choice.ecdsaBrainpoolP384r1Signature.rSig.present ==
|
||||
Vanetza_Security_EccP384CurvePoint_PR_x_only;
|
||||
default:
|
||||
return true; // not an ECDSA signature at all
|
||||
}
|
||||
}
|
||||
|
||||
void copy_coordinates(const Vanetza_Security_EccP256CurvePoint_t& point, PublicKey& key)
|
||||
{
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
|
||||
key.compression = KeyCompression::NoCompression;
|
||||
pki::copy(point.choice.uncompressedP256.x, key.x);
|
||||
pki::copy(point.choice.uncompressedP256.y, key.y);
|
||||
break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||
key.compression = KeyCompression::Y0;
|
||||
pki::copy(point.choice.compressed_y_0, key.x);
|
||||
break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||
key.compression = KeyCompression::Y1;
|
||||
pki::copy(point.choice.compressed_y_1, key.x);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("unsupported curve point type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
template<KeyType> PublicKey make_public_key(const Vanetza_Security_EccP256CurvePoint_t& point);
|
||||
|
||||
template<> PublicKey make_public_key<KeyType::NistP256>(const Vanetza_Security_EccP256CurvePoint_t& point)
|
||||
{
|
||||
PublicKey pub;
|
||||
pub.type = KeyType::NistP256;
|
||||
copy_coordinates(point, pub);
|
||||
return pub;
|
||||
}
|
||||
|
||||
template<> PublicKey make_public_key<KeyType::BrainpoolP256r1>(const Vanetza_Security_EccP256CurvePoint_t& point)
|
||||
{
|
||||
PublicKey pub;
|
||||
pub.type = KeyType::BrainpoolP256r1;
|
||||
copy_coordinates(point, pub);
|
||||
return pub;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Certificate::Certificate() : m_asn1(asn_DEF_Vanetza_Security_EtsiTs103097Certificate)
|
||||
{
|
||||
}
|
||||
|
||||
Certificate::Certificate(const Vanetza_Security_EtsiTs103097Certificate_t& src) :
|
||||
m_asn1(asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &src)
|
||||
{
|
||||
}
|
||||
|
||||
std::string Certificate::get_name() const
|
||||
{
|
||||
return pki::get_name(*m_asn1);
|
||||
}
|
||||
|
||||
PublicKey Certificate::get_public_key() const
|
||||
{
|
||||
return pki::get_public_key(*m_asn1);
|
||||
}
|
||||
|
||||
boost::optional<PublicKey> Certificate::get_encryption_key() const
|
||||
{
|
||||
if (m_asn1->toBeSigned.encryptionKey) {
|
||||
const Vanetza_Security_PublicEncryptionKey_t& enckey = *m_asn1->toBeSigned.encryptionKey;
|
||||
switch (enckey.publicKey.present) {
|
||||
case Vanetza_Security_BasePublicEncryptionKey_PR_eciesNistP256:
|
||||
return make_public_key<KeyType::NistP256>(enckey.publicKey.choice.eciesNistP256);
|
||||
break;
|
||||
case Vanetza_Security_BasePublicEncryptionKey_PR_eciesBrainpoolP256r1:
|
||||
return make_public_key<KeyType::BrainpoolP256r1>(enckey.publicKey.choice.eciesBrainpoolP256r1);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("unsupported encryption key type");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
Clock::time_point Certificate::valid_since() const
|
||||
{
|
||||
return Clock::time_point { std::chrono::seconds(m_asn1->toBeSigned.validityPeriod.start) };
|
||||
}
|
||||
|
||||
Clock::time_point Certificate::valid_until() const
|
||||
{
|
||||
Clock::duration d;
|
||||
const Vanetza_Security_Duration& asn1_d = m_asn1->toBeSigned.validityPeriod.duration;
|
||||
switch (asn1_d.present) {
|
||||
case Vanetza_Security_Duration_PR_years:
|
||||
// IEEE 1609.2: "A year is considered to be 31556952 seconds"
|
||||
d = asn1_d.choice.years * std::chrono::seconds(31556952);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_sixtyHours:
|
||||
d = std::chrono::hours(60 * asn1_d.choice.sixtyHours);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_hours:
|
||||
d = std::chrono::hours(asn1_d.choice.hours);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_minutes:
|
||||
d = std::chrono::minutes(asn1_d.choice.minutes);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_seconds:
|
||||
d = std::chrono::seconds(asn1_d.choice.seconds);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_milliseconds:
|
||||
d = std::chrono::milliseconds(asn1_d.choice.milliseconds);
|
||||
break;
|
||||
case Vanetza_Security_Duration_PR_microseconds:
|
||||
d = std::chrono::microseconds(asn1_d.choice.microseconds);
|
||||
break;
|
||||
default:
|
||||
// no validity duration as safe fallback
|
||||
d = std::chrono::seconds(0);
|
||||
break;
|
||||
}
|
||||
return valid_since() + d;
|
||||
}
|
||||
|
||||
bool Certificate::decode(const char* data, std::size_t length)
|
||||
{
|
||||
return m_asn1.decode(data, length);
|
||||
}
|
||||
|
||||
bool Certificate::decode(const std::string& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
bool Certificate::decode(const ByteBuffer& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
ByteBuffer Certificate::encode() const
|
||||
{
|
||||
return m_asn1.encode();
|
||||
}
|
||||
|
||||
void Certificate::print() const
|
||||
{
|
||||
xer_fprint(stdout, &asn_DEF_Vanetza_Security_EtsiTs103097Certificate, &*m_asn1);
|
||||
}
|
||||
|
||||
bool Certificate::is_canonical() const
|
||||
{
|
||||
return vanetza::pki::is_canonical(*m_asn1);
|
||||
}
|
||||
|
||||
HashedId8 Certificate::calculate_hashed_id8(SecurityModule& sec) const
|
||||
{
|
||||
return vanetza::pki::calculate_hashed_id8(sec, *m_asn1);
|
||||
}
|
||||
|
||||
Sha256Hash calculate_sha256_hash(SecurityModule& sec, const Certificate& cert)
|
||||
{
|
||||
ByteBuffer buffer = cert.encode();
|
||||
return sec.calculate_sha256_hash(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
Sha384Hash calculate_sha384_hash(SecurityModule& sec, const Certificate& cert)
|
||||
{
|
||||
ByteBuffer buffer = cert.encode();
|
||||
return sec.calculate_sha384_hash(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
bool is_currently_valid(const Certificate& cert, Clock::time_point t)
|
||||
{
|
||||
return cert.valid_since() <= t && cert.valid_until() >= t;
|
||||
}
|
||||
|
||||
bool is_root_ca(const Certificate& cert)
|
||||
{
|
||||
const auto& issuer = cert.raw().issuer;
|
||||
const bool self_issued = (issuer.present == Vanetza_Security_IssuerIdentifier_PR_self);
|
||||
if (!self_issued) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& tbs = cert.raw().toBeSigned;
|
||||
const bool can_issue = tbs.certIssuePermissions && tbs.certIssuePermissions->list.count > 0;
|
||||
if (!can_issue) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (tbs.appPermissions) {
|
||||
bool sign_crl = false;
|
||||
bool sign_ctl = false;
|
||||
|
||||
for (int i = 0; i < tbs.appPermissions->list.count; ++i) {
|
||||
const Vanetza_Security_PsidSsp_t* permission = tbs.appPermissions->list.array[i];
|
||||
if (!permission) {
|
||||
continue;
|
||||
}
|
||||
switch (permission->psid) {
|
||||
case aid::CTL:
|
||||
sign_ctl = true;
|
||||
break;
|
||||
|
||||
case aid::CRL:
|
||||
sign_crl = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
// no op
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!sign_ctl || !sign_crl) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
bool issuing_scope_contains(const Certificate& cert, ItsAid target)
|
||||
{
|
||||
const auto* cip = cert.raw().toBeSigned.certIssuePermissions;
|
||||
if (!cip) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < cip->list.count; ++i) {
|
||||
const auto* group = cip->list.array[i];
|
||||
if (!group) {
|
||||
continue;
|
||||
}
|
||||
const auto& sp = group->subjectPermissions;
|
||||
if (sp.present == Vanetza_Security_SubjectPermissions_PR_all) {
|
||||
return true;
|
||||
}
|
||||
if (sp.present == Vanetza_Security_SubjectPermissions_PR_explicit) {
|
||||
const auto& ranges = sp.choice.Explicit.list;
|
||||
for (int j = 0; j < ranges.count; ++j) {
|
||||
if (ranges.array[j] && ranges.array[j]->psid == static_cast<long>(target)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool app_permissions_contains(const Certificate& cert, ItsAid target)
|
||||
{
|
||||
const auto* ap = cert.raw().toBeSigned.appPermissions;
|
||||
if (!ap) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < ap->list.count; ++i) {
|
||||
if (ap->list.array[i] && ap->list.array[i]->psid == static_cast<long>(target)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CertificateRole certificate_role(const Certificate& cert)
|
||||
{
|
||||
if (is_root_ca(cert)) {
|
||||
return CertificateRole::RootCa;
|
||||
}
|
||||
|
||||
const auto& tbs = cert.raw().toBeSigned;
|
||||
const bool self_issued = (cert.raw().issuer.present == Vanetza_Security_IssuerIdentifier_PR_self);
|
||||
const bool has_cert_issue = tbs.certIssuePermissions && tbs.certIssuePermissions->list.count > 0;
|
||||
|
||||
if (self_issued) {
|
||||
// TS 103 097 §7.2.5: TLM is self-signed, signs the CTL, no certIssuePermissions.
|
||||
if (!has_cert_issue && app_permissions_contains(cert, aid::CTL)) {
|
||||
return CertificateRole::Tlm;
|
||||
}
|
||||
return CertificateRole::Unknown;
|
||||
}
|
||||
|
||||
if (has_cert_issue) {
|
||||
// TS 103 097 §7.2.4 subordinate CA. Per TS 102 941 Table 1 the EA issues
|
||||
// enrolment credentials (SCR in scope); the AA issues authorization tickets.
|
||||
return issuing_scope_contains(cert, aid::SCR) ? CertificateRole::EnrolmentAuthority :
|
||||
CertificateRole::AuthorizationAuthority;
|
||||
}
|
||||
|
||||
// End entity: §7.2.2 EC uses CertificateId name, §7.2.1 AT uses CertificateId none.
|
||||
switch (tbs.id.present) {
|
||||
case Vanetza_Security_CertificateId_PR_name:
|
||||
return CertificateRole::EnrolmentCredential;
|
||||
case Vanetza_Security_CertificateId_PR_none:
|
||||
return CertificateRole::AuthorizationTicket;
|
||||
default:
|
||||
return CertificateRole::Unknown;
|
||||
}
|
||||
}
|
||||
|
||||
bool is_canonical(const Vanetza_Security_EtsiTs103097Certificate_t& cert)
|
||||
{
|
||||
bool compressed_point = true;
|
||||
const Vanetza_Security_VerificationKeyIndicator& indicator = cert.toBeSigned.verifyKeyIndicator;
|
||||
if (indicator.present == Vanetza_Security_VerificationKeyIndicator_PR_verificationKey) {
|
||||
const Vanetza_Security_PublicVerificationKey& pubkey = indicator.choice.verificationKey;
|
||||
switch (pubkey.present) {
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256:
|
||||
compressed_point = is_compressed(pubkey.choice.ecdsaNistP256);
|
||||
break;
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1:
|
||||
compressed_point = is_compressed(pubkey.choice.ecdsaBrainpoolP256r1);
|
||||
break;
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP384r1:
|
||||
compressed_point = is_compressed(pubkey.choice.ecdsaBrainpoolP384r1);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else if (indicator.present == Vanetza_Security_VerificationKeyIndicator_PR_reconstructionValue) {
|
||||
compressed_point = is_compressed(indicator.choice.reconstructionValue);
|
||||
}
|
||||
|
||||
if (!compressed_point) {
|
||||
return false;
|
||||
} else if (cert.signature && !is_signature_x_only(*cert.signature)) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Sha256Hash calculate_sha256_hash(SecurityModule& security, const Vanetza_Security_Certificate_t& cert)
|
||||
{
|
||||
ByteBuffer buffer = asn1::encode_oer(asn_DEF_Vanetza_Security_Certificate, &cert);
|
||||
return security.calculate_sha256_hash(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
Sha384Hash calculate_sha384_hash(SecurityModule& sec, const Vanetza_Security_Certificate_t& cert)
|
||||
{
|
||||
ByteBuffer buffer = asn1::encode_oer(asn_DEF_Vanetza_Security_Certificate, &cert);
|
||||
return sec.calculate_sha384_hash(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
HashedId8 calculate_hashed_id8(SecurityModule& sec, const Vanetza_Security_Certificate_t& cert)
|
||||
{
|
||||
if (!is_canonical(cert)) {
|
||||
throw std::runtime_error("HashedId8 can only be calculated for canonical certificates");
|
||||
}
|
||||
|
||||
// all explicit certificates possess an verification key
|
||||
const Vanetza_Security_VerificationKeyIndicator& indicator = cert.toBeSigned.verifyKeyIndicator;
|
||||
if (indicator.present == Vanetza_Security_VerificationKeyIndicator_PR_verificationKey) {
|
||||
switch (indicator.choice.verificationKey.present) {
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256:
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1:
|
||||
return HashedId8 { calculate_sha256_hash(sec, cert) };
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP384r1:
|
||||
return HashedId8 { calculate_sha384_hash(sec, cert) };
|
||||
default:
|
||||
throw std::runtime_error("do not know how to hash the certificate");
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
// fall back to SHA-256
|
||||
return HashedId8 { calculate_sha256_hash(sec, cert) };
|
||||
}
|
||||
}
|
||||
|
||||
PublicKey make_public_key(KeyType t, const Vanetza_Security_EccP256CurvePoint_t& point)
|
||||
{
|
||||
PublicKey pub;
|
||||
pub.type = t;
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_0:
|
||||
pub.compression = KeyCompression::Y0;
|
||||
pub.x = copy(point.choice.compressed_y_0);
|
||||
break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_compressed_y_1:
|
||||
pub.compression = KeyCompression::Y1;
|
||||
pub.x = copy(point.choice.compressed_y_1);
|
||||
break;
|
||||
case Vanetza_Security_EccP256CurvePoint_PR_uncompressedP256:
|
||||
pub.compression = KeyCompression::NoCompression;
|
||||
pub.x = copy(point.choice.uncompressedP256.x);
|
||||
pub.y = copy(point.choice.uncompressedP256.y);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("cannot create public key from given curve point");
|
||||
break;
|
||||
}
|
||||
return pub;
|
||||
}
|
||||
|
||||
PublicKey make_public_key(KeyType t, const Vanetza_Security_EccP384CurvePoint_t& point)
|
||||
{
|
||||
PublicKey pub;
|
||||
pub.type = t;
|
||||
switch (point.present) {
|
||||
case Vanetza_Security_EccP384CurvePoint_PR_compressed_y_0:
|
||||
pub.compression = KeyCompression::Y0;
|
||||
pub.x = copy(point.choice.compressed_y_0);
|
||||
break;
|
||||
case Vanetza_Security_EccP384CurvePoint_PR_compressed_y_1:
|
||||
pub.compression = KeyCompression::Y1;
|
||||
pub.x = copy(point.choice.compressed_y_1);
|
||||
break;
|
||||
case Vanetza_Security_EccP384CurvePoint_PR_uncompressedP384:
|
||||
pub.compression = KeyCompression::NoCompression;
|
||||
pub.x = copy(point.choice.uncompressedP384.x);
|
||||
pub.y = copy(point.choice.uncompressedP384.y);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("cannot create public key from given curve point");
|
||||
break;
|
||||
}
|
||||
return pub;
|
||||
}
|
||||
|
||||
PublicKey get_public_key(const Vanetza_Security_PublicVerificationKey_t& input)
|
||||
{
|
||||
switch (input.present) {
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaNistP256:
|
||||
return make_public_key(KeyType::NistP256, input.choice.ecdsaNistP256);
|
||||
break;
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP256r1:
|
||||
return make_public_key(KeyType::BrainpoolP256r1, input.choice.ecdsaBrainpoolP256r1);
|
||||
break;
|
||||
case Vanetza_Security_PublicVerificationKey_PR_ecdsaBrainpoolP384r1:
|
||||
return make_public_key(KeyType::BrainpoolP384r1, input.choice.ecdsaBrainpoolP384r1);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("unknown public verification key type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
PublicKey get_public_key(const Vanetza_Security_Certificate_t& cert)
|
||||
{
|
||||
switch (cert.toBeSigned.verifyKeyIndicator.present) {
|
||||
case Vanetza_Security_VerificationKeyIndicator_PR_verificationKey:
|
||||
return get_public_key(cert.toBeSigned.verifyKeyIndicator.choice.verificationKey);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("unable to fetch public key from certificate");
|
||||
}
|
||||
}
|
||||
|
||||
std::string get_name(const Vanetza_Security_Certificate_t& cert)
|
||||
{
|
||||
std::string name;
|
||||
if (cert.toBeSigned.id.present == Vanetza_Security_CertificateId_PR_name) {
|
||||
const UTF8String_t& hostname = cert.toBeSigned.id.choice.name;
|
||||
name = std::string { hostname.buf, hostname.buf + hostname.size };
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,92 @@
|
||||
#pragma once
|
||||
|
||||
#include "hashed_id8.hpp"
|
||||
#include "keys.hpp"
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/Certificate.h>
|
||||
#include <vanetza/asn1/security/EtsiTs103097Certificate.h>
|
||||
#include <vanetza/common/clock.hpp>
|
||||
|
||||
// asn1c quirk: complete the struct tags it forward-declares but never defines.
|
||||
struct Vanetza_Security_Certificate : Vanetza_Security_CertificateBase
|
||||
{
|
||||
};
|
||||
|
||||
struct Vanetza_Security_EtsiTs103097Certificate : Vanetza_Security_ExplicitCertificate_t
|
||||
{
|
||||
};
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class SecurityModule;
|
||||
|
||||
class Certificate
|
||||
{
|
||||
public:
|
||||
Certificate();
|
||||
explicit Certificate(const Vanetza_Security_EtsiTs103097Certificate_t&);
|
||||
|
||||
HashedId8 calculate_hashed_id8(SecurityModule&) const;
|
||||
bool is_canonical() const;
|
||||
std::string get_name() const;
|
||||
PublicKey get_public_key() const;
|
||||
Clock::time_point valid_since() const;
|
||||
Clock::time_point valid_until() const;
|
||||
boost::optional<PublicKey> get_encryption_key() const;
|
||||
|
||||
bool decode(const char* data, std::size_t length);
|
||||
bool decode(const std::string&);
|
||||
bool decode(const ByteBuffer&);
|
||||
ByteBuffer encode() const;
|
||||
|
||||
const Vanetza_Security_EtsiTs103097Certificate_t& raw() const
|
||||
{
|
||||
return *m_asn1;
|
||||
}
|
||||
|
||||
void print() const;
|
||||
|
||||
private:
|
||||
vanetza::asn1::asn1c_oer_wrapper<Vanetza_Security_EtsiTs103097Certificate_t> m_asn1;
|
||||
};
|
||||
|
||||
bool is_currently_valid(const Certificate&, Clock::time_point);
|
||||
|
||||
/**
|
||||
* Check if certificate is a compliant Root CA certificate.
|
||||
* Rules are given by section 7.3.2 in TS 103 097 V1.3.1
|
||||
*
|
||||
* \param cert
|
||||
* \return true if certificate complies
|
||||
*/
|
||||
bool is_root_ca(const Certificate&);
|
||||
|
||||
// PKI role inferred from issuer, permissions and CertificateId per TS 103 097 V2.1.1 §7.2.
|
||||
enum class CertificateRole
|
||||
{
|
||||
RootCa, // §7.2.3: self-issued CA
|
||||
EnrolmentAuthority, // §7.2.4: sub-CA whose issuing scope grants SCR
|
||||
AuthorizationAuthority, // §7.2.4: sub-CA whose issuing scope grants services
|
||||
EnrolmentCredential, // §7.2.2: end entity with CertificateId name
|
||||
AuthorizationTicket, // §7.2.1: end entity with CertificateId none
|
||||
Tlm, // §7.2.5: self-issued, signs CTL, no certIssuePermissions
|
||||
Unknown, // matches no profile above
|
||||
};
|
||||
|
||||
// Classify the certificate's PKI role. Never throws.
|
||||
CertificateRole certificate_role(const Certificate&);
|
||||
|
||||
Sha256Hash calculate_sha256_hash(SecurityModule&, const Certificate&);
|
||||
Sha384Hash calculate_sha384_hash(SecurityModule&, const Certificate&);
|
||||
Sha256Hash calculate_sha256_hash(SecurityModule&, const Vanetza_Security_Certificate_t&);
|
||||
Sha384Hash calculate_sha384_hash(SecurityModule&, const Vanetza_Security_Certificate_t&);
|
||||
HashedId8 calculate_hashed_id8(SecurityModule&, const Vanetza_Security_Certificate_t&);
|
||||
PublicKey get_public_key(const Vanetza_Security_Certificate_t&);
|
||||
std::string get_name(const Vanetza_Security_Certificate_t&);
|
||||
bool is_canonical(const Vanetza_Security_Certificate_t&);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
#include "certificate_filesystem_storage.hpp"
|
||||
#include "filesystem.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <boost/range/adaptor/filtered.hpp>
|
||||
#include <boost/range/adaptor/transformed.hpp>
|
||||
#include <boost/range/iterator_range.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
CertificateFilesystemStorage::CertificateFilesystemStorage(std::shared_ptr<SecurityModule> sec,
|
||||
const std::filesystem::path& root, std::string extension) :
|
||||
m_security(sec), m_root(root), m_extension(std::move(extension))
|
||||
{
|
||||
std::filesystem::create_directories(m_root);
|
||||
}
|
||||
|
||||
boost::optional<Certificate> CertificateFilesystemStorage::fetch(const HashedId8& id) const
|
||||
{
|
||||
const std::filesystem::path path = filename(id);
|
||||
if (std::filesystem::is_regular_file(path)) {
|
||||
ByteBuffer buffer = read(path);
|
||||
Certificate cert;
|
||||
if (cert.decode(buffer)) {
|
||||
return cert;
|
||||
}
|
||||
}
|
||||
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
void CertificateFilesystemStorage::store(const Certificate& cert)
|
||||
{
|
||||
HashedId8 id = cert.calculate_hashed_id8(*m_security);
|
||||
write(filename(id), cert.encode());
|
||||
}
|
||||
|
||||
bool CertificateFilesystemStorage::erase(const HashedId8& id)
|
||||
{
|
||||
return std::filesystem::remove(filename(id));
|
||||
}
|
||||
|
||||
std::filesystem::path CertificateFilesystemStorage::filename(const HashedId8& id) const
|
||||
{
|
||||
std::string filename = hexstring(id) + m_extension;
|
||||
std::filesystem::path path = m_root / filename;
|
||||
return path;
|
||||
}
|
||||
|
||||
HashedId8Range CertificateFilesystemStorage::list() const
|
||||
{
|
||||
auto rng =
|
||||
boost::make_iterator_range(std::filesystem::directory_iterator(m_root), std::filesystem::directory_iterator()) |
|
||||
boost::adaptors::filtered([this](const std::filesystem::directory_entry& e) {
|
||||
return e.path().extension() == m_extension && std::filesystem::is_regular_file(e.path()) &&
|
||||
HashedId8::from_hexstring(e.path().stem().string()).has_value();
|
||||
}) |
|
||||
boost::adaptors::transformed([](const std::filesystem::directory_entry& e) {
|
||||
return *HashedId8::from_hexstring(e.path().stem().string());
|
||||
});
|
||||
return HashedId8Range(rng);
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate_storage.hpp"
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class SecurityModule;
|
||||
|
||||
class CertificateFilesystemStorage : public CertificateStorage
|
||||
{
|
||||
public:
|
||||
CertificateFilesystemStorage(std::shared_ptr<SecurityModule>, const std::filesystem::path&,
|
||||
std::string extension = ".oer");
|
||||
boost::optional<Certificate> fetch(const HashedId8&) const override;
|
||||
void store(const Certificate&) override;
|
||||
bool erase(const HashedId8&) override;
|
||||
HashedId8Range list() const override;
|
||||
|
||||
protected:
|
||||
std::filesystem::path filename(const HashedId8&) const;
|
||||
|
||||
private:
|
||||
std::shared_ptr<SecurityModule> m_security;
|
||||
std::filesystem::path m_root;
|
||||
std::string m_extension;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#include "certificate_revocation_list.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "filesystem.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/asn1/security/ToBeSignedCrl.h>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
CertificateRevocationList::CertificateRevocationList() :
|
||||
m_asn1(asn_DEF_Vanetza_Security_CertificateRevocationListMessage)
|
||||
{
|
||||
}
|
||||
|
||||
bool CertificateRevocationList::decode(const std::string& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
bool CertificateRevocationList::decode(const ByteBuffer& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
ByteBuffer CertificateRevocationList::encode() const
|
||||
{
|
||||
return m_asn1.encode();
|
||||
}
|
||||
|
||||
CertificateRevocationList CertificateRevocationList::from_file(const std::filesystem::path& path)
|
||||
{
|
||||
ByteBuffer buffer = read(path);
|
||||
if (buffer.empty()) {
|
||||
throw DecodingFailure("CRL file is empty or missing");
|
||||
}
|
||||
|
||||
CertificateRevocationList crl;
|
||||
if (!crl.decode(buffer)) {
|
||||
throw DecodingFailure("CRL message could not be decoded");
|
||||
}
|
||||
return crl;
|
||||
}
|
||||
|
||||
boost::optional<HashedId8> CertificateRevocationList::get_hashed_id8(SecurityModule& security) const
|
||||
{
|
||||
const Vanetza_Security_SignedData_t* signed_data = get_signed_data(raw());
|
||||
if (signed_data) {
|
||||
switch (signed_data->signer.present) {
|
||||
case Vanetza_Security_SignerIdentifier_PR_digest:
|
||||
return HashedId8::from_buffer(signed_data->signer.choice.digest);
|
||||
case Vanetza_Security_SignerIdentifier_PR_certificate: {
|
||||
const Vanetza_Security_SequenceOfCertificate_t& certs = signed_data->signer.choice.certificate;
|
||||
if (certs.list.count == 1 && certs.list.array[0]) {
|
||||
return calculate_hashed_id8(security, *certs.list.array[0]);
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
boost::optional<std::vector<HashedId8>> CertificateRevocationList::revoked_entries() const
|
||||
{
|
||||
const OCTET_STRING_t* opaque = get_signed_payload(raw().content);
|
||||
if (!opaque) {
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
// Signed payload is an EtsiTs102941Data carrying the ToBeSignedCrl in its content CHOICE.
|
||||
MgmtData mgmt;
|
||||
if (!mgmt.decode(*opaque)) {
|
||||
return boost::none;
|
||||
}
|
||||
if (mgmt->content.present != Vanetza_Security_EtsiTs102941DataContent_PR_certificateRevocationList) {
|
||||
return boost::none;
|
||||
}
|
||||
const Vanetza_Security_ToBeSignedCrl_t& tbs = mgmt->content.choice.certificateRevocationList;
|
||||
|
||||
const auto& list = tbs.entries.list;
|
||||
std::vector<HashedId8> result;
|
||||
result.reserve(list.count);
|
||||
for (int i = 0; i < list.count; ++i) {
|
||||
const Vanetza_Security_CrlEntry_t* entry = list.array[i];
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
if (auto id = HashedId8::from_buffer(*entry)) {
|
||||
result.push_back(*id);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include "hashed_id8.hpp"
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/CertificateRevocationListMessage.h>
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class SecurityModule;
|
||||
|
||||
class CertificateRevocationList
|
||||
{
|
||||
public:
|
||||
CertificateRevocationList();
|
||||
bool decode(const std::string&);
|
||||
bool decode(const ByteBuffer&);
|
||||
ByteBuffer encode() const;
|
||||
|
||||
/**
|
||||
* Read the OER-encoded CRL message from a file and decode it.
|
||||
*
|
||||
* \throws DecodingFailure if the file is empty or decoding fails
|
||||
*/
|
||||
static CertificateRevocationList from_file(const std::filesystem::path&);
|
||||
|
||||
boost::optional<HashedId8> get_hashed_id8(SecurityModule&) const;
|
||||
|
||||
/**
|
||||
* Decode the signed payload and return the revoked HashedId8 entries.
|
||||
* An empty vector is valid: CRLs are reissued periodically even when
|
||||
* nothing is revoked. boost::none indicates a decode failure.
|
||||
*/
|
||||
boost::optional<std::vector<HashedId8>> revoked_entries() const;
|
||||
|
||||
const Vanetza_Security_EtsiTs103097Data_t& raw() const
|
||||
{
|
||||
return *m_asn1;
|
||||
}
|
||||
|
||||
private:
|
||||
asn1::asn1c_oer_wrapper<Vanetza_Security_CertificateRevocationListMessage_t> m_asn1;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <boost/range/any_range.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
/// \brief Lazy, single-pass view over stored HashedId8s.
|
||||
using HashedId8Range = boost::any_range<HashedId8, boost::single_pass_traversal_tag, HashedId8, std::ptrdiff_t>;
|
||||
|
||||
class CertificateStorage
|
||||
{
|
||||
public:
|
||||
virtual ~CertificateStorage() = default;
|
||||
virtual boost::optional<Certificate> fetch(const HashedId8&) const = 0;
|
||||
virtual void store(const Certificate&) = 0;
|
||||
virtual bool erase(const HashedId8&) = 0;
|
||||
virtual HashedId8Range list() const = 0;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,524 @@
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "certificate_storage.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "filesystem.hpp"
|
||||
#include "hexstring.hpp"
|
||||
#include "trust_list_storage.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/security/v3/asn1_conversions.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_io.hpp>
|
||||
#include <iostream>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
CertificateTrustList::CertificateTrustList() : m_asn1(asn_DEF_Vanetza_Security_TlmCertificateTrustListMessage)
|
||||
{
|
||||
}
|
||||
|
||||
bool CertificateTrustList::decode(const std::string& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
bool CertificateTrustList::decode(const ByteBuffer& buffer)
|
||||
{
|
||||
return m_asn1.decode(buffer.data(), buffer.size());
|
||||
}
|
||||
|
||||
ByteBuffer CertificateTrustList::encode() const
|
||||
{
|
||||
return m_asn1.encode();
|
||||
}
|
||||
|
||||
CertificateTrustList CertificateTrustList::from_file(const std::filesystem::path& path)
|
||||
{
|
||||
ByteBuffer buffer = read(path);
|
||||
if (buffer.empty()) {
|
||||
throw DecodingFailure("trust list file is empty or missing");
|
||||
}
|
||||
|
||||
CertificateTrustList ctl;
|
||||
if (!ctl.decode(buffer)) {
|
||||
throw DecodingFailure("trust list message could not be decoded");
|
||||
}
|
||||
return ctl;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
const OCTET_STRING_t& require_signed_payload(const Vanetza_Security_EtsiTs103097Data_t& msg)
|
||||
{
|
||||
const OCTET_STRING_t* opaque = get_signed_payload(msg.content);
|
||||
if (!opaque) {
|
||||
throw DecodingFailure("cannot access signed payload of trust list message");
|
||||
}
|
||||
return *opaque;
|
||||
}
|
||||
|
||||
template<class Commands> void dispatch_ctl_commands(const Commands& commands, CtlVisitor& visitor)
|
||||
{
|
||||
for (int i = 0; i < commands.list.count; ++i) {
|
||||
const Vanetza_Security_CtlCommand_t* cmd = commands.list.array[i];
|
||||
if (!cmd) {
|
||||
continue;
|
||||
} else if (cmd->present == Vanetza_Security_CtlCommand_PR_add) {
|
||||
const Vanetza_Security_CtlEntry_t& entry = cmd->choice.add;
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_rca:
|
||||
visitor.add_root_ca(entry.choice.rca);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_tlm:
|
||||
visitor.add_trust_list_manager(entry.choice.tlm);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc:
|
||||
visitor.add_distribution_centre(entry.choice.dc);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_aa:
|
||||
visitor.add_authorization_authority(entry.choice.aa);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_ea:
|
||||
visitor.add_enrolment_authority(entry.choice.ea);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else if (cmd->present == Vanetza_Security_CtlCommand_PR_delete) {
|
||||
const Vanetza_Security_CtlDelete_t& del = cmd->choice.Delete;
|
||||
switch (del.present) {
|
||||
case Vanetza_Security_CtlDelete_PR_cert:
|
||||
visitor.remove_certificate(del.choice.cert);
|
||||
break;
|
||||
case Vanetza_Security_CtlDelete_PR_dc:
|
||||
visitor.remove_distribution_centre(del.choice.dc);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const Vanetza_Security_CtlFormat_t* find_ctl_format(const Vanetza_Security_EtsiTs102941Data_t& mgmt)
|
||||
{
|
||||
switch (mgmt.content.present) {
|
||||
case Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListRca:
|
||||
return &mgmt.content.choice.certificateTrustListRca;
|
||||
case Vanetza_Security_EtsiTs102941DataContent_PR_certificateTrustListTlm:
|
||||
return &mgmt.content.choice.certificateTrustListTlm;
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void CertificateTrustList::visit_tlm_ctl(CtlVisitor& visitor) const
|
||||
{
|
||||
auto mgmt = TlmCtlData::from_opaque(require_signed_payload(*m_asn1));
|
||||
dispatch_ctl_commands(mgmt->content.choice.certificateTrustListTlm.ctlCommands, visitor);
|
||||
}
|
||||
|
||||
void CertificateTrustList::visit_rca_ctl(CtlVisitor& visitor) const
|
||||
{
|
||||
auto mgmt = RcaCtlData::from_opaque(require_signed_payload(*m_asn1));
|
||||
dispatch_ctl_commands(mgmt->content.choice.certificateTrustListRca.ctlCommands, visitor);
|
||||
}
|
||||
|
||||
boost::optional<bool> CertificateTrustList::is_full_ctl() const
|
||||
{
|
||||
const OCTET_STRING_t* opaque = get_signed_payload(raw().content);
|
||||
if (!opaque) {
|
||||
return boost::none;
|
||||
}
|
||||
MgmtData mgmt;
|
||||
if (!mgmt.decode(*opaque)) {
|
||||
return boost::none;
|
||||
}
|
||||
const Vanetza_Security_CtlFormat_t* format = find_ctl_format(*mgmt);
|
||||
if (!format) {
|
||||
return boost::none;
|
||||
}
|
||||
return format->isFullCtl != 0;
|
||||
}
|
||||
|
||||
boost::optional<std::uint8_t> CertificateTrustList::ctl_sequence() const
|
||||
{
|
||||
const OCTET_STRING_t* opaque = get_signed_payload(raw().content);
|
||||
if (!opaque) {
|
||||
return boost::none;
|
||||
}
|
||||
MgmtData mgmt;
|
||||
if (!mgmt.decode(*opaque)) {
|
||||
return boost::none;
|
||||
}
|
||||
const Vanetza_Security_CtlFormat_t* format = find_ctl_format(*mgmt);
|
||||
if (!format) {
|
||||
return boost::none;
|
||||
}
|
||||
return static_cast<std::uint8_t>(format->ctlSequence);
|
||||
}
|
||||
|
||||
void CertificateTrustList::print() const
|
||||
{
|
||||
xer_fprint(stdout, &asn_DEF_Vanetza_Security_TlmCertificateTrustListMessage, &*m_asn1);
|
||||
}
|
||||
|
||||
boost::optional<HashedId8> CertificateTrustList::get_hashed_id8(SecurityModule& security) const
|
||||
{
|
||||
const Vanetza_Security_SignedData_t* signed_data = get_signed_data(raw());
|
||||
if (signed_data) {
|
||||
switch (signed_data->signer.present) {
|
||||
case Vanetza_Security_SignerIdentifier_PR_digest:
|
||||
return HashedId8::from_buffer(signed_data->signer.choice.digest);
|
||||
case Vanetza_Security_SignerIdentifier_PR_certificate: {
|
||||
const Vanetza_Security_SequenceOfCertificate_t& certs = signed_data->signer.choice.certificate;
|
||||
if (certs.list.count == 1 && certs.list.array[0]) {
|
||||
return calculate_hashed_id8(security, *certs.list.array[0]);
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
CertificateTrustListProcessor::CertificateTrustListProcessor(std::shared_ptr<SecurityModule> security) :
|
||||
m_security(security)
|
||||
{
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::process(const CertificateTrustList& ctl)
|
||||
{
|
||||
const Vanetza_Security_Opaque_t* payload = get_signed_payload(ctl.raw().content);
|
||||
boost::optional<HashedId8> ctl_signer = ctl.get_hashed_id8(*m_security);
|
||||
if (!payload || !ctl_signer) {
|
||||
return;
|
||||
}
|
||||
|
||||
MgmtData mgmt;
|
||||
if (!mgmt.decode(*payload)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const Vanetza_Security_CtlFormat_t* format = find_ctl_format(*mgmt);
|
||||
if (!format) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Per TS 102 941 v1.4.1 §6.3.4: a full CTL is the complete trust state.
|
||||
// Drop everything before applying so entries absent from the new full list
|
||||
// don't linger. This is correct under the single-CTL-chain contract on this
|
||||
// processor (one instance per issuer; see class comment).
|
||||
if (format->isFullCtl) {
|
||||
m_enrolment_authorities.clear();
|
||||
m_authorization_authorities.clear();
|
||||
m_distribution_centres.clear();
|
||||
m_root_cas.clear();
|
||||
m_trust_list_managers.clear();
|
||||
}
|
||||
for (int i = 0; i < format->ctlCommands.list.count; ++i) {
|
||||
this->process(*format->ctlCommands.list.array[i], *ctl_signer);
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::process(const Vanetza_Security_CtlCommand_t& cmd, const HashedId8& ctl_signer)
|
||||
{
|
||||
switch (cmd.present) {
|
||||
case Vanetza_Security_CtlCommand_PR_add:
|
||||
add(cmd.choice.add, ctl_signer);
|
||||
break;
|
||||
case Vanetza_Security_CtlCommand_PR_delete:
|
||||
remove(cmd.choice.Delete);
|
||||
break;
|
||||
default:
|
||||
// no op
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add(const Vanetza_Security_CtlEntry_t& entry, const HashedId8& ctl_signer)
|
||||
{
|
||||
switch (entry.present) {
|
||||
case Vanetza_Security_CtlEntry_PR_aa:
|
||||
add_authorization_authority(entry.choice.aa, ctl_signer);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_ea:
|
||||
add_enrolment_authority(entry.choice.ea, ctl_signer);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_dc:
|
||||
add_distribution_centre(entry.choice.dc);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_rca:
|
||||
add_root_ca(entry.choice.rca);
|
||||
break;
|
||||
case Vanetza_Security_CtlEntry_PR_tlm:
|
||||
add_trust_list_manager(entry.choice.tlm);
|
||||
break;
|
||||
default:
|
||||
// no op
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::remove(const Vanetza_Security_CtlDelete_t& removal)
|
||||
{
|
||||
switch (removal.present) {
|
||||
case Vanetza_Security_CtlDelete_PR_cert:
|
||||
remove_certificate(removal.choice.cert);
|
||||
break;
|
||||
case Vanetza_Security_CtlDelete_PR_dc:
|
||||
remove_dc(removal.choice.dc);
|
||||
break;
|
||||
default:
|
||||
// no op
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add_root_ca(const Vanetza_Security_RootCaEntry_t& rca)
|
||||
{
|
||||
// The RCA's self-signed certificate is the trust anchor; key by its own HashedId8.
|
||||
// The optional successorTo backlink (TS 102 941 v1.4.1 §6.3.4) is informational and
|
||||
// ignored here — see [[gap-link-certificates]] for the rollover mechanism.
|
||||
Certificate cert(rca.selfsignedRootCa);
|
||||
HashedId8 hid = cert.calculate_hashed_id8(*m_security);
|
||||
m_root_cas.insert_or_assign(hid, std::move(cert));
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add_authorization_authority(const Vanetza_Security_AaEntry_t& entry,
|
||||
const HashedId8& ctl_signer)
|
||||
{
|
||||
AuthorizationAuthority aa;
|
||||
aa.access_point.assign(reinterpret_cast<const char*>(entry.accessPoint.buf), entry.accessPoint.size);
|
||||
aa.certificate = Certificate(entry.aaCertificate);
|
||||
m_authorization_authorities.insert_or_assign(ctl_signer, std::move(aa));
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add_enrolment_authority(const Vanetza_Security_EaEntry_t& entry,
|
||||
const HashedId8& ctl_signer)
|
||||
{
|
||||
EnrolmentAuthority ea;
|
||||
ea.aa_access_point.assign(reinterpret_cast<const char*>(entry.aaAccessPoint.buf), entry.aaAccessPoint.size);
|
||||
if (entry.itsAccessPoint) {
|
||||
auto buf = reinterpret_cast<const char*>(entry.itsAccessPoint->buf);
|
||||
ea.its_access_point.assign(buf, entry.itsAccessPoint->size);
|
||||
}
|
||||
ea.certificate = Certificate(entry.eaCertificate);
|
||||
m_enrolment_authorities.insert_or_assign(ctl_signer, std::move(ea));
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add_distribution_centre(const Vanetza_Security_DcEntry_t& dc)
|
||||
{
|
||||
std::string url(reinterpret_cast<const char*>(dc.url.buf), dc.url.size);
|
||||
for (int i = 0; i < dc.cert.list.count; ++i) {
|
||||
const Vanetza_Security_HashedId8_t* cert = dc.cert.list.array[i];
|
||||
if (!cert) {
|
||||
continue;
|
||||
}
|
||||
if (auto hid = HashedId8::from_buffer(*cert)) {
|
||||
m_distribution_centres.insert_or_assign(*hid, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::add_trust_list_manager(const Vanetza_Security_TlmEntry_t& tlm)
|
||||
{
|
||||
// CPOC access point (tlm.accessPoint) not tracked here; add a parallel map if callers need it.
|
||||
Certificate cert(tlm.selfSignedTLMCertificate);
|
||||
HashedId8 hid = cert.calculate_hashed_id8(*m_security);
|
||||
m_trust_list_managers.insert_or_assign(hid, std::move(cert));
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::remove_certificate(const Vanetza_Security_HashedId8_t& id)
|
||||
{
|
||||
HashedId8 hid;
|
||||
hid.octets = security::v3::convert(id);
|
||||
m_enrolment_authorities.erase(hid);
|
||||
m_authorization_authorities.erase(hid);
|
||||
m_distribution_centres.erase(hid);
|
||||
m_root_cas.erase(hid);
|
||||
m_trust_list_managers.erase(hid);
|
||||
}
|
||||
|
||||
void CertificateTrustListProcessor::remove_dc(const Vanetza_Security_Url_t& url)
|
||||
{
|
||||
std::string target(reinterpret_cast<const char*>(url.buf), url.size);
|
||||
for (auto it = m_distribution_centres.begin(); it != m_distribution_centres.end();) {
|
||||
if (it->second == target) {
|
||||
it = m_distribution_centres.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<EnrolmentAuthority>
|
||||
CertificateTrustListProcessor::get_enrolment_authority(const HashedId8& root_ca) const
|
||||
{
|
||||
auto found = m_enrolment_authorities.find(root_ca);
|
||||
if (found != m_enrolment_authorities.end()) {
|
||||
return found->second;
|
||||
} else {
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<AuthorizationAuthority>
|
||||
CertificateTrustListProcessor::get_authorization_authority(const HashedId8& root_ca) const
|
||||
{
|
||||
auto found = m_authorization_authorities.find(root_ca);
|
||||
if (found != m_authorization_authorities.end()) {
|
||||
return found->second;
|
||||
} else {
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<Certificate> CertificateTrustListProcessor::get_root_ca(const HashedId8& digest) const
|
||||
{
|
||||
auto found = m_root_cas.find(digest);
|
||||
if (found != m_root_cas.end()) {
|
||||
return found->second;
|
||||
}
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
boost::optional<Certificate> CertificateTrustListProcessor::get_trust_list_manager(const HashedId8& digest) const
|
||||
{
|
||||
auto found = m_trust_list_managers.find(digest);
|
||||
if (found != m_trust_list_managers.end()) {
|
||||
return found->second;
|
||||
}
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
boost::optional<std::string> CertificateTrustListProcessor::get_distribution_centre(const HashedId8& cert_digest) const
|
||||
{
|
||||
auto found = m_distribution_centres.find(cert_digest);
|
||||
if (found != m_distribution_centres.end()) {
|
||||
return found->second;
|
||||
}
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
std::string build_ctl_name(SecurityModule& security, const Vanetza_Security_EtsiTs103097Certificate_t& cert)
|
||||
{
|
||||
auto name = get_name(cert);
|
||||
auto hid8 = hexstring(calculate_hashed_id8(security, cert));
|
||||
if (name.empty()) {
|
||||
return "<HashedId8:" + hid8 + ">";
|
||||
} else {
|
||||
return name + " (" + hid8 + ")";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void CtlListingVisitor::add_root_ca(const Vanetza_Security_RootCaEntry_t& rca)
|
||||
{
|
||||
std::cout << "- Root CA: " << build_ctl_name(m_security, rca.selfsignedRootCa) << "\n";
|
||||
Certificate root_ca_cert { rca.selfsignedRootCa };
|
||||
std::cout << "|-> valid: from " << Clock::at(root_ca_cert.valid_since()) << " until "
|
||||
<< Clock::at(root_ca_cert.valid_until()) << "\n";
|
||||
}
|
||||
|
||||
void CtlListingVisitor::add_trust_list_manager(const Vanetza_Security_TlmEntry_t& tlm)
|
||||
{
|
||||
std::cout << "- TLM: " << build_ctl_name(m_security, tlm.selfSignedTLMCertificate) << "\n";
|
||||
std::cout << "|-> access point: " << to_string(tlm.accessPoint) << "\n";
|
||||
}
|
||||
|
||||
void CtlListingVisitor::add_distribution_centre(const Vanetza_Security_DcEntry_t& dc)
|
||||
{
|
||||
std::cout << "- DC: " << to_string(dc.url) << "\n";
|
||||
for (int i = 0; i < dc.cert.list.count; ++i) {
|
||||
auto digest = security::v3::convert(*dc.cert.list.array[i]);
|
||||
std::cout << "|-> for Root CA " << hexstring(digest) << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void CtlListingVisitor::add_authorization_authority(const Vanetza_Security_AaEntry_t& aa)
|
||||
{
|
||||
std::cout << "- AA: " << to_string(aa.accessPoint) << "\n";
|
||||
}
|
||||
|
||||
void CtlListingVisitor::add_enrolment_authority(const Vanetza_Security_EaEntry_t& ea)
|
||||
{
|
||||
std::cout << "- EA: " << to_string(ea.aaAccessPoint) << " [AA]\n";
|
||||
if (ea.itsAccessPoint) {
|
||||
std::cout << "- EA: " << to_string(*ea.itsAccessPoint) << " [ITS]\n";
|
||||
}
|
||||
}
|
||||
|
||||
CertificateExportVisitor::CertificateExportVisitor(
|
||||
std::shared_ptr<CertificateStorage> aa, std::shared_ptr<CertificateStorage> ea)
|
||||
: m_aa(std::move(aa)), m_ea(std::move(ea))
|
||||
{
|
||||
}
|
||||
|
||||
void CertificateExportVisitor::add_authorization_authority(const Vanetza_Security_AaEntry_t& entry)
|
||||
{
|
||||
if (m_aa) {
|
||||
m_aa->store(Certificate(entry.aaCertificate));
|
||||
++m_exported_aa;
|
||||
}
|
||||
}
|
||||
|
||||
void CertificateExportVisitor::add_enrolment_authority(const Vanetza_Security_EaEntry_t& entry)
|
||||
{
|
||||
if (m_ea) {
|
||||
m_ea->store(Certificate(entry.eaCertificate));
|
||||
++m_exported_ea;
|
||||
}
|
||||
}
|
||||
|
||||
CertificateTrustListProcessor process_stored_ctl(const TrustListStorage& trust_lists,
|
||||
std::shared_ptr<SecurityModule> security, const HashedId8& root_ca)
|
||||
{
|
||||
auto maybe_ctl = trust_lists.fetch(root_ca);
|
||||
if (!maybe_ctl) {
|
||||
throw UsageError("no CTL is in store for the current Root CA", "fetch a CTL via 'dc fetch ctl'");
|
||||
}
|
||||
CertificateTrustListProcessor processor(std::move(security));
|
||||
processor.process(*maybe_ctl);
|
||||
return processor;
|
||||
}
|
||||
|
||||
EnrolmentAuthority require_enrolment_authority(const CertificateTrustListProcessor& processor, const HashedId8& root_ca)
|
||||
{
|
||||
auto maybe_ea = processor.get_enrolment_authority(root_ca);
|
||||
if (!maybe_ea) {
|
||||
throw UsageError("no Enrolment Authority is known for the current Root CA", "fetch a fresh CTL");
|
||||
}
|
||||
if (!maybe_ea->certificate.get_encryption_key()) {
|
||||
throw DecodingFailure("missing encryption key in EA certificate");
|
||||
}
|
||||
return std::move(*maybe_ea);
|
||||
}
|
||||
|
||||
AuthorizationAuthority require_authorization_authority(const CertificateTrustListProcessor& processor,
|
||||
const HashedId8& root_ca)
|
||||
{
|
||||
auto maybe_aa = processor.get_authorization_authority(root_ca);
|
||||
if (!maybe_aa) {
|
||||
throw UsageError("no Authorization Authority is known for the current Root CA", "fetch a fresh CTL");
|
||||
}
|
||||
if (!maybe_aa->certificate.get_encryption_key()) {
|
||||
throw DecodingFailure("missing encryption key in AA certificate");
|
||||
}
|
||||
return std::move(*maybe_aa);
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,228 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include <vanetza/asn1/asn1c_wrapper.hpp>
|
||||
#include <vanetza/asn1/security/CtlCommand.h>
|
||||
#include <vanetza/asn1/security/TlmCertificateTrustListMessage.h>
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
// forward declarations
|
||||
class Certificate;
|
||||
class CertificateStorage;
|
||||
class SecurityModule;
|
||||
class TrustListStorage;
|
||||
|
||||
/// \brief Visitor for the entries of a TLM certificate trust list.
|
||||
class CtlVisitor
|
||||
{
|
||||
public:
|
||||
virtual ~CtlVisitor() = default;
|
||||
|
||||
// add commands
|
||||
virtual void add_root_ca(const Vanetza_Security_RootCaEntry_t&)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void add_trust_list_manager(const Vanetza_Security_TlmEntry_t&)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void add_distribution_centre(const Vanetza_Security_DcEntry_t&)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void add_authorization_authority(const Vanetza_Security_AaEntry_t&)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void add_enrolment_authority(const Vanetza_Security_EaEntry_t&)
|
||||
{
|
||||
}
|
||||
|
||||
// delete commands
|
||||
virtual void remove_certificate(const Vanetza_Security_HashedId8_t&)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void remove_distribution_centre(const Vanetza_Security_Url_t&)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Prints CTL entries to stdout as a human-readable tree.
|
||||
*
|
||||
* Works for both RCA CTLs (visit_rca_ctl) and TLM CTLs/ECTLs (visit_tlm_ctl).
|
||||
*/
|
||||
class CtlListingVisitor : public CtlVisitor
|
||||
{
|
||||
public:
|
||||
explicit CtlListingVisitor(SecurityModule& security) : m_security(security)
|
||||
{
|
||||
}
|
||||
|
||||
void add_root_ca(const Vanetza_Security_RootCaEntry_t&) override;
|
||||
void add_trust_list_manager(const Vanetza_Security_TlmEntry_t&) override;
|
||||
void add_distribution_centre(const Vanetza_Security_DcEntry_t&) override;
|
||||
void add_authorization_authority(const Vanetza_Security_AaEntry_t&) override;
|
||||
void add_enrolment_authority(const Vanetza_Security_EaEntry_t&) override;
|
||||
|
||||
private:
|
||||
SecurityModule& m_security;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Exports the AA/EA certificates embedded in an RCA CTL to standalone storage.
|
||||
*
|
||||
* Run after a CTL has been validated and stored so downstream consumers (e.g. a
|
||||
* security stack) can load issuer certificates as plain cert files without
|
||||
* having to parse CTLs themselves.
|
||||
*/
|
||||
class CertificateExportVisitor : public CtlVisitor
|
||||
{
|
||||
public:
|
||||
CertificateExportVisitor(std::shared_ptr<CertificateStorage> aa, std::shared_ptr<CertificateStorage> ea);
|
||||
|
||||
void add_authorization_authority(const Vanetza_Security_AaEntry_t&) override;
|
||||
void add_enrolment_authority(const Vanetza_Security_EaEntry_t&) override;
|
||||
|
||||
std::size_t exported_aa_certificates() const { return m_exported_aa; }
|
||||
std::size_t exported_ea_certificates() const { return m_exported_ea; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<CertificateStorage> m_aa;
|
||||
std::shared_ptr<CertificateStorage> m_ea;
|
||||
std::size_t m_exported_aa = 0;
|
||||
std::size_t m_exported_ea = 0;
|
||||
};
|
||||
|
||||
class CertificateTrustList
|
||||
{
|
||||
public:
|
||||
CertificateTrustList();
|
||||
bool decode(const std::string&);
|
||||
bool decode(const ByteBuffer&);
|
||||
ByteBuffer encode() const;
|
||||
|
||||
/**
|
||||
* Read the OER-encoded trust list message from a file and decode it.
|
||||
*
|
||||
* \throws DecodingFailure if the file is empty or decoding fails
|
||||
*/
|
||||
static CertificateTrustList from_file(const std::filesystem::path&);
|
||||
|
||||
boost::optional<HashedId8> get_hashed_id8(SecurityModule&) const;
|
||||
|
||||
/**
|
||||
* Per TS 102 941 v1.4.1 §6.3.4: full CTL carries the complete trust state
|
||||
* (only add commands); delta CTL carries changes (adds + deletes) on top of
|
||||
* the previous full list with ctlSequence one less than this one.
|
||||
*
|
||||
* Returns boost::none if the inner CtlFormat cannot be decoded.
|
||||
*/
|
||||
boost::optional<bool> is_full_ctl() const;
|
||||
boost::optional<std::uint8_t> ctl_sequence() const;
|
||||
|
||||
/**
|
||||
* Iterate the TLM certificate trust list entries through `visitor`.
|
||||
*
|
||||
* \throws DecodingFailure on missing payload, malformed management data,
|
||||
* or content that is not a TLM certificate trust list
|
||||
*/
|
||||
void visit_tlm_ctl(CtlVisitor&) const;
|
||||
|
||||
// Same as visit_tlm_ctl but for RCA certificate trust lists.
|
||||
void visit_rca_ctl(CtlVisitor&) const;
|
||||
|
||||
void print() const;
|
||||
|
||||
const Vanetza_Security_EtsiTs103097Data_t& raw() const
|
||||
{
|
||||
return *m_asn1;
|
||||
}
|
||||
|
||||
private:
|
||||
asn1::asn1c_oer_wrapper<Vanetza_Security_TlmCertificateTrustListMessage_t> m_asn1;
|
||||
};
|
||||
|
||||
struct EnrolmentAuthority
|
||||
{
|
||||
Certificate certificate;
|
||||
std::string aa_access_point;
|
||||
std::string its_access_point;
|
||||
};
|
||||
|
||||
struct AuthorizationAuthority
|
||||
{
|
||||
Certificate certificate;
|
||||
std::string access_point;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Decoded view of a CertificateTrustList's commands.
|
||||
*
|
||||
* One instance processes a single CTL chain — either (full, delta, delta, ...)
|
||||
* from one RCA, or the same from one TLM. Mixing issuers (e.g. an RCA CTL and
|
||||
* an ECTL) on the same instance is unsupported: a full CTL clears all state,
|
||||
* so later content from a different issuer would silently wipe earlier content.
|
||||
* Build a fresh processor per chain.
|
||||
*/
|
||||
class CertificateTrustListProcessor
|
||||
{
|
||||
public:
|
||||
CertificateTrustListProcessor(std::shared_ptr<SecurityModule>);
|
||||
void process(const CertificateTrustList&);
|
||||
|
||||
boost::optional<EnrolmentAuthority> get_enrolment_authority(const HashedId8&) const;
|
||||
boost::optional<AuthorizationAuthority> get_authorization_authority(const HashedId8&) const;
|
||||
boost::optional<Certificate> get_root_ca(const HashedId8&) const;
|
||||
boost::optional<Certificate> get_trust_list_manager(const HashedId8&) const;
|
||||
boost::optional<std::string> get_distribution_centre(const HashedId8&) const;
|
||||
|
||||
protected:
|
||||
void process(const Vanetza_Security_CtlCommand_t&, const HashedId8& ctl_signer);
|
||||
void add(const Vanetza_Security_CtlEntry_t&, const HashedId8& ctl_signer);
|
||||
void remove(const Vanetza_Security_CtlDelete_t&);
|
||||
|
||||
void add_root_ca(const Vanetza_Security_RootCaEntry_t&);
|
||||
void add_authorization_authority(const Vanetza_Security_AaEntry_t&, const HashedId8& ctl_signer); // signer = issuing RCA, key for AA map
|
||||
void add_enrolment_authority(const Vanetza_Security_EaEntry_t&, const HashedId8& ctl_signer); // signer = issuing RCA, key for EA map
|
||||
void add_distribution_centre(const Vanetza_Security_DcEntry_t&);
|
||||
void add_trust_list_manager(const Vanetza_Security_TlmEntry_t&);
|
||||
|
||||
void remove_certificate(const Vanetza_Security_HashedId8_t&);
|
||||
void remove_dc(const Vanetza_Security_Url_t&);
|
||||
|
||||
private:
|
||||
std::shared_ptr<SecurityModule> m_security;
|
||||
std::map<HashedId8, EnrolmentAuthority> m_enrolment_authorities;
|
||||
std::map<HashedId8, AuthorizationAuthority> m_authorization_authorities;
|
||||
std::map<HashedId8, std::string> m_distribution_centres;
|
||||
std::map<HashedId8, Certificate> m_root_cas;
|
||||
std::map<HashedId8, Certificate> m_trust_list_managers;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch and process the stored CTL for `root_ca`.
|
||||
*
|
||||
* \throws UsageError if no CTL is stored for `root_ca`
|
||||
*/
|
||||
CertificateTrustListProcessor process_stored_ctl(const TrustListStorage& trust_lists,
|
||||
std::shared_ptr<SecurityModule> security, const HashedId8& root_ca);
|
||||
|
||||
// Require the EA/AA for `root_ca` to be listed and carry an encryption key.
|
||||
EnrolmentAuthority require_enrolment_authority(const CertificateTrustListProcessor&, const HashedId8& root_ca);
|
||||
AuthorizationAuthority require_authorization_authority(const CertificateTrustListProcessor&, const HashedId8& root_ca);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,47 @@
|
||||
#include "asn1.hpp"
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
boost::optional<std::string> lookup_dc_url(const std::filesystem::path& ectl_file, const HashedId8& root_ca)
|
||||
{
|
||||
struct DcUrlFinder : CtlVisitor
|
||||
{
|
||||
const HashedId8& root_ca;
|
||||
boost::optional<std::string> url;
|
||||
|
||||
explicit DcUrlFinder(const HashedId8& ca) : root_ca(ca)
|
||||
{
|
||||
}
|
||||
|
||||
void add_distribution_centre(const Vanetza_Security_DcEntry_t& dc) override
|
||||
{
|
||||
if (url) {
|
||||
return;
|
||||
}
|
||||
for (int j = 0; j < dc.cert.list.count; ++j) {
|
||||
if (dc.cert.list.array[j] && equals(*dc.cert.list.array[j], root_ca)) {
|
||||
url = to_string(dc.url);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
CertificateTrustList ctl = CertificateTrustList::from_file(ectl_file);
|
||||
DcUrlFinder finder { root_ca };
|
||||
ctl.visit_tlm_ctl(finder);
|
||||
return finder.url;
|
||||
} catch (const std::exception&) {
|
||||
// ECTL missing or malformed: treat as "no DC URL available"
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,322 @@
|
||||
#include "cpoc.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "certificate_storage.hpp"
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "hashed_id8_validator.hpp"
|
||||
#include "http.hpp"
|
||||
#include "time.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <boost/beast/http/field.hpp>
|
||||
#include <boost/date_time/posix_time/posix_time_io.hpp>
|
||||
#include <functional>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
struct Context
|
||||
{
|
||||
Context(const MainConfig& c) : cfg(c)
|
||||
{
|
||||
}
|
||||
|
||||
std::filesystem::path ectl_file() const
|
||||
{
|
||||
return cfg.data_path / "ectl.ctl";
|
||||
}
|
||||
|
||||
const MainConfig& cfg;
|
||||
std::string cpoc_url = "https://cpoc.jrc.ec.europa.eu/L0";
|
||||
HashedId8 hid8;
|
||||
std::function<void()> action;
|
||||
};
|
||||
|
||||
const HashedId8Validator hid8_validator;
|
||||
|
||||
Certificate fetch_tlm_certificate(const std::string& base_url, const HashedId8* id)
|
||||
{
|
||||
auto query = HttpQuery::from_url(base_url + "/gettlmcertificate/" + (id ? hexstring(*id) : ""));
|
||||
auto response = http_get(query);
|
||||
if (response.result() != boost::beast::http::status::ok) {
|
||||
throw HttpException("CPOC returned an unexpected HTTP status when fetching TLM certificate",
|
||||
std::move(response));
|
||||
} else if (response[boost::beast::http::field::content_type] != "application/octet-stream") {
|
||||
throw HttpException("did not receive bytes from CPOC when fetching TLM certificate");
|
||||
} else {
|
||||
Certificate cert;
|
||||
if (!cert.decode(response.body())) {
|
||||
throw DecodingFailure("decoding received TLM certificate failed");
|
||||
} else {
|
||||
return cert;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<std::tuple<Certificate, HashedId8>> lookup_default_tlm_certificate(const Context& context)
|
||||
{
|
||||
const CertificateStorage& storage = *context.cfg.tlm;
|
||||
boost::optional<std::tuple<Certificate, HashedId8>> match;
|
||||
Clock::time_point now = current_time();
|
||||
|
||||
for (const HashedId8& hid8 : storage.list()) {
|
||||
boost::optional<Certificate> candidate = storage.fetch(hid8);
|
||||
if (candidate && is_currently_valid(*candidate, now)) {
|
||||
if (!match) {
|
||||
match = std::make_tuple(*candidate, hid8);
|
||||
} else if (std::get<0>(*match).valid_since() < candidate->valid_since()) {
|
||||
match = std::make_tuple(*candidate, hid8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return match;
|
||||
}
|
||||
|
||||
void list_tlm(Context& context)
|
||||
{
|
||||
const Clock::time_point now = current_time();
|
||||
std::cout << "Trusted TLM certificates are:\n";
|
||||
for (const HashedId8& hid8 : context.cfg.tlm->list()) {
|
||||
boost::optional<Certificate> cert = context.cfg.tlm->fetch(hid8);
|
||||
if (!cert) {
|
||||
std::cout << "- " << hexstring(hid8) << "\n";
|
||||
continue;
|
||||
}
|
||||
const std::string name = cert->get_name();
|
||||
std::cout << "- " << (name.empty() ? hexstring(hid8) : name + " (" + hexstring(hid8) + ")") << "\n";
|
||||
const char* status = "valid";
|
||||
if (now < cert->valid_since()) {
|
||||
status = "not yet valid";
|
||||
} else if (now > cert->valid_until()) {
|
||||
status = "expired";
|
||||
}
|
||||
std::cout << " |-> valid from " << Clock::at(cert->valid_since()) << " until "
|
||||
<< Clock::at(cert->valid_until()) << " [" << status << "]\n";
|
||||
}
|
||||
}
|
||||
|
||||
void fetch_tlm(Context& context, const HashedId8* id, bool dry_run)
|
||||
{
|
||||
Certificate tlm = fetch_tlm_certificate(context.cpoc_url, id);
|
||||
const HashedId8 tlm_hid8 = tlm.calculate_hashed_id8(*context.cfg.security);
|
||||
if (id && *id != tlm_hid8) {
|
||||
throw VerificationFailure("fetched TLM certificate's HashedId8 does not match requested HashedId8");
|
||||
}
|
||||
const std::string name = tlm.get_name();
|
||||
const std::string hex_hid8 = hexstring(tlm_hid8);
|
||||
if (dry_run) {
|
||||
std::cout << "CPOC can provide TLM certificate "
|
||||
<< (name.empty() ? hex_hid8 : "\"" + name + "\" (" + hex_hid8 + ")")
|
||||
<< ". Storage unchanged in this dry run.\n";
|
||||
return;
|
||||
}
|
||||
context.cfg.tlm->store(tlm);
|
||||
if (name.empty()) {
|
||||
std::cout << "Added TLM certificate (" << hex_hid8 << ")\n";
|
||||
} else {
|
||||
std::cout << "Added TLM certificate \"" << name << "\" (" << hex_hid8 << ")\n";
|
||||
}
|
||||
}
|
||||
|
||||
void discard_tlm(Context& context, const HashedId8& id)
|
||||
{
|
||||
if (context.cfg.tlm->erase(id)) {
|
||||
std::cout << "Removed " << hexstring(id) << " from trusted TLM certificates\n";
|
||||
} else {
|
||||
std::cout << "No TLM certificate with " << hexstring(id) << " found in local storage\n";
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<CLI::App> build_tlm_command(std::shared_ptr<Context> context)
|
||||
{
|
||||
auto app = std::make_shared<CLI::App>("Trust List Manager", "tlm");
|
||||
|
||||
auto list = app->add_subcommand("list", "list all trusted TLM certificates");
|
||||
list->callback([context]() { context->action = [context]() { list_tlm(*context); }; });
|
||||
|
||||
auto fetch = app->add_subcommand("fetch", "fetch a TLM certificate from CPOC (omit the id to fetch the latest)");
|
||||
auto fetch_id =
|
||||
fetch->add_option("hid8", context->hid8, "HashedId8 of the TLM certificate to fetch; omit for the latest")
|
||||
->check(hid8_validator);
|
||||
auto fetch_dry = fetch->add_flag("--dry-run,-n", "do not store the fetched certificate");
|
||||
fetch->callback([context, fetch_id, fetch_dry]() {
|
||||
const bool has_id = fetch_id->count() > 0;
|
||||
const bool dry_run = fetch_dry->as<bool>();
|
||||
context->action = [context, has_id, dry_run]() {
|
||||
fetch_tlm(*context, has_id ? &context->hid8 : nullptr, dry_run);
|
||||
};
|
||||
});
|
||||
|
||||
auto discard = app->add_subcommand("discard", "discard a TLM certificate (distrust it)");
|
||||
discard->add_option("hid8", context->hid8, "HashedId8 of the TLM certificate to discard")
|
||||
->required()
|
||||
->check(hid8_validator);
|
||||
discard->callback([context]() { context->action = [context]() { discard_tlm(*context, context->hid8); }; });
|
||||
|
||||
app->final_callback([context]() {
|
||||
if (!context->action) {
|
||||
context->action = [context]() { list_tlm(*context); };
|
||||
}
|
||||
context->action();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
void list_ectl(Context& context)
|
||||
{
|
||||
CertificateTrustList ctl = CertificateTrustList::from_file(context.ectl_file());
|
||||
std::cout << "ECTL contains:\n";
|
||||
CtlListingVisitor visitor(*context.cfg.security);
|
||||
ctl.visit_tlm_ctl(visitor);
|
||||
}
|
||||
|
||||
// tlm_id == nullptr -> use the locally known latest TLM certificate.
|
||||
void fetch_ectl(Context& context, const HashedId8* tlm_id, bool dry_run)
|
||||
{
|
||||
CertificateStorage& storage = *context.cfg.tlm;
|
||||
|
||||
HashedId8 tlm_hid8;
|
||||
if (tlm_id) {
|
||||
tlm_hid8 = *tlm_id;
|
||||
} else {
|
||||
auto lookup = lookup_default_tlm_certificate(context);
|
||||
if (!lookup) {
|
||||
throw UsageError("no TLM certificate found", "run 'cpoc tlm fetch' first");
|
||||
}
|
||||
tlm_hid8 = std::get<1>(*lookup);
|
||||
}
|
||||
|
||||
struct UpdateVisitor : CtlVisitor
|
||||
{
|
||||
UpdateVisitor(std::shared_ptr<CertificateStorage> certs) : certificates(certs)
|
||||
{
|
||||
}
|
||||
|
||||
void add_root_ca(const Vanetza_Security_RootCaEntry_t& rca) override
|
||||
{
|
||||
Certificate root_ca { rca.selfsignedRootCa };
|
||||
certificates->store(root_ca);
|
||||
}
|
||||
|
||||
std::shared_ptr<CertificateStorage> certificates;
|
||||
};
|
||||
|
||||
auto query = HttpQuery::from_url(context.cpoc_url + "/getectl/" + hexstring(tlm_hid8));
|
||||
auto response = http_get(query);
|
||||
if (response.result() != boost::beast::http::status::ok) {
|
||||
throw HttpException("CPOC returned an unexpected HTTP status when fetching full ECTL",
|
||||
std::move(response));
|
||||
} else if (response[boost::beast::http::field::content_type] != "application/octet-stream") {
|
||||
throw HttpException("did not receive bytes from CPOC when fetching full ECTL");
|
||||
}
|
||||
|
||||
CertificateTrustList tlm_message;
|
||||
if (!tlm_message.decode(response.body())) {
|
||||
throw DecodingFailure("decoding received TLM certificate list message failed");
|
||||
} else if (const Vanetza_Security_SignedData_t* sdata = get_signed_data(tlm_message.raw())) {
|
||||
const Vanetza_Security_EtsiTs103097Certificate_t* ectl_certificate = nullptr;
|
||||
if (sdata->signer.present == Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||
if (!equals(sdata->signer.choice.digest, tlm_hid8)) {
|
||||
throw VerificationFailure("expected a different HashedId8 digest in response message");
|
||||
}
|
||||
} else if (sdata->signer.present == Vanetza_Security_SignerIdentifier_PR_certificate) {
|
||||
const Vanetza_Security_SequenceOfCertificate& certlist = sdata->signer.choice.certificate;
|
||||
if (certlist.list.count >= 1) {
|
||||
ectl_certificate = certlist.list.array[0];
|
||||
HashedId8 cert_hid8 = calculate_hashed_id8(*context.cfg.security, *ectl_certificate);
|
||||
if (cert_hid8 != tlm_hid8) {
|
||||
throw VerificationFailure("signing certificate's digest does not match requested HashedId8");
|
||||
}
|
||||
} else {
|
||||
throw DecodingFailure("missing certificate used for signing");
|
||||
}
|
||||
} else {
|
||||
throw VerificationFailure("received ECTL message is not signed by expected TLM HashedId8");
|
||||
}
|
||||
|
||||
boost::optional<Certificate> stored_tlm = storage.fetch(tlm_hid8);
|
||||
if (!stored_tlm) {
|
||||
if (!ectl_certificate) {
|
||||
throw UsageError("missing TLM certificate to verify ECTL", "run 'cpoc tlm fetch' first");
|
||||
}
|
||||
stored_tlm = Certificate(*ectl_certificate);
|
||||
if (!dry_run) {
|
||||
storage.store(*stored_tlm);
|
||||
}
|
||||
}
|
||||
|
||||
if (!validate(*context.cfg.security, *sdata, stored_tlm->raw())) {
|
||||
throw VerificationFailure("signature verification of ECTL failed");
|
||||
}
|
||||
|
||||
if (dry_run) {
|
||||
std::cout << "ECTL signature verified. Storage unchanged in this dry run.\n";
|
||||
return;
|
||||
}
|
||||
|
||||
write(context.ectl_file(), ByteBuffer { response.body().begin(), response.body().end() });
|
||||
std::cout << "Stored ECTL\n";
|
||||
|
||||
UpdateVisitor visitor(context.cfg.root_ca);
|
||||
tlm_message.visit_tlm_ctl(visitor);
|
||||
} else {
|
||||
throw DecodingFailure("message contains no signed data");
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<CLI::App> build_ectl_command(std::shared_ptr<Context> context)
|
||||
{
|
||||
auto app = std::make_shared<CLI::App>("European Certificate Trust List", "ectl");
|
||||
|
||||
auto list = app->add_subcommand("list", "list trusted CAs from the locally stored ECTL");
|
||||
list->callback([context]() { context->action = [context]() { list_ectl(*context); }; });
|
||||
|
||||
auto fetch =
|
||||
app->add_subcommand("fetch", "fetch the full ECTL signed by the TLM (omit the id to use the latest known TLM)");
|
||||
auto fetch_id =
|
||||
fetch->add_option("hid8", context->hid8, "HashedId8 of the TLM; omit to use the latest known TLM certificate")
|
||||
->check(hid8_validator);
|
||||
auto fetch_dry = fetch->add_flag("--dry-run,-n", "fetch and verify only; do not store the ECTL");
|
||||
fetch->callback([context, fetch_id, fetch_dry]() {
|
||||
const bool has_id = fetch_id->count() > 0;
|
||||
const bool dry_run = fetch_dry->as<bool>();
|
||||
context->action = [context, has_id, dry_run]() {
|
||||
fetch_ectl(*context, has_id ? &context->hid8 : nullptr, dry_run);
|
||||
};
|
||||
});
|
||||
|
||||
app->final_callback([context]() {
|
||||
if (!context->action) {
|
||||
context->action = [context]() { list_ectl(*context); };
|
||||
}
|
||||
context->action();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::shared_ptr<CLI::App> build_cpoc_command(const MainConfig& config)
|
||||
{
|
||||
auto ctx = std::make_shared<Context>(config);
|
||||
auto app = std::make_shared<CLI::App>("C-ITS Point of Contact Protocol", "cpoc");
|
||||
app->add_option("--url", ctx->cpoc_url, "CPOC base URL")->capture_default_str();
|
||||
|
||||
app->add_subcommand(build_ectl_command(ctx));
|
||||
app->add_subcommand(build_tlm_command(ctx));
|
||||
app->require_subcommand();
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "main.hpp"
|
||||
#include <CLI/App.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
std::shared_ptr<CLI::App> build_cpoc_command(const MainConfig&);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
#include "credential_filesystem_storage.hpp"
|
||||
#include "openssl.hpp"
|
||||
#include <boost/range/adaptor/filtered.hpp>
|
||||
#include <boost/range/adaptor/transformed.hpp>
|
||||
#include <boost/range/iterator_range.hpp>
|
||||
#include <openssl/bio.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <system_error>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
CredentialFilesystemStorage::CredentialFilesystemStorage(const std::filesystem::path& root) : m_root(root)
|
||||
{
|
||||
std::filesystem::create_directories(m_root);
|
||||
}
|
||||
|
||||
std::filesystem::path CredentialFilesystemStorage::build_key_path(const PublicKey& key)
|
||||
{
|
||||
auto key_path = m_root / canonical_hexstring(key);
|
||||
key_path += ".pem";
|
||||
return key_path;
|
||||
}
|
||||
|
||||
void CredentialFilesystemStorage::store(const PublicKey& pub, const PrivateKey& priv)
|
||||
{
|
||||
std::filesystem::path path = build_key_path(pub);
|
||||
OpenSslPointer<BIO> out = make_owner_only_bio(path);
|
||||
|
||||
int nid = openssl_nid(priv.type);
|
||||
OpenSslPointer<EC_KEY> ec_key { EC_KEY_new_by_curve_name(nid), "construction of EC key failed" };
|
||||
OpenSslPointer<BIGNUM> bn_priv { BN_bin2bn(priv.key.data(), priv.key.size(), nullptr),
|
||||
"converting private key to BIGNUM failed" };
|
||||
openssl_result(EC_KEY_set_private_key(ec_key.raw(), bn_priv.raw()), "setting private key failed");
|
||||
|
||||
OpenSslPointer<EC_POINT> ecp_pub = make_ec_point(pub);
|
||||
openssl_result(EC_KEY_set_public_key(ec_key.raw(), ecp_pub.raw()), "setting public key failed");
|
||||
|
||||
openssl_result(EC_KEY_check_key(ec_key.raw()), "EC key is invalid");
|
||||
|
||||
OpenSslPointer<EVP_PKEY> key { EVP_PKEY_new() };
|
||||
openssl_result(EVP_PKEY_set1_EC_KEY(key.raw(), ec_key.raw()), "set1_EC_KEY");
|
||||
|
||||
openssl_result(PEM_write_bio_PKCS8PrivateKey(out.raw(), key.raw(), nullptr, nullptr, 0, nullptr, nullptr),
|
||||
"writing PEM encoded private key failed");
|
||||
}
|
||||
|
||||
boost::optional<PrivateKey> CredentialFilesystemStorage::fetch(const PublicKey& pub)
|
||||
{
|
||||
std::filesystem::path path = build_key_path(pub);
|
||||
if (std::filesystem::is_regular_file(path)) {
|
||||
OpenSslPointer<BIO> in { BIO_new_file(path.c_str(), "r"),
|
||||
"could not create OpenSSL BIO to read file at " + path.string() };
|
||||
OpenSslPointer<EVP_PKEY> key { PEM_read_bio_PrivateKey(in.raw(), nullptr, nullptr, nullptr),
|
||||
"reading private key failed" };
|
||||
|
||||
int pub_nid = openssl_nid(pub.type);
|
||||
const EC_KEY* ec_key = EVP_PKEY_get0_EC_KEY(key.raw());
|
||||
if (!ec_key) {
|
||||
throw std::runtime_error("key is not an EC key");
|
||||
}
|
||||
const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key);
|
||||
if (!ec_group) {
|
||||
throw std::runtime_error("EC group is not set");
|
||||
}
|
||||
int key_nid = EC_GROUP_get_curve_name(ec_group);
|
||||
if (pub_nid != key_nid) {
|
||||
throw std::runtime_error("private key has different type than public key");
|
||||
}
|
||||
|
||||
PrivateKey priv;
|
||||
priv.type = pub.type;
|
||||
const BIGNUM* bn_priv = EC_KEY_get0_private_key(ec_key);
|
||||
priv.key.resize(BN_num_bytes(bn_priv));
|
||||
BN_bn2bin(bn_priv, priv.key.data());
|
||||
return priv;
|
||||
}
|
||||
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
bool CredentialFilesystemStorage::discard(const PublicKey& key)
|
||||
{
|
||||
std::error_code ec;
|
||||
return std::filesystem::remove(build_key_path(key), ec);
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
/**
|
||||
* \brief Accept "02"|"03" prefix + 64 hex (P-256) or 96 hex (P-384) chars.
|
||||
*
|
||||
* Near-misses are rejected here so they are never flagged as orphans and deleted.
|
||||
*/
|
||||
bool is_valid_canonical_hex_stem(const std::string& stem)
|
||||
{
|
||||
if (stem.size() != 66 && stem.size() != 98) {
|
||||
return false;
|
||||
} else if (stem[0] != '0' || (stem[1] != '2' && stem[1] != '3')) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t i = 2; i < stem.size(); ++i) {
|
||||
char c = stem[i];
|
||||
const bool ok = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::filesystem::path CredentialFilesystemStorage::build_key_path(const std::string& canonical_hex) const
|
||||
{
|
||||
auto p = m_root / canonical_hex;
|
||||
p += ".pem";
|
||||
return p;
|
||||
}
|
||||
|
||||
CredentialNameRange CredentialFilesystemStorage::list() const
|
||||
{
|
||||
auto rng =
|
||||
boost::make_iterator_range(std::filesystem::directory_iterator(m_root), std::filesystem::directory_iterator()) |
|
||||
boost::adaptors::filtered([](const std::filesystem::directory_entry& e) {
|
||||
return e.path().extension() == ".pem" && std::filesystem::is_regular_file(e.path()) &&
|
||||
is_valid_canonical_hex_stem(e.path().stem().string());
|
||||
}) |
|
||||
boost::adaptors::transformed([](const std::filesystem::directory_entry& e) {
|
||||
return e.path().stem().string();
|
||||
});
|
||||
return CredentialNameRange(rng);
|
||||
}
|
||||
|
||||
bool CredentialFilesystemStorage::discard(const std::string& canonical_hex)
|
||||
{
|
||||
std::error_code ec;
|
||||
return std::filesystem::remove(build_key_path(canonical_hex), ec);
|
||||
}
|
||||
|
||||
bool CredentialFilesystemStorage::contains(const std::string& canonical_hex) const
|
||||
{
|
||||
return std::filesystem::is_regular_file(build_key_path(canonical_hex));
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
#pragma once
|
||||
|
||||
#include "credential_storage.hpp"
|
||||
#include <filesystem>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class CredentialFilesystemStorage : public CredentialStorage
|
||||
{
|
||||
public:
|
||||
CredentialFilesystemStorage(const std::filesystem::path& root);
|
||||
|
||||
void store(const PublicKey&, const PrivateKey&) override;
|
||||
boost::optional<PrivateKey> fetch(const PublicKey&) override;
|
||||
bool discard(const PublicKey&) override;
|
||||
CredentialNameRange list() const override;
|
||||
bool discard(const std::string& canonical_hex) override;
|
||||
bool contains(const std::string& canonical_hex) const override;
|
||||
|
||||
private:
|
||||
std::filesystem::path build_key_path(const PublicKey&);
|
||||
std::filesystem::path build_key_path(const std::string& canonical_hex) const;
|
||||
|
||||
std::filesystem::path m_root;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
|
||||
#include "keys.hpp"
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <boost/range/any_range.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
/// \brief Lazy, single-pass view over canonical-hex credential names.
|
||||
using CredentialNameRange =
|
||||
boost::any_range<std::string, boost::single_pass_traversal_tag, std::string, std::ptrdiff_t>;
|
||||
|
||||
class CredentialStorage
|
||||
{
|
||||
public:
|
||||
virtual ~CredentialStorage() = default;
|
||||
virtual void store(const PublicKey&, const PrivateKey&) = 0;
|
||||
virtual boost::optional<PrivateKey> fetch(const PublicKey&) = 0;
|
||||
virtual bool discard(const PublicKey&) = 0;
|
||||
|
||||
/// \brief Lazy iteration over the canonical-hex name of every stored credential.
|
||||
virtual CredentialNameRange list() const = 0;
|
||||
|
||||
/// \brief Discard a credential by its canonical-hex name; returns true iff one was removed.
|
||||
virtual bool discard(const std::string& canonical_hex) = 0;
|
||||
|
||||
/// \brief Existence check by canonical-hex name; cheap, no key parsing.
|
||||
virtual bool contains(const std::string& canonical_hex) const = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief RAII handle that discards a credential on destruction unless commit() was called.
|
||||
*
|
||||
* Use to bind a freshly generated key to the lifetime of a protocol step:
|
||||
* store now, drop the key if anything throws before the step succeeds.
|
||||
*/
|
||||
class ScopedCredential
|
||||
{
|
||||
public:
|
||||
ScopedCredential(CredentialStorage& storage, PublicKey pub) : m_storage(&storage), m_public_key(std::move(pub))
|
||||
{
|
||||
}
|
||||
|
||||
ScopedCredential(CredentialStorage& storage, PublicKey pub, const PrivateKey& priv) : ScopedCredential(storage, pub)
|
||||
{
|
||||
m_storage->store(m_public_key, priv);
|
||||
}
|
||||
|
||||
~ScopedCredential()
|
||||
{
|
||||
if (m_storage) {
|
||||
m_storage->discard(m_public_key);
|
||||
}
|
||||
}
|
||||
|
||||
// no copy
|
||||
ScopedCredential(const ScopedCredential&) = delete;
|
||||
ScopedCredential& operator=(const ScopedCredential&) = delete;
|
||||
// no move
|
||||
ScopedCredential(ScopedCredential&&) = delete;
|
||||
ScopedCredential& operator=(ScopedCredential&&) = delete;
|
||||
|
||||
void commit()
|
||||
{
|
||||
m_storage = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
CredentialStorage* m_storage = nullptr;
|
||||
PublicKey m_public_key;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,76 @@
|
||||
#include "crl_store.hpp"
|
||||
#include "certificate_revocation_list.hpp"
|
||||
#include "filesystem.hpp"
|
||||
#include "hexstring.hpp"
|
||||
#include "security_module.hpp"
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
CrlFilesystemStore::CrlFilesystemStore(std::shared_ptr<SecurityModule> security, const std::filesystem::path& root) :
|
||||
m_security(security), m_root(root)
|
||||
{
|
||||
std::filesystem::create_directories(m_root);
|
||||
for (const auto& entry : std::filesystem::directory_iterator(m_root)) {
|
||||
if (!entry.is_regular_file() || entry.path().extension() != ".crl") {
|
||||
continue;
|
||||
}
|
||||
ByteBuffer buf = read(entry.path());
|
||||
CertificateRevocationList crl;
|
||||
if (crl.decode(buf)) {
|
||||
index(crl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool CrlFilesystemStore::store(const CertificateRevocationList& crl)
|
||||
{
|
||||
auto issuer = index(crl);
|
||||
if (!issuer) {
|
||||
return false;
|
||||
}
|
||||
write(filename(*issuer), crl.encode());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CrlFilesystemStore::is_revoked(const security::HashedId8& issuer, const security::HashedId8& cert) const
|
||||
{
|
||||
auto it = m_revoked.find(issuer);
|
||||
if (it == m_revoked.end()) {
|
||||
return false;
|
||||
}
|
||||
return it->second.count(cert) != 0;
|
||||
}
|
||||
|
||||
std::filesystem::path CrlFilesystemStore::filename(const HashedId8& id) const
|
||||
{
|
||||
return m_root / (hexstring(id.octets) + ".crl");
|
||||
}
|
||||
|
||||
boost::optional<HashedId8> CrlFilesystemStore::index(const CertificateRevocationList& crl)
|
||||
{
|
||||
auto issuer = crl.get_hashed_id8(*m_security);
|
||||
if (!issuer) {
|
||||
return boost::none;
|
||||
}
|
||||
auto entries = crl.revoked_entries();
|
||||
if (!entries) {
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
// Empty CRL is valid: it withdraws any prior revocations from this issuer.
|
||||
// Erase the existing bucket and only create a new one if there's content.
|
||||
m_revoked.erase(issuer->octets);
|
||||
if (!entries->empty()) {
|
||||
auto& bucket = m_revoked[issuer->octets];
|
||||
for (const auto& cert : *entries) {
|
||||
bucket.insert(cert.octets);
|
||||
}
|
||||
}
|
||||
return issuer;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include "hashed_id8.hpp"
|
||||
#include <vanetza/security/hashed_id.hpp>
|
||||
#include <vanetza/security/v3/revocation_lookup.hpp>
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class CertificateRevocationList;
|
||||
class SecurityModule;
|
||||
|
||||
/**
|
||||
* Constructor scans \p root and indexes every "*.crl" file.
|
||||
* store() replaces any prior CRL from the same issuer (one file per issuer).
|
||||
*/
|
||||
class CrlFilesystemStore : public security::v3::RevocationLookup
|
||||
{
|
||||
public:
|
||||
CrlFilesystemStore(std::shared_ptr<SecurityModule>, const std::filesystem::path& root);
|
||||
|
||||
// Returns false if the CRL has no extractable issuer or a malformed payload.
|
||||
bool store(const CertificateRevocationList&);
|
||||
|
||||
bool is_revoked(const security::HashedId8& issuer, const security::HashedId8& cert) const override;
|
||||
|
||||
protected:
|
||||
std::filesystem::path filename(const HashedId8&) const;
|
||||
boost::optional<HashedId8> index(const CertificateRevocationList&);
|
||||
|
||||
private:
|
||||
std::shared_ptr<SecurityModule> m_security;
|
||||
std::filesystem::path m_root;
|
||||
std::unordered_map<security::HashedId8, std::unordered_set<security::HashedId8>> m_revoked;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,219 @@
|
||||
#include "dc_command.hpp"
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "distribution_centre.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8_validator.hpp"
|
||||
#include "http.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <boost/date_time/posix_time/posix_time_io.hpp>
|
||||
#include <functional>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
const HashedId8Validator hid8_validator;
|
||||
|
||||
struct Context
|
||||
{
|
||||
Context(const MainConfig& c) : cfg(c)
|
||||
{
|
||||
}
|
||||
|
||||
void lookup_root_ca(CLI::Option* hid8_opt)
|
||||
{
|
||||
if (hid8_opt->count() == 0) {
|
||||
auto root_ca = cfg.station->get_root_ca();
|
||||
if (!root_ca) {
|
||||
throw UsageError("hid8 is required (station has no Root CA configured)");
|
||||
}
|
||||
hid8 = *root_ca;
|
||||
}
|
||||
}
|
||||
|
||||
std::string url() const
|
||||
{
|
||||
return resolve_url(cfg.dc_url, url_override);
|
||||
}
|
||||
|
||||
const MainConfig& cfg;
|
||||
HashedId8 hid8;
|
||||
std::string url_override;
|
||||
bool print = false;
|
||||
std::function<void()> action;
|
||||
};
|
||||
|
||||
void show_info(Context& ctx)
|
||||
{
|
||||
std::cout << "DC URL: " << (ctx.url().empty() ? "[not set]" : ctx.url()) << "\n";
|
||||
}
|
||||
|
||||
void fetch_ctl(Context& ctx, CLI::Option* hid8_opt, CLI::Option* dry_flag)
|
||||
{
|
||||
ctx.lookup_root_ca(hid8_opt);
|
||||
DistributionCentre dc;
|
||||
dc.set_url(ctx.url());
|
||||
auto ctl = dc.fetch_trust_list(ctx.hid8);
|
||||
if (ctl) {
|
||||
if (ctx.print) {
|
||||
CtlListingVisitor visitor(*ctx.cfg.security);
|
||||
ctl->visit_rca_ctl(visitor);
|
||||
}
|
||||
|
||||
auto ctl_digest = ctl->get_hashed_id8(*ctx.cfg.security);
|
||||
if (ctl_digest == ctx.hid8) {
|
||||
std::cout << "Fetched CTL matches Root CA digest\n";
|
||||
} else if (ctl_digest) {
|
||||
std::cout << "Fetched CTL has " << hexstring(*ctl_digest) << " digest mismatch.\n";
|
||||
} else {
|
||||
std::cout << "Cannot determine digest of CTL.\n";
|
||||
}
|
||||
|
||||
if (auto cert = ctx.cfg.root_ca->fetch(ctx.hid8)) {
|
||||
bool valid = validate(*ctx.cfg.security, ctl->raw(), *cert);
|
||||
if (valid) {
|
||||
if (dry_flag->as<bool>()) {
|
||||
std::cout << "CTL is valid. Storage unchanged in this dry run.\n";
|
||||
} else {
|
||||
ctx.cfg.trust_lists->store(*ctl);
|
||||
std::cout << "CTL is valid. Added to local trust list storage.\n";
|
||||
// Materialize the AA/EA certs embedded in the validated CTL
|
||||
CertificateExportVisitor exporter(ctx.cfg.authorization_authorities, ctx.cfg.enrolment_authorities);
|
||||
ctl->visit_rca_ctl(exporter);
|
||||
std::cout << "Exported " << exporter.exported_aa_certificates() << " AA and "
|
||||
<< exporter.exported_ea_certificates() << " EA certificate(s).\n";
|
||||
}
|
||||
} else {
|
||||
std::cout << "CTL cannot be trusted.\n";
|
||||
}
|
||||
} else {
|
||||
std::cout << "Cannot validate CTL because of missing Root CA certificate.\n";
|
||||
}
|
||||
} else {
|
||||
throw std::runtime_error("DC has no trust list matching HashedId8 " + hexstring(ctx.hid8));
|
||||
}
|
||||
}
|
||||
|
||||
void fetch_crl(Context& ctx, CLI::Option* hid8_opt, CLI::Option* dry_flag)
|
||||
{
|
||||
ctx.lookup_root_ca(hid8_opt);
|
||||
DistributionCentre dc;
|
||||
dc.set_url(ctx.url());
|
||||
auto crl = dc.fetch_revocation_list(ctx.hid8);
|
||||
if (!crl) {
|
||||
throw std::runtime_error("DC has no revocation list matching HashedId8 " + hexstring(ctx.hid8));
|
||||
}
|
||||
|
||||
auto crl_digest = crl->get_hashed_id8(*ctx.cfg.security);
|
||||
if (crl_digest == ctx.hid8) {
|
||||
std::cout << "Fetched CRL matches Root CA digest\n";
|
||||
} else if (crl_digest) {
|
||||
std::cout << "Fetched CRL has " << hexstring(*crl_digest) << " digest mismatch.\n";
|
||||
} else {
|
||||
std::cout << "Cannot determine digest of CRL.\n";
|
||||
}
|
||||
|
||||
if (ctx.print) {
|
||||
if (crl_digest) {
|
||||
std::cout << "Issuer: " << hexstring(*crl_digest) << "\n";
|
||||
}
|
||||
if (auto entries = crl->revoked_entries()) {
|
||||
std::cout << "Revoked certificates (" << entries->size() << "):\n";
|
||||
for (const auto& id : *entries) {
|
||||
std::cout << "- " << hexstring(id) << "\n";
|
||||
}
|
||||
} else {
|
||||
std::cout << "Revoked entries could not be decoded.\n";
|
||||
}
|
||||
}
|
||||
|
||||
auto root_cert = ctx.cfg.root_ca->fetch(ctx.hid8);
|
||||
if (!root_cert) {
|
||||
std::cout << "Cannot validate CRL because of missing Root CA certificate.\n";
|
||||
return;
|
||||
}
|
||||
if (!validate(*ctx.cfg.security, crl->raw(), *root_cert)) {
|
||||
std::cout << "CRL cannot be trusted.\n";
|
||||
return;
|
||||
}
|
||||
|
||||
if (dry_flag->as<bool>()) {
|
||||
std::cout << "CRL is valid. Storage unchanged in this dry run.\n";
|
||||
} else if (ctx.cfg.crl_store->store(*crl)) {
|
||||
std::cout << "CRL is valid. Added to local revocation list storage.\n";
|
||||
} else {
|
||||
std::cout << "CRL is valid but could not be indexed.\n";
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<CLI::App> build_info_command(std::shared_ptr<Context> ctx)
|
||||
{
|
||||
auto app = std::make_shared<CLI::App>("Distribution Centre info", "info");
|
||||
app->callback([ctx]() { ctx->action = [ctx]() { show_info(*ctx); }; });
|
||||
app->fallthrough();
|
||||
return app;
|
||||
}
|
||||
|
||||
std::shared_ptr<CLI::App> build_ctl_command(std::shared_ptr<Context> ctx)
|
||||
{
|
||||
auto app = std::make_shared<CLI::App>("fetch certificate trust list (CTL)", "ctl");
|
||||
app->alias("getctl");
|
||||
|
||||
auto hid8_opt = app->add_option("hid8", ctx->hid8, "HashedId8 of issuing entity (defaults to station's Root CA)")
|
||||
->check(hid8_validator);
|
||||
auto dry_flag = app->add_flag("--dry-run,-n", "fetch and validate only; do not store the CTL");
|
||||
|
||||
app->callback([ctx, hid8_opt, dry_flag]() {
|
||||
ctx->action = [ctx, hid8_opt, dry_flag]() { fetch_ctl(*ctx, hid8_opt, dry_flag); };
|
||||
});
|
||||
|
||||
app->fallthrough();
|
||||
return app;
|
||||
}
|
||||
|
||||
std::shared_ptr<CLI::App> build_crl_command(std::shared_ptr<Context> ctx)
|
||||
{
|
||||
auto app = std::make_shared<CLI::App>("fetch certificate revocation list (CRL)", "crl");
|
||||
app->alias("getcrl");
|
||||
|
||||
auto hid8_opt = app->add_option("hid8", ctx->hid8, "HashedId8 of issuing Root CA (defaults to station's Root CA)")
|
||||
->check(hid8_validator);
|
||||
auto dry_flag = app->add_flag("--dry-run,-n", "fetch and validate only; do not store the CRL");
|
||||
|
||||
app->callback([ctx, hid8_opt, dry_flag]() {
|
||||
ctx->action = [ctx, hid8_opt, dry_flag]() { fetch_crl(*ctx, hid8_opt, dry_flag); };
|
||||
});
|
||||
|
||||
app->fallthrough();
|
||||
return app;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::shared_ptr<CLI::App> build_dc_command(const MainConfig& cfg)
|
||||
{
|
||||
auto ctx = std::make_shared<Context>(cfg);
|
||||
auto app = std::make_shared<CLI::App>("PKI Distribution Centre", "dc");
|
||||
app->add_flag("--print", ctx->print, "print received data in addition");
|
||||
app->add_option("--url", ctx->url_override, "override the Distribution Centre URL");
|
||||
|
||||
app->add_subcommand(build_info_command(ctx));
|
||||
app->add_subcommand(build_ctl_command(ctx));
|
||||
app->add_subcommand(build_crl_command(ctx));
|
||||
|
||||
app->require_subcommand(0, 1);
|
||||
app->final_callback([ctx]() {
|
||||
if (!ctx->action) {
|
||||
ctx->action = [ctx]() { show_info(*ctx); };
|
||||
}
|
||||
ctx->action();
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "main.hpp"
|
||||
#include <CLI/App.hpp>
|
||||
#include <memory>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
std::shared_ptr<CLI::App> build_dc_command(const MainConfig&);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "distribution_centre.hpp"
|
||||
#include "http.hpp"
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
DistributionCentre::DistributionCentre()
|
||||
{
|
||||
}
|
||||
|
||||
void DistributionCentre::set_url(const std::string& url)
|
||||
{
|
||||
m_base_query = HttpQuery::from_url(url);
|
||||
}
|
||||
|
||||
boost::optional<CertificateTrustList> DistributionCentre::fetch_trust_list(const HashedId8& digest)
|
||||
{
|
||||
HttpQuery query = m_base_query;
|
||||
query.path += "/getctl/" + hexstring(digest);
|
||||
|
||||
HttpResponse response = http_get(query);
|
||||
if (response.result() != boost::beast::http::status::ok) {
|
||||
return boost::none;
|
||||
} else if (response[boost::beast::http::field::content_type] != "application/x-its-ctl") {
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
CertificateTrustList trust_list;
|
||||
if (trust_list.decode(response.body())) {
|
||||
return trust_list;
|
||||
} else {
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
boost::optional<CertificateRevocationList> DistributionCentre::fetch_revocation_list(const HashedId8& digest)
|
||||
{
|
||||
// TS 102 941 v1.4.1 Annex D.2: GET <dc>/getcrl/<UPPERCASE-HEX-HashedId8>; reply application/x-its-crl.
|
||||
HttpQuery query = m_base_query;
|
||||
query.path += "/getcrl/" + hexstring(digest);
|
||||
|
||||
HttpResponse response = http_get(query);
|
||||
if (response.result() != boost::beast::http::status::ok) {
|
||||
return boost::none;
|
||||
} else if (response[boost::beast::http::field::content_type] != "application/x-its-crl") {
|
||||
return boost::none;
|
||||
}
|
||||
|
||||
CertificateRevocationList crl;
|
||||
if (crl.decode(response.body())) {
|
||||
return crl;
|
||||
} else {
|
||||
return boost::none;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate_revocation_list.hpp"
|
||||
#include "certificate_trust_list.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "http.hpp"
|
||||
#include <boost/optional/optional.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class DistributionCentre
|
||||
{
|
||||
public:
|
||||
DistributionCentre();
|
||||
|
||||
void set_url(const std::string&);
|
||||
|
||||
// TS 102 941 v1.4.1 Annex D.1.
|
||||
boost::optional<CertificateTrustList> fetch_trust_list(const HashedId8&);
|
||||
|
||||
// TS 102 941 v1.4.1 Annex D.2.
|
||||
boost::optional<CertificateRevocationList> fetch_revocation_list(const HashedId8&);
|
||||
|
||||
private:
|
||||
HttpQuery m_base_query;
|
||||
};
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,119 @@
|
||||
#include "ea_request.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "encrypted_data.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "psid_ssp.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include "signed_builder.hpp"
|
||||
#include "signed_data.hpp"
|
||||
#include <vanetza/asn1/security/InnerEcRequest.h>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
class InnerEcRequest : public asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest_t>
|
||||
{
|
||||
public:
|
||||
using wrapper = asn1::asn1c_oer_wrapper<Vanetza_Security_InnerEcRequest_t>;
|
||||
|
||||
InnerEcRequest() : wrapper(asn_DEF_Vanetza_Security_InnerEcRequest)
|
||||
{
|
||||
m_struct->certificateFormat = Vanetza_Security_CertificateFormat_ts103097v131;
|
||||
}
|
||||
|
||||
void set_its_id(const std::string& id)
|
||||
{
|
||||
if (OCTET_STRING_fromBuf(&m_struct->itsId, id.data(), id.size()) != 0) {
|
||||
throw std::runtime_error("setting ITS ID failed");
|
||||
}
|
||||
}
|
||||
|
||||
void set_verification_key(const PublicKey& pubkey)
|
||||
{
|
||||
pki::set_verification_key(m_struct->publicKeys.verificationKey, pubkey);
|
||||
}
|
||||
|
||||
void add_permission(const PsidSsp& perm)
|
||||
{
|
||||
if (m_struct->requestedSubjectAttributes.appPermissions == nullptr) {
|
||||
m_struct->requestedSubjectAttributes.appPermissions =
|
||||
asn1::allocate<Vanetza_Security_SequenceOfPsidSsp_t>();
|
||||
}
|
||||
|
||||
auto psid_ssp = asn1::allocate<Vanetza_Security_PsidSsp_t>();
|
||||
psid_ssp->psid = perm.psid;
|
||||
if (!perm.ssp.empty()) {
|
||||
psid_ssp->ssp = asn1::allocate<Vanetza_Security_ServiceSpecificPermissions_t>();
|
||||
psid_ssp->ssp->present = Vanetza_Security_ServiceSpecificPermissions_PR_bitmapSsp;
|
||||
copy(perm.ssp, psid_ssp->ssp->choice.bitmapSsp);
|
||||
}
|
||||
|
||||
auto* perms = m_struct->requestedSubjectAttributes.appPermissions;
|
||||
if (asn_sequence_add(perms, psid_ssp) != 0) {
|
||||
throw std::runtime_error("adding app permission to InnerEcRequest failed");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
ByteBuffer build_signed_enrolment_request(SecurityModule& security, const EnrolmentRequestParameters& params)
|
||||
{
|
||||
if (params.its_id.empty()) {
|
||||
throw std::invalid_argument("EnrolmentRequest: its_id must not be empty");
|
||||
}
|
||||
|
||||
// 1. InnerEcRequest
|
||||
InnerEcRequest inner;
|
||||
inner.set_its_id(params.its_id);
|
||||
inner.set_verification_key(params.verification_key);
|
||||
inner.add_permission(PsidSsp { aid::SCR, { 0x01, 0xC0 } });
|
||||
if (!inner.validate()) {
|
||||
throw std::runtime_error("EnrolmentRequest: constructed InnerEcRequest is invalid");
|
||||
}
|
||||
|
||||
// 2. InnerEcRequestSignedForPop wrapped in EtsiTs102941Data
|
||||
MgmtData pop_data;
|
||||
pop_data->version = Vanetza_Security_Version_v1;
|
||||
pop_data->content.present = Vanetza_Security_EtsiTs102941DataContent_PR_enrolmentRequest;
|
||||
// Inner PoP is always signer = self (TS 102 941 §6.2.3.2.1)
|
||||
create_signed(inner.encode(), security, params.verification_key, params.hash_algo, nullptr)
|
||||
.move_into(pop_data->content.choice.enrolmentRequest);
|
||||
|
||||
// 3. Outer EtsiTs103097Data-Signed: signer = self for initial enrolment or
|
||||
// signer = digest(outer_signer_certificate) for a re-keying renewal.
|
||||
SignedData outer = create_signed(pop_data.encode(), security, params.outer_signer_key, params.hash_algo,
|
||||
params.outer_signer_certificate);
|
||||
return outer.encode();
|
||||
}
|
||||
|
||||
EncryptedData build_enrolment_request(SecurityModule& security, const EnrolmentRequestParameters& params,
|
||||
const Certificate& ea_certificate)
|
||||
{
|
||||
boost::optional<PublicKey> ea_enckey = ea_certificate.get_encryption_key();
|
||||
if (!ea_enckey) {
|
||||
throw DecodingFailure("EnrolmentRequest: EA certificate has no encryption key");
|
||||
}
|
||||
|
||||
ByteBuffer signed_request = build_signed_enrolment_request(security, params);
|
||||
|
||||
Sha256Hash ea_cert_sha256 = calculate_sha256_hash(security, ea_certificate);
|
||||
auto ecies_unique = security.create_ecies_context(*ea_enckey, ea_cert_sha256);
|
||||
std::shared_ptr<SecurityModule::EciesContext> ecies { std::move(ecies_unique) };
|
||||
EncryptedData encrypted { ecies };
|
||||
encrypted.generate_ciphertext(signed_request);
|
||||
encrypted.add_recipient_info(ea_certificate.calculate_hashed_id8(security));
|
||||
|
||||
return encrypted;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include "keys.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <vanetza/security/hash_algorithm.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class Certificate;
|
||||
class EncryptedData;
|
||||
class SecurityModule;
|
||||
|
||||
using security::HashAlgorithm;
|
||||
|
||||
/**
|
||||
* \brief Parameters for an InnerEcRequest / outer EtsiTs103097Data-Signed enrolment message.
|
||||
* \see TS 102 941 §6.2.3.2
|
||||
*/
|
||||
struct EnrolmentRequestParameters
|
||||
{
|
||||
std::string its_id; // canonical id (initial) or current EC HashedId8 (re-enrolment)
|
||||
PublicKey verification_key; // to be certified; private key in SecurityModule for POP signature
|
||||
PublicKey outer_signer_key; // signs outer Data-Signed; canonical key (initial) or current EC verification key (re-enrolment)
|
||||
HashAlgorithm hash_algo = HashAlgorithm::SHA256; // POP and outer signatures
|
||||
const Certificate* outer_signer_certificate = nullptr; // null → signer=self; non-null → signer=digest of this cert
|
||||
};
|
||||
|
||||
/**
|
||||
* \brief Build the signed (but not yet encrypted) enrolment request payload.
|
||||
*
|
||||
* Layered signatures: outer EtsiTs103097Data-Signed (signed with outer_signer_key;
|
||||
* signer=self for initial enrolment, digest(outer_signer_certificate) for re-keying)
|
||||
* wraps EtsiTs102941Data{enrolmentRequest=InnerEcRequestSignedForPop}, which is
|
||||
* the OER-encoded InnerEcRequest signed with verification_key (signer=self) as POP.
|
||||
* Exposed for testing; production code should call build_enrolment_request().
|
||||
*/
|
||||
ByteBuffer build_signed_enrolment_request(SecurityModule& security, const EnrolmentRequestParameters& parameters);
|
||||
|
||||
/**
|
||||
* \brief Build the EA-encrypted enrolment request.
|
||||
*
|
||||
* Call .encode() on the result for the OER bytes to POST. The ECIES context
|
||||
* held in the returned EncryptedData is also needed to decrypt the EA's
|
||||
* response (same symmetric key via pskRecipInfo).
|
||||
*/
|
||||
EncryptedData build_enrolment_request(SecurityModule& security, const EnrolmentRequestParameters& parameters,
|
||||
const Certificate& ea_certificate);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,74 @@
|
||||
#include "ea_response.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include "signed_data.hpp"
|
||||
#include "validation.hpp"
|
||||
#include <vanetza/asn1/security/EtsiTs102941Data.h>
|
||||
#include <vanetza/asn1/security/InnerEcResponse.h>
|
||||
#include <vanetza/common/its_aid.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
EnrolmentResponse parse_enrolment_response(SecurityModule& security, const ByteBuffer& decrypted,
|
||||
const Certificate& ea_certificate)
|
||||
{
|
||||
SignedData outer;
|
||||
if (!outer.decode(decrypted)) {
|
||||
throw DecodingFailure("decoding signed enrolment response failed");
|
||||
}
|
||||
if (outer->content->present != Vanetza_Security_Ieee1609Dot2Content_PR_signedData) {
|
||||
throw DecodingFailure("enrolment response content is not signedData");
|
||||
}
|
||||
const Vanetza_Security_SignedData_t& sd = *outer->content->choice.signedData;
|
||||
|
||||
// Per TS 102 941 §6.2.3.2.2 the EA signs enrolment responses with signer = digest(EA cert).
|
||||
const HashedId8 ea_hid8 = ea_certificate.calculate_hashed_id8(security);
|
||||
if (sd.signer.present != Vanetza_Security_SignerIdentifier_PR_digest) {
|
||||
throw DecodingFailure("enrolment response must have signer = digest");
|
||||
}
|
||||
if (sd.signer.choice.digest != ea_hid8.octets) {
|
||||
throw VerificationFailure("enrolment response signer digest does not match EA certificate");
|
||||
}
|
||||
|
||||
if (sd.tbsData->headerInfo.psid != aid::SCR) {
|
||||
throw DecodingFailure("enrolment response PSID is not SCR");
|
||||
}
|
||||
|
||||
if (!validate(security, sd, ea_certificate.raw())) {
|
||||
throw VerificationFailure("enrolment response signature does not verify against EA certificate");
|
||||
}
|
||||
|
||||
const Vanetza_Security_Opaque_t* inner_opaque = get_signed_payload(outer->content);
|
||||
if (!inner_opaque) {
|
||||
throw DecodingFailure("enrolment response carries no unsecured signed payload");
|
||||
}
|
||||
|
||||
EnrolmentResponseData inner = EnrolmentResponseData::from_opaque(*inner_opaque);
|
||||
if (inner->version != Vanetza_Security_Version_v1) {
|
||||
throw DecodingFailure("inner EtsiTs102941Data version is not v1");
|
||||
}
|
||||
|
||||
const Vanetza_Security_InnerEcResponse_t& ec_resp = inner->content.choice.enrolmentResponse;
|
||||
|
||||
EnrolmentResponse result;
|
||||
result.code = EnrolmentResponseCode { ec_resp.responseCode };
|
||||
result.request_hash.assign(ec_resp.requestHash.buf, ec_resp.requestHash.buf + ec_resp.requestHash.size);
|
||||
|
||||
if (ec_resp.certificate) {
|
||||
result.certificate = Certificate(*ec_resp.certificate);
|
||||
}
|
||||
|
||||
if (ec_resp.responseCode == Vanetza_Security_EnrolmentResponseCode_ok && !result.certificate) {
|
||||
throw DecodingFailure("enrolment response code is ok but no certificate is included");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include "certificate.hpp"
|
||||
#include "response_codes.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <boost/optional/optional.hpp>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
class SecurityModule;
|
||||
|
||||
/**
|
||||
* \brief Decoded view of an InnerEcResponse payload.
|
||||
* \see TS 102 941 §6.2.3.2.2
|
||||
*/
|
||||
struct EnrolmentResponse
|
||||
{
|
||||
EnrolmentResponseCode code; // EA's responseCode; parsing succeeds for any value
|
||||
ByteBuffer request_hash; // SHA-256 prefix of the matching request
|
||||
boost::optional<Certificate> certificate; // new EC; present iff one was decoded — caller must still check `code == ok`
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a decrypted EnrolmentResponse per ETSI TS 102 941 §6.2.3.2.2.
|
||||
*
|
||||
* Verifies:
|
||||
* - outer Ieee1609Dot2Data is signedData
|
||||
* - signer = digest, matching HashedId8(ea_certificate)
|
||||
* - tbsData.headerInfo.psid == aid::SCR
|
||||
* - outer signature verifies against ea_certificate
|
||||
* - inner EtsiTs102941Data.version == v1
|
||||
* - inner content variant is enrolmentResponse
|
||||
*
|
||||
* For a non-ok responseCode the function returns normally and `code` holds it;
|
||||
* `certificate` is populated iff the response actually contains one.
|
||||
*
|
||||
* \throws DecodingFailure on structural failure
|
||||
* \throws VerificationFailure on signer-digest or signature mismatch
|
||||
*/
|
||||
EnrolmentResponse parse_enrolment_response(SecurityModule& security, const ByteBuffer& decrypted,
|
||||
const Certificate& ea_certificate);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "ecies.hpp"
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
ByteBuffer calculate_kdf2(SecurityModule& security, const ByteBuffer& shared_secret, const ByteBuffer& kdp,
|
||||
std::size_t dl)
|
||||
{
|
||||
Sha256Function fn = [&security](const ByteBuffer& buffer) {
|
||||
return security.calculate_sha256_hash(buffer.data(), buffer.size());
|
||||
};
|
||||
return calculate_kdf2(fn, shared_secret, kdp, dl);
|
||||
}
|
||||
|
||||
ByteBuffer calculate_kdf2(Sha256Function hash_fn, const ByteBuffer& shared_secret, const ByteBuffer& kdp,
|
||||
std::size_t dl)
|
||||
{
|
||||
ByteBuffer derived;
|
||||
ByteBuffer concat;
|
||||
|
||||
// each iteration adds 32 bytes (SHA-256 hash)
|
||||
const std::uint32_t iterations = dl / Sha256Hash::length + (dl % Sha256Hash::length ? 1 : 0);
|
||||
|
||||
// initialize counter with 1: see IEEE 1363.2a-2004 KDF2
|
||||
for (std::uint32_t counter = 1; counter <= iterations; ++counter) {
|
||||
// start concatenation with shared secret
|
||||
concat = shared_secret;
|
||||
// append 4-byte counter in big-endian order
|
||||
concat.insert(concat.end(), {
|
||||
static_cast<std::uint8_t>(counter >> 24),
|
||||
static_cast<std::uint8_t>(counter >> 16),
|
||||
static_cast<std::uint8_t>(counter >> 8),
|
||||
static_cast<std::uint8_t>(counter)
|
||||
});
|
||||
// finalize with key derivation parameter (P1)
|
||||
concat.insert(concat.end(), kdp.begin(), kdp.end());
|
||||
|
||||
Sha256Hash hash = hash_fn(concat);
|
||||
std::copy(hash.octets.begin(), hash.octets.end(), std::back_inserter(derived));
|
||||
}
|
||||
|
||||
// left most bytes are the derived key
|
||||
assert(derived.size() >= dl);
|
||||
derived.resize(dl);
|
||||
return derived;
|
||||
}
|
||||
|
||||
EncryptedSymmetricKey encrypt_key(SecurityModule& security, const SecurityModule::EciesContext& ecies,
|
||||
const ByteBuffer& key, const Sha256Hash& info)
|
||||
{
|
||||
const std::size_t ke_length = key.size();
|
||||
static constexpr std::size_t km_length = 32;
|
||||
|
||||
// derive ke and km from shared secret
|
||||
ByteBuffer kdp { info.octets.begin(), info.octets.end() };
|
||||
auto hashed_shared_secret = calculate_kdf2(security, ecies.shared_secret(), kdp, ke_length + km_length);
|
||||
assert(hashed_shared_secret.size() == ke_length + km_length);
|
||||
|
||||
EncryptedSymmetricKey result;
|
||||
result.public_key = ecies.ephemeral_public_key();
|
||||
|
||||
// encrypt symmetric key
|
||||
result.wrapped_key.resize(ke_length);
|
||||
std::uint8_t* ke = hashed_shared_secret.data();
|
||||
for (std::size_t i = 0; i < ke_length; ++i) {
|
||||
result.wrapped_key[i] = ke[i] ^ key[i];
|
||||
}
|
||||
|
||||
// generate authentication tag
|
||||
ByteBuffer km { std::next(hashed_shared_secret.begin(), ke_length), hashed_shared_secret.end() };
|
||||
assert(km.size() == km_length);
|
||||
result.authentication_tag = security.calculate_hmac_sha256(km, result.wrapped_key);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "security_module.hpp"
|
||||
#include <vanetza/common/byte_buffer.hpp>
|
||||
#include <cstddef>
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
using Sha256Function = std::function<Sha256Hash(const ByteBuffer&)>;
|
||||
|
||||
ByteBuffer calculate_kdf2(SecurityModule&, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t dl);
|
||||
ByteBuffer calculate_kdf2(Sha256Function, const ByteBuffer& shared_secret, const ByteBuffer& kdp, std::size_t dl);
|
||||
|
||||
struct EncryptedSymmetricKey
|
||||
{
|
||||
PublicKey public_key;
|
||||
ByteBuffer authentication_tag;
|
||||
ByteBuffer wrapped_key;
|
||||
};
|
||||
|
||||
EncryptedSymmetricKey encrypt_key(SecurityModule&, const SecurityModule::EciesContext&, const ByteBuffer& key,
|
||||
const Sha256Hash& info);
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
@@ -0,0 +1,133 @@
|
||||
#include "encrypted_data.hpp"
|
||||
#include "asn1.hpp"
|
||||
#include "certificate.hpp"
|
||||
#include "exception.hpp"
|
||||
#include "hashed_id8.hpp"
|
||||
#include "security_module.hpp"
|
||||
#include "signed_builder.hpp"
|
||||
|
||||
namespace vanetza
|
||||
{
|
||||
namespace pki
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
const Vanetza_Security_AesCcmCiphertext_t*
|
||||
get_aes_ccm_ciphertext(const Vanetza_Security_EtsiTs103097Data_Encrypted_85P0_t& dest)
|
||||
{
|
||||
if (dest.content && dest.content->present == Vanetza_Security_Ieee1609Dot2Content_PR_encryptedData) {
|
||||
const auto& enc = dest.content->choice.encryptedData;
|
||||
if (enc.ciphertext.present == Vanetza_Security_SymmetricCiphertext_PR_aes128ccm) {
|
||||
return &enc.ciphertext.choice.aes128ccm;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void EncryptedData::init(asn1c_type& dest)
|
||||
{
|
||||
dest.protocolVersion = ieee1609dot2_protocol_version;
|
||||
dest.content = asn1::allocate<Vanetza_Security_Ieee1609Dot2Content_t>();
|
||||
dest.content->present = Vanetza_Security_Ieee1609Dot2Content_PR_encryptedData;
|
||||
}
|
||||
|
||||
void EncryptedData::set_aes_ccm_ciphertext(asn1c_type& dest, SecurityModule::EciesContext& ecies,
|
||||
const ByteBuffer& plaintext)
|
||||
{
|
||||
ByteBuffer ciphertext = ecies.encrypt(plaintext);
|
||||
auto& aes = dest.content->choice.encryptedData.ciphertext;
|
||||
aes.present = Vanetza_Security_SymmetricCiphertext_PR_aes128ccm;
|
||||
copy(ecies.nonce(), aes.choice.aes128ccm.nonce);
|
||||
copy(ciphertext, aes.choice.aes128ccm.ccmCiphertext);
|
||||
}
|
||||
|
||||
void EncryptedData::append_recipient_info(asn1c_type& dest, const SecurityModule::EciesContext& ecies,
|
||||
const HashedId8& cert)
|
||||
{
|
||||
auto recipient = asn1::allocate<Vanetza_Security_RecipientInfo_t>();
|
||||
asn_sequence_add(&dest.content->choice.encryptedData.recipients.list, recipient);
|
||||
recipient->present = Vanetza_Security_RecipientInfo_PR_certRecipInfo;
|
||||
OCTET_STRING_fromBuf(&recipient->choice.certRecipInfo.recipientId,
|
||||
reinterpret_cast<const char*>(cert.octets.data()), cert.octets.size());
|
||||
|
||||
Vanetza_Security_EncryptedDataEncryptionKey_t& enckey = recipient->choice.certRecipInfo.encKey;
|
||||
switch (ecies.ephemeral_public_key().type) {
|
||||
case KeyType::NistP256:
|
||||
enckey.present = Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesNistP256;
|
||||
fill_curve_point(ecies.ephemeral_public_key(), enckey.choice.eciesNistP256.v);
|
||||
copy(ecies.authentication_tag(), enckey.choice.eciesNistP256.t);
|
||||
copy(ecies.encrypted_key(), enckey.choice.eciesNistP256.c);
|
||||
break;
|
||||
case KeyType::BrainpoolP256r1:
|
||||
enckey.present = Vanetza_Security_EncryptedDataEncryptionKey_PR_eciesBrainpoolP256r1;
|
||||
fill_curve_point(ecies.ephemeral_public_key(), enckey.choice.eciesBrainpoolP256r1.v);
|
||||
copy(ecies.authentication_tag(), enckey.choice.eciesBrainpoolP256r1.t);
|
||||
copy(ecies.encrypted_key(), enckey.choice.eciesBrainpoolP256r1.c);
|
||||
break;
|
||||
default:
|
||||
throw std::runtime_error("unsupported encryption key type");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
EncryptedData::EncryptedData(std::shared_ptr<SecurityModule::EciesContext> ecies) :
|
||||
wrapper(asn_DEF_Vanetza_Security_EtsiTs103097Data_Encrypted_85P0), m_ecies(ecies)
|
||||
{
|
||||
init(*m_struct);
|
||||
}
|
||||
|
||||
void EncryptedData::generate_ciphertext(const ByteBuffer& plaintext)
|
||||
{
|
||||
set_aes_ccm_ciphertext(*m_struct, *m_ecies, plaintext);
|
||||
}
|
||||
|
||||
void EncryptedData::add_recipient_info(const HashedId8& cert)
|
||||
{
|
||||
append_recipient_info(*m_struct, *m_ecies, cert);
|
||||
}
|
||||
|
||||
const OCTET_STRING_t* EncryptedData::get_nonce() const
|
||||
{
|
||||
auto aes_ccm = get_aes_ccm_ciphertext(*m_struct);
|
||||
return aes_ccm ? &aes_ccm->nonce : nullptr;
|
||||
}
|
||||
|
||||
const OCTET_STRING_t* EncryptedData::get_ciphertext() const
|
||||
{
|
||||
auto aes_ccm = get_aes_ccm_ciphertext(*m_struct);
|
||||
return aes_ccm ? &aes_ccm->ccmCiphertext : nullptr;
|
||||
}
|
||||
|
||||
bool EncryptedData::has_psk_recipient() const
|
||||
{
|
||||
const auto& recipients = m_struct->content->choice.encryptedData.recipients;
|
||||
for (int i = 0; i < recipients.list.count; ++i) {
|
||||
const Vanetza_Security_RecipientInfo_t* recipient = recipients.list.array[i];
|
||||
if (recipient && recipient->present == Vanetza_Security_RecipientInfo_PR_pskRecipInfo) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ByteBuffer EncryptedData::decrypt()
|
||||
{
|
||||
auto aes_ccm = get_aes_ccm_ciphertext(*m_struct);
|
||||
if (!aes_ccm) {
|
||||
throw DecodingFailure("missing AES CCM ciphertext");
|
||||
}
|
||||
// A PKI response reuses the request's symmetric key, referenced via pskRecipInfo.
|
||||
if (!has_psk_recipient()) {
|
||||
throw DecodingFailure("encrypted PKI response lacks expected pskRecipInfo recipient");
|
||||
}
|
||||
|
||||
m_ecies->nonce(to_buffer(aes_ccm->nonce));
|
||||
return m_ecies->decrypt(aes_ccm->ccmCiphertext.buf, aes_ccm->ccmCiphertext.size);
|
||||
}
|
||||
|
||||
} // namespace pki
|
||||
} // namespace vanetza
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user