Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
initializer.cc
1 #include "initializer.h"
2 
3 #include <string>
4 
5 #include <openssl/bio.h>
6 #include <boost/scoped_array.hpp>
7 
8 #include "bootstrap/bootstrap.h"
9 #include "crypto/keymanager.h"
10 #include "logging/logging.h"
11 
12 // Postcondition: device_id is in the storage
13 void Initializer::initDeviceId() {
14  // If device_id is already stored, just return.
15  std::string device_id;
16  if (storage_->loadDeviceId(&device_id)) {
17  return;
18  }
19 
20  // If device_id is specified in the config, use that.
21  device_id = config_.device_id;
22  if (device_id.empty()) {
23  // Otherwise, try to read the device certificate if it is available.
24  try {
25  device_id = keys_.getCN();
26  } catch (const std::exception& e) {
27  // No certificate: for device credential provisioning, abort. For shared
28  // credential provisioning, generate a random name.
29  if (config_.mode == ProvisionMode::kSharedCred || config_.mode == ProvisionMode::kSharedCredReuse) {
30  device_id = Utils::genPrettyName();
31  } else if (config_.mode == ProvisionMode::kDeviceCred) {
32  throw e;
33  } else {
34  throw Error("Unknown provisioning method");
35  }
36  }
37  }
38 
39  storage_->storeDeviceId(device_id);
40 }
41 
42 void Initializer::resetDeviceId() { storage_->clearDeviceId(); }
43 
44 // Postcondition [(serial, hw_id)] is in the storage
45 void Initializer::initEcuSerials() {
46  EcuSerials stored_ecu_serials;
47  storage_->loadEcuSerials(&stored_ecu_serials);
48 
49  std::string primary_ecu_serial_local = config_.primary_ecu_serial;
50  if (primary_ecu_serial_local.empty()) {
51  primary_ecu_serial_local = keys_.UptanePublicKey().KeyId();
52  }
53 
54  std::string primary_ecu_hardware_id = config_.primary_ecu_hardware_id;
55  if (primary_ecu_hardware_id.empty()) {
56  primary_ecu_hardware_id = Utils::getHostname();
57  if (primary_ecu_hardware_id.empty()) {
58  throw Error("Could not get current host name, please configure an hardware ID explicitly");
59  }
60  }
61 
62  new_ecu_serials_.emplace_back(Uptane::EcuSerial(primary_ecu_serial_local),
63  Uptane::HardwareIdentifier(primary_ecu_hardware_id));
64  for (const auto& s : secondaries_) {
65  new_ecu_serials_.emplace_back(s.first, s.second->getHwId());
66  }
67 
68  register_ecus_ = stored_ecu_serials.empty();
69  if (!stored_ecu_serials.empty()) {
70  // We should probably clear the misconfigured_ecus table once we have
71  // consent working.
72  std::vector<bool> found(stored_ecu_serials.size(), false);
73 
74  EcuCompare primary_comp(new_ecu_serials_[0]);
75  EcuSerials::const_iterator store_it;
76  store_it = std::find_if(stored_ecu_serials.cbegin(), stored_ecu_serials.cend(), primary_comp);
77  if (store_it == stored_ecu_serials.cend()) {
78  LOG_INFO << "Configured Primary ECU serial " << new_ecu_serials_[0].first << " with hardware ID "
79  << new_ecu_serials_[0].second << " not found in storage.";
80  register_ecus_ = true;
81  } else {
82  found[static_cast<size_t>(store_it - stored_ecu_serials.cbegin())] = true;
83  }
84 
85  // Check all configured Secondaries to see if any are new.
86  for (auto it = secondaries_.cbegin(); it != secondaries_.cend(); ++it) {
87  EcuCompare secondary_comp(std::make_pair(it->second->getSerial(), it->second->getHwId()));
88  store_it = std::find_if(stored_ecu_serials.cbegin(), stored_ecu_serials.cend(), secondary_comp);
89  if (store_it == stored_ecu_serials.cend()) {
90  LOG_INFO << "Configured Secondary ECU serial " << it->second->getSerial() << " with hardware ID "
91  << it->second->getHwId() << " not found in storage.";
92  register_ecus_ = true;
93  } else {
94  found[static_cast<size_t>(store_it - stored_ecu_serials.cbegin())] = true;
95  }
96  }
97 
98  // Check all stored Secondaries not already matched to see if any have been
99  // removed. Store them in a separate table to keep track of them.
100  std::vector<bool>::iterator found_it;
101  for (found_it = found.begin(); found_it != found.end(); ++found_it) {
102  if (!*found_it) {
103  auto not_registered = stored_ecu_serials[static_cast<size_t>(found_it - found.begin())];
104  LOG_INFO << "ECU serial " << not_registered.first << " with hardware ID " << not_registered.second
105  << " in storage was not found in Secondary configuration.";
106  register_ecus_ = true;
107  storage_->saveMisconfiguredEcu({not_registered.first, not_registered.second, EcuState::kOld});
108  }
109  }
110  }
111 }
112 
113 // Postcondition: (public, private) is in the storage. It should not be stored until Secondaries are provisioned
114 void Initializer::initPrimaryEcuKeys() {
115  std::string key_pair;
116  try {
117  key_pair = keys_.generateUptaneKeyPair();
118  } catch (const std::exception& e) {
119  throw KeyGenerationError(e.what());
120  }
121 
122  if (key_pair.empty()) {
123  throw KeyGenerationError("Unknow error");
124  }
125 }
126 
127 bool Initializer::loadSetTlsCreds() {
128  keys_.copyCertsToCurl(*http_client_);
129  return keys_.isOk();
130 }
131 
132 // Postcondition: TLS credentials are in the storage
133 void Initializer::initTlsCreds() {
134  if (loadSetTlsCreds()) {
135  return;
136  }
137 
138  if (config_.mode == ProvisionMode::kDeviceCred) {
139  throw StorageError("Device credentials expected but not found");
140  }
141 
142  // Shared credential provisioning is required and possible => (automatically)
143  // provision with shared credentials.
144 
145  // Set bootstrap (shared) credentials.
146  Bootstrap boot(config_.provision_path, config_.p12_password);
147  http_client_->setCerts(boot.getCa(), CryptoSource::kFile, boot.getCert(), CryptoSource::kFile, boot.getPkey(),
148  CryptoSource::kFile);
149 
150  Json::Value data;
151  std::string device_id;
152  if (!storage_->loadDeviceId(&device_id)) {
153  throw StorageError("Unable to load device_id during shared credential provisioning");
154  }
155  data["deviceId"] = device_id;
156  data["ttl"] = config_.expiry_days;
157  HttpResponse response = http_client_->post(config_.server + "/devices", data);
158  if (!response.isOk()) {
159  Json::Value resp_code = response.getJson()["code"];
160  if (resp_code.isString() && resp_code.asString() == "device_already_registered") {
161  LOG_ERROR << "Device ID " << device_id << " is already registered.";
162  throw ServerOccupied();
163  }
164  const auto err = std::string("Shared credential provisioning failed: ") +
165  std::to_string(response.http_status_code) + " " + response.body;
166  throw ServerError(err);
167  }
168 
169  std::string pkey;
170  std::string cert;
171  std::string ca;
172  StructGuard<BIO> device_p12(BIO_new_mem_buf(response.body.c_str(), static_cast<int>(response.body.size())),
173  BIO_vfree);
174  if (!Crypto::parseP12(device_p12.get(), "", &pkey, &cert, &ca)) {
175  throw ServerError("Received malformed device credentials from the server");
176  }
177  storage_->storeTlsCreds(ca, cert, pkey);
178 
179  // Set provisioned (device) credentials.
180  if (!loadSetTlsCreds()) {
181  throw Error("Failed to configure HTTP client with device credentials.");
182  }
183 
184  if (config_.mode != ProvisionMode::kSharedCredReuse) {
185  // Remove shared provisioning credentials from the archive; we have no more
186  // use for them.
187  Utils::removeFileFromArchive(config_.provision_path, "autoprov_credentials.p12");
188  // Remove the treehub.json if it's still there. It shouldn't have been put on
189  // the device, but it has happened before.
190  try {
191  Utils::removeFileFromArchive(config_.provision_path, "treehub.json");
192  } catch (...) {
193  }
194  }
195 
196  LOG_INFO << "Provisioned successfully on Device Gateway.";
197 }
198 
199 void Initializer::resetTlsCreds() {
200  if (config_.mode != ProvisionMode::kDeviceCred) {
201  storage_->clearTlsCreds();
202  }
203 }
204 
205 // Postcondition: "ECUs registered" flag set in the storage
206 void Initializer::initEcuRegister() {
207  // Allow re-registration if the ECUs have changed.
208  if (!register_ecus_) {
209  LOG_DEBUG << "All ECUs are already registered with the server.";
210  return;
211  }
212 
213  PublicKey uptane_public_key = keys_.UptanePublicKey();
214 
215  if (uptane_public_key.Type() == KeyType::kUnknown) {
216  throw StorageError("Invalid key in storage");
217  }
218 
219  Json::Value all_ecus;
220  all_ecus["primary_ecu_serial"] = new_ecu_serials_[0].first.ToString();
221  all_ecus["ecus"] = Json::arrayValue;
222  {
223  Json::Value primary_ecu;
224  primary_ecu["hardware_identifier"] = new_ecu_serials_[0].second.ToString();
225  primary_ecu["ecu_serial"] = new_ecu_serials_[0].first.ToString();
226  primary_ecu["clientKey"] = keys_.UptanePublicKey().ToUptane();
227  all_ecus["ecus"].append(primary_ecu);
228  }
229 
230  for (const auto& info : sec_info_) {
231  Json::Value ecu;
232  ecu["hardware_identifier"] = info.hw_id.ToString();
233  ecu["ecu_serial"] = info.serial.ToString();
234  ecu["clientKey"] = info.pub_key.ToUptane();
235  all_ecus["ecus"].append(ecu);
236  }
237 
238  HttpResponse response = http_client_->post(config_.ecu_registration_endpoint, all_ecus);
239  if (!response.isOk()) {
240  Json::Value resp_code = response.getJson()["code"];
241  if (resp_code.isString() &&
242  (resp_code.asString() == "ecu_already_registered" || resp_code.asString() == "device_already_registered")) {
243  throw ServerError("One or more ECUs are unexpectedly already registered");
244  }
245  const auto err =
246  std::string("Error registering device: ") + std::to_string(response.http_status_code) + " " + response.body;
247  throw ServerError(err);
248  }
249 
250  // Only store the changes if we successfully registered the ECUs.
251  storage_->storeEcuSerials(new_ecu_serials_);
252  for (const auto& info : sec_info_) {
253  storage_->saveSecondaryInfo(info.serial, info.type, info.pub_key);
254  }
255  storage_->storeEcuRegistered();
256 
257  LOG_INFO << "ECUs have been successfully registered with the server.";
258 }
259 
260 void Initializer::initSecondaryInfo() {
261  for (const auto& s : secondaries_) {
262  const Uptane::EcuSerial serial = s.first;
263  SecondaryInterface& sec = *s.second;
264 
265  SecondaryInfo info;
266  // If upgrading from the older version of the storage without the
267  // secondary_ecus table, we need to migrate the data. This should be done
268  // regardless of whether we need to (re-)register the ECUs.
269  // The ECU serials should be already initialized by this point.
270  if (!storage_->loadSecondaryInfo(serial, &info) || info.type.empty() || info.pub_key.Type() == KeyType::kUnknown) {
271  info.serial = serial;
272  info.hw_id = sec.getHwId();
273  info.type = sec.Type();
274  const PublicKey& p = sec.getPublicKey();
275  if (p.Type() != KeyType::kUnknown) {
276  info.pub_key = p;
277  }
278  // If we don't need to register the ECUs, we still need to store this info
279  // to complete the migration.
280  if (!register_ecus_) {
281  storage_->saveSecondaryInfo(info.serial, info.type, info.pub_key);
282  }
283  }
284  // We will need this info later if the device is not yet provisioned
285  sec_info_.push_back(std::move(info));
286  }
287 }
288 
289 void Initializer::initEcuReportCounter() {
290  std::vector<std::pair<Uptane::EcuSerial, int64_t>> ecu_cnt;
291 
292  if (storage_->loadEcuReportCounter(&ecu_cnt)) {
293  return;
294  }
295 
296  EcuSerials ecu_serials;
297 
298  if (!storage_->loadEcuSerials(&ecu_serials) || ecu_serials.empty()) {
299  throw Error("Could not load ECU serials");
300  }
301 
302  storage_->saveEcuReportCounter(Uptane::EcuSerial(ecu_serials[0].first.ToString()), 0);
303 }
304 
305 // Postcondition: "ECUs registered" flag set in the storage
306 Initializer::Initializer(const ProvisionConfig& config_in, std::shared_ptr<INvStorage> storage_in,
307  std::shared_ptr<HttpInterface> http_client_in, KeyManager& keys_in,
308  const std::map<Uptane::EcuSerial, std::shared_ptr<SecondaryInterface>>& secondaries_in)
309  : config_(config_in),
310  storage_(std::move(storage_in)),
311  http_client_(std::move(http_client_in)),
312  keys_(keys_in),
313  secondaries_(secondaries_in) {
314  for (int i = 0; i < MaxInitializationAttempts; i++) {
315  initDeviceId();
316 
317  try {
318  initTlsCreds();
319  } catch (const ServerOccupied& e) {
320  // if a device with the same ID has already been registered to the server,
321  // generate a new one
322  resetDeviceId();
323  LOG_ERROR << "Device name is already registered. Retrying.";
324  continue;
325  }
326 
327  initPrimaryEcuKeys();
328 
329  initEcuSerials();
330 
331  initSecondaryInfo();
332 
333  initEcuRegister();
334 
335  initEcuReportCounter();
336 
337  return;
338  }
339 
340  throw Error(std::string("Initialization failed after ") + std::to_string(MaxInitializationAttempts) + " attempts");
341 }
ProvisionConfig
Definition: config.h:51
KeyManager
Definition: keymanager.h:13
EcuCompare
Definition: initializer.h:63
PublicKey::ToUptane
Json::Value ToUptane() const
Uptane Json representation of this public key.
Definition: crypto.cc:77
data
General data structures.
Definition: types.h:217
Uptane::HardwareIdentifier
Definition: types.h:323
HttpResponse
Definition: httpinterface.h:17
Uptane::EcuSerial
Definition: types.h:354
SecondaryInfo
Definition: types.h:470
PublicKey
Definition: types.h:119
Bootstrap
Definition: bootstrap.h:7
SecondaryInterface
Definition: secondaryinterface.h:9