blob: 69d2ec0d70dd0cbd3de986bbe8f7f32122c92dfe [file] [log] [blame]
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -07001/*
2 * Copyright (C) 2014 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 "RouteController.h"
18
19#include "Fwmark.h"
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -070020#include "UidRanges.h"
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070021
22#define LOG_TAG "Netd"
23#include "log/log.h"
24#include "logwrap/logwrap.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070025
Lorenzo Colittiba25df92014-06-18 00:22:17 +090026#include <arpa/inet.h>
Lorenzo Colitti4753afd2014-06-20 23:03:29 +090027#include <linux/fib_rules.h>
Paul Jensena561e122014-06-12 16:46:37 -040028#include <map>
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070029#include <net/if.h>
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070030
31namespace {
32
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070033// BEGIN CONSTANTS --------------------------------------------------------------------------------
34
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070035const uint32_t RULE_PRIORITY_PRIVILEGED_LEGACY = 11000;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -070036const uint32_t RULE_PRIORITY_SECURE_VPN = 12000;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070037const uint32_t RULE_PRIORITY_PER_NETWORK_EXPLICIT = 13000;
38const uint32_t RULE_PRIORITY_PER_NETWORK_INTERFACE = 14000;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070039const uint32_t RULE_PRIORITY_LEGACY = 16000;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070040const uint32_t RULE_PRIORITY_PER_NETWORK_NORMAL = 17000;
41const uint32_t RULE_PRIORITY_DEFAULT_NETWORK = 19000;
42const uint32_t RULE_PRIORITY_MAIN = 20000;
Sreeram Ramachandran56afacf2014-05-28 15:07:00 -070043// TODO: Uncomment once we are sure everything works.
44#if 0
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070045const uint32_t RULE_PRIORITY_UNREACHABLE = 21000;
Sreeram Ramachandran56afacf2014-05-28 15:07:00 -070046#endif
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070047
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070048// TODO: These should be turned into per-UID tables once the kernel supports UID-based routing.
49const int ROUTE_TABLE_PRIVILEGED_LEGACY = RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX - 901;
50const int ROUTE_TABLE_LEGACY = RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX - 902;
51
Lorenzo Colitti59656512014-06-25 03:20:29 +090052// TODO: These values aren't defined by the Linux kernel, because our UID routing changes are not
53// upstream (yet?), so we can't just pick them up from kernel headers. When (if?) the changes make
54// it upstream, we'll remove this and rely on the kernel header values. For now, add a static assert
55// that will warn us if upstream has given these values some other meaning.
56const uint16_t FRA_UID_START = 18;
57const uint16_t FRA_UID_END = 19;
58static_assert(FRA_UID_START > FRA_MAX,
59 "Android-specific FRA_UID_{START,END} values also assigned in Linux uapi. "
60 "Check that these values match what the kernel does and then update this assertion.");
61
Lorenzo Colitti72723682014-06-26 13:51:10 +090062const uint16_t NETLINK_REQUEST_FLAGS = NLM_F_REQUEST | NLM_F_ACK;
63const uint16_t NETLINK_CREATE_REQUEST_FLAGS = NETLINK_REQUEST_FLAGS | NLM_F_CREATE | NLM_F_EXCL;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +090064
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070065const sockaddr_nl NETLINK_ADDRESS = {AF_NETLINK, 0, 0, 0};
66
67const uint8_t AF_FAMILIES[] = {AF_INET, AF_INET6};
68
69const char* const IP_VERSIONS[] = {"-4", "-6"};
70
71// Avoids "non-constant-expression cannot be narrowed from type 'unsigned int' to 'unsigned short'"
72// warnings when using RTA_LENGTH(x) inside static initializers (even when x is already uint16_t).
73constexpr uint16_t U16_RTA_LENGTH(uint16_t x) {
74 return RTA_LENGTH(x);
75}
76
77// These are practically const, but can't be declared so, because they are used to initialize
78// non-const pointers ("void* iov_base") in iovec arrays.
79rtattr FRATTR_PRIORITY = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_PRIORITY };
80rtattr FRATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_TABLE };
81rtattr FRATTR_FWMARK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMARK };
82rtattr FRATTR_FWMASK = { U16_RTA_LENGTH(sizeof(uint32_t)), FRA_FWMASK };
83rtattr FRATTR_UID_START = { U16_RTA_LENGTH(sizeof(uid_t)), FRA_UID_START };
84rtattr FRATTR_UID_END = { U16_RTA_LENGTH(sizeof(uid_t)), FRA_UID_END };
85
86rtattr RTATTR_TABLE = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_TABLE };
87rtattr RTATTR_OIF = { U16_RTA_LENGTH(sizeof(uint32_t)), RTA_OIF };
88
89uint8_t PADDING_BUFFER[RTA_ALIGNTO] = {0, 0, 0, 0};
90
91// END CONSTANTS ----------------------------------------------------------------------------------
92
Paul Jensena561e122014-06-12 16:46:37 -040093std::map<std::string, uint32_t> interfaceToIndex;
94
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070095uint32_t getRouteTableForInterface(const char* interface) {
Sreeram Ramachandrana4811802014-04-10 12:10:24 -070096 uint32_t index = if_nametoindex(interface);
Paul Jensena561e122014-06-12 16:46:37 -040097 if (index) {
98 interfaceToIndex[interface] = index;
99 } else {
100 // If the interface goes away if_nametoindex() will return 0 but we still need to know
101 // the index so we can remove the rules and routes.
102 std::map<std::string, uint32_t>::iterator it = interfaceToIndex.find(interface);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700103 if (it != interfaceToIndex.end()) {
Paul Jensena561e122014-06-12 16:46:37 -0400104 index = it->second;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700105 }
Paul Jensena561e122014-06-12 16:46:37 -0400106 }
Sreeram Ramachandrana4811802014-04-10 12:10:24 -0700107 return index ? index + RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX : 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700108}
109
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900110// Sends a netlink request and expects an ack.
111// |iov| is an array of struct iovec that contains the netlink message payload.
112// The netlink header is generated by this function based on |action| and |flags|.
113// Returns -errno if there was an error or if the kernel reported an error.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700114WARN_UNUSED_RESULT int sendNetlinkRequest(uint16_t action, uint16_t flags, iovec* iov, int iovlen) {
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900115 nlmsghdr nlmsg = {
116 .nlmsg_type = action,
117 .nlmsg_flags = flags,
118 };
119 iov[0].iov_base = &nlmsg;
120 iov[0].iov_len = sizeof(nlmsg);
121 for (int i = 0; i < iovlen; ++i) {
122 nlmsg.nlmsg_len += iov[i].iov_len;
123 }
124
125 int ret;
126 struct {
127 nlmsghdr msg;
128 nlmsgerr err;
129 } response;
130
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900131 int sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
132 if (sock != -1 &&
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700133 connect(sock, reinterpret_cast<const sockaddr*>(&NETLINK_ADDRESS),
134 sizeof(NETLINK_ADDRESS)) != -1 &&
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900135 writev(sock, iov, iovlen) != -1 &&
136 (ret = recv(sock, &response, sizeof(response), 0)) != -1) {
137 if (ret == sizeof(response)) {
138 ret = response.err.error; // Netlink errors are negative errno.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700139 if (ret) {
140 ALOGE("netlink response contains error (%s)", strerror(-ret));
141 }
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900142 } else {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700143 ALOGE("bad netlink response message size (%d != %zu)", ret, sizeof(response));
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900144 ret = -EBADMSG;
145 }
146 } else {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700147 ALOGE("netlink socket/connect/writev/recv failed (%s)", strerror(errno));
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900148 ret = -errno;
149 }
150
151 if (sock != -1) {
152 close(sock);
153 }
154
155 return ret;
156}
157
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700158// Adds or removes a routing rule for IPv4 and IPv6.
159//
160// + If |table| is non-zero, the rule points at the specified routing table. Otherwise, the rule
161// returns ENETUNREACH.
162// + If |mask| is non-zero, the rule matches the specified fwmark and mask. Otherwise, |fwmark| is
163// ignored.
164// + If |interface| is non-NULL, the rule matches the specified outgoing interface.
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900165//
166// Returns 0 on success or negative errno on failure.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700167WARN_UNUSED_RESULT int modifyIpRule(uint16_t action, uint32_t priority, uint32_t table,
168 uint32_t fwmark, uint32_t mask, const char* interface,
169 uid_t uidStart, uid_t uidEnd) {
170 // Ensure that if you set a bit in the fwmark, it's not being ignored by the mask.
171 if (fwmark & ~mask) {
172 ALOGE("mask 0x%x does not select all the bits set in fwmark 0x%x", mask, fwmark);
173 return -ERANGE;
174 }
175
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900176 // The interface name must include exactly one terminating NULL and be properly padded, or older
177 // kernels will refuse to delete rules.
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900178 uint16_t paddingLength = 0;
179 size_t interfaceLength = 0;
180 char oifname[IFNAMSIZ];
181 if (interface) {
182 interfaceLength = strlcpy(oifname, interface, IFNAMSIZ) + 1;
183 if (interfaceLength > IFNAMSIZ) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700184 ALOGE("interface name too long (%zu > %u)", interfaceLength, IFNAMSIZ);
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900185 return -ENAMETOOLONG;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700186 }
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900187 paddingLength = RTA_SPACE(interfaceLength) - RTA_LENGTH(interfaceLength);
188 }
189
Lorenzo Colitti59656512014-06-25 03:20:29 +0900190 // Either both start and end UID must be specified, or neither.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700191 if ((uidStart == INVALID_UID) != (uidEnd == INVALID_UID)) {
Sreeram Ramachandrancf891382014-07-01 15:49:20 -0700192 ALOGE("incompatible start and end UIDs (%u vs %u)", uidStart, uidEnd);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900193 return -EUSERS;
194 }
Lorenzo Colitti72723682014-06-26 13:51:10 +0900195 bool isUidRule = (uidStart != INVALID_UID);
Lorenzo Colitti59656512014-06-25 03:20:29 +0900196
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900197 // Assemble a rule request and put it in an array of iovec structures.
198 fib_rule_hdr rule = {
199 .action = static_cast<uint8_t>(table ? FR_ACT_TO_TBL : FR_ACT_UNREACHABLE),
200 };
201
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700202 rtattr fraOifname = { U16_RTA_LENGTH(interfaceLength), FRA_OIFNAME };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900203
204 iovec iov[] = {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700205 { NULL, 0 },
206 { &rule, sizeof(rule) },
207 { &FRATTR_PRIORITY, sizeof(FRATTR_PRIORITY) },
208 { &priority, sizeof(priority) },
209 { &FRATTR_TABLE, table ? sizeof(FRATTR_TABLE) : 0 },
210 { &table, table ? sizeof(table) : 0 },
211 { &FRATTR_FWMARK, mask ? sizeof(FRATTR_FWMARK) : 0 },
212 { &fwmark, mask ? sizeof(fwmark) : 0 },
213 { &FRATTR_FWMASK, mask ? sizeof(FRATTR_FWMASK) : 0 },
214 { &mask, mask ? sizeof(mask) : 0 },
215 { &FRATTR_UID_START, isUidRule ? sizeof(FRATTR_UID_START) : 0 },
216 { &uidStart, isUidRule ? sizeof(uidStart) : 0 },
217 { &FRATTR_UID_END, isUidRule ? sizeof(FRATTR_UID_END) : 0 },
218 { &uidEnd, isUidRule ? sizeof(uidEnd) : 0 },
219 { &fraOifname, interface ? sizeof(fraOifname) : 0 },
220 { oifname, interfaceLength },
221 { PADDING_BUFFER, paddingLength },
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900222 };
223
Lorenzo Colitti72723682014-06-26 13:51:10 +0900224 uint16_t flags = (action == RTM_NEWRULE) ? NETLINK_CREATE_REQUEST_FLAGS : NETLINK_REQUEST_FLAGS;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700225 for (size_t i = 0; i < ARRAY_SIZE(AF_FAMILIES); ++i) {
226 rule.family = AF_FAMILIES[i];
227 if (int ret = sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov))) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900228 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700229 }
230 }
231
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900232 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700233}
234
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900235// Adds or deletes an IPv4 or IPv6 route.
236// Returns 0 on success or negative errno on failure.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700237WARN_UNUSED_RESULT int modifyIpRoute(uint16_t action, uint32_t table, const char* interface,
238 const char* destination, const char* nexthop) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900239 // At least the destination must be non-null.
240 if (!destination) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700241 ALOGE("null destination");
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900242 return -EFAULT;
243 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700244
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900245 // Parse the prefix.
246 uint8_t rawAddress[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700247 uint8_t family;
248 uint8_t prefixLength;
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900249 int rawLength = parsePrefix(destination, &family, rawAddress, sizeof(rawAddress),
250 &prefixLength);
251 if (rawLength < 0) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700252 ALOGE("parsePrefix failed for destination %s (%s)", destination, strerror(-rawLength));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900253 return rawLength;
254 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700255
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900256 if (static_cast<size_t>(rawLength) > sizeof(rawAddress)) {
Sreeram Ramachandran1201e842014-07-01 15:06:05 -0700257 ALOGE("impossible! address too long (%d vs %zu)", rawLength, sizeof(rawAddress));
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900258 return -ENOBUFS; // Cannot happen; parsePrefix only supports IPv4 and IPv6.
259 }
260
261 // If an interface was specified, find the ifindex.
262 uint32_t ifindex;
263 if (interface) {
264 ifindex = if_nametoindex(interface);
265 if (!ifindex) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700266 ALOGE("cannot find interface %s", interface);
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900267 return -ENODEV;
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700268 }
269 }
270
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900271 // If a nexthop was specified, parse it as the same family as the prefix.
272 uint8_t rawNexthop[sizeof(in6_addr)];
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700273 if (nexthop && inet_pton(family, nexthop, rawNexthop) <= 0) {
274 ALOGE("inet_pton failed for nexthop %s", nexthop);
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900275 return -EINVAL;
276 }
277
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900278 // Assemble a rtmsg and put it in an array of iovec structures.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700279 rtmsg route = {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900280 .rtm_protocol = RTPROT_STATIC,
281 .rtm_type = RTN_UNICAST,
282 .rtm_family = family,
283 .rtm_dst_len = prefixLength,
284 };
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900285
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700286 rtattr rtaDst = { U16_RTA_LENGTH(rawLength), RTA_DST };
287 rtattr rtaGateway = { U16_RTA_LENGTH(rawLength), RTA_GATEWAY };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900288
289 iovec iov[] = {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700290 { NULL, 0 },
291 { &route, sizeof(route) },
292 { &RTATTR_TABLE, sizeof(RTATTR_TABLE) },
293 { &table, sizeof(table) },
294 { &rtaDst, sizeof(rtaDst) },
295 { rawAddress, static_cast<size_t>(rawLength) },
296 { &RTATTR_OIF, interface ? sizeof(RTATTR_OIF) : 0 },
297 { &ifindex, interface ? sizeof(ifindex) : 0 },
298 { &rtaGateway, nexthop ? sizeof(rtaGateway) : 0 },
299 { rawNexthop, nexthop ? static_cast<size_t>(rawLength) : 0 },
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900300 };
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900301
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700302 uint16_t flags = (action == RTM_NEWROUTE) ? NETLINK_CREATE_REQUEST_FLAGS :
303 NETLINK_REQUEST_FLAGS;
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900304 return sendNetlinkRequest(action, flags, iov, ARRAY_SIZE(iov));
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700305}
306
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700307WARN_UNUSED_RESULT int modifyIncomingPacketMark(unsigned netId, const char* interface, bool add) {
308 // An iptables rule to mark incoming packets on a network with the netId of the network.
309 //
310 // This is so that the kernel can:
311 // + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors,
312 // ping replies).
313 // + Mark sockets that accept connections from this interface so that the connection stays on
314 // the same interface.
315 char markString[UINT32_HEX_STRLEN];
316 snprintf(markString, sizeof(markString), "0x%x", netId);
317 if (execIptables(V4V6, "-t", "mangle", add ? "-A" : "-D", "INPUT", "-i", interface, "-j",
318 "MARK", "--set-mark", markString, NULL)) {
319 ALOGE("failed to change iptables rule that sets incoming packet mark");
320 return -EREMOTEIO;
321 }
322 return 0;
323}
324
325WARN_UNUSED_RESULT int modifyPerNetworkRules(unsigned netId, const char* interface, uint32_t table,
326 Permission permission, uid_t uidStart, uid_t uidEnd,
327 bool add, bool modifyIptables) {
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700328 if (!table) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700329 table = getRouteTableForInterface(interface);
330 if (!table) {
331 ALOGE("cannot find interface %s", interface);
332 return -ESRCH;
333 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700334 }
335
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900336 uint16_t action = add ? RTM_NEWRULE : RTM_DELRULE;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700337
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700338 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700339 Fwmark mask;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700340
341 // A rule to route traffic based on a chosen outgoing interface.
342 //
343 // Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already
344 // knows the outgoing interface (typically for link-local communications).
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700345 fwmark.permission = permission;
346 mask.permission = permission;
347 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_INTERFACE, table, fwmark.intValue,
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700348 mask.intValue, interface, uidStart, uidEnd)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900349 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700350 }
351
352 // A rule to route traffic based on the chosen network.
353 //
354 // This is for sockets that have not explicitly requested a particular network, but have been
355 // bound to one when they called connect(). This ensures that sockets connected on a particular
356 // network stay on that network even if the default network changes.
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700357 fwmark.netId = netId;
358 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700359 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_NORMAL, table, fwmark.intValue,
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700360 mask.intValue, NULL, uidStart, uidEnd)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900361 return ret;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700362 }
363
364 // A rule to route traffic based on an explicitly chosen network.
365 //
366 // Supports apps that use the multinetwork APIs to restrict their traffic to a network.
367 //
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700368 // Even though we check permissions at the time we set a netId into the fwmark of a socket, we
369 // still need to check it again in the rules here, because a network's permissions may have been
370 // updated via modifyNetworkPermission().
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700371 fwmark.explicitlySelected = true;
372 mask.explicitlySelected = true;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700373 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_EXPLICIT, table, fwmark.intValue,
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700374 mask.intValue, NULL, uidStart, uidEnd)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900375 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700376 }
377
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700378 if (modifyIptables) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700379 if (int ret = modifyIncomingPacketMark(netId, interface, add)) {
380 return ret;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700381 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700382 }
383
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900384 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700385}
386
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700387// Adds or removes rules for VPNs that affect UIDs in |uidRanges|. If |modifyInterfaceBasedRules|
388// is true, also modifies the rules that are based only on the |interface| and not on |uidRanges|.
389// When adding or removing an interface to the VPN, set it to true. When adding or removing UIDs
390// without changing the VPN's interfaces, set it to false.
391WARN_UNUSED_RESULT int modifyVpnRules(unsigned netId, const char* interface,
392 const UidRanges& uidRanges, bool add,
393 bool modifyInterfaceBasedRules) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700394 uint32_t table = getRouteTableForInterface(interface);
395 if (!table) {
396 ALOGE("cannot find interface %s", interface);
397 return -ESRCH;
398 }
399
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700400 uint16_t action = add ? RTM_NEWRULE : RTM_DELRULE;
401
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700402 Fwmark fwmark;
403 Fwmark mask;
404
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700405 fwmark.protectedFromVpn = false;
406 mask.protectedFromVpn = true;
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700407
408 for (const std::pair<uid_t, uid_t>& range : uidRanges.getRanges()) {
409 if (int ret = modifyPerNetworkRules(netId, interface, table, PERMISSION_NONE, range.first,
410 range.second, add, false)) {
411 return ret;
412 }
413
414 // A rule to route all traffic from a given set of UIDs to go over the VPN.
415 //
416 // Notice that this rule doesn't use the netId. I.e., no matter what netId the user's socket
417 // may have, if they are subject to this VPN, their traffic has to go through it. Allows the
418 // traffic to bypass the VPN if the protectedFromVpn bit is set.
419 if (int ret = modifyIpRule(action, RULE_PRIORITY_SECURE_VPN, table, fwmark.intValue,
420 mask.intValue, NULL, range.first, range.second)) {
421 return ret;
422 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700423 }
424
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700425 if (modifyInterfaceBasedRules) {
426 if (int ret = modifyIncomingPacketMark(netId, interface, add)) {
427 return ret;
428 }
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700429
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700430 // A rule to allow privileged apps to send traffic over this VPN even if they are not part
431 // of the target set of UIDs.
432 //
433 // This is needed for DnsProxyListener to correctly resolve a request for a user who is in
434 // the target set, but where the DnsProxyListener itself is not.
435 fwmark.protectedFromVpn = false;
436 mask.protectedFromVpn = false;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700437
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700438 fwmark.netId = netId;
439 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700440
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700441 fwmark.permission = PERMISSION_CONNECTIVITY_INTERNAL;
442 mask.permission = PERMISSION_CONNECTIVITY_INTERNAL;
443
444 if (int ret = modifyIpRule(action, RULE_PRIORITY_SECURE_VPN, table, fwmark.intValue,
445 mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
446 return ret;
447 }
448 }
449
450 return 0;
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700451}
452
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700453WARN_UNUSED_RESULT int modifyDefaultNetworkRules(const char* interface, Permission permission,
454 uint16_t action) {
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700455 uint32_t table = getRouteTableForInterface(interface);
456 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700457 ALOGE("cannot find interface %s", interface);
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900458 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700459 }
460
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700461 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700462 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700463
464 fwmark.netId = 0;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700465 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700466
467 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700468 mask.permission = permission;
469
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900470 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700471 mask.intValue, NULL, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700472}
473
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700474// Adds or removes an IPv4 or IPv6 route to the specified table and, if it's a directly-connected
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900475// route, to the main table as well.
476// Returns 0 on success or negative errno on failure.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700477WARN_UNUSED_RESULT int modifyRoute(const char* interface, const char* destination,
478 const char* nexthop, uint16_t action,
479 RouteController::TableType tableType, uid_t /*uid*/) {
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700480 uint32_t table = 0;
481 switch (tableType) {
482 case RouteController::INTERFACE: {
483 table = getRouteTableForInterface(interface);
484 break;
485 }
486 case RouteController::LEGACY: {
487 // TODO: Use the UID to assign a unique table per UID instead of this fixed table.
488 table = ROUTE_TABLE_LEGACY;
489 break;
490 }
491 case RouteController::PRIVILEGED_LEGACY: {
492 // TODO: Use the UID to assign a unique table per UID instead of this fixed table.
493 table = ROUTE_TABLE_PRIVILEGED_LEGACY;
494 break;
495 }
496 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700497 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700498 ALOGE("cannot find table for interface %s and tableType %d", interface, tableType);
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900499 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700500 }
501
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900502 int ret = modifyIpRoute(action, table, interface, destination, nexthop);
Sreeram Ramachandran1077d292014-06-27 06:42:11 -0700503 // We allow apps to call requestRouteToHost() multiple times with the same route, so ignore
504 // EEXIST failures when adding routes to legacy tables.
505 if (ret != 0 && !(action == RTM_NEWROUTE && ret == -EEXIST &&
506 (tableType == RouteController::LEGACY ||
507 tableType == RouteController::PRIVILEGED_LEGACY))) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900508 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -0700509 }
510
511 // If there's no nexthop, this is a directly connected route. Add it to the main table also, to
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900512 // let the kernel find it when validating nexthops when global routes are added.
513 if (!nexthop) {
514 ret = modifyIpRoute(action, RT_TABLE_MAIN, interface, destination, NULL);
515 // A failure with action == ADD && errno == EEXIST means that the route already exists in
516 // the main table, perhaps because the kernel added it automatically as part of adding the
517 // IP address to the interface. Ignore this, but complain about everything else.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700518 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900519 return ret;
520 }
Sreeram Ramachandranc9213372014-04-16 12:32:18 -0700521 }
522
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900523 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700524}
525
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700526// Returns 0 on success or negative errno on failure.
527WARN_UNUSED_RESULT int flushRoutes(const char* interface) {
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700528 uint32_t table = getRouteTableForInterface(interface);
529 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700530 ALOGE("cannot find interface %s", interface);
531 return -ESRCH;
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700532 }
Paul Jensena561e122014-06-12 16:46:37 -0400533 interfaceToIndex.erase(interface);
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700534
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900535 char tableString[UINT32_STRLEN];
536 snprintf(tableString, sizeof(tableString), "%u", table);
537
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700538 for (size_t i = 0; i < ARRAY_SIZE(IP_VERSIONS); ++i) {
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900539 const char* argv[] = {
540 IP_PATH,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700541 IP_VERSIONS[i],
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900542 "route"
543 "flush",
544 "table",
545 tableString,
546 };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700547 if (android_fork_execvp(ARRAY_SIZE(argv), const_cast<char**>(argv), NULL, false, false)) {
548 ALOGE("failed to flush routes");
549 return -EREMOTEIO;
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900550 }
551 }
552
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700553 return 0;
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700554}
555
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700556} // namespace
557
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700558int RouteController::Init() {
559 Fwmark fwmark;
560 Fwmark mask;
561
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700562 // Add a new rule to look up the 'main' table, with the same selectors as the "default network"
563 // rule, but with a lower priority. Since the default network rule points to a table with a
564 // default route, the rule we're adding will never be used for normal routing lookups. However,
565 // the kernel may fall-through to it to find directly-connected routes when it validates that a
566 // nexthop (in a route being added) is reachable.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700567 //
568 // TODO: This isn't true if the default network requires non-zero permissions. In that case, an
569 // app without those permissions may still be able to access directly-connected routes, since
570 // it won't match the default network rule. Fix this by only allowing the root UID (as a proxy
571 // for the kernel) to lookup this main table rule.
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700572 fwmark.netId = 0;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700573 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700574 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_MAIN, RT_TABLE_MAIN, fwmark.intValue,
575 mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
576 return ret;
577 }
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700578
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700579 // Add rules to allow lookup of legacy routes.
580 //
581 // TODO: Remove these once the kernel supports UID-based routing. Instead, add them on demand
582 // when routes are added.
583 fwmark.netId = 0;
584 mask.netId = 0;
585
586 fwmark.explicitlySelected = false;
587 mask.explicitlySelected = true;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700588 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY, ROUTE_TABLE_LEGACY,
589 fwmark.intValue, mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
590 return ret;
591 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700592
593 fwmark.permission = PERMISSION_CONNECTIVITY_INTERNAL;
594 mask.permission = PERMISSION_CONNECTIVITY_INTERNAL;
595
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700596 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_PRIVILEGED_LEGACY,
597 ROUTE_TABLE_PRIVILEGED_LEGACY, fwmark.intValue, mask.intValue, NULL,
598 INVALID_UID, INVALID_UID)) {
599 return ret;
600 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700601
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700602// TODO: Uncomment once we are sure everything works.
603#if 0
604 // Add a rule to preempt the pre-defined "from all lookup main" rule. This ensures that packets
605 // that are already marked with a specific NetId don't fall-through to the main table.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700606 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, 0, 0, 0, NULL, INVALID_UID,
607 INVALID_UID);
608#else
609 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700610#endif
611}
612
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900613int RouteController::addInterfaceToNetwork(unsigned netId, const char* interface,
614 Permission permission) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700615 return modifyPerNetworkRules(netId, interface, 0, permission, INVALID_UID, INVALID_UID, true,
616 true);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700617}
618
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900619int RouteController::removeInterfaceFromNetwork(unsigned netId, const char* interface,
620 Permission permission) {
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700621 if (int ret = modifyPerNetworkRules(netId, interface, 0, permission, INVALID_UID, INVALID_UID,
622 false, true)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700623 return ret;
624 }
625 return flushRoutes(interface);
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700626}
627
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700628int RouteController::addInterfaceToVpn(unsigned netId, const char* interface,
629 const UidRanges& uidRanges) {
630 return modifyVpnRules(netId, interface, uidRanges, true, true);
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700631}
632
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700633int RouteController::removeInterfaceFromVpn(unsigned netId, const char* interface,
634 const UidRanges& uidRanges) {
635 if (int ret = modifyVpnRules(netId, interface, uidRanges, false, true)) {
Sreeram Ramachandran4043f012014-06-23 12:41:37 -0700636 return ret;
637 }
638 return flushRoutes(interface);
639}
640
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900641int RouteController::modifyNetworkPermission(unsigned netId, const char* interface,
642 Permission oldPermission, Permission newPermission) {
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700643 // Add the new rules before deleting the old ones, to avoid race conditions.
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700644 if (int ret = modifyPerNetworkRules(netId, interface, 0, newPermission, INVALID_UID,
645 INVALID_UID, true, false)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700646 return ret;
647 }
Sreeram Ramachandranb1425cc2014-06-23 18:54:27 -0700648 return modifyPerNetworkRules(netId, interface, 0, oldPermission, INVALID_UID, INVALID_UID,
649 false, false);
650}
651
652int RouteController::addUsersToVpn(unsigned netId, const char* interface,
653 const UidRanges& uidRanges) {
654 return modifyVpnRules(netId, interface, uidRanges, true, false);
655}
656
657int RouteController::removeUsersFromVpn(unsigned netId, const char* interface,
658 const UidRanges& uidRanges) {
659 return modifyVpnRules(netId, interface, uidRanges, false, false);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700660}
661
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900662int RouteController::addToDefaultNetwork(const char* interface, Permission permission) {
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900663 return modifyDefaultNetworkRules(interface, permission, RTM_NEWRULE);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700664}
665
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900666int RouteController::removeFromDefaultNetwork(const char* interface, Permission permission) {
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900667 return modifyDefaultNetworkRules(interface, permission, RTM_DELRULE);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700668}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700669
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700670int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
671 TableType tableType, uid_t uid) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900672 return modifyRoute(interface, destination, nexthop, RTM_NEWROUTE, tableType, uid);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700673}
674
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900675int RouteController::removeRoute(const char* interface, const char* destination,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700676 const char* nexthop, TableType tableType, uid_t uid) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900677 return modifyRoute(interface, destination, nexthop, RTM_DELROUTE, tableType, uid);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700678}