1 //
2 // Copyright (C) 2011 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 #include "update_engine/cros/omaha_response_handler_action.h"
18 
19 #include <limits>
20 #include <string>
21 
22 #include <base/logging.h>
23 #include <base/strings/string_number_conversions.h>
24 #include <base/version.h>
25 #include <policy/device_policy.h>
26 
27 #include "update_engine/common/constants.h"
28 #include "update_engine/common/hardware_interface.h"
29 #include "update_engine/common/prefs_interface.h"
30 #include "update_engine/common/system_state.h"
31 #include "update_engine/common/utils.h"
32 #include "update_engine/cros/connection_manager_interface.h"
33 #include "update_engine/cros/omaha_request_params.h"
34 #include "update_engine/cros/payload_state_interface.h"
35 #include "update_engine/payload_consumer/delta_performer.h"
36 #include "update_engine/update_manager/policy.h"
37 #include "update_engine/update_manager/update_manager.h"
38 
39 using chromeos_update_manager::kRollforwardInfinity;
40 using chromeos_update_manager::Policy;
41 using chromeos_update_manager::UpdateManager;
42 using std::numeric_limits;
43 using std::string;
44 
45 namespace chromeos_update_engine {
46 
OmahaResponseHandlerAction()47 OmahaResponseHandlerAction::OmahaResponseHandlerAction()
48     : deadline_file_(constants::kOmahaResponseDeadlineFile) {}
49 
PerformAction()50 void OmahaResponseHandlerAction::PerformAction() {
51   CHECK(HasInputObject());
52   ScopedActionCompleter completer(processor_, this);
53   const OmahaResponse& response = GetInputObject();
54   if (!response.update_exists) {
55     LOG(INFO) << "There are no updates. Aborting.";
56     completer.set_code(ErrorCode::kNoUpdate);
57     return;
58   }
59 
60   // All decisions as to which URL should be used have already been done. So,
61   // make the current URL as the download URL.
62   string current_url = SystemState::Get()->payload_state()->GetCurrentUrl();
63   if (current_url.empty()) {
64     // This shouldn't happen as we should always supply the HTTPS backup URL.
65     // Handling this anyway, just in case.
66     LOG(ERROR) << "There are no suitable URLs in the response to use.";
67     completer.set_code(ErrorCode::kOmahaResponseInvalid);
68     return;
69   }
70 
71   // This is the url to the first package, not all packages.
72   // (For updates): All |Action|s prior to this must pass in non-excluded URLs
73   // within the |OmahaResponse|, reference exlusion logic in
74   // |OmahaRequestAction| and keep the enforcement of exclusions for updates.
75   install_plan_.download_url = current_url;
76   install_plan_.version = response.version;
77 
78   OmahaRequestParams* const params = SystemState::Get()->request_params();
79   PayloadStateInterface* const payload_state =
80       SystemState::Get()->payload_state();
81 
82   // If we're using p2p to download and there is a local peer, use it.
83   if (payload_state->GetUsingP2PForDownloading() &&
84       !payload_state->GetP2PUrl().empty()) {
85     LOG(INFO) << "Replacing URL " << install_plan_.download_url
86               << " with local URL " << payload_state->GetP2PUrl()
87               << " since p2p is enabled.";
88     install_plan_.download_url = payload_state->GetP2PUrl();
89     payload_state->SetUsingP2PForDownloading(true);
90   }
91 
92   // Fill up the other properties based on the response.
93   string update_check_response_hash;
94   for (const auto& package : response.packages) {
95     brillo::Blob raw_hash;
96     if (!base::HexStringToBytes(package.hash, &raw_hash)) {
97       LOG(ERROR) << "Failed to convert payload hash from hex string to bytes: "
98                  << package.hash;
99       completer.set_code(ErrorCode::kOmahaResponseInvalid);
100       return;
101     }
102     install_plan_.payloads.push_back(
103         {.payload_urls = package.payload_urls,
104          .size = package.size,
105          .metadata_size = package.metadata_size,
106          .metadata_signature = package.metadata_signature,
107          .hash = raw_hash,
108          .type = package.is_delta ? InstallPayloadType::kDelta
109                                   : InstallPayloadType::kFull,
110          .fp = package.fp,
111          .app_id = package.app_id});
112     update_check_response_hash += package.hash + ":";
113   }
114   install_plan_.public_key_rsa = response.public_key_rsa;
115   install_plan_.hash_checks_mandatory = AreHashChecksMandatory(response);
116   install_plan_.is_resume = DeltaPerformer::CanResumeUpdate(
117       SystemState::Get()->prefs(), update_check_response_hash);
118   if (install_plan_.is_resume) {
119     payload_state->UpdateResumed();
120   } else {
121     payload_state->UpdateRestarted();
122     LOG_IF(WARNING,
123            !DeltaPerformer::ResetUpdateProgress(SystemState::Get()->prefs(),
124                                                 false))
125         << "Unable to reset the update progress.";
126     LOG_IF(WARNING,
127            !SystemState::Get()->prefs()->SetString(
128                kPrefsUpdateCheckResponseHash, update_check_response_hash))
129         << "Unable to save the update check response hash.";
130   }
131 
132   if (params->is_install()) {
133     install_plan_.target_slot =
134         SystemState::Get()->boot_control()->GetCurrentSlot();
135     install_plan_.source_slot = BootControlInterface::kInvalidSlot;
136   } else {
137     install_plan_.source_slot =
138         SystemState::Get()->boot_control()->GetCurrentSlot();
139     install_plan_.target_slot = install_plan_.source_slot == 0 ? 1 : 0;
140   }
141 
142   // The Omaha response doesn't include the channel name for this image, so we
143   // use the download_channel we used during the request to tag the target slot.
144   // This will be used in the next boot to know the channel the image was
145   // downloaded from.
146   string current_channel_key =
147       kPrefsChannelOnSlotPrefix + std::to_string(install_plan_.target_slot);
148   SystemState::Get()->prefs()->SetString(current_channel_key,
149                                          params->download_channel());
150 
151   // Checking whether device is able to boot up the returned rollback image.
152   if (response.is_rollback) {
153     if (!params->rollback_allowed()) {
154       LOG(ERROR) << "Received rollback image but rollback is not allowed.";
155       completer.set_code(ErrorCode::kOmahaResponseInvalid);
156       return;
157     }
158 
159     // Calculate the values on the version values on current device.
160     auto min_kernel_key_version = static_cast<uint32_t>(
161         SystemState::Get()->hardware()->GetMinKernelKeyVersion());
162     auto min_firmware_key_version = static_cast<uint32_t>(
163         SystemState::Get()->hardware()->GetMinFirmwareKeyVersion());
164 
165     uint32_t kernel_key_version =
166         static_cast<uint32_t>(response.rollback_key_version.kernel_key) << 16 |
167         static_cast<uint32_t>(response.rollback_key_version.kernel);
168     uint32_t firmware_key_version =
169         static_cast<uint32_t>(response.rollback_key_version.firmware_key)
170             << 16 |
171         static_cast<uint32_t>(response.rollback_key_version.firmware);
172 
173     LOG(INFO) << "Rollback image versions:"
174               << " device_kernel_key_version=" << min_kernel_key_version
175               << " image_kernel_key_version=" << kernel_key_version
176               << " device_firmware_key_version=" << min_firmware_key_version
177               << " image_firmware_key_version=" << firmware_key_version;
178 
179     // Don't attempt a rollback if the versions are incompatible or the
180     // target image does not specify the version information.
181     if (kernel_key_version == numeric_limits<uint32_t>::max() ||
182         firmware_key_version == numeric_limits<uint32_t>::max() ||
183         kernel_key_version < min_kernel_key_version ||
184         firmware_key_version < min_firmware_key_version) {
185       LOG(ERROR) << "Device won't be able to boot up the rollback image.";
186       completer.set_code(ErrorCode::kRollbackNotPossible);
187       return;
188     }
189     install_plan_.is_rollback = true;
190     install_plan_.rollback_data_save_requested =
191         params->rollback_data_save_requested();
192   }
193 
194   // Powerwash if either the response requires it or the parameters indicated
195   // powerwash (usually because there was a channel downgrade) and we are
196   // downgrading the version. Enterprise rollback, indicated by
197   // |response.is_rollback| is dealt with separately above.
198   if (response.powerwash_required) {
199     install_plan_.powerwash_required = true;
200   } else if (params->ShouldPowerwash() && !response.is_rollback) {
201     base::Version new_version(response.version);
202     base::Version current_version(params->app_version());
203 
204     if (!new_version.IsValid()) {
205       LOG(WARNING) << "Not powerwashing,"
206                    << " the update's version number is unreadable."
207                    << " Update's version number: " << response.version;
208     } else if (!current_version.IsValid()) {
209       LOG(WARNING) << "Not powerwashing,"
210                    << " the current version number is unreadable."
211                    << " Current version number: " << params->app_version();
212     } else if (new_version < current_version) {
213       install_plan_.powerwash_required = true;
214       // Always try to preserve enrollment and wifi data for enrolled devices.
215       install_plan_.rollback_data_save_requested =
216           SystemState::Get()->device_policy() &&
217           SystemState::Get()->device_policy()->IsEnterpriseEnrolled();
218     }
219   }
220 
221   TEST_AND_RETURN(HasOutputPipe());
222   if (HasOutputPipe())
223     SetOutputObject(install_plan_);
224   install_plan_.Dump();
225 
226   // Send the deadline data (if any) to Chrome through a file. This is a pretty
227   // hacky solution but should be OK for now.
228   //
229   // TODO(petkov): Re-architect this to avoid communication through a
230   // file. Ideally, we would include this information in D-Bus's GetStatus
231   // method and UpdateStatus signal. A potential issue is that update_engine may
232   // be unresponsive during an update download.
233   if (!deadline_file_.empty()) {
234     if (payload_state->GetRollbackHappened()) {
235       // Don't do forced update if rollback has happened since the last update
236       // check where policy was present.
237       LOG(INFO) << "Not forcing update because a rollback happened.";
238       utils::WriteFile(deadline_file_.c_str(), nullptr, 0);
239     } else {
240       utils::WriteFile(deadline_file_.c_str(),
241                        response.deadline.data(),
242                        response.deadline.size());
243     }
244     chmod(deadline_file_.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
245   }
246 
247   // Check the generated install-plan with the Policy to confirm that
248   // it can be applied at this time (or at all).
249   UpdateManager* const update_manager = SystemState::Get()->update_manager();
250   CHECK(update_manager);
251   auto ec = ErrorCode::kSuccess;
252   update_manager->PolicyRequest(
253       &Policy::UpdateCanBeApplied, &ec, &install_plan_);
254   completer.set_code(ec);
255 
256   const auto allowed_milestones = params->rollback_allowed_milestones();
257   if (allowed_milestones > 0) {
258     auto max_firmware_rollforward = numeric_limits<uint32_t>::max();
259     auto max_kernel_rollforward = numeric_limits<uint32_t>::max();
260 
261     // Determine the version to update the max rollforward verified boot
262     // value.
263     OmahaResponse::RollbackKeyVersion version =
264         response.past_rollback_key_version;
265 
266     // Determine the max rollforward values to be set in the TPM.
267     max_firmware_rollforward = static_cast<uint32_t>(version.firmware_key)
268                                    << 16 |
269                                static_cast<uint32_t>(version.firmware);
270     max_kernel_rollforward = static_cast<uint32_t>(version.kernel_key) << 16 |
271                              static_cast<uint32_t>(version.kernel);
272 
273     // In the case that the value is 0xffffffff, log a warning because the
274     // device should not be installing a rollback image without having version
275     // information.
276     if (max_firmware_rollforward == numeric_limits<uint32_t>::max() ||
277         max_kernel_rollforward == numeric_limits<uint32_t>::max()) {
278       LOG(WARNING)
279           << "Max rollforward values were not sent in rollback response: "
280           << " max_kernel_rollforward=" << max_kernel_rollforward
281           << " max_firmware_rollforward=" << max_firmware_rollforward
282           << " rollback_allowed_milestones="
283           << params->rollback_allowed_milestones();
284     } else {
285       LOG(INFO) << "Setting the max rollforward values: "
286                 << " max_kernel_rollforward=" << max_kernel_rollforward
287                 << " max_firmware_rollforward=" << max_firmware_rollforward
288                 << " rollback_allowed_milestones="
289                 << params->rollback_allowed_milestones();
290       SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
291           max_kernel_rollforward);
292       // TODO(crbug/783998): Set max firmware rollforward when implemented.
293     }
294   } else {
295     LOG(INFO) << "Rollback is not allowed. Setting max rollforward values"
296               << " to infinity";
297     // When rollback is not allowed, explicitly set the max roll forward to
298     // infinity.
299     SystemState::Get()->hardware()->SetMaxKernelKeyRollforward(
300         kRollforwardInfinity);
301     // TODO(crbug/783998): Set max firmware rollforward when implemented.
302   }
303 }
304 
AreHashChecksMandatory(const OmahaResponse & response)305 bool OmahaResponseHandlerAction::AreHashChecksMandatory(
306     const OmahaResponse& response) {
307   // We sometimes need to waive the hash checks in order to download from
308   // sources that don't provide hashes, such as dev server.
309   // At this point UpdateAttempter::IsAnyUpdateSourceAllowed() has already been
310   // checked, so an unofficial update URL won't get this far unless it's OK to
311   // use without a hash. Additionally, we want to always waive hash checks on
312   // unofficial builds (i.e. dev/test images).
313   // The end result is this:
314   //  * Base image:
315   //    - Official URLs require a hash.
316   //    - Unofficial URLs only get this far if the IsAnyUpdateSourceAllowed()
317   //      devmode/debugd checks pass, in which case the hash is waived.
318   //  * Dev/test image:
319   //    - Any URL is allowed through with no hash checking.
320   if (!SystemState::Get()->request_params()->IsUpdateUrlOfficial() ||
321       !SystemState::Get()->hardware()->IsOfficialBuild()) {
322     // Still do a hash check if a public key is included.
323     if (!response.public_key_rsa.empty()) {
324       // The autoupdate_CatchBadSignatures test checks for this string
325       // in log-files. Keep in sync.
326       LOG(INFO) << "Mandating payload hash checks since Omaha Response "
327                 << "for unofficial build includes public RSA key.";
328       return true;
329     } else {
330       LOG(INFO) << "Waiving payload hash checks for unofficial update URL.";
331       return false;
332     }
333   }
334 
335   LOG(INFO) << "Mandating hash checks for official URL on official build.";
336   return true;
337 }
338 
339 }  // namespace chromeos_update_engine
340