1 // Copyright 2013 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/renderer/webcrypto/webcrypto_impl.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 "content/renderer/webcrypto/webcrypto_util.h"
16 #include "crypto/openssl_util.h"
17 #include "crypto/secure_util.h"
18 #include "third_party/WebKit/public/platform/WebArrayBuffer.h"
19 #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h"
20 #include "third_party/WebKit/public/platform/WebCryptoAlgorithmParams.h"
24 using webcrypto::Status;
28 class SymKeyHandle : public blink::WebCryptoKeyHandle {
30 SymKeyHandle(const unsigned char* key_data, unsigned int key_data_size)
31 : key_(key_data, key_data + key_data_size) {}
33 const std::vector<unsigned char>& key() const { return key_; }
36 const std::vector<unsigned char> key_;
38 DISALLOW_COPY_AND_ASSIGN(SymKeyHandle);
41 const EVP_CIPHER* GetAESCipherByKeyLength(unsigned int key_length_bytes) {
42 // OpenSSL supports AES CBC ciphers for only 3 key lengths: 128, 192, 256 bits
43 switch (key_length_bytes) {
45 return EVP_aes_128_cbc();
47 return EVP_aes_192_cbc();
49 return EVP_aes_256_cbc();
55 // OpenSSL constants for EVP_CipherInit_ex(), do not change
56 enum CipherOperation {
61 Status AesCbcEncryptDecrypt(CipherOperation cipher_operation,
62 const blink::WebCryptoAlgorithm& algorithm,
63 const blink::WebCryptoKey& key,
64 const unsigned char* data,
65 unsigned int data_size,
66 blink::WebArrayBuffer* buffer) {
67 DCHECK_EQ(blink::WebCryptoAlgorithmIdAesCbc, algorithm.id());
68 DCHECK_EQ(algorithm.id(), key.algorithm().id());
69 DCHECK_EQ(blink::WebCryptoKeyTypeSecret, key.type());
71 if (data_size >= INT_MAX - AES_BLOCK_SIZE) {
72 // TODO(padolph): Handle this by chunking the input fed into OpenSSL. Right
73 // now it doesn't make much difference since the one-shot API would end up
74 // blowing out the memory and crashing anyway.
75 return Status::ErrorDataTooLarge();
78 // Note: PKCS padding is enabled by default
79 crypto::ScopedOpenSSL<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> context(
80 EVP_CIPHER_CTX_new());
83 return Status::Error();
85 SymKeyHandle* const sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
87 const EVP_CIPHER* const cipher =
88 GetAESCipherByKeyLength(sym_key->key().size());
91 const blink::WebCryptoAesCbcParams* const params = algorithm.aesCbcParams();
92 if (params->iv().size() != AES_BLOCK_SIZE)
93 return Status::ErrorIncorrectSizeAesCbcIv();
95 if (!EVP_CipherInit_ex(context.get(),
101 return Status::Error();
104 // According to the openssl docs, the amount of data written may be as large
105 // as (data_size + cipher_block_size - 1), constrained to a multiple of
106 // cipher_block_size.
107 unsigned int output_max_len = data_size + AES_BLOCK_SIZE - 1;
108 const unsigned remainder = output_max_len % AES_BLOCK_SIZE;
110 output_max_len += AES_BLOCK_SIZE - remainder;
111 DCHECK_GT(output_max_len, data_size);
113 *buffer = blink::WebArrayBuffer::create(output_max_len, 1);
115 unsigned char* const buffer_data =
116 reinterpret_cast<unsigned char*>(buffer->data());
119 if (!EVP_CipherUpdate(
120 context.get(), buffer_data, &output_len, data, data_size))
121 return Status::Error();
122 int final_output_chunk_len = 0;
123 if (!EVP_CipherFinal_ex(
124 context.get(), buffer_data + output_len, &final_output_chunk_len)) {
125 return Status::Error();
128 const unsigned int final_output_len =
129 static_cast<unsigned int>(output_len) +
130 static_cast<unsigned int>(final_output_chunk_len);
131 DCHECK_LE(final_output_len, output_max_len);
133 webcrypto::ShrinkBuffer(buffer, final_output_len);
135 return Status::Success();
138 Status ExportKeyInternalRaw(
139 const blink::WebCryptoKey& key,
140 blink::WebArrayBuffer* buffer) {
142 DCHECK(key.handle());
145 if (key.type() != blink::WebCryptoKeyTypeSecret)
146 return Status::ErrorUnexpectedKeyType();
148 // TODO(eroman): This should be in a more generic location.
149 if (!key.extractable())
150 return Status::ErrorKeyNotExtractable();
152 const SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
154 *buffer = webcrypto::CreateArrayBuffer(
155 webcrypto::Uint8VectorStart(sym_key->key()), sym_key->key().size());
157 return Status::Success();
162 void WebCryptoImpl::Init() { crypto::EnsureOpenSSLInit(); }
164 Status WebCryptoImpl::EncryptInternal(
165 const blink::WebCryptoAlgorithm& algorithm,
166 const blink::WebCryptoKey& key,
167 const unsigned char* data,
168 unsigned int data_size,
169 blink::WebArrayBuffer* buffer) {
170 if (algorithm.id() == blink::WebCryptoAlgorithmIdAesCbc) {
171 return AesCbcEncryptDecrypt(
172 kDoEncrypt, algorithm, key, data, data_size, buffer);
175 return Status::ErrorUnsupported();
178 Status WebCryptoImpl::DecryptInternal(
179 const blink::WebCryptoAlgorithm& algorithm,
180 const blink::WebCryptoKey& key,
181 const unsigned char* data,
182 unsigned int data_size,
183 blink::WebArrayBuffer* buffer) {
184 if (algorithm.id() == blink::WebCryptoAlgorithmIdAesCbc) {
185 return AesCbcEncryptDecrypt(
186 kDoDecrypt, algorithm, key, data, data_size, buffer);
189 return Status::ErrorUnsupported();
192 Status WebCryptoImpl::DigestInternal(const blink::WebCryptoAlgorithm& algorithm,
193 const unsigned char* data,
194 unsigned int data_size,
195 blink::WebArrayBuffer* buffer) {
197 crypto::OpenSSLErrStackTracer(FROM_HERE);
199 const EVP_MD* digest_algorithm;
200 switch (algorithm.id()) {
201 case blink::WebCryptoAlgorithmIdSha1:
202 digest_algorithm = EVP_sha1();
204 case blink::WebCryptoAlgorithmIdSha224:
205 digest_algorithm = EVP_sha224();
207 case blink::WebCryptoAlgorithmIdSha256:
208 digest_algorithm = EVP_sha256();
210 case blink::WebCryptoAlgorithmIdSha384:
211 digest_algorithm = EVP_sha384();
213 case blink::WebCryptoAlgorithmIdSha512:
214 digest_algorithm = EVP_sha512();
217 // Not a digest algorithm.
218 return Status::ErrorUnsupported();
221 crypto::ScopedOpenSSL<EVP_MD_CTX, EVP_MD_CTX_destroy> digest_context(
222 EVP_MD_CTX_create());
223 if (!digest_context.get())
224 return Status::Error();
226 if (!EVP_DigestInit_ex(digest_context.get(), digest_algorithm, NULL) ||
227 !EVP_DigestUpdate(digest_context.get(), data, data_size)) {
228 return Status::Error();
231 const int hash_expected_size = EVP_MD_CTX_size(digest_context.get());
232 if (hash_expected_size <= 0) {
233 return Status::ErrorUnexpected();
235 DCHECK_LE(hash_expected_size, EVP_MAX_MD_SIZE);
237 *buffer = blink::WebArrayBuffer::create(hash_expected_size, 1);
238 unsigned char* const hash_buffer =
239 reinterpret_cast<unsigned char* const>(buffer->data());
241 unsigned int hash_size = 0;
242 if (!EVP_DigestFinal_ex(digest_context.get(), hash_buffer, &hash_size) ||
243 static_cast<int>(hash_size) != hash_expected_size) {
245 return Status::Error();
248 return Status::Success();
251 Status WebCryptoImpl::GenerateSecretKeyInternal(
252 const blink::WebCryptoAlgorithm& algorithm,
254 blink::WebCryptoKeyUsageMask usage_mask,
255 blink::WebCryptoKey* key) {
257 unsigned int keylen_bytes = 0;
258 blink::WebCryptoKeyType key_type;
259 switch (algorithm.id()) {
260 case blink::WebCryptoAlgorithmIdAesCbc: {
261 const blink::WebCryptoAesKeyGenParams* params =
262 algorithm.aesKeyGenParams();
264 if (params->lengthBits() % 8)
265 return Status::ErrorGenerateKeyLength();
266 keylen_bytes = params->lengthBits() / 8;
267 if (!GetAESCipherByKeyLength(keylen_bytes))
268 return Status::Error();
269 key_type = blink::WebCryptoKeyTypeSecret;
272 case blink::WebCryptoAlgorithmIdHmac: {
273 const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
275 if (params->hasLengthBytes())
276 keylen_bytes = params->optionalLengthBytes();
278 keylen_bytes = webcrypto::ShaBlockSizeBytes(params->hash().id());
279 key_type = blink::WebCryptoKeyTypeSecret;
283 default: { return Status::ErrorUnsupported(); }
286 if (keylen_bytes == 0)
287 return Status::ErrorGenerateKeyLength();
289 crypto::OpenSSLErrStackTracer(FROM_HERE);
291 std::vector<unsigned char> random_bytes(keylen_bytes, 0);
292 if (!(RAND_bytes(&random_bytes[0], keylen_bytes)))
293 return Status::Error();
295 *key = blink::WebCryptoKey::create(
296 new SymKeyHandle(&random_bytes[0], random_bytes.size()),
297 key_type, extractable, algorithm, usage_mask);
299 return Status::Success();
302 Status WebCryptoImpl::GenerateKeyPairInternal(
303 const blink::WebCryptoAlgorithm& algorithm,
305 blink::WebCryptoKeyUsageMask usage_mask,
306 blink::WebCryptoKey* public_key,
307 blink::WebCryptoKey* private_key) {
308 // TODO(padolph): Placeholder for OpenSSL implementation.
309 // Issue http://crbug.com/267888.
310 return Status::ErrorUnsupported();
313 Status WebCryptoImpl::ImportKeyInternal(
314 blink::WebCryptoKeyFormat format,
315 const unsigned char* key_data,
316 unsigned int key_data_size,
317 const blink::WebCryptoAlgorithm& algorithm_or_null,
319 blink::WebCryptoKeyUsageMask usage_mask,
320 blink::WebCryptoKey* key) {
321 // TODO(eroman): Currently expects algorithm to always be specified, as it is
322 // required for raw format.
323 if (algorithm_or_null.isNull())
324 return Status::ErrorMissingAlgorithmImportRawKey();
325 const blink::WebCryptoAlgorithm& algorithm = algorithm_or_null;
327 // TODO(padolph): Support all relevant alg types and then remove this gate.
328 if (algorithm.id() != blink::WebCryptoAlgorithmIdHmac &&
329 algorithm.id() != blink::WebCryptoAlgorithmIdAesCbc) {
330 return Status::ErrorUnsupported();
333 // TODO(padolph): Need to split handling for symmetric (raw format) and
334 // asymmetric (spki or pkcs8 format) keys.
335 // Currently only supporting symmetric.
337 // Symmetric keys are always type secret
338 blink::WebCryptoKeyType type = blink::WebCryptoKeyTypeSecret;
340 const unsigned char* raw_key_data;
341 unsigned int raw_key_data_size;
343 case blink::WebCryptoKeyFormatRaw:
344 raw_key_data = key_data;
345 raw_key_data_size = key_data_size;
346 // The NSS implementation fails when importing a raw AES key with a length
347 // incompatible with AES. The line below is to match this behavior.
348 if (algorithm.id() == blink::WebCryptoAlgorithmIdAesCbc &&
349 !GetAESCipherByKeyLength(raw_key_data_size)) {
350 return Status::Error();
353 case blink::WebCryptoKeyFormatJwk:
354 return Status::ErrorUnexpected();
356 return Status::ErrorUnsupported();
359 *key = blink::WebCryptoKey::create(
360 new SymKeyHandle(raw_key_data, raw_key_data_size),
361 type, extractable, algorithm, usage_mask);
363 return Status::Success();
366 Status WebCryptoImpl::ExportKeyInternal(
367 blink::WebCryptoKeyFormat format,
368 const blink::WebCryptoKey& key,
369 blink::WebArrayBuffer* buffer) {
371 case blink::WebCryptoKeyFormatRaw:
372 return ExportKeyInternalRaw(key, buffer);
373 case blink::WebCryptoKeyFormatSpki:
374 // TODO(padolph): Implement spki export
375 return Status::ErrorUnsupported();
376 case blink::WebCryptoKeyFormatPkcs8:
377 // TODO(padolph): Implement pkcs8 export
378 return Status::ErrorUnsupported();
380 return Status::ErrorUnsupported();
382 return Status::ErrorUnsupported();
385 Status WebCryptoImpl::SignInternal(
386 const blink::WebCryptoAlgorithm& algorithm,
387 const blink::WebCryptoKey& key,
388 const unsigned char* data,
389 unsigned int data_size,
390 blink::WebArrayBuffer* buffer) {
392 blink::WebArrayBuffer result;
394 switch (algorithm.id()) {
395 case blink::WebCryptoAlgorithmIdHmac: {
397 DCHECK_EQ(key.algorithm().id(), blink::WebCryptoAlgorithmIdHmac);
398 DCHECK_NE(0, key.usages() & blink::WebCryptoKeyUsageSign);
400 const blink::WebCryptoHmacParams* const params = algorithm.hmacParams();
402 return Status::ErrorUnexpected();
404 const EVP_MD* evp_sha = 0;
405 unsigned int hmac_expected_length = 0;
406 // Note that HMAC length is determined by the hash used.
407 switch (params->hash().id()) {
408 case blink::WebCryptoAlgorithmIdSha1:
409 evp_sha = EVP_sha1();
410 hmac_expected_length = SHA_DIGEST_LENGTH;
412 case blink::WebCryptoAlgorithmIdSha224:
413 evp_sha = EVP_sha224();
414 hmac_expected_length = SHA224_DIGEST_LENGTH;
416 case blink::WebCryptoAlgorithmIdSha256:
417 evp_sha = EVP_sha256();
418 hmac_expected_length = SHA256_DIGEST_LENGTH;
420 case blink::WebCryptoAlgorithmIdSha384:
421 evp_sha = EVP_sha384();
422 hmac_expected_length = SHA384_DIGEST_LENGTH;
424 case blink::WebCryptoAlgorithmIdSha512:
425 evp_sha = EVP_sha512();
426 hmac_expected_length = SHA512_DIGEST_LENGTH;
429 // Not a digest algorithm.
430 return Status::ErrorUnsupported();
433 SymKeyHandle* const sym_key =
434 reinterpret_cast<SymKeyHandle*>(key.handle());
435 const std::vector<unsigned char>& raw_key = sym_key->key();
437 // OpenSSL wierdness here.
438 // First, HMAC() needs a void* for the key data, so make one up front as a
439 // cosmetic to avoid a cast. Second, OpenSSL does not like a NULL key,
440 // which will result if the raw_key vector is empty; an entirely valid
441 // case. Handle this specific case by pointing to an empty array.
442 const unsigned char null_key[] = {};
443 const void* const raw_key_voidp = raw_key.size() ? &raw_key[0] : null_key;
445 result = blink::WebArrayBuffer::create(hmac_expected_length, 1);
446 crypto::ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> hmac_result(
447 reinterpret_cast<unsigned char*>(result.data()),
448 hmac_expected_length);
450 crypto::OpenSSLErrStackTracer(FROM_HERE);
452 unsigned int hmac_actual_length;
453 unsigned char* const success = HMAC(evp_sha,
458 hmac_result.safe_buffer(),
459 &hmac_actual_length);
460 if (!success || hmac_actual_length != hmac_expected_length)
461 return Status::Error();
466 return Status::ErrorUnsupported();
470 return Status::Success();
473 Status WebCryptoImpl::VerifySignatureInternal(
474 const blink::WebCryptoAlgorithm& algorithm,
475 const blink::WebCryptoKey& key,
476 const unsigned char* signature,
477 unsigned int signature_size,
478 const unsigned char* data,
479 unsigned int data_size,
480 bool* signature_match) {
481 switch (algorithm.id()) {
482 case blink::WebCryptoAlgorithmIdHmac: {
483 blink::WebArrayBuffer result;
484 Status status = SignInternal(algorithm, key, data, data_size, &result);
485 if (status.IsError())
488 // Handling of truncated signatures is underspecified in the WebCrypto
489 // spec, so here we fail verification if a truncated signature is being
491 // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23097
493 result.byteLength() == signature_size &&
494 crypto::SecureMemEqual(result.data(), signature, signature_size);
499 return Status::ErrorUnsupported();
501 return Status::Success();
504 Status WebCryptoImpl::ImportRsaPublicKeyInternal(
505 const unsigned char* modulus_data,
506 unsigned int modulus_size,
507 const unsigned char* exponent_data,
508 unsigned int exponent_size,
509 const blink::WebCryptoAlgorithm& algorithm,
511 blink::WebCryptoKeyUsageMask usage_mask,
512 blink::WebCryptoKey* key) {
513 // TODO(padolph): Placeholder for OpenSSL implementation.
514 // Issue http://crbug.com/267888.
515 return Status::ErrorUnsupported();
518 } // namespace content