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