Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / renderer / webcrypto / webcrypto_impl_openssl.cc
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.
4
5 #include "content/renderer/webcrypto/webcrypto_impl.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 "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"
21
22 namespace content {
23
24 using webcrypto::Status;
25
26 namespace {
27
28 class SymKeyHandle : public blink::WebCryptoKeyHandle {
29  public:
30   SymKeyHandle(const unsigned char* key_data, unsigned int key_data_size)
31       : key_(key_data, key_data + key_data_size) {}
32
33   const std::vector<unsigned char>& key() const { return key_; }
34
35  private:
36   const std::vector<unsigned char> key_;
37
38   DISALLOW_COPY_AND_ASSIGN(SymKeyHandle);
39 };
40
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) {
44     case 16:
45       return EVP_aes_128_cbc();
46     case 24:
47       return EVP_aes_192_cbc();
48     case 32:
49       return EVP_aes_256_cbc();
50     default:
51       return NULL;
52   }
53 }
54
55 // OpenSSL constants for EVP_CipherInit_ex(), do not change
56 enum CipherOperation {
57   kDoDecrypt = 0,
58   kDoEncrypt = 1
59 };
60
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());
70
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();
76   }
77
78   // Note: PKCS padding is enabled by default
79   crypto::ScopedOpenSSL<EVP_CIPHER_CTX, EVP_CIPHER_CTX_free> context(
80       EVP_CIPHER_CTX_new());
81
82   if (!context.get())
83     return Status::Error();
84
85   SymKeyHandle* const sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
86
87   const EVP_CIPHER* const cipher =
88       GetAESCipherByKeyLength(sym_key->key().size());
89   DCHECK(cipher);
90
91   const blink::WebCryptoAesCbcParams* const params = algorithm.aesCbcParams();
92   if (params->iv().size() != AES_BLOCK_SIZE)
93     return Status::ErrorIncorrectSizeAesCbcIv();
94
95   if (!EVP_CipherInit_ex(context.get(),
96                          cipher,
97                          NULL,
98                          &sym_key->key()[0],
99                          params->iv().data(),
100                          cipher_operation)) {
101     return Status::Error();
102   }
103
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;
109   if (remainder != 0)
110     output_max_len += AES_BLOCK_SIZE - remainder;
111   DCHECK_GT(output_max_len, data_size);
112
113   *buffer = blink::WebArrayBuffer::create(output_max_len, 1);
114
115   unsigned char* const buffer_data =
116       reinterpret_cast<unsigned char*>(buffer->data());
117
118   int output_len = 0;
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();
126   }
127
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);
132
133   webcrypto::ShrinkBuffer(buffer, final_output_len);
134
135   return Status::Success();
136 }
137
138 Status ExportKeyInternalRaw(
139     const blink::WebCryptoKey& key,
140     blink::WebArrayBuffer* buffer) {
141
142   DCHECK(key.handle());
143   DCHECK(buffer);
144
145   if (key.type() != blink::WebCryptoKeyTypeSecret)
146     return Status::ErrorUnexpectedKeyType();
147
148   // TODO(eroman): This should be in a more generic location.
149   if (!key.extractable())
150     return Status::ErrorKeyNotExtractable();
151
152   const SymKeyHandle* sym_key = reinterpret_cast<SymKeyHandle*>(key.handle());
153
154   *buffer = webcrypto::CreateArrayBuffer(
155       webcrypto::Uint8VectorStart(sym_key->key()), sym_key->key().size());
156
157   return Status::Success();
158 }
159
160 }  // namespace
161
162 void WebCryptoImpl::Init() { crypto::EnsureOpenSSLInit(); }
163
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);
173   }
174
175   return Status::ErrorUnsupported();
176 }
177
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);
187   }
188
189   return Status::ErrorUnsupported();
190 }
191
192 Status WebCryptoImpl::DigestInternal(const blink::WebCryptoAlgorithm& algorithm,
193                                      const unsigned char* data,
194                                      unsigned int data_size,
195                                      blink::WebArrayBuffer* buffer) {
196
197   crypto::OpenSSLErrStackTracer(FROM_HERE);
198
199   const EVP_MD* digest_algorithm;
200   switch (algorithm.id()) {
201     case blink::WebCryptoAlgorithmIdSha1:
202       digest_algorithm = EVP_sha1();
203       break;
204     case blink::WebCryptoAlgorithmIdSha224:
205       digest_algorithm = EVP_sha224();
206       break;
207     case blink::WebCryptoAlgorithmIdSha256:
208       digest_algorithm = EVP_sha256();
209       break;
210     case blink::WebCryptoAlgorithmIdSha384:
211       digest_algorithm = EVP_sha384();
212       break;
213     case blink::WebCryptoAlgorithmIdSha512:
214       digest_algorithm = EVP_sha512();
215       break;
216     default:
217       // Not a digest algorithm.
218       return Status::ErrorUnsupported();
219   }
220
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();
225
226   if (!EVP_DigestInit_ex(digest_context.get(), digest_algorithm, NULL) ||
227       !EVP_DigestUpdate(digest_context.get(), data, data_size)) {
228     return Status::Error();
229   }
230
231   const int hash_expected_size = EVP_MD_CTX_size(digest_context.get());
232   if (hash_expected_size <= 0) {
233     return Status::ErrorUnexpected();
234   }
235   DCHECK_LE(hash_expected_size, EVP_MAX_MD_SIZE);
236
237   *buffer = blink::WebArrayBuffer::create(hash_expected_size, 1);
238   unsigned char* const hash_buffer =
239       reinterpret_cast<unsigned char* const>(buffer->data());
240
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) {
244     buffer->reset();
245     return Status::Error();
246   }
247
248   return Status::Success();
249 }
250
251 Status WebCryptoImpl::GenerateSecretKeyInternal(
252     const blink::WebCryptoAlgorithm& algorithm,
253     bool extractable,
254     blink::WebCryptoKeyUsageMask usage_mask,
255     blink::WebCryptoKey* key) {
256
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();
263       DCHECK(params);
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;
270       break;
271     }
272     case blink::WebCryptoAlgorithmIdHmac: {
273       const blink::WebCryptoHmacKeyParams* params = algorithm.hmacKeyParams();
274       DCHECK(params);
275       if (params->hasLengthBytes())
276         keylen_bytes = params->optionalLengthBytes();
277       else
278         keylen_bytes = webcrypto::ShaBlockSizeBytes(params->hash().id());
279       key_type = blink::WebCryptoKeyTypeSecret;
280       break;
281     }
282
283     default: { return Status::ErrorUnsupported(); }
284   }
285
286   if (keylen_bytes == 0)
287     return Status::ErrorGenerateKeyLength();
288
289   crypto::OpenSSLErrStackTracer(FROM_HERE);
290
291   std::vector<unsigned char> random_bytes(keylen_bytes, 0);
292   if (!(RAND_bytes(&random_bytes[0], keylen_bytes)))
293     return Status::Error();
294
295   *key = blink::WebCryptoKey::create(
296       new SymKeyHandle(&random_bytes[0], random_bytes.size()),
297       key_type, extractable, algorithm, usage_mask);
298
299   return Status::Success();
300 }
301
302 Status WebCryptoImpl::GenerateKeyPairInternal(
303     const blink::WebCryptoAlgorithm& algorithm,
304     bool extractable,
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();
311 }
312
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,
318     bool extractable,
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;
326
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();
331   }
332
333   // TODO(padolph): Need to split handling for symmetric (raw format) and
334   // asymmetric (spki or pkcs8 format) keys.
335   // Currently only supporting symmetric.
336
337   // Symmetric keys are always type secret
338   blink::WebCryptoKeyType type = blink::WebCryptoKeyTypeSecret;
339
340   const unsigned char* raw_key_data;
341   unsigned int raw_key_data_size;
342   switch (format) {
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();
351       }
352       break;
353     case blink::WebCryptoKeyFormatJwk:
354       return Status::ErrorUnexpected();
355     default:
356       return Status::ErrorUnsupported();
357   }
358
359   *key = blink::WebCryptoKey::create(
360       new SymKeyHandle(raw_key_data, raw_key_data_size),
361       type, extractable, algorithm, usage_mask);
362
363   return Status::Success();
364 }
365
366 Status WebCryptoImpl::ExportKeyInternal(
367     blink::WebCryptoKeyFormat format,
368     const blink::WebCryptoKey& key,
369     blink::WebArrayBuffer* buffer) {
370   switch (format) {
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();
379     default:
380       return Status::ErrorUnsupported();
381   }
382   return Status::ErrorUnsupported();
383 }
384
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) {
391
392   blink::WebArrayBuffer result;
393
394   switch (algorithm.id()) {
395     case blink::WebCryptoAlgorithmIdHmac: {
396
397       DCHECK_EQ(key.algorithm().id(), blink::WebCryptoAlgorithmIdHmac);
398       DCHECK_NE(0, key.usages() & blink::WebCryptoKeyUsageSign);
399
400       const blink::WebCryptoHmacParams* const params = algorithm.hmacParams();
401       if (!params)
402         return Status::ErrorUnexpected();
403
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;
411           break;
412         case blink::WebCryptoAlgorithmIdSha224:
413           evp_sha = EVP_sha224();
414           hmac_expected_length = SHA224_DIGEST_LENGTH;
415           break;
416         case blink::WebCryptoAlgorithmIdSha256:
417           evp_sha = EVP_sha256();
418           hmac_expected_length = SHA256_DIGEST_LENGTH;
419           break;
420         case blink::WebCryptoAlgorithmIdSha384:
421           evp_sha = EVP_sha384();
422           hmac_expected_length = SHA384_DIGEST_LENGTH;
423           break;
424         case blink::WebCryptoAlgorithmIdSha512:
425           evp_sha = EVP_sha512();
426           hmac_expected_length = SHA512_DIGEST_LENGTH;
427           break;
428         default:
429           // Not a digest algorithm.
430           return Status::ErrorUnsupported();
431       }
432
433       SymKeyHandle* const sym_key =
434           reinterpret_cast<SymKeyHandle*>(key.handle());
435       const std::vector<unsigned char>& raw_key = sym_key->key();
436
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;
444
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);
449
450       crypto::OpenSSLErrStackTracer(FROM_HERE);
451
452       unsigned int hmac_actual_length;
453       unsigned char* const success = HMAC(evp_sha,
454                                           raw_key_voidp,
455                                           raw_key.size(),
456                                           data,
457                                           data_size,
458                                           hmac_result.safe_buffer(),
459                                           &hmac_actual_length);
460       if (!success || hmac_actual_length != hmac_expected_length)
461         return Status::Error();
462
463       break;
464     }
465     default:
466       return Status::ErrorUnsupported();
467   }
468
469   *buffer = result;
470   return Status::Success();
471 }
472
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())
486         return status;
487
488       // Handling of truncated signatures is underspecified in the WebCrypto
489       // spec, so here we fail verification if a truncated signature is being
490       // verified.
491       // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=23097
492       *signature_match =
493           result.byteLength() == signature_size &&
494           crypto::SecureMemEqual(result.data(), signature, signature_size);
495
496       break;
497     }
498     default:
499       return Status::ErrorUnsupported();
500   }
501   return Status::Success();
502 }
503
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,
510     bool extractable,
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();
516 }
517
518 }  // namespace content