問題:
項(xiàng)目中有一下情況:進(jìn)程A調(diào)用另一進(jìn)程的B ContentProvider,B在該此次query中需要在query另一個(gè) 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(...);
...
...
}
}
}
在這種情況下饥臂,系統(tǒng)拋出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)
分析:
由于錯(cuò)誤log首先反應(yīng)了沒有C ContentProvider的權(quán)限,但檢查A應(yīng)用是有C的讀寫權(quán)限的瀑晒。所以排除了A的權(quán)限問題论笔。
繼續(xù)分析:
通過log可以看到確實(shí)是ContentProvider在做權(quán)限檢查時(shí)出錯(cuò)。通過log中對(duì)應(yīng)的源碼進(jìn)行分析:
首先可以看到ContentProvider.query()的時(shí)候做了權(quán)限檢查懂昂,注意介时,傳入的enforceReadPermission()的callingPkg是調(diào)用方的包名,以上面為例,就是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()調(diào)用了.checkPermissionAndAppOp()方法循衰,ContentProvider.checkPermissionAndAppOp()調(diào)用了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調(diào)用到了AppOpsService.noteProxyOperation()方法会钝,注意,這里傳入的是AppOpsService.noteProxyOperation()的后兩個(gè)參數(shù)為Binder.getCallingUid()和之前層層傳入的調(diào)用方的包名工三,也就是上面例子的B的包名迁酸。
下面,繼續(xù)看binder另一側(cè)的AppOpsService.noteProxyOperation()方法,我們結(jié)合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和包名進(jìn)行判斷:比對(duì)該包對(duì)應(yīng)的uid和傳入的uid比較俭正,如果不一致就報(bào)錯(cuò)奸鬓。錯(cuò)誤信息和log中的一致:
Bad call: specified package com.providers.xxx under uid 10032 but it is really 10001
上文提到了,這個(gè)包名是傳入的ContentProvider的調(diào)用方的包名掸读,也就是例子中的B的包名串远。而uid是在AppOpsManager中通過Binder.getCallingUid()獲得的。log中顯示儿惫,此uid并不是B的uid澡罚,而是其上游調(diào)用者A的uid。
為什么在C中調(diào)用Binder.getCallingUid()得到的是A進(jìn)程的呢肾请?我找到了袁輝輝大神的一片博客: Binder IPC的權(quán)限控制
“線程B通過Binder調(diào)用當(dāng)前線程的某個(gè)組件:此時(shí)線程B是線程B某個(gè)組件的調(diào)用端留搔,則mCallingUid和mCallingPid應(yīng)該保存當(dāng)前線程B的PID和UID,故需要調(diào)用clearCallingIdentity()方法完成這個(gè)功能铛铁。當(dāng)線程B調(diào)用完某個(gè)組件催式,由于線程B仍然處于線程A的被調(diào)用端,因此mCallingUid和mCallingPid需要恢復(fù)成線程A的UID和PID避归,這是調(diào)用restoreCallingIdentity()即可完成荣月。”
Binder的機(jī)制就是這么設(shè)計(jì)的梳毙,所以需要在B進(jìn)行下一次Binder調(diào)用(也就是query ContentProvider)之前調(diào)用clearCallingIdentity()來將B的
PID和UID附給mCallingUid和mCallingPid哺窄。Binder調(diào)用結(jié)束后在restoreCallingIdentity()來將其恢復(fù)成其原本調(diào)用方的PID和UID。這樣在C里就會(huì)用B的相關(guān)信息進(jìn)行權(quán)限校驗(yàn)账锹,在AppOpsService.getOpsRawLocked()萌业,UID和包名都是B的,是一致的奸柬,就不會(huì)報(bào)錯(cuò)生年。
解決辦法:
其實(shí)上文也已經(jīng)提到了,參考 Binder IPC的權(quán)限控制廓奕,在B進(jìn)行Query前后分別調(diào)用clearCallingIdentity()
//作用是清空遠(yuǎn)程調(diào)用端的uid和pid抱婉,用當(dāng)前本地進(jìn)程的uid和pid替代档叔,這樣在之后的調(diào)用方去進(jìn)行權(quán)限校驗(yàn)時(shí)會(huì)以B的信息為主,不會(huì)出現(xiàn)包名和UID不一致的情況蒸绩。
最后修改過的調(diào)用方式如下:
long token = Binder.clearCallingIdentity();
try {
Cursor cursor = mContext.getContentResolver().query(...);
if (cursor != null) {
try {
//do something;
} finally {
cursor.close();
}
}
} finally {
Binder.restoreCallingIdentity(token);
}
總結(jié):
1.ContentProvider是用Binder實(shí)現(xiàn)的衙四,查詢的過程其實(shí)就是一次Binder調(diào)用,所以想深入了解ContentProvider一定要會(huì)一些Binder相關(guān)的知識(shí)患亿。
2.ContentProvider在接受一次查詢前會(huì)調(diào)用AppOpsManager(其會(huì)通過Binder再由AppOpsService完成)進(jìn)行權(quán)限校驗(yàn)传蹈,其中會(huì)校驗(yàn)調(diào)用方的UID和包名是否一致,其相關(guān)功能可見文章: Android 權(quán)限管理 —— AppOps步藕。
2.Binder調(diào)用時(shí)候可以通過Binder.getCallingPid()和Binder.getCallingUid()來獲取調(diào)用方的PID和UID惦界,而如果A通過Binder調(diào)用B,B又Binder調(diào)用了C咙冗,那么在C中Binder.getCallingPid()和Binder.getCallingUid()得到的是A的PID和UID沾歪,這種情況下需要在B調(diào)用C的前后用Binder.clearCallingIdentity()和Binder.restoreCallingIdentity()使其帶上B的PID和UID,從而在C中進(jìn)行權(quán)限校驗(yàn)時(shí)候用B的信息進(jìn)行校驗(yàn)乞娄,當(dāng)然這也符合邏輯,B調(diào)用的C显歧,應(yīng)該B需要有相應(yīng)權(quán)限仪或。
3.Binder.clearCallingIdentity()和Binder.restoreCallingIdentity()的實(shí)現(xiàn)原理 Binder IPC的權(quán)限控制也有介紹,是通過移位實(shí)現(xiàn)的士骤。