• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 <errno.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <netdb.h>
21 #include <spawn.h>
22 #include <string.h>
23 
24 #include <sys/socket.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 
32 #include <array>
33 #include <cstdlib>
34 #include <regex>
35 #include <string>
36 #include <vector>
37 
38 #define LOG_TAG "TetherController"
39 #include <android-base/stringprintf.h>
40 #include <android-base/strings.h>
41 #include <android-base/unique_fd.h>
42 #include <cutils/properties.h>
43 #include <log/log.h>
44 #include <netdutils/StatusOr.h>
45 
46 #include "Controllers.h"
47 #include "Fwmark.h"
48 #include "InterfaceController.h"
49 #include "NetdConstants.h"
50 #include "NetworkController.h"
51 #include "Permission.h"
52 #include "TetherController.h"
53 
54 namespace android {
55 namespace net {
56 
57 using android::base::Join;
58 using android::base::Pipe;
59 using android::base::StringPrintf;
60 using android::base::unique_fd;
61 using android::netdutils::statusFromErrno;
62 using android::netdutils::StatusOr;
63 
64 namespace {
65 
66 const char BP_TOOLS_MODE[] = "bp-tools";
67 const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
68 const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
69 const char SEPARATOR[] = "|";
70 constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
71 
72 // Chosen to match AID_DNS_TETHER, as made "friendly" by fs_config_generator.py.
73 constexpr const char kDnsmasqUsername[] = "dns_tether";
74 
writeToFile(const char * filename,const char * value)75 bool writeToFile(const char* filename, const char* value) {
76     int fd = open(filename, O_WRONLY | O_CLOEXEC);
77     if (fd < 0) {
78         ALOGE("Failed to open %s: %s", filename, strerror(errno));
79         return false;
80     }
81 
82     const ssize_t len = strlen(value);
83     if (write(fd, value, len) != len) {
84         ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
85         close(fd);
86         return false;
87     }
88     close(fd);
89     return true;
90 }
91 
92 // TODO: Consider altering TCP and UDP timeouts as well.
configureForTethering(bool enabled)93 void configureForTethering(bool enabled) {
94     writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
95 }
96 
configureForIPv6Router(const char * interface)97 bool configureForIPv6Router(const char *interface) {
98     return (InterfaceController::setEnableIPv6(interface, 0) == 0)
99             && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
100             && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
101             && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
102             && (InterfaceController::setEnableIPv6(interface, 1) == 0);
103 }
104 
configureForIPv6Client(const char * interface)105 void configureForIPv6Client(const char *interface) {
106     InterfaceController::setAcceptIPv6Ra(interface, 1);
107     InterfaceController::setAcceptIPv6Dad(interface, 1);
108     InterfaceController::setIPv6DadTransmits(interface, "1");
109     InterfaceController::setEnableIPv6(interface, 0);
110 }
111 
inBpToolsMode()112 bool inBpToolsMode() {
113     // In BP tools mode, do not disable IP forwarding
114     char bootmode[PROPERTY_VALUE_MAX] = {0};
115     property_get("ro.bootmode", bootmode, "unknown");
116     return !strcmp(BP_TOOLS_MODE, bootmode);
117 }
118 
setPosixSpawnFileActionsAddDup2(posix_spawn_file_actions_t * fa,int fd,int new_fd)119 int setPosixSpawnFileActionsAddDup2(posix_spawn_file_actions_t* fa, int fd, int new_fd) {
120     int res = posix_spawn_file_actions_init(fa);
121     if (res) {
122         return res;
123     }
124     return posix_spawn_file_actions_adddup2(fa, fd, new_fd);
125 }
126 
setPosixSpawnAttrFlags(posix_spawnattr_t * attr,short flags)127 int setPosixSpawnAttrFlags(posix_spawnattr_t* attr, short flags) {
128     int res = posix_spawnattr_init(attr);
129     if (res) {
130         return res;
131     }
132     return posix_spawnattr_setflags(attr, flags);
133 }
134 
135 }  // namespace
136 
137 auto TetherController::iptablesRestoreFunction = execIptablesRestoreWithOutput;
138 
139 const std::string GET_TETHER_STATS_COMMAND = StringPrintf(
140     "*filter\n"
141     "-nvx -L %s\n"
142     "COMMIT\n", android::net::TetherController::LOCAL_TETHER_COUNTERS_CHAIN);
143 
sendCmd(int daemonFd,const std::string & cmd)144 int TetherController::DnsmasqState::sendCmd(int daemonFd, const std::string& cmd) {
145     if (cmd.empty()) return 0;
146 
147     gLog.log("Sending update msg to dnsmasq [%s]", cmd.c_str());
148     // Send the trailing \0 as well.
149     if (write(daemonFd, cmd.c_str(), cmd.size() + 1) < 0) {
150         gLog.error("Failed to send update command to dnsmasq (%s)", strerror(errno));
151         errno = EREMOTEIO;
152         return -1;
153     }
154     return 0;
155 }
156 
clear()157 void TetherController::DnsmasqState::clear() {
158     update_ifaces_cmd.clear();
159     update_dns_cmd.clear();
160 }
161 
sendAllState(int daemonFd) const162 int TetherController::DnsmasqState::sendAllState(int daemonFd) const {
163     return sendCmd(daemonFd, update_ifaces_cmd) | sendCmd(daemonFd, update_dns_cmd);
164 }
165 
TetherController()166 TetherController::TetherController() {
167     if (inBpToolsMode()) {
168         enableForwarding(BP_TOOLS_MODE);
169     } else {
170         setIpFwdEnabled();
171     }
172 }
173 
setIpFwdEnabled()174 bool TetherController::setIpFwdEnabled() {
175     bool success = true;
176     bool disable = mForwardingRequests.empty();
177     const char* value = disable ? "0" : "1";
178     ALOGD("Setting IP forward enable = %s", value);
179     success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
180     success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
181     if (disable) {
182         // Turning off the forwarding sysconf in the kernel has the side effect
183         // of turning on ICMP redirect, which is a security hazard.
184         // Turn ICMP redirect back off immediately.
185         int rv = InterfaceController::disableIcmpRedirects();
186         success &= (rv == 0);
187     }
188     return success;
189 }
190 
enableForwarding(const char * requester)191 bool TetherController::enableForwarding(const char* requester) {
192     // Don't return an error if this requester already requested forwarding. Only return errors for
193     // things that the caller caller needs to care about, such as "couldn't write to the file to
194     // enable forwarding".
195     mForwardingRequests.insert(requester);
196     return setIpFwdEnabled();
197 }
198 
disableForwarding(const char * requester)199 bool TetherController::disableForwarding(const char* requester) {
200     mForwardingRequests.erase(requester);
201     return setIpFwdEnabled();
202 }
203 
getIpfwdRequesterList() const204 const std::set<std::string>& TetherController::getIpfwdRequesterList() const {
205     return mForwardingRequests;
206 }
207 
startTethering(int num_addrs,char ** dhcp_ranges)208 int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
209     if (mDaemonPid != 0) {
210         ALOGE("Tethering already started");
211         errno = EBUSY;
212         return -errno;
213     }
214 
215     ALOGD("Starting tethering services");
216 
217     unique_fd pipeRead, pipeWrite;
218     if (!Pipe(&pipeRead, &pipeWrite, O_CLOEXEC)) {
219         int res = errno;
220         ALOGE("pipe2() failed (%s)", strerror(errno));
221         return -res;
222     }
223 
224     // Set parameters
225     Fwmark fwmark;
226     fwmark.netId = NetworkController::LOCAL_NET_ID;
227     fwmark.explicitlySelected = true;
228     fwmark.protectedFromVpn = true;
229     fwmark.permission = PERMISSION_SYSTEM;
230     char markStr[UINT32_HEX_STRLEN];
231     snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
232 
233     std::vector<const std::string> argVector = {
234             "/system/bin/dnsmasq",
235             "--keep-in-foreground",
236             "--no-resolv",
237             "--no-poll",
238             "--dhcp-authoritative",
239             // TODO: pipe through metered status from ConnService
240             "--dhcp-option-force=43,ANDROID_METERED",
241             "--pid-file",
242             "--listen-mark",
243             markStr,
244             "--user",
245             kDnsmasqUsername,
246     };
247 
248     // DHCP server will be disabled if num_addrs == 0 and no --dhcp-range is
249     // passed.
250     for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
251         argVector.push_back(StringPrintf("--dhcp-range=%s,%s,1h", dhcp_ranges[addrIndex],
252                                          dhcp_ranges[addrIndex + 1]));
253     }
254 
255     std::vector<char*> args(argVector.size() + 1);
256     for (unsigned i = 0; i < argVector.size(); i++) {
257         args[i] = (char*)argVector[i].c_str();
258     }
259 
260     /*
261      * TODO: Create a monitoring thread to handle and restart
262      * the daemon if it exits prematurely
263      */
264 
265     // Note that don't modify any memory between vfork and execv.
266     // Changing state of file descriptors would be fine. See posix_spawn_file_actions_add*
267     // dup2 creates fd without CLOEXEC, dnsmasq will receive commands through the
268     // duplicated fd.
269     posix_spawn_file_actions_t fa;
270     int res = setPosixSpawnFileActionsAddDup2(&fa, pipeRead.get(), STDIN_FILENO);
271     if (res) {
272         ALOGE("posix_spawn set fa failed (%s)", strerror(res));
273         return -res;
274     }
275 
276     posix_spawnattr_t attr;
277     res = setPosixSpawnAttrFlags(&attr, POSIX_SPAWN_USEVFORK);
278     if (res) {
279         ALOGE("posix_spawn set attr flag failed (%s)", strerror(res));
280         return -res;
281     }
282 
283     pid_t pid;
284     res = posix_spawn(&pid, args[0], &fa, &attr, &args[0], nullptr);
285     posix_spawnattr_destroy(&attr);
286     posix_spawn_file_actions_destroy(&fa);
287     if (res) {
288         ALOGE("posix_spawn failed (%s)", strerror(res));
289         return -res;
290     }
291     mDaemonPid = pid;
292     mDaemonFd = pipeWrite.release();
293     configureForTethering(true);
294     applyDnsInterfaces();
295     ALOGD("Tethering services running");
296 
297     return 0;
298 }
299 
toCstrVec(const std::vector<std::string> & addrs)300 std::vector<char*> TetherController::toCstrVec(const std::vector<std::string>& addrs) {
301     std::vector<char*> addrsCstrVec{};
302     addrsCstrVec.reserve(addrs.size());
303     for (const auto& addr : addrs) {
304         addrsCstrVec.push_back(const_cast<char*>(addr.data()));
305     }
306     return addrsCstrVec;
307 }
308 
startTethering(const std::vector<std::string> & dhcpRanges)309 int TetherController::startTethering(const std::vector<std::string>& dhcpRanges) {
310     struct in_addr v4_addr;
311     for (const auto& dhcpRange : dhcpRanges) {
312         if (!inet_aton(dhcpRange.c_str(), &v4_addr)) {
313             return -EINVAL;
314         }
315     }
316     auto dhcp_ranges = toCstrVec(dhcpRanges);
317     return startTethering(dhcp_ranges.size(), dhcp_ranges.data());
318 }
319 
stopTethering()320 int TetherController::stopTethering() {
321     configureForTethering(false);
322 
323     if (mDaemonPid == 0) {
324         ALOGE("Tethering already stopped");
325         return 0;
326     }
327 
328     ALOGD("Stopping tethering services");
329 
330     kill(mDaemonPid, SIGTERM);
331     waitpid(mDaemonPid, nullptr, 0);
332     mDaemonPid = 0;
333     close(mDaemonFd);
334     mDaemonFd = -1;
335     mDnsmasqState.clear();
336     ALOGD("Tethering services stopped");
337     return 0;
338 }
339 
isTetheringStarted()340 bool TetherController::isTetheringStarted() {
341     return (mDaemonPid == 0 ? false : true);
342 }
343 
344 // dnsmasq can't parse commands larger than this due to the fixed-size buffer
345 // in check_android_listeners(). The receiving buffer is 1024 bytes long, but
346 // dnsmasq reads up to 1023 bytes.
347 const size_t MAX_CMD_SIZE = 1023;
348 
349 // TODO: Remove overload function and update this after NDC migration.
setDnsForwarders(unsigned netId,char ** servers,int numServers)350 int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
351     Fwmark fwmark;
352     fwmark.netId = netId;
353     fwmark.explicitlySelected = true;
354     fwmark.protectedFromVpn = true;
355     fwmark.permission = PERMISSION_SYSTEM;
356 
357     std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
358 
359     mDnsForwarders.clear();
360     for (int i = 0; i < numServers; i++) {
361         ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
362 
363         addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
364         int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
365         freeaddrinfo(res);
366         if (ret) {
367             ALOGE("Failed to parse DNS server '%s'", servers[i]);
368             mDnsForwarders.clear();
369             errno = EINVAL;
370             return -errno;
371         }
372 
373         if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
374             ALOGE("Too many DNS servers listed");
375             break;
376         }
377 
378         daemonCmd += SEPARATOR;
379         daemonCmd += servers[i];
380         mDnsForwarders.push_back(servers[i]);
381     }
382 
383     mDnsNetId = netId;
384     mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
385     if (mDaemonFd != -1) {
386         if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
387             mDnsForwarders.clear();
388             errno = EREMOTEIO;
389             return -errno;
390         }
391     }
392     return 0;
393 }
394 
setDnsForwarders(unsigned netId,const std::vector<std::string> & servers)395 int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
396     auto dnsServers = toCstrVec(servers);
397     return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
398 }
399 
getDnsNetId()400 unsigned TetherController::getDnsNetId() {
401     return mDnsNetId;
402 }
403 
getDnsForwarders() const404 const std::list<std::string> &TetherController::getDnsForwarders() const {
405     return mDnsForwarders;
406 }
407 
applyDnsInterfaces()408 bool TetherController::applyDnsInterfaces() {
409     std::string daemonCmd = "update_ifaces";
410     bool haveInterfaces = false;
411 
412     for (const auto& ifname : mInterfaces) {
413         if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
414             ALOGE("Too many DNS servers listed");
415             break;
416         }
417 
418         daemonCmd += SEPARATOR;
419         daemonCmd += ifname;
420         haveInterfaces = true;
421     }
422 
423     if (!haveInterfaces) {
424         mDnsmasqState.update_ifaces_cmd.clear();
425     } else {
426         mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
427         if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
428     }
429     return true;
430 }
431 
tetherInterface(const char * interface)432 int TetherController::tetherInterface(const char *interface) {
433     ALOGD("tetherInterface(%s)", interface);
434     if (!isIfaceName(interface)) {
435         errno = ENOENT;
436         return -errno;
437     }
438 
439     if (!configureForIPv6Router(interface)) {
440         configureForIPv6Client(interface);
441         return -EREMOTEIO;
442     }
443     mInterfaces.push_back(interface);
444 
445     if (!applyDnsInterfaces()) {
446         mInterfaces.pop_back();
447         configureForIPv6Client(interface);
448         return -EREMOTEIO;
449     } else {
450         return 0;
451     }
452 }
453 
untetherInterface(const char * interface)454 int TetherController::untetherInterface(const char *interface) {
455     ALOGD("untetherInterface(%s)", interface);
456 
457     for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
458         if (!strcmp(interface, it->c_str())) {
459             mInterfaces.erase(it);
460 
461             configureForIPv6Client(interface);
462             return applyDnsInterfaces() ? 0 : -EREMOTEIO;
463         }
464     }
465     errno = ENOENT;
466     return -errno;
467 }
468 
getTetheredInterfaceList() const469 const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
470     return mInterfaces;
471 }
472 
setupIptablesHooks()473 int TetherController::setupIptablesHooks() {
474     int res;
475     res = setDefaults();
476     if (res < 0) {
477         return res;
478     }
479 
480     // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
481     // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
482     // This is no longer optional and tethering will fail to start if it fails.
483     std::string mssRewriteCommand = StringPrintf(
484         "*mangle\n"
485         "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
486         "COMMIT\n", LOCAL_MANGLE_FORWARD);
487 
488     // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
489     std::string defaultCommands = StringPrintf(
490         "*filter\n"
491         ":%s -\n"
492         "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
493 
494     res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
495     if (res < 0) {
496         return res;
497     }
498 
499     res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
500     if (res < 0) {
501         return res;
502     }
503 
504     mFwdIfaces.clear();
505 
506     return 0;
507 }
508 
setDefaults()509 int TetherController::setDefaults() {
510     std::string v4Cmd = StringPrintf(
511         "*filter\n"
512         ":%s -\n"
513         "-A %s -j DROP\n"
514         "COMMIT\n"
515         "*nat\n"
516         ":%s -\n"
517         "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
518 
519     std::string v6Cmd = StringPrintf(
520             "*filter\n"
521             ":%s -\n"
522             "COMMIT\n"
523             "*raw\n"
524             ":%s -\n"
525             "COMMIT\n",
526             LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
527 
528     int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
529     if (res < 0) {
530         return res;
531     }
532 
533     res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
534     if (res < 0) {
535         return res;
536     }
537 
538     return 0;
539 }
540 
enableNat(const char * intIface,const char * extIface)541 int TetherController::enableNat(const char* intIface, const char* extIface) {
542     ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
543 
544     if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
545         return -ENODEV;
546     }
547 
548     /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
549     if (!strcmp(intIface, extIface)) {
550         ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
551         return -EINVAL;
552     }
553 
554     if (isForwardingPairEnabled(intIface, extIface)) {
555         return 0;
556     }
557 
558     // add this if we are the first enabled nat for this upstream
559     if (!isAnyForwardingEnabledOnUpstream(extIface)) {
560         std::vector<std::string> v4Cmds = {
561             "*nat",
562             StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
563             "COMMIT\n"
564         };
565 
566         if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
567             setTetherGlobalAlertRule()) {
568             ALOGE("Error setting postroute rule: iface=%s", extIface);
569             if (!isAnyForwardingPairEnabled()) {
570                 // unwind what's been done, but don't care about success - what more could we do?
571                 setDefaults();
572             }
573             return -EREMOTEIO;
574         }
575     }
576 
577     if (setForwardRules(true, intIface, extIface) != 0) {
578         ALOGE("Error setting forward rules");
579         if (!isAnyForwardingPairEnabled()) {
580             setDefaults();
581         }
582         return -ENODEV;
583     }
584 
585     return 0;
586 }
587 
setTetherGlobalAlertRule()588 int TetherController::setTetherGlobalAlertRule() {
589     // Only add this if we are the first enabled nat
590     if (isAnyForwardingPairEnabled()) {
591         return 0;
592     }
593     const std::string cmds =
594             "*filter\n" +
595             StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
596             "COMMIT\n";
597 
598     return iptablesRestoreFunction(V4V6, cmds, nullptr);
599 }
600 
setupIPv6CountersChain()601 int TetherController::setupIPv6CountersChain() {
602     // Only add this if we are the first enabled nat
603     if (isAnyForwardingPairEnabled()) {
604         return 0;
605     }
606 
607     /*
608      * IPv6 tethering doesn't need the state-based conntrack rules, so
609      * it unconditionally jumps to the tether counters chain all the time.
610      */
611     const std::string v6Cmds =
612             "*filter\n" +
613             StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
614 
615     return iptablesRestoreFunction(V6, v6Cmds, nullptr);
616 }
617 
618 // Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
findForwardingDownstream(const std::string & intIface,const std::string & extIface)619 TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
620         const std::string& intIface, const std::string& extIface) {
621     auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
622     for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
623         if (it->second.iface == intIface) {
624             return &(it->second);
625         }
626     }
627     return nullptr;
628 }
629 
addForwardingPair(const std::string & intIface,const std::string & extIface)630 void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
631     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
632     if (existingEntry != nullptr) {
633         existingEntry->active = true;
634         return;
635     }
636 
637     mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
638         .iface = intIface,
639         .active = true
640     }));
641 }
642 
markForwardingPairDisabled(const std::string & intIface,const std::string & extIface)643 void TetherController::markForwardingPairDisabled(
644         const std::string& intIface, const std::string& extIface) {
645     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
646     if (existingEntry == nullptr) {
647         return;
648     }
649 
650     existingEntry->active = false;
651 }
652 
isForwardingPairEnabled(const std::string & intIface,const std::string & extIface)653 bool TetherController::isForwardingPairEnabled(
654         const std::string& intIface, const std::string& extIface) {
655     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
656     return existingEntry != nullptr && existingEntry->active;
657 }
658 
isAnyForwardingEnabledOnUpstream(const std::string & extIface)659 bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
660     auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
661     for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
662         if (it->second.active) {
663             return true;
664         }
665     }
666     return false;
667 }
668 
isAnyForwardingPairEnabled()669 bool TetherController::isAnyForwardingPairEnabled() {
670     for (auto& it : mFwdIfaces) {
671         if (it.second.active) {
672             return true;
673         }
674     }
675     return false;
676 }
677 
tetherCountingRuleExists(const std::string & iface1,const std::string & iface2)678 bool TetherController::tetherCountingRuleExists(
679         const std::string& iface1, const std::string& iface2) {
680     // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
681     // is in the map regardless of its active status. Rules are added both ways so we check with
682     // the 2 combinations.
683     return findForwardingDownstream(iface1, iface2) != nullptr
684         || findForwardingDownstream(iface2, iface1) != nullptr;
685 }
686 
687 /* static */
makeTetherCountingRule(const char * if1,const char * if2)688 std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
689     return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
690 }
691 
setForwardRules(bool add,const char * intIface,const char * extIface)692 int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
693     const char *op = add ? "-A" : "-D";
694 
695     std::string rpfilterCmd = StringPrintf(
696         "*raw\n"
697         "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
698         "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
699     if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
700         return -EREMOTEIO;
701     }
702 
703     std::vector<std::string> v4 = {
704             "*raw",
705             StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
706                          LOCAL_RAW_PREROUTING, intIface),
707             StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
708                          LOCAL_RAW_PREROUTING, intIface),
709             "COMMIT",
710             "*filter",
711             StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
712                          LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
713             StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
714                          intIface, extIface),
715             StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
716                          LOCAL_TETHER_COUNTERS_CHAIN),
717     };
718 
719     std::vector<std::string> v6 = {
720         "*filter",
721     };
722 
723     // We only ever add tethering quota rules so that they stick.
724     if (add && !tetherCountingRuleExists(intIface, extIface)) {
725         v4.push_back(makeTetherCountingRule(intIface, extIface));
726         v4.push_back(makeTetherCountingRule(extIface, intIface));
727         v6.push_back(makeTetherCountingRule(intIface, extIface));
728         v6.push_back(makeTetherCountingRule(extIface, intIface));
729     }
730 
731     // Always make sure the drop rule is at the end.
732     // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
733     // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
734     if (add) {
735         v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
736         v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
737     }
738 
739     v4.push_back("COMMIT\n");
740     v6.push_back("COMMIT\n");
741 
742     // We only add IPv6 rules here, never remove them.
743     if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
744         (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
745         // unwind what's been done, but don't care about success - what more could we do?
746         if (add) {
747             setForwardRules(false, intIface, extIface);
748         }
749         return -EREMOTEIO;
750     }
751 
752     if (add) {
753         addForwardingPair(intIface, extIface);
754     } else {
755         markForwardingPairDisabled(intIface, extIface);
756     }
757 
758     return 0;
759 }
760 
disableNat(const char * intIface,const char * extIface)761 int TetherController::disableNat(const char* intIface, const char* extIface) {
762     if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
763         errno = ENODEV;
764         return -errno;
765     }
766 
767     setForwardRules(false, intIface, extIface);
768     if (!isAnyForwardingPairEnabled()) {
769         setDefaults();
770     }
771     return 0;
772 }
773 
addStats(TetherStatsList & statsList,const TetherStats & stats)774 void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
775     for (TetherStats& existing : statsList) {
776         if (existing.addStatsIfMatch(stats)) {
777             return;
778         }
779     }
780     // No match. Insert a new interface pair.
781     statsList.push_back(stats);
782 }
783 
784 /*
785  * Parse the ptks and bytes out of:
786  *   Chain tetherctrl_counters (4 references)
787  *       pkts      bytes target     prot opt in     out     source               destination
788  *         26     2373 RETURN     all  --  wlan0  rmnet0  0.0.0.0/0            0.0.0.0/0
789  *         27     2002 RETURN     all  --  rmnet0 wlan0   0.0.0.0/0            0.0.0.0/0
790  *       1040   107471 RETURN     all  --  bt-pan rmnet0  0.0.0.0/0            0.0.0.0/0
791  *       1450  1708806 RETURN     all  --  rmnet0 bt-pan  0.0.0.0/0            0.0.0.0/0
792  * or:
793  *   Chain tetherctrl_counters (0 references)
794  *       pkts      bytes target     prot opt in     out     source               destination
795  *          0        0 RETURN     all      wlan0  rmnet_data0  ::/0                 ::/0
796  *          0        0 RETURN     all      rmnet_data0 wlan0   ::/0                 ::/0
797  *
798  */
addForwardChainStats(TetherStatsList & statsList,const std::string & statsOutput,std::string & extraProcessingInfo)799 int TetherController::addForwardChainStats(TetherStatsList& statsList,
800                                            const std::string& statsOutput,
801                                            std::string &extraProcessingInfo) {
802     enum IndexOfIptChain {
803         ORIG_LINE,
804         PACKET_COUNTS,
805         BYTE_COUNTS,
806         HYPHEN,
807         IFACE0_NAME,
808         IFACE1_NAME,
809         SOURCE,
810         DESTINATION
811     };
812     TetherStats stats;
813     const TetherStats empty;
814 
815     static const std::string NUM = "(\\d+)";
816     static const std::string IFACE = "([^\\s]+)";
817     static const std::string DST = "(0.0.0.0/0|::/0)";
818     static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
819                                         " RETURN     all(  --  |      )" + IFACE + "\\s+" + IFACE +
820                                         "\\s+" + DST + "\\s+" + DST;
821     static const std::regex IP_RE(COUNTERS);
822 
823     const std::vector<std::string> lines = base::Split(statsOutput, "\n");
824     int headerLine = 0;
825     for (const std::string& line : lines) {
826         // Skip headers.
827         if (headerLine < 2) {
828             if (line.empty()) {
829                 ALOGV("Empty header while parsing tethering stats");
830                 return -EREMOTEIO;
831             }
832             headerLine++;
833             continue;
834         }
835 
836         if (line.empty()) continue;
837 
838         extraProcessingInfo = line;
839         std::smatch matches;
840         if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
841         // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
842         // IPv4 has "--" indicating what to do with fragments...
843         //		 26 	2373 RETURN     all  --  wlan0	rmnet0	0.0.0.0/0			 0.0.0.0/0
844         // ... but IPv6 does not.
845         //		 26 	2373 RETURN 	all      wlan0	rmnet0	::/0				 ::/0
846         // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
847         int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
848         int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
849         std::string iface0 = matches[IFACE0_NAME].str();
850         std::string iface1 = matches[IFACE1_NAME].str();
851         std::string rest = matches[SOURCE].str();
852 
853         ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
854               " rest=<%s> orig line=<%s>",
855               iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
856         /*
857          * The following assumes that the 1st rule has in:extIface out:intIface,
858          * which is what TetherController sets up.
859          * The 1st matches rx, and sets up the pair for the tx side.
860          */
861         if (!stats.intIface[0]) {
862             ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
863                   " ", iface0.c_str(), iface1.c_str(), bytes, packets);
864             stats.intIface = iface0;
865             stats.extIface = iface1;
866             stats.txPackets = packets;
867             stats.txBytes = bytes;
868         } else if (stats.intIface == iface1 && stats.extIface == iface0) {
869             ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
870                   " ", iface0.c_str(), iface1.c_str(), bytes, packets);
871             stats.rxPackets = packets;
872             stats.rxBytes = bytes;
873         }
874         if (stats.rxBytes != -1 && stats.txBytes != -1) {
875             ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
876             addStats(statsList, stats);
877             stats = empty;
878         }
879     }
880 
881     /* It is always an error to find only one side of the stats. */
882     if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
883         return -EREMOTEIO;
884     }
885     return 0;
886 }
887 
getTetherStats()888 StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
889     TetherStatsList statsList;
890     std::string parsedIptablesOutput;
891 
892     for (const IptablesTarget target : {V4, V6}) {
893         std::string statsString;
894         if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
895             return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
896                                                       target, ret));
897         }
898 
899         if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
900             return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
901                                                       target == V4 ? "IPv4": "IPv6",
902                                                       parsedIptablesOutput.c_str()));
903         }
904     }
905 
906     return statsList;
907 }
908 
909 }  // namespace net
910 }  // namespace android
911