Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1132)

Side by Side Diff: content/child/webcrypto/platform_crypto_openssl.cc

Issue 401983002: Revert 284192 due to a failing test. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « content/child/webcrypto/platform_crypto_nss.cc ('k') | content/child/webcrypto/shared_crypto.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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.
4
5 #include "content/child/webcrypto/platform_crypto.h"
6
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>
13
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"
24
25 namespace content {
26
27 namespace webcrypto {
28
29 namespace platform {
30
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()) {}
35
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;
43 }
44
45 const std::vector<unsigned char>& key() const { return key_; }
46
47 private:
48 const std::vector<unsigned char> key_;
49
50 DISALLOW_COPY_AND_ASSIGN(SymKey);
51 };
52
53 namespace {
54
55 const EVP_CIPHER* GetAESCipherByKeyLength(unsigned int key_length_bytes) {
56 // OpenSSL supports AES CBC ciphers for only 2 key lengths: 128, 256 bits
57 switch (key_length_bytes) {
58 case 16:
59 return EVP_aes_128_cbc();
60 case 32:
61 return EVP_aes_256_cbc();
62 default:
63 return NULL;
64 }
65 }
66
67 const EVP_MD* GetDigest(blink::WebCryptoAlgorithmId id) {
68 switch (id) {
69 case blink::WebCryptoAlgorithmIdSha1:
70 return EVP_sha1();
71 case blink::WebCryptoAlgorithmIdSha256:
72 return EVP_sha256();
73 case blink::WebCryptoAlgorithmIdSha384:
74 return EVP_sha384();
75 case blink::WebCryptoAlgorithmIdSha512:
76 return EVP_sha512();
77 default:
78 return NULL;
79 }
80 }
81
82 // OpenSSL constants for EVP_CipherInit_ex(), do not change
83 enum CipherOperation { kDoDecrypt = 0, kDoEncrypt = 1 };
84
85 Status AesCbcEncryptDecrypt(EncryptOrDecrypt mode,
86 SymKey* key,
87 const CryptoData& iv,
88 const CryptoData& data,
89 std::vector<uint8>* buffer) {
90 CipherOperation cipher_operation =
91 (mode == ENCRYPT) ? kDoEncrypt : kDoDecrypt;
92
93 if (data.byte_length() >= INT_MAX - AES_BLOCK_SIZE) {
94 // TODO(padolph): Handle this by chunking the input fed into OpenSSL. Right
95 // now it doesn't make much difference since the one-shot API would end up
96 // blowing out the memory and crashing anyway.
97 return Status::ErrorDataTooLarge();
98 }
99
100 // Note: PKCS padding is enabled by default
101 crypto::ScopedOpenSSL<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free>::Type context(
102 EVP_CIPHER_CTX_new());
103
104 if (!context.get())
105 return Status::OperationError();
106
107 const EVP_CIPHER* const cipher = GetAESCipherByKeyLength(key->key().size());
108 DCHECK(cipher);
109
110 if (!EVP_CipherInit_ex(context.get(),
111 cipher,
112 NULL,
113 &key->key()[0],
114 iv.bytes(),
115 cipher_operation)) {
116 return Status::OperationError();
117 }
118
119 // According to the openssl docs, the amount of data written may be as large
120 // as (data_size + cipher_block_size - 1), constrained to a multiple of
121 // cipher_block_size.
122 unsigned int output_max_len = data.byte_length() + AES_BLOCK_SIZE - 1;
123 const unsigned remainder = output_max_len % AES_BLOCK_SIZE;
124 if (remainder != 0)
125 output_max_len += AES_BLOCK_SIZE - remainder;
126 DCHECK_GT(output_max_len, data.byte_length());
127
128 buffer->resize(output_max_len);
129
130 unsigned char* const buffer_data = Uint8VectorStart(buffer);
131
132 int output_len = 0;
133 if (!EVP_CipherUpdate(context.get(),
134 buffer_data,
135 &output_len,
136 data.bytes(),
137 data.byte_length()))
138 return Status::OperationError();
139 int final_output_chunk_len = 0;
140 if (!EVP_CipherFinal_ex(
141 context.get(), buffer_data + output_len, &final_output_chunk_len)) {
142 return Status::OperationError();
143 }
144
145 const unsigned int final_output_len =
146 static_cast<unsigned int>(output_len) +
147 static_cast<unsigned int>(final_output_chunk_len);
148 DCHECK_LE(final_output_len, output_max_len);
149
150 buffer->resize(final_output_len);
151
152 return Status::Success();
153 }
154
155 } // namespace
156
157 class DigestorOpenSSL : public blink::WebCryptoDigestor {
158 public:
159 explicit DigestorOpenSSL(blink::WebCryptoAlgorithmId algorithm_id)
160 : initialized_(false),
161 digest_context_(EVP_MD_CTX_create()),
162 algorithm_id_(algorithm_id) {}
163
164 virtual bool consume(const unsigned char* data, unsigned int size) {
165 return ConsumeWithStatus(data, size).IsSuccess();
166 }
167
168 Status ConsumeWithStatus(const unsigned char* data, unsigned int size) {
169 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
170 Status error = Init();
171 if (!error.IsSuccess())
172 return error;
173
174 if (!EVP_DigestUpdate(digest_context_.get(), data, size))
175 return Status::OperationError();
176
177 return Status::Success();
178 }
179
180 virtual bool finish(unsigned char*& result_data,
181 unsigned int& result_data_size) {
182 Status error = FinishInternal(result_, &result_data_size);
183 if (!error.IsSuccess())
184 return false;
185 result_data = result_;
186 return true;
187 }
188
189 Status FinishWithVectorAndStatus(std::vector<uint8>* result) {
190 const int hash_expected_size = EVP_MD_CTX_size(digest_context_.get());
191 result->resize(hash_expected_size);
192 unsigned char* const hash_buffer = Uint8VectorStart(result);
193 unsigned int hash_buffer_size; // ignored
194 return FinishInternal(hash_buffer, &hash_buffer_size);
195 }
196
197 private:
198 Status Init() {
199 if (initialized_)
200 return Status::Success();
201
202 const EVP_MD* digest_algorithm = GetDigest(algorithm_id_);
203 if (!digest_algorithm)
204 return Status::ErrorUnexpected();
205
206 if (!digest_context_.get())
207 return Status::OperationError();
208
209 if (!EVP_DigestInit_ex(digest_context_.get(), digest_algorithm, NULL))
210 return Status::OperationError();
211
212 initialized_ = true;
213 return Status::Success();
214 }
215
216 Status FinishInternal(unsigned char* result, unsigned int* result_size) {
217 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
218 Status error = Init();
219 if (!error.IsSuccess())
220 return error;
221
222 const int hash_expected_size = EVP_MD_CTX_size(digest_context_.get());
223 if (hash_expected_size <= 0)
224 return Status::ErrorUnexpected();
225 DCHECK_LE(hash_expected_size, EVP_MAX_MD_SIZE);
226
227 if (!EVP_DigestFinal_ex(digest_context_.get(), result, result_size) ||
228 static_cast<int>(*result_size) != hash_expected_size)
229 return Status::OperationError();
230
231 return Status::Success();
232 }
233
234 bool initialized_;
235 crypto::ScopedEVP_MD_CTX digest_context_;
236 blink::WebCryptoAlgorithmId algorithm_id_;
237 unsigned char result_[EVP_MAX_MD_SIZE];
238 };
239
240 Status ExportKeyRaw(SymKey* key, std::vector<uint8>* buffer) {
241 *buffer = key->key();
242 return Status::Success();
243 }
244
245 void Init() { crypto::EnsureOpenSSLInit(); }
246
247 Status EncryptDecryptAesCbc(EncryptOrDecrypt mode,
248 SymKey* key,
249 const CryptoData& data,
250 const CryptoData& iv,
251 std::vector<uint8>* buffer) {
252 // TODO(eroman): inline the function here.
253 return AesCbcEncryptDecrypt(mode, key, iv, data, buffer);
254 }
255
256 Status DigestSha(blink::WebCryptoAlgorithmId algorithm,
257 const CryptoData& data,
258 std::vector<uint8>* buffer) {
259 DigestorOpenSSL digestor(algorithm);
260 Status error = digestor.ConsumeWithStatus(data.bytes(), data.byte_length());
261 if (!error.IsSuccess())
262 return error;
263 return digestor.FinishWithVectorAndStatus(buffer);
264 }
265
266 scoped_ptr<blink::WebCryptoDigestor> CreateDigestor(
267 blink::WebCryptoAlgorithmId algorithm_id) {
268 return scoped_ptr<blink::WebCryptoDigestor>(
269 new DigestorOpenSSL(algorithm_id));
270 }
271
272 Status GenerateSecretKey(const blink::WebCryptoAlgorithm& algorithm,
273 bool extractable,
274 blink::WebCryptoKeyUsageMask usage_mask,
275 unsigned keylen_bytes,
276 blink::WebCryptoKey* key) {
277 // TODO(eroman): Is this right?
278 if (keylen_bytes == 0)
279 return Status::ErrorGenerateKeyLength();
280
281 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
282
283 std::vector<unsigned char> random_bytes(keylen_bytes, 0);
284 if (!(RAND_bytes(&random_bytes[0], keylen_bytes)))
285 return Status::OperationError();
286
287 blink::WebCryptoKeyAlgorithm key_algorithm;
288 if (!CreateSecretKeyAlgorithm(algorithm, keylen_bytes, &key_algorithm))
289 return Status::ErrorUnexpected();
290
291 *key = blink::WebCryptoKey::create(new SymKey(CryptoData(random_bytes)),
292 blink::WebCryptoKeyTypeSecret,
293 extractable,
294 key_algorithm,
295 usage_mask);
296
297 return Status::Success();
298 }
299
300 Status GenerateRsaKeyPair(const blink::WebCryptoAlgorithm& algorithm,
301 bool extractable,
302 blink::WebCryptoKeyUsageMask public_key_usage_mask,
303 blink::WebCryptoKeyUsageMask private_key_usage_mask,
304 unsigned int modulus_length_bits,
305 unsigned long public_exponent,
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();
311 }
312
313 Status ImportKeyRaw(const blink::WebCryptoAlgorithm& algorithm,
314 const CryptoData& key_data,
315 bool extractable,
316 blink::WebCryptoKeyUsageMask usage_mask,
317 blink::WebCryptoKey* key) {
318
319 blink::WebCryptoKeyAlgorithm key_algorithm;
320 if (!CreateSecretKeyAlgorithm(
321 algorithm, key_data.byte_length(), &key_algorithm))
322 return Status::ErrorUnexpected();
323
324 *key = blink::WebCryptoKey::create(new SymKey(key_data),
325 blink::WebCryptoKeyTypeSecret,
326 extractable,
327 key_algorithm,
328 usage_mask);
329
330 return Status::Success();
331 }
332
333 Status SignHmac(SymKey* key,
334 const blink::WebCryptoAlgorithm& hash,
335 const CryptoData& data,
336 std::vector<uint8>* buffer) {
337 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
338
339 const EVP_MD* digest_algorithm = GetDigest(hash.id());
340 if (!digest_algorithm)
341 return Status::ErrorUnsupported();
342 unsigned int hmac_expected_length = EVP_MD_size(digest_algorithm);
343
344 const std::vector<unsigned char>& raw_key = key->key();
345
346 // OpenSSL wierdness here.
347 // First, HMAC() needs a void* for the key data, so make one up front as a
348 // cosmetic to avoid a cast. Second, OpenSSL does not like a NULL key,
349 // which will result if the raw_key vector is empty; an entirely valid
350 // case. Handle this specific case by pointing to an empty array.
351 const unsigned char null_key[] = {};
352 const void* const raw_key_voidp = raw_key.size() ? &raw_key[0] : null_key;
353
354 buffer->resize(hmac_expected_length);
355 crypto::ScopedOpenSSLSafeSizeBuffer<EVP_MAX_MD_SIZE> hmac_result(
356 Uint8VectorStart(buffer), hmac_expected_length);
357
358 unsigned int hmac_actual_length;
359 unsigned char* const success = HMAC(digest_algorithm,
360 raw_key_voidp,
361 raw_key.size(),
362 data.bytes(),
363 data.byte_length(),
364 hmac_result.safe_buffer(),
365 &hmac_actual_length);
366 if (!success || hmac_actual_length != hmac_expected_length)
367 return Status::OperationError();
368
369 return Status::Success();
370 }
371
372 Status ImportRsaPublicKey(const blink::WebCryptoAlgorithm& algorithm,
373 bool extractable,
374 blink::WebCryptoKeyUsageMask usage_mask,
375 const CryptoData& modulus_data,
376 const CryptoData& exponent_data,
377 blink::WebCryptoKey* key) {
378 // TODO(padolph): Placeholder for OpenSSL implementation.
379 // Issue
380 return Status::ErrorUnsupported();
381 }
382
383 Status ImportRsaPrivateKey(const blink::WebCryptoAlgorithm& algorithm,
384 bool extractable,
385 blink::WebCryptoKeyUsageMask usage_mask,
386 const CryptoData& modulus,
387 const CryptoData& public_exponent,
388 const CryptoData& private_exponent,
389 const CryptoData& prime1,
390 const CryptoData& prime2,
391 const CryptoData& exponent1,
392 const CryptoData& exponent2,
393 const CryptoData& coefficient,
394 blink::WebCryptoKey* key) {
395 // TODO(eroman): http://crbug.com/267888
396 return Status::ErrorUnsupported();
397 }
398
399 const EVP_AEAD* GetAesGcmAlgorithmFromKeySize(unsigned int key_size_bytes) {
400 switch (key_size_bytes) {
401 case 16:
402 return EVP_aead_aes_128_gcm();
403 // TODO(eroman): Hook up 256-bit support when it is available.
404 default:
405 return NULL;
406 }
407 }
408
409 Status EncryptDecryptAesGcm(EncryptOrDecrypt mode,
410 SymKey* key,
411 const CryptoData& data,
412 const CryptoData& iv,
413 const CryptoData& additional_data,
414 unsigned int tag_length_bits,
415 std::vector<uint8>* buffer) {
416 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
417
418 DCHECK(tag_length_bits % 8 == 0);
419 const unsigned int tag_length_bytes = tag_length_bits / 8;
420
421 EVP_AEAD_CTX ctx;
422
423 const EVP_AEAD* const aead_alg =
424 GetAesGcmAlgorithmFromKeySize(key->key().size());
425 if (!aead_alg)
426 return Status::ErrorUnexpected();
427
428 if (!EVP_AEAD_CTX_init(&ctx,
429 aead_alg,
430 Uint8VectorStart(key->key()),
431 key->key().size(),
432 tag_length_bytes,
433 NULL)) {
434 return Status::OperationError();
435 }
436
437 crypto::ScopedOpenSSL<EVP_AEAD_CTX, EVP_AEAD_CTX_cleanup>::Type ctx_cleanup(
438 &ctx);
439
440 size_t len;
441 int ok;
442
443 if (mode == DECRYPT) {
444 if (data.byte_length() < tag_length_bytes)
445 return Status::ErrorDataTooSmall();
446
447 buffer->resize(data.byte_length() - tag_length_bytes);
448
449 ok = EVP_AEAD_CTX_open(&ctx,
450 Uint8VectorStart(buffer),
451 &len,
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);
463
464 ok = EVP_AEAD_CTX_seal(&ctx,
465 Uint8VectorStart(buffer),
466 &len,
467 buffer->size(),
468 iv.bytes(),
469 iv.byte_length(),
470 data.bytes(),
471 data.byte_length(),
472 additional_data.bytes(),
473 additional_data.byte_length());
474 }
475
476 if (!ok)
477 return Status::OperationError();
478 buffer->resize(len);
479 return Status::Success();
480 }
481
482 Status EncryptRsaOaep(PublicKey* key,
483 const blink::WebCryptoAlgorithm& hash,
484 const CryptoData& label,
485 const CryptoData& data,
486 std::vector<uint8>* buffer) {
487 // TODO(eroman): http://crbug.com/267888
488 return Status::ErrorUnsupported();
489 }
490
491 Status DecryptRsaOaep(PrivateKey* key,
492 const blink::WebCryptoAlgorithm& hash,
493 const CryptoData& label,
494 const CryptoData& data,
495 std::vector<uint8>* buffer) {
496 // TODO(eroman): http://crbug.com/267888
497 return Status::ErrorUnsupported();
498 }
499
500 Status SignRsaSsaPkcs1v1_5(PrivateKey* key,
501 const blink::WebCryptoAlgorithm& hash,
502 const CryptoData& data,
503 std::vector<uint8>* buffer) {
504 // TODO(eroman): http://crbug.com/267888
505 return Status::ErrorUnsupported();
506 }
507
508 // Key is guaranteed to be an RSA SSA key.
509 Status VerifyRsaSsaPkcs1v1_5(PublicKey* key,
510 const blink::WebCryptoAlgorithm& hash,
511 const CryptoData& signature,
512 const CryptoData& data,
513 bool* signature_match) {
514 // TODO(eroman): http://crbug.com/267888
515 return Status::ErrorUnsupported();
516 }
517
518 Status ImportKeySpki(const blink::WebCryptoAlgorithm& algorithm,
519 const CryptoData& key_data,
520 bool extractable,
521 blink::WebCryptoKeyUsageMask usage_mask,
522 blink::WebCryptoKey* key) {
523 // TODO(eroman): http://crbug.com/267888
524 return Status::ErrorUnsupported();
525 }
526
527 Status ImportKeyPkcs8(const blink::WebCryptoAlgorithm& algorithm,
528 const CryptoData& key_data,
529 bool extractable,
530 blink::WebCryptoKeyUsageMask usage_mask,
531 blink::WebCryptoKey* key) {
532 // TODO(eroman): http://crbug.com/267888
533 return Status::ErrorUnsupported();
534 }
535
536 Status ExportKeySpki(PublicKey* key, std::vector<uint8>* buffer) {
537 // TODO(eroman): http://crbug.com/267888
538 return Status::ErrorUnsupported();
539 }
540
541 Status ExportKeyPkcs8(PrivateKey* key,
542 const blink::WebCryptoKeyAlgorithm& key_algorithm,
543 std::vector<uint8>* buffer) {
544 // TODO(eroman): http://crbug.com/267888
545 return Status::ErrorUnsupported();
546 }
547
548 Status ExportRsaPublicKey(PublicKey* key,
549 std::vector<uint8>* modulus,
550 std::vector<uint8>* public_exponent) {
551 // TODO(eroman): http://crbug.com/267888
552 return Status::ErrorUnsupported();
553 }
554
555 Status ExportRsaPrivateKey(PrivateKey* key,
556 std::vector<uint8>* modulus,
557 std::vector<uint8>* public_exponent,
558 std::vector<uint8>* private_exponent,
559 std::vector<uint8>* prime1,
560 std::vector<uint8>* prime2,
561 std::vector<uint8>* exponent1,
562 std::vector<uint8>* exponent2,
563 std::vector<uint8>* coefficient) {
564 // TODO(eroman): http://crbug.com/267888
565 return Status::ErrorUnsupported();
566 }
567
568 Status EncryptDecryptAesKw(EncryptOrDecrypt mode,
569 SymKey* key,
570 const CryptoData& data,
571 std::vector<uint8>* buffer) {
572 // TODO(eroman): http://crbug.com/267888
573 return Status::ErrorUnsupported();
574 }
575
576 bool ThreadSafeDeserializeKeyForClone(
577 const blink::WebCryptoKeyAlgorithm& algorithm,
578 blink::WebCryptoKeyType type,
579 bool extractable,
580 blink::WebCryptoKeyUsageMask usages,
581 const CryptoData& key_data,
582 blink::WebCryptoKey* key) {
583 // TODO(eroman): http://crbug.com/267888
584 return false;
585 }
586
587 } // namespace platform
588
589 } // namespace webcrypto
590
591 } // namespace content
OLDNEW
« no previous file with comments | « content/child/webcrypto/platform_crypto_nss.cc ('k') | content/child/webcrypto/shared_crypto.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698