blob: 4b0192a22bfbb3a947dc4f7c27cd212e842f463d [file] [log] [blame]
Glenn Kasten44deb052012-02-05 18:09:08 -08001/*
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
guochuang0c55eae2024-03-08 19:42:54 +080017//#define LOG_NDEBUG 0
Eric Laurent9b11c022018-06-06 19:19:22 -070018#define LOG_TAG "ServiceUtilities"
19
Andy Hunga85efab2019-12-23 11:41:29 -080020#include <audio_utils/clock.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070021#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080022#include <binder/IPCThreadState.h>
23#include <binder/IServiceManager.h>
24#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070025#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080026#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070027#include <media/AidlConversion.h>
28#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000029#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080030
Kevin Rocard8be94972019-02-22 13:26:25 -080031#include <iterator>
32#include <algorithm>
Andy Hunga85efab2019-12-23 11:41:29 -080033#include <pwd.h>
Kevin Rocard8be94972019-02-22 13:26:25 -080034
Svet Ganovbe71aa22015-04-28 12:06:02 -070035/* 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
Glenn Kasten44deb052012-02-05 18:09:08 -080042namespace android {
43
Svet Ganov33761132021-05-13 22:51:08 +000044using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070045
Svet Ganov5b81f552018-03-02 09:21:30 -080046static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070047static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
48static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010049static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
Eric Laurent24df2832023-10-13 18:13:43 +020050static const String16 sAndroidPermissionBluetoothConnect("android.permission.BLUETOOTH_CONNECT");
Svet Ganov5b81f552018-03-02 09:21:30 -080051
Svet Ganov5b81f552018-03-02 09:21:30 -080052static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053 const std::optional<String16> opPackageName, uid_t uid) {
54 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
55 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070056 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070057 // In some cases the calling code has no access to the package it runs under.
58 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
59 // case we will get the packages for the calling UID and pick the first one
60 // for attributing the app op. This will work correctly for runtime permissions
61 // as for legacy apps we will toggle the app op for all packages in the UID.
62 // The caveat is that the operation may be attributed to the wrong package and
63 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080064 Vector<String16> packages;
65 permissionController.getPackagesForUid(uid, packages);
66 if (packages.isEmpty()) {
67 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070068 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080069 }
70 return packages[0];
71}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000072
Eric Laurent45e16b92021-05-20 11:10:47 +020073int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080074 switch (source) {
75 case AUDIO_SOURCE_HOTWORD:
76 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Mickey Keeley90d657d2021-10-20 18:06:38 -070077 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080078 case AUDIO_SOURCE_REMOTE_SUBMIX:
79 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070080 case AUDIO_SOURCE_VOICE_DOWNLINK:
81 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080082 case AUDIO_SOURCE_DEFAULT:
83 default:
84 return AppOpsManager::OP_RECORD_AUDIO;
85 }
86}
87
Svet Ganov33761132021-05-13 22:51:08 +000088std::optional<AttributionSourceState> resolveAttributionSource(
Marvin Raminb03b49f2024-04-04 16:25:31 +020089 const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
Svet Ganov33761132021-05-13 22:51:08 +000090 AttributionSourceState nextAttributionSource = callerAttributionSource;
91
92 if (!nextAttributionSource.packageName.has_value()) {
93 nextAttributionSource = AttributionSourceState(nextAttributionSource);
94 PermissionController permissionController;
95 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
96 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
97 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
98 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
99 uid)));
100 if (!nextAttributionSource.packageName.has_value()) {
101 return std::nullopt;
102 }
103 }
Marvin Raminb03b49f2024-04-04 16:25:31 +0200104 nextAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000105
106 AttributionSourceState myAttributionSource;
107 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
108 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Nate Myrene84d6912022-11-10 14:09:34 -0800109 // Create a static token for audioserver requests, which identifies the
110 // audioserver to the app ops system
111 static sp<BBinder> appOpsToken = sp<BBinder>::make();
112 myAttributionSource.token = appOpsToken;
Marvin Raminb03b49f2024-04-04 16:25:31 +0200113 myAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000114 myAttributionSource.next.push_back(nextAttributionSource);
115
116 return std::optional<AttributionSourceState>{myAttributionSource};
117}
118
Marvin Ramine5a122d2023-12-07 13:57:59 +0100119 static bool checkRecordingInternal(const AttributionSourceState &attributionSource,
120 const uint32_t virtualDeviceId,
121 const String16 &msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700122 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800123 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700124 // system_server loses its RECORD_AUDIO permission when a secondary
125 // user is active, but it is a core system service so let it through.
126 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000127 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700128 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000129
Svet Ganov5b81f552018-03-02 09:21:30 -0800130 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000131 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800132 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Marvin Ramine5a122d2023-12-07 13:57:59 +0100133 std::optional<AttributionSourceState> resolvedAttributionSource =
Marvin Raminb03b49f2024-04-04 16:25:31 +0200134 resolveAttributionSource(attributionSource, virtualDeviceId);
Svet Ganov33761132021-05-13 22:51:08 +0000135 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800136 return false;
137 }
138
Svet Ganov33761132021-05-13 22:51:08 +0000139 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000140
Svet Ganov33761132021-05-13 22:51:08 +0000141 permission::PermissionChecker permissionChecker;
142 bool permitted = false;
Svet Ganov5b81f552018-03-02 09:21:30 -0800143 if (start) {
Svet Ganov33761132021-05-13 22:51:08 +0000144 permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
145 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
146 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svet Ganov5b81f552018-03-02 09:21:30 -0800147 } else {
Svet Ganov33761132021-05-13 22:51:08 +0000148 permitted = (permissionChecker.checkPermissionForPreflightFromDatasource(
149 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
150 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000151 }
152
Svet Ganov33761132021-05-13 22:51:08 +0000153 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800154}
155
Marvin Ramine5a122d2023-12-07 13:57:59 +0100156static constexpr int DEVICE_ID_DEFAULT = 0;
157
158bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
159 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
160 source);
161}
162
163bool recordingAllowed(const AttributionSourceState &attributionSource,
164 const uint32_t virtualDeviceId,
165 audio_source_t source) {
166 return checkRecordingInternal(attributionSource, virtualDeviceId,
167 String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800168}
169
Marvin Raminb03b49f2024-04-04 16:25:31 +0200170bool startRecording(const AttributionSourceState& attributionSource,
171 const uint32_t virtualDeviceId,
172 const String16& msg,
173 audio_source_t source) {
174 return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100175 source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800176}
177
Marvin Raminb03b49f2024-04-04 16:25:31 +0200178void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
179 audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800180 // Okay to not track in app ops as audio server is us and if
181 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000182 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
183 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800184
Svet Ganov33761132021-05-13 22:51:08 +0000185 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
186 // may open a record track on behalf of a client. Note that pid may be a tid.
187 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
188 const std::optional<AttributionSourceState> resolvedAttributionSource =
Marvin Raminb03b49f2024-04-04 16:25:31 +0200189 resolveAttributionSource(attributionSource, virtualDeviceId);
Svet Ganov33761132021-05-13 22:51:08 +0000190 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800191 return;
192 }
193
Svet Ganov33761132021-05-13 22:51:08 +0000194 const int32_t attributedOpCode = getOpForSource(source);
195 permission::PermissionChecker permissionChecker;
196 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
197 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800198}
199
Svet Ganov33761132021-05-13 22:51:08 +0000200bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
201 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700202 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700203 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
lpeter20d2e032022-06-01 19:38:44 +0800204 // Use PermissionChecker, which includes some logic for allowing the isolated
205 // HotwordDetectionService to hold certain permissions.
206 permission::PermissionChecker permissionChecker;
207 bool ok = (permissionChecker.checkPermissionForPreflight(
208 sCaptureAudioOutput, attributionSource, String16(),
209 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700210 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700211 return ok;
212}
213
Svet Ganov33761132021-05-13 22:51:08 +0000214bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
215 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
216 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800217 if (isAudioServerOrRootUid(uid)) return true;
218 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
219 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
220 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
221 return ok;
222}
223
Svet Ganov33761132021-05-13 22:51:08 +0000224bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
225 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
226 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800227 if (isAudioServerOrRootUid(uid)) return true;
228 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
229 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
230 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
231 return ok;
232}
233
Svet Ganov33761132021-05-13 22:51:08 +0000234bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
235 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
236 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200237 if (isAudioServerOrRootUid(uid)) return true;
238 static const String16 sCaptureVoiceCommOutput(
239 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
240 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
241 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
242 return ok;
243}
244
Carter Hsua3abb402021-10-26 11:11:20 +0800245bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
246 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
247 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
248 if (isAudioServerOrRootUid(uid)) return true;
249 static const String16 sAccessUltrasound(
250 "android.permission.ACCESS_ULTRASOUND");
251 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
252 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
253 return ok;
254}
255
Svet Ganov33761132021-05-13 22:51:08 +0000256bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700257 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000258 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700259
260 if (ok) {
261 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700262 // Use PermissionChecker, which includes some logic for allowing the isolated
263 // HotwordDetectionService to hold certain permissions.
264 permission::PermissionChecker permissionChecker;
265 ok = (permissionChecker.checkPermissionForPreflight(
266 sCaptureHotwordAllowed, attributionSource, String16(),
267 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700268 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700269 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700270 return ok;
271}
272
Glenn Kasten44deb052012-02-05 18:09:08 -0800273bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700274 // given this is a permission check, could this be isAudioServerOrRootUid()?
275 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800276 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700277 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
278 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800279 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
280 return ok;
281}
282
Eric Laurent5284ed52014-05-29 14:37:38 -0700283bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000284 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800285}
286
Svet Ganov33761132021-05-13 22:51:08 +0000287bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
288 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
289 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800290 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700291 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800292 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
293 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
294 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700295 return ok;
296}
297
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700298bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000299 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800300}
301
Svet Ganov33761132021-05-13 22:51:08 +0000302bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
303 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
304 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800305 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
306
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700307 static const String16 sModifyDefaultAudioEffectsAllowed(
308 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
309 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800310 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
311 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
312 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700313 return ok;
314}
315
Glenn Kasten44deb052012-02-05 18:09:08 -0800316bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800317 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700318 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800319 bool ok = PermissionCache::checkCallingPermission(sDump);
320 // convention is for caller to dump an error message to fd instead of logging here
321 //if (!ok) ALOGE("Request requires android.permission.DUMP");
322 return ok;
323}
324
Svet Ganov33761132021-05-13 22:51:08 +0000325bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
326 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
327 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800328 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700329 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
330 return ok;
331}
332
333// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000334bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
335 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
336 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700337 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
338 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
339 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
340 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
341 ALOGE_IF(!ok, "Request requires %s or %s",
342 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200343 return ok;
344}
345
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100346bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
347 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
348 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
349
350 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
351 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
Eric Laurenta6244a02021-12-14 14:05:25 +0100352 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100353 __func__, uid);
354 return ok;
355}
356
Svet Ganov33761132021-05-13 22:51:08 +0000357AttributionSourceState getCallingAttributionSource() {
358 AttributionSourceState attributionSource = AttributionSourceState();
359 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
360 IPCThreadState::self()->getCallingPid()));
361 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
362 IPCThreadState::self()->getCallingUid()));
363 attributionSource.token = sp<BBinder>::make();
364 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700365}
366
Eric Laurent269acb42021-04-23 16:53:22 +0200367void purgePermissionCache() {
368 PermissionCache::purgeCache();
369}
370
Eric Laurent9b11c022018-06-06 19:19:22 -0700371status_t checkIMemory(const sp<IMemory>& iMemory)
372{
373 if (iMemory == 0) {
374 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
375 return BAD_VALUE;
376 }
377
378 sp<IMemoryHeap> heap = iMemory->getMemory();
379 if (heap == 0) {
380 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
381 return BAD_VALUE;
382 }
383
384 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
385 lseek(heap->getHeapID(), 0, SEEK_SET);
386
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700387 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700388 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700389 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700390 return BAD_VALUE;
391 }
392
393 return NO_ERROR;
394}
395
Eric Laurent24df2832023-10-13 18:13:43 +0200396/**
397 * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
398 * a native audio service (audio flinger, audio policy) must be anonymized.
399 * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
400 * are not anonymized.
401 *
402 * @param attributionSource The attribution source of the calling app.
403 * @param caller string identifying the caller for logging.
404 * @return true if the MAC addresses must be anonymized, false otherwise.
405 */
406bool mustAnonymizeBluetoothAddress(
407 const AttributionSourceState& attributionSource, const String16& caller) {
Eric Laurent24df2832023-10-13 18:13:43 +0200408 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
409 if (isAudioServerOrSystemServerUid(uid)) {
410 return false;
411 }
412 const std::optional<AttributionSourceState> resolvedAttributionSource =
Marvin Raminb03b49f2024-04-04 16:25:31 +0200413 resolveAttributionSource(attributionSource, DEVICE_ID_DEFAULT);
Eric Laurent24df2832023-10-13 18:13:43 +0200414 if (!resolvedAttributionSource.has_value()) {
415 return true;
416 }
417 permission::PermissionChecker permissionChecker;
418 return permissionChecker.checkPermissionForPreflightFromDatasource(
419 sAndroidPermissionBluetoothConnect, resolvedAttributionSource.value(), caller,
420 AppOpsManager::OP_BLUETOOTH_CONNECT)
421 != permission::PermissionChecker::PERMISSION_GRANTED;
422}
423
424/**
425 * Modifies the passed MAC address string in place for consumption by unprivileged clients.
426 * the string is assumed to have a valid MAC address format.
427 * the anonymzation must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
428 *
429 * @param address input/output the char string contining the MAC address to anonymize.
430 */
431void anonymizeBluetoothAddress(char *address) {
432 if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
433 return;
434 }
435 memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
436}
437
Oreste Salerno703ec262020-12-17 16:38:38 +0100438sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800439 const sp<IServiceManager> sm = defaultServiceManager();
440 if (sm == nullptr) {
441 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700442 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800443 }
444 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
445 if (packageManager == nullptr) {
446 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700447 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800448 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700449 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800450}
451
452std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
453 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700454 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100455 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700456 if (mPackageManager == nullptr) {
457 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
458 return std::nullopt;
459 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800460 }
461
Oreste Salerno703ec262020-12-17 16:38:38 +0100462 // Retrieve package names for the UID and transform to a std::vector<std::string>.
463 Vector<String16> str16PackageNames;
464 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800465 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100466 for (const auto& str16PackageName : str16PackageNames) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000467 packageNames.emplace_back(String8(str16PackageName).c_str());
Kevin Rocard8be94972019-02-22 13:26:25 -0800468 }
469 if (packageNames.empty()) {
470 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100471 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800472 return std::nullopt;
473 }
474 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100475 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800476 if (!status.isOk()) {
477 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
478 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
479 return std::nullopt;
480 }
481 if (packageNames.size() != isAllowed.size()) {
482 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
483 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
484 return std::nullopt;
485 }
486
487 // Zip together packageNames and isAllowed for debug logs
488 Packages& packages = mDebugLog[uid];
489 packages.resize(packageNames.size()); // Reuse all objects
490 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
491 begin(packages), [] (auto& name, bool isAllowed) -> Package {
492 return {std::move(name), isAllowed};
493 });
494
495 // Only allow playback record if all packages in this UID allow it
496 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
497 [](bool b) { return b; });
498
499 return playbackCaptureAllowed;
500}
501
502void MediaPackageManager::dump(int fd, int spaces) const {
503 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
504 if (mPackageManager == nullptr) {
505 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
506 }
507 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
508
509 for (const auto& uidCache : mDebugLog) {
510 for (const auto& package : std::get<Packages>(uidCache)) {
511 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
512 std::get<const uid_t>(uidCache),
513 package.playbackCaptureAllowed ? "true " : "false",
514 package.name.c_str());
515 }
516 }
517}
518
Andy Hunga85efab2019-12-23 11:41:29 -0800519// How long we hold info before we re-fetch it (24 hours) if we found it previously.
520static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
521// Maximum info records we retain before clearing everything.
522static constexpr size_t INFO_CACHE_MAX = 1000;
523
524// The original code is from MediaMetricsService.cpp.
525mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
526{
527 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
528 struct mediautils::UidInfo::Info info;
529 {
530 std::lock_guard _l(mLock);
531 auto it = mInfoMap.find(uid);
532 if (it != mInfoMap.end()) {
533 info = it->second;
534 ALOGV("%s: uid %d expiration %lld now %lld",
535 __func__, uid, (long long)info.expirationNs, (long long)now);
536 if (info.expirationNs <= now) {
537 // purge the stale entry and fall into re-fetching
538 ALOGV("%s: entry for uid %d expired, now %lld",
539 __func__, uid, (long long)now);
540 mInfoMap.erase(it);
541 info.uid = (uid_t)-1; // this is always fully overwritten
542 }
543 }
544 }
545
546 // if we did not find it in our map, look it up
547 if (info.uid == (uid_t)(-1)) {
548 sp<IServiceManager> sm = defaultServiceManager();
549 sp<content::pm::IPackageManagerNative> package_mgr;
550 if (sm.get() == nullptr) {
551 ALOGE("%s: Cannot find service manager", __func__);
552 } else {
553 sp<IBinder> binder = sm->getService(String16("package_native"));
554 if (binder.get() == nullptr) {
555 ALOGE("%s: Cannot find package_native", __func__);
556 } else {
557 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
558 }
559 }
560
561 // find package name
562 std::string pkg;
563 if (package_mgr != nullptr) {
564 std::vector<std::string> names;
565 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
566 if (!status.isOk()) {
567 ALOGE("%s: getNamesForUids failed: %s",
568 __func__, status.exceptionMessage().c_str());
569 } else {
570 if (!names[0].empty()) {
571 pkg = names[0].c_str();
572 }
573 }
574 }
575
576 if (pkg.empty()) {
577 struct passwd pw{}, *result;
578 char buf[8192]; // extra buffer space - should exceed what is
579 // required in struct passwd_pw (tested),
580 // and even then this is only used in backup
581 // when the package manager is unavailable.
582 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
583 && result != nullptr
584 && result->pw_name != nullptr) {
585 pkg = result->pw_name;
586 }
587 }
588
589 // strip any leading "shared:" strings that came back
590 if (pkg.compare(0, 7, "shared:") == 0) {
591 pkg.erase(0, 7);
592 }
593
594 // determine how pkg was installed and the versionCode
595 std::string installer;
596 int64_t versionCode = 0;
597 bool notFound = false;
598 if (pkg.empty()) {
599 pkg = std::to_string(uid); // not found
600 notFound = true;
601 } else if (strchr(pkg.c_str(), '.') == nullptr) {
602 // not of form 'com.whatever...'; assume internal
603 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800604 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
605 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800606 } else if (package_mgr.get() != nullptr) {
607 String16 pkgName16(pkg.c_str());
608 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
609 if (!status.isOk()) {
610 ALOGE("%s: getInstallerForPackage failed: %s",
611 __func__, status.exceptionMessage().c_str());
612 }
613
614 // skip if we didn't get an installer
615 if (status.isOk()) {
616 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
617 if (!status.isOk()) {
618 ALOGE("%s: getVersionCodeForPackage failed: %s",
619 __func__, status.exceptionMessage().c_str());
620 }
621 }
622
623 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
624 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
625 }
626
627 // add it to the map, to save a subsequent lookup
628 std::lock_guard _l(mLock);
629 // first clear if we have too many cached elements. This would be rare.
630 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
631
632 // always overwrite
633 info.uid = uid;
634 info.package = std::move(pkg);
635 info.installer = std::move(installer);
636 info.versionCode = versionCode;
637 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
638 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
639 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
640 mInfoMap[uid] = info;
641 }
642 return info;
643}
644
Glenn Kasten44deb052012-02-05 18:09:08 -0800645} // namespace android