• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "ServiceUtilities"
19 
20 #include <audio_utils/clock.h>
21 #include <android-base/properties.h>
22 #include <binder/AppOpsManager.h>
23 #include <binder/IPCThreadState.h>
24 #include <binder/IServiceManager.h>
25 #include <binder/PermissionCache.h>
26 #include "mediautils/ServiceUtilities.h"
27 #include <system/audio-hal-enums.h>
28 #include <media/AidlConversion.h>
29 #include <media/AidlConversionUtil.h>
30 #include <android/content/AttributionSourceState.h>
31 
32 #include <algorithm>
33 #include <iterator>
34 #include <mutex>
35 #include <pwd.h>
36 #include <thread>
37 
38 /* When performing permission checks we do not use permission cache for
39  * runtime permissions (protection level dangerous) as they may change at
40  * runtime. All other permissions (protection level normal and dangerous)
41  * can be cached as they never change. Of course all permission checked
42  * here are platform defined.
43  */
44 
45 namespace android {
46 
47 namespace {
48 constexpr auto PERMISSION_GRANTED = permission::PermissionChecker::PERMISSION_GRANTED;
49 constexpr auto PERMISSION_HARD_DENIED = permission::PermissionChecker::PERMISSION_HARD_DENIED;
50 }
51 
52 using content::AttributionSourceState;
53 
54 static const String16 sAndroidPermissionRecordAudio("android.permission.RECORD_AUDIO");
55 static const String16 sModifyPhoneState("android.permission.MODIFY_PHONE_STATE");
56 static const String16 sModifyAudioRouting("android.permission.MODIFY_AUDIO_ROUTING");
57 static const String16 sCallAudioInterception("android.permission.CALL_AUDIO_INTERCEPTION");
58 static const String16 sModifyAudioSettingsPrivileged(
59         "android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED");
60 
resolveCallingPackage(PermissionController & permissionController,const std::optional<String16> opPackageName,uid_t uid)61 static String16 resolveCallingPackage(PermissionController& permissionController,
62         const std::optional<String16> opPackageName, uid_t uid) {
63     if (opPackageName.has_value() && opPackageName.value().size() > 0) {
64         return opPackageName.value();
65     }
66     // In some cases the calling code has no access to the package it runs under.
67     // For example, code using the wilhelm framework's OpenSL-ES APIs. In this
68     // case we will get the packages for the calling UID and pick the first one
69     // for attributing the app op. This will work correctly for runtime permissions
70     // as for legacy apps we will toggle the app op for all packages in the UID.
71     // The caveat is that the operation may be attributed to the wrong package and
72     // stats based on app ops may be slightly off.
73     Vector<String16> packages;
74     permissionController.getPackagesForUid(uid, packages);
75     if (packages.isEmpty()) {
76         ALOGE("No packages for uid %d", uid);
77         return String16();
78     }
79     return packages[0];
80 }
81 
82 // NOTE/TODO(b/379754682):
83 // AUDIO_SOURCE_VOICE_CALL is handled specially:
84 // CALL includes both uplink and downlink, but we attribute RECORD_OP (only), since
85 // there is not support for noting multiple ops.
getOpForSource(audio_source_t source)86 int32_t getOpForSource(audio_source_t source) {
87   switch (source) {
88     // BEGIN output sources
89     case AUDIO_SOURCE_FM_TUNER:
90         return AppOpsManager::OP_NONE;
91     case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
92     case AUDIO_SOURCE_REMOTE_SUBMIX:
93         // TODO -- valid in all cases?
94       return AppOpsManager::OP_RECORD_AUDIO_OUTPUT;
95     case AUDIO_SOURCE_VOICE_DOWNLINK:
96       return AppOpsManager::OP_RECORD_INCOMING_PHONE_AUDIO;
97     // END output sources
98     case AUDIO_SOURCE_HOTWORD:
99       return AppOpsManager::OP_RECORD_AUDIO_HOTWORD;
100     case AUDIO_SOURCE_DEFAULT:
101     default:
102       return AppOpsManager::OP_RECORD_AUDIO;
103   }
104 }
105 
isRecordOpRequired(audio_source_t source)106 bool isRecordOpRequired(audio_source_t source) {
107   switch (source) {
108     case AUDIO_SOURCE_FM_TUNER:
109     case AUDIO_SOURCE_ECHO_REFERENCE: // fallthrough
110     case AUDIO_SOURCE_REMOTE_SUBMIX:
111     case AUDIO_SOURCE_VOICE_DOWNLINK:
112         return false;
113     default:
114       return true;
115   }
116 }
117 
resolveAttributionSource(const AttributionSourceState & callerAttributionSource,const uint32_t virtualDeviceId)118 std::optional<AttributionSourceState> resolveAttributionSource(
119         const AttributionSourceState& callerAttributionSource, const uint32_t virtualDeviceId) {
120     AttributionSourceState nextAttributionSource = callerAttributionSource;
121 
122     if (!nextAttributionSource.packageName.has_value()) {
123         nextAttributionSource = AttributionSourceState(nextAttributionSource);
124         PermissionController permissionController;
125         const uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(nextAttributionSource.uid));
126         nextAttributionSource.packageName = VALUE_OR_FATAL(legacy2aidl_String16_string(
127                 resolveCallingPackage(permissionController, VALUE_OR_FATAL(
128                 aidl2legacy_string_view_String16(nextAttributionSource.packageName.value_or(""))),
129                 uid)));
130         if (!nextAttributionSource.packageName.has_value()) {
131             return std::nullopt;
132         }
133     }
134     nextAttributionSource.deviceId = virtualDeviceId;
135 
136     AttributionSourceState myAttributionSource;
137     myAttributionSource.uid = VALUE_OR_FATAL(android::legacy2aidl_uid_t_int32_t(getuid()));
138     myAttributionSource.pid = VALUE_OR_FATAL(android::legacy2aidl_pid_t_int32_t(getpid()));
139     // Create a static token for audioserver requests, which identifies the
140     // audioserver to the app ops system
141     static sp<BBinder> appOpsToken = sp<BBinder>::make();
142     myAttributionSource.token = appOpsToken;
143     myAttributionSource.deviceId = virtualDeviceId;
144     myAttributionSource.next.push_back(nextAttributionSource);
145 
146     return std::optional<AttributionSourceState>{myAttributionSource};
147 }
148 
149 
checkRecordingInternal(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,const String16 & msg,bool start,audio_source_t source)150 static int checkRecordingInternal(const AttributionSourceState &attributionSource,
151                                        const uint32_t virtualDeviceId,
152                                        const String16 &msg, bool start, audio_source_t source) {
153     // Okay to not track in app ops as audio server or media server is us and if
154     // device is rooted security model is considered compromised.
155     // system_server loses its RECORD_AUDIO permission when a secondary
156     // user is active, but it is a core system service so let it through.
157     // TODO(b/141210120): UserManager.DISALLOW_RECORD_AUDIO should not affect system user 0
158     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
159     if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return PERMISSION_GRANTED;
160 
161     const int32_t attributedOpCode = getOpForSource(source);
162     if (isRecordOpRequired(source)) {
163         // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
164         // may open a record track on behalf of a client. Note that pid may be a tid.
165         // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
166         std::optional<AttributionSourceState> resolvedAttributionSource =
167                 resolveAttributionSource(attributionSource, virtualDeviceId);
168         if (!resolvedAttributionSource.has_value()) {
169             return PERMISSION_HARD_DENIED;
170         }
171 
172         permission::PermissionChecker permissionChecker;
173         int permitted;
174         if (start) {
175             // Do a double-check, where we first check without actually starting in order to handle
176             // the behavior of AppOps where ops are sometimes started but paused for SOFT_DENIED.
177             // Since there is no way to maintain reference consensus due to this behavior, avoid
178             // starting an op when a restriction is in place by first checking. In the case where we
179             // startOp would fail, call a noteOp (which will also fail) instead. This preserves
180             // behavior that is reliant on listening to op rejected events (such as the hint
181             // dialogue to unmute the microphone). Technically racy, but very unlikely.
182             //
183             // TODO(b/294609684) To be removed when the pause state for an OP is removed.
184             permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
185                     sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
186                     attributedOpCode);
187             if (permitted == PERMISSION_GRANTED) {
188                 permitted = permissionChecker.checkPermissionForStartDataDeliveryFromDatasource(
189                         sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
190                         attributedOpCode);
191             } else {
192                 // intentionally don't set permitted
193                 permissionChecker.checkPermissionForDataDeliveryFromDatasource(
194                             sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
195                             attributedOpCode);
196             }
197         } else {
198             permitted = permissionChecker.checkPermissionForPreflightFromDatasource(
199                     sAndroidPermissionRecordAudio, resolvedAttributionSource.value(), msg,
200                     attributedOpCode);
201         }
202 
203         return permitted;
204     } else {
205         if (attributedOpCode == AppOpsManager::OP_NONE) return PERMISSION_GRANTED;  // nothing to do
206         AppOpsManager ap{};
207         PermissionController pc{};
208         return ap.startOpNoThrow(
209                 attributedOpCode, attributionSource.uid,
210                 resolveCallingPackage(pc,
211                                       String16{attributionSource.packageName.value_or("").c_str()},
212                                       attributionSource.uid),
213                 false,
214                 attributionSource.attributionTag.has_value()
215                         ? String16{attributionSource.attributionTag.value().c_str()}
216                         : String16{},
217                 msg);
218     }
219 }
220 
221 static constexpr int DEVICE_ID_DEFAULT = 0;
222 
recordingAllowed(const AttributionSourceState & attributionSource,audio_source_t source)223 bool recordingAllowed(const AttributionSourceState &attributionSource, audio_source_t source) {
224     return checkRecordingInternal(attributionSource, DEVICE_ID_DEFAULT, String16(), /*start*/ false,
225                                   source) != PERMISSION_HARD_DENIED;
226 }
227 
recordingAllowed(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,audio_source_t source)228 bool recordingAllowed(const AttributionSourceState &attributionSource,
229                       const uint32_t virtualDeviceId,
230                       audio_source_t source) {
231     return checkRecordingInternal(attributionSource, virtualDeviceId,
232                                   String16(), /*start*/ false, source) != PERMISSION_HARD_DENIED;
233 }
234 
startRecording(const AttributionSourceState & attributionSource,const uint32_t virtualDeviceId,const String16 & msg,audio_source_t source)235 int startRecording(const AttributionSourceState& attributionSource,
236                     const uint32_t virtualDeviceId,
237                     const String16& msg,
238                     audio_source_t source) {
239     return checkRecordingInternal(attributionSource, virtualDeviceId, msg, /*start*/ true,
240                                   source);
241 }
242 
finishRecording(const AttributionSourceState & attributionSource,uint32_t virtualDeviceId,audio_source_t source)243 void finishRecording(const AttributionSourceState &attributionSource, uint32_t virtualDeviceId,
244                      audio_source_t source) {
245     // Okay to not track in app ops as audio server is us and if
246     // device is rooted security model is considered compromised.
247     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
248     if (isAudioServerOrMediaServerOrSystemServerOrRootUid(uid)) return;
249 
250     const int32_t attributedOpCode = getOpForSource(source);
251     if (isRecordOpRequired(source)) {
252         // We specify a pid and uid here as mediaserver (aka MediaRecorder or StageFrightRecorder)
253         // may open a record track on behalf of a client. Note that pid may be a tid.
254         // IMPORTANT: DON'T USE PermissionCache - RUNTIME PERMISSIONS CHANGE.
255         const std::optional<AttributionSourceState> resolvedAttributionSource =
256                 resolveAttributionSource(attributionSource, virtualDeviceId);
257         if (!resolvedAttributionSource.has_value()) {
258             return;
259         }
260 
261         permission::PermissionChecker permissionChecker;
262         permissionChecker.finishDataDeliveryFromDatasource(attributedOpCode,
263                 resolvedAttributionSource.value());
264     } else {
265         if (attributedOpCode == AppOpsManager::OP_NONE) return;  // nothing to do
266         AppOpsManager ap{};
267         PermissionController pc{};
268         ap.finishOp(attributedOpCode, attributionSource.uid,
269                     resolveCallingPackage(
270                             pc, String16{attributionSource.packageName.value_or("").c_str()},
271                             attributionSource.uid),
272                     attributionSource.attributionTag.has_value()
273                             ? String16{attributionSource.attributionTag.value().c_str()}
274                             : String16{});
275     }
276 }
277 
captureAudioOutputAllowed(const AttributionSourceState & attributionSource)278 bool captureAudioOutputAllowed(const AttributionSourceState& attributionSource) {
279     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
280     if (isAudioServerOrRootUid(uid)) return true;
281     static const String16 sCaptureAudioOutput("android.permission.CAPTURE_AUDIO_OUTPUT");
282     // Use PermissionChecker, which includes some logic for allowing the isolated
283     // HotwordDetectionService to hold certain permissions.
284     permission::PermissionChecker permissionChecker;
285     bool ok = (permissionChecker.checkPermissionForPreflight(
286             sCaptureAudioOutput, attributionSource, String16(),
287             AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
288     if (!ok) ALOGV("Request requires android.permission.CAPTURE_AUDIO_OUTPUT");
289     return ok;
290 }
291 
captureMediaOutputAllowed(const AttributionSourceState & attributionSource)292 bool captureMediaOutputAllowed(const AttributionSourceState& attributionSource) {
293     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
294     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
295     if (isAudioServerOrRootUid(uid)) return true;
296     static const String16 sCaptureMediaOutput("android.permission.CAPTURE_MEDIA_OUTPUT");
297     bool ok = PermissionCache::checkPermission(sCaptureMediaOutput, pid, uid);
298     if (!ok) ALOGE("Request requires android.permission.CAPTURE_MEDIA_OUTPUT");
299     return ok;
300 }
301 
captureTunerAudioInputAllowed(const AttributionSourceState & attributionSource)302 bool captureTunerAudioInputAllowed(const AttributionSourceState& attributionSource) {
303     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
304     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
305     if (isAudioServerOrRootUid(uid)) return true;
306     static const String16 sCaptureTunerAudioInput("android.permission.CAPTURE_TUNER_AUDIO_INPUT");
307     bool ok = PermissionCache::checkPermission(sCaptureTunerAudioInput, pid, uid);
308     if (!ok) ALOGV("Request requires android.permission.CAPTURE_TUNER_AUDIO_INPUT");
309     return ok;
310 }
311 
captureVoiceCommunicationOutputAllowed(const AttributionSourceState & attributionSource)312 bool captureVoiceCommunicationOutputAllowed(const AttributionSourceState& attributionSource) {
313     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
314     uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
315     if (isAudioServerOrRootUid(uid)) return true;
316     static const String16 sCaptureVoiceCommOutput(
317         "android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
318     bool ok = PermissionCache::checkPermission(sCaptureVoiceCommOutput, pid, uid);
319     if (!ok) ALOGE("Request requires android.permission.CAPTURE_VOICE_COMMUNICATION_OUTPUT");
320     return ok;
321 }
322 
bypassConcurrentPolicyAllowed(const AttributionSourceState & attributionSource)323 bool bypassConcurrentPolicyAllowed(const AttributionSourceState& attributionSource) {
324     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
325     uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
326     if (isAudioServerOrRootUid(uid)) return true;
327     static const String16 sBypassConcurrentPolicy(
328             "android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION ");
329     // Use PermissionChecker, which includes some logic for allowing the isolated
330     // HotwordDetectionService to hold certain permissions.
331     bool ok = PermissionCache::checkPermission(sBypassConcurrentPolicy, pid, uid);
332     if (!ok) {
333         ALOGV("Request requires android.permission.BYPASS_CONCURRENT_RECORD_AUDIO_RESTRICTION");
334     }
335     return ok;
336 }
337 
accessUltrasoundAllowed(const AttributionSourceState & attributionSource)338 bool accessUltrasoundAllowed(const AttributionSourceState& attributionSource) {
339     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
340     uid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
341     if (isAudioServerOrRootUid(uid)) return true;
342     static const String16 sAccessUltrasound(
343         "android.permission.ACCESS_ULTRASOUND");
344     bool ok = PermissionCache::checkPermission(sAccessUltrasound, pid, uid);
345     if (!ok) ALOGE("Request requires android.permission.ACCESS_ULTRASOUND");
346     return ok;
347 }
348 
captureHotwordAllowed(const AttributionSourceState & attributionSource)349 bool captureHotwordAllowed(const AttributionSourceState& attributionSource) {
350     // CAPTURE_AUDIO_HOTWORD permission implies RECORD_AUDIO permission
351     bool ok = recordingAllowed(attributionSource);
352 
353     if (ok) {
354         static const String16 sCaptureHotwordAllowed("android.permission.CAPTURE_AUDIO_HOTWORD");
355         // Use PermissionChecker, which includes some logic for allowing the isolated
356         // HotwordDetectionService to hold certain permissions.
357         permission::PermissionChecker permissionChecker;
358         ok = (permissionChecker.checkPermissionForPreflight(
359                 sCaptureHotwordAllowed, attributionSource, String16(),
360                 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED);
361     }
362     if (!ok) ALOGV("android.permission.CAPTURE_AUDIO_HOTWORD");
363     return ok;
364 }
365 
settingsAllowed()366 bool settingsAllowed() {
367     // given this is a permission check, could this be isAudioServerOrRootUid()?
368     if (isAudioServerUid(IPCThreadState::self()->getCallingUid())) return true;
369     static const String16 sAudioSettings("android.permission.MODIFY_AUDIO_SETTINGS");
370     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
371     bool ok = PermissionCache::checkCallingPermission(sAudioSettings);
372     if (!ok) ALOGE("Request requires android.permission.MODIFY_AUDIO_SETTINGS");
373     return ok;
374 }
375 
modifyAudioRoutingAllowed()376 bool modifyAudioRoutingAllowed() {
377     return modifyAudioRoutingAllowed(getCallingAttributionSource());
378 }
379 
modifyAudioRoutingAllowed(const AttributionSourceState & attributionSource)380 bool modifyAudioRoutingAllowed(const AttributionSourceState& attributionSource) {
381     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
382     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
383     if (isAudioServerUid(uid)) return true;
384     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
385     bool ok = PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
386     if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_ROUTING denied for uid %d",
387         __func__, uid);
388     return ok;
389 }
390 
modifyDefaultAudioEffectsAllowed()391 bool modifyDefaultAudioEffectsAllowed() {
392     return modifyDefaultAudioEffectsAllowed(getCallingAttributionSource());
393 }
394 
modifyDefaultAudioEffectsAllowed(const AttributionSourceState & attributionSource)395 bool modifyDefaultAudioEffectsAllowed(const AttributionSourceState& attributionSource) {
396     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
397     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
398     if (isAudioServerUid(uid)) return true;
399 
400     static const String16 sModifyDefaultAudioEffectsAllowed(
401             "android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS");
402     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
403     bool ok = PermissionCache::checkPermission(sModifyDefaultAudioEffectsAllowed, pid, uid);
404     ALOGE_IF(!ok, "%s(): android.permission.MODIFY_DEFAULT_AUDIO_EFFECTS denied for uid %d",
405             __func__, uid);
406     return ok;
407 }
408 
modifyAudioSettingsPrivilegedAllowed(const AttributionSourceState & attributionSource)409 bool modifyAudioSettingsPrivilegedAllowed(const AttributionSourceState& attributionSource) {
410     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
411     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
412     if (isAudioServerUid(uid)) return true;
413     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
414     bool ok = PermissionCache::checkPermission(sModifyAudioSettingsPrivileged, pid, uid);
415     if (!ok) ALOGE("%s(): android.permission.MODIFY_AUDIO_SETTINGS_PRIVILEGED denied for uid %d",
416                    __func__, uid);
417     return ok;
418 }
419 
dumpAllowed()420 bool dumpAllowed() {
421     static const String16 sDump("android.permission.DUMP");
422     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
423     bool ok = PermissionCache::checkCallingPermission(sDump);
424     // convention is for caller to dump an error message to fd instead of logging here
425     //if (!ok) ALOGE("Request requires android.permission.DUMP");
426     return ok;
427 }
428 
modifyPhoneStateAllowed(const AttributionSourceState & attributionSource)429 bool modifyPhoneStateAllowed(const AttributionSourceState& attributionSource) {
430     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
431     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
432     bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid);
433     ALOGE_IF(!ok, "Request requires %s", String8(sModifyPhoneState).c_str());
434     return ok;
435 }
436 
437 // privileged behavior needed by Dialer, Settings, SetupWizard and CellBroadcastReceiver
bypassInterruptionPolicyAllowed(const AttributionSourceState & attributionSource)438 bool bypassInterruptionPolicyAllowed(const AttributionSourceState& attributionSource) {
439     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
440     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
441     static const String16 sWriteSecureSettings("android.permission.WRITE_SECURE_SETTINGS");
442     bool ok = PermissionCache::checkPermission(sModifyPhoneState, pid, uid)
443         || PermissionCache::checkPermission(sWriteSecureSettings, pid, uid)
444         || PermissionCache::checkPermission(sModifyAudioRouting, pid, uid);
445     ALOGE_IF(!ok, "Request requires %s or %s",
446              String8(sModifyPhoneState).c_str(), String8(sWriteSecureSettings).c_str());
447     return ok;
448 }
449 
callAudioInterceptionAllowed(const AttributionSourceState & attributionSource)450 bool callAudioInterceptionAllowed(const AttributionSourceState& attributionSource) {
451     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
452     pid_t pid = VALUE_OR_FATAL(aidl2legacy_int32_t_pid_t(attributionSource.pid));
453 
454     // IMPORTANT: Use PermissionCache - not a runtime permission and may not change.
455     bool ok = PermissionCache::checkPermission(sCallAudioInterception, pid, uid);
456     if (!ok) ALOGV("%s(): android.permission.CALL_AUDIO_INTERCEPTION denied for uid %d",
457         __func__, uid);
458     return ok;
459 }
460 
getCallingAttributionSource()461 AttributionSourceState getCallingAttributionSource() {
462     AttributionSourceState attributionSource = AttributionSourceState();
463     attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
464             IPCThreadState::self()->getCallingPid()));
465     attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
466             IPCThreadState::self()->getCallingUid()));
467     attributionSource.token = sp<BBinder>::make();
468   return attributionSource;
469 }
470 
purgePermissionCache()471 void purgePermissionCache() {
472     PermissionCache::purgeCache();
473 }
474 
checkIMemory(const sp<IMemory> & iMemory)475 status_t checkIMemory(const sp<IMemory>& iMemory)
476 {
477     if (iMemory == 0) {
478         ALOGE("%s check failed: NULL IMemory pointer", __FUNCTION__);
479         return BAD_VALUE;
480     }
481 
482     sp<IMemoryHeap> heap = iMemory->getMemory();
483     if (heap == 0) {
484         ALOGE("%s check failed: NULL heap pointer", __FUNCTION__);
485         return BAD_VALUE;
486     }
487 
488     off_t size = lseek(heap->getHeapID(), 0, SEEK_END);
489     lseek(heap->getHeapID(), 0, SEEK_SET);
490 
491     if (iMemory->unsecurePointer() == NULL || size < (off_t)iMemory->size()) {
492         ALOGE("%s check failed: pointer %p size %zu fd size %u",
493               __FUNCTION__, iMemory->unsecurePointer(), iMemory->size(), (uint32_t)size);
494         return BAD_VALUE;
495     }
496 
497     return NO_ERROR;
498 }
499 
500 // TODO(b/285588444), clean this up on main, but soak it for backporting purposes for now
501 namespace {
502 class BluetoothPermissionCache {
503     static constexpr auto SYSPROP_NAME = "cache_key.system_server.package_info";
504     const String16 BLUETOOTH_PERM {"android.permission.BLUETOOTH_CONNECT"};
505     mutable std::mutex mLock;
506     // Cached property conditionally defined, since only avail on bionic. On host, don't inval cache
507 #if defined(__BIONIC__)
508     // Unlocked, but only accessed from mListenerThread
509     base::CachedProperty mCachedProperty;
510 #endif
511     // This thread is designed to never join/terminate, so no signal is fine
512     const std::thread mListenerThread;
513     GUARDED_BY(mLock)
514     std::string mPropValue;
515     GUARDED_BY(mLock)
516     std::unordered_map<uid_t, bool> mCache;
517     PermissionController mPc{};
518 public:
BluetoothPermissionCache()519     BluetoothPermissionCache()
520 #if defined(__BIONIC__)
521             : mCachedProperty{SYSPROP_NAME},
__anon6f05e6f80302() 522             mListenerThread([this]() mutable {
523                     while (true) {
524                         std::string newVal = mCachedProperty.WaitForChange() ?: "";
525                         std::lock_guard l{mLock};
526                         if (newVal != mPropValue) {
527                             ALOGV("Bluetooth permission update");
528                             mPropValue = newVal;
529                             mCache.clear();
530                         }
531                     }
532                 })
533 #endif
534             {}
535 
checkPermission(uid_t uid,pid_t pid)536     bool checkPermission(uid_t uid, pid_t pid) {
537         std::lock_guard l{mLock};
538         auto it = mCache.find(uid);
539         if (it == mCache.end()) {
540             it = mCache.insert({uid, mPc.checkPermission(BLUETOOTH_PERM, pid, uid)}).first;
541         }
542         return it->second;
543     }
544 };
545 
546 // Don't call this from locks, since it potentially calls up to system server!
547 // Check for non-app UIDs above this method!
checkBluetoothPermission(const AttributionSourceState & attr)548 bool checkBluetoothPermission(const AttributionSourceState& attr) {
549     [[clang::no_destroy]]  static BluetoothPermissionCache impl{};
550     return impl.checkPermission(attr.uid, attr.pid);
551 }
552 } // anonymous
553 
554 /**
555  * Determines if the MAC address in Bluetooth device descriptors returned by APIs of
556  * a native audio service (audio flinger, audio policy) must be anonymized.
557  * MAC addresses returned to system server or apps with BLUETOOTH_CONNECT permission
558  * are not anonymized.
559  *
560  * @param attributionSource The attribution source of the calling app.
561  * @param caller string identifying the caller for logging.
562  * @return true if the MAC addresses must be anonymized, false otherwise.
563  */
mustAnonymizeBluetoothAddressLegacy(const AttributionSourceState & attributionSource,const String16 &)564 bool mustAnonymizeBluetoothAddressLegacy(
565         const AttributionSourceState& attributionSource, const String16&) {
566     uid_t uid = VALUE_OR_FATAL(aidl2legacy_int32_t_uid_t(attributionSource.uid));
567     bool res;
568     switch(multiuser_get_app_id(uid)) {
569         case AID_ROOT:
570         case AID_SYSTEM:
571         case AID_RADIO:
572         case AID_BLUETOOTH:
573         case AID_MEDIA:
574         case AID_AUDIOSERVER:
575             // Don't anonymize for privileged clients
576             res = false;
577             break;
578         default:
579             res = !checkBluetoothPermission(attributionSource);
580             break;
581     }
582     ALOGV("%s uid: %d, result: %d", __func__, uid, res);
583     return res;
584 }
585 
586 /**
587  * Modifies the passed MAC address string in place for consumption by unprivileged clients.
588  * the string is assumed to have a valid MAC address format.
589  * the anonymization must be kept in sync with toAnonymizedAddress() in BluetoothUtils.java
590  *
591  * @param address input/output the char string contining the MAC address to anonymize.
592  */
anonymizeBluetoothAddress(char * address)593 void anonymizeBluetoothAddress(char *address) {
594     if (address == nullptr || strlen(address) != strlen("AA:BB:CC:DD:EE:FF")) {
595         return;
596     }
597     memcpy(address, "XX:XX:XX:XX", strlen("XX:XX:XX:XX"));
598 }
599 
retrievePackageManager()600 sp<content::pm::IPackageManagerNative> MediaPackageManager::retrievePackageManager() {
601     const sp<IServiceManager> sm = defaultServiceManager();
602     if (sm == nullptr) {
603         ALOGW("%s: failed to retrieve defaultServiceManager", __func__);
604         return nullptr;
605     }
606     sp<IBinder> packageManager = sm->checkService(String16(nativePackageManagerName));
607     if (packageManager == nullptr) {
608         ALOGW("%s: failed to retrieve native package manager", __func__);
609         return nullptr;
610     }
611     return interface_cast<content::pm::IPackageManagerNative>(packageManager);
612 }
613 
doIsAllowed(uid_t uid)614 std::optional<bool> MediaPackageManager::doIsAllowed(uid_t uid) {
615     if (mPackageManager == nullptr) {
616         /** Can not fetch package manager at construction it may not yet be registered. */
617         mPackageManager = retrievePackageManager();
618         if (mPackageManager == nullptr) {
619             ALOGW("%s: Playback capture is denied as package manager is not reachable", __func__);
620             return std::nullopt;
621         }
622     }
623 
624     // Retrieve package names for the UID and transform to a std::vector<std::string>.
625     Vector<String16> str16PackageNames;
626     PermissionController{}.getPackagesForUid(uid, str16PackageNames);
627     std::vector<std::string> packageNames;
628     for (const auto& str16PackageName : str16PackageNames) {
629         packageNames.emplace_back(String8(str16PackageName).c_str());
630     }
631     if (packageNames.empty()) {
632         ALOGW("%s: Playback capture for uid %u is denied as no package name could be retrieved "
633               "from the package manager.", __func__, uid);
634         return std::nullopt;
635     }
636     std::vector<bool> isAllowed;
637     auto status = mPackageManager->isAudioPlaybackCaptureAllowed(packageNames, &isAllowed);
638     if (!status.isOk()) {
639         ALOGW("%s: Playback capture is denied for uid %u as the manifest property could not be "
640               "retrieved from the package manager: %s", __func__, uid, status.toString8().c_str());
641         return std::nullopt;
642     }
643     if (packageNames.size() != isAllowed.size()) {
644         ALOGW("%s: Playback capture is denied for uid %u as the package manager returned incoherent"
645               " response size: %zu != %zu", __func__, uid, packageNames.size(), isAllowed.size());
646         return std::nullopt;
647     }
648 
649     // Zip together packageNames and isAllowed for debug logs
650     Packages& packages = mDebugLog[uid];
651     packages.resize(packageNames.size()); // Reuse all objects
652     std::transform(begin(packageNames), end(packageNames), begin(isAllowed),
653                    begin(packages), [] (auto& name, bool isAllowed) -> Package {
654                        return {std::move(name), isAllowed};
655                    });
656 
657     // Only allow playback record if all packages in this UID allow it
658     bool playbackCaptureAllowed = std::all_of(begin(isAllowed), end(isAllowed),
659                                                   [](bool b) { return b; });
660 
661     return playbackCaptureAllowed;
662 }
663 
dump(int fd,int spaces) const664 void MediaPackageManager::dump(int fd, int spaces) const {
665     dprintf(fd, "%*sAllow playback capture log:\n", spaces, "");
666     if (mPackageManager == nullptr) {
667         dprintf(fd, "%*sNo package manager\n", spaces + 2, "");
668     }
669     dprintf(fd, "%*sPackage manager errors: %u\n", spaces + 2, "", mPackageManagerErrors);
670 
671     for (const auto& uidCache : mDebugLog) {
672         for (const auto& package : std::get<Packages>(uidCache)) {
673             dprintf(fd, "%*s- uid=%5u, allowPlaybackCapture=%s, packageName=%s\n", spaces + 2, "",
674                     std::get<const uid_t>(uidCache),
675                     package.playbackCaptureAllowed ? "true " : "false",
676                     package.name.c_str());
677         }
678     }
679 }
680 
681 namespace mediautils {
682 
683 // How long we hold info before we re-fetch it (24 hours) if we found it previously.
684 static constexpr nsecs_t INFO_EXPIRATION_NS = 24 * 60 * 60 * NANOS_PER_SECOND;
685 // Maximum info records we retain before clearing everything.
686 static constexpr size_t INFO_CACHE_MAX = 1000;
687 
688 // The original code is from MediaMetricsService.cpp.
getCachedInfo(uid_t uid)689 std::shared_ptr<const UidInfo::Info> UidInfo::getCachedInfo(uid_t uid)
690 {
691     std::shared_ptr<const UidInfo::Info> info;
692 
693     const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
694     {
695         std::lock_guard _l(mLock);
696         auto it = mInfoMap.find(uid);
697         if (it != mInfoMap.end()) {
698             info = it->second;
699             ALOGV("%s: uid %d expiration %lld now %lld",
700                     __func__, uid, (long long)info->expirationNs, (long long)now);
701             if (info->expirationNs <= now) {
702                 // purge the stale entry and fall into re-fetching
703                 ALOGV("%s: entry for uid %d expired, now %lld",
704                         __func__, uid, (long long)now);
705                 mInfoMap.erase(it);
706                 info.reset();  // force refetch
707             }
708         }
709     }
710 
711     // if we did not find it in our map, look it up
712     if (!info) {
713         sp<IServiceManager> sm = defaultServiceManager();
714         sp<content::pm::IPackageManagerNative> package_mgr;
715         if (sm.get() == nullptr) {
716             ALOGE("%s: Cannot find service manager", __func__);
717         } else {
718             sp<IBinder> binder = sm->getService(String16("package_native"));
719             if (binder.get() == nullptr) {
720                 ALOGE("%s: Cannot find package_native", __func__);
721             } else {
722                 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
723             }
724         }
725 
726         // find package name
727         std::string pkg;
728         if (package_mgr != nullptr) {
729             std::vector<std::string> names;
730             binder::Status status = package_mgr->getNamesForUids({(int)uid}, &names);
731             if (!status.isOk()) {
732                 ALOGE("%s: getNamesForUids failed: %s",
733                         __func__, status.exceptionMessage().c_str());
734             } else {
735                 if (!names[0].empty()) {
736                     pkg = names[0].c_str();
737                 }
738             }
739         }
740 
741         if (pkg.empty()) {
742             struct passwd pw{}, *result;
743             char buf[8192]; // extra buffer space - should exceed what is
744                             // required in struct passwd_pw (tested),
745                             // and even then this is only used in backup
746                             // when the package manager is unavailable.
747             if (getpwuid_r(uid, &pw, buf, sizeof(buf), &result) == 0
748                     && result != nullptr
749                     && result->pw_name != nullptr) {
750                 pkg = result->pw_name;
751             }
752         }
753 
754         // strip any leading "shared:" strings that came back
755         if (pkg.compare(0, 7, "shared:") == 0) {
756             pkg.erase(0, 7);
757         }
758 
759         // determine how pkg was installed and the versionCode
760         std::string installer;
761         int64_t versionCode = 0;
762         bool notFound = false;
763         if (pkg.empty()) {
764             pkg = std::to_string(uid); // not found
765             notFound = true;
766         } else if (strchr(pkg.c_str(), '.') == nullptr) {
767             // not of form 'com.whatever...'; assume internal
768             // so we don't need to look it up in package manager.
769         } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
770             // android.* packages are assumed fine
771         } else if (package_mgr.get() != nullptr) {
772             String16 pkgName16(pkg.c_str());
773             binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
774             if (!status.isOk()) {
775                 ALOGE("%s: getInstallerForPackage failed: %s",
776                         __func__, status.exceptionMessage().c_str());
777             }
778 
779             // skip if we didn't get an installer
780             if (status.isOk()) {
781                 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
782                 if (!status.isOk()) {
783                     ALOGE("%s: getVersionCodeForPackage failed: %s",
784                             __func__, status.exceptionMessage().c_str());
785                 }
786             }
787 
788             ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
789                     __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
790         }
791 
792         // add it to the map, to save a subsequent lookup
793         std::lock_guard _l(mLock);
794         // first clear if we have too many cached elements.  This would be rare.
795         if (mInfoMap.size() >= INFO_CACHE_MAX) mInfoMap.clear();
796 
797         info = std::make_shared<const UidInfo::Info>(
798                 uid,
799                 std::move(pkg),
800                 std::move(installer),
801                 versionCode,
802                 now + (notFound ? 0 : INFO_EXPIRATION_NS));
803         ALOGV("%s: adding uid %d package '%s' expirationNs: %lld",
804                 __func__, uid, info->package.c_str(), (long long)info->expirationNs);
805         mInfoMap[uid] = info;
806     }
807     return info;
808 }
809 
810 /* static */
getUidInfo()811 UidInfo& UidInfo::getUidInfo() {
812     [[clang::no_destroy]] static UidInfo uidInfo;
813     return uidInfo;
814 }
815 
816 /* static */
getInfo(uid_t uid)817 std::shared_ptr<const UidInfo::Info> UidInfo::getInfo(uid_t uid) {
818     return UidInfo::getUidInfo().getCachedInfo(uid);
819 }
820 
821 } // namespace mediautils
822 
823 } // namespace android
824