blob: d0e14619dd51a5826ef0e406f5276d00df3f963c [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 Ramachandranf4f6c8d2014-06-23 09:54:06 -070020
21#define LOG_TAG "Netd"
22#include "log/log.h"
23#include "logwrap/logwrap.h"
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070024
Lorenzo Colittiba25df92014-06-18 00:22:17 +090025#include <arpa/inet.h>
Lorenzo Colitti4753afd2014-06-20 23:03:29 +090026#include <linux/fib_rules.h>
Paul Jensena561e122014-06-12 16:46:37 -040027#include <map>
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070028#include <net/if.h>
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070029
30namespace {
31
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070032// BEGIN CONSTANTS --------------------------------------------------------------------------------
33
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070034const uint32_t RULE_PRIORITY_PRIVILEGED_LEGACY = 11000;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070035const uint32_t RULE_PRIORITY_PER_NETWORK_EXPLICIT = 13000;
36const uint32_t RULE_PRIORITY_PER_NETWORK_INTERFACE = 14000;
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070037const uint32_t RULE_PRIORITY_LEGACY = 16000;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070038const uint32_t RULE_PRIORITY_PER_NETWORK_NORMAL = 17000;
39const uint32_t RULE_PRIORITY_DEFAULT_NETWORK = 19000;
40const uint32_t RULE_PRIORITY_MAIN = 20000;
Sreeram Ramachandran56afacf2014-05-28 15:07:00 -070041// TODO: Uncomment once we are sure everything works.
42#if 0
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -070043const uint32_t RULE_PRIORITY_UNREACHABLE = 21000;
Sreeram Ramachandran56afacf2014-05-28 15:07:00 -070044#endif
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -070045
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -070046// TODO: These should be turned into per-UID tables once the kernel supports UID-based routing.
47const int ROUTE_TABLE_PRIVILEGED_LEGACY = RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX - 901;
48const int ROUTE_TABLE_LEGACY = RouteController::ROUTE_TABLE_OFFSET_FROM_INDEX - 902;
49
Lorenzo Colitti59656512014-06-25 03:20:29 +090050// TODO: These values aren't defined by the Linux kernel, because our UID routing changes are not
51// upstream (yet?), so we can't just pick them up from kernel headers. When (if?) the changes make
52// it upstream, we'll remove this and rely on the kernel header values. For now, add a static assert
53// that will warn us if upstream has given these values some other meaning.
54const uint16_t FRA_UID_START = 18;
55const uint16_t FRA_UID_END = 19;
56static_assert(FRA_UID_START > FRA_MAX,
57 "Android-specific FRA_UID_{START,END} values also assigned in Linux uapi. "
58 "Check that these values match what the kernel does and then update this assertion.");
59
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -070060const uid_t INVALID_UID = static_cast<uid_t>(-1);
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 Ramachandranf4f6c8d2014-06-23 09:54:06 -0700143 ALOGE("bad netlink response message size (%d != %u)", 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 Ramachandranf4f6c8d2014-06-23 09:54:06 -0700184 ALOGE("interface name too long (%u > %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)) {
192 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 Ramachandranf4f6c8d2014-06-23 09:54:06 -0700257 ALOGE("impossible! address too long (%d vs %u)", 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 Ramachandranf4f6c8d2014-06-23 09:54:06 -0700307WARN_UNUSED_RESULT int modifyPerNetworkRules(unsigned netId, const char* interface,
308 Permission permission, bool add, bool modifyIptables) {
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700309 uint32_t table = getRouteTableForInterface(interface);
310 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700311 ALOGE("cannot find interface %s", interface);
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900312 return -ESRCH;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700313 }
314
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900315 uint16_t action = add ? RTM_NEWRULE : RTM_DELRULE;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700316
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700317 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700318 Fwmark mask;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700319
320 // A rule to route traffic based on a chosen outgoing interface.
321 //
322 // Supports apps that use SO_BINDTODEVICE or IP_PKTINFO options and the kernel that already
323 // knows the outgoing interface (typically for link-local communications).
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700324 fwmark.permission = permission;
325 mask.permission = permission;
326 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_INTERFACE, table, fwmark.intValue,
327 mask.intValue, interface, INVALID_UID, INVALID_UID)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900328 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700329 }
330
331 // A rule to route traffic based on the chosen network.
332 //
333 // This is for sockets that have not explicitly requested a particular network, but have been
334 // bound to one when they called connect(). This ensures that sockets connected on a particular
335 // network stay on that network even if the default network changes.
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700336 fwmark.netId = netId;
337 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700338 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_NORMAL, table, fwmark.intValue,
339 mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900340 return ret;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700341 }
342
343 // A rule to route traffic based on an explicitly chosen network.
344 //
345 // Supports apps that use the multinetwork APIs to restrict their traffic to a network.
346 //
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700347 // Even though we check permissions at the time we set a netId into the fwmark of a socket, we
348 // still need to check it again in the rules here, because a network's permissions may have been
349 // updated via modifyNetworkPermission().
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700350 fwmark.explicitlySelected = true;
351 mask.explicitlySelected = true;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700352 if (int ret = modifyIpRule(action, RULE_PRIORITY_PER_NETWORK_EXPLICIT, table, fwmark.intValue,
353 mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900354 return ret;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700355 }
356
357 // An iptables rule to mark incoming packets on a network with the netId of the network.
358 //
359 // This is so that the kernel can:
360 // + Use the right fwmark for (and thus correctly route) replies (e.g.: TCP RST, ICMP errors,
Sreeram Ramachandrana4811802014-04-10 12:10:24 -0700361 // ping replies).
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700362 // + Mark sockets that accept connections from this interface so that the connection stays on
363 // the same interface.
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700364 if (modifyIptables) {
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700365 char markString[UINT32_HEX_STRLEN];
366 snprintf(markString, sizeof(markString), "0x%x", netId);
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700367 if (execIptables(V4V6, "-t", "mangle", add ? "-A" : "-D", "INPUT", "-i", interface,
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900368 "-j", "MARK", "--set-mark", markString, NULL)) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700369 ALOGE("failed to change iptables rule that sets incoming packet mark");
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900370 return -EREMOTEIO;
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700371 }
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700372 }
373
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900374 return 0;
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700375}
376
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700377WARN_UNUSED_RESULT int modifyDefaultNetworkRules(const char* interface, Permission permission,
378 uint16_t action) {
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700379 uint32_t table = getRouteTableForInterface(interface);
380 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700381 ALOGE("cannot find interface %s", interface);
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900382 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700383 }
384
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700385 Fwmark fwmark;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700386 Fwmark mask;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700387
388 fwmark.netId = 0;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700389 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700390
391 fwmark.permission = permission;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700392 mask.permission = permission;
393
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900394 return modifyIpRule(action, RULE_PRIORITY_DEFAULT_NETWORK, table, fwmark.intValue,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700395 mask.intValue, NULL, INVALID_UID, INVALID_UID);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700396}
397
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700398// 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 +0900399// route, to the main table as well.
400// Returns 0 on success or negative errno on failure.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700401WARN_UNUSED_RESULT int modifyRoute(const char* interface, const char* destination,
402 const char* nexthop, uint16_t action,
403 RouteController::TableType tableType, uid_t /*uid*/) {
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700404 uint32_t table = 0;
405 switch (tableType) {
406 case RouteController::INTERFACE: {
407 table = getRouteTableForInterface(interface);
408 break;
409 }
410 case RouteController::LEGACY: {
411 // TODO: Use the UID to assign a unique table per UID instead of this fixed table.
412 table = ROUTE_TABLE_LEGACY;
413 break;
414 }
415 case RouteController::PRIVILEGED_LEGACY: {
416 // TODO: Use the UID to assign a unique table per UID instead of this fixed table.
417 table = ROUTE_TABLE_PRIVILEGED_LEGACY;
418 break;
419 }
420 }
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700421 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700422 ALOGE("cannot find table for interface %s and tableType %d", interface, tableType);
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900423 return -ESRCH;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700424 }
425
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900426 int ret = modifyIpRoute(action, table, interface, destination, nexthop);
Sreeram Ramachandran1077d292014-06-27 06:42:11 -0700427 // We allow apps to call requestRouteToHost() multiple times with the same route, so ignore
428 // EEXIST failures when adding routes to legacy tables.
429 if (ret != 0 && !(action == RTM_NEWROUTE && ret == -EEXIST &&
430 (tableType == RouteController::LEGACY ||
431 tableType == RouteController::PRIVILEGED_LEGACY))) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900432 return ret;
Sreeram Ramachandranc9213372014-04-16 12:32:18 -0700433 }
434
435 // 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 +0900436 // let the kernel find it when validating nexthops when global routes are added.
437 if (!nexthop) {
438 ret = modifyIpRoute(action, RT_TABLE_MAIN, interface, destination, NULL);
439 // A failure with action == ADD && errno == EEXIST means that the route already exists in
440 // the main table, perhaps because the kernel added it automatically as part of adding the
441 // IP address to the interface. Ignore this, but complain about everything else.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700442 if (ret && !(action == RTM_NEWROUTE && ret == -EEXIST)) {
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900443 return ret;
444 }
Sreeram Ramachandranc9213372014-04-16 12:32:18 -0700445 }
446
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900447 return 0;
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700448}
449
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700450// Returns 0 on success or negative errno on failure.
451WARN_UNUSED_RESULT int flushRoutes(const char* interface) {
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700452 uint32_t table = getRouteTableForInterface(interface);
453 if (!table) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700454 ALOGE("cannot find interface %s", interface);
455 return -ESRCH;
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700456 }
Paul Jensena561e122014-06-12 16:46:37 -0400457 interfaceToIndex.erase(interface);
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700458
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900459 char tableString[UINT32_STRLEN];
460 snprintf(tableString, sizeof(tableString), "%u", table);
461
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700462 for (size_t i = 0; i < ARRAY_SIZE(IP_VERSIONS); ++i) {
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900463 const char* argv[] = {
464 IP_PATH,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700465 IP_VERSIONS[i],
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900466 "route"
467 "flush",
468 "table",
469 tableString,
470 };
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700471 if (android_fork_execvp(ARRAY_SIZE(argv), const_cast<char**>(argv), NULL, false, false)) {
472 ALOGE("failed to flush routes");
473 return -EREMOTEIO;
Lorenzo Colitti357e5622014-06-17 16:14:17 +0900474 }
475 }
476
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700477 return 0;
Sreeram Ramachandran92b66c42014-04-15 14:28:55 -0700478}
479
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700480} // namespace
481
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700482int RouteController::Init() {
483 Fwmark fwmark;
484 Fwmark mask;
485
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700486 // Add a new rule to look up the 'main' table, with the same selectors as the "default network"
487 // rule, but with a lower priority. Since the default network rule points to a table with a
488 // default route, the rule we're adding will never be used for normal routing lookups. However,
489 // the kernel may fall-through to it to find directly-connected routes when it validates that a
490 // nexthop (in a route being added) is reachable.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700491 //
492 // TODO: This isn't true if the default network requires non-zero permissions. In that case, an
493 // app without those permissions may still be able to access directly-connected routes, since
494 // it won't match the default network rule. Fix this by only allowing the root UID (as a proxy
495 // for the kernel) to lookup this main table rule.
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700496 fwmark.netId = 0;
Sreeram Ramachandran122f5812014-05-11 20:29:49 -0700497 mask.netId = FWMARK_NET_ID_MASK;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700498 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_MAIN, RT_TABLE_MAIN, fwmark.intValue,
499 mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
500 return ret;
501 }
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700502
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700503 // Add rules to allow lookup of legacy routes.
504 //
505 // TODO: Remove these once the kernel supports UID-based routing. Instead, add them on demand
506 // when routes are added.
507 fwmark.netId = 0;
508 mask.netId = 0;
509
510 fwmark.explicitlySelected = false;
511 mask.explicitlySelected = true;
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700512 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_LEGACY, ROUTE_TABLE_LEGACY,
513 fwmark.intValue, mask.intValue, NULL, INVALID_UID, INVALID_UID)) {
514 return ret;
515 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700516
517 fwmark.permission = PERMISSION_CONNECTIVITY_INTERNAL;
518 mask.permission = PERMISSION_CONNECTIVITY_INTERNAL;
519
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700520 if (int ret = modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_PRIVILEGED_LEGACY,
521 ROUTE_TABLE_PRIVILEGED_LEGACY, fwmark.intValue, mask.intValue, NULL,
522 INVALID_UID, INVALID_UID)) {
523 return ret;
524 }
Sreeram Ramachandran38b7af12014-05-22 14:21:49 -0700525
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700526// TODO: Uncomment once we are sure everything works.
527#if 0
528 // Add a rule to preempt the pre-defined "from all lookup main" rule. This ensures that packets
529 // that are already marked with a specific NetId don't fall-through to the main table.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700530 return modifyIpRule(RTM_NEWRULE, RULE_PRIORITY_UNREACHABLE, 0, 0, 0, NULL, INVALID_UID,
531 INVALID_UID);
532#else
533 return 0;
Sreeram Ramachandran8fe9c8e2014-04-16 12:08:05 -0700534#endif
535}
536
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900537int RouteController::addInterfaceToNetwork(unsigned netId, const char* interface,
538 Permission permission) {
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700539 return modifyPerNetworkRules(netId, interface, permission, true, true);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700540}
541
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900542int RouteController::removeInterfaceFromNetwork(unsigned netId, const char* interface,
543 Permission permission) {
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700544 if (int ret = modifyPerNetworkRules(netId, interface, permission, false, true)) {
545 return ret;
546 }
547 return flushRoutes(interface);
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700548}
549
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900550int RouteController::modifyNetworkPermission(unsigned netId, const char* interface,
551 Permission oldPermission, Permission newPermission) {
Sreeram Ramachandran379bd332014-04-10 19:58:06 -0700552 // Add the new rules before deleting the old ones, to avoid race conditions.
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700553 if (int ret = modifyPerNetworkRules(netId, interface, newPermission, true, false)) {
554 return ret;
555 }
556 return modifyPerNetworkRules(netId, interface, oldPermission, false, false);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700557}
558
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900559int RouteController::addToDefaultNetwork(const char* interface, Permission permission) {
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900560 return modifyDefaultNetworkRules(interface, permission, RTM_NEWRULE);
Sreeram Ramachandran9c0d3132014-04-10 20:35:04 -0700561}
562
Lorenzo Colitti96f261e2014-06-23 15:09:54 +0900563int RouteController::removeFromDefaultNetwork(const char* interface, Permission permission) {
Lorenzo Colitti4753afd2014-06-20 23:03:29 +0900564 return modifyDefaultNetworkRules(interface, permission, RTM_DELRULE);
Sreeram Ramachandran5c181bf2014-04-07 14:10:04 -0700565}
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700566
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700567int RouteController::addRoute(const char* interface, const char* destination, const char* nexthop,
568 TableType tableType, uid_t uid) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900569 return modifyRoute(interface, destination, nexthop, RTM_NEWROUTE, tableType, uid);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700570}
571
Lorenzo Colittif7fc8ec2014-06-18 00:41:58 +0900572int RouteController::removeRoute(const char* interface, const char* destination,
Sreeram Ramachandranf4f6c8d2014-06-23 09:54:06 -0700573 const char* nexthop, TableType tableType, uid_t uid) {
Lorenzo Colittiba25df92014-06-18 00:22:17 +0900574 return modifyRoute(interface, destination, nexthop, RTM_DELROUTE, tableType, uid);
Sreeram Ramachandran7619e1b2014-04-15 14:23:08 -0700575}