1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/child/webcrypto/platform_crypto.h"
8 #include <openssl/aes.h>
9 #include <openssl/evp.h>
10 #include <openssl/hmac.h>
11 #include <openssl/rand.h>
12 #include <openssl/sha.h>
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "content/child/webcrypto/crypto_data.h"
17 #include "content/child/webcrypto/status.h"
18 #include "content/child/webcrypto/webcrypto_util.h"
19 #include "crypto/openssl_util.h"
20 #include "crypto/scoped_openssl_types.h"
21 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
22 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
23 #include "third_party/WebKit/public/platform/WebCryptoKeyAlgorithm.h"
31 class SymKey
: public Key
{
33 explicit SymKey(const CryptoData
& key_data
)
34 : key_(key_data
.bytes(), key_data
.bytes() + key_data
.byte_length()) {}
36 virtual SymKey
* AsSymKey() OVERRIDE
{ return this; }
37 virtual PublicKey
* AsPublicKey() OVERRIDE
{ return NULL
; }
38 virtual PrivateKey
* AsPrivateKey() OVERRIDE
{ return NULL
; }
39 virtual bool ThreadSafeSerializeForClone(
40 blink::WebVector
<uint8
>* key_data
) OVERRIDE
{
41 key_data
->assign(Uint8VectorStart(key_
), key_
.size());
45 const std::vector
<unsigned char>& key() const { return key_
; }
48 const std::vector
<unsigned char> key_
;
50 DISALLOW_COPY_AND_ASSIGN(SymKey
);
55 const EVP_CIPHER
* GetAESCipherByKeyLength(unsigned int key_length_bytes
) {
56 // OpenSSL supports AES CBC ciphers for only 3 key lengths: 128, 192, 256 bits
57 switch (key_length_bytes
) {
59 return EVP_aes_128_cbc();
61 return EVP_aes_192_cbc();
63 return EVP_aes_256_cbc();
69 const EVP_MD
* GetDigest(blink::WebCryptoAlgorithmId id
) {
71 case blink::WebCryptoAlgorithmIdSha1
:
73 case blink::WebCryptoAlgorithmIdSha256
:
75 case blink::WebCryptoAlgorithmIdSha384
:
77 case blink::WebCryptoAlgorithmIdSha512
:
84 // OpenSSL constants for EVP_CipherInit_ex(), do not change
85 enum CipherOperation
{ kDoDecrypt
= 0, kDoEncrypt
= 1 };
87 Status
AesCbcEncryptDecrypt(EncryptOrDecrypt mode
,
90 const CryptoData
& data
,
91 std::vector
<uint8
>* buffer
) {
92 CipherOperation cipher_operation
=
93 (mode
== ENCRYPT
) ? kDoEncrypt
: kDoDecrypt
;
95 if (data
.byte_length() >= INT_MAX
- AES_BLOCK_SIZE
) {
96 // TODO(padolph): Handle this by chunking the input fed into OpenSSL. Right
97 // now it doesn't make much difference since the one-shot API would end up
98 // blowing out the memory and crashing anyway.
99 return Status::ErrorDataTooLarge();
102 // Note: PKCS padding is enabled by default
103 crypto::ScopedOpenSSL
<EVP_CIPHER_CTX
, EVP_CIPHER_CTX_free
>::Type
context(
104 EVP_CIPHER_CTX_new());
107 return Status::OperationError();
109 const EVP_CIPHER
* const cipher
= GetAESCipherByKeyLength(key
->key().size());
112 if (!EVP_CipherInit_ex(context
.get(),
118 return Status::OperationError();
121 // According to the openssl docs, the amount of data written may be as large
122 // as (data_size + cipher_block_size - 1), constrained to a multiple of
123 // cipher_block_size.
124 unsigned int output_max_len
= data
.byte_length() + AES_BLOCK_SIZE
- 1;
125 const unsigned remainder
= output_max_len
% AES_BLOCK_SIZE
;
127 output_max_len
+= AES_BLOCK_SIZE
- remainder
;
128 DCHECK_GT(output_max_len
, data
.byte_length());
130 buffer
->resize(output_max_len
);
132 unsigned char* const buffer_data
= Uint8VectorStart(buffer
);
135 if (!EVP_CipherUpdate(context
.get(),
140 return Status::OperationError();
141 int final_output_chunk_len
= 0;
142 if (!EVP_CipherFinal_ex(
143 context
.get(), buffer_data
+ output_len
, &final_output_chunk_len
)) {
144 return Status::OperationError();
147 const unsigned int final_output_len
=
148 static_cast<unsigned int>(output_len
) +
149 static_cast<unsigned int>(final_output_chunk_len
);
150 DCHECK_LE(final_output_len
, output_max_len
);
152 buffer
->resize(final_output_len
);
154 return Status::Success();
159 class DigestorOpenSSL
: public blink::WebCryptoDigestor
{
161 explicit DigestorOpenSSL(blink::WebCryptoAlgorithmId algorithm_id
)
162 : initialized_(false),
163 digest_context_(EVP_MD_CTX_create()),
164 algorithm_id_(algorithm_id
) {}
166 virtual bool consume(const unsigned char* data
, unsigned int size
) {
167 return ConsumeWithStatus(data
, size
).IsSuccess();
170 Status
ConsumeWithStatus(const unsigned char* data
, unsigned int size
) {
171 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
172 Status error
= Init();
173 if (!error
.IsSuccess())
176 if (!EVP_DigestUpdate(digest_context_
.get(), data
, size
))
177 return Status::OperationError();
179 return Status::Success();
182 virtual bool finish(unsigned char*& result_data
,
183 unsigned int& result_data_size
) {
184 Status error
= FinishInternal(result_
, &result_data_size
);
185 if (!error
.IsSuccess())
187 result_data
= result_
;
191 Status
FinishWithVectorAndStatus(std::vector
<uint8
>* result
) {
192 const int hash_expected_size
= EVP_MD_CTX_size(digest_context_
.get());
193 result
->resize(hash_expected_size
);
194 unsigned char* const hash_buffer
= Uint8VectorStart(result
);
195 unsigned int hash_buffer_size
; // ignored
196 return FinishInternal(hash_buffer
, &hash_buffer_size
);
202 return Status::Success();
204 const EVP_MD
* digest_algorithm
= GetDigest(algorithm_id_
);
205 if (!digest_algorithm
)
206 return Status::ErrorUnexpected();
208 if (!digest_context_
.get())
209 return Status::OperationError();
211 if (!EVP_DigestInit_ex(digest_context_
.get(), digest_algorithm
, NULL
))
212 return Status::OperationError();
215 return Status::Success();
218 Status
FinishInternal(unsigned char* result
, unsigned int* result_size
) {
219 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
220 Status error
= Init();
221 if (!error
.IsSuccess())
224 const int hash_expected_size
= EVP_MD_CTX_size(digest_context_
.get());
225 if (hash_expected_size
<= 0)
226 return Status::ErrorUnexpected();
227 DCHECK_LE(hash_expected_size
, EVP_MAX_MD_SIZE
);
229 if (!EVP_DigestFinal_ex(digest_context_
.get(), result
, result_size
) ||
230 static_cast<int>(*result_size
) != hash_expected_size
)
231 return Status::OperationError();
233 return Status::Success();
237 crypto::ScopedEVP_MD_CTX digest_context_
;
238 blink::WebCryptoAlgorithmId algorithm_id_
;
239 unsigned char result_
[EVP_MAX_MD_SIZE
];
242 Status
ExportKeyRaw(SymKey
* key
, std::vector
<uint8
>* buffer
) {
243 *buffer
= key
->key();
244 return Status::Success();
247 void Init() { crypto::EnsureOpenSSLInit(); }
249 Status
EncryptDecryptAesCbc(EncryptOrDecrypt mode
,
251 const CryptoData
& data
,
252 const CryptoData
& iv
,
253 std::vector
<uint8
>* buffer
) {
254 // TODO(eroman): inline the function here.
255 return AesCbcEncryptDecrypt(mode
, key
, iv
, data
, buffer
);
258 Status
DigestSha(blink::WebCryptoAlgorithmId algorithm
,
259 const CryptoData
& data
,
260 std::vector
<uint8
>* buffer
) {
261 DigestorOpenSSL
digestor(algorithm
);
262 Status error
= digestor
.ConsumeWithStatus(data
.bytes(), data
.byte_length());
263 if (!error
.IsSuccess())
265 return digestor
.FinishWithVectorAndStatus(buffer
);
268 scoped_ptr
<blink::WebCryptoDigestor
> CreateDigestor(
269 blink::WebCryptoAlgorithmId algorithm_id
) {
270 return scoped_ptr
<blink::WebCryptoDigestor
>(
271 new DigestorOpenSSL(algorithm_id
));
274 Status
GenerateSecretKey(const blink::WebCryptoAlgorithm
& algorithm
,
276 blink::WebCryptoKeyUsageMask usage_mask
,
277 unsigned keylen_bytes
,
278 blink::WebCryptoKey
* key
) {
279 // TODO(eroman): Is this right?
280 if (keylen_bytes
== 0)
281 return Status::ErrorGenerateKeyLength();
283 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
285 std::vector
<unsigned char> random_bytes(keylen_bytes
, 0);
286 if (!(RAND_bytes(&random_bytes
[0], keylen_bytes
)))
287 return Status::OperationError();
289 blink::WebCryptoKeyAlgorithm key_algorithm
;
290 if (!CreateSecretKeyAlgorithm(algorithm
, keylen_bytes
, &key_algorithm
))
291 return Status::ErrorUnexpected();
293 *key
= blink::WebCryptoKey::create(new SymKey(CryptoData(random_bytes
)),
294 blink::WebCryptoKeyTypeSecret
,
299 return Status::Success();
302 Status
GenerateRsaKeyPair(const blink::WebCryptoAlgorithm
& algorithm
,
304 blink::WebCryptoKeyUsageMask public_key_usage_mask
,
305 blink::WebCryptoKeyUsageMask private_key_usage_mask
,
306 unsigned int modulus_length_bits
,
307 unsigned long public_exponent
,
308 blink::WebCryptoKey
* public_key
,
309 blink::WebCryptoKey
* private_key
) {
310 // TODO(padolph): Placeholder for OpenSSL implementation.
311 // Issue http://crbug.com/267888.
312 return Status::ErrorUnsupported();
315 Status
ImportKeyRaw(const blink::WebCryptoAlgorithm
& algorithm
,
316 const CryptoData
& key_data
,
318 blink::WebCryptoKeyUsageMask usage_mask
,
319 blink::WebCryptoKey
* key
) {
321 blink::WebCryptoKeyAlgorithm key_algorithm
;
322 if (!CreateSecretKeyAlgorithm(
323 algorithm
, key_data
.byte_length(), &key_algorithm
))
324 return Status::ErrorUnexpected();
326 *key
= blink::WebCryptoKey::create(new SymKey(key_data
),
327 blink::WebCryptoKeyTypeSecret
,
332 return Status::Success();
335 Status
SignHmac(SymKey
* key
,
336 const blink::WebCryptoAlgorithm
& hash
,
337 const CryptoData
& data
,
338 std::vector
<uint8
>* buffer
) {
339 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
341 const EVP_MD
* digest_algorithm
= GetDigest(hash
.id());
342 if (!digest_algorithm
)
343 return Status::ErrorUnsupported();
344 unsigned int hmac_expected_length
= EVP_MD_size(digest_algorithm
);
346 const std::vector
<unsigned char>& raw_key
= key
->key();
348 // OpenSSL wierdness here.
349 // First, HMAC() needs a void* for the key data, so make one up front as a
350 // cosmetic to avoid a cast. Second, OpenSSL does not like a NULL key,
351 // which will result if the raw_key vector is empty; an entirely valid
352 // case. Handle this specific case by pointing to an empty array.
353 const unsigned char null_key
[] = {};
354 const void* const raw_key_voidp
= raw_key
.size() ? &raw_key
[0] : null_key
;
356 buffer
->resize(hmac_expected_length
);
357 crypto::ScopedOpenSSLSafeSizeBuffer
<EVP_MAX_MD_SIZE
> hmac_result(
358 Uint8VectorStart(buffer
), hmac_expected_length
);
360 unsigned int hmac_actual_length
;
361 unsigned char* const success
= HMAC(digest_algorithm
,
366 hmac_result
.safe_buffer(),
367 &hmac_actual_length
);
368 if (!success
|| hmac_actual_length
!= hmac_expected_length
)
369 return Status::OperationError();
371 return Status::Success();
374 Status
ImportRsaPublicKey(const blink::WebCryptoAlgorithm
& algorithm
,
376 blink::WebCryptoKeyUsageMask usage_mask
,
377 const CryptoData
& modulus_data
,
378 const CryptoData
& exponent_data
,
379 blink::WebCryptoKey
* key
) {
380 // TODO(padolph): Placeholder for OpenSSL implementation.
382 return Status::ErrorUnsupported();
385 Status
ImportRsaPrivateKey(const blink::WebCryptoAlgorithm
& algorithm
,
387 blink::WebCryptoKeyUsageMask usage_mask
,
388 const CryptoData
& modulus
,
389 const CryptoData
& public_exponent
,
390 const CryptoData
& private_exponent
,
391 const CryptoData
& prime1
,
392 const CryptoData
& prime2
,
393 const CryptoData
& exponent1
,
394 const CryptoData
& exponent2
,
395 const CryptoData
& coefficient
,
396 blink::WebCryptoKey
* key
) {
397 // TODO(eroman): http://crbug.com/267888
398 return Status::ErrorUnsupported();
401 const EVP_AEAD
* GetAesGcmAlgorithmFromKeySize(unsigned int key_size_bytes
) {
402 switch (key_size_bytes
) {
404 return EVP_aead_aes_128_gcm();
405 // TODO(eroman): Hook up 256-bit support when it is available.
411 Status
EncryptDecryptAesGcm(EncryptOrDecrypt mode
,
413 const CryptoData
& data
,
414 const CryptoData
& iv
,
415 const CryptoData
& additional_data
,
416 unsigned int tag_length_bits
,
417 std::vector
<uint8
>* buffer
) {
418 crypto::OpenSSLErrStackTracer
err_tracer(FROM_HERE
);
420 DCHECK(tag_length_bits
% 8 == 0);
421 const unsigned int tag_length_bytes
= tag_length_bits
/ 8;
425 const EVP_AEAD
* const aead_alg
=
426 GetAesGcmAlgorithmFromKeySize(key
->key().size());
428 return Status::ErrorUnexpected();
430 if (!EVP_AEAD_CTX_init(&ctx
,
432 Uint8VectorStart(key
->key()),
436 return Status::OperationError();
439 crypto::ScopedOpenSSL
<EVP_AEAD_CTX
, EVP_AEAD_CTX_cleanup
>::Type
ctx_cleanup(
444 if (mode
== DECRYPT
) {
445 if (data
.byte_length() < tag_length_bytes
)
446 return Status::ErrorDataTooSmall();
448 buffer
->resize(data
.byte_length() - tag_length_bytes
);
450 len
= EVP_AEAD_CTX_open(&ctx
,
451 Uint8VectorStart(buffer
),
457 additional_data
.bytes(),
458 additional_data
.byte_length());
460 // No need to check for unsigned integer overflow here (seal fails if
461 // the output buffer is too small).
462 buffer
->resize(data
.byte_length() + tag_length_bytes
);
464 len
= EVP_AEAD_CTX_seal(&ctx
,
465 Uint8VectorStart(buffer
),
471 additional_data
.bytes(),
472 additional_data
.byte_length());
476 return Status::OperationError();
478 return Status::Success();
481 Status
EncryptRsaOaep(PublicKey
* key
,
482 const blink::WebCryptoAlgorithm
& hash
,
483 const CryptoData
& label
,
484 const CryptoData
& data
,
485 std::vector
<uint8
>* buffer
) {
486 // TODO(eroman): http://crbug.com/267888
487 return Status::ErrorUnsupported();
490 Status
DecryptRsaOaep(PrivateKey
* key
,
491 const blink::WebCryptoAlgorithm
& hash
,
492 const CryptoData
& label
,
493 const CryptoData
& data
,
494 std::vector
<uint8
>* buffer
) {
495 // TODO(eroman): http://crbug.com/267888
496 return Status::ErrorUnsupported();
499 Status
SignRsaSsaPkcs1v1_5(PrivateKey
* key
,
500 const blink::WebCryptoAlgorithm
& hash
,
501 const CryptoData
& data
,
502 std::vector
<uint8
>* buffer
) {
503 // TODO(eroman): http://crbug.com/267888
504 return Status::ErrorUnsupported();
507 // Key is guaranteed to be an RSA SSA key.
508 Status
VerifyRsaSsaPkcs1v1_5(PublicKey
* key
,
509 const blink::WebCryptoAlgorithm
& hash
,
510 const CryptoData
& signature
,
511 const CryptoData
& data
,
512 bool* signature_match
) {
513 // TODO(eroman): http://crbug.com/267888
514 return Status::ErrorUnsupported();
517 Status
ImportKeySpki(const blink::WebCryptoAlgorithm
& algorithm
,
518 const CryptoData
& key_data
,
520 blink::WebCryptoKeyUsageMask usage_mask
,
521 blink::WebCryptoKey
* key
) {
522 // TODO(eroman): http://crbug.com/267888
523 return Status::ErrorUnsupported();
526 Status
ImportKeyPkcs8(const blink::WebCryptoAlgorithm
& algorithm
,
527 const CryptoData
& key_data
,
529 blink::WebCryptoKeyUsageMask usage_mask
,
530 blink::WebCryptoKey
* key
) {
531 // TODO(eroman): http://crbug.com/267888
532 return Status::ErrorUnsupported();
535 Status
ExportKeySpki(PublicKey
* key
, std::vector
<uint8
>* buffer
) {
536 // TODO(eroman): http://crbug.com/267888
537 return Status::ErrorUnsupported();
540 Status
ExportKeyPkcs8(PrivateKey
* key
,
541 const blink::WebCryptoKeyAlgorithm
& key_algorithm
,
542 std::vector
<uint8
>* buffer
) {
543 // TODO(eroman): http://crbug.com/267888
544 return Status::ErrorUnsupported();
547 Status
ExportRsaPublicKey(PublicKey
* key
,
548 std::vector
<uint8
>* modulus
,
549 std::vector
<uint8
>* public_exponent
) {
550 // TODO(eroman): http://crbug.com/267888
551 return Status::ErrorUnsupported();
554 Status
ExportRsaPrivateKey(PrivateKey
* key
,
555 std::vector
<uint8
>* modulus
,
556 std::vector
<uint8
>* public_exponent
,
557 std::vector
<uint8
>* private_exponent
,
558 std::vector
<uint8
>* prime1
,
559 std::vector
<uint8
>* prime2
,
560 std::vector
<uint8
>* exponent1
,
561 std::vector
<uint8
>* exponent2
,
562 std::vector
<uint8
>* coefficient
) {
563 // TODO(eroman): http://crbug.com/267888
564 return Status::ErrorUnsupported();
567 Status
EncryptDecryptAesKw(EncryptOrDecrypt mode
,
569 const CryptoData
& data
,
570 std::vector
<uint8
>* buffer
) {
571 // TODO(eroman): http://crbug.com/267888
572 return Status::ErrorUnsupported();
575 bool ThreadSafeDeserializeKeyForClone(
576 const blink::WebCryptoKeyAlgorithm
& algorithm
,
577 blink::WebCryptoKeyType type
,
579 blink::WebCryptoKeyUsageMask usages
,
580 const CryptoData
& key_data
,
581 blink::WebCryptoKey
* key
) {
582 // TODO(eroman): http://crbug.com/267888
586 } // namespace platform
588 } // namespace webcrypto
590 } // namespace content