• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #define PW_LOG_MODULE_NAME "PWSU"
16 #define PW_LOG_LEVEL PW_LOG_LEVEL_WARN
17 
18 #include "pw_software_update/update_bundle_accessor.h"
19 
20 #include <cstddef>
21 #include <cstring>
22 #include <string_view>
23 
24 #include "pw_crypto/ecdsa.h"
25 #include "pw_crypto/sha256.h"
26 #include "pw_log/log.h"
27 #include "pw_protobuf/message.h"
28 #include "pw_result/result.h"
29 #include "pw_software_update/config.h"
30 #include "pw_software_update/manifest_accessor.h"
31 #include "pw_software_update/update_bundle.pwpb.h"
32 #include "pw_stream/interval_reader.h"
33 #include "pw_stream/memory_stream.h"
34 #include "pw_string/string_builder.h"
35 
36 namespace pw::software_update {
37 namespace {
38 
VerifyEcdsaSignature(protobuf::Bytes public_key,ConstByteSpan digest,protobuf::Bytes signature)39 Result<bool> VerifyEcdsaSignature(protobuf::Bytes public_key,
40                                   ConstByteSpan digest,
41                                   protobuf::Bytes signature) {
42   // TODO(pwbug/456): Move this logic into an variant of the API in
43   // pw_crypto:ecdsa that takes readers as inputs.
44   std::byte public_key_bytes[65];
45   std::byte signature_bytes[64];
46   stream::IntervalReader key_reader = public_key.GetBytesReader();
47   stream::IntervalReader sig_reader = signature.GetBytesReader();
48   PW_TRY(key_reader.Read(public_key_bytes));
49   PW_TRY(sig_reader.Read(signature_bytes));
50   Status status = crypto::ecdsa::VerifyP256Signature(
51       public_key_bytes, digest, signature_bytes);
52   if (!status.ok()) {
53     return false;
54   }
55 
56   return true;
57 }
58 
59 // Convert an integer from [0, 16) to a hex char
IntToHex(uint8_t val)60 char IntToHex(uint8_t val) {
61   PW_ASSERT(val < 16);
62   return val >= 10 ? (val - 10) + 'a' : val + '0';
63 }
64 
LogKeyId(ConstByteSpan key_id)65 void LogKeyId(ConstByteSpan key_id) {
66   char key_id_str[pw::crypto::sha256::kDigestSizeBytes * 2 + 1] = {0};
67   for (size_t i = 0; i < pw::crypto::sha256::kDigestSizeBytes; i++) {
68     uint8_t value = std::to_integer<uint8_t>(key_id[i]);
69     key_id_str[i * 2] = IntToHex((value >> 4) & 0xf);
70     key_id_str[i * 2 + 1] = IntToHex(value & 0xf);
71   }
72 
73   PW_LOG_DEBUG("key_id: %s", key_id_str);
74 }
75 
76 // Verifies signatures of a TUF metadata.
VerifyMetadataSignatures(protobuf::Bytes message,protobuf::RepeatedMessages signatures,protobuf::Message signature_requirement,protobuf::StringToMessageMap key_mapping)77 Status VerifyMetadataSignatures(protobuf::Bytes message,
78                                 protobuf::RepeatedMessages signatures,
79                                 protobuf::Message signature_requirement,
80                                 protobuf::StringToMessageMap key_mapping) {
81   // Gets the threshold -- at least `threshold` number of signatures must
82   // pass verification in order to trust this metadata.
83   protobuf::Uint32 threshold = signature_requirement.AsUint32(
84       static_cast<uint32_t>(SignatureRequirement::Fields::THRESHOLD));
85   PW_TRY(threshold.status());
86 
87   // Gets the ids of keys that are allowed for verifying the signatures.
88   protobuf::RepeatedBytes allowed_key_ids =
89       signature_requirement.AsRepeatedBytes(
90           static_cast<uint32_t>(SignatureRequirement::Fields::KEY_IDS));
91   PW_TRY(allowed_key_ids.status());
92 
93   // Verifies the signatures. Check that at least `threshold` number of
94   // signatures can be verified using the allowed keys.
95   size_t verified_count = 0;
96   size_t total_signatures = 0;
97   for (protobuf::Message signature : signatures) {
98     total_signatures++;
99     protobuf::Bytes key_id =
100         signature.AsBytes(static_cast<uint32_t>(Signature::Fields::KEY_ID));
101     PW_TRY(key_id.status());
102 
103     // Reads the key id into a buffer, so that we can check whether it is
104     // listed as allowed and look up the key value later.
105     std::byte key_id_buf[pw::crypto::sha256::kDigestSizeBytes];
106     stream::IntervalReader key_id_reader = key_id.GetBytesReader();
107     Result<ByteSpan> key_id_read_res = key_id_reader.Read(key_id_buf);
108     PW_TRY(key_id_read_res.status());
109     if (key_id_read_res.value().size() != sizeof(key_id_buf)) {
110       return Status::Internal();
111     }
112 
113     // Verify that the `key_id` is listed in `allowed_key_ids`.
114     // Note that the function assumes that the key id is properly derived
115     // from the key (via sha256).
116     bool key_id_is_allowed = false;
117     for (protobuf::Bytes trusted : allowed_key_ids) {
118       Result<bool> key_id_equal = trusted.Equal(key_id_buf);
119       PW_TRY(key_id_equal.status());
120       if (key_id_equal.value()) {
121         key_id_is_allowed = true;
122         break;
123       }
124     }
125 
126     if (!key_id_is_allowed) {
127       PW_LOG_DEBUG("Skipping a key id not listed in allowed key ids");
128       LogKeyId(key_id_buf);
129       continue;
130     }
131 
132     // Retrieves the signature bytes.
133     protobuf::Bytes sig =
134         signature.AsBytes(static_cast<uint32_t>(Signature::Fields::SIG));
135     PW_TRY(sig.status());
136 
137     // Extracts the key type, scheme and value information.
138     std::string_view key_id_str(reinterpret_cast<const char*>(key_id_buf),
139                                 sizeof(key_id_buf));
140     protobuf::Message key_info = key_mapping[key_id_str];
141     PW_TRY(key_info.status());
142 
143     protobuf::Bytes key_val =
144         key_info.AsBytes(static_cast<uint32_t>(Key::Fields::KEYVAL));
145     PW_TRY(key_val.status());
146 
147     // The function assume that all keys are ECDSA keys. This is guaranteed
148     // by the fact that all trusted roots have undergone content check.
149 
150     // computes the sha256 hash
151     std::byte sha256_digest[32];
152     stream::IntervalReader bytes_reader = message.GetBytesReader();
153     PW_TRY(crypto::sha256::Hash(bytes_reader, sha256_digest));
154     Result<bool> res = VerifyEcdsaSignature(key_val, sha256_digest, sig);
155     PW_TRY(res.status());
156     if (res.value()) {
157       verified_count++;
158       if (verified_count == threshold.value()) {
159         return OkStatus();
160       }
161     }
162   }
163 
164   if (total_signatures == 0) {
165     // For self verification to tell apart unsigned bundles.
166     return Status::NotFound();
167   }
168 
169   PW_LOG_ERROR("Insufficient signatures. Requires at least %u, verified %u",
170                threshold.value(),
171                verified_count);
172   return Status::Unauthenticated();
173 }
174 
175 // Verifies the signatures of a signed new root metadata against a given
176 // trusted root. The helper function extracts the corresponding key maping
177 // signature requirement, signatures from the trusted root and passes them
178 // to VerifyMetadataSignatures().
179 //
180 // Precondition: The trusted root metadata has undergone content validity check.
VerifyRootMetadataSignatures(protobuf::Message trusted_root,protobuf::Message new_root)181 Result<bool> VerifyRootMetadataSignatures(protobuf::Message trusted_root,
182                                           protobuf::Message new_root) {
183   // Retrieves the trusted root metadata content message.
184   protobuf::Message trusted = trusted_root.AsMessage(static_cast<uint32_t>(
185       SignedRootMetadata::Fields::SERIALIZED_ROOT_METADATA));
186   PW_TRY(trusted.status());
187 
188   // Retrieves the serialized new root metadata bytes.
189   protobuf::Bytes serialized = new_root.AsBytes(static_cast<uint32_t>(
190       SignedRootMetadata::Fields::SERIALIZED_ROOT_METADATA));
191   PW_TRY(serialized.status());
192 
193   // Gets the key mapping from the trusted root metadata.
194   protobuf::StringToMessageMap key_mapping = trusted.AsStringToMessageMap(
195       static_cast<uint32_t>(RootMetadata::Fields::KEYS));
196   PW_TRY(key_mapping.status());
197 
198   // Gets the signatures of the new root.
199   protobuf::RepeatedMessages signatures = new_root.AsRepeatedMessages(
200       static_cast<uint32_t>(SignedRootMetadata::Fields::SIGNATURES));
201   PW_TRY(signatures.status());
202 
203   // Gets the signature requirement from the trusted root metadata.
204   protobuf::Message signature_requirement = trusted.AsMessage(
205       static_cast<uint32_t>(RootMetadata::Fields::ROOT_SIGNATURE_REQUIREMENT));
206   PW_TRY(signature_requirement.status());
207 
208   // Verifies the signatures.
209   PW_TRY(VerifyMetadataSignatures(
210       serialized, signatures, signature_requirement, key_mapping));
211   return true;
212 }
213 
GetMetadataVersion(protobuf::Message & metadata,uint32_t common_metatdata_field_number)214 Result<uint32_t> GetMetadataVersion(protobuf::Message& metadata,
215                                     uint32_t common_metatdata_field_number) {
216   // message [Root|Targets]Metadata {
217   //   ...
218   //   CommonMetadata common_metadata = <field_number>;
219   //   ...
220   // }
221   //
222   // message CommonMetadata {
223   //   ...
224   //   uint32 version = <field_number>;
225   //   ...
226   // }
227   protobuf::Message common_metadata =
228       metadata.AsMessage(common_metatdata_field_number);
229   PW_TRY(common_metadata.status());
230   protobuf::Uint32 res = common_metadata.AsUint32(
231       static_cast<uint32_t>(software_update::CommonMetadata::Fields::VERSION));
232   PW_TRY(res.status());
233   return res.value();
234 }
235 
236 // Reads a protobuf::String into a buffer and returns a std::string_view.
ReadProtoString(protobuf::String str,std::span<char> buffer)237 Result<std::string_view> ReadProtoString(protobuf::String str,
238                                          std::span<char> buffer) {
239   stream::IntervalReader reader = str.GetBytesReader();
240   if (reader.interval_size() > buffer.size()) {
241     return Status::ResourceExhausted();
242   }
243 
244   Result<ByteSpan> res = reader.Read(std::as_writable_bytes(buffer));
245   PW_TRY(res.status());
246   return std::string_view(buffer.data(), res.value().size());
247 }
248 
249 }  // namespace
250 
OpenAndVerify()251 Status UpdateBundleAccessor::OpenAndVerify() {
252   if (Status status = DoOpen(); !status.ok()) {
253     PW_LOG_ERROR("Failed to open staged bundle");
254     return status;
255   }
256 
257   if (Status status = DoVerify(); !status.ok()) {
258     PW_LOG_ERROR("Failed to verified staged bundle");
259     Close();
260     return status;
261   }
262 
263   return OkStatus();
264 }
265 
GetTotalPayloadSize()266 Result<uint64_t> UpdateBundleAccessor::GetTotalPayloadSize() {
267   protobuf::RepeatedMessages manifested_targets =
268       GetManifest().GetTargetFiles();
269   PW_TRY(manifested_targets.status());
270 
271   protobuf::StringToBytesMap bundled_payloads = bundle_.AsStringToBytesMap(
272       static_cast<uint32_t>(UpdateBundle::Fields::TARGET_PAYLOADS));
273   PW_TRY(bundled_payloads.status());
274 
275   uint64_t total_bytes;
276   std::array<std::byte, MAX_TARGET_NAME_LENGTH> name_buffer = {};
277   for (protobuf::Message target : manifested_targets) {
278     protobuf::String target_name =
279         target.AsString(static_cast<uint32_t>(TargetFile::Fields::FILE_NAME));
280 
281     stream::IntervalReader name_reader = target_name.GetBytesReader();
282     PW_TRY(name_reader.status());
283     if (name_reader.interval_size() > name_buffer.size()) {
284       return Status::OutOfRange();
285     }
286 
287     Result<ByteSpan> read_result = name_reader.Read(name_buffer);
288     PW_TRY(read_result.status());
289 
290     ConstByteSpan name_span = read_result.value();
291     std::string_view name_view(reinterpret_cast<const char*>(name_span.data()),
292                                name_span.size_bytes());
293 
294     if (!bundled_payloads[name_view].ok()) {
295       continue;
296     }
297     protobuf::Uint64 target_length =
298         target.AsUint64(static_cast<uint32_t>(TargetFile::Fields::LENGTH));
299     PW_TRY(target_length.status());
300     total_bytes += target_length.value();
301   }
302 
303   return total_bytes;
304 }
305 
306 // Get the target element corresponding to `target_file`
GetTargetPayload(std::string_view target_name)307 stream::IntervalReader UpdateBundleAccessor::GetTargetPayload(
308     std::string_view target_name) {
309   protobuf::Message manifest_entry = GetManifest().GetTargetFile(target_name);
310   PW_TRY(manifest_entry.status());
311 
312   protobuf::StringToBytesMap payloads_map = bundle_.AsStringToBytesMap(
313       static_cast<uint32_t>(UpdateBundle::Fields::TARGET_PAYLOADS));
314   return payloads_map[target_name].GetBytesReader();
315 }
316 
317 // Get the target element corresponding to `target_file`
GetTargetPayload(protobuf::String target_name)318 stream::IntervalReader UpdateBundleAccessor::GetTargetPayload(
319     protobuf::String target_name) {
320   char name_buf[MAX_TARGET_NAME_LENGTH] = {0};
321   Result<std::string_view> name_view = ReadProtoString(target_name, name_buf);
322   PW_TRY(name_view.status());
323   return GetTargetPayload(name_view.value());
324 }
325 
PersistManifest()326 Status UpdateBundleAccessor::PersistManifest() {
327   ManifestAccessor manifest = GetManifest();
328   // GetManifest() fails if the bundle is yet to be verified.
329   PW_TRY(manifest.status());
330 
331   // Notify backend to prepare to receive a new manifest.
332   PW_TRY(backend_.BeforeManifestWrite());
333 
334   Result<stream::Writer*> writer = backend_.GetManifestWriter();
335   PW_TRY(writer.status());
336   PW_CHECK_NOTNULL(writer.value());
337 
338   PW_TRY(manifest.Export(*writer.value()));
339 
340   // Notify backend we are done writing. Backend should finalize
341   // (seal the box).
342   PW_TRY(backend_.AfterManifestWrite());
343 
344   return OkStatus();
345 }
346 
Close()347 Status UpdateBundleAccessor::Close() {
348   bundle_verified_ = false;
349   return blob_store_reader_.IsOpen() ? blob_store_reader_.Close() : OkStatus();
350 }
351 
DoOpen()352 Status UpdateBundleAccessor::DoOpen() {
353   PW_TRY(blob_store_.Init());
354   PW_TRY(blob_store_reader_.Open());
355   bundle_ = protobuf::Message(blob_store_reader_,
356                               blob_store_reader_.ConservativeReadLimit());
357   if (!bundle_.ok()) {
358     blob_store_reader_.Close();
359     return bundle_.status();
360   }
361   return OkStatus();
362 }
363 
DoVerify()364 Status UpdateBundleAccessor::DoVerify() {
365 #if PW_SOFTWARE_UPDATE_DISABLE_BUNDLE_VERIFICATION
366   PW_LOG_WARN("Bundle verification is compiled out.");
367   bundle_verified_ = true;
368   return OkStatus();
369 #else   // PW_SOFTWARE_UPDATE_DISABLE_BUNDLE_VERIFICATION
370   bundle_verified_ = false;
371 
372   // Verify and upgrade the on-device trust to the incoming root metadata if
373   // one is included.
374   if (Status status = UpgradeRoot(); !status.ok()) {
375     PW_LOG_ERROR("Failed to upgrade to Root in staged bundle");
376     return status;
377   }
378 
379   // TODO(pwbug/456): Verify the targets metadata against the current trusted
380   // root.
381   if (Status status = VerifyTargetsMetadata(); !status.ok()) {
382     PW_LOG_ERROR("Failed to verify Targets metadata");
383     return status;
384   }
385 
386   // TODO(pwbug/456): Investigate whether targets payload verification should
387   // be performed here or deferred until a specific target is requested.
388   if (Status status = VerifyTargetsPayloads(); !status.ok()) {
389     PW_LOG_ERROR("Failed to verify all manifested payloads");
390     return status;
391   }
392 
393   // TODO(pwbug/456): Invoke the backend to do downstream verification of the
394   // bundle (e.g. compatibility and manifest completeness checks).
395 
396   bundle_verified_ = true;
397   return OkStatus();
398 #endif  // PW_SOFTWARE_UPDATE_DISABLE_BUNDLE_VERIFICATION
399 }
400 
GetOnDeviceTrustedRoot()401 protobuf::Message UpdateBundleAccessor::GetOnDeviceTrustedRoot() {
402   Result<stream::SeekableReader*> res = backend_.GetRootMetadataReader();
403   if (!(res.ok() && res.value())) {
404     PW_LOG_ERROR("Failed to get on-device Root metadata");
405     return res.status();
406   }
407   // Seek to the beginning so that ConservativeReadLimit() returns the correct
408   // value.
409   PW_TRY(res.value()->Seek(0, stream::Stream::Whence::kBeginning));
410   return protobuf::Message(*res.value(), res.value()->ConservativeReadLimit());
411 }
412 
GetOnDeviceManifest()413 ManifestAccessor UpdateBundleAccessor::GetOnDeviceManifest() {
414   // Notify backend to check if an on-device manifest exists and is valid and if
415   // yes, prepare a ready-to-go reader.
416   PW_TRY(backend_.BeforeManifestRead());
417 
418   Result<stream::SeekableReader*> manifest_reader =
419       backend_.GetManifestReader();
420   PW_TRY(manifest_reader.status());
421   PW_CHECK_NOTNULL(manifest_reader.value());
422 
423   // In case `backend_.BeforeManifestRead()` forgot to reset the reader.
424   PW_TRY(manifest_reader.value()->Seek(0, stream::Stream::Whence::kBeginning));
425 
426   return ManifestAccessor::FromManifest(
427       protobuf::Message(*manifest_reader.value(),
428                         manifest_reader.value()->ConservativeReadLimit()));
429 }
430 
UpgradeRoot()431 Status UpdateBundleAccessor::UpgradeRoot() {
432   protobuf::Message new_root = bundle_.AsMessage(
433       static_cast<uint32_t>(UpdateBundle::Fields::ROOT_METADATA));
434 
435   // Try self-verification even if verification is disabled by the caller. This
436   // minimizes surprises when the caller do decide to turn on verification.
437   bool self_verifying = disable_verification_;
438 
439   // Choose and cache the root metadata to trust.
440   trusted_root_ = self_verifying ? new_root : GetOnDeviceTrustedRoot();
441 
442   if (!new_root.status().ok()) {
443     // Don't bother upgrading if not found or invalid.
444     PW_LOG_WARN("Incoming root metadata not found or invalid");
445     return OkStatus();
446   }
447 
448   // A valid trust anchor is required onwards from here.
449   PW_TRY(trusted_root_.status());
450 
451   // TODO(pwbug/456): Check whether the bundle contains a root metadata that
452   // is different from the on-device trusted root.
453 
454   // Verify the signatures against the trusted root metadata.
455   Result<bool> verify_res =
456       VerifyRootMetadataSignatures(trusted_root_, new_root);
457   if (!(verify_res.status().ok() && verify_res.value())) {
458     PW_LOG_ERROR("Failed to verify incoming root against the current root");
459     return Status::Unauthenticated();
460   }
461 
462   // TODO(pwbug/456): Verifiy the content of the new root metadata, including:
463   //    1) Check role magic field.
464   //    2) Check signature requirement. Specifically, check that no key is
465   //       reused across different roles and keys are unique in the same
466   //       requirement.
467   //    3) Check key mapping. Specifically, check that all keys are unique,
468   //       ECDSA keys, and the key ids are exactly the SHA256 of `key type +
469   //       key scheme + key value`.
470 
471   // Verify the signatures against the new root metadata.
472   verify_res = VerifyRootMetadataSignatures(new_root, new_root);
473   if (!(verify_res.status().ok() && verify_res.value())) {
474     PW_LOG_ERROR("Fail to verify incoming root against itself");
475     return Status::Unauthenticated();
476   }
477 
478   // TODO(pwbug/456): Check rollback.
479   // Retrieves the trusted root metadata content message.
480   protobuf::Message trusted_root_content =
481       trusted_root_.AsMessage(static_cast<uint32_t>(
482           SignedRootMetadata::Fields::SERIALIZED_ROOT_METADATA));
483   PW_TRY(trusted_root_content.status());
484   Result<uint32_t> trusted_root_version = GetMetadataVersion(
485       trusted_root_content,
486       static_cast<uint32_t>(RootMetadata::Fields::COMMON_METADATA));
487   PW_TRY(trusted_root_version.status());
488 
489   // Retrieves the serialized new root metadata message.
490   protobuf::Message new_root_content = new_root.AsMessage(static_cast<uint32_t>(
491       SignedRootMetadata::Fields::SERIALIZED_ROOT_METADATA));
492   PW_TRY(new_root_content.status());
493   Result<uint32_t> new_root_version = GetMetadataVersion(
494       new_root_content,
495       static_cast<uint32_t>(RootMetadata::Fields::COMMON_METADATA));
496   PW_TRY(new_root_version.status());
497 
498   if (trusted_root_version.value() > new_root_version.value()) {
499     PW_LOG_ERROR("Root attempts to rollback from %u to %u",
500                  trusted_root_version.value(),
501                  new_root_version.value());
502     return Status::Unauthenticated();
503   }
504 
505   if (!self_verifying) {
506     // Persist the root immediately after it is successfully verified. This is
507     // to make sure the trust anchor is up-to-date in storage as soon as
508     // we are confident. Although targets metadata and product-specific
509     // verification have not been done yet. They should be independent from and
510     // not gate the upgrade of root key. This allows timely revokation of
511     // compromise keys.
512     stream::IntervalReader new_root_reader =
513         new_root.ToBytes().GetBytesReader();
514     PW_TRY(backend_.SafelyPersistRootMetadata(new_root_reader));
515   }
516 
517   // TODO(pwbug/456): Implement key change detection to determine whether
518   // rotation has occured or not. Delete the persisted targets metadata version
519   // if any of the targets keys has been rotated.
520 
521   return OkStatus();
522 }
523 
VerifyTargetsMetadata()524 Status UpdateBundleAccessor::VerifyTargetsMetadata() {
525   bool self_verifying = disable_verification_;
526 
527   if (self_verifying && !trusted_root_.status().ok()) {
528     PW_LOG_WARN(
529         "Self-verification won't verify Targets metadata because there is no "
530         "root");
531     return OkStatus();
532   }
533 
534   // A valid trust anchor is required from now on.
535   PW_TRY(trusted_root_.status());
536 
537   // Retrieve the signed targets metadata map.
538   //
539   // message UpdateBundle {
540   //   ...
541   //   map<string, SignedTargetsMetadata> target_metadata = <id>;
542   //   ...
543   // }
544   protobuf::StringToMessageMap signed_targets_metadata_map =
545       bundle_.AsStringToMessageMap(
546           static_cast<uint32_t>(UpdateBundle::Fields::TARGETS_METADATA));
547   PW_TRY(signed_targets_metadata_map.status());
548 
549   // The top-level targets metadata is identified by key name "targets" in the
550   // map.
551   protobuf::Message signed_top_level_targets_metadata =
552       signed_targets_metadata_map[kTopLevelTargetsName];
553   PW_TRY(signed_top_level_targets_metadata.status());
554 
555   // Retrieve the serialized metadata.
556   //
557   // message SignedTargetsMetadata {
558   //   ...
559   //   bytes serialized_target_metadata = <id>;
560   //   ...
561   // }
562   protobuf::Message top_level_targets_metadata =
563       signed_top_level_targets_metadata.AsMessage(static_cast<uint32_t>(
564           SignedTargetsMetadata::Fields::SERIALIZED_TARGETS_METADATA));
565 
566   // Get the sigantures from the signed targets metadata.
567   protobuf::RepeatedMessages signatures =
568       signed_top_level_targets_metadata.AsRepeatedMessages(
569           static_cast<uint32_t>(SignedTargetsMetadata::Fields::SIGNATURES));
570   PW_TRY(signatures.status());
571 
572   // Retrieve the trusted root metadata message.
573   protobuf::Message trusted_root =
574       trusted_root_.AsMessage(static_cast<uint32_t>(
575           SignedRootMetadata::Fields::SERIALIZED_ROOT_METADATA));
576   PW_TRY(trusted_root.status());
577 
578   // Get the key_mapping from the trusted root metadata.
579   protobuf::StringToMessageMap key_mapping = trusted_root.AsStringToMessageMap(
580       static_cast<uint32_t>(RootMetadata::Fields::KEYS));
581   PW_TRY(key_mapping.status());
582 
583   // Get the targest metadtata siganture requirement from the trusted root.
584   protobuf::Message signature_requirement =
585       trusted_root.AsMessage(static_cast<uint32_t>(
586           RootMetadata::Fields::TARGETS_SIGNATURE_REQUIREMENT));
587   PW_TRY(signature_requirement.status());
588 
589   // Verify the sigantures
590   Status sig_res =
591       VerifyMetadataSignatures(top_level_targets_metadata.ToBytes(),
592                                signatures,
593                                signature_requirement,
594                                key_mapping);
595 
596   if (self_verifying && sig_res.IsNotFound()) {
597     PW_LOG_WARN("Self-verification ignoring unsigned bundle");
598     return OkStatus();
599   }
600 
601   if (!sig_res.ok()) {
602     PW_LOG_ERROR("Targets Metadata failed signature verification");
603     return Status::Unauthenticated();
604   }
605 
606   // TODO(pwbug/456): Check targets metadtata content.
607 
608   if (self_verifying) {
609     // Don't bother because it does not matter.
610     PW_LOG_WARN("Self verification does not do Targets metadata anti-rollback");
611     return OkStatus();
612   }
613 
614   // Anti-rollback check.
615   ManifestAccessor device_manifest = GetOnDeviceManifest();
616   if (device_manifest.status().IsNotFound()) {
617     PW_LOG_WARN("Skipping OTA anti-rollback due to absent device manifest");
618     return OkStatus();
619   }
620 
621   protobuf::Uint32 current_version = device_manifest.GetVersion();
622   PW_TRY(current_version.status());
623 
624   // Retrieves the version from the new metadata
625   Result<uint32_t> new_version = GetMetadataVersion(
626       top_level_targets_metadata,
627       static_cast<uint32_t>(
628           software_update::TargetsMetadata::Fields::COMMON_METADATA));
629   PW_TRY(new_version.status());
630   if (current_version.value() > new_version.value()) {
631     PW_LOG_ERROR("Blocking Targets metadata rollback from %u to %u",
632                  current_version.value(),
633                  new_version.value());
634     return Status::Unauthenticated();
635   }
636 
637   return OkStatus();
638 }
639 
VerifyTargetsPayloads()640 Status UpdateBundleAccessor::VerifyTargetsPayloads() {
641   ManifestAccessor bundle_manifest = ManifestAccessor::FromBundle(bundle_);
642   PW_TRY(bundle_manifest.status());
643 
644   // Target file descriptors (pathname, length, hash, etc.) listed in the bundle
645   // manifest.
646   protobuf::RepeatedMessages target_files = bundle_manifest.GetTargetFiles();
647   PW_TRY(target_files.status());
648 
649   // Verify length and SHA256 hash for each file listed in the manifest.
650   for (protobuf::Message target_file : target_files) {
651     // Extract target file name in the form of a `std::string_view`.
652     protobuf::String name_proto = target_file.AsString(
653         static_cast<uint32_t>(TargetFile::Fields::FILE_NAME));
654     PW_TRY(name_proto.status());
655     char name_buf[MAX_TARGET_NAME_LENGTH] = {0};
656     Result<std::string_view> target_name =
657         ReadProtoString(name_proto, name_buf);
658     PW_TRY(target_name.status());
659 
660     // Get target length.
661     protobuf::Uint64 target_length =
662         target_file.AsUint64(static_cast<uint32_t>(TargetFile::Fields::LENGTH));
663     PW_TRY(target_length.status());
664     if (target_length.value() > PW_SOFTWARE_UPDATE_MAX_TARGET_PAYLOAD_SIZE) {
665       PW_LOG_ERROR("Target payload too big. Maximum is %llu bytes",
666                    PW_SOFTWARE_UPDATE_MAX_TARGET_PAYLOAD_SIZE);
667       return Status::OutOfRange();
668     }
669 
670     // Get target SHA256 hash.
671     protobuf::Bytes target_sha256 = Status::NotFound();
672     protobuf::RepeatedMessages hashes = target_file.AsRepeatedMessages(
673         static_cast<uint32_t>(TargetFile::Fields::HASHES));
674     for (protobuf::Message hash : hashes) {
675       protobuf::Uint32 hash_function =
676           hash.AsUint32(static_cast<uint32_t>(Hash::Fields::FUNCTION));
677       PW_TRY(hash_function.status());
678 
679       if (hash_function.value() ==
680           static_cast<uint32_t>(HashFunction::SHA256)) {
681         target_sha256 = hash.AsBytes(static_cast<uint32_t>(Hash::Fields::HASH));
682         break;
683       }
684     }
685     PW_TRY(target_sha256.status());
686 
687     if (Status status = VerifyTargetPayload(
688             bundle_manifest, target_name.value(), target_length, target_sha256);
689         !status.ok()) {
690       PW_LOG_ERROR("Target: %s failed verification",
691                    pw::MakeString(target_name.value()).c_str());
692       return status;
693     }
694   }  // for each target file in manifest.
695 
696   return OkStatus();
697 }
698 
VerifyTargetPayload(ManifestAccessor manifest,std::string_view target_name,protobuf::Uint64 expected_length,protobuf::Bytes expected_sha256)699 Status UpdateBundleAccessor::VerifyTargetPayload(
700     ManifestAccessor manifest,
701     std::string_view target_name,
702     protobuf::Uint64 expected_length,
703     protobuf::Bytes expected_sha256) {
704   protobuf::StringToBytesMap payloads_map = bundle_.AsStringToBytesMap(
705       static_cast<uint32_t>(UpdateBundle::Fields::TARGET_PAYLOADS));
706   stream::IntervalReader payload_reader =
707       payloads_map[target_name].GetBytesReader();
708 
709   Status status;
710 
711   if (payload_reader.ok()) {
712     status = VerifyInBundleTargetPayload(
713         expected_length, expected_sha256, payload_reader);
714   } else {
715     status = VerifyOutOfBundleTargetPayload(
716         target_name, expected_length, expected_sha256);
717   }
718 
719   // TODO(alizhang): Notify backend to do additional checks by calling
720   // backend_.VerifyTargetFile(...).
721   return status;
722 }
723 
724 // TODO(alizhang): Add unit tests for all failure conditions.
VerifyOutOfBundleTargetPayload(std::string_view target_name,protobuf::Uint64 expected_length,protobuf::Bytes expected_sha256)725 Status UpdateBundleAccessor::VerifyOutOfBundleTargetPayload(
726     std::string_view target_name,
727     protobuf::Uint64 expected_length,
728     protobuf::Bytes expected_sha256) {
729 #if PW_SOFTWARE_UPDATE_WITH_PERSONALIZATION
730   // The target payload is "personalized out". We we can't take a measurement
731   // without backend help. For now we will check against the device manifest
732   // which contains a cached measurement of the last software update.
733   ManifestAccessor device_manifest = GetOnDeviceManifest();
734   if (!device_manifest.ok()) {
735     PW_LOG_ERROR(
736         "Can't verify personalized-out target because on-device manifest is "
737         "not found");
738     return Status::Unauthenticated();
739   }
740 
741   protobuf::Message cached = device_manifest.GetTargetFile(target_name);
742   if (!cached.ok()) {
743     PW_LOG_ERROR(
744         "Can't verify personalized-out target because it is not found from "
745         "on-device manifest");
746     return Status::Unauthenticated();
747   }
748 
749   protobuf::Uint64 cached_length =
750       cached.AsUint64(static_cast<uint32_t>(TargetFile::Fields::LENGTH));
751   PW_TRY(cached_length.status());
752   if (cached_length.value() != expected_length.value()) {
753     PW_LOG_ERROR("Personalized-out target has bad length: %llu, expected: %llu",
754                  cached_length.value(),
755                  expected_length.value());
756     return Status::Unauthenticated();
757   }
758 
759   protobuf::Bytes cached_sha256 = Status::NotFound();
760   protobuf::RepeatedMessages hashes = cached.AsRepeatedMessages(
761       static_cast<uint32_t>(TargetFile::Fields::HASHES));
762   for (protobuf::Message hash : hashes) {
763     protobuf::Uint32 hash_function =
764         hash.AsUint32(static_cast<uint32_t>(Hash::Fields::FUNCTION));
765     PW_TRY(hash_function.status());
766 
767     if (hash_function.value() == static_cast<uint32_t>(HashFunction::SHA256)) {
768       cached_sha256 = hash.AsBytes(static_cast<uint32_t>(Hash::Fields::HASH));
769       break;
770     }
771   }
772   std::byte sha256[crypto::sha256::kDigestSizeBytes] = {};
773   PW_TRY(cached_sha256.GetBytesReader().Read(sha256));
774 
775   Result<bool> hash_equal = expected_sha256.Equal(sha256);
776   PW_TRY(hash_equal.status());
777   if (!hash_equal.value()) {
778     PW_LOG_ERROR("Personalized-out target has a bad hash");
779     return Status::Unauthenticated();
780   }
781 
782   return OkStatus();
783 #else
784   PW_LOG_ERROR("Target file %s not found in bundle", target_name);
785   return Status::Unauthenticated();
786 #endif  // PW_SOFTWARE_UPDATE_WITH_PERSONALIZATION
787 }
788 
VerifyInBundleTargetPayload(protobuf::Uint64 expected_length,protobuf::Bytes expected_sha256,stream::IntervalReader payload_reader)789 Status UpdateBundleAccessor::VerifyInBundleTargetPayload(
790     protobuf::Uint64 expected_length,
791     protobuf::Bytes expected_sha256,
792     stream::IntervalReader payload_reader) {
793   // If the target payload is included in the bundle, simply take a
794   // measurement.
795   uint64_t actual_length = payload_reader.interval_size();
796   if (actual_length != expected_length.value()) {
797     PW_LOG_ERROR("Wrong payload length. Expected: %llu, actual: %llu",
798                  expected_length.value(),
799                  actual_length);
800     return Status::Unauthenticated();
801   }
802 
803   std::byte actual_sha256[crypto::sha256::kDigestSizeBytes] = {};
804   PW_TRY(crypto::sha256::Hash(payload_reader, actual_sha256));
805   Result<bool> hash_equal = expected_sha256.Equal(actual_sha256);
806   PW_TRY(hash_equal.status());
807   if (!hash_equal.value()) {
808     PW_LOG_ERROR("Wrong payload sha256 hash");
809     return Status::Unauthenticated();
810   }
811 
812   return OkStatus();
813 }
814 
GetManifest()815 ManifestAccessor UpdateBundleAccessor::GetManifest() {
816   if (!bundle_verified_) {
817     PW_LOG_DEBUG("Bundled has not passed verification yet");
818     return Status::FailedPrecondition();
819   }
820 
821   return ManifestAccessor::FromBundle(bundle_);
822 }
823 
824 }  // namespace pw::software_update
825