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     // system_server loses its RECORD_AUDIO permission when a secondary
67     // user is active, but it is a core system service so let it through.
68     // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
69     if (isAudioServerOrSystemServerOrRootUid(uid)) return true;
70 
71     // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
72     // may open a record track on behalf of a client.  Note that pid may be a tid.
73     // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
74     PermissionController permissionController;
75     const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio, pid, uid);
76     if (!ok) {
77         ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
78         return false;
79     }
80 
81     String16 resolvedOpPackageName = resolveCallingPackage(
82             permissionController, opPackageName, uid);
83     if (resolvedOpPackageName.size() == 0) {
84         return false;
85     }
86 
87     AppOpsManager appOps;
88     const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
89     if (start) {
90         if (appOps.startOpNoThrow(op, uid, resolvedOpPackageName, /*startIfModeDefault*/ false)
91                 != AppOpsManager::MODE_ALLOWED) {
92             ALOGE("Request denied by app op: %d", op);
93             return false;
94         }
95     } else {
96         if (appOps.checkOp(op, uid, resolvedOpPackageName) != AppOpsManager::MODE_ALLOWED) {
97             ALOGE("Request denied by app op: %d", op);
98             return false;
99         }
100     }
101 
102     return true;
103 }
104 
recordingAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)105 bool recordingAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
106     return checkRecordingInternal(opPackageName, pid, uid, /*start*/ false);
107 }
108 
startRecording(const String16 & opPackageName,pid_t pid,uid_t uid)109 bool startRecording(const String16& opPackageName, pid_t pid, uid_t uid) {
110      return checkRecordingInternal(opPackageName, pid, uid, /*start*/ true);
111 }
112 
finishRecording(const String16 & opPackageName,uid_t uid)113 void finishRecording(const String16& opPackageName, uid_t uid) {
114     // Okay to not track in app ops as audio server is us and if
115     // device is rooted security model is considered compromised.
116     if (isAudioServerOrRootUid(uid)) return;
117 
118     PermissionController permissionController;
119     String16 resolvedOpPackageName = resolveCallingPackage(
120             permissionController, opPackageName, uid);
121     if (resolvedOpPackageName.size() == 0) {
122         return;
123     }
124 
125     AppOpsManager appOps;
126     const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
127     appOps.finishOp(op, uid, resolvedOpPackageName);
128 }
129 
captureAudioOutputAllowed(pid_t pid,uid_t uid)130 bool captureAudioOutputAllowed(pid_t pid, uid_t uid) {
131     if (isAudioServerOrRootUid(uid)) return true;
132     static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
133     bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
134     if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
135     return ok;
136 }
137 
captureMediaOutputAllowed(pid_t pid,uid_t uid)138 bool captureMediaOutputAllowed(pid_t pid, uid_t uid) {
139     if (isAudioServerOrRootUid(uid)) return true;
140     static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
141     bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
142     if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
143     return ok;
144 }
145 
captureHotwordAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)146 bool captureHotwordAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
147     // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
148     bool ok = recordingAllowed(opPackageName, pid, uid);
149 
150     if (ok) {
151         static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
152         // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
153         ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
154     }
155     if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
156     return ok;
157 }
158 
settingsAllowed()159 bool settingsAllowed() {
160     // given this is a permission check, could this be isAudioServerOrRootUid()?
161     if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
162     static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
163     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
164     bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
165     if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
166     return ok;
167 }
168 
modifyAudioRoutingAllowed()169 bool modifyAudioRoutingAllowed() {
170     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
171     bool ok = PermissionCache::checkCallingPermission(sModifyAudioRouting);
172     if (!ok) ALOGE("android.permission.MODIFY_AUDIO_ROUTING");
173     return ok;
174 }
175 
modifyDefaultAudioEffectsAllowed()176 bool modifyDefaultAudioEffectsAllowed() {
177     return modifyDefaultAudioEffectsAllowed(
178         IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
179 }
180 
modifyDefaultAudioEffectsAllowed(pid_t pid,uid_t uid)181 bool modifyDefaultAudioEffectsAllowed(pid_t pid, uid_t uid) {
182     if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
183 
184     static const String16 sModifyDefaultAudioEffectsAllowed(
185             "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
186     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
187     bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
188     ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
189             __func__, uid);
190     return ok;
191 }
192 
dumpAllowed()193 bool dumpAllowed() {
194     static const String16 sDump("android.permission.DUMP");
195     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
196     bool ok = PermissionCache::checkCallingPermission(sDump);
197     // convention is for caller to dump an error message to fd instead of logging here
198     //if (!ok) ALOGE("Request requires android.permission.DUMP");
199     return ok;
200 }
201 
modifyPhoneStateAllowed(pid_t pid,uid_t uid)202 bool modifyPhoneStateAllowed(pid_t pid, uid_t uid) {
203     bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
204     ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
205     return ok;
206 }
207 
208 // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
bypassInterruptionPolicyAllowed(pid_t pid,uid_t uid)209 bool bypassInterruptionPolicyAllowed(pid_t pid, uid_t uid) {
210     static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
211     bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
212         || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
213         || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
214     ALOGE_IF(!ok, "Request requires %s or %s",
215              String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
216     return ok;
217 }
218 
checkIMemory(const sp<IMemory> & iMemory)219 status_t checkIMemory(const sp<IMemory>& iMemory)
220 {
221     if (iMemory == 0) {
222         ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
223         return BAD_VALUE;
224     }
225 
226     sp<IMemoryHeap> heap = iMemory->getMemory();
227     if (heap == 0) {
228         ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
229         return BAD_VALUE;
230     }
231 
232     off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
233     lseek(heap->getHeapID(), 0, SEEK_SET);
234 
235     if (iMemory->pointer() == NULL || size < (off_t)iMemory->size()) {
236         ALOGE("%s check failed: pointer %p size %zu fd size %u",
237               __FUNCTION__, iMemory->pointer(), iMemory->size(), (uint32_t)size);
238         return BAD_VALUE;
239     }
240 
241     return NO_ERROR;
242 }
243 
retreivePackageManager()244 sp<content::pm::IPackageManagerNative> MediaPackageManager::retreivePackageManager() {
245     const sp<IServiceManager> sm = defaultServiceManager();
246     if (sm == nullptr) {
247         ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
248         return nullptr;
249     }
250     sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
251     if (packageManager == nullptr) {
252         ALOGW("%s: failed to retrieve native package manager", __func__);
253         return nullptr;
254     }
255     return interface_cast<content::pm::IPackageManagerNative>(packageManager);
256 }
257 
doIsAllowed(uid_t uid)258 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
259     if (mPackageManager == nullptr) {
260         /** Can not fetch package manager at construction it may not yet be registered. */
261         mPackageManager = retreivePackageManager();
262         if (mPackageManager == nullptr) {
263             ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
264             return std::nullopt;
265         }
266     }
267 
268     std::vector<std::string> packageNames;
269     auto status = mPackageManager->getNamesForUids({(int32_t)uid}, &packageNames);
270     if (!status.isOk()) {
271         ALOGW("%s: Playback capture is denied for uid %u as the package names could not be "
272               "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
273         return std::nullopt;
274     }
275     if (packageNames.empty()) {
276         ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
277               "from the package manager: %s", __func__, uid, status.toString8().c_str());
278         return std::nullopt;
279     }
280     std::vector<bool> isAllowed;
281     status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
282     if (!status.isOk()) {
283         ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
284               "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
285         return std::nullopt;
286     }
287     if (packageNames.size() != isAllowed.size()) {
288         ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
289               " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
290         return std::nullopt;
291     }
292 
293     // Zip together packageNames and isAllowed for debug logs
294     Packages& packages = mDebugLog[uid];
295     packages.resize(packageNames.size()); // Reuse all objects
296     std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
297                    begin(packages), [] (auto& name, bool isAllowed) -> Package {
298                        return {std::move(name), isAllowed};
299                    });
300 
301     // Only allow playback record if all packages in this UID allow it
302     bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
303                                                   [](bool b) { return b; });
304 
305     return playbackCaptureAllowed;
306 }
307 
dump(int fd,int spaces) const308 void MediaPackageManager::dump(int fd, int spaces) const {
309     dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
310     if (mPackageManager == nullptr) {
311         dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
312     }
313     dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
314 
315     for (const auto& uidCache : mDebugLog) {
316         for (const auto& package : std::get<Packages>(uidCache)) {
317             dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
318                     std::get<const uid_t>(uidCache),
319                     package.playbackCaptureAllowed ? "true " : "false",
320                     package.name.c_str());
321         }
322     }
323 }
324 
325 } // namespace android
326