Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(117)

Side by Side Diff: content/renderer/webcrypto/webcrypto_impl.cc

Issue 25906002: [webcrypto] Add JWK import for HMAC and AES-CBC key. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: rebase Created 7 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/renderer/webcrypto/webcrypto_impl.h" 5 #include "content/renderer/webcrypto/webcrypto_impl.h"
6 6
7 #include <algorithm>
8 #include <functional>
9 #include <map>
10 #include "base/json/json_reader.h"
11 #include "base/lazy_instance.h"
7 #include "base/logging.h" 12 #include "base/logging.h"
8 #include "base/memory/scoped_ptr.h" 13 #include "base/memory/scoped_ptr.h"
9 #include "third_party/WebKit/public/platform/WebArrayBuffer.h" 14 #include "base/strings/string_piece.h"
15 #include "base/values.h"
16 #include "content/renderer/webcrypto/webcrypto_util.h"
10 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h" 17 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
18 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
11 #include "third_party/WebKit/public/platform/WebCryptoKey.h" 19 #include "third_party/WebKit/public/platform/WebCryptoKey.h"
12 20
13 namespace content { 21 namespace content {
14 22
23 namespace {
24
25 // Binds a specific key length value to a compatible factory function.
26 typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncWithOneShortArg)(
27 unsigned short);
28 template <AlgFactoryFuncWithOneShortArg func, unsigned short key_length>
29 WebKit::WebCryptoAlgorithm BindAlgFactoryWithKeyLen() {
30 return func(key_length);
31 }
32
33 // Binds a WebCryptoAlgorithmId value to a compatible factory function.
34 typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncWithWebCryptoAlgIdArg)(
35 WebKit::WebCryptoAlgorithmId);
36 template <AlgFactoryFuncWithWebCryptoAlgIdArg func,
37 WebKit::WebCryptoAlgorithmId algorithm_id>
38 WebKit::WebCryptoAlgorithm BindAlgFactoryAlgorithmId() {
39 return func(algorithm_id);
40 }
41
42 // Defines a map between a JWK 'alg' string ID and a corresponding Web Crypto
43 // factory function.
44 typedef WebKit::WebCryptoAlgorithm (*AlgFactoryFuncNoArgs)();
45 typedef std::map<std::string, AlgFactoryFuncNoArgs> JwkAlgFactoryMap;
46
47 class JwkAlgorithmFactoryMap {
48 public:
49 JwkAlgorithmFactoryMap() {
50 map_["HS256"] =
51 &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 256>;
52 map_["HS256"] =
53 &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 256>;
54 map_["HS384"] =
55 &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 384>;
56 map_["HS384"] =
57 &BindAlgFactoryWithKeyLen<CreateHmacAlgorithmByDigestLen, 512>;
58 map_["RS256"] =
59 &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
60 WebKit::WebCryptoAlgorithmIdSha256>;
61 map_["RS384"] =
62 &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
63 WebKit::WebCryptoAlgorithmIdSha384>;
64 map_["RS512"] =
65 &BindAlgFactoryAlgorithmId<CreateRsaSsaAlgorithm,
66 WebKit::WebCryptoAlgorithmIdSha512>;
67 map_["RSA1_5"] = &CreateRsaEsAlgorithm;
68 map_["RSA-OAEP"] =
69 &BindAlgFactoryAlgorithmId<CreateRsaOaepAlgorithm,
70 WebKit::WebCryptoAlgorithmIdSha1>;
71 map_["A128KW"] = &WebKit::WebCryptoAlgorithm::createNull;
72 map_["A256KW"] = &WebKit::WebCryptoAlgorithm::createNull;
73 map_["A128GCM"] =
74 &BindAlgFactoryWithKeyLen<CreateAesGcmKeyGenAlgorithm, 256>;
eroman 2013/11/01 20:59:58 Shouldn't this be 128?
padolph 2013/11/01 23:08:50 Done.
75 map_["A256GCM"] =
76 &BindAlgFactoryWithKeyLen<CreateAesGcmKeyGenAlgorithm, 256>;
77 map_["A128CBC"] =
78 &BindAlgFactoryWithKeyLen<CreateAesCbcKeyGenAlgorithm, 128>;
79 map_["A256CBC"] =
80 &BindAlgFactoryWithKeyLen<CreateAesCbcKeyGenAlgorithm, 256>;
81 map_["A384CBC"] =
82 &BindAlgFactoryWithKeyLen<CreateAesCbcKeyGenAlgorithm, 384>;
83 map_["A512CBC"] =
84 &BindAlgFactoryWithKeyLen<CreateAesCbcKeyGenAlgorithm, 512>;
85 }
86 WebKit::WebCryptoAlgorithm CreateAlgorithmFromName(
eroman 2013/11/01 20:59:58 [optional] Can you add a newlinea above this?
padolph 2013/11/01 23:08:50 Done.
87 const std::string& alg_id) {
88 const JwkAlgFactoryMap::const_iterator pos = map_.find(alg_id);
89 if (pos == map_.end())
90 return WebKit::WebCryptoAlgorithm::createNull();
91 return pos->second();
92 }
93
94 private:
95 JwkAlgFactoryMap map_;
96 };
97 base::LazyInstance<JwkAlgorithmFactoryMap> jwk_alg_factory =
eroman 2013/11/01 20:59:58 ditto on newline.
padolph 2013/11/01 23:08:50 Done.
98 LAZY_INSTANCE_INITIALIZER;
99
100 // TODO(padolph): Verify this logic is sufficient to judge algorithm
101 // "consistency" for JWK import, and for all supported algorithms.
102 bool WebCryptoAlgorithmsConsistent(const WebKit::WebCryptoAlgorithm& lhs,
eroman 2013/11/01 20:59:58 Rather than "lhs" and "rhs" I suggest something mo
padolph 2013/11/01 23:08:50 Done.
103 const WebKit::WebCryptoAlgorithm& rhs) {
104 DCHECK(!lhs.isNull());
105 DCHECK(!rhs.isNull());
106 if (lhs.id() == rhs.id()) {
107 if (lhs.id() == WebKit::WebCryptoAlgorithmIdHmac ||
108 lhs.id() == WebKit::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 ||
109 lhs.id() == WebKit::WebCryptoAlgorithmIdRsaOaep) {
110 if (WebCryptoAlgorithmsConsistent(GetInnerHashAlgorithm(lhs),
111 GetInnerHashAlgorithm(rhs))) {
112 return true;
113 }
114 return false;
115 }
116 return true;
117 }
118 return false;
119 }
120
121 } // namespace
122
15 WebCryptoImpl::WebCryptoImpl() { 123 WebCryptoImpl::WebCryptoImpl() {
16 Init(); 124 Init();
17 } 125 }
18 126
19 // static 127 WebCryptoImpl::~WebCryptoImpl() {}
20 // TODO(eroman): This works by re-allocating a new buffer. It would be better if
21 // the WebArrayBuffer could just be truncated instead.
22 void WebCryptoImpl::ShrinkBuffer(
23 WebKit::WebArrayBuffer* buffer,
24 unsigned new_size) {
25 DCHECK_LE(new_size, buffer->byteLength());
26
27 if (new_size == buffer->byteLength())
28 return;
29
30 WebKit::WebArrayBuffer new_buffer =
31 WebKit::WebArrayBuffer::create(new_size, 1);
32 DCHECK(!new_buffer.isNull());
33 memcpy(new_buffer.data(), buffer->data(), new_size);
34 *buffer = new_buffer;
35 }
36 128
37 // static 129 // static
38 // TODO(eroman): Expose functionality in Blink instead. 130 // TODO(eroman): Expose functionality in Blink instead.
39 WebKit::WebCryptoKey WebCryptoImpl::NullKey() { 131 WebKit::WebCryptoKey WebCryptoImpl::NullKey() {
40 // Needs a non-null algorithm to succeed. 132 // Needs a non-null algorithm to succeed.
41 return WebKit::WebCryptoKey::create( 133 return WebKit::WebCryptoKey::create(
42 NULL, WebKit::WebCryptoKeyTypeSecret, false, 134 NULL, WebKit::WebCryptoKeyTypeSecret, false,
43 WebKit::WebCryptoAlgorithm::adoptParamsAndCreate( 135 WebKit::WebCryptoAlgorithm::adoptParamsAndCreate(
44 WebKit::WebCryptoAlgorithmIdAesGcm, NULL), 0); 136 WebKit::WebCryptoAlgorithmIdAesGcm, NULL), 0);
45 } 137 }
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
108 200
109 void WebCryptoImpl::importKey( 201 void WebCryptoImpl::importKey(
110 WebKit::WebCryptoKeyFormat format, 202 WebKit::WebCryptoKeyFormat format,
111 const unsigned char* key_data, 203 const unsigned char* key_data,
112 unsigned key_data_size, 204 unsigned key_data_size,
113 const WebKit::WebCryptoAlgorithm& algorithm_or_null, 205 const WebKit::WebCryptoAlgorithm& algorithm_or_null,
114 bool extractable, 206 bool extractable,
115 WebKit::WebCryptoKeyUsageMask usage_mask, 207 WebKit::WebCryptoKeyUsageMask usage_mask,
116 WebKit::WebCryptoResult result) { 208 WebKit::WebCryptoResult result) {
117 WebKit::WebCryptoKey key = NullKey(); 209 WebKit::WebCryptoKey key = NullKey();
118 if (!ImportKeyInternal(format, 210 if (format == WebKit::WebCryptoKeyFormatJwk) {
119 key_data, 211 if (!ImportKeyJwk(key_data,
120 key_data_size, 212 key_data_size,
121 algorithm_or_null, 213 algorithm_or_null,
122 extractable, 214 extractable,
123 usage_mask, 215 usage_mask,
124 &key)) { 216 &key)) {
125 result.completeWithError(); 217 result.completeWithError();
126 return; 218 }
219 } else {
220 if (!ImportKeyInternal(format,
221 key_data,
222 key_data_size,
223 algorithm_or_null,
224 extractable,
225 usage_mask,
226 &key)) {
227 result.completeWithError();
228 }
127 } 229 }
128 DCHECK(key.handle()); 230 DCHECK(key.handle());
129 DCHECK(!key.algorithm().isNull()); 231 DCHECK(!key.algorithm().isNull());
130 DCHECK_EQ(extractable, key.extractable()); 232 DCHECK_EQ(extractable, key.extractable());
131 result.completeWithKey(key); 233 result.completeWithKey(key);
132 } 234 }
133 235
134 void WebCryptoImpl::sign( 236 void WebCryptoImpl::sign(
135 const WebKit::WebCryptoAlgorithm& algorithm, 237 const WebKit::WebCryptoAlgorithm& algorithm,
136 const WebKit::WebCryptoKey& key, 238 const WebKit::WebCryptoKey& key,
(...skipping 25 matching lines...) Expand all
162 signature_size, 264 signature_size,
163 data, 265 data,
164 data_size, 266 data_size,
165 &signature_match)) { 267 &signature_match)) {
166 result.completeWithError(); 268 result.completeWithError();
167 } else { 269 } else {
168 result.completeWithBoolean(signature_match); 270 result.completeWithBoolean(signature_match);
169 } 271 }
170 } 272 }
171 273
274 bool WebCryptoImpl::ImportKeyJwk(
275 const unsigned char* key_data,
276 unsigned key_data_size,
277 const WebKit::WebCryptoAlgorithm& input_algorithm,
278 bool extractable,
279 WebKit::WebCryptoKeyUsageMask usage_mask,
280 WebKit::WebCryptoKey* key) {
281
282 // JSON Web Key Format (JWK)
283 // http://tools.ietf.org/html/draft-ietf-jose-json-web-key-16
284 // TODO(padolph): Not all possible values are handled by this code right now
285 //
286 // A JWK is a simple JSON dictionary with the following entries
287 // - "kty" (Key Type) Parameter, REQUIRED
288 // - <kty-specific parameters, see below>, REQUIRED
289 // - "use" (Key Use) Parameter, OPTIONAL
290 // - "alg" (Algorithm) Parameter, OPTIONAL
291 // - "extractable" (Key Exportability), OPTIONAL [NOTE: not yet part of JOSE]
eroman 2013/11/01 20:59:58 Is there a bug number that can be linked to here?
padolph 2013/11/01 23:08:50 Not that I know of. Do you know how we can follow
292 // (all other entries are ignored)
293 //
294 // Input key_data contains the JWK. To build a Web Crypto Key, the JWK values
295 // are parsed out and used as follows:
296 // Web Crypto Key type <-- (deduced)
297 // Web Crypto Key extractable <-- extractable
298 // Web Crypto Key algorithm <-- alg
299 // Web Crypto Key keyUsage <-- usage
300 // Web Crypto Key keying material <-- kty-specific parameters
301 //
302 // Values for each entry are case-sensitive and defined in
303 // http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16.
304 // Note that not all values specified by JOSE are handled by this code. Only
305 // handled values are listed.
306 // - kty (Key Type)
307 // +-------+--------------------------------------------------------------+
308 // | "RSA" | RSA [RFC3447] |
309 // | "oct" | Octet sequence (used to represent symmetric keys) |
310 // +-------+--------------------------------------------------------------+
311 // - use (Key Use)
312 // +-------+--------------------------------------------------------------+
313 // | "enc" | encrypt and decrypt operations |
314 // | "sig" | sign and verify (MAC) operations |
315 // | "wrap"| key wrap and unwrap [not yet part of JOSE] |
316 // +-------+--------------------------------------------------------------+
317 // - extractable (Key Exportability)
318 // +-------+--------------------------------------------------------------+
319 // | true | Key may be exported from the trusted environment |
320 // | false | Key cannot exit the trusted environment |
321 // +-------+--------------------------------------------------------------+
322 // - alg (Algorithm)
323 // See http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-16
324 // +--------------+-------------------------------------------------------+
325 // | Digital Signature or MAC Algorithm |
326 // +--------------+-------------------------------------------------------+
327 // | "HS256" | HMAC using SHA-256 hash algorithm |
328 // | "HS384" | HMAC using SHA-384 hash algorithm |
329 // | "HS512" | HMAC using SHA-512 hash algorithm |
330 // | "RS256" | RSASSA using SHA-256 hash algorithm |
331 // | "RS384" | RSASSA using SHA-384 hash algorithm |
332 // | "RS512" | RSASSA using SHA-512 hash algorithm |
333 // +--------------+-------------------------------------------------------|
334 // | Key Management Algorithm |
335 // +--------------+-------------------------------------------------------+
336 // | "RSA1_5" | RSAES-PKCS1-V1_5 [RFC3447] |
337 // | "RSA-OAEP" | RSAES using Optimal Asymmetric Encryption Padding |
338 // | | (OAEP) [RFC3447], with the default parameters |
339 // | | specified by RFC3447 in Section A.2.1 |
340 // | "A128KW" | Advanced Encryption Standard (AES) Key Wrap Algorithm |
341 // | | [RFC3394] using 128 bit keys |
342 // | "A256KW" | AES Key Wrap Algorithm using 256 bit keys |
343 // | "A128GCM" | AES in Galois/Counter Mode (GCM) [NIST.800-38D] using |
344 // | | 128 bit keys |
345 // | "A256GCM" | AES GCM using 256 bit keys |
346 // | "A128CBC" | AES in Cipher Block Chaining Mode (CBC) with PKCS #5 |
347 // | | padding [NIST.800-38A] [not yet part of JOSE] |
348 // | "A256CBC" | AES CBC using 256 bit keys [not yet part of JOSE] |
349 // | "A384CBC" | AES CBC using 384 bit keys [not yet part of JOSE] |
350 // | "A512CBC" | AES CBC using 512 bit keys [not yet part of JOSE] |
351 // +--------------+-------------------------------------------------------+
352 //
353 // kty-specific parameters
354 // The value of kty determines the type and content of the keying material
355 // carried in the JWK to be imported. Currently only two possibilities are
356 // supported: a raw key or an RSA public key. RSA private keys are not
357 // supported because typical applications seldom need to import a private key,
358 // and the large number of JWK parameters required to describe one.
359 // - kty == "oct" (symmetric or other raw key)
360 // +-------+--------------------------------------------------------------+
361 // | "k" | Contains the value of the symmetric (or other single-valued) |
362 // | | key. It is represented as the base64url encoding of the |
363 // | | octet sequence containing the key value. |
364 // +-------+--------------------------------------------------------------+
365 // - kty == "RSA" (RSA public key)
366 // +-------+--------------------------------------------------------------+
367 // | "n" | Contains the modulus value for the RSA public key. It is |
368 // | | represented as the base64url encoding of the value's |
369 // | | unsigned big endian representation as an octet sequence. |
370 // +-------+--------------------------------------------------------------+
371 // | "e" | Contains the exponent value for the RSA public key. It is |
372 // | | represented as the base64url encoding of the value's |
373 // | | unsigned big endian representation as an octet sequence. |
374 // +-------+--------------------------------------------------------------+
375 //
376 // Conflict resolution
eroman 2013/11/01 20:59:58 Just wanted to re-iterate, I found the comments fo
padolph 2013/11/01 23:08:50 :-) They did take a while to type in. I needed a c
377 // The input_algorithm, extractable, and usage_mask input parameters may be
378 // different from similar values inside the JWK. The Web Crypto spec says that
379 // if a JWK value is present but is inconsistent with the input value, it is
380 // an error and the operation must fail. Conversely, should they be missing
381 // from the JWK, the input values should be used to "fill-in" for the
382 // corresponding JWK-optional values (use, alg, extractable).
383
384 DCHECK(key);
385
386 // Parse the incoming JWK JSON.
387 if (!key_data || !key_data_size)
388 return false;
389 base::StringPiece json_string(reinterpret_cast<const char*>(key_data),
390 key_data_size);
391 scoped_ptr<base::Value> value(base::JSONReader::Read(json_string));
392 // Note, bare pointer dict_value is ok since it points into scoped value.
393 base::DictionaryValue* dict_value = NULL;
394 if (!value.get() || !value->GetAsDictionary(&dict_value) || !dict_value)
395 return false;
396
397 // JWK "kty". Exit early if this required JWK parameter is missing.
398 std::string jwk_kty_value;
399 if (!dict_value->GetString("kty", &jwk_kty_value))
400 return false;
401
402 // JWK "extractable" (optional) --> extractable parameter
403 bool jwk_extractable_value;
eroman 2013/11/01 20:59:58 Paranoia: I would hate for future code to referenc
padolph 2013/11/01 23:08:50 Done.
404 if (dict_value->GetBoolean("extractable", &jwk_extractable_value)) {
eroman 2013/11/01 20:59:58 Should we be doing stronger error checking here?
Ryan Sleevi 2013/11/01 22:45:14 This, I think, highlights some of the issues with
padolph 2013/11/01 23:08:50 What is the best way to move this forward?
405 if (jwk_extractable_value != extractable)
406 return false;
407 }
408
409 // JWK "alg" (optional) --> algorithm parameter
410 // Note: input algorithm is also optional, so we have six cases to handle.
411 // 1. JWK alg present but unrecognized: error
412 // 2. JWK alg valid AND input algorithm isNull: use JWK value
413 // 3. JWK alg valid AND input algorithm specified, but JWK value
414 // inconsistent with input: error
415 // 4. JWK alg valid AND input algorithm specified, both consistent: use
416 // input value (because it has potentially more details)
417 // 5. JWK alg missing AND input algorithm isNull: error
418 // 6. JWK alg missing AND input algorithm specified: use input value
419 WebKit::WebCryptoAlgorithm algorithm =
420 WebKit::WebCryptoAlgorithm::createNull();
421 std::string jwk_alg_value;
422 if (dict_value->GetString("alg", &jwk_alg_value)) {
423 // JWK alg present
424 const WebKit::WebCryptoAlgorithm jwk_algorithm =
425 jwk_alg_factory.Get().CreateAlgorithmFromName(jwk_alg_value);
426 if (jwk_algorithm.isNull()) {
427 // JWK alg unrecognized
428 return false; // case 1
429 }
430 // JWK alg valid
431 if (input_algorithm.isNull()) {
432 // input algorithm not specified
433 algorithm = jwk_algorithm; // case 2
434 } else {
435 // input algorithm specified
436 if (!WebCryptoAlgorithmsConsistent(jwk_algorithm, input_algorithm))
437 return false; // case 3
438 algorithm = input_algorithm; // case 4
439 }
440 } else {
441 // JWK alg missing
442 if (input_algorithm.isNull())
443 return false; // case 5
444 algorithm = input_algorithm; // case 6
445 }
446
eroman 2013/11/01 20:59:58 Purely for readability, I suggest adding here:
padolph 2013/11/01 23:08:50 Done.
447 // JWK "use" (optional) --> usage_mask parameter
448 std::string jwk_use_value;
449 if (dict_value->GetString("use", &jwk_use_value)) {
450 unsigned jwk_usage_mask;
eroman 2013/11/01 20:59:58 Please use the type as WebKit::WebCryptoKeyUsageMa
padolph 2013/11/01 23:08:50 Done.
451 if (jwk_use_value == "enc") {
452 jwk_usage_mask =
453 WebKit::WebCryptoKeyUsageEncrypt | WebKit::WebCryptoKeyUsageDecrypt;
454 } else if (jwk_use_value == "sig") {
455 jwk_usage_mask =
456 WebKit::WebCryptoKeyUsageSign | WebKit::WebCryptoKeyUsageVerify;
457 } else if (jwk_use_value == "wrap") {
458 jwk_usage_mask =
459 WebKit::WebCryptoKeyUsageWrapKey | WebKit::WebCryptoKeyUsageUnwrapKey;
460 } else {
461 return false;
462 }
463 if ((jwk_usage_mask & usage_mask) != usage_mask) {
eroman 2013/11/01 20:59:58 Side comment (on spec): having to duplicate specif
padolph 2013/11/01 23:08:50 I totally agree. Especially if this JWK comes from
464 // A usage_mask must be a subset of jwk_usage_mask.
465 return false;
466 }
467 }
468
469 // JWK keying material --> ImportKeyInternal()
470 if (jwk_kty_value == "oct") {
471 std::string jwk_k_value_url64;
472 if (!dict_value->GetString("k", &jwk_k_value_url64))
473 return false;
474 std::string jwk_k_value;
475 if (!Base64DecodeUrlSafe(jwk_k_value_url64, &jwk_k_value) ||
476 !jwk_k_value.size()) {
477 return false;
478 }
479 if (!ImportKeyInternal(WebKit::WebCryptoKeyFormatRaw,
480 reinterpret_cast<const uint8*>(jwk_k_value.data()),
481 jwk_k_value.size(),
482 algorithm,
483 extractable,
484 usage_mask,
485 key)) {
486 return false;
eroman 2013/11/01 20:59:58 What do you think about making this: return Impor
padolph 2013/11/01 23:08:50 Done.
487 }
488 } else if (jwk_kty_value == "RSA") {
489 // TODO(padolph): JWK import RSA public key
490 return false;
491 } else {
492 return false;
493 }
494
495 return true;
496 }
497
172 } // namespace content 498 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698