• 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 #define LOG_TAG "DnsResolverService"
18 
19 #include "DnsResolverService.h"
20 
21 #include <set>
22 #include <vector>
23 
24 #include <android-base/stringprintf.h>
25 #include <android-base/strings.h>
26 #include <android/binder_manager.h>
27 #include <android/binder_process.h>
28 #include <json/value.h>
29 #include <json/writer.h>
30 #include <log/log.h>
31 #include <netdutils/DumpWriter.h>
32 #include <openssl/base64.h>
33 #include <private/android_filesystem_config.h>  // AID_SYSTEM
34 
35 #include "BinderUtil.h"
36 #include "DnsResolver.h"
37 #include "NetdConstants.h"    // SHA256_SIZE
38 #include "NetdPermissions.h"  // PERM_*
39 #include "ResolverEventReporter.h"
40 #include "resolv_cache.h"
41 
42 using aidl::android::net::ResolverParamsParcel;
43 using android::base::Join;
44 using android::base::StringPrintf;
45 using android::netdutils::DumpWriter;
46 
47 namespace android {
48 namespace net {
49 
50 namespace {
51 
52 #define ENFORCE_ANY_PERMISSION(...)                                      \
53     do {                                                                 \
54         ::ndk::ScopedAStatus status = checkAnyPermission({__VA_ARGS__}); \
55         if (!status.isOk()) {                                            \
56             return status;                                               \
57         }                                                                \
58     } while (0)
59 
60 #define ENFORCE_INTERNAL_PERMISSIONS() \
61     ENFORCE_ANY_PERMISSION(PERM_CONNECTIVITY_INTERNAL, PERM_MAINLINE_NETWORK_STACK)
62 
63 #define ENFORCE_NETWORK_STACK_PERMISSIONS() \
64     ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK)
65 
statusFromErrcode(int ret)66 inline ::ndk::ScopedAStatus statusFromErrcode(int ret) {
67     if (ret) {
68         return ::ndk::ScopedAStatus(
69                 AStatus_fromServiceSpecificErrorWithMessage(-ret, strerror(-ret)));
70     }
71     return ::ndk::ScopedAStatus(AStatus_newOk());
72 }
73 
74 }  // namespace
75 
DnsResolverService()76 DnsResolverService::DnsResolverService() {
77     // register log callback to BnDnsResolver::logFunc
78     BnDnsResolver::logFunc =
79             std::bind(binderCallLogFn, std::placeholders::_1,
80                       [](const std::string& msg) { gResNetdCallbacks.log(msg.c_str()); });
81 }
82 
start()83 binder_status_t DnsResolverService::start() {
84     // TODO: Add disableBackgroundScheduling(true) after libbinder_ndk support it. b/126506010
85     // NetdNativeService does call disableBackgroundScheduling currently, so it is fine now.
86     DnsResolverService* resolverService = new DnsResolverService();
87     binder_status_t status =
88             AServiceManager_addService(resolverService->asBinder().get(), getServiceName());
89     if (status != STATUS_OK) {
90         return status;
91     }
92 
93     ABinderProcess_startThreadPool();
94 
95     // TODO: register log callback if binder NDK backend support it. b/126501406
96 
97     return STATUS_OK;
98 }
99 
dump(int fd,const char **,uint32_t)100 binder_status_t DnsResolverService::dump(int fd, const char**, uint32_t) {
101     auto dump_permission = checkAnyPermission({PERM_DUMP});
102     if (!dump_permission.isOk()) {
103         return STATUS_PERMISSION_DENIED;
104     }
105 
106     // This method does not grab any locks. If individual classes need locking
107     // their dump() methods MUST handle locking appropriately.
108     DumpWriter dw(fd);
109     for (auto netId : resolv_list_caches()) {
110         dw.println("NetId: %u", netId);
111         gDnsResolv->resolverCtrl.dump(dw, netId);
112         dw.blankline();
113     }
114 
115     return STATUS_OK;
116 }
117 
isAlive(bool * alive)118 ::ndk::ScopedAStatus DnsResolverService::isAlive(bool* alive) {
119     ENFORCE_INTERNAL_PERMISSIONS();
120 
121     *alive = true;
122 
123     return ::ndk::ScopedAStatus(AStatus_newOk());
124 }
125 
registerEventListener(const std::shared_ptr<aidl::android::net::metrics::INetdEventListener> & listener)126 ::ndk::ScopedAStatus DnsResolverService::registerEventListener(
127         const std::shared_ptr<aidl::android::net::metrics::INetdEventListener>& listener) {
128     ENFORCE_NETWORK_STACK_PERMISSIONS();
129 
130     int res = ResolverEventReporter::getInstance().addListener(listener);
131 
132     return statusFromErrcode(res);
133 }
134 
checkAnyPermission(const std::vector<const char * > & permissions)135 ::ndk::ScopedAStatus DnsResolverService::checkAnyPermission(
136         const std::vector<const char*>& permissions) {
137     // TODO: Remove callback and move this to unnamed namespace after libbiner_ndk supports
138     // check_permission.
139     if (!gResNetdCallbacks.check_calling_permission) {
140         return ::ndk::ScopedAStatus(AStatus_fromExceptionCodeWithMessage(
141                 EX_NULL_POINTER, "check_calling_permission is null"));
142     }
143     pid_t pid = AIBinder_getCallingPid();
144     uid_t uid = AIBinder_getCallingUid();
145 
146     // If the caller is the system UID, don't check permissions.
147     // Otherwise, if the system server's binder thread pool is full, and all the threads are
148     // blocked on a thread that's waiting for us to complete, we deadlock. http://b/69389492
149     //
150     // From a security perspective, there is currently no difference, because:
151     // 1. The only permissions we check in netd's binder interface are CONNECTIVITY_INTERNAL
152     //    and NETWORK_STACK, which the system server always has (or MAINLINE_NETWORK_STACK, which
153     //    is equivalent to having both CONNECTIVITY_INTERNAL and NETWORK_STACK).
154     // 2. AID_SYSTEM always has all permissions. See ActivityManager#checkComponentPermission.
155     if (uid == AID_SYSTEM) {
156         return ::ndk::ScopedAStatus(AStatus_newOk());
157     }
158 
159     for (const char* permission : permissions) {
160         if (gResNetdCallbacks.check_calling_permission(permission)) {
161             return ::ndk::ScopedAStatus(AStatus_newOk());
162         }
163     }
164 
165     auto err = StringPrintf("UID %d / PID %d does not have any of the following permissions: %s",
166                             uid, pid, Join(permissions, ',').c_str());
167     return ::ndk::ScopedAStatus(AStatus_fromExceptionCodeWithMessage(EX_SECURITY, err.c_str()));
168 }
169 
170 namespace {
171 
172 // Parse a base64 encoded string into a vector of bytes.
173 // On failure, return an empty vector.
parseBase64(const std::string & input)174 static std::vector<uint8_t> parseBase64(const std::string& input) {
175     std::vector<uint8_t> decoded;
176     size_t out_len;
177     if (EVP_DecodedLength(&out_len, input.size()) != 1) {
178         return decoded;
179     }
180     // out_len is now an upper bound on the output length.
181     decoded.resize(out_len);
182     if (EVP_DecodeBase64(decoded.data(), &out_len, decoded.size(),
183                          reinterpret_cast<const uint8_t*>(input.data()), input.size()) == 1) {
184         // Possibly shrink the vector if the actual output was smaller than the bound.
185         decoded.resize(out_len);
186     } else {
187         decoded.clear();
188     }
189     if (out_len != SHA256_SIZE) {
190         decoded.clear();
191     }
192     return decoded;
193 }
194 
195 }  // namespace
196 
setResolverConfiguration(const ResolverParamsParcel & resolverParams)197 ::ndk::ScopedAStatus DnsResolverService::setResolverConfiguration(
198         const ResolverParamsParcel& resolverParams) {
199     // Locking happens in PrivateDnsConfiguration and res_* functions.
200     ENFORCE_INTERNAL_PERMISSIONS();
201     // TODO: Remove this log after AIDL gen_log supporting more types, b/129732660
202     auto entry =
203             gDnsResolverLog.newEntry()
204                     .prettyFunction(__PRETTY_FUNCTION__)
205                     .args(resolverParams.netId, resolverParams.servers, resolverParams.domains,
206                           resolverParams.sampleValiditySeconds, resolverParams.successThreshold,
207                           resolverParams.minSamples, resolverParams.maxSamples,
208                           resolverParams.baseTimeoutMsec, resolverParams.retryCount,
209                           resolverParams.tlsServers, resolverParams.tlsFingerprints);
210 
211     std::set<std::vector<uint8_t>> decoded_fingerprints;
212     for (const std::string& fingerprint : resolverParams.tlsFingerprints) {
213         std::vector<uint8_t> decoded = parseBase64(fingerprint);
214         if (decoded.empty()) {
215             return ::ndk::ScopedAStatus(AStatus_fromServiceSpecificErrorWithMessage(
216                     EINVAL, "ResolverController error: bad fingerprint"));
217         }
218         decoded_fingerprints.emplace(decoded);
219     }
220 
221     int res =
222             gDnsResolv->resolverCtrl.setResolverConfiguration(resolverParams, decoded_fingerprints);
223 
224     gResNetdCallbacks.log(entry.returns(res).withAutomaticDuration().toString().c_str());
225 
226     return statusFromErrcode(res);
227 }
228 
getResolverInfo(int32_t netId,std::vector<std::string> * servers,std::vector<std::string> * domains,std::vector<std::string> * tlsServers,std::vector<int32_t> * params,std::vector<int32_t> * stats,std::vector<int32_t> * wait_for_pending_req_timeout_count)229 ::ndk::ScopedAStatus DnsResolverService::getResolverInfo(
230         int32_t netId, std::vector<std::string>* servers, std::vector<std::string>* domains,
231         std::vector<std::string>* tlsServers, std::vector<int32_t>* params,
232         std::vector<int32_t>* stats, std::vector<int32_t>* wait_for_pending_req_timeout_count) {
233     // Locking happens in PrivateDnsConfiguration and res_* functions.
234     ENFORCE_NETWORK_STACK_PERMISSIONS();
235 
236     int res = gDnsResolv->resolverCtrl.getResolverInfo(netId, servers, domains, tlsServers, params,
237                                                        stats, wait_for_pending_req_timeout_count);
238 
239     return statusFromErrcode(res);
240 }
241 
startPrefix64Discovery(int32_t netId)242 ::ndk::ScopedAStatus DnsResolverService::startPrefix64Discovery(int32_t netId) {
243     // Locking happens in Dns64Configuration.
244     ENFORCE_NETWORK_STACK_PERMISSIONS();
245 
246     gDnsResolv->resolverCtrl.startPrefix64Discovery(netId);
247 
248     return ::ndk::ScopedAStatus(AStatus_newOk());
249 }
250 
stopPrefix64Discovery(int32_t netId)251 ::ndk::ScopedAStatus DnsResolverService::stopPrefix64Discovery(int32_t netId) {
252     // Locking happens in Dns64Configuration.
253     ENFORCE_NETWORK_STACK_PERMISSIONS();
254 
255     gDnsResolv->resolverCtrl.stopPrefix64Discovery(netId);
256 
257     return ::ndk::ScopedAStatus(AStatus_newOk());
258 }
259 
getPrefix64(int netId,std::string * stringPrefix)260 ::ndk::ScopedAStatus DnsResolverService::getPrefix64(int netId, std::string* stringPrefix) {
261     ENFORCE_NETWORK_STACK_PERMISSIONS();
262 
263     netdutils::IPPrefix prefix{};
264     int res = gDnsResolv->resolverCtrl.getPrefix64(netId, &prefix);
265     *stringPrefix = prefix.toString();
266 
267     return statusFromErrcode(res);
268 }
269 
setLogSeverity(int32_t logSeverity)270 ::ndk::ScopedAStatus DnsResolverService::setLogSeverity(int32_t logSeverity) {
271     ENFORCE_NETWORK_STACK_PERMISSIONS();
272 
273     int res = gDnsResolv->setLogSeverity(logSeverity);
274 
275     return statusFromErrcode(res);
276 }
277 
destroyNetworkCache(int netId)278 ::ndk::ScopedAStatus DnsResolverService::destroyNetworkCache(int netId) {
279     // Locking happens in res_cache.cpp functions.
280     ENFORCE_NETWORK_STACK_PERMISSIONS();
281 
282     gDnsResolv->resolverCtrl.destroyNetworkCache(netId);
283 
284     return ::ndk::ScopedAStatus(AStatus_newOk());
285 }
286 
createNetworkCache(int netId)287 ::ndk::ScopedAStatus DnsResolverService::createNetworkCache(int netId) {
288     // Locking happens in res_cache.cpp functions.
289     ENFORCE_NETWORK_STACK_PERMISSIONS();
290 
291     int res = gDnsResolv->resolverCtrl.createNetworkCache(netId);
292 
293     return statusFromErrcode(res);
294 }
295 
296 }  // namespace net
297 }  // namespace android
298