blob: 17ed49aea463f9f100396f297e6ab3404d13a80e [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
Nate Myrene69cada2020-12-10 10:00:36 -080070static int32_t getOpForSource(audio_source_t source) {
71 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(
119 identity.attributionTag)), msg) != AppOpsManager::MODE_ALLOWED) {
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 {
Narayan Kamathbf85d8b2020-08-20 17:19:57 +0100125 // Always use OP_RECORD_AUDIO for checks at creation time.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700126 if (int32_t mode = appOps.checkOp(op, uid,
127 resolvedOpPackageName) != AppOpsManager::MODE_ALLOWED) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000128 ALOGE("Request check for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700129 String8(resolvedOpPackageName).c_str(), identity.uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800130 return false;
131 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000132 }
133
134 return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800135}
136
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700137bool recordingAllowed(const Identity& identity) {
138 return checkRecordingInternal(identity, String16(), /*start*/ false, AUDIO_SOURCE_DEFAULT);
Svet Ganov5b81f552018-03-02 09:21:30 -0800139}
140
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700141bool startRecording(const Identity& identity, const String16& msg, audio_source_t source) {
142 return checkRecordingInternal(identity, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800143}
144
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700145void finishRecording(const Identity& identity, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800146 // Okay to not track in app ops as audio server is us and if
147 // device is rooted security model is considered compromised.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700148 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700149 if (isAudioServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800150
151 PermissionController permissionController;
152 String16 resolvedOpPackageName = resolveCallingPackage(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700153 permissionController,
154 VALUE_OR_FATAL(aidl2legacy_string_view_String16(identity.packageName.value_or(""))),
155 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800156 if (resolvedOpPackageName.size() == 0) {
157 return;
158 }
159
160 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800161
162 const int32_t op = getOpForSource(source);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700163 appOps.finishOp(op, identity.uid, resolvedOpPackageName,
164 VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16(
165 identity.attributionTag)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800166}
167
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700168bool captureAudioOutputAllowed(const Identity& identity) {
169 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
170 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700171 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700172 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800173 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700174 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700175 return ok;
176}
177
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700178bool captureMediaOutputAllowed(const Identity& identity) {
179 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
180 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800181 if (isAudioServerOrRootUid(uid)) return true;
182 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
183 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
184 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
185 return ok;
186}
187
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700188bool captureTunerAudioInputAllowed(const Identity& identity) {
189 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
190 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800191 if (isAudioServerOrRootUid(uid)) return true;
192 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
193 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
194 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
195 return ok;
196}
197
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700198bool captureVoiceCommunicationOutputAllowed(const Identity& identity) {
199 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
200 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200201 if (isAudioServerOrRootUid(uid)) return true;
202 static const String16 sCaptureVoiceCommOutput(
203 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
204 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
205 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
206 return ok;
207}
208
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700209bool captureHotwordAllowed(const Identity& identity) {
210 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
211 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent7504b9e2017-08-15 18:17:26 -0700212 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700213 bool ok = recordingAllowed(identity);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700214
215 if (ok) {
216 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
217 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
jiabin68e0df72019-03-18 17:55:35 -0700218 ok = PermissionCache::checkPermission(sCaptureHotwordAllowed, pid, uid);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700219 }
Eric Laurent6ede98f2019-06-11 14:50:30 -0700220 if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
Eric Laurent9a54bc22013-09-09 09:08:44 -0700221 return ok;
222}
223
Glenn Kasten44deb052012-02-05 18:09:08 -0800224bool settingsAllowed() {
Andy Hung4ef19fa2018-05-15 19:35:29 -0700225 // given this is a permission check, could this be isAudioServerOrRootUid()?
226 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800227 static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700228 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
229 bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
Glenn Kasten44deb052012-02-05 18:09:08 -0800230 if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
231 return ok;
232}
233
Eric Laurent5284ed52014-05-29 14:37:38 -0700234bool modifyAudioRoutingAllowed() {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700235 return modifyAudioRoutingAllowed(getCallingIdentity());
Eric Laurent8a1095a2019-11-08 14:44:16 -0800236}
237
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700238bool modifyAudioRoutingAllowed(const Identity& identity) {
239 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
240 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent8a1095a2019-11-08 14:44:16 -0800241 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700242 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent8a1095a2019-11-08 14:44:16 -0800243 bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
244 if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
245 __func__, uid);
Eric Laurent5284ed52014-05-29 14:37:38 -0700246 return ok;
247}
248
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700249bool modifyDefaultAudioEffectsAllowed() {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700250 return modifyDefaultAudioEffectsAllowed(getCallingIdentity());
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800251}
252
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700253bool modifyDefaultAudioEffectsAllowed(const Identity& identity) {
254 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
255 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800256 if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
257
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700258 static const String16 sModifyDefaultAudioEffectsAllowed(
259 "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
260 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Eric Laurent3f75a5b2019-11-12 15:55:51 -0800261 bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
262 ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
263 __func__, uid);
Ari Hausman-Cohen433722e2018-04-24 14:25:22 -0700264 return ok;
265}
266
Glenn Kasten44deb052012-02-05 18:09:08 -0800267bool dumpAllowed() {
Glenn Kasten44deb052012-02-05 18:09:08 -0800268 static const String16 sDump("android.permission.DUMP");
Svet Ganovbe71aa22015-04-28 12:06:02 -0700269 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
Glenn Kasten44deb052012-02-05 18:09:08 -0800270 bool ok = PermissionCache::checkCallingPermission(sDump);
271 // convention is for caller to dump an error message to fd instead of logging here
272 //if (!ok) ALOGE("Request requires android.permission.DUMP");
273 return ok;
274}
275
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700276bool modifyPhoneStateAllowed(const Identity& identity) {
277 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
278 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Svet Ganov5b81f552018-03-02 09:21:30 -0800279 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
Eric Laurent42984412019-05-09 17:57:03 -0700280 ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
281 return ok;
282}
283
284// privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700285bool bypassInterruptionPolicyAllowed(const Identity& identity) {
286 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
287 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent42984412019-05-09 17:57:03 -0700288 static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
289 bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
290 || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
291 || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
292 ALOGE_IF(!ok, "Request requires %s or %s",
293 String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
Nadav Bar766fb022018-01-07 12:18:03 +0200294 return ok;
295}
296
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700297Identity getCallingIdentity() {
298 Identity identity = Identity();
299 identity.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(IPCThreadState::self()->getCallingPid()));
300 identity.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(IPCThreadState::self()->getCallingUid()));
301 return identity;
302}
303
Eric Laurent9b11c022018-06-06 19:19:22 -0700304status_t checkIMemory(const sp<IMemory>& iMemory)
305{
306 if (iMemory == 0) {
307 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
308 return BAD_VALUE;
309 }
310
311 sp<IMemoryHeap> heap = iMemory->getMemory();
312 if (heap == 0) {
313 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
314 return BAD_VALUE;
315 }
316
317 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
318 lseek(heap->getHeapID(), 0, SEEK_SET);
319
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700320 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700321 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700322 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700323 return BAD_VALUE;
324 }
325
326 return NO_ERROR;
327}
328
Oreste Salerno703ec262020-12-17 16:38:38 +0100329sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800330 const sp<IServiceManager> sm = defaultServiceManager();
331 if (sm == nullptr) {
332 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700333 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800334 }
335 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
336 if (packageManager == nullptr) {
337 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700338 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800339 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700340 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800341}
342
343std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
344 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700345 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100346 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700347 if (mPackageManager == nullptr) {
348 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
349 return std::nullopt;
350 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800351 }
352
Oreste Salerno703ec262020-12-17 16:38:38 +0100353 // Retrieve package names for the UID and transform to a std::vector<std::string>.
354 Vector<String16> str16PackageNames;
355 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800356 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100357 for (const auto& str16PackageName : str16PackageNames) {
358 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800359 }
360 if (packageNames.empty()) {
361 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100362 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800363 return std::nullopt;
364 }
365 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100366 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800367 if (!status.isOk()) {
368 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
369 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
370 return std::nullopt;
371 }
372 if (packageNames.size() != isAllowed.size()) {
373 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
374 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
375 return std::nullopt;
376 }
377
378 // Zip together packageNames and isAllowed for debug logs
379 Packages& packages = mDebugLog[uid];
380 packages.resize(packageNames.size()); // Reuse all objects
381 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
382 begin(packages), [] (auto& name, bool isAllowed) -> Package {
383 return {std::move(name), isAllowed};
384 });
385
386 // Only allow playback record if all packages in this UID allow it
387 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
388 [](bool b) { return b; });
389
390 return playbackCaptureAllowed;
391}
392
393void MediaPackageManager::dump(int fd, int spaces) const {
394 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
395 if (mPackageManager == nullptr) {
396 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
397 }
398 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
399
400 for (const auto& uidCache : mDebugLog) {
401 for (const auto& package : std::get<Packages>(uidCache)) {
402 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
403 std::get<const uid_t>(uidCache),
404 package.playbackCaptureAllowed ? "true " : "false",
405 package.name.c_str());
406 }
407 }
408}
409
Andy Hunga85efab2019-12-23 11:41:29 -0800410// How long we hold info before we re-fetch it (24 hours) if we found it previously.
411static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
412// Maximum info records we retain before clearing everything.
413static constexpr size_t INFO_CACHE_MAX = 1000;
414
415// The original code is from MediaMetricsService.cpp.
416mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
417{
418 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
419 struct mediautils::UidInfo::Info info;
420 {
421 std::lock_guard _l(mLock);
422 auto it = mInfoMap.find(uid);
423 if (it != mInfoMap.end()) {
424 info = it->second;
425 ALOGV("%s: uid %d expiration %lld now %lld",
426 __func__, uid, (long long)info.expirationNs, (long long)now);
427 if (info.expirationNs <= now) {
428 // purge the stale entry and fall into re-fetching
429 ALOGV("%s: entry for uid %d expired, now %lld",
430 __func__, uid, (long long)now);
431 mInfoMap.erase(it);
432 info.uid = (uid_t)-1; // this is always fully overwritten
433 }
434 }
435 }
436
437 // if we did not find it in our map, look it up
438 if (info.uid == (uid_t)(-1)) {
439 sp<IServiceManager> sm = defaultServiceManager();
440 sp<content::pm::IPackageManagerNative> package_mgr;
441 if (sm.get() == nullptr) {
442 ALOGE("%s: Cannot find service manager", __func__);
443 } else {
444 sp<IBinder> binder = sm->getService(String16("package_native"));
445 if (binder.get() == nullptr) {
446 ALOGE("%s: Cannot find package_native", __func__);
447 } else {
448 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
449 }
450 }
451
452 // find package name
453 std::string pkg;
454 if (package_mgr != nullptr) {
455 std::vector<std::string> names;
456 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
457 if (!status.isOk()) {
458 ALOGE("%s: getNamesForUids failed: %s",
459 __func__, status.exceptionMessage().c_str());
460 } else {
461 if (!names[0].empty()) {
462 pkg = names[0].c_str();
463 }
464 }
465 }
466
467 if (pkg.empty()) {
468 struct passwd pw{}, *result;
469 char buf[8192]; // extra buffer space - should exceed what is
470 // required in struct passwd_pw (tested),
471 // and even then this is only used in backup
472 // when the package manager is unavailable.
473 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
474 && result != nullptr
475 && result->pw_name != nullptr) {
476 pkg = result->pw_name;
477 }
478 }
479
480 // strip any leading "shared:" strings that came back
481 if (pkg.compare(0, 7, "shared:") == 0) {
482 pkg.erase(0, 7);
483 }
484
485 // determine how pkg was installed and the versionCode
486 std::string installer;
487 int64_t versionCode = 0;
488 bool notFound = false;
489 if (pkg.empty()) {
490 pkg = std::to_string(uid); // not found
491 notFound = true;
492 } else if (strchr(pkg.c_str(), '.') == nullptr) {
493 // not of form 'com.whatever...'; assume internal
494 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800495 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
496 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800497 } else if (package_mgr.get() != nullptr) {
498 String16 pkgName16(pkg.c_str());
499 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
500 if (!status.isOk()) {
501 ALOGE("%s: getInstallerForPackage failed: %s",
502 __func__, status.exceptionMessage().c_str());
503 }
504
505 // skip if we didn't get an installer
506 if (status.isOk()) {
507 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
508 if (!status.isOk()) {
509 ALOGE("%s: getVersionCodeForPackage failed: %s",
510 __func__, status.exceptionMessage().c_str());
511 }
512 }
513
514 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
515 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
516 }
517
518 // add it to the map, to save a subsequent lookup
519 std::lock_guard _l(mLock);
520 // first clear if we have too many cached elements. This would be rare.
521 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
522
523 // always overwrite
524 info.uid = uid;
525 info.package = std::move(pkg);
526 info.installer = std::move(installer);
527 info.versionCode = versionCode;
528 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
529 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
530 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
531 mInfoMap[uid] = info;
532 }
533 return info;
534}
535
Glenn Kasten44deb052012-02-05 18:09:08 -0800536} // namespace android