Map WebSocket URL schemes to HTTP URL schemes for auth purposes.
[chromium-blink-merge.git] / content / child / webcrypto / platform_crypto_openssl.cc
blob89212ea55b201472c878c2e6edfe1431ed913223
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"
7 #include <vector>
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"
25 namespace content {
27 namespace webcrypto {
29 namespace platform {
31 class SymKey : public Key {
32 public:
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());
42 return true;
45 const std::vector<unsigned char>& key() const { return key_; }
47 private:
48 const std::vector<unsigned char> key_;
50 DISALLOW_COPY_AND_ASSIGN(SymKey);
53 namespace {
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) {
58 case 16:
59 return EVP_aes_128_cbc();
60 case 24:
61 return EVP_aes_192_cbc();
62 case 32:
63 return EVP_aes_256_cbc();
64 default:
65 return NULL;
69 const EVP_MD* GetDigest(blink::WebCryptoAlgorithmId id) {
70 switch (id) {
71 case blink::WebCryptoAlgorithmIdSha1:
72 return EVP_sha1();
73 case blink::WebCryptoAlgorithmIdSha256:
74 return EVP_sha256();
75 case blink::WebCryptoAlgorithmIdSha384:
76 return EVP_sha384();
77 case blink::WebCryptoAlgorithmIdSha512:
78 return EVP_sha512();
79 default:
80 return NULL;
84 // OpenSSL constants for EVP_CipherInit_ex(), do not change
85 enum CipherOperation { kDoDecrypt = 0, kDoEncrypt = 1 };
87 Status AesCbcEncryptDecrypt(EncryptOrDecrypt mode,
88 SymKey* key,
89 const CryptoData& iv,
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());
106 if (!context.get())
107 return Status::OperationError();
109 const EVP_CIPHER* const cipher = GetAESCipherByKeyLength(key->key().size());
110 DCHECK(cipher);
112 if (!EVP_CipherInit_ex(context.get(),
113 cipher,
114 NULL,
115 &key->key()[0],
116 iv.bytes(),
117 cipher_operation)) {
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;
126 if (remainder != 0)
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);
134 int output_len = 0;
135 if (!EVP_CipherUpdate(context.get(),
136 buffer_data,
137 &output_len,
138 data.bytes(),
139 data.byte_length()))
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();
157 } // namespace
159 class DigestorOpenSSL : public blink::WebCryptoDigestor {
160 public:
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())
174 return error;
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())
186 return false;
187 result_data = result_;
188 return true;
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);
199 private:
200 Status Init() {
201 if (initialized_)
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();
214 initialized_ = true;
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())
222 return error;
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();
236 bool initialized_;
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,
250 SymKey* key,
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())
264 return error;
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,
275 bool extractable,
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,
295 extractable,
296 key_algorithm,
297 usage_mask);
299 return Status::Success();
302 Status GenerateRsaKeyPair(const blink::WebCryptoAlgorithm& algorithm,
303 bool extractable,
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,
317 bool extractable,
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,
328 extractable,
329 key_algorithm,
330 usage_mask);
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,
362 raw_key_voidp,
363 raw_key.size(),
364 data.bytes(),
365 data.byte_length(),
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,
375 bool extractable,
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.
381 // Issue
382 return Status::ErrorUnsupported();
385 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm,
386 bool extractable,
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) {
403 case 16:
404 return EVP_aead_aes_128_gcm();
405 // TODO(eroman): Hook up 256-bit support when it is available.
406 default:
407 return NULL;
411 Status EncryptDecryptAesGcm(EncryptOrDecrypt mode,
412 SymKey* key,
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;
423 EVP_AEAD_CTX ctx;
425 const EVP_AEAD* const aead_alg =
426 GetAesGcmAlgorithmFromKeySize(key->key().size());
427 if (!aead_alg)
428 return Status::ErrorUnexpected();
430 if (!EVP_AEAD_CTX_init(&ctx,
431 aead_alg,
432 Uint8VectorStart(key->key()),
433 key->key().size(),
434 tag_length_bytes,
435 NULL)) {
436 return Status::OperationError();
439 crypto::ScopedOpenSSL<EVP_AEAD_CTX, EVP_AEAD_CTX_cleanup>::Type ctx_cleanup(
440 &ctx);
442 ssize_t len;
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),
452 buffer->size(),
453 iv.bytes(),
454 iv.byte_length(),
455 data.bytes(),
456 data.byte_length(),
457 additional_data.bytes(),
458 additional_data.byte_length());
459 } else {
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),
466 buffer->size(),
467 iv.bytes(),
468 iv.byte_length(),
469 data.bytes(),
470 data.byte_length(),
471 additional_data.bytes(),
472 additional_data.byte_length());
475 if (len < 0)
476 return Status::OperationError();
477 buffer->resize(len);
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,
519 bool extractable,
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,
528 bool extractable,
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,
568 SymKey* key,
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,
578 bool extractable,
579 blink::WebCryptoKeyUsageMask usages,
580 const CryptoData& key_data,
581 blink::WebCryptoKey* key) {
582 // TODO(eroman): http://crbug.com/267888
583 return false;
586 } // namespace platform
588 } // namespace webcrypto
590 } // namespace content