blob: e264fa560bda5abcf2c2e7c3330a4d9509747682 [file] [log] [blame]
Greg Kerr019d59c2016-11-17 14:28:49 -08001// Copyright 2016 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Ben Chan045849f2017-12-18 17:27:07 -08005#include "imageloader/component.h"
Greg Kerr019d59c2016-11-17 14:28:49 -08006
7#include <fcntl.h>
8
9#include <algorithm>
10#include <string>
Eric Caruso089bbff2017-03-21 11:34:15 -070011#include <utility>
Greg Kerr019d59c2016-11-17 14:28:49 -080012#include <vector>
13
14#include <base/files/file.h>
Eric Caruso089bbff2017-03-21 11:34:15 -070015#include <base/files/file_enumerator.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080016#include <base/files/file_path.h>
17#include <base/files/file_util.h>
18#include <base/files/scoped_file.h>
19#include <base/json/json_string_value_serializer.h>
20#include <base/logging.h>
Qijiang Fan886c4692021-02-19 11:54:10 +090021#include <base/notreached.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080022#include <base/numerics/safe_conversions.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080023#include <base/posix/eintr_wrapper.h>
Eric Caruso089bbff2017-03-21 11:34:15 -070024#include <base/strings/string_number_conversions.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080025#include <base/strings/string_util.h>
26#include <crypto/secure_hash.h>
27#include <crypto/sha2.h>
28#include <crypto/signature_verifier.h>
29
Amin Hassani17a185b2021-02-10 12:07:57 -080030#include "imageloader/global_context.h"
Greg Kerr09f06de2018-02-16 15:32:07 -080031#include "imageloader/helper_process_proxy.h"
Greg Kerr9944e242017-01-26 15:09:31 -080032
Greg Kerr019d59c2016-11-17 14:28:49 -080033namespace imageloader {
34
35namespace {
36
37// The name of the imageloader manifest file.
38constexpr char kManifestName[] = "imageloader.json";
39// The name of the fingerprint file.
40constexpr char kFingerprintName[] = "manifest.fingerprint";
41// The manifest signature.
Eric Caruso0b79bc82017-03-21 13:44:34 -070042constexpr char kManifestSignatureNamePattern[] = "imageloader.sig.[1-2]";
Xiaochu Liuc2264342017-08-14 16:37:42 -070043// The name of the image file (squashfs).
44constexpr char kImageFileNameSquashFS[] = "image.squash";
45// The name of the image file (ext4).
46constexpr char kImageFileNameExt4[] = "image.ext4";
Greg Kerr019d59c2016-11-17 14:28:49 -080047// The name of the table file.
48constexpr char kTableFileName[] = "table";
Greg Kerr019d59c2016-11-17 14:28:49 -080049
50base::FilePath GetManifestPath(const base::FilePath& component_dir) {
51 return component_dir.Append(kManifestName);
52}
53
Eric Caruso089bbff2017-03-21 11:34:15 -070054bool GetSignaturePath(const base::FilePath& component_dir,
55 base::FilePath* signature_path,
Eric Caruso9588e642017-04-07 15:18:45 -070056 size_t* key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070057 DCHECK(signature_path);
58 DCHECK(key_number);
59
Greg Kerr09f06de2018-02-16 15:32:07 -080060 base::FileEnumerator files(component_dir, false,
Eric Caruso089bbff2017-03-21 11:34:15 -070061 base::FileEnumerator::FileType::FILES,
62 kManifestSignatureNamePattern);
63 for (base::FilePath path = files.Next(); !path.empty(); path = files.Next()) {
64 // Extract the key number.
65 std::string key_ext = path.FinalExtension();
66 if (key_ext.empty())
67 continue;
68
Eric Caruso9588e642017-04-07 15:18:45 -070069 size_t ext_number;
70 if (!base::StringToSizeT(key_ext.substr(1), &ext_number))
Eric Caruso089bbff2017-03-21 11:34:15 -070071 continue;
72
73 *signature_path = path;
74 *key_number = ext_number;
75 return true;
76 }
77 return false;
78}
79
80base::FilePath GetSignaturePathForKey(const base::FilePath& component_dir,
Eric Caruso9588e642017-04-07 15:18:45 -070081 size_t key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070082 std::string signature_name(kManifestSignatureNamePattern);
83 signature_name =
84 signature_name.substr(0, signature_name.find_last_of('.') + 1);
Hidehiko Abe0deb0542019-08-15 01:56:10 +090085 return component_dir.Append(signature_name +
86 base::NumberToString(key_number));
Greg Kerr019d59c2016-11-17 14:28:49 -080087}
88
89base::FilePath GetFingerprintPath(const base::FilePath& component_dir) {
90 return component_dir.Append(kFingerprintName);
91}
92
93base::FilePath GetTablePath(const base::FilePath& component_dir) {
94 return component_dir.Append(kTableFileName);
95}
96
Xiaochu Liuc2264342017-08-14 16:37:42 -070097base::FilePath GetImagePath(const base::FilePath& component_dir,
Xiaochu Liue61e1d62018-11-12 13:20:09 -080098 FileSystem fs_type) {
99 if (fs_type == FileSystem::kExt4) {
Xiaochu Liuc2264342017-08-14 16:37:42 -0700100 return component_dir.Append(kImageFileNameExt4);
Xiaochu Liue61e1d62018-11-12 13:20:09 -0800101 } else if (fs_type == FileSystem::kSquashFS) {
Xiaochu Liuc2264342017-08-14 16:37:42 -0700102 return component_dir.Append(kImageFileNameSquashFS);
Greg Kerr09f06de2018-02-16 15:32:07 -0800103 } else {
Xiaochu Liuc2264342017-08-14 16:37:42 -0700104 NOTREACHED();
105 return base::FilePath();
106 }
Greg Kerr019d59c2016-11-17 14:28:49 -0800107}
108
109bool WriteFileToDisk(const base::FilePath& path, const std::string& contents) {
Greg Kerr09f06de2018-02-16 15:32:07 -0800110 base::ScopedFD fd(HANDLE_EINTR(open(
111 path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL, kComponentFilePerms)));
Greg Kerr019d59c2016-11-17 14:28:49 -0800112 if (!fd.is_valid()) {
113 PLOG(ERROR) << "Error creating file for " << path.value();
114 return false;
115 }
116
117 base::File file(fd.release());
118 int size = base::checked_cast<int>(contents.size());
119 return file.Write(0, contents.data(), contents.size()) == size;
120}
121
Greg Kerr019d59c2016-11-17 14:28:49 -0800122bool GetAndVerifyTable(const base::FilePath& path,
123 const std::vector<uint8_t>& hash,
124 std::string* out_table) {
125 std::string table;
126 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
127 return false;
128 }
129
130 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
131 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
132 if (table_hash != hash) {
133 LOG(ERROR) << "dm-verity table file has the wrong hash.";
134 return false;
135 }
136
137 out_table->assign(table);
138 return true;
139}
140
141} // namespace
142
Eric Caruso089bbff2017-03-21 11:34:15 -0700143Component::Component(const base::FilePath& component_dir, int key_number)
144 : component_dir_(component_dir), key_number_(key_number) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800145
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700146std::unique_ptr<Component> Component::Create(
Greg Kerr09f06de2018-02-16 15:32:07 -0800147 const base::FilePath& component_dir, const Keys& public_keys) {
Amin Hassani17a185b2021-02-10 12:07:57 -0800148 bool is_official_build = GlobalContext::Current()->IsOfficialBuild();
149
150 // Try to verify signatures in all type of images (signed/test/etc) if they
151 // exists. Only for non-official images, if the signature is missing, ignore
152 // verification otherwise fail.
Eric Caruso089bbff2017-03-21 11:34:15 -0700153 base::FilePath signature_path;
Amin Hassani17a185b2021-02-10 12:07:57 -0800154 size_t key_number = 0;
155 if (GetSignaturePath(component_dir, &signature_path, &key_number)) {
156 if (key_number < 1 || key_number > public_keys.size()) {
157 LOG(ERROR) << "Invalid key number.";
158 return nullptr;
159 }
160 } else if (is_official_build) {
161 LOG(ERROR) << "Could not find manifest signature.";
Eric Caruso089bbff2017-03-21 11:34:15 -0700162 return nullptr;
Amin Hassani17a185b2021-02-10 12:07:57 -0800163 } else {
164 LOG(WARNING) << "Could not find manifest signature, but since this is not "
165 << "an official image, we allow loading the component.";
Eric Caruso0b79bc82017-03-21 13:44:34 -0700166 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700167
168 std::unique_ptr<Component> component(
169 new Component(component_dir, key_number));
Amin Hassani17a185b2021-02-10 12:07:57 -0800170 if (key_number > 0) {
171 if (!component->LoadManifest(public_keys[key_number - 1])) {
172 return nullptr;
173 }
174 } else if (!component->LoadManifestWithoutVerifyingKeyForTestingOnly()) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700175 return nullptr;
Amin Hassani17a185b2021-02-10 12:07:57 -0800176 }
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700177 return component;
Greg Kerr019d59c2016-11-17 14:28:49 -0800178}
179
Xiaochu Liue61e1d62018-11-12 13:20:09 -0800180const Manifest& Component::manifest() {
Greg Kerr019d59c2016-11-17 14:28:49 -0800181 return manifest_;
182}
183
Greg Kerr09f06de2018-02-16 15:32:07 -0800184bool Component::Mount(HelperProcessProxy* mounter,
185 const base::FilePath& dest_dir) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700186 // Read the table in and verify the hash.
Greg Kerr019d59c2016-11-17 14:28:49 -0800187 std::string table;
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700188 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256(),
Greg Kerr019d59c2016-11-17 14:28:49 -0800189 &table)) {
190 LOG(ERROR) << "Could not read and verify dm-verity table.";
191 return false;
192 }
193
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700194 base::FilePath image_path(GetImagePath(component_dir_, manifest_.fs_type()));
Greg Kerr019d59c2016-11-17 14:28:49 -0800195 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
196 if (!image.IsValid()) {
197 LOG(ERROR) << "Could not open image file.";
198 return false;
199 }
200 base::ScopedFD image_fd(image.TakePlatformFile());
201
Xiaochu Liuc2264342017-08-14 16:37:42 -0700202 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(),
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700203 manifest_.fs_type(), table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800204}
205
Amin Hassani17a185b2021-02-10 12:07:57 -0800206bool Component::LoadManifestWithoutVerifyingKeyForTestingOnly() {
207 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
208 &manifest_raw_, kMaximumFilesize)) {
209 LOG(ERROR) << "Could not read manifest file.";
210 return false;
211 }
212 return manifest_.ParseManifest(manifest_raw_);
213}
214
Greg Kerr019d59c2016-11-17 14:28:49 -0800215bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
216 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
217 &manifest_raw_, kMaximumFilesize)) {
218 LOG(ERROR) << "Could not read manifest file.";
219 return false;
220 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700221 if (!base::ReadFileToStringWithMaxSize(
Greg Kerr09f06de2018-02-16 15:32:07 -0800222 GetSignaturePathForKey(component_dir_, key_number_), &manifest_sig_,
223 kMaximumFilesize)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800224 LOG(ERROR) << "Could not read signature file.";
225 return false;
226 }
227
228 crypto::SignatureVerifier verifier;
229
230 if (!verifier.VerifyInit(
231 crypto::SignatureVerifier::ECDSA_SHA256,
232 reinterpret_cast<const uint8_t*>(manifest_sig_.data()),
233 base::checked_cast<int>(manifest_sig_.size()), public_key.data(),
234 base::checked_cast<int>(public_key.size()))) {
235 LOG(ERROR) << "Failed to initialize signature verification.";
236 return false;
237 }
238
239 verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(manifest_raw_.data()),
240 base::checked_cast<int>(manifest_raw_.size()));
241
242 if (!verifier.VerifyFinal()) {
243 LOG(ERROR) << "Manifest failed signature verification.";
244 return false;
245 }
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700246 return manifest_.ParseManifest(manifest_raw_);
Greg Kerr019d59c2016-11-17 14:28:49 -0800247}
248
249bool Component::CopyTo(const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800250 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
Amin Hassani17a185b2021-02-10 12:07:57 -0800251 (key_number_ > 0 &&
252 !WriteFileToDisk(GetSignaturePathForKey(dest_dir, key_number_),
253 manifest_sig_))) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800254 LOG(ERROR) << "Could not write manifest and signature to disk.";
255 return false;
256 }
257
258 base::FilePath table_src(GetTablePath(component_dir_));
259 base::FilePath table_dest(GetTablePath(dest_dir));
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700260 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256())) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800261 LOG(ERROR) << "Could not copy table file.";
262 return false;
263 }
264
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700265 base::FilePath image_src(GetImagePath(component_dir_, manifest_.fs_type()));
266 base::FilePath image_dest(GetImagePath(dest_dir, manifest_.fs_type()));
267 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256())) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800268 LOG(ERROR) << "Could not copy image file.";
269 return false;
270 }
271
272 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
273 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
274 return false;
275 }
276
277 return true;
278}
279
280bool Component::CopyComponentFile(const base::FilePath& src,
Eric Caruso355e37c2017-03-15 14:31:41 -0700281 const base::FilePath& dest_path,
282 const std::vector<uint8_t>& expected_hash) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800283 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
Eric Caruso355e37c2017-03-15 14:31:41 -0700284 if (!file.IsValid())
285 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800286
287 base::ScopedFD dest(
288 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
289 kComponentFilePerms)));
Eric Caruso355e37c2017-03-15 14:31:41 -0700290 if (!dest.is_valid())
291 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800292
293 base::File out_file(dest.release());
294 std::unique_ptr<crypto::SecureHash> sha256(
295 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
296
297 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
298 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
299 LOG(ERROR) << "Failed to read image file.";
300 return false;
301 }
302
303 if (expected_hash != file_hash) {
304 LOG(ERROR) << "Image is corrupt or modified.";
305 return false;
306 }
307 return true;
308}
309
310bool Component::ReadHashAndCopyFile(base::File* file,
311 std::vector<uint8_t>* file_hash,
312 base::File* out_file) {
313 std::unique_ptr<crypto::SecureHash> sha256(
314 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
315 int size = file->GetLength();
Eric Caruso355e37c2017-03-15 14:31:41 -0700316 if (size <= 0)
317 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800318
319 int rv = 0, bytes_read = 0;
320 char buf[4096];
321 do {
322 int remaining = size - bytes_read;
323 int bytes_to_read =
324 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
325
326 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
Greg Kerr09f06de2018-02-16 15:32:07 -0800327 if (rv <= 0)
328 break;
Greg Kerr019d59c2016-11-17 14:28:49 -0800329
330 bytes_read += rv;
331 sha256->Update(buf, rv);
332 if (out_file) {
333 out_file->WriteAtCurrentPos(buf, rv);
334 }
335 } while (bytes_read <= size);
336
337 sha256->Finish(file_hash->data(), file_hash->size());
338 return bytes_read == size;
339}
340
341bool Component::CopyFingerprintFile(const base::FilePath& src,
342 const base::FilePath& dest) {
343 base::FilePath fingerprint_path(GetFingerprintPath(src));
344 if (base::PathExists(fingerprint_path)) {
345 std::string fingerprint_contents;
346 if (!base::ReadFileToStringWithMaxSize(
347 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
348 return false;
349 }
350
Eric Caruso355e37c2017-03-15 14:31:41 -0700351 if (!IsValidFingerprintFile(fingerprint_contents))
352 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800353
354 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
355 return false;
356 }
357 }
358 return true;
359}
360
361// The client inserts manifest.fingerprint into components after unpacking the
362// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
Greg Kerr04c1cee2020-10-15 14:08:44 +0000363// for security of the disk image, we are fine with validating the contents
Greg Kerr019d59c2016-11-17 14:28:49 -0800364// and then preserving the unsigned file.
365bool Component::IsValidFingerprintFile(const std::string& contents) {
366 return contents.size() <= 256 &&
367 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
368 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
369 }) == contents.end();
370}
371
372} // namespace imageloader