• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 // Copyright (C) 2010 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_
18 #define UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_
19 
20 #include <inttypes.h>
21 
22 #include <string>
23 #include <vector>
24 
25 #include <base/time/time.h>
26 #include <brillo/secure_blob.h>
27 #include <google/protobuf/repeated_field.h>
28 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
29 
30 #include "update_engine/common/hash_calculator.h"
31 #include "update_engine/common/platform_constants.h"
32 #include "update_engine/payload_consumer/file_descriptor.h"
33 #include "update_engine/payload_consumer/file_writer.h"
34 #include "update_engine/payload_consumer/install_plan.h"
35 #include "update_engine/update_metadata.pb.h"
36 
37 namespace chromeos_update_engine {
38 
39 class DownloadActionDelegate;
40 class BootControlInterface;
41 class HardwareInterface;
42 class PrefsInterface;
43 
44 // This class performs the actions in a delta update synchronously. The delta
45 // update itself should be passed in in chunks as it is received.
46 
47 class DeltaPerformer : public FileWriter {
48  public:
49   enum MetadataParseResult {
50     kMetadataParseSuccess,
51     kMetadataParseError,
52     kMetadataParseInsufficientData,
53   };
54 
55   static const uint64_t kDeltaVersionOffset;
56   static const uint64_t kDeltaVersionSize;
57   static const uint64_t kDeltaManifestSizeOffset;
58   static const uint64_t kDeltaManifestSizeSize;
59   static const uint64_t kDeltaMetadataSignatureSizeSize;
60   static const uint64_t kMaxPayloadHeaderSize;
61   static const uint64_t kSupportedMajorPayloadVersion;
62   static const uint32_t kSupportedMinorPayloadVersion;
63 
64   // Defines the granularity of progress logging in terms of how many "completed
65   // chunks" we want to report at the most.
66   static const unsigned kProgressLogMaxChunks;
67   // Defines a timeout since the last progress was logged after which we want to
68   // force another log message (even if the current chunk was not completed).
69   static const unsigned kProgressLogTimeoutSeconds;
70   // These define the relative weights (0-100) we give to the different work
71   // components associated with an update when computing an overall progress.
72   // Currently they include the download progress and the number of completed
73   // operations. They must add up to one hundred (100).
74   static const unsigned kProgressDownloadWeight;
75   static const unsigned kProgressOperationsWeight;
76 
DeltaPerformer(PrefsInterface * prefs,BootControlInterface * boot_control,HardwareInterface * hardware,DownloadActionDelegate * download_delegate,InstallPlan * install_plan,InstallPlan::Payload * payload)77   DeltaPerformer(PrefsInterface* prefs,
78                  BootControlInterface* boot_control,
79                  HardwareInterface* hardware,
80                  DownloadActionDelegate* download_delegate,
81                  InstallPlan* install_plan,
82                  InstallPlan::Payload* payload)
83       : prefs_(prefs),
84         boot_control_(boot_control),
85         hardware_(hardware),
86         download_delegate_(download_delegate),
87         install_plan_(install_plan),
88         payload_(payload) {}
89 
90   // FileWriter's Write implementation where caller doesn't care about
91   // error codes.
Write(const void * bytes,size_t count)92   bool Write(const void* bytes, size_t count) override {
93     ErrorCode error;
94     return Write(bytes, count, &error);
95   }
96 
97   // FileWriter's Write implementation that returns a more specific |error| code
98   // in case of failures in Write operation.
99   bool Write(const void* bytes, size_t count, ErrorCode *error) override;
100 
101   // Wrapper around close. Returns 0 on success or -errno on error.
102   // Closes both 'path' given to Open() and the kernel path.
103   int Close() override;
104 
105   // Open the target and source (if delta payload) file descriptors for the
106   // |current_partition_|. The manifest needs to be already parsed for this to
107   // work. Returns whether the required file descriptors were successfully open.
108   bool OpenCurrentPartition();
109 
110   // Closes the current partition file descriptors if open. Returns 0 on success
111   // or -errno on error.
112   int CloseCurrentPartition();
113 
114   // Returns |true| only if the manifest has been processed and it's valid.
115   bool IsManifestValid();
116 
117   // Verifies the downloaded payload against the signed hash included in the
118   // payload, against the update check hash and size using the public key and
119   // returns ErrorCode::kSuccess on success, an error code on failure.
120   // This method should be called after closing the stream. Note this method
121   // skips the signed hash check if the public key is unavailable; it returns
122   // ErrorCode::kSignedDeltaPayloadExpectedError if the public key is available
123   // but the delta payload doesn't include a signature.
124   ErrorCode VerifyPayload(const brillo::Blob& update_check_response_hash,
125                           const uint64_t update_check_response_size);
126 
127   // Converts an ordered collection of Extent objects which contain data of
128   // length full_length to a comma-separated string. For each Extent, the
129   // string will have the start offset and then the length in bytes.
130   // The length value of the last extent in the string may be short, since
131   // the full length of all extents in the string is capped to full_length.
132   // Also, an extent starting at kSparseHole, appears as -1 in the string.
133   // For example, if the Extents are {1, 1}, {4, 2}, {kSparseHole, 1},
134   // {0, 1}, block_size is 4096, and full_length is 5 * block_size - 13,
135   // the resulting string will be: "4096:4096,16384:8192,-1:4096,0:4083"
136   static bool ExtentsToBsdiffPositionsString(
137       const google::protobuf::RepeatedPtrField<Extent>& extents,
138       uint64_t block_size,
139       uint64_t full_length,
140       std::string* positions_string);
141 
142   // Returns true if a previous update attempt can be continued based on the
143   // persistent preferences and the new update check response hash.
144   static bool CanResumeUpdate(PrefsInterface* prefs,
145                               const std::string& update_check_response_hash);
146 
147   // Resets the persistent update progress state to indicate that an update
148   // can't be resumed. Performs a quick update-in-progress reset if |quick| is
149   // true, otherwise resets all progress-related update state. Returns true on
150   // success, false otherwise.
151   static bool ResetUpdateProgress(PrefsInterface* prefs, bool quick);
152 
153   // Attempts to parse the update metadata starting from the beginning of
154   // |payload|. On success, returns kMetadataParseSuccess. Returns
155   // kMetadataParseInsufficientData if more data is needed to parse the complete
156   // metadata. Returns kMetadataParseError if the metadata can't be parsed given
157   // the payload.
158   MetadataParseResult ParsePayloadMetadata(const brillo::Blob& payload,
159                                            ErrorCode* error);
160 
set_public_key_path(const std::string & public_key_path)161   void set_public_key_path(const std::string& public_key_path) {
162     public_key_path_ = public_key_path;
163   }
164 
165   // Set |*out_offset| to the byte offset where the size of the metadata signature
166   // is stored in a payload. Return true on success, if this field is not
167   // present in the payload, return false.
168   bool GetMetadataSignatureSizeOffset(uint64_t* out_offset) const;
169 
170   // Set |*out_offset| to the byte offset at which the manifest protobuf begins
171   // in a payload. Return true on success, false if the offset is unknown.
172   bool GetManifestOffset(uint64_t* out_offset) const;
173 
174   // Returns the size of the payload metadata, which includes the payload header
175   // and the manifest. If the header was not yet parsed, returns zero.
176   uint64_t GetMetadataSize() const;
177 
178   // If the manifest was successfully parsed, copies it to |*out_manifest_p|.
179   // Returns true on success.
180   bool GetManifest(DeltaArchiveManifest* out_manifest_p) const;
181 
182   // Return true if header parsing is finished and no errors occurred.
183   bool IsHeaderParsed() const;
184 
185   // Returns the major payload version. If the version was not yet parsed,
186   // returns zero.
187   uint64_t GetMajorVersion() const;
188 
189   // Returns the delta minor version. If this value is defined in the manifest,
190   // it returns that value, otherwise it returns the default value.
191   uint32_t GetMinorVersion() const;
192 
193  private:
194   friend class DeltaPerformerTest;
195   friend class DeltaPerformerIntegrationTest;
196   FRIEND_TEST(DeltaPerformerTest, BrilloMetadataSignatureSizeTest);
197   FRIEND_TEST(DeltaPerformerTest, BrilloVerifyMetadataSignatureTest);
198   FRIEND_TEST(DeltaPerformerTest, UsePublicKeyFromResponse);
199 
200   // Parse and move the update instructions of all partitions into our local
201   // |partitions_| variable based on the version of the payload. Requires the
202   // manifest to be parsed and valid.
203   bool ParseManifestPartitions(ErrorCode* error);
204 
205   // Appends up to |*count_p| bytes from |*bytes_p| to |buffer_|, but only to
206   // the extent that the size of |buffer_| does not exceed |max|. Advances
207   // |*cbytes_p| and decreases |*count_p| by the actual number of bytes copied,
208   // and returns this number.
209   size_t CopyDataToBuffer(const char** bytes_p, size_t* count_p, size_t max);
210 
211   // If |op_result| is false, emits an error message using |op_type_name| and
212   // sets |*error| accordingly. Otherwise does nothing. Returns |op_result|.
213   bool HandleOpResult(bool op_result, const char* op_type_name,
214                       ErrorCode* error);
215 
216   // Logs the progress of downloading/applying an update.
217   void LogProgress(const char* message_prefix);
218 
219   // Update overall progress metrics, log as necessary.
220   void UpdateOverallProgress(bool force_log, const char* message_prefix);
221 
222   // Returns true if enough of the delta file has been passed via Write()
223   // to be able to perform a given install operation.
224   bool CanPerformInstallOperation(const InstallOperation& operation);
225 
226   // Checks the integrity of the payload manifest. Returns true upon success,
227   // false otherwise.
228   ErrorCode ValidateManifest();
229 
230   // Validates that the hash of the blobs corresponding to the given |operation|
231   // matches what's specified in the manifest in the payload.
232   // Returns ErrorCode::kSuccess on match or a suitable error code otherwise.
233   ErrorCode ValidateOperationHash(const InstallOperation& operation);
234 
235   // Given the |payload|, verifies that the signed hash of its metadata matches
236   // what's specified in the install plan from Omaha (if present) or the
237   // metadata signature in payload itself (if present). Returns
238   // ErrorCode::kSuccess on match or a suitable error code otherwise. This
239   // method must be called before any part of the metadata is parsed so that a
240   // man-in-the-middle attack on the SSL connection to the payload server
241   // doesn't exploit any vulnerability in the code that parses the protocol
242   // buffer.
243   ErrorCode ValidateMetadataSignature(const brillo::Blob& payload);
244 
245   // Returns true on success.
246   bool PerformInstallOperation(const InstallOperation& operation);
247 
248   // These perform a specific type of operation and return true on success.
249   // |error| will be set if source hash mismatch, otherwise |error| might not be
250   // set even if it fails.
251   bool PerformReplaceOperation(const InstallOperation& operation);
252   bool PerformZeroOrDiscardOperation(const InstallOperation& operation);
253   bool PerformMoveOperation(const InstallOperation& operation);
254   bool PerformBsdiffOperation(const InstallOperation& operation);
255   bool PerformSourceCopyOperation(const InstallOperation& operation,
256                                   ErrorCode* error);
257   bool PerformSourceBsdiffOperation(const InstallOperation& operation,
258                                     ErrorCode* error);
259 
260   // Extracts the payload signature message from the blob on the |operation| if
261   // the offset matches the one specified by the manifest. Returns whether the
262   // signature was extracted.
263   bool ExtractSignatureMessageFromOperation(const InstallOperation& operation);
264 
265   // Extracts the payload signature message from the current |buffer_| if the
266   // offset matches the one specified by the manifest. Returns whether the
267   // signature was extracted.
268   bool ExtractSignatureMessage();
269 
270   // Updates the payload hash calculator with the bytes in |buffer_|, also
271   // updates the signed hash calculator with the first |signed_hash_buffer_size|
272   // bytes in |buffer_|. Then discard the content, ensuring that memory is being
273   // deallocated. If |do_advance_offset|, advances the internal offset counter
274   // accordingly.
275   void DiscardBuffer(bool do_advance_offset, size_t signed_hash_buffer_size);
276 
277   // Checkpoints the update progress into persistent storage to allow this
278   // update attempt to be resumed after reboot.
279   bool CheckpointUpdateProgress();
280 
281   // Primes the required update state. Returns true if the update state was
282   // successfully initialized to a saved resume state or if the update is a new
283   // update. Returns false otherwise.
284   bool PrimeUpdateState();
285 
286   // If the Omaha response contains a public RSA key and we're allowed
287   // to use it (e.g. if we're in developer mode), extract the key from
288   // the response and store it in a temporary file and return true. In
289   // the affirmative the path to the temporary file is stored in
290   // |out_tmp_key| and it is the responsibility of the caller to clean
291   // it up.
292   bool GetPublicKeyFromResponse(base::FilePath *out_tmp_key);
293 
294   // Update Engine preference store.
295   PrefsInterface* prefs_;
296 
297   // BootControl and Hardware interface references.
298   BootControlInterface* boot_control_;
299   HardwareInterface* hardware_;
300 
301   // The DownloadActionDelegate instance monitoring the DownloadAction, or a
302   // nullptr if not used.
303   DownloadActionDelegate* download_delegate_;
304 
305   // Install Plan based on Omaha Response.
306   InstallPlan* install_plan_;
307 
308   // Pointer to the current payload in install_plan_.payloads.
309   InstallPlan::Payload* payload_{nullptr};
310 
311   // File descriptor of the source partition. Only set while updating a
312   // partition when using a delta payload.
313   FileDescriptorPtr source_fd_{nullptr};
314 
315   // File descriptor of the target partition. Only set while performing the
316   // operations of a given partition.
317   FileDescriptorPtr target_fd_{nullptr};
318 
319   // Paths the |source_fd_| and |target_fd_| refer to.
320   std::string source_path_;
321   std::string target_path_;
322 
323   // Parsed manifest. Set after enough bytes to parse the manifest were
324   // downloaded.
325   DeltaArchiveManifest manifest_;
326   bool manifest_parsed_{false};
327   bool manifest_valid_{false};
328   uint64_t metadata_size_{0};
329   uint64_t manifest_size_{0};
330   uint32_t metadata_signature_size_{0};
331   uint64_t major_payload_version_{0};
332 
333   // Accumulated number of operations per partition. The i-th element is the
334   // sum of the number of operations for all the partitions from 0 to i
335   // inclusive. Valid when |manifest_valid_| is true.
336   std::vector<size_t> acc_num_operations_;
337 
338   // The total operations in a payload. Valid when |manifest_valid_| is true,
339   // otherwise 0.
340   size_t num_total_operations_{0};
341 
342   // The list of partitions to update as found in the manifest major version 2.
343   // When parsing an older manifest format, the information is converted over to
344   // this format instead.
345   std::vector<PartitionUpdate> partitions_;
346 
347   // Index in the list of partitions (|partitions_| member) of the current
348   // partition being processed.
349   size_t current_partition_{0};
350 
351   // Index of the next operation to perform in the manifest. The index is linear
352   // on the total number of operation on the manifest.
353   size_t next_operation_num_{0};
354 
355   // A buffer used for accumulating downloaded data. Initially, it stores the
356   // payload metadata; once that's downloaded and parsed, it stores data for the
357   // next update operation.
358   brillo::Blob buffer_;
359   // Offset of buffer_ in the binary blobs section of the update.
360   uint64_t buffer_offset_{0};
361 
362   // Last |buffer_offset_| value updated as part of the progress update.
363   uint64_t last_updated_buffer_offset_{std::numeric_limits<uint64_t>::max()};
364 
365   // The block size (parsed from the manifest).
366   uint32_t block_size_{0};
367 
368   // Calculates the whole payload file hash, including headers and signatures.
369   HashCalculator payload_hash_calculator_;
370 
371   // Calculates the hash of the portion of the payload signed by the payload
372   // signature. This hash skips the metadata signature portion, located after
373   // the metadata and doesn't include the payload signature itself.
374   HashCalculator signed_hash_calculator_;
375 
376   // Signatures message blob extracted directly from the payload.
377   brillo::Blob signatures_message_data_;
378 
379   // The public key to be used. Provided as a member so that tests can
380   // override with test keys.
381   std::string public_key_path_{constants::kUpdatePayloadPublicKeyPath};
382 
383   // The number of bytes received so far, used for progress tracking.
384   size_t total_bytes_received_{0};
385 
386   // An overall progress counter, which should reflect both download progress
387   // and the ratio of applied operations. Range is 0-100.
388   unsigned overall_progress_{0};
389 
390   // The last progress chunk recorded.
391   unsigned last_progress_chunk_{0};
392 
393   // The timeout after which we should force emitting a progress log (constant),
394   // and the actual point in time for the next forced log to be emitted.
395   const base::TimeDelta forced_progress_log_wait_{
396       base::TimeDelta::FromSeconds(kProgressLogTimeoutSeconds)};
397   base::Time forced_progress_log_time_;
398 
399   // The payload major payload version supported by DeltaPerformer.
400   uint64_t supported_major_version_{kSupportedMajorPayloadVersion};
401 
402   // The delta minor payload version supported by DeltaPerformer.
403   uint32_t supported_minor_version_{kSupportedMinorPayloadVersion};
404 
405   DISALLOW_COPY_AND_ASSIGN(DeltaPerformer);
406 };
407 
408 }  // namespace chromeos_update_engine
409 
410 #endif  // UPDATE_ENGINE_PAYLOAD_CONSUMER_DELTA_PERFORMER_H_
411