blob: ddb93fe9f4b89edf4d0c0b0fcf75cb2c518f6373 [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>
Atneya Nair23348762024-10-14 14:16:06 -070021#include <android-base/properties.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070022#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080023#include <binder/IPCThreadState.h>
24#include <binder/IServiceManager.h>
25#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070026#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080027#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070028#include <media/AidlConversion.h>
29#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000030#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080031
Chaitanya Cheemala (xWF)e1dfc0f2024-10-08 09:41:45 +000032#include <algorithm>
Atneya Nair23348762024-10-14 14:16:06 -070033#include <iterator>
34#include <mutex>
Andy Hunga85efab2019-12-23 11:41:29 -080035#include <pwd.h>
Atneya Nair23348762024-10-14 14:16:06 -070036#include <thread>
Kevin Rocard8be94972019-02-22 13:26:25 -080037
Svet Ganovbe71aa22015-04-28 12:06:02 -070038/* 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
Glenn Kasten44deb052012-02-05 18:09:08 -080045namespace android {
46
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000047namespace {
Atneya Nair38558e12024-10-25 17:59:36 -070048constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
Atneya Nairdb6ef1e2024-09-16 20:26:30 +000049constexpr auto PERMISSION_HARD_DENIED = permission::PermissionChecker::PERMISSION_HARD_DENIED;
50}
51
Svet Ganov33761132021-05-13 22:51:08 +000052using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070053
Svet Ganov5b81f552018-03-02 09:21:30 -080054static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070055static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
56static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010057static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
Svet Ganov5b81f552018-03-02 09:21:30 -080058
Svet Ganov5b81f552018-03-02 09:21:30 -080059static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070060 const std::optional<String16> opPackageName, uid_t uid) {
61 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
62 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070063 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070064 // In some cases the calling code has no access to the package it runs under.
65 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
66 // case we will get the packages for the calling UID and pick the first one
67 // for attributing the app op. This will work correctly for runtime permissions
68 // as for legacy apps we will toggle the app op for all packages in the UID.
69 // The caveat is that the operation may be attributed to the wrong package and
70 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080071 Vector<String16> packages;
72 permissionController.getPackagesForUid(uid, packages);
73 if (packages.isEmpty()) {
74 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070075 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080076 }
77 return packages[0];
78}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000079
Eric Laurent45e16b92021-05-20 11:10:47 +020080int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080081 switch (source) {
Atneya Nair38558e12024-10-25 17:59:36 -070082 case AUDIO_SOURCE_FM_TUNER:
83 return AppOpsManager::OP_NONE;
Mickey Keeley90d657d2021-10-20 18:06:38 -070084 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080085 case AUDIO_SOURCE_REMOTE_SUBMIX:
86 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070087 case AUDIO_SOURCE_VOICE_DOWNLINK:
88 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Atneya Nair38558e12024-10-25 17:59:36 -070089 case AUDIO_SOURCE_HOTWORD:
90 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Nate Myrene69cada2020-12-10 10:00:36 -080091 case AUDIO_SOURCE_DEFAULT:
92 default:
93 return AppOpsManager::OP_RECORD_AUDIO;
94 }
95}
96
Atneya Nair38558e12024-10-25 17:59:36 -070097bool isRecordOpRequired(audio_source_t source) {
98 switch (source) {
99 case AUDIO_SOURCE_FM_TUNER:
100 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
101 case AUDIO_SOURCE_REMOTE_SUBMIX:
102 return false;
103 default:
104 return true;
105 }
106}
107
Svet Ganov33761132021-05-13 22:51:08 +0000108std::optional<AttributionSourceState> resolveAttributionSource(
Marvin Raminb03b49f2024-04-04 16:25:31 +0200109 const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
Svet Ganov33761132021-05-13 22:51:08 +0000110 AttributionSourceState nextAttributionSource = callerAttributionSource;
111
112 if (!nextAttributionSource.packageName.has_value()) {
113 nextAttributionSource = AttributionSourceState(nextAttributionSource);
114 PermissionController permissionController;
115 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
116 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
117 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
118 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
119 uid)));
120 if (!nextAttributionSource.packageName.has_value()) {
121 return std::nullopt;
122 }
123 }
Marvin Raminb03b49f2024-04-04 16:25:31 +0200124 nextAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000125
126 AttributionSourceState myAttributionSource;
127 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
128 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Nate Myrene84d6912022-11-10 14:09:34 -0800129 // Create a static token for audioserver requests, which identifies the
130 // audioserver to the app ops system
131 static sp<BBinder> appOpsToken = sp<BBinder>::make();
132 myAttributionSource.token = appOpsToken;
Marvin Raminb03b49f2024-04-04 16:25:31 +0200133 myAttributionSource.deviceId = virtualDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +0000134 myAttributionSource.next.push_back(nextAttributionSource);
135
136 return std::optional<AttributionSourceState>{myAttributionSource};
137}
138
Atneya Nair38558e12024-10-25 17:59:36 -0700139
140static int checkRecordingInternal(const AttributionSourceState &attributionSource,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100141 const uint32_t virtualDeviceId,
142 const String16 &msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700143 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800144 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700145 // system_server loses its RECORD_AUDIO permission when a secondary
146 // user is active, but it is a core system service so let it through.
147 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000148 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Atneya Nair38558e12024-10-25 17:59:36 -0700149 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return PERMISSION_GRANTED;
Svet Ganov5b81f552018-03-02 09:21:30 -0800150
Svet Ganov33761132021-05-13 22:51:08 +0000151 const int32_t attributedOpCode = getOpForSource(source);
Atneya Nair38558e12024-10-25 17:59:36 -0700152 if (isRecordOpRequired(source)) {
153 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
154 // may open a record track on behalf of a client. Note that pid may be a tid.
155 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
156 std::optional<AttributionSourceState> resolvedAttributionSource =
157 resolveAttributionSource(attributionSource, virtualDeviceId);
158 if (!resolvedAttributionSource.has_value()) {
159 return PERMISSION_HARD_DENIED;
160 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000161
Atneya Nair38558e12024-10-25 17:59:36 -0700162 permission::PermissionChecker permissionChecker;
163 int permitted;
164 if (start) {
165 permitted = permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
166 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
167 attributedOpCode);
168 } else {
169 permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
170 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
171 attributedOpCode);
172 }
173
174 return permitted;
Svet Ganov5b81f552018-03-02 09:21:30 -0800175 } else {
Atneya Nair38558e12024-10-25 17:59:36 -0700176 if (attributedOpCode == AppOpsManager::OP_NONE) return PERMISSION_GRANTED; // nothing to do
177 AppOpsManager ap{};
178 PermissionController pc{};
179 return ap.startOpNoThrow(
180 attributedOpCode, attributionSource.uid,
181 resolveCallingPackage(pc,
182 String16{attributionSource.packageName.value_or("").c_str()},
183 attributionSource.uid),
184 false,
185 attributionSource.attributionTag.has_value()
186 ? String16{attributionSource.attributionTag.value().c_str()}
187 : String16{},
188 msg);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000189 }
Glenn Kasten44deb052012-02-05 18:09:08 -0800190}
191
Marvin Ramine5a122d2023-12-07 13:57:59 +0100192static constexpr int DEVICE_ID_DEFAULT = 0;
193
194bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
195 return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000196 source) != PERMISSION_HARD_DENIED;
Marvin Ramine5a122d2023-12-07 13:57:59 +0100197}
198
199bool recordingAllowed(const AttributionSourceState &attributionSource,
200 const uint32_t virtualDeviceId,
201 audio_source_t source) {
202 return checkRecordingInternal(attributionSource, virtualDeviceId,
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000203 String16(), /*start*/ false, source) != PERMISSION_HARD_DENIED;
Svet Ganov5b81f552018-03-02 09:21:30 -0800204}
205
Atneya Nairdb6ef1e2024-09-16 20:26:30 +0000206int startRecording(const AttributionSourceState& attributionSource,
Marvin Raminb03b49f2024-04-04 16:25:31 +0200207 const uint32_t virtualDeviceId,
208 const String16& msg,
209 audio_source_t source) {
210 return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
Marvin Ramine5a122d2023-12-07 13:57:59 +0100211 source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800212}
213
Marvin Raminb03b49f2024-04-04 16:25:31 +0200214void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
215 audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800216 // Okay to not track in app ops as audio server is us and if
217 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000218 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
219 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800220
Svet Ganov33761132021-05-13 22:51:08 +0000221 const int32_t attributedOpCode = getOpForSource(source);
Atneya Nair38558e12024-10-25 17:59:36 -0700222 if (isRecordOpRequired(source)) {
223 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
224 // may open a record track on behalf of a client. Note that pid may be a tid.
225 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
226 const std::optional<AttributionSourceState> resolvedAttributionSource =
227 resolveAttributionSource(attributionSource, virtualDeviceId);
228 if (!resolvedAttributionSource.has_value()) {
229 return;
230 }
231
232 permission::PermissionChecker permissionChecker;
233 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
234 resolvedAttributionSource.value());
235 } else {
236 if (attributedOpCode == AppOpsManager::OP_NONE) return; // nothing to do
237 AppOpsManager ap{};
238 PermissionController pc{};
239 ap.finishOp(attributedOpCode, attributionSource.uid,
240 resolveCallingPackage(
241 pc, String16{attributionSource.packageName.value_or("").c_str()},
242 attributionSource.uid),
243 attributionSource.attributionTag.has_value()
244 ? String16{attributionSource.attributionTag.value().c_str()}
245 : String16{});
246 }
Svet Ganov5b81f552018-03-02 09:21:30 -0800247}
248
Svet Ganov33761132021-05-13 22:51:08 +0000249bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
250 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700251 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700252 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
lpeter20d2e032022-06-01 19:38:44 +0800253 // Use PermissionChecker, which includes some logic for allowing the isolated
254 // HotwordDetectionService to hold certain permissions.
255 permission::PermissionChecker permissionChecker;
256 bool ok = (permissionChecker.checkPermissionForPreflight(
257 sCaptureAudioOutput, attributionSource, String16(),
258 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700259 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700260 return ok;
261}
262
Svet Ganov33761132021-05-13 22:51:08 +0000263bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
264 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
265 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800266 if (isAudioServerOrRootUid(uid)) return true;
267 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
268 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
269 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
270 return ok;
271}
272
Svet Ganov33761132021-05-13 22:51:08 +0000273bool captureTunerAudioInputAllowed(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));
Hayden Gomesb7429922020-12-11 13:59:18 -0800276 if (isAudioServerOrRootUid(uid)) return true;
277 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
278 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
279 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
280 return ok;
281}
282
Svet Ganov33761132021-05-13 22:51:08 +0000283bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
284 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
285 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200286 if (isAudioServerOrRootUid(uid)) return true;
287 static const String16 sCaptureVoiceCommOutput(
288 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
289 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
290 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
291 return ok;
292}
293
Carter Hsua3abb402021-10-26 11:11:20 +0800294bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
295 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
296 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
297 if (isAudioServerOrRootUid(uid)) return true;
298 static const String16 sAccessUltrasound(
299 "android.permission.ACCESS_ULTRASOUND");
300 bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
301 if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
302 return ok;
303}
304
Svet Ganov33761132021-05-13 22:51:08 +0000305bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700306 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000307 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700308
309 if (ok) {
310 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700311 // Use PermissionChecker, which includes some logic for allowing the isolated
312 // HotwordDetectionService to hold certain permissions.
313 permission::PermissionChecker permissionChecker;
314 ok = (permissionChecker.checkPermissionForPreflight(
315 sCaptureHotwordAllowed, attributionSource, String16(),
316 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700317 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700318 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700319 return ok;
320}
321
Glenn Kasten44deb052012-02-05 18:09:08 -0800322bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700323 // given this is a permission check, could this be isAudioServerOrRootUid()?
324 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800325 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700326 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
327 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800328 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
329 return ok;
330}
331
Eric Laurent5284ed52014-05-29 14:37:38 -0700332bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000333 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800334}
335
Svet Ganov33761132021-05-13 22:51:08 +0000336bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
337 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
338 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700339 if (isAudioServerUid(uid)) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700340 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800341 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
342 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
343 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700344 return ok;
345}
346
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700347bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000348 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800349}
350
Svet Ganov33761132021-05-13 22:51:08 +0000351bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
352 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
353 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Atneya Nairb7199082024-08-17 19:04:46 -0700354 if (isAudioServerUid(uid)) return true;
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800355
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700356 static const String16 sModifyDefaultAudioEffectsAllowed(
357 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
358 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800359 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
360 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
361 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700362 return ok;
363}
364
Glenn Kasten44deb052012-02-05 18:09:08 -0800365bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800366 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700367 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800368 bool ok = PermissionCache::checkCallingPermission(sDump);
369 // convention is for caller to dump an error message to fd instead of logging here
370 //if (!ok) ALOGE("Request requires android.permission.DUMP");
371 return ok;
372}
373
Svet Ganov33761132021-05-13 22:51:08 +0000374bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
375 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
376 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800377 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700378 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
379 return ok;
380}
381
382// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000383bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
384 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
385 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700386 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
387 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
388 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
389 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
390 ALOGE_IF(!ok, "Request requires %s or %s",
391 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200392 return ok;
393}
394
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100395bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
396 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
397 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
398
399 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
400 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
Eric Laurenta6244a02021-12-14 14:05:25 +0100401 if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100402 __func__, uid);
403 return ok;
404}
405
Svet Ganov33761132021-05-13 22:51:08 +0000406AttributionSourceState getCallingAttributionSource() {
407 AttributionSourceState attributionSource = AttributionSourceState();
408 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
409 IPCThreadState::self()->getCallingPid()));
410 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
411 IPCThreadState::self()->getCallingUid()));
412 attributionSource.token = sp<BBinder>::make();
413 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700414}
415
Eric Laurent269acb42021-04-23 16:53:22 +0200416void purgePermissionCache() {
417 PermissionCache::purgeCache();
418}
419
Eric Laurent9b11c022018-06-06 19:19:22 -0700420status_t checkIMemory(const sp<IMemory>& iMemory)
421{
422 if (iMemory == 0) {
423 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
424 return BAD_VALUE;
425 }
426
427 sp<IMemoryHeap> heap = iMemory->getMemory();
428 if (heap == 0) {
429 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
430 return BAD_VALUE;
431 }
432
433 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
434 lseek(heap->getHeapID(), 0, SEEK_SET);
435
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700436 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700437 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700438 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700439 return BAD_VALUE;
440 }
441
442 return NO_ERROR;
443}
444
Atneya Nair23348762024-10-14 14:16:06 -0700445// TODO(b/285588444), clean this up on main, but soak it for backporting purposes for now
446namespace {
447class BluetoothPermissionCache {
448 static constexpr auto SYSPROP_NAME = "cache_key.system_server.package_info";
449 const String16 BLUETOOTH_PERM {"android.permission.BLUETOOTH_CONNECT"};
450 mutable std::mutex mLock;
451 // Cached property conditionally defined, since only avail on bionic. On host, don't inval cache
452#if defined(__BIONIC__)
453 // Unlocked, but only accessed from mListenerThread
454 base::CachedProperty mCachedProperty;
455#endif
456 // This thread is designed to never join/terminate, so no signal is fine
457 const std::thread mListenerThread;
458 GUARDED_BY(mLock)
459 std::string mPropValue;
460 GUARDED_BY(mLock)
461 std::unordered_map<uid_t, bool> mCache;
462 PermissionController mPc{};
463public:
464 BluetoothPermissionCache()
465#if defined(__BIONIC__)
466 : mCachedProperty{SYSPROP_NAME},
467 mListenerThread([this]() mutable {
468 while (true) {
469 std::string newVal = mCachedProperty.WaitForChange() ?: "";
470 std::lock_guard l{mLock};
471 if (newVal != mPropValue) {
472 ALOGV("Bluetooth permission update");
473 mPropValue = newVal;
474 mCache.clear();
475 }
476 }
477 })
478#endif
479 {}
480
481 bool checkPermission(uid_t uid, pid_t pid) {
482 std::lock_guard l{mLock};
483 auto it = mCache.find(uid);
484 if (it == mCache.end()) {
485 it = mCache.insert({uid, mPc.checkPermission(BLUETOOTH_PERM, pid, uid)}).first;
486 }
487 return it->second;
488 }
489};
490
491// Don't call this from locks, since it potentially calls up to system server!
492// Check for non-app UIDs above this method!
493bool checkBluetoothPermission(const AttributionSourceState& attr) {
494 [[clang::no_destroy]] static BluetoothPermissionCache impl{};
495 return impl.checkPermission(attr.uid, attr.pid);
496}
497} // anonymous
498
499/**
500 * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
501 * a native audio service (audio flinger, audio policy) must be anonymized.
502 * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
503 * are not anonymized.
504 *
505 * @param attributionSource The attribution source of the calling app.
506 * @param caller string identifying the caller for logging.
507 * @return true if the MAC addresses must be anonymized, false otherwise.
508 */
509bool mustAnonymizeBluetoothAddress(
510 const AttributionSourceState& attributionSource, const String16&) {
511 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
512 bool res;
513 switch(multiuser_get_app_id(uid)) {
514 case AID_ROOT:
515 case AID_SYSTEM:
516 case AID_RADIO:
517 case AID_BLUETOOTH:
518 case AID_MEDIA:
519 case AID_AUDIOSERVER:
520 // Don't anonymize for privileged clients
521 res = false;
522 break;
523 default:
524 res = !checkBluetoothPermission(attributionSource);
525 break;
526 }
527 ALOGV("%s uid: %d, result: %d", __func__, uid, res);
528 return res;
529}
530
531/**
532 * Modifies the passed MAC address string in place for consumption by unprivileged clients.
533 * the string is assumed to have a valid MAC address format.
534 * the anonymization must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
535 *
536 * @param address input/output the char string contining the MAC address to anonymize.
537 */
538void anonymizeBluetoothAddress(char *address) {
539 if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
540 return;
541 }
542 memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
543}
544
Oreste Salerno703ec262020-12-17 16:38:38 +0100545sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800546 const sp<IServiceManager> sm = defaultServiceManager();
547 if (sm == nullptr) {
548 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700549 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800550 }
551 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
552 if (packageManager == nullptr) {
553 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700554 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800555 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700556 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800557}
558
559std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
560 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700561 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100562 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700563 if (mPackageManager == nullptr) {
564 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
565 return std::nullopt;
566 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800567 }
568
Oreste Salerno703ec262020-12-17 16:38:38 +0100569 // Retrieve package names for the UID and transform to a std::vector<std::string>.
570 Vector<String16> str16PackageNames;
571 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800572 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100573 for (const auto& str16PackageName : str16PackageNames) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000574 packageNames.emplace_back(String8(str16PackageName).c_str());
Kevin Rocard8be94972019-02-22 13:26:25 -0800575 }
576 if (packageNames.empty()) {
577 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100578 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800579 return std::nullopt;
580 }
581 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100582 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800583 if (!status.isOk()) {
584 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
585 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
586 return std::nullopt;
587 }
588 if (packageNames.size() != isAllowed.size()) {
589 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
590 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
591 return std::nullopt;
592 }
593
594 // Zip together packageNames and isAllowed for debug logs
595 Packages& packages = mDebugLog[uid];
596 packages.resize(packageNames.size()); // Reuse all objects
597 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
598 begin(packages), [] (auto& name, bool isAllowed) -> Package {
599 return {std::move(name), isAllowed};
600 });
601
602 // Only allow playback record if all packages in this UID allow it
603 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
604 [](bool b) { return b; });
605
606 return playbackCaptureAllowed;
607}
608
609void MediaPackageManager::dump(int fd, int spaces) const {
610 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
611 if (mPackageManager == nullptr) {
612 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
613 }
614 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
615
616 for (const auto& uidCache : mDebugLog) {
617 for (const auto& package : std::get<Packages>(uidCache)) {
618 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
619 std::get<const uid_t>(uidCache),
620 package.playbackCaptureAllowed ? "true " : "false",
621 package.name.c_str());
622 }
623 }
624}
625
Andy Hungb26a1c82024-08-30 11:54:40 -0700626namespace mediautils {
627
Andy Hunga85efab2019-12-23 11:41:29 -0800628// How long we hold info before we re-fetch it (24 hours) if we found it previously.
629static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
630// Maximum info records we retain before clearing everything.
631static constexpr size_t INFO_CACHE_MAX = 1000;
632
633// The original code is from MediaMetricsService.cpp.
Andy Hungb26a1c82024-08-30 11:54:40 -0700634std::shared_ptr<const UidInfo::Info> UidInfo::getCachedInfo(uid_t uid)
Andy Hunga85efab2019-12-23 11:41:29 -0800635{
Andy Hungb26a1c82024-08-30 11:54:40 -0700636 std::shared_ptr<const UidInfo::Info> info;
637
Andy Hunga85efab2019-12-23 11:41:29 -0800638 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hunga85efab2019-12-23 11:41:29 -0800639 {
640 std::lock_guard _l(mLock);
641 auto it = mInfoMap.find(uid);
642 if (it != mInfoMap.end()) {
643 info = it->second;
644 ALOGV("%s: uid %d expiration %lld now %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700645 __func__, uid, (long long)info->expirationNs, (long long)now);
646 if (info->expirationNs <= now) {
Andy Hunga85efab2019-12-23 11:41:29 -0800647 // purge the stale entry and fall into re-fetching
648 ALOGV("%s: entry for uid %d expired, now %lld",
649 __func__, uid, (long long)now);
650 mInfoMap.erase(it);
Andy Hungb26a1c82024-08-30 11:54:40 -0700651 info.reset(); // force refetch
Andy Hunga85efab2019-12-23 11:41:29 -0800652 }
653 }
654 }
655
656 // if we did not find it in our map, look it up
Andy Hungb26a1c82024-08-30 11:54:40 -0700657 if (!info) {
Andy Hunga85efab2019-12-23 11:41:29 -0800658 sp<IServiceManager> sm = defaultServiceManager();
659 sp<content::pm::IPackageManagerNative> package_mgr;
660 if (sm.get() == nullptr) {
661 ALOGE("%s: Cannot find service manager", __func__);
662 } else {
663 sp<IBinder> binder = sm->getService(String16("package_native"));
664 if (binder.get() == nullptr) {
665 ALOGE("%s: Cannot find package_native", __func__);
666 } else {
667 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
668 }
669 }
670
671 // find package name
672 std::string pkg;
673 if (package_mgr != nullptr) {
674 std::vector<std::string> names;
675 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
676 if (!status.isOk()) {
677 ALOGE("%s: getNamesForUids failed: %s",
678 __func__, status.exceptionMessage().c_str());
679 } else {
680 if (!names[0].empty()) {
681 pkg = names[0].c_str();
682 }
683 }
684 }
685
686 if (pkg.empty()) {
687 struct passwd pw{}, *result;
688 char buf[8192]; // extra buffer space - should exceed what is
689 // required in struct passwd_pw (tested),
690 // and even then this is only used in backup
691 // when the package manager is unavailable.
692 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
693 && result != nullptr
694 && result->pw_name != nullptr) {
695 pkg = result->pw_name;
696 }
697 }
698
699 // strip any leading "shared:" strings that came back
700 if (pkg.compare(0, 7, "shared:") == 0) {
701 pkg.erase(0, 7);
702 }
703
704 // determine how pkg was installed and the versionCode
705 std::string installer;
706 int64_t versionCode = 0;
707 bool notFound = false;
708 if (pkg.empty()) {
709 pkg = std::to_string(uid); // not found
710 notFound = true;
711 } else if (strchr(pkg.c_str(), '.') == nullptr) {
712 // not of form 'com.whatever...'; assume internal
713 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800714 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
715 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800716 } else if (package_mgr.get() != nullptr) {
717 String16 pkgName16(pkg.c_str());
718 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
719 if (!status.isOk()) {
720 ALOGE("%s: getInstallerForPackage failed: %s",
721 __func__, status.exceptionMessage().c_str());
722 }
723
724 // skip if we didn't get an installer
725 if (status.isOk()) {
726 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
727 if (!status.isOk()) {
728 ALOGE("%s: getVersionCodeForPackage failed: %s",
729 __func__, status.exceptionMessage().c_str());
730 }
731 }
732
733 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
734 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
735 }
736
737 // add it to the map, to save a subsequent lookup
738 std::lock_guard _l(mLock);
739 // first clear if we have too many cached elements. This would be rare.
740 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
741
Andy Hungb26a1c82024-08-30 11:54:40 -0700742 info = std::make_shared<const UidInfo::Info>(
743 uid,
744 std::move(pkg),
745 std::move(installer),
746 versionCode,
747 now + (notFound ? 0 : INFO_EXPIRATION_NS));
Andy Hunga85efab2019-12-23 11:41:29 -0800748 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
Andy Hungb26a1c82024-08-30 11:54:40 -0700749 __func__, uid, info->package.c_str(), (long long)info->expirationNs);
Andy Hunga85efab2019-12-23 11:41:29 -0800750 mInfoMap[uid] = info;
751 }
752 return info;
753}
754
Andy Hungb26a1c82024-08-30 11:54:40 -0700755/* static */
756UidInfo& UidInfo::getUidInfo() {
757 [[clang::no_destroy]] static UidInfo uidInfo;
758 return uidInfo;
759}
760
761/* static */
762std::shared_ptr<const UidInfo::Info> UidInfo::getInfo(uid_t uid) {
763 return UidInfo::getUidInfo().getCachedInfo(uid);
764}
765
766} // namespace mediautils
767
Glenn Kasten44deb052012-02-05 18:09:08 -0800768} // namespace android