blob: e2e1043f29800a3a3e6681a2f2ccda144f48951a [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;
76 case AUDIO_SOURCE_DEFAULT:
77 default:
78 return AppOpsManager::OP_RECORD_AUDIO;
79 }
80}
81
Philip P. Moltmannbda45752020-07-17 16:41:18 -070082static bool checkRecordingInternal(const Identity& identity, const String16& msg,
83 bool start, audio_source_t source) {
Eric Laurent58a0dd82019-10-24 12:42:17 -070084 // Okay to not track in app ops as audio server or media server is us and if
Svet Ganov5b81f552018-03-02 09:21:30 -080085 // device is rooted security model is considered compromised.
Jeffrey Carlyle62cc92b2019-09-17 11:15:15 -070086 // system_server loses its RECORD_AUDIO permission when a secondary
87 // user is active, but it is a core system service so let it through.
88 // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
Philip P. Moltmannbda45752020-07-17 16:41:18 -070089 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
Eric Laurent58a0dd82019-10-24 12:42:17 -070090 if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return true;
Svetoslav Ganov599ec462018-03-01 22:19:55 +000091
Svet Ganov5b81f552018-03-02 09:21:30 -080092 // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
93 // may open a record track on behalf of a client. Note that pid may be a tid.
94 // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
95 PermissionController permissionController;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070096 const bool ok = permissionController.checkPermission(sAndroidPermissionRecordAudio,
97 identity.pid, identity.uid);
Svet Ganov5b81f552018-03-02 09:21:30 -080098 if (!ok) {
99 ALOGE("Request requires %s", String8(sAndroidPermissionRecordAudio).c_str());
100 return false;
101 }
102
103 String16 resolvedOpPackageName = resolveCallingPackage(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700104 permissionController, VALUE_OR_FATAL(aidl2legacy_string_view_String16(
105 identity.packageName.value_or(""))), uid);
Svet Ganov5b81f552018-03-02 09:21:30 -0800106 if (resolvedOpPackageName.size() == 0) {
107 return false;
Svet Ganovbe71aa22015-04-28 12:06:02 -0700108 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000109
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700110
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000111 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800112 const int32_t op = getOpForSource(source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800113 if (start) {
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114 if (int32_t mode = appOps.startOpNoThrow(op, identity.uid,
115 resolvedOpPackageName, /*startIfModeDefault*/ false,
116 VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16(
117 identity.attributionTag)), msg) != AppOpsManager::MODE_ALLOWED) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000118 ALOGE("Request start for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119 String8(resolvedOpPackageName).c_str(), identity.uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800120 return false;
121 }
122 } else {
Narayan Kamathbf85d8b2020-08-20 17:19:57 +0100123 // Always use OP_RECORD_AUDIO for checks at creation time.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700124 if (int32_t mode = appOps.checkOp(op, uid,
125 resolvedOpPackageName) != AppOpsManager::MODE_ALLOWED) {
Mikhail Naganov70ff2372020-12-07 22:18:49 +0000126 ALOGE("Request check for \"%s\" (uid %d) denied by app op: %d, mode: %d",
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700127 String8(resolvedOpPackageName).c_str(), identity.uid, op, mode);
Svet Ganov5b81f552018-03-02 09:21:30 -0800128 return false;
129 }
Svetoslav Ganov599ec462018-03-01 22:19:55 +0000130 }
131
132 return true;
Glenn Kasten44deb052012-02-05 18:09:08 -0800133}
134
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700135bool recordingAllowed(const Identity& identity) {
136 return checkRecordingInternal(identity, String16(), /*start*/ false, AUDIO_SOURCE_DEFAULT);
Svet Ganov5b81f552018-03-02 09:21:30 -0800137}
138
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700139bool startRecording(const Identity& identity, const String16& msg, audio_source_t source) {
140 return checkRecordingInternal(identity, msg, /*start*/ true, source);
Svet Ganov5b81f552018-03-02 09:21:30 -0800141}
142
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700143void finishRecording(const Identity& identity, audio_source_t source) {
Svet Ganov5b81f552018-03-02 09:21:30 -0800144 // Okay to not track in app ops as audio server is us and if
145 // device is rooted security model is considered compromised.
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700146 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700147 if (isAudioServerOrRootUid(uid)) return;
Svet Ganov5b81f552018-03-02 09:21:30 -0800148
149 PermissionController permissionController;
150 String16 resolvedOpPackageName = resolveCallingPackage(
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700151 permissionController,
152 VALUE_OR_FATAL(aidl2legacy_string_view_String16(identity.packageName.value_or(""))),
153 VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800154 if (resolvedOpPackageName.size() == 0) {
155 return;
156 }
157
158 AppOpsManager appOps;
Nate Myrene69cada2020-12-10 10:00:36 -0800159
160 const int32_t op = getOpForSource(source);
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700161 appOps.finishOp(op, identity.uid, resolvedOpPackageName,
162 VALUE_OR_FATAL(aidl2legacy_optional_string_view_optional_String16(
163 identity.attributionTag)));
Svet Ganov5b81f552018-03-02 09:21:30 -0800164}
165
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700166bool captureAudioOutputAllowed(const Identity& identity) {
167 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
168 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Andy Hung4ef19fa2018-05-15 19:35:29 -0700169 if (isAudioServerOrRootUid(uid)) return true;
Jeff Brown893a5642013-08-16 20:19:26 -0700170 static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
Svet Ganov5b81f552018-03-02 09:21:30 -0800171 bool ok = PermissionCache::checkPermission(sCaptureAudioOutput, pid, uid);
Eric Laurent6ede98f2019-06-11 14:50:30 -0700172 if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
Jeff Brown893a5642013-08-16 20:19:26 -0700173 return ok;
174}
175
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700176bool captureMediaOutputAllowed(const Identity& identity) {
177 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
178 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Kevin Rocard36b17552019-03-07 18:48:07 -0800179 if (isAudioServerOrRootUid(uid)) return true;
180 static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
181 bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
182 if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
183 return ok;
184}
185
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700186bool captureTunerAudioInputAllowed(const Identity& identity) {
187 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
188 pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Hayden Gomesb7429922020-12-11 13:59:18 -0800189 if (isAudioServerOrRootUid(uid)) return true;
190 static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
191 bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
192 if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
193 return ok;
194}
195
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700196bool captureVoiceCommunicationOutputAllowed(const Identity& identity) {
197 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
198 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Nadav Bardbf0a2e2020-01-16 23:09:25 +0200199 if (isAudioServerOrRootUid(uid)) return true;
200 static const String16 sCaptureVoiceCommOutput(
201 "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
202 bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
203 if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
204 return ok;
205}
206
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700207bool captureHotwordAllowed(const Identity& identity) {
208 uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(identity.uid));
209 uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(identity.pid));
Eric Laurent7504b9e2017-08-15 18:17:26 -0700210 // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700211 bool ok = recordingAllowed(identity);
Eric Laurent7504b9e2017-08-15 18:17:26 -0700212
213 if (ok) {
214 static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
215 // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
jiabin68e0df72019-03-18 17:55:35 -0700216 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 Laurent9b11c022018-06-06 19:19:22 -0700302status_t checkIMemory(const sp<IMemory>& iMemory)
303{
304 if (iMemory == 0) {
305 ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
306 return BAD_VALUE;
307 }
308
309 sp<IMemoryHeap> heap = iMemory->getMemory();
310 if (heap == 0) {
311 ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
312 return BAD_VALUE;
313 }
314
315 off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
316 lseek(heap->getHeapID(), 0, SEEK_SET);
317
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700318 if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
Eric Laurent9b11c022018-06-06 19:19:22 -0700319 ALOGE("%s check failed: pointer %p size %zu fd size %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -0700320 __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
Eric Laurent9b11c022018-06-06 19:19:22 -0700321 return BAD_VALUE;
322 }
323
324 return NO_ERROR;
325}
326
Oreste Salerno703ec262020-12-17 16:38:38 +0100327sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
Kevin Rocard8be94972019-02-22 13:26:25 -0800328 const sp<IServiceManager> sm = defaultServiceManager();
329 if (sm == nullptr) {
330 ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700331 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800332 }
333 sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
334 if (packageManager == nullptr) {
335 ALOGW("%s: failed to retrieve native package manager", __func__);
Ricardo Correa57a37692020-03-23 17:27:25 -0700336 return nullptr;
Kevin Rocard8be94972019-02-22 13:26:25 -0800337 }
Ricardo Correa57a37692020-03-23 17:27:25 -0700338 return interface_cast<content::pm::IPackageManagerNative>(packageManager);
Kevin Rocard8be94972019-02-22 13:26:25 -0800339}
340
341std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
342 if (mPackageManager == nullptr) {
Ricardo Correa57a37692020-03-23 17:27:25 -0700343 /** Can not fetch package manager at construction it may not yet be registered. */
Oreste Salerno703ec262020-12-17 16:38:38 +0100344 mPackageManager = retrievePackageManager();
Ricardo Correa57a37692020-03-23 17:27:25 -0700345 if (mPackageManager == nullptr) {
346 ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
347 return std::nullopt;
348 }
Kevin Rocard8be94972019-02-22 13:26:25 -0800349 }
350
Oreste Salerno703ec262020-12-17 16:38:38 +0100351 // Retrieve package names for the UID and transform to a std::vector<std::string>.
352 Vector<String16> str16PackageNames;
353 PermissionController{}.getPackagesForUid(uid, str16PackageNames);
Kevin Rocard8be94972019-02-22 13:26:25 -0800354 std::vector<std::string> packageNames;
Oreste Salerno703ec262020-12-17 16:38:38 +0100355 for (const auto& str16PackageName : str16PackageNames) {
356 packageNames.emplace_back(String8(str16PackageName).string());
Kevin Rocard8be94972019-02-22 13:26:25 -0800357 }
358 if (packageNames.empty()) {
359 ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
Oreste Salerno703ec262020-12-17 16:38:38 +0100360 "from the package manager.", __func__, uid);
Kevin Rocard8be94972019-02-22 13:26:25 -0800361 return std::nullopt;
362 }
363 std::vector<bool> isAllowed;
Oreste Salerno703ec262020-12-17 16:38:38 +0100364 auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
Kevin Rocard8be94972019-02-22 13:26:25 -0800365 if (!status.isOk()) {
366 ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
367 "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
368 return std::nullopt;
369 }
370 if (packageNames.size() != isAllowed.size()) {
371 ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
372 " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
373 return std::nullopt;
374 }
375
376 // Zip together packageNames and isAllowed for debug logs
377 Packages& packages = mDebugLog[uid];
378 packages.resize(packageNames.size()); // Reuse all objects
379 std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
380 begin(packages), [] (auto& name, bool isAllowed) -> Package {
381 return {std::move(name), isAllowed};
382 });
383
384 // Only allow playback record if all packages in this UID allow it
385 bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
386 [](bool b) { return b; });
387
388 return playbackCaptureAllowed;
389}
390
391void MediaPackageManager::dump(int fd, int spaces) const {
392 dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
393 if (mPackageManager == nullptr) {
394 dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
395 }
396 dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
397
398 for (const auto& uidCache : mDebugLog) {
399 for (const auto& package : std::get<Packages>(uidCache)) {
400 dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
401 std::get<const uid_t>(uidCache),
402 package.playbackCaptureAllowed ? "true " : "false",
403 package.name.c_str());
404 }
405 }
406}
407
Andy Hunga85efab2019-12-23 11:41:29 -0800408// How long we hold info before we re-fetch it (24 hours) if we found it previously.
409static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
410// Maximum info records we retain before clearing everything.
411static constexpr size_t INFO_CACHE_MAX = 1000;
412
413// The original code is from MediaMetricsService.cpp.
414mediautils::UidInfo::Info mediautils::UidInfo::getInfo(uid_t uid)
415{
416 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
417 struct mediautils::UidInfo::Info info;
418 {
419 std::lock_guard _l(mLock);
420 auto it = mInfoMap.find(uid);
421 if (it != mInfoMap.end()) {
422 info = it->second;
423 ALOGV("%s: uid %d expiration %lld now %lld",
424 __func__, uid, (long long)info.expirationNs, (long long)now);
425 if (info.expirationNs <= now) {
426 // purge the stale entry and fall into re-fetching
427 ALOGV("%s: entry for uid %d expired, now %lld",
428 __func__, uid, (long long)now);
429 mInfoMap.erase(it);
430 info.uid = (uid_t)-1; // this is always fully overwritten
431 }
432 }
433 }
434
435 // if we did not find it in our map, look it up
436 if (info.uid == (uid_t)(-1)) {
437 sp<IServiceManager> sm = defaultServiceManager();
438 sp<content::pm::IPackageManagerNative> package_mgr;
439 if (sm.get() == nullptr) {
440 ALOGE("%s: Cannot find service manager", __func__);
441 } else {
442 sp<IBinder> binder = sm->getService(String16("package_native"));
443 if (binder.get() == nullptr) {
444 ALOGE("%s: Cannot find package_native", __func__);
445 } else {
446 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
447 }
448 }
449
450 // find package name
451 std::string pkg;
452 if (package_mgr != nullptr) {
453 std::vector<std::string> names;
454 binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
455 if (!status.isOk()) {
456 ALOGE("%s: getNamesForUids failed: %s",
457 __func__, status.exceptionMessage().c_str());
458 } else {
459 if (!names[0].empty()) {
460 pkg = names[0].c_str();
461 }
462 }
463 }
464
465 if (pkg.empty()) {
466 struct passwd pw{}, *result;
467 char buf[8192]; // extra buffer space - should exceed what is
468 // required in struct passwd_pw (tested),
469 // and even then this is only used in backup
470 // when the package manager is unavailable.
471 if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
472 && result != nullptr
473 && result->pw_name != nullptr) {
474 pkg = result->pw_name;
475 }
476 }
477
478 // strip any leading "shared:" strings that came back
479 if (pkg.compare(0, 7, "shared:") == 0) {
480 pkg.erase(0, 7);
481 }
482
483 // determine how pkg was installed and the versionCode
484 std::string installer;
485 int64_t versionCode = 0;
486 bool notFound = false;
487 if (pkg.empty()) {
488 pkg = std::to_string(uid); // not found
489 notFound = true;
490 } else if (strchr(pkg.c_str(), '.') == nullptr) {
491 // not of form 'com.whatever...'; assume internal
492 // so we don't need to look it up in package manager.
Andy Hunge6a65ac2020-01-08 16:56:17 -0800493 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
494 // android.* packages are assumed fine
Andy Hunga85efab2019-12-23 11:41:29 -0800495 } else if (package_mgr.get() != nullptr) {
496 String16 pkgName16(pkg.c_str());
497 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
498 if (!status.isOk()) {
499 ALOGE("%s: getInstallerForPackage failed: %s",
500 __func__, status.exceptionMessage().c_str());
501 }
502
503 // skip if we didn't get an installer
504 if (status.isOk()) {
505 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
506 if (!status.isOk()) {
507 ALOGE("%s: getVersionCodeForPackage failed: %s",
508 __func__, status.exceptionMessage().c_str());
509 }
510 }
511
512 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
513 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
514 }
515
516 // add it to the map, to save a subsequent lookup
517 std::lock_guard _l(mLock);
518 // first clear if we have too many cached elements. This would be rare.
519 if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
520
521 // always overwrite
522 info.uid = uid;
523 info.package = std::move(pkg);
524 info.installer = std::move(installer);
525 info.versionCode = versionCode;
526 info.expirationNs = now + (notFound ? 0 : INFO_EXPIRATION_NS);
527 ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
528 __func__, uid, info.package.c_str(), (long long)info.expirationNs);
529 mInfoMap[uid] = info;
530 }
531 return info;
532}
533
Glenn Kasten44deb052012-02-05 18:09:08 -0800534} // namespace android