1 //
2 // Copyright (C) 2013 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/hardware_chromeos.h"
18 
19 #include <utility>
20 
21 #include <base/files/file_path.h>
22 #include <base/files/file_util.h>
23 #include <base/logging.h>
24 #include <base/strings/string_number_conversions.h>
25 #include <base/strings/string_util.h>
26 #include <brillo/key_value_store.h>
27 #include <debugd/dbus-constants.h>
28 #include <vboot/crossystem.h>
29 
30 extern "C" {
31 #include "vboot/vboot_host.h"
32 }
33 
34 #include "update_engine/common/constants.h"
35 #include "update_engine/common/hardware.h"
36 #include "update_engine/common/hwid_override.h"
37 #include "update_engine/common/platform_constants.h"
38 #include "update_engine/common/subprocess.h"
39 #include "update_engine/common/utils.h"
40 #include "update_engine/dbus_connection.h"
41 
42 using std::string;
43 using std::vector;
44 
45 namespace {
46 
47 const char kOOBECompletedMarker[] = "/home/chronos/.oobe_completed";
48 
49 // The stateful directory used by update_engine to store powerwash-safe files.
50 // The files stored here must be added to the powerwash script allowlist.
51 const char kPowerwashSafeDirectory[] =
52     "/mnt/stateful_partition/unencrypted/preserve";
53 
54 // The powerwash_count marker file contains the number of times the device was
55 // powerwashed. This value is incremented by the clobber-state script when
56 // a powerwash is performed.
57 const char kPowerwashCountMarker[] = "powerwash_count";
58 
59 // The name of the marker file used to trigger powerwash when post-install
60 // completes successfully so that the device is powerwashed on next reboot.
61 const char kPowerwashMarkerFile[] =
62     "/mnt/stateful_partition/factory_install_reset";
63 
64 // The name of the marker file used to trigger a save of rollback data
65 // during the next shutdown.
66 const char kRollbackSaveMarkerFile[] =
67     "/mnt/stateful_partition/.save_rollback_data";
68 
69 // The contents of the powerwash marker file for the non-rollback case.
70 const char kPowerwashCommand[] = "safe fast keepimg reason=update_engine\n";
71 
72 // The contents of the powerwas marker file for the rollback case.
73 const char kRollbackPowerwashCommand[] =
74     "safe fast keepimg rollback reason=update_engine\n";
75 
76 // UpdateManager config path.
77 const char* kConfigFilePath = "/etc/update_manager.conf";
78 
79 // UpdateManager config options:
80 const char* kConfigOptsIsOOBEEnabled = "is_oobe_enabled";
81 
82 const char* kActivePingKey = "first_active_omaha_ping_sent";
83 
84 const char* kOemRequisitionKey = "oem_device_requisition";
85 
86 // Gets a string value from the vpd for a given key using the `vpd_get_value`
87 // shell command. Returns true on success.
GetVpdValue(string key,string * result)88 int GetVpdValue(string key, string* result) {
89   int exit_code = 0;
90   string value, error;
91   vector<string> cmd = {"vpd_get_value", key};
92   if (!chromeos_update_engine::Subprocess::SynchronousExec(
93           cmd, &exit_code, &value, &error) ||
94       exit_code) {
95     LOG(ERROR) << "Failed to get vpd key for " << value
96                << " with exit code: " << exit_code << " and error: " << error;
97     return false;
98   } else if (!error.empty()) {
99     LOG(INFO) << "vpd_get_value succeeded but with following errors: " << error;
100   }
101 
102   base::TrimWhitespaceASCII(value, base::TRIM_ALL, &value);
103   *result = value;
104   return true;
105 }
106 
107 }  // namespace
108 
109 namespace chromeos_update_engine {
110 
111 namespace hardware {
112 
113 // Factory defined in hardware.h.
CreateHardware()114 std::unique_ptr<HardwareInterface> CreateHardware() {
115   std::unique_ptr<HardwareChromeOS> hardware(new HardwareChromeOS());
116   hardware->Init();
117   return std::move(hardware);
118 }
119 
120 }  // namespace hardware
121 
Init()122 void HardwareChromeOS::Init() {
123   LoadConfig("" /* root_prefix */, IsNormalBootMode());
124   debugd_proxy_.reset(
125       new org::chromium::debugdProxy(DBusConnection::Get()->GetDBus()));
126 }
127 
IsOfficialBuild() const128 bool HardwareChromeOS::IsOfficialBuild() const {
129   return VbGetSystemPropertyInt("debug_build") == 0;
130 }
131 
IsNormalBootMode() const132 bool HardwareChromeOS::IsNormalBootMode() const {
133   bool dev_mode = VbGetSystemPropertyInt("devsw_boot") != 0;
134   return !dev_mode;
135 }
136 
AreDevFeaturesEnabled() const137 bool HardwareChromeOS::AreDevFeaturesEnabled() const {
138   // Even though the debugd tools are also gated on devmode, checking here can
139   // save us a D-Bus call so it's worth doing explicitly.
140   if (IsNormalBootMode())
141     return false;
142 
143   int32_t dev_features = debugd::DEV_FEATURES_DISABLED;
144   brillo::ErrorPtr error;
145   // Some boards may not include debugd so it's expected that this may fail,
146   // in which case we treat it as disabled.
147   if (debugd_proxy_ && debugd_proxy_->QueryDevFeatures(&dev_features, &error) &&
148       !(dev_features & debugd::DEV_FEATURES_DISABLED)) {
149     LOG(INFO) << "Debugd dev tools enabled.";
150     return true;
151   }
152   return false;
153 }
154 
IsOOBEEnabled() const155 bool HardwareChromeOS::IsOOBEEnabled() const {
156   return is_oobe_enabled_;
157 }
158 
IsOOBEComplete(base::Time * out_time_of_oobe) const159 bool HardwareChromeOS::IsOOBEComplete(base::Time* out_time_of_oobe) const {
160   if (!is_oobe_enabled_) {
161     LOG(WARNING) << "OOBE is not enabled but IsOOBEComplete() was called";
162   }
163   struct stat statbuf;
164   if (stat(kOOBECompletedMarker, &statbuf) != 0) {
165     if (errno != ENOENT) {
166       PLOG(ERROR) << "Error getting information about " << kOOBECompletedMarker;
167     }
168     return false;
169   }
170 
171   if (out_time_of_oobe != nullptr)
172     *out_time_of_oobe = base::Time::FromTimeT(statbuf.st_mtime);
173   return true;
174 }
175 
ReadValueFromCrosSystem(const string & key)176 static string ReadValueFromCrosSystem(const string& key) {
177   char value_buffer[VB_MAX_STRING_PROPERTY];
178 
179   const char* rv = VbGetSystemPropertyString(
180       key.c_str(), value_buffer, sizeof(value_buffer));
181   if (rv != nullptr) {
182     string return_value(value_buffer);
183     base::TrimWhitespaceASCII(return_value, base::TRIM_ALL, &return_value);
184     return return_value;
185   }
186 
187   LOG(ERROR) << "Unable to read crossystem key " << key;
188   return "";
189 }
190 
GetHardwareClass() const191 string HardwareChromeOS::GetHardwareClass() const {
192   if (USE_HWID_OVERRIDE) {
193     return HwidOverride::Read(base::FilePath("/"));
194   }
195   return ReadValueFromCrosSystem("hwid");
196 }
197 
GetFirmwareVersion() const198 string HardwareChromeOS::GetFirmwareVersion() const {
199   return ReadValueFromCrosSystem("fwid");
200 }
201 
GetECVersion() const202 string HardwareChromeOS::GetECVersion() const {
203   string input_line, error;
204   int exit_code = 0;
205   vector<string> cmd = {"/usr/sbin/mosys", "-k", "ec", "info"};
206 
207   if (!Subprocess::SynchronousExec(cmd, &exit_code, &input_line, &error) ||
208       exit_code != 0) {
209     LOG(ERROR) << "Unable to read EC info from mosys with exit code: "
210                << exit_code << " and error: " << error;
211     return "";
212   }
213 
214   return utils::ParseECVersion(input_line);
215 }
216 
GetDeviceRequisition() const217 string HardwareChromeOS::GetDeviceRequisition() const {
218   string requisition;
219   return GetVpdValue(kOemRequisitionKey, &requisition) ? requisition : "";
220 }
221 
GetMinKernelKeyVersion() const222 int HardwareChromeOS::GetMinKernelKeyVersion() const {
223   return VbGetSystemPropertyInt("tpm_kernver");
224 }
225 
GetMaxFirmwareKeyRollforward() const226 int HardwareChromeOS::GetMaxFirmwareKeyRollforward() const {
227   return VbGetSystemPropertyInt("firmware_max_rollforward");
228 }
229 
SetMaxFirmwareKeyRollforward(int firmware_max_rollforward)230 bool HardwareChromeOS::SetMaxFirmwareKeyRollforward(
231     int firmware_max_rollforward) {
232   // Not all devices have this field yet. So first try to read
233   // it and if there is an error just fail.
234   if (GetMaxFirmwareKeyRollforward() == -1)
235     return false;
236 
237   return VbSetSystemPropertyInt("firmware_max_rollforward",
238                                 firmware_max_rollforward) == 0;
239 }
240 
GetMinFirmwareKeyVersion() const241 int HardwareChromeOS::GetMinFirmwareKeyVersion() const {
242   return VbGetSystemPropertyInt("tpm_fwver");
243 }
244 
SetMaxKernelKeyRollforward(int kernel_max_rollforward)245 bool HardwareChromeOS::SetMaxKernelKeyRollforward(int kernel_max_rollforward) {
246   return VbSetSystemPropertyInt("kernel_max_rollforward",
247                                 kernel_max_rollforward) == 0;
248 }
249 
GetPowerwashCount() const250 int HardwareChromeOS::GetPowerwashCount() const {
251   int powerwash_count;
252   base::FilePath marker_path =
253       base::FilePath(kPowerwashSafeDirectory).Append(kPowerwashCountMarker);
254   string contents;
255   if (!utils::ReadFile(marker_path.value(), &contents))
256     return -1;
257   base::TrimWhitespaceASCII(contents, base::TRIM_TRAILING, &contents);
258   if (!base::StringToInt(contents, &powerwash_count))
259     return -1;
260   return powerwash_count;
261 }
262 
SchedulePowerwash(bool save_rollback_data)263 bool HardwareChromeOS::SchedulePowerwash(bool save_rollback_data) {
264   if (save_rollback_data) {
265     if (!utils::WriteFile(kRollbackSaveMarkerFile, nullptr, 0)) {
266       PLOG(ERROR) << "Error in creating rollback save marker file: "
267                   << kRollbackSaveMarkerFile << ". Rollback will not"
268                   << " preserve any data.";
269     } else {
270       LOG(INFO) << "Rollback data save has been scheduled on next shutdown.";
271     }
272   }
273 
274   const char* powerwash_command =
275       save_rollback_data ? kRollbackPowerwashCommand : kPowerwashCommand;
276   bool result = utils::WriteFile(
277       kPowerwashMarkerFile, powerwash_command, strlen(powerwash_command));
278   if (result) {
279     LOG(INFO) << "Created " << kPowerwashMarkerFile
280               << " to powerwash on next reboot ("
281               << "save_rollback_data=" << save_rollback_data << ")";
282   } else {
283     PLOG(ERROR) << "Error in creating powerwash marker file: "
284                 << kPowerwashMarkerFile;
285   }
286 
287   return result;
288 }
289 
CancelPowerwash()290 bool HardwareChromeOS::CancelPowerwash() {
291   bool result = base::DeleteFile(base::FilePath(kPowerwashMarkerFile), false);
292 
293   if (result) {
294     LOG(INFO) << "Successfully deleted the powerwash marker file : "
295               << kPowerwashMarkerFile;
296   } else {
297     PLOG(ERROR) << "Could not delete the powerwash marker file : "
298                 << kPowerwashMarkerFile;
299   }
300 
301   // Delete the rollback save marker file if it existed.
302   if (!base::DeleteFile(base::FilePath(kRollbackSaveMarkerFile), false)) {
303     PLOG(ERROR) << "Could not remove rollback save marker";
304   }
305 
306   return result;
307 }
308 
GetNonVolatileDirectory(base::FilePath * path) const309 bool HardwareChromeOS::GetNonVolatileDirectory(base::FilePath* path) const {
310   *path = base::FilePath(constants::kNonVolatileDirectory);
311   return true;
312 }
313 
GetPowerwashSafeDirectory(base::FilePath * path) const314 bool HardwareChromeOS::GetPowerwashSafeDirectory(base::FilePath* path) const {
315   *path = base::FilePath(kPowerwashSafeDirectory);
316   return true;
317 }
318 
GetBuildTimestamp() const319 int64_t HardwareChromeOS::GetBuildTimestamp() const {
320   // TODO(senj): implement this in Chrome OS.
321   return 0;
322 }
323 
LoadConfig(const string & root_prefix,bool normal_mode)324 void HardwareChromeOS::LoadConfig(const string& root_prefix, bool normal_mode) {
325   brillo::KeyValueStore store;
326 
327   if (normal_mode) {
328     store.Load(base::FilePath(root_prefix + kConfigFilePath));
329   } else {
330     if (store.Load(base::FilePath(root_prefix + kStatefulPartition +
331                                   kConfigFilePath))) {
332       LOG(INFO) << "UpdateManager Config loaded from stateful partition.";
333     } else {
334       store.Load(base::FilePath(root_prefix + kConfigFilePath));
335     }
336   }
337 
338   if (!store.GetBoolean(kConfigOptsIsOOBEEnabled, &is_oobe_enabled_))
339     is_oobe_enabled_ = true;  // Default value.
340 }
341 
GetFirstActiveOmahaPingSent() const342 bool HardwareChromeOS::GetFirstActiveOmahaPingSent() const {
343   string active_ping_str;
344   if (!GetVpdValue(kActivePingKey, &active_ping_str)) {
345     return false;
346   }
347 
348   int active_ping;
349   if (active_ping_str.empty() ||
350       !base::StringToInt(active_ping_str, &active_ping)) {
351     LOG(INFO) << "Failed to parse active_ping value: " << active_ping_str;
352     return false;
353   }
354   return static_cast<bool>(active_ping);
355 }
356 
SetFirstActiveOmahaPingSent()357 bool HardwareChromeOS::SetFirstActiveOmahaPingSent() {
358   int exit_code = 0;
359   string output, error;
360   vector<string> vpd_set_cmd = {
361       "vpd", "-i", "RW_VPD", "-s", string(kActivePingKey) + "=1"};
362   if (!Subprocess::SynchronousExec(vpd_set_cmd, &exit_code, &output, &error) ||
363       exit_code) {
364     LOG(ERROR) << "Failed to set vpd key for " << kActivePingKey
365                << " with exit code: " << exit_code << " with output: " << output
366                << " and error: " << error;
367     return false;
368   } else if (!error.empty()) {
369     LOG(INFO) << "vpd succeeded but with error logs: " << error;
370   }
371 
372   vector<string> vpd_dump_cmd = {"dump_vpd_log", "--force"};
373   if (!Subprocess::SynchronousExec(vpd_dump_cmd, &exit_code, &output, &error) ||
374       exit_code) {
375     LOG(ERROR) << "Failed to cache " << kActivePingKey << " using dump_vpd_log"
376                << " with exit code: " << exit_code << " with output: " << output
377                << " and error: " << error;
378     return false;
379   } else if (!error.empty()) {
380     LOG(INFO) << "dump_vpd_log succeeded but with error logs: " << error;
381   }
382   return true;
383 }
384 
SetWarmReset(bool warm_reset)385 void HardwareChromeOS::SetWarmReset(bool warm_reset) {}
386 
387 }  // namespace chromeos_update_engine
388