blob: 3ee7626de0913533d8e2ecde1dd927c3bfe45366 [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
Eric Laurent9b11c022018-06-06 19:19:22 -070017#define LOG_TAG "ServiceUtilities"
18
Andy Hunga85efab2019-12-23 11:41:29 -080019#include <audio_utils/clock.h>
Svet Ganovbe71aa22015-04-28 12:06:02 -070020#include <binder/AppOpsManager.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080021#include <binder/IPCThreadState.h>
22#include <binder/IServiceManager.h>
23#include <binder/PermissionCache.h>
Andy Hungab7ef302018-05-15 19:35:29 -070024#include "mediautils/ServiceUtilities.h"
Nate Myrene69cada2020-12-10 10:00:36 -080025#include <system/audio-hal-enums.h>
Philip P. Moltmannbda45752020-07-17 16:41:18 -070026#include <media/AidlConversion.h>
27#include <media/AidlConversionUtil.h>
Svet Ganov33761132021-05-13 22:51:08 +000028#include <android/content/AttributionSourceState.h>
Glenn Kasten44deb052012-02-05 18:09:08 -080029
Kevin Rocard8be94972019-02-22 13:26:25 -080030#include <iterator>
31#include <algorithm>
Andy Hunga85efab2019-12-23 11:41:29 -080032#include <pwd.h>
Kevin Rocard8be94972019-02-22 13:26:25 -080033
Svet Ganovbe71aa22015-04-28 12:06:02 -070034/* When performing permission checks we do not use permission cache for
35 * runtime permissions (protection level dangerous) as they may change at
36 * runtime. All other permissions (protection level normal and dangerous)
37 * can be cached as they never change. Of course all permission checked
38 * here are platform defined.
39 */
40
Glenn Kasten44deb052012-02-05 18:09:08 -080041namespace android {
42
Svet Ganov33761132021-05-13 22:51:08 +000043using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070044
Svet Ganov5b81f552018-03-02 09:21:30 -080045static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
Eric Laurent42984412019-05-09 17:57:03 -070046static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
47static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
Eric Laurentb0eff0f2021-11-09 16:05:49 +010048static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
Svet Ganov5b81f552018-03-02 09:21:30 -080049
Svet Ganov5b81f552018-03-02 09:21:30 -080050static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070051 const std::optional<String16> opPackageName, uid_t uid) {
52 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
53 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070054 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070055 // In some cases the calling code has no access to the package it runs under.
56 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
57 // case we will get the packages for the calling UID and pick the first one
58 // for attributing the app op. This will work correctly for runtime permissions
59 // as for legacy apps we will toggle the app op for all packages in the UID.
60 // The caveat is that the operation may be attributed to the wrong package and
61 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080062 Vector<String16> packages;
63 permissionController.getPackagesForUid(uid, packages);
64 if (packages.isEmpty()) {
65 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070066 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080067 }
68 return packages[0];
69}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000070
Eric Laurent45e16b92021-05-20 11:10:47 +020071int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080072 switch (source) {
73 case AUDIO_SOURCE_HOTWORD:
74 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Mickey Keeley90d657d2021-10-20 18:06:38 -070075 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080076 case AUDIO_SOURCE_REMOTE_SUBMIX:
77 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070078 case AUDIO_SOURCE_VOICE_DOWNLINK:
79 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080080 case AUDIO_SOURCE_DEFAULT:
81 default:
82 return AppOpsManager::OP_RECORD_AUDIO;
83 }
84}
85
Svet Ganov33761132021-05-13 22:51:08 +000086std::optional<AttributionSourceState> resolveAttributionSource(
87 const AttributionSourceState& callerAttributionSource) {
88 AttributionSourceState nextAttributionSource = callerAttributionSource;
89
90 if (!nextAttributionSource.packageName.has_value()) {
91 nextAttributionSource = AttributionSourceState(nextAttributionSource);
92 PermissionController permissionController;
93 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
94 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
95 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
96 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
97 uid)));
98 if (!nextAttributionSource.packageName.has_value()) {
99 return std::nullopt;
100 }
101 }
102
103 AttributionSourceState myAttributionSource;
104 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
105 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Lei Shic8fbfd42021-11-03 15:41:51 +0800106 if (callerAttributionSource.token != nullptr) {
107 myAttributionSource.token = callerAttributionSource.token;
108 } else {
109 myAttributionSource.token = sp<BBinder>::make();
110 }
Svet Ganov33761132021-05-13 22:51:08 +0000111 myAttributionSource.next.push_back(nextAttributionSource);
112
113 return std::optional<AttributionSourceState>{myAttributionSource};
114}
115
116static bool checkRecordingInternal(const AttributionSourceState& attributionSource,
117 const String16& msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700118 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800119 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700120 // system_server loses its RECORD_AUDIO permission when a secondary
121 // user is active, but it is a core system service so let it through.
122 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000123 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700124 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000125
Svet Ganov5b81f552018-03-02 09:21:30 -0800126 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000127 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800128 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Svet Ganov33761132021-05-13 22:51:08 +0000129 const std::optional<AttributionSourceState> resolvedAttributionSource =
130 resolveAttributionSource(attributionSource);
131 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800132 return false;
133 }
134
Svet Ganov33761132021-05-13 22:51:08 +0000135 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000136
Svet Ganov33761132021-05-13 22:51:08 +0000137 permission::PermissionChecker permissionChecker;
138 bool permitted = false;
Svet Ganov5b81f552018-03-02 09:21:30 -0800139 if (start) {
Svet Ganov33761132021-05-13 22:51:08 +0000140 permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
141 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
142 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svet Ganov5b81f552018-03-02 09:21:30 -0800143 } else {
Svet Ganov33761132021-05-13 22:51:08 +0000144 permitted = (permissionChecker.checkPermissionForPreflightFromDatasource(
145 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
146 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000147 }
148
Svet Ganov33761132021-05-13 22:51:08 +0000149 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800150}
151
Svet Ganov33761132021-05-13 22:51:08 +0000152bool recordingAllowed(const AttributionSourceState& attributionSource, audio_source_t source) {
153 return checkRecordingInternal(attributionSource, String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800154}
155
Svet Ganov33761132021-05-13 22:51:08 +0000156bool startRecording(const AttributionSourceState& attributionSource, const String16& msg,
157 audio_source_t source) {
158 return checkRecordingInternal(attributionSource, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800159}
160
Svet Ganov33761132021-05-13 22:51:08 +0000161void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800162 // Okay to not track in app ops as audio server is us and if
163 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000164 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
165 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800166
Svet Ganov33761132021-05-13 22:51:08 +0000167 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
168 // may open a record track on behalf of a client. Note that pid may be a tid.
169 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
170 const std::optional<AttributionSourceState> resolvedAttributionSource =
171 resolveAttributionSource(attributionSource);
172 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800173 return;
174 }
175
Svet Ganov33761132021-05-13 22:51:08 +0000176 const int32_t attributedOpCode = getOpForSource(source);
177 permission::PermissionChecker permissionChecker;
178 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
179 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800180}
181
Svet Ganov33761132021-05-13 22:51:08 +0000182bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
183 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
184 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700185 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700186 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800187 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700188 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700189 return ok;
190}
191
Svet Ganov33761132021-05-13 22:51:08 +0000192bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
193 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
194 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800195 if (isAudioServerOrRootUid(uid)) return true;
196 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
197 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
198 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
199 return ok;
200}
201
Svet Ganov33761132021-05-13 22:51:08 +0000202bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
203 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
204 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800205 if (isAudioServerOrRootUid(uid)) return true;
206 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
207 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
208 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
209 return ok;
210}
211
Svet Ganov33761132021-05-13 22:51:08 +0000212bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
213 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
214 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200215 if (isAudioServerOrRootUid(uid)) return true;
216 static const String16 sCaptureVoiceCommOutput(
217 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
218 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
219 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
220 return ok;
221}
222
Svet Ganov33761132021-05-13 22:51:08 +0000223bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700224 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000225 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700226
227 if (ok) {
228 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700229 // Use PermissionChecker, which includes some logic for allowing the isolated
230 // HotwordDetectionService to hold certain permissions.
231 permission::PermissionChecker permissionChecker;
232 ok = (permissionChecker.checkPermissionForPreflight(
233 sCaptureHotwordAllowed, attributionSource, String16(),
234 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700235 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700236 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700237 return ok;
238}
239
Glenn Kasten44deb052012-02-05 18:09:08 -0800240bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700241 // given this is a permission check, could this be isAudioServerOrRootUid()?
242 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800243 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700244 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
245 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800246 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
247 return ok;
248}
249
Eric Laurent5284ed52014-05-29 14:37:38 -0700250bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000251 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800252}
253
Svet Ganov33761132021-05-13 22:51:08 +0000254bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
255 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
256 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800257 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700258 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800259 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
260 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
261 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700262 return ok;
263}
264
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700265bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000266 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800267}
268
Svet Ganov33761132021-05-13 22:51:08 +0000269bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
270 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
271 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800272 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
273
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700274 static const String16 sModifyDefaultAudioEffectsAllowed(
275 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
276 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800277 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
278 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
279 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700280 return ok;
281}
282
Glenn Kasten44deb052012-02-05 18:09:08 -0800283bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800284 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700285 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800286 bool ok = PermissionCache::checkCallingPermission(sDump);
287 // convention is for caller to dump an error message to fd instead of logging here
288 //if (!ok) ALOGE("Request requires android.permission.DUMP");
289 return ok;
290}
291
Svet Ganov33761132021-05-13 22:51:08 +0000292bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
293 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
294 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800295 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700296 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
297 return ok;
298}
299
300// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000301bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
302 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
303 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700304 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
305 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
306 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
307 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
308 ALOGE_IF(!ok, "Request requires %s or %s",
309 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200310 return ok;
311}
312
Eric Laurentb0eff0f2021-11-09 16:05:49 +0100313bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
314 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
315 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
316
317 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
318 bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
319 if (!ok) ALOGE("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
320 __func__, uid);
321 return ok;
322}
323
Svet Ganov33761132021-05-13 22:51:08 +0000324AttributionSourceState getCallingAttributionSource() {
325 AttributionSourceState attributionSource = AttributionSourceState();
326 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
327 IPCThreadState::self()->getCallingPid()));
328 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
329 IPCThreadState::self()->getCallingUid()));
330 attributionSource.token = sp<BBinder>::make();
331 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700332}
333
Eric Laurent269acb42021-04-23 16:53:22 +0200334void purgePermissionCache() {
335 PermissionCache::purgeCache();
336}
337
Eric Laurent9b11c022018-06-06 19:19:22 -0700338status_t checkIMemory(const sp<IMemory>& iMemory)
339{
340 if (iMemory == 0) {
341 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
342 return BAD_VALUE;
343 }
344
345 sp<IMemoryHeap> heap = iMemory->getMemory();
346 if (heap == 0) {
347 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
348 return BAD_VALUE;
349 }
350
351 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
352 lseek(heap->getHeapID(), 0, SEEK_SET);
353
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700354 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700355 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700356 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700357 return BAD_VALUE;
358 }
359
360 return NO_ERROR;
361}
362
Oreste Salerno703ec262020-12-17 16:38:38 +0100363sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800364 const sp<IServiceManager> sm = defaultServiceManager();
365 if (sm == nullptr) {
366 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700367 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800368 }
369 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
370 if (packageManager == nullptr) {
371 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700372 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800373 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700374 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800375}
376
377std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
378 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700379 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100380 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700381 if (mPackageManager == nullptr) {
382 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
383 return std::nullopt;
384 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800385 }
386
Oreste Salerno703ec262020-12-17 16:38:38 +0100387 // Retrieve package names for the UID and transform to a std::vector<std::string>.
388 Vector<String16> str16PackageNames;
389 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800390 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100391 for (const auto& str16PackageName : str16PackageNames) {
392 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800393 }
394 if (packageNames.empty()) {
395 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100396 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800397 return std::nullopt;
398 }
399 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100400 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800401 if (!status.isOk()) {
402 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
403 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
404 return std::nullopt;
405 }
406 if (packageNames.size() != isAllowed.size()) {
407 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
408 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
409 return std::nullopt;
410 }
411
412 // Zip together packageNames and isAllowed for debug logs
413 Packages& packages = mDebugLog[uid];
414 packages.resize(packageNames.size()); // Reuse all objects
415 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
416 begin(packages), [] (auto& name, bool isAllowed) -> Package {
417 return {std::move(name), isAllowed};
418 });
419
420 // Only allow playback record if all packages in this UID allow it
421 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
422 [](bool b) { return b; });
423
424 return playbackCaptureAllowed;
425}
426
427void MediaPackageManager::dump(int fd, int spaces) const {
428 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
429 if (mPackageManager == nullptr) {
430 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
431 }
432 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
433
434 for (const auto& uidCache : mDebugLog) {
435 for (const auto& package : std::get<Packages>(uidCache)) {
436 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
437 std::get<const uid_t>(uidCache),
438 package.playbackCaptureAllowed ? "true " : "false",
439 package.name.c_str());
440 }
441 }
442}
443
Andy Hunga85efab2019-12-23 11:41:29 -0800444// How long we hold info before we re-fetch it (24 hours) if we found it previously.
445static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
446// Maximum info records we retain before clearing everything.
447static constexpr size_t INFO_CACHE_MAX = 1000;
448
449// The original code is from MediaMetricsService.cpp.
450mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
451{
452 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
453 struct mediautils::UidInfo::Info info;
454 {
455 std::lock_guard _l(mLock);
456 auto it = mInfoMap.find(uid);
457 if (it != mInfoMap.end()) {
458 info = it->second;
459 ALOGV("%s: uid %d expiration %lld now %lld",
460 __func__, uid, (long long)info.expirationNs, (long long)now);
461 if (info.expirationNs <= now) {
462 // purge the stale entry and fall into re-fetching
463 ALOGV("%s: entry for uid %d expired, now %lld",
464 __func__, uid, (long long)now);
465 mInfoMap.erase(it);
466 info.uid = (uid_t)-1; // this is always fully overwritten
467 }
468 }
469 }
470
471 // if we did not find it in our map, look it up
472 if (info.uid == (uid_t)(-1)) {
473 sp<IServiceManager> sm = defaultServiceManager();
474 sp<content::pm::IPackageManagerNative> package_mgr;
475 if (sm.get() == nullptr) {
476 ALOGE("%s: Cannot find service manager", __func__);
477 } else {
478 sp<IBinder> binder = sm->getService(String16("package_native"));
479 if (binder.get() == nullptr) {
480 ALOGE("%s: Cannot find package_native", __func__);
481 } else {
482 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
483 }
484 }
485
486 // find package name
487 std::string pkg;
488 if (package_mgr != nullptr) {
489 std::vector<std::string> names;
490 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
491 if (!status.isOk()) {
492 ALOGE("%s: getNamesForUids failed: %s",
493 __func__, status.exceptionMessage().c_str());
494 } else {
495 if (!names[0].empty()) {
496 pkg = names[0].c_str();
497 }
498 }
499 }
500
501 if (pkg.empty()) {
502 struct passwd pw{}, *result;
503 char buf[8192]; // extra buffer space - should exceed what is
504 // required in struct passwd_pw (tested),
505 // and even then this is only used in backup
506 // when the package manager is unavailable.
507 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
508 && result != nullptr
509 && result->pw_name != nullptr) {
510 pkg = result->pw_name;
511 }
512 }
513
514 // strip any leading "shared:" strings that came back
515 if (pkg.compare(0, 7, "shared:") == 0) {
516 pkg.erase(0, 7);
517 }
518
519 // determine how pkg was installed and the versionCode
520 std::string installer;
521 int64_t versionCode = 0;
522 bool notFound = false;
523 if (pkg.empty()) {
524 pkg = std::to_string(uid); // not found
525 notFound = true;
526 } else if (strchr(pkg.c_str(), '.') == nullptr) {
527 // not of form 'com.whatever...'; assume internal
528 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800529 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
530 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800531 } else if (package_mgr.get() != nullptr) {
532 String16 pkgName16(pkg.c_str());
533 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
534 if (!status.isOk()) {
535 ALOGE("%s: getInstallerForPackage failed: %s",
536 __func__, status.exceptionMessage().c_str());
537 }
538
539 // skip if we didn't get an installer
540 if (status.isOk()) {
541 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
542 if (!status.isOk()) {
543 ALOGE("%s: getVersionCodeForPackage failed: %s",
544 __func__, status.exceptionMessage().c_str());
545 }
546 }
547
548 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
549 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
550 }
551
552 // add it to the map, to save a subsequent lookup
553 std::lock_guard _l(mLock);
554 // first clear if we have too many cached elements. This would be rare.
555 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
556
557 // always overwrite
558 info.uid = uid;
559 info.package = std::move(pkg);
560 info.installer = std::move(installer);
561 info.versionCode = versionCode;
562 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
563 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
564 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
565 mInfoMap[uid] = info;
566 }
567 return info;
568}
569
Glenn Kasten44deb052012-02-05 18:09:08 -0800570} // namespace android