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