Debian Codegraph @

src/decrypters/clearkey/ClearKeyCencSingleSampleDecrypter.cpp

raw
1 /*
2 * Copyright (C) 2024 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "ClearKeyCencSingleSampleDecrypter.h"
10
11 #include "ClearKeyDecrypter.h"
12 #include "CompSettings.h"
13 #include "SrvBroker.h"
14 #include "utils/Base64Utils.h"
15 #include "utils/CurlUtils.h"
16 #include "utils/FileUtils.h"
17 #include "utils/StringUtils.h"
18 #include "utils/log.h"
19
20 #include <algorithm>
21
22 #include <rapidjson/document.h>
23 #include <rapidjson/stringbuffer.h>
24 #include <rapidjson/writer.h>
25
26 using namespace UTILS;
27
28 namespace
29 {
30 void CkB64Encode(std::string& str)
31 {
32 STRING::ReplaceAll(str, "+", "-");
33 STRING::ReplaceAll(str, "/", "_");
34 }
35
36 void CkB64Decode(std::string& str)
37 {
38 STRING::ReplaceAll(str, "-", "+");
39 STRING::ReplaceAll(str, "_", "/");
40 }
41 }
42
43 CClearKeyCencSingleSampleDecrypter::CClearKeyCencSingleSampleDecrypter(
44 std::string_view licenseUrl,
45 const std::map<std::string, std::string>& licenseHeaders,
46 const std::vector<uint8_t>& defaultKeyId,
47 CClearKeyDecrypter* host)
48 : m_host(host)
49 {
50 if (licenseUrl.empty())
51 {
52 LOG::LogF(LOGERROR, "License server URL not found");
53 return;
54 }
55
56 const std::string postData = CreateLicenseRequest(defaultKeyId);
57
58 if (CSrvBroker::GetSettings().IsDebugLicense())
59 {
60 const std::string debugFilePath =
61 FILESYS::PathCombine(m_host->GetLibraryPath(), "ClearKey.init");
62 FILESYS::SaveFile(debugFilePath, postData.c_str(), true);
63 }
64
65 CURL::CUrl curl{licenseUrl, postData};
66 curl.AddHeader("Accept", "application/json");
67 curl.AddHeader("Content-Type", "application/json");
68 curl.AddHeaders(licenseHeaders);
69
70 std::string response;
71 int statusCode = curl.Open();
72 if (statusCode == -1 || statusCode >= 400)
73 {
74 LOG::Log(LOGERROR, "License server returned failure (HTTP error %i)", statusCode);
75 return;
76 }
77
78 if (curl.Read(response) != CURL::ReadStatus::IS_EOF)
79 {
80 LOG::LogF(LOGERROR, "Could not read the license server response");
81 return;
82 }
83
84 if (CSrvBroker::GetSettings().IsDebugLicense())
85 {
86 const std::string debugFilePath =
87 FILESYS::PathCombine(m_host->GetLibraryPath(), "ClearKey.response");
88 FILESYS::SaveFile(debugFilePath, response, true);
89 }
90
91 if (!ParseLicenseResponse(response))
92 {
93 LOG::LogF(LOGERROR, "Could not parse the license server response");
94 return;
95 }
96
97 const std::string b64DefaultKeyId = BASE64::Encode(defaultKeyId);
98 if (!STRING::KeyExists(m_keyPairs, b64DefaultKeyId))
99 {
100 LOG::LogF(LOGERROR, "Key not found on license server response");
101 return;
102 }
103
104 const std::vector<uint8_t> keyBytes = BASE64::Decode(m_keyPairs[b64DefaultKeyId]);
105 if (AP4_FAILED(AP4_CencSingleSampleDecrypter::Create(AP4_CENC_CIPHER_AES_128_CTR, keyBytes.data(),
106 static_cast<AP4_Size>(keyBytes.size()), 0, 0,
107 nullptr, false, m_singleSampleDecrypter)))
108 {
109 LOG::LogF(LOGERROR, "Failed to create AP4_CencSingleSampleDecrypter");
110 }
111 SetParentIsOwner(false);
112 AddSessionKey(defaultKeyId);
113 }
114
115 CClearKeyCencSingleSampleDecrypter::CClearKeyCencSingleSampleDecrypter(
116 const std::vector<uint8_t>& initData,
117 const std::vector<uint8_t>& defaultKeyId,
118 const std::map<std::string, std::string>& keys,
119 CClearKeyDecrypter* host)
120 : m_host(host)
121 {
122 std::vector<uint8_t> hexKey;
123
124 if (keys.empty()) // Assume key is provided from the manifest
125 {
126 hexKey = initData;
127 }
128 else // Key provided in Kodi props
129 {
130 const std::string hexDefKid = STRING::ToHexadecimal(defaultKeyId);
131
132 if (STRING::KeyExists(keys, hexDefKid))
133 STRING::ToHexBytes(keys.at(hexDefKid), hexKey);
134 else
135 LOG::LogF(LOGERROR, "Missing KeyId \"%s\" on DRM configuration", defaultKeyId.data());
136 }
137
138 AP4_CencSingleSampleDecrypter::Create(AP4_CENC_CIPHER_AES_128_CTR, hexKey.data(),
139 static_cast<AP4_Size>(hexKey.size()), 0, 0, nullptr, false,
140 m_singleSampleDecrypter);
141 SetParentIsOwner(false);
142 AddSessionKey(defaultKeyId);
143 }
144
145 void CClearKeyCencSingleSampleDecrypter::AddSessionKey(const std::vector<uint8_t>& keyId)
146 {
147 if (std::find(m_keyIds.begin(), m_keyIds.end(), keyId) == m_keyIds.end())
148 m_keyIds.emplace_back(keyId);
149 }
150
151 bool CClearKeyCencSingleSampleDecrypter::HasKeyId(const std::vector<uint8_t>& keyid)
152 {
153 if (!keyid.empty())
154 {
155 for (const std::vector<uint8_t>& key : m_keyIds)
156 {
157 if (key == keyid)
158 return true;
159 }
160 }
161 return false;
162 }
163
164 AP4_Result CClearKeyCencSingleSampleDecrypter::DecryptSampleData(
165 AP4_UI32 pool_id,
166 AP4_DataBuffer& data_in,
167 AP4_DataBuffer& data_out,
168 const AP4_UI08* iv,
169 unsigned int subsample_count,
170 const AP4_UI16* bytes_of_cleartext_data,
171 const AP4_UI32* bytes_of_encrypted_data)
172 {
173 if (!m_singleSampleDecrypter)
174 {
175 return AP4_FAILURE;
176 }
177 return (m_singleSampleDecrypter)
178 ->DecryptSampleData(data_in, data_out, iv, subsample_count, bytes_of_cleartext_data,
179 bytes_of_encrypted_data);
180 }
181
182 std::string CClearKeyCencSingleSampleDecrypter::CreateLicenseRequest(
183 const std::vector<uint8_t>& defaultKeyId)
184 {
185 // github.com/Dash-Industry-Forum/ClearKey-Content-Protection/blob/master/README.md
186 /* Expected JSON structure for license request:
187 * { "kids":
188 * [
189 * "nrQFDeRLSAKTLifXUIPiZg"
190 * ]
191 * "type":"temporary" }
192 */
193
194 std::string b64Kid = BASE64::Encode(defaultKeyId, false);
195 CkB64Encode(b64Kid);
196
197 rapidjson::Document jDoc;
198 jDoc.SetObject();
199 auto& allocator = jDoc.GetAllocator();
200
201 rapidjson::Value kids{rapidjson::kArrayType};
202 rapidjson::Value jKid;
203
204 jKid.SetString(b64Kid.c_str(), allocator);
205 kids.PushBack(jKid, allocator);
206
207 jDoc.AddMember("kids", kids, allocator);
208 jDoc.AddMember("type", "temporary", allocator);
209
210 rapidjson::StringBuffer buffer;
211 rapidjson::Writer<rapidjson::StringBuffer> writer{buffer};
212 jDoc.Accept(writer);
213 return buffer.GetString();
214 }
215
216 bool CClearKeyCencSingleSampleDecrypter::ParseLicenseResponse(std::string data)
217 {
218 /* Expected JSON structure for license response:
219 * { "keys": [
220 * {
221 * "k": "FmY0xnWCPCNaSpRG-tUuTQ",
222 * "kid": "nrQFDeRLSAKTLifXUIPiZg",
223 * "kty": "oct"
224 * }
225 * "type": "temporary"}
226 */
227
228 rapidjson::Document jDoc;
229 jDoc.Parse(data.c_str(), data.size());
230
231 if (!jDoc.IsObject())
232 {
233 LOG::LogF(LOGERROR, "Malformed JSON data in license response");
234 return false;
235 }
236
237 for (auto& jChildObj : jDoc.GetObject())
238 {
239 std::string b64Key;
240 std::string b64KeyId;
241 const std::string keyName = jChildObj.name.GetString();
242 rapidjson::Value& jDictVal = jChildObj.value;
243
244 if (keyName == "Message" && jDictVal.IsString())
245 {
246 LOG::LogF(LOGERROR, "Error in license response: %s", jDictVal.GetString());
247 return false;
248 }
249
250 if (!jDoc.HasMember("keys"))
251 {
252 LOG::LogF(LOGERROR, "No keys in license response");
253 return false;
254 }
255
256 if (keyName == "keys" && jDictVal.IsArray())
257 {
258 // NOTE: for now we assume that one key only is requested and one only will come in the license response
259 for (auto const& jArrayKey : jDictVal.GetArray())
260 {
261 if (jArrayKey.IsObject())
262 {
263 if (jArrayKey.HasMember("k") && jArrayKey["k"].IsString())
264 b64Key = jArrayKey["k"].GetString();
265
266 if (jArrayKey.HasMember("kid") && jArrayKey["kid"].IsString())
267 b64KeyId = jArrayKey["kid"].GetString();
268 }
269
270 if (!b64Key.empty() && !b64KeyId.empty())
271 {
272 CkB64Decode(b64Key);
273 BASE64::AddPadding(b64Key);
274
275 CkB64Decode(b64KeyId);
276 BASE64::AddPadding(b64KeyId);
277
278 m_keyPairs.emplace(b64KeyId, b64Key);
279 break;
280 }
281 }
282 }
283 }
284 return true;
285 }