NaCl: Update revision in DEPS, r13724 -> r13730
[chromium-blink-merge.git] / extensions / browser / verified_contents.cc
blob47c94662a166ca18d999ef9a32992318d9b4e9ad
1 // Copyright 2014 The Chromium 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.
5 #include "extensions/browser/verified_contents.h"
7 #include "base/base64.h"
8 #include "base/files/file_util.h"
9 #include "base/json/json_reader.h"
10 #include "base/strings/string_util.h"
11 #include "base/values.h"
12 #include "components/crx_file/id_util.h"
13 #include "crypto/signature_verifier.h"
14 #include "extensions/common/extension.h"
16 using base::DictionaryValue;
17 using base::ListValue;
18 using base::Value;
20 namespace {
22 // Note: this structure is an ASN.1 which encodes the algorithm used with its
23 // parameters. The signature algorithm is "RSA256" aka "RSASSA-PKCS-v1_5 using
24 // SHA-256 hash algorithm". This is defined in PKCS #1 (RFC 3447).
25 // It is encoding: { OID sha256WithRSAEncryption PARAMETERS NULL }
26 const uint8 kSignatureAlgorithm[15] = {0x30, 0x0d, 0x06, 0x09, 0x2a,
27 0x86, 0x48, 0x86, 0xf7, 0x0d,
28 0x01, 0x01, 0x0b, 0x05, 0x00};
30 const char kBlockSizeKey[] = "block_size";
31 const char kContentHashesKey[] = "content_hashes";
32 const char kDescriptionKey[] = "description";
33 const char kFilesKey[] = "files";
34 const char kFormatKey[] = "format";
35 const char kHashBlockSizeKey[] = "hash_block_size";
36 const char kHeaderKidKey[] = "header.kid";
37 const char kItemIdKey[] = "item_id";
38 const char kItemVersionKey[] = "item_version";
39 const char kPathKey[] = "path";
40 const char kPayloadKey[] = "payload";
41 const char kProtectedKey[] = "protected";
42 const char kRootHashKey[] = "root_hash";
43 const char kSignatureKey[] = "signature";
44 const char kSignaturesKey[] = "signatures";
45 const char kSignedContentKey[] = "signed_content";
46 const char kTreeHashPerFile[] = "treehash per file";
47 const char kTreeHash[] = "treehash";
48 const char kWebstoreKId[] = "webstore";
50 // Helper function to iterate over a list of dictionaries, returning the
51 // dictionary that has |key| -> |value| in it, if any, or NULL.
52 DictionaryValue* FindDictionaryWithValue(const ListValue* list,
53 std::string key,
54 std::string value) {
55 for (ListValue::const_iterator i = list->begin(); i != list->end(); ++i) {
56 if (!(*i)->IsType(Value::TYPE_DICTIONARY))
57 continue;
58 DictionaryValue* dictionary = static_cast<DictionaryValue*>(*i);
59 std::string found_value;
60 if (dictionary->GetString(key, &found_value) && found_value == value)
61 return dictionary;
63 return NULL;
66 } // namespace
68 namespace extensions {
70 // static
71 bool VerifiedContents::FixupBase64Encoding(std::string* input) {
72 for (std::string::iterator i = input->begin(); i != input->end(); ++i) {
73 if (*i == '-')
74 *i = '+';
75 else if (*i == '_')
76 *i = '/';
78 switch (input->size() % 4) {
79 case 0:
80 break;
81 case 2:
82 input->append("==");
83 break;
84 case 3:
85 input->append("=");
86 break;
87 default:
88 return false;
90 return true;
93 VerifiedContents::VerifiedContents(const uint8* public_key, int public_key_size)
94 : public_key_(public_key),
95 public_key_size_(public_key_size),
96 valid_signature_(false), // Guilty until proven innocent.
97 block_size_(0) {
100 VerifiedContents::~VerifiedContents() {
103 // The format of the payload json is:
104 // {
105 // "item_id": "<extension id>",
106 // "item_version": "<extension version>",
107 // "content_hashes": [
108 // {
109 // "block_size": 4096,
110 // "hash_block_size": 4096,
111 // "format": "treehash",
112 // "files": [
113 // {
114 // "path": "foo/bar",
115 // "root_hash": "<base64url encoded bytes>"
116 // },
117 // ...
118 // ]
119 // }
120 // ]
121 // }
122 bool VerifiedContents::InitFrom(const base::FilePath& path,
123 bool ignore_invalid_signature) {
124 std::string payload;
125 if (!GetPayload(path, &payload, ignore_invalid_signature))
126 return false;
128 scoped_ptr<base::Value> value(base::JSONReader::Read(payload));
129 if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY))
130 return false;
131 DictionaryValue* dictionary = static_cast<DictionaryValue*>(value.get());
133 std::string item_id;
134 if (!dictionary->GetString(kItemIdKey, &item_id) ||
135 !crx_file::id_util::IdIsValid(item_id))
136 return false;
137 extension_id_ = item_id;
139 std::string version_string;
140 if (!dictionary->GetString(kItemVersionKey, &version_string))
141 return false;
142 version_ = base::Version(version_string);
143 if (!version_.IsValid())
144 return false;
146 ListValue* hashes_list = NULL;
147 if (!dictionary->GetList(kContentHashesKey, &hashes_list))
148 return false;
150 for (size_t i = 0; i < hashes_list->GetSize(); i++) {
151 DictionaryValue* hashes = NULL;
152 if (!hashes_list->GetDictionary(i, &hashes))
153 return false;
154 std::string format;
155 if (!hashes->GetString(kFormatKey, &format) || format != kTreeHash)
156 continue;
158 int block_size = 0;
159 int hash_block_size = 0;
160 if (!hashes->GetInteger(kBlockSizeKey, &block_size) ||
161 !hashes->GetInteger(kHashBlockSizeKey, &hash_block_size))
162 return false;
163 block_size_ = block_size;
165 // We don't support using a different block_size and hash_block_size at
166 // the moment.
167 if (block_size_ != hash_block_size)
168 return false;
170 ListValue* files = NULL;
171 if (!hashes->GetList(kFilesKey, &files))
172 return false;
174 for (size_t j = 0; j < files->GetSize(); j++) {
175 DictionaryValue* data = NULL;
176 if (!files->GetDictionary(j, &data))
177 return false;
178 std::string file_path_string;
179 std::string encoded_root_hash;
180 std::string root_hash;
181 if (!data->GetString(kPathKey, &file_path_string) ||
182 !base::IsStringUTF8(file_path_string) ||
183 !data->GetString(kRootHashKey, &encoded_root_hash) ||
184 !FixupBase64Encoding(&encoded_root_hash) ||
185 !base::Base64Decode(encoded_root_hash, &root_hash))
186 return false;
187 base::FilePath file_path =
188 base::FilePath::FromUTF8Unsafe(file_path_string);
189 root_hashes_[file_path] = std::string();
190 root_hashes_[file_path].swap(root_hash);
193 break;
195 return true;
198 const std::string* VerifiedContents::GetTreeHashRoot(
199 const base::FilePath& relative_path) {
200 std::map<base::FilePath, std::string>::const_iterator i =
201 root_hashes_.find(relative_path.NormalizePathSeparatorsTo('/'));
202 if (i == root_hashes_.end())
203 return NULL;
204 return &i->second;
207 // We're loosely following the "JSON Web Signature" draft spec for signing
208 // a JSON payload:
210 // http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-26
212 // The idea is that you have some JSON that you want to sign, so you
213 // base64-encode that and put it as the "payload" field in a containing
214 // dictionary. There might be signatures of it done with multiple
215 // algorithms/parameters, so the payload is followed by a list of one or more
216 // signature sections. Each signature section specifies the
217 // algorithm/parameters in a JSON object which is base64url encoded into one
218 // string and put into a "protected" field in the signature. Then the encoded
219 // "payload" and "protected" strings are concatenated with a "." in between
220 // them and those bytes are signed and the resulting signature is base64url
221 // encoded and placed in the "signature" field. To allow for extensibility, we
222 // wrap this, so we can include additional kinds of payloads in the future. E.g.
223 // [
224 // {
225 // "description": "treehash per file",
226 // "signed_content": {
227 // "payload": "<base64url encoded JSON to sign>",
228 // "signatures": [
229 // {
230 // "protected": "<base64url encoded JSON with algorithm/parameters>",
231 // "header": {
232 // <object with metadata about this signature, eg a key identifier>
233 // }
234 // "signature":
235 // "<base64url encoded signature over payload || . || protected>"
236 // },
237 // ... <zero or more additional signatures> ...
238 // ]
239 // }
240 // }
241 // ]
242 // There might be both a signature generated with a webstore private key and a
243 // signature generated with the extension's private key - for now we only
244 // verify the webstore one (since the id is in the payload, so we can trust
245 // that it is for a given extension), but in the future we may validate using
246 // the extension's key too (eg for non-webstore hosted extensions such as
247 // enterprise installs).
248 bool VerifiedContents::GetPayload(const base::FilePath& path,
249 std::string* payload,
250 bool ignore_invalid_signature) {
251 std::string contents;
252 if (!base::ReadFileToString(path, &contents))
253 return false;
254 scoped_ptr<base::Value> value(base::JSONReader::Read(contents));
255 if (!value.get() || !value->IsType(Value::TYPE_LIST))
256 return false;
257 ListValue* top_list = static_cast<ListValue*>(value.get());
259 // Find the "treehash per file" signed content, e.g.
260 // [
261 // {
262 // "description": "treehash per file",
263 // "signed_content": {
264 // "signatures": [ ... ],
265 // "payload": "..."
266 // }
267 // }
268 // ]
269 DictionaryValue* dictionary =
270 FindDictionaryWithValue(top_list, kDescriptionKey, kTreeHashPerFile);
271 DictionaryValue* signed_content = NULL;
272 if (!dictionary ||
273 !dictionary->GetDictionaryWithoutPathExpansion(kSignedContentKey,
274 &signed_content)) {
275 return false;
278 ListValue* signatures = NULL;
279 if (!signed_content->GetList(kSignaturesKey, &signatures))
280 return false;
282 DictionaryValue* signature_dict =
283 FindDictionaryWithValue(signatures, kHeaderKidKey, kWebstoreKId);
284 if (!signature_dict)
285 return false;
287 std::string protected_value;
288 std::string encoded_signature;
289 std::string decoded_signature;
290 if (!signature_dict->GetString(kProtectedKey, &protected_value) ||
291 !signature_dict->GetString(kSignatureKey, &encoded_signature) ||
292 !FixupBase64Encoding(&encoded_signature) ||
293 !base::Base64Decode(encoded_signature, &decoded_signature))
294 return false;
296 std::string encoded_payload;
297 if (!signed_content->GetString(kPayloadKey, &encoded_payload))
298 return false;
300 valid_signature_ =
301 VerifySignature(protected_value, encoded_payload, decoded_signature);
302 if (!valid_signature_ && !ignore_invalid_signature)
303 return false;
305 if (!FixupBase64Encoding(&encoded_payload) ||
306 !base::Base64Decode(encoded_payload, payload))
307 return false;
309 return true;
312 bool VerifiedContents::VerifySignature(const std::string& protected_value,
313 const std::string& payload,
314 const std::string& signature_bytes) {
315 crypto::SignatureVerifier signature_verifier;
316 if (!signature_verifier.VerifyInit(
317 kSignatureAlgorithm,
318 sizeof(kSignatureAlgorithm),
319 reinterpret_cast<const uint8*>(signature_bytes.data()),
320 signature_bytes.size(),
321 public_key_,
322 public_key_size_)) {
323 VLOG(1) << "Could not verify signature - VerifyInit failure";
324 return false;
327 signature_verifier.VerifyUpdate(
328 reinterpret_cast<const uint8*>(protected_value.data()),
329 protected_value.size());
331 std::string dot(".");
332 signature_verifier.VerifyUpdate(reinterpret_cast<const uint8*>(dot.data()),
333 dot.size());
335 signature_verifier.VerifyUpdate(
336 reinterpret_cast<const uint8*>(payload.data()), payload.size());
338 if (!signature_verifier.VerifyFinal()) {
339 VLOG(1) << "Could not verify signature - VerifyFinal failure";
340 return false;
342 return true;
345 } // namespace extensions