blob: d2e7b5603dbca6ac628ddfab166948f134d550a2 [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) {
92 if (!base::HexStringToBytes(hash_str, bytes)) return false;
93 return bytes->size() == crypto::kSHA256Length;
94}
95
96bool GetAndVerifyTable(const base::FilePath& path,
97 const std::vector<uint8_t>& hash,
98 std::string* out_table) {
99 std::string table;
100 if (!base::ReadFileToStringWithMaxSize(path, &table, kMaximumFilesize)) {
101 return false;
102 }
103
104 std::vector<uint8_t> table_hash(crypto::kSHA256Length);
105 crypto::SHA256HashString(table, table_hash.data(), table_hash.size());
106 if (table_hash != hash) {
107 LOG(ERROR) << "dm-verity table file has the wrong hash.";
108 return false;
109 }
110
111 out_table->assign(table);
112 return true;
113}
114
115} // namespace
116
117Component::Component(const base::FilePath& component_dir)
Greg Kerr7ad73242016-12-06 14:59:20 -0800118 : component_dir_(component_dir), initialized_(false) {}
Greg Kerr019d59c2016-11-17 14:28:49 -0800119
120bool Component::Init(const std::vector<uint8_t>& public_key) {
121 if (initialized_) {
122 NOTREACHED() << "Component already initialized";
123 return false;
124 }
125 initialized_ = LoadManifest(public_key);
126 return initialized_;
127}
128
129const Component::Manifest& Component::manifest() {
130 // If the manifest is accessed without initialization, crash.
131 CHECK(initialized_);
132 return manifest_;
133}
134
Greg Kerr9944e242017-01-26 15:09:31 -0800135bool Component::Mount(HelperProcess* mounter, const base::FilePath& dest_dir) {
Greg Kerr019d59c2016-11-17 14:28:49 -0800136 if (!initialized_) {
137 NOTREACHED() << "Component not initialized";
138 return false;
139 }
140 // Now read the table in and verify the hash.
141 std::string table;
142 if (!GetAndVerifyTable(GetTablePath(component_dir_), manifest_.table_sha256,
143 &table)) {
144 LOG(ERROR) << "Could not read and verify dm-verity table.";
145 return false;
146 }
147
148 base::FilePath image_path(GetImagePath(component_dir_));
149 base::File image(image_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
150 if (!image.IsValid()) {
151 LOG(ERROR) << "Could not open image file.";
152 return false;
153 }
154 base::ScopedFD image_fd(image.TakePlatformFile());
155
Greg Kerr9944e242017-01-26 15:09:31 -0800156 return mounter->SendMountCommand(image_fd.get(), dest_dir.value(), table);
Greg Kerr019d59c2016-11-17 14:28:49 -0800157}
158
159bool Component::ParseManifest() {
160 // Now deserialize the manifest json and read out the rest of the component.
161 int error_code;
162 std::string error_message;
163 JSONStringValueDeserializer deserializer(manifest_raw_);
164 std::unique_ptr<base::Value> value =
165 deserializer.Deserialize(&error_code, &error_message);
166
167 if (!value) {
168 LOG(ERROR) << "Could not deserialize the manifest file. Error "
169 << error_code << ": " << error_message;
170 return false;
171 }
172
173 base::DictionaryValue* manifest_dict = nullptr;
174 if (!value->GetAsDictionary(&manifest_dict)) {
175 LOG(ERROR) << "Could not parse manifest file as JSON.";
176 return false;
177 }
178
179 // This will have to be changed if the manifest version is bumped.
180 int version;
181 if (!manifest_dict->GetInteger(kManifestVersionField, &version)) {
182 LOG(ERROR) << "Could not parse manifest version field from manifest.";
183 return false;
184 }
185 if (version != kCurrentManifestVersion) {
186 LOG(ERROR) << "Unsupported version of the manifest.";
187 return false;
188 }
189 manifest_.manifest_version = version;
190
191 std::string image_hash_str;
192 if (!manifest_dict->GetString(kImageHashField, &image_hash_str)) {
193 LOG(ERROR) << "Could not parse image hash from manifest.";
194 return false;
195 }
196
197 if (!GetSHA256FromString(image_hash_str, &(manifest_.image_sha256))) {
198 LOG(ERROR) << "Could not convert image hash to bytes.";
199 return false;
200 }
201
202 std::string table_hash_str;
203 if (!manifest_dict->GetString(kTableHashField, &table_hash_str)) {
204 LOG(ERROR) << "Could not parse table hash from manifest.";
205 return false;
206 }
207
208 if (!GetSHA256FromString(table_hash_str, &(manifest_.table_sha256))) {
209 LOG(ERROR) << "Could not convert table hash to bytes.";
210 return false;
211 }
212
213 if (!manifest_dict->GetString(kVersionField, &(manifest_.version))) {
214 LOG(ERROR) << "Could not parse component version from manifest.";
215 return false;
216 }
217
218 return true;
219}
220
221bool Component::LoadManifest(const std::vector<uint8_t>& public_key) {
222 if (!base::ReadFileToStringWithMaxSize(GetManifestPath(component_dir_),
223 &manifest_raw_, kMaximumFilesize)) {
224 LOG(ERROR) << "Could not read manifest file.";
225 return false;
226 }
227 if (!base::ReadFileToStringWithMaxSize(GetSignaturePath(component_dir_),
228 &manifest_sig_, kMaximumFilesize)) {
229 LOG(ERROR) << "Could not read signature file.";
230 return false;
231 }
232
233 crypto::SignatureVerifier verifier;
234
235 if (!verifier.VerifyInit(
236 crypto::SignatureVerifier::ECDSA_SHA256,
237 reinterpret_cast<const uint8_t*>(manifest_sig_.data()),
238 base::checked_cast<int>(manifest_sig_.size()), public_key.data(),
239 base::checked_cast<int>(public_key.size()))) {
240 LOG(ERROR) << "Failed to initialize signature verification.";
241 return false;
242 }
243
244 verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(manifest_raw_.data()),
245 base::checked_cast<int>(manifest_raw_.size()));
246
247 if (!verifier.VerifyFinal()) {
248 LOG(ERROR) << "Manifest failed signature verification.";
249 return false;
250 }
251 return ParseManifest();
252}
253
254bool Component::CopyTo(const base::FilePath& dest_dir) {
255 if (!initialized_) {
256 NOTREACHED() << "Component not initialized";
257 return false;
258 }
259
260 if (!WriteFileToDisk(GetManifestPath(dest_dir), manifest_raw_) ||
261 !WriteFileToDisk(GetSignaturePath(dest_dir), manifest_sig_)) {
262 LOG(ERROR) << "Could not write manifest and signature to disk.";
263 return false;
264 }
265
266 base::FilePath table_src(GetTablePath(component_dir_));
267 base::FilePath table_dest(GetTablePath(dest_dir));
268 if (!CopyComponentFile(table_src, table_dest, manifest_.table_sha256)) {
269 LOG(ERROR) << "Could not copy table file.";
270 return false;
271 }
272
273 base::FilePath image_src(GetImagePath(component_dir_));
274 base::FilePath image_dest(GetImagePath(dest_dir));
275 if (!CopyComponentFile(image_src, image_dest, manifest_.image_sha256)) {
276 LOG(ERROR) << "Could not copy image file.";
277 return false;
278 }
279
280 if (!CopyFingerprintFile(component_dir_, dest_dir)) {
281 LOG(ERROR) << "Could not copy manifest.fingerprint file.";
282 return false;
283 }
284
285 return true;
286}
287
288bool Component::CopyComponentFile(const base::FilePath& src,
289 const base::FilePath& dest_path,
290 const std::vector<uint8_t>& expected_hash) {
291 base::File file(src, base::File::FLAG_OPEN | base::File::FLAG_READ);
292 if (!file.IsValid()) return false;
293
294 base::ScopedFD dest(
295 HANDLE_EINTR(open(dest_path.value().c_str(), O_CREAT | O_WRONLY | O_EXCL,
296 kComponentFilePerms)));
297 if (!dest.is_valid()) return false;
298
299 base::File out_file(dest.release());
300 std::unique_ptr<crypto::SecureHash> sha256(
301 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
302
303 std::vector<uint8_t> file_hash(crypto::kSHA256Length);
304 if (!ReadHashAndCopyFile(&file, &file_hash, &out_file)) {
305 LOG(ERROR) << "Failed to read image file.";
306 return false;
307 }
308
309 if (expected_hash != file_hash) {
310 LOG(ERROR) << "Image is corrupt or modified.";
311 return false;
312 }
313 return true;
314}
315
316bool Component::ReadHashAndCopyFile(base::File* file,
317 std::vector<uint8_t>* file_hash,
318 base::File* out_file) {
319 std::unique_ptr<crypto::SecureHash> sha256(
320 crypto::SecureHash::Create(crypto::SecureHash::SHA256));
321 int size = file->GetLength();
322 if (size <= 0) return false;
323
324 int rv = 0, bytes_read = 0;
325 char buf[4096];
326 do {
327 int remaining = size - bytes_read;
328 int bytes_to_read =
329 std::min(remaining, base::checked_cast<int>(sizeof(buf)));
330
331 rv = file->ReadAtCurrentPos(buf, bytes_to_read);
332 if (rv <= 0) break;
333
334 bytes_read += rv;
335 sha256->Update(buf, rv);
336 if (out_file) {
337 out_file->WriteAtCurrentPos(buf, rv);
338 }
339 } while (bytes_read <= size);
340
341 sha256->Finish(file_hash->data(), file_hash->size());
342 return bytes_read == size;
343}
344
345bool Component::CopyFingerprintFile(const base::FilePath& src,
346 const base::FilePath& dest) {
347 base::FilePath fingerprint_path(GetFingerprintPath(src));
348 if (base::PathExists(fingerprint_path)) {
349 std::string fingerprint_contents;
350 if (!base::ReadFileToStringWithMaxSize(
351 fingerprint_path, &fingerprint_contents, kMaximumFilesize)) {
352 return false;
353 }
354
355 if (!IsValidFingerprintFile(fingerprint_contents)) return false;
356
357 if (!WriteFileToDisk(GetFingerprintPath(dest), fingerprint_contents)) {
358 return false;
359 }
360 }
361 return true;
362}
363
364// The client inserts manifest.fingerprint into components after unpacking the
365// CRX. The file is used for delta updates. Since Chrome OS doesn't rely on it
366// for security of the disk image, we are fine with sanity checking the contents
367// and then preserving the unsigned file.
368bool Component::IsValidFingerprintFile(const std::string& contents) {
369 return contents.size() <= 256 &&
370 std::find_if_not(contents.begin(), contents.end(), [](char ch) {
371 return base::IsAsciiAlpha(ch) || base::IsAsciiDigit(ch) || ch == '.';
372 }) == contents.end();
373}
374
375} // namespace imageloader