blob: 90374ddccae9d879f41d08f7eb4198165cd78fd3 [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 Caruso089bbff2017-03-21 11:34:15 -070040constexpr char kManifestSignatureNamePattern[] = "imageloader.sig.1";
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";
49// The name of the image file.
50constexpr char kImageFileName[] = "image.squash";
51// The name of the field containing the table hash.
52constexpr char kTableHashField[] = "table-sha256-hash";
53// The name of the table file.
54constexpr char kTableFileName[] = "table";
55// The maximum size of any file to read into memory.
56constexpr size_t kMaximumFilesize = 4096 * 10;
57
58base::FilePath GetManifestPath(const base::FilePath& component_dir) {
59 return component_dir.Append(kManifestName);
60}
61
Eric Caruso089bbff2017-03-21 11:34:15 -070062bool GetSignaturePath(const base::FilePath& component_dir,
63 base::FilePath* signature_path,
Eric Caruso9588e642017-04-07 15:18:45 -070064 size_t* key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070065 DCHECK(signature_path);
66 DCHECK(key_number);
67
68 base::FileEnumerator files(component_dir,
69 false,
70 base::FileEnumerator::FileType::FILES,
71 kManifestSignatureNamePattern);
72 for (base::FilePath path = files.Next(); !path.empty(); path = files.Next()) {
73 // Extract the key number.
74 std::string key_ext = path.FinalExtension();
75 if (key_ext.empty())
76 continue;
77
Eric Caruso9588e642017-04-07 15:18:45 -070078 size_t ext_number;
79 if (!base::StringToSizeT(key_ext.substr(1), &ext_number))
Eric Caruso089bbff2017-03-21 11:34:15 -070080 continue;
81
82 *signature_path = path;
83 *key_number = ext_number;
84 return true;
85 }
86 return false;
87}
88
89base::FilePath GetSignaturePathForKey(const base::FilePath& component_dir,
Eric Caruso9588e642017-04-07 15:18:45 -070090 size_t key_number) {
Eric Caruso089bbff2017-03-21 11:34:15 -070091 std::string signature_name(kManifestSignatureNamePattern);
92 signature_name =
93 signature_name.substr(0, signature_name.find_last_of('.') + 1);
Eric Caruso9588e642017-04-07 15:18:45 -070094 return component_dir.Append(signature_name + base::SizeTToString(key_number));
Greg Kerr019d59c2016-11-17 14:28:49 -080095}
96
97base::FilePath GetFingerprintPath(const base::FilePath& component_dir) {
98 return component_dir.Append(kFingerprintName);
99}
100
101base::FilePath GetTablePath(const base::FilePath& component_dir) {
102 return component_dir.Append(kTableFileName);
103}
104
105base::FilePath GetImagePath(const base::FilePath& component_dir) {
106 return component_dir.Append(kImageFileName);
107}
108
109bool WriteFileToDisk(const base::FilePath& path, const std::string& contents) {
110 base::ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(),
111 O_CREAT | O_WRONLY | O_EXCL,
112 kComponentFilePerms)));
113 if (!fd.is_valid()) {
114 PLOG(ERROR) << "Error creating file for " << path.value();
115 return false;
116 }
117
118 base::File file(fd.release());
119 int size = base::checked_cast<int>(contents.size());
120 return file.Write(0, contents.data(), contents.size()) == size;
121}
122
123bool GetSHA256FromString(const std::string& hash_str,
124 std::vector<uint8_t>* bytes) {
Eric Caruso355e37c2017-03-15 14:31:41 -0700125 if (!base::HexStringToBytes(hash_str, bytes))
126 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800127 return bytes->size() == crypto::kSHA256Length;
128}
129
130bool GetAndVerifyTable(const base::FilePath& path,
131 const std::vector<uint8_t>& hash,
132 std::string* out_table) {
133 std::string table;
134 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
135 return false;
136 }
137
138 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
139 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
140 if (table_hash != hash) {
141 LOG(ERROR) << "dm-verity table file has the wrong hash.";
142 return false;
143 }
144
145 out_table->assign(table);
146 return true;
147}
148
149} // namespace
150
Eric Caruso089bbff2017-03-21 11:34:15 -0700151Component::Component(const base::FilePath& component_dir, int key_number)
152 : component_dir_(component_dir), key_number_(key_number) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800153
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700154std::unique_ptr<Component> Component::Create(
155 const base::FilePath& component_dir,
156 const std::vector<uint8_t>& public_key) {
Eric Caruso089bbff2017-03-21 11:34:15 -0700157 base::FilePath signature_path;
Eric Caruso9588e642017-04-07 15:18:45 -0700158 size_t key_number;
Eric Caruso089bbff2017-03-21 11:34:15 -0700159 if (!GetSignaturePath(component_dir, &signature_path, &key_number)) {
160 LOG(ERROR) << "Could not find manifest signature";
161 return nullptr;
162 }
163
164 std::unique_ptr<Component> component(
165 new Component(component_dir, key_number));
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700166 if (!component->LoadManifest(public_key))
167 return nullptr;
168 return component;
Greg Kerr019d59c2016-11-17 14:28:49 -0800169}
170
171const Component::Manifest& Component::manifest() {
Greg Kerr019d59c2016-11-17 14:28:49 -0800172 return manifest_;
173}
174
Greg Kerr9944e242017-01-26 15:09:31 -0800175bool Component::Mount(HelperProcess* mounter, const base::FilePath& dest_dir) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700176 // Read the table in and verify the hash.
Greg Kerr019d59c2016-11-17 14:28:49 -0800177 std::string table;
178 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256,
179 &table)) {
180 LOG(ERROR) << "Could not read and verify dm-verity table.";
181 return false;
182 }
183
184 base::FilePath image_path(GetImagePath(component_dir_));
185 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
186 if (!image.IsValid()) {
187 LOG(ERROR) << "Could not open image file.";
188 return false;
189 }
190 base::ScopedFD image_fd(image.TakePlatformFile());
191
Greg Kerr9944e242017-01-26 15:09:31 -0800192 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(), table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800193}
194
195bool Component::ParseManifest() {
196 // Now deserialize the manifest json and read out the rest of the component.
197 int error_code;
198 std::string error_message;
199 JSONStringValueDeserializer deserializer(manifest_raw_);
200 std::unique_ptr<base::Value> value =
201 deserializer.Deserialize(&error_code, &error_message);
202
203 if (!value) {
204 LOG(ERROR) << "Could not deserialize the manifest file. Error "
205 << error_code << ": " << error_message;
206 return false;
207 }
208
209 base::DictionaryValue* manifest_dict = nullptr;
210 if (!value->GetAsDictionary(&manifest_dict)) {
211 LOG(ERROR) << "Could not parse manifest file as JSON.";
212 return false;
213 }
214
215 // This will have to be changed if the manifest version is bumped.
216 int version;
217 if (!manifest_dict->GetInteger(kManifestVersionField, &version)) {
218 LOG(ERROR) << "Could not parse manifest version field from manifest.";
219 return false;
220 }
221 if (version != kCurrentManifestVersion) {
222 LOG(ERROR) << "Unsupported version of the manifest.";
223 return false;
224 }
225 manifest_.manifest_version = version;
226
227 std::string image_hash_str;
228 if (!manifest_dict->GetString(kImageHashField, &image_hash_str)) {
229 LOG(ERROR) << "Could not parse image hash from manifest.";
230 return false;
231 }
232
233 if (!GetSHA256FromString(image_hash_str, &(manifest_.image_sha256))) {
234 LOG(ERROR) << "Could not convert image hash to bytes.";
235 return false;
236 }
237
238 std::string table_hash_str;
239 if (!manifest_dict->GetString(kTableHashField, &table_hash_str)) {
240 LOG(ERROR) << "Could not parse table hash from manifest.";
241 return false;
242 }
243
244 if (!GetSHA256FromString(table_hash_str, &(manifest_.table_sha256))) {
245 LOG(ERROR) << "Could not convert table hash to bytes.";
246 return false;
247 }
248
249 if (!manifest_dict->GetString(kVersionField, &(manifest_.version))) {
250 LOG(ERROR) << "Could not parse component version from manifest.";
251 return false;
252 }
253
254 return true;
255}
256
257bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
258 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
259 &manifest_raw_, kMaximumFilesize)) {
260 LOG(ERROR) << "Could not read manifest file.";
261 return false;
262 }
Eric Caruso089bbff2017-03-21 11:34:15 -0700263 if (!base::ReadFileToStringWithMaxSize(
264 GetSignaturePathForKey(component_dir_, key_number_),
265 &manifest_sig_, kMaximumFilesize)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800266 LOG(ERROR) << "Could not read signature file.";
267 return false;
268 }
269
270 crypto::SignatureVerifier verifier;
271
272 if (!verifier.VerifyInit(
273 crypto::SignatureVerifier::ECDSA_SHA256,
274 reinterpret_cast<const uint8_t*>(manifest_sig_.data()),
275 base::checked_cast<int>(manifest_sig_.size()), public_key.data(),
276 base::checked_cast<int>(public_key.size()))) {
277 LOG(ERROR) << "Failed to initialize signature verification.";
278 return false;
279 }
280
281 verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(manifest_raw_.data()),
282 base::checked_cast<int>(manifest_raw_.size()));
283
284 if (!verifier.VerifyFinal()) {
285 LOG(ERROR) << "Manifest failed signature verification.";
286 return false;
287 }
288 return ParseManifest();
289}
290
291bool Component::CopyTo(const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800292 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
Eric Caruso089bbff2017-03-21 11:34:15 -0700293 !WriteFileToDisk(GetSignaturePathForKey(dest_dir, key_number_),
294 manifest_sig_)) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800295 LOG(ERROR) << "Could not write manifest and signature to disk.";
296 return false;
297 }
298
299 base::FilePath table_src(GetTablePath(component_dir_));
300 base::FilePath table_dest(GetTablePath(dest_dir));
301 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256)) {
302 LOG(ERROR) << "Could not copy table file.";
303 return false;
304 }
305
306 base::FilePath image_src(GetImagePath(component_dir_));
307 base::FilePath image_dest(GetImagePath(dest_dir));
308 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256)) {
309 LOG(ERROR) << "Could not copy image file.";
310 return false;
311 }
312
313 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
314 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
315 return false;
316 }
317
318 return true;
319}
320
321bool Component::CopyComponentFile(const base::FilePath& src,
Eric Caruso355e37c2017-03-15 14:31:41 -0700322 const base::FilePath& dest_path,
323 const std::vector<uint8_t>& expected_hash) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800324 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
Eric Caruso355e37c2017-03-15 14:31:41 -0700325 if (!file.IsValid())
326 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800327
328 base::ScopedFD dest(
329 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
330 kComponentFilePerms)));
Eric Caruso355e37c2017-03-15 14:31:41 -0700331 if (!dest.is_valid())
332 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800333
334 base::File out_file(dest.release());
335 std::unique_ptr<crypto::SecureHash> sha256(
336 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
337
338 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
339 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
340 LOG(ERROR) << "Failed to read image file.";
341 return false;
342 }
343
344 if (expected_hash != file_hash) {
345 LOG(ERROR) << "Image is corrupt or modified.";
346 return false;
347 }
348 return true;
349}
350
351bool Component::ReadHashAndCopyFile(base::File* file,
352 std::vector<uint8_t>* file_hash,
353 base::File* out_file) {
354 std::unique_ptr<crypto::SecureHash> sha256(
355 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
356 int size = file->GetLength();
Eric Caruso355e37c2017-03-15 14:31:41 -0700357 if (size <= 0)
358 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800359
360 int rv = 0, bytes_read = 0;
361 char buf[4096];
362 do {
363 int remaining = size - bytes_read;
364 int bytes_to_read =
365 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
366
367 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
368 if (rv <= 0) break;
369
370 bytes_read += rv;
371 sha256->Update(buf, rv);
372 if (out_file) {
373 out_file->WriteAtCurrentPos(buf, rv);
374 }
375 } while (bytes_read <= size);
376
377 sha256->Finish(file_hash->data(), file_hash->size());
378 return bytes_read == size;
379}
380
381bool Component::CopyFingerprintFile(const base::FilePath& src,
382 const base::FilePath& dest) {
383 base::FilePath fingerprint_path(GetFingerprintPath(src));
384 if (base::PathExists(fingerprint_path)) {
385 std::string fingerprint_contents;
386 if (!base::ReadFileToStringWithMaxSize(
387 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
388 return false;
389 }
390
Eric Caruso355e37c2017-03-15 14:31:41 -0700391 if (!IsValidFingerprintFile(fingerprint_contents))
392 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800393
394 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
395 return false;
396 }
397 }
398 return true;
399}
400
401// The client inserts manifest.fingerprint into components after unpacking the
402// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
403// for security of the disk image, we are fine with sanity checking the contents
404// and then preserving the unsigned file.
405bool Component::IsValidFingerprintFile(const std::string& contents) {
406 return contents.size() <= 256 &&
407 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
408 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
409 }) == contents.end();
410}
411
412} // namespace imageloader