blob: 642264f523b75512dde85276b2b119d84222b7e9 [file] [log] [blame]
Kyle Zhang6605add2022-01-13 17:51:23 +00001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "CryptoHalAidl"
19
20#include <aidlcommonsupport/NativeHandle.h>
21#include <android/binder_auto_utils.h>
22#include <android/binder_manager.h>
23#include <media/hardware/CryptoAPI.h>
24#include <media/stagefright/MediaErrors.h>
25#include <media/stagefright/foundation/ADebug.h>
26#include <media/stagefright/foundation/AString.h>
27#include <media/stagefright/foundation/hexdump.h>
28#include <mediadrm/CryptoHalAidl.h>
29#include <mediadrm/DrmUtils.h>
30
Kyle Zhang994023a2022-02-09 05:32:12 +000031using ::aidl::android::hardware::drm::CryptoSchemes;
Kyle Zhang6605add2022-01-13 17:51:23 +000032using DestinationBufferAidl = ::aidl::android::hardware::drm::DestinationBuffer;
33using ::aidl::android::hardware::drm::Mode;
34using ::aidl::android::hardware::drm::Pattern;
35using SharedBufferAidl = ::aidl::android::hardware::drm::SharedBuffer;
36using ::aidl::android::hardware::drm::Status;
37using ::aidl::android::hardware::drm::SubSample;
38using ::aidl::android::hardware::drm::Uuid;
Kyle Zhang994023a2022-02-09 05:32:12 +000039using ::aidl::android::hardware::drm::SecurityLevel;
40using NativeHandleAidlCommon = ::aidl::android::hardware::common::NativeHandle;
41using ::aidl::android::hardware::drm::DecryptArgs;
Kyle Zhang6605add2022-01-13 17:51:23 +000042
43using ::android::sp;
Kyle Zhang96af9572022-02-05 06:38:53 +000044using ::android::DrmUtils::statusAidlToStatusT;
Kyle Zhang6605add2022-01-13 17:51:23 +000045using ::android::hardware::hidl_array;
46using ::android::hardware::hidl_handle;
47using ::android::hardware::hidl_memory;
48using ::android::hardware::hidl_string;
49using ::android::hardware::hidl_vec;
50using ::android::hardware::HidlMemory;
51using ::android::hardware::Return;
52using ::android::hardware::Void;
53
54using ::aidl::android::hardware::drm::Uuid;
55// -------Hidl interface related-----------------
56// TODO: replace before removing hidl interface
57
58using BufferTypeHidl = ::android::hardware::drm::V1_0::BufferType;
59using SharedBufferHidl = ::android::hardware::drm::V1_0::SharedBuffer;
60using DestinationBufferHidl = ::android::hardware::drm::V1_0::DestinationBuffer;
61
62// -------Hidl interface related end-------------
63
64namespace android {
65
Kyle Zhang6605add2022-01-13 17:51:23 +000066template <typename Byte = uint8_t>
67static std::vector<Byte> toStdVec(const Vector<uint8_t>& vector) {
68 auto v = reinterpret_cast<const Byte*>(vector.array());
69 std::vector<Byte> vec(v, v + vector.size());
70 return vec;
71}
72
73// -------Hidl interface related-----------------
74// TODO: replace before removing hidl interface
75status_t CryptoHalAidl::checkSharedBuffer(const SharedBufferHidl& buffer) {
76 int32_t seqNum = static_cast<int32_t>(buffer.bufferId);
77 // memory must be in one of the heaps that have been set
78 if (mHeapSizes.indexOfKey(seqNum) < 0) {
79 return UNKNOWN_ERROR;
80 }
81
82 // memory must be within the address space of the heap
83 size_t heapSize = mHeapSizes.valueFor(seqNum);
84 if (heapSize < buffer.offset + buffer.size || SIZE_MAX - buffer.offset < buffer.size) {
85 android_errorWriteLog(0x534e4554, "76221123");
86 return UNKNOWN_ERROR;
87 }
88
89 return OK;
90}
91
92static SharedBufferAidl hidlSharedBufferToAidlSharedBuffer(const SharedBufferHidl& buffer) {
93 SharedBufferAidl aidlsb;
94 aidlsb.bufferId = buffer.bufferId;
95 aidlsb.offset = buffer.offset;
96 aidlsb.size = buffer.size;
97 return aidlsb;
98}
99
100static DestinationBufferAidl hidlDestinationBufferToAidlDestinationBuffer(
101 const DestinationBufferHidl& buffer) {
102 DestinationBufferAidl aidldb;
103 // skip negative convert check as count of enum elements are 2
Kyle Zhang994023a2022-02-09 05:32:12 +0000104 switch(buffer.type) {
105 case BufferTypeHidl::SHARED_MEMORY:
106 aidldb.set<DestinationBufferAidl::Tag::nonsecureMemory>(
107 hidlSharedBufferToAidlSharedBuffer(buffer.nonsecureMemory));
108 break;
109 default:
110 auto handle = buffer.secureMemory.getNativeHandle();
111 if (handle) {
112 aidldb.set<DestinationBufferAidl::Tag::secureMemory>(
Robert Shihfc5d61d2022-02-15 23:06:48 -0800113 ::android::dupToAidl(handle));
Kyle Zhang994023a2022-02-09 05:32:12 +0000114 } else {
115 NativeHandleAidlCommon emptyhandle;
116 aidldb.set<DestinationBufferAidl::Tag::secureMemory>(
117 std::move(emptyhandle));
118 }
119 break;
Robert Shihcc4a2ce2022-02-03 08:27:08 -0800120 }
Kyle Zhang994023a2022-02-09 05:32:12 +0000121
Kyle Zhang6605add2022-01-13 17:51:23 +0000122 return aidldb;
123}
124
125static hidl_vec<uint8_t> toHidlVec(const void* ptr, size_t size) {
126 hidl_vec<uint8_t> vec;
127 vec.resize(size);
128 memcpy(vec.data(), ptr, size);
129 return vec;
130}
131
132static const Vector<uint8_t> toVector(const std::vector<uint8_t>& vec) {
133 Vector<uint8_t> vector;
134 vector.appendArray(vec.data(), vec.size());
135 return *const_cast<const Vector<uint8_t>*>(&vector);
136}
137
138static String8 toString8(const std::string& string) {
139 return String8(string.c_str());
140}
141
Robert Shihcc4a2ce2022-02-03 08:27:08 -0800142static std::vector<uint8_t> toStdVec(const uint8_t* ptr, size_t n) {
143 if (!ptr) {
144 return std::vector<uint8_t>();
145 }
146 return std::vector<uint8_t>(ptr, ptr + n);
147}
148
Kyle Zhang6605add2022-01-13 17:51:23 +0000149// -------Hidl interface related end--------------
150
Kyle Zhang994023a2022-02-09 05:32:12 +0000151bool CryptoHalAidl::isCryptoSchemeSupportedInternal(const uint8_t uuid[16], int* factoryIdx) {
152 Uuid uuidAidl = DrmUtils::toAidlUuid(uuid);
153 for (size_t i = 0; i < mFactories.size(); i++) {
154 CryptoSchemes schemes{};
155 if (mFactories[i]->getSupportedCryptoSchemes(&schemes).isOk()) {
156 if (std::count(schemes.uuids.begin(), schemes.uuids.end(), uuidAidl)) {
157 if (factoryIdx != NULL) *factoryIdx = i;
158 return true;
159 }
160 }
161 }
162
163 return false;
164}
165
Kyle Zhang6605add2022-01-13 17:51:23 +0000166CryptoHalAidl::CryptoHalAidl()
Kyle Zhang994023a2022-02-09 05:32:12 +0000167 : mFactories(DrmUtils::makeDrmFactoriesAidl()),
Kyle Zhang6605add2022-01-13 17:51:23 +0000168 mInitCheck((mFactories.size() == 0) ? ERROR_UNSUPPORTED : NO_INIT),
169 mHeapSeqNum(0) {}
170
171CryptoHalAidl::~CryptoHalAidl() {}
172
Kyle Zhang6605add2022-01-13 17:51:23 +0000173status_t CryptoHalAidl::initCheck() const {
174 return mInitCheck;
175}
176
177bool CryptoHalAidl::isCryptoSchemeSupported(const uint8_t uuid[16]) {
178 Mutex::Autolock autoLock(mLock);
179
Kyle Zhang994023a2022-02-09 05:32:12 +0000180 return isCryptoSchemeSupportedInternal(uuid, NULL);
Kyle Zhang6605add2022-01-13 17:51:23 +0000181}
182
183status_t CryptoHalAidl::createPlugin(const uint8_t uuid[16], const void* data, size_t size) {
184 Mutex::Autolock autoLock(mLock);
185
Kyle Zhang994023a2022-02-09 05:32:12 +0000186 Uuid uuidAidl = DrmUtils::toAidlUuid(uuid);
Kyle Zhang6605add2022-01-13 17:51:23 +0000187 std::vector<uint8_t> dataAidl = toStdVec(toVector(toHidlVec(data, size)));
Kyle Zhang994023a2022-02-09 05:32:12 +0000188 int i = 0;
189 if (isCryptoSchemeSupportedInternal(uuid, &i)) {
190 mPlugin = makeCryptoPlugin(mFactories[i], uuidAidl, dataAidl);
Kyle Zhang6605add2022-01-13 17:51:23 +0000191 }
192
193 if (mInitCheck == NO_INIT) {
194 mInitCheck = mPlugin == NULL ? ERROR_UNSUPPORTED : OK;
195 }
196
197 return mInitCheck;
198}
199
200std::shared_ptr<ICryptoPluginAidl> CryptoHalAidl::makeCryptoPlugin(
Kyle Zhang994023a2022-02-09 05:32:12 +0000201 const std::shared_ptr<IDrmFactoryAidl>& factory, const Uuid& uuidAidl,
Kyle Zhang6605add2022-01-13 17:51:23 +0000202 const std::vector<uint8_t> initData) {
203 std::shared_ptr<ICryptoPluginAidl> pluginAidl;
Kyle Zhang994023a2022-02-09 05:32:12 +0000204 if (factory->createCryptoPlugin(uuidAidl, initData, &pluginAidl).isOk()) {
Kyle Zhang6605add2022-01-13 17:51:23 +0000205 ALOGI("Create ICryptoPluginAidl. UUID:[%s]", uuidAidl.toString().c_str());
206 } else {
207 mInitCheck = DEAD_OBJECT;
208 ALOGE("Failed to create ICryptoPluginAidl. UUID:[%s]", uuidAidl.toString().c_str());
209 }
210
211 return pluginAidl;
212}
213
214status_t CryptoHalAidl::destroyPlugin() {
215 Mutex::Autolock autoLock(mLock);
216
217 if (mInitCheck != OK) {
218 return mInitCheck;
219 }
220
221 mPlugin.reset();
222 return OK;
223}
224
225bool CryptoHalAidl::requiresSecureDecoderComponent(const char* mime) const {
226 Mutex::Autolock autoLock(mLock);
227
228 if (mInitCheck != OK) {
229 return false;
230 }
231
232 std::string mimeStr = std::string(mime);
233 bool result;
234 if (!mPlugin->requiresSecureDecoderComponent(mimeStr, &result).isOk()) {
235 ALOGE("Failed to requiresSecureDecoderComponent. mime:[%s]", mime);
236 return false;
237 }
238
239 return result;
240}
241
242void CryptoHalAidl::notifyResolution(uint32_t width, uint32_t height) {
243 Mutex::Autolock autoLock(mLock);
244
245 if (mInitCheck != OK) {
246 return;
247 }
248
249 // Check negative width and height after type conversion
250 // Log error and return if any is negative
251 if ((int32_t)width < 0 || (int32_t)height < 0) {
252 ALOGE("Negative width: %d or height %d in notifyResolution", width, height);
253 return;
254 }
255
256 ::ndk::ScopedAStatus status = mPlugin->notifyResolution(width, height);
257 if (!status.isOk()) {
258 ALOGE("notifyResolution txn failed status code: %d", status.getServiceSpecificError());
259 }
260}
261
262status_t CryptoHalAidl::setMediaDrmSession(const Vector<uint8_t>& sessionId) {
263 Mutex::Autolock autoLock(mLock);
264
265 if (mInitCheck != OK) {
266 return mInitCheck;
267 }
268
269 auto err = mPlugin->setMediaDrmSession(toStdVec(sessionId));
Kyle Zhang96af9572022-02-05 06:38:53 +0000270 return statusAidlToStatusT(err);
Kyle Zhang6605add2022-01-13 17:51:23 +0000271}
272
273ssize_t CryptoHalAidl::decrypt(const uint8_t keyId[16], const uint8_t iv[16],
274 CryptoPlugin::Mode mode, const CryptoPlugin::Pattern& pattern,
275 const SharedBufferHidl& hSource, size_t offset,
276 const CryptoPlugin::SubSample* subSamples, size_t numSubSamples,
277 const DestinationBufferHidl& hDestination, AString* errorDetailMsg) {
278 Mutex::Autolock autoLock(mLock);
279
280 if (mInitCheck != OK) {
281 return mInitCheck;
282 }
283
284 Mode aMode;
285 switch (mode) {
286 case CryptoPlugin::kMode_Unencrypted:
287 aMode = Mode::UNENCRYPTED;
288 break;
289 case CryptoPlugin::kMode_AES_CTR:
290 aMode = Mode::AES_CTR;
291 break;
292 case CryptoPlugin::kMode_AES_WV:
293 aMode = Mode::AES_CBC_CTS;
294 break;
295 case CryptoPlugin::kMode_AES_CBC:
296 aMode = Mode::AES_CBC;
297 break;
298 default:
299 return UNKNOWN_ERROR;
300 }
301
302 Pattern aPattern;
303 aPattern.encryptBlocks = pattern.mEncryptBlocks;
304 aPattern.skipBlocks = pattern.mSkipBlocks;
305
306 std::vector<SubSample> stdSubSamples;
307 for (size_t i = 0; i < numSubSamples; i++) {
308 SubSample subSample;
309 subSample.numBytesOfClearData = subSamples[i].mNumBytesOfClearData;
310 subSample.numBytesOfEncryptedData = subSamples[i].mNumBytesOfEncryptedData;
311 stdSubSamples.push_back(subSample);
312 }
313
314 bool secure;
315 if (hDestination.type == BufferTypeHidl::SHARED_MEMORY) {
316 status_t status = checkSharedBuffer(hDestination.nonsecureMemory);
317 if (status != OK) {
318 return status;
319 }
320 secure = false;
321 } else if (hDestination.type == BufferTypeHidl::NATIVE_HANDLE) {
322 secure = true;
323 } else {
324 android_errorWriteLog(0x534e4554, "70526702");
325 return UNKNOWN_ERROR;
326 }
327
328 status_t status = checkSharedBuffer(hSource);
329 if (status != OK) {
330 return status;
331 }
332
333 status_t err = UNKNOWN_ERROR;
334 mLock.unlock();
335
Robert Shihcc4a2ce2022-02-03 08:27:08 -0800336 std::vector<uint8_t> keyIdAidl(toStdVec(keyId, 16));
337 std::vector<uint8_t> ivAidl(toStdVec(iv, 16));
Kyle Zhang994023a2022-02-09 05:32:12 +0000338
339 DecryptArgs args;
340 args.secure = secure;
341 args.keyId = keyIdAidl;
342 args.iv = ivAidl;
343 args.mode = aMode;
344 args.pattern = aPattern;
345 args.subSamples = std::move(stdSubSamples);
346 args.source = hidlSharedBufferToAidlSharedBuffer(hSource);
347 args.offset = offset;
348 args.destination = hidlDestinationBufferToAidlDestinationBuffer(hDestination);
349
350
351 int32_t result = 0;
352 ::ndk::ScopedAStatus statusAidl = mPlugin->decrypt(args, &result);
Kyle Zhang6605add2022-01-13 17:51:23 +0000353
Kyle Zhang96af9572022-02-05 06:38:53 +0000354 err = statusAidlToStatusT(statusAidl);
Kyle Zhang994023a2022-02-09 05:32:12 +0000355 std::string msgStr(statusAidl.getMessage());
356 *errorDetailMsg = toString8(msgStr);
Kyle Zhang6605add2022-01-13 17:51:23 +0000357 if (err != OK) {
Kyle Zhang994023a2022-02-09 05:32:12 +0000358 ALOGE("Failed on decrypt, error message:%s, bytes written:%d", statusAidl.getMessage(),
359 result);
Kyle Zhang6605add2022-01-13 17:51:23 +0000360 return err;
361 }
362
Kyle Zhang994023a2022-02-09 05:32:12 +0000363 return result;
Kyle Zhang6605add2022-01-13 17:51:23 +0000364}
365
366int32_t CryptoHalAidl::setHeap(const sp<HidlMemory>& heap) {
367 if (heap == NULL || mHeapSeqNum < 0) {
368 ALOGE("setHeap(): heap %p mHeapSeqNum %d", heap.get(), mHeapSeqNum);
369 return -1;
370 }
371
372 Mutex::Autolock autoLock(mLock);
373
374 int32_t seqNum = mHeapSeqNum++;
375 uint32_t bufferId = static_cast<uint32_t>(seqNum);
376 mHeapSizes.add(seqNum, heap->size());
377
Kyle Zhang994023a2022-02-09 05:32:12 +0000378 SharedBufferAidl memAidl;
379 memAidl.handle = ::android::makeToAidl(heap->handle());
Kyle Zhang6605add2022-01-13 17:51:23 +0000380 memAidl.size = heap->size();
Kyle Zhang994023a2022-02-09 05:32:12 +0000381 memAidl.bufferId = bufferId;
Kyle Zhang6605add2022-01-13 17:51:23 +0000382
Kyle Zhang994023a2022-02-09 05:32:12 +0000383 auto status = mPlugin->setSharedBufferBase(memAidl);
384 ALOGE_IF(!status.isOk(),
Kyle Zhang6605add2022-01-13 17:51:23 +0000385 "setSharedBufferBase(): remote call failed");
386 return seqNum;
387}
388
389void CryptoHalAidl::unsetHeap(int32_t seqNum) {
390 Mutex::Autolock autoLock(mLock);
391
392 /*
393 * Clear the remote shared memory mapping by setting the shared
394 * buffer base to a null hidl_memory.
395 *
396 * TODO: Add a releaseSharedBuffer method in a future DRM HAL
397 * API version to make this explicit.
398 */
399 ssize_t index = mHeapSizes.indexOfKey(seqNum);
400 if (index >= 0) {
401 if (mPlugin != NULL) {
402 uint32_t bufferId = static_cast<uint32_t>(seqNum);
Kyle Zhang994023a2022-02-09 05:32:12 +0000403 SharedBufferAidl memAidl{};
404 memAidl.bufferId = bufferId;
405 auto status = mPlugin->setSharedBufferBase(memAidl);
406 ALOGE_IF(!status.isOk(),
Kyle Zhang6605add2022-01-13 17:51:23 +0000407 "setSharedBufferBase(): remote call failed");
408 }
409 mHeapSizes.removeItem(seqNum);
410 }
411}
412
413status_t CryptoHalAidl::getLogMessages(Vector<drm::V1_4::LogMessage>& logs) const {
414 Mutex::Autolock autoLock(mLock);
415 // Need to convert logmessage
416
Kyle Zhang96af9572022-02-05 06:38:53 +0000417 return DrmUtils::GetLogMessagesAidl<ICryptoPluginAidl>(mPlugin, logs);
Kyle Zhang6605add2022-01-13 17:51:23 +0000418}
419} // namespace android