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 "media/cdm/aes_decryptor.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "crypto/encryptor.h"
14 #include "crypto/symmetric_key.h"
15 #include "media/base/audio_decoder_config.h"
16 #include "media/base/cdm_key_information.h"
17 #include "media/base/cdm_promise.h"
18 #include "media/base/decoder_buffer.h"
19 #include "media/base/decrypt_config.h"
20 #include "media/base/video_decoder_config.h"
21 #include "media/base/video_frame.h"
22 #include "media/cdm/cenc_utils.h"
23 #include "media/cdm/json_web_key.h"
27 // Keeps track of the session IDs and DecryptionKeys. The keys are ordered by
28 // insertion time (last insertion is first). It takes ownership of the
30 class AesDecryptor::SessionIdDecryptionKeyMap
{
31 // Use a std::list to actually hold the data. Insertion is always done
32 // at the front, so the "latest" decryption key is always the first one
34 typedef std::list
<std::pair
<std::string
, DecryptionKey
*> > KeyList
;
37 SessionIdDecryptionKeyMap() {}
38 ~SessionIdDecryptionKeyMap() { STLDeleteValues(&key_list_
); }
40 // Replaces value if |session_id| is already present, or adds it if not.
41 // This |decryption_key| becomes the latest until another insertion or
42 // |session_id| is erased.
43 void Insert(const std::string
& session_id
,
44 scoped_ptr
<DecryptionKey
> decryption_key
);
46 // Deletes the entry for |session_id| if present.
47 void Erase(const std::string
& session_id
);
49 // Returns whether the list is empty
50 bool Empty() const { return key_list_
.empty(); }
52 // Returns the last inserted DecryptionKey.
53 DecryptionKey
* LatestDecryptionKey() {
54 DCHECK(!key_list_
.empty());
55 return key_list_
.begin()->second
;
58 bool Contains(const std::string
& session_id
) {
59 return Find(session_id
) != key_list_
.end();
63 // Searches the list for an element with |session_id|.
64 KeyList::iterator
Find(const std::string
& session_id
);
66 // Deletes the entry pointed to by |position|.
67 void Erase(KeyList::iterator position
);
71 DISALLOW_COPY_AND_ASSIGN(SessionIdDecryptionKeyMap
);
74 void AesDecryptor::SessionIdDecryptionKeyMap::Insert(
75 const std::string
& session_id
,
76 scoped_ptr
<DecryptionKey
> decryption_key
) {
77 KeyList::iterator it
= Find(session_id
);
78 if (it
!= key_list_
.end())
80 DecryptionKey
* raw_ptr
= decryption_key
.release();
81 key_list_
.push_front(std::make_pair(session_id
, raw_ptr
));
84 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
85 const std::string
& session_id
) {
86 KeyList::iterator it
= Find(session_id
);
87 if (it
== key_list_
.end())
92 AesDecryptor::SessionIdDecryptionKeyMap::KeyList::iterator
93 AesDecryptor::SessionIdDecryptionKeyMap::Find(const std::string
& session_id
) {
94 for (KeyList::iterator it
= key_list_
.begin(); it
!= key_list_
.end(); ++it
) {
95 if (it
->first
== session_id
)
98 return key_list_
.end();
101 void AesDecryptor::SessionIdDecryptionKeyMap::Erase(
102 KeyList::iterator position
) {
103 DCHECK(position
->second
);
104 delete position
->second
;
105 key_list_
.erase(position
);
108 uint32
AesDecryptor::next_session_id_
= 1;
110 enum ClearBytesBufferSel
{
111 kSrcContainsClearBytes
,
112 kDstContainsClearBytes
115 static void CopySubsamples(const std::vector
<SubsampleEntry
>& subsamples
,
116 const ClearBytesBufferSel sel
,
119 for (size_t i
= 0; i
< subsamples
.size(); i
++) {
120 const SubsampleEntry
& subsample
= subsamples
[i
];
121 if (sel
== kSrcContainsClearBytes
) {
122 src
+= subsample
.clear_bytes
;
124 dst
+= subsample
.clear_bytes
;
126 memcpy(dst
, src
, subsample
.cypher_bytes
);
127 src
+= subsample
.cypher_bytes
;
128 dst
+= subsample
.cypher_bytes
;
132 // Decrypts |input| using |key|. Returns a DecoderBuffer with the decrypted
133 // data if decryption succeeded or NULL if decryption failed.
134 static scoped_refptr
<DecoderBuffer
> DecryptData(const DecoderBuffer
& input
,
135 crypto::SymmetricKey
* key
) {
136 CHECK(input
.data_size());
137 CHECK(input
.decrypt_config());
140 crypto::Encryptor encryptor
;
141 if (!encryptor
.Init(key
, crypto::Encryptor::CTR
, "")) {
142 DVLOG(1) << "Could not initialize decryptor.";
146 DCHECK_EQ(input
.decrypt_config()->iv().size(),
147 static_cast<size_t>(DecryptConfig::kDecryptionKeySize
));
148 if (!encryptor
.SetCounter(input
.decrypt_config()->iv())) {
149 DVLOG(1) << "Could not set counter block.";
153 const char* sample
= reinterpret_cast<const char*>(input
.data());
154 size_t sample_size
= static_cast<size_t>(input
.data_size());
156 DCHECK_GT(sample_size
, 0U) << "No sample data to be decrypted.";
157 if (sample_size
== 0)
160 if (input
.decrypt_config()->subsamples().empty()) {
161 std::string decrypted_text
;
162 base::StringPiece
encrypted_text(sample
, sample_size
);
163 if (!encryptor
.Decrypt(encrypted_text
, &decrypted_text
)) {
164 DVLOG(1) << "Could not decrypt data.";
168 // TODO(xhwang): Find a way to avoid this data copy.
169 return DecoderBuffer::CopyFrom(
170 reinterpret_cast<const uint8
*>(decrypted_text
.data()),
171 decrypted_text
.size());
174 const std::vector
<SubsampleEntry
>& subsamples
=
175 input
.decrypt_config()->subsamples();
177 size_t total_clear_size
= 0;
178 size_t total_encrypted_size
= 0;
179 for (size_t i
= 0; i
< subsamples
.size(); i
++) {
180 total_clear_size
+= subsamples
[i
].clear_bytes
;
181 total_encrypted_size
+= subsamples
[i
].cypher_bytes
;
182 // Check for overflow. This check is valid because *_size is unsigned.
183 DCHECK(total_clear_size
>= subsamples
[i
].clear_bytes
);
184 if (total_encrypted_size
< subsamples
[i
].cypher_bytes
)
187 size_t total_size
= total_clear_size
+ total_encrypted_size
;
188 if (total_size
< total_clear_size
|| total_size
!= sample_size
) {
189 DVLOG(1) << "Subsample sizes do not equal input size";
193 // No need to decrypt if there is no encrypted data.
194 if (total_encrypted_size
<= 0) {
195 return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8
*>(sample
),
199 // The encrypted portions of all subsamples must form a contiguous block,
200 // such that an encrypted subsample that ends away from a block boundary is
201 // immediately followed by the start of the next encrypted subsample. We
202 // copy all encrypted subsamples to a contiguous buffer, decrypt them, then
203 // copy the decrypted bytes over the encrypted bytes in the output.
204 // TODO(strobe): attempt to reduce number of memory copies
205 scoped_ptr
<uint8
[]> encrypted_bytes(new uint8
[total_encrypted_size
]);
206 CopySubsamples(subsamples
, kSrcContainsClearBytes
,
207 reinterpret_cast<const uint8
*>(sample
), encrypted_bytes
.get());
209 base::StringPiece
encrypted_text(
210 reinterpret_cast<const char*>(encrypted_bytes
.get()),
211 total_encrypted_size
);
212 std::string decrypted_text
;
213 if (!encryptor
.Decrypt(encrypted_text
, &decrypted_text
)) {
214 DVLOG(1) << "Could not decrypt data.";
217 DCHECK_EQ(decrypted_text
.size(), encrypted_text
.size());
219 scoped_refptr
<DecoderBuffer
> output
= DecoderBuffer::CopyFrom(
220 reinterpret_cast<const uint8
*>(sample
), sample_size
);
221 CopySubsamples(subsamples
, kDstContainsClearBytes
,
222 reinterpret_cast<const uint8
*>(decrypted_text
.data()),
223 output
->writable_data());
227 AesDecryptor::AesDecryptor(const SessionMessageCB
& session_message_cb
,
228 const SessionClosedCB
& session_closed_cb
,
229 const SessionKeysChangeCB
& session_keys_change_cb
)
230 : session_message_cb_(session_message_cb
),
231 session_closed_cb_(session_closed_cb
),
232 session_keys_change_cb_(session_keys_change_cb
) {
233 DCHECK(!session_message_cb_
.is_null());
234 DCHECK(!session_closed_cb_
.is_null());
235 DCHECK(!session_keys_change_cb_
.is_null());
238 AesDecryptor::~AesDecryptor() {
242 void AesDecryptor::SetServerCertificate(const uint8
* certificate_data
,
243 int certificate_data_length
,
244 scoped_ptr
<SimpleCdmPromise
> promise
) {
246 NOT_SUPPORTED_ERROR
, 0, "SetServerCertificate() is not supported.");
249 void AesDecryptor::CreateSessionAndGenerateRequest(
250 SessionType session_type
,
251 const std::string
& init_data_type
,
252 const uint8
* init_data
,
253 int init_data_length
,
254 scoped_ptr
<NewSessionCdmPromise
> promise
) {
255 std::string
session_id(base::UintToString(next_session_id_
++));
256 valid_sessions_
.insert(session_id
);
258 // For now, the AesDecryptor does not care about |session_type|.
259 // TODO(jrummell): Validate |session_type|.
261 std::vector
<uint8
> message
;
262 // TODO(jrummell): Since unprefixed will never send NULL, remove this check
263 // when prefixed EME is removed (http://crbug.com/249976).
264 if (init_data
&& init_data_length
) {
265 std::vector
<std::vector
<uint8
>> keys
;
266 if (init_data_type
== "webm") {
267 // |init_data| is simply the key needed.
269 std::vector
<uint8
>(init_data
, init_data
+ init_data_length
));
270 } else if (init_data_type
== "cenc") {
271 // |init_data| is a set of 0 or more concatenated 'pssh' boxes.
272 if (!GetKeyIdsForCommonSystemId(init_data
, init_data_length
, &keys
)) {
273 promise
->reject(NOT_SUPPORTED_ERROR
, 0, "No supported PSSH box found.");
277 // TODO(jrummell): Support init_data_type == "keyids".
278 promise
->reject(NOT_SUPPORTED_ERROR
, 0, "init_data_type not supported.");
281 CreateLicenseRequest(keys
, session_type
, &message
);
284 promise
->resolve(session_id
);
286 // No URL needed for license requests.
287 session_message_cb_
.Run(session_id
, LICENSE_REQUEST
, message
,
291 void AesDecryptor::LoadSession(SessionType session_type
,
292 const std::string
& session_id
,
293 scoped_ptr
<NewSessionCdmPromise
> promise
) {
294 // TODO(xhwang): Change this to NOTREACHED() when blink checks for key systems
295 // that do not support loadSession. See http://crbug.com/342481
296 promise
->reject(NOT_SUPPORTED_ERROR
, 0, "LoadSession() is not supported.");
299 void AesDecryptor::UpdateSession(const std::string
& session_id
,
300 const uint8
* response
,
302 scoped_ptr
<SimpleCdmPromise
> promise
) {
304 CHECK_GT(response_length
, 0);
306 // TODO(jrummell): Convert back to a DCHECK once prefixed EME is removed.
307 if (valid_sessions_
.find(session_id
) == valid_sessions_
.end()) {
308 promise
->reject(INVALID_ACCESS_ERROR
, 0, "Session does not exist.");
312 std::string
key_string(reinterpret_cast<const char*>(response
),
315 KeyIdAndKeyPairs keys
;
316 SessionType session_type
= MediaKeys::TEMPORARY_SESSION
;
317 if (!ExtractKeysFromJWKSet(key_string
, &keys
, &session_type
)) {
319 INVALID_ACCESS_ERROR
, 0, "Response is not a valid JSON Web Key Set.");
323 // Make sure that at least one key was extracted.
326 INVALID_ACCESS_ERROR
, 0, "Response does not contain any keys.");
330 for (KeyIdAndKeyPairs::iterator it
= keys
.begin(); it
!= keys
.end(); ++it
) {
331 if (it
->second
.length() !=
332 static_cast<size_t>(DecryptConfig::kDecryptionKeySize
)) {
333 DVLOG(1) << "Invalid key length: " << it
->second
.length();
334 promise
->reject(INVALID_ACCESS_ERROR
, 0, "Invalid key length.");
337 if (!AddDecryptionKey(session_id
, it
->first
, it
->second
)) {
338 promise
->reject(INVALID_ACCESS_ERROR
, 0, "Unable to add key.");
344 base::AutoLock
auto_lock(new_key_cb_lock_
);
346 if (!new_audio_key_cb_
.is_null())
347 new_audio_key_cb_
.Run();
349 if (!new_video_key_cb_
.is_null())
350 new_video_key_cb_
.Run();
355 // Create the list of all available keys for this session.
356 CdmKeysInfo keys_info
;
358 base::AutoLock
auto_lock(key_map_lock_
);
359 for (const auto& item
: key_map_
) {
360 if (item
.second
->Contains(session_id
)) {
361 scoped_ptr
<CdmKeyInformation
> key_info(new CdmKeyInformation
);
362 key_info
->key_id
.assign(item
.first
.begin(), item
.first
.end());
363 key_info
->status
= CdmKeyInformation::USABLE
;
364 key_info
->system_code
= 0;
365 keys_info
.push_back(key_info
.release());
370 // Assume that at least 1 new key has been successfully added and thus
371 // sending true for |has_additional_usable_key|. http://crbug.com/448219.
372 session_keys_change_cb_
.Run(session_id
, true, keys_info
.Pass());
375 void AesDecryptor::CloseSession(const std::string
& session_id
,
376 scoped_ptr
<SimpleCdmPromise
> promise
) {
377 // Validate that this is a reference to an active session and then forget it.
378 std::set
<std::string
>::iterator it
= valid_sessions_
.find(session_id
);
379 DCHECK(it
!= valid_sessions_
.end());
381 valid_sessions_
.erase(it
);
383 // Close the session.
384 DeleteKeysForSession(session_id
);
386 session_closed_cb_
.Run(session_id
);
389 void AesDecryptor::RemoveSession(const std::string
& session_id
,
390 scoped_ptr
<SimpleCdmPromise
> promise
) {
391 // AesDecryptor doesn't keep any persistent data, so this should be
393 // TODO(jrummell): Make sure persistent session types are rejected.
394 // http://crbug.com/384152.
396 // However, v0.1b calls to CancelKeyRequest() will call this, so close the
397 // session, if it exists.
398 // TODO(jrummell): Remove the close() call when prefixed EME is removed.
399 // http://crbug.com/249976.
400 if (valid_sessions_
.find(session_id
) != valid_sessions_
.end()) {
401 CloseSession(session_id
, promise
.Pass());
405 promise
->reject(INVALID_ACCESS_ERROR
, 0, "Session does not exist.");
408 CdmContext
* AesDecryptor::GetCdmContext() {
412 Decryptor
* AesDecryptor::GetDecryptor() {
416 #if defined(ENABLE_BROWSER_CDMS)
417 int AesDecryptor::GetCdmId() const {
418 return kInvalidCdmId
;
420 #endif // defined(ENABLE_BROWSER_CDMS)
422 void AesDecryptor::RegisterNewKeyCB(StreamType stream_type
,
423 const NewKeyCB
& new_key_cb
) {
424 base::AutoLock
auto_lock(new_key_cb_lock_
);
426 switch (stream_type
) {
428 new_audio_key_cb_
= new_key_cb
;
431 new_video_key_cb_
= new_key_cb
;
438 void AesDecryptor::Decrypt(StreamType stream_type
,
439 const scoped_refptr
<DecoderBuffer
>& encrypted
,
440 const DecryptCB
& decrypt_cb
) {
441 CHECK(encrypted
->decrypt_config());
443 scoped_refptr
<DecoderBuffer
> decrypted
;
444 // An empty iv string signals that the frame is unencrypted.
445 if (encrypted
->decrypt_config()->iv().empty()) {
446 decrypted
= DecoderBuffer::CopyFrom(encrypted
->data(),
447 encrypted
->data_size());
449 const std::string
& key_id
= encrypted
->decrypt_config()->key_id();
450 DecryptionKey
* key
= GetKey(key_id
);
452 DVLOG(1) << "Could not find a matching key for the given key ID.";
453 decrypt_cb
.Run(kNoKey
, NULL
);
457 crypto::SymmetricKey
* decryption_key
= key
->decryption_key();
458 decrypted
= DecryptData(*encrypted
.get(), decryption_key
);
459 if (!decrypted
.get()) {
460 DVLOG(1) << "Decryption failed.";
461 decrypt_cb
.Run(kError
, NULL
);
466 decrypted
->set_timestamp(encrypted
->timestamp());
467 decrypted
->set_duration(encrypted
->duration());
468 decrypt_cb
.Run(kSuccess
, decrypted
);
471 void AesDecryptor::CancelDecrypt(StreamType stream_type
) {
472 // Decrypt() calls the DecryptCB synchronously so there's nothing to cancel.
475 void AesDecryptor::InitializeAudioDecoder(const AudioDecoderConfig
& config
,
476 const DecoderInitCB
& init_cb
) {
477 // AesDecryptor does not support audio decoding.
481 void AesDecryptor::InitializeVideoDecoder(const VideoDecoderConfig
& config
,
482 const DecoderInitCB
& init_cb
) {
483 // AesDecryptor does not support video decoding.
487 void AesDecryptor::DecryptAndDecodeAudio(
488 const scoped_refptr
<DecoderBuffer
>& encrypted
,
489 const AudioDecodeCB
& audio_decode_cb
) {
490 NOTREACHED() << "AesDecryptor does not support audio decoding";
493 void AesDecryptor::DecryptAndDecodeVideo(
494 const scoped_refptr
<DecoderBuffer
>& encrypted
,
495 const VideoDecodeCB
& video_decode_cb
) {
496 NOTREACHED() << "AesDecryptor does not support video decoding";
499 void AesDecryptor::ResetDecoder(StreamType stream_type
) {
500 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
503 void AesDecryptor::DeinitializeDecoder(StreamType stream_type
) {
504 NOTREACHED() << "AesDecryptor does not support audio/video decoding";
507 bool AesDecryptor::AddDecryptionKey(const std::string
& session_id
,
508 const std::string
& key_id
,
509 const std::string
& key_string
) {
510 scoped_ptr
<DecryptionKey
> decryption_key(new DecryptionKey(key_string
));
511 if (!decryption_key
->Init()) {
512 DVLOG(1) << "Could not initialize decryption key.";
516 base::AutoLock
auto_lock(key_map_lock_
);
517 KeyIdToSessionKeysMap::iterator key_id_entry
= key_map_
.find(key_id
);
518 if (key_id_entry
!= key_map_
.end()) {
519 key_id_entry
->second
->Insert(session_id
, decryption_key
.Pass());
523 // |key_id| not found, so need to create new entry.
524 scoped_ptr
<SessionIdDecryptionKeyMap
> inner_map(
525 new SessionIdDecryptionKeyMap());
526 inner_map
->Insert(session_id
, decryption_key
.Pass());
527 key_map_
.add(key_id
, inner_map
.Pass());
531 AesDecryptor::DecryptionKey
* AesDecryptor::GetKey(
532 const std::string
& key_id
) const {
533 base::AutoLock
auto_lock(key_map_lock_
);
534 KeyIdToSessionKeysMap::const_iterator key_id_found
= key_map_
.find(key_id
);
535 if (key_id_found
== key_map_
.end())
538 // Return the key from the "latest" session_id entry.
539 return key_id_found
->second
->LatestDecryptionKey();
542 void AesDecryptor::DeleteKeysForSession(const std::string
& session_id
) {
543 base::AutoLock
auto_lock(key_map_lock_
);
545 // Remove all keys associated with |session_id|. Since the data is
546 // optimized for access in GetKey(), we need to look at each entry in
548 KeyIdToSessionKeysMap::iterator it
= key_map_
.begin();
549 while (it
!= key_map_
.end()) {
550 it
->second
->Erase(session_id
);
551 if (it
->second
->Empty()) {
552 // Need to get rid of the entry for this key_id. This will mess up the
553 // iterator, so we need to increment it first.
554 KeyIdToSessionKeysMap::iterator current
= it
;
556 key_map_
.erase(current
);
563 AesDecryptor::DecryptionKey::DecryptionKey(const std::string
& secret
)
567 AesDecryptor::DecryptionKey::~DecryptionKey() {}
569 bool AesDecryptor::DecryptionKey::Init() {
570 CHECK(!secret_
.empty());
571 decryption_key_
.reset(crypto::SymmetricKey::Import(
572 crypto::SymmetricKey::AES
, secret_
));
573 if (!decryption_key_
)