OLD | NEW |
---|---|
1 // Copyright 2014 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "content/child/webcrypto/platform_crypto.h" | 5 #include "content/child/webcrypto/nss/rsa_key_nss.h" |
6 | 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" | 7 #include "base/logging.h" |
16 #include "base/memory/scoped_ptr.h" | |
17 #include "content/child/webcrypto/crypto_data.h" | 8 #include "content/child/webcrypto/crypto_data.h" |
9 #include "content/child/webcrypto/jwk.h" | |
10 #include "content/child/webcrypto/nss/key_nss.h" | |
11 #include "content/child/webcrypto/nss/util_nss.h" | |
18 #include "content/child/webcrypto/status.h" | 12 #include "content/child/webcrypto/status.h" |
19 #include "content/child/webcrypto/webcrypto_util.h" | 13 #include "content/child/webcrypto/webcrypto_util.h" |
20 #include "crypto/nss_util.h" | |
21 #include "crypto/scoped_nss_types.h" | 14 #include "crypto/scoped_nss_types.h" |
22 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h" | |
23 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h" | 15 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h" |
24 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h" | 16 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h" |
25 | 17 |
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 { | 18 namespace content { |
178 | 19 |
179 namespace webcrypto { | 20 namespace webcrypto { |
180 | 21 |
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 { | 22 namespace { |
279 | 23 |
280 Status NssSupportsAesGcm() { | 24 // Converts a (big-endian) WebCrypto BigInteger, with or without leading zeros, |
281 if (g_nss_runtime_support.Get().IsAesGcmSupported()) | 25 // to unsigned long. |
282 return Status::Success(); | 26 bool BigIntegerToLong(const uint8* data, |
283 return Status::ErrorUnsupported( | 27 unsigned int data_size, |
284 "NSS version doesn't support AES-GCM. Try using version 3.15 or later"); | 28 unsigned long* result) { |
29 // TODO(eroman): Fix handling of empty biginteger. | |
Ryan Sleevi
2014/07/17 00:06:54
BUG #?
eroman
2014/07/17 20:37:25
Done. Added http://crubg.com/373552
| |
30 if (data_size == 0) | |
31 return false; | |
32 | |
33 *result = 0; | |
34 for (size_t i = 0; i < data_size; ++i) { | |
35 size_t reverse_i = data_size - i - 1; | |
36 | |
37 if (reverse_i >= sizeof(unsigned long) && data[i]) | |
38 return false; // Too large for a long. | |
39 | |
40 *result |= data[i] << 8 * reverse_i; | |
41 } | |
42 return true; | |
285 } | 43 } |
286 | 44 |
287 Status NssSupportsRsaOaep() { | 45 bool CreatePublicKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm, |
288 if (g_nss_runtime_support.Get().IsRsaOaepSupported()) | 46 SECKEYPublicKey* key, |
289 return Status::Success(); | 47 blink::WebCryptoKeyAlgorithm* key_algorithm) { |
290 return Status::ErrorUnsupported( | 48 // TODO(eroman): What about other key types rsaPss, rsaOaep. |
291 "NSS version doesn't support RSA-OAEP. Try using version 3.16.2 or " | 49 if (!key || key->keyType != rsaKey) |
292 "later"); | 50 return false; |
51 | |
52 unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8; | |
53 CryptoData public_exponent(key->u.rsa.publicExponent.data, | |
54 key->u.rsa.publicExponent.len); | |
55 | |
56 switch (algorithm.paramsType()) { | |
57 case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams: | |
58 case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams: | |
59 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed( | |
60 algorithm.id(), | |
61 modulus_length_bits, | |
62 public_exponent.bytes(), | |
63 public_exponent.byte_length(), | |
64 GetInnerHashAlgorithm(algorithm).id()); | |
65 return true; | |
66 default: | |
67 return false; | |
68 } | |
69 } | |
70 | |
71 bool CreatePrivateKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm, | |
72 SECKEYPrivateKey* key, | |
73 blink::WebCryptoKeyAlgorithm* key_algorithm) { | |
74 crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key)); | |
75 return CreatePublicKeyAlgorithm(algorithm, public_key.get(), key_algorithm); | |
293 } | 76 } |
294 | 77 |
295 #if defined(USE_NSS) && !defined(OS_CHROMEOS) | 78 #if defined(USE_NSS) && !defined(OS_CHROMEOS) |
296 Status ErrorRsaKeyImportNotSupported() { | 79 Status ErrorRsaKeyImportNotSupported() { |
297 return Status::ErrorUnsupported( | 80 return Status::ErrorUnsupported( |
298 "NSS version must be at least 3.16.2 for RSA key import. See " | 81 "NSS version must be at least 3.16.2 for RSA key import. See " |
299 "http://crbug.com/380424"); | 82 "http://crbug.com/380424"); |
300 } | 83 } |
301 | 84 |
302 Status NssSupportsKeyImport(blink::WebCryptoAlgorithmId algorithm) { | 85 // Prior to NSS 3.16.2 RSA key parameters were not validated. This is |
303 // Prior to NSS 3.16.2 RSA key parameters were not validated. This is | 86 // a security problem for RSA private key import from JWK which uses a |
304 // a security problem for RSA private key import from JWK which uses a | 87 // CKA_ID based on the public modulus to retrieve the private key. |
305 // CKA_ID based on the public modulus to retrieve the private key. | 88 Status NssSupportsRsaKeyImport() { |
306 | |
307 if (!IsAlgorithmRsa(algorithm)) | |
308 return Status::Success(); | |
309 | |
310 if (!NSS_VersionCheck("3.16.2")) | 89 if (!NSS_VersionCheck("3.16.2")) |
311 return ErrorRsaKeyImportNotSupported(); | 90 return ErrorRsaKeyImportNotSupported(); |
312 | 91 |
313 // Also ensure that the version of Softoken is 3.16.2 or later. | 92 // Also ensure that the version of Softoken is 3.16.2 or later. |
314 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); | 93 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); |
315 CK_SLOT_INFO info = {}; | 94 CK_SLOT_INFO info = {}; |
316 if (PK11_GetSlotInfo(slot.get(), &info) != SECSuccess) | 95 if (PK11_GetSlotInfo(slot.get(), &info) != SECSuccess) |
317 return ErrorRsaKeyImportNotSupported(); | 96 return ErrorRsaKeyImportNotSupported(); |
318 | 97 |
319 // CK_SLOT_INFO.hardwareVersion contains the major.minor | 98 // CK_SLOT_INFO.hardwareVersion contains the major.minor |
320 // version info for Softoken in the corresponding .major/.minor | 99 // version info for Softoken in the corresponding .major/.minor |
321 // fields, and .firmwareVersion contains the patch.build | 100 // fields, and .firmwareVersion contains the patch.build |
322 // version info (in the .major/.minor fields) | 101 // version info (in the .major/.minor fields) |
323 if ((info.hardwareVersion.major > 3) || | 102 if ((info.hardwareVersion.major > 3) || |
324 (info.hardwareVersion.major == 3 && | 103 (info.hardwareVersion.major == 3 && |
325 (info.hardwareVersion.minor > 16 || | 104 (info.hardwareVersion.minor > 16 || |
326 (info.hardwareVersion.minor == 16 && | 105 (info.hardwareVersion.minor == 16 && |
327 info.firmwareVersion.major >= 2)))) { | 106 info.firmwareVersion.major >= 2)))) { |
328 return Status::Success(); | 107 return Status::Success(); |
329 } | 108 } |
330 | 109 |
331 return ErrorRsaKeyImportNotSupported(); | 110 return ErrorRsaKeyImportNotSupported(); |
332 } | 111 } |
333 #else | 112 #else |
334 Status NssSupportsKeyImport(blink::WebCryptoAlgorithmId) { | 113 Status NssSupportsRsaKeyImport() { |
335 return Status::Success(); | 114 return Status::Success(); |
336 } | 115 } |
337 #endif | 116 #endif |
338 | 117 |
339 // Creates a SECItem for the data in |buffer|. This does NOT make a copy, so | 118 bool CreateRsaHashedPublicKeyAlgorithm( |
340 // |buffer| should outlive the SECItem. | 119 const blink::WebCryptoAlgorithm& algorithm, |
341 SECItem MakeSECItemForBuffer(const CryptoData& buffer) { | 120 SECKEYPublicKey* key, |
342 SECItem item = { | 121 blink::WebCryptoKeyAlgorithm* key_algorithm) { |
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 ¶m, | |
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. | 122 // TODO(eroman): What about other key types rsaPss, rsaOaep. |
598 if (!key || key->keyType != rsaKey) | 123 if (!key || key->keyType != rsaKey) |
599 return false; | 124 return false; |
600 | 125 |
601 unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8; | 126 unsigned int modulus_length_bits = SECKEY_PublicKeyStrength(key) * 8; |
602 CryptoData public_exponent(key->u.rsa.publicExponent.data, | 127 CryptoData public_exponent(key->u.rsa.publicExponent.data, |
603 key->u.rsa.publicExponent.len); | 128 key->u.rsa.publicExponent.len); |
604 | 129 |
605 switch (algorithm.paramsType()) { | 130 switch (algorithm.paramsType()) { |
606 case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams: | 131 case blink::WebCryptoAlgorithmParamsTypeRsaHashedImportParams: |
607 case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams: | 132 case blink::WebCryptoAlgorithmParamsTypeRsaHashedKeyGenParams: |
608 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed( | 133 *key_algorithm = blink::WebCryptoKeyAlgorithm::createRsaHashed( |
609 algorithm.id(), | 134 algorithm.id(), |
610 modulus_length_bits, | 135 modulus_length_bits, |
611 public_exponent.bytes(), | 136 public_exponent.bytes(), |
612 public_exponent.byte_length(), | 137 public_exponent.byte_length(), |
613 GetInnerHashAlgorithm(algorithm).id()); | 138 GetInnerHashAlgorithm(algorithm).id()); |
614 return true; | 139 return true; |
615 default: | 140 default: |
616 return false; | 141 return false; |
617 } | 142 } |
618 } | 143 } |
619 | 144 |
620 bool CreatePrivateKeyAlgorithm(const blink::WebCryptoAlgorithm& algorithm, | 145 bool CreateRsaHashedPrivateKeyAlgorithm( |
621 SECKEYPrivateKey* key, | 146 const blink::WebCryptoAlgorithm& algorithm, |
622 blink::WebCryptoKeyAlgorithm* key_algorithm) { | 147 SECKEYPrivateKey* key, |
148 blink::WebCryptoKeyAlgorithm* key_algorithm) { | |
623 crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key)); | 149 crypto::ScopedSECKEYPublicKey public_key(SECKEY_ConvertToPublicKey(key)); |
624 return CreatePublicKeyAlgorithm(algorithm, public_key.get(), key_algorithm); | 150 if (!public_key) |
625 } | 151 return false; |
626 | 152 return CreateRsaHashedPublicKeyAlgorithm( |
627 // The Default IV for AES-KW. See http://www.ietf.org/rfc/rfc3394.txt | 153 algorithm, public_key.get(), key_algorithm); |
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 } | 154 } |
733 | 155 |
734 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]: | 156 // From PKCS#1 [http://tools.ietf.org/html/rfc3447]: |
735 // | 157 // |
736 // RSAPrivateKey ::= SEQUENCE { | 158 // RSAPrivateKey ::= SEQUENCE { |
737 // version Version, | 159 // version Version, |
738 // modulus INTEGER, -- n | 160 // modulus INTEGER, -- n |
739 // publicExponent INTEGER, -- e | 161 // publicExponent INTEGER, -- e |
740 // privateExponent INTEGER, -- d | 162 // privateExponent INTEGER, -- d |
741 // prime1 INTEGER, -- p | 163 // prime1 INTEGER, -- p |
(...skipping 97 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
839 SECITEM_FreeItem(&out->public_exponent, PR_FALSE); | 261 SECITEM_FreeItem(&out->public_exponent, PR_FALSE); |
840 SECITEM_FreeItem(&out->private_exponent, PR_FALSE); | 262 SECITEM_FreeItem(&out->private_exponent, PR_FALSE); |
841 SECITEM_FreeItem(&out->prime1, PR_FALSE); | 263 SECITEM_FreeItem(&out->prime1, PR_FALSE); |
842 SECITEM_FreeItem(&out->prime2, PR_FALSE); | 264 SECITEM_FreeItem(&out->prime2, PR_FALSE); |
843 SECITEM_FreeItem(&out->exponent1, PR_FALSE); | 265 SECITEM_FreeItem(&out->exponent1, PR_FALSE); |
844 SECITEM_FreeItem(&out->exponent2, PR_FALSE); | 266 SECITEM_FreeItem(&out->exponent2, PR_FALSE); |
845 SECITEM_FreeItem(&out->coefficient, PR_FALSE); | 267 SECITEM_FreeItem(&out->coefficient, PR_FALSE); |
846 } | 268 } |
847 }; | 269 }; |
848 | 270 |
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, | 271 typedef scoped_ptr<CERTSubjectPublicKeyInfo, |
1004 crypto::NSSDestroyer<CERTSubjectPublicKeyInfo, | 272 crypto::NSSDestroyer<CERTSubjectPublicKeyInfo, |
1005 SECKEY_DestroySubjectPublicKeyInfo> > | 273 SECKEY_DestroySubjectPublicKeyInfo> > |
1006 ScopedCERTSubjectPublicKeyInfo; | 274 ScopedCERTSubjectPublicKeyInfo; |
1007 | 275 |
1008 // Validates an NSS KeyType against a WebCrypto import algorithm. | 276 struct DestroyGenericObject { |
1009 bool ValidateNssKeyTypeAgainstInputAlgorithm( | 277 void operator()(PK11GenericObject* o) const { |
1010 KeyType key_type, | 278 if (o) |
1011 const blink::WebCryptoAlgorithm& algorithm) { | 279 PK11_DestroyGenericObject(o); |
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 } | 280 } |
1024 return false; | 281 }; |
282 | |
283 typedef scoped_ptr<PK11GenericObject, DestroyGenericObject> | |
284 ScopedPK11GenericObject; | |
285 | |
286 // Helper to add an attribute to a template. | |
287 void AddAttribute(CK_ATTRIBUTE_TYPE type, | |
288 void* value, | |
289 unsigned long length, | |
290 std::vector<CK_ATTRIBUTE>* templ) { | |
291 CK_ATTRIBUTE attribute = {type, value, length}; | |
292 templ->push_back(attribute); | |
1025 } | 293 } |
1026 | 294 |
1027 } // namespace | 295 // Helper to optionally add an attribute to a template, if the provided data is |
1028 | 296 // non-empty. |
1029 Status ImportKeySpki(const blink::WebCryptoAlgorithm& algorithm, | 297 void AddOptionalAttribute(CK_ATTRIBUTE_TYPE type, |
1030 const CryptoData& key_data, | 298 const CryptoData& data, |
1031 bool extractable, | 299 std::vector<CK_ATTRIBUTE>* templ) { |
1032 blink::WebCryptoKeyUsageMask usage_mask, | 300 if (!data.byte_length()) |
1033 blink::WebCryptoKey* key) { | 301 return; |
1034 Status status = NssSupportsKeyImport(algorithm.id()); | 302 CK_ATTRIBUTE attribute = {type, const_cast<unsigned char*>(data.bytes()), |
1035 if (status.IsError()) | 303 data.byte_length()}; |
1036 return status; | 304 templ->push_back(attribute); |
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 } | 305 } |
1079 | 306 |
1080 Status ExportKeySpki(PublicKey* key, std::vector<uint8>* buffer) { | 307 void AddOptionalAttribute(CK_ATTRIBUTE_TYPE type, |
1081 const crypto::ScopedSECItem spki_der( | 308 const std::string& data, |
1082 SECKEY_EncodeDERSubjectPublicKeyInfo(key->key())); | 309 std::vector<CK_ATTRIBUTE>* templ) { |
1083 // http://crbug.com/366427: the spec does not define any other failures for | 310 AddOptionalAttribute(type, CryptoData(data), templ); |
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 } | 311 } |
1095 | 312 |
1096 Status ExportRsaPublicKey(PublicKey* key, | 313 Status ExportKeyPkcs8Nss(SECKEYPrivateKey* key, std::vector<uint8>* buffer) { |
1097 std::vector<uint8>* modulus, | 314 if (key->keyType != rsaKey) |
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(); | 315 return Status::ErrorUnsupported(); |
1148 | 316 |
1149 // TODO(rsleevi): Implement OAEP support according to the spec. | 317 // TODO(rsleevi): Implement OAEP support according to the spec. |
1150 | 318 |
1151 #if defined(USE_NSS) | 319 #if defined(USE_NSS) |
1152 // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code. | 320 // PK11_ExportDERPrivateKeyInfo isn't available. Use our fallback code. |
1153 const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; | 321 const SECOidTag algorithm = SEC_OID_PKCS1_RSA_ENCRYPTION; |
1154 const int kPrivateKeyInfoVersion = 0; | 322 const int kPrivateKeyInfoVersion = 0; |
1155 | 323 |
1156 SECKEYPrivateKeyInfo private_key_info = {}; | 324 SECKEYPrivateKeyInfo private_key_info = {}; |
1157 RSAPrivateKey rsa_private_key = {}; | 325 RSAPrivateKey rsa_private_key = {}; |
1158 scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key( | 326 scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key( |
1159 &rsa_private_key); | 327 &rsa_private_key); |
1160 | 328 |
1161 // http://crbug.com/366427: the spec does not define any other failures for | 329 // http://crbug.com/366427: the spec does not define any other failures for |
1162 // exporting, so none of the subsequent errors are spec compliant. | 330 // exporting, so none of the subsequent errors are spec compliant. |
1163 if (!InitRSAPrivateKey(key->key(), &rsa_private_key)) | 331 if (!InitRSAPrivateKey(key, &rsa_private_key)) |
1164 return Status::OperationError(); | 332 return Status::OperationError(); |
1165 | 333 |
1166 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE)); | 334 crypto::ScopedPLArenaPool arena(PORT_NewArena(DER_DEFAULT_CHUNKSIZE)); |
1167 if (!arena.get()) | 335 if (!arena.get()) |
1168 return Status::OperationError(); | 336 return Status::OperationError(); |
1169 | 337 |
1170 if (!SEC_ASN1EncodeItem(arena.get(), | 338 if (!SEC_ASN1EncodeItem(arena.get(), |
1171 &private_key_info.privateKey, | 339 &private_key_info.privateKey, |
1172 &rsa_private_key, | 340 &rsa_private_key, |
1173 RSAPrivateKeyTemplate)) | 341 RSAPrivateKeyTemplate)) |
(...skipping 18 matching lines...) Expand all Loading... | |
1192 PK11_ExportDERPrivateKeyInfo(key->key(), NULL)); | 360 PK11_ExportDERPrivateKeyInfo(key->key(), NULL)); |
1193 #endif // defined(USE_NSS) | 361 #endif // defined(USE_NSS) |
1194 | 362 |
1195 if (!encoded_key.get()) | 363 if (!encoded_key.get()) |
1196 return Status::OperationError(); | 364 return Status::OperationError(); |
1197 | 365 |
1198 buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len); | 366 buffer->assign(encoded_key->data, encoded_key->data + encoded_key->len); |
1199 return Status::Success(); | 367 return Status::Success(); |
1200 } | 368 } |
1201 | 369 |
1202 Status ImportKeyPkcs8(const blink::WebCryptoAlgorithm& algorithm, | 370 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm, |
1203 const CryptoData& key_data, | 371 bool extractable, |
1204 bool extractable, | 372 blink::WebCryptoKeyUsageMask usage_mask, |
1205 blink::WebCryptoKeyUsageMask usage_mask, | 373 const JwkRsaInfo& params, |
1206 blink::WebCryptoKey* key) { | 374 blink::WebCryptoKey* key) { |
1207 Status status = NssSupportsKeyImport(algorithm.id()); | 375 Status status = NssSupportsRsaKeyImport(); |
1208 if (status.IsError()) | 376 if (status.IsError()) |
1209 return status; | 377 return status; |
1210 | 378 |
1211 DCHECK(key); | 379 CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY; |
380 CK_KEY_TYPE key_type = CKK_RSA; | |
381 CK_BBOOL ck_false = CK_FALSE; | |
1212 | 382 |
1213 if (!key_data.byte_length()) | 383 std::vector<CK_ATTRIBUTE> key_template; |
1214 return Status::ErrorImportEmptyKeyData(); | |
1215 DCHECK(key_data.bytes()); | |
1216 | 384 |
1217 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8 | 385 AddAttribute(CKA_CLASS, &obj_class, sizeof(obj_class), &key_template); |
1218 // private key info object. | 386 AddAttribute(CKA_KEY_TYPE, &key_type, sizeof(key_type), &key_template); |
1219 SECItem pki_der = MakeSECItemForBuffer(key_data); | 387 AddAttribute(CKA_TOKEN, &ck_false, sizeof(ck_false), &key_template); |
388 AddAttribute(CKA_SENSITIVE, &ck_false, sizeof(ck_false), &key_template); | |
389 AddAttribute(CKA_PRIVATE, &ck_false, sizeof(ck_false), &key_template); | |
1220 | 390 |
1221 SECKEYPrivateKey* seckey_private_key = NULL; | 391 // Required properties. |
392 AddOptionalAttribute(CKA_MODULUS, params.n, &key_template); | |
393 AddOptionalAttribute(CKA_PUBLIC_EXPONENT, params.e, &key_template); | |
394 AddOptionalAttribute(CKA_PRIVATE_EXPONENT, params.d, &key_template); | |
395 | |
396 // Manufacture a CKA_ID so the created key can be retrieved later as a | |
397 // SECKEYPrivateKey using FindKeyByKeyID(). Unfortunately there isn't a more | |
398 // direct way to do this in NSS. | |
399 // | |
400 // For consistency with other NSS key creation methods, set the CKA_ID to | |
401 // PK11_MakeIDFromPubKey(). There are some problems with | |
402 // this approach: | |
403 // | |
404 // (1) Prior to NSS 3.16.2, there is no parameter validation when creating | |
405 // private keys. It is therefore possible to construct a key using the | |
406 // known public modulus, and where all the other parameters are bogus. | |
407 // FindKeyByKeyID() returns the first key matching the ID. So this would | |
408 // effectively allow an attacker to retrieve a private key of their | |
409 // choice. | |
410 // TODO(eroman): Once NSS rolls and this is fixed, disallow RSA key | |
411 // import on older versions of NSS. | |
412 // http://crbug.com/378315 | |
Ryan Sleevi
2014/07/17 00:06:54
Can you do this now, for all non-Linux platforms?
eroman
2014/07/17 20:37:25
This is already done. I have removed the TODO.
No
| |
413 // | |
414 // (2) The ID space is shared by different key types. So theoretically | |
415 // possible to retrieve a key of the wrong type which has a matching | |
416 // CKA_ID. In practice I am told this is not likely except for small key | |
417 // sizes, since would require constructing keys with the same public | |
418 // data. | |
419 // | |
420 // (3) FindKeyByKeyID() doesn't necessarily return the object that was just | |
421 // created by CreateGenericObject. If the pre-existing key was | |
422 // provisioned with flags incompatible with WebCrypto (for instance | |
423 // marked sensitive) then this will break things. | |
424 SECItem modulus_item = MakeSECItemForBuffer(CryptoData(params.n)); | |
425 crypto::ScopedSECItem object_id(PK11_MakeIDFromPubKey(&modulus_item)); | |
426 AddOptionalAttribute( | |
427 CKA_ID, CryptoData(object_id->data, object_id->len), &key_template); | |
428 | |
429 // Optional properties (all of these will have been specified or none). | |
430 AddOptionalAttribute(CKA_PRIME_1, params.p, &key_template); | |
431 AddOptionalAttribute(CKA_PRIME_2, params.q, &key_template); | |
432 AddOptionalAttribute(CKA_EXPONENT_1, params.dp, &key_template); | |
433 AddOptionalAttribute(CKA_EXPONENT_2, params.dq, &key_template); | |
434 AddOptionalAttribute(CKA_COEFFICIENT, params.qi, &key_template); | |
435 | |
1222 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); | 436 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 | 437 |
1237 const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get()); | 438 ScopedPK11GenericObject key_object(PK11_CreateGenericObject( |
1238 if (!ValidateNssKeyTypeAgainstInputAlgorithm(sec_key_type, algorithm)) | 439 slot.get(), &key_template[0], key_template.size(), PR_FALSE)); |
1239 return Status::DataError(); | 440 |
441 if (!key_object) | |
442 return Status::OperationError(); | |
443 | |
444 crypto::ScopedSECKEYPrivateKey private_key_tmp( | |
445 PK11_FindKeyByKeyID(slot.get(), object_id.get(), NULL)); | |
446 | |
447 // PK11_FindKeyByKeyID() may return a handle to an existing key, rather than | |
448 // the object created by PK11_CreateGenericObject(). | |
449 crypto::ScopedSECKEYPrivateKey private_key( | |
450 SECKEY_CopyPrivateKey(private_key_tmp.get())); | |
451 | |
452 if (!private_key) | |
453 return Status::OperationError(); | |
1240 | 454 |
1241 blink::WebCryptoKeyAlgorithm key_algorithm; | 455 blink::WebCryptoKeyAlgorithm key_algorithm; |
1242 if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm)) | 456 if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm)) |
1243 return Status::ErrorUnexpected(); | 457 return Status::ErrorUnexpected(); |
1244 | 458 |
1245 scoped_ptr<PrivateKey> key_handle; | 459 std::vector<uint8> pkcs8_data; |
1246 status = PrivateKey::Create(private_key.Pass(), key_algorithm, &key_handle); | 460 status = ExportKeyPkcs8Nss(private_key.get(), &pkcs8_data); |
1247 if (status.IsError()) | 461 if (status.IsError()) |
1248 return status; | 462 return status; |
1249 | 463 |
464 scoped_ptr<PrivateKeyNss> key_handle( | |
465 new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data))); | |
466 | |
1250 *key = blink::WebCryptoKey::create(key_handle.release(), | 467 *key = blink::WebCryptoKey::create(key_handle.release(), |
1251 blink::WebCryptoKeyTypePrivate, | 468 blink::WebCryptoKeyTypePrivate, |
1252 extractable, | 469 extractable, |
1253 key_algorithm, | 470 key_algorithm, |
1254 usage_mask); | 471 usage_mask); |
472 return Status::Success(); | |
473 } | |
474 | |
475 Status ExportKeySpkiNss(SECKEYPublicKey* key, std::vector<uint8>* buffer) { | |
476 const crypto::ScopedSECItem spki_der( | |
477 SECKEY_EncodeDERSubjectPublicKeyInfo(key)); | |
478 if (!spki_der) | |
479 return Status::OperationError(); | |
480 | |
481 DCHECK(spki_der->data); | |
482 DCHECK(spki_der->len); | |
Ryan Sleevi
2014/07/17 00:06:54
Also questioning whether this should be CHECK.
eroman
2014/07/17 20:37:26
Removed the DCHECKs (they provide little value to
| |
483 | |
484 buffer->assign(spki_der->data, spki_der->data + spki_der->len); | |
1255 | 485 |
1256 return Status::Success(); | 486 return Status::Success(); |
1257 } | 487 } |
1258 | 488 |
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 ¶m_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 ¶m_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 ¶m, | |
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 ¶m, | |
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 // keySizeInBits is a signed type, don't pass in a negative value. | |
1508 if (modulus_length_bits > INT_MAX) | |
1509 return Status::OperationError(); | |
1510 rsa_gen_params.keySizeInBits = modulus_length_bits; | |
1511 rsa_gen_params.pe = public_exponent; | |
1512 | |
1513 // Flags are verified at the Blink layer; here the flags are set to all | |
1514 // possible operations for the given key type. | |
1515 CK_FLAGS operation_flags; | |
1516 switch (algorithm.id()) { | |
1517 case blink::WebCryptoAlgorithmIdRsaOaep: | |
1518 operation_flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP; | |
1519 break; | |
1520 case blink::WebCryptoAlgorithmIdRsaSsaPkcs1v1_5: | |
1521 operation_flags = CKF_SIGN | CKF_VERIFY; | |
1522 break; | |
1523 default: | |
1524 NOTREACHED(); | |
1525 return Status::ErrorUnexpected(); | |
1526 } | |
1527 const CK_FLAGS operation_flags_mask = | |
1528 CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP; | |
1529 | |
1530 // The private key must be marked as insensitive and extractable, otherwise it | |
1531 // cannot later be exported in unencrypted form or structured-cloned. | |
1532 const PK11AttrFlags attribute_flags = | |
1533 PK11_ATTR_INSENSITIVE | PK11_ATTR_EXTRACTABLE; | |
1534 | |
1535 // Note: NSS does not generate an sec_public_key if the call below fails, | |
1536 // so there is no danger of a leaked sec_public_key. | |
1537 SECKEYPublicKey* sec_public_key = NULL; | |
1538 crypto::ScopedSECKEYPrivateKey scoped_sec_private_key( | |
1539 PK11_GenerateKeyPairWithOpFlags(slot.get(), | |
1540 CKM_RSA_PKCS_KEY_PAIR_GEN, | |
1541 &rsa_gen_params, | |
1542 &sec_public_key, | |
1543 attribute_flags, | |
1544 operation_flags, | |
1545 operation_flags_mask, | |
1546 NULL)); | |
1547 if (!scoped_sec_private_key) | |
1548 return Status::OperationError(); | |
1549 | |
1550 blink::WebCryptoKeyAlgorithm key_algorithm; | |
1551 if (!CreatePublicKeyAlgorithm(algorithm, sec_public_key, &key_algorithm)) | |
1552 return Status::ErrorUnexpected(); | |
1553 | |
1554 scoped_ptr<PublicKey> public_key_handle; | |
1555 Status status = PublicKey::Create( | |
1556 crypto::ScopedSECKEYPublicKey(sec_public_key), &public_key_handle); | |
1557 if (status.IsError()) | |
1558 return status; | |
1559 | |
1560 scoped_ptr<PrivateKey> private_key_handle; | |
1561 status = PrivateKey::Create( | |
1562 scoped_sec_private_key.Pass(), key_algorithm, &private_key_handle); | |
1563 if (status.IsError()) | |
1564 return status; | |
1565 | |
1566 *public_key = blink::WebCryptoKey::create(public_key_handle.release(), | |
1567 blink::WebCryptoKeyTypePublic, | |
1568 true, | |
1569 key_algorithm, | |
1570 public_key_usage_mask); | |
1571 *private_key = blink::WebCryptoKey::create(private_key_handle.release(), | |
1572 blink::WebCryptoKeyTypePrivate, | |
1573 extractable, | |
1574 key_algorithm, | |
1575 private_key_usage_mask); | |
1576 | |
1577 return Status::Success(); | |
1578 } | |
1579 | |
1580 void Init() { | |
1581 crypto::EnsureNSSInit(); | |
1582 } | |
1583 | |
1584 Status DigestSha(blink::WebCryptoAlgorithmId algorithm, | |
1585 const CryptoData& data, | |
1586 std::vector<uint8>* buffer) { | |
1587 DigestorNSS digestor(algorithm); | |
1588 Status error = digestor.ConsumeWithStatus(data.bytes(), data.byte_length()); | |
1589 // http://crbug.com/366427: the spec does not define any other failures for | |
1590 // digest, so none of the subsequent errors are spec compliant. | |
1591 if (!error.IsSuccess()) | |
1592 return error; | |
1593 return digestor.FinishWithVectorAndStatus(buffer); | |
1594 } | |
1595 | |
1596 scoped_ptr<blink::WebCryptoDigestor> CreateDigestor( | |
1597 blink::WebCryptoAlgorithmId algorithm_id) { | |
1598 return scoped_ptr<blink::WebCryptoDigestor>(new DigestorNSS(algorithm_id)); | |
1599 } | |
1600 | |
1601 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm, | |
1602 bool extractable, | |
1603 blink::WebCryptoKeyUsageMask usage_mask, | |
1604 unsigned keylen_bytes, | |
1605 blink::WebCryptoKey* key) { | |
1606 CK_MECHANISM_TYPE mech = WebCryptoAlgorithmToGenMechanism(algorithm); | |
1607 blink::WebCryptoKeyType key_type = blink::WebCryptoKeyTypeSecret; | |
1608 | |
1609 if (mech == CKM_INVALID_MECHANISM) | |
1610 return Status::ErrorUnsupported(); | |
1611 | |
1612 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot()); | |
1613 if (!slot) | |
1614 return Status::OperationError(); | |
1615 | |
1616 crypto::ScopedPK11SymKey pk11_key( | |
1617 PK11_KeyGen(slot.get(), mech, NULL, keylen_bytes, NULL)); | |
1618 | |
1619 if (!pk11_key) | |
1620 return Status::OperationError(); | |
1621 | |
1622 blink::WebCryptoKeyAlgorithm key_algorithm; | |
1623 if (!CreateSecretKeyAlgorithm(algorithm, keylen_bytes, &key_algorithm)) | |
1624 return Status::ErrorUnexpected(); | |
1625 | |
1626 scoped_ptr<SymKey> key_handle; | |
1627 Status status = SymKey::Create(pk11_key.Pass(), &key_handle); | |
1628 if (status.IsError()) | |
1629 return status; | |
1630 | |
1631 *key = blink::WebCryptoKey::create( | |
1632 key_handle.release(), key_type, extractable, key_algorithm, usage_mask); | |
1633 return Status::Success(); | |
1634 } | |
1635 | |
1636 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm, | 489 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm, |
1637 bool extractable, | 490 bool extractable, |
1638 blink::WebCryptoKeyUsageMask usage_mask, | 491 blink::WebCryptoKeyUsageMask usage_mask, |
1639 const CryptoData& modulus_data, | 492 const CryptoData& modulus_data, |
1640 const CryptoData& exponent_data, | 493 const CryptoData& exponent_data, |
1641 blink::WebCryptoKey* key) { | 494 blink::WebCryptoKey* key) { |
1642 if (!modulus_data.byte_length()) | 495 if (!modulus_data.byte_length()) |
1643 return Status::ErrorImportRsaEmptyModulus(); | 496 return Status::ErrorImportRsaEmptyModulus(); |
1644 | 497 |
1645 if (!exponent_data.byte_length()) | 498 if (!exponent_data.byte_length()) |
(...skipping 14 matching lines...) Expand all Loading... | |
1660 SECItem modulus; | 513 SECItem modulus; |
1661 SECItem exponent; | 514 SECItem exponent; |
1662 }; | 515 }; |
1663 const RsaPublicKeyData pubkey_in = { | 516 const RsaPublicKeyData pubkey_in = { |
1664 {siUnsignedInteger, const_cast<unsigned char*>(modulus_data.bytes()), | 517 {siUnsignedInteger, const_cast<unsigned char*>(modulus_data.bytes()), |
1665 modulus_data.byte_length()}, | 518 modulus_data.byte_length()}, |
1666 {siUnsignedInteger, const_cast<unsigned char*>(exponent_data.bytes()), | 519 {siUnsignedInteger, const_cast<unsigned char*>(exponent_data.bytes()), |
1667 exponent_data.byte_length()}}; | 520 exponent_data.byte_length()}}; |
1668 const SEC_ASN1Template rsa_public_key_template[] = { | 521 const SEC_ASN1Template rsa_public_key_template[] = { |
1669 {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)}, | 522 {SEC_ASN1_SEQUENCE, 0, NULL, sizeof(RsaPublicKeyData)}, |
1670 {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), }, | 523 { |
1671 {SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), }, | 524 SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, modulus), |
1672 {0, }}; | 525 }, |
526 { | |
527 SEC_ASN1_INTEGER, offsetof(RsaPublicKeyData, exponent), | |
528 }, | |
529 { | |
530 0, | |
531 }}; | |
1673 | 532 |
1674 // DER-encode the public key. | 533 // DER-encode the public key. |
1675 crypto::ScopedSECItem pubkey_der( | 534 crypto::ScopedSECItem pubkey_der( |
1676 SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template)); | 535 SEC_ASN1EncodeItem(NULL, NULL, &pubkey_in, rsa_public_key_template)); |
1677 if (!pubkey_der) | 536 if (!pubkey_der) |
1678 return Status::OperationError(); | 537 return Status::OperationError(); |
1679 | 538 |
1680 // Import the DER-encoded public key to create an RSA SECKEYPublicKey. | 539 // Import the DER-encoded public key to create an RSA SECKEYPublicKey. |
1681 crypto::ScopedSECKEYPublicKey pubkey( | 540 crypto::ScopedSECKEYPublicKey pubkey( |
1682 SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA)); | 541 SECKEY_ImportDERPublicKey(pubkey_der.get(), CKK_RSA)); |
1683 if (!pubkey) | 542 if (!pubkey) |
1684 return Status::OperationError(); | 543 return Status::OperationError(); |
1685 | 544 |
1686 blink::WebCryptoKeyAlgorithm key_algorithm; | 545 blink::WebCryptoKeyAlgorithm key_algorithm; |
1687 if (!CreatePublicKeyAlgorithm(algorithm, pubkey.get(), &key_algorithm)) | 546 if (!CreatePublicKeyAlgorithm(algorithm, pubkey.get(), &key_algorithm)) |
1688 return Status::ErrorUnexpected(); | 547 return Status::ErrorUnexpected(); |
1689 | 548 |
1690 scoped_ptr<PublicKey> key_handle; | 549 std::vector<uint8> spki_data; |
1691 Status status = PublicKey::Create(pubkey.Pass(), &key_handle); | 550 Status status = ExportKeySpkiNss(pubkey.get(), &spki_data); |
1692 if (status.IsError()) | 551 if (status.IsError()) |
1693 return status; | 552 return status; |
1694 | 553 |
554 scoped_ptr<PublicKeyNss> key_handle( | |
555 new PublicKeyNss(pubkey.Pass(), CryptoData(spki_data))); | |
556 | |
1695 *key = blink::WebCryptoKey::create(key_handle.release(), | 557 *key = blink::WebCryptoKey::create(key_handle.release(), |
1696 blink::WebCryptoKeyTypePublic, | 558 blink::WebCryptoKeyTypePublic, |
1697 extractable, | 559 extractable, |
1698 key_algorithm, | 560 key_algorithm, |
1699 usage_mask); | 561 usage_mask); |
1700 return Status::Success(); | 562 return Status::Success(); |
1701 } | 563 } |
1702 | 564 |
1703 struct DestroyGenericObject { | 565 } // namespace |
1704 void operator()(PK11GenericObject* o) const { | 566 |
1705 if (o) | 567 Status RsaHashedAlgorithm::VerifyKeyUsagesBeforeGenerateKeyPair( |
1706 PK11_DestroyGenericObject(o); | 568 blink::WebCryptoKeyUsageMask combined_usage_mask, |
569 blink::WebCryptoKeyUsageMask* public_usage_mask, | |
570 blink::WebCryptoKeyUsageMask* private_usage_mask) const { | |
571 Status status = CheckKeyCreationUsages( | |
572 all_public_key_usages_ | all_private_key_usages_, combined_usage_mask); | |
573 if (status.IsError()) | |
574 return status; | |
575 | |
576 *public_usage_mask = combined_usage_mask & all_public_key_usages_; | |
577 *private_usage_mask = combined_usage_mask & all_private_key_usages_; | |
578 | |
579 return Status::Success(); | |
580 } | |
581 | |
582 Status RsaHashedAlgorithm::GenerateKeyPair( | |
583 const blink::WebCryptoAlgorithm& algorithm, | |
584 bool extractable, | |
585 blink::WebCryptoKeyUsageMask public_usage_mask, | |
586 blink::WebCryptoKeyUsageMask private_usage_mask, | |
587 blink::WebCryptoKey* public_key, | |
588 blink::WebCryptoKey* private_key) const { | |
589 const blink::WebCryptoRsaHashedKeyGenParams* params = | |
590 algorithm.rsaHashedKeyGenParams(); | |
591 | |
592 if (!params->modulusLengthBits()) | |
593 return Status::ErrorGenerateRsaZeroModulus(); | |
594 | |
595 unsigned long public_exponent = 0; | |
596 if (!BigIntegerToLong(params->publicExponent().data(), | |
597 params->publicExponent().size(), | |
598 &public_exponent) || | |
599 (public_exponent != 3 && public_exponent != 65537)) { | |
600 return Status::ErrorGenerateKeyPublicExponent(); | |
1707 } | 601 } |
1708 }; | 602 |
1709 | 603 crypto::ScopedPK11Slot slot(PK11_GetInternalKeySlot()); |
1710 typedef scoped_ptr<PK11GenericObject, DestroyGenericObject> | 604 if (!slot) |
1711 ScopedPK11GenericObject; | 605 return Status::OperationError(); |
1712 | 606 |
1713 // Helper to add an attribute to a template. | 607 PK11RSAGenParams rsa_gen_params; |
1714 void AddAttribute(CK_ATTRIBUTE_TYPE type, | 608 // keySizeInBits is a signed type, don't pass in a negative value. |
1715 void* value, | 609 if (params->modulusLengthBits() > INT_MAX) |
1716 unsigned long length, | 610 return Status::OperationError(); |
1717 std::vector<CK_ATTRIBUTE>* templ) { | 611 rsa_gen_params.keySizeInBits = params->modulusLengthBits(); |
1718 CK_ATTRIBUTE attribute = {type, value, length}; | 612 rsa_gen_params.pe = public_exponent; |
1719 templ->push_back(attribute); | 613 |
1720 } | 614 const CK_FLAGS operation_flags_mask = |
1721 | 615 CKF_ENCRYPT | CKF_DECRYPT | CKF_SIGN | CKF_VERIFY | CKF_WRAP | CKF_UNWRAP; |
1722 // Helper to optionally add an attribute to a template, if the provided data is | 616 |
1723 // non-empty. | 617 // The private key must be marked as insensitive and extractable, otherwise it |
1724 void AddOptionalAttribute(CK_ATTRIBUTE_TYPE type, | 618 // cannot later be exported in unencrypted form or structured-cloned. |
1725 const CryptoData& data, | 619 const PK11AttrFlags attribute_flags = |
1726 std::vector<CK_ATTRIBUTE>* templ) { | 620 PK11_ATTR_INSENSITIVE | PK11_ATTR_EXTRACTABLE; |
1727 if (!data.byte_length()) | 621 |
1728 return; | 622 // Note: NSS does not generate an sec_public_key if the call below fails, |
1729 CK_ATTRIBUTE attribute = {type, const_cast<unsigned char*>(data.bytes()), | 623 // so there is no danger of a leaked sec_public_key. |
1730 data.byte_length()}; | 624 SECKEYPublicKey* sec_public_key; |
1731 templ->push_back(attribute); | 625 crypto::ScopedSECKEYPrivateKey scoped_sec_private_key( |
1732 } | 626 PK11_GenerateKeyPairWithOpFlags(slot.get(), |
1733 | 627 CKM_RSA_PKCS_KEY_PAIR_GEN, |
1734 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm, | 628 &rsa_gen_params, |
1735 bool extractable, | 629 &sec_public_key, |
1736 blink::WebCryptoKeyUsageMask usage_mask, | 630 attribute_flags, |
1737 const CryptoData& modulus, | 631 generate_flags_, |
1738 const CryptoData& public_exponent, | 632 operation_flags_mask, |
1739 const CryptoData& private_exponent, | 633 NULL)); |
1740 const CryptoData& prime1, | 634 if (!scoped_sec_private_key) |
1741 const CryptoData& prime2, | 635 return Status::OperationError(); |
1742 const CryptoData& exponent1, | 636 |
1743 const CryptoData& exponent2, | 637 blink::WebCryptoKeyAlgorithm key_algorithm; |
1744 const CryptoData& coefficient, | 638 if (!CreatePublicKeyAlgorithm(algorithm, sec_public_key, &key_algorithm)) |
1745 blink::WebCryptoKey* key) { | 639 return Status::ErrorUnexpected(); |
1746 Status status = NssSupportsKeyImport(algorithm.id()); | 640 |
1747 if (status.IsError()) | 641 std::vector<uint8> spki_data; |
1748 return status; | 642 Status status = ExportKeySpkiNss(sec_public_key, &spki_data); |
1749 | 643 if (status.IsError()) |
1750 CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY; | 644 return status; |
1751 CK_KEY_TYPE key_type = CKK_RSA; | 645 |
1752 CK_BBOOL ck_false = CK_FALSE; | 646 scoped_ptr<PublicKeyNss> public_key_handle(new PublicKeyNss( |
1753 | 647 crypto::ScopedSECKEYPublicKey(sec_public_key), CryptoData(spki_data))); |
1754 std::vector<CK_ATTRIBUTE> key_template; | 648 |
1755 | 649 std::vector<uint8> pkcs8_data; |
1756 AddAttribute(CKA_CLASS, &obj_class, sizeof(obj_class), &key_template); | 650 status = ExportKeyPkcs8Nss(scoped_sec_private_key.get(), &pkcs8_data); |
1757 AddAttribute(CKA_KEY_TYPE, &key_type, sizeof(key_type), &key_template); | 651 if (status.IsError()) |
1758 AddAttribute(CKA_TOKEN, &ck_false, sizeof(ck_false), &key_template); | 652 return status; |
1759 AddAttribute(CKA_SENSITIVE, &ck_false, sizeof(ck_false), &key_template); | 653 |
1760 AddAttribute(CKA_PRIVATE, &ck_false, sizeof(ck_false), &key_template); | 654 scoped_ptr<PrivateKeyNss> private_key_handle( |
1761 | 655 new PrivateKeyNss(scoped_sec_private_key.Pass(), CryptoData(pkcs8_data))); |
1762 // Required properties. | 656 |
1763 AddOptionalAttribute(CKA_MODULUS, modulus, &key_template); | 657 *public_key = blink::WebCryptoKey::create(public_key_handle.release(), |
1764 AddOptionalAttribute(CKA_PUBLIC_EXPONENT, public_exponent, &key_template); | 658 blink::WebCryptoKeyTypePublic, |
1765 AddOptionalAttribute(CKA_PRIVATE_EXPONENT, private_exponent, &key_template); | 659 true, |
1766 | 660 key_algorithm, |
1767 // Manufacture a CKA_ID so the created key can be retrieved later as a | 661 public_usage_mask); |
1768 // SECKEYPrivateKey using FindKeyByKeyID(). Unfortunately there isn't a more | 662 *private_key = blink::WebCryptoKey::create(private_key_handle.release(), |
1769 // direct way to do this in NSS. | 663 blink::WebCryptoKeyTypePrivate, |
1770 // | 664 extractable, |
1771 // For consistency with other NSS key creation methods, set the CKA_ID to | 665 key_algorithm, |
1772 // PK11_MakeIDFromPubKey(). There are some problems with | 666 private_usage_mask); |
1773 // this approach: | 667 |
1774 // | 668 return Status::Success(); |
1775 // (1) Prior to NSS 3.16.2, there is no parameter validation when creating | 669 } |
1776 // private keys. It is therefore possible to construct a key using the | 670 |
1777 // known public modulus, and where all the other parameters are bogus. | 671 Status RsaHashedAlgorithm::VerifyKeyUsagesBeforeImportKey( |
1778 // FindKeyByKeyID() returns the first key matching the ID. So this would | 672 blink::WebCryptoKeyFormat format, |
1779 // effectively allow an attacker to retrieve a private key of their | 673 blink::WebCryptoKeyUsageMask usage_mask) const { |
1780 // choice. | 674 switch (format) { |
1781 // TODO(eroman): Once NSS rolls and this is fixed, disallow RSA key | 675 case blink::WebCryptoKeyFormatSpki: |
1782 // import on older versions of NSS. | 676 return CheckKeyCreationUsages(all_public_key_usages_, usage_mask); |
1783 // http://crbug.com/378315 | 677 case blink::WebCryptoKeyFormatPkcs8: |
1784 // | 678 return CheckKeyCreationUsages(all_private_key_usages_, usage_mask); |
1785 // (2) The ID space is shared by different key types. So theoretically | 679 case blink::WebCryptoKeyFormatJwk: |
1786 // possible to retrieve a key of the wrong type which has a matching | 680 return CheckKeyCreationUsages( |
1787 // CKA_ID. In practice I am told this is not likely except for small key | 681 all_public_key_usages_ | all_private_key_usages_, usage_mask); |
1788 // sizes, since would require constructing keys with the same public | 682 default: |
1789 // data. | 683 return Status::ErrorUnsupportedImportKeyFormat(); |
1790 // | 684 } |
1791 // (3) FindKeyByKeyID() doesn't necessarily return the object that was just | 685 } |
1792 // created by CreateGenericObject. If the pre-existing key was | 686 |
1793 // provisioned with flags incompatible with WebCrypto (for instance | 687 |
1794 // marked sensitive) then this will break things. | 688 Status RsaHashedAlgorithm::ImportKeyPkcs8( |
1795 SECItem modulus_item = MakeSECItemForBuffer(CryptoData(modulus)); | 689 const CryptoData& key_data, |
1796 crypto::ScopedSECItem object_id(PK11_MakeIDFromPubKey(&modulus_item)); | 690 const blink::WebCryptoAlgorithm& algorithm, |
1797 AddOptionalAttribute( | 691 bool extractable, |
1798 CKA_ID, CryptoData(object_id->data, object_id->len), &key_template); | 692 blink::WebCryptoKeyUsageMask usage_mask, |
1799 | 693 blink::WebCryptoKey* key) const { |
1800 // Optional properties (all of these will have been specified or none). | 694 Status status = NssSupportsRsaKeyImport(); |
1801 AddOptionalAttribute(CKA_PRIME_1, prime1, &key_template); | 695 if (status.IsError()) |
1802 AddOptionalAttribute(CKA_PRIME_2, prime2, &key_template); | 696 return status; |
1803 AddOptionalAttribute(CKA_EXPONENT_1, exponent1, &key_template); | 697 |
1804 AddOptionalAttribute(CKA_EXPONENT_2, exponent2, &key_template); | 698 if (!key_data.byte_length()) |
1805 AddOptionalAttribute(CKA_COEFFICIENT, coefficient, &key_template); | 699 return Status::ErrorImportEmptyKeyData(); |
1806 | 700 |
701 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 PKCS#8 | |
702 // private key info object. | |
703 SECItem pki_der = MakeSECItemForBuffer(key_data); | |
704 | |
705 SECKEYPrivateKey* seckey_private_key = NULL; | |
1807 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); | 706 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); |
1808 | 707 if (PK11_ImportDERPrivateKeyInfoAndReturnKey(slot.get(), |
1809 ScopedPK11GenericObject key_object(PK11_CreateGenericObject( | 708 &pki_der, |
1810 slot.get(), &key_template[0], key_template.size(), PR_FALSE)); | 709 NULL, // nickname |
1811 | 710 NULL, // publicValue |
1812 if (!key_object) | 711 false, // isPerm |
1813 return Status::OperationError(); | 712 false, // isPrivate |
1814 | 713 KU_ALL, // usage |
1815 crypto::ScopedSECKEYPrivateKey private_key_tmp( | 714 &seckey_private_key, |
1816 PK11_FindKeyByKeyID(slot.get(), object_id.get(), NULL)); | 715 NULL) != SECSuccess) { |
1817 | 716 return Status::DataError(); |
1818 // PK11_FindKeyByKeyID() may return a handle to an existing key, rather than | 717 } |
1819 // the object created by PK11_CreateGenericObject(). | 718 DCHECK(seckey_private_key); |
1820 crypto::ScopedSECKEYPrivateKey private_key( | 719 crypto::ScopedSECKEYPrivateKey private_key(seckey_private_key); |
1821 SECKEY_CopyPrivateKey(private_key_tmp.get())); | 720 |
1822 | 721 const KeyType sec_key_type = SECKEY_GetPrivateKeyType(private_key.get()); |
1823 if (!private_key) | 722 if (sec_key_type != rsaKey) |
1824 return Status::OperationError(); | 723 return Status::DataError(); |
1825 | 724 |
1826 blink::WebCryptoKeyAlgorithm key_algorithm; | 725 blink::WebCryptoKeyAlgorithm key_algorithm; |
1827 if (!CreatePrivateKeyAlgorithm(algorithm, private_key.get(), &key_algorithm)) | 726 if (!CreateRsaHashedPrivateKeyAlgorithm( |
1828 return Status::ErrorUnexpected(); | 727 algorithm, private_key.get(), &key_algorithm)) |
1829 | 728 return Status::ErrorUnexpected(); |
1830 scoped_ptr<PrivateKey> key_handle; | 729 |
1831 status = PrivateKey::Create(private_key.Pass(), key_algorithm, &key_handle); | 730 // TODO(eroman): This is probably going to be the same as the input. |
Ryan Sleevi
2014/07/17 00:06:54
Not sure what this comment means, but no, it's not
| |
1832 if (status.IsError()) | 731 std::vector<uint8> pkcs8_data; |
1833 return status; | 732 status = ExportKeyPkcs8Nss(private_key.get(), &pkcs8_data); |
733 if (status.IsError()) | |
734 return status; | |
735 | |
736 scoped_ptr<PrivateKeyNss> key_handle( | |
737 new PrivateKeyNss(private_key.Pass(), CryptoData(pkcs8_data))); | |
1834 | 738 |
1835 *key = blink::WebCryptoKey::create(key_handle.release(), | 739 *key = blink::WebCryptoKey::create(key_handle.release(), |
1836 blink::WebCryptoKeyTypePrivate, | 740 blink::WebCryptoKeyTypePrivate, |
1837 extractable, | 741 extractable, |
1838 key_algorithm, | 742 key_algorithm, |
1839 usage_mask); | 743 usage_mask); |
1840 return Status::Success(); | 744 |
1841 } | 745 return Status::Success(); |
1842 | 746 } |
1843 Status WrapSymKeyAesKw(PK11SymKey* key, | 747 |
1844 SymKey* wrapping_key, | 748 Status RsaHashedAlgorithm::ImportKeySpki( |
1845 std::vector<uint8>* buffer) { | 749 const CryptoData& key_data, |
1846 // The data size must be at least 16 bytes and a multiple of 8 bytes. | 750 const blink::WebCryptoAlgorithm& algorithm, |
1847 // RFC 3394 does not specify a maximum allowed data length, but since only | 751 bool extractable, |
1848 // keys are being wrapped in this application (which are small), a reasonable | 752 blink::WebCryptoKeyUsageMask usage_mask, |
1849 // max limit is whatever will fit into an unsigned. For the max size test, | 753 blink::WebCryptoKey* key) const { |
1850 // note that AES Key Wrap always adds 8 bytes to the input data size. | 754 Status status = NssSupportsRsaKeyImport(); |
1851 const unsigned int input_length = PK11_GetKeyLength(key); | 755 if (status.IsError()) |
1852 DCHECK_GE(input_length, 16u); | 756 return status; |
1853 DCHECK((input_length % 8) == 0); | 757 |
1854 if (input_length > UINT_MAX - 8) | 758 if (!key_data.byte_length()) |
1855 return Status::ErrorDataTooLarge(); | 759 return Status::ErrorImportEmptyKeyData(); |
1856 | 760 |
1857 SECItem iv_item = MakeSECItemForBuffer(CryptoData(kAesIv, sizeof(kAesIv))); | 761 // The binary blob 'key_data' is expected to be a DER-encoded ASN.1 Subject |
1858 crypto::ScopedSECItem param_item( | 762 // Public Key Info. Decode this to a CERTSubjectPublicKeyInfo. |
1859 PK11_ParamFromIV(CKM_NSS_AES_KEY_WRAP, &iv_item)); | 763 SECItem spki_item = MakeSECItemForBuffer(key_data); |
1860 if (!param_item) | 764 const ScopedCERTSubjectPublicKeyInfo spki( |
1861 return Status::ErrorUnexpected(); | 765 SECKEY_DecodeDERSubjectPublicKeyInfo(&spki_item)); |
1862 | 766 if (!spki) |
1863 const unsigned int output_length = input_length + 8; | 767 return Status::DataError(); |
1864 buffer->resize(output_length); | 768 |
1865 SECItem wrapped_key_item = MakeSECItemForBuffer(CryptoData(*buffer)); | 769 crypto::ScopedSECKEYPublicKey sec_public_key( |
1866 | 770 SECKEY_ExtractPublicKey(spki.get())); |
1867 if (SECSuccess != PK11_WrapSymKey(CKM_NSS_AES_KEY_WRAP, | 771 if (!sec_public_key) |
1868 param_item.get(), | 772 return Status::DataError(); |
1869 wrapping_key->key(), | 773 |
1870 key, | 774 const KeyType sec_key_type = SECKEY_GetPublicKeyType(sec_public_key.get()); |
1871 &wrapped_key_item)) { | 775 if (sec_key_type != rsaKey) |
1872 return Status::OperationError(); | 776 return Status::DataError(); |
777 | |
778 blink::WebCryptoKeyAlgorithm key_algorithm; | |
779 if (!CreateRsaHashedPublicKeyAlgorithm( | |
780 algorithm, sec_public_key.get(), &key_algorithm)) | |
781 return Status::ErrorUnexpected(); | |
782 | |
783 // TODO(eroman): This is probably going to be the same as the input. | |
784 std::vector<uint8> spki_data; | |
Ryan Sleevi
2014/07/17 00:06:54
ditto
| |
785 status = ExportKeySpkiNss(sec_public_key.get(), &spki_data); | |
786 if (status.IsError()) | |
787 return status; | |
788 | |
789 scoped_ptr<PublicKeyNss> key_handle( | |
790 new PublicKeyNss(sec_public_key.Pass(), CryptoData(spki_data))); | |
791 | |
792 *key = blink::WebCryptoKey::create(key_handle.release(), | |
793 blink::WebCryptoKeyTypePublic, | |
794 extractable, | |
795 key_algorithm, | |
796 usage_mask); | |
797 | |
798 return Status::Success(); | |
799 } | |
800 | |
801 Status RsaHashedAlgorithm::ExportKeyPkcs8(const blink::WebCryptoKey& key, | |
802 std::vector<uint8>* buffer) const { | |
803 if (key.type() != blink::WebCryptoKeyTypePrivate) | |
804 return Status::ErrorUnexpectedKeyType(); | |
805 *buffer = PrivateKeyNss::Cast(key)->pkcs8_data(); | |
806 return Status::Success(); | |
807 } | |
808 | |
809 Status RsaHashedAlgorithm::ExportKeySpki(const blink::WebCryptoKey& key, | |
810 std::vector<uint8>* buffer) const { | |
811 if (key.type() != blink::WebCryptoKeyTypePublic) | |
812 return Status::ErrorUnexpectedKeyType(); | |
813 *buffer = PublicKeyNss::Cast(key)->spki_data(); | |
814 return Status::Success(); | |
815 } | |
816 | |
817 Status RsaHashedAlgorithm::ImportKeyJwk( | |
818 const CryptoData& key_data, | |
819 const blink::WebCryptoAlgorithm& algorithm, | |
820 bool extractable, | |
821 blink::WebCryptoKeyUsageMask usage_mask, | |
822 blink::WebCryptoKey* key) const { | |
823 const char* jwk_algorithm = | |
824 GetJwkAlgorithm(algorithm.rsaHashedImportParams()->hash().id()); | |
825 | |
826 if (!jwk_algorithm) | |
827 return Status::ErrorUnexpected(); | |
828 | |
829 JwkRsaInfo jwk; | |
830 Status status = | |
831 ReadRsaKeyJwk(key_data, jwk_algorithm, extractable, usage_mask, &jwk); | |
832 if (status.IsError()) | |
833 return status; | |
834 | |
835 // Once the key type is known, verify the usages. | |
836 status = CheckKeyCreationUsages( | |
837 jwk.is_private_key ? all_private_key_usages_ : all_public_key_usages_, | |
838 usage_mask); | |
839 if (status.IsError()) | |
840 return Status::ErrorCreateKeyBadUsages(); | |
841 | |
842 return jwk.is_private_key | |
843 ? ImportRsaPrivateKey(algorithm, extractable, usage_mask, jwk, key) | |
844 : ImportRsaPublicKey(algorithm, | |
845 extractable, | |
846 usage_mask, | |
847 CryptoData(jwk.n), | |
848 CryptoData(jwk.e), | |
849 key); | |
850 } | |
851 | |
852 Status RsaHashedAlgorithm::ExportKeyJwk(const blink::WebCryptoKey& key, | |
853 std::vector<uint8>* buffer) const { | |
854 const char* jwk_algorithm = | |
855 GetJwkAlgorithm(key.algorithm().rsaHashedParams()->hash().id()); | |
856 | |
857 if (!jwk_algorithm) | |
858 return Status::ErrorUnexpected(); | |
859 | |
860 switch (key.type()) { | |
861 case blink::WebCryptoKeyTypePublic: { | |
862 SECKEYPublicKey* nss_key = PublicKeyNss::Cast(key)->key(); | |
863 if (nss_key->keyType != rsaKey) | |
864 return Status::ErrorUnsupported(); | |
865 | |
866 WriteRsaPublicKeyJwk(SECItemToCryptoData(nss_key->u.rsa.modulus), | |
867 SECItemToCryptoData(nss_key->u.rsa.publicExponent), | |
868 jwk_algorithm, | |
869 key.extractable(), | |
870 key.usages(), | |
871 buffer); | |
872 | |
873 return Status::Success(); | |
874 } | |
875 | |
876 case blink::WebCryptoKeyTypePrivate: { | |
877 SECKEYPrivateKey* nss_key = PrivateKeyNss::Cast(key)->key(); | |
878 RSAPrivateKey key_props = {}; | |
879 scoped_ptr<RSAPrivateKey, FreeRsaPrivateKey> free_private_key(&key_props); | |
880 | |
881 if (!InitRSAPrivateKey(nss_key, &key_props)) | |
882 return Status::OperationError(); | |
883 | |
884 WriteRsaPrivateKeyJwk(SECItemToCryptoData(key_props.modulus), | |
885 SECItemToCryptoData(key_props.public_exponent), | |
886 SECItemToCryptoData(key_props.private_exponent), | |
887 SECItemToCryptoData(key_props.prime1), | |
888 SECItemToCryptoData(key_props.prime2), | |
889 SECItemToCryptoData(key_props.exponent1), | |
890 SECItemToCryptoData(key_props.exponent2), | |
891 SECItemToCryptoData(key_props.coefficient), | |
892 jwk_algorithm, | |
893 key.extractable(), | |
894 key.usages(), | |
895 buffer); | |
896 | |
897 return Status::Success(); | |
898 } | |
899 default: | |
900 return Status::ErrorUnexpected(); | |
1873 } | 901 } |
1874 if (output_length != wrapped_key_item.len) | 902 } |
1875 return Status::ErrorUnexpected(); | |
1876 | |
1877 return Status::Success(); | |
1878 } | |
1879 | |
1880 Status DecryptAesKw(SymKey* wrapping_key, | |
1881 const CryptoData& data, | |
1882 std::vector<uint8>* buffer) { | |
1883 // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be | |
1884 // temporarily viewed as a symmetric key to be unwrapped (decrypted). | |
1885 crypto::ScopedPK11SymKey decrypted; | |
1886 Status status = DoUnwrapSymKeyAesKw( | |
1887 data, wrapping_key, CKK_GENERIC_SECRET, 0, &decrypted); | |
1888 if (status.IsError()) | |
1889 return status; | |
1890 | |
1891 // Once the decrypt is complete, extract the resultant raw bytes from NSS and | |
1892 // return them to the caller. | |
1893 if (PK11_ExtractKeyValue(decrypted.get()) != SECSuccess) | |
1894 return Status::OperationError(); | |
1895 const SECItem* const key_data = PK11_GetKeyData(decrypted.get()); | |
1896 if (!key_data) | |
1897 return Status::OperationError(); | |
1898 buffer->assign(key_data->data, key_data->data + key_data->len); | |
1899 | |
1900 return Status::Success(); | |
1901 } | |
1902 | |
1903 Status EncryptAesKw(SymKey* wrapping_key, | |
1904 const CryptoData& data, | |
1905 std::vector<uint8>* buffer) { | |
1906 // Due to limitations in the NSS API for the AES-KW algorithm, |data| must be | |
1907 // temporarily viewed as a symmetric key to be wrapped (encrypted). | |
1908 SECItem data_item = MakeSECItemForBuffer(data); | |
1909 crypto::ScopedPK11Slot slot(PK11_GetInternalSlot()); | |
1910 crypto::ScopedPK11SymKey data_as_sym_key(PK11_ImportSymKey(slot.get(), | |
1911 CKK_GENERIC_SECRET, | |
1912 PK11_OriginUnwrap, | |
1913 CKA_SIGN, | |
1914 &data_item, | |
1915 NULL)); | |
1916 if (!data_as_sym_key) | |
1917 return Status::OperationError(); | |
1918 | |
1919 return WrapSymKeyAesKw(data_as_sym_key.get(), wrapping_key, buffer); | |
1920 } | |
1921 | |
1922 Status EncryptDecryptAesKw(EncryptOrDecrypt mode, | |
1923 SymKey* wrapping_key, | |
1924 const CryptoData& data, | |
1925 std::vector<uint8>* buffer) { | |
1926 return mode == ENCRYPT ? EncryptAesKw(wrapping_key, data, buffer) | |
1927 : DecryptAesKw(wrapping_key, data, buffer); | |
1928 } | |
1929 | |
1930 } // namespace platform | |
1931 | 903 |
1932 } // namespace webcrypto | 904 } // namespace webcrypto |
1933 | 905 |
1934 } // namespace content | 906 } // namespace content |
OLD | NEW |