1 /*
2 * Copyright (C) 2012 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_TAG "ServiceUtilities"
18
19 #include <binder/AppOpsManager.h>
20 #include <binder/IPCThreadState.h>
21 #include <binder/IServiceManager.h>
22 #include <binder/PermissionCache.h>
23 #include "mediautils/ServiceUtilities.h"
24
25 #include <iterator>
26 #include <algorithm>
27
28 /* When performing permission checks we do not use permission cache for
29 * runtime permissions (protection level dangerous) as they may change at
30 * runtime. All other permissions (protection level normal and dangerous)
31 * can be cached as they never change. Of course all permission checked
32 * here are platform defined.
33 */
34
35 namespace android {
36
37 static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
38 static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
39 static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
40
resolveCallingPackage(PermissionController & permissionController,const String16 & opPackageName,uid_t uid)41 static String16 resolveCallingPackage(PermissionController& permissionController,
42 const String16& opPackageName, uid_t uid) {
43 if (opPackageName.size() > 0) {
44 return opPackageName;
45 }
46 // In some cases the calling code has no access to the package it runs under.
47 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
48 // case we will get the packages for the calling UID and pick the first one
49 // for attributing the app op. This will work correctly for runtime permissions
50 // as for legacy apps we will toggle the app op for all packages in the UID.
51 // The caveat is that the operation may be attributed to the wrong package and
52 // stats based on app ops may be slightly off.
53 Vector<String16> packages;
54 permissionController.getPackagesForUid(uid, packages);
55 if (packages.isEmpty()) {
56 ALOGE("No packages for uid %d", uid);
57 return opPackageName; // empty string
58 }
59 return packages[0];
60 }
61
checkRecordingInternal(const String16 & opPackageName,pid_t pid,uid_t uid,bool start)62 static bool checkRecordingInternal(const String16& opPackageName, pid_t pid,
63 uid_t uid, bool start) {
64 // Okay to not track in app ops as audio server is us and if
65 // device is rooted security model is considered compromised.
66 if (isAudioServerOrRootUid(uid)) return true;
67
68 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
69 // may open a record track on behalf of a client. Note that pid may be a tid.
70 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
71 PermissionController permissionController;
72 const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio, pid, uid);
73 if (!ok) {
74 ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
75 return false;
76 }
77
78 String16 resolvedOpPackageName = resolveCallingPackage(
79 permissionController, opPackageName, uid);
80 if (resolvedOpPackageName.size() == 0) {
81 return false;
82 }
83
84 AppOpsManager appOps;
85 const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
86 if (start) {
87 if (appOps.startOpNoThrow(op, uid, resolvedOpPackageName, /*startIfModeDefault*/ false)
88 != AppOpsManager::MODE_ALLOWED) {
89 ALOGE("Request denied by app op: %d", op);
90 return false;
91 }
92 } else {
93 if (appOps.checkOp(op, uid, resolvedOpPackageName) != AppOpsManager::MODE_ALLOWED) {
94 ALOGE("Request denied by app op: %d", op);
95 return false;
96 }
97 }
98
99 return true;
100 }
101
recordingAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)102 bool recordingAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
103 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ false);
104 }
105
startRecording(const String16 & opPackageName,pid_t pid,uid_t uid)106 bool startRecording(const String16& opPackageName, pid_t pid, uid_t uid) {
107 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ true);
108 }
109
finishRecording(const String16 & opPackageName,uid_t uid)110 void finishRecording(const String16& opPackageName, uid_t uid) {
111 // Okay to not track in app ops as audio server is us and if
112 // device is rooted security model is considered compromised.
113 if (isAudioServerOrRootUid(uid)) return;
114
115 PermissionController permissionController;
116 String16 resolvedOpPackageName = resolveCallingPackage(
117 permissionController, opPackageName, uid);
118 if (resolvedOpPackageName.size() == 0) {
119 return;
120 }
121
122 AppOpsManager appOps;
123 const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
124 appOps.finishOp(op, uid, resolvedOpPackageName);
125 }
126
captureAudioOutputAllowed(pid_t pid,uid_t uid)127 bool captureAudioOutputAllowed(pid_t pid, uid_t uid) {
128 if (isAudioServerOrRootUid(uid)) return true;
129 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
130 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
131 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
132 return ok;
133 }
134
captureMediaOutputAllowed(pid_t pid,uid_t uid)135 bool captureMediaOutputAllowed(pid_t pid, uid_t uid) {
136 if (isAudioServerOrRootUid(uid)) return true;
137 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
138 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
139 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
140 return ok;
141 }
142
captureHotwordAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)143 bool captureHotwordAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
144 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
145 bool ok = recordingAllowed(opPackageName, pid, uid);
146
147 if (ok) {
148 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
149 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
150 ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
151 }
152 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
153 return ok;
154 }
155
settingsAllowed()156 bool settingsAllowed() {
157 // given this is a permission check, could this be isAudioServerOrRootUid()?
158 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
159 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
160 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
161 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
162 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
163 return ok;
164 }
165
modifyAudioRoutingAllowed()166 bool modifyAudioRoutingAllowed() {
167 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
168 bool ok = PermissionCache::checkCallingPermission(sModifyAudioRouting);
169 if (!ok) ALOGE("android.permission.MODIFY_AUDIO_ROUTING");
170 return ok;
171 }
172
modifyDefaultAudioEffectsAllowed()173 bool modifyDefaultAudioEffectsAllowed() {
174 static const String16 sModifyDefaultAudioEffectsAllowed(
175 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
176 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
177 bool ok = PermissionCache::checkCallingPermission(sModifyDefaultAudioEffectsAllowed);
178
179 #ifdef TARGET_ANDROID_THINGS
180 if (!ok) {
181 // Use a secondary permission on Android Things to allow a more lenient level of protection.
182 static const String16 sModifyDefaultAudioEffectsAndroidThingsAllowed(
183 "com.google.android.things.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
184 ok = PermissionCache::checkCallingPermission(
185 sModifyDefaultAudioEffectsAndroidThingsAllowed);
186 }
187 if (!ok) ALOGE("com.google.android.things.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
188 #else
189 if (!ok) ALOGE("android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
190 #endif
191 return ok;
192 }
193
dumpAllowed()194 bool dumpAllowed() {
195 static const String16 sDump("android.permission.DUMP");
196 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
197 bool ok = PermissionCache::checkCallingPermission(sDump);
198 // convention is for caller to dump an error message to fd instead of logging here
199 //if (!ok) ALOGE("Request requires android.permission.DUMP");
200 return ok;
201 }
202
modifyPhoneStateAllowed(pid_t pid,uid_t uid)203 bool modifyPhoneStateAllowed(pid_t pid, uid_t uid) {
204 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
205 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
206 return ok;
207 }
208
209 // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
bypassInterruptionPolicyAllowed(pid_t pid,uid_t uid)210 bool bypassInterruptionPolicyAllowed(pid_t pid, uid_t uid) {
211 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
212 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
213 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
214 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
215 ALOGE_IF(!ok, "Request requires %s or %s",
216 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
217 return ok;
218 }
219
checkIMemory(const sp<IMemory> & iMemory)220 status_t checkIMemory(const sp<IMemory>& iMemory)
221 {
222 if (iMemory == 0) {
223 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
224 return BAD_VALUE;
225 }
226
227 sp<IMemoryHeap> heap = iMemory->getMemory();
228 if (heap == 0) {
229 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
230 return BAD_VALUE;
231 }
232
233 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
234 lseek(heap->getHeapID(), 0, SEEK_SET);
235
236 if (iMemory->pointer() == NULL || size < (off_t)iMemory->size()) {
237 ALOGE("%s check failed: pointer %p size %zu fd size %u",
238 __FUNCTION__, iMemory->pointer(), iMemory->size(), (uint32_t)size);
239 return BAD_VALUE;
240 }
241
242 return NO_ERROR;
243 }
244
retreivePackageManager()245 sp<content::pm::IPackageManagerNative> MediaPackageManager::retreivePackageManager() {
246 const sp<IServiceManager> sm = defaultServiceManager();
247 if (sm == nullptr) {
248 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
249 return nullptr;
250 }
251 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
252 if (packageManager == nullptr) {
253 ALOGW("%s: failed to retrieve native package manager", __func__);
254 return nullptr;
255 }
256 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
257 }
258
doIsAllowed(uid_t uid)259 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
260 if (mPackageManager == nullptr) {
261 /** Can not fetch package manager at construction it may not yet be registered. */
262 mPackageManager = retreivePackageManager();
263 if (mPackageManager == nullptr) {
264 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
265 return std::nullopt;
266 }
267 }
268
269 std::vector<std::string> packageNames;
270 auto status = mPackageManager->getNamesForUids({(int32_t)uid}, &packageNames);
271 if (!status.isOk()) {
272 ALOGW("%s: Playback capture is denied for uid %u as the package names could not be "
273 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
274 return std::nullopt;
275 }
276 if (packageNames.empty()) {
277 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
278 "from the package manager: %s", __func__, uid, status.toString8().c_str());
279 return std::nullopt;
280 }
281 std::vector<bool> isAllowed;
282 status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
283 if (!status.isOk()) {
284 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
285 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
286 return std::nullopt;
287 }
288 if (packageNames.size() != isAllowed.size()) {
289 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
290 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
291 return std::nullopt;
292 }
293
294 // Zip together packageNames and isAllowed for debug logs
295 Packages& packages = mDebugLog[uid];
296 packages.resize(packageNames.size()); // Reuse all objects
297 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
298 begin(packages), [] (auto& name, bool isAllowed) -> Package {
299 return {std::move(name), isAllowed};
300 });
301
302 // Only allow playback record if all packages in this UID allow it
303 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
304 [](bool b) { return b; });
305
306 return playbackCaptureAllowed;
307 }
308
dump(int fd,int spaces) const309 void MediaPackageManager::dump(int fd, int spaces) const {
310 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
311 if (mPackageManager == nullptr) {
312 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
313 }
314 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
315
316 for (const auto& uidCache : mDebugLog) {
317 for (const auto& package : std::get<Packages>(uidCache)) {
318 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
319 std::get<const uid_t>(uidCache),
320 package.playbackCaptureAllowed ? "true " : "false",
321 package.name.c_str());
322 }
323 }
324 }
325
326 } // namespace android
327