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 "content/child/webcrypto/platform_crypto.h"
14 #include "base/lazy_instance.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "content/child/webcrypto/crypto_data.h"
18 #include "content/child/webcrypto/status.h"
19 #include "content/child/webcrypto/webcrypto_util.h"
20 #include "crypto/nss_util.h"
21 #include "crypto/scoped_nss_types.h"
22 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
23 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
24 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
31 // At the time of this writing:
32 // * Windows and Mac builds ship with their own copy of NSS (3.15+)
33 // * Linux builds use the system's libnss, which is 3.14 on Debian (but 3.15+
36 // Since NSS provides AES-GCM support starting in version 3.15, it may be
37 // unavailable for Linux Chrome users.
39 // * !defined(CKM_AES_GCM)
41 // This means that at build time, the NSS header pkcs11t.h is older than
42 // 3.15. However at runtime support may be present.
44 // * !defined(USE_NSS)
46 // This means that Chrome is being built with an embedded copy of NSS,
47 // which can be assumed to be >= 3.15. On the other hand if USE_NSS is
48 // defined, it also implies running on Linux.
50 // TODO(eroman): Simplify this once 3.15+ is required by Linux builds.
51 #if !defined(CKM_AES_GCM)
52 #define CKM_AES_GCM 0x00001087
54 struct CK_GCM_PARAMS
{
61 #endif // !defined(CKM_AES_GCM)
65 // Signature for PK11_Encrypt and PK11_Decrypt.
66 typedef SECStatus (*PK11_EncryptDecryptFunction
)(PK11SymKey
*,
75 // Signature for PK11_PubEncrypt
76 typedef SECStatus (*PK11_PubEncryptFunction
)(SECKEYPublicKey
*,
86 // Signature for PK11_PrivDecrypt
87 typedef SECStatus (*PK11_PrivDecryptFunction
)(SECKEYPrivateKey
*,
96 // Singleton to abstract away dynamically loading libnss3.so
97 class NssRuntimeSupport
{
99 bool IsAesGcmSupported() const {
100 return pk11_encrypt_func_
&& pk11_decrypt_func_
;
103 bool IsRsaOaepSupported() const {
104 return pk11_pub_encrypt_func_
&& pk11_priv_decrypt_func_
&&
105 internal_slot_does_oaep_
;
108 // Returns NULL if unsupported.
109 PK11_EncryptDecryptFunction
pk11_encrypt_func() const {
110 return pk11_encrypt_func_
;
113 // Returns NULL if unsupported.
114 PK11_EncryptDecryptFunction
pk11_decrypt_func() const {
115 return pk11_decrypt_func_
;
118 // Returns NULL if unsupported.
119 PK11_PubEncryptFunction
pk11_pub_encrypt_func() const {
120 return pk11_pub_encrypt_func_
;
123 // Returns NULL if unsupported.
124 PK11_PrivDecryptFunction
pk11_priv_decrypt_func() const {
125 return pk11_priv_decrypt_func_
;
129 friend struct base::DefaultLazyInstanceTraits
<NssRuntimeSupport
>;
131 NssRuntimeSupport() : internal_slot_does_oaep_(false) {
132 #if !defined(USE_NSS)
133 // Using a bundled version of NSS that is guaranteed to have this symbol.
134 pk11_encrypt_func_
= PK11_Encrypt
;
135 pk11_decrypt_func_
= PK11_Decrypt
;
136 pk11_pub_encrypt_func_
= PK11_PubEncrypt
;
137 pk11_priv_decrypt_func_
= PK11_PrivDecrypt
;
138 internal_slot_does_oaep_
= true;
140 // Using system NSS libraries and PCKS #11 modules, which may not have the
141 // necessary function (PK11_Encrypt) or mechanism support (CKM_AES_GCM).
143 // If PK11_Encrypt() was successfully resolved, then NSS will support
144 // AES-GCM directly. This was introduced in NSS 3.15.
145 pk11_encrypt_func_
= reinterpret_cast<PK11_EncryptDecryptFunction
>(
146 dlsym(RTLD_DEFAULT
, "PK11_Encrypt"));
147 pk11_decrypt_func_
= reinterpret_cast<PK11_EncryptDecryptFunction
>(
148 dlsym(RTLD_DEFAULT
, "PK11_Decrypt"));
150 // Even though NSS's pk11wrap layer may support
151 // PK11_PubEncrypt/PK11_PubDecrypt (introduced in NSS 3.16.2), it may have
152 // loaded a softoken that does not include OAEP support.
153 pk11_pub_encrypt_func_
= reinterpret_cast<PK11_PubEncryptFunction
>(
154 dlsym(RTLD_DEFAULT
, "PK11_PubEncrypt"));
155 pk11_priv_decrypt_func_
= reinterpret_cast<PK11_PrivDecryptFunction
>(
156 dlsym(RTLD_DEFAULT
, "PK11_PrivDecrypt"));
157 if (pk11_priv_decrypt_func_
&& pk11_pub_encrypt_func_
) {
158 crypto::ScopedPK11Slot
slot(PK11_GetInternalKeySlot());
159 internal_slot_does_oaep_
=
160 !!PK11_DoesMechanism(slot
.get(), CKM_RSA_PKCS_OAEP
);
165 PK11_EncryptDecryptFunction pk11_encrypt_func_
;
166 PK11_EncryptDecryptFunction pk11_decrypt_func_
;
167 PK11_PubEncryptFunction pk11_pub_encrypt_func_
;
168 PK11_PrivDecryptFunction pk11_priv_decrypt_func_
;
169 bool internal_slot_does_oaep_
;
172 base::LazyInstance
<NssRuntimeSupport
>::Leaky g_nss_runtime_support
=
173 LAZY_INSTANCE_INITIALIZER
;
179 namespace webcrypto
{
183 // Each key maintains a copy of its serialized form
184 // in either 'raw', 'pkcs8', or 'spki' format. This is to allow
185 // structured cloning of keys synchronously from the target Blink
186 // thread without having to lock access to the key.
188 // TODO(eroman): Take advantage of this for implementing exportKey(): no need
189 // to call into NSS if the serialized form already exists.
190 // http://crubg.com/366836
191 class SymKey
: public Key
{
193 static Status
Create(crypto::ScopedPK11SymKey key
, scoped_ptr
<SymKey
>* out
) {
194 out
->reset(new SymKey(key
.Pass()));
195 return ExportKeyRaw(out
->get(), &(*out
)->serialized_key_
);
198 PK11SymKey
* key() { return key_
.get(); }
200 virtual SymKey
* AsSymKey() OVERRIDE
{ return this; }
201 virtual PublicKey
* AsPublicKey() OVERRIDE
{ return NULL
; }
202 virtual PrivateKey
* AsPrivateKey() OVERRIDE
{ return NULL
; }
204 virtual bool ThreadSafeSerializeForClone(
205 blink::WebVector
<uint8
>* key_data
) OVERRIDE
{
206 key_data
->assign(Uint8VectorStart(serialized_key_
), serialized_key_
.size());
211 explicit SymKey(crypto::ScopedPK11SymKey key
) : key_(key
.Pass()) {}
213 crypto::ScopedPK11SymKey key_
;
214 std::vector
<uint8
> serialized_key_
;
216 DISALLOW_COPY_AND_ASSIGN(SymKey
);
219 class PublicKey
: public Key
{
221 static Status
Create(crypto::ScopedSECKEYPublicKey key
,
222 scoped_ptr
<PublicKey
>* out
) {
223 out
->reset(new PublicKey(key
.Pass()));
224 return ExportKeySpki(out
->get(), &(*out
)->serialized_key_
);
227 SECKEYPublicKey
* key() { return key_
.get(); }
229 virtual SymKey
* AsSymKey() OVERRIDE
{ return NULL
; }
230 virtual PublicKey
* AsPublicKey() OVERRIDE
{ return this; }
231 virtual PrivateKey
* AsPrivateKey() OVERRIDE
{ return NULL
; }
233 virtual bool ThreadSafeSerializeForClone(
234 blink::WebVector
<uint8
>* key_data
) OVERRIDE
{
235 key_data
->assign(Uint8VectorStart(serialized_key_
), serialized_key_
.size());
240 explicit PublicKey(crypto::ScopedSECKEYPublicKey key
) : key_(key
.Pass()) {}
242 crypto::ScopedSECKEYPublicKey key_
;
243 std::vector
<uint8
> serialized_key_
;
245 DISALLOW_COPY_AND_ASSIGN(PublicKey
);
248 class PrivateKey
: public Key
{
250 static Status
Create(crypto::ScopedSECKEYPrivateKey key
,
251 const blink::WebCryptoKeyAlgorithm
& algorithm
,
252 scoped_ptr
<PrivateKey
>* out
) {
253 out
->reset(new PrivateKey(key
.Pass()));
254 return ExportKeyPkcs8(out
->get(), algorithm
, &(*out
)->serialized_key_
);
257 SECKEYPrivateKey
* key() { return key_
.get(); }
259 virtual SymKey
* AsSymKey() OVERRIDE
{ return NULL
; }
260 virtual PublicKey
* AsPublicKey() OVERRIDE
{ return NULL
; }
261 virtual PrivateKey
* AsPrivateKey() OVERRIDE
{ return this; }
263 virtual bool ThreadSafeSerializeForClone(
264 blink::WebVector
<uint8
>* key_data
) OVERRIDE
{
265 key_data
->assign(Uint8VectorStart(serialized_key_
), serialized_key_
.size());
270 explicit PrivateKey(crypto::ScopedSECKEYPrivateKey key
) : key_(key
.Pass()) {}
272 crypto::ScopedSECKEYPrivateKey key_
;
273 std::vector
<uint8
> serialized_key_
;
275 DISALLOW_COPY_AND_ASSIGN(PrivateKey
);
280 // Creates a SECItem for the data in |buffer|. This does NOT make a copy, so
281 // |buffer| should outlive the SECItem.
282 SECItem
MakeSECItemForBuffer(const CryptoData
& buffer
) {
285 // NSS requires non-const data even though it is just for input.
286 const_cast<unsigned char*>(buffer
.bytes()), buffer
.byte_length()};
290 HASH_HashType
WebCryptoAlgorithmToNSSHashType(
291 blink::WebCryptoAlgorithmId algorithm
) {
293 case blink::WebCryptoAlgorithmIdSha1
:
295 case blink::WebCryptoAlgorithmIdSha256
:
296 return HASH_AlgSHA256
;
297 case blink::WebCryptoAlgorithmIdSha384
:
298 return HASH_AlgSHA384
;
299 case blink::WebCryptoAlgorithmIdSha512
:
300 return HASH_AlgSHA512
;
302 // Not a digest algorithm.
307 CK_MECHANISM_TYPE
WebCryptoHashToHMACMechanism(
308 const blink::WebCryptoAlgorithm
& algorithm
) {
309 switch (algorithm
.id()) {
310 case blink::WebCryptoAlgorithmIdSha1
:
311 return CKM_SHA_1_HMAC
;
312 case blink::WebCryptoAlgorithmIdSha256
:
313 return CKM_SHA256_HMAC
;
314 case blink::WebCryptoAlgorithmIdSha384
:
315 return CKM_SHA384_HMAC
;
316 case blink::WebCryptoAlgorithmIdSha512
:
317 return CKM_SHA512_HMAC
;
319 // Not a supported algorithm.
320 return CKM_INVALID_MECHANISM
;
324 CK_MECHANISM_TYPE
WebCryptoHashToDigestMechanism(
325 const blink::WebCryptoAlgorithm
& algorithm
) {
326 switch (algorithm
.id()) {
327 case blink::WebCryptoAlgorithmIdSha1
:
329 case blink::WebCryptoAlgorithmIdSha256
:
331 case blink::WebCryptoAlgorithmIdSha384
:
333 case blink::WebCryptoAlgorithmIdSha512
:
336 // Not a supported algorithm.
337 return CKM_INVALID_MECHANISM
;
341 CK_MECHANISM_TYPE
WebCryptoHashToMGFMechanism(
342 const blink::WebCryptoAlgorithm
& algorithm
) {
343 switch (algorithm
.id()) {
344 case blink::WebCryptoAlgorithmIdSha1
:
345 return CKG_MGF1_SHA1
;
346 case blink::WebCryptoAlgorithmIdSha256
:
347 return CKG_MGF1_SHA256
;
348 case blink::WebCryptoAlgorithmIdSha384
:
349 return CKG_MGF1_SHA384
;
350 case blink::WebCryptoAlgorithmIdSha512
:
351 return CKG_MGF1_SHA512
;
353 return CKM_INVALID_MECHANISM
;
357 bool InitializeRsaOaepParams(const blink::WebCryptoAlgorithm
& hash
,
358 const CryptoData
& label
,
359 CK_RSA_PKCS_OAEP_PARAMS
* oaep_params
) {
360 oaep_params
->source
= CKZ_DATA_SPECIFIED
;
361 oaep_params
->pSourceData
= const_cast<unsigned char*>(label
.bytes());
362 oaep_params
->ulSourceDataLen
= label
.byte_length();
363 oaep_params
->mgf
= WebCryptoHashToMGFMechanism(hash
);
364 oaep_params
->hashAlg
= WebCryptoHashToDigestMechanism(hash
);
366 if (oaep_params
->mgf
== CKM_INVALID_MECHANISM
||
367 oaep_params
->hashAlg
== CKM_INVALID_MECHANISM
) {
374 Status
AesCbcEncryptDecrypt(EncryptOrDecrypt mode
,
376 const CryptoData
& iv
,
377 const CryptoData
& data
,
378 std::vector
<uint8
>* buffer
) {
379 CK_ATTRIBUTE_TYPE operation
= (mode
== ENCRYPT
) ? CKA_ENCRYPT
: CKA_DECRYPT
;
381 SECItem iv_item
= MakeSECItemForBuffer(iv
);
383 crypto::ScopedSECItem
param(PK11_ParamFromIV(CKM_AES_CBC_PAD
, &iv_item
));
385 return Status::OperationError();
387 crypto::ScopedPK11Context
context(PK11_CreateContextBySymKey(
388 CKM_AES_CBC_PAD
, operation
, key
->key(), param
.get()));
391 return Status::OperationError();
393 // Oddly PK11_CipherOp takes input and output lengths as "int" rather than
394 // "unsigned int". Do some checks now to avoid integer overflowing.
395 if (data
.byte_length() >= INT_MAX
- AES_BLOCK_SIZE
) {
396 // TODO(eroman): Handle this by chunking the input fed into NSS. Right now
397 // it doesn't make much difference since the one-shot API would end up
398 // blowing out the memory and crashing anyway.
399 return Status::ErrorDataTooLarge();
402 // PK11_CipherOp does an invalid memory access when given empty decryption
403 // input, or input which is not a multiple of the block size. See also
404 // https://bugzilla.mozilla.com/show_bug.cgi?id=921687.
405 if (operation
== CKA_DECRYPT
&&
406 (data
.byte_length() == 0 || (data
.byte_length() % AES_BLOCK_SIZE
!= 0))) {
407 return Status::OperationError();
410 // TODO(eroman): Refine the output buffer size. It can be computed exactly for
411 // encryption, and can be smaller for decryption.
412 unsigned int output_max_len
= data
.byte_length() + AES_BLOCK_SIZE
;
413 CHECK_GT(output_max_len
, data
.byte_length());
415 buffer
->resize(output_max_len
);
417 unsigned char* buffer_data
= Uint8VectorStart(buffer
);
420 if (SECSuccess
!= PK11_CipherOp(context
.get(),
425 data
.byte_length())) {
426 return Status::OperationError();
429 unsigned int final_output_chunk_len
;
430 if (SECSuccess
!= PK11_DigestFinal(context
.get(),
431 buffer_data
+ output_len
,
432 &final_output_chunk_len
,
433 output_max_len
- output_len
)) {
434 return Status::OperationError();
437 buffer
->resize(final_output_chunk_len
+ output_len
);
438 return Status::Success();
441 // Helper to either encrypt or decrypt for AES-GCM. The result of encryption is
442 // the concatenation of the ciphertext and the authentication tag. Similarly,
443 // this is the expectation for the input to decryption.
444 Status
AesGcmEncryptDecrypt(EncryptOrDecrypt mode
,
446 const CryptoData
& data
,
447 const CryptoData
& iv
,
448 const CryptoData
& additional_data
,
449 unsigned int tag_length_bits
,
450 std::vector
<uint8
>* buffer
) {
451 if (!g_nss_runtime_support
.Get().IsAesGcmSupported())
452 return Status::ErrorUnsupported();
454 unsigned int tag_length_bytes
= tag_length_bits
/ 8;
456 CK_GCM_PARAMS gcm_params
= {0};
457 gcm_params
.pIv
= const_cast<unsigned char*>(iv
.bytes());
458 gcm_params
.ulIvLen
= iv
.byte_length();
460 gcm_params
.pAAD
= const_cast<unsigned char*>(additional_data
.bytes());
461 gcm_params
.ulAADLen
= additional_data
.byte_length();
463 gcm_params
.ulTagBits
= tag_length_bits
;
466 param
.type
= siBuffer
;
467 param
.data
= reinterpret_cast<unsigned char*>(&gcm_params
);
468 param
.len
= sizeof(gcm_params
);
470 unsigned int buffer_size
= 0;
472 // Calculate the output buffer size.
473 if (mode
== ENCRYPT
) {
474 // TODO(eroman): This is ugly, abstract away the safe integer arithmetic.
475 if (data
.byte_length() > (UINT_MAX
- tag_length_bytes
))
476 return Status::ErrorDataTooLarge();
477 buffer_size
= data
.byte_length() + tag_length_bytes
;
479 // TODO(eroman): In theory the buffer allocated for the plain text should be
480 // sized as |data.byte_length() - tag_length_bytes|.
482 // However NSS has a bug whereby it will fail if the output buffer size is
483 // not at least as large as the ciphertext:
485 // https://bugzilla.mozilla.org/show_bug.cgi?id=%20853674
487 // From the analysis of that bug it looks like it might be safe to pass a
488 // correctly sized buffer but lie about its size. Since resizing the
489 // WebCryptoArrayBuffer is expensive that hack may be worth looking into.
490 buffer_size
= data
.byte_length();
493 buffer
->resize(buffer_size
);
494 unsigned char* buffer_data
= Uint8VectorStart(buffer
);
496 PK11_EncryptDecryptFunction func
=
497 (mode
== ENCRYPT
) ? g_nss_runtime_support
.Get().pk11_encrypt_func()
498 : g_nss_runtime_support
.Get().pk11_decrypt_func();
500 unsigned int output_len
= 0;
501 SECStatus result
= func(key
->key(),
510 if (result
!= SECSuccess
)
511 return Status::OperationError();
513 // Unfortunately the buffer needs to be shrunk for decryption (see the NSS bug
515 buffer
->resize(output_len
);
517 return Status::Success();
520 CK_MECHANISM_TYPE
WebCryptoAlgorithmToGenMechanism(
521 const blink::WebCryptoAlgorithm
& algorithm
) {
522 switch (algorithm
.id()) {
523 case blink::WebCryptoAlgorithmIdAesCbc
:
524 case blink::WebCryptoAlgorithmIdAesGcm
:
525 case blink::WebCryptoAlgorithmIdAesKw
:
526 return CKM_AES_KEY_GEN
;
527 case blink::WebCryptoAlgorithmIdHmac
:
528 return WebCryptoHashToHMACMechanism(algorithm
.hmacKeyGenParams()->hash());
530 return CKM_INVALID_MECHANISM
;
534 // Converts a (big-endian) WebCrypto BigInteger, with or without leading zeros,
536 bool BigIntegerToLong(const uint8
* data
,
537 unsigned int data_size
,
538 unsigned long* result
) {
539 // TODO(padolph): Is it correct to say that empty data is an error, or does it
540 // mean value 0? See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23655
545 for (size_t i
= 0; i
< data_size
; ++i
) {
546 size_t reverse_i
= data_size
- i
- 1;
548 if (reverse_i
>= sizeof(unsigned long) && data
[i
])
549 return false; // Too large for a long.
551 *result
|= data
[i
] << 8 * reverse_i
;
556 bool CreatePublicKeyAlgorithm(const blink::WebCryptoAlgorithm
& algorithm
,
557 SECKEYPublicKey
* key
,
558 blink::WebCryptoKeyAlgorithm
* key_algorithm
) {
559 // TODO(eroman): What about other key types rsaPss, rsaOaep.
560 if (!key
|| key
->keyType
!= rsaKey
)
563 unsigned int modulus_length_bits
= SECKEY_PublicKeyStrength(key
) * 8;
564 CryptoData
public_exponent(key
->u
.rsa
.publicExponent
.data
,
565 key
->u
.rsa
.publicExponent
.len
);
567 switch (algorithm
.paramsType()) {
568 case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams
:
569 case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams
:
570 *key_algorithm
= blink::WebCryptoKeyAlgorithm::createRsaHashed(
573 public_exponent
.bytes(),
574 public_exponent
.byte_length(),
575 GetInnerHashAlgorithm(algorithm
).id());
582 bool CreatePrivateKeyAlgorithm(const blink::WebCryptoAlgorithm
& algorithm
,
583 SECKEYPrivateKey
* key
,
584 blink::WebCryptoKeyAlgorithm
* key_algorithm
) {
585 crypto::ScopedSECKEYPublicKey
public_key(SECKEY_ConvertToPublicKey(key
));
586 return CreatePublicKeyAlgorithm(algorithm
, public_key
.get(), key_algorithm
);
589 // The Default IV for AES-KW. See http://www.ietf.org/rfc/rfc3394.txt
591 // TODO(padolph): Move to common place to be shared with OpenSSL implementation.
592 const unsigned char kAesIv
[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
594 // Sets NSS CK_MECHANISM_TYPE and CK_FLAGS corresponding to the input Web Crypto
596 Status
WebCryptoAlgorithmToNssMechFlags(
597 const blink::WebCryptoAlgorithm
& algorithm
,
598 CK_MECHANISM_TYPE
* mechanism
,
600 // Flags are verified at the Blink layer; here the flags are set to all
601 // possible operations of a key for the input algorithm type.
602 switch (algorithm
.id()) {
603 case blink::WebCryptoAlgorithmIdHmac
: {
604 const blink::WebCryptoAlgorithm hash
= GetInnerHashAlgorithm(algorithm
);
605 *mechanism
= WebCryptoHashToHMACMechanism(hash
);
606 if (*mechanism
== CKM_INVALID_MECHANISM
)
607 return Status::ErrorUnsupported();
608 *flags
= CKF_SIGN
| CKF_VERIFY
;
611 case blink::WebCryptoAlgorithmIdAesCbc
: {
612 *mechanism
= CKM_AES_CBC
;
613 *flags
= CKF_ENCRYPT
| CKF_DECRYPT
;
616 case blink::WebCryptoAlgorithmIdAesKw
: {
617 *mechanism
= CKM_NSS_AES_KEY_WRAP
;
618 *flags
= CKF_WRAP
| CKF_WRAP
;
621 case blink::WebCryptoAlgorithmIdAesGcm
: {
622 if (!g_nss_runtime_support
.Get().IsAesGcmSupported())
623 return Status::ErrorUnsupported();
624 *mechanism
= CKM_AES_GCM
;
625 *flags
= CKF_ENCRYPT
| CKF_DECRYPT
;
629 return Status::ErrorUnsupported();
631 return Status::Success();
634 Status
DoUnwrapSymKeyAesKw(const CryptoData
& wrapped_key_data
,
635 SymKey
* wrapping_key
,
636 CK_MECHANISM_TYPE mechanism
,
638 crypto::ScopedPK11SymKey
* unwrapped_key
) {
639 DCHECK_GE(wrapped_key_data
.byte_length(), 24u);
640 DCHECK_EQ(wrapped_key_data
.byte_length() % 8, 0u);
642 SECItem iv_item
= MakeSECItemForBuffer(CryptoData(kAesIv
, sizeof(kAesIv
)));
643 crypto::ScopedSECItem
param_item(
644 PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP
, &iv_item
));
646 return Status::ErrorUnexpected();
648 SECItem cipher_text
= MakeSECItemForBuffer(wrapped_key_data
);
650 // The plaintext length is always 64 bits less than the data size.
651 const unsigned int plaintext_length
= wrapped_key_data
.byte_length() - 8;
654 // Part of workaround for
655 // https://bugzilla.mozilla.org/show_bug.cgi?id=981170. See the explanation
656 // later in this function.
660 crypto::ScopedPK11SymKey
new_key(
661 PK11_UnwrapSymKeyWithFlags(wrapping_key
->key(),
662 CKM_NSS_AES_KEY_WRAP
,
670 // TODO(padolph): Use NSS PORT_GetError() and friends to report a more
671 // accurate error, providing if doesn't leak any information to web pages
672 // about other web crypto users, key details, etc.
674 return Status::OperationError();
677 // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=981170
678 // which was fixed in NSS 3.16.0.
679 // If unwrap fails, NSS nevertheless returns a valid-looking PK11SymKey,
680 // with a reasonable length but with key data pointing to uninitialized
682 // To understand this workaround see the fix for 981170:
683 // https://hg.mozilla.org/projects/nss/rev/753bb69e543c
684 if (!NSS_VersionCheck("3.16") && PORT_GetError() == SEC_ERROR_BAD_DATA
)
685 return Status::OperationError();
688 *unwrapped_key
= new_key
.Pass();
689 return Status::Success();
692 void CopySECItemToVector(const SECItem
& item
, std::vector
<uint8
>* out
) {
693 out
->assign(item
.data
, item
.data
+ item
.len
);
696 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]:
698 // RSAPrivateKey ::= SEQUENCE {
700 // modulus INTEGER, -- n
701 // publicExponent INTEGER, -- e
702 // privateExponent INTEGER, -- d
703 // prime1 INTEGER, -- p
704 // prime2 INTEGER, -- q
705 // exponent1 INTEGER, -- d mod (p-1)
706 // exponent2 INTEGER, -- d mod (q-1)
707 // coefficient INTEGER, -- (inverse of q) mod p
708 // otherPrimeInfos OtherPrimeInfos OPTIONAL
711 // Note that otherPrimeInfos is only applicable for version=1. Since NSS
712 // doesn't use multi-prime can safely use version=0.
713 struct RSAPrivateKey
{
716 SECItem public_exponent
;
717 SECItem private_exponent
;
725 // The system NSS library doesn't have the new PK11_ExportDERPrivateKeyInfo
726 // function yet (https://bugzilla.mozilla.org/show_bug.cgi?id=519255). So we
727 // provide a fallback implementation.
729 const SEC_ASN1Template RSAPrivateKeyTemplate
[] = {
730 {SEC_ASN1_SEQUENCE
, 0, NULL
, sizeof(RSAPrivateKey
)},
731 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, version
)},
732 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, modulus
)},
733 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, public_exponent
)},
734 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, private_exponent
)},
735 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, prime1
)},
736 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, prime2
)},
737 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, exponent1
)},
738 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, exponent2
)},
739 {SEC_ASN1_INTEGER
, offsetof(RSAPrivateKey
, coefficient
)},
741 #endif // defined(USE_NSS)
743 // On success |value| will be filled with data which must be freed by
744 // SECITEM_FreeItem(value, PR_FALSE);
745 bool ReadUint(SECKEYPrivateKey
* key
,
746 CK_ATTRIBUTE_TYPE attribute
,
748 SECStatus rv
= PK11_ReadRawAttribute(PK11_TypePrivKey
, key
, attribute
, value
);
750 // PK11_ReadRawAttribute() returns items of type siBuffer. However in order
751 // for the ASN.1 encoding to be correct, the items must be of type
752 // siUnsignedInteger.
753 value
->type
= siUnsignedInteger
;
755 return rv
== SECSuccess
;
758 // Fills |out| with the RSA private key properties. Returns true on success.
759 // Regardless of the return value, the caller must invoke FreeRSAPrivateKey()
760 // to free up any allocated memory.
762 // The passed in RSAPrivateKey must be zero-initialized.
763 bool InitRSAPrivateKey(SECKEYPrivateKey
* key
, RSAPrivateKey
* out
) {
764 if (key
->keyType
!= rsaKey
)
767 // Everything should be zero-ed out. These are just some spot checks.
768 DCHECK(!out
->version
.data
);
769 DCHECK(!out
->version
.len
);
770 DCHECK(!out
->modulus
.data
);
771 DCHECK(!out
->modulus
.len
);
773 // Always use version=0 since not using multi-prime.
774 if (!SEC_ASN1EncodeInteger(NULL
, &out
->version
, 0))
777 if (!ReadUint(key
, CKA_MODULUS
, &out
->modulus
))
779 if (!ReadUint(key
, CKA_PUBLIC_EXPONENT
, &out
->public_exponent
))
781 if (!ReadUint(key
, CKA_PRIVATE_EXPONENT
, &out
->private_exponent
))
783 if (!ReadUint(key
, CKA_PRIME_1
, &out
->prime1
))
785 if (!ReadUint(key
, CKA_PRIME_2
, &out
->prime2
))
787 if (!ReadUint(key
, CKA_EXPONENT_1
, &out
->exponent1
))
789 if (!ReadUint(key
, CKA_EXPONENT_2
, &out
->exponent2
))
791 if (!ReadUint(key
, CKA_COEFFICIENT
, &out
->coefficient
))
797 struct FreeRsaPrivateKey
{
798 void operator()(RSAPrivateKey
* out
) {
799 SECITEM_FreeItem(&out
->version
, PR_FALSE
);
800 SECITEM_FreeItem(&out
->modulus
, PR_FALSE
);
801 SECITEM_FreeItem(&out
->public_exponent
, PR_FALSE
);
802 SECITEM_FreeItem(&out
->private_exponent
, PR_FALSE
);
803 SECITEM_FreeItem(&out
->prime1
, PR_FALSE
);
804 SECITEM_FreeItem(&out
->prime2
, PR_FALSE
);
805 SECITEM_FreeItem(&out
->exponent1
, PR_FALSE
);
806 SECITEM_FreeItem(&out
->exponent2
, PR_FALSE
);
807 SECITEM_FreeItem(&out
->coefficient
, PR_FALSE
);
813 class DigestorNSS
: public blink::WebCryptoDigestor
{
815 explicit DigestorNSS(blink::WebCryptoAlgorithmId algorithm_id
)
816 : hash_context_(NULL
), algorithm_id_(algorithm_id
) {}
818 virtual ~DigestorNSS() {
822 HASH_Destroy(hash_context_
);
823 hash_context_
= NULL
;
826 virtual bool consume(const unsigned char* data
, unsigned int size
) {
827 return ConsumeWithStatus(data
, size
).IsSuccess();
830 Status
ConsumeWithStatus(const unsigned char* data
, unsigned int size
) {
831 // Initialize everything if the object hasn't been initialized yet.
832 if (!hash_context_
) {
833 Status error
= Init();
834 if (!error
.IsSuccess())
838 HASH_Update(hash_context_
, data
, size
);
840 return Status::Success();
843 virtual bool finish(unsigned char*& result_data
,
844 unsigned int& result_data_size
) {
845 Status error
= FinishInternal(result_
, &result_data_size
);
846 if (!error
.IsSuccess())
848 result_data
= result_
;
852 Status
FinishWithVectorAndStatus(std::vector
<uint8
>* result
) {
854 return Status::ErrorUnexpected();
856 unsigned int result_length
= HASH_ResultLenContext(hash_context_
);
857 result
->resize(result_length
);
858 unsigned char* digest
= Uint8VectorStart(result
);
859 unsigned int digest_size
; // ignored
860 return FinishInternal(digest
, &digest_size
);
865 HASH_HashType hash_type
= WebCryptoAlgorithmToNSSHashType(algorithm_id_
);
867 if (hash_type
== HASH_AlgNULL
)
868 return Status::ErrorUnsupported();
870 hash_context_
= HASH_Create(hash_type
);
872 return Status::OperationError();
874 HASH_Begin(hash_context_
);
876 return Status::Success();
879 Status
FinishInternal(unsigned char* result
, unsigned int* result_size
) {
880 if (!hash_context_
) {
881 Status error
= Init();
882 if (!error
.IsSuccess())
886 unsigned int hash_result_length
= HASH_ResultLenContext(hash_context_
);
887 DCHECK_LE(hash_result_length
, static_cast<size_t>(HASH_LENGTH_MAX
));
889 HASH_End(hash_context_
, result
, result_size
, hash_result_length
);
891 if (*result_size
!= hash_result_length
)
892 return Status::ErrorUnexpected();
893 return Status::Success();
896 HASHContext
* hash_context_
;
897 blink::WebCryptoAlgorithmId algorithm_id_
;
898 unsigned char result_
[HASH_LENGTH_MAX
];
901 Status
ImportKeyRaw(const blink::WebCryptoAlgorithm
& algorithm
,
902 const CryptoData
& key_data
,
904 blink::WebCryptoKeyUsageMask usage_mask
,
905 blink::WebCryptoKey
* key
) {
906 DCHECK(!algorithm
.isNull());
908 CK_MECHANISM_TYPE mechanism
;
911 WebCryptoAlgorithmToNssMechFlags(algorithm
, &mechanism
, &flags
);
912 if (status
.IsError())
915 SECItem key_item
= MakeSECItemForBuffer(key_data
);
917 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
918 crypto::ScopedPK11SymKey
pk11_sym_key(
919 PK11_ImportSymKeyWithFlags(slot
.get(),
927 if (!pk11_sym_key
.get())
928 return Status::OperationError();
930 blink::WebCryptoKeyAlgorithm key_algorithm
;
931 if (!CreateSecretKeyAlgorithm(
932 algorithm
, key_data
.byte_length(), &key_algorithm
))
933 return Status::ErrorUnexpected();
935 scoped_ptr
<SymKey
> key_handle
;
936 status
= SymKey::Create(pk11_sym_key
.Pass(), &key_handle
);
937 if (status
.IsError())
940 *key
= blink::WebCryptoKey::create(key_handle
.release(),
941 blink::WebCryptoKeyTypeSecret
,
945 return Status::Success();
948 Status
ExportKeyRaw(SymKey
* key
, std::vector
<uint8
>* buffer
) {
949 if (PK11_ExtractKeyValue(key
->key()) != SECSuccess
)
950 return Status::OperationError();
952 // http://crbug.com/366427: the spec does not define any other failures for
953 // exporting, so none of the subsequent errors are spec compliant.
954 const SECItem
* key_data
= PK11_GetKeyData(key
->key());
956 return Status::OperationError();
958 buffer
->assign(key_data
->data
, key_data
->data
+ key_data
->len
);
960 return Status::Success();
965 typedef scoped_ptr
<CERTSubjectPublicKeyInfo
,
966 crypto::NSSDestroyer
<CERTSubjectPublicKeyInfo
,
967 SECKEY_DestroySubjectPublicKeyInfo
> >
968 ScopedCERTSubjectPublicKeyInfo
;
970 // Validates an NSS KeyType against a WebCrypto import algorithm.
971 bool ValidateNssKeyTypeAgainstInputAlgorithm(
973 const blink::WebCryptoAlgorithm
& algorithm
) {
976 return IsAlgorithmRsa(algorithm
.id());
981 // TODO(padolph): Handle other key types.
991 Status
ImportKeySpki(const blink::WebCryptoAlgorithm
& algorithm
,
992 const CryptoData
& key_data
,
994 blink::WebCryptoKeyUsageMask usage_mask
,
995 blink::WebCryptoKey
* key
) {
998 if (!key_data
.byte_length())
999 return Status::ErrorImportEmptyKeyData();
1000 DCHECK(key_data
.bytes());
1002 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
1003 // Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
1004 SECItem spki_item
= MakeSECItemForBuffer(key_data
);
1005 const ScopedCERTSubjectPublicKeyInfo
spki(
1006 SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item
));
1008 return Status::DataError();
1010 crypto::ScopedSECKEYPublicKey
sec_public_key(
1011 SECKEY_ExtractPublicKey(spki
.get()));
1012 if (!sec_public_key
)
1013 return Status::DataError();
1015 const KeyType sec_key_type
= SECKEY_GetPublicKeyType(sec_public_key
.get());
1016 if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type
, algorithm
))
1017 return Status::DataError();
1019 blink::WebCryptoKeyAlgorithm key_algorithm
;
1020 if (!CreatePublicKeyAlgorithm(
1021 algorithm
, sec_public_key
.get(), &key_algorithm
))
1022 return Status::ErrorUnexpected();
1024 scoped_ptr
<PublicKey
> key_handle
;
1025 Status status
= PublicKey::Create(sec_public_key
.Pass(), &key_handle
);
1026 if (status
.IsError())
1029 *key
= blink::WebCryptoKey::create(key_handle
.release(),
1030 blink::WebCryptoKeyTypePublic
,
1035 return Status::Success();
1038 Status
ExportKeySpki(PublicKey
* key
, std::vector
<uint8
>* buffer
) {
1039 const crypto::ScopedSECItem
spki_der(
1040 SECKEY_EncodeDERSubjectPublicKeyInfo(key
->key()));
1041 // http://crbug.com/366427: the spec does not define any other failures for
1042 // exporting, so none of the subsequent errors are spec compliant.
1044 return Status::OperationError();
1046 DCHECK(spki_der
->data
);
1047 DCHECK(spki_der
->len
);
1049 buffer
->assign(spki_der
->data
, spki_der
->data
+ spki_der
->len
);
1051 return Status::Success();
1054 Status
ExportRsaPublicKey(PublicKey
* key
,
1055 std::vector
<uint8
>* modulus
,
1056 std::vector
<uint8
>* public_exponent
) {
1059 if (key
->key()->keyType
!= rsaKey
)
1060 return Status::ErrorUnsupported();
1061 CopySECItemToVector(key
->key()->u
.rsa
.modulus
, modulus
);
1062 CopySECItemToVector(key
->key()->u
.rsa
.publicExponent
, public_exponent
);
1063 if (modulus
->empty() || public_exponent
->empty())
1064 return Status::ErrorUnexpected();
1065 return Status::Success();
1068 void AssignVectorFromSecItem(const SECItem
& item
, std::vector
<uint8
>* output
) {
1069 output
->assign(item
.data
, item
.data
+ item
.len
);
1072 Status
ExportRsaPrivateKey(PrivateKey
* key
,
1073 std::vector
<uint8
>* modulus
,
1074 std::vector
<uint8
>* public_exponent
,
1075 std::vector
<uint8
>* private_exponent
,
1076 std::vector
<uint8
>* prime1
,
1077 std::vector
<uint8
>* prime2
,
1078 std::vector
<uint8
>* exponent1
,
1079 std::vector
<uint8
>* exponent2
,
1080 std::vector
<uint8
>* coefficient
) {
1081 RSAPrivateKey key_props
= {};
1082 scoped_ptr
<RSAPrivateKey
, FreeRsaPrivateKey
> free_private_key(&key_props
);
1084 if (!InitRSAPrivateKey(key
->key(), &key_props
))
1085 return Status::OperationError();
1087 AssignVectorFromSecItem(key_props
.modulus
, modulus
);
1088 AssignVectorFromSecItem(key_props
.public_exponent
, public_exponent
);
1089 AssignVectorFromSecItem(key_props
.private_exponent
, private_exponent
);
1090 AssignVectorFromSecItem(key_props
.prime1
, prime1
);
1091 AssignVectorFromSecItem(key_props
.prime2
, prime2
);
1092 AssignVectorFromSecItem(key_props
.exponent1
, exponent1
);
1093 AssignVectorFromSecItem(key_props
.exponent2
, exponent2
);
1094 AssignVectorFromSecItem(key_props
.coefficient
, coefficient
);
1096 return Status::Success();
1099 Status
ExportKeyPkcs8(PrivateKey
* key
,
1100 const blink::WebCryptoKeyAlgorithm
& key_algorithm
,
1101 std::vector
<uint8
>* buffer
) {
1102 // TODO(eroman): Support other RSA key types as they are added to Blink.
1103 if (key_algorithm
.id() != blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5
&&
1104 key_algorithm
.id() != blink::WebCryptoAlgorithmIdRsaOaep
)
1105 return Status::ErrorUnsupported();
1107 // TODO(rsleevi): Implement OAEP support according to the spec.
1109 #if defined(USE_NSS)
1110 // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code.
1111 const SECOidTag algorithm
= SEC_OID_PKCS1_RSA_ENCRYPTION
;
1112 const int kPrivateKeyInfoVersion
= 0;
1114 SECKEYPrivateKeyInfo private_key_info
= {};
1115 RSAPrivateKey rsa_private_key
= {};
1116 scoped_ptr
<RSAPrivateKey
, FreeRsaPrivateKey
> free_private_key(
1119 // http://crbug.com/366427: the spec does not define any other failures for
1120 // exporting, so none of the subsequent errors are spec compliant.
1121 if (!InitRSAPrivateKey(key
->key(), &rsa_private_key
))
1122 return Status::OperationError();
1124 crypto::ScopedPLArenaPool
arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE
));
1126 return Status::OperationError();
1128 if (!SEC_ASN1EncodeItem(arena
.get(),
1129 &private_key_info
.privateKey
,
1131 RSAPrivateKeyTemplate
))
1132 return Status::OperationError();
1135 SECOID_SetAlgorithmID(
1136 arena
.get(), &private_key_info
.algorithm
, algorithm
, NULL
))
1137 return Status::OperationError();
1139 if (!SEC_ASN1EncodeInteger(
1140 arena
.get(), &private_key_info
.version
, kPrivateKeyInfoVersion
))
1141 return Status::OperationError();
1143 crypto::ScopedSECItem
encoded_key(
1144 SEC_ASN1EncodeItem(NULL
,
1147 SEC_ASN1_GET(SECKEY_PrivateKeyInfoTemplate
)));
1148 #else // defined(USE_NSS)
1149 crypto::ScopedSECItem
encoded_key(
1150 PK11_ExportDERPrivateKeyInfo(key
->key(), NULL
));
1151 #endif // defined(USE_NSS)
1153 if (!encoded_key
.get())
1154 return Status::OperationError();
1156 buffer
->assign(encoded_key
->data
, encoded_key
->data
+ encoded_key
->len
);
1157 return Status::Success();
1160 Status
ImportKeyPkcs8(const blink::WebCryptoAlgorithm
& algorithm
,
1161 const CryptoData
& key_data
,
1163 blink::WebCryptoKeyUsageMask usage_mask
,
1164 blink::WebCryptoKey
* key
) {
1167 if (!key_data
.byte_length())
1168 return Status::ErrorImportEmptyKeyData();
1169 DCHECK(key_data
.bytes());
1171 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
1172 // private key info object.
1173 SECItem pki_der
= MakeSECItemForBuffer(key_data
);
1175 SECKEYPrivateKey
* seckey_private_key
= NULL
;
1176 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
1177 if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot
.get(),
1180 NULL
, // publicValue
1184 &seckey_private_key
,
1185 NULL
) != SECSuccess
) {
1186 return Status::DataError();
1188 DCHECK(seckey_private_key
);
1189 crypto::ScopedSECKEYPrivateKey
private_key(seckey_private_key
);
1191 const KeyType sec_key_type
= SECKEY_GetPrivateKeyType(private_key
.get());
1192 if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type
, algorithm
))
1193 return Status::DataError();
1195 blink::WebCryptoKeyAlgorithm key_algorithm
;
1196 if (!CreatePrivateKeyAlgorithm(algorithm
, private_key
.get(), &key_algorithm
))
1197 return Status::ErrorUnexpected();
1199 scoped_ptr
<PrivateKey
> key_handle
;
1201 PrivateKey::Create(private_key
.Pass(), key_algorithm
, &key_handle
);
1202 if (status
.IsError())
1205 *key
= blink::WebCryptoKey::create(key_handle
.release(),
1206 blink::WebCryptoKeyTypePrivate
,
1211 return Status::Success();
1214 // -----------------------------------
1216 // -----------------------------------
1218 Status
SignHmac(SymKey
* key
,
1219 const blink::WebCryptoAlgorithm
& hash
,
1220 const CryptoData
& data
,
1221 std::vector
<uint8
>* buffer
) {
1222 DCHECK_EQ(PK11_GetMechanism(key
->key()), WebCryptoHashToHMACMechanism(hash
));
1224 SECItem param_item
= {siBuffer
, NULL
, 0};
1225 SECItem data_item
= MakeSECItemForBuffer(data
);
1226 // First call is to figure out the length.
1227 SECItem signature_item
= {siBuffer
, NULL
, 0};
1229 if (PK11_SignWithSymKey(key
->key(),
1230 PK11_GetMechanism(key
->key()),
1233 &data_item
) != SECSuccess
) {
1234 return Status::OperationError();
1237 DCHECK_NE(0u, signature_item
.len
);
1239 buffer
->resize(signature_item
.len
);
1240 signature_item
.data
= Uint8VectorStart(buffer
);
1242 if (PK11_SignWithSymKey(key
->key(),
1243 PK11_GetMechanism(key
->key()),
1246 &data_item
) != SECSuccess
) {
1247 return Status::OperationError();
1250 DCHECK_EQ(buffer
->size(), signature_item
.len
);
1251 return Status::Success();
1254 // -----------------------------------
1256 // -----------------------------------
1258 Status
EncryptRsaOaep(PublicKey
* key
,
1259 const blink::WebCryptoAlgorithm
& hash
,
1260 const CryptoData
& label
,
1261 const CryptoData
& data
,
1262 std::vector
<uint8
>* buffer
) {
1263 if (!g_nss_runtime_support
.Get().IsRsaOaepSupported())
1264 return Status::ErrorUnsupported();
1266 CK_RSA_PKCS_OAEP_PARAMS oaep_params
= {0};
1267 if (!InitializeRsaOaepParams(hash
, label
, &oaep_params
))
1268 return Status::ErrorUnsupported();
1271 param
.type
= siBuffer
;
1272 param
.data
= reinterpret_cast<unsigned char*>(&oaep_params
);
1273 param
.len
= sizeof(oaep_params
);
1275 buffer
->resize(SECKEY_PublicKeyStrength(key
->key()));
1276 unsigned char* buffer_data
= Uint8VectorStart(buffer
);
1277 unsigned int output_len
;
1278 if (g_nss_runtime_support
.Get().pk11_pub_encrypt_func()(key
->key(),
1286 NULL
) != SECSuccess
) {
1287 return Status::OperationError();
1290 DCHECK_LE(output_len
, buffer
->size());
1291 buffer
->resize(output_len
);
1292 return Status::Success();
1295 Status
DecryptRsaOaep(PrivateKey
* key
,
1296 const blink::WebCryptoAlgorithm
& hash
,
1297 const CryptoData
& label
,
1298 const CryptoData
& data
,
1299 std::vector
<uint8
>* buffer
) {
1300 if (!g_nss_runtime_support
.Get().IsRsaOaepSupported())
1301 return Status::ErrorUnsupported();
1303 CK_RSA_PKCS_OAEP_PARAMS oaep_params
= {0};
1304 if (!InitializeRsaOaepParams(hash
, label
, &oaep_params
))
1305 return Status::ErrorUnsupported();
1308 param
.type
= siBuffer
;
1309 param
.data
= reinterpret_cast<unsigned char*>(&oaep_params
);
1310 param
.len
= sizeof(oaep_params
);
1312 const int modulus_length_bytes
= PK11_GetPrivateModulusLen(key
->key());
1313 if (modulus_length_bytes
<= 0)
1314 return Status::ErrorUnexpected();
1316 buffer
->resize(modulus_length_bytes
);
1318 unsigned char* buffer_data
= Uint8VectorStart(buffer
);
1319 unsigned int output_len
;
1320 if (g_nss_runtime_support
.Get().pk11_priv_decrypt_func()(
1328 data
.byte_length()) != SECSuccess
) {
1329 return Status::OperationError();
1332 DCHECK_LE(output_len
, buffer
->size());
1333 buffer
->resize(output_len
);
1334 return Status::Success();
1337 // -----------------------------------
1339 // -----------------------------------
1341 Status
SignRsaSsaPkcs1v1_5(PrivateKey
* key
,
1342 const blink::WebCryptoAlgorithm
& hash
,
1343 const CryptoData
& data
,
1344 std::vector
<uint8
>* buffer
) {
1345 // Pick the NSS signing algorithm by combining RSA-SSA (RSA PKCS1) and the
1346 // inner hash of the input Web Crypto algorithm.
1347 SECOidTag sign_alg_tag
;
1348 switch (hash
.id()) {
1349 case blink::WebCryptoAlgorithmIdSha1
:
1350 sign_alg_tag
= SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION
;
1352 case blink::WebCryptoAlgorithmIdSha256
:
1353 sign_alg_tag
= SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION
;
1355 case blink::WebCryptoAlgorithmIdSha384
:
1356 sign_alg_tag
= SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION
;
1358 case blink::WebCryptoAlgorithmIdSha512
:
1359 sign_alg_tag
= SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION
;
1362 return Status::ErrorUnsupported();
1365 crypto::ScopedSECItem
signature_item(SECITEM_AllocItem(NULL
, NULL
, 0));
1366 if (SEC_SignData(signature_item
.get(),
1370 sign_alg_tag
) != SECSuccess
) {
1371 return Status::OperationError();
1374 buffer
->assign(signature_item
->data
,
1375 signature_item
->data
+ signature_item
->len
);
1376 return Status::Success();
1379 Status
VerifyRsaSsaPkcs1v1_5(PublicKey
* key
,
1380 const blink::WebCryptoAlgorithm
& hash
,
1381 const CryptoData
& signature
,
1382 const CryptoData
& data
,
1383 bool* signature_match
) {
1384 const SECItem signature_item
= MakeSECItemForBuffer(signature
);
1386 SECOidTag hash_alg_tag
;
1387 switch (hash
.id()) {
1388 case blink::WebCryptoAlgorithmIdSha1
:
1389 hash_alg_tag
= SEC_OID_SHA1
;
1391 case blink::WebCryptoAlgorithmIdSha256
:
1392 hash_alg_tag
= SEC_OID_SHA256
;
1394 case blink::WebCryptoAlgorithmIdSha384
:
1395 hash_alg_tag
= SEC_OID_SHA384
;
1397 case blink::WebCryptoAlgorithmIdSha512
:
1398 hash_alg_tag
= SEC_OID_SHA512
;
1401 return Status::ErrorUnsupported();
1405 SECSuccess
== VFY_VerifyDataDirect(data
.bytes(),
1409 SEC_OID_PKCS1_RSA_ENCRYPTION
,
1413 return Status::Success();
1416 Status
EncryptDecryptAesCbc(EncryptOrDecrypt mode
,
1418 const CryptoData
& data
,
1419 const CryptoData
& iv
,
1420 std::vector
<uint8
>* buffer
) {
1421 // TODO(eroman): Inline.
1422 return AesCbcEncryptDecrypt(mode
, key
, iv
, data
, buffer
);
1425 Status
EncryptDecryptAesGcm(EncryptOrDecrypt mode
,
1427 const CryptoData
& data
,
1428 const CryptoData
& iv
,
1429 const CryptoData
& additional_data
,
1430 unsigned int tag_length_bits
,
1431 std::vector
<uint8
>* buffer
) {
1432 // TODO(eroman): Inline.
1433 return AesGcmEncryptDecrypt(
1434 mode
, key
, data
, iv
, additional_data
, tag_length_bits
, buffer
);
1437 // -----------------------------------
1439 // -----------------------------------
1441 Status
GenerateRsaKeyPair(const blink::WebCryptoAlgorithm
& algorithm
,
1443 blink::WebCryptoKeyUsageMask public_key_usage_mask
,
1444 blink::WebCryptoKeyUsageMask private_key_usage_mask
,
1445 unsigned int modulus_length_bits
,
1446 const CryptoData
& public_exponent
,
1447 blink::WebCryptoKey
* public_key
,
1448 blink::WebCryptoKey
* private_key
) {
1449 if (algorithm
.id() == blink::WebCryptoAlgorithmIdRsaOaep
&&
1450 !g_nss_runtime_support
.Get().IsRsaOaepSupported()) {
1451 return Status::ErrorUnsupported();
1454 crypto::ScopedPK11Slot
slot(PK11_GetInternalKeySlot());
1456 return Status::OperationError();
1458 unsigned long public_exponent_long
;
1459 if (!BigIntegerToLong(public_exponent
.bytes(),
1460 public_exponent
.byte_length(),
1461 &public_exponent_long
) ||
1462 !public_exponent_long
) {
1463 return Status::ErrorGenerateKeyPublicExponent();
1466 PK11RSAGenParams rsa_gen_params
;
1467 rsa_gen_params
.keySizeInBits
= modulus_length_bits
;
1468 rsa_gen_params
.pe
= public_exponent_long
;
1470 // Flags are verified at the Blink layer; here the flags are set to all
1471 // possible operations for the given key type.
1472 CK_FLAGS operation_flags
;
1473 switch (algorithm
.id()) {
1474 case blink::WebCryptoAlgorithmIdRsaOaep
:
1475 operation_flags
= CKF_ENCRYPT
| CKF_DECRYPT
| CKF_WRAP
| CKF_UNWRAP
;
1477 case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5
:
1478 operation_flags
= CKF_SIGN
| CKF_VERIFY
;
1482 return Status::ErrorUnexpected();
1484 const CK_FLAGS operation_flags_mask
=
1485 CKF_ENCRYPT
| CKF_DECRYPT
| CKF_SIGN
| CKF_VERIFY
| CKF_WRAP
| CKF_UNWRAP
;
1487 // The private key must be marked as insensitive and extractable, otherwise it
1488 // cannot later be exported in unencrypted form or structured-cloned.
1489 const PK11AttrFlags attribute_flags
=
1490 PK11_ATTR_INSENSITIVE
| PK11_ATTR_EXTRACTABLE
;
1492 // Note: NSS does not generate an sec_public_key if the call below fails,
1493 // so there is no danger of a leaked sec_public_key.
1494 SECKEYPublicKey
* sec_public_key
;
1495 crypto::ScopedSECKEYPrivateKey
scoped_sec_private_key(
1496 PK11_GenerateKeyPairWithOpFlags(slot
.get(),
1497 CKM_RSA_PKCS_KEY_PAIR_GEN
,
1502 operation_flags_mask
,
1505 return Status::OperationError();
1507 blink::WebCryptoKeyAlgorithm key_algorithm
;
1508 if (!CreatePublicKeyAlgorithm(algorithm
, sec_public_key
, &key_algorithm
))
1509 return Status::ErrorUnexpected();
1511 scoped_ptr
<PublicKey
> public_key_handle
;
1512 Status status
= PublicKey::Create(
1513 crypto::ScopedSECKEYPublicKey(sec_public_key
), &public_key_handle
);
1514 if (status
.IsError())
1517 scoped_ptr
<PrivateKey
> private_key_handle
;
1518 status
= PrivateKey::Create(
1519 scoped_sec_private_key
.Pass(), key_algorithm
, &private_key_handle
);
1520 if (status
.IsError())
1523 *public_key
= blink::WebCryptoKey::create(public_key_handle
.release(),
1524 blink::WebCryptoKeyTypePublic
,
1527 public_key_usage_mask
);
1528 *private_key
= blink::WebCryptoKey::create(private_key_handle
.release(),
1529 blink::WebCryptoKeyTypePrivate
,
1532 private_key_usage_mask
);
1534 return Status::Success();
1538 crypto::EnsureNSSInit();
1541 Status
DigestSha(blink::WebCryptoAlgorithmId algorithm
,
1542 const CryptoData
& data
,
1543 std::vector
<uint8
>* buffer
) {
1544 DigestorNSS
digestor(algorithm
);
1545 Status error
= digestor
.ConsumeWithStatus(data
.bytes(), data
.byte_length());
1546 // http://crbug.com/366427: the spec does not define any other failures for
1547 // digest, so none of the subsequent errors are spec compliant.
1548 if (!error
.IsSuccess())
1550 return digestor
.FinishWithVectorAndStatus(buffer
);
1553 scoped_ptr
<blink::WebCryptoDigestor
> CreateDigestor(
1554 blink::WebCryptoAlgorithmId algorithm_id
) {
1555 return scoped_ptr
<blink::WebCryptoDigestor
>(new DigestorNSS(algorithm_id
));
1558 Status
GenerateSecretKey(const blink::WebCryptoAlgorithm
& algorithm
,
1560 blink::WebCryptoKeyUsageMask usage_mask
,
1561 unsigned keylen_bytes
,
1562 blink::WebCryptoKey
* key
) {
1563 CK_MECHANISM_TYPE mech
= WebCryptoAlgorithmToGenMechanism(algorithm
);
1564 blink::WebCryptoKeyType key_type
= blink::WebCryptoKeyTypeSecret
;
1566 if (mech
== CKM_INVALID_MECHANISM
)
1567 return Status::ErrorUnsupported();
1569 crypto::ScopedPK11Slot
slot(PK11_GetInternalKeySlot());
1571 return Status::OperationError();
1573 crypto::ScopedPK11SymKey
pk11_key(
1574 PK11_KeyGen(slot
.get(), mech
, NULL
, keylen_bytes
, NULL
));
1577 return Status::OperationError();
1579 blink::WebCryptoKeyAlgorithm key_algorithm
;
1580 if (!CreateSecretKeyAlgorithm(algorithm
, keylen_bytes
, &key_algorithm
))
1581 return Status::ErrorUnexpected();
1583 scoped_ptr
<SymKey
> key_handle
;
1584 Status status
= SymKey::Create(pk11_key
.Pass(), &key_handle
);
1585 if (status
.IsError())
1588 *key
= blink::WebCryptoKey::create(
1589 key_handle
.release(), key_type
, extractable
, key_algorithm
, usage_mask
);
1590 return Status::Success();
1593 Status
ImportRsaPublicKey(const blink::WebCryptoAlgorithm
& algorithm
,
1595 blink::WebCryptoKeyUsageMask usage_mask
,
1596 const CryptoData
& modulus_data
,
1597 const CryptoData
& exponent_data
,
1598 blink::WebCryptoKey
* key
) {
1599 if (!modulus_data
.byte_length())
1600 return Status::ErrorImportRsaEmptyModulus();
1602 if (!exponent_data
.byte_length())
1603 return Status::ErrorImportRsaEmptyExponent();
1605 DCHECK(modulus_data
.bytes());
1606 DCHECK(exponent_data
.bytes());
1608 // NSS does not provide a way to create an RSA public key directly from the
1609 // modulus and exponent values, but it can import an DER-encoded ASN.1 blob
1610 // with these values and create the public key from that. The code below
1611 // follows the recommendation described in
1612 // https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
1614 // Pack the input values into a struct compatible with NSS ASN.1 encoding, and
1615 // set up an ASN.1 encoder template for it.
1616 struct RsaPublicKeyData
{
1620 const RsaPublicKeyData pubkey_in
= {
1621 {siUnsignedInteger
, const_cast<unsigned char*>(modulus_data
.bytes()),
1622 modulus_data
.byte_length()},
1623 {siUnsignedInteger
, const_cast<unsigned char*>(exponent_data
.bytes()),
1624 exponent_data
.byte_length()}};
1625 const SEC_ASN1Template rsa_public_key_template
[] = {
1626 {SEC_ASN1_SEQUENCE
, 0, NULL
, sizeof(RsaPublicKeyData
)},
1627 {SEC_ASN1_INTEGER
, offsetof(RsaPublicKeyData
, modulus
), },
1628 {SEC_ASN1_INTEGER
, offsetof(RsaPublicKeyData
, exponent
), },
1631 // DER-encode the public key.
1632 crypto::ScopedSECItem
pubkey_der(
1633 SEC_ASN1EncodeItem(NULL
, NULL
, &pubkey_in
, rsa_public_key_template
));
1635 return Status::OperationError();
1637 // Import the DER-encoded public key to create an RSA SECKEYPublicKey.
1638 crypto::ScopedSECKEYPublicKey
pubkey(
1639 SECKEY_ImportDERPublicKey(pubkey_der
.get(), CKK_RSA
));
1641 return Status::OperationError();
1643 blink::WebCryptoKeyAlgorithm key_algorithm
;
1644 if (!CreatePublicKeyAlgorithm(algorithm
, pubkey
.get(), &key_algorithm
))
1645 return Status::ErrorUnexpected();
1647 scoped_ptr
<PublicKey
> key_handle
;
1648 Status status
= PublicKey::Create(pubkey
.Pass(), &key_handle
);
1649 if (status
.IsError())
1652 *key
= blink::WebCryptoKey::create(key_handle
.release(),
1653 blink::WebCryptoKeyTypePublic
,
1657 return Status::Success();
1660 struct DestroyGenericObject
{
1661 void operator()(PK11GenericObject
* o
) const {
1663 PK11_DestroyGenericObject(o
);
1667 typedef scoped_ptr
<PK11GenericObject
, DestroyGenericObject
>
1668 ScopedPK11GenericObject
;
1670 // Helper to add an attribute to a template.
1671 void AddAttribute(CK_ATTRIBUTE_TYPE type
,
1673 unsigned long length
,
1674 std::vector
<CK_ATTRIBUTE
>* templ
) {
1675 CK_ATTRIBUTE attribute
= {type
, value
, length
};
1676 templ
->push_back(attribute
);
1679 // Helper to optionally add an attribute to a template, if the provided data is
1681 void AddOptionalAttribute(CK_ATTRIBUTE_TYPE type
,
1682 const CryptoData
& data
,
1683 std::vector
<CK_ATTRIBUTE
>* templ
) {
1684 if (!data
.byte_length())
1686 CK_ATTRIBUTE attribute
= {type
, const_cast<unsigned char*>(data
.bytes()),
1687 data
.byte_length()};
1688 templ
->push_back(attribute
);
1691 Status
ImportRsaPrivateKey(const blink::WebCryptoAlgorithm
& algorithm
,
1693 blink::WebCryptoKeyUsageMask usage_mask
,
1694 const CryptoData
& modulus
,
1695 const CryptoData
& public_exponent
,
1696 const CryptoData
& private_exponent
,
1697 const CryptoData
& prime1
,
1698 const CryptoData
& prime2
,
1699 const CryptoData
& exponent1
,
1700 const CryptoData
& exponent2
,
1701 const CryptoData
& coefficient
,
1702 blink::WebCryptoKey
* key
) {
1703 CK_OBJECT_CLASS obj_class
= CKO_PRIVATE_KEY
;
1704 CK_KEY_TYPE key_type
= CKK_RSA
;
1705 CK_BBOOL ck_false
= CK_FALSE
;
1707 std::vector
<CK_ATTRIBUTE
> key_template
;
1709 AddAttribute(CKA_CLASS
, &obj_class
, sizeof(obj_class
), &key_template
);
1710 AddAttribute(CKA_KEY_TYPE
, &key_type
, sizeof(key_type
), &key_template
);
1711 AddAttribute(CKA_TOKEN
, &ck_false
, sizeof(ck_false
), &key_template
);
1712 AddAttribute(CKA_SENSITIVE
, &ck_false
, sizeof(ck_false
), &key_template
);
1713 AddAttribute(CKA_PRIVATE
, &ck_false
, sizeof(ck_false
), &key_template
);
1715 // Required properties.
1716 AddOptionalAttribute(CKA_MODULUS
, modulus
, &key_template
);
1717 AddOptionalAttribute(CKA_PUBLIC_EXPONENT
, public_exponent
, &key_template
);
1718 AddOptionalAttribute(CKA_PRIVATE_EXPONENT
, private_exponent
, &key_template
);
1720 // Manufacture a CKA_ID so the created key can be retrieved later as a
1721 // SECKEYPrivateKey using FindKeyByKeyID(). Unfortunately there isn't a more
1722 // direct way to do this in NSS.
1724 // For consistency with other NSS key creation methods, set the CKA_ID to
1725 // PK11_MakeIDFromPubKey(). There are some problems with
1728 // (1) Prior to NSS 3.16.2, there is no parameter validation when creating
1729 // private keys. It is therefore possible to construct a key using the
1730 // known public modulus, and where all the other parameters are bogus.
1731 // FindKeyByKeyID() returns the first key matching the ID. So this would
1732 // effectively allow an attacker to retrieve a private key of their
1734 // TODO(eroman): Once NSS rolls and this is fixed, disallow RSA key
1735 // import on older versions of NSS.
1736 // http://crbug.com/378315
1738 // (2) The ID space is shared by different key types. So theoretically
1739 // possible to retrieve a key of the wrong type which has a matching
1740 // CKA_ID. In practice I am told this is not likely except for small key
1741 // sizes, since would require constructing keys with the same public
1744 // (3) FindKeyByKeyID() doesn't necessarily return the object that was just
1745 // created by CreateGenericObject. If the pre-existing key was
1746 // provisioned with flags incompatible with WebCrypto (for instance
1747 // marked sensitive) then this will break things.
1748 SECItem modulus_item
= MakeSECItemForBuffer(CryptoData(modulus
));
1749 crypto::ScopedSECItem
object_id(PK11_MakeIDFromPubKey(&modulus_item
));
1750 AddOptionalAttribute(
1751 CKA_ID
, CryptoData(object_id
->data
, object_id
->len
), &key_template
);
1753 // Optional properties (all of these will have been specified or none).
1754 AddOptionalAttribute(CKA_PRIME_1
, prime1
, &key_template
);
1755 AddOptionalAttribute(CKA_PRIME_2
, prime2
, &key_template
);
1756 AddOptionalAttribute(CKA_EXPONENT_1
, exponent1
, &key_template
);
1757 AddOptionalAttribute(CKA_EXPONENT_2
, exponent2
, &key_template
);
1758 AddOptionalAttribute(CKA_COEFFICIENT
, coefficient
, &key_template
);
1760 crypto::ScopedPK11Slot
slot(PK11_GetInternalSlot());
1762 ScopedPK11GenericObject
key_object(PK11_CreateGenericObject(
1763 slot
.get(), &key_template
[0], key_template
.size(), PR_FALSE
));
1766 return Status::OperationError();
1768 crypto::ScopedSECKEYPrivateKey
private_key_tmp(
1769 PK11_FindKeyByKeyID(slot
.get(), object_id
.get(), NULL
));
1771 // PK11_FindKeyByKeyID() may return a handle to an existing key, rather than
1772 // the object created by PK11_CreateGenericObject().
1773 crypto::ScopedSECKEYPrivateKey
private_key(
1774 SECKEY_CopyPrivateKey(private_key_tmp
.get()));
1777 return Status::OperationError();
1779 blink::WebCryptoKeyAlgorithm key_algorithm
;
1780 if (!CreatePrivateKeyAlgorithm(algorithm
, private_key
.get(), &key_algorithm
))
1781 return Status::ErrorUnexpected();
1783 scoped_ptr
<PrivateKey
> key_handle
;
1785 PrivateKey::Create(private_key
.Pass(), key_algorithm
, &key_handle
);
1786 if (status
.IsError())
1789 *key
= blink::WebCryptoKey::create(key_handle
.release(),
1790 blink::WebCryptoKeyTypePrivate
,
1794 return Status::Success();
1797 Status
WrapSymKeyAesKw(SymKey
* key
,
1798 SymKey
* wrapping_key
,
1799 std::vector
<uint8
>* buffer
) {
1800 // The data size must be at least 16 bytes and a multiple of 8 bytes.
1801 // RFC 3394 does not specify a maximum allowed data length, but since only
1802 // keys are being wrapped in this application (which are small), a reasonable
1803 // max limit is whatever will fit into an unsigned. For the max size test,
1804 // note that AES Key Wrap always adds 8 bytes to the input data size.
1805 const unsigned int input_length
= PK11_GetKeyLength(key
->key());
1806 if (input_length
< 16)
1807 return Status::ErrorDataTooSmall();
1808 if (input_length
> UINT_MAX
- 8)
1809 return Status::ErrorDataTooLarge();
1810 if (input_length
% 8)
1811 return Status::ErrorInvalidAesKwDataLength();
1813 SECItem iv_item
= MakeSECItemForBuffer(CryptoData(kAesIv
, sizeof(kAesIv
)));
1814 crypto::ScopedSECItem
param_item(
1815 PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP
, &iv_item
));
1817 return Status::ErrorUnexpected();
1819 const unsigned int output_length
= input_length
+ 8;
1820 buffer
->resize(output_length
);
1821 SECItem wrapped_key_item
= MakeSECItemForBuffer(CryptoData(*buffer
));
1823 if (SECSuccess
!= PK11_WrapSymKey(CKM_NSS_AES_KEY_WRAP
,
1825 wrapping_key
->key(),
1827 &wrapped_key_item
)) {
1828 return Status::OperationError();
1830 if (output_length
!= wrapped_key_item
.len
)
1831 return Status::ErrorUnexpected();
1833 return Status::Success();
1836 Status
UnwrapSymKeyAesKw(const CryptoData
& wrapped_key_data
,
1837 SymKey
* wrapping_key
,
1838 const blink::WebCryptoAlgorithm
& algorithm
,
1840 blink::WebCryptoKeyUsageMask usage_mask
,
1841 blink::WebCryptoKey
* key
) {
1842 // Determine the proper NSS key properties from the input algorithm.
1843 CK_MECHANISM_TYPE mechanism
;
1846 WebCryptoAlgorithmToNssMechFlags(algorithm
, &mechanism
, &flags
);
1847 if (status
.IsError())
1850 crypto::ScopedPK11SymKey unwrapped_key
;
1851 status
= DoUnwrapSymKeyAesKw(
1852 wrapped_key_data
, wrapping_key
, mechanism
, flags
, &unwrapped_key
);
1853 if (status
.IsError())
1856 blink::WebCryptoKeyAlgorithm key_algorithm
;
1857 if (!CreateSecretKeyAlgorithm(
1858 algorithm
, PK11_GetKeyLength(unwrapped_key
.get()), &key_algorithm
))
1859 return Status::ErrorUnexpected();
1861 scoped_ptr
<SymKey
> key_handle
;
1862 status
= SymKey::Create(unwrapped_key
.Pass(), &key_handle
);
1863 if (status
.IsError())
1866 *key
= blink::WebCryptoKey::create(key_handle
.release(),
1867 blink::WebCryptoKeyTypeSecret
,
1871 return Status::Success();
1874 Status
DecryptAesKw(SymKey
* wrapping_key
,
1875 const CryptoData
& data
,
1876 std::vector
<uint8
>* buffer
) {
1877 // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be
1878 // temporarily viewed as a symmetric key to be unwrapped (decrypted).
1879 crypto::ScopedPK11SymKey decrypted
;
1880 Status status
= DoUnwrapSymKeyAesKw(
1881 data
, wrapping_key
, CKK_GENERIC_SECRET
, 0, &decrypted
);
1882 if (status
.IsError())
1885 // Once the decrypt is complete, extract the resultant raw bytes from NSS and
1886 // return them to the caller.
1887 if (PK11_ExtractKeyValue(decrypted
.get()) != SECSuccess
)
1888 return Status::OperationError();
1889 const SECItem
* const key_data
= PK11_GetKeyData(decrypted
.get());
1891 return Status::OperationError();
1892 buffer
->assign(key_data
->data
, key_data
->data
+ key_data
->len
);
1894 return Status::Success();
1897 } // namespace platform
1899 } // namespace webcrypto
1901 } // namespace content