blob: 1afaf62e8543c2b5a444d66d21dd523b1e460296 [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>
11#include <vector>
12
13#include <base/files/file.h>
14#include <base/files/file_path.h>
15#include <base/files/file_util.h>
16#include <base/files/scoped_file.h>
17#include <base/json/json_string_value_serializer.h>
18#include <base/logging.h>
19#include <base/numerics/safe_conversions.h>
20#include <base/strings/string_number_conversions.h>
21#include <base/posix/eintr_wrapper.h>
22#include <base/strings/string_util.h>
23#include <crypto/secure_hash.h>
24#include <crypto/sha2.h>
25#include <crypto/signature_verifier.h>
26
Greg Kerr9944e242017-01-26 15:09:31 -080027#include "helper_process.h"
28
Greg Kerr019d59c2016-11-17 14:28:49 -080029namespace imageloader {
30
31namespace {
32
33// The name of the imageloader manifest file.
34constexpr char kManifestName[] = "imageloader.json";
35// The name of the fingerprint file.
36constexpr char kFingerprintName[] = "manifest.fingerprint";
37// The manifest signature.
38constexpr char kManifestSignatureName[] = "imageloader.sig.1";
39// The current version of the manifest file.
40constexpr int kCurrentManifestVersion = 1;
41// The name of the version field in the manifest.
42constexpr char kManifestVersionField[] = "manifest-version";
43// The name of the component version field in the manifest.
44constexpr char kVersionField[] = "version";
45// The name of the field containing the image hash.
46constexpr char kImageHashField[] = "image-sha256-hash";
47// The name of the image file.
48constexpr char kImageFileName[] = "image.squash";
49// The name of the field containing the table hash.
50constexpr char kTableHashField[] = "table-sha256-hash";
51// The name of the table file.
52constexpr char kTableFileName[] = "table";
53// The maximum size of any file to read into memory.
54constexpr size_t kMaximumFilesize = 4096 * 10;
55
56base::FilePath GetManifestPath(const base::FilePath& component_dir) {
57 return component_dir.Append(kManifestName);
58}
59
60base::FilePath GetSignaturePath(const base::FilePath& component_dir) {
61 return component_dir.Append(kManifestSignatureName);
62}
63
64base::FilePath GetFingerprintPath(const base::FilePath& component_dir) {
65 return component_dir.Append(kFingerprintName);
66}
67
68base::FilePath GetTablePath(const base::FilePath& component_dir) {
69 return component_dir.Append(kTableFileName);
70}
71
72base::FilePath GetImagePath(const base::FilePath& component_dir) {
73 return component_dir.Append(kImageFileName);
74}
75
76bool WriteFileToDisk(const base::FilePath& path, const std::string& contents) {
77 base::ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(),
78 O_CREAT | O_WRONLY | O_EXCL,
79 kComponentFilePerms)));
80 if (!fd.is_valid()) {
81 PLOG(ERROR) << "Error creating file for " << path.value();
82 return false;
83 }
84
85 base::File file(fd.release());
86 int size = base::checked_cast<int>(contents.size());
87 return file.Write(0, contents.data(), contents.size()) == size;
88}
89
90bool GetSHA256FromString(const std::string& hash_str,
91 std::vector<uint8_t>* bytes) {
Eric Caruso355e37c2017-03-15 14:31:41 -070092 if (!base::HexStringToBytes(hash_str, bytes))
93 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -080094 return bytes->size() == crypto::kSHA256Length;
95}
96
97bool GetAndVerifyTable(const base::FilePath& path,
98 const std::vector<uint8_t>& hash,
99 std::string* out_table) {
100 std::string table;
101 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
102 return false;
103 }
104
105 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
106 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
107 if (table_hash != hash) {
108 LOG(ERROR) << "dm-verity table file has the wrong hash.";
109 return false;
110 }
111
112 out_table->assign(table);
113 return true;
114}
115
116} // namespace
117
118Component::Component(const base::FilePath& component_dir)
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700119 : component_dir_(component_dir) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800120
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700121std::unique_ptr<Component> Component::Create(
122 const base::FilePath& component_dir,
123 const std::vector<uint8_t>& public_key) {
124 std::unique_ptr<Component> component(new Component(component_dir));
125 if (!component->LoadManifest(public_key))
126 return nullptr;
127 return component;
Greg Kerr019d59c2016-11-17 14:28:49 -0800128}
129
130const Component::Manifest& Component::manifest() {
Greg Kerr019d59c2016-11-17 14:28:49 -0800131 return manifest_;
132}
133
Greg Kerr9944e242017-01-26 15:09:31 -0800134bool Component::Mount(HelperProcess* mounter, const base::FilePath& dest_dir) {
Eric Carusocbe1c5c2017-03-15 14:21:08 -0700135 // Read the table in and verify the hash.
Greg Kerr019d59c2016-11-17 14:28:49 -0800136 std::string table;
137 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256,
138 &table)) {
139 LOG(ERROR) << "Could not read and verify dm-verity table.";
140 return false;
141 }
142
143 base::FilePath image_path(GetImagePath(component_dir_));
144 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
145 if (!image.IsValid()) {
146 LOG(ERROR) << "Could not open image file.";
147 return false;
148 }
149 base::ScopedFD image_fd(image.TakePlatformFile());
150
Greg Kerr9944e242017-01-26 15:09:31 -0800151 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(), table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800152}
153
154bool Component::ParseManifest() {
155 // Now deserialize the manifest json and read out the rest of the component.
156 int error_code;
157 std::string error_message;
158 JSONStringValueDeserializer deserializer(manifest_raw_);
159 std::unique_ptr<base::Value> value =
160 deserializer.Deserialize(&error_code, &error_message);
161
162 if (!value) {
163 LOG(ERROR) << "Could not deserialize the manifest file. Error "
164 << error_code << ": " << error_message;
165 return false;
166 }
167
168 base::DictionaryValue* manifest_dict = nullptr;
169 if (!value->GetAsDictionary(&manifest_dict)) {
170 LOG(ERROR) << "Could not parse manifest file as JSON.";
171 return false;
172 }
173
174 // This will have to be changed if the manifest version is bumped.
175 int version;
176 if (!manifest_dict->GetInteger(kManifestVersionField, &version)) {
177 LOG(ERROR) << "Could not parse manifest version field from manifest.";
178 return false;
179 }
180 if (version != kCurrentManifestVersion) {
181 LOG(ERROR) << "Unsupported version of the manifest.";
182 return false;
183 }
184 manifest_.manifest_version = version;
185
186 std::string image_hash_str;
187 if (!manifest_dict->GetString(kImageHashField, &image_hash_str)) {
188 LOG(ERROR) << "Could not parse image hash from manifest.";
189 return false;
190 }
191
192 if (!GetSHA256FromString(image_hash_str, &(manifest_.image_sha256))) {
193 LOG(ERROR) << "Could not convert image hash to bytes.";
194 return false;
195 }
196
197 std::string table_hash_str;
198 if (!manifest_dict->GetString(kTableHashField, &table_hash_str)) {
199 LOG(ERROR) << "Could not parse table hash from manifest.";
200 return false;
201 }
202
203 if (!GetSHA256FromString(table_hash_str, &(manifest_.table_sha256))) {
204 LOG(ERROR) << "Could not convert table hash to bytes.";
205 return false;
206 }
207
208 if (!manifest_dict->GetString(kVersionField, &(manifest_.version))) {
209 LOG(ERROR) << "Could not parse component version from manifest.";
210 return false;
211 }
212
213 return true;
214}
215
216bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
217 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
218 &manifest_raw_, kMaximumFilesize)) {
219 LOG(ERROR) << "Could not read manifest file.";
220 return false;
221 }
222 if (!base::ReadFileToStringWithMaxSize(GetSignaturePath(component_dir_),
223 &manifest_sig_, kMaximumFilesize)) {
224 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 }
246 return ParseManifest();
247}
248
249bool Component::CopyTo(const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800250 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
251 !WriteFileToDisk(GetSignaturePath(dest_dir), manifest_sig_)) {
252 LOG(ERROR) << "Could not write manifest and signature to disk.";
253 return false;
254 }
255
256 base::FilePath table_src(GetTablePath(component_dir_));
257 base::FilePath table_dest(GetTablePath(dest_dir));
258 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256)) {
259 LOG(ERROR) << "Could not copy table file.";
260 return false;
261 }
262
263 base::FilePath image_src(GetImagePath(component_dir_));
264 base::FilePath image_dest(GetImagePath(dest_dir));
265 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256)) {
266 LOG(ERROR) << "Could not copy image file.";
267 return false;
268 }
269
270 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
271 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
272 return false;
273 }
274
275 return true;
276}
277
278bool Component::CopyComponentFile(const base::FilePath& src,
Eric Caruso355e37c2017-03-15 14:31:41 -0700279 const base::FilePath& dest_path,
280 const std::vector<uint8_t>& expected_hash) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800281 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
Eric Caruso355e37c2017-03-15 14:31:41 -0700282 if (!file.IsValid())
283 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800284
285 base::ScopedFD dest(
286 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
287 kComponentFilePerms)));
Eric Caruso355e37c2017-03-15 14:31:41 -0700288 if (!dest.is_valid())
289 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800290
291 base::File out_file(dest.release());
292 std::unique_ptr<crypto::SecureHash> sha256(
293 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
294
295 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
296 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
297 LOG(ERROR) << "Failed to read image file.";
298 return false;
299 }
300
301 if (expected_hash != file_hash) {
302 LOG(ERROR) << "Image is corrupt or modified.";
303 return false;
304 }
305 return true;
306}
307
308bool Component::ReadHashAndCopyFile(base::File* file,
309 std::vector<uint8_t>* file_hash,
310 base::File* out_file) {
311 std::unique_ptr<crypto::SecureHash> sha256(
312 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
313 int size = file->GetLength();
Eric Caruso355e37c2017-03-15 14:31:41 -0700314 if (size <= 0)
315 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800316
317 int rv = 0, bytes_read = 0;
318 char buf[4096];
319 do {
320 int remaining = size - bytes_read;
321 int bytes_to_read =
322 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
323
324 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
325 if (rv <= 0) break;
326
327 bytes_read += rv;
328 sha256->Update(buf, rv);
329 if (out_file) {
330 out_file->WriteAtCurrentPos(buf, rv);
331 }
332 } while (bytes_read <= size);
333
334 sha256->Finish(file_hash->data(), file_hash->size());
335 return bytes_read == size;
336}
337
338bool Component::CopyFingerprintFile(const base::FilePath& src,
339 const base::FilePath& dest) {
340 base::FilePath fingerprint_path(GetFingerprintPath(src));
341 if (base::PathExists(fingerprint_path)) {
342 std::string fingerprint_contents;
343 if (!base::ReadFileToStringWithMaxSize(
344 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
345 return false;
346 }
347
Eric Caruso355e37c2017-03-15 14:31:41 -0700348 if (!IsValidFingerprintFile(fingerprint_contents))
349 return false;
Greg Kerr019d59c2016-11-17 14:28:49 -0800350
351 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
352 return false;
353 }
354 }
355 return true;
356}
357
358// The client inserts manifest.fingerprint into components after unpacking the
359// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
360// for security of the disk image, we are fine with sanity checking the contents
361// and then preserving the unsigned file.
362bool Component::IsValidFingerprintFile(const std::string& contents) {
363 return contents.size() <= 256 &&
364 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
365 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
366 }) == contents.end();
367}
368
369} // namespace imageloader