ad1a1a9d999bcfaaa8567a4844a472c9f59cf383
[platform/framework/web/crosswalk.git] / src / content / child / webcrypto / platform_crypto_nss.cc
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.
4
5 #include "content/child/webcrypto/platform_crypto.h"
6
7 #include <cryptohi.h>
8 #include <pk11pub.h>
9 #include <secerr.h>
10 #include <sechash.h>
11
12 #include <vector>
13
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"
25
26 #if defined(USE_NSS)
27 #include <dlfcn.h>
28 #include <secoid.h>
29 #endif
30
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+
34 //     on other distros).
35 //
36 // Since NSS provides AES-GCM support starting in version 3.15, it may be
37 // unavailable for Linux Chrome users.
38 //
39 //  * !defined(CKM_AES_GCM)
40 //
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.
43 //
44 //  * !defined(USE_NSS)
45 //
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.
49 //
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
53
54 struct CK_GCM_PARAMS {
55   CK_BYTE_PTR pIv;
56   CK_ULONG ulIvLen;
57   CK_BYTE_PTR pAAD;
58   CK_ULONG ulAADLen;
59   CK_ULONG ulTagBits;
60 };
61 #endif  // !defined(CKM_AES_GCM)
62
63 namespace {
64
65 // Signature for PK11_Encrypt and PK11_Decrypt.
66 typedef SECStatus (*PK11_EncryptDecryptFunction)(PK11SymKey*,
67                                                  CK_MECHANISM_TYPE,
68                                                  SECItem*,
69                                                  unsigned char*,
70                                                  unsigned int*,
71                                                  unsigned int,
72                                                  const unsigned char*,
73                                                  unsigned int);
74
75 // Signature for PK11_PubEncrypt
76 typedef SECStatus (*PK11_PubEncryptFunction)(SECKEYPublicKey*,
77                                              CK_MECHANISM_TYPE,
78                                              SECItem*,
79                                              unsigned char*,
80                                              unsigned int*,
81                                              unsigned int,
82                                              const unsigned char*,
83                                              unsigned int,
84                                              void*);
85
86 // Signature for PK11_PrivDecrypt
87 typedef SECStatus (*PK11_PrivDecryptFunction)(SECKEYPrivateKey*,
88                                               CK_MECHANISM_TYPE,
89                                               SECItem*,
90                                               unsigned char*,
91                                               unsigned int*,
92                                               unsigned int,
93                                               const unsigned char*,
94                                               unsigned int);
95
96 // Singleton to abstract away dynamically loading libnss3.so
97 class NssRuntimeSupport {
98  public:
99   bool IsAesGcmSupported() const {
100     return pk11_encrypt_func_ && pk11_decrypt_func_;
101   }
102
103   bool IsRsaOaepSupported() const {
104     return pk11_pub_encrypt_func_ && pk11_priv_decrypt_func_ &&
105            internal_slot_does_oaep_;
106   }
107
108   // Returns NULL if unsupported.
109   PK11_EncryptDecryptFunction pk11_encrypt_func() const {
110     return pk11_encrypt_func_;
111   }
112
113   // Returns NULL if unsupported.
114   PK11_EncryptDecryptFunction pk11_decrypt_func() const {
115     return pk11_decrypt_func_;
116   }
117
118   // Returns NULL if unsupported.
119   PK11_PubEncryptFunction pk11_pub_encrypt_func() const {
120     return pk11_pub_encrypt_func_;
121   }
122
123   // Returns NULL if unsupported.
124   PK11_PrivDecryptFunction pk11_priv_decrypt_func() const {
125     return pk11_priv_decrypt_func_;
126   }
127
128  private:
129   friend struct base::DefaultLazyInstanceTraits<NssRuntimeSupport>;
130
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;
139 #else
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).
142
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"));
149
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);
161     }
162 #endif
163   }
164
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_;
170 };
171
172 base::LazyInstance<NssRuntimeSupport>::Leaky g_nss_runtime_support =
173     LAZY_INSTANCE_INITIALIZER;
174
175 }  // namespace
176
177 namespace content {
178
179 namespace webcrypto {
180
181 namespace platform {
182
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.
187 //
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 {
192  public:
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_);
196   }
197
198   PK11SymKey* key() { return key_.get(); }
199
200   virtual SymKey* AsSymKey() OVERRIDE { return this; }
201   virtual PublicKey* AsPublicKey() OVERRIDE { return NULL; }
202   virtual PrivateKey* AsPrivateKey() OVERRIDE { return NULL; }
203
204   virtual bool ThreadSafeSerializeForClone(
205       blink::WebVector<uint8>* key_data) OVERRIDE {
206     key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
207     return true;
208   }
209
210  private:
211   explicit SymKey(crypto::ScopedPK11SymKey key) : key_(key.Pass()) {}
212
213   crypto::ScopedPK11SymKey key_;
214   std::vector<uint8> serialized_key_;
215
216   DISALLOW_COPY_AND_ASSIGN(SymKey);
217 };
218
219 class PublicKey : public Key {
220  public:
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_);
225   }
226
227   SECKEYPublicKey* key() { return key_.get(); }
228
229   virtual SymKey* AsSymKey() OVERRIDE { return NULL; }
230   virtual PublicKey* AsPublicKey() OVERRIDE { return this; }
231   virtual PrivateKey* AsPrivateKey() OVERRIDE { return NULL; }
232
233   virtual bool ThreadSafeSerializeForClone(
234       blink::WebVector<uint8>* key_data) OVERRIDE {
235     key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
236     return true;
237   }
238
239  private:
240   explicit PublicKey(crypto::ScopedSECKEYPublicKey key) : key_(key.Pass()) {}
241
242   crypto::ScopedSECKEYPublicKey key_;
243   std::vector<uint8> serialized_key_;
244
245   DISALLOW_COPY_AND_ASSIGN(PublicKey);
246 };
247
248 class PrivateKey : public Key {
249  public:
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_);
255   }
256
257   SECKEYPrivateKey* key() { return key_.get(); }
258
259   virtual SymKey* AsSymKey() OVERRIDE { return NULL; }
260   virtual PublicKey* AsPublicKey() OVERRIDE { return NULL; }
261   virtual PrivateKey* AsPrivateKey() OVERRIDE { return this; }
262
263   virtual bool ThreadSafeSerializeForClone(
264       blink::WebVector<uint8>* key_data) OVERRIDE {
265     key_data->assign(Uint8VectorStart(serialized_key_), serialized_key_.size());
266     return true;
267   }
268
269  private:
270   explicit PrivateKey(crypto::ScopedSECKEYPrivateKey key) : key_(key.Pass()) {}
271
272   crypto::ScopedSECKEYPrivateKey key_;
273   std::vector<uint8> serialized_key_;
274
275   DISALLOW_COPY_AND_ASSIGN(PrivateKey);
276 };
277
278 namespace {
279
280 Status NssSupportsAesGcm() {
281   if (g_nss_runtime_support.Get().IsAesGcmSupported())
282     return Status::Success();
283   return Status::ErrorUnsupported(
284       "NSS version doesn't support AES-GCM. Try using version 3.15 or later");
285 }
286
287 Status NssSupportsRsaOaep() {
288   if (g_nss_runtime_support.Get().IsRsaOaepSupported())
289     return Status::Success();
290   return Status::ErrorUnsupported(
291       "NSS version doesn't support RSA-OAEP. Try using version 3.16.2 or "
292       "later");
293 }
294
295 #if defined(USE_NSS) && !defined(OS_CHROMEOS)
296 Status ErrorRsaKeyImportNotSupported() {
297   return Status::ErrorUnsupported(
298       "NSS version must be at least 3.16.2 for RSA key import. See "
299       "http://crbug.com/380424");
300 }
301
302 Status NssSupportsKeyImport(blink::WebCryptoAlgorithmId algorithm) {
303   // Prior to NSS 3.16.2 RSA key parameters were not validated. This is
304   // a security problem for RSA private key import from JWK which uses a
305   // CKA_ID based on the public modulus to retrieve the private key.
306
307   if (!IsAlgorithmRsa(algorithm))
308     return Status::Success();
309
310   if (!NSS_VersionCheck("3.16.2"))
311     return ErrorRsaKeyImportNotSupported();
312
313   // Also ensure that the version of Softoken is 3.16.2 or later.
314   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
315   CK_SLOT_INFO info = {};
316   if (PK11_GetSlotInfo(slot.get(), &info) != SECSuccess)
317     return ErrorRsaKeyImportNotSupported();
318
319   // CK_SLOT_INFO.hardwareVersion contains the major.minor
320   // version info for Softoken in the corresponding .major/.minor
321   // fields, and .firmwareVersion contains the patch.build
322   // version info (in the .major/.minor fields)
323   if ((info.hardwareVersion.major > 3) ||
324       (info.hardwareVersion.major == 3 &&
325        (info.hardwareVersion.minor > 16 ||
326         (info.hardwareVersion.minor == 16 &&
327          info.firmwareVersion.major >= 2)))) {
328     return Status::Success();
329   }
330
331   return ErrorRsaKeyImportNotSupported();
332 }
333 #else
334 Status NssSupportsKeyImport(blink::WebCryptoAlgorithmId) {
335   return Status::Success();
336 }
337 #endif
338
339 // Creates a SECItem for the data in |buffer|. This does NOT make a copy, so
340 // |buffer| should outlive the SECItem.
341 SECItem MakeSECItemForBuffer(const CryptoData& buffer) {
342   SECItem item = {
343       siBuffer,
344       // NSS requires non-const data even though it is just for input.
345       const_cast<unsigned char*>(buffer.bytes()), buffer.byte_length()};
346   return item;
347 }
348
349 HASH_HashType WebCryptoAlgorithmToNSSHashType(
350     blink::WebCryptoAlgorithmId algorithm) {
351   switch (algorithm) {
352     case blink::WebCryptoAlgorithmIdSha1:
353       return HASH_AlgSHA1;
354     case blink::WebCryptoAlgorithmIdSha256:
355       return HASH_AlgSHA256;
356     case blink::WebCryptoAlgorithmIdSha384:
357       return HASH_AlgSHA384;
358     case blink::WebCryptoAlgorithmIdSha512:
359       return HASH_AlgSHA512;
360     default:
361       // Not a digest algorithm.
362       return HASH_AlgNULL;
363   }
364 }
365
366 CK_MECHANISM_TYPE WebCryptoHashToHMACMechanism(
367     const blink::WebCryptoAlgorithm& algorithm) {
368   switch (algorithm.id()) {
369     case blink::WebCryptoAlgorithmIdSha1:
370       return CKM_SHA_1_HMAC;
371     case blink::WebCryptoAlgorithmIdSha256:
372       return CKM_SHA256_HMAC;
373     case blink::WebCryptoAlgorithmIdSha384:
374       return CKM_SHA384_HMAC;
375     case blink::WebCryptoAlgorithmIdSha512:
376       return CKM_SHA512_HMAC;
377     default:
378       // Not a supported algorithm.
379       return CKM_INVALID_MECHANISM;
380   }
381 }
382
383 CK_MECHANISM_TYPE WebCryptoHashToDigestMechanism(
384     const blink::WebCryptoAlgorithm& algorithm) {
385   switch (algorithm.id()) {
386     case blink::WebCryptoAlgorithmIdSha1:
387       return CKM_SHA_1;
388     case blink::WebCryptoAlgorithmIdSha256:
389       return CKM_SHA256;
390     case blink::WebCryptoAlgorithmIdSha384:
391       return CKM_SHA384;
392     case blink::WebCryptoAlgorithmIdSha512:
393       return CKM_SHA512;
394     default:
395       // Not a supported algorithm.
396       return CKM_INVALID_MECHANISM;
397   }
398 }
399
400 CK_MECHANISM_TYPE WebCryptoHashToMGFMechanism(
401     const blink::WebCryptoAlgorithm& algorithm) {
402   switch (algorithm.id()) {
403     case blink::WebCryptoAlgorithmIdSha1:
404       return CKG_MGF1_SHA1;
405     case blink::WebCryptoAlgorithmIdSha256:
406       return CKG_MGF1_SHA256;
407     case blink::WebCryptoAlgorithmIdSha384:
408       return CKG_MGF1_SHA384;
409     case blink::WebCryptoAlgorithmIdSha512:
410       return CKG_MGF1_SHA512;
411     default:
412       return CKM_INVALID_MECHANISM;
413   }
414 }
415
416 bool InitializeRsaOaepParams(const blink::WebCryptoAlgorithm& hash,
417                              const CryptoData& label,
418                              CK_RSA_PKCS_OAEP_PARAMS* oaep_params) {
419   oaep_params->source = CKZ_DATA_SPECIFIED;
420   oaep_params->pSourceData = const_cast<unsigned char*>(label.bytes());
421   oaep_params->ulSourceDataLen = label.byte_length();
422   oaep_params->mgf = WebCryptoHashToMGFMechanism(hash);
423   oaep_params->hashAlg = WebCryptoHashToDigestMechanism(hash);
424
425   if (oaep_params->mgf == CKM_INVALID_MECHANISM ||
426       oaep_params->hashAlg == CKM_INVALID_MECHANISM) {
427     return false;
428   }
429
430   return true;
431 }
432
433 Status AesCbcEncryptDecrypt(EncryptOrDecrypt mode,
434                             SymKey* key,
435                             const CryptoData& iv,
436                             const CryptoData& data,
437                             std::vector<uint8>* buffer) {
438   CK_ATTRIBUTE_TYPE operation = (mode == ENCRYPT) ? CKA_ENCRYPT : CKA_DECRYPT;
439
440   SECItem iv_item = MakeSECItemForBuffer(iv);
441
442   crypto::ScopedSECItem param(PK11_ParamFromIV(CKM_AES_CBC_PAD, &iv_item));
443   if (!param)
444     return Status::OperationError();
445
446   crypto::ScopedPK11Context context(PK11_CreateContextBySymKey(
447       CKM_AES_CBC_PAD, operation, key->key(), param.get()));
448
449   if (!context.get())
450     return Status::OperationError();
451
452   // Oddly PK11_CipherOp takes input and output lengths as "int" rather than
453   // "unsigned int". Do some checks now to avoid integer overflowing.
454   if (data.byte_length() >= INT_MAX - AES_BLOCK_SIZE) {
455     // TODO(eroman): Handle this by chunking the input fed into NSS. Right now
456     // it doesn't make much difference since the one-shot API would end up
457     // blowing out the memory and crashing anyway.
458     return Status::ErrorDataTooLarge();
459   }
460
461   // PK11_CipherOp does an invalid memory access when given empty decryption
462   // input, or input which is not a multiple of the block size. See also
463   // https://bugzilla.mozilla.com/show_bug.cgi?id=921687.
464   if (operation == CKA_DECRYPT &&
465       (data.byte_length() == 0 || (data.byte_length() % AES_BLOCK_SIZE != 0))) {
466     return Status::OperationError();
467   }
468
469   // TODO(eroman): Refine the output buffer size. It can be computed exactly for
470   //               encryption, and can be smaller for decryption.
471   unsigned int output_max_len = data.byte_length() + AES_BLOCK_SIZE;
472   CHECK_GT(output_max_len, data.byte_length());
473
474   buffer->resize(output_max_len);
475
476   unsigned char* buffer_data = Uint8VectorStart(buffer);
477
478   int output_len;
479   if (SECSuccess != PK11_CipherOp(context.get(),
480                                   buffer_data,
481                                   &output_len,
482                                   buffer->size(),
483                                   data.bytes(),
484                                   data.byte_length())) {
485     return Status::OperationError();
486   }
487
488   unsigned int final_output_chunk_len;
489   if (SECSuccess != PK11_DigestFinal(context.get(),
490                                      buffer_data + output_len,
491                                      &final_output_chunk_len,
492                                      output_max_len - output_len)) {
493     return Status::OperationError();
494   }
495
496   buffer->resize(final_output_chunk_len + output_len);
497   return Status::Success();
498 }
499
500 // Helper to either encrypt or decrypt for AES-GCM. The result of encryption is
501 // the concatenation of the ciphertext and the authentication tag. Similarly,
502 // this is the expectation for the input to decryption.
503 Status AesGcmEncryptDecrypt(EncryptOrDecrypt mode,
504                             SymKey* key,
505                             const CryptoData& data,
506                             const CryptoData& iv,
507                             const CryptoData& additional_data,
508                             unsigned int tag_length_bits,
509                             std::vector<uint8>* buffer) {
510   Status status = NssSupportsAesGcm();
511   if (status.IsError())
512     return status;
513
514   unsigned int tag_length_bytes = tag_length_bits / 8;
515
516   CK_GCM_PARAMS gcm_params = {0};
517   gcm_params.pIv = const_cast<unsigned char*>(iv.bytes());
518   gcm_params.ulIvLen = iv.byte_length();
519
520   gcm_params.pAAD = const_cast<unsigned char*>(additional_data.bytes());
521   gcm_params.ulAADLen = additional_data.byte_length();
522
523   gcm_params.ulTagBits = tag_length_bits;
524
525   SECItem param;
526   param.type = siBuffer;
527   param.data = reinterpret_cast<unsigned char*>(&gcm_params);
528   param.len = sizeof(gcm_params);
529
530   unsigned int buffer_size = 0;
531
532   // Calculate the output buffer size.
533   if (mode == ENCRYPT) {
534     // TODO(eroman): This is ugly, abstract away the safe integer arithmetic.
535     if (data.byte_length() > (UINT_MAX - tag_length_bytes))
536       return Status::ErrorDataTooLarge();
537     buffer_size = data.byte_length() + tag_length_bytes;
538   } else {
539     // TODO(eroman): In theory the buffer allocated for the plain text should be
540     // sized as |data.byte_length() - tag_length_bytes|.
541     //
542     // However NSS has a bug whereby it will fail if the output buffer size is
543     // not at least as large as the ciphertext:
544     //
545     // https://bugzilla.mozilla.org/show_bug.cgi?id=%20853674
546     //
547     // From the analysis of that bug it looks like it might be safe to pass a
548     // correctly sized buffer but lie about its size. Since resizing the
549     // WebCryptoArrayBuffer is expensive that hack may be worth looking into.
550     buffer_size = data.byte_length();
551   }
552
553   buffer->resize(buffer_size);
554   unsigned char* buffer_data = Uint8VectorStart(buffer);
555
556   PK11_EncryptDecryptFunction func =
557       (mode == ENCRYPT) ? g_nss_runtime_support.Get().pk11_encrypt_func()
558                         : g_nss_runtime_support.Get().pk11_decrypt_func();
559
560   unsigned int output_len = 0;
561   SECStatus result = func(key->key(),
562                           CKM_AES_GCM,
563                           &param,
564                           buffer_data,
565                           &output_len,
566                           buffer->size(),
567                           data.bytes(),
568                           data.byte_length());
569
570   if (result != SECSuccess)
571     return Status::OperationError();
572
573   // Unfortunately the buffer needs to be shrunk for decryption (see the NSS bug
574   // above).
575   buffer->resize(output_len);
576
577   return Status::Success();
578 }
579
580 CK_MECHANISM_TYPE WebCryptoAlgorithmToGenMechanism(
581     const blink::WebCryptoAlgorithm& algorithm) {
582   switch (algorithm.id()) {
583     case blink::WebCryptoAlgorithmIdAesCbc:
584     case blink::WebCryptoAlgorithmIdAesGcm:
585     case blink::WebCryptoAlgorithmIdAesKw:
586       return CKM_AES_KEY_GEN;
587     case blink::WebCryptoAlgorithmIdHmac:
588       return WebCryptoHashToHMACMechanism(algorithm.hmacKeyGenParams()->hash());
589     default:
590       return CKM_INVALID_MECHANISM;
591   }
592 }
593
594 bool CreatePublicKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm,
595                               SECKEYPublicKey* key,
596                               blink::WebCryptoKeyAlgorithm* key_algorithm) {
597   // TODO(eroman): What about other key types rsaPss, rsaOaep.
598   if (!key || key->keyType != rsaKey)
599     return false;
600
601   unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8;
602   CryptoData public_exponent(key->u.rsa.publicExponent.data,
603                              key->u.rsa.publicExponent.len);
604
605   switch (algorithm.paramsType()) {
606     case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams:
607     case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams:
608       *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed(
609           algorithm.id(),
610           modulus_length_bits,
611           public_exponent.bytes(),
612           public_exponent.byte_length(),
613           GetInnerHashAlgorithm(algorithm).id());
614       return true;
615     default:
616       return false;
617   }
618 }
619
620 bool CreatePrivateKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm,
621                                SECKEYPrivateKey* key,
622                                blink::WebCryptoKeyAlgorithm* key_algorithm) {
623   crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key));
624   return CreatePublicKeyAlgorithm(algorithm, public_key.get(), key_algorithm);
625 }
626
627 // The Default IV for AES-KW. See http://www.ietf.org/rfc/rfc3394.txt
628 // Section 2.2.3.1.
629 // TODO(padolph): Move to common place to be shared with OpenSSL implementation.
630 const unsigned char kAesIv[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
631
632 // Sets NSS CK_MECHANISM_TYPE and CK_FLAGS corresponding to the input Web Crypto
633 // algorithm ID.
634 Status WebCryptoAlgorithmToNssMechFlags(
635     const blink::WebCryptoAlgorithm& algorithm,
636     CK_MECHANISM_TYPE* mechanism,
637     CK_FLAGS* flags) {
638   // Flags are verified at the Blink layer; here the flags are set to all
639   // possible operations of a key for the input algorithm type.
640   switch (algorithm.id()) {
641     case blink::WebCryptoAlgorithmIdHmac: {
642       const blink::WebCryptoAlgorithm hash = GetInnerHashAlgorithm(algorithm);
643       *mechanism = WebCryptoHashToHMACMechanism(hash);
644       if (*mechanism == CKM_INVALID_MECHANISM)
645         return Status::ErrorUnsupported();
646       *flags = CKF_SIGN | CKF_VERIFY;
647       return Status::Success();
648     }
649     case blink::WebCryptoAlgorithmIdAesCbc: {
650       *mechanism = CKM_AES_CBC;
651       *flags = CKF_ENCRYPT | CKF_DECRYPT;
652       return Status::Success();
653     }
654     case blink::WebCryptoAlgorithmIdAesKw: {
655       *mechanism = CKM_NSS_AES_KEY_WRAP;
656       *flags = CKF_WRAP | CKF_WRAP;
657       return Status::Success();
658     }
659     case blink::WebCryptoAlgorithmIdAesGcm: {
660       Status status = NssSupportsAesGcm();
661       if (status.IsError())
662         return status;
663       *mechanism = CKM_AES_GCM;
664       *flags = CKF_ENCRYPT | CKF_DECRYPT;
665       return Status::Success();
666     }
667     default:
668       return Status::ErrorUnsupported();
669   }
670 }
671
672 Status DoUnwrapSymKeyAesKw(const CryptoData& wrapped_key_data,
673                            SymKey* wrapping_key,
674                            CK_MECHANISM_TYPE mechanism,
675                            CK_FLAGS flags,
676                            crypto::ScopedPK11SymKey* unwrapped_key) {
677   DCHECK_GE(wrapped_key_data.byte_length(), 24u);
678   DCHECK_EQ(wrapped_key_data.byte_length() % 8, 0u);
679
680   SECItem iv_item = MakeSECItemForBuffer(CryptoData(kAesIv, sizeof(kAesIv)));
681   crypto::ScopedSECItem param_item(
682       PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP, &iv_item));
683   if (!param_item)
684     return Status::ErrorUnexpected();
685
686   SECItem cipher_text = MakeSECItemForBuffer(wrapped_key_data);
687
688   // The plaintext length is always 64 bits less than the data size.
689   const unsigned int plaintext_length = wrapped_key_data.byte_length() - 8;
690
691 #if defined(USE_NSS)
692   // Part of workaround for
693   // https://bugzilla.mozilla.org/show_bug.cgi?id=981170. See the explanation
694   // later in this function.
695   PORT_SetError(0);
696 #endif
697
698   crypto::ScopedPK11SymKey new_key(
699       PK11_UnwrapSymKeyWithFlags(wrapping_key->key(),
700                                  CKM_NSS_AES_KEY_WRAP,
701                                  param_item.get(),
702                                  &cipher_text,
703                                  mechanism,
704                                  CKA_FLAGS_ONLY,
705                                  plaintext_length,
706                                  flags));
707
708   // TODO(padolph): Use NSS PORT_GetError() and friends to report a more
709   // accurate error, providing if doesn't leak any information to web pages
710   // about other web crypto users, key details, etc.
711   if (!new_key)
712     return Status::OperationError();
713
714 #if defined(USE_NSS)
715   // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=981170
716   // which was fixed in NSS 3.16.0.
717   // If unwrap fails, NSS nevertheless returns a valid-looking PK11SymKey,
718   // with a reasonable length but with key data pointing to uninitialized
719   // memory.
720   // To understand this workaround see the fix for 981170:
721   // https://hg.mozilla.org/projects/nss/rev/753bb69e543c
722   if (!NSS_VersionCheck("3.16") && PORT_GetError() == SEC_ERROR_BAD_DATA)
723     return Status::OperationError();
724 #endif
725
726   *unwrapped_key = new_key.Pass();
727   return Status::Success();
728 }
729
730 void CopySECItemToVector(const SECItem& item, std::vector<uint8>* out) {
731   out->assign(item.data, item.data + item.len);
732 }
733
734 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]:
735 //
736 //    RSAPrivateKey ::= SEQUENCE {
737 //      version           Version,
738 //      modulus           INTEGER,  -- n
739 //      publicExponent    INTEGER,  -- e
740 //      privateExponent   INTEGER,  -- d
741 //      prime1            INTEGER,  -- p
742 //      prime2            INTEGER,  -- q
743 //      exponent1         INTEGER,  -- d mod (p-1)
744 //      exponent2         INTEGER,  -- d mod (q-1)
745 //      coefficient       INTEGER,  -- (inverse of q) mod p
746 //      otherPrimeInfos   OtherPrimeInfos OPTIONAL
747 //    }
748 //
749 // Note that otherPrimeInfos is only applicable for version=1. Since NSS
750 // doesn't use multi-prime can safely use version=0.
751 struct RSAPrivateKey {
752   SECItem version;
753   SECItem modulus;
754   SECItem public_exponent;
755   SECItem private_exponent;
756   SECItem prime1;
757   SECItem prime2;
758   SECItem exponent1;
759   SECItem exponent2;
760   SECItem coefficient;
761 };
762
763 // The system NSS library doesn't have the new PK11_ExportDERPrivateKeyInfo
764 // function yet (https://bugzilla.mozilla.org/show_bug.cgi?id=519255). So we
765 // provide a fallback implementation.
766 #if defined(USE_NSS)
767 const SEC_ASN1Template RSAPrivateKeyTemplate[] = {
768     {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RSAPrivateKey)},
769     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, version)},
770     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, modulus)},
771     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, public_exponent)},
772     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, private_exponent)},
773     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime1)},
774     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, prime2)},
775     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent1)},
776     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, exponent2)},
777     {SEC_ASN1_INTEGER, offsetof(RSAPrivateKey, coefficient)},
778     {0}};
779 #endif  // defined(USE_NSS)
780
781 // On success |value| will be filled with data which must be freed by
782 // SECITEM_FreeItem(value, PR_FALSE);
783 bool ReadUint(SECKEYPrivateKey* key,
784               CK_ATTRIBUTE_TYPE attribute,
785               SECItem* value) {
786   SECStatus rv = PK11_ReadRawAttribute(PK11_TypePrivKey, key, attribute, value);
787
788   // PK11_ReadRawAttribute() returns items of type siBuffer. However in order
789   // for the ASN.1 encoding to be correct, the items must be of type
790   // siUnsignedInteger.
791   value->type = siUnsignedInteger;
792
793   return rv == SECSuccess;
794 }
795
796 // Fills |out| with the RSA private key properties. Returns true on success.
797 // Regardless of the return value, the caller must invoke FreeRSAPrivateKey()
798 // to free up any allocated memory.
799 //
800 // The passed in RSAPrivateKey must be zero-initialized.
801 bool InitRSAPrivateKey(SECKEYPrivateKey* key, RSAPrivateKey* out) {
802   if (key->keyType != rsaKey)
803     return false;
804
805   // Everything should be zero-ed out. These are just some spot checks.
806   DCHECK(!out->version.data);
807   DCHECK(!out->version.len);
808   DCHECK(!out->modulus.data);
809   DCHECK(!out->modulus.len);
810
811   // Always use version=0 since not using multi-prime.
812   if (!SEC_ASN1EncodeInteger(NULL, &out->version, 0))
813     return false;
814
815   if (!ReadUint(key, CKA_MODULUS, &out->modulus))
816     return false;
817   if (!ReadUint(key, CKA_PUBLIC_EXPONENT, &out->public_exponent))
818     return false;
819   if (!ReadUint(key, CKA_PRIVATE_EXPONENT, &out->private_exponent))
820     return false;
821   if (!ReadUint(key, CKA_PRIME_1, &out->prime1))
822     return false;
823   if (!ReadUint(key, CKA_PRIME_2, &out->prime2))
824     return false;
825   if (!ReadUint(key, CKA_EXPONENT_1, &out->exponent1))
826     return false;
827   if (!ReadUint(key, CKA_EXPONENT_2, &out->exponent2))
828     return false;
829   if (!ReadUint(key, CKA_COEFFICIENT, &out->coefficient))
830     return false;
831
832   return true;
833 }
834
835 struct FreeRsaPrivateKey {
836   void operator()(RSAPrivateKey* out) {
837     SECITEM_FreeItem(&out->version, PR_FALSE);
838     SECITEM_FreeItem(&out->modulus, PR_FALSE);
839     SECITEM_FreeItem(&out->public_exponent, PR_FALSE);
840     SECITEM_FreeItem(&out->private_exponent, PR_FALSE);
841     SECITEM_FreeItem(&out->prime1, PR_FALSE);
842     SECITEM_FreeItem(&out->prime2, PR_FALSE);
843     SECITEM_FreeItem(&out->exponent1, PR_FALSE);
844     SECITEM_FreeItem(&out->exponent2, PR_FALSE);
845     SECITEM_FreeItem(&out->coefficient, PR_FALSE);
846   }
847 };
848
849 }  // namespace
850
851 class DigestorNSS : public blink::WebCryptoDigestor {
852  public:
853   explicit DigestorNSS(blink::WebCryptoAlgorithmId algorithm_id)
854       : hash_context_(NULL), algorithm_id_(algorithm_id) {}
855
856   virtual ~DigestorNSS() {
857     if (!hash_context_)
858       return;
859
860     HASH_Destroy(hash_context_);
861     hash_context_ = NULL;
862   }
863
864   virtual bool consume(const unsigned char* data, unsigned int size) {
865     return ConsumeWithStatus(data, size).IsSuccess();
866   }
867
868   Status ConsumeWithStatus(const unsigned char* data, unsigned int size) {
869     // Initialize everything if the object hasn't been initialized yet.
870     if (!hash_context_) {
871       Status error = Init();
872       if (!error.IsSuccess())
873         return error;
874     }
875
876     HASH_Update(hash_context_, data, size);
877
878     return Status::Success();
879   }
880
881   virtual bool finish(unsigned char*& result_data,
882                       unsigned int& result_data_size) {
883     Status error = FinishInternal(result_, &result_data_size);
884     if (!error.IsSuccess())
885       return false;
886     result_data = result_;
887     return true;
888   }
889
890   Status FinishWithVectorAndStatus(std::vector<uint8>* result) {
891     if (!hash_context_)
892       return Status::ErrorUnexpected();
893
894     unsigned int result_length = HASH_ResultLenContext(hash_context_);
895     result->resize(result_length);
896     unsigned char* digest = Uint8VectorStart(result);
897     unsigned int digest_size;  // ignored
898     return FinishInternal(digest, &digest_size);
899   }
900
901  private:
902   Status Init() {
903     HASH_HashType hash_type = WebCryptoAlgorithmToNSSHashType(algorithm_id_);
904
905     if (hash_type == HASH_AlgNULL)
906       return Status::ErrorUnsupported();
907
908     hash_context_ = HASH_Create(hash_type);
909     if (!hash_context_)
910       return Status::OperationError();
911
912     HASH_Begin(hash_context_);
913
914     return Status::Success();
915   }
916
917   Status FinishInternal(unsigned char* result, unsigned int* result_size) {
918     if (!hash_context_) {
919       Status error = Init();
920       if (!error.IsSuccess())
921         return error;
922     }
923
924     unsigned int hash_result_length = HASH_ResultLenContext(hash_context_);
925     DCHECK_LE(hash_result_length, static_cast<size_t>(HASH_LENGTH_MAX));
926
927     HASH_End(hash_context_, result, result_size, hash_result_length);
928
929     if (*result_size != hash_result_length)
930       return Status::ErrorUnexpected();
931     return Status::Success();
932   }
933
934   HASHContext* hash_context_;
935   blink::WebCryptoAlgorithmId algorithm_id_;
936   unsigned char result_[HASH_LENGTH_MAX];
937 };
938
939 Status ImportKeyRaw(const blink::WebCryptoAlgorithm& algorithm,
940                     const CryptoData& key_data,
941                     bool extractable,
942                     blink::WebCryptoKeyUsageMask usage_mask,
943                     blink::WebCryptoKey* key) {
944   DCHECK(!algorithm.isNull());
945
946   CK_MECHANISM_TYPE mechanism = CKM_INVALID_MECHANISM;
947   CK_FLAGS flags = 0;
948   Status status =
949       WebCryptoAlgorithmToNssMechFlags(algorithm, &mechanism, &flags);
950   if (status.IsError())
951     return status;
952
953   SECItem key_item = MakeSECItemForBuffer(key_data);
954
955   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
956   crypto::ScopedPK11SymKey pk11_sym_key(
957       PK11_ImportSymKeyWithFlags(slot.get(),
958                                  mechanism,
959                                  PK11_OriginUnwrap,
960                                  CKA_FLAGS_ONLY,
961                                  &key_item,
962                                  flags,
963                                  false,
964                                  NULL));
965   if (!pk11_sym_key.get())
966     return Status::OperationError();
967
968   blink::WebCryptoKeyAlgorithm key_algorithm;
969   if (!CreateSecretKeyAlgorithm(
970           algorithm, key_data.byte_length(), &key_algorithm))
971     return Status::ErrorUnexpected();
972
973   scoped_ptr<SymKey> key_handle;
974   status = SymKey::Create(pk11_sym_key.Pass(), &key_handle);
975   if (status.IsError())
976     return status;
977
978   *key = blink::WebCryptoKey::create(key_handle.release(),
979                                      blink::WebCryptoKeyTypeSecret,
980                                      extractable,
981                                      key_algorithm,
982                                      usage_mask);
983   return Status::Success();
984 }
985
986 Status ExportKeyRaw(SymKey* key, std::vector<uint8>* buffer) {
987   if (PK11_ExtractKeyValue(key->key()) != SECSuccess)
988     return Status::OperationError();
989
990   // http://crbug.com/366427: the spec does not define any other failures for
991   // exporting, so none of the subsequent errors are spec compliant.
992   const SECItem* key_data = PK11_GetKeyData(key->key());
993   if (!key_data)
994     return Status::OperationError();
995
996   buffer->assign(key_data->data, key_data->data + key_data->len);
997
998   return Status::Success();
999 }
1000
1001 namespace {
1002
1003 typedef scoped_ptr<CERTSubjectPublicKeyInfo,
1004                    crypto::NSSDestroyer<CERTSubjectPublicKeyInfo,
1005                                         SECKEY_DestroySubjectPublicKeyInfo> >
1006     ScopedCERTSubjectPublicKeyInfo;
1007
1008 // Validates an NSS KeyType against a WebCrypto import algorithm.
1009 bool ValidateNssKeyTypeAgainstInputAlgorithm(
1010     KeyType key_type,
1011     const blink::WebCryptoAlgorithm& algorithm) {
1012   switch (key_type) {
1013     case rsaKey:
1014       return IsAlgorithmRsa(algorithm.id());
1015     case dsaKey:
1016     case ecKey:
1017     case rsaPssKey:
1018     case rsaOaepKey:
1019       // TODO(padolph): Handle other key types.
1020       break;
1021     default:
1022       break;
1023   }
1024   return false;
1025 }
1026
1027 }  // namespace
1028
1029 Status ImportKeySpki(const blink::WebCryptoAlgorithm& algorithm,
1030                      const CryptoData& key_data,
1031                      bool extractable,
1032                      blink::WebCryptoKeyUsageMask usage_mask,
1033                      blink::WebCryptoKey* key) {
1034   Status status = NssSupportsKeyImport(algorithm.id());
1035   if (status.IsError())
1036     return status;
1037
1038   DCHECK(key);
1039
1040   if (!key_data.byte_length())
1041     return Status::ErrorImportEmptyKeyData();
1042   DCHECK(key_data.bytes());
1043
1044   // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject
1045   // Public Key Info. Decode this to a CERTSubjectPublicKeyInfo.
1046   SECItem spki_item = MakeSECItemForBuffer(key_data);
1047   const ScopedCERTSubjectPublicKeyInfo spki(
1048       SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item));
1049   if (!spki)
1050     return Status::DataError();
1051
1052   crypto::ScopedSECKEYPublicKey sec_public_key(
1053       SECKEY_ExtractPublicKey(spki.get()));
1054   if (!sec_public_key)
1055     return Status::DataError();
1056
1057   const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get());
1058   if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type, algorithm))
1059     return Status::DataError();
1060
1061   blink::WebCryptoKeyAlgorithm key_algorithm;
1062   if (!CreatePublicKeyAlgorithm(
1063           algorithm, sec_public_key.get(), &key_algorithm))
1064     return Status::ErrorUnexpected();
1065
1066   scoped_ptr<PublicKey> key_handle;
1067   status = PublicKey::Create(sec_public_key.Pass(), &key_handle);
1068   if (status.IsError())
1069     return status;
1070
1071   *key = blink::WebCryptoKey::create(key_handle.release(),
1072                                      blink::WebCryptoKeyTypePublic,
1073                                      extractable,
1074                                      key_algorithm,
1075                                      usage_mask);
1076
1077   return Status::Success();
1078 }
1079
1080 Status ExportKeySpki(PublicKey* key, std::vector<uint8>* buffer) {
1081   const crypto::ScopedSECItem spki_der(
1082       SECKEY_EncodeDERSubjectPublicKeyInfo(key->key()));
1083   // http://crbug.com/366427: the spec does not define any other failures for
1084   // exporting, so none of the subsequent errors are spec compliant.
1085   if (!spki_der)
1086     return Status::OperationError();
1087
1088   DCHECK(spki_der->data);
1089   DCHECK(spki_der->len);
1090
1091   buffer->assign(spki_der->data, spki_der->data + spki_der->len);
1092
1093   return Status::Success();
1094 }
1095
1096 Status ExportRsaPublicKey(PublicKey* key,
1097                           std::vector<uint8>* modulus,
1098                           std::vector<uint8>* public_exponent) {
1099   DCHECK(key);
1100   DCHECK(key->key());
1101   if (key->key()->keyType != rsaKey)
1102     return Status::ErrorUnsupported();
1103   CopySECItemToVector(key->key()->u.rsa.modulus, modulus);
1104   CopySECItemToVector(key->key()->u.rsa.publicExponent, public_exponent);
1105   if (modulus->empty() || public_exponent->empty())
1106     return Status::ErrorUnexpected();
1107   return Status::Success();
1108 }
1109
1110 void AssignVectorFromSecItem(const SECItem& item, std::vector<uint8>* output) {
1111   output->assign(item.data, item.data + item.len);
1112 }
1113
1114 Status ExportRsaPrivateKey(PrivateKey* key,
1115                            std::vector<uint8>* modulus,
1116                            std::vector<uint8>* public_exponent,
1117                            std::vector<uint8>* private_exponent,
1118                            std::vector<uint8>* prime1,
1119                            std::vector<uint8>* prime2,
1120                            std::vector<uint8>* exponent1,
1121                            std::vector<uint8>* exponent2,
1122                            std::vector<uint8>* coefficient) {
1123   RSAPrivateKey key_props = {};
1124   scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(&key_props);
1125
1126   if (!InitRSAPrivateKey(key->key(), &key_props))
1127     return Status::OperationError();
1128
1129   AssignVectorFromSecItem(key_props.modulus, modulus);
1130   AssignVectorFromSecItem(key_props.public_exponent, public_exponent);
1131   AssignVectorFromSecItem(key_props.private_exponent, private_exponent);
1132   AssignVectorFromSecItem(key_props.prime1, prime1);
1133   AssignVectorFromSecItem(key_props.prime2, prime2);
1134   AssignVectorFromSecItem(key_props.exponent1, exponent1);
1135   AssignVectorFromSecItem(key_props.exponent2, exponent2);
1136   AssignVectorFromSecItem(key_props.coefficient, coefficient);
1137
1138   return Status::Success();
1139 }
1140
1141 Status ExportKeyPkcs8(PrivateKey* key,
1142                       const blink::WebCryptoKeyAlgorithm& key_algorithm,
1143                       std::vector<uint8>* buffer) {
1144   // TODO(eroman): Support other RSA key types as they are added to Blink.
1145   if (key_algorithm.id() != blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5 &&
1146       key_algorithm.id() != blink::WebCryptoAlgorithmIdRsaOaep)
1147     return Status::ErrorUnsupported();
1148
1149 // TODO(rsleevi): Implement OAEP support according to the spec.
1150
1151 #if defined(USE_NSS)
1152   // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code.
1153   const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION;
1154   const int kPrivateKeyInfoVersion = 0;
1155
1156   SECKEYPrivateKeyInfo private_key_info = {};
1157   RSAPrivateKey rsa_private_key = {};
1158   scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(
1159       &rsa_private_key);
1160
1161   // http://crbug.com/366427: the spec does not define any other failures for
1162   // exporting, so none of the subsequent errors are spec compliant.
1163   if (!InitRSAPrivateKey(key->key(), &rsa_private_key))
1164     return Status::OperationError();
1165
1166   crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE));
1167   if (!arena.get())
1168     return Status::OperationError();
1169
1170   if (!SEC_ASN1EncodeItem(arena.get(),
1171                           &private_key_info.privateKey,
1172                           &rsa_private_key,
1173                           RSAPrivateKeyTemplate))
1174     return Status::OperationError();
1175
1176   if (SECSuccess !=
1177       SECOID_SetAlgorithmID(
1178           arena.get(), &private_key_info.algorithm, algorithm, NULL))
1179     return Status::OperationError();
1180
1181   if (!SEC_ASN1EncodeInteger(
1182           arena.get(), &private_key_info.version, kPrivateKeyInfoVersion))
1183     return Status::OperationError();
1184
1185   crypto::ScopedSECItem encoded_key(
1186       SEC_ASN1EncodeItem(NULL,
1187                          NULL,
1188                          &private_key_info,
1189                          SEC_ASN1_GET(SECKEY_PrivateKeyInfoTemplate)));
1190 #else   // defined(USE_NSS)
1191   crypto::ScopedSECItem encoded_key(
1192       PK11_ExportDERPrivateKeyInfo(key->key(), NULL));
1193 #endif  // defined(USE_NSS)
1194
1195   if (!encoded_key.get())
1196     return Status::OperationError();
1197
1198   buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len);
1199   return Status::Success();
1200 }
1201
1202 Status ImportKeyPkcs8(const blink::WebCryptoAlgorithm& algorithm,
1203                       const CryptoData& key_data,
1204                       bool extractable,
1205                       blink::WebCryptoKeyUsageMask usage_mask,
1206                       blink::WebCryptoKey* key) {
1207   Status status = NssSupportsKeyImport(algorithm.id());
1208   if (status.IsError())
1209     return status;
1210
1211   DCHECK(key);
1212
1213   if (!key_data.byte_length())
1214     return Status::ErrorImportEmptyKeyData();
1215   DCHECK(key_data.bytes());
1216
1217   // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8
1218   // private key info object.
1219   SECItem pki_der = MakeSECItemForBuffer(key_data);
1220
1221   SECKEYPrivateKey* seckey_private_key = NULL;
1222   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
1223   if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(),
1224                                                &pki_der,
1225                                                NULL,    // nickname
1226                                                NULL,    // publicValue
1227                                                false,   // isPerm
1228                                                false,   // isPrivate
1229                                                KU_ALL,  // usage
1230                                                &seckey_private_key,
1231                                                NULL) != SECSuccess) {
1232     return Status::DataError();
1233   }
1234   DCHECK(seckey_private_key);
1235   crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key);
1236
1237   const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get());
1238   if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type, algorithm))
1239     return Status::DataError();
1240
1241   blink::WebCryptoKeyAlgorithm key_algorithm;
1242   if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm))
1243     return Status::ErrorUnexpected();
1244
1245   scoped_ptr<PrivateKey> key_handle;
1246   status = PrivateKey::Create(private_key.Pass(), key_algorithm, &key_handle);
1247   if (status.IsError())
1248     return status;
1249
1250   *key = blink::WebCryptoKey::create(key_handle.release(),
1251                                      blink::WebCryptoKeyTypePrivate,
1252                                      extractable,
1253                                      key_algorithm,
1254                                      usage_mask);
1255
1256   return Status::Success();
1257 }
1258
1259 // -----------------------------------
1260 // Hmac
1261 // -----------------------------------
1262
1263 Status SignHmac(SymKey* key,
1264                 const blink::WebCryptoAlgorithm& hash,
1265                 const CryptoData& data,
1266                 std::vector<uint8>* buffer) {
1267   DCHECK_EQ(PK11_GetMechanism(key->key()), WebCryptoHashToHMACMechanism(hash));
1268
1269   SECItem param_item = {siBuffer, NULL, 0};
1270   SECItem data_item = MakeSECItemForBuffer(data);
1271   // First call is to figure out the length.
1272   SECItem signature_item = {siBuffer, NULL, 0};
1273
1274   if (PK11_SignWithSymKey(key->key(),
1275                           PK11_GetMechanism(key->key()),
1276                           &param_item,
1277                           &signature_item,
1278                           &data_item) != SECSuccess) {
1279     return Status::OperationError();
1280   }
1281
1282   DCHECK_NE(0u, signature_item.len);
1283
1284   buffer->resize(signature_item.len);
1285   signature_item.data = Uint8VectorStart(buffer);
1286
1287   if (PK11_SignWithSymKey(key->key(),
1288                           PK11_GetMechanism(key->key()),
1289                           &param_item,
1290                           &signature_item,
1291                           &data_item) != SECSuccess) {
1292     return Status::OperationError();
1293   }
1294
1295   DCHECK_EQ(buffer->size(), signature_item.len);
1296   return Status::Success();
1297 }
1298
1299 // -----------------------------------
1300 // RsaOaep
1301 // -----------------------------------
1302
1303 Status EncryptRsaOaep(PublicKey* key,
1304                       const blink::WebCryptoAlgorithm& hash,
1305                       const CryptoData& label,
1306                       const CryptoData& data,
1307                       std::vector<uint8>* buffer) {
1308   Status status = NssSupportsRsaOaep();
1309   if (status.IsError())
1310     return status;
1311
1312   CK_RSA_PKCS_OAEP_PARAMS oaep_params = {0};
1313   if (!InitializeRsaOaepParams(hash, label, &oaep_params))
1314     return Status::ErrorUnsupported();
1315
1316   SECItem param;
1317   param.type = siBuffer;
1318   param.data = reinterpret_cast<unsigned char*>(&oaep_params);
1319   param.len = sizeof(oaep_params);
1320
1321   buffer->resize(SECKEY_PublicKeyStrength(key->key()));
1322   unsigned char* buffer_data = Uint8VectorStart(buffer);
1323   unsigned int output_len;
1324   if (g_nss_runtime_support.Get().pk11_pub_encrypt_func()(key->key(),
1325                                                           CKM_RSA_PKCS_OAEP,
1326                                                           &param,
1327                                                           buffer_data,
1328                                                           &output_len,
1329                                                           buffer->size(),
1330                                                           data.bytes(),
1331                                                           data.byte_length(),
1332                                                           NULL) != SECSuccess) {
1333     return Status::OperationError();
1334   }
1335
1336   DCHECK_LE(output_len, buffer->size());
1337   buffer->resize(output_len);
1338   return Status::Success();
1339 }
1340
1341 Status DecryptRsaOaep(PrivateKey* key,
1342                       const blink::WebCryptoAlgorithm& hash,
1343                       const CryptoData& label,
1344                       const CryptoData& data,
1345                       std::vector<uint8>* buffer) {
1346   Status status = NssSupportsRsaOaep();
1347   if (status.IsError())
1348     return status;
1349
1350   CK_RSA_PKCS_OAEP_PARAMS oaep_params = {0};
1351   if (!InitializeRsaOaepParams(hash, label, &oaep_params))
1352     return Status::ErrorUnsupported();
1353
1354   SECItem param;
1355   param.type = siBuffer;
1356   param.data = reinterpret_cast<unsigned char*>(&oaep_params);
1357   param.len = sizeof(oaep_params);
1358
1359   const int modulus_length_bytes = PK11_GetPrivateModulusLen(key->key());
1360   if (modulus_length_bytes <= 0)
1361     return Status::ErrorUnexpected();
1362
1363   buffer->resize(modulus_length_bytes);
1364
1365   unsigned char* buffer_data = Uint8VectorStart(buffer);
1366   unsigned int output_len;
1367   if (g_nss_runtime_support.Get().pk11_priv_decrypt_func()(
1368           key->key(),
1369           CKM_RSA_PKCS_OAEP,
1370           &param,
1371           buffer_data,
1372           &output_len,
1373           buffer->size(),
1374           data.bytes(),
1375           data.byte_length()) != SECSuccess) {
1376     return Status::OperationError();
1377   }
1378
1379   DCHECK_LE(output_len, buffer->size());
1380   buffer->resize(output_len);
1381   return Status::Success();
1382 }
1383
1384 // -----------------------------------
1385 // RsaSsaPkcs1v1_5
1386 // -----------------------------------
1387
1388 Status SignRsaSsaPkcs1v1_5(PrivateKey* key,
1389                            const blink::WebCryptoAlgorithm& hash,
1390                            const CryptoData& data,
1391                            std::vector<uint8>* buffer) {
1392   // Pick the NSS signing algorithm by combining RSA-SSA (RSA PKCS1) and the
1393   // inner hash of the input Web Crypto algorithm.
1394   SECOidTag sign_alg_tag;
1395   switch (hash.id()) {
1396     case blink::WebCryptoAlgorithmIdSha1:
1397       sign_alg_tag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION;
1398       break;
1399     case blink::WebCryptoAlgorithmIdSha256:
1400       sign_alg_tag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
1401       break;
1402     case blink::WebCryptoAlgorithmIdSha384:
1403       sign_alg_tag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION;
1404       break;
1405     case blink::WebCryptoAlgorithmIdSha512:
1406       sign_alg_tag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION;
1407       break;
1408     default:
1409       return Status::ErrorUnsupported();
1410   }
1411
1412   crypto::ScopedSECItem signature_item(SECITEM_AllocItem(NULL, NULL, 0));
1413   if (SEC_SignData(signature_item.get(),
1414                    data.bytes(),
1415                    data.byte_length(),
1416                    key->key(),
1417                    sign_alg_tag) != SECSuccess) {
1418     return Status::OperationError();
1419   }
1420
1421   buffer->assign(signature_item->data,
1422                  signature_item->data + signature_item->len);
1423   return Status::Success();
1424 }
1425
1426 Status VerifyRsaSsaPkcs1v1_5(PublicKey* key,
1427                              const blink::WebCryptoAlgorithm& hash,
1428                              const CryptoData& signature,
1429                              const CryptoData& data,
1430                              bool* signature_match) {
1431   const SECItem signature_item = MakeSECItemForBuffer(signature);
1432
1433   SECOidTag hash_alg_tag;
1434   switch (hash.id()) {
1435     case blink::WebCryptoAlgorithmIdSha1:
1436       hash_alg_tag = SEC_OID_SHA1;
1437       break;
1438     case blink::WebCryptoAlgorithmIdSha256:
1439       hash_alg_tag = SEC_OID_SHA256;
1440       break;
1441     case blink::WebCryptoAlgorithmIdSha384:
1442       hash_alg_tag = SEC_OID_SHA384;
1443       break;
1444     case blink::WebCryptoAlgorithmIdSha512:
1445       hash_alg_tag = SEC_OID_SHA512;
1446       break;
1447     default:
1448       return Status::ErrorUnsupported();
1449   }
1450
1451   *signature_match =
1452       SECSuccess == VFY_VerifyDataDirect(data.bytes(),
1453                                          data.byte_length(),
1454                                          key->key(),
1455                                          &signature_item,
1456                                          SEC_OID_PKCS1_RSA_ENCRYPTION,
1457                                          hash_alg_tag,
1458                                          NULL,
1459                                          NULL);
1460   return Status::Success();
1461 }
1462
1463 Status EncryptDecryptAesCbc(EncryptOrDecrypt mode,
1464                             SymKey* key,
1465                             const CryptoData& data,
1466                             const CryptoData& iv,
1467                             std::vector<uint8>* buffer) {
1468   // TODO(eroman): Inline.
1469   return AesCbcEncryptDecrypt(mode, key, iv, data, buffer);
1470 }
1471
1472 Status EncryptDecryptAesGcm(EncryptOrDecrypt mode,
1473                             SymKey* key,
1474                             const CryptoData& data,
1475                             const CryptoData& iv,
1476                             const CryptoData& additional_data,
1477                             unsigned int tag_length_bits,
1478                             std::vector<uint8>* buffer) {
1479   // TODO(eroman): Inline.
1480   return AesGcmEncryptDecrypt(
1481       mode, key, data, iv, additional_data, tag_length_bits, buffer);
1482 }
1483
1484 // -----------------------------------
1485 // Key generation
1486 // -----------------------------------
1487
1488 Status GenerateRsaKeyPair(const blink::WebCryptoAlgorithm& algorithm,
1489                           bool extractable,
1490                           blink::WebCryptoKeyUsageMask public_key_usage_mask,
1491                           blink::WebCryptoKeyUsageMask private_key_usage_mask,
1492                           unsigned int modulus_length_bits,
1493                           unsigned long public_exponent,
1494                           blink::WebCryptoKey* public_key,
1495                           blink::WebCryptoKey* private_key) {
1496   if (algorithm.id() == blink::WebCryptoAlgorithmIdRsaOaep) {
1497     Status status = NssSupportsRsaOaep();
1498     if (status.IsError())
1499       return status;
1500   }
1501
1502   crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
1503   if (!slot)
1504     return Status::OperationError();
1505
1506   PK11RSAGenParams rsa_gen_params;
1507   rsa_gen_params.keySizeInBits = modulus_length_bits;
1508   rsa_gen_params.pe = public_exponent;
1509
1510   // Flags are verified at the Blink layer; here the flags are set to all
1511   // possible operations for the given key type.
1512   CK_FLAGS operation_flags;
1513   switch (algorithm.id()) {
1514     case blink::WebCryptoAlgorithmIdRsaOaep:
1515       operation_flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP;
1516       break;
1517     case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5:
1518       operation_flags = CKF_SIGN | CKF_VERIFY;
1519       break;
1520     default:
1521       NOTREACHED();
1522       return Status::ErrorUnexpected();
1523   }
1524   const CK_FLAGS operation_flags_mask =
1525       CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP;
1526
1527   // The private key must be marked as insensitive and extractable, otherwise it
1528   // cannot later be exported in unencrypted form or structured-cloned.
1529   const PK11AttrFlags attribute_flags =
1530       PK11_ATTR_INSENSITIVE | PK11_ATTR_EXTRACTABLE;
1531
1532   // Note: NSS does not generate an sec_public_key if the call below fails,
1533   // so there is no danger of a leaked sec_public_key.
1534   SECKEYPublicKey* sec_public_key;
1535   crypto::ScopedSECKEYPrivateKey scoped_sec_private_key(
1536       PK11_GenerateKeyPairWithOpFlags(slot.get(),
1537                                       CKM_RSA_PKCS_KEY_PAIR_GEN,
1538                                       &rsa_gen_params,
1539                                       &sec_public_key,
1540                                       attribute_flags,
1541                                       operation_flags,
1542                                       operation_flags_mask,
1543                                       NULL));
1544   if (!private_key)
1545     return Status::OperationError();
1546
1547   blink::WebCryptoKeyAlgorithm key_algorithm;
1548   if (!CreatePublicKeyAlgorithm(algorithm, sec_public_key, &key_algorithm))
1549     return Status::ErrorUnexpected();
1550
1551   scoped_ptr<PublicKey> public_key_handle;
1552   Status status = PublicKey::Create(
1553       crypto::ScopedSECKEYPublicKey(sec_public_key), &public_key_handle);
1554   if (status.IsError())
1555     return status;
1556
1557   scoped_ptr<PrivateKey> private_key_handle;
1558   status = PrivateKey::Create(
1559       scoped_sec_private_key.Pass(), key_algorithm, &private_key_handle);
1560   if (status.IsError())
1561     return status;
1562
1563   *public_key = blink::WebCryptoKey::create(public_key_handle.release(),
1564                                             blink::WebCryptoKeyTypePublic,
1565                                             true,
1566                                             key_algorithm,
1567                                             public_key_usage_mask);
1568   *private_key = blink::WebCryptoKey::create(private_key_handle.release(),
1569                                              blink::WebCryptoKeyTypePrivate,
1570                                              extractable,
1571                                              key_algorithm,
1572                                              private_key_usage_mask);
1573
1574   return Status::Success();
1575 }
1576
1577 void Init() {
1578   crypto::EnsureNSSInit();
1579 }
1580
1581 Status DigestSha(blink::WebCryptoAlgorithmId algorithm,
1582                  const CryptoData& data,
1583                  std::vector<uint8>* buffer) {
1584   DigestorNSS digestor(algorithm);
1585   Status error = digestor.ConsumeWithStatus(data.bytes(), data.byte_length());
1586   // http://crbug.com/366427: the spec does not define any other failures for
1587   // digest, so none of the subsequent errors are spec compliant.
1588   if (!error.IsSuccess())
1589     return error;
1590   return digestor.FinishWithVectorAndStatus(buffer);
1591 }
1592
1593 scoped_ptr<blink::WebCryptoDigestor> CreateDigestor(
1594     blink::WebCryptoAlgorithmId algorithm_id) {
1595   return scoped_ptr<blink::WebCryptoDigestor>(new DigestorNSS(algorithm_id));
1596 }
1597
1598 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
1599                          bool extractable,
1600                          blink::WebCryptoKeyUsageMask usage_mask,
1601                          unsigned keylen_bytes,
1602                          blink::WebCryptoKey* key) {
1603   CK_MECHANISM_TYPE mech = WebCryptoAlgorithmToGenMechanism(algorithm);
1604   blink::WebCryptoKeyType key_type = blink::WebCryptoKeyTypeSecret;
1605
1606   if (mech == CKM_INVALID_MECHANISM)
1607     return Status::ErrorUnsupported();
1608
1609   crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot());
1610   if (!slot)
1611     return Status::OperationError();
1612
1613   crypto::ScopedPK11SymKey pk11_key(
1614       PK11_KeyGen(slot.get(), mech, NULL, keylen_bytes, NULL));
1615
1616   if (!pk11_key)
1617     return Status::OperationError();
1618
1619   blink::WebCryptoKeyAlgorithm key_algorithm;
1620   if (!CreateSecretKeyAlgorithm(algorithm, keylen_bytes, &key_algorithm))
1621     return Status::ErrorUnexpected();
1622
1623   scoped_ptr<SymKey> key_handle;
1624   Status status = SymKey::Create(pk11_key.Pass(), &key_handle);
1625   if (status.IsError())
1626     return status;
1627
1628   *key = blink::WebCryptoKey::create(
1629       key_handle.release(), key_type, extractable, key_algorithm, usage_mask);
1630   return Status::Success();
1631 }
1632
1633 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm,
1634                           bool extractable,
1635                           blink::WebCryptoKeyUsageMask usage_mask,
1636                           const CryptoData& modulus_data,
1637                           const CryptoData& exponent_data,
1638                           blink::WebCryptoKey* key) {
1639   if (!modulus_data.byte_length())
1640     return Status::ErrorImportRsaEmptyModulus();
1641
1642   if (!exponent_data.byte_length())
1643     return Status::ErrorImportRsaEmptyExponent();
1644
1645   DCHECK(modulus_data.bytes());
1646   DCHECK(exponent_data.bytes());
1647
1648   // NSS does not provide a way to create an RSA public key directly from the
1649   // modulus and exponent values, but it can import an DER-encoded ASN.1 blob
1650   // with these values and create the public key from that. The code below
1651   // follows the recommendation described in
1652   // https://developer.mozilla.org/en-US/docs/NSS/NSS_Tech_Notes/nss_tech_note7
1653
1654   // Pack the input values into a struct compatible with NSS ASN.1 encoding, and
1655   // set up an ASN.1 encoder template for it.
1656   struct RsaPublicKeyData {
1657     SECItem modulus;
1658     SECItem exponent;
1659   };
1660   const RsaPublicKeyData pubkey_in = {
1661       {siUnsignedInteger, const_cast<unsigned char*>(modulus_data.bytes()),
1662        modulus_data.byte_length()},
1663       {siUnsignedInteger, const_cast<unsigned char*>(exponent_data.bytes()),
1664        exponent_data.byte_length()}};
1665   const SEC_ASN1Template rsa_public_key_template[] = {
1666       {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)},
1667       {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), },
1668       {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), },
1669       {0, }};
1670
1671   // DER-encode the public key.
1672   crypto::ScopedSECItem pubkey_der(
1673       SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template));
1674   if (!pubkey_der)
1675     return Status::OperationError();
1676
1677   // Import the DER-encoded public key to create an RSA SECKEYPublicKey.
1678   crypto::ScopedSECKEYPublicKey pubkey(
1679       SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA));
1680   if (!pubkey)
1681     return Status::OperationError();
1682
1683   blink::WebCryptoKeyAlgorithm key_algorithm;
1684   if (!CreatePublicKeyAlgorithm(algorithm, pubkey.get(), &key_algorithm))
1685     return Status::ErrorUnexpected();
1686
1687   scoped_ptr<PublicKey> key_handle;
1688   Status status = PublicKey::Create(pubkey.Pass(), &key_handle);
1689   if (status.IsError())
1690     return status;
1691
1692   *key = blink::WebCryptoKey::create(key_handle.release(),
1693                                      blink::WebCryptoKeyTypePublic,
1694                                      extractable,
1695                                      key_algorithm,
1696                                      usage_mask);
1697   return Status::Success();
1698 }
1699
1700 struct DestroyGenericObject {
1701   void operator()(PK11GenericObject* o) const {
1702     if (o)
1703       PK11_DestroyGenericObject(o);
1704   }
1705 };
1706
1707 typedef scoped_ptr<PK11GenericObject, DestroyGenericObject>
1708     ScopedPK11GenericObject;
1709
1710 // Helper to add an attribute to a template.
1711 void AddAttribute(CK_ATTRIBUTE_TYPE type,
1712                   void* value,
1713                   unsigned long length,
1714                   std::vector<CK_ATTRIBUTE>* templ) {
1715   CK_ATTRIBUTE attribute = {type, value, length};
1716   templ->push_back(attribute);
1717 }
1718
1719 // Helper to optionally add an attribute to a template, if the provided data is
1720 // non-empty.
1721 void AddOptionalAttribute(CK_ATTRIBUTE_TYPE type,
1722                           const CryptoData& data,
1723                           std::vector<CK_ATTRIBUTE>* templ) {
1724   if (!data.byte_length())
1725     return;
1726   CK_ATTRIBUTE attribute = {type, const_cast<unsigned char*>(data.bytes()),
1727                             data.byte_length()};
1728   templ->push_back(attribute);
1729 }
1730
1731 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm,
1732                            bool extractable,
1733                            blink::WebCryptoKeyUsageMask usage_mask,
1734                            const CryptoData& modulus,
1735                            const CryptoData& public_exponent,
1736                            const CryptoData& private_exponent,
1737                            const CryptoData& prime1,
1738                            const CryptoData& prime2,
1739                            const CryptoData& exponent1,
1740                            const CryptoData& exponent2,
1741                            const CryptoData& coefficient,
1742                            blink::WebCryptoKey* key) {
1743   Status status = NssSupportsKeyImport(algorithm.id());
1744   if (status.IsError())
1745     return status;
1746
1747   CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY;
1748   CK_KEY_TYPE key_type = CKK_RSA;
1749   CK_BBOOL ck_false = CK_FALSE;
1750
1751   std::vector<CK_ATTRIBUTE> key_template;
1752
1753   AddAttribute(CKA_CLASS, &obj_class, sizeof(obj_class), &key_template);
1754   AddAttribute(CKA_KEY_TYPE, &key_type, sizeof(key_type), &key_template);
1755   AddAttribute(CKA_TOKEN, &ck_false, sizeof(ck_false), &key_template);
1756   AddAttribute(CKA_SENSITIVE, &ck_false, sizeof(ck_false), &key_template);
1757   AddAttribute(CKA_PRIVATE, &ck_false, sizeof(ck_false), &key_template);
1758
1759   // Required properties.
1760   AddOptionalAttribute(CKA_MODULUS, modulus, &key_template);
1761   AddOptionalAttribute(CKA_PUBLIC_EXPONENT, public_exponent, &key_template);
1762   AddOptionalAttribute(CKA_PRIVATE_EXPONENT, private_exponent, &key_template);
1763
1764   // Manufacture a CKA_ID so the created key can be retrieved later as a
1765   // SECKEYPrivateKey using FindKeyByKeyID(). Unfortunately there isn't a more
1766   // direct way to do this in NSS.
1767   //
1768   // For consistency with other NSS key creation methods, set the CKA_ID to
1769   // PK11_MakeIDFromPubKey(). There are some problems with
1770   // this approach:
1771   //
1772   //  (1) Prior to NSS 3.16.2, there is no parameter validation when creating
1773   //      private keys. It is therefore possible to construct a key using the
1774   //      known public modulus, and where all the other parameters are bogus.
1775   //      FindKeyByKeyID() returns the first key matching the ID. So this would
1776   //      effectively allow an attacker to retrieve a private key of their
1777   //      choice.
1778   //      TODO(eroman): Once NSS rolls and this is fixed, disallow RSA key
1779   //                    import on older versions of NSS.
1780   //                    http://crbug.com/378315
1781   //
1782   //  (2) The ID space is shared by different key types. So theoretically
1783   //      possible to retrieve a key of the wrong type which has a matching
1784   //      CKA_ID. In practice I am told this is not likely except for small key
1785   //      sizes, since would require constructing keys with the same public
1786   //      data.
1787   //
1788   //  (3) FindKeyByKeyID() doesn't necessarily return the object that was just
1789   //      created by CreateGenericObject. If the pre-existing key was
1790   //      provisioned with flags incompatible with WebCrypto (for instance
1791   //      marked sensitive) then this will break things.
1792   SECItem modulus_item = MakeSECItemForBuffer(CryptoData(modulus));
1793   crypto::ScopedSECItem object_id(PK11_MakeIDFromPubKey(&modulus_item));
1794   AddOptionalAttribute(
1795       CKA_ID, CryptoData(object_id->data, object_id->len), &key_template);
1796
1797   // Optional properties (all of these will have been specified or none).
1798   AddOptionalAttribute(CKA_PRIME_1, prime1, &key_template);
1799   AddOptionalAttribute(CKA_PRIME_2, prime2, &key_template);
1800   AddOptionalAttribute(CKA_EXPONENT_1, exponent1, &key_template);
1801   AddOptionalAttribute(CKA_EXPONENT_2, exponent2, &key_template);
1802   AddOptionalAttribute(CKA_COEFFICIENT, coefficient, &key_template);
1803
1804   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
1805
1806   ScopedPK11GenericObject key_object(PK11_CreateGenericObject(
1807       slot.get(), &key_template[0], key_template.size(), PR_FALSE));
1808
1809   if (!key_object)
1810     return Status::OperationError();
1811
1812   crypto::ScopedSECKEYPrivateKey private_key_tmp(
1813       PK11_FindKeyByKeyID(slot.get(), object_id.get(), NULL));
1814
1815   // PK11_FindKeyByKeyID() may return a handle to an existing key, rather than
1816   // the object created by PK11_CreateGenericObject().
1817   crypto::ScopedSECKEYPrivateKey private_key(
1818       SECKEY_CopyPrivateKey(private_key_tmp.get()));
1819
1820   if (!private_key)
1821     return Status::OperationError();
1822
1823   blink::WebCryptoKeyAlgorithm key_algorithm;
1824   if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm))
1825     return Status::ErrorUnexpected();
1826
1827   scoped_ptr<PrivateKey> key_handle;
1828   status = PrivateKey::Create(private_key.Pass(), key_algorithm, &key_handle);
1829   if (status.IsError())
1830     return status;
1831
1832   *key = blink::WebCryptoKey::create(key_handle.release(),
1833                                      blink::WebCryptoKeyTypePrivate,
1834                                      extractable,
1835                                      key_algorithm,
1836                                      usage_mask);
1837   return Status::Success();
1838 }
1839
1840 Status WrapSymKeyAesKw(PK11SymKey* key,
1841                        SymKey* wrapping_key,
1842                        std::vector<uint8>* buffer) {
1843   // The data size must be at least 16 bytes and a multiple of 8 bytes.
1844   // RFC 3394 does not specify a maximum allowed data length, but since only
1845   // keys are being wrapped in this application (which are small), a reasonable
1846   // max limit is whatever will fit into an unsigned. For the max size test,
1847   // note that AES Key Wrap always adds 8 bytes to the input data size.
1848   const unsigned int input_length = PK11_GetKeyLength(key);
1849   DCHECK_GE(input_length, 16u);
1850   DCHECK((input_length % 8) == 0);
1851   if (input_length > UINT_MAX - 8)
1852     return Status::ErrorDataTooLarge();
1853
1854   SECItem iv_item = MakeSECItemForBuffer(CryptoData(kAesIv, sizeof(kAesIv)));
1855   crypto::ScopedSECItem param_item(
1856       PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP, &iv_item));
1857   if (!param_item)
1858     return Status::ErrorUnexpected();
1859
1860   const unsigned int output_length = input_length + 8;
1861   buffer->resize(output_length);
1862   SECItem wrapped_key_item = MakeSECItemForBuffer(CryptoData(*buffer));
1863
1864   if (SECSuccess != PK11_WrapSymKey(CKM_NSS_AES_KEY_WRAP,
1865                                     param_item.get(),
1866                                     wrapping_key->key(),
1867                                     key,
1868                                     &wrapped_key_item)) {
1869     return Status::OperationError();
1870   }
1871   if (output_length != wrapped_key_item.len)
1872     return Status::ErrorUnexpected();
1873
1874   return Status::Success();
1875 }
1876
1877 Status DecryptAesKw(SymKey* wrapping_key,
1878                     const CryptoData& data,
1879                     std::vector<uint8>* buffer) {
1880   // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be
1881   // temporarily viewed as a symmetric key to be unwrapped (decrypted).
1882   crypto::ScopedPK11SymKey decrypted;
1883   Status status = DoUnwrapSymKeyAesKw(
1884       data, wrapping_key, CKK_GENERIC_SECRET, 0, &decrypted);
1885   if (status.IsError())
1886     return status;
1887
1888   // Once the decrypt is complete, extract the resultant raw bytes from NSS and
1889   // return them to the caller.
1890   if (PK11_ExtractKeyValue(decrypted.get()) != SECSuccess)
1891     return Status::OperationError();
1892   const SECItem* const key_data = PK11_GetKeyData(decrypted.get());
1893   if (!key_data)
1894     return Status::OperationError();
1895   buffer->assign(key_data->data, key_data->data + key_data->len);
1896
1897   return Status::Success();
1898 }
1899
1900 Status EncryptAesKw(SymKey* wrapping_key,
1901                     const CryptoData& data,
1902                     std::vector<uint8>* buffer) {
1903   // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be
1904   // temporarily viewed as a symmetric key to be wrapped (encrypted).
1905   SECItem data_item = MakeSECItemForBuffer(data);
1906   crypto::ScopedPK11Slot slot(PK11_GetInternalSlot());
1907   crypto::ScopedPK11SymKey data_as_sym_key(PK11_ImportSymKey(slot.get(),
1908                                                              CKK_GENERIC_SECRET,
1909                                                              PK11_OriginUnwrap,
1910                                                              CKA_SIGN,
1911                                                              &data_item,
1912                                                              NULL));
1913   if (!data_as_sym_key)
1914     return Status::OperationError();
1915
1916   return WrapSymKeyAesKw(data_as_sym_key.get(), wrapping_key, buffer);
1917 }
1918
1919 Status EncryptDecryptAesKw(EncryptOrDecrypt mode,
1920                            SymKey* wrapping_key,
1921                            const CryptoData& data,
1922                            std::vector<uint8>* buffer) {
1923   return mode == ENCRYPT ? EncryptAesKw(wrapping_key, data, buffer)
1924                          : DecryptAesKw(wrapping_key, data, buffer);
1925 }
1926
1927 }  // namespace platform
1928
1929 }  // namespace webcrypto
1930
1931 }  // namespace content