1 /*
2 * Copyright (C) 2020 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 #include "IncrementalServiceValidation.h"
18
19 #include <android-base/stringprintf.h>
20 #include <binder/IPCThreadState.h>
21 #include <binder/PermissionCache.h>
22 #include <binder/PermissionController.h>
23 #include <errno.h>
24 #include <utils/String16.h>
25
26 namespace android::incremental {
27
Ok()28 binder::Status Ok() {
29 return binder::Status::ok();
30 }
31
Exception(uint32_t code,const std::string & msg)32 binder::Status Exception(uint32_t code, const std::string& msg) {
33 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
34 }
35
fromBinderStatus(const binder::Status & status)36 int fromBinderStatus(const binder::Status& status) {
37 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
38 ? status.serviceSpecificErrorCode() > 0
39 ? -status.serviceSpecificErrorCode()
40 : status.serviceSpecificErrorCode() == 0 ? -EFAULT
41 : status.serviceSpecificErrorCode()
42 : -EIO;
43 }
44
CheckPermissionForDataDelivery(const char * permission,const char * operation,const char * package)45 binder::Status CheckPermissionForDataDelivery(const char* permission, const char* operation,
46 const char* package) {
47 using android::base::StringPrintf;
48
49 int32_t pid;
50 int32_t uid;
51
52 if (!PermissionCache::checkCallingPermission(String16(permission), &pid, &uid)) {
53 return Exception(binder::Status::EX_SECURITY,
54 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, permission));
55 }
56
57 String16 packageName{package};
58
59 PermissionController pc;
60 if (auto packageUid = pc.getPackageUid(packageName, 0); packageUid != uid) {
61 return Exception(binder::Status::EX_SECURITY,
62 StringPrintf("UID %d / PID %d does not own package %s", uid, pid,
63 package));
64 }
65
66 if (!operation) {
67 return binder::Status::ok();
68 }
69
70 // Caller must also have op granted.
71 switch (auto result = pc.noteOp(String16(operation), uid, packageName); result) {
72 case PermissionController::MODE_ALLOWED:
73 case PermissionController::MODE_DEFAULT:
74 return binder::Status::ok();
75 default:
76 return Exception(binder::Status::EX_SECURITY,
77 StringPrintf("UID %d / PID %d / package %s lacks app-op %s, error %d",
78 uid, pid, package, operation, result));
79 }
80 }
81
82 } // namespace android::incremental
83