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 <audio_utils/clock.h>
20 #include <binder/AppOpsManager.h>
21 #include <binder/IPCThreadState.h>
22 #include <binder/IServiceManager.h>
23 #include <binder/PermissionCache.h>
24 #include "mediautils/ServiceUtilities.h"
25
26 #include <iterator>
27 #include <algorithm>
28 #include <pwd.h>
29
30 /* When performing permission checks we do not use permission cache for
31 * runtime permissions (protection level dangerous) as they may change at
32 * runtime. All other permissions (protection level normal and dangerous)
33 * can be cached as they never change. Of course all permission checked
34 * here are platform defined.
35 */
36
37 namespace android {
38
39 static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
40 static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
41 static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
42
resolveCallingPackage(PermissionController & permissionController,const String16 & opPackageName,uid_t uid)43 static String16 resolveCallingPackage(PermissionController& permissionController,
44 const String16& opPackageName, uid_t uid) {
45 if (opPackageName.size() > 0) {
46 return opPackageName;
47 }
48 // In some cases the calling code has no access to the package it runs under.
49 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
50 // case we will get the packages for the calling UID and pick the first one
51 // for attributing the app op. This will work correctly for runtime permissions
52 // as for legacy apps we will toggle the app op for all packages in the UID.
53 // The caveat is that the operation may be attributed to the wrong package and
54 // stats based on app ops may be slightly off.
55 Vector<String16> packages;
56 permissionController.getPackagesForUid(uid, packages);
57 if (packages.isEmpty()) {
58 ALOGE("No packages for uid %d", uid);
59 return opPackageName; // empty string
60 }
61 return packages[0];
62 }
63
checkRecordingInternal(const String16 & opPackageName,pid_t pid,uid_t uid,bool start)64 static bool checkRecordingInternal(const String16& opPackageName, pid_t pid,
65 uid_t uid, bool start) {
66 // Okay to not track in app ops as audio server or media server is us and if
67 // device is rooted security model is considered compromised.
68 // system_server loses its RECORD_AUDIO permission when a secondary
69 // user is active, but it is a core system service so let it through.
70 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
71 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
72
73 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
74 // may open a record track on behalf of a client. Note that pid may be a tid.
75 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
76 PermissionController permissionController;
77 const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio, pid, uid);
78 if (!ok) {
79 ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
80 return false;
81 }
82
83 String16 resolvedOpPackageName = resolveCallingPackage(
84 permissionController, opPackageName, uid);
85 if (resolvedOpPackageName.size() == 0) {
86 return false;
87 }
88
89 AppOpsManager appOps;
90 const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
91 if (start) {
92 if (appOps.startOpNoThrow(op, uid, resolvedOpPackageName, /*startIfModeDefault*/ false)
93 != AppOpsManager::MODE_ALLOWED) {
94 ALOGE("Request denied by app op: %d", op);
95 return false;
96 }
97 } else {
98 if (appOps.checkOp(op, uid, resolvedOpPackageName) != AppOpsManager::MODE_ALLOWED) {
99 ALOGE("Request denied by app op: %d", op);
100 return false;
101 }
102 }
103
104 return true;
105 }
106
recordingAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)107 bool recordingAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
108 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ false);
109 }
110
startRecording(const String16 & opPackageName,pid_t pid,uid_t uid)111 bool startRecording(const String16& opPackageName, pid_t pid, uid_t uid) {
112 return checkRecordingInternal(opPackageName, pid, uid, /*start*/ true);
113 }
114
finishRecording(const String16 & opPackageName,uid_t uid)115 void finishRecording(const String16& opPackageName, uid_t uid) {
116 // Okay to not track in app ops as audio server is us and if
117 // device is rooted security model is considered compromised.
118 if (isAudioServerOrRootUid(uid)) return;
119
120 PermissionController permissionController;
121 String16 resolvedOpPackageName = resolveCallingPackage(
122 permissionController, opPackageName, uid);
123 if (resolvedOpPackageName.size() == 0) {
124 return;
125 }
126
127 AppOpsManager appOps;
128 const int32_t op = appOps.permissionToOpCode(sAndroidPermissionRecordAudio);
129 appOps.finishOp(op, uid, resolvedOpPackageName);
130 }
131
captureAudioOutputAllowed(pid_t pid,uid_t uid)132 bool captureAudioOutputAllowed(pid_t pid, uid_t uid) {
133 if (isAudioServerOrRootUid(uid)) return true;
134 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
135 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
136 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
137 return ok;
138 }
139
captureMediaOutputAllowed(pid_t pid,uid_t uid)140 bool captureMediaOutputAllowed(pid_t pid, uid_t uid) {
141 if (isAudioServerOrRootUid(uid)) return true;
142 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
143 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
144 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
145 return ok;
146 }
147
captureVoiceCommunicationOutputAllowed(pid_t pid,uid_t uid)148 bool captureVoiceCommunicationOutputAllowed(pid_t pid, uid_t uid) {
149 if (isAudioServerOrRootUid(uid)) return true;
150 static const String16 sCaptureVoiceCommOutput(
151 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
152 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
153 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
154 return ok;
155 }
156
captureHotwordAllowed(const String16 & opPackageName,pid_t pid,uid_t uid)157 bool captureHotwordAllowed(const String16& opPackageName, pid_t pid, uid_t uid) {
158 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
159 bool ok = recordingAllowed(opPackageName, pid, uid);
160
161 if (ok) {
162 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
163 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
164 ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
165 }
166 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
167 return ok;
168 }
169
settingsAllowed()170 bool settingsAllowed() {
171 // given this is a permission check, could this be isAudioServerOrRootUid()?
172 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
173 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
174 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
175 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
176 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
177 return ok;
178 }
179
modifyAudioRoutingAllowed()180 bool modifyAudioRoutingAllowed() {
181 return modifyAudioRoutingAllowed(
182 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
183 }
184
modifyAudioRoutingAllowed(pid_t pid,uid_t uid)185 bool modifyAudioRoutingAllowed(pid_t pid, uid_t uid) {
186 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
187 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
188 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
189 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
190 __func__, uid);
191 return ok;
192 }
193
modifyDefaultAudioEffectsAllowed()194 bool modifyDefaultAudioEffectsAllowed() {
195 return modifyDefaultAudioEffectsAllowed(
196 IPCThreadState::self()->getCallingPid(), IPCThreadState::self()->getCallingUid());
197 }
198
modifyDefaultAudioEffectsAllowed(pid_t pid,uid_t uid)199 bool modifyDefaultAudioEffectsAllowed(pid_t pid, uid_t uid) {
200 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
201
202 static const String16 sModifyDefaultAudioEffectsAllowed(
203 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
204 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
205 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
206 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
207 __func__, uid);
208 return ok;
209 }
210
dumpAllowed()211 bool dumpAllowed() {
212 static const String16 sDump("android.permission.DUMP");
213 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
214 bool ok = PermissionCache::checkCallingPermission(sDump);
215 // convention is for caller to dump an error message to fd instead of logging here
216 //if (!ok) ALOGE("Request requires android.permission.DUMP");
217 return ok;
218 }
219
modifyPhoneStateAllowed(pid_t pid,uid_t uid)220 bool modifyPhoneStateAllowed(pid_t pid, uid_t uid) {
221 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
222 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
223 return ok;
224 }
225
226 // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
bypassInterruptionPolicyAllowed(pid_t pid,uid_t uid)227 bool bypassInterruptionPolicyAllowed(pid_t pid, uid_t uid) {
228 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
229 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
230 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
231 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
232 ALOGE_IF(!ok, "Request requires %s or %s",
233 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
234 return ok;
235 }
236
checkIMemory(const sp<IMemory> & iMemory)237 status_t checkIMemory(const sp<IMemory>& iMemory)
238 {
239 if (iMemory == 0) {
240 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
241 return BAD_VALUE;
242 }
243
244 sp<IMemoryHeap> heap = iMemory->getMemory();
245 if (heap == 0) {
246 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
247 return BAD_VALUE;
248 }
249
250 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
251 lseek(heap->getHeapID(), 0, SEEK_SET);
252
253 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
254 ALOGE("%s check failed: pointer %p size %zu fd size %u",
255 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
256 return BAD_VALUE;
257 }
258
259 return NO_ERROR;
260 }
261
retreivePackageManager()262 sp<content::pm::IPackageManagerNative> MediaPackageManager::retreivePackageManager() {
263 const sp<IServiceManager> sm = defaultServiceManager();
264 if (sm == nullptr) {
265 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
266 return nullptr;
267 }
268 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
269 if (packageManager == nullptr) {
270 ALOGW("%s: failed to retrieve native package manager", __func__);
271 return nullptr;
272 }
273 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
274 }
275
doIsAllowed(uid_t uid)276 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
277 if (mPackageManager == nullptr) {
278 /** Can not fetch package manager at construction it may not yet be registered. */
279 mPackageManager = retreivePackageManager();
280 if (mPackageManager == nullptr) {
281 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
282 return std::nullopt;
283 }
284 }
285
286 std::vector<std::string> packageNames;
287 auto status = mPackageManager->getNamesForUids({(int32_t)uid}, &packageNames);
288 if (!status.isOk()) {
289 ALOGW("%s: Playback capture is denied for uid %u as the package names could not be "
290 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
291 return std::nullopt;
292 }
293 if (packageNames.empty()) {
294 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
295 "from the package manager: %s", __func__, uid, status.toString8().c_str());
296 return std::nullopt;
297 }
298 std::vector<bool> isAllowed;
299 status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
300 if (!status.isOk()) {
301 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
302 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
303 return std::nullopt;
304 }
305 if (packageNames.size() != isAllowed.size()) {
306 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
307 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
308 return std::nullopt;
309 }
310
311 // Zip together packageNames and isAllowed for debug logs
312 Packages& packages = mDebugLog[uid];
313 packages.resize(packageNames.size()); // Reuse all objects
314 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
315 begin(packages), [] (auto& name, bool isAllowed) -> Package {
316 return {std::move(name), isAllowed};
317 });
318
319 // Only allow playback record if all packages in this UID allow it
320 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
321 [](bool b) { return b; });
322
323 return playbackCaptureAllowed;
324 }
325
dump(int fd,int spaces) const326 void MediaPackageManager::dump(int fd, int spaces) const {
327 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
328 if (mPackageManager == nullptr) {
329 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
330 }
331 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
332
333 for (const auto& uidCache : mDebugLog) {
334 for (const auto& package : std::get<Packages>(uidCache)) {
335 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
336 std::get<const uid_t>(uidCache),
337 package.playbackCaptureAllowed ? "true " : "false",
338 package.name.c_str());
339 }
340 }
341 }
342
343 // How long we hold info before we re-fetch it (24 hours) if we found it previously.
344 static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
345 // Maximum info records we retain before clearing everything.
346 static constexpr size_t INFO_CACHE_MAX = 1000;
347
348 // The original code is from MediaMetricsService.cpp.
getInfo(uid_t uid)349 mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
350 {
351 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
352 struct mediautils::UidInfo::Info info;
353 {
354 std::lock_guard _l(mLock);
355 auto it = mInfoMap.find(uid);
356 if (it != mInfoMap.end()) {
357 info = it->second;
358 ALOGV("%s: uid %d expiration %lld now %lld",
359 __func__, uid, (long long)info.expirationNs, (long long)now);
360 if (info.expirationNs <= now) {
361 // purge the stale entry and fall into re-fetching
362 ALOGV("%s: entry for uid %d expired, now %lld",
363 __func__, uid, (long long)now);
364 mInfoMap.erase(it);
365 info.uid = (uid_t)-1; // this is always fully overwritten
366 }
367 }
368 }
369
370 // if we did not find it in our map, look it up
371 if (info.uid == (uid_t)(-1)) {
372 sp<IServiceManager> sm = defaultServiceManager();
373 sp<content::pm::IPackageManagerNative> package_mgr;
374 if (sm.get() == nullptr) {
375 ALOGE("%s: Cannot find service manager", __func__);
376 } else {
377 sp<IBinder> binder = sm->getService(String16("package_native"));
378 if (binder.get() == nullptr) {
379 ALOGE("%s: Cannot find package_native", __func__);
380 } else {
381 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
382 }
383 }
384
385 // find package name
386 std::string pkg;
387 if (package_mgr != nullptr) {
388 std::vector<std::string> names;
389 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
390 if (!status.isOk()) {
391 ALOGE("%s: getNamesForUids failed: %s",
392 __func__, status.exceptionMessage().c_str());
393 } else {
394 if (!names[0].empty()) {
395 pkg = names[0].c_str();
396 }
397 }
398 }
399
400 if (pkg.empty()) {
401 struct passwd pw{}, *result;
402 char buf[8192]; // extra buffer space - should exceed what is
403 // required in struct passwd_pw (tested),
404 // and even then this is only used in backup
405 // when the package manager is unavailable.
406 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
407 && result != nullptr
408 && result->pw_name != nullptr) {
409 pkg = result->pw_name;
410 }
411 }
412
413 // strip any leading "shared:" strings that came back
414 if (pkg.compare(0, 7, "shared:") == 0) {
415 pkg.erase(0, 7);
416 }
417
418 // determine how pkg was installed and the versionCode
419 std::string installer;
420 int64_t versionCode = 0;
421 bool notFound = false;
422 if (pkg.empty()) {
423 pkg = std::to_string(uid); // not found
424 notFound = true;
425 } else if (strchr(pkg.c_str(), '.') == nullptr) {
426 // not of form 'com.whatever...'; assume internal
427 // so we don't need to look it up in package manager.
428 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
429 // android.* packages are assumed fine
430 } else if (package_mgr.get() != nullptr) {
431 String16 pkgName16(pkg.c_str());
432 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
433 if (!status.isOk()) {
434 ALOGE("%s: getInstallerForPackage failed: %s",
435 __func__, status.exceptionMessage().c_str());
436 }
437
438 // skip if we didn't get an installer
439 if (status.isOk()) {
440 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
441 if (!status.isOk()) {
442 ALOGE("%s: getVersionCodeForPackage failed: %s",
443 __func__, status.exceptionMessage().c_str());
444 }
445 }
446
447 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
448 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
449 }
450
451 // add it to the map, to save a subsequent lookup
452 std::lock_guard _l(mLock);
453 // first clear if we have too many cached elements. This would be rare.
454 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
455
456 // always overwrite
457 info.uid = uid;
458 info.package = std::move(pkg);
459 info.installer = std::move(installer);
460 info.versionCode = versionCode;
461 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
462 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
463 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
464 mInfoMap[uid] = info;
465 }
466 return info;
467 }
468
469 } // namespace android
470