DnsResolverService.cpp 11 KB

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