blob: 214a174ca1ec609c3a8c0b6b7f2f6f3df612edca [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>
28#include <android/media/permission/Identity.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
Philip P. Moltmannbda45752020-07-17 16:41:18 -070043using media::permission::Identity;
44
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
Philip P. Moltmannbda45752020-07-17 16:41:18 -070084static bool checkRecordingInternal(const Identity& identity, const String16& msg,
85 bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -070086 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -080087 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -070088 // system_server loses its RECORD_AUDIO permission when a secondary
89 // user is active, but it is a core system service so let it through.
90 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Philip P. Moltmannbda45752020-07-17 16:41:18 -070091 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -070092 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +000093
Svet Ganov5b81f552018-03-02 09:21:30 -080094 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
95 // may open a record track on behalf of a client. Note that pid may be a tid.
96 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
97 PermissionController permissionController;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070098 const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio,
99 identity.pid, identity.uid);
Svet Ganov5b81f552018-03-02 09:21:30 -0800100 if (!ok) {
101 ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
102 return false;
103 }
104
105 String16 resolvedOpPackageName = resolveCallingPackage(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700106 permissionController, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
107 identity.packageName.value_or(""))), uid);
Svet Ganov5b81f552018-03-02 09:21:30 -0800108 if (resolvedOpPackageName.size() == 0) {
109 return false;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700110 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000111
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700112
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000113 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800114 const int32_t op = getOpForSource(source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800115 if (start) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700116 if (int32_t mode = appOps.startOpNoThrow(op, identity.uid,
117 resolvedOpPackageName, /*startIfModeDefault*/ false,
118 VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16(
Evan Severson643423e2021-02-12 13:44:09 -0800119 identity.attributionTag)), msg) == AppOpsManager::MODE_ERRORED) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000120 ALOGE("Request start for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700121 String8(resolvedOpPackageName).c_str(), identity.uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800122 return false;
123 }
124 } else {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700125 if (int32_t mode = appOps.checkOp(op, uid,
Evan Severson643423e2021-02-12 13:44:09 -0800126 resolvedOpPackageName) == AppOpsManager::MODE_ERRORED) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000127 ALOGE("Request check for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700128 String8(resolvedOpPackageName).c_str(), identity.uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800129 return false;
130 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000131 }
132
133 return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800134}
135
Eric Laurent45e16b92021-05-20 11:10:47 +0200136bool recordingAllowed(const Identity& identity, audio_source_t source) {
137 return checkRecordingInternal(identity, String16(), /*start*/ false, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800138}
139
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700140bool startRecording(const Identity& identity, const String16& msg, audio_source_t source) {
141 return checkRecordingInternal(identity, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800142}
143
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700144void finishRecording(const Identity& identity, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800145 // Okay to not track in app ops as audio server is us and if
146 // device is rooted security model is considered compromised.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700147 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700148 if (isAudioServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800149
150 PermissionController permissionController;
151 String16 resolvedOpPackageName = resolveCallingPackage(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700152 permissionController,
153 VALUE_OR_FATAL(aidl2legacy_string_view_String16(identity.packageName.value_or(""))),
154 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800155 if (resolvedOpPackageName.size() == 0) {
156 return;
157 }
158
159 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800160
161 const int32_t op = getOpForSource(source);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700162 appOps.finishOp(op, identity.uid, resolvedOpPackageName,
163 VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16(
164 identity.attributionTag)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800165}
166
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700167bool captureAudioOutputAllowed(const Identity& identity) {
168 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
169 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700170 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700171 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800172 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700173 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700174 return ok;
175}
176
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700177bool captureMediaOutputAllowed(const Identity& identity) {
178 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
179 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800180 if (isAudioServerOrRootUid(uid)) return true;
181 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
182 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
183 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
184 return ok;
185}
186
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700187bool captureTunerAudioInputAllowed(const Identity& identity) {
188 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
189 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800190 if (isAudioServerOrRootUid(uid)) return true;
191 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
192 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
193 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
194 return ok;
195}
196
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700197bool captureVoiceCommunicationOutputAllowed(const Identity& identity) {
198 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
199 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200200 if (isAudioServerOrRootUid(uid)) return true;
201 static const String16 sCaptureVoiceCommOutput(
202 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
203 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
204 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
205 return ok;
206}
207
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700208bool captureHotwordAllowed(const Identity& identity) {
209 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
210 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent7504b9e2017-08-15 18:17:26 -0700211 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700212 bool ok = recordingAllowed(identity);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700213
214 if (ok) {
215 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent269acb42021-04-23 16:53:22 +0200216 ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700217 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700218 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700219 return ok;
220}
221
Glenn Kasten44deb052012-02-05 18:09:08 -0800222bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700223 // given this is a permission check, could this be isAudioServerOrRootUid()?
224 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800225 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700226 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
227 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800228 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
229 return ok;
230}
231
Eric Laurent5284ed52014-05-29 14:37:38 -0700232bool modifyAudioRoutingAllowed() {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700233 return modifyAudioRoutingAllowed(getCallingIdentity());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800234}
235
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700236bool modifyAudioRoutingAllowed(const Identity& identity) {
237 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
238 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800239 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700240 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800241 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
242 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
243 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700244 return ok;
245}
246
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700247bool modifyDefaultAudioEffectsAllowed() {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700248 return modifyDefaultAudioEffectsAllowed(getCallingIdentity());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800249}
250
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700251bool modifyDefaultAudioEffectsAllowed(const Identity& identity) {
252 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
253 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800254 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
255
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700256 static const String16 sModifyDefaultAudioEffectsAllowed(
257 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
258 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800259 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
260 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
261 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700262 return ok;
263}
264
Glenn Kasten44deb052012-02-05 18:09:08 -0800265bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800266 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700267 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800268 bool ok = PermissionCache::checkCallingPermission(sDump);
269 // convention is for caller to dump an error message to fd instead of logging here
270 //if (!ok) ALOGE("Request requires android.permission.DUMP");
271 return ok;
272}
273
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700274bool modifyPhoneStateAllowed(const Identity& identity) {
275 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
276 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800277 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700278 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
279 return ok;
280}
281
282// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700283bool bypassInterruptionPolicyAllowed(const Identity& identity) {
284 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
285 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700286 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
287 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
288 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
289 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
290 ALOGE_IF(!ok, "Request requires %s or %s",
291 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200292 return ok;
293}
294
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700295Identity getCallingIdentity() {
296 Identity identity = Identity();
297 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
298 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
299 return identity;
300}
301
Eric Laurent269acb42021-04-23 16:53:22 +0200302void purgePermissionCache() {
303 PermissionCache::purgeCache();
304}
305
Eric Laurent9b11c022018-06-06 19:19:22 -0700306status_t checkIMemory(const sp<IMemory>& iMemory)
307{
308 if (iMemory == 0) {
309 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
310 return BAD_VALUE;
311 }
312
313 sp<IMemoryHeap> heap = iMemory->getMemory();
314 if (heap == 0) {
315 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
316 return BAD_VALUE;
317 }
318
319 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
320 lseek(heap->getHeapID(), 0, SEEK_SET);
321
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700322 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700323 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700324 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700325 return BAD_VALUE;
326 }
327
328 return NO_ERROR;
329}
330
Oreste Salerno703ec262020-12-17 16:38:38 +0100331sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800332 const sp<IServiceManager> sm = defaultServiceManager();
333 if (sm == nullptr) {
334 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700335 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800336 }
337 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
338 if (packageManager == nullptr) {
339 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700340 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800341 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700342 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800343}
344
345std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
346 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700347 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100348 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700349 if (mPackageManager == nullptr) {
350 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
351 return std::nullopt;
352 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800353 }
354
Oreste Salerno703ec262020-12-17 16:38:38 +0100355 // Retrieve package names for the UID and transform to a std::vector<std::string>.
356 Vector<String16> str16PackageNames;
357 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800358 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100359 for (const auto& str16PackageName : str16PackageNames) {
360 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800361 }
362 if (packageNames.empty()) {
363 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100364 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800365 return std::nullopt;
366 }
367 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100368 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800369 if (!status.isOk()) {
370 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
371 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
372 return std::nullopt;
373 }
374 if (packageNames.size() != isAllowed.size()) {
375 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
376 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
377 return std::nullopt;
378 }
379
380 // Zip together packageNames and isAllowed for debug logs
381 Packages& packages = mDebugLog[uid];
382 packages.resize(packageNames.size()); // Reuse all objects
383 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
384 begin(packages), [] (auto& name, bool isAllowed) -> Package {
385 return {std::move(name), isAllowed};
386 });
387
388 // Only allow playback record if all packages in this UID allow it
389 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
390 [](bool b) { return b; });
391
392 return playbackCaptureAllowed;
393}
394
395void MediaPackageManager::dump(int fd, int spaces) const {
396 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
397 if (mPackageManager == nullptr) {
398 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
399 }
400 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
401
402 for (const auto& uidCache : mDebugLog) {
403 for (const auto& package : std::get<Packages>(uidCache)) {
404 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
405 std::get<const uid_t>(uidCache),
406 package.playbackCaptureAllowed ? "true " : "false",
407 package.name.c_str());
408 }
409 }
410}
411
Andy Hunga85efab2019-12-23 11:41:29 -0800412// How long we hold info before we re-fetch it (24 hours) if we found it previously.
413static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
414// Maximum info records we retain before clearing everything.
415static constexpr size_t INFO_CACHE_MAX = 1000;
416
417// The original code is from MediaMetricsService.cpp.
418mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
419{
420 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
421 struct mediautils::UidInfo::Info info;
422 {
423 std::lock_guard _l(mLock);
424 auto it = mInfoMap.find(uid);
425 if (it != mInfoMap.end()) {
426 info = it->second;
427 ALOGV("%s: uid %d expiration %lld now %lld",
428 __func__, uid, (long long)info.expirationNs, (long long)now);
429 if (info.expirationNs <= now) {
430 // purge the stale entry and fall into re-fetching
431 ALOGV("%s: entry for uid %d expired, now %lld",
432 __func__, uid, (long long)now);
433 mInfoMap.erase(it);
434 info.uid = (uid_t)-1; // this is always fully overwritten
435 }
436 }
437 }
438
439 // if we did not find it in our map, look it up
440 if (info.uid == (uid_t)(-1)) {
441 sp<IServiceManager> sm = defaultServiceManager();
442 sp<content::pm::IPackageManagerNative> package_mgr;
443 if (sm.get() == nullptr) {
444 ALOGE("%s: Cannot find service manager", __func__);
445 } else {
446 sp<IBinder> binder = sm->getService(String16("package_native"));
447 if (binder.get() == nullptr) {
448 ALOGE("%s: Cannot find package_native", __func__);
449 } else {
450 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
451 }
452 }
453
454 // find package name
455 std::string pkg;
456 if (package_mgr != nullptr) {
457 std::vector<std::string> names;
458 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
459 if (!status.isOk()) {
460 ALOGE("%s: getNamesForUids failed: %s",
461 __func__, status.exceptionMessage().c_str());
462 } else {
463 if (!names[0].empty()) {
464 pkg = names[0].c_str();
465 }
466 }
467 }
468
469 if (pkg.empty()) {
470 struct passwd pw{}, *result;
471 char buf[8192]; // extra buffer space - should exceed what is
472 // required in struct passwd_pw (tested),
473 // and even then this is only used in backup
474 // when the package manager is unavailable.
475 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
476 && result != nullptr
477 && result->pw_name != nullptr) {
478 pkg = result->pw_name;
479 }
480 }
481
482 // strip any leading "shared:" strings that came back
483 if (pkg.compare(0, 7, "shared:") == 0) {
484 pkg.erase(0, 7);
485 }
486
487 // determine how pkg was installed and the versionCode
488 std::string installer;
489 int64_t versionCode = 0;
490 bool notFound = false;
491 if (pkg.empty()) {
492 pkg = std::to_string(uid); // not found
493 notFound = true;
494 } else if (strchr(pkg.c_str(), '.') == nullptr) {
495 // not of form 'com.whatever...'; assume internal
496 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800497 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
498 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800499 } else if (package_mgr.get() != nullptr) {
500 String16 pkgName16(pkg.c_str());
501 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
502 if (!status.isOk()) {
503 ALOGE("%s: getInstallerForPackage failed: %s",
504 __func__, status.exceptionMessage().c_str());
505 }
506
507 // skip if we didn't get an installer
508 if (status.isOk()) {
509 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
510 if (!status.isOk()) {
511 ALOGE("%s: getVersionCodeForPackage failed: %s",
512 __func__, status.exceptionMessage().c_str());
513 }
514 }
515
516 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
517 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
518 }
519
520 // add it to the map, to save a subsequent lookup
521 std::lock_guard _l(mLock);
522 // first clear if we have too many cached elements. This would be rare.
523 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
524
525 // always overwrite
526 info.uid = uid;
527 info.package = std::move(pkg);
528 info.installer = std::move(installer);
529 info.versionCode = versionCode;
530 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
531 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
532 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
533 mInfoMap[uid] = info;
534 }
535 return info;
536}
537
Glenn Kasten44deb052012-02-05 18:09:08 -0800538} // namespace android