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 <android-base/properties.h>
22 #include <binder/AppOpsManager.h>
23 #include <binder/IPCThreadState.h>
24 #include <binder/IServiceManager.h>
25 #include <binder/PermissionCache.h>
26 #include "mediautils/ServiceUtilities.h"
27 #include <system/audio-hal-enums.h>
28 #include <media/AidlConversion.h>
29 #include <media/AidlConversionUtil.h>
30 #include <android/content/AttributionSourceState.h>
31
32 #include <algorithm>
33 #include <iterator>
34 #include <mutex>
35 #include <pwd.h>
36 #include <thread>
37
38 /* When performing permission checks we do not use permission cache for
39 * runtime permissions (protection level dangerous) as they may change at
40 * runtime. All other permissions (protection level normal and dangerous)
41 * can be cached as they never change. Of course all permission checked
42 * here are platform defined.
43 */
44
45 namespace android {
46
47 namespace {
48 constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
49 constexpr auto PERMISSION_HARD_DENIED = permission::PermissionChecker::PERMISSION_HARD_DENIED;
50 }
51
52 using content::AttributionSourceState;
53
54 static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
55 static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
56 static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
57 static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
58 static const String16 sModifyAudioSettingsPrivileged(
59 "android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED");
60
resolveCallingPackage(PermissionController & permissionController,const std::optional<String16> opPackageName,uid_t uid)61 static String16 resolveCallingPackage(PermissionController& permissionController,
62 const std::optional<String16> opPackageName, uid_t uid) {
63 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
64 return opPackageName.value();
65 }
66 // In some cases the calling code has no access to the package it runs under.
67 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
68 // case we will get the packages for the calling UID and pick the first one
69 // for attributing the app op. This will work correctly for runtime permissions
70 // as for legacy apps we will toggle the app op for all packages in the UID.
71 // The caveat is that the operation may be attributed to the wrong package and
72 // stats based on app ops may be slightly off.
73 Vector<String16> packages;
74 permissionController.getPackagesForUid(uid, packages);
75 if (packages.isEmpty()) {
76 ALOGE("No packages for uid %d", uid);
77 return String16();
78 }
79 return packages[0];
80 }
81
82 // NOTE/TODO(b/379754682):
83 // AUDIO_SOURCE_VOICE_CALL is handled specially:
84 // CALL includes both uplink and downlink, but we attribute RECORD_OP (only), since
85 // there is not support for noting multiple ops.
getOpForSource(audio_source_t source)86 int32_t getOpForSource(audio_source_t source) {
87 switch (source) {
88 // BEGIN output sources
89 case AUDIO_SOURCE_FM_TUNER:
90 return AppOpsManager::OP_NONE;
91 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
92 case AUDIO_SOURCE_REMOTE_SUBMIX:
93 // TODO -- valid in all cases?
94 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
95 case AUDIO_SOURCE_VOICE_DOWNLINK:
96 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
97 // END output sources
98 case AUDIO_SOURCE_HOTWORD:
99 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
100 case AUDIO_SOURCE_DEFAULT:
101 default:
102 return AppOpsManager::OP_RECORD_AUDIO;
103 }
104 }
105
isRecordOpRequired(audio_source_t source)106 bool isRecordOpRequired(audio_source_t source) {
107 switch (source) {
108 case AUDIO_SOURCE_FM_TUNER:
109 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
110 case AUDIO_SOURCE_REMOTE_SUBMIX:
111 case AUDIO_SOURCE_VOICE_DOWNLINK:
112 return false;
113 default:
114 return true;
115 }
116 }
117
resolveAttributionSource(const AttributionSourceState & callerAttributionSource,const uint32_t virtualDeviceId)118 std::optional<AttributionSourceState> resolveAttributionSource(
119 const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
120 AttributionSourceState nextAttributionSource = callerAttributionSource;
121
122 if (!nextAttributionSource.packageName.has_value()) {
123 nextAttributionSource = AttributionSourceState(nextAttributionSource);
124 PermissionController permissionController;
125 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
126 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
127 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
128 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
129 uid)));
130 if (!nextAttributionSource.packageName.has_value()) {
131 return std::nullopt;
132 }
133 }
134 nextAttributionSource.deviceId = virtualDeviceId;
135
136 AttributionSourceState myAttributionSource;
137 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
138 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
139 // Create a static token for audioserver requests, which identifies the
140 // audioserver to the app ops system
141 static sp<BBinder> appOpsToken = sp<BBinder>::make();
142 myAttributionSource.token = appOpsToken;
143 myAttributionSource.deviceId = virtualDeviceId;
144 myAttributionSource.next.push_back(nextAttributionSource);
145
146 return std::optional<AttributionSourceState>{myAttributionSource};
147 }
148
149
checkRecordingInternal(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,const String16 & msg,bool start,audio_source_t source)150 static int checkRecordingInternal(const AttributionSourceState &attributionSource,
151 const uint32_t virtualDeviceId,
152 const String16 &msg, bool start, audio_source_t source) {
153 // Okay to not track in app ops as audio server or media server is us and if
154 // device is rooted security model is considered compromised.
155 // system_server loses its RECORD_AUDIO permission when a secondary
156 // user is active, but it is a core system service so let it through.
157 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
158 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
159 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return PERMISSION_GRANTED;
160
161 const int32_t attributedOpCode = getOpForSource(source);
162 if (isRecordOpRequired(source)) {
163 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
164 // may open a record track on behalf of a client. Note that pid may be a tid.
165 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
166 std::optional<AttributionSourceState> resolvedAttributionSource =
167 resolveAttributionSource(attributionSource, virtualDeviceId);
168 if (!resolvedAttributionSource.has_value()) {
169 return PERMISSION_HARD_DENIED;
170 }
171
172 permission::PermissionChecker permissionChecker;
173 int permitted;
174 if (start) {
175 permitted = permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
176 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
177 attributedOpCode);
178 } else {
179 permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
180 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
181 attributedOpCode);
182 }
183
184 return permitted;
185 } else {
186 if (attributedOpCode == AppOpsManager::OP_NONE) return PERMISSION_GRANTED; // nothing to do
187 AppOpsManager ap{};
188 PermissionController pc{};
189 return ap.startOpNoThrow(
190 attributedOpCode, attributionSource.uid,
191 resolveCallingPackage(pc,
192 String16{attributionSource.packageName.value_or("").c_str()},
193 attributionSource.uid),
194 false,
195 attributionSource.attributionTag.has_value()
196 ? String16{attributionSource.attributionTag.value().c_str()}
197 : String16{},
198 msg);
199 }
200 }
201
202 static constexpr int DEVICE_ID_DEFAULT = 0;
203
recordingAllowed(const AttributionSourceState & attributionSource,audio_source_t source)204 bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
205 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
206 source) != PERMISSION_HARD_DENIED;
207 }
208
recordingAllowed(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,audio_source_t source)209 bool recordingAllowed(const AttributionSourceState &attributionSource,
210 const uint32_t virtualDeviceId,
211 audio_source_t source) {
212 return checkRecordingInternal(attributionSource, virtualDeviceId,
213 String16(), /*start*/ false, source) != PERMISSION_HARD_DENIED;
214 }
215
startRecording(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,const String16 & msg,audio_source_t source)216 int startRecording(const AttributionSourceState& attributionSource,
217 const uint32_t virtualDeviceId,
218 const String16& msg,
219 audio_source_t source) {
220 return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
221 source);
222 }
223
finishRecording(const AttributionSourceState & attributionSource,uint32_t virtualDeviceId,audio_source_t source)224 void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
225 audio_source_t source) {
226 // Okay to not track in app ops as audio server is us and if
227 // device is rooted security model is considered compromised.
228 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
229 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
230
231 const int32_t attributedOpCode = getOpForSource(source);
232 if (isRecordOpRequired(source)) {
233 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
234 // may open a record track on behalf of a client. Note that pid may be a tid.
235 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
236 const std::optional<AttributionSourceState> resolvedAttributionSource =
237 resolveAttributionSource(attributionSource, virtualDeviceId);
238 if (!resolvedAttributionSource.has_value()) {
239 return;
240 }
241
242 permission::PermissionChecker permissionChecker;
243 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
244 resolvedAttributionSource.value());
245 } else {
246 if (attributedOpCode == AppOpsManager::OP_NONE) return; // nothing to do
247 AppOpsManager ap{};
248 PermissionController pc{};
249 ap.finishOp(attributedOpCode, attributionSource.uid,
250 resolveCallingPackage(
251 pc, String16{attributionSource.packageName.value_or("").c_str()},
252 attributionSource.uid),
253 attributionSource.attributionTag.has_value()
254 ? String16{attributionSource.attributionTag.value().c_str()}
255 : String16{});
256 }
257 }
258
captureAudioOutputAllowed(const AttributionSourceState & attributionSource)259 bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
260 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
261 if (isAudioServerOrRootUid(uid)) return true;
262 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
263 // Use PermissionChecker, which includes some logic for allowing the isolated
264 // HotwordDetectionService to hold certain permissions.
265 permission::PermissionChecker permissionChecker;
266 bool ok = (permissionChecker.checkPermissionForPreflight(
267 sCaptureAudioOutput, attributionSource, String16(),
268 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
269 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
270 return ok;
271 }
272
captureMediaOutputAllowed(const AttributionSourceState & attributionSource)273 bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
274 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
275 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
276 if (isAudioServerOrRootUid(uid)) return true;
277 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
278 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
279 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
280 return ok;
281 }
282
captureTunerAudioInputAllowed(const AttributionSourceState & attributionSource)283 bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
284 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
285 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
286 if (isAudioServerOrRootUid(uid)) return true;
287 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
288 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
289 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
290 return ok;
291 }
292
captureVoiceCommunicationOutputAllowed(const AttributionSourceState & attributionSource)293 bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
294 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
295 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
296 if (isAudioServerOrRootUid(uid)) return true;
297 static const String16 sCaptureVoiceCommOutput(
298 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
299 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
300 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
301 return ok;
302 }
303
bypassConcurrentPolicyAllowed(const AttributionSourceState & attributionSource)304 bool bypassConcurrentPolicyAllowed(const AttributionSourceState& attributionSource) {
305 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
306 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
307 if (isAudioServerOrRootUid(uid)) return true;
308 static const String16 sBypassConcurrentPolicy(
309 "android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION ");
310 // Use PermissionChecker, which includes some logic for allowing the isolated
311 // HotwordDetectionService to hold certain permissions.
312 bool ok = PermissionCache::checkPermission(sBypassConcurrentPolicy, pid, uid);
313 if (!ok) {
314 ALOGV("Request requires android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION");
315 }
316 return ok;
317 }
318
accessUltrasoundAllowed(const AttributionSourceState & attributionSource)319 bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
320 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
321 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
322 if (isAudioServerOrRootUid(uid)) return true;
323 static const String16 sAccessUltrasound(
324 "android.permission.ACCESS_ULTRASOUND");
325 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
326 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
327 return ok;
328 }
329
captureHotwordAllowed(const AttributionSourceState & attributionSource)330 bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
331 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
332 bool ok = recordingAllowed(attributionSource);
333
334 if (ok) {
335 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
336 // Use PermissionChecker, which includes some logic for allowing the isolated
337 // HotwordDetectionService to hold certain permissions.
338 permission::PermissionChecker permissionChecker;
339 ok = (permissionChecker.checkPermissionForPreflight(
340 sCaptureHotwordAllowed, attributionSource, String16(),
341 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
342 }
343 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
344 return ok;
345 }
346
settingsAllowed()347 bool settingsAllowed() {
348 // given this is a permission check, could this be isAudioServerOrRootUid()?
349 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
350 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
351 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
352 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
353 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
354 return ok;
355 }
356
modifyAudioRoutingAllowed()357 bool modifyAudioRoutingAllowed() {
358 return modifyAudioRoutingAllowed(getCallingAttributionSource());
359 }
360
modifyAudioRoutingAllowed(const AttributionSourceState & attributionSource)361 bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
362 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
363 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
364 if (isAudioServerUid(uid)) return true;
365 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
366 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
367 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
368 __func__, uid);
369 return ok;
370 }
371
modifyDefaultAudioEffectsAllowed()372 bool modifyDefaultAudioEffectsAllowed() {
373 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
374 }
375
modifyDefaultAudioEffectsAllowed(const AttributionSourceState & attributionSource)376 bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
377 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
378 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
379 if (isAudioServerUid(uid)) return true;
380
381 static const String16 sModifyDefaultAudioEffectsAllowed(
382 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
383 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
384 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
385 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
386 __func__, uid);
387 return ok;
388 }
389
modifyAudioSettingsPrivilegedAllowed(const AttributionSourceState & attributionSource)390 bool modifyAudioSettingsPrivilegedAllowed(const AttributionSourceState& attributionSource) {
391 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
392 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
393 if (isAudioServerUid(uid)) return true;
394 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
395 bool ok = PermissionCache::checkPermission(sModifyAudioSettingsPrivileged, pid, uid);
396 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED denied for uid %d",
397 __func__, uid);
398 return ok;
399 }
400
dumpAllowed()401 bool dumpAllowed() {
402 static const String16 sDump("android.permission.DUMP");
403 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
404 bool ok = PermissionCache::checkCallingPermission(sDump);
405 // convention is for caller to dump an error message to fd instead of logging here
406 //if (!ok) ALOGE("Request requires android.permission.DUMP");
407 return ok;
408 }
409
modifyPhoneStateAllowed(const AttributionSourceState & attributionSource)410 bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
411 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
412 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
413 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
414 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
415 return ok;
416 }
417
418 // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
bypassInterruptionPolicyAllowed(const AttributionSourceState & attributionSource)419 bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
420 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
421 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
422 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
423 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
424 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
425 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
426 ALOGE_IF(!ok, "Request requires %s or %s",
427 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
428 return ok;
429 }
430
callAudioInterceptionAllowed(const AttributionSourceState & attributionSource)431 bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
432 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
433 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
434
435 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
436 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
437 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
438 __func__, uid);
439 return ok;
440 }
441
getCallingAttributionSource()442 AttributionSourceState getCallingAttributionSource() {
443 AttributionSourceState attributionSource = AttributionSourceState();
444 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
445 IPCThreadState::self()->getCallingPid()));
446 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
447 IPCThreadState::self()->getCallingUid()));
448 attributionSource.token = sp<BBinder>::make();
449 return attributionSource;
450 }
451
purgePermissionCache()452 void purgePermissionCache() {
453 PermissionCache::purgeCache();
454 }
455
checkIMemory(const sp<IMemory> & iMemory)456 status_t checkIMemory(const sp<IMemory>& iMemory)
457 {
458 if (iMemory == 0) {
459 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
460 return BAD_VALUE;
461 }
462
463 sp<IMemoryHeap> heap = iMemory->getMemory();
464 if (heap == 0) {
465 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
466 return BAD_VALUE;
467 }
468
469 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
470 lseek(heap->getHeapID(), 0, SEEK_SET);
471
472 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
473 ALOGE("%s check failed: pointer %p size %zu fd size %u",
474 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
475 return BAD_VALUE;
476 }
477
478 return NO_ERROR;
479 }
480
481 // TODO(b/285588444), clean this up on main, but soak it for backporting purposes for now
482 namespace {
483 class BluetoothPermissionCache {
484 static constexpr auto SYSPROP_NAME = "cache_key.system_server.package_info";
485 const String16 BLUETOOTH_PERM {"android.permission.BLUETOOTH_CONNECT"};
486 mutable std::mutex mLock;
487 // Cached property conditionally defined, since only avail on bionic. On host, don't inval cache
488 #if defined(__BIONIC__)
489 // Unlocked, but only accessed from mListenerThread
490 base::CachedProperty mCachedProperty;
491 #endif
492 // This thread is designed to never join/terminate, so no signal is fine
493 const std::thread mListenerThread;
494 GUARDED_BY(mLock)
495 std::string mPropValue;
496 GUARDED_BY(mLock)
497 std::unordered_map<uid_t, bool> mCache;
498 PermissionController mPc{};
499 public:
BluetoothPermissionCache()500 BluetoothPermissionCache()
501 #if defined(__BIONIC__)
502 : mCachedProperty{SYSPROP_NAME},
__anon12146c780302() 503 mListenerThread([this]() mutable {
504 while (true) {
505 std::string newVal = mCachedProperty.WaitForChange() ?: "";
506 std::lock_guard l{mLock};
507 if (newVal != mPropValue) {
508 ALOGV("Bluetooth permission update");
509 mPropValue = newVal;
510 mCache.clear();
511 }
512 }
513 })
514 #endif
515 {}
516
checkPermission(uid_t uid,pid_t pid)517 bool checkPermission(uid_t uid, pid_t pid) {
518 std::lock_guard l{mLock};
519 auto it = mCache.find(uid);
520 if (it == mCache.end()) {
521 it = mCache.insert({uid, mPc.checkPermission(BLUETOOTH_PERM, pid, uid)}).first;
522 }
523 return it->second;
524 }
525 };
526
527 // Don't call this from locks, since it potentially calls up to system server!
528 // Check for non-app UIDs above this method!
checkBluetoothPermission(const AttributionSourceState & attr)529 bool checkBluetoothPermission(const AttributionSourceState& attr) {
530 [[clang::no_destroy]] static BluetoothPermissionCache impl{};
531 return impl.checkPermission(attr.uid, attr.pid);
532 }
533 } // anonymous
534
535 /**
536 * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
537 * a native audio service (audio flinger, audio policy) must be anonymized.
538 * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
539 * are not anonymized.
540 *
541 * @param attributionSource The attribution source of the calling app.
542 * @param caller string identifying the caller for logging.
543 * @return true if the MAC addresses must be anonymized, false otherwise.
544 */
mustAnonymizeBluetoothAddressLegacy(const AttributionSourceState & attributionSource,const String16 &)545 bool mustAnonymizeBluetoothAddressLegacy(
546 const AttributionSourceState& attributionSource, const String16&) {
547 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
548 bool res;
549 switch(multiuser_get_app_id(uid)) {
550 case AID_ROOT:
551 case AID_SYSTEM:
552 case AID_RADIO:
553 case AID_BLUETOOTH:
554 case AID_MEDIA:
555 case AID_AUDIOSERVER:
556 // Don't anonymize for privileged clients
557 res = false;
558 break;
559 default:
560 res = !checkBluetoothPermission(attributionSource);
561 break;
562 }
563 ALOGV("%s uid: %d, result: %d", __func__, uid, res);
564 return res;
565 }
566
567 /**
568 * Modifies the passed MAC address string in place for consumption by unprivileged clients.
569 * the string is assumed to have a valid MAC address format.
570 * the anonymization must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
571 *
572 * @param address input/output the char string contining the MAC address to anonymize.
573 */
anonymizeBluetoothAddress(char * address)574 void anonymizeBluetoothAddress(char *address) {
575 if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
576 return;
577 }
578 memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
579 }
580
retrievePackageManager()581 sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
582 const sp<IServiceManager> sm = defaultServiceManager();
583 if (sm == nullptr) {
584 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
585 return nullptr;
586 }
587 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
588 if (packageManager == nullptr) {
589 ALOGW("%s: failed to retrieve native package manager", __func__);
590 return nullptr;
591 }
592 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
593 }
594
doIsAllowed(uid_t uid)595 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
596 if (mPackageManager == nullptr) {
597 /** Can not fetch package manager at construction it may not yet be registered. */
598 mPackageManager = retrievePackageManager();
599 if (mPackageManager == nullptr) {
600 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
601 return std::nullopt;
602 }
603 }
604
605 // Retrieve package names for the UID and transform to a std::vector<std::string>.
606 Vector<String16> str16PackageNames;
607 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
608 std::vector<std::string> packageNames;
609 for (const auto& str16PackageName : str16PackageNames) {
610 packageNames.emplace_back(String8(str16PackageName).c_str());
611 }
612 if (packageNames.empty()) {
613 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
614 "from the package manager.", __func__, uid);
615 return std::nullopt;
616 }
617 std::vector<bool> isAllowed;
618 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
619 if (!status.isOk()) {
620 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
621 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
622 return std::nullopt;
623 }
624 if (packageNames.size() != isAllowed.size()) {
625 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
626 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
627 return std::nullopt;
628 }
629
630 // Zip together packageNames and isAllowed for debug logs
631 Packages& packages = mDebugLog[uid];
632 packages.resize(packageNames.size()); // Reuse all objects
633 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
634 begin(packages), [] (auto& name, bool isAllowed) -> Package {
635 return {std::move(name), isAllowed};
636 });
637
638 // Only allow playback record if all packages in this UID allow it
639 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
640 [](bool b) { return b; });
641
642 return playbackCaptureAllowed;
643 }
644
dump(int fd,int spaces) const645 void MediaPackageManager::dump(int fd, int spaces) const {
646 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
647 if (mPackageManager == nullptr) {
648 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
649 }
650 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
651
652 for (const auto& uidCache : mDebugLog) {
653 for (const auto& package : std::get<Packages>(uidCache)) {
654 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
655 std::get<const uid_t>(uidCache),
656 package.playbackCaptureAllowed ? "true " : "false",
657 package.name.c_str());
658 }
659 }
660 }
661
662 namespace mediautils {
663
664 // How long we hold info before we re-fetch it (24 hours) if we found it previously.
665 static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
666 // Maximum info records we retain before clearing everything.
667 static constexpr size_t INFO_CACHE_MAX = 1000;
668
669 // The original code is from MediaMetricsService.cpp.
getCachedInfo(uid_t uid)670 std::shared_ptr<const UidInfo::Info> UidInfo::getCachedInfo(uid_t uid)
671 {
672 std::shared_ptr<const UidInfo::Info> info;
673
674 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
675 {
676 std::lock_guard _l(mLock);
677 auto it = mInfoMap.find(uid);
678 if (it != mInfoMap.end()) {
679 info = it->second;
680 ALOGV("%s: uid %d expiration %lld now %lld",
681 __func__, uid, (long long)info->expirationNs, (long long)now);
682 if (info->expirationNs <= now) {
683 // purge the stale entry and fall into re-fetching
684 ALOGV("%s: entry for uid %d expired, now %lld",
685 __func__, uid, (long long)now);
686 mInfoMap.erase(it);
687 info.reset(); // force refetch
688 }
689 }
690 }
691
692 // if we did not find it in our map, look it up
693 if (!info) {
694 sp<IServiceManager> sm = defaultServiceManager();
695 sp<content::pm::IPackageManagerNative> package_mgr;
696 if (sm.get() == nullptr) {
697 ALOGE("%s: Cannot find service manager", __func__);
698 } else {
699 sp<IBinder> binder = sm->getService(String16("package_native"));
700 if (binder.get() == nullptr) {
701 ALOGE("%s: Cannot find package_native", __func__);
702 } else {
703 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
704 }
705 }
706
707 // find package name
708 std::string pkg;
709 if (package_mgr != nullptr) {
710 std::vector<std::string> names;
711 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
712 if (!status.isOk()) {
713 ALOGE("%s: getNamesForUids failed: %s",
714 __func__, status.exceptionMessage().c_str());
715 } else {
716 if (!names[0].empty()) {
717 pkg = names[0].c_str();
718 }
719 }
720 }
721
722 if (pkg.empty()) {
723 struct passwd pw{}, *result;
724 char buf[8192]; // extra buffer space - should exceed what is
725 // required in struct passwd_pw (tested),
726 // and even then this is only used in backup
727 // when the package manager is unavailable.
728 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
729 && result != nullptr
730 && result->pw_name != nullptr) {
731 pkg = result->pw_name;
732 }
733 }
734
735 // strip any leading "shared:" strings that came back
736 if (pkg.compare(0, 7, "shared:") == 0) {
737 pkg.erase(0, 7);
738 }
739
740 // determine how pkg was installed and the versionCode
741 std::string installer;
742 int64_t versionCode = 0;
743 bool notFound = false;
744 if (pkg.empty()) {
745 pkg = std::to_string(uid); // not found
746 notFound = true;
747 } else if (strchr(pkg.c_str(), '.') == nullptr) {
748 // not of form 'com.whatever...'; assume internal
749 // so we don't need to look it up in package manager.
750 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
751 // android.* packages are assumed fine
752 } else if (package_mgr.get() != nullptr) {
753 String16 pkgName16(pkg.c_str());
754 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
755 if (!status.isOk()) {
756 ALOGE("%s: getInstallerForPackage failed: %s",
757 __func__, status.exceptionMessage().c_str());
758 }
759
760 // skip if we didn't get an installer
761 if (status.isOk()) {
762 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
763 if (!status.isOk()) {
764 ALOGE("%s: getVersionCodeForPackage failed: %s",
765 __func__, status.exceptionMessage().c_str());
766 }
767 }
768
769 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
770 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
771 }
772
773 // add it to the map, to save a subsequent lookup
774 std::lock_guard _l(mLock);
775 // first clear if we have too many cached elements. This would be rare.
776 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
777
778 info = std::make_shared<const UidInfo::Info>(
779 uid,
780 std::move(pkg),
781 std::move(installer),
782 versionCode,
783 now + (notFound ? 0 : INFO_EXPIRATION_NS));
784 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
785 __func__, uid, info->package.c_str(), (long long)info->expirationNs);
786 mInfoMap[uid] = info;
787 }
788 return info;
789 }
790
791 /* static */
getUidInfo()792 UidInfo& UidInfo::getUidInfo() {
793 [[clang::no_destroy]] static UidInfo uidInfo;
794 return uidInfo;
795 }
796
797 /* static */
getInfo(uid_t uid)798 std::shared_ptr<const UidInfo::Info> UidInfo::getInfo(uid_t uid) {
799 return UidInfo::getUidInfo().getCachedInfo(uid);
800 }
801
802 } // namespace mediautils
803
804 } // namespace android
805