2 * Copyright (C) 2017 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "CryptoHal"
19 #include <utils/Log.h>
21 #include <android/hardware/drm/1.0/types.h>
22 #include <android/hidl/manager/1.0/IServiceManager.h>
24 #include <binder/IMemory.h>
25 #include <cutils/native_handle.h>
26 #include <media/CryptoHal.h>
27 #include <media/hardware/CryptoAPI.h>
28 #include <media/stagefright/foundation/ADebug.h>
29 #include <media/stagefright/foundation/AString.h>
30 #include <media/stagefright/foundation/hexdump.h>
31 #include <media/stagefright/MediaErrors.h>
33 using ::android::hardware::drm::V1_0::BufferType;
34 using ::android::hardware::drm::V1_0::DestinationBuffer;
35 using ::android::hardware::drm::V1_0::ICryptoFactory;
36 using ::android::hardware::drm::V1_0::ICryptoPlugin;
37 using ::android::hardware::drm::V1_0::Mode;
38 using ::android::hardware::drm::V1_0::Pattern;
39 using ::android::hardware::drm::V1_0::SharedBuffer;
40 using ::android::hardware::drm::V1_0::Status;
41 using ::android::hardware::drm::V1_0::SubSample;
42 using ::android::hardware::hidl_array;
43 using ::android::hardware::hidl_handle;
44 using ::android::hardware::hidl_memory;
45 using ::android::hardware::hidl_string;
46 using ::android::hardware::hidl_vec;
47 using ::android::hardware::Return;
48 using ::android::hardware::Void;
49 using ::android::hidl::manager::V1_0::IServiceManager;
55 static status_t toStatusT(Status status) {
59 case Status::ERROR_DRM_NO_LICENSE:
60 return ERROR_DRM_NO_LICENSE;
61 case Status::ERROR_DRM_LICENSE_EXPIRED:
62 return ERROR_DRM_LICENSE_EXPIRED;
63 case Status::ERROR_DRM_RESOURCE_BUSY:
64 return ERROR_DRM_RESOURCE_BUSY;
65 case Status::ERROR_DRM_INSUFFICIENT_OUTPUT_PROTECTION:
66 return ERROR_DRM_INSUFFICIENT_OUTPUT_PROTECTION;
67 case Status::ERROR_DRM_SESSION_NOT_OPENED:
68 return ERROR_DRM_SESSION_NOT_OPENED;
69 case Status::ERROR_DRM_CANNOT_HANDLE:
70 return ERROR_DRM_CANNOT_HANDLE;
71 case Status::ERROR_DRM_DECRYPT:
72 return ERROR_DRM_DECRYPT;
79 static hidl_vec<uint8_t> toHidlVec(const Vector<uint8_t> &vector) {
80 hidl_vec<uint8_t> vec;
81 vec.setToExternal(const_cast<uint8_t *>(vector.array()), vector.size());
85 static hidl_vec<uint8_t> toHidlVec(const void *ptr, size_t size) {
86 hidl_vec<uint8_t> vec;
88 memcpy(vec.data(), ptr, size);
92 static hidl_array<uint8_t, 16> toHidlArray16(const uint8_t *ptr) {
94 return hidl_array<uint8_t, 16>();
96 return hidl_array<uint8_t, 16>(ptr);
100 static String8 toString8(hidl_string hString) {
101 return String8(hString.c_str());
105 CryptoHal::CryptoHal()
106 : mFactories(makeCryptoFactories()),
107 mInitCheck((mFactories.size() == 0) ? ERROR_UNSUPPORTED : NO_INIT),
112 CryptoHal::~CryptoHal() {
115 Vector<sp<ICryptoFactory>> CryptoHal::makeCryptoFactories() {
116 Vector<sp<ICryptoFactory>> factories;
118 auto manager = ::IServiceManager::getService();
119 if (manager != NULL) {
120 manager->listByInterface(ICryptoFactory::descriptor,
121 [&factories](const hidl_vec<hidl_string> ®istered) {
122 for (const auto &instance : registered) {
123 auto factory = ICryptoFactory::getService(instance);
124 if (factory != NULL) {
125 factories.push_back(factory);
126 ALOGI("makeCryptoFactories: factory instance %s is %s",
128 factory->isRemote() ? "Remote" : "Not Remote");
135 if (factories.size() == 0) {
136 // must be in passthrough mode, load the default passthrough service
137 auto passthrough = ICryptoFactory::getService();
138 if (passthrough != NULL) {
139 ALOGI("makeCryptoFactories: using default crypto instance");
140 factories.push_back(passthrough);
142 ALOGE("Failed to find any crypto factories");
148 sp<ICryptoPlugin> CryptoHal::makeCryptoPlugin(const sp<ICryptoFactory>& factory,
149 const uint8_t uuid[16], const void *initData, size_t initDataSize) {
151 sp<ICryptoPlugin> plugin;
152 Return<void> hResult = factory->createPlugin(toHidlArray16(uuid),
153 toHidlVec(initData, initDataSize),
154 [&](Status status, const sp<ICryptoPlugin>& hPlugin) {
155 if (status != Status::OK) {
156 ALOGE("Failed to make crypto plugin");
166 status_t CryptoHal::initCheck() const {
171 bool CryptoHal::isCryptoSchemeSupported(const uint8_t uuid[16]) {
172 Mutex::Autolock autoLock(mLock);
174 for (size_t i = 0; i < mFactories.size(); i++) {
175 if (mFactories[i]->isCryptoSchemeSupported(uuid)) {
182 status_t CryptoHal::createPlugin(const uint8_t uuid[16], const void *data,
184 Mutex::Autolock autoLock(mLock);
186 for (size_t i = 0; i < mFactories.size(); i++) {
187 if (mFactories[i]->isCryptoSchemeSupported(uuid)) {
188 mPlugin = makeCryptoPlugin(mFactories[i], uuid, data, size);
192 if (mPlugin == NULL) {
193 mInitCheck = ERROR_UNSUPPORTED;
201 status_t CryptoHal::destroyPlugin() {
202 Mutex::Autolock autoLock(mLock);
204 if (mInitCheck != OK) {
212 bool CryptoHal::requiresSecureDecoderComponent(const char *mime) const {
213 Mutex::Autolock autoLock(mLock);
215 if (mInitCheck != OK) {
219 return mPlugin->requiresSecureDecoderComponent(hidl_string(mime));
224 * If the heap base isn't set, get the heap base from the IMemory
225 * and send it to the HAL so it can map a remote heap of the same
226 * size. Once the heap base is established, shared memory buffers
227 * are sent by providing an offset into the heap and a buffer size.
229 int32_t CryptoHal::setHeapBase(const sp<IMemoryHeap>& heap) {
231 ALOGE("setHeapBase(): heap is NULL");
234 native_handle_t* nativeHandle = native_handle_create(1, 0);
236 ALOGE("setHeapBase(), failed to create native handle");
240 Mutex::Autolock autoLock(mLock);
242 int32_t seqNum = mHeapSeqNum++;
244 int fd = heap->getHeapID();
245 nativeHandle->data[0] = fd;
246 auto hidlHandle = hidl_handle(nativeHandle);
247 auto hidlMemory = hidl_memory("ashmem", hidlHandle, heap->getSize());
248 mHeapBases.add(seqNum, HeapBase(mNextBufferId, heap->getSize()));
249 Return<void> hResult = mPlugin->setSharedBufferBase(hidlMemory, mNextBufferId++);
250 ALOGE_IF(!hResult.isOk(), "setSharedBufferBase(): remote call failed");
254 void CryptoHal::clearHeapBase(int32_t seqNum) {
255 Mutex::Autolock autoLock(mLock);
257 mHeapBases.removeItem(seqNum);
260 status_t CryptoHal::toSharedBuffer(const sp<IMemory>& memory, int32_t seqNum, ::SharedBuffer* buffer) {
264 if (memory == NULL && buffer == NULL) {
265 return UNEXPECTED_NULL;
268 sp<IMemoryHeap> heap = memory->getMemory(&offset, &size);
270 return UNEXPECTED_NULL;
273 // memory must be in one of the heaps that have been set
274 if (mHeapBases.indexOfKey(seqNum) < 0) {
275 return UNKNOWN_ERROR;
278 // heap must be the same size as the one that was set in setHeapBase
279 if (mHeapBases.valueFor(seqNum).getSize() != heap->getSize()) {
280 android_errorWriteLog(0x534e4554, "76221123");
281 return UNKNOWN_ERROR;
284 // memory must be within the address space of the heap
285 if (memory->pointer() != static_cast<uint8_t *>(heap->getBase()) + memory->offset() ||
286 heap->getSize() < memory->offset() + memory->size() ||
287 SIZE_MAX - memory->offset() < memory->size()) {
288 android_errorWriteLog(0x534e4554, "76221123");
289 return UNKNOWN_ERROR;
292 buffer->bufferId = mHeapBases.valueFor(seqNum).getBufferId();
293 buffer->offset = offset >= 0 ? offset : 0;
298 ssize_t CryptoHal::decrypt(const uint8_t keyId[16], const uint8_t iv[16],
299 CryptoPlugin::Mode mode, const CryptoPlugin::Pattern &pattern,
300 const ICrypto::SourceBuffer &source, size_t offset,
301 const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
302 const ICrypto::DestinationBuffer &destination, AString *errorDetailMsg) {
303 Mutex::Autolock autoLock(mLock);
305 if (mInitCheck != OK) {
311 case CryptoPlugin::kMode_Unencrypted:
312 hMode = Mode::UNENCRYPTED ;
314 case CryptoPlugin::kMode_AES_CTR:
315 hMode = Mode::AES_CTR;
317 case CryptoPlugin::kMode_AES_WV:
318 hMode = Mode::AES_CBC_CTS;
320 case CryptoPlugin::kMode_AES_CBC:
321 hMode = Mode::AES_CBC;
324 return UNKNOWN_ERROR;
328 hPattern.encryptBlocks = pattern.mEncryptBlocks;
329 hPattern.skipBlocks = pattern.mSkipBlocks;
331 std::vector<SubSample> stdSubSamples;
332 for (size_t i = 0; i < numSubSamples; i++) {
334 subSample.numBytesOfClearData = subSamples[i].mNumBytesOfClearData;
335 subSample.numBytesOfEncryptedData = subSamples[i].mNumBytesOfEncryptedData;
336 stdSubSamples.push_back(subSample);
338 auto hSubSamples = hidl_vec<SubSample>(stdSubSamples);
340 int32_t heapSeqNum = source.mHeapSeqNum;
342 ::DestinationBuffer hDestination;
343 if (destination.mType == kDestinationTypeSharedMemory) {
344 hDestination.type = BufferType::SHARED_MEMORY;
345 status_t status = toSharedBuffer(destination.mSharedMemory, heapSeqNum,
346 &hDestination.nonsecureMemory);
351 } else if (destination.mType == kDestinationTypeNativeHandle) {
352 hDestination.type = BufferType::NATIVE_HANDLE;
353 hDestination.secureMemory = hidl_handle(destination.mHandle);
356 android_errorWriteLog(0x534e4554, "70526702");
357 return UNKNOWN_ERROR;
360 ::SharedBuffer hSource;
361 status_t status = toSharedBuffer(source.mSharedMemory, heapSeqNum, &hSource);
366 status_t err = UNKNOWN_ERROR;
367 uint32_t bytesWritten = 0;
369 Return<void> hResult = mPlugin->decrypt(secure, toHidlArray16(keyId), toHidlArray16(iv), hMode,
370 hPattern, hSubSamples, hSource, offset, hDestination,
371 [&](Status status, uint32_t hBytesWritten, hidl_string hDetailedError) {
372 if (status == Status::OK) {
373 bytesWritten = hBytesWritten;
374 *errorDetailMsg = toString8(hDetailedError);
376 err = toStatusT(status);
380 if (!hResult.isOk()) {
390 void CryptoHal::notifyResolution(uint32_t width, uint32_t height) {
391 Mutex::Autolock autoLock(mLock);
393 if (mInitCheck != OK) {
397 mPlugin->notifyResolution(width, height);
400 status_t CryptoHal::setMediaDrmSession(const Vector<uint8_t> &sessionId) {
401 Mutex::Autolock autoLock(mLock);
403 if (mInitCheck != OK) {
407 return toStatusT(mPlugin->setMediaDrmSession(toHidlVec(sessionId)));
410 } // namespace android