問題:
項目中有一下情況:進程A調用另一進程的B ContentProvider,B在該此次query中需要在query另一個 C ContentProvider:
class BContentProvider extends ContentProvider {
Context mContext;
...
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
...
try {
// query C ContentProvider:
Cursor cursor = mContext.getContentResolver().query(...);
if (cursor != null) {
try {
//do something;
} finally {
cursor.close();
}
}
Cursor cursor = mContext.getContentResolver().query(...);
...
...
}
}
}
在這種情況下,系統拋出Exception如下:
1-11 16:04:51.867 2633 3557 W AppOps : Bad call: specified package com.providers.xxx under uid 10032 but it is really 10001
01-11 16:04:51.867 2633 3557 W AppOps : java.lang.RuntimeException: here
01-11 16:04:51.867 2633 3557 W AppOps : at com.android.server.AppOpsService.getOpsRawLocked(AppOpsService.java:1399)
01-11 16:04:51.867 2633 3557 W AppOps : at com.android.server.AppOpsService.noteOperationUnchecked(AppOpsService.java:1115)
01-11 16:04:51.867 2633 3557 W AppOps : at com.android.server.AppOpsService.noteProxyOperation(AppOpsService.java:1093)
01-11 16:04:51.867 2633 3557 W AppOps : at com.android.internal.app.IAppOpsService$Stub.onTransact(IAppOpsService.java:157)
01-11 16:04:51.867 2633 3557 W AppOps : at android.os.BinderInjector.onTransact(BinderInjector.java:30)
01-11 16:04:51.867 2633 3557 W AppOps : at android.os.Binder.execTransact(Binder.java:569)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: Writing exception to parcel
01-11 16:04:51.868 4659 6791 E DatabaseUtils: java.lang.SecurityException: Proxy package com.providers.xxx from uid 10001 or calling package com.providers.xxx from uid 10032 not allowed to perform READ_PROVIDER_C
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.app.AppOpsManager.noteProxyOp(AppOpsManager.java:1834)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProvider.checkPermissionAndAppOp(ContentProvider.java:538)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:560)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:483)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProvider$Transport.query(ContentProvider.java:212)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentResolver.query(ContentResolver.java:532)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentResolver.query(ContentResolver.java:473)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at com.android.providers.xxx.BDatabaseHelper.query(BDatabaseHelper.java:7238)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProvider$Transport.query(ContentProvider.java:239)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.os.BinderInjector.onTransact(BinderInjector.java:30)
01-11 16:04:51.868 4659 6791 E DatabaseUtils: at android.os.Binder.execTransact(Binder.java:569)
分析:
由于錯誤log首先反應了沒有C ContentProvider的權限,但檢查A應用是有C的讀寫權限的。所以排除了A的權限問題。
繼續分析:
通過log可以看到確實是ContentProvider在做權限檢查時出錯。通過log中對應的源碼進行分析:
首先可以看到ContentProvider.query()的時候做了權限檢查,注意,傳入的enforceReadPermission()的callingPkg是調用方的包名,以上面為例,就是B的包名。
ContentProvider.query():
@Override
public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
@Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
validateIncomingUri(uri);
uri = maybeGetUriWithoutUserId(uri);
if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
enforceReadPermission()調用了.checkPermissionAndAppOp()方法,ContentProvider.checkPermissionAndAppOp()調用了AppOpsManager.noteProxyOp()去做檢查出了異常。
AppOpsManager.noteProxyOp():
public int noteProxyOp(int op, String proxiedPackageName) {
int mode = noteProxyOpNoThrow(op, proxiedPackageName);
if (mode == MODE_ERRORED) {
throw new SecurityException("Proxy package " + mContext.getOpPackageName()
+ " from uid " + Process.myUid() + " or calling package "
+ proxiedPackageName + " from uid " + Binder.getCallingUid()
+ " not allowed to perform " + sOpNames[op]);
}
return mode;
}
noteProxyOpNoThrow()又做了什么呢?
AppOpsManager.noteProxyOpNoThrow():
/**
* Like {@link #noteProxyOp(int, String)} but instead
* of throwing a {@link SecurityException} it returns {@link #MODE_ERRORED}.
* @hide
*/
public int noteProxyOpNoThrow(int op, String proxiedPackageName) {
try {
return mService.noteProxyOperation(op, mContext.getOpPackageName(),
Binder.getCallingUid(), proxiedPackageName);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
可見noteProxyOpNoThrow()是通過binder調用到了AppOpsService.noteProxyOperation()方法,注意,這里傳入的是AppOpsService.noteProxyOperation()的后兩個參數為Binder.getCallingUid()和之前層層傳入的調用方的包名,也就是上面例子的B的包名。
下面,繼續看binder另一側的AppOpsService.noteProxyOperation()方法,我們結合log中AppOps的輸出log:
AppOpsService.noteProxyOperation():
@Override
public int noteProxyOperation(int code, String proxyPackageName,
int proxiedUid, String proxiedPackageName) {
verifyIncomingOp(code);
final int proxyUid = Binder.getCallingUid();
String resolveProxyPackageName = resolvePackageName(proxyUid, proxyPackageName);
if (resolveProxyPackageName == null) {
return AppOpsManager.MODE_IGNORED;
}
final int proxyMode = noteOperationUnchecked(code, proxyUid,
resolveProxyPackageName, -1, null);
if (proxyMode != AppOpsManager.MODE_ALLOWED || Binder.getCallingUid() == proxiedUid) {
return proxyMode;
}
String resolveProxiedPackageName = resolvePackageName(proxiedUid, proxiedPackageName);
if (resolveProxiedPackageName == null) {
return AppOpsManager.MODE_IGNORED;
}
return noteOperationUnchecked(code, proxiedUid, resolveProxiedPackageName,
proxyMode, resolveProxyPackageName);
}
AppOpsService.noteOperationUnchecked():
private int noteOperationUnchecked(int code, int uid, String packageName,
int proxyUid, String proxyPackageName) {
Op op = null;
Op switchOp = null;
int switchCode;
int resultMode = AppOpsManager.MODE_ALLOWED;
synchronized (this) {
Ops ops = getOpsRawLocked(uid, packageName, true);
...
}
...
}
AppOpsService.getOpsRawLocked():
private Ops getOpsRawLocked(int uid, String packageName, boolean edit) {
...
Ops ops = uidState.pkgOps.get(packageName);
if (ops == null) {
if (!edit) {
return null;
}
boolean isPrivileged = false;
// This is the first time we have seen this package name under this uid,
// so let's make sure it is valid.
if (uid != 0) {
final long ident = Binder.clearCallingIdentity();
try {
int pkgUid = -1;
try {
ApplicationInfo appInfo = ActivityThread.getPackageManager()
.getApplicationInfo(packageName,
PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
UserHandle.getUserId(uid));
if (appInfo != null) {
pkgUid = appInfo.uid;
isPrivileged = (appInfo.privateFlags
& ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
}
...
}
...
if (pkgUid != uid) {
// Oops! The package name is not valid for the uid they are calling
// under. Abort.
RuntimeException ex = new RuntimeException("here");
ex.fillInStackTrace();
Slog.w(TAG, "Bad call: specified package " + packageName
+ " under uid " + uid + " but it is really " + pkgUid, ex);
return null;
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
ops = new Ops(packageName, uidState, isPrivileged);
uidState.pkgOps.put(packageName, ops);
}
return ops;
}
這里主要的操作就是將傳入的uid和包名進行判斷:比對該包對應的uid和傳入的uid比較,如果不一致就報錯。錯誤信息和log中的一致:
Bad call: specified package com.providers.xxx under uid 10032 but it is really 10001
上文提到了,這個包名是傳入的ContentProvider的調用方的包名,也就是例子中的B的包名。而uid是在AppOpsManager中通過Binder.getCallingUid()獲得的。log中顯示,此uid并不是B的uid,而是其上游調用者A的uid。
為什么在C中調用Binder.getCallingUid()得到的是A進程的呢?我找到了袁輝輝大神的一片博客: Binder IPC的權限控制
“線程B通過Binder調用當前線程的某個組件:此時線程B是線程B某個組件的調用端,則mCallingUid和mCallingPid應該保存當前線程B的PID和UID,故需要調用clearCallingIdentity()方法完成這個功能。當線程B調用完某個組件,由于線程B仍然處于線程A的被調用端,因此mCallingUid和mCallingPid需要恢復成線程A的UID和PID,這是調用restoreCallingIdentity()即可完成。”
Binder的機制就是這么設計的,所以需要在B進行下一次Binder調用(也就是query ContentProvider)之前調用clearCallingIdentity()來將B的
PID和UID附給mCallingUid和mCallingPid。Binder調用結束后在restoreCallingIdentity()來將其恢復成其原本調用方的PID和UID。這樣在C里就會用B的相關信息進行權限校驗,在AppOpsService.getOpsRawLocked(),UID和包名都是B的,是一致的,就不會報錯。
解決辦法:
其實上文也已經提到了,參考 Binder IPC的權限控制,在B進行Query前后分別調用clearCallingIdentity()
//作用是清空遠程調用端的uid和pid,用當前本地進程的uid和pid替代,這樣在之后的調用方去進行權限校驗時會以B的信息為主,不會出現包名和UID不一致的情況。
最后修改過的調用方式如下:
long token = Binder.clearCallingIdentity();
try {
Cursor cursor = mContext.getContentResolver().query(...);
if (cursor != null) {
try {
//do something;
} finally {
cursor.close();
}
}
} finally {
Binder.restoreCallingIdentity(token);
}
總結:
1.ContentProvider是用Binder實現的,查詢的過程其實就是一次Binder調用,所以想深入了解ContentProvider一定要會一些Binder相關的知識。
2.ContentProvider在接受一次查詢前會調用AppOpsManager(其會通過Binder再由AppOpsService完成)進行權限校驗,其中會校驗調用方的UID和包名是否一致,其相關功能可見文章: Android 權限管理 —— AppOps。
2.Binder調用時候可以通過Binder.getCallingPid()和Binder.getCallingUid()來獲取調用方的PID和UID,而如果A通過Binder調用B,B又Binder調用了C,那么在C中Binder.getCallingPid()和Binder.getCallingUid()得到的是A的PID和UID,這種情況下需要在B調用C的前后用Binder.clearCallingIdentity()和Binder.restoreCallingIdentity()使其帶上B的PID和UID,從而在C中進行權限校驗時候用B的信息進行校驗,當然這也符合邏輯,B調用的C,應該B需要有相應權限。
3.Binder.clearCallingIdentity()和Binder.restoreCallingIdentity()的實現原理 Binder IPC的權限控制也有介紹,是通過移位實現的。