aes_decryptor.cc revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
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 <list> 8#include <vector> 9 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/decoder_buffer.h" 17#include "media/base/decrypt_config.h" 18#include "media/base/video_decoder_config.h" 19#include "media/base/video_frame.h" 20#include "media/cdm/json_web_key.h" 21 22namespace media { 23 24// Keeps track of the session IDs and DecryptionKeys. The keys are ordered by 25// insertion time (last insertion is first). It takes ownership of the 26// DecryptionKeys. 27class AesDecryptor::SessionIdDecryptionKeyMap { 28 // Use a std::list to actually hold the data. Insertion is always done 29 // at the front, so the "latest" decryption key is always the first one 30 // in the list. 31 typedef std::list<std::pair<uint32, DecryptionKey*> > KeyList; 32 33 public: 34 SessionIdDecryptionKeyMap() {} 35 ~SessionIdDecryptionKeyMap() { STLDeleteValues(&key_list_); } 36 37 // Replaces value if |session_id| is already present, or adds it if not. 38 // This |decryption_key| becomes the latest until another insertion or 39 // |session_id| is erased. 40 void Insert(uint32 session_id, scoped_ptr<DecryptionKey> decryption_key); 41 42 // Deletes the entry for |session_id| if present. 43 void Erase(const uint32 session_id); 44 45 // Returns whether the list is empty 46 bool Empty() const { return key_list_.empty(); } 47 48 // Returns the last inserted DecryptionKey. 49 DecryptionKey* LatestDecryptionKey() { 50 DCHECK(!key_list_.empty()); 51 return key_list_.begin()->second; 52 } 53 54 private: 55 // Searches the list for an element with |session_id|. 56 KeyList::iterator Find(const uint32 session_id); 57 58 // Deletes the entry pointed to by |position|. 59 void Erase(KeyList::iterator position); 60 61 KeyList key_list_; 62 63 DISALLOW_COPY_AND_ASSIGN(SessionIdDecryptionKeyMap); 64}; 65 66void AesDecryptor::SessionIdDecryptionKeyMap::Insert( 67 uint32 session_id, 68 scoped_ptr<DecryptionKey> decryption_key) { 69 KeyList::iterator it = Find(session_id); 70 if (it != key_list_.end()) 71 Erase(it); 72 DecryptionKey* raw_ptr = decryption_key.release(); 73 key_list_.push_front(std::make_pair(session_id, raw_ptr)); 74} 75 76void AesDecryptor::SessionIdDecryptionKeyMap::Erase(const uint32 session_id) { 77 KeyList::iterator it = Find(session_id); 78 if (it == key_list_.end()) 79 return; 80 Erase(it); 81} 82 83AesDecryptor::SessionIdDecryptionKeyMap::KeyList::iterator 84AesDecryptor::SessionIdDecryptionKeyMap::Find(const uint32 session_id) { 85 for (KeyList::iterator it = key_list_.begin(); it != key_list_.end(); ++it) { 86 if (it->first == session_id) 87 return it; 88 } 89 return key_list_.end(); 90} 91 92void AesDecryptor::SessionIdDecryptionKeyMap::Erase( 93 KeyList::iterator position) { 94 DCHECK(position->second); 95 delete position->second; 96 key_list_.erase(position); 97} 98 99uint32 AesDecryptor::next_web_session_id_ = 1; 100 101enum ClearBytesBufferSel { 102 kSrcContainsClearBytes, 103 kDstContainsClearBytes 104}; 105 106static void CopySubsamples(const std::vector<SubsampleEntry>& subsamples, 107 const ClearBytesBufferSel sel, 108 const uint8* src, 109 uint8* dst) { 110 for (size_t i = 0; i < subsamples.size(); i++) { 111 const SubsampleEntry& subsample = subsamples[i]; 112 if (sel == kSrcContainsClearBytes) { 113 src += subsample.clear_bytes; 114 } else { 115 dst += subsample.clear_bytes; 116 } 117 memcpy(dst, src, subsample.cypher_bytes); 118 src += subsample.cypher_bytes; 119 dst += subsample.cypher_bytes; 120 } 121} 122 123// Decrypts |input| using |key|. Returns a DecoderBuffer with the decrypted 124// data if decryption succeeded or NULL if decryption failed. 125static scoped_refptr<DecoderBuffer> DecryptData(const DecoderBuffer& input, 126 crypto::SymmetricKey* key) { 127 CHECK(input.data_size()); 128 CHECK(input.decrypt_config()); 129 CHECK(key); 130 131 crypto::Encryptor encryptor; 132 if (!encryptor.Init(key, crypto::Encryptor::CTR, "")) { 133 DVLOG(1) << "Could not initialize decryptor."; 134 return NULL; 135 } 136 137 DCHECK_EQ(input.decrypt_config()->iv().size(), 138 static_cast<size_t>(DecryptConfig::kDecryptionKeySize)); 139 if (!encryptor.SetCounter(input.decrypt_config()->iv())) { 140 DVLOG(1) << "Could not set counter block."; 141 return NULL; 142 } 143 144 const int data_offset = input.decrypt_config()->data_offset(); 145 const char* sample = 146 reinterpret_cast<const char*>(input.data() + data_offset); 147 DCHECK_GT(input.data_size(), data_offset); 148 size_t sample_size = static_cast<size_t>(input.data_size() - data_offset); 149 150 DCHECK_GT(sample_size, 0U) << "No sample data to be decrypted."; 151 if (sample_size == 0) 152 return NULL; 153 154 if (input.decrypt_config()->subsamples().empty()) { 155 std::string decrypted_text; 156 base::StringPiece encrypted_text(sample, sample_size); 157 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) { 158 DVLOG(1) << "Could not decrypt data."; 159 return NULL; 160 } 161 162 // TODO(xhwang): Find a way to avoid this data copy. 163 return DecoderBuffer::CopyFrom( 164 reinterpret_cast<const uint8*>(decrypted_text.data()), 165 decrypted_text.size()); 166 } 167 168 const std::vector<SubsampleEntry>& subsamples = 169 input.decrypt_config()->subsamples(); 170 171 size_t total_clear_size = 0; 172 size_t total_encrypted_size = 0; 173 for (size_t i = 0; i < subsamples.size(); i++) { 174 total_clear_size += subsamples[i].clear_bytes; 175 total_encrypted_size += subsamples[i].cypher_bytes; 176 // Check for overflow. This check is valid because *_size is unsigned. 177 DCHECK(total_clear_size >= subsamples[i].clear_bytes); 178 if (total_encrypted_size < subsamples[i].cypher_bytes) 179 return NULL; 180 } 181 size_t total_size = total_clear_size + total_encrypted_size; 182 if (total_size < total_clear_size || total_size != sample_size) { 183 DVLOG(1) << "Subsample sizes do not equal input size"; 184 return NULL; 185 } 186 187 // No need to decrypt if there is no encrypted data. 188 if (total_encrypted_size <= 0) { 189 return DecoderBuffer::CopyFrom(reinterpret_cast<const uint8*>(sample), 190 sample_size); 191 } 192 193 // The encrypted portions of all subsamples must form a contiguous block, 194 // such that an encrypted subsample that ends away from a block boundary is 195 // immediately followed by the start of the next encrypted subsample. We 196 // copy all encrypted subsamples to a contiguous buffer, decrypt them, then 197 // copy the decrypted bytes over the encrypted bytes in the output. 198 // TODO(strobe): attempt to reduce number of memory copies 199 scoped_ptr<uint8[]> encrypted_bytes(new uint8[total_encrypted_size]); 200 CopySubsamples(subsamples, kSrcContainsClearBytes, 201 reinterpret_cast<const uint8*>(sample), encrypted_bytes.get()); 202 203 base::StringPiece encrypted_text( 204 reinterpret_cast<const char*>(encrypted_bytes.get()), 205 total_encrypted_size); 206 std::string decrypted_text; 207 if (!encryptor.Decrypt(encrypted_text, &decrypted_text)) { 208 DVLOG(1) << "Could not decrypt data."; 209 return NULL; 210 } 211 DCHECK_EQ(decrypted_text.size(), encrypted_text.size()); 212 213 scoped_refptr<DecoderBuffer> output = DecoderBuffer::CopyFrom( 214 reinterpret_cast<const uint8*>(sample), sample_size); 215 CopySubsamples(subsamples, kDstContainsClearBytes, 216 reinterpret_cast<const uint8*>(decrypted_text.data()), 217 output->writable_data()); 218 return output; 219} 220 221AesDecryptor::AesDecryptor(const SessionCreatedCB& session_created_cb, 222 const SessionMessageCB& session_message_cb, 223 const SessionReadyCB& session_ready_cb, 224 const SessionClosedCB& session_closed_cb, 225 const SessionErrorCB& session_error_cb) 226 : session_created_cb_(session_created_cb), 227 session_message_cb_(session_message_cb), 228 session_ready_cb_(session_ready_cb), 229 session_closed_cb_(session_closed_cb), 230 session_error_cb_(session_error_cb) {} 231 232AesDecryptor::~AesDecryptor() { 233 key_map_.clear(); 234} 235 236bool AesDecryptor::CreateSession(uint32 session_id, 237 const std::string& type, 238 const uint8* init_data, 239 int init_data_length) { 240 std::string web_session_id_string(base::UintToString(next_web_session_id_++)); 241 242 // For now, the AesDecryptor does not care about |type|; 243 // just fire the event with the |init_data| as the request. 244 std::vector<uint8> message; 245 if (init_data && init_data_length) 246 message.assign(init_data, init_data + init_data_length); 247 248 session_created_cb_.Run(session_id, web_session_id_string); 249 session_message_cb_.Run(session_id, message, std::string()); 250 return true; 251} 252 253void AesDecryptor::UpdateSession(uint32 session_id, 254 const uint8* response, 255 int response_length) { 256 CHECK(response); 257 CHECK_GT(response_length, 0); 258 // TODO(jrummell): Verify that the session for |session_id| exists. 259 260 std::string key_string(reinterpret_cast<const char*>(response), 261 response_length); 262 KeyIdAndKeyPairs keys; 263 if (!ExtractKeysFromJWKSet(key_string, &keys)) { 264 session_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0); 265 return; 266 } 267 268 // Make sure that at least one key was extracted. 269 if (keys.empty()) { 270 session_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0); 271 return; 272 } 273 274 for (KeyIdAndKeyPairs::iterator it = keys.begin(); it != keys.end(); ++it) { 275 if (it->second.length() != 276 static_cast<size_t>(DecryptConfig::kDecryptionKeySize)) { 277 DVLOG(1) << "Invalid key length: " << key_string.length(); 278 session_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0); 279 return; 280 } 281 if (!AddDecryptionKey(session_id, it->first, it->second)) { 282 session_error_cb_.Run(session_id, MediaKeys::kUnknownError, 0); 283 return; 284 } 285 } 286 287 if (!new_audio_key_cb_.is_null()) 288 new_audio_key_cb_.Run(); 289 290 if (!new_video_key_cb_.is_null()) 291 new_video_key_cb_.Run(); 292 293 session_ready_cb_.Run(session_id); 294} 295 296void AesDecryptor::ReleaseSession(uint32 session_id) { 297 DeleteKeysForSession(session_id); 298 session_closed_cb_.Run(session_id); 299} 300 301Decryptor* AesDecryptor::GetDecryptor() { 302 return this; 303} 304 305void AesDecryptor::RegisterNewKeyCB(StreamType stream_type, 306 const NewKeyCB& new_key_cb) { 307 switch (stream_type) { 308 case kAudio: 309 new_audio_key_cb_ = new_key_cb; 310 break; 311 case kVideo: 312 new_video_key_cb_ = new_key_cb; 313 break; 314 default: 315 NOTREACHED(); 316 } 317} 318 319void AesDecryptor::Decrypt(StreamType stream_type, 320 const scoped_refptr<DecoderBuffer>& encrypted, 321 const DecryptCB& decrypt_cb) { 322 CHECK(encrypted->decrypt_config()); 323 324 scoped_refptr<DecoderBuffer> decrypted; 325 // An empty iv string signals that the frame is unencrypted. 326 if (encrypted->decrypt_config()->iv().empty()) { 327 int data_offset = encrypted->decrypt_config()->data_offset(); 328 decrypted = DecoderBuffer::CopyFrom(encrypted->data() + data_offset, 329 encrypted->data_size() - data_offset); 330 } else { 331 const std::string& key_id = encrypted->decrypt_config()->key_id(); 332 DecryptionKey* key = GetKey(key_id); 333 if (!key) { 334 DVLOG(1) << "Could not find a matching key for the given key ID."; 335 decrypt_cb.Run(kNoKey, NULL); 336 return; 337 } 338 339 crypto::SymmetricKey* decryption_key = key->decryption_key(); 340 decrypted = DecryptData(*encrypted.get(), decryption_key); 341 if (!decrypted.get()) { 342 DVLOG(1) << "Decryption failed."; 343 decrypt_cb.Run(kError, NULL); 344 return; 345 } 346 } 347 348 decrypted->set_timestamp(encrypted->timestamp()); 349 decrypted->set_duration(encrypted->duration()); 350 decrypt_cb.Run(kSuccess, decrypted); 351} 352 353void AesDecryptor::CancelDecrypt(StreamType stream_type) { 354 // Decrypt() calls the DecryptCB synchronously so there's nothing to cancel. 355} 356 357void AesDecryptor::InitializeAudioDecoder(const AudioDecoderConfig& config, 358 const DecoderInitCB& init_cb) { 359 // AesDecryptor does not support audio decoding. 360 init_cb.Run(false); 361} 362 363void AesDecryptor::InitializeVideoDecoder(const VideoDecoderConfig& config, 364 const DecoderInitCB& init_cb) { 365 // AesDecryptor does not support video decoding. 366 init_cb.Run(false); 367} 368 369void AesDecryptor::DecryptAndDecodeAudio( 370 const scoped_refptr<DecoderBuffer>& encrypted, 371 const AudioDecodeCB& audio_decode_cb) { 372 NOTREACHED() << "AesDecryptor does not support audio decoding"; 373} 374 375void AesDecryptor::DecryptAndDecodeVideo( 376 const scoped_refptr<DecoderBuffer>& encrypted, 377 const VideoDecodeCB& video_decode_cb) { 378 NOTREACHED() << "AesDecryptor does not support video decoding"; 379} 380 381void AesDecryptor::ResetDecoder(StreamType stream_type) { 382 NOTREACHED() << "AesDecryptor does not support audio/video decoding"; 383} 384 385void AesDecryptor::DeinitializeDecoder(StreamType stream_type) { 386 NOTREACHED() << "AesDecryptor does not support audio/video decoding"; 387} 388 389bool AesDecryptor::AddDecryptionKey(const uint32 session_id, 390 const std::string& key_id, 391 const std::string& key_string) { 392 scoped_ptr<DecryptionKey> decryption_key(new DecryptionKey(key_string)); 393 if (!decryption_key) { 394 DVLOG(1) << "Could not create key."; 395 return false; 396 } 397 398 if (!decryption_key->Init()) { 399 DVLOG(1) << "Could not initialize decryption key."; 400 return false; 401 } 402 403 base::AutoLock auto_lock(key_map_lock_); 404 KeyIdToSessionKeysMap::iterator key_id_entry = key_map_.find(key_id); 405 if (key_id_entry != key_map_.end()) { 406 key_id_entry->second->Insert(session_id, decryption_key.Pass()); 407 return true; 408 } 409 410 // |key_id| not found, so need to create new entry. 411 scoped_ptr<SessionIdDecryptionKeyMap> inner_map( 412 new SessionIdDecryptionKeyMap()); 413 inner_map->Insert(session_id, decryption_key.Pass()); 414 key_map_.add(key_id, inner_map.Pass()); 415 return true; 416} 417 418AesDecryptor::DecryptionKey* AesDecryptor::GetKey( 419 const std::string& key_id) const { 420 base::AutoLock auto_lock(key_map_lock_); 421 KeyIdToSessionKeysMap::const_iterator key_id_found = key_map_.find(key_id); 422 if (key_id_found == key_map_.end()) 423 return NULL; 424 425 // Return the key from the "latest" session_id entry. 426 return key_id_found->second->LatestDecryptionKey(); 427} 428 429void AesDecryptor::DeleteKeysForSession(const uint32 session_id) { 430 base::AutoLock auto_lock(key_map_lock_); 431 432 // Remove all keys associated with |session_id|. Since the data is optimized 433 // for access in GetKey(), we need to look at each entry in |key_map_|. 434 KeyIdToSessionKeysMap::iterator it = key_map_.begin(); 435 while (it != key_map_.end()) { 436 it->second->Erase(session_id); 437 if (it->second->Empty()) { 438 // Need to get rid of the entry for this key_id. This will mess up the 439 // iterator, so we need to increment it first. 440 KeyIdToSessionKeysMap::iterator current = it; 441 ++it; 442 key_map_.erase(current); 443 } else { 444 ++it; 445 } 446 } 447} 448 449AesDecryptor::DecryptionKey::DecryptionKey(const std::string& secret) 450 : secret_(secret) { 451} 452 453AesDecryptor::DecryptionKey::~DecryptionKey() {} 454 455bool AesDecryptor::DecryptionKey::Init() { 456 CHECK(!secret_.empty()); 457 decryption_key_.reset(crypto::SymmetricKey::Import( 458 crypto::SymmetricKey::AES, secret_)); 459 if (!decryption_key_) 460 return false; 461 return true; 462} 463 464} // namespace media 465