Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
aktualizr_secondary.cc
1 #include "aktualizr_secondary.h"
2 
3 #include "crypto/keymanager.h"
4 #include "logging/logging.h"
5 #include "update_agent.h"
6 #include "uptane/manifest.h"
7 #include "utilities/utils.h"
8 
9 #include <sys/types.h>
10 #include <memory>
11 
12 AktualizrSecondary::AktualizrSecondary(AktualizrSecondaryConfig config, std::shared_ptr<INvStorage> storage,
13  std::shared_ptr<KeyManager> key_mngr, std::shared_ptr<UpdateAgent> update_agent)
14  : config_(std::move(config)),
15  storage_(std::move(storage)),
16  keys_(std::move(key_mngr)),
17  update_agent_(std::move(update_agent)) {
18  uptaneInitialize();
19  manifest_issuer_ = std::make_shared<Uptane::ManifestIssuer>(keys_, ecu_serial_);
20  initPendingTargetIfAny();
21 
22  if (hasPendingUpdate()) {
23  // TODO: refactor this to make it simpler as we don't need to persist/store
24  // an installation status of each ECU but store it just for a given secondary ECU
25  std::vector<Uptane::Target> installed_versions;
26  boost::optional<Uptane::Target> pending_target;
27  storage_->loadInstalledVersions(ecu_serial_.ToString(), nullptr, &pending_target);
28  data::InstallationResult install_res =
29  data::InstallationResult(data::ResultCode::Numeric::kUnknown, "Unknown installation error");
30  LOG_INFO << "Pending update found; attempting to apply it. Target hash: " << pending_target->sha256Hash();
31 
32  if (!!pending_target) {
33  install_res = update_agent_->applyPendingInstall(*pending_target);
34 
35  if (install_res.result_code != data::ResultCode::Numeric::kNeedCompletion) {
36  storage_->saveEcuInstallationResult(ecu_serial_, install_res);
37 
38  if (install_res.success) {
39  LOG_INFO << "Pending update has been successfully applied: " << pending_target->sha256Hash();
40  storage_->saveInstalledVersion(ecu_serial_.ToString(), *pending_target, InstalledVersionUpdateMode::kCurrent);
41  } else {
42  LOG_ERROR << "Application of the pending update has failed: (" << install_res.result_code.toString() << ")"
43  << install_res.description;
44  storage_->saveInstalledVersion(ecu_serial_.ToString(), *pending_target, InstalledVersionUpdateMode::kNone);
45  }
46 
47  director_repo_.dropTargets(*storage_);
48  } else {
49  LOG_INFO << "Pending update hasn't been applied because a reboot hasn't been detected";
50  }
51  }
52  }
53 }
54 
55 Uptane::EcuSerial AktualizrSecondary::getSerial() const { return ecu_serial_; }
56 
57 Uptane::HardwareIdentifier AktualizrSecondary::getHwId() const { return hardware_id_; }
58 
59 PublicKey AktualizrSecondary::getPublicKey() const { return keys_->UptanePublicKey(); }
60 
61 Uptane::Manifest AktualizrSecondary::getManifest() const {
62  Uptane::InstalledImageInfo installed_image_info;
63  Uptane::Manifest manifest;
64  if (update_agent_->getInstalledImageInfo(installed_image_info)) {
65  manifest = manifest_issuer_->assembleAndSignManifest(installed_image_info);
66  }
67 
68  return manifest;
69 }
70 
71 int32_t AktualizrSecondary::getRootVersion(bool director) const {
72  std::string root_meta;
73  if (!storage_->loadLatestRoot(&root_meta,
74  (director) ? Uptane::RepositoryType::Director() : Uptane::RepositoryType::Image())) {
75  LOG_ERROR << "Could not load root metadata";
76  return -1;
77  }
78 
79  return Uptane::extractVersionUntrusted(root_meta);
80 }
81 
82 bool AktualizrSecondary::putRoot(const std::string& root, bool director) {
83  (void)root;
84  (void)director;
85  LOG_ERROR << "putRootResp is not implemented yet";
86  return false;
87 }
88 
89 bool AktualizrSecondary::putMetadata(const Metadata& metadata) { return doFullVerification(metadata); }
90 
91 bool AktualizrSecondary::sendFirmware(const std::string& firmware) {
92  if (!pending_target_.IsValid()) {
93  LOG_ERROR << "Aborting image download/receiving; no valid target found.";
94  return false;
95  }
96 
97  if (!update_agent_->download(pending_target_, firmware)) {
98  LOG_ERROR << "Failed to pull/store an update data";
99  pending_target_ = Uptane::Target::Unknown();
100  return false;
101  }
102 
103  return true;
104 }
105 
106 data::ResultCode::Numeric AktualizrSecondary::install(const std::string& target_name) {
107  if (!pending_target_.IsValid()) {
108  LOG_ERROR << "Aborting target image installation; no valid target found.";
110  }
111 
112  if (pending_target_.filename() != target_name) {
113  LOG_ERROR << "name of the target to install and a name of the pending target do not match";
115  }
116 
117  auto install_result = update_agent_->install(pending_target_);
118 
119  switch (install_result) {
120  case data::ResultCode::Numeric::kOk: {
121  storage_->saveInstalledVersion(ecu_serial_.ToString(), pending_target_, InstalledVersionUpdateMode::kCurrent);
122  pending_target_ = Uptane::Target::Unknown();
123  LOG_INFO << "The target has been successfully installed: " << target_name;
124  break;
125  }
126  case data::ResultCode::Numeric::kNeedCompletion: {
127  storage_->saveInstalledVersion(ecu_serial_.ToString(), pending_target_, InstalledVersionUpdateMode::kPending);
128  LOG_INFO << "The target has been successfully installed, but a reboot is required to be applied: " << target_name;
129  break;
130  }
131  default: { LOG_INFO << "Failed to install the target: " << target_name; }
132  }
133 
134  return install_result;
135 }
136 
137 bool AktualizrSecondary::doFullVerification(const Metadata& metadata) {
138  // 5.4.4.2. Full verification https://uptane.github.io/uptane-standard/uptane-standard.html#metadata_verification
139 
140  // 1. Load and verify the current time or the most recent securely attested time.
141  //
142  // We trust the time that the given system/OS/ECU provides, In ECU We Trust :)
143  TimeStamp now(TimeStamp::Now());
144 
145  // 2. Download and check the Root metadata file from the Director repository, following the procedure in
146  // Section 5.4.4.3. DirectorRepository::updateMeta() method implements this verification step, certain steps are
147  // missing though. see the method source code for details
148 
149  // 3. NOT SUPPORTED: Download and check the Timestamp metadata file from the Director repository, following the
150  // procedure in Section 5.4.4.4.
151  // 4. NOT SUPPORTED: Download and check the Snapshot metadata file from the Director repository, following the
152  // procedure in Section 5.4.4.5.
153  //
154  // 5. Download and check the Targets metadata file from the Director repository, following the procedure in
155  // Section 5.4.4.6. DirectorRepository::updateMeta() method implements this verification step
156  //
157  // The followin steps of the Director's target metadata verification are missing in DirectorRepository::updateMeta()
158  // 6. If checking Targets metadata from the Director repository, verify that there are no delegations.
159  // 7. If checking Targets metadata from the Director repository, check that no ECU identifier is represented more
160  // than once.
161  if (!director_repo_.updateMeta(*storage_, metadata)) {
162  LOG_ERROR << "Failed to update director metadata: " << director_repo_.getLastException().what();
163  return false;
164  }
165 
166  // 6. Download and check the Root metadata file from the Image repository, following the procedure in Section 5.4.4.3.
167  // 7. Download and check the Timestamp metadata file from the Image repository, following the procedure in
168  // Section 5.4.4.4.
169  // 8. Download and check the Snapshot metadata file from the Image repository, following the procedure in
170  // Section 5.4.4.5.
171  // 9. Download and check the top-level Targets metadata file from the Image repository, following the procedure in
172  // Section 5.4.4.6.
173  if (!image_repo_.updateMeta(*storage_, metadata)) {
174  LOG_ERROR << "Failed to update image metadata: " << image_repo_.getLastException().what();
175  return false;
176  }
177 
178  // 10. Verify that Targets metadata from the Director and Image repositories match.
179  if (!director_repo_.matchTargetsWithImageTargets(*(image_repo_.getTargets()))) {
180  LOG_ERROR << "Targets metadata from the Director and Image repositories DOES NOT match ";
181  return false;
182  }
183 
184  auto targetsForThisEcu = director_repo_.getTargets(getSerial(), getHwId());
185 
186  if (targetsForThisEcu.size() != 1) {
187  LOG_ERROR << "Invalid number of targets (should be 1): " << targetsForThisEcu.size();
188  return false;
189  }
190 
191  if (!update_agent_->isTargetSupported(targetsForThisEcu[0])) {
192  LOG_ERROR << "The given target type is not supported: " << targetsForThisEcu[0].type();
193  return false;
194  }
195 
196  pending_target_ = targetsForThisEcu[0];
197 
198  return true;
199 }
200 
201 void AktualizrSecondary::uptaneInitialize() {
202  if (keys_->generateUptaneKeyPair().size() == 0) {
203  throw std::runtime_error("Failed to generate uptane key pair");
204  }
205 
206  // from uptane/initialize.cc but we only take care of our own serial/hwid
207  EcuSerials ecu_serials;
208 
209  if (storage_->loadEcuSerials(&ecu_serials)) {
210  ecu_serial_ = ecu_serials[0].first;
211  hardware_id_ = ecu_serials[0].second;
212  return;
213  }
214 
215  std::string ecu_serial_local = config_.uptane.ecu_serial;
216  if (ecu_serial_local.empty()) {
217  ecu_serial_local = keys_->UptanePublicKey().KeyId();
218  }
219 
220  std::string ecu_hardware_id = config_.uptane.ecu_hardware_id;
221  if (ecu_hardware_id.empty()) {
222  ecu_hardware_id = Utils::getHostname();
223  if (ecu_hardware_id == "") {
224  throw std::runtime_error("Failed to define ECU hardware ID");
225  }
226  }
227 
228  ecu_serials.emplace_back(Uptane::EcuSerial(ecu_serial_local), Uptane::HardwareIdentifier(ecu_hardware_id));
229  storage_->storeEcuSerials(ecu_serials);
230  ecu_serial_ = ecu_serials[0].first;
231  hardware_id_ = ecu_serials[0].second;
232 
233  // this is a way to find out and store a value of the target name that is installed
234  // at the initial/provisioning stage and included into a device manifest
235  // i.e. 'filepath' field or ["signed"]["installed_image"]["filepath"]
236  // this value must match the value pushed to the backend during the bitbaking process,
237  // specifically, at its ostree push phase and is equal to
238  // GARAGE_TARGET_NAME ?= "${OSTREE_BRANCHNAME}" which in turn is equal to OSTREE_BRANCHNAME ?= "${SOTA_HARDWARE_ID}"
239  // therefore, by default GARAGE_TARGET_NAME == OSTREE_BRANCHNAME == SOTA_HARDWARE_ID
240  // If there is no match then the backend/UI will not render/highlight currently installed version at all/correctly
241  storage_->importInstalledVersions(config_.import.base_path);
242 }
243 
244 void AktualizrSecondary::initPendingTargetIfAny() {
245  if (!director_repo_.checkMetaOffline(*storage_)) {
246  LOG_INFO << "No any valid and pending director's targets to be applied";
247  return;
248  }
249 
250  auto targetsForThisEcu = director_repo_.getTargets(ecu_serial_, hardware_id_);
251 
252  if (targetsForThisEcu.size() != 1) {
253  LOG_ERROR << "Invalid number of targets (should be 1): " << targetsForThisEcu.size();
254  return;
255  }
256 
257  if (!update_agent_->isTargetSupported(targetsForThisEcu[0])) {
258  LOG_ERROR << "The given target type is not supported: " << targetsForThisEcu[0].type();
259  return;
260  }
261 
262  LOG_INFO << "There is a valid and pending director's target to be applied";
263  pending_target_ = targetsForThisEcu[0];
264 }
data::InstallationResult
Definition: types.h:179
AktualizrSecondaryConfig
Definition: aktualizr_secondary_config.h:39
Uptane::HardwareIdentifier
Definition: tuf.h:143
TimeStamp
Definition: types.h:85
Uptane::InstalledImageInfo
Definition: tuf.h:132
Uptane::EcuSerial
Definition: tuf.h:174
PublicKey
Definition: crypto.h:26
data::ResultCode::Numeric::kInternalError
SWM Internal integrity error.
data::ResultCode::Numeric
Numeric
Definition: types.h:125
Metadata
Definition: aktualizr_secondary_metadata.h:8
Uptane::Manifest
Definition: manifest.h:13