• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 #pragma once
18 
19 #include "NetdPermissions.h"
20 
21 #include <android-base/stringprintf.h>
22 #include <android-base/strings.h>
23 #include <binder/IPCThreadState.h>
24 #include <binder/IServiceManager.h>
25 #include <binder/Status.h>
26 #include <fmt/format.h>
27 #include <private/android_filesystem_config.h>
28 
29 #ifdef ANDROID_BINDER_STATUS_H
30 #define IS_BINDER_OK(__ex__) (__ex__ == ::android::binder::Status::EX_NONE)
31 
32 #define EXCEPTION_TO_STRING(__ex__, str)    \
33     case ::android::binder::Status::__ex__: \
34         return str;
35 
36 #define TO_EXCEPTION(__ex__) __ex__;
37 
38 #else
39 #define IS_BINDER_OK(__ex__) (AStatus_isOk(AStatus_fromExceptionCode(__ex__)))
40 
41 #define EXCEPTION_TO_STRING(__ex__, str) \
42     case __ex__:                         \
43         return str;
44 
45 #define TO_EXCEPTION(__ex__) AStatus_getExceptionCode(AStatus_fromExceptionCode(__ex__));
46 
47 #endif
48 
exceptionToString(int32_t exception)49 inline std::string exceptionToString(int32_t exception) {
50     switch (exception) {
51         EXCEPTION_TO_STRING(EX_SECURITY, "SecurityException")
52         EXCEPTION_TO_STRING(EX_BAD_PARCELABLE, "BadParcelableException")
53         EXCEPTION_TO_STRING(EX_ILLEGAL_ARGUMENT, "IllegalArgumentException")
54         EXCEPTION_TO_STRING(EX_NULL_POINTER, "NullPointerException")
55         EXCEPTION_TO_STRING(EX_ILLEGAL_STATE, "IllegalStateException")
56         EXCEPTION_TO_STRING(EX_NETWORK_MAIN_THREAD, "NetworkMainThreadException")
57         EXCEPTION_TO_STRING(EX_UNSUPPORTED_OPERATION, "UnsupportedOperationException")
58         EXCEPTION_TO_STRING(EX_SERVICE_SPECIFIC, "ServiceSpecificException")
59         EXCEPTION_TO_STRING(EX_PARCELABLE, "ParcelableException")
60         EXCEPTION_TO_STRING(EX_TRANSACTION_FAILED, "TransactionFailedException")
61         default:
62             return "UnknownException";
63     }
64 }
65 
66 using LogFn = std::function<void(const std::string& msg)>;
67 
68 template <typename LogType>
binderCallLogFn(const LogType & log,const LogFn & logFn)69 void binderCallLogFn(const LogType& log, const LogFn& logFn) {
70     using namespace std::string_literals;
71 
72     bool hasReturnArgs;
73     std::string output;
74 
75     hasReturnArgs = !log.result.empty();
76     output.append(log.method_name + "("s);
77 
78     // input args
79     for (size_t i = 0; i < log.input_args.size(); ++i) {
80         output.append(log.input_args[i].second);
81         if (i != log.input_args.size() - 1) {
82             output.append(", "s);
83         }
84     }
85     output.append(")"s);
86 
87     const int exceptionCode = TO_EXCEPTION(log.exception_code);
88 
89     if (hasReturnArgs || !IS_BINDER_OK(exceptionCode)) {
90         output.append(" -> "s);
91     }
92 
93     // return status
94     if (!IS_BINDER_OK(exceptionCode)) {
95         // an exception occurred
96         const int errCode = log.service_specific_error_code;
97         output.append(fmt::format("{}({}, \"{}\")", exceptionToString(exceptionCode),
98                                   (errCode != 0) ? errCode : exceptionCode, log.exception_message));
99     }
100     // return args
101     if (hasReturnArgs) {
102         output.append("{" + log.result + "}");
103     }
104     // duration time
105     output.append(fmt::format(" <{:.2f}ms>", log.duration_ms));
106 
107     // escape newline characters to avoid multiline log entries
108     logFn(::android::base::StringReplace(output, "\n", "\\n", true));
109 }
110 
111 // The input permissions should be equivalent that this function would return ok if any of them is
112 // granted.
checkAnyPermission(const std::vector<const char * > & permissions)113 inline android::binder::Status checkAnyPermission(const std::vector<const char*>& permissions) {
114     pid_t pid = android::IPCThreadState::self()->getCallingPid();
115     uid_t uid = android::IPCThreadState::self()->getCallingUid();
116 
117     // TODO: Do the pure permission check in this function. Have another method
118     // (e.g. checkNetworkStackPermission) to wrap AID_SYSTEM and
119     // AID_NETWORK_STACK uid check.
120     // If the caller is the system UID, don't check permissions.
121     // Otherwise, if the system server's binder thread pool is full, and all the threads are
122     // blocked on a thread that's waiting for us to complete, we deadlock. http://b/69389492
123     //
124     // From a security perspective, there is currently no difference, because:
125     // 1. The system server has the NETWORK_STACK permission, which grants access to all the
126     //    IPCs in this file.
127     // 2. AID_SYSTEM always has all permissions. See ActivityManager#checkComponentPermission.
128     if (uid == AID_SYSTEM) {
129         return android::binder::Status::ok();
130     }
131     // AID_NETWORK_STACK own MAINLINE_NETWORK_STACK permission, don't IPC to system server to check
132     // MAINLINE_NETWORK_STACK permission. Cross-process(netd, networkstack and system server)
133     // deadlock: http://b/149766727
134     if (uid == AID_NETWORK_STACK) {
135         for (const char* permission : permissions) {
136             if (std::strcmp(permission, PERM_MAINLINE_NETWORK_STACK) == 0) {
137                 return android::binder::Status::ok();
138             }
139         }
140     }
141 
142     for (const char* permission : permissions) {
143         if (checkPermission(android::String16(permission), pid, uid)) {
144             return android::binder::Status::ok();
145         }
146     }
147 
148     auto err = android::base::StringPrintf(
149             "UID %d / PID %d does not have any of the following permissions: %s", uid, pid,
150             android::base::Join(permissions, ',').c_str());
151     return android::binder::Status::fromExceptionCode(android::binder::Status::EX_SECURITY,
152                                                       err.c_str());
153 }
154 
statusFromErrcode(int ret)155 inline android::binder::Status statusFromErrcode(int ret) {
156     if (ret) {
157         return android::binder::Status::fromServiceSpecificError(-ret, strerror(-ret));
158     }
159     return android::binder::Status::ok();
160 }
161