• 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 "Permission.h"
55 #include "TcUtils.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     ::stopProcess(mDaemonPid, "tethering(dnsmasq)");
354     mDaemonPid = 0;
355     close(mDaemonFd);
356     mDaemonFd = -1;
357     mDnsmasqState.clear();
358     ALOGD("Tethering services stopped");
359     return 0;
360 }
361 
isTetheringStarted()362 bool TetherController::isTetheringStarted() {
363     return mIsTetheringStarted;
364 }
365 
366 // dnsmasq can't parse commands larger than this due to the fixed-size buffer
367 // in check_android_listeners(). The receiving buffer is 1024 bytes long, but
368 // dnsmasq reads up to 1023 bytes.
369 const size_t MAX_CMD_SIZE = 1023;
370 
371 // TODO: Remove overload function and update this after NDC migration.
setDnsForwarders(unsigned netId,char ** servers,int numServers)372 int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
373     Fwmark fwmark;
374     fwmark.netId = netId;
375     fwmark.explicitlySelected = true;
376     fwmark.protectedFromVpn = true;
377     fwmark.permission = PERMISSION_SYSTEM;
378 
379     std::string daemonCmd = StringPrintf("update_dns%s0x%x", SEPARATOR, fwmark.intValue);
380 
381     mDnsForwarders.clear();
382     for (int i = 0; i < numServers; i++) {
383         ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
384 
385         addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
386         int ret = getaddrinfo(servers[i], nullptr, &hints, &res);
387         freeaddrinfo(res);
388         if (ret) {
389             ALOGE("Failed to parse DNS server '%s'", servers[i]);
390             mDnsForwarders.clear();
391             errno = EINVAL;
392             return -errno;
393         }
394 
395         if (daemonCmd.size() + 1 + strlen(servers[i]) >= MAX_CMD_SIZE) {
396             ALOGE("Too many DNS servers listed");
397             break;
398         }
399 
400         daemonCmd += SEPARATOR;
401         daemonCmd += servers[i];
402         mDnsForwarders.push_back(servers[i]);
403     }
404 
405     mDnsNetId = netId;
406     mDnsmasqState.update_dns_cmd = std::move(daemonCmd);
407     if (mDaemonFd != -1) {
408         if (mDnsmasqState.sendAllState(mDaemonFd) != 0) {
409             mDnsForwarders.clear();
410             errno = EREMOTEIO;
411             return -errno;
412         }
413     }
414     return 0;
415 }
416 
setDnsForwarders(unsigned netId,const std::vector<std::string> & servers)417 int TetherController::setDnsForwarders(unsigned netId, const std::vector<std::string>& servers) {
418     auto dnsServers = toCstrVec(servers);
419     return setDnsForwarders(netId, dnsServers.data(), dnsServers.size());
420 }
421 
getDnsNetId()422 unsigned TetherController::getDnsNetId() {
423     return mDnsNetId;
424 }
425 
getDnsForwarders() const426 const std::list<std::string> &TetherController::getDnsForwarders() const {
427     return mDnsForwarders;
428 }
429 
applyDnsInterfaces()430 bool TetherController::applyDnsInterfaces() {
431     std::string daemonCmd = "update_ifaces";
432     bool haveInterfaces = false;
433 
434     for (const auto& ifname : mInterfaces) {
435         if (daemonCmd.size() + 1 + ifname.size() >= MAX_CMD_SIZE) {
436             ALOGE("Too many DNS servers listed");
437             break;
438         }
439 
440         daemonCmd += SEPARATOR;
441         daemonCmd += ifname;
442         haveInterfaces = true;
443     }
444 
445     if (!haveInterfaces) {
446         mDnsmasqState.update_ifaces_cmd.clear();
447     } else {
448         mDnsmasqState.update_ifaces_cmd = std::move(daemonCmd);
449         if (mDaemonFd != -1) return (mDnsmasqState.sendAllState(mDaemonFd) == 0);
450     }
451     return true;
452 }
453 
tetherInterface(const char * interface)454 int TetherController::tetherInterface(const char *interface) {
455     ALOGD("tetherInterface(%s)", interface);
456     if (!isIfaceName(interface)) {
457         errno = ENOENT;
458         return -errno;
459     }
460 
461     if (!configureForIPv6Router(interface)) {
462         configureForIPv6Client(interface);
463         return -EREMOTEIO;
464     }
465     mInterfaces.push_back(interface);
466 
467     if (!applyDnsInterfaces()) {
468         mInterfaces.pop_back();
469         configureForIPv6Client(interface);
470         return -EREMOTEIO;
471     } else {
472         return 0;
473     }
474 }
475 
untetherInterface(const char * interface)476 int TetherController::untetherInterface(const char *interface) {
477     ALOGD("untetherInterface(%s)", interface);
478 
479     for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
480         if (!strcmp(interface, it->c_str())) {
481             mInterfaces.erase(it);
482 
483             configureForIPv6Client(interface);
484             return applyDnsInterfaces() ? 0 : -EREMOTEIO;
485         }
486     }
487     errno = ENOENT;
488     return -errno;
489 }
490 
getTetheredInterfaceList() const491 const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
492     return mInterfaces;
493 }
494 
setupIptablesHooks()495 int TetherController::setupIptablesHooks() {
496     int res;
497     res = setDefaults();
498     if (res < 0) {
499         return res;
500     }
501 
502     // Used to limit downstream mss to the upstream pmtu so we don't end up fragmenting every large
503     // packet tethered devices send. This is IPv4-only, because in IPv6 we send the MTU in the RA.
504     // This is no longer optional and tethering will fail to start if it fails.
505     std::string mssRewriteCommand = StringPrintf(
506         "*mangle\n"
507         "-A %s -p tcp --tcp-flags SYN SYN -j TCPMSS --clamp-mss-to-pmtu\n"
508         "COMMIT\n", LOCAL_MANGLE_FORWARD);
509 
510     // This is for tethering counters. This chain is reached via --goto, and then RETURNS.
511     std::string defaultCommands = StringPrintf(
512         "*filter\n"
513         ":%s -\n"
514         "COMMIT\n", LOCAL_TETHER_COUNTERS_CHAIN);
515 
516     res = iptablesRestoreFunction(V4, mssRewriteCommand, nullptr);
517     if (res < 0) {
518         return res;
519     }
520 
521     res = iptablesRestoreFunction(V4V6, defaultCommands, nullptr);
522     if (res < 0) {
523         return res;
524     }
525 
526     mFwdIfaces.clear();
527 
528     return 0;
529 }
530 
setDefaults()531 int TetherController::setDefaults() {
532     std::string v4Cmd = StringPrintf(
533         "*filter\n"
534         ":%s -\n"
535         "-A %s -j DROP\n"
536         "COMMIT\n"
537         "*nat\n"
538         ":%s -\n"
539         "COMMIT\n", LOCAL_FORWARD, LOCAL_FORWARD, LOCAL_NAT_POSTROUTING);
540 
541     std::string v6Cmd = StringPrintf(
542             "*filter\n"
543             ":%s -\n"
544             "COMMIT\n"
545             "*raw\n"
546             ":%s -\n"
547             "COMMIT\n",
548             LOCAL_FORWARD, LOCAL_RAW_PREROUTING);
549 
550     int res = iptablesRestoreFunction(V4, v4Cmd, nullptr);
551     if (res < 0) {
552         return res;
553     }
554 
555     res = iptablesRestoreFunction(V6, v6Cmd, nullptr);
556     if (res < 0) {
557         return res;
558     }
559 
560     return 0;
561 }
562 
enableNat(const char * intIface,const char * extIface)563 int TetherController::enableNat(const char* intIface, const char* extIface) {
564     ALOGV("enableNat(intIface=<%s>, extIface=<%s>)",intIface, extIface);
565 
566     if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
567         return -ENODEV;
568     }
569 
570     /* Bug: b/9565268. "enableNat wlan0 wlan0". For now we fail until java-land is fixed */
571     if (!strcmp(intIface, extIface)) {
572         ALOGE("Duplicate interface specified: %s %s", intIface, extIface);
573         return -EINVAL;
574     }
575 
576     if (isForwardingPairEnabled(intIface, extIface)) {
577         return 0;
578     }
579 
580     // add this if we are the first enabled nat for this upstream
581     if (!isAnyForwardingEnabledOnUpstream(extIface)) {
582         std::vector<std::string> v4Cmds = {
583             "*nat",
584             StringPrintf("-A %s -o %s -j MASQUERADE", LOCAL_NAT_POSTROUTING, extIface),
585             "COMMIT\n"
586         };
587 
588         if (iptablesRestoreFunction(V4, Join(v4Cmds, '\n'), nullptr) || setupIPv6CountersChain() ||
589             setTetherGlobalAlertRule()) {
590             ALOGE("Error setting postroute rule: iface=%s", extIface);
591             if (!isAnyForwardingPairEnabled()) {
592                 // unwind what's been done, but don't care about success - what more could we do?
593                 setDefaults();
594             }
595             return -EREMOTEIO;
596         }
597     }
598 
599     if (setForwardRules(true, intIface, extIface) != 0) {
600         ALOGE("Error setting forward rules");
601         if (!isAnyForwardingPairEnabled()) {
602             setDefaults();
603         }
604         return -ENODEV;
605     }
606 
607     return 0;
608 }
609 
setTetherGlobalAlertRule()610 int TetherController::setTetherGlobalAlertRule() {
611     // Only add this if we are the first enabled nat
612     if (isAnyForwardingPairEnabled()) {
613         return 0;
614     }
615     const std::string cmds =
616             "*filter\n" +
617             StringPrintf("-I %s -j %s\n", LOCAL_FORWARD, BandwidthController::LOCAL_GLOBAL_ALERT) +
618             "COMMIT\n";
619 
620     return iptablesRestoreFunction(V4V6, cmds, nullptr);
621 }
622 
setupIPv6CountersChain()623 int TetherController::setupIPv6CountersChain() {
624     // Only add this if we are the first enabled nat
625     if (isAnyForwardingPairEnabled()) {
626         return 0;
627     }
628 
629     /*
630      * IPv6 tethering doesn't need the state-based conntrack rules, so
631      * it unconditionally jumps to the tether counters chain all the time.
632      */
633     const std::string v6Cmds =
634             "*filter\n" +
635             StringPrintf("-A %s -g %s\n", LOCAL_FORWARD, LOCAL_TETHER_COUNTERS_CHAIN) + "COMMIT\n";
636 
637     return iptablesRestoreFunction(V6, v6Cmds, nullptr);
638 }
639 
640 // Gets a pointer to the ForwardingDownstream for an interface pair in the map, or nullptr
findForwardingDownstream(const std::string & intIface,const std::string & extIface)641 TetherController::ForwardingDownstream* TetherController::findForwardingDownstream(
642         const std::string& intIface, const std::string& extIface) {
643     auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
644     for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
645         if (it->second.iface == intIface) {
646             return &(it->second);
647         }
648     }
649     return nullptr;
650 }
651 
addForwardingPair(const std::string & intIface,const std::string & extIface)652 void TetherController::addForwardingPair(const std::string& intIface, const std::string& extIface) {
653     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
654     if (existingEntry != nullptr) {
655         existingEntry->active = true;
656         return;
657     }
658 
659     mFwdIfaces.insert(std::pair<std::string, ForwardingDownstream>(extIface, {
660         .iface = intIface,
661         .active = true
662     }));
663 }
664 
markForwardingPairDisabled(const std::string & intIface,const std::string & extIface)665 void TetherController::markForwardingPairDisabled(
666         const std::string& intIface, const std::string& extIface) {
667     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
668     if (existingEntry == nullptr) {
669         return;
670     }
671 
672     existingEntry->active = false;
673 }
674 
isForwardingPairEnabled(const std::string & intIface,const std::string & extIface)675 bool TetherController::isForwardingPairEnabled(
676         const std::string& intIface, const std::string& extIface) {
677     ForwardingDownstream* existingEntry = findForwardingDownstream(intIface, extIface);
678     return existingEntry != nullptr && existingEntry->active;
679 }
680 
isAnyForwardingEnabledOnUpstream(const std::string & extIface)681 bool TetherController::isAnyForwardingEnabledOnUpstream(const std::string& extIface) {
682     auto extIfaceMatches = mFwdIfaces.equal_range(extIface);
683     for (auto it = extIfaceMatches.first; it != extIfaceMatches.second; ++it) {
684         if (it->second.active) {
685             return true;
686         }
687     }
688     return false;
689 }
690 
isAnyForwardingPairEnabled()691 bool TetherController::isAnyForwardingPairEnabled() {
692     for (auto& it : mFwdIfaces) {
693         if (it.second.active) {
694             return true;
695         }
696     }
697     return false;
698 }
699 
tetherCountingRuleExists(const std::string & iface1,const std::string & iface2)700 bool TetherController::tetherCountingRuleExists(
701         const std::string& iface1, const std::string& iface2) {
702     // A counting rule exists if NAT was ever enabled for this interface pair, so if the pair
703     // is in the map regardless of its active status. Rules are added both ways so we check with
704     // the 2 combinations.
705     return findForwardingDownstream(iface1, iface2) != nullptr
706         || findForwardingDownstream(iface2, iface1) != nullptr;
707 }
708 
709 /* static */
makeTetherCountingRule(const char * if1,const char * if2)710 std::string TetherController::makeTetherCountingRule(const char *if1, const char *if2) {
711     return StringPrintf("-A %s -i %s -o %s -j RETURN", LOCAL_TETHER_COUNTERS_CHAIN, if1, if2);
712 }
713 
setForwardRules(bool add,const char * intIface,const char * extIface)714 int TetherController::setForwardRules(bool add, const char *intIface, const char *extIface) {
715     const char *op = add ? "-A" : "-D";
716 
717     std::string rpfilterCmd = StringPrintf(
718         "*raw\n"
719         "%s %s -i %s -m rpfilter --invert ! -s fe80::/64 -j DROP\n"
720         "COMMIT\n", op, LOCAL_RAW_PREROUTING, intIface);
721     if (iptablesRestoreFunction(V6, rpfilterCmd, nullptr) == -1 && add) {
722         return -EREMOTEIO;
723     }
724 
725     std::vector<std::string> v4 = {
726             "*raw",
727             StringPrintf("%s %s -p tcp --dport 21 -i %s -j CT --helper ftp", op,
728                          LOCAL_RAW_PREROUTING, intIface),
729             StringPrintf("%s %s -p tcp --dport 1723 -i %s -j CT --helper pptp", op,
730                          LOCAL_RAW_PREROUTING, intIface),
731             "COMMIT",
732             "*filter",
733             StringPrintf("%s %s -i %s -o %s -m state --state ESTABLISHED,RELATED -g %s", op,
734                          LOCAL_FORWARD, extIface, intIface, LOCAL_TETHER_COUNTERS_CHAIN),
735             StringPrintf("%s %s -i %s -o %s -m state --state INVALID -j DROP", op, LOCAL_FORWARD,
736                          intIface, extIface),
737             StringPrintf("%s %s -i %s -o %s -g %s", op, LOCAL_FORWARD, intIface, extIface,
738                          LOCAL_TETHER_COUNTERS_CHAIN),
739     };
740 
741     std::vector<std::string> v6 = {
742         "*filter",
743     };
744 
745     // We only ever add tethering quota rules so that they stick.
746     if (add && !tetherCountingRuleExists(intIface, extIface)) {
747         v4.push_back(makeTetherCountingRule(intIface, extIface));
748         v4.push_back(makeTetherCountingRule(extIface, intIface));
749         v6.push_back(makeTetherCountingRule(intIface, extIface));
750         v6.push_back(makeTetherCountingRule(extIface, intIface));
751     }
752 
753     // Always make sure the drop rule is at the end.
754     // TODO: instead of doing this, consider just rebuilding LOCAL_FORWARD completely from scratch
755     // every time, starting with ":tetherctrl_FORWARD -\n". This would likely be a bit simpler.
756     if (add) {
757         v4.push_back(StringPrintf("-D %s -j DROP", LOCAL_FORWARD));
758         v4.push_back(StringPrintf("-A %s -j DROP", LOCAL_FORWARD));
759     }
760 
761     v4.push_back("COMMIT\n");
762     v6.push_back("COMMIT\n");
763 
764     // We only add IPv6 rules here, never remove them.
765     if (iptablesRestoreFunction(V4, Join(v4, '\n'), nullptr) == -1 ||
766         (add && iptablesRestoreFunction(V6, Join(v6, '\n'), nullptr) == -1)) {
767         // unwind what's been done, but don't care about success - what more could we do?
768         if (add) {
769             setForwardRules(false, intIface, extIface);
770         }
771         return -EREMOTEIO;
772     }
773 
774     if (add) {
775         addForwardingPair(intIface, extIface);
776     } else {
777         markForwardingPairDisabled(intIface, extIface);
778     }
779 
780     return 0;
781 }
782 
disableNat(const char * intIface,const char * extIface)783 int TetherController::disableNat(const char* intIface, const char* extIface) {
784     if (!isIfaceName(intIface) || !isIfaceName(extIface)) {
785         errno = ENODEV;
786         return -errno;
787     }
788 
789     setForwardRules(false, intIface, extIface);
790     if (!isAnyForwardingPairEnabled()) setDefaults();
791     return 0;
792 }
793 
addStats(TetherStatsList & statsList,const TetherStats & stats)794 void TetherController::addStats(TetherStatsList& statsList, const TetherStats& stats) {
795     for (TetherStats& existing : statsList) {
796         if (existing.addStatsIfMatch(stats)) {
797             return;
798         }
799     }
800     // No match. Insert a new interface pair.
801     statsList.push_back(stats);
802 }
803 
804 /*
805  * Parse the ptks and bytes out of:
806  *   Chain tetherctrl_counters (4 references)
807  *       pkts      bytes target     prot opt in     out     source               destination
808  *         26     2373 RETURN     all  --  wlan0  rmnet0  0.0.0.0/0            0.0.0.0/0
809  *         27     2002 RETURN     all  --  rmnet0 wlan0   0.0.0.0/0            0.0.0.0/0
810  *       1040   107471 RETURN     all  --  bt-pan rmnet0  0.0.0.0/0            0.0.0.0/0
811  *       1450  1708806 RETURN     all  --  rmnet0 bt-pan  0.0.0.0/0            0.0.0.0/0
812  * or:
813  *   Chain tetherctrl_counters (0 references)
814  *       pkts      bytes target     prot opt in     out     source               destination
815  *          0        0 RETURN     all      wlan0  rmnet_data0  ::/0                 ::/0
816  *          0        0 RETURN     all      rmnet_data0 wlan0   ::/0                 ::/0
817  *
818  */
addForwardChainStats(TetherStatsList & statsList,const std::string & statsOutput,std::string & extraProcessingInfo)819 int TetherController::addForwardChainStats(TetherStatsList& statsList,
820                                            const std::string& statsOutput,
821                                            std::string &extraProcessingInfo) {
822     enum IndexOfIptChain {
823         ORIG_LINE,
824         PACKET_COUNTS,
825         BYTE_COUNTS,
826         HYPHEN,
827         IFACE0_NAME,
828         IFACE1_NAME,
829         SOURCE,
830         DESTINATION
831     };
832     TetherStats stats;
833     const TetherStats empty;
834 
835     static const std::string NUM = "(\\d+)";
836     static const std::string IFACE = "([^\\s]+)";
837     static const std::string DST = "(0.0.0.0/0|::/0)";
838     static const std::string COUNTERS = "\\s*" + NUM + "\\s+" + NUM +
839                                         " RETURN     all(  --  |      )" + IFACE + "\\s+" + IFACE +
840                                         "\\s+" + DST + "\\s+" + DST;
841     static const std::regex IP_RE(COUNTERS);
842 
843     const std::vector<std::string> lines = base::Split(statsOutput, "\n");
844     int headerLine = 0;
845     for (const std::string& line : lines) {
846         // Skip headers.
847         if (headerLine < 2) {
848             if (line.empty()) {
849                 ALOGV("Empty header while parsing tethering stats");
850                 return -EREMOTEIO;
851             }
852             headerLine++;
853             continue;
854         }
855 
856         if (line.empty()) continue;
857 
858         extraProcessingInfo = line;
859         std::smatch matches;
860         if (!std::regex_search(line, matches, IP_RE)) return -EREMOTEIO;
861         // Here use IP_RE to distiguish IPv4 and IPv6 iptables.
862         // IPv4 has "--" indicating what to do with fragments...
863         //		 26 	2373 RETURN     all  --  wlan0	rmnet0	0.0.0.0/0			 0.0.0.0/0
864         // ... but IPv6 does not.
865         //		 26 	2373 RETURN 	all      wlan0	rmnet0	::/0				 ::/0
866         // TODO: Replace strtoXX() calls with ParseUint() /ParseInt()
867         int64_t packets = strtoul(matches[PACKET_COUNTS].str().c_str(), nullptr, 10);
868         int64_t bytes = strtoul(matches[BYTE_COUNTS].str().c_str(), nullptr, 10);
869         std::string iface0 = matches[IFACE0_NAME].str();
870         std::string iface1 = matches[IFACE1_NAME].str();
871         std::string rest = matches[SOURCE].str();
872 
873         ALOGV("parse iface0=<%s> iface1=<%s> pkts=%" PRId64 " bytes=%" PRId64
874               " rest=<%s> orig line=<%s>",
875               iface0.c_str(), iface1.c_str(), packets, bytes, rest.c_str(), line.c_str());
876         /*
877          * The following assumes that the 1st rule has in:extIface out:intIface,
878          * which is what TetherController sets up.
879          * The 1st matches rx, and sets up the pair for the tx side.
880          */
881         if (stats.intIface.empty()) {
882             ALOGV("0Filter RX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
883                   " ", iface0.c_str(), iface1.c_str(), bytes, packets);
884             stats.intIface = iface0;
885             stats.extIface = iface1;
886             stats.txPackets = packets;
887             stats.txBytes = bytes;
888         } else if (stats.intIface == iface1 && stats.extIface == iface0) {
889             ALOGV("0Filter TX iface_in=%s iface_out=%s rx_bytes=%" PRId64 " rx_packets=%" PRId64
890                   " ", iface0.c_str(), iface1.c_str(), bytes, packets);
891             stats.rxPackets = packets;
892             stats.rxBytes = bytes;
893         }
894         if (stats.rxBytes != -1 && stats.txBytes != -1) {
895             ALOGV("rx_bytes=%" PRId64" tx_bytes=%" PRId64, stats.rxBytes, stats.txBytes);
896             addStats(statsList, stats);
897             stats = empty;
898         }
899     }
900 
901     /* It is always an error to find only one side of the stats. */
902     if (((stats.rxBytes == -1) != (stats.txBytes == -1))) {
903         return -EREMOTEIO;
904     }
905     return 0;
906 }
907 
getTetherStats()908 StatusOr<TetherController::TetherStatsList> TetherController::getTetherStats() {
909     TetherStatsList statsList;
910     std::string parsedIptablesOutput;
911 
912     for (const IptablesTarget target : {V4, V6}) {
913         std::string statsString;
914         if (int ret = iptablesRestoreFunction(target, GET_TETHER_STATS_COMMAND, &statsString)) {
915             return statusFromErrno(-ret, StringPrintf("failed to fetch tether stats (%d): %d",
916                                                       target, ret));
917         }
918 
919         if (int ret = addForwardChainStats(statsList, statsString, parsedIptablesOutput)) {
920             return statusFromErrno(-ret, StringPrintf("failed to parse %s tether stats:\n%s",
921                                                       target == V4 ? "IPv4": "IPv6",
922                                                       parsedIptablesOutput.c_str()));
923         }
924     }
925 
926     return statsList;
927 }
928 
dumpIfaces(DumpWriter & dw)929 void TetherController::dumpIfaces(DumpWriter& dw) {
930     dw.println("Interface pairs:");
931 
932     ScopedIndent ifaceIndent(dw);
933     for (const auto& it : mFwdIfaces) {
934         dw.println("%s -> %s %s", it.first.c_str(), it.second.iface.c_str(),
935                    (it.second.active ? "ACTIVE" : "DISABLED"));
936     }
937 }
938 
dump(DumpWriter & dw)939 void TetherController::dump(DumpWriter& dw) {
940     std::lock_guard guard(lock);
941 
942     ScopedIndent tetherControllerIndent(dw);
943     dw.println("TetherController");
944     dw.incIndent();
945 
946     dw.println("Forwarding requests: " + Join(mForwardingRequests, ' '));
947     if (mDnsNetId != 0) {
948         dw.println(StringPrintf("DNS: netId %d servers [%s]", mDnsNetId,
949                                 Join(mDnsForwarders, ", ").c_str()));
950     }
951     if (mDaemonPid != 0) {
952         dw.println("dnsmasq PID: %d", mDaemonPid);
953     }
954 
955     dumpIfaces(dw);
956 }
957 
958 }  // namespace net
959 }  // namespace android
960