1 /*
2  * Copyright (C) 2015 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 <libboot_control/libboot_control.h>
18 
19 #include <endian.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <string.h>
23 
24 #include <string>
25 
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/unique_fd.h>
31 #include <bootloader_message/bootloader_message.h>
32 
33 #include "private/boot_control_definition.h"
34 
35 namespace android {
36 namespace bootable {
37 
38 using ::android::hardware::boot::V1_1::MergeStatus;
39 
40 // The number of boot attempts that should be made from a new slot before
41 // rolling back to the previous slot.
42 constexpr unsigned int kDefaultBootAttempts = 7;
43 static_assert(kDefaultBootAttempts < 8, "tries_remaining field only has 3 bits");
44 
45 constexpr unsigned int kMaxNumSlots =
46     sizeof(bootloader_control::slot_info) / sizeof(bootloader_control::slot_info[0]);
47 constexpr const char* kSlotSuffixes[kMaxNumSlots] = { "_a", "_b", "_c", "_d" };
48 constexpr off_t kBootloaderControlOffset = offsetof(bootloader_message_ab, slot_suffix);
49 
CRC32(const uint8_t * buf,size_t size)50 static uint32_t CRC32(const uint8_t* buf, size_t size) {
51   static uint32_t crc_table[256];
52 
53   // Compute the CRC-32 table only once.
54   if (!crc_table[1]) {
55     for (uint32_t i = 0; i < 256; ++i) {
56       uint32_t crc = i;
57       for (uint32_t j = 0; j < 8; ++j) {
58         uint32_t mask = -(crc & 1);
59         crc = (crc >> 1) ^ (0xEDB88320 & mask);
60       }
61       crc_table[i] = crc;
62     }
63   }
64 
65   uint32_t ret = -1;
66   for (size_t i = 0; i < size; ++i) {
67     ret = (ret >> 8) ^ crc_table[(ret ^ buf[i]) & 0xFF];
68   }
69 
70   return ~ret;
71 }
72 
73 // Return the little-endian representation of the CRC-32 of the first fields
74 // in |boot_ctrl| up to the crc32_le field.
BootloaderControlLECRC(const bootloader_control * boot_ctrl)75 uint32_t BootloaderControlLECRC(const bootloader_control* boot_ctrl) {
76   return htole32(
77       CRC32(reinterpret_cast<const uint8_t*>(boot_ctrl), offsetof(bootloader_control, crc32_le)));
78 }
79 
LoadBootloaderControl(const std::string & misc_device,bootloader_control * buffer)80 bool LoadBootloaderControl(const std::string& misc_device, bootloader_control* buffer) {
81   android::base::unique_fd fd(open(misc_device.c_str(), O_RDONLY));
82   if (fd.get() == -1) {
83     PLOG(ERROR) << "failed to open " << misc_device;
84     return false;
85   }
86   if (lseek(fd, kBootloaderControlOffset, SEEK_SET) != kBootloaderControlOffset) {
87     PLOG(ERROR) << "failed to lseek " << misc_device;
88     return false;
89   }
90   if (!android::base::ReadFully(fd.get(), buffer, sizeof(bootloader_control))) {
91     PLOG(ERROR) << "failed to read " << misc_device;
92     return false;
93   }
94   return true;
95 }
96 
UpdateAndSaveBootloaderControl(const std::string & misc_device,bootloader_control * buffer)97 bool UpdateAndSaveBootloaderControl(const std::string& misc_device, bootloader_control* buffer) {
98   buffer->crc32_le = BootloaderControlLECRC(buffer);
99   android::base::unique_fd fd(open(misc_device.c_str(), O_WRONLY | O_SYNC));
100   if (fd.get() == -1) {
101     PLOG(ERROR) << "failed to open " << misc_device;
102     return false;
103   }
104   if (lseek(fd.get(), kBootloaderControlOffset, SEEK_SET) != kBootloaderControlOffset) {
105     PLOG(ERROR) << "failed to lseek " << misc_device;
106     return false;
107   }
108   if (!android::base::WriteFully(fd.get(), buffer, sizeof(bootloader_control))) {
109     PLOG(ERROR) << "failed to write " << misc_device;
110     return false;
111   }
112   return true;
113 }
114 
InitDefaultBootloaderControl(BootControl * control,bootloader_control * boot_ctrl)115 void InitDefaultBootloaderControl(BootControl* control, bootloader_control* boot_ctrl) {
116   memset(boot_ctrl, 0, sizeof(*boot_ctrl));
117 
118   unsigned int current_slot = control->GetCurrentSlot();
119   if (current_slot < kMaxNumSlots) {
120     strlcpy(boot_ctrl->slot_suffix, kSlotSuffixes[current_slot], sizeof(boot_ctrl->slot_suffix));
121   }
122   boot_ctrl->magic = BOOT_CTRL_MAGIC;
123   boot_ctrl->version = BOOT_CTRL_VERSION;
124 
125   // Figure out the number of slots by checking if the partitions exist,
126   // otherwise assume the maximum supported by the header.
127   boot_ctrl->nb_slot = kMaxNumSlots;
128   std::string base_path = control->misc_device();
129   size_t last_path_sep = base_path.rfind('/');
130   if (last_path_sep != std::string::npos) {
131     // We test the existence of the "boot" partition on each possible slot,
132     // which is a partition required by Android Bootloader Requirements.
133     base_path = base_path.substr(0, last_path_sep + 1) + "boot";
134     int last_existing_slot = -1;
135     int first_missing_slot = -1;
136     for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
137       std::string partition_path = base_path + kSlotSuffixes[slot];
138       struct stat part_stat;
139       int err = stat(partition_path.c_str(), &part_stat);
140       if (!err) {
141         last_existing_slot = slot;
142         LOG(INFO) << "Found slot: " << kSlotSuffixes[slot];
143       } else if (err < 0 && errno == ENOENT && first_missing_slot == -1) {
144         first_missing_slot = slot;
145       }
146     }
147     // We only declare that we found the actual number of slots if we found all
148     // the boot partitions up to the number of slots, and no boot partition
149     // after that. Not finding any of the boot partitions implies a problem so
150     // we just leave the number of slots in the maximum value.
151     if ((last_existing_slot != -1 && last_existing_slot + 1 == first_missing_slot) ||
152         (first_missing_slot == -1 && last_existing_slot + 1 == kMaxNumSlots)) {
153       boot_ctrl->nb_slot = last_existing_slot + 1;
154       LOG(INFO) << "Found a system with " << last_existing_slot + 1 << " slots.";
155     }
156   }
157 
158   for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
159     slot_metadata entry = {};
160 
161     if (slot < boot_ctrl->nb_slot) {
162       entry.priority = 7;
163       entry.tries_remaining = kDefaultBootAttempts;
164       entry.successful_boot = 0;
165     } else {
166       entry.priority = 0;  // Unbootable
167     }
168 
169     // When the boot_control stored on disk is invalid, we assume that the
170     // current slot is successful. The bootloader should repair this situation
171     // before booting and write a valid boot_control slot, so if we reach this
172     // stage it means that the misc partition was corrupted since boot.
173     if (current_slot == slot) {
174       entry.successful_boot = 1;
175     }
176 
177     boot_ctrl->slot_info[slot] = entry;
178   }
179   boot_ctrl->recovery_tries_remaining = 0;
180 
181   boot_ctrl->crc32_le = BootloaderControlLECRC(boot_ctrl);
182 }
183 
184 // Return the index of the slot suffix passed or -1 if not a valid slot suffix.
SlotSuffixToIndex(const char * suffix)185 int SlotSuffixToIndex(const char* suffix) {
186   for (unsigned int slot = 0; slot < kMaxNumSlots; ++slot) {
187     if (!strcmp(kSlotSuffixes[slot], suffix)) return slot;
188   }
189   return -1;
190 }
191 
192 // Initialize the boot_control_private struct with the information from
193 // the bootloader_message buffer stored in |boot_ctrl|. Returns whether the
194 // initialization succeeded.
Init()195 bool BootControl::Init() {
196   if (initialized_) return true;
197 
198   // Initialize the current_slot from the read-only property. If the property
199   // was not set (from either the command line or the device tree), we can later
200   // initialize it from the bootloader_control struct.
201   std::string suffix_prop = android::base::GetProperty("ro.boot.slot_suffix", "");
202   if (suffix_prop.empty()) {
203     LOG(ERROR) << "Slot suffix property is not set";
204     return false;
205   }
206   current_slot_ = SlotSuffixToIndex(suffix_prop.c_str());
207 
208   std::string err;
209   std::string device = get_bootloader_message_blk_device(&err);
210   if (device.empty()) {
211     LOG(ERROR) << "Could not find bootloader message block device: " << err;
212     return false;
213   }
214 
215   bootloader_control boot_ctrl;
216   if (!LoadBootloaderControl(device.c_str(), &boot_ctrl)) {
217     LOG(ERROR) << "Failed to load bootloader control block";
218     return false;
219   }
220 
221   // Note that since there isn't a module unload function this memory is leaked.
222   // We use `device` below sometimes, so it's not moved out of here.
223   misc_device_ = device;
224   initialized_ = true;
225 
226   // Validate the loaded data, otherwise we will destroy it and re-initialize it
227   // with the current information.
228   uint32_t computed_crc32 = BootloaderControlLECRC(&boot_ctrl);
229   if (boot_ctrl.crc32_le != computed_crc32) {
230     LOG(WARNING) << "Invalid boot control found, expected CRC-32 0x" << std::hex << computed_crc32
231                  << " but found 0x" << std::hex << boot_ctrl.crc32_le << ". Re-initializing.";
232     InitDefaultBootloaderControl(this, &boot_ctrl);
233     UpdateAndSaveBootloaderControl(device.c_str(), &boot_ctrl);
234   }
235 
236   if (!InitMiscVirtualAbMessageIfNeeded()) {
237     return false;
238   }
239 
240   num_slots_ = boot_ctrl.nb_slot;
241   return true;
242 }
243 
GetNumberSlots()244 unsigned int BootControl::GetNumberSlots() {
245   return num_slots_;
246 }
247 
GetCurrentSlot()248 unsigned int BootControl::GetCurrentSlot() {
249   return current_slot_;
250 }
251 
MarkBootSuccessful()252 bool BootControl::MarkBootSuccessful() {
253   bootloader_control bootctrl;
254   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
255 
256   bootctrl.slot_info[current_slot_].successful_boot = 1;
257   // tries_remaining == 0 means that the slot is not bootable anymore, make
258   // sure we mark the current slot as bootable if it succeeds in the last
259   // attempt.
260   bootctrl.slot_info[current_slot_].tries_remaining = 1;
261   return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
262 }
263 
GetActiveBootSlot()264 unsigned int BootControl::GetActiveBootSlot() {
265   bootloader_control bootctrl;
266   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
267 
268   // Use the current slot by default.
269   unsigned int active_boot_slot = current_slot_;
270   unsigned int max_priority = bootctrl.slot_info[current_slot_].priority;
271   // Find the slot with the highest priority.
272   for (unsigned int i = 0; i < num_slots_; ++i) {
273     if (bootctrl.slot_info[i].priority > max_priority) {
274       max_priority = bootctrl.slot_info[i].priority;
275       active_boot_slot = i;
276     }
277   }
278 
279   return active_boot_slot;
280 }
281 
SetActiveBootSlot(unsigned int slot)282 bool BootControl::SetActiveBootSlot(unsigned int slot) {
283   if (slot >= kMaxNumSlots || slot >= num_slots_) {
284     // Invalid slot number.
285     return false;
286   }
287 
288   bootloader_control bootctrl;
289   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
290 
291   // Set every other slot with a lower priority than the new "active" slot.
292   const unsigned int kActivePriority = 15;
293   const unsigned int kActiveTries = 6;
294   for (unsigned int i = 0; i < num_slots_; ++i) {
295     if (i != slot) {
296       if (bootctrl.slot_info[i].priority >= kActivePriority)
297         bootctrl.slot_info[i].priority = kActivePriority - 1;
298     }
299   }
300 
301   // Note that setting a slot as active doesn't change the successful bit.
302   // The successful bit will only be changed by setSlotAsUnbootable().
303   bootctrl.slot_info[slot].priority = kActivePriority;
304   bootctrl.slot_info[slot].tries_remaining = kActiveTries;
305 
306   // Setting the current slot as active is a way to revert the operation that
307   // set *another* slot as active at the end of an updater. This is commonly
308   // used to cancel the pending update. We should only reset the verity_corrpted
309   // bit when attempting a new slot, otherwise the verity bit on the current
310   // slot would be flip.
311   if (slot != current_slot_) bootctrl.slot_info[slot].verity_corrupted = 0;
312 
313   return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
314 }
315 
SetSlotAsUnbootable(unsigned int slot)316 bool BootControl::SetSlotAsUnbootable(unsigned int slot) {
317   if (slot >= kMaxNumSlots || slot >= num_slots_) {
318     // Invalid slot number.
319     return false;
320   }
321 
322   bootloader_control bootctrl;
323   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
324 
325   // The only way to mark a slot as unbootable, regardless of the priority is to
326   // set the tries_remaining to 0.
327   bootctrl.slot_info[slot].successful_boot = 0;
328   bootctrl.slot_info[slot].tries_remaining = 0;
329   return UpdateAndSaveBootloaderControl(misc_device_, &bootctrl);
330 }
331 
IsSlotBootable(unsigned int slot)332 bool BootControl::IsSlotBootable(unsigned int slot) {
333   if (slot >= kMaxNumSlots || slot >= num_slots_) {
334     // Invalid slot number.
335     return false;
336   }
337 
338   bootloader_control bootctrl;
339   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
340 
341   return bootctrl.slot_info[slot].tries_remaining != 0;
342 }
343 
IsSlotMarkedSuccessful(unsigned int slot)344 bool BootControl::IsSlotMarkedSuccessful(unsigned int slot) {
345   if (slot >= kMaxNumSlots || slot >= num_slots_) {
346     // Invalid slot number.
347     return false;
348   }
349 
350   bootloader_control bootctrl;
351   if (!LoadBootloaderControl(misc_device_, &bootctrl)) return false;
352 
353   return bootctrl.slot_info[slot].successful_boot && bootctrl.slot_info[slot].tries_remaining;
354 }
355 
IsValidSlot(unsigned int slot)356 bool BootControl::IsValidSlot(unsigned int slot) {
357   return slot < kMaxNumSlots && slot < num_slots_;
358 }
359 
SetSnapshotMergeStatus(MergeStatus status)360 bool BootControl::SetSnapshotMergeStatus(MergeStatus status) {
361   return SetMiscVirtualAbMergeStatus(current_slot_, status);
362 }
363 
GetSnapshotMergeStatus()364 MergeStatus BootControl::GetSnapshotMergeStatus() {
365   MergeStatus status;
366   if (!GetMiscVirtualAbMergeStatus(current_slot_, &status)) {
367     return MergeStatus::UNKNOWN;
368   }
369   return status;
370 }
371 
GetSuffix(unsigned int slot)372 const char* BootControl::GetSuffix(unsigned int slot) {
373   if (slot >= kMaxNumSlots || slot >= num_slots_) {
374     return nullptr;
375   }
376   return kSlotSuffixes[slot];
377 }
378 
InitMiscVirtualAbMessageIfNeeded()379 bool InitMiscVirtualAbMessageIfNeeded() {
380   std::string err;
381   misc_virtual_ab_message message;
382   if (!ReadMiscVirtualAbMessage(&message, &err)) {
383     LOG(ERROR) << "Could not read merge status: " << err;
384     return false;
385   }
386 
387   if (message.version == MISC_VIRTUAL_AB_MESSAGE_VERSION &&
388       message.magic == MISC_VIRTUAL_AB_MAGIC_HEADER) {
389     // Already initialized.
390     return true;
391   }
392 
393   message = {};
394   message.version = MISC_VIRTUAL_AB_MESSAGE_VERSION;
395   message.magic = MISC_VIRTUAL_AB_MAGIC_HEADER;
396   if (!WriteMiscVirtualAbMessage(message, &err)) {
397     LOG(ERROR) << "Could not write merge status: " << err;
398     return false;
399   }
400   return true;
401 }
402 
SetMiscVirtualAbMergeStatus(unsigned int current_slot,android::hardware::boot::V1_1::MergeStatus status)403 bool SetMiscVirtualAbMergeStatus(unsigned int current_slot,
404                                  android::hardware::boot::V1_1::MergeStatus status) {
405   std::string err;
406   misc_virtual_ab_message message;
407 
408   if (!ReadMiscVirtualAbMessage(&message, &err)) {
409     LOG(ERROR) << "Could not read merge status: " << err;
410     return false;
411   }
412 
413   message.merge_status = static_cast<uint8_t>(status);
414   message.source_slot = current_slot;
415   if (!WriteMiscVirtualAbMessage(message, &err)) {
416     LOG(ERROR) << "Could not write merge status: " << err;
417     return false;
418   }
419   return true;
420 }
421 
GetMiscVirtualAbMergeStatus(unsigned int current_slot,android::hardware::boot::V1_1::MergeStatus * status)422 bool GetMiscVirtualAbMergeStatus(unsigned int current_slot,
423                                  android::hardware::boot::V1_1::MergeStatus* status) {
424   std::string err;
425   misc_virtual_ab_message message;
426 
427   if (!ReadMiscVirtualAbMessage(&message, &err)) {
428     LOG(ERROR) << "Could not read merge status: " << err;
429     return false;
430   }
431 
432   // If the slot reverted after having created a snapshot, then the snapshot will
433   // be thrown away at boot. Thus we don't count this as being in a snapshotted
434   // state.
435   *status = static_cast<MergeStatus>(message.merge_status);
436   if (*status == MergeStatus::SNAPSHOTTED && current_slot == message.source_slot) {
437     *status = MergeStatus::NONE;
438   }
439   return true;
440 }
441 
442 }  // namespace bootable
443 }  // namespace android
444