• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2022, 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 "BpfHandler"
18 
19 #include "BpfHandler.h"
20 
21 #include <linux/bpf.h>
22 
23 #include <android-base/unique_fd.h>
24 #include <android-modules-utils/sdk_level.h>
25 #include <bpf/WaitForProgsLoaded.h>
26 #include <log/log.h>
27 #include <netdutils/UidConstants.h>
28 #include <private/android_filesystem_config.h>
29 
30 #include "BpfSyscallWrappers.h"
31 
32 namespace android {
33 namespace net {
34 
35 using base::unique_fd;
36 using bpf::getSocketCookie;
37 using bpf::retrieveProgram;
38 using netdutils::Status;
39 using netdutils::statusFromErrno;
40 
41 constexpr int PER_UID_STATS_ENTRIES_LIMIT = 500;
42 // At most 90% of the stats map may be used by tagged traffic entries. This ensures
43 // that 10% of the map is always available to count untagged traffic, one entry per UID.
44 // Otherwise, apps would be able to avoid data usage accounting entirely by filling up the
45 // map with tagged traffic entries.
46 constexpr int TOTAL_UID_STATS_ENTRIES_LIMIT = STATS_MAP_SIZE * 0.9;
47 
48 static_assert(STATS_MAP_SIZE - TOTAL_UID_STATS_ENTRIES_LIMIT > 100,
49               "The limit for stats map is to high, stats data may be lost due to overflow");
50 
attachProgramToCgroup(const char * programPath,const unique_fd & cgroupFd,bpf_attach_type type)51 static Status attachProgramToCgroup(const char* programPath, const unique_fd& cgroupFd,
52                                     bpf_attach_type type) {
53     unique_fd cgroupProg(retrieveProgram(programPath));
54     if (cgroupProg == -1) {
55         int ret = errno;
56         ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
57         return statusFromErrno(ret, "cgroup program get failed");
58     }
59     if (android::bpf::attachProgram(type, cgroupProg, cgroupFd)) {
60         int ret = errno;
61         ALOGE("Program from %s attach failed: %s", programPath, strerror(ret));
62         return statusFromErrno(ret, "program attach failed");
63     }
64     return netdutils::status::ok;
65 }
66 
checkProgramAccessible(const char * programPath)67 static Status checkProgramAccessible(const char* programPath) {
68     unique_fd prog(retrieveProgram(programPath));
69     if (prog == -1) {
70         int ret = errno;
71         ALOGE("Failed to get program from %s: %s", programPath, strerror(ret));
72         return statusFromErrno(ret, "program retrieve failed");
73     }
74     return netdutils::status::ok;
75 }
76 
initPrograms(const char * cg2_path)77 static Status initPrograms(const char* cg2_path) {
78     if (modules::sdklevel::IsAtLeastU() && !!strcmp(cg2_path, "/sys/fs/cgroup")) abort();
79 
80     unique_fd cg_fd(open(cg2_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
81     if (cg_fd == -1) {
82         const int ret = errno;
83         ALOGE("Failed to open the cgroup directory: %s", strerror(ret));
84         return statusFromErrno(ret, "Open the cgroup directory failed");
85     }
86     RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_ALLOWLIST_PROG_PATH));
87     RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_DENYLIST_PROG_PATH));
88     RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_EGRESS_PROG_PATH));
89     RETURN_IF_NOT_OK(checkProgramAccessible(XT_BPF_INGRESS_PROG_PATH));
90     RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_EGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_EGRESS));
91     RETURN_IF_NOT_OK(attachProgramToCgroup(BPF_INGRESS_PROG_PATH, cg_fd, BPF_CGROUP_INET_INGRESS));
92 
93     // For the devices that support cgroup socket filter, the socket filter
94     // should be loaded successfully by bpfloader. So we attach the filter to
95     // cgroup if the program is pinned properly.
96     // TODO: delete the if statement once all devices should support cgroup
97     // socket filter (ie. the minimum kernel version required is 4.14).
98     if (bpf::isAtLeastKernelVersion(4, 14, 0)) {
99         RETURN_IF_NOT_OK(
100                 attachProgramToCgroup(CGROUP_SOCKET_PROG_PATH, cg_fd, BPF_CGROUP_INET_SOCK_CREATE));
101     }
102     return netdutils::status::ok;
103 }
104 
BpfHandler()105 BpfHandler::BpfHandler()
106     : mPerUidStatsEntriesLimit(PER_UID_STATS_ENTRIES_LIMIT),
107       mTotalUidStatsEntriesLimit(TOTAL_UID_STATS_ENTRIES_LIMIT) {}
108 
BpfHandler(uint32_t perUidLimit,uint32_t totalLimit)109 BpfHandler::BpfHandler(uint32_t perUidLimit, uint32_t totalLimit)
110     : mPerUidStatsEntriesLimit(perUidLimit), mTotalUidStatsEntriesLimit(totalLimit) {}
111 
init(const char * cg2_path)112 Status BpfHandler::init(const char* cg2_path) {
113     // Make sure BPF programs are loaded before doing anything
114     android::bpf::waitForProgsLoaded();
115     ALOGI("BPF programs are loaded");
116 
117     RETURN_IF_NOT_OK(initPrograms(cg2_path));
118     RETURN_IF_NOT_OK(initMaps());
119 
120     return netdutils::status::ok;
121 }
122 
initMaps()123 Status BpfHandler::initMaps() {
124     RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
125     RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
126     RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
127     RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
128     // initialized last so mCookieTagMap.isValid() implies everything else is valid too
129     RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
130     ALOGI("%s successfully", __func__);
131 
132     return netdutils::status::ok;
133 }
134 
hasUpdateDeviceStatsPermission(uid_t uid)135 bool BpfHandler::hasUpdateDeviceStatsPermission(uid_t uid) {
136     // This implementation is the same logic as method ActivityManager#checkComponentPermission.
137     // It implies that the real uid can never be the same as PER_USER_RANGE.
138     uint32_t appId = uid % PER_USER_RANGE;
139     auto permission = mUidPermissionMap.readValue(appId);
140     if (permission.ok() && (permission.value() & BPF_PERMISSION_UPDATE_DEVICE_STATS)) {
141         return true;
142     }
143     return ((appId == AID_ROOT) || (appId == AID_SYSTEM) || (appId == AID_DNS));
144 }
145 
tagSocket(int sockFd,uint32_t tag,uid_t chargeUid,uid_t realUid)146 int BpfHandler::tagSocket(int sockFd, uint32_t tag, uid_t chargeUid, uid_t realUid) {
147     if (!mCookieTagMap.isValid()) return -EPERM;
148 
149     if (chargeUid != realUid && !hasUpdateDeviceStatsPermission(realUid)) return -EPERM;
150 
151     // Note that tagging the socket to AID_CLAT is only implemented in JNI ClatCoordinator.
152     // The process is not allowed to tag socket to AID_CLAT via tagSocket() which would cause
153     // process data usage accounting to be bypassed. Tagging AID_CLAT is used for avoiding counting
154     // CLAT traffic data usage twice. See packages/modules/Connectivity/service/jni/
155     // com_android_server_connectivity_ClatCoordinator.cpp
156     if (chargeUid == AID_CLAT) return -EPERM;
157 
158     // The socket destroy listener only monitors on the group {INET_TCP, INET_UDP, INET6_TCP,
159     // INET6_UDP}. Tagging listener unsupported socket causes that the tag can't be removed from
160     // tag map automatically. Eventually, the tag map may run out of space because of dead tag
161     // entries. Note that although tagSocket() of net client has already denied the family which
162     // is neither AF_INET nor AF_INET6, the family validation is still added here just in case.
163     // See tagSocket in system/netd/client/NetdClient.cpp and
164     // TrafficController::makeSkDestroyListener in
165     // packages/modules/Connectivity/service/native/TrafficController.cpp
166     // TODO: remove this once the socket destroy listener can detect more types of socket destroy.
167     int socketFamily;
168     socklen_t familyLen = sizeof(socketFamily);
169     if (getsockopt(sockFd, SOL_SOCKET, SO_DOMAIN, &socketFamily, &familyLen)) {
170         ALOGE("Failed to getsockopt SO_DOMAIN: %s, fd: %d", strerror(errno), sockFd);
171         return -errno;
172     }
173     if (socketFamily != AF_INET && socketFamily != AF_INET6) {
174         ALOGE("Unsupported family: %d", socketFamily);
175         return -EAFNOSUPPORT;
176     }
177 
178     int socketProto;
179     socklen_t protoLen = sizeof(socketProto);
180     if (getsockopt(sockFd, SOL_SOCKET, SO_PROTOCOL, &socketProto, &protoLen)) {
181         ALOGE("Failed to getsockopt SO_PROTOCOL: %s, fd: %d", strerror(errno), sockFd);
182         return -errno;
183     }
184     if (socketProto != IPPROTO_UDP && socketProto != IPPROTO_TCP) {
185         ALOGE("Unsupported protocol: %d", socketProto);
186         return -EPROTONOSUPPORT;
187     }
188 
189     uint64_t sock_cookie = getSocketCookie(sockFd);
190     if (!sock_cookie) return -errno;
191 
192     UidTagValue newKey = {.uid = (uint32_t)chargeUid, .tag = tag};
193 
194     uint32_t totalEntryCount = 0;
195     uint32_t perUidEntryCount = 0;
196     // Now we go through the stats map and count how many entries are associated
197     // with chargeUid. If the uid entry hit the limit for each chargeUid, we block
198     // the request to prevent the map from overflow. Note though that it isn't really
199     // safe here to iterate over the map since it might be modified by the system server,
200     // which might toggle the live stats map and clean it.
201     const auto countUidStatsEntries = [chargeUid, &totalEntryCount, &perUidEntryCount](
202                                               const StatsKey& key,
203                                               const BpfMap<StatsKey, StatsValue>&) {
204         if (key.uid == chargeUid) {
205             perUidEntryCount++;
206         }
207         totalEntryCount++;
208         return base::Result<void>();
209     };
210     auto configuration = mConfigurationMap.readValue(CURRENT_STATS_MAP_CONFIGURATION_KEY);
211     if (!configuration.ok()) {
212         ALOGE("Failed to get current configuration: %s, fd: %d",
213               strerror(configuration.error().code()), mConfigurationMap.getMap().get());
214         return -configuration.error().code();
215     }
216     if (configuration.value() != SELECT_MAP_A && configuration.value() != SELECT_MAP_B) {
217         ALOGE("unknown configuration value: %d", configuration.value());
218         return -EINVAL;
219     }
220 
221     BpfMap<StatsKey, StatsValue>& currentMap =
222             (configuration.value() == SELECT_MAP_A) ? mStatsMapA : mStatsMapB;
223     // HACK: mStatsMapB becomes RW BpfMap here, but countUidStatsEntries doesn't modify so it works
224     base::Result<void> res = currentMap.iterate(countUidStatsEntries);
225     if (!res.ok()) {
226         ALOGE("Failed to count the stats entry in map %d: %s", currentMap.getMap().get(),
227               strerror(res.error().code()));
228         return -res.error().code();
229     }
230 
231     if (totalEntryCount > mTotalUidStatsEntriesLimit ||
232         perUidEntryCount > mPerUidStatsEntriesLimit) {
233         ALOGE("Too many stats entries in the map, total count: %u, chargeUid(%u) count: %u,"
234               " blocking tag request to prevent map overflow",
235               totalEntryCount, chargeUid, perUidEntryCount);
236         return -EMFILE;
237     }
238     // Update the tag information of a socket to the cookieUidMap. Use BPF_ANY
239     // flag so it will insert a new entry to the map if that value doesn't exist
240     // yet and update the tag if there is already a tag stored. Since the eBPF
241     // program in kernel only read this map, and is protected by rcu read lock. It
242     // should be fine to concurrently update the map while eBPF program is running.
243     res = mCookieTagMap.writeValue(sock_cookie, newKey, BPF_ANY);
244     if (!res.ok()) {
245         ALOGE("Failed to tag the socket: %s, fd: %d", strerror(res.error().code()),
246               mCookieTagMap.getMap().get());
247         return -res.error().code();
248     }
249     return 0;
250 }
251 
untagSocket(int sockFd)252 int BpfHandler::untagSocket(int sockFd) {
253     uint64_t sock_cookie = getSocketCookie(sockFd);
254     if (!sock_cookie) return -errno;
255 
256     if (!mCookieTagMap.isValid()) return -EPERM;
257     base::Result<void> res = mCookieTagMap.deleteValue(sock_cookie);
258     if (!res.ok()) {
259         ALOGE("Failed to untag socket: %s", strerror(res.error().code()));
260         return -res.error().code();
261     }
262     return 0;
263 }
264 
265 }  // namespace net
266 }  // namespace android
267