1 #include "initializer.h"
5 #include <openssl/bio.h>
6 #include <boost/scoped_array.hpp>
8 #include "bootstrap/bootstrap.h"
9 #include "crypto/keymanager.h"
10 #include "logging/logging.h"
11 #include "storage/invstorage.h"
14 void Initializer::initDeviceId() {
16 std::string device_id;
17 if (storage_->loadDeviceId(&device_id)) {
22 device_id = config_.device_id;
23 if (device_id.empty()) {
24 if (config_.mode == ProvisionMode::kSharedCred) {
25 device_id = Utils::genPrettyName();
26 }
else if (config_.mode == ProvisionMode::kDeviceCred) {
27 device_id = keys_.getCN();
29 throw Error(
"Unknown provisioning method");
33 storage_->storeDeviceId(device_id);
36 void Initializer::resetDeviceId() { storage_->clearDeviceId(); }
39 void Initializer::initEcuSerials() {
40 EcuSerials ecu_serials;
44 if (storage_->loadEcuSerials(&ecu_serials)) {
48 std::string primary_ecu_serial_local = config_.primary_ecu_serial;
49 if (primary_ecu_serial_local.empty()) {
50 primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();
53 std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;
54 if (primary_ecu_hardware_id.empty()) {
55 primary_ecu_hardware_id = Utils::getHostname();
56 if (primary_ecu_hardware_id ==
"") {
57 throw Error(
"Could not get current host name, please configure an hardware ID explicitely");
64 for (
const auto& s : secondaries_) {
65 ecu_serials.emplace_back(s.first, s.second->getHwId());
68 storage_->storeEcuSerials(ecu_serials);
71 void Initializer::resetEcuSerials() { storage_->clearEcuSerials(); }
74 void Initializer::initPrimaryEcuKeys() {
77 key_pair = keys_.generateUptaneKeyPair();
78 }
catch (
const std::exception& e) {
79 throw KeyGenerationError(e.what());
82 if (key_pair.size() == 0U) {
83 throw KeyGenerationError(
"Unknow error");
87 void Initializer::resetEcuKeys() { storage_->clearPrimaryKeys(); }
89 bool Initializer::loadSetTlsCreds() {
90 keys_.copyCertsToCurl(*http_client_);
95 void Initializer::initTlsCreds() {
96 if (loadSetTlsCreds()) {
100 if (config_.mode != ProvisionMode::kSharedCred) {
101 throw StorageError(
"Shared credentials expected but not found");
108 Bootstrap boot(config_.provision_path, config_.p12_password);
109 http_client_->setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),
110 CryptoSource::kFile);
113 std::string device_id;
114 if (!storage_->loadDeviceId(&device_id)) {
115 throw StorageError(
"Unable to load device_id during shared credential provisioning");
117 data[
"deviceId"] = device_id;
118 data[
"ttl"] = config_.expiry_days;
119 HttpResponse response = http_client_->post(config_.server +
"/devices",
data);
120 if (!response.isOk()) {
121 Json::Value resp_code = response.getJson()[
"code"];
122 if (resp_code.isString() && resp_code.asString() ==
"device_already_registered") {
123 LOG_ERROR <<
"Device ID " << device_id <<
" is already registered.";
124 throw ServerOccupied();
126 const auto err = std::string(
"Shared credential provisioning failed: ") +
127 std::to_string(response.http_status_code) +
" " + response.body;
128 throw ServerError(err);
134 StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), static_cast<int>(response.body.size())),
136 if (!Crypto::parseP12(device_p12.get(),
"", &pkey, &cert, &ca)) {
137 throw ServerError(
"Received malformed device credentials from the server");
139 storage_->storeTlsCreds(ca, cert, pkey);
142 if (!loadSetTlsCreds()) {
143 throw Error(
"Failed to configure HTTP client with device credentials.");
146 LOG_INFO <<
"Provisioned successfully on Device Gateway.";
149 void Initializer::resetTlsCreds() {
150 if (config_.mode != ProvisionMode::kDeviceCred) {
151 storage_->clearTlsCreds();
156 void Initializer::initEcuRegister() {
157 if (storage_->loadEcuRegistered()) {
161 PublicKey uptane_public_key = keys_.UptanePublicKey();
163 if (uptane_public_key.Type() == KeyType::kUnknown) {
164 throw StorageError(
"Invalid key in storage");
167 EcuSerials ecu_serials;
169 if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.size() < 1) {
170 throw StorageError(
"Could not load ECUs from storage");
173 Json::Value all_ecus;
174 all_ecus[
"primary_ecu_serial"] = ecu_serials[0].first.ToString();
175 all_ecus[
"ecus"] = Json::arrayValue;
177 Json::Value primary_ecu;
178 primary_ecu[
"hardware_identifier"] = ecu_serials[0].second.ToString();
179 primary_ecu[
"ecu_serial"] = ecu_serials[0].first.ToString();
180 primary_ecu[
"clientKey"] = keys_.UptanePublicKey().
ToUptane();
181 all_ecus[
"ecus"].append(primary_ecu);
184 for (
const auto& sec : secondaries_) {
189 const PublicKey pub_key = itf.getPublicKey();
190 storage_->saveSecondaryInfo(ecu_serial, itf.Type(), pub_key);
193 ecu[
"hardware_identifier"] = hw_id.ToString();
194 ecu[
"ecu_serial"] = ecu_serial.ToString();
195 ecu[
"clientKey"] = pub_key.
ToUptane();
196 all_ecus[
"ecus"].append(ecu);
199 HttpResponse response = http_client_->post(config_.ecu_registration_endpoint, all_ecus);
200 if (!response.isOk()) {
201 Json::Value resp_code = response.getJson()[
"code"];
202 if (resp_code.isString() &&
203 (resp_code.asString() ==
"ecu_already_registered" || resp_code.asString() ==
"device_already_registered")) {
204 throw ServerError(
"One or more ECUs are unexpectedly already registered");
207 std::string(
"Error registering device: ") + std::to_string(response.http_status_code) +
" " + response.body;
208 throw ServerError(err);
211 LOG_INFO <<
"ECUs have been successfully registered with the server.";
214 void Initializer::initEcuReportCounter() {
215 std::vector<std::pair<Uptane::EcuSerial, int64_t>> ecu_cnt;
217 if (storage_->loadEcuReportCounter(&ecu_cnt)) {
221 EcuSerials ecu_serials;
223 if (!storage_->loadEcuSerials(&ecu_serials) || (ecu_serials.size() == 0)) {
224 throw Error(
"Could not load ECU serials");
227 storage_->saveEcuReportCounter(
Uptane::EcuSerial(ecu_serials[0].first.ToString()), 0);
231 Initializer::Initializer(
const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in,
232 std::shared_ptr<HttpInterface> http_client_in,
KeyManager& keys_in,
233 const std::map<
Uptane::EcuSerial, std::shared_ptr<Uptane::SecondaryInterface>>& secondaries_in)
234 : config_(config_in),
235 storage_(std::move(storage_in)),
236 http_client_(std::move(http_client_in)),
238 secondaries_(secondaries_in) {
239 for (
int i = 0; i < MaxInitializationAttempts; i++) {
244 }
catch (
const ServerOccupied& e) {
248 LOG_ERROR <<
"Device name is already registered. Retrying.";
252 initPrimaryEcuKeys();
256 initEcuReportCounter();
260 storage_->storeEcuRegistered();
265 throw Error(std::string(
"Initialization failed after ") + std::to_string(MaxInitializationAttempts) +
" attempts");