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