1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
|
/*
* Copyright (C) 2017 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "InitDataRegistry.h"
#if ENABLE(ENCRYPTED_MEDIA)
#include "ISOProtectionSystemSpecificHeaderBox.h"
#include <JavaScriptCore/DataView.h>
#include "NotImplemented.h"
#include "SharedBuffer.h"
#include <wtf/JSONValues.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/text/Base64.h>
#if USE(GSTREAMER)
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <wtf/Scope.h>
#endif
#if HAVE(FAIRPLAYSTREAMING_CENC_INITDATA)
#include "CDMFairPlayStreaming.h"
#include "ISOFairPlayStreamingPsshBox.h"
#endif
namespace WebCore {
namespace {
const uint32_t kCencMaxBoxSize = 64 * KB;
// ContentEncKeyID has this EBML code [47][E2] in WebM,
// as per spec the size of the ContentEncKeyID is encoded on 16 bits.
// https://matroska.org/technical/specs/index.html#ContentEncKeyID/
const uint32_t kWebMMaxContentEncKeyIDSize = 64 * KB; // 2^16
const uint32_t kKeyIdsMinKeyIdSizeInBytes = 1;
const uint32_t kKeyIdsMaxKeyIdSizeInBytes = 512;
}
static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsKeyids(const SharedBuffer& buffer)
{
// 1. Format
// https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
if (buffer.size() > std::numeric_limits<unsigned>::max())
return std::nullopt;
String json { buffer.data(), static_cast<unsigned>(buffer.size()) };
auto value = JSON::Value::parseJSON(json);
if (!value)
return std::nullopt;
auto object = value->asObject();
if (!object)
return std::nullopt;
auto kidsArray = object->getArray("kids"_s);
if (!kidsArray)
return std::nullopt;
Vector<Ref<SharedBuffer>> keyIDs;
for (auto& value : *kidsArray) {
auto keyID = value->asString();
if (!keyID)
continue;
auto keyIDData = base64URLDecode(keyID);
if (!keyIDData)
continue;
if (keyIDData->size() < kKeyIdsMinKeyIdSizeInBytes || keyIDData->size() > kKeyIdsMaxKeyIdSizeInBytes)
return std::nullopt;
keyIDs.append(SharedBuffer::create(WTFMove(*keyIDData)));
}
return keyIDs;
}
static RefPtr<SharedBuffer> sanitizeKeyids(const SharedBuffer& buffer)
{
// 1. Format
// https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
auto keyIDBuffer = extractKeyIDsKeyids(buffer);
if (!keyIDBuffer)
return nullptr;
auto object = JSON::Object::create();
auto kidsArray = JSON::Array::create();
for (auto& buffer : keyIDBuffer.value())
kidsArray->pushString(base64URLEncodeToString(buffer->data(), buffer->size()));
object->setArray("kids"_s, WTFMove(kidsArray));
CString jsonData = object->toJSONString().utf8();
return SharedBuffer::create(jsonData.data(), jsonData.length());
}
std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> InitDataRegistry::extractPsshBoxesFromCenc(const SharedBuffer& buffer)
{
// 4. Common SystemID and PSSH Box Format
// https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
if (buffer.size() >= kCencMaxBoxSize)
return std::nullopt;
unsigned offset = 0;
Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>> psshBoxes;
auto view = JSC::DataView::create(buffer.tryCreateArrayBuffer(), offset, buffer.size());
while (auto optionalBoxType = ISOBox::peekBox(view, offset)) {
auto& boxTypeName = optionalBoxType.value().first;
auto& boxSize = optionalBoxType.value().second;
if (boxTypeName != ISOProtectionSystemSpecificHeaderBox::boxTypeName() || boxSize > buffer.size())
return std::nullopt;
auto systemID = ISOProtectionSystemSpecificHeaderBox::peekSystemID(view, offset);
#if HAVE(FAIRPLAYSTREAMING_CENC_INITDATA)
if (systemID == ISOFairPlayStreamingPsshBox::fairPlaySystemID()) {
auto fpsPssh = makeUnique<ISOFairPlayStreamingPsshBox>();
if (!fpsPssh->read(view, offset))
return std::nullopt;
psshBoxes.append(WTFMove(fpsPssh));
continue;
}
#else
UNUSED_PARAM(systemID);
#endif
auto psshBox = makeUnique<ISOProtectionSystemSpecificHeaderBox>();
if (!psshBox->read(view, offset))
return std::nullopt;
psshBoxes.append(WTFMove(psshBox));
}
return psshBoxes;
}
std::optional<Vector<Ref<SharedBuffer>>> InitDataRegistry::extractKeyIDsCenc(const SharedBuffer& buffer)
{
Vector<Ref<SharedBuffer>> keyIDs;
auto psshBoxes = extractPsshBoxesFromCenc(buffer);
if (!psshBoxes)
return std::nullopt;
for (auto& psshBox : psshBoxes.value()) {
ASSERT(psshBox);
if (!psshBox)
return std::nullopt;
#if HAVE(FAIRPLAYSTREAMING_CENC_INITDATA)
if (is<ISOFairPlayStreamingPsshBox>(*psshBox)) {
ISOFairPlayStreamingPsshBox& fpsPssh = downcast<ISOFairPlayStreamingPsshBox>(*psshBox);
FourCC scheme = fpsPssh.initDataBox().info().scheme();
if (CDMPrivateFairPlayStreaming::validFairPlayStreamingSchemes().contains(scheme)) {
for (const auto& request : fpsPssh.initDataBox().requests()) {
auto& keyID = request.requestInfo().keyID();
keyIDs.append(SharedBuffer::create(keyID.data(), keyID.size()));
}
}
}
#endif
for (auto& value : psshBox->keyIDs())
keyIDs.append(SharedBuffer::create(WTFMove(value)));
}
return keyIDs;
}
#if USE(GSTREAMER)
bool isPlayReadySanitizedInitializationData(const SharedBuffer& buffer)
{
const char* protectionData = buffer.dataAsCharPtr();
size_t protectionDataLength = buffer.size();
// The protection data starts with a 10-byte PlayReady version
// header that needs to be skipped over to avoid XML parsing
// errors.
char* startTag = const_cast<char*>(protectionData);
while (startTag && *startTag != '<')
startTag++;
if (!startTag)
return false;
size_t protectionDataXMLLength = protectionDataLength - (startTag - protectionData);
xmlDocPtr protectionDataXML = xmlReadMemory(static_cast<const char*>(startTag), protectionDataXMLLength, "protectionData", "utf-16", 0);
if (!protectionDataXML)
return false;
xmlXPathContextPtr xpathContext = nullptr;
xmlXPathObjectPtr xpathObject = nullptr;
auto exitFunction = makeScopeExit([&] {
if (xpathContext)
xmlXPathFreeContext(xpathContext);
if (xpathObject)
xmlXPathFreeObject(xpathObject);
xmlFreeDoc(protectionDataXML);
});
xmlNode* protectionDataRootElement = xmlDocGetRootElement(protectionDataXML);
if (!protectionDataRootElement || protectionDataRootElement->type != XML_ELEMENT_NODE
|| xmlStrcmp(protectionDataRootElement->name, reinterpret_cast<const xmlChar*>("WRMHEADER"))
|| !protectionDataRootElement->ns)
return false;
xpathContext = xmlXPathNewContext(protectionDataXML);
if (!xpathContext)
return false;
const xmlChar* protectionDataNamespace = protectionDataRootElement->ns->href;
if (xmlXPathRegisterNs(xpathContext, reinterpret_cast<const xmlChar*>("prhdr"), protectionDataNamespace) < 0)
return false;
xpathObject = xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>("//prhdr:KID"), xpathContext);
if (!xpathObject)
return false;
xmlNodeSetPtr keyIDNode = xpathObject->nodesetval;
int numberOfKeyIDs = keyIDNode ? keyIDNode->nodeNr : 0;
if (!numberOfKeyIDs || keyIDNode->nodeTab[0]->type != XML_ELEMENT_NODE)
return false;
xmlChar* encodedKeyID = xmlNodeGetContent(keyIDNode->nodeTab[0]);
std::optional<Vector<uint8_t>> decodedKeyID = base64Decode(encodedKeyID, xmlStrlen(encodedKeyID));
xmlFree(encodedKeyID);
if (!decodedKeyID)
return false;
return true;
}
#endif
RefPtr<SharedBuffer> InitDataRegistry::sanitizeCenc(const SharedBuffer& buffer)
{
// 4. Common SystemID and PSSH Box Format
// https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
if (!extractKeyIDsCenc(buffer)) {
#if USE(GSTREAMER)
if (!isPlayReadySanitizedInitializationData(buffer))
#endif
return nullptr;
}
return buffer.makeContiguous();
}
static RefPtr<SharedBuffer> sanitizeWebM(const SharedBuffer& buffer)
{
// Check if the buffer is a valid WebM initData.
// The WebM initData is the ContentEncKeyID, so should be less than kWebMMaxContentEncKeyIDSize.
if (buffer.isEmpty() || buffer.size() > kWebMMaxContentEncKeyIDSize)
return nullptr;
return buffer.makeContiguous();
}
static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsWebM(const SharedBuffer& buffer)
{
Vector<Ref<SharedBuffer>> keyIDs;
RefPtr<SharedBuffer> sanitizedBuffer = sanitizeWebM(buffer);
if (!sanitizedBuffer)
return std::nullopt;
// 1. Format
// https://w3c.github.io/encrypted-media/format-registry/initdata/webm.html#format
keyIDs.append(sanitizedBuffer.releaseNonNull());
return keyIDs;
}
InitDataRegistry& InitDataRegistry::shared()
{
static NeverDestroyed<InitDataRegistry> registry;
return registry.get();
}
InitDataRegistry::InitDataRegistry()
{
registerInitDataType("keyids"_s, { sanitizeKeyids, extractKeyIDsKeyids });
registerInitDataType("cenc"_s, { sanitizeCenc, extractKeyIDsCenc });
registerInitDataType("webm"_s, { sanitizeWebM, extractKeyIDsWebM });
}
InitDataRegistry::~InitDataRegistry() = default;
RefPtr<SharedBuffer> InitDataRegistry::sanitizeInitData(const AtomString& initDataType, const SharedBuffer& buffer)
{
auto iter = m_types.find(initDataType);
if (iter == m_types.end() || !iter->value.sanitizeInitData)
return nullptr;
return iter->value.sanitizeInitData(buffer);
}
std::optional<Vector<Ref<SharedBuffer>>> InitDataRegistry::extractKeyIDs(const AtomString& initDataType, const SharedBuffer& buffer)
{
auto iter = m_types.find(initDataType);
if (iter == m_types.end() || !iter->value.sanitizeInitData)
return std::nullopt;
return iter->value.extractKeyIDs(buffer);
}
void InitDataRegistry::registerInitDataType(const AtomString& initDataType, InitDataTypeCallbacks&& callbacks)
{
ASSERT(!m_types.contains(initDataType));
m_types.set(initDataType, WTFMove(callbacks));
}
const AtomString& InitDataRegistry::cencName()
{
static MainThreadNeverDestroyed<const AtomString> sinf { MAKE_STATIC_STRING_IMPL("cenc") };
return sinf;
}
const AtomString& InitDataRegistry::keyidsName()
{
static MainThreadNeverDestroyed<const AtomString> sinf { MAKE_STATIC_STRING_IMPL("keyids") };
return sinf;
}
const AtomString& InitDataRegistry::webmName()
{
static MainThreadNeverDestroyed<const AtomString> sinf { MAKE_STATIC_STRING_IMPL("webm") };
return sinf;
}
}
#endif // ENABLE(ENCRYPTED_MEDIA)
|