CryptoHal.cpp revision abeb36a8c2f044772297536e70340c3b245863e4
1/*
2 * Copyright (C) 2017 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 "CryptoHal"
19#include <utils/Log.h>
20
21#include <android/hardware/drm/1.0/types.h>
22#include <android/hidl/manager/1.0/IServiceManager.h>
23
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>
32
33using ::android::hardware::drm::V1_0::BufferType;
34using ::android::hardware::drm::V1_0::DestinationBuffer;
35using ::android::hardware::drm::V1_0::ICryptoFactory;
36using ::android::hardware::drm::V1_0::ICryptoPlugin;
37using ::android::hardware::drm::V1_0::Mode;
38using ::android::hardware::drm::V1_0::Pattern;
39using ::android::hardware::drm::V1_0::SharedBuffer;
40using ::android::hardware::drm::V1_0::Status;
41using ::android::hardware::drm::V1_0::SubSample;
42using ::android::hardware::hidl_array;
43using ::android::hardware::hidl_handle;
44using ::android::hardware::hidl_memory;
45using ::android::hardware::hidl_string;
46using ::android::hardware::hidl_vec;
47using ::android::hardware::Return;
48using ::android::hardware::Void;
49using ::android::hidl::manager::V1_0::IServiceManager;
50using ::android::sp;
51
52
53namespace android {
54
55static status_t toStatusT(Status status) {
56    switch (status) {
57    case Status::OK:
58        return OK;
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    default:
72        return UNKNOWN_ERROR;
73    }
74}
75
76
77static hidl_vec<uint8_t> toHidlVec(const Vector<uint8_t> &vector) {
78    hidl_vec<uint8_t> vec;
79    vec.setToExternal(const_cast<uint8_t *>(vector.array()), vector.size());
80    return vec;
81}
82
83static hidl_vec<uint8_t> toHidlVec(const void *ptr, size_t size) {
84    hidl_vec<uint8_t> vec;
85    vec.resize(size);
86    memcpy(vec.data(), ptr, size);
87    return vec;
88}
89
90static hidl_array<uint8_t, 16> toHidlArray16(const uint8_t *ptr) {
91    if (!ptr) {
92        return hidl_array<uint8_t, 16>();
93    }
94    return hidl_array<uint8_t, 16>(ptr);
95}
96
97
98static String8 toString8(hidl_string hString) {
99    return String8(hString.c_str());
100}
101
102
103CryptoHal::CryptoHal()
104    : mFactories(makeCryptoFactories()),
105      mInitCheck((mFactories.size() == 0) ? ERROR_UNSUPPORTED : NO_INIT),
106      mNextBufferId(0) {
107}
108
109CryptoHal::~CryptoHal() {
110}
111
112Vector<sp<ICryptoFactory>> CryptoHal::makeCryptoFactories() {
113    Vector<sp<ICryptoFactory>> factories;
114
115    auto manager = ::IServiceManager::getService("manager");
116    if (manager != NULL) {
117        manager->listByInterface(ICryptoFactory::descriptor,
118                [&factories](const hidl_vec<hidl_string> &registered) {
119                    for (const auto &instance : registered) {
120                        auto factory = ICryptoFactory::getService(instance);
121                        if (factory != NULL) {
122                            factories.push_back(factory);
123                            ALOGI("makeCryptoFactories: factory instance %s is %s",
124                                    instance.c_str(),
125                                    factory->isRemote() ? "Remote" : "Not Remote");
126                        }
127                    }
128                }
129            );
130    }
131
132    if (factories.size() == 0) {
133        // must be in passthrough mode, load the default passthrough service
134        auto passthrough = ICryptoFactory::getService("crypto");
135        if (passthrough != NULL) {
136            ALOGI("makeCryptoFactories: using default crypto instance");
137            factories.push_back(passthrough);
138        } else {
139            ALOGE("Failed to find any crypto factories");
140        }
141    }
142    return factories;
143}
144
145sp<ICryptoPlugin> CryptoHal::makeCryptoPlugin(const sp<ICryptoFactory>& factory,
146        const uint8_t uuid[16], const void *initData, size_t initDataSize) {
147
148    sp<ICryptoPlugin> plugin;
149    Return<void> hResult = factory->createPlugin(toHidlArray16(uuid),
150            toHidlVec(initData, initDataSize),
151            [&](Status status, const sp<ICryptoPlugin>& hPlugin) {
152                if (status != Status::OK) {
153                    ALOGE("Failed to make crypto plugin");
154                    return;
155                }
156                plugin = hPlugin;
157            }
158        );
159    return plugin;
160}
161
162
163status_t CryptoHal::initCheck() const {
164    return mInitCheck;
165}
166
167
168bool CryptoHal::isCryptoSchemeSupported(const uint8_t uuid[16]) {
169    Mutex::Autolock autoLock(mLock);
170
171    for (size_t i = 0; i < mFactories.size(); i++) {
172        if (mFactories[i]->isCryptoSchemeSupported(uuid)) {
173            return true;
174        }
175    }
176    return false;
177}
178
179status_t CryptoHal::createPlugin(const uint8_t uuid[16], const void *data,
180        size_t size) {
181    Mutex::Autolock autoLock(mLock);
182
183    for (size_t i = 0; i < mFactories.size(); i++) {
184        if (mFactories[i]->isCryptoSchemeSupported(uuid)) {
185            mPlugin = makeCryptoPlugin(mFactories[i], uuid, data, size);
186        }
187    }
188
189    if (mPlugin == NULL) {
190        mInitCheck = ERROR_UNSUPPORTED;
191    } else {
192        mInitCheck = OK;
193    }
194
195    return mInitCheck;
196}
197
198status_t CryptoHal::destroyPlugin() {
199    Mutex::Autolock autoLock(mLock);
200
201    if (mInitCheck != OK) {
202        return mInitCheck;
203    }
204
205    mPlugin.clear();
206    return OK;
207}
208
209bool CryptoHal::requiresSecureDecoderComponent(const char *mime) const {
210    Mutex::Autolock autoLock(mLock);
211
212    if (mInitCheck != OK) {
213        return mInitCheck;
214    }
215
216    return mPlugin->requiresSecureDecoderComponent(hidl_string(mime));
217}
218
219
220/**
221 * If the heap base isn't set, get the heap base from the IMemory
222 * and send it to the HAL so it can map a remote heap of the same
223 * size.  Once the heap base is established, shared memory buffers
224 * are sent by providing an offset into the heap and a buffer size.
225 */
226void CryptoHal::setHeapBase(const sp<IMemoryHeap>& heap) {
227    native_handle_t* nativeHandle = native_handle_create(1, 0);
228    if (!nativeHandle) {
229        ALOGE("setSharedBufferBase(), failed to create native handle");
230        return;
231    }
232    if (heap == NULL) {
233        ALOGE("setSharedBufferBase(): heap is NULL");
234        return;
235    }
236    int fd = heap->getHeapID();
237    nativeHandle->data[0] = fd;
238    auto hidlHandle = hidl_handle(nativeHandle);
239    auto hidlMemory = hidl_memory("ashmem", hidlHandle, heap->getSize());
240    mHeapBases.add(heap->getBase(), mNextBufferId);
241    Return<void> hResult = mPlugin->setSharedBufferBase(hidlMemory, mNextBufferId++);
242    ALOGE_IF(!hResult.isOk(), "setSharedBufferBase(): remote call failed");
243}
244
245status_t CryptoHal::toSharedBuffer(const sp<IMemory>& memory, ::SharedBuffer* buffer) {
246    ssize_t offset;
247    size_t size;
248
249    if (memory == NULL && buffer == NULL) {
250        return UNEXPECTED_NULL;
251    }
252
253    sp<IMemoryHeap> heap = memory->getMemory(&offset, &size);
254    if (heap == NULL) {
255        return UNEXPECTED_NULL;
256    }
257
258    if (mHeapBases.indexOfKey(heap->getBase()) < 0) {
259        setHeapBase(heap);
260    }
261
262    buffer->bufferId = mHeapBases.valueFor(heap->getBase());
263    buffer->offset = offset >= 0 ? offset : 0;
264    buffer->size = size;
265    return OK;
266}
267
268ssize_t CryptoHal::decrypt(const uint8_t keyId[16], const uint8_t iv[16],
269        CryptoPlugin::Mode mode, const CryptoPlugin::Pattern &pattern,
270        const sp<IMemory> &source, size_t offset,
271        const CryptoPlugin::SubSample *subSamples, size_t numSubSamples,
272        const ICrypto::DestinationBuffer &destination, AString *errorDetailMsg) {
273    Mutex::Autolock autoLock(mLock);
274
275    if (mInitCheck != OK) {
276        return mInitCheck;
277    }
278
279    Mode hMode;
280    switch(mode) {
281    case CryptoPlugin::kMode_Unencrypted:
282        hMode = Mode::UNENCRYPTED ;
283        break;
284    case CryptoPlugin::kMode_AES_CTR:
285        hMode = Mode::AES_CTR;
286        break;
287    case CryptoPlugin::kMode_AES_WV:
288        hMode = Mode::AES_CBC_CTS;
289        break;
290    case CryptoPlugin::kMode_AES_CBC:
291        hMode = Mode::AES_CBC;
292        break;
293    default:
294        return UNKNOWN_ERROR;
295    }
296
297    Pattern hPattern;
298    hPattern.encryptBlocks = pattern.mEncryptBlocks;
299    hPattern.skipBlocks = pattern.mSkipBlocks;
300
301    std::vector<SubSample> stdSubSamples;
302    for (size_t i = 0; i < numSubSamples; i++) {
303        SubSample subSample;
304        subSample.numBytesOfClearData = subSamples[i].mNumBytesOfClearData;
305        subSample.numBytesOfEncryptedData = subSamples[i].mNumBytesOfEncryptedData;
306        stdSubSamples.push_back(subSample);
307    }
308    auto hSubSamples = hidl_vec<SubSample>(stdSubSamples);
309
310    bool secure;
311    ::DestinationBuffer hDestination;
312    if (destination.mType == kDestinationTypeSharedMemory) {
313        hDestination.type = BufferType::SHARED_MEMORY;
314        status_t status = toSharedBuffer(destination.mSharedMemory,
315                &hDestination.nonsecureMemory);
316        if (status != OK) {
317            return status;
318        }
319        secure = false;
320    } else {
321        hDestination.type = BufferType::NATIVE_HANDLE;
322        hDestination.secureMemory = hidl_handle(destination.mHandle);
323        secure = true;
324    }
325
326    ::SharedBuffer hSource;
327    status_t status = toSharedBuffer(source, &hSource);
328    if (status != OK) {
329        return status;
330    }
331
332    status_t err = UNKNOWN_ERROR;
333    uint32_t bytesWritten = 0;
334
335    Return<void> hResult = mPlugin->decrypt(secure, toHidlArray16(keyId), toHidlArray16(iv), hMode,
336            hPattern, hSubSamples, hSource, offset, hDestination,
337            [&](Status status, uint32_t hBytesWritten, hidl_string hDetailedError) {
338                if (status == Status::OK) {
339                    bytesWritten = hBytesWritten;
340                    *errorDetailMsg = toString8(hDetailedError);
341                }
342                err = toStatusT(status);
343            }
344        );
345
346    if (!hResult.isOk()) {
347        err = DEAD_OBJECT;
348    }
349
350    if (err == OK) {
351        return bytesWritten;
352    }
353    return err;
354}
355
356void CryptoHal::notifyResolution(uint32_t width, uint32_t height) {
357    Mutex::Autolock autoLock(mLock);
358
359    if (mInitCheck != OK) {
360        return;
361    }
362
363    mPlugin->notifyResolution(width, height);
364}
365
366status_t CryptoHal::setMediaDrmSession(const Vector<uint8_t> &sessionId) {
367    Mutex::Autolock autoLock(mLock);
368
369    if (mInitCheck != OK) {
370        return mInitCheck;
371    }
372
373    return toStatusT(mPlugin->setMediaDrmSession(toHidlVec(sessionId)));
374}
375
376}  // namespace android
377