blob: 42f48a542ee918fe0fbc88b200a465a84a32aab6 [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;
74 case AUDIO_SOURCE_REMOTE_SUBMIX:
75 return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
Nate Myrenf7c88352021-04-12 14:41:49 -070076 case AUDIO_SOURCE_VOICE_DOWNLINK:
77 return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
Nate Myrene69cada2020-12-10 10:00:36 -080078 case AUDIO_SOURCE_DEFAULT:
79 default:
80 return AppOpsManager::OP_RECORD_AUDIO;
81 }
82}
83
Svet Ganov33761132021-05-13 22:51:08 +000084std::optional<AttributionSourceState> resolveAttributionSource(
85 const AttributionSourceState& callerAttributionSource) {
86 AttributionSourceState nextAttributionSource = callerAttributionSource;
87
88 if (!nextAttributionSource.packageName.has_value()) {
89 nextAttributionSource = AttributionSourceState(nextAttributionSource);
90 PermissionController permissionController;
91 const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
92 nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
93 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
94 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
95 uid)));
96 if (!nextAttributionSource.packageName.has_value()) {
97 return std::nullopt;
98 }
99 }
100
101 AttributionSourceState myAttributionSource;
102 myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
103 myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
Lei Shic8fbfd42021-11-03 15:41:51 +0800104 if (callerAttributionSource.token != nullptr) {
105 myAttributionSource.token = callerAttributionSource.token;
106 } else {
107 myAttributionSource.token = sp<BBinder>::make();
108 }
Svet Ganov33761132021-05-13 22:51:08 +0000109 myAttributionSource.next.push_back(nextAttributionSource);
110
111 return std::optional<AttributionSourceState>{myAttributionSource};
112}
113
114static bool checkRecordingInternal(const AttributionSourceState& attributionSource,
115 const String16& msg, bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -0700116 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -0800117 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -0700118 // system_server loses its RECORD_AUDIO permission when a secondary
119 // user is active, but it is a core system service so let it through.
120 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Svet Ganov33761132021-05-13 22:51:08 +0000121 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -0700122 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000123
Svet Ganov5b81f552018-03-02 09:21:30 -0800124 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
Svet Ganov33761132021-05-13 22:51:08 +0000125 // may open a record track on behalf of a client. Note that pid may be a tid.
Svet Ganov5b81f552018-03-02 09:21:30 -0800126 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
Svet Ganov33761132021-05-13 22:51:08 +0000127 const std::optional<AttributionSourceState> resolvedAttributionSource =
128 resolveAttributionSource(attributionSource);
129 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800130 return false;
131 }
132
Svet Ganov33761132021-05-13 22:51:08 +0000133 const int32_t attributedOpCode = getOpForSource(source);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000134
Svet Ganov33761132021-05-13 22:51:08 +0000135 permission::PermissionChecker permissionChecker;
136 bool permitted = false;
Svet Ganov5b81f552018-03-02 09:21:30 -0800137 if (start) {
Svet Ganov33761132021-05-13 22:51:08 +0000138 permitted = (permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
139 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
140 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svet Ganov5b81f552018-03-02 09:21:30 -0800141 } else {
Svet Ganov33761132021-05-13 22:51:08 +0000142 permitted = (permissionChecker.checkPermissionForPreflightFromDatasource(
143 sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
144 attributedOpCode) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000145 }
146
Svet Ganov33761132021-05-13 22:51:08 +0000147 return permitted;
Glenn Kasten44deb052012-02-05 18:09:08 -0800148}
149
Svet Ganov33761132021-05-13 22:51:08 +0000150bool recordingAllowed(const AttributionSourceState& attributionSource, audio_source_t source) {
151 return checkRecordingInternal(attributionSource, String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800152}
153
Svet Ganov33761132021-05-13 22:51:08 +0000154bool startRecording(const AttributionSourceState& attributionSource, const String16& msg,
155 audio_source_t source) {
156 return checkRecordingInternal(attributionSource, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800157}
158
Svet Ganov33761132021-05-13 22:51:08 +0000159void finishRecording(const AttributionSourceState& attributionSource, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800160 // Okay to not track in app ops as audio server is us and if
161 // device is rooted security model is considered compromised.
Svet Ganov33761132021-05-13 22:51:08 +0000162 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
163 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800164
Svet Ganov33761132021-05-13 22:51:08 +0000165 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
166 // may open a record track on behalf of a client. Note that pid may be a tid.
167 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
168 const std::optional<AttributionSourceState> resolvedAttributionSource =
169 resolveAttributionSource(attributionSource);
170 if (!resolvedAttributionSource.has_value()) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800171 return;
172 }
173
Svet Ganov33761132021-05-13 22:51:08 +0000174 const int32_t attributedOpCode = getOpForSource(source);
175 permission::PermissionChecker permissionChecker;
176 permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
177 resolvedAttributionSource.value());
Svet Ganov5b81f552018-03-02 09:21:30 -0800178}
179
Svet Ganov33761132021-05-13 22:51:08 +0000180bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
181 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
182 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700183 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700184 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800185 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700186 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700187 return ok;
188}
189
Svet Ganov33761132021-05-13 22:51:08 +0000190bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
191 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
192 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800193 if (isAudioServerOrRootUid(uid)) return true;
194 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
195 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
196 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
197 return ok;
198}
199
Svet Ganov33761132021-05-13 22:51:08 +0000200bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
201 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
202 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800203 if (isAudioServerOrRootUid(uid)) return true;
204 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
205 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
206 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
207 return ok;
208}
209
Svet Ganov33761132021-05-13 22:51:08 +0000210bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
211 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
212 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200213 if (isAudioServerOrRootUid(uid)) return true;
214 static const String16 sCaptureVoiceCommOutput(
215 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
216 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
217 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
218 return ok;
219}
220
Svet Ganov33761132021-05-13 22:51:08 +0000221bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
Eric Laurent7504b9e2017-08-15 18:17:26 -0700222 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Svet Ganov33761132021-05-13 22:51:08 +0000223 bool ok = recordingAllowed(attributionSource);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700224
225 if (ok) {
226 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Ahaan Ugaleb18227c2021-06-07 11:52:54 -0700227 // Use PermissionChecker, which includes some logic for allowing the isolated
228 // HotwordDetectionService to hold certain permissions.
229 permission::PermissionChecker permissionChecker;
230 ok = (permissionChecker.checkPermissionForPreflight(
231 sCaptureHotwordAllowed, attributionSource, String16(),
232 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700233 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700234 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700235 return ok;
236}
237
Glenn Kasten44deb052012-02-05 18:09:08 -0800238bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700239 // given this is a permission check, could this be isAudioServerOrRootUid()?
240 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800241 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700242 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
243 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800244 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
245 return ok;
246}
247
Eric Laurent5284ed52014-05-29 14:37:38 -0700248bool modifyAudioRoutingAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000249 return modifyAudioRoutingAllowed(getCallingAttributionSource());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800250}
251
Svet Ganov33761132021-05-13 22:51:08 +0000252bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
253 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
254 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800255 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700256 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800257 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
258 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
259 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700260 return ok;
261}
262
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700263bool modifyDefaultAudioEffectsAllowed() {
Svet Ganov33761132021-05-13 22:51:08 +0000264 return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800265}
266
Svet Ganov33761132021-05-13 22:51:08 +0000267bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
268 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
269 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800270 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
271
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700272 static const String16 sModifyDefaultAudioEffectsAllowed(
273 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
274 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800275 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
276 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
277 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700278 return ok;
279}
280
Glenn Kasten44deb052012-02-05 18:09:08 -0800281bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800282 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700283 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800284 bool ok = PermissionCache::checkCallingPermission(sDump);
285 // convention is for caller to dump an error message to fd instead of logging here
286 //if (!ok) ALOGE("Request requires android.permission.DUMP");
287 return ok;
288}
289
Svet Ganov33761132021-05-13 22:51:08 +0000290bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
291 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
292 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800293 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700294 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
295 return ok;
296}
297
298// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Svet Ganov33761132021-05-13 22:51:08 +0000299bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
300 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
301 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700302 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
303 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
304 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
305 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
306 ALOGE_IF(!ok, "Request requires %s or %s",
307 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200308 return ok;
309}
310
Svet Ganov33761132021-05-13 22:51:08 +0000311AttributionSourceState getCallingAttributionSource() {
312 AttributionSourceState attributionSource = AttributionSourceState();
313 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
314 IPCThreadState::self()->getCallingPid()));
315 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
316 IPCThreadState::self()->getCallingUid()));
317 attributionSource.token = sp<BBinder>::make();
318 return attributionSource;
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700319}
320
Eric Laurent269acb42021-04-23 16:53:22 +0200321void purgePermissionCache() {
322 PermissionCache::purgeCache();
323}
324
Eric Laurent9b11c022018-06-06 19:19:22 -0700325status_t checkIMemory(const sp<IMemory>& iMemory)
326{
327 if (iMemory == 0) {
328 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
329 return BAD_VALUE;
330 }
331
332 sp<IMemoryHeap> heap = iMemory->getMemory();
333 if (heap == 0) {
334 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
335 return BAD_VALUE;
336 }
337
338 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
339 lseek(heap->getHeapID(), 0, SEEK_SET);
340
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700341 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700342 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700343 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700344 return BAD_VALUE;
345 }
346
347 return NO_ERROR;
348}
349
Oreste Salerno703ec262020-12-17 16:38:38 +0100350sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800351 const sp<IServiceManager> sm = defaultServiceManager();
352 if (sm == nullptr) {
353 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700354 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800355 }
356 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
357 if (packageManager == nullptr) {
358 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700359 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800360 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700361 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800362}
363
364std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
365 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700366 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100367 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700368 if (mPackageManager == nullptr) {
369 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
370 return std::nullopt;
371 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800372 }
373
Oreste Salerno703ec262020-12-17 16:38:38 +0100374 // Retrieve package names for the UID and transform to a std::vector<std::string>.
375 Vector<String16> str16PackageNames;
376 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800377 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100378 for (const auto& str16PackageName : str16PackageNames) {
379 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800380 }
381 if (packageNames.empty()) {
382 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100383 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800384 return std::nullopt;
385 }
386 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100387 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800388 if (!status.isOk()) {
389 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
390 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
391 return std::nullopt;
392 }
393 if (packageNames.size() != isAllowed.size()) {
394 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
395 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
396 return std::nullopt;
397 }
398
399 // Zip together packageNames and isAllowed for debug logs
400 Packages& packages = mDebugLog[uid];
401 packages.resize(packageNames.size()); // Reuse all objects
402 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
403 begin(packages), [] (auto& name, bool isAllowed) -> Package {
404 return {std::move(name), isAllowed};
405 });
406
407 // Only allow playback record if all packages in this UID allow it
408 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
409 [](bool b) { return b; });
410
411 return playbackCaptureAllowed;
412}
413
414void MediaPackageManager::dump(int fd, int spaces) const {
415 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
416 if (mPackageManager == nullptr) {
417 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
418 }
419 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
420
421 for (const auto& uidCache : mDebugLog) {
422 for (const auto& package : std::get<Packages>(uidCache)) {
423 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
424 std::get<const uid_t>(uidCache),
425 package.playbackCaptureAllowed ? "true " : "false",
426 package.name.c_str());
427 }
428 }
429}
430
Andy Hunga85efab2019-12-23 11:41:29 -0800431// How long we hold info before we re-fetch it (24 hours) if we found it previously.
432static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
433// Maximum info records we retain before clearing everything.
434static constexpr size_t INFO_CACHE_MAX = 1000;
435
436// The original code is from MediaMetricsService.cpp.
437mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
438{
439 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
440 struct mediautils::UidInfo::Info info;
441 {
442 std::lock_guard _l(mLock);
443 auto it = mInfoMap.find(uid);
444 if (it != mInfoMap.end()) {
445 info = it->second;
446 ALOGV("%s: uid %d expiration %lld now %lld",
447 __func__, uid, (long long)info.expirationNs, (long long)now);
448 if (info.expirationNs <= now) {
449 // purge the stale entry and fall into re-fetching
450 ALOGV("%s: entry for uid %d expired, now %lld",
451 __func__, uid, (long long)now);
452 mInfoMap.erase(it);
453 info.uid = (uid_t)-1; // this is always fully overwritten
454 }
455 }
456 }
457
458 // if we did not find it in our map, look it up
459 if (info.uid == (uid_t)(-1)) {
460 sp<IServiceManager> sm = defaultServiceManager();
461 sp<content::pm::IPackageManagerNative> package_mgr;
462 if (sm.get() == nullptr) {
463 ALOGE("%s: Cannot find service manager", __func__);
464 } else {
465 sp<IBinder> binder = sm->getService(String16("package_native"));
466 if (binder.get() == nullptr) {
467 ALOGE("%s: Cannot find package_native", __func__);
468 } else {
469 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
470 }
471 }
472
473 // find package name
474 std::string pkg;
475 if (package_mgr != nullptr) {
476 std::vector<std::string> names;
477 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
478 if (!status.isOk()) {
479 ALOGE("%s: getNamesForUids failed: %s",
480 __func__, status.exceptionMessage().c_str());
481 } else {
482 if (!names[0].empty()) {
483 pkg = names[0].c_str();
484 }
485 }
486 }
487
488 if (pkg.empty()) {
489 struct passwd pw{}, *result;
490 char buf[8192]; // extra buffer space - should exceed what is
491 // required in struct passwd_pw (tested),
492 // and even then this is only used in backup
493 // when the package manager is unavailable.
494 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
495 && result != nullptr
496 && result->pw_name != nullptr) {
497 pkg = result->pw_name;
498 }
499 }
500
501 // strip any leading "shared:" strings that came back
502 if (pkg.compare(0, 7, "shared:") == 0) {
503 pkg.erase(0, 7);
504 }
505
506 // determine how pkg was installed and the versionCode
507 std::string installer;
508 int64_t versionCode = 0;
509 bool notFound = false;
510 if (pkg.empty()) {
511 pkg = std::to_string(uid); // not found
512 notFound = true;
513 } else if (strchr(pkg.c_str(), '.') == nullptr) {
514 // not of form 'com.whatever...'; assume internal
515 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800516 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
517 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800518 } else if (package_mgr.get() != nullptr) {
519 String16 pkgName16(pkg.c_str());
520 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
521 if (!status.isOk()) {
522 ALOGE("%s: getInstallerForPackage failed: %s",
523 __func__, status.exceptionMessage().c_str());
524 }
525
526 // skip if we didn't get an installer
527 if (status.isOk()) {
528 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
529 if (!status.isOk()) {
530 ALOGE("%s: getVersionCodeForPackage failed: %s",
531 __func__, status.exceptionMessage().c_str());
532 }
533 }
534
535 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
536 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
537 }
538
539 // add it to the map, to save a subsequent lookup
540 std::lock_guard _l(mLock);
541 // first clear if we have too many cached elements. This would be rare.
542 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
543
544 // always overwrite
545 info.uid = uid;
546 info.package = std::move(pkg);
547 info.installer = std::move(installer);
548 info.versionCode = versionCode;
549 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
550 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
551 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
552 mInfoMap[uid] = info;
553 }
554 return info;
555}
556
Glenn Kasten44deb052012-02-05 18:09:08 -0800557} // namespace android