aes_decryptor.cc revision 58537e28ecd584eab876aee8be7156509866d23a
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 "media/cdm/aes_decryptor.h"
6
7#include <vector>
8
9#include "base/base64.h"
10#include "base/json/json_reader.h"
11#include "base/logging.h"
12#include "base/stl_util.h"
13#include "base/strings/string_number_conversions.h"
14#include "base/strings/string_util.h"
15#include "base/values.h"
16#include "crypto/encryptor.h"
17#include "crypto/symmetric_key.h"
18#include "media/base/audio_decoder_config.h"
19#include "media/base/decoder_buffer.h"
20#include "media/base/decrypt_config.h"
21#include "media/base/video_decoder_config.h"
22#include "media/base/video_frame.h"
23
24namespace media {
25
26uint32 AesDecryptor::next_session_id_ = 1;
27
28enum ClearBytesBufferSel {
29  kSrcContainsClearBytes,
30  kDstContainsClearBytes
31};
32
33typedef std::vector<std::pair<std::string, std::string> > JWKKeys;
34
35static void CopySubsamples(const std::vector<SubsampleEntry>& subsamples,
36                           const ClearBytesBufferSel sel,
37                           const uint8* src,
38                           uint8* dst) {
39  for (size_t i = 0; i < subsamples.size(); i++) {
40    const SubsampleEntry& subsample = subsamples[i];
41    if (sel == kSrcContainsClearBytes) {
42      src += subsample.clear_bytes;
43    } else {
44      dst += subsample.clear_bytes;
45    }
46    memcpy(dst, src, subsample.cypher_bytes);
47    src += subsample.cypher_bytes;
48    dst += subsample.cypher_bytes;
49  }
50}
51
52// Processes a JSON Web Key to extract the key id and key value. Adds the
53// id/value pair to |jwk_keys| and returns true on success.
54static bool ProcessSymmetricKeyJWK(const DictionaryValue& jwk,
55                                   JWKKeys* jwk_keys) {
56  // A symmetric keys JWK looks like the following in JSON:
57  //   { "kty":"oct",
58  //     "kid":"AAECAwQFBgcICQoLDA0ODxAREhM=",
59  //     "k":"FBUWFxgZGhscHR4fICEiIw==" }
60  // There may be other properties specified, but they are ignored.
61  // Ref: http://tools.ietf.org/html/draft-ietf-jose-json-web-key-14
62  // and:
63  // http://tools.ietf.org/html/draft-jones-jose-json-private-and-symmetric-key-00
64
65  // Have found a JWK, start by checking that it is a symmetric key.
66  std::string type;
67  if (!jwk.GetString("kty", &type) || type != "oct") {
68    DVLOG(1) << "JWK is not a symmetric key";
69    return false;
70  }
71
72  // Get the key id and actual key parameters.
73  std::string encoded_key_id;
74  std::string encoded_key;
75  if (!jwk.GetString("kid", &encoded_key_id)) {
76    DVLOG(1) << "Missing 'kid' parameter";
77    return false;
78  }
79  if (!jwk.GetString("k", &encoded_key)) {
80    DVLOG(1) << "Missing 'k' parameter";
81    return false;
82  }
83
84  // Key ID and key are base64-encoded strings, so decode them.
85  // TODO(jrummell): The JWK spec and the EME spec don't say that 'kid' must be
86  // base64-encoded (they don't say anything at all). Verify with the EME spec.
87  std::string decoded_key_id;
88  std::string decoded_key;
89  if (!base::Base64Decode(encoded_key_id, &decoded_key_id) ||
90      decoded_key_id.empty()) {
91    DVLOG(1) << "Invalid 'kid' value";
92    return false;
93  }
94  if (!base::Base64Decode(encoded_key, &decoded_key) ||
95      decoded_key.length() !=
96          static_cast<size_t>(DecryptConfig::kDecryptionKeySize)) {
97    DVLOG(1) << "Invalid length of 'k' " << decoded_key.length();
98    return false;
99  }
100
101  // Add the decoded key ID and the decoded key to the list.
102  jwk_keys->push_back(std::make_pair(decoded_key_id, decoded_key));
103  return true;
104}
105
106// Extracts the JSON Web Keys from a JSON Web Key Set. If |input| looks like
107// a valid JWK Set, then true is returned and |jwk_keys| is updated to contain
108// the list of keys found. Otherwise return false.
109static bool ExtractJWKKeys(const std::string& input, JWKKeys* jwk_keys) {
110  // TODO(jrummell): The EME spec references a smaller set of allowed ASCII
111  // values. Verify with spec that the smaller character set is needed.
112  if (!IsStringASCII(input))
113    return false;
114
115  scoped_ptr<Value> root(base::JSONReader().ReadToValue(input));
116  if (!root.get() || root->GetType() != Value::TYPE_DICTIONARY)
117    return false;
118
119  // A JSON Web Key Set looks like the following in JSON:
120  //   { "keys": [ JWK1, JWK2, ... ] }
121  // (See ProcessSymmetricKeyJWK() for description of JWK.)
122  // There may be other properties specified, but they are ignored.
123  // Locate the set from the dictionary.
124  DictionaryValue* dictionary = static_cast<DictionaryValue*>(root.get());
125  ListValue* list_val = NULL;
126  if (!dictionary->GetList("keys", &list_val)) {
127    DVLOG(1) << "Missing 'keys' parameter or not a list in JWK Set";
128    return false;
129  }
130
131  // Create a local list of keys, so that |jwk_keys| only gets updated on
132  // success.
133  JWKKeys local_keys;
134  for (size_t i = 0; i < list_val->GetSize(); ++i) {
135    DictionaryValue* jwk = NULL;
136    if (!list_val->GetDictionary(i, &jwk)) {
137      DVLOG(1) << "Unable to access 'keys'[" << i << "] in JWK Set";
138      return false;
139    }
140    if (!ProcessSymmetricKeyJWK(*jwk, &local_keys)) {
141      DVLOG(1) << "Error from 'keys'[" << i << "]";
142      return false;
143    }
144  }
145
146  // Successfully processed all JWKs in the set.
147  jwk_keys->swap(local_keys);
148  return true;
149}
150
151// Decrypts |input| using |key|.  Returns a DecoderBuffer with the decrypted
152// data if decryption succeeded or NULL if decryption failed.
153static scoped_refptr<DecoderBuffer> DecryptData(const DecoderBuffer& input,
154                                                crypto::SymmetricKey* key) {
155  CHECK(input.data_size());
156  CHECK(input.decrypt_config());
157  CHECK(key);
158
159  crypto::Encryptor encryptor;
160  if (!encryptor.Init(key, crypto::Encryptor::CTR, "")) {
161    DVLOG(1) << "Could not initialize decryptor.";
162    return NULL;
163  }
164
165  DCHECK_EQ(input.decrypt_config()->iv().size(),
166            static_cast<size_t>(DecryptConfig::kDecryptionKeySize));
167  if (!encryptor.SetCounter(input.decrypt_config()->iv())) {
168    DVLOG(1) << "Could not set counter block.";
169    return NULL;
170  }
171
172  const int data_offset = input.decrypt_config()->data_offset();
173  const char* sample =
174      reinterpret_cast<const char*>(input.data() + data_offset);
175  int sample_size = input.data_size() - data_offset;
176
177  DCHECK_GT(sample_size, 0) << "No sample data to be decrypted.";
178  if (sample_size <= 0)
179    return NULL;
180
181  if (input.decrypt_config()->subsamples().empty()) {
182    std::string decrypted_text;
183    base::StringPiece encrypted_text(sample, sample_size);
184    if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
185      DVLOG(1) << "Could not decrypt data.";
186      return NULL;
187    }
188
189    // TODO(xhwang): Find a way to avoid this data copy.
190    return DecoderBuffer::CopyFrom(
191        reinterpret_cast<const uint8*>(decrypted_text.data()),
192        decrypted_text.size());
193  }
194
195  const std::vector<SubsampleEntry>& subsamples =
196      input.decrypt_config()->subsamples();
197
198  int total_clear_size = 0;
199  int total_encrypted_size = 0;
200  for (size_t i = 0; i < subsamples.size(); i++) {
201    total_clear_size += subsamples[i].clear_bytes;
202    total_encrypted_size += subsamples[i].cypher_bytes;
203  }
204  if (total_clear_size + total_encrypted_size != sample_size) {
205    DVLOG(1) << "Subsample sizes do not equal input size";
206    return NULL;
207  }
208
209  // No need to decrypt if there is no encrypted data.
210  if (total_encrypted_size <= 0) {
211    return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8*>(sample),
212                                   sample_size);
213  }
214
215  // The encrypted portions of all subsamples must form a contiguous block,
216  // such that an encrypted subsample that ends away from a block boundary is
217  // immediately followed by the start of the next encrypted subsample. We
218  // copy all encrypted subsamples to a contiguous buffer, decrypt them, then
219  // copy the decrypted bytes over the encrypted bytes in the output.
220  // TODO(strobe): attempt to reduce number of memory copies
221  scoped_ptr<uint8[]> encrypted_bytes(new uint8[total_encrypted_size]);
222  CopySubsamples(subsamples, kSrcContainsClearBytes,
223                 reinterpret_cast<const uint8*>(sample), encrypted_bytes.get());
224
225  base::StringPiece encrypted_text(
226      reinterpret_cast<const char*>(encrypted_bytes.get()),
227      total_encrypted_size);
228  std::string decrypted_text;
229  if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) {
230    DVLOG(1) << "Could not decrypt data.";
231    return NULL;
232  }
233  DCHECK_EQ(decrypted_text.size(), encrypted_text.size());
234
235  scoped_refptr<DecoderBuffer> output = DecoderBuffer::CopyFrom(
236      reinterpret_cast<const uint8*>(sample), sample_size);
237  CopySubsamples(subsamples, kDstContainsClearBytes,
238                 reinterpret_cast<const uint8*>(decrypted_text.data()),
239                 output->writable_data());
240  return output;
241}
242
243AesDecryptor::AesDecryptor(const KeyAddedCB& key_added_cb,
244                           const KeyErrorCB& key_error_cb,
245                           const KeyMessageCB& key_message_cb)
246    : key_added_cb_(key_added_cb),
247      key_error_cb_(key_error_cb),
248      key_message_cb_(key_message_cb) {
249}
250
251AesDecryptor::~AesDecryptor() {
252  STLDeleteValues(&key_map_);
253}
254
255bool AesDecryptor::GenerateKeyRequest(const std::string& type,
256                                      const uint8* init_data,
257                                      int init_data_length) {
258  std::string session_id_string(base::UintToString(next_session_id_++));
259
260  // For now, the AesDecryptor does not care about |type|;
261  // just fire the event with the |init_data| as the request.
262  std::vector<uint8> message;
263  if (init_data && init_data_length)
264    message.assign(init_data, init_data + init_data_length);
265
266  key_message_cb_.Run(session_id_string, message, std::string());
267  return true;
268}
269
270void AesDecryptor::AddKey(const uint8* key,
271                          int key_length,
272                          const uint8* init_data,
273                          int init_data_length,
274                          const std::string& session_id) {
275  CHECK(key);
276  CHECK_GT(key_length, 0);
277
278  // AddKey() is called from update(), where the key(s) are passed as a JSON
279  // Web Key (JWK) set. Each JWK needs to be a symmetric key ('kty' = "oct"),
280  // with 'kid' being the base64-encoded key id, and 'k' being the
281  // base64-encoded key.
282  //
283  // For backwards compatibility with v0.1b of the spec (where |key| is the raw
284  // key and |init_data| is the key id), if |key| is not valid JSON, then
285  // attempt to process it as a raw key.
286
287  // TODO(xhwang): Add |session_id| check after we figure out how:
288  // https://www.w3.org/Bugs/Public/show_bug.cgi?id=16550
289
290  std::string key_string(reinterpret_cast<const char*>(key), key_length);
291  JWKKeys jwk_keys;
292  if (ExtractJWKKeys(key_string, &jwk_keys)) {
293    // Since |key| represents valid JSON, init_data must be empty.
294    DCHECK(!init_data);
295    DCHECK_EQ(init_data_length, 0);
296
297    // Make sure that at least one key was extracted.
298    if (jwk_keys.empty()) {
299      key_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0);
300      return;
301    }
302    for (JWKKeys::iterator it = jwk_keys.begin() ; it != jwk_keys.end(); ++it) {
303      if (!AddDecryptionKey(it->first, it->second)) {
304        key_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0);
305        return;
306      }
307    }
308  } else {
309    // v0.1b backwards compatibility support.
310    // TODO(jrummell): Remove this code once v0.1b no longer supported.
311
312    if (key_string.length() !=
313        static_cast<size_t>(DecryptConfig::kDecryptionKeySize)) {
314      DVLOG(1) << "Invalid key length: " << key_string.length();
315      key_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0);
316      return;
317    }
318
319    // TODO(xhwang): Fix the decryptor to accept no |init_data|. See
320    // http://crbug.com/123265. Until then, ensure a non-empty value is passed.
321    static const uint8 kDummyInitData[1] = {0};
322    if (!init_data) {
323      init_data = kDummyInitData;
324      init_data_length = arraysize(kDummyInitData);
325    }
326
327    // TODO(xhwang): For now, use |init_data| for key ID. Make this more spec
328    // compliant later (http://crbug.com/123262, http://crbug.com/123265).
329    std::string key_id_string(reinterpret_cast<const char*>(init_data),
330                              init_data_length);
331    if (!AddDecryptionKey(key_id_string, key_string)) {
332      // Error logged in AddDecryptionKey()
333      key_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0);
334      return;
335    }
336  }
337
338  if (!new_audio_key_cb_.is_null())
339    new_audio_key_cb_.Run();
340
341  if (!new_video_key_cb_.is_null())
342    new_video_key_cb_.Run();
343
344  key_added_cb_.Run(session_id);
345}
346
347void AesDecryptor::CancelKeyRequest(const std::string& session_id) {
348}
349
350Decryptor* AesDecryptor::GetDecryptor() {
351  return this;
352}
353
354void AesDecryptor::RegisterNewKeyCB(StreamType stream_type,
355                                    const NewKeyCB& new_key_cb) {
356  switch (stream_type) {
357    case kAudio:
358      new_audio_key_cb_ = new_key_cb;
359      break;
360    case kVideo:
361      new_video_key_cb_ = new_key_cb;
362      break;
363    default:
364      NOTREACHED();
365  }
366}
367
368void AesDecryptor::Decrypt(StreamType stream_type,
369                           const scoped_refptr<DecoderBuffer>& encrypted,
370                           const DecryptCB& decrypt_cb) {
371  CHECK(encrypted->decrypt_config());
372
373  scoped_refptr<DecoderBuffer> decrypted;
374  // An empty iv string signals that the frame is unencrypted.
375  if (encrypted->decrypt_config()->iv().empty()) {
376    int data_offset = encrypted->decrypt_config()->data_offset();
377    decrypted = DecoderBuffer::CopyFrom(encrypted->data() + data_offset,
378                                        encrypted->data_size() - data_offset);
379  } else {
380    const std::string& key_id = encrypted->decrypt_config()->key_id();
381    DecryptionKey* key = GetKey(key_id);
382    if (!key) {
383      DVLOG(1) << "Could not find a matching key for the given key ID.";
384      decrypt_cb.Run(kNoKey, NULL);
385      return;
386    }
387
388    crypto::SymmetricKey* decryption_key = key->decryption_key();
389    decrypted = DecryptData(*encrypted.get(), decryption_key);
390    if (!decrypted.get()) {
391      DVLOG(1) << "Decryption failed.";
392      decrypt_cb.Run(kError, NULL);
393      return;
394    }
395  }
396
397  decrypted->set_timestamp(encrypted->timestamp());
398  decrypted->set_duration(encrypted->duration());
399  decrypt_cb.Run(kSuccess, decrypted);
400}
401
402void AesDecryptor::CancelDecrypt(StreamType stream_type) {
403  // Decrypt() calls the DecryptCB synchronously so there's nothing to cancel.
404}
405
406void AesDecryptor::InitializeAudioDecoder(const AudioDecoderConfig& config,
407                                          const DecoderInitCB& init_cb) {
408  // AesDecryptor does not support audio decoding.
409  init_cb.Run(false);
410}
411
412void AesDecryptor::InitializeVideoDecoder(const VideoDecoderConfig& config,
413                                          const DecoderInitCB& init_cb) {
414  // AesDecryptor does not support video decoding.
415  init_cb.Run(false);
416}
417
418void AesDecryptor::DecryptAndDecodeAudio(
419    const scoped_refptr<DecoderBuffer>& encrypted,
420    const AudioDecodeCB& audio_decode_cb) {
421  NOTREACHED() << "AesDecryptor does not support audio decoding";
422}
423
424void AesDecryptor::DecryptAndDecodeVideo(
425    const scoped_refptr<DecoderBuffer>& encrypted,
426    const VideoDecodeCB& video_decode_cb) {
427  NOTREACHED() << "AesDecryptor does not support video decoding";
428}
429
430void AesDecryptor::ResetDecoder(StreamType stream_type) {
431  NOTREACHED() << "AesDecryptor does not support audio/video decoding";
432}
433
434void AesDecryptor::DeinitializeDecoder(StreamType stream_type) {
435  NOTREACHED() << "AesDecryptor does not support audio/video decoding";
436}
437
438bool AesDecryptor::AddDecryptionKey(const std::string& key_id,
439                                    const std::string& key_string) {
440  scoped_ptr<DecryptionKey> decryption_key(new DecryptionKey(key_string));
441  if (!decryption_key) {
442    DVLOG(1) << "Could not create key.";
443    return false;
444  }
445
446  if (!decryption_key->Init()) {
447    DVLOG(1) << "Could not initialize decryption key.";
448    return false;
449  }
450
451  base::AutoLock auto_lock(key_map_lock_);
452  KeyMap::iterator found = key_map_.find(key_id);
453  if (found != key_map_.end()) {
454    delete found->second;
455    key_map_.erase(found);
456  }
457  key_map_[key_id] = decryption_key.release();
458  return true;
459}
460
461AesDecryptor::DecryptionKey* AesDecryptor::GetKey(
462    const std::string& key_id) const {
463  base::AutoLock auto_lock(key_map_lock_);
464  KeyMap::const_iterator found = key_map_.find(key_id);
465  if (found == key_map_.end())
466    return NULL;
467
468  return found->second;
469}
470
471AesDecryptor::DecryptionKey::DecryptionKey(const std::string& secret)
472    : secret_(secret) {
473}
474
475AesDecryptor::DecryptionKey::~DecryptionKey() {}
476
477bool AesDecryptor::DecryptionKey::Init() {
478  CHECK(!secret_.empty());
479  decryption_key_.reset(crypto::SymmetricKey::Import(
480      crypto::SymmetricKey::AES, secret_));
481  if (!decryption_key_)
482    return false;
483  return true;
484}
485
486}  // namespace media
487