blob: ee791bf6b79c4a820544e59a686e5eaed56d9338 [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>
21#include <base/numerics/safe_conversions.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080022#include <base/posix/eintr_wrapper.h>
Eric Caruso089bbff2017-03-21 11:34:15 -070023#include <base/strings/string_number_conversions.h>
Greg Kerr019d59c2016-11-17 14:28:49 -080024#include <base/strings/string_util.h>
25#include <crypto/secure_hash.h>
26#include <crypto/sha2.h>
27#include <crypto/signature_verifier.h>
28
Greg Kerr09f06de2018-02-16 15:32:07 -080029#include "imageloader/helper_process_proxy.h"
Greg Kerr9944e242017-01-26 15:09:31 -080030
Greg Kerr019d59c2016-11-17 14:28:49 -080031namespace imageloader {
32
33namespace {
34
35// The name of the imageloader manifest file.
36constexpr char kManifestName[] = "imageloader.json";
37// The name of the fingerprint file.
38constexpr char kFingerprintName[] = "manifest.fingerprint";
39// The manifest signature.
Eric Caruso0b79bc82017-03-21 13:44:34 -070040constexpr char kManifestSignatureNamePattern[] = "imageloader.sig.[1-2]";
Xiaochu Liuc2264342017-08-14 16:37:42 -070041// The name of the image file (squashfs).
42constexpr char kImageFileNameSquashFS[] = "image.squash";
43// The name of the image file (ext4).
44constexpr char kImageFileNameExt4[] = "image.ext4";
Greg Kerr019d59c2016-11-17 14:28:49 -080045// The name of the table file.
46constexpr char kTableFileName[] = "table";
47// The maximum size of any file to read into memory.
48constexpr size_t kMaximumFilesize = 4096 * 10;
49
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);
Eric Caruso9588e642017-04-07 15:18:45 -070085 return component_dir.Append(signature_name + base::SizeTToString(key_number));
Greg Kerr019d59c2016-11-17 14:28:49 -080086}
87
88base::FilePath GetFingerprintPath(const base::FilePath& component_dir) {
89 return component_dir.Append(kFingerprintName);
90}
91
92base::FilePath GetTablePath(const base::FilePath& component_dir) {
93 return component_dir.Append(kTableFileName);
94}
95
Xiaochu Liuc2264342017-08-14 16:37:42 -070096base::FilePath GetImagePath(const base::FilePath& component_dir,
97 FileSystem fs_type) {
Greg Kerr09f06de2018-02-16 15:32:07 -080098 if (fs_type == FileSystem::kExt4) {
Xiaochu Liuc2264342017-08-14 16:37:42 -070099 return component_dir.Append(kImageFileNameExt4);
Greg Kerr09f06de2018-02-16 15:32:07 -0800100 } else if (fs_type == FileSystem::kSquashFS) {
Xiaochu Liuc2264342017-08-14 16:37:42 -0700101 return component_dir.Append(kImageFileNameSquashFS);
Greg Kerr09f06de2018-02-16 15:32:07 -0800102 } else {
Xiaochu Liuc2264342017-08-14 16:37:42 -0700103 NOTREACHED();
104 return base::FilePath();
105 }
Greg Kerr019d59c2016-11-17 14:28:49 -0800106}
107
108bool WriteFileToDisk(const base::FilePath& path, const std::string& contents) {
Greg Kerr09f06de2018-02-16 15:32:07 -0800109 base::ScopedFD fd(HANDLE_EINTR(open(
110 path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL, kComponentFilePerms)));
Greg Kerr019d59c2016-11-17 14:28:49 -0800111 if (!fd.is_valid()) {
112 PLOG(ERROR) << "Error creating file for " << path.value();
113 return false;
114 }
115
116 base::File file(fd.release());
117 int size = base::checked_cast<int>(contents.size());
118 return file.Write(0, contents.data(), contents.size()) == size;
119}
120
Greg Kerr019d59c2016-11-17 14:28:49 -0800121bool GetAndVerifyTable(const base::FilePath& path,
122 const std::vector<uint8_t>& hash,
123 std::string* out_table) {
124 std::string table;
125 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
126 return false;
127 }
128
129 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
130 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
131 if (table_hash != hash) {
132 LOG(ERROR) << "dm-verity table file has the wrong hash.";
133 return false;
134 }
135
136 out_table->assign(table);
137 return true;
138}
139
140} // namespace
141
Eric Caruso089bbff2017-03-21 11:34:15 -0700142Component::Component(const base::FilePath& component_dir, int key_number)
143 : component_dir_(component_dir), key_number_(key_number) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800144
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700145std::unique_ptr<Component> Component::Create(
Greg Kerr09f06de2018-02-16 15:32:07 -0800146 const base::FilePath& component_dir, const Keys& public_keys) {
Eric Caruso089bbff2017-03-21 11:34:15 -0700147 base::FilePath signature_path;
Eric Caruso9588e642017-04-07 15:18:45 -0700148 size_t key_number;
Eric Caruso089bbff2017-03-21 11:34:15 -0700149 if (!GetSignaturePath(component_dir, &signature_path, &key_number)) {
150 LOG(ERROR) << "Could not find manifest signature";
151 return nullptr;
152 }
Eric Caruso0b79bc82017-03-21 13:44:34 -0700153 if (key_number < 1 || key_number > public_keys.size()) {
154 LOG(ERROR) << "Invalid key number";
155 return nullptr;
156 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700157
158 std::unique_ptr<Component> component(
159 new Component(component_dir, key_number));
Eric Caruso0b79bc82017-03-21 13:44:34 -0700160 if (!component->LoadManifest(public_keys[key_number - 1]))
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700161 return nullptr;
162 return component;
Greg Kerr019d59c2016-11-17 14:28:49 -0800163}
164
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700165const Manifest& Component::manifest() {
Greg Kerr019d59c2016-11-17 14:28:49 -0800166 return manifest_;
167}
168
Greg Kerr09f06de2018-02-16 15:32:07 -0800169bool Component::Mount(HelperProcessProxy* mounter,
170 const base::FilePath& dest_dir) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700171 // Read the table in and verify the hash.
Greg Kerr019d59c2016-11-17 14:28:49 -0800172 std::string table;
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700173 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256(),
Greg Kerr019d59c2016-11-17 14:28:49 -0800174 &table)) {
175 LOG(ERROR) << "Could not read and verify dm-verity table.";
176 return false;
177 }
178
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700179 base::FilePath image_path(GetImagePath(component_dir_, manifest_.fs_type()));
Greg Kerr019d59c2016-11-17 14:28:49 -0800180 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
181 if (!image.IsValid()) {
182 LOG(ERROR) << "Could not open image file.";
183 return false;
184 }
185 base::ScopedFD image_fd(image.TakePlatformFile());
186
Xiaochu Liuc2264342017-08-14 16:37:42 -0700187 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(),
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700188 manifest_.fs_type(), table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800189}
190
191bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
192 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
193 &manifest_raw_, kMaximumFilesize)) {
194 LOG(ERROR) << "Could not read manifest file.";
195 return false;
196 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700197 if (!base::ReadFileToStringWithMaxSize(
Greg Kerr09f06de2018-02-16 15:32:07 -0800198 GetSignaturePathForKey(component_dir_, key_number_), &manifest_sig_,
199 kMaximumFilesize)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800200 LOG(ERROR) << "Could not read signature file.";
201 return false;
202 }
203
204 crypto::SignatureVerifier verifier;
205
206 if (!verifier.VerifyInit(
207 crypto::SignatureVerifier::ECDSA_SHA256,
208 reinterpret_cast<const uint8_t*>(manifest_sig_.data()),
209 base::checked_cast<int>(manifest_sig_.size()), public_key.data(),
210 base::checked_cast<int>(public_key.size()))) {
211 LOG(ERROR) << "Failed to initialize signature verification.";
212 return false;
213 }
214
215 verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(manifest_raw_.data()),
216 base::checked_cast<int>(manifest_raw_.size()));
217
218 if (!verifier.VerifyFinal()) {
219 LOG(ERROR) << "Manifest failed signature verification.";
220 return false;
221 }
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700222 return manifest_.ParseManifest(manifest_raw_);
Greg Kerr019d59c2016-11-17 14:28:49 -0800223}
224
225bool Component::CopyTo(const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800226 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
Eric Caruso089bbff2017-03-21 11:34:15 -0700227 !WriteFileToDisk(GetSignaturePathForKey(dest_dir, key_number_),
Greg Kerr09f06de2018-02-16 15:32:07 -0800228 manifest_sig_)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800229 LOG(ERROR) << "Could not write manifest and signature to disk.";
230 return false;
231 }
232
233 base::FilePath table_src(GetTablePath(component_dir_));
234 base::FilePath table_dest(GetTablePath(dest_dir));
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700235 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256())) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800236 LOG(ERROR) << "Could not copy table file.";
237 return false;
238 }
239
Xiaochu Liuc209aab2018-06-19 13:42:15 -0700240 base::FilePath image_src(GetImagePath(component_dir_, manifest_.fs_type()));
241 base::FilePath image_dest(GetImagePath(dest_dir, manifest_.fs_type()));
242 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256())) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800243 LOG(ERROR) << "Could not copy image file.";
244 return false;
245 }
246
247 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
248 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
249 return false;
250 }
251
252 return true;
253}
254
255bool Component::CopyComponentFile(const base::FilePath& src,
Eric Caruso355e37c2017-03-15 14:31:41 -0700256 const base::FilePath& dest_path,
257 const std::vector<uint8_t>& expected_hash) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800258 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
Eric Caruso355e37c2017-03-15 14:31:41 -0700259 if (!file.IsValid())
260 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800261
262 base::ScopedFD dest(
263 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
264 kComponentFilePerms)));
Eric Caruso355e37c2017-03-15 14:31:41 -0700265 if (!dest.is_valid())
266 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800267
268 base::File out_file(dest.release());
269 std::unique_ptr<crypto::SecureHash> sha256(
270 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
271
272 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
273 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
274 LOG(ERROR) << "Failed to read image file.";
275 return false;
276 }
277
278 if (expected_hash != file_hash) {
279 LOG(ERROR) << "Image is corrupt or modified.";
280 return false;
281 }
282 return true;
283}
284
285bool Component::ReadHashAndCopyFile(base::File* file,
286 std::vector<uint8_t>* file_hash,
287 base::File* out_file) {
288 std::unique_ptr<crypto::SecureHash> sha256(
289 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
290 int size = file->GetLength();
Eric Caruso355e37c2017-03-15 14:31:41 -0700291 if (size <= 0)
292 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800293
294 int rv = 0, bytes_read = 0;
295 char buf[4096];
296 do {
297 int remaining = size - bytes_read;
298 int bytes_to_read =
299 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
300
301 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
Greg Kerr09f06de2018-02-16 15:32:07 -0800302 if (rv <= 0)
303 break;
Greg Kerr019d59c2016-11-17 14:28:49 -0800304
305 bytes_read += rv;
306 sha256->Update(buf, rv);
307 if (out_file) {
308 out_file->WriteAtCurrentPos(buf, rv);
309 }
310 } while (bytes_read <= size);
311
312 sha256->Finish(file_hash->data(), file_hash->size());
313 return bytes_read == size;
314}
315
316bool Component::CopyFingerprintFile(const base::FilePath& src,
317 const base::FilePath& dest) {
318 base::FilePath fingerprint_path(GetFingerprintPath(src));
319 if (base::PathExists(fingerprint_path)) {
320 std::string fingerprint_contents;
321 if (!base::ReadFileToStringWithMaxSize(
322 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
323 return false;
324 }
325
Eric Caruso355e37c2017-03-15 14:31:41 -0700326 if (!IsValidFingerprintFile(fingerprint_contents))
327 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800328
329 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
330 return false;
331 }
332 }
333 return true;
334}
335
336// The client inserts manifest.fingerprint into components after unpacking the
337// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
338// for security of the disk image, we are fine with sanity checking the contents
339// and then preserving the unsigned file.
340bool Component::IsValidFingerprintFile(const std::string& contents) {
341 return contents.size() <= 256 &&
342 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
343 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
344 }) == contents.end();
345}
346
347} // namespace imageloader