Debian Codegraph @

core/java/android/content/AttributionSource.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2021 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 package android.content;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.annotation.RequiresPermission;
22 import android.annotation.SystemApi;
23 import android.annotation.TestApi;
24 import android.app.ActivityThread;
25 import android.app.AppGlobals;
26 import android.os.Binder;
27 import android.os.Build;
28 import android.os.IBinder;
29 import android.os.Parcel;
30 import android.os.Parcelable;
31 import android.os.Process;
32 import android.os.UserHandle;
33 import android.permission.PermissionManager;
34 import android.util.ArraySet;
35
36 import com.android.internal.annotations.Immutable;
37
38 import java.util.Arrays;
39 import java.util.Collections;
40 import java.util.Objects;
41 import java.util.Set;
42
43 /**
44 * This class represents a source to which access to permission protected data should be
45 * attributed. Attribution sources can be chained to represent cases where the protected
46 * data would flow through several applications. For example, app A may ask app B for
47 * contacts and in turn app B may ask app C for contacts. In this case, the attribution
48 * chain would be A -> B -> C and the data flow would be C -> B -> A. There are two
49 * main benefits of using the attribution source mechanism: avoid doing explicit permission
50 * checks on behalf of the calling app if you are accessing private data on their behalf
51 * to send back; avoid double data access blaming which happens as you check the calling
52 * app's permissions and when you access the data behind these permissions (for runtime
53 * permissions). Also if not explicitly blaming the caller the data access would be
54 * counted towards your app vs to the previous app where yours was just a proxy.
55 * <p>
56 * Every {@link Context} has an attribution source and you can get it via {@link
57 * Context#getAttributionSource()} representing itself, which is a chain of one. You
58 * can attribute work to another app, or more precisely to a chain of apps, through
59 * which the data you would be accessing would flow, via {@link Context#createContext(
60 * ContextParams)} plus specifying an attribution source for the next app to receive
61 * the protected data you are accessing via {@link AttributionSource.Builder#setNext(
62 * AttributionSource)}. Creating this attribution chain ensures that the datasource would
63 * check whether every app in the attribution chain has permission to access the data
64 * before releasing it. The datasource will also record appropriately that this data was
65 * accessed by the apps in the sequence if the data is behind a sensitive permission
66 * (e.g. dangerous). Again, this is useful if you are accessing the data on behalf of another
67 * app, for example a speech recognizer using the mic so it can provide recognition to
68 * a calling app.
69 * <p>
70 * You can create an attribution chain of you and any other app without any verification
71 * as this is something already available via the {@link android.app.AppOpsManager} APIs.
72 * This is supported to handle cases where you don't have access to the caller's attribution
73 * source and you can directly use the {@link AttributionSource.Builder} APIs. However,
74 * if the data flows through more than two apps (more than you access the data for the
75 * caller) you need to have a handle to the {@link AttributionSource} for the calling app's
76 * context in order to create an attribution context. This means you either need to have an
77 * API for the other app to send you its attribution source or use a platform API that pipes
78 * the callers attribution source.
79 * <p>
80 * You cannot forge an attribution chain without the participation of every app in the
81 * attribution chain (aside of the special case mentioned above). To create an attribution
82 * source that is trusted you need to create an attribution context that points to an
83 * attribution source that was explicitly created by the app that it refers to, recursively.
84 * <p>
85 * Since creating an attribution context leads to all permissions for apps in the attribution
86 * chain being checked, you need to expect getting a security exception when accessing
87 * permission protected APIs since some app in the chain may not have the permission.
88 */
89 @Immutable
90 public final class AttributionSource implements Parcelable {
91 private static final String DESCRIPTOR = "android.content.AttributionSource";
92
93 private static final Binder sDefaultToken = new Binder(DESCRIPTOR);
94
95 private final @NonNull AttributionSourceState mAttributionSourceState;
96
97 private @Nullable AttributionSource mNextCached;
98 private @Nullable Set<String> mRenouncedPermissionsCached;
99
100 /** @hide */
101 @TestApi
102 public AttributionSource(int uid, @Nullable String packageName,
103 @Nullable String attributionTag) {
104 this(uid, packageName, attributionTag, sDefaultToken);
105 }
106
107 /** @hide */
108 @TestApi
109 public AttributionSource(int uid, @Nullable String packageName,
110 @Nullable String attributionTag, @NonNull IBinder token) {
111 this(uid, packageName, attributionTag, token, /*renouncedPermissions*/ null,
112 /*next*/ null);
113 }
114
115 /** @hide */
116 public AttributionSource(int uid, @Nullable String packageName,
117 @Nullable String attributionTag, @NonNull IBinder token,
118 @Nullable AttributionSource next) {
119 this(uid, packageName, attributionTag, token, /*renouncedPermissions*/ null, next);
120 }
121
122 /** @hide */
123 @TestApi
124 public AttributionSource(int uid, @Nullable String packageName,
125 @Nullable String attributionTag, @Nullable Set<String> renouncedPermissions,
126 @Nullable AttributionSource next) {
127 this(uid, packageName, attributionTag, (renouncedPermissions != null)
128 ? renouncedPermissions.toArray(new String[0]) : null, next);
129 }
130
131 /** @hide */
132 public AttributionSource(@NonNull AttributionSource current, @Nullable AttributionSource next) {
133 this(current.getUid(), current.getPackageName(), current.getAttributionTag(),
134 current.getToken(), current.mAttributionSourceState.renouncedPermissions, next);
135 }
136
137 AttributionSource(int uid, @Nullable String packageName, @Nullable String attributionTag,
138 @Nullable String[] renouncedPermissions, @Nullable AttributionSource next) {
139 this(uid, packageName, attributionTag, sDefaultToken, renouncedPermissions, next);
140 }
141
142 AttributionSource(int uid, @Nullable String packageName, @Nullable String attributionTag,
143 @NonNull IBinder token, @Nullable String[] renouncedPermissions,
144 @Nullable AttributionSource next) {
145 mAttributionSourceState = new AttributionSourceState();
146 mAttributionSourceState.uid = uid;
147 mAttributionSourceState.token = token;
148 mAttributionSourceState.packageName = packageName;
149 mAttributionSourceState.attributionTag = attributionTag;
150 mAttributionSourceState.renouncedPermissions = renouncedPermissions;
151 mAttributionSourceState.next = (next != null) ? new AttributionSourceState[]
152 {next.mAttributionSourceState} : new AttributionSourceState[0];
153 }
154
155 AttributionSource(@NonNull Parcel in) {
156 this(AttributionSourceState.CREATOR.createFromParcel(in));
157
158 // Since we just unpacked this object as part of it transiting a Binder
159 // call, this is the perfect time to enforce that its UID and PID can be trusted
160 enforceCallingUidAndPid();
161 }
162
163 /** @hide */
164 public AttributionSource(@NonNull AttributionSourceState attributionSourceState) {
165 mAttributionSourceState = attributionSourceState;
166 }
167
168 /** @hide */
169 public AttributionSource withNextAttributionSource(@Nullable AttributionSource next) {
170 return new AttributionSource(getUid(), getPackageName(), getAttributionTag(),
171 mAttributionSourceState.renouncedPermissions, next);
172 }
173
174 /** @hide */
175 public AttributionSource withPackageName(@Nullable String packageName) {
176 return new AttributionSource(getUid(), packageName, getAttributionTag(),
177 mAttributionSourceState.renouncedPermissions, getNext());
178 }
179
180 /** @hide */
181 public AttributionSource withToken(@NonNull Binder token) {
182 return new AttributionSource(getUid(), getPackageName(), getAttributionTag(),
183 token, mAttributionSourceState.renouncedPermissions, getNext());
184 }
185
186 /** @hide */
187 public @NonNull AttributionSourceState asState() {
188 return mAttributionSourceState;
189 }
190
191 /** @hide */
192 public @NonNull ScopedParcelState asScopedParcelState() {
193 return new ScopedParcelState(this);
194 }
195
196 /**
197 * Returns a generic {@link AttributionSource} that represents the entire
198 * calling process.
199 *
200 * <p>Callers are <em>strongly</em> encouraged to use a more specific
201 * attribution source whenever possible, such as from
202 * {@link Context#getAttributionSource()}, since that enables developers to
203 * have more detailed and scoped control over attribution within
204 * sub-components of their app.
205 *
206 * @see Context#createAttributionContext(String)
207 * @see Context#getAttributionTag()
208 * @return a generic {@link AttributionSource} representing the entire
209 * calling process
210 * @throws IllegalStateException when no accurate {@link AttributionSource}
211 * can be determined
212 */
213 public static @NonNull AttributionSource myAttributionSource() {
214
215 final AttributionSource globalSource = ActivityThread.currentAttributionSource();
216 if (globalSource != null) {
217 return globalSource;
218 }
219
220 int uid = Process.myUid();
221 if (uid == Process.ROOT_UID) {
222 uid = Process.SYSTEM_UID;
223 }
224 try {
225 return new AttributionSource.Builder(uid)
226 .setPackageName(AppGlobals.getPackageManager().getPackagesForUid(uid)[0])
227 .build();
228 } catch (Exception ignored) {
229 }
230
231 throw new IllegalStateException("Failed to resolve AttributionSource");
232 }
233
234 /**
235 * This is a scoped object that exposes the content of an attribution source
236 * as a parcel. This is useful when passing one to native and avoid custom
237 * conversion logic from Java to native state that needs to be kept in sync
238 * as attribution source evolves. This way we use the same logic for passing
239 * to native as the ones for passing in an IPC - in both cases this is the
240 * same auto generated code.
241 *
242 * @hide
243 */
244 public static class ScopedParcelState implements AutoCloseable {
245 private final Parcel mParcel;
246
247 public @NonNull Parcel getParcel() {
248 return mParcel;
249 }
250
251 public ScopedParcelState(AttributionSource attributionSource) {
252 mParcel = Parcel.obtain();
253 attributionSource.writeToParcel(mParcel, 0);
254 mParcel.setDataPosition(0);
255 }
256
257 public void close() {
258 mParcel.recycle();
259 }
260 }
261
262 /**
263 * If you are handling an IPC and you don't trust the caller you need to validate whether the
264 * attribution source is one for the calling app to prevent the caller to pass you a source from
265 * another app without including themselves in the attribution chain.
266 *
267 * @throws SecurityException if the attribution source cannot be trusted to be from the caller.
268 */
269 private void enforceCallingUidAndPid() {
270 enforceCallingUid();
271 enforceCallingPid();
272 }
273
274 /**
275 * If you are handling an IPC and you don't trust the caller you need to validate
276 * whether the attribution source is one for the calling app to prevent the caller
277 * to pass you a source from another app without including themselves in the
278 * attribution chain.
279 *
280 * @throws SecurityException if the attribution source cannot be trusted to be from the caller.
281 */
282 public void enforceCallingUid() {
283 if (!checkCallingUid()) {
284 throw new SecurityException("Calling uid: " + Binder.getCallingUid()
285 + " doesn't match source uid: " + mAttributionSourceState.uid);
286 }
287 // No need to check package as app ops manager does it already.
288 }
289
290 /**
291 * If you are handling an IPC and you don't trust the caller you need to validate
292 * whether the attribution source is one for the calling app to prevent the caller
293 * to pass you a source from another app without including themselves in the
294 * attribution chain.
295 *
296 * @return if the attribution source cannot be trusted to be from the caller.
297 */
298 public boolean checkCallingUid() {
299 final int callingUid = Binder.getCallingUid();
300 if (callingUid != Process.ROOT_UID
301 && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID
302 && callingUid != mAttributionSourceState.uid) {
303 return false;
304 }
305 // No need to check package as app ops manager does it already.
306 return true;
307 }
308
309 /**
310 * Validate that the pid being claimed for the calling app is not spoofed
311 *
312 * @throws SecurityException if the attribution source cannot be trusted to be from the caller.
313 * @hide
314 */
315 @TestApi
316 public void enforceCallingPid() {
317 if (!checkCallingPid()) {
318 throw new SecurityException("Calling pid: " + Binder.getCallingPid()
319 + " doesn't match source pid: " + mAttributionSourceState.pid);
320 }
321 }
322
323 /**
324 * Validate that the pid being claimed for the calling app is not spoofed
325 *
326 * @return if the attribution source cannot be trusted to be from the caller.
327 */
328 private boolean checkCallingPid() {
329 final int callingPid = Binder.getCallingPid();
330 if (mAttributionSourceState.pid != -1 && callingPid != mAttributionSourceState.pid) {
331 return false;
332 }
333 return true;
334 }
335
336 @Override
337 public String toString() {
338 if (Build.IS_DEBUGGABLE) {
339 return "AttributionSource { " +
340 "uid = " + mAttributionSourceState.uid + ", " +
341 "packageName = " + mAttributionSourceState.packageName + ", " +
342 "attributionTag = " + mAttributionSourceState.attributionTag + ", " +
343 "token = " + mAttributionSourceState.token + ", " +
344 "next = " + (mAttributionSourceState.next != null
345 && mAttributionSourceState.next.length > 0
346 ? mAttributionSourceState.next[0] : null) +
347 " }";
348 }
349 return super.toString();
350 }
351
352 /**
353 * @return The next UID that would receive the permission protected data.
354 *
355 * @hide
356 */
357 public int getNextUid() {
358 if (mAttributionSourceState.next != null
359 && mAttributionSourceState.next.length > 0) {
360 return mAttributionSourceState.next[0].uid;
361 }
362 return Process.INVALID_UID;
363 }
364
365 /**
366 * @return The next package that would receive the permission protected data.
367 *
368 * @hide
369 */
370 public @Nullable String getNextPackageName() {
371 if (mAttributionSourceState.next != null
372 && mAttributionSourceState.next.length > 0) {
373 return mAttributionSourceState.next[0].packageName;
374 }
375 return null;
376 }
377
378 /**
379 * @return The next package's attribution tag that would receive
380 * the permission protected data.
381 *
382 * @hide
383 */
384 public @Nullable String getNextAttributionTag() {
385 if (mAttributionSourceState.next != null
386 && mAttributionSourceState.next.length > 0) {
387 return mAttributionSourceState.next[0].attributionTag;
388 }
389 return null;
390 }
391
392 /**
393 * @return The next package's token that would receive
394 * the permission protected data.
395 *
396 * @hide
397 */
398 public @Nullable IBinder getNextToken() {
399 if (mAttributionSourceState.next != null
400 && mAttributionSourceState.next.length > 0) {
401 return mAttributionSourceState.next[0].token;
402 }
403 return null;
404 }
405
406 /**
407 * Checks whether this attribution source can be trusted. That is whether
408 * the app it refers to created it and provided to the attribution chain.
409 *
410 * @param context Context handle.
411 * @return Whether this is a trusted source.
412 */
413 public boolean isTrusted(@NonNull Context context) {
414 return mAttributionSourceState.token != null
415 && context.getSystemService(PermissionManager.class)
416 .isRegisteredAttributionSource(this);
417 }
418
419 /**
420 * Permissions that should be considered revoked regardless if granted.
421 *
422 * @hide
423 */
424 @SystemApi
425 @RequiresPermission(android.Manifest.permission.RENOUNCE_PERMISSIONS)
426 @NonNull
427 public Set<String> getRenouncedPermissions() {
428 if (mRenouncedPermissionsCached == null) {
429 if (mAttributionSourceState.renouncedPermissions != null) {
430 mRenouncedPermissionsCached = new ArraySet<>(
431 mAttributionSourceState.renouncedPermissions);
432 } else {
433 mRenouncedPermissionsCached = Collections.emptySet();
434 }
435 }
436 return mRenouncedPermissionsCached;
437 }
438
439 /**
440 * The UID that is accessing the permission protected data.
441 */
442 public int getUid() {
443 return mAttributionSourceState.uid;
444 }
445
446 /**
447 * The package that is accessing the permission protected data.
448 */
449 public @Nullable String getPackageName() {
450 return mAttributionSourceState.packageName;
451 }
452
453 /**
454 * The attribution tag of the app accessing the permission protected data.
455 */
456 public @Nullable String getAttributionTag() {
457 return mAttributionSourceState.attributionTag;
458 }
459
460 /**
461 * Unique token for that source.
462 *
463 * @hide
464 */
465 public @NonNull IBinder getToken() {
466 return mAttributionSourceState.token;
467 }
468
469 /**
470 * The next app to receive the permission protected data.
471 */
472 public @Nullable AttributionSource getNext() {
473 if (mNextCached == null && mAttributionSourceState.next != null
474 && mAttributionSourceState.next.length > 0) {
475 mNextCached = new AttributionSource(mAttributionSourceState.next[0]);
476 }
477 return mNextCached;
478 }
479
480 @Override
481 public boolean equals(@Nullable Object o) {
482 if (this == o) return true;
483 if (o == null || getClass() != o.getClass()) return false;
484 AttributionSource that = (AttributionSource) o;
485 return mAttributionSourceState.uid == that.mAttributionSourceState.uid
486 && Objects.equals(mAttributionSourceState.packageName,
487 that.mAttributionSourceState.packageName)
488 && Objects.equals(mAttributionSourceState.attributionTag,
489 that.mAttributionSourceState.attributionTag)
490 && Objects.equals(mAttributionSourceState.token,
491 that.mAttributionSourceState.token)
492 && Arrays.equals(mAttributionSourceState.renouncedPermissions,
493 that.mAttributionSourceState.renouncedPermissions)
494 && Objects.equals(getNext(), that.getNext());
495 }
496
497 @Override
498 public int hashCode() {
499 return Objects.hash(mAttributionSourceState.uid, mAttributionSourceState.packageName,
500 mAttributionSourceState.attributionTag, mAttributionSourceState.token,
501 Arrays.hashCode(mAttributionSourceState.renouncedPermissions), getNext());
502 }
503
504 @Override
505 public void writeToParcel(@NonNull Parcel dest, int flags) {
506 mAttributionSourceState.writeToParcel(dest, flags);
507 }
508
509 @Override
510 public int describeContents() { return 0; }
511
512 public static final @NonNull Parcelable.Creator<AttributionSource> CREATOR
513 = new Parcelable.Creator<AttributionSource>() {
514 @Override
515 public AttributionSource[] newArray(int size) {
516 return new AttributionSource[size];
517 }
518
519 @Override
520 public AttributionSource createFromParcel(@NonNull Parcel in) {
521 return new AttributionSource(in);
522 }
523 };
524
525 /**
526 * A builder for {@link AttributionSource}
527 */
528 public static final class Builder {
529 private @NonNull final AttributionSourceState mAttributionSourceState =
530 new AttributionSourceState();
531
532 private long mBuilderFieldsSet = 0L;
533
534 /**
535 * Creates a new Builder.
536 *
537 * @param uid
538 * The UID that is accessing the permission protected data.
539 */
540 public Builder(int uid) {
541 mAttributionSourceState.uid = uid;
542 }
543
544 public Builder(@NonNull AttributionSource current) {
545 if (current == null) {
546 throw new IllegalArgumentException("current AttributionSource can not be null");
547 }
548 mAttributionSourceState.uid = current.getUid();
549 mAttributionSourceState.packageName = current.getPackageName();
550 mAttributionSourceState.attributionTag = current.getAttributionTag();
551 mAttributionSourceState.token = current.getToken();
552 mAttributionSourceState.renouncedPermissions =
553 current.mAttributionSourceState.renouncedPermissions;
554 }
555
556 /**
557 * The package that is accessing the permission protected data.
558 */
559 public @NonNull Builder setPackageName(@Nullable String value) {
560 checkNotUsed();
561 mBuilderFieldsSet |= 0x2;
562 mAttributionSourceState.packageName = value;
563 return this;
564 }
565
566 /**
567 * The attribution tag of the app accessing the permission protected data.
568 */
569 public @NonNull Builder setAttributionTag(@Nullable String value) {
570 checkNotUsed();
571 mBuilderFieldsSet |= 0x4;
572 mAttributionSourceState.attributionTag = value;
573 return this;
574 }
575
576 /**
577 * Sets permissions which have been voluntarily "renounced" by the
578 * calling app.
579 * <p>
580 * Interactions performed through services obtained from the created
581 * Context will ideally be treated as if these "renounced" permissions
582 * have not actually been granted to the app, regardless of their actual
583 * grant status.
584 * <p>
585 * This is designed for use by separate logical components within an app
586 * which have no intention of interacting with data or services that are
587 * protected by the renounced permissions.
588 * <p>
589 * Note that only {@link PermissionInfo#PROTECTION_DANGEROUS}
590 * permissions are supported by this mechanism. Additionally, this
591 * mechanism only applies to calls made through services obtained via
592 * {@link Context#getSystemService}; it has no effect on static or raw
593 * Binder calls.
594 *
595 * @param renouncedPermissions The set of permissions to treat as
596 * renounced, which is as if not granted.
597 * @return This builder.
598 * @hide
599 */
600 @SystemApi
601 @RequiresPermission(android.Manifest.permission.RENOUNCE_PERMISSIONS)
602 public @NonNull Builder setRenouncedPermissions(@Nullable Set<String> value) {
603 checkNotUsed();
604 mBuilderFieldsSet |= 0x8;
605 mAttributionSourceState.renouncedPermissions = (value != null)
606 ? value.toArray(new String[0]) : null;
607 return this;
608 }
609
610 /**
611 * The next app to receive the permission protected data.
612 */
613 public @NonNull Builder setNext(@Nullable AttributionSource value) {
614 checkNotUsed();
615 mBuilderFieldsSet |= 0x10;
616 mAttributionSourceState.next = (value != null) ? new AttributionSourceState[]
617 {value.mAttributionSourceState} : mAttributionSourceState.next;
618 return this;
619 }
620
621 /** Builds the instance. This builder should not be touched after calling this! */
622 public @NonNull AttributionSource build() {
623 checkNotUsed();
624 mBuilderFieldsSet |= 0x40; // Mark builder used
625
626 if ((mBuilderFieldsSet & 0x2) == 0) {
627 mAttributionSourceState.packageName = null;
628 }
629 if ((mBuilderFieldsSet & 0x4) == 0) {
630 mAttributionSourceState.attributionTag = null;
631 }
632 if ((mBuilderFieldsSet & 0x8) == 0) {
633 mAttributionSourceState.renouncedPermissions = null;
634 }
635 if ((mBuilderFieldsSet & 0x10) == 0) {
636 mAttributionSourceState.next = null;
637 }
638
639 mAttributionSourceState.token = sDefaultToken;
640
641 if (mAttributionSourceState.next == null) {
642 // The NDK aidl backend doesn't support null parcelable arrays.
643 mAttributionSourceState.next = new AttributionSourceState[0];
644 }
645 return new AttributionSource(mAttributionSourceState);
646 }
647
648 private void checkNotUsed() {
649 if ((mBuilderFieldsSet & 0x40) != 0) {
650 throw new IllegalStateException(
651 "This Builder should not be reused. Use a new Builder instance instead");
652 }
653 }
654 }
655 }