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/sha.h>
12 #include <openssl/evp.h>
13 #include <openssl/rand.h>
15 #include "base/logging.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"
26 class SymKeyHandle : public WebKit::WebCryptoKeyHandle {
28 SymKeyHandle(const unsigned char* key_data, unsigned key_data_size)
29 : key_(key_data, key_data + key_data_size) {}
31 const std::vector<unsigned char>& key() const { return key_; }
34 const std::vector<unsigned char> key_;
36 DISALLOW_COPY_AND_ASSIGN(SymKeyHandle);
39 const EVP_CIPHER* GetAESCipherByKeyLength(unsigned key_length_bytes) {
40 // OpenSSL supports AES CBC ciphers for only 3 key lengths: 128, 192, 256 bits
41 switch (key_length_bytes) {
43 return EVP_aes_128_cbc();
45 return EVP_aes_192_cbc();
47 return EVP_aes_256_cbc();
53 unsigned WebCryptoHmacParamsToBlockSize(
54 const WebKit::WebCryptoHmacKeyParams* params) {
56 switch (params->hash().id()) {
57 case WebKit::WebCryptoAlgorithmIdSha1:
58 return SHA_DIGEST_LENGTH / 8;
59 case WebKit::WebCryptoAlgorithmIdSha224:
60 return SHA224_DIGEST_LENGTH / 8;
61 case WebKit::WebCryptoAlgorithmIdSha256:
62 return SHA256_DIGEST_LENGTH / 8;
63 case WebKit::WebCryptoAlgorithmIdSha384:
64 return SHA384_DIGEST_LENGTH / 8;
65 case WebKit::WebCryptoAlgorithmIdSha512:
66 return SHA512_DIGEST_LENGTH / 8;
72 // OpenSSL constants for EVP_CipherInit_ex(), do not change
73 enum CipherOperation {
78 bool AesCbcEncryptDecrypt(CipherOperation cipher_operation,
79 const WebKit::WebCryptoAlgorithm& algorithm,
80 const WebKit::WebCryptoKey& key,
81 const unsigned char* data,
83 WebKit::WebArrayBuffer* buffer) {
85 // TODO(padolph): Handle other encrypt operations and then remove this gate
86 if (algorithm.id() != WebKit::WebCryptoAlgorithmIdAesCbc)
89 DCHECK_EQ(algorithm.id(), key.algorithm().id());
90 DCHECK_EQ(WebKit::WebCryptoKeyTypeSecret, key.type());
92 if (data_size >= INT_MAX - AES_BLOCK_SIZE) {
93 // TODO(padolph): Handle this by chunking the input fed into OpenSSL. Right
94 // now it doesn't make much difference since the one-shot API would end up
95 // blowing out the memory and crashing anyway. However a newer version of
96 // the spec allows for a sequence<CryptoData> so this will be relevant.
100 // Note: PKCS padding is enabled by default
101 crypto::ScopedOpenSSL<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> context(
102 EVP_CIPHER_CTX_new());
107 SymKeyHandle* const sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
109 const EVP_CIPHER* const cipher =
110 GetAESCipherByKeyLength(sym_key->key().size());
113 const WebKit::WebCryptoAesCbcParams* const params = algorithm.aesCbcParams();
114 if (params->iv().size() != AES_BLOCK_SIZE)
117 if (!EVP_CipherInit_ex(context.get(),
126 // According to the openssl docs, the amount of data written may be as large
127 // as (data_size + cipher_block_size - 1), constrained to a multiple of
128 // cipher_block_size.
129 unsigned output_max_len = data_size + AES_BLOCK_SIZE - 1;
130 const unsigned remainder = output_max_len % AES_BLOCK_SIZE;
132 output_max_len += AES_BLOCK_SIZE - remainder;
133 DCHECK_GT(output_max_len, data_size);
135 *buffer = WebKit::WebArrayBuffer::create(output_max_len, 1);
137 unsigned char* const buffer_data =
138 reinterpret_cast<unsigned char*>(buffer->data());
141 if (!EVP_CipherUpdate(
142 context.get(), buffer_data, &output_len, data, data_size))
144 int final_output_chunk_len = 0;
145 if (!EVP_CipherFinal_ex(
146 context.get(), buffer_data + output_len, &final_output_chunk_len))
149 const unsigned final_output_len =
150 static_cast<unsigned>(output_len) +
151 static_cast<unsigned>(final_output_chunk_len);
152 DCHECK_LE(final_output_len, output_max_len);
154 WebCryptoImpl::ShrinkBuffer(buffer, final_output_len);
161 void WebCryptoImpl::Init() { crypto::EnsureOpenSSLInit(); }
163 bool WebCryptoImpl::EncryptInternal(const WebKit::WebCryptoAlgorithm& algorithm,
164 const WebKit::WebCryptoKey& key,
165 const unsigned char* data,
167 WebKit::WebArrayBuffer* buffer) {
168 if (algorithm.id() == WebKit::WebCryptoAlgorithmIdAesCbc) {
169 return AesCbcEncryptDecrypt(
170 kDoEncrypt, algorithm, key, data, data_size, buffer);
176 bool WebCryptoImpl::DecryptInternal(const WebKit::WebCryptoAlgorithm& algorithm,
177 const WebKit::WebCryptoKey& key,
178 const unsigned char* data,
180 WebKit::WebArrayBuffer* buffer) {
181 if (algorithm.id() == WebKit::WebCryptoAlgorithmIdAesCbc) {
182 return AesCbcEncryptDecrypt(
183 kDoDecrypt, algorithm, key, data, data_size, buffer);
189 bool WebCryptoImpl::DigestInternal(const WebKit::WebCryptoAlgorithm& algorithm,
190 const unsigned char* data,
192 WebKit::WebArrayBuffer* buffer) {
194 crypto::OpenSSLErrStackTracer(FROM_HERE);
196 const EVP_MD* digest_algorithm;
197 switch (algorithm.id()) {
198 case WebKit::WebCryptoAlgorithmIdSha1:
199 digest_algorithm = EVP_sha1();
201 case WebKit::WebCryptoAlgorithmIdSha224:
202 digest_algorithm = EVP_sha224();
204 case WebKit::WebCryptoAlgorithmIdSha256:
205 digest_algorithm = EVP_sha256();
207 case WebKit::WebCryptoAlgorithmIdSha384:
208 digest_algorithm = EVP_sha384();
210 case WebKit::WebCryptoAlgorithmIdSha512:
211 digest_algorithm = EVP_sha512();
214 // Not a digest algorithm.
218 crypto::ScopedOpenSSL<EVP_MD_CTX, EVP_MD_CTX_destroy> digest_context(
219 EVP_MD_CTX_create());
220 if (!digest_context.get()) {
224 if (!EVP_DigestInit_ex(digest_context.get(), digest_algorithm, NULL) ||
225 !EVP_DigestUpdate(digest_context.get(), data, data_size)) {
229 const int hash_expected_size = EVP_MD_CTX_size(digest_context.get());
230 if (hash_expected_size <= 0) {
233 DCHECK_LE(hash_expected_size, EVP_MAX_MD_SIZE);
235 *buffer = WebKit::WebArrayBuffer::create(hash_expected_size, 1);
236 unsigned char* const hash_buffer =
237 reinterpret_cast<unsigned char* const>(buffer->data());
239 unsigned hash_size = 0;
240 if (!EVP_DigestFinal_ex(digest_context.get(), hash_buffer, &hash_size) ||
241 static_cast<int>(hash_size) != hash_expected_size) {
249 bool WebCryptoImpl::GenerateKeyInternal(
250 const WebKit::WebCryptoAlgorithm& algorithm,
252 WebKit::WebCryptoKeyUsageMask usage_mask,
253 WebKit::WebCryptoKey* key) {
255 unsigned keylen_bytes = 0;
256 WebKit::WebCryptoKeyType key_type;
257 switch (algorithm.id()) {
258 case WebKit::WebCryptoAlgorithmIdAesCbc: {
259 const WebKit::WebCryptoAesKeyGenParams* params =
260 algorithm.aesKeyGenParams();
262 if (params->length() % 8)
264 keylen_bytes = params->length() / 8;
265 if (!GetAESCipherByKeyLength(keylen_bytes)) {
268 key_type = WebKit::WebCryptoKeyTypeSecret;
271 case WebKit::WebCryptoAlgorithmIdHmac: {
272 const WebKit::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
274 if (!params->getLength(keylen_bytes)) {
275 keylen_bytes = WebCryptoHmacParamsToBlockSize(params);
277 key_type = WebKit::WebCryptoKeyTypeSecret;
281 default: { return false; }
284 if (keylen_bytes == 0) {
288 crypto::OpenSSLErrStackTracer(FROM_HERE);
290 std::vector<unsigned char> random_bytes(keylen_bytes, 0);
291 if (!(RAND_bytes(&random_bytes[0], keylen_bytes))) {
295 *key = WebKit::WebCryptoKey::create(
296 new SymKeyHandle(&random_bytes[0], random_bytes.size()),
297 key_type, extractable, algorithm, usage_mask);
302 bool WebCryptoImpl::GenerateKeyPairInternal(
303 const WebKit::WebCryptoAlgorithm& algorithm,
305 WebKit::WebCryptoKeyUsageMask usage_mask,
306 WebKit::WebCryptoKey* public_key,
307 WebKit::WebCryptoKey* private_key) {
308 // TODO(padolph): Placeholder for OpenSSL implementation.
309 // Issue http://crbug.com/267888.
313 bool WebCryptoImpl::ImportKeyInternal(
314 WebKit::WebCryptoKeyFormat format,
315 const unsigned char* key_data,
316 unsigned key_data_size,
317 const WebKit::WebCryptoAlgorithm& algorithm_or_null,
319 WebKit::WebCryptoKeyUsageMask usage_mask,
320 WebKit::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())
325 const WebKit::WebCryptoAlgorithm& algorithm = algorithm_or_null;
327 // TODO(padolph): Support all relevant alg types and then remove this gate.
328 if (algorithm.id() != WebKit::WebCryptoAlgorithmIdHmac &&
329 algorithm.id() != WebKit::WebCryptoAlgorithmIdAesCbc) {
333 // TODO(padolph): Need to split handling for symmetric (raw or jwk format) and
334 // asymmetric (jwk, spki, or pkcs8 format) keys.
335 // Currently only supporting symmetric.
337 // TODO(padolph): jwk handling. Define precedence between jwk contents and
338 // this method's parameters, e.g. 'alg' in jwk vs algorithm.id(). Who wins if
339 // they differ? (jwk, probably)
341 // Symmetric keys are always type secret
342 WebKit::WebCryptoKeyType type = WebKit::WebCryptoKeyTypeSecret;
344 const unsigned char* raw_key_data;
345 unsigned raw_key_data_size;
347 case WebKit::WebCryptoKeyFormatRaw:
348 raw_key_data = key_data;
349 raw_key_data_size = key_data_size;
350 // The NSS implementation fails when importing a raw AES key with a length
351 // incompatible with AES. The line below is to match this behavior.
352 if (algorithm.id() == WebKit::WebCryptoAlgorithmIdAesCbc &&
353 !GetAESCipherByKeyLength(raw_key_data_size)) {
357 case WebKit::WebCryptoKeyFormatJwk:
358 // TODO(padolph): Handle jwk format; need simple JSON parser.
365 *key = WebKit::WebCryptoKey::create(
366 new SymKeyHandle(raw_key_data, raw_key_data_size),
367 type, extractable, algorithm, usage_mask);
372 bool WebCryptoImpl::SignInternal(
373 const WebKit::WebCryptoAlgorithm& algorithm,
374 const WebKit::WebCryptoKey& key,
375 const unsigned char* data,
377 WebKit::WebArrayBuffer* buffer) {
379 WebKit::WebArrayBuffer result;
381 switch (algorithm.id()) {
382 case WebKit::WebCryptoAlgorithmIdHmac: {
384 DCHECK_EQ(key.algorithm().id(), WebKit::WebCryptoAlgorithmIdHmac);
385 DCHECK_NE(0, key.usages() & WebKit::WebCryptoKeyUsageSign);
387 const WebKit::WebCryptoHmacParams* const params = algorithm.hmacParams();
391 const EVP_MD* evp_sha = 0;
392 unsigned int hmac_expected_length = 0;
393 // Note that HMAC length is determined by the hash used.
394 switch (params->hash().id()) {
395 case WebKit::WebCryptoAlgorithmIdSha1:
396 evp_sha = EVP_sha1();
397 hmac_expected_length = SHA_DIGEST_LENGTH;
399 case WebKit::WebCryptoAlgorithmIdSha224:
400 evp_sha = EVP_sha224();
401 hmac_expected_length = SHA224_DIGEST_LENGTH;
403 case WebKit::WebCryptoAlgorithmIdSha256:
404 evp_sha = EVP_sha256();
405 hmac_expected_length = SHA256_DIGEST_LENGTH;
407 case WebKit::WebCryptoAlgorithmIdSha384:
408 evp_sha = EVP_sha384();
409 hmac_expected_length = SHA384_DIGEST_LENGTH;
411 case WebKit::WebCryptoAlgorithmIdSha512:
412 evp_sha = EVP_sha512();
413 hmac_expected_length = SHA512_DIGEST_LENGTH;
416 // Not a digest algorithm.
420 SymKeyHandle* const sym_key =
421 reinterpret_cast<SymKeyHandle*>(key.handle());
422 const std::vector<unsigned char>& raw_key = sym_key->key();
424 // OpenSSL wierdness here.
425 // First, HMAC() needs a void* for the key data, so make one up front as a
426 // cosmetic to avoid a cast. Second, OpenSSL does not like a NULL key,
427 // which will result if the raw_key vector is empty; an entirely valid
428 // case. Handle this specific case by pointing to an empty array.
429 const unsigned char null_key[] = {};
430 const void* const raw_key_voidp = raw_key.size() ? &raw_key[0] : null_key;
432 result = WebKit::WebArrayBuffer::create(hmac_expected_length, 1);
433 crypto::ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> hmac_result(
434 reinterpret_cast<unsigned char*>(result.data()),
435 hmac_expected_length);
437 crypto::OpenSSLErrStackTracer(FROM_HERE);
439 unsigned int hmac_actual_length;
440 unsigned char* const success = HMAC(evp_sha,
445 hmac_result.safe_buffer(),
446 &hmac_actual_length);
447 if (!success || hmac_actual_length != hmac_expected_length)
460 bool WebCryptoImpl::VerifySignatureInternal(
461 const WebKit::WebCryptoAlgorithm& algorithm,
462 const WebKit::WebCryptoKey& key,
463 const unsigned char* signature,
464 unsigned signature_size,
465 const unsigned char* data,
467 bool* signature_match) {
468 switch (algorithm.id()) {
469 case WebKit::WebCryptoAlgorithmIdHmac: {
470 WebKit::WebArrayBuffer result;
471 if (!SignInternal(algorithm, key, data, data_size, &result)) {
475 // Handling of truncated signatures is underspecified in the WebCrypto
476 // spec, so here we fail verification if a truncated signature is being
478 // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23097
480 result.byteLength() == signature_size &&
481 crypto::SecureMemEqual(result.data(), signature, signature_size);
491 } // namespace content