1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Permission is hereby granted, free of charge, to any person
5  * obtaining a copy of this software and associated documentation
6  * files (the "Software"), to deal in the Software without
7  * restriction, including without limitation the rights to use, copy,
8  * modify, merge, publish, distribute, sublicense, and/or sell copies
9  * of the Software, and to permit persons to whom the Software is
10  * furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
19  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
20  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 
25 #include "avb_ops.h"
26 
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <linux/fs.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/ioctl.h>
33 #include <sys/stat.h>
34 
35 #include <string>
36 
37 #include <android-base/macros.h>
38 #include <android-base/strings.h>
39 #include <android-base/unique_fd.h>
40 #include <libavb/libavb.h>
41 #include <libdm/dm.h>
42 #include <utils/Compat.h>
43 
44 #include "util.h"
45 
46 using namespace std::literals;
47 
48 namespace android {
49 namespace fs_mgr {
50 
read_from_partition(AvbOps * ops,const char * partition,int64_t offset,size_t num_bytes,void * buffer,size_t * out_num_read)51 static AvbIOResult read_from_partition(AvbOps* ops, const char* partition, int64_t offset,
52                                        size_t num_bytes, void* buffer, size_t* out_num_read) {
53     return FsManagerAvbOps::GetInstanceFromAvbOps(ops)->ReadFromPartition(
54             partition, offset, num_bytes, buffer, out_num_read);
55 }
56 
no_op_read_rollback_index(AvbOps * ops ATTRIBUTE_UNUSED,size_t rollback_index_location ATTRIBUTE_UNUSED,uint64_t * out_rollback_index)57 static AvbIOResult no_op_read_rollback_index(AvbOps* ops ATTRIBUTE_UNUSED,
58                                             size_t rollback_index_location ATTRIBUTE_UNUSED,
59                                             uint64_t* out_rollback_index) {
60     // rollback_index has been checked in bootloader phase.
61     // In user-space, returns the smallest value 0 to pass the check.
62     *out_rollback_index = 0;
63     return AVB_IO_RESULT_OK;
64 }
65 
no_op_validate_vbmeta_public_key(AvbOps * ops ATTRIBUTE_UNUSED,const uint8_t * public_key_data ATTRIBUTE_UNUSED,size_t public_key_length ATTRIBUTE_UNUSED,const uint8_t * public_key_metadata ATTRIBUTE_UNUSED,size_t public_key_metadata_length ATTRIBUTE_UNUSED,bool * out_is_trusted)66 static AvbIOResult no_op_validate_vbmeta_public_key(
67         AvbOps* ops ATTRIBUTE_UNUSED, const uint8_t* public_key_data ATTRIBUTE_UNUSED,
68         size_t public_key_length ATTRIBUTE_UNUSED,
69         const uint8_t* public_key_metadata ATTRIBUTE_UNUSED,
70         size_t public_key_metadata_length ATTRIBUTE_UNUSED, bool* out_is_trusted) {
71     // vbmeta public key has been checked in bootloader phase.
72     // In user-space, returns true to pass the check.
73     //
74     // Addtionally, user-space should check
75     // androidboot.vbmeta.{hash_alg, size, digest} against the digest
76     // of all vbmeta images after invoking avb_slot_verify().
77     *out_is_trusted = true;
78     return AVB_IO_RESULT_OK;
79 }
80 
no_op_read_is_device_unlocked(AvbOps * ops ATTRIBUTE_UNUSED,bool * out_is_unlocked)81 static AvbIOResult no_op_read_is_device_unlocked(AvbOps* ops ATTRIBUTE_UNUSED,
82                                                 bool* out_is_unlocked) {
83     // The function is for bootloader to update the value into
84     // androidboot.vbmeta.device_state in kernel cmdline.
85     // In user-space, returns true as we don't need to update it anymore.
86     *out_is_unlocked = true;
87     return AVB_IO_RESULT_OK;
88 }
89 
no_op_get_unique_guid_for_partition(AvbOps * ops ATTRIBUTE_UNUSED,const char * partition ATTRIBUTE_UNUSED,char * guid_buf,size_t guid_buf_size)90 static AvbIOResult no_op_get_unique_guid_for_partition(AvbOps* ops ATTRIBUTE_UNUSED,
91                                                       const char* partition ATTRIBUTE_UNUSED,
92                                                       char* guid_buf, size_t guid_buf_size) {
93     // The function is for bootloader to set the correct UUID
94     // for a given partition in kernel cmdline.
95     // In user-space, returns a faking one as we don't need to update
96     // it anymore.
97     snprintf(guid_buf, guid_buf_size, "1234-fake-guid-for:%s", partition);
98     return AVB_IO_RESULT_OK;
99 }
100 
get_size_of_partition(AvbOps * ops ATTRIBUTE_UNUSED,const char * partition ATTRIBUTE_UNUSED,uint64_t * out_size_num_byte)101 static AvbIOResult get_size_of_partition(AvbOps* ops ATTRIBUTE_UNUSED,
102                                          const char* partition ATTRIBUTE_UNUSED,
103                                          uint64_t* out_size_num_byte) {
104     return FsManagerAvbOps::GetInstanceFromAvbOps(ops)->GetSizeOfPartition(partition,
105                                                                            out_size_num_byte);
106 }
107 
108 // Converts a partition name (with ab_suffix) to the corresponding mount point.
109 // e.g., "system_a" => "/system",
110 // e.g., "vendor_a" => "/vendor",
DeriveMountPoint(const std::string & partition_name,const std::string & ab_suffix)111 static std::string DeriveMountPoint(const std::string& partition_name,
112                                     const std::string& ab_suffix) {
113     std::string mount_point(partition_name);
114     auto found = partition_name.rfind(ab_suffix);
115     if (found != std::string::npos) {
116         mount_point.erase(found);  // converts system_a => system
117     }
118 
119     return "/" + mount_point;
120 }
121 
FsManagerAvbOps(const std::string & slot_suffix)122 FsManagerAvbOps::FsManagerAvbOps(const std::string& slot_suffix) {
123     // We only need to provide the implementation of read_from_partition()
124     // operation since that's all what is being used by the avb_slot_verify().
125     // Other I/O operations are only required in bootloader but not in
126     // user-space so we set them as no-op operations. Also zero the entire
127     // struct so operations added in the future will be set to NULL.
128     memset(&avb_ops_, 0, sizeof(AvbOps));
129     avb_ops_.read_from_partition = read_from_partition;
130     avb_ops_.read_rollback_index = no_op_read_rollback_index;
131     avb_ops_.validate_vbmeta_public_key = no_op_validate_vbmeta_public_key;
132     avb_ops_.read_is_device_unlocked = no_op_read_is_device_unlocked;
133     avb_ops_.get_unique_guid_for_partition = no_op_get_unique_guid_for_partition;
134     avb_ops_.get_size_of_partition = get_size_of_partition;
135 
136     // Sets user_data for GetInstanceFromAvbOps() to convert it back to FsManagerAvbOps.
137     avb_ops_.user_data = this;
138 
139     slot_suffix_ = slot_suffix;
140     if (slot_suffix_.empty()) {
141         slot_suffix_ = fs_mgr_get_slot_suffix();
142     }
143 }
144 
145 // Given a partition name (with ab_suffix), e.g., system_a, returns the corresponding
146 // dm-linear path for it. e.g., /dev/block/dm-0. If not found, returns an empty string.
147 // This assumes that the prefix of the partition name and the mount point are the same.
148 // e.g., partition vendor_a is mounted under /vendor, product_a is mounted under /product, etc.
149 // This might not be true for some special fstab files, e.g., fstab.postinstall.
150 // But it's good enough for the default fstab. Also note that the logical path is a
151 // fallback solution when the physical path (/dev/block/by-name/<partition>) cannot be found.
GetLogicalPath(const std::string & partition_name)152 std::string FsManagerAvbOps::GetLogicalPath(const std::string& partition_name) {
153     if (fstab_.empty() && !ReadDefaultFstab(&fstab_)) {
154         return "";
155     }
156 
157     const auto mount_point = DeriveMountPoint(partition_name, slot_suffix_);
158     if (mount_point.empty()) return "";
159 
160     auto fstab_entry = GetEntryForMountPoint(&fstab_, mount_point);
161     if (!fstab_entry) return "";
162 
163     std::string device_path;
164     if (fstab_entry->fs_mgr_flags.logical) {
165         dm::DeviceMapper& dm = dm::DeviceMapper::Instance();
166         if (!dm.GetDmDevicePathByName(fstab_entry->blk_device, &device_path)) {
167             LERROR << "Failed to resolve logical device path for: " << fstab_entry->blk_device;
168             return "";
169         }
170         return device_path;
171     }
172 
173     return "";
174 }
GetPartitionPath(const char * partition)175 std::string FsManagerAvbOps::GetPartitionPath(const char* partition) {
176     std::string path = "/dev/block/by-name/"s + partition;
177     if (!WaitForFile(path, 1s)) {
178         LERROR << "Device path not found: " << path;
179         // Falls back to logical path if the physical path is not found.
180         // This mostly only works for emulator (no bootloader). Because in normal
181         // device, bootloader is unable to read logical partitions. So if libavb in
182         // the bootloader failed to read a physical partition, it will failed to boot
183         // the HLOS and we won't reach the code here.
184         path = GetLogicalPath(partition);
185         if (path.empty() || !WaitForFile(path, 1s)) return "";
186     }
187     return path;
188 }
189 
GetSizeOfPartition(const char * partition,uint64_t * out_size_num_byte)190 AvbIOResult FsManagerAvbOps::GetSizeOfPartition(const char* partition,
191                                                 uint64_t* out_size_num_byte) {
192     const auto path = GetPartitionPath(partition);
193     if (path.empty()) {
194         return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
195     }
196     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
197     if (fd < 0) {
198         PERROR << "Failed to open " << path;
199         return AVB_IO_RESULT_ERROR_IO;
200     }
201     int err = ioctl(fd, BLKGETSIZE64, out_size_num_byte);
202     if (err) {
203         *out_size_num_byte = 0;
204         return AVB_IO_RESULT_ERROR_IO;
205     }
206     return AVB_IO_RESULT_OK;
207 }
208 
ReadFromPartition(const char * partition,int64_t offset,size_t num_bytes,void * buffer,size_t * out_num_read)209 AvbIOResult FsManagerAvbOps::ReadFromPartition(const char* partition, int64_t offset,
210                                                size_t num_bytes, void* buffer,
211                                                size_t* out_num_read) {
212     std::string path = GetPartitionPath(partition);
213     if (path.empty()) {
214         return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
215     }
216 
217     android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
218     if (fd < 0) {
219         PERROR << "Failed to open " << path;
220         return AVB_IO_RESULT_ERROR_IO;
221     }
222 
223     // If offset is negative, interprets its absolute value as the
224     //  number of bytes from the end of the partition.
225     if (offset < 0) {
226         off64_t total_size = lseek64(fd, 0, SEEK_END);
227         if (total_size == -1) {
228             PERROR << "Failed to lseek64 to end of the partition";
229             return AVB_IO_RESULT_ERROR_IO;
230         }
231         offset = total_size + offset;
232         // Repositions the offset to the beginning.
233         if (lseek64(fd, 0, SEEK_SET) == -1) {
234             PERROR << "Failed to lseek64 to the beginning of the partition";
235             return AVB_IO_RESULT_ERROR_IO;
236         }
237     }
238 
239     // On Linux, we never get partial reads from block devices (except
240     // for EOF).
241     ssize_t num_read = TEMP_FAILURE_RETRY(pread64(fd, buffer, num_bytes, offset));
242     if (num_read < 0 || (size_t)num_read != num_bytes) {
243         PERROR << "Failed to read " << num_bytes << " bytes from " << path << " offset " << offset;
244         return AVB_IO_RESULT_ERROR_IO;
245     }
246 
247     if (out_num_read != nullptr) {
248         *out_num_read = num_read;
249     }
250 
251     return AVB_IO_RESULT_OK;
252 }
253 
AvbSlotVerify(const std::string & ab_suffix,AvbSlotVerifyFlags flags,std::vector<VBMetaData> * out_vbmeta_images)254 AvbSlotVerifyResult FsManagerAvbOps::AvbSlotVerify(const std::string& ab_suffix,
255                                                    AvbSlotVerifyFlags flags,
256                                                    std::vector<VBMetaData>* out_vbmeta_images) {
257     // Invokes avb_slot_verify() to load and verify all vbmeta images.
258     // Sets requested_partitions to nullptr as it's to copy the contents
259     // of HASH partitions into handle>avb_slot_data_, which is not required as
260     // fs_mgr only deals with HASHTREE partitions.
261     const char* requested_partitions[] = {nullptr};
262 
263     // Local resource to store vbmeta images from avb_slot_verify();
264     AvbSlotVerifyData* avb_slot_data;
265 
266     // The |hashtree_error_mode| field doesn't matter as it only
267     // influences the generated kernel cmdline parameters.
268     auto verify_result =
269             avb_slot_verify(&avb_ops_, requested_partitions, ab_suffix.c_str(), flags,
270                             AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE, &avb_slot_data);
271 
272     if (!avb_slot_data) return verify_result;
273     // Copies avb_slot_data->vbmeta_images[].
274     for (size_t i = 0; i < avb_slot_data->num_vbmeta_images; i++) {
275         out_vbmeta_images->emplace_back(VBMetaData(avb_slot_data->vbmeta_images[i].vbmeta_data,
276                                                    avb_slot_data->vbmeta_images[i].vbmeta_size,
277                                                    avb_slot_data->vbmeta_images[i].partition_name));
278     }
279 
280     // Free the local resource.
281     avb_slot_verify_data_free(avb_slot_data);
282 
283     return verify_result;
284 }
285 
286 }  // namespace fs_mgr
287 }  // namespace android
288