1 /*
2  * Copyright (C) 2018 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 "hidl_ClearKeyCryptoPlugin"
19 #include <utils/Log.h>
20 
21 #include "CryptoPlugin.h"
22 #include "SessionLibrary.h"
23 #include "TypeConvert.h"
24 
25 #include <hidlmemory/mapping.h>
26 
27 namespace android {
28 namespace hardware {
29 namespace drm {
30 namespace V1_2 {
31 namespace clearkey {
32 
33 using ::android::hardware::drm::V1_0::BufferType;
34 
setSharedBufferBase(const hidl_memory & base,uint32_t bufferId)35 Return<void> CryptoPlugin::setSharedBufferBase(
36         const hidl_memory& base, uint32_t bufferId) {
37     sp<IMemory> hidlMemory = mapMemory(base);
38     ALOGE_IF(hidlMemory == nullptr, "mapMemory returns nullptr");
39 
40     // allow mapMemory to return nullptr
41     mSharedBufferMap[bufferId] = hidlMemory;
42     return Void();
43 }
44 
decrypt(bool secure,const hidl_array<uint8_t,16> & keyId,const hidl_array<uint8_t,16> & iv,Mode mode,const Pattern & pattern,const hidl_vec<SubSample> & subSamples,const SharedBuffer & source,uint64_t offset,const DestinationBuffer & destination,decrypt_cb _hidl_cb)45 Return<void> CryptoPlugin::decrypt(
46     bool secure,
47     const hidl_array<uint8_t, 16>& keyId,
48     const hidl_array<uint8_t, 16>& iv,
49     Mode mode,
50     const Pattern& pattern,
51     const hidl_vec<SubSample>& subSamples,
52     const SharedBuffer& source,
53     uint64_t offset,
54     const DestinationBuffer& destination,
55     decrypt_cb _hidl_cb) {
56 
57   Status status = Status::ERROR_DRM_UNKNOWN;
58   hidl_string detailedError;
59   uint32_t bytesWritten = 0;
60 
61   Return<void> hResult = decrypt_1_2(
62       secure, keyId, iv, mode, pattern, subSamples, source, offset, destination,
63       [&](Status_V1_2 hStatus, uint32_t hBytesWritten, hidl_string hDetailedError) {
64         status = toStatus_1_0(hStatus);
65         if (status == Status::OK) {
66           bytesWritten = hBytesWritten;
67           detailedError = hDetailedError;
68         }
69       }
70     );
71 
72   status = hResult.isOk() ? status : Status::ERROR_DRM_CANNOT_HANDLE;
73   _hidl_cb(status, bytesWritten, detailedError);
74   return Void();
75 }
76 
77 // Returns negative values for error code and positive values for the size of
78 // decrypted data.  In theory, the output size can be larger than the input
79 // size, but in practice this will never happen for AES-CTR.
decrypt_1_2(bool secure,const hidl_array<uint8_t,KEY_ID_SIZE> & keyId,const hidl_array<uint8_t,KEY_IV_SIZE> & iv,Mode mode,const Pattern & pattern,const hidl_vec<SubSample> & subSamples,const SharedBuffer & source,uint64_t offset,const DestinationBuffer & destination,decrypt_1_2_cb _hidl_cb)80 Return<void> CryptoPlugin::decrypt_1_2(
81         bool secure,
82         const hidl_array<uint8_t, KEY_ID_SIZE>& keyId,
83         const hidl_array<uint8_t, KEY_IV_SIZE>& iv,
84         Mode mode,
85         const Pattern& pattern,
86         const hidl_vec<SubSample>& subSamples,
87         const SharedBuffer& source,
88         uint64_t offset,
89         const DestinationBuffer& destination,
90         decrypt_1_2_cb _hidl_cb) {
91     UNUSED(pattern);
92 
93     if (secure) {
94         _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0,
95             "Secure decryption is not supported with ClearKey.");
96         return Void();
97     }
98 
99     if (mSharedBufferMap.find(source.bufferId) == mSharedBufferMap.end()) {
100       _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0,
101                "source decrypt buffer base not set");
102       return Void();
103     }
104 
105     if (destination.type == BufferType::SHARED_MEMORY) {
106       const SharedBuffer& dest = destination.nonsecureMemory;
107       if (mSharedBufferMap.find(dest.bufferId) == mSharedBufferMap.end()) {
108         _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0,
109                  "destination decrypt buffer base not set");
110         return Void();
111       }
112     }
113 
114     sp<IMemory> sourceBase = mSharedBufferMap[source.bufferId];
115     if (sourceBase == nullptr) {
116         _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0, "source is a nullptr");
117         return Void();
118     }
119 
120     if (source.offset + offset + source.size > sourceBase->getSize()) {
121         _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0, "invalid buffer size");
122         return Void();
123     }
124 
125     uint8_t *base = static_cast<uint8_t *>
126             (static_cast<void *>(sourceBase->getPointer()));
127     uint8_t* srcPtr = static_cast<uint8_t *>(base + source.offset + offset);
128     void* destPtr = NULL;
129     if (destination.type == BufferType::SHARED_MEMORY) {
130         const SharedBuffer& destBuffer = destination.nonsecureMemory;
131         sp<IMemory> destBase = mSharedBufferMap[destBuffer.bufferId];
132         if (destBase == nullptr) {
133             _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0, "destination is a nullptr");
134             return Void();
135         }
136 
137         if (destBuffer.offset + destBuffer.size > destBase->getSize()) {
138             _hidl_cb(Status_V1_2::ERROR_DRM_FRAME_TOO_LARGE, 0, "invalid buffer size");
139             return Void();
140         }
141         destPtr = static_cast<void *>(base + destination.nonsecureMemory.offset);
142     } else if (destination.type == BufferType::NATIVE_HANDLE) {
143         native_handle_t *handle = const_cast<native_handle_t *>(
144         destination.secureMemory.getNativeHandle());
145         destPtr = static_cast<void *>(handle);
146     }
147 
148     // Calculate the output buffer size and determine if any subsamples are
149     // encrypted.
150     size_t destSize = 0;
151     bool haveEncryptedSubsamples = false;
152     for (size_t i = 0; i < subSamples.size(); i++) {
153         const SubSample &subSample = subSamples[i];
154         destSize += subSample.numBytesOfClearData;
155         destSize += subSample.numBytesOfEncryptedData;
156         if (subSample.numBytesOfEncryptedData > 0) {
157         haveEncryptedSubsamples = true;
158         }
159     }
160 
161     if (mode == Mode::UNENCRYPTED) {
162         if (haveEncryptedSubsamples) {
163             _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0,
164                     "Encrypted subsamples found in allegedly unencrypted data.");
165             return Void();
166         }
167 
168         size_t offset = 0;
169         for (size_t i = 0; i < subSamples.size(); ++i) {
170             const SubSample& subSample = subSamples[i];
171             if (subSample.numBytesOfClearData != 0) {
172                 memcpy(reinterpret_cast<uint8_t*>(destPtr) + offset,
173                        reinterpret_cast<const uint8_t*>(srcPtr) + offset,
174                        subSample.numBytesOfClearData);
175                 offset += subSample.numBytesOfClearData;
176             }
177         }
178 
179         _hidl_cb(Status_V1_2::OK, static_cast<ssize_t>(offset), "");
180         return Void();
181     } else if (mode == Mode::AES_CTR) {
182         size_t bytesDecrypted;
183         Status_V1_2 res = mSession->decrypt(keyId.data(), iv.data(), srcPtr,
184                 static_cast<uint8_t*>(destPtr), toVector(subSamples), &bytesDecrypted);
185         if (res == Status_V1_2::OK) {
186             _hidl_cb(Status_V1_2::OK, static_cast<ssize_t>(bytesDecrypted), "");
187             return Void();
188         } else {
189             _hidl_cb(res, 0, "Decryption Error");
190             return Void();
191         }
192     } else {
193         _hidl_cb(Status_V1_2::ERROR_DRM_CANNOT_HANDLE, 0,
194                 "Selected encryption mode is not supported by the ClearKey DRM Plugin.");
195         return Void();
196     }
197 }
198 
setMediaDrmSession(const hidl_vec<uint8_t> & sessionId)199 Return<Status> CryptoPlugin::setMediaDrmSession(
200         const hidl_vec<uint8_t>& sessionId) {
201     if (!sessionId.size()) {
202         mSession = nullptr;
203     } else {
204         mSession = SessionLibrary::get()->findSession(sessionId);
205         if (!mSession.get()) {
206             return Status::ERROR_DRM_SESSION_NOT_OPENED;
207         }
208     }
209     return Status::OK;
210 }
211 
212 } // namespace clearkey
213 } // namespace V1_2
214 } // namespace drm
215 } // namespace hardware
216 } // namespace android
217