blob: a688728aea8222964b9f64ccf69db87ce2efca93 [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
31using ::aidl::android::hardware::drm::BufferType;
32using ::aidl::android::hardware::drm::DecryptResult;
33using DestinationBufferAidl = ::aidl::android::hardware::drm::DestinationBuffer;
34using ::aidl::android::hardware::drm::Mode;
35using ::aidl::android::hardware::drm::Pattern;
36using SharedBufferAidl = ::aidl::android::hardware::drm::SharedBuffer;
37using ::aidl::android::hardware::drm::Status;
38using ::aidl::android::hardware::drm::SubSample;
39using ::aidl::android::hardware::drm::Uuid;
40
41using ::aidl::android::hardware::common::Ashmem;
42
43using ::android::sp;
44using ::android::DrmUtils::toStatusTAidl;
45using ::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
66static Uuid toAidlUuid(const uint8_t* uuid) {
67 Uuid uuidAidl;
68 uuidAidl.uuid = std::vector<uint8_t>(uuid, uuid + 16);
69 return uuidAidl;
70}
71
72template <typename Byte = uint8_t>
73static std::vector<Byte> toStdVec(const Vector<uint8_t>& vector) {
74 auto v = reinterpret_cast<const Byte*>(vector.array());
75 std::vector<Byte> vec(v, v + vector.size());
76 return vec;
77}
78
79// -------Hidl interface related-----------------
80// TODO: replace before removing hidl interface
81status_t CryptoHalAidl::checkSharedBuffer(const SharedBufferHidl& buffer) {
82 int32_t seqNum = static_cast<int32_t>(buffer.bufferId);
83 // memory must be in one of the heaps that have been set
84 if (mHeapSizes.indexOfKey(seqNum) < 0) {
85 return UNKNOWN_ERROR;
86 }
87
88 // memory must be within the address space of the heap
89 size_t heapSize = mHeapSizes.valueFor(seqNum);
90 if (heapSize < buffer.offset + buffer.size || SIZE_MAX - buffer.offset < buffer.size) {
91 android_errorWriteLog(0x534e4554, "76221123");
92 return UNKNOWN_ERROR;
93 }
94
95 return OK;
96}
97
98static SharedBufferAidl hidlSharedBufferToAidlSharedBuffer(const SharedBufferHidl& buffer) {
99 SharedBufferAidl aidlsb;
100 aidlsb.bufferId = buffer.bufferId;
101 aidlsb.offset = buffer.offset;
102 aidlsb.size = buffer.size;
103 return aidlsb;
104}
105
106static DestinationBufferAidl hidlDestinationBufferToAidlDestinationBuffer(
107 const DestinationBufferHidl& buffer) {
108 DestinationBufferAidl aidldb;
109 // skip negative convert check as count of enum elements are 2
110 aidldb.type = static_cast<BufferType>((int32_t)buffer.type);
111 aidldb.nonsecureMemory = hidlSharedBufferToAidlSharedBuffer(buffer.nonsecureMemory);
112 aidldb.secureMemory = ::android::makeToAidl(buffer.secureMemory.getNativeHandle());
113 return aidldb;
114}
115
116static hidl_vec<uint8_t> toHidlVec(const void* ptr, size_t size) {
117 hidl_vec<uint8_t> vec;
118 vec.resize(size);
119 memcpy(vec.data(), ptr, size);
120 return vec;
121}
122
123static const Vector<uint8_t> toVector(const std::vector<uint8_t>& vec) {
124 Vector<uint8_t> vector;
125 vector.appendArray(vec.data(), vec.size());
126 return *const_cast<const Vector<uint8_t>*>(&vector);
127}
128
129static String8 toString8(const std::string& string) {
130 return String8(string.c_str());
131}
132
133// -------Hidl interface related end--------------
134
135CryptoHalAidl::CryptoHalAidl()
136 : mFactories(makeCryptoFactories()),
137 mInitCheck((mFactories.size() == 0) ? ERROR_UNSUPPORTED : NO_INIT),
138 mHeapSeqNum(0) {}
139
140CryptoHalAidl::~CryptoHalAidl() {}
141
142std::vector<std::shared_ptr<ICryptoFactoryAidl>> CryptoHalAidl::makeCryptoFactories() {
143 std::vector<std::shared_ptr<ICryptoFactoryAidl>> factories;
144 AServiceManager_forEachDeclaredInstance(
145 ICryptoFactoryAidl::descriptor, static_cast<void*>(&factories),
146 [](const char* instance, void* context) {
147 auto fullName = std::string(ICryptoFactoryAidl::descriptor) + "/" + std::string(instance);
148 auto factory = ICryptoFactoryAidl::fromBinder(
149 ::ndk::SpAIBinder(AServiceManager_getService(fullName.c_str())));
150 if (factory == nullptr) {
151 ALOGE("not found ICryptoFactoryAidl. Instance name:[%s]", fullName.c_str());
152 return;
153 }
154
155 ALOGI("found ICryptoFactoryAidl. Instance name:[%s]", fullName.c_str());
156 static_cast<std::vector<std::shared_ptr<ICryptoFactoryAidl>>*>(context)
157 ->emplace_back(factory);
158 });
159
160 return factories;
161}
162
163status_t CryptoHalAidl::initCheck() const {
164 return mInitCheck;
165}
166
167bool CryptoHalAidl::isCryptoSchemeSupported(const uint8_t uuid[16]) {
168 Mutex::Autolock autoLock(mLock);
169
170 bool isSupported = false;
171 Uuid uuidAidl = toAidlUuid(uuid);
172 for (size_t i = 0; i < mFactories.size(); i++) {
173 if (mFactories[i]->isCryptoSchemeSupported(uuidAidl, &isSupported).isOk()) {
174 if (isSupported) break;
175 }
176 }
177 return isSupported;
178}
179
180status_t CryptoHalAidl::createPlugin(const uint8_t uuid[16], const void* data, size_t size) {
181 Mutex::Autolock autoLock(mLock);
182
183 bool isSupported = false;
184 Uuid uuidAidl = toAidlUuid(uuid);
185 std::vector<uint8_t> dataAidl = toStdVec(toVector(toHidlVec(data, size)));
186 for (size_t i = 0; i < mFactories.size(); i++) {
187 if (mFactories[i]->isCryptoSchemeSupported(uuidAidl, &isSupported).isOk() && isSupported) {
188 mPlugin = makeCryptoPlugin(mFactories[i], uuidAidl, dataAidl);
189 // Reserve place for future plugins with new versions
190
191 break;
192 }
193 }
194
195 if (mInitCheck == NO_INIT) {
196 mInitCheck = mPlugin == NULL ? ERROR_UNSUPPORTED : OK;
197 }
198
199 return mInitCheck;
200}
201
202std::shared_ptr<ICryptoPluginAidl> CryptoHalAidl::makeCryptoPlugin(
203 const std::shared_ptr<ICryptoFactoryAidl>& factory, const Uuid& uuidAidl,
204 const std::vector<uint8_t> initData) {
205 std::shared_ptr<ICryptoPluginAidl> pluginAidl;
206 if (factory->createPlugin(uuidAidl, initData, &pluginAidl).isOk()) {
207 ALOGI("Create ICryptoPluginAidl. UUID:[%s]", uuidAidl.toString().c_str());
208 } else {
209 mInitCheck = DEAD_OBJECT;
210 ALOGE("Failed to create ICryptoPluginAidl. UUID:[%s]", uuidAidl.toString().c_str());
211 }
212
213 return pluginAidl;
214}
215
216status_t CryptoHalAidl::destroyPlugin() {
217 Mutex::Autolock autoLock(mLock);
218
219 if (mInitCheck != OK) {
220 return mInitCheck;
221 }
222
223 mPlugin.reset();
224 return OK;
225}
226
227bool CryptoHalAidl::requiresSecureDecoderComponent(const char* mime) const {
228 Mutex::Autolock autoLock(mLock);
229
230 if (mInitCheck != OK) {
231 return false;
232 }
233
234 std::string mimeStr = std::string(mime);
235 bool result;
236 if (!mPlugin->requiresSecureDecoderComponent(mimeStr, &result).isOk()) {
237 ALOGE("Failed to requiresSecureDecoderComponent. mime:[%s]", mime);
238 return false;
239 }
240
241 return result;
242}
243
244void CryptoHalAidl::notifyResolution(uint32_t width, uint32_t height) {
245 Mutex::Autolock autoLock(mLock);
246
247 if (mInitCheck != OK) {
248 return;
249 }
250
251 // Check negative width and height after type conversion
252 // Log error and return if any is negative
253 if ((int32_t)width < 0 || (int32_t)height < 0) {
254 ALOGE("Negative width: %d or height %d in notifyResolution", width, height);
255 return;
256 }
257
258 ::ndk::ScopedAStatus status = mPlugin->notifyResolution(width, height);
259 if (!status.isOk()) {
260 ALOGE("notifyResolution txn failed status code: %d", status.getServiceSpecificError());
261 }
262}
263
264status_t CryptoHalAidl::setMediaDrmSession(const Vector<uint8_t>& sessionId) {
265 Mutex::Autolock autoLock(mLock);
266
267 if (mInitCheck != OK) {
268 return mInitCheck;
269 }
270
271 auto err = mPlugin->setMediaDrmSession(toStdVec(sessionId));
272 return err.isOk() ? toStatusTAidl(err.getServiceSpecificError()) : DEAD_OBJECT;
273}
274
275ssize_t CryptoHalAidl::decrypt(const uint8_t keyId[16], const uint8_t iv[16],
276 CryptoPlugin::Mode mode, const CryptoPlugin::Pattern& pattern,
277 const SharedBufferHidl& hSource, size_t offset,
278 const CryptoPlugin::SubSample* subSamples, size_t numSubSamples,
279 const DestinationBufferHidl& hDestination, AString* errorDetailMsg) {
280 Mutex::Autolock autoLock(mLock);
281
282 if (mInitCheck != OK) {
283 return mInitCheck;
284 }
285
286 Mode aMode;
287 switch (mode) {
288 case CryptoPlugin::kMode_Unencrypted:
289 aMode = Mode::UNENCRYPTED;
290 break;
291 case CryptoPlugin::kMode_AES_CTR:
292 aMode = Mode::AES_CTR;
293 break;
294 case CryptoPlugin::kMode_AES_WV:
295 aMode = Mode::AES_CBC_CTS;
296 break;
297 case CryptoPlugin::kMode_AES_CBC:
298 aMode = Mode::AES_CBC;
299 break;
300 default:
301 return UNKNOWN_ERROR;
302 }
303
304 Pattern aPattern;
305 aPattern.encryptBlocks = pattern.mEncryptBlocks;
306 aPattern.skipBlocks = pattern.mSkipBlocks;
307
308 std::vector<SubSample> stdSubSamples;
309 for (size_t i = 0; i < numSubSamples; i++) {
310 SubSample subSample;
311 subSample.numBytesOfClearData = subSamples[i].mNumBytesOfClearData;
312 subSample.numBytesOfEncryptedData = subSamples[i].mNumBytesOfEncryptedData;
313 stdSubSamples.push_back(subSample);
314 }
315
316 bool secure;
317 if (hDestination.type == BufferTypeHidl::SHARED_MEMORY) {
318 status_t status = checkSharedBuffer(hDestination.nonsecureMemory);
319 if (status != OK) {
320 return status;
321 }
322 secure = false;
323 } else if (hDestination.type == BufferTypeHidl::NATIVE_HANDLE) {
324 secure = true;
325 } else {
326 android_errorWriteLog(0x534e4554, "70526702");
327 return UNKNOWN_ERROR;
328 }
329
330 status_t status = checkSharedBuffer(hSource);
331 if (status != OK) {
332 return status;
333 }
334
335 status_t err = UNKNOWN_ERROR;
336 mLock.unlock();
337
338 std::vector<uint8_t> keyIdAidl = std::vector<uint8_t>(keyId, keyId + 16);
339 std::vector<uint8_t> ivAidl = std::vector<uint8_t>(iv, iv + 16);
340 DecryptResult result;
341 err = mPlugin->decrypt(secure, keyIdAidl, ivAidl, aMode, aPattern, stdSubSamples,
342 hidlSharedBufferToAidlSharedBuffer(hSource), offset,
343 hidlDestinationBufferToAidlDestinationBuffer(hDestination), &result)
344 .isOk()
345 ? OK
346 : DEAD_OBJECT;
347
348 *errorDetailMsg = toString8(result.detailedError);
349 if (err != OK) {
350 ALOGE("Failed on decrypt, error message:%s, bytes written:%d", result.detailedError.c_str(),
351 result.bytesWritten);
352 return err;
353 }
354
355 return result.bytesWritten;
356}
357
358int32_t CryptoHalAidl::setHeap(const sp<HidlMemory>& heap) {
359 if (heap == NULL || mHeapSeqNum < 0) {
360 ALOGE("setHeap(): heap %p mHeapSeqNum %d", heap.get(), mHeapSeqNum);
361 return -1;
362 }
363
364 Mutex::Autolock autoLock(mLock);
365
366 int32_t seqNum = mHeapSeqNum++;
367 uint32_t bufferId = static_cast<uint32_t>(seqNum);
368 mHeapSizes.add(seqNum, heap->size());
369
370 Ashmem memAidl;
371 memAidl.fd.set(heap->handle()->data[0]);
372 memAidl.size = heap->size();
373
374 ALOGE_IF(!mPlugin->setSharedBufferBase(memAidl, bufferId).isOk(),
375 "setSharedBufferBase(): remote call failed");
376 return seqNum;
377}
378
379void CryptoHalAidl::unsetHeap(int32_t seqNum) {
380 Mutex::Autolock autoLock(mLock);
381
382 /*
383 * Clear the remote shared memory mapping by setting the shared
384 * buffer base to a null hidl_memory.
385 *
386 * TODO: Add a releaseSharedBuffer method in a future DRM HAL
387 * API version to make this explicit.
388 */
389 ssize_t index = mHeapSizes.indexOfKey(seqNum);
390 if (index >= 0) {
391 if (mPlugin != NULL) {
392 uint32_t bufferId = static_cast<uint32_t>(seqNum);
393 Ashmem memAidl;
394 memAidl.fd.set(-1);
395 memAidl.size = 0;
396 ALOGE_IF(!mPlugin->setSharedBufferBase(memAidl, bufferId).isOk(),
397 "setSharedBufferBase(): remote call failed");
398 }
399 mHeapSizes.removeItem(seqNum);
400 }
401}
402
403status_t CryptoHalAidl::getLogMessages(Vector<drm::V1_4::LogMessage>& logs) const {
404 Mutex::Autolock autoLock(mLock);
405 // Need to convert logmessage
406
407 return DrmUtils::GetLogMessagesAidl<ICryptoPluginAidl>(mPlugin, logs);
408}
409} // namespace android