blob: 9620d2498fcdc3621fe4c7f22c024be1c148fea6 [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");
Svet Ganov5b81f552018-03-02 09:21:30 -080048
Svet Ganov5b81f552018-03-02 09:21:30 -080049static String16 resolveCallingPackage(PermissionController& permissionController,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070050 const std::optional<String16> opPackageName, uid_t uid) {
51 if (opPackageName.has_value() && opPackageName.value().size() > 0) {
52 return opPackageName.value();
Svet Ganovbe71aa22015-04-28 12:06:02 -070053 }
Svet Ganovbe71aa22015-04-28 12:06:02 -070054 // In some cases the calling code has no access to the package it runs under.
55 // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
56 // case we will get the packages for the calling UID and pick the first one
57 // for attributing the app op. This will work correctly for runtime permissions
58 // as for legacy apps we will toggle the app op for all packages in the UID.
59 // The caveat is that the operation may be attributed to the wrong package and
60 // stats based on app ops may be slightly off.
Svet Ganov5b81f552018-03-02 09:21:30 -080061 Vector<String16> packages;
62 permissionController.getPackagesForUid(uid, packages);
63 if (packages.isEmpty()) {
64 ALOGE("No packages for uid %d", uid);
Philip P. Moltmannbda45752020-07-17 16:41:18 -070065 return String16();
Svet Ganov5b81f552018-03-02 09:21:30 -080066 }
67 return packages[0];
68}
Svetoslav Ganov599ec462018-03-01 22:19:55 +000069
Eric Laurent45e16b92021-05-20 11:10:47 +020070int32_t getOpForSource(audio_source_t source) {
Nate Myrene69cada2020-12-10 10:00:36 -080071 switch (source) {
72 case AUDIO_SOURCE_HOTWORD:
73 return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
Mickey Keeley90d657d2021-10-20 18:06:38 -070074 case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
Nate Myrene69cada2020-12-10 10:00:36 -080075 case AUDIO_SOURCE_REMOTE_SUBMIX:
76 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070077 case AUDIO_SOURCE_VOICE_DOWNLINK:
78 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080079 case AUDIO_SOURCE_DEFAULT:
80 default:
81 return AppOpsManager::OP_RECORD_AUDIO;
82 }
83}
84
Svet Ganov33761132021-05-13 22:51:08 +000085std::optional<AttributionSourceState> resolveAttributionSource(
86 const AttributionSourceState& callerAttributionSource) {
87 AttributionSourceState nextAttributionSource = callerAttributionSource;
88
89 if (!nextAttributionSource.packageName.has_value()) {
90 nextAttributionSource = AttributionSourceState(nextAttributionSource);
91 PermissionController permissionController;
92 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
93 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
94 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
95 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
96 uid)));
97 if (!nextAttributionSource.packageName.has_value()) {
98 return std::nullopt;
99 }
100 }
101
102 AttributionSourceState myAttributionSource;
103 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
104 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
105 myAttributionSource.token = sp<BBinder>::make();
106 myAttributionSource.next.push_back(nextAttributionSource);
107
108 return std::optional<AttributionSourceState>{myAttributionSource};
109}
110
111static bool checkRecordingInternal(const AttributionSourceState& attributionSource,
112 const String16& msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700113 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800114 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700115 // system_server loses its RECORD_AUDIO permission when a secondary
116 // user is active, but it is a core system service so let it through.
117 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000118 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700119 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000120
Svet Ganov5b81f552018-03-02 09:21:30 -0800121 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000122 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800123 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Svet Ganov33761132021-05-13 22:51:08 +0000124 const std::optional<AttributionSourceState> resolvedAttributionSource =
125 resolveAttributionSource(attributionSource);
126 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800127 return false;
128 }
129
Svet Ganov33761132021-05-13 22:51:08 +0000130 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000131
Svet Ganov33761132021-05-13 22:51:08 +0000132 permission::PermissionChecker permissionChecker;
133 bool permitted = false;
Svet Ganov5b81f552018-03-02 09:21:30 -0800134 if (start) {
Svet Ganov33761132021-05-13 22:51:08 +0000135 permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
136 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
137 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svet Ganov5b81f552018-03-02 09:21:30 -0800138 } else {
Svet Ganov33761132021-05-13 22:51:08 +0000139 permitted = (permissionChecker.checkPermissionForPreflightFromDatasource(
140 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
141 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000142 }
143
Svet Ganov33761132021-05-13 22:51:08 +0000144 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800145}
146
Svet Ganov33761132021-05-13 22:51:08 +0000147bool recordingAllowed(const AttributionSourceState& attributionSource, audio_source_t source) {
148 return checkRecordingInternal(attributionSource, String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800149}
150
Svet Ganov33761132021-05-13 22:51:08 +0000151bool startRecording(const AttributionSourceState& attributionSource, const String16& msg,
152 audio_source_t source) {
153 return checkRecordingInternal(attributionSource, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800154}
155
Svet Ganov33761132021-05-13 22:51:08 +0000156void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800157 // Okay to not track in app ops as audio server is us and if
158 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000159 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
160 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800161
Svet Ganov33761132021-05-13 22:51:08 +0000162 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
163 // may open a record track on behalf of a client. Note that pid may be a tid.
164 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
165 const std::optional<AttributionSourceState> resolvedAttributionSource =
166 resolveAttributionSource(attributionSource);
167 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800168 return;
169 }
170
Svet Ganov33761132021-05-13 22:51:08 +0000171 const int32_t attributedOpCode = getOpForSource(source);
172 permission::PermissionChecker permissionChecker;
173 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
174 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800175}
176
Svet Ganov33761132021-05-13 22:51:08 +0000177bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
178 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
179 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700180 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700181 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800182 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700183 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700184 return ok;
185}
186
Svet Ganov33761132021-05-13 22:51:08 +0000187bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
188 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
189 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800190 if (isAudioServerOrRootUid(uid)) return true;
191 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
192 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
193 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
194 return ok;
195}
196
Svet Ganov33761132021-05-13 22:51:08 +0000197bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
198 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
199 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800200 if (isAudioServerOrRootUid(uid)) return true;
201 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
202 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
203 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
204 return ok;
205}
206
Svet Ganov33761132021-05-13 22:51:08 +0000207bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
208 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
209 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200210 if (isAudioServerOrRootUid(uid)) return true;
211 static const String16 sCaptureVoiceCommOutput(
212 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
213 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
214 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
215 return ok;
216}
217
Svet Ganov33761132021-05-13 22:51:08 +0000218bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700219 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000220 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700221
222 if (ok) {
223 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700224 // Use PermissionChecker, which includes some logic for allowing the isolated
225 // HotwordDetectionService to hold certain permissions.
226 permission::PermissionChecker permissionChecker;
227 ok = (permissionChecker.checkPermissionForPreflight(
228 sCaptureHotwordAllowed, attributionSource, String16(),
229 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700230 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700231 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700232 return ok;
233}
234
Glenn Kasten44deb052012-02-05 18:09:08 -0800235bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700236 // given this is a permission check, could this be isAudioServerOrRootUid()?
237 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800238 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700239 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
240 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800241 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
242 return ok;
243}
244
Eric Laurent5284ed52014-05-29 14:37:38 -0700245bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000246 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800247}
248
Svet Ganov33761132021-05-13 22:51:08 +0000249bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
250 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
251 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800252 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700253 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800254 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
255 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
256 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700257 return ok;
258}
259
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700260bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000261 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800262}
263
Svet Ganov33761132021-05-13 22:51:08 +0000264bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
265 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
266 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800267 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
268
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700269 static const String16 sModifyDefaultAudioEffectsAllowed(
270 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
271 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800272 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
273 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
274 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700275 return ok;
276}
277
Glenn Kasten44deb052012-02-05 18:09:08 -0800278bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800279 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700280 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800281 bool ok = PermissionCache::checkCallingPermission(sDump);
282 // convention is for caller to dump an error message to fd instead of logging here
283 //if (!ok) ALOGE("Request requires android.permission.DUMP");
284 return ok;
285}
286
Svet Ganov33761132021-05-13 22:51:08 +0000287bool modifyPhoneStateAllowed(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));
Svet Ganov5b81f552018-03-02 09:21:30 -0800290 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700291 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
292 return ok;
293}
294
295// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000296bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
297 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
298 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700299 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
300 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
301 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
302 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
303 ALOGE_IF(!ok, "Request requires %s or %s",
304 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200305 return ok;
306}
307
Svet Ganov33761132021-05-13 22:51:08 +0000308AttributionSourceState getCallingAttributionSource() {
309 AttributionSourceState attributionSource = AttributionSourceState();
310 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
311 IPCThreadState::self()->getCallingPid()));
312 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
313 IPCThreadState::self()->getCallingUid()));
314 attributionSource.token = sp<BBinder>::make();
315 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700316}
317
Eric Laurent269acb42021-04-23 16:53:22 +0200318void purgePermissionCache() {
319 PermissionCache::purgeCache();
320}
321
Eric Laurent9b11c022018-06-06 19:19:22 -0700322status_t checkIMemory(const sp<IMemory>& iMemory)
323{
324 if (iMemory == 0) {
325 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
326 return BAD_VALUE;
327 }
328
329 sp<IMemoryHeap> heap = iMemory->getMemory();
330 if (heap == 0) {
331 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
332 return BAD_VALUE;
333 }
334
335 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
336 lseek(heap->getHeapID(), 0, SEEK_SET);
337
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700338 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700339 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700340 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700341 return BAD_VALUE;
342 }
343
344 return NO_ERROR;
345}
346
Oreste Salerno703ec262020-12-17 16:38:38 +0100347sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800348 const sp<IServiceManager> sm = defaultServiceManager();
349 if (sm == nullptr) {
350 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700351 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800352 }
353 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
354 if (packageManager == nullptr) {
355 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700356 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800357 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700358 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800359}
360
361std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
362 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700363 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100364 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700365 if (mPackageManager == nullptr) {
366 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
367 return std::nullopt;
368 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800369 }
370
Oreste Salerno703ec262020-12-17 16:38:38 +0100371 // Retrieve package names for the UID and transform to a std::vector<std::string>.
372 Vector<String16> str16PackageNames;
373 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800374 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100375 for (const auto& str16PackageName : str16PackageNames) {
376 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800377 }
378 if (packageNames.empty()) {
379 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100380 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800381 return std::nullopt;
382 }
383 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100384 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800385 if (!status.isOk()) {
386 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
387 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
388 return std::nullopt;
389 }
390 if (packageNames.size() != isAllowed.size()) {
391 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
392 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
393 return std::nullopt;
394 }
395
396 // Zip together packageNames and isAllowed for debug logs
397 Packages& packages = mDebugLog[uid];
398 packages.resize(packageNames.size()); // Reuse all objects
399 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
400 begin(packages), [] (auto& name, bool isAllowed) -> Package {
401 return {std::move(name), isAllowed};
402 });
403
404 // Only allow playback record if all packages in this UID allow it
405 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
406 [](bool b) { return b; });
407
408 return playbackCaptureAllowed;
409}
410
411void MediaPackageManager::dump(int fd, int spaces) const {
412 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
413 if (mPackageManager == nullptr) {
414 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
415 }
416 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
417
418 for (const auto& uidCache : mDebugLog) {
419 for (const auto& package : std::get<Packages>(uidCache)) {
420 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
421 std::get<const uid_t>(uidCache),
422 package.playbackCaptureAllowed ? "true " : "false",
423 package.name.c_str());
424 }
425 }
426}
427
Andy Hunga85efab2019-12-23 11:41:29 -0800428// How long we hold info before we re-fetch it (24 hours) if we found it previously.
429static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
430// Maximum info records we retain before clearing everything.
431static constexpr size_t INFO_CACHE_MAX = 1000;
432
433// The original code is from MediaMetricsService.cpp.
434mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
435{
436 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
437 struct mediautils::UidInfo::Info info;
438 {
439 std::lock_guard _l(mLock);
440 auto it = mInfoMap.find(uid);
441 if (it != mInfoMap.end()) {
442 info = it->second;
443 ALOGV("%s: uid %d expiration %lld now %lld",
444 __func__, uid, (long long)info.expirationNs, (long long)now);
445 if (info.expirationNs <= now) {
446 // purge the stale entry and fall into re-fetching
447 ALOGV("%s: entry for uid %d expired, now %lld",
448 __func__, uid, (long long)now);
449 mInfoMap.erase(it);
450 info.uid = (uid_t)-1; // this is always fully overwritten
451 }
452 }
453 }
454
455 // if we did not find it in our map, look it up
456 if (info.uid == (uid_t)(-1)) {
457 sp<IServiceManager> sm = defaultServiceManager();
458 sp<content::pm::IPackageManagerNative> package_mgr;
459 if (sm.get() == nullptr) {
460 ALOGE("%s: Cannot find service manager", __func__);
461 } else {
462 sp<IBinder> binder = sm->getService(String16("package_native"));
463 if (binder.get() == nullptr) {
464 ALOGE("%s: Cannot find package_native", __func__);
465 } else {
466 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
467 }
468 }
469
470 // find package name
471 std::string pkg;
472 if (package_mgr != nullptr) {
473 std::vector<std::string> names;
474 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
475 if (!status.isOk()) {
476 ALOGE("%s: getNamesForUids failed: %s",
477 __func__, status.exceptionMessage().c_str());
478 } else {
479 if (!names[0].empty()) {
480 pkg = names[0].c_str();
481 }
482 }
483 }
484
485 if (pkg.empty()) {
486 struct passwd pw{}, *result;
487 char buf[8192]; // extra buffer space - should exceed what is
488 // required in struct passwd_pw (tested),
489 // and even then this is only used in backup
490 // when the package manager is unavailable.
491 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
492 && result != nullptr
493 && result->pw_name != nullptr) {
494 pkg = result->pw_name;
495 }
496 }
497
498 // strip any leading "shared:" strings that came back
499 if (pkg.compare(0, 7, "shared:") == 0) {
500 pkg.erase(0, 7);
501 }
502
503 // determine how pkg was installed and the versionCode
504 std::string installer;
505 int64_t versionCode = 0;
506 bool notFound = false;
507 if (pkg.empty()) {
508 pkg = std::to_string(uid); // not found
509 notFound = true;
510 } else if (strchr(pkg.c_str(), '.') == nullptr) {
511 // not of form 'com.whatever...'; assume internal
512 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800513 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
514 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800515 } else if (package_mgr.get() != nullptr) {
516 String16 pkgName16(pkg.c_str());
517 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
518 if (!status.isOk()) {
519 ALOGE("%s: getInstallerForPackage failed: %s",
520 __func__, status.exceptionMessage().c_str());
521 }
522
523 // skip if we didn't get an installer
524 if (status.isOk()) {
525 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
526 if (!status.isOk()) {
527 ALOGE("%s: getVersionCodeForPackage failed: %s",
528 __func__, status.exceptionMessage().c_str());
529 }
530 }
531
532 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
533 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
534 }
535
536 // add it to the map, to save a subsequent lookup
537 std::lock_guard _l(mLock);
538 // first clear if we have too many cached elements. This would be rare.
539 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
540
541 // always overwrite
542 info.uid = uid;
543 info.package = std::move(pkg);
544 info.installer = std::move(installer);
545 info.versionCode = versionCode;
546 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
547 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
548 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
549 mInfoMap[uid] = info;
550 }
551 return info;
552}
553
Glenn Kasten44deb052012-02-05 18:09:08 -0800554} // namespace android