Aktualizr
C++ SOTA Client
All Classes Namespaces Files Functions Variables Enumerations Enumerator Pages
tuf.cc
1 #include "uptane/tuf.h"
2 
3 #include <ctime>
4 #include <ostream>
5 #include <sstream>
6 
7 #include <boost/algorithm/hex.hpp>
8 #include <boost/algorithm/string/case_conv.hpp>
9 #include <utility>
10 
11 #include "crypto/crypto.h"
12 #include "libaktualizr/types.h"
13 #include "logging/logging.h"
14 #include "utilities/exceptions.h"
15 
16 using Uptane::Target;
17 using Uptane::Version;
18 
19 std::ostream &Uptane::operator<<(std::ostream &os, const Version &v) {
20  if (v.version_ == Version::ANY_VERSION) {
21  os << "vANY";
22  } else {
23  os << "v" << v.version_;
24  }
25  return os;
26 }
27 
28 std::ostream &Uptane::operator<<(std::ostream &os, const HardwareIdentifier &hwid) {
29  os << hwid.hwid_;
30  return os;
31 }
32 
33 std::ostream &Uptane::operator<<(std::ostream &os, const EcuSerial &ecu_serial) {
34  os << ecu_serial.ecu_serial_;
35  return os;
36 }
37 
38 std::string Hash::encodeVector(const std::vector<Hash> &hashes) {
39  std::stringstream hs;
40 
41  for (auto it = hashes.cbegin(); it != hashes.cend(); it++) {
42  hs << it->TypeString() << ":" << it->HashString();
43  if (std::next(it) != hashes.cend()) {
44  hs << ";";
45  }
46  }
47 
48  return hs.str();
49 }
50 
51 std::vector<Hash> Hash::decodeVector(std::string hashes_str) {
52  std::vector<Hash> hash_v;
53 
54  std::string cs = std::move(hashes_str);
55  while (!cs.empty()) {
56  size_t scp = cs.find(';');
57  std::string hash_token = cs.substr(0, scp);
58  if (scp == std::string::npos) {
59  cs = "";
60  } else {
61  cs = cs.substr(scp + 1);
62  }
63  if (hash_token.empty()) {
64  break;
65  }
66 
67  size_t cp = hash_token.find(':');
68  std::string hash_type_str = hash_token.substr(0, cp);
69  if (cp == std::string::npos) {
70  break;
71  }
72  std::string hash_value_str = hash_token.substr(cp + 1);
73 
74  if (!hash_value_str.empty()) {
75  Hash h{hash_type_str, hash_value_str};
76  if (h.type() != Hash::Type::kUnknownAlgorithm) {
77  hash_v.push_back(std::move(h));
78  }
79  }
80  }
81 
82  return hash_v;
83 }
84 
85 Target::Target(std::string filename, const Json::Value &content) : filename_(std::move(filename)) {
86  if (content.isMember("custom")) {
87  custom_ = content["custom"];
88 
89  // Image repo provides an array of hardware IDs.
90  if (custom_.isMember("hardwareIds")) {
91  Json::Value hwids = custom_["hardwareIds"];
92  for (auto i = hwids.begin(); i != hwids.end(); ++i) {
93  hwids_.emplace_back(HardwareIdentifier((*i).asString()));
94  }
95  }
96 
97  // Director provides a map of ECU serials to hardware IDs.
98  Json::Value ecus = custom_["ecuIdentifiers"];
99  for (auto i = ecus.begin(); i != ecus.end(); ++i) {
100  ecus_.insert({EcuSerial(i.key().asString()), HardwareIdentifier((*i)["hardwareId"].asString())});
101  }
102 
103  if (custom_.isMember("targetFormat")) {
104  type_ = custom_["targetFormat"].asString();
105  }
106 
107  if (custom_.isMember("uri")) {
108  std::string custom_uri = custom_["uri"].asString();
109  // Ignore this exact URL for backwards compatibility with old defaults that inserted it.
110  if (custom_uri != "https://example.com/") {
111  uri_ = std::move(custom_uri);
112  }
113  }
114  }
115 
116  length_ = content["length"].asUInt64();
117 
118  Json::Value hashes = content["hashes"];
119  for (auto i = hashes.begin(); i != hashes.end(); ++i) {
120  Hash h(i.key().asString(), (*i).asString());
121  if (h.HaveAlgorithm()) {
122  hashes_.push_back(h);
123  }
124  }
125  // sort hashes so that higher priority hash algorithm goes first
126  std::sort(hashes_.begin(), hashes_.end(), [](const Hash &l, const Hash &r) { return l.type() < r.type(); });
127 }
128 
129 // Internal use only.
130 Target::Target(std::string filename, EcuMap ecus, std::vector<Hash> hashes, uint64_t length, std::string correlation_id)
131  : filename_(std::move(filename)),
132  ecus_(std::move(ecus)),
133  hashes_(std::move(hashes)),
134  length_(length),
135  correlation_id_(std::move(correlation_id)) {
136  // sort hashes so that higher priority hash algorithm goes first
137  std::sort(hashes_.begin(), hashes_.end(), [](const Hash &l, const Hash &r) { return l.type() < r.type(); });
138  type_ = "UNKNOWN";
139 }
140 
141 Target Target::Unknown() {
142  Json::Value t_json;
143  t_json["hashes"]["sha256"] = boost::algorithm::to_lower_copy(boost::algorithm::hex(Crypto::sha256digest("")));
144  t_json["length"] = 0;
145  Uptane::Target target{"unknown", t_json};
146 
147  target.valid = false;
148 
149  return target;
150 }
151 
152 bool Target::MatchHash(const Hash &hash) const {
153  return (std::find(hashes_.begin(), hashes_.end(), hash) != hashes_.end());
154 }
155 
156 std::string Target::hashString(Hash::Type type) const {
157  std::vector<Hash>::const_iterator it;
158  for (it = hashes_.begin(); it != hashes_.end(); it++) {
159  if (it->type() == type) {
160  return boost::algorithm::to_lower_copy(it->HashString());
161  }
162  }
163  return std::string("");
164 }
165 
166 std::string Target::sha256Hash() const { return hashString(Hash::Type::kSha256); }
167 
168 std::string Target::sha512Hash() const { return hashString(Hash::Type::kSha512); }
169 
170 bool Target::IsOstree() const {
171  if (type_ == "OSTREE") {
172  // Modern servers explicitly specify the type of the target
173  return true;
174  } else if (type_.empty() && length() == 0) {
175  // Older servers don't specify the type of the target. Assume that it is
176  // an OSTree target if the length is zero.
177  return true;
178  } else {
179  // If type is explicitly not OSTREE or the length is non-zero, then this
180  // is a firmware blob.
181  return false;
182  }
183 }
184 
185 bool Target::MatchTarget(const Target &t2) const {
186  // type_ (targetFormat) is only provided by the Image repo.
187  // ecus_ is only provided by the Image repo.
188  // correlation_id_ is only provided by the Director.
189  // uri_ is not matched. If the Director provides it, we use that. If not, but
190  // the Image repository does, use that. Otherwise, leave it empty and use the
191  // default.
192  if (filename_ != t2.filename_) {
193  return false;
194  }
195  if (length_ != t2.length_) {
196  return false;
197  }
198 
199  // If the HWID vector and ECU->HWID map match, we're good. Otherwise, assume
200  // we have a Target from the Director (ECU->HWID map populated, HWID vector
201  // empty) and a Target from the Image repo (HWID vector populated,
202  // ECU->HWID map empty). Figure out which Target has the map, and then for
203  // every item in the map, make sure it's in the other Target's HWID vector.
204  if (hwids_ != t2.hwids_ || ecus_ != t2.ecus_) {
205  std::shared_ptr<EcuMap> ecu_map; // Director
206  std::shared_ptr<std::vector<HardwareIdentifier>> hwid_vector; // Image repo
207  if (!hwids_.empty() && ecus_.empty() && t2.hwids_.empty() && !t2.ecus_.empty()) {
208  ecu_map = std::make_shared<EcuMap>(t2.ecus_);
209  hwid_vector = std::make_shared<std::vector<HardwareIdentifier>>(hwids_);
210  } else if (!t2.hwids_.empty() && t2.ecus_.empty() && hwids_.empty() && !ecus_.empty()) {
211  ecu_map = std::make_shared<EcuMap>(ecus_);
212  hwid_vector = std::make_shared<std::vector<HardwareIdentifier>>(t2.hwids_);
213  } else {
214  return false;
215  }
216  for (auto map_it = ecu_map->cbegin(); map_it != ecu_map->cend(); ++map_it) {
217  auto vec_it = find(hwid_vector->cbegin(), hwid_vector->cend(), map_it->second);
218  if (vec_it == hwid_vector->end()) {
219  return false;
220  }
221  }
222  }
223 
224  // requirements:
225  // - all hashes of the same type should match
226  // - at least one pair of hashes should match
227  bool oneMatchingHash = false;
228  for (const Hash &hash : hashes_) {
229  for (const Hash &hash2 : t2.hashes_) {
230  if (hash.type() == hash2.type() && !(hash == hash2)) {
231  return false;
232  }
233  if (hash == hash2) {
234  oneMatchingHash = true;
235  }
236  }
237  }
238  return oneMatchingHash;
239 }
240 
241 Json::Value Target::toDebugJson() const {
242  Json::Value res;
243  for (const auto &ecu : ecus_) {
244  res["custom"]["ecuIdentifiers"][ecu.first.ToString()]["hardwareId"] = ecu.second.ToString();
245  }
246  if (!hwids_.empty()) {
247  Json::Value hwids;
248  for (Json::Value::ArrayIndex i = 0; i < static_cast<Json::Value::ArrayIndex>(hwids_.size()); ++i) {
249  hwids[i] = hwids_[i].ToString();
250  }
251  res["custom"]["hardwareIds"] = hwids;
252  }
253  res["custom"]["targetFormat"] = type_;
254 
255  for (const auto &hash : hashes_) {
256  res["hashes"][hash.TypeString()] = hash.HashString();
257  }
258  res["length"] = Json::Value(static_cast<Json::Value::Int64>(length_));
259  return res;
260 }
261 
262 std::ostream &Uptane::operator<<(std::ostream &os, const Target &t) {
263  os << "Target(" << t.filename_;
264  os << " ecu_identifiers: (";
265  for (const auto &ecu : t.ecus_) {
266  os << ecu.first << " (hw_id: " << ecu.second << "), ";
267  }
268  os << ")"
269  << " hw_ids: (";
270  for (const auto &hwid : t.hwids_) {
271  os << hwid << ", ";
272  }
273  os << ")"
274  << " length:" << t.length();
275  os << " hashes: (";
276  for (const auto &hash : t.hashes_) {
277  os << hash << ", ";
278  }
279  os << "))";
280 
281  return os;
282 }
283 
284 void Uptane::BaseMeta::init(const Json::Value &json) {
285  if (!json.isObject() || !json.isMember("signed")) {
286  LOG_ERROR << "Failure during base metadata initialization from json";
287  throw Uptane::InvalidMetadata("", "", "invalid metadata json");
288  }
289 
290  version_ = json["signed"]["version"].asInt();
291  try {
292  expiry_ = TimeStamp(json["signed"]["expires"].asString());
293  } catch (const TimeStamp::InvalidTimeStamp &exc) {
294  throw Uptane::InvalidMetadata("", "", "invalid timestamp");
295  }
296  original_object_ = json;
297 }
298 Uptane::BaseMeta::BaseMeta(const Json::Value &json) { init(json); }
299 
300 Uptane::BaseMeta::BaseMeta(RepositoryType repo, const Role &role, const Json::Value &json,
301  const std::shared_ptr<MetaWithKeys> &signer) {
302  if (!json.isObject() || !json.isMember("signed")) {
303  throw Uptane::InvalidMetadata("", "", "invalid metadata json");
304  }
305 
306  signer->UnpackSignedObject(repo, role, json);
307 
308  init(json);
309 }
310 
311 void Uptane::Targets::init(const Json::Value &json) {
312  if (!json.isObject() || json["signed"]["_type"] != "Targets") {
313  throw Uptane::InvalidMetadata("", "targets", "invalid targets.json");
314  }
315 
316  const Json::Value target_list = json["signed"]["targets"];
317  for (auto t_it = target_list.begin(); t_it != target_list.end(); t_it++) {
318  Target t(t_it.key().asString(), *t_it);
319  targets.push_back(t);
320  }
321 
322  if (json["signed"]["delegations"].isObject()) {
323  const Json::Value key_list = json["signed"]["delegations"]["keys"];
324  ParseKeys(Uptane::RepositoryType::Image(), key_list);
325 
326  const Json::Value role_list = json["signed"]["delegations"]["roles"];
327  for (auto it = role_list.begin(); it != role_list.end(); it++) {
328  const std::string role_name = (*it)["name"].asString();
329  const Role role = Role::Delegation(role_name);
330  delegated_role_names_.push_back(role_name);
331  ParseRole(Uptane::RepositoryType::Image(), it, role, name_);
332 
333  const Json::Value paths_list = (*it)["paths"];
334  std::vector<std::string> paths;
335  for (auto p_it = paths_list.begin(); p_it != paths_list.end(); p_it++) {
336  paths.emplace_back((*p_it).asString());
337  }
338  paths_for_role_[role] = paths;
339 
340  terminating_role_[role] = (*it)["terminating"].asBool();
341  }
342  }
343 
344  if (json["signed"]["custom"].isObject()) {
345  correlation_id_ = json["signed"]["custom"]["correlationId"].asString();
346  } else {
347  correlation_id_ = "";
348  }
349 }
350 
351 Uptane::Targets::Targets(const Json::Value &json) : MetaWithKeys(json) { init(json); }
352 
353 Uptane::Targets::Targets(RepositoryType repo, const Role &role, const Json::Value &json,
354  const std::shared_ptr<MetaWithKeys> &signer)
355  : MetaWithKeys(repo, role, json, signer), name_(role.ToString()) {
356  init(json);
357 }
358 
359 void Uptane::TimestampMeta::init(const Json::Value &json) {
360  Json::Value hashes_list = json["signed"]["meta"]["snapshot.json"]["hashes"];
361  Json::Value meta_size = json["signed"]["meta"]["snapshot.json"]["length"];
362  Json::Value meta_version = json["signed"]["meta"]["snapshot.json"]["version"];
363  if (!json.isObject() || json["signed"]["_type"] != "Timestamp" || !hashes_list.isObject() ||
364  !meta_size.isIntegral() || !meta_version.isIntegral()) {
365  throw Uptane::InvalidMetadata("", "timestamp", "invalid timestamp.json");
366  }
367 
368  for (auto it = hashes_list.begin(); it != hashes_list.end(); ++it) {
369  Hash h(it.key().asString(), (*it).asString());
370  snapshot_hashes_.push_back(h);
371  }
372  snapshot_size_ = meta_size.asInt();
373  snapshot_version_ = meta_version.asInt();
374 }
375 
376 Uptane::TimestampMeta::TimestampMeta(const Json::Value &json) : BaseMeta(json) { init(json); }
377 
378 Uptane::TimestampMeta::TimestampMeta(RepositoryType repo, const Json::Value &json,
379  const std::shared_ptr<MetaWithKeys> &signer)
380  : BaseMeta(repo, Role::Timestamp(), json, signer) {
381  init(json);
382 }
383 
384 void Uptane::Snapshot::init(const Json::Value &json) {
385  Json::Value meta_list = json["signed"]["meta"];
386  if (!json.isObject() || json["signed"]["_type"] != "Snapshot" || !meta_list.isObject()) {
387  throw Uptane::InvalidMetadata("", "snapshot", "invalid snapshot.json");
388  }
389 
390  for (auto it = meta_list.begin(); it != meta_list.end(); ++it) {
391  Json::Value hashes_list = (*it)["hashes"];
392  Json::Value meta_size = (*it)["length"];
393  Json::Value meta_version = (*it)["version"];
394 
395  if (!meta_version.isIntegral()) {
396  throw Uptane::InvalidMetadata("", "snapshot", "invalid snapshot.json");
397  }
398 
399  auto role_name =
400  it.key().asString().substr(0, it.key().asString().rfind('.')); // strip extension from the role name
401  auto role_object = Role(role_name, !Role::IsReserved(role_name));
402 
403  if (meta_version.isIntegral()) {
404  role_version_[role_object] = meta_version.asInt();
405  } else {
406  role_version_[role_object] = -1;
407  }
408 
409  // Size and hashes are not required, but we may as well record them if
410  // present.
411  if (meta_size.isObject()) {
412  role_size_[role_object] = meta_size.asInt64();
413  } else {
414  role_size_[role_object] = -1;
415  }
416  if (hashes_list.isObject()) {
417  for (auto h_it = hashes_list.begin(); h_it != hashes_list.end(); ++h_it) {
418  Hash h(h_it.key().asString(), (*h_it).asString());
419  role_hashes_[role_object].push_back(h);
420  }
421  }
422  }
423 }
424 
425 Uptane::Snapshot::Snapshot(const Json::Value &json) : BaseMeta(json) { init(json); }
426 
427 Uptane::Snapshot::Snapshot(RepositoryType repo, const Json::Value &json, const std::shared_ptr<MetaWithKeys> &signer)
428  : BaseMeta(repo, Role::Snapshot(), json, signer) {
429  init(json);
430 }
431 
432 std::vector<Hash> Uptane::Snapshot::role_hashes(const Uptane::Role &role) const {
433  auto hashes = role_hashes_.find(role);
434  if (hashes == role_hashes_.end()) {
435  return std::vector<Hash>();
436  } else {
437  return hashes->second;
438  }
439 }
440 
441 int64_t Uptane::Snapshot::role_size(const Uptane::Role &role) const {
442  auto size = role_size_.find(role);
443  if (size == role_size_.end()) {
444  return 0;
445  } else {
446  return size->second;
447  }
448 }
449 
450 int Uptane::Snapshot::role_version(const Uptane::Role &role) const {
451  auto version = role_version_.find(role);
452  if (version == role_version_.end()) {
453  return -1;
454  } else {
455  return version->second;
456  }
457 };
458 
459 int Uptane::extractVersionUntrusted(const std::string &meta) {
460  auto version_json = Utils::parseJSON(meta)["signed"]["version"];
461  if (!version_json.isIntegral()) {
462  return -1;
463  } else {
464  return version_json.asInt();
465  }
466 }
467 
468 std::string Uptane::getMetaFromBundle(const MetaBundle &bundle, const RepositoryType repo, const Role &role) {
469  auto it = bundle.find(std::make_pair(repo, role));
470  if (it == bundle.end()) {
471  throw std::runtime_error("Metadata not found for " + role.ToString() + " role from the " + repo.toString() +
472  " repository.");
473  }
474  return it->second;
475 }
Metadata version numbers.
Definition: tuf.h:120
STL namespace.
bool IsOstree() const
Is this an OSTree target? OSTree targets need special treatment because the hash doesn&#39;t represent th...
Definition: tuf.cc:170
MetaWithKeys()
An empty metadata object that could contain keys.
Definition: tuf.h:167
TUF Roles.
Definition: tuf.h:61
The Hash class The hash of a file or Uptane metadata.
Definition: types.h:157