blob: 889176f373ad9f2be21af231186e82d5eb4ce211 [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
5#include "component.h"
6
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 Kerr9944e242017-01-26 15:09:31 -080029#include "helper_process.h"
30
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]";
Greg Kerr019d59c2016-11-17 14:28:49 -080041// The current version of the manifest file.
42constexpr int kCurrentManifestVersion = 1;
43// The name of the version field in the manifest.
44constexpr char kManifestVersionField[] = "manifest-version";
45// The name of the component version field in the manifest.
46constexpr char kVersionField[] = "version";
47// The name of the field containing the image hash.
48constexpr char kImageHashField[] = "image-sha256-hash";
Xiaochu Liuc2264342017-08-14 16:37:42 -070049// The name of the image file (squashfs).
50constexpr char kImageFileNameSquashFS[] = "image.squash";
51// The name of the image file (ext4).
52constexpr char kImageFileNameExt4[] = "image.ext4";
Greg Kerr019d59c2016-11-17 14:28:49 -080053// The name of the field containing the table hash.
54constexpr char kTableHashField[] = "table-sha256-hash";
Xiaochu Liuc2264342017-08-14 16:37:42 -070055// The name of the optional field containing the file system type.
56constexpr char kFSType[] = "fs-type";
Greg Kerr019d59c2016-11-17 14:28:49 -080057// The name of the table file.
58constexpr char kTableFileName[] = "table";
59// The maximum size of any file to read into memory.
60constexpr size_t kMaximumFilesize = 4096 * 10;
61
62base::FilePath GetManifestPath(const base::FilePath& component_dir) {
63 return component_dir.Append(kManifestName);
64}
65
Eric Caruso089bbff2017-03-21 11:34:15 -070066bool GetSignaturePath(const base::FilePath& component_dir,
67 base::FilePath* signature_path,
Eric Caruso9588e642017-04-07 15:18:45 -070068 size_t* key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070069 DCHECK(signature_path);
70 DCHECK(key_number);
71
72 base::FileEnumerator files(component_dir,
73 false,
74 base::FileEnumerator::FileType::FILES,
75 kManifestSignatureNamePattern);
76 for (base::FilePath path = files.Next(); !path.empty(); path = files.Next()) {
77 // Extract the key number.
78 std::string key_ext = path.FinalExtension();
79 if (key_ext.empty())
80 continue;
81
Eric Caruso9588e642017-04-07 15:18:45 -070082 size_t ext_number;
83 if (!base::StringToSizeT(key_ext.substr(1), &ext_number))
Eric Caruso089bbff2017-03-21 11:34:15 -070084 continue;
85
86 *signature_path = path;
87 *key_number = ext_number;
88 return true;
89 }
90 return false;
91}
92
93base::FilePath GetSignaturePathForKey(const base::FilePath& component_dir,
Eric Caruso9588e642017-04-07 15:18:45 -070094 size_t key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070095 std::string signature_name(kManifestSignatureNamePattern);
96 signature_name =
97 signature_name.substr(0, signature_name.find_last_of('.') + 1);
Eric Caruso9588e642017-04-07 15:18:45 -070098 return component_dir.Append(signature_name + base::SizeTToString(key_number));
Greg Kerr019d59c2016-11-17 14:28:49 -080099}
100
101base::FilePath GetFingerprintPath(const base::FilePath& component_dir) {
102 return component_dir.Append(kFingerprintName);
103}
104
105base::FilePath GetTablePath(const base::FilePath& component_dir) {
106 return component_dir.Append(kTableFileName);
107}
108
Xiaochu Liuc2264342017-08-14 16:37:42 -0700109base::FilePath GetImagePath(const base::FilePath& component_dir,
110 FileSystem fs_type) {
111 if (fs_type == FileSystem::kExt4)
112 return component_dir.Append(kImageFileNameExt4);
113 else if (fs_type == FileSystem::kSquashFS)
114 return component_dir.Append(kImageFileNameSquashFS);
115 else {
116 NOTREACHED();
117 return base::FilePath();
118 }
Greg Kerr019d59c2016-11-17 14:28:49 -0800119}
120
121bool WriteFileToDisk(const base::FilePath& path, const std::string& contents) {
122 base::ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(),
123 O_CREAT | O_WRONLY | O_EXCL,
124 kComponentFilePerms)));
125 if (!fd.is_valid()) {
126 PLOG(ERROR) << "Error creating file for " << path.value();
127 return false;
128 }
129
130 base::File file(fd.release());
131 int size = base::checked_cast<int>(contents.size());
132 return file.Write(0, contents.data(), contents.size()) == size;
133}
134
135bool GetSHA256FromString(const std::string& hash_str,
136 std::vector<uint8_t>* bytes) {
Eric Caruso355e37c2017-03-15 14:31:41 -0700137 if (!base::HexStringToBytes(hash_str, bytes))
138 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800139 return bytes->size() == crypto::kSHA256Length;
140}
141
142bool GetAndVerifyTable(const base::FilePath& path,
143 const std::vector<uint8_t>& hash,
144 std::string* out_table) {
145 std::string table;
146 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
147 return false;
148 }
149
150 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
151 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
152 if (table_hash != hash) {
153 LOG(ERROR) << "dm-verity table file has the wrong hash.";
154 return false;
155 }
156
157 out_table->assign(table);
158 return true;
159}
160
161} // namespace
162
Eric Caruso089bbff2017-03-21 11:34:15 -0700163Component::Component(const base::FilePath& component_dir, int key_number)
164 : component_dir_(component_dir), key_number_(key_number) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800165
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700166std::unique_ptr<Component> Component::Create(
167 const base::FilePath& component_dir,
Eric Caruso0b79bc82017-03-21 13:44:34 -0700168 const Keys& public_keys) {
Eric Caruso089bbff2017-03-21 11:34:15 -0700169 base::FilePath signature_path;
Eric Caruso9588e642017-04-07 15:18:45 -0700170 size_t key_number;
Eric Caruso089bbff2017-03-21 11:34:15 -0700171 if (!GetSignaturePath(component_dir, &signature_path, &key_number)) {
172 LOG(ERROR) << "Could not find manifest signature";
173 return nullptr;
174 }
Eric Caruso0b79bc82017-03-21 13:44:34 -0700175 if (key_number < 1 || key_number > public_keys.size()) {
176 LOG(ERROR) << "Invalid key number";
177 return nullptr;
178 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700179
180 std::unique_ptr<Component> component(
181 new Component(component_dir, key_number));
Eric Caruso0b79bc82017-03-21 13:44:34 -0700182 if (!component->LoadManifest(public_keys[key_number - 1]))
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700183 return nullptr;
184 return component;
Greg Kerr019d59c2016-11-17 14:28:49 -0800185}
186
187const Component::Manifest& Component::manifest() {
Greg Kerr019d59c2016-11-17 14:28:49 -0800188 return manifest_;
189}
190
Greg Kerr9944e242017-01-26 15:09:31 -0800191bool Component::Mount(HelperProcess* mounter, const base::FilePath& dest_dir) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700192 // Read the table in and verify the hash.
Greg Kerr019d59c2016-11-17 14:28:49 -0800193 std::string table;
194 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256,
195 &table)) {
196 LOG(ERROR) << "Could not read and verify dm-verity table.";
197 return false;
198 }
199
Xiaochu Liuc2264342017-08-14 16:37:42 -0700200 base::FilePath image_path(GetImagePath(component_dir_, manifest_.fs_type));
Greg Kerr019d59c2016-11-17 14:28:49 -0800201 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
202 if (!image.IsValid()) {
203 LOG(ERROR) << "Could not open image file.";
204 return false;
205 }
206 base::ScopedFD image_fd(image.TakePlatformFile());
207
Xiaochu Liuc2264342017-08-14 16:37:42 -0700208 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(),
209 manifest_.fs_type, table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800210}
211
212bool Component::ParseManifest() {
213 // Now deserialize the manifest json and read out the rest of the component.
214 int error_code;
215 std::string error_message;
216 JSONStringValueDeserializer deserializer(manifest_raw_);
217 std::unique_ptr<base::Value> value =
218 deserializer.Deserialize(&error_code, &error_message);
219
220 if (!value) {
221 LOG(ERROR) << "Could not deserialize the manifest file. Error "
222 << error_code << ": " << error_message;
223 return false;
224 }
225
226 base::DictionaryValue* manifest_dict = nullptr;
227 if (!value->GetAsDictionary(&manifest_dict)) {
228 LOG(ERROR) << "Could not parse manifest file as JSON.";
229 return false;
230 }
231
232 // This will have to be changed if the manifest version is bumped.
233 int version;
234 if (!manifest_dict->GetInteger(kManifestVersionField, &version)) {
235 LOG(ERROR) << "Could not parse manifest version field from manifest.";
236 return false;
237 }
238 if (version != kCurrentManifestVersion) {
239 LOG(ERROR) << "Unsupported version of the manifest.";
240 return false;
241 }
242 manifest_.manifest_version = version;
243
244 std::string image_hash_str;
245 if (!manifest_dict->GetString(kImageHashField, &image_hash_str)) {
246 LOG(ERROR) << "Could not parse image hash from manifest.";
247 return false;
248 }
249
250 if (!GetSHA256FromString(image_hash_str, &(manifest_.image_sha256))) {
251 LOG(ERROR) << "Could not convert image hash to bytes.";
252 return false;
253 }
254
255 std::string table_hash_str;
256 if (!manifest_dict->GetString(kTableHashField, &table_hash_str)) {
257 LOG(ERROR) << "Could not parse table hash from manifest.";
258 return false;
259 }
260
261 if (!GetSHA256FromString(table_hash_str, &(manifest_.table_sha256))) {
262 LOG(ERROR) << "Could not convert table hash to bytes.";
263 return false;
264 }
265
266 if (!manifest_dict->GetString(kVersionField, &(manifest_.version))) {
267 LOG(ERROR) << "Could not parse component version from manifest.";
268 return false;
269 }
270
Xiaochu Liuc2264342017-08-14 16:37:42 -0700271 // The fs_type field is optional, and squashfs by default.
272 manifest_.fs_type = FileSystem::kSquashFS;
273 std::string fs_type;
274 if (manifest_dict->GetString(kFSType, &fs_type)) {
275 if (fs_type == "ext4") {
276 manifest_.fs_type = FileSystem::kExt4;
277 } else if (fs_type == "squashfs") {
278 manifest_.fs_type = FileSystem::kSquashFS;
279 } else {
280 LOG(ERROR) << "Unsupported file system type: " << fs_type;
281 return false;
282 }
283 }
284
Greg Kerr019d59c2016-11-17 14:28:49 -0800285 return true;
286}
287
288bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
289 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
290 &manifest_raw_, kMaximumFilesize)) {
291 LOG(ERROR) << "Could not read manifest file.";
292 return false;
293 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700294 if (!base::ReadFileToStringWithMaxSize(
295 GetSignaturePathForKey(component_dir_, key_number_),
296 &manifest_sig_, kMaximumFilesize)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800297 LOG(ERROR) << "Could not read signature file.";
298 return false;
299 }
300
301 crypto::SignatureVerifier verifier;
302
303 if (!verifier.VerifyInit(
304 crypto::SignatureVerifier::ECDSA_SHA256,
305 reinterpret_cast<const uint8_t*>(manifest_sig_.data()),
306 base::checked_cast<int>(manifest_sig_.size()), public_key.data(),
307 base::checked_cast<int>(public_key.size()))) {
308 LOG(ERROR) << "Failed to initialize signature verification.";
309 return false;
310 }
311
312 verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(manifest_raw_.data()),
313 base::checked_cast<int>(manifest_raw_.size()));
314
315 if (!verifier.VerifyFinal()) {
316 LOG(ERROR) << "Manifest failed signature verification.";
317 return false;
318 }
319 return ParseManifest();
320}
321
322bool Component::CopyTo(const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800323 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
Eric Caruso089bbff2017-03-21 11:34:15 -0700324 !WriteFileToDisk(GetSignaturePathForKey(dest_dir, key_number_),
325 manifest_sig_)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800326 LOG(ERROR) << "Could not write manifest and signature to disk.";
327 return false;
328 }
329
330 base::FilePath table_src(GetTablePath(component_dir_));
331 base::FilePath table_dest(GetTablePath(dest_dir));
332 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256)) {
333 LOG(ERROR) << "Could not copy table file.";
334 return false;
335 }
336
Xiaochu Liuc2264342017-08-14 16:37:42 -0700337 base::FilePath image_src(GetImagePath(component_dir_, manifest_.fs_type));
338 base::FilePath image_dest(GetImagePath(dest_dir, manifest_.fs_type));
Greg Kerr019d59c2016-11-17 14:28:49 -0800339 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256)) {
340 LOG(ERROR) << "Could not copy image file.";
341 return false;
342 }
343
344 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
345 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
346 return false;
347 }
348
349 return true;
350}
351
352bool Component::CopyComponentFile(const base::FilePath& src,
Eric Caruso355e37c2017-03-15 14:31:41 -0700353 const base::FilePath& dest_path,
354 const std::vector<uint8_t>& expected_hash) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800355 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
Eric Caruso355e37c2017-03-15 14:31:41 -0700356 if (!file.IsValid())
357 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800358
359 base::ScopedFD dest(
360 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
361 kComponentFilePerms)));
Eric Caruso355e37c2017-03-15 14:31:41 -0700362 if (!dest.is_valid())
363 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800364
365 base::File out_file(dest.release());
366 std::unique_ptr<crypto::SecureHash> sha256(
367 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
368
369 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
370 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
371 LOG(ERROR) << "Failed to read image file.";
372 return false;
373 }
374
375 if (expected_hash != file_hash) {
376 LOG(ERROR) << "Image is corrupt or modified.";
377 return false;
378 }
379 return true;
380}
381
382bool Component::ReadHashAndCopyFile(base::File* file,
383 std::vector<uint8_t>* file_hash,
384 base::File* out_file) {
385 std::unique_ptr<crypto::SecureHash> sha256(
386 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
387 int size = file->GetLength();
Eric Caruso355e37c2017-03-15 14:31:41 -0700388 if (size <= 0)
389 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800390
391 int rv = 0, bytes_read = 0;
392 char buf[4096];
393 do {
394 int remaining = size - bytes_read;
395 int bytes_to_read =
396 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
397
398 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
399 if (rv <= 0) break;
400
401 bytes_read += rv;
402 sha256->Update(buf, rv);
403 if (out_file) {
404 out_file->WriteAtCurrentPos(buf, rv);
405 }
406 } while (bytes_read <= size);
407
408 sha256->Finish(file_hash->data(), file_hash->size());
409 return bytes_read == size;
410}
411
412bool Component::CopyFingerprintFile(const base::FilePath& src,
413 const base::FilePath& dest) {
414 base::FilePath fingerprint_path(GetFingerprintPath(src));
415 if (base::PathExists(fingerprint_path)) {
416 std::string fingerprint_contents;
417 if (!base::ReadFileToStringWithMaxSize(
418 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
419 return false;
420 }
421
Eric Caruso355e37c2017-03-15 14:31:41 -0700422 if (!IsValidFingerprintFile(fingerprint_contents))
423 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800424
425 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
426 return false;
427 }
428 }
429 return true;
430}
431
432// The client inserts manifest.fingerprint into components after unpacking the
433// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
434// for security of the disk image, we are fine with sanity checking the contents
435// and then preserving the unsigned file.
436bool Component::IsValidFingerprintFile(const std::string& contents) {
437 return contents.size() <= 256 &&
438 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
439 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
440 }) == contents.end();
441}
442
443} // namespace imageloader