├── MODULE_LICENSE_APACHE2 ├── Android.mk ├── tests ├── netd_integration_test.cpp ├── Android.mk └── dns_responder.h ├── server ├── netd.rc ├── NetdCommand.cpp ├── binder │ └── android │ │ └── net │ │ ├── UidRange.aidl │ │ ├── metrics │ │ └── IDnsEventListener.aidl │ │ ├── UidRange.h │ │ └── UidRange.cpp ├── NetdCommand.h ├── oem_iptables_hook.h ├── Controllers.cpp ├── ConnmarkFlags.h ├── LocalNetwork.h ├── DumpWriter.h ├── DummyNetwork.h ├── ClatdController.h ├── FwmarkServer.h ├── DummyNetwork.cpp ├── PppController.h ├── UidRanges.h ├── IdletimerController.h ├── StrictController.h ├── Controllers.h ├── DumpWriter.cpp ├── LocalNetwork.cpp ├── SoftapController.h ├── NatController.h ├── NetlinkManager.h ├── QtiDataController.h ├── IptablesBaseTest.h ├── Network.h ├── PhysicalNetwork.h ├── TetherController.h ├── NetlinkHandler.h ├── VirtualNetwork.h ├── ResolverController.h ├── CleanSpec.mk ├── InterfaceController.h ├── Network.cpp ├── oem_iptables_hook.cpp ├── NetdNativeService.h ├── SockDiag.h ├── FirewallController.h ├── NetdConstants.h ├── UidRanges.cpp ├── ResponseCode.h ├── VirtualNetwork.cpp ├── PppController.cpp ├── ClatdController.cpp ├── QtiDataController.cpp ├── ResolverStats.h ├── Android.mk ├── RouteController.h ├── StrictControllerTest.cpp ├── MDnsSdListener.h ├── main.cpp ├── NetworkController.h ├── DnsProxyListener.h ├── IptablesBaseTest.cpp ├── CommandListener.h ├── NatControllerTest.cpp ├── ndc.c ├── NetlinkManager.cpp ├── PhysicalNetwork.cpp └── FirewallControllerTest.cpp ├── client ├── Android.mk ├── FwmarkClient.h ├── FwmarkClient.cpp └── NetdClient.cpp └── include ├── Fwmark.h ├── FwmarkCommand.h ├── NetdClient.h └── Permission.h /MODULE_LICENSE_APACHE2: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Android.mk: -------------------------------------------------------------------------------- 1 | include $(call all-subdir-makefiles) 2 | -------------------------------------------------------------------------------- /tests/netd_integration_test.cpp: -------------------------------------------------------------------------------- 1 | // This file currently exists only so we can do: 2 | // runtest -x system/netd/tests/netd_integration_test.cpp 3 | -------------------------------------------------------------------------------- /server/netd.rc: -------------------------------------------------------------------------------- 1 | service netd /system/bin/netd 2 | class main 3 | socket netd stream 0660 root system 4 | socket dnsproxyd stream 0660 root inet 5 | socket mdns stream 0660 root system 6 | socket fwmarkd stream 0660 root inet 7 | -------------------------------------------------------------------------------- /server/NetdCommand.cpp: -------------------------------------------------------------------------------- 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 "NetdCommand.h" 18 | 19 | NetdCommand::NetdCommand(const char *cmd) : 20 | FrameworkCommand(cmd) { 21 | } 22 | -------------------------------------------------------------------------------- /server/binder/android/net/UidRange.aidl: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 | package android.net; 18 | 19 | /** 20 | * An inclusive range of UIDs. 21 | * 22 | * {@hide} 23 | */ 24 | parcelable UidRange cpp_header "binder/android/net/UidRange.h"; 25 | -------------------------------------------------------------------------------- /server/NetdCommand.h: -------------------------------------------------------------------------------- 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 | #ifndef _NETD_COMMAND_H 18 | #define _NETD_COMMAND_H 19 | 20 | #include 21 | 22 | class NetdCommand : public FrameworkCommand { 23 | public: 24 | NetdCommand(const char *cmd); 25 | virtual ~NetdCommand() {} 26 | }; 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /server/oem_iptables_hook.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _OEM_IPTABLES_HOOK_H 18 | #define _OEM_IPTABLES_HOOK_H 19 | 20 | #define OEM_IPTABLES_FILTER_OUTPUT "oem_out" 21 | #define OEM_IPTABLES_FILTER_FORWARD "oem_fwd" 22 | #define OEM_IPTABLES_NAT_PREROUTING "oem_nat_pre" 23 | 24 | void setupOemIptablesHook(); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /server/Controllers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 "Controllers.h" 18 | 19 | namespace android { 20 | namespace net { 21 | 22 | Controllers::Controllers() : clatdCtrl(&netCtrl) { 23 | InterfaceController::initializeAll(); 24 | } 25 | 26 | Controllers* gCtls = nullptr; 27 | 28 | } // namespace net 29 | } // namespace android 30 | -------------------------------------------------------------------------------- /client/Android.mk: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2014 The Android Open Source Project 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | LOCAL_PATH := $(call my-dir) 16 | 17 | include $(CLEAR_VARS) 18 | 19 | LOCAL_C_INCLUDES := bionic/libc/dns/include system/netd/include 20 | LOCAL_CLANG := true 21 | LOCAL_CPPFLAGS := -std=c++11 -Wall -Werror 22 | LOCAL_MODULE := libnetd_client 23 | LOCAL_SRC_FILES := FwmarkClient.cpp NetdClient.cpp 24 | 25 | include $(BUILD_SHARED_LIBRARY) 26 | -------------------------------------------------------------------------------- /server/binder/android/net/metrics/IDnsEventListener.aidl: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2016, 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 | package android.net.metrics; 18 | 19 | /** 20 | * Logs DNS lookups. 21 | * 22 | * {@hide} 23 | */ 24 | oneway interface IDnsEventListener { 25 | const int EVENT_GETADDRINFO = 1; 26 | const int EVENT_GETHOSTBYNAME = 2; 27 | 28 | // Logs a single DNS lookup. 29 | void onDnsEvent(int netId, int eventType, int returnCode, int latencyMs); 30 | } 31 | -------------------------------------------------------------------------------- /server/ConnmarkFlags.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2015 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 | #ifndef _CONNMARK_FLAGS_H 18 | #define _CONNMARK_FLAGS_H 19 | 20 | /* 21 | * iptables CONNMARK flag values used by various controllers. These values 22 | * need to be stored in one place to avoid clashes. 23 | */ 24 | class ConnmarkFlags { 25 | public: 26 | static const unsigned int STRICT_RESOLVED_ACCEPT = 0x01000000; 27 | static const unsigned int STRICT_RESOLVED_REJECT = 0x02000000; 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /server/LocalNetwork.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_LOCAL_NETWORK_H 18 | #define NETD_SERVER_LOCAL_NETWORK_H 19 | 20 | #include "Network.h" 21 | 22 | class LocalNetwork : public Network { 23 | public: 24 | explicit LocalNetwork(unsigned netId); 25 | virtual ~LocalNetwork(); 26 | 27 | private: 28 | Type getType() const override; 29 | int addInterface(const std::string& interface) override WARN_UNUSED_RESULT; 30 | int removeInterface(const std::string& interface) override WARN_UNUSED_RESULT; 31 | }; 32 | 33 | #endif // NETD_SERVER_LOCAL_NETWORK_H 34 | -------------------------------------------------------------------------------- /server/DumpWriter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 | #ifndef NETD_SERVER_DUMPWRITER_H_ 18 | #define NETD_SERVER_DUMPWRITER_H_ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | 25 | class DumpWriter { 26 | public: 27 | DumpWriter(int fd); 28 | 29 | void incIndent(); 30 | void decIndent(); 31 | 32 | void println(const std::string& line); 33 | void println(const char* fmt, ...); 34 | void blankline() { println(""); } 35 | 36 | private: 37 | uint8_t mIndentLevel; 38 | int mFd; 39 | }; 40 | 41 | #endif // NETD_SERVER_DUMPWRITER_H_ 42 | -------------------------------------------------------------------------------- /server/DummyNetwork.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_DUMMY_NETWORK_H 18 | #define NETD_SERVER_DUMMY_NETWORK_H 19 | 20 | #include "Network.h" 21 | 22 | class DummyNetwork : public Network { 23 | public: 24 | static const char* INTERFACE_NAME; 25 | explicit DummyNetwork(unsigned netId); 26 | virtual ~DummyNetwork(); 27 | 28 | private: 29 | Type getType() const override; 30 | int addInterface(const std::string& interface) override WARN_UNUSED_RESULT; 31 | int removeInterface(const std::string& interface) override WARN_UNUSED_RESULT; 32 | }; 33 | 34 | #endif // NETD_SERVER_DUMMY_NETWORK_H 35 | -------------------------------------------------------------------------------- /server/ClatdController.h: -------------------------------------------------------------------------------- 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 | #ifndef _CLATD_CONTROLLER_H 18 | #define _CLATD_CONTROLLER_H 19 | 20 | #include 21 | 22 | class NetworkController; 23 | 24 | class ClatdController { 25 | public: 26 | explicit ClatdController(NetworkController* controller); 27 | virtual ~ClatdController(); 28 | 29 | int startClatd(char *interface); 30 | int stopClatd(char* interface); 31 | bool isClatdStarted(char* interface); 32 | 33 | private: 34 | NetworkController* const mNetCtrl; 35 | std::map mClatdPids; 36 | pid_t getClatdPid(char* interface); 37 | }; 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /include/Fwmark.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_INCLUDE_FWMARK_H 18 | #define NETD_INCLUDE_FWMARK_H 19 | 20 | #include "Permission.h" 21 | 22 | #include 23 | 24 | union Fwmark { 25 | uint32_t intValue; 26 | struct { 27 | unsigned netId : 16; 28 | bool explicitlySelected : 1; 29 | bool protectedFromVpn : 1; 30 | Permission permission : 2; 31 | }; 32 | Fwmark() : intValue(0) {} 33 | }; 34 | 35 | static const unsigned FWMARK_NET_ID_MASK = 0xffff; 36 | 37 | static_assert(sizeof(Fwmark) == sizeof(uint32_t), "The entire fwmark must fit into 32 bits"); 38 | 39 | #endif // NETD_INCLUDE_FWMARK_H 40 | -------------------------------------------------------------------------------- /server/FwmarkServer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_FWMARK_SERVER_H 18 | #define NETD_SERVER_FWMARK_SERVER_H 19 | 20 | #include "sysutils/SocketListener.h" 21 | 22 | class NetworkController; 23 | 24 | class FwmarkServer : public SocketListener { 25 | public: 26 | explicit FwmarkServer(NetworkController* networkController); 27 | 28 | private: 29 | // Overridden from SocketListener: 30 | bool onDataAvailable(SocketClient* client); 31 | 32 | // Returns 0 on success or a negative errno value on failure. 33 | int processClient(SocketClient* client, int* socketFd); 34 | 35 | NetworkController* const mNetworkController; 36 | }; 37 | 38 | #endif // NETD_SERVER_FWMARK_SERVER_H 39 | -------------------------------------------------------------------------------- /server/DummyNetwork.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "DummyNetwork.h" 18 | 19 | #include "RouteController.h" 20 | 21 | #define LOG_TAG "Netd" 22 | #include "log/log.h" 23 | #include "errno.h" 24 | 25 | const char* DummyNetwork::INTERFACE_NAME = "dummy0"; 26 | 27 | DummyNetwork::DummyNetwork(unsigned netId) : Network(netId) { 28 | mInterfaces.insert(INTERFACE_NAME); 29 | } 30 | 31 | DummyNetwork::~DummyNetwork() { 32 | } 33 | 34 | Network::Type DummyNetwork::getType() const { 35 | return DUMMY; 36 | } 37 | 38 | int DummyNetwork::addInterface(const std::string& /* interface */) { 39 | return -EINVAL; 40 | } 41 | 42 | int DummyNetwork::removeInterface(const std::string& /* interface */) { 43 | return -EINVAL; 44 | } 45 | -------------------------------------------------------------------------------- /server/PppController.h: -------------------------------------------------------------------------------- 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 | #ifndef _PPP_CONTROLLER_H 18 | #define _PPP_CONTROLLER_H 19 | 20 | #include 21 | 22 | #include 23 | 24 | typedef std::list TtyCollection; 25 | 26 | class PppController { 27 | TtyCollection *mTtys; 28 | pid_t mPid; // TODO: Add support for > 1 pppd instance 29 | 30 | public: 31 | PppController(); 32 | virtual ~PppController(); 33 | 34 | int attachPppd(const char *tty, struct in_addr local, 35 | struct in_addr remote, struct in_addr dns1, 36 | struct in_addr dns2); 37 | int detachPppd(const char *tty); 38 | TtyCollection *getTtyList(); 39 | 40 | private: 41 | int updateTtyList(); 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /include/FwmarkCommand.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_INCLUDE_FWMARK_COMMAND_H 18 | #define NETD_INCLUDE_FWMARK_COMMAND_H 19 | 20 | #include 21 | 22 | // Commands sent from clients to the fwmark server to mark sockets (i.e., set their SO_MARK). 23 | struct FwmarkCommand { 24 | enum { 25 | ON_ACCEPT, 26 | ON_CONNECT, 27 | SELECT_NETWORK, 28 | PROTECT_FROM_VPN, 29 | SELECT_FOR_USER, 30 | QUERY_USER_ACCESS, 31 | } cmdId; 32 | unsigned netId; // used only in the SELECT_NETWORK command; ignored otherwise. 33 | uid_t uid; // used only in the SELECT_FOR_USER and QUERY_USER_ACCESS commands; 34 | // ignored otherwise. 35 | }; 36 | 37 | #endif // NETD_INCLUDE_FWMARK_COMMAND_H 38 | -------------------------------------------------------------------------------- /client/FwmarkClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_CLIENT_FWMARK_CLIENT_H 18 | #define NETD_CLIENT_FWMARK_CLIENT_H 19 | 20 | #include 21 | 22 | struct FwmarkCommand; 23 | 24 | class FwmarkClient { 25 | public: 26 | // Returns true if a socket of the given |family| should be sent to the fwmark server to have 27 | // its SO_MARK set. 28 | static bool shouldSetFwmark(int family); 29 | 30 | FwmarkClient(); 31 | ~FwmarkClient(); 32 | 33 | // Sends |data| to the fwmark server, along with |fd| as ancillary data using cmsg(3). 34 | // Returns 0 on success or a negative errno value on failure. 35 | int send(FwmarkCommand* data, int fd); 36 | 37 | private: 38 | int mChannel; 39 | }; 40 | 41 | #endif // NETD_CLIENT_FWMARK_CLIENT_H 42 | -------------------------------------------------------------------------------- /include/NetdClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_INCLUDE_NETD_CLIENT_H 18 | #define NETD_INCLUDE_NETD_CLIENT_H 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | __BEGIN_DECLS 25 | 26 | // All functions below that return an int return 0 on success or a negative errno value on failure. 27 | 28 | int getNetworkForSocket(unsigned* netId, int socketFd); 29 | int setNetworkForSocket(unsigned netId, int socketFd); 30 | 31 | unsigned getNetworkForProcess(void); 32 | int setNetworkForProcess(unsigned netId); 33 | 34 | int setNetworkForResolv(unsigned netId); 35 | 36 | int protectFromVpn(int socketFd); 37 | 38 | int setNetworkForUser(uid_t uid, int socketFd); 39 | 40 | int queryUserAccess(uid_t uid, unsigned netId); 41 | 42 | __END_DECLS 43 | 44 | #endif // NETD_INCLUDE_NETD_CLIENT_H 45 | -------------------------------------------------------------------------------- /server/UidRanges.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_UID_RANGES_H 18 | #define NETD_SERVER_UID_RANGES_H 19 | 20 | #include "android/net/UidRange.h" 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | class UidRanges { 27 | public: 28 | // TODO: replace with AIDL type: android::net::UidRange 29 | // int32_t may not be a safe replacement for uid_t. If not, UidRange will need to change to use 30 | // a larger type first. 31 | typedef std::pair Range; 32 | 33 | UidRanges() {} 34 | UidRanges(const std::vector& ranges); 35 | 36 | bool hasUid(uid_t uid) const; 37 | const std::vector& getRanges() const; 38 | 39 | bool parseFrom(int argc, char* argv[]); 40 | std::string toString() const; 41 | 42 | void add(const UidRanges& other); 43 | void remove(const UidRanges& other); 44 | 45 | private: 46 | std::vector mRanges; 47 | }; 48 | 49 | #endif // NETD_SERVER_UID_RANGES_H 50 | -------------------------------------------------------------------------------- /server/IdletimerController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _IDLETIMER_CONTROLLER_H 17 | #define _IDLETIMER_CONTROLLER_H 18 | 19 | class IdletimerController { 20 | public: 21 | 22 | IdletimerController(); 23 | virtual ~IdletimerController(); 24 | 25 | int enableIdletimerControl(); 26 | int disableIdletimerControl(); 27 | int addInterfaceIdletimer(const char *iface, uint32_t timeout, 28 | const char *classLabel); 29 | int removeInterfaceIdletimer(const char *iface, uint32_t timeout, 30 | const char *classLabel); 31 | bool setupIptablesHooks(); 32 | 33 | static const char* LOCAL_RAW_PREROUTING; 34 | static const char* LOCAL_MANGLE_POSTROUTING; 35 | 36 | private: 37 | enum IptOp { IptOpAdd, IptOpDelete }; 38 | int setDefaults(); 39 | int runIpxtablesCmd(int argc, const char **cmd); 40 | int modifyInterfaceIdletimer(IptOp op, const char *iface, uint32_t timeout, 41 | const char *classLabel); 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /server/StrictController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _STRICT_CONTROLLER_H 18 | #define _STRICT_CONTROLLER_H 19 | 20 | #include 21 | 22 | #include "NetdConstants.h" 23 | 24 | enum StrictPenalty { INVALID, ACCEPT, LOG, REJECT }; 25 | 26 | /* 27 | * Help apps catch unwanted low-level networking behavior, like 28 | * connections not wrapped in TLS. 29 | */ 30 | class StrictController { 31 | public: 32 | StrictController(); 33 | 34 | int enableStrict(void); 35 | int disableStrict(void); 36 | 37 | int setUidCleartextPenalty(uid_t, StrictPenalty); 38 | 39 | static const char* LOCAL_OUTPUT; 40 | static const char* LOCAL_CLEAR_DETECT; 41 | static const char* LOCAL_CLEAR_CAUGHT; 42 | static const char* LOCAL_PENALTY_LOG; 43 | static const char* LOCAL_PENALTY_REJECT; 44 | 45 | protected: 46 | // For testing. 47 | friend class StrictControllerTest; 48 | static int (*execIptables)(IptablesTarget target, ...); 49 | static int (*execIptablesRestore)(IptablesTarget target, const std::string& commands); 50 | }; 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /tests/Android.mk: -------------------------------------------------------------------------------- 1 | # 2 | # Copyright (C) 2016 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 | LOCAL_PATH := $(call my-dir) 17 | 18 | # APCT build target 19 | include $(CLEAR_VARS) 20 | LOCAL_MODULE := netd_integration_test 21 | LOCAL_CFLAGS := -Wall -Werror -Wunused-parameter 22 | EXTRA_LDLIBS := -lpthread 23 | LOCAL_SHARED_LIBRARIES += libbase libbinder libcutils liblog liblogwrap libnetdaidl libnetd_client \ 24 | libnetutils libutils 25 | LOCAL_STATIC_LIBRARIES += libtestUtil 26 | LOCAL_AIDL_INCLUDES := system/netd/server/binder 27 | LOCAL_C_INCLUDES += system/netd/include system/extras/tests/include system/netd/binder/include \ 28 | system/netd/server system/core/logwrapper/include \ 29 | system/core/libnetutils/include \ 30 | system/extras/tests/include bionic/libc/dns/include 31 | # netd_integration_test.cpp is currently empty and exists only so that we can do: 32 | # runtest -x system/netd/tests/netd_integration_test.cpp 33 | LOCAL_SRC_FILES := binder_test.cpp \ 34 | dns_responder.cpp \ 35 | netd_integration_test.cpp \ 36 | netd_test.cpp \ 37 | ../server/NetdConstants.cpp 38 | LOCAL_MODULE_TAGS := eng tests 39 | include $(BUILD_NATIVE_TEST) 40 | -------------------------------------------------------------------------------- /server/Controllers.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 | #ifndef _CONTROLLERS_H__ 18 | #define _CONTROLLERS_H__ 19 | 20 | #include 21 | 22 | #include "NetworkController.h" 23 | #include "TetherController.h" 24 | #include "NatController.h" 25 | #include "PppController.h" 26 | #include "SoftapController.h" 27 | #include "BandwidthController.h" 28 | #include "IdletimerController.h" 29 | #include "InterfaceController.h" 30 | #include "ResolverController.h" 31 | #include "FirewallController.h" 32 | #include "ClatdController.h" 33 | #include "StrictController.h" 34 | 35 | namespace android { 36 | namespace net { 37 | 38 | struct Controllers { 39 | Controllers(); 40 | 41 | NetworkController netCtrl; 42 | TetherController tetherCtrl; 43 | NatController natCtrl; 44 | PppController pppCtrl; 45 | SoftapController softapCtrl; 46 | BandwidthController bandwidthCtrl; 47 | IdletimerController idletimerCtrl; 48 | ResolverController resolverCtrl; 49 | FirewallController firewallCtrl; 50 | ClatdController clatdCtrl; 51 | StrictController strictCtrl; 52 | }; 53 | 54 | extern Controllers* gCtls; 55 | 56 | } // namespace net 57 | } // namespace android 58 | 59 | #endif // _CONTROLLERS_H__ 60 | -------------------------------------------------------------------------------- /server/DumpWriter.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 "DumpWriter.h" 18 | 19 | #include 20 | #include 21 | 22 | using android::base::StringAppendV; 23 | using android::String16; 24 | using android::Vector; 25 | 26 | namespace { 27 | 28 | const char kIndentString[] = " "; 29 | const size_t kIndentStringLen = strlen(kIndentString); 30 | 31 | } // namespace 32 | 33 | 34 | DumpWriter::DumpWriter(int fd) : mIndentLevel(0), mFd(fd) {} 35 | 36 | void DumpWriter::incIndent() { 37 | if (mIndentLevel < 255) { 38 | mIndentLevel++; 39 | } 40 | } 41 | 42 | void DumpWriter::decIndent() { 43 | if (mIndentLevel > 0) { 44 | mIndentLevel--; 45 | } 46 | } 47 | 48 | void DumpWriter::println(const std::string& line) { 49 | if (!line.empty()) { 50 | for (int i = 0; i < mIndentLevel; i++) { 51 | write(mFd, kIndentString, kIndentStringLen); 52 | } 53 | write(mFd, line.c_str(), line.size()); 54 | } 55 | write(mFd, "\n", 1); 56 | } 57 | 58 | void DumpWriter::println(const char* fmt, ...) { 59 | std::string line; 60 | va_list ap; 61 | va_start(ap, fmt); 62 | StringAppendV(&line, fmt, ap); 63 | va_end(ap); 64 | println(line); 65 | } 66 | -------------------------------------------------------------------------------- /server/LocalNetwork.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "LocalNetwork.h" 18 | 19 | #include "RouteController.h" 20 | 21 | #define LOG_TAG "Netd" 22 | #include "log/log.h" 23 | 24 | LocalNetwork::LocalNetwork(unsigned netId) : Network(netId) { 25 | } 26 | 27 | LocalNetwork::~LocalNetwork() { 28 | } 29 | 30 | Network::Type LocalNetwork::getType() const { 31 | return LOCAL; 32 | } 33 | 34 | int LocalNetwork::addInterface(const std::string& interface) { 35 | if (hasInterface(interface)) { 36 | return 0; 37 | } 38 | if (int ret = RouteController::addInterfaceToLocalNetwork(mNetId, interface.c_str())) { 39 | ALOGE("failed to add interface %s to local netId %u", interface.c_str(), mNetId); 40 | return ret; 41 | } 42 | mInterfaces.insert(interface); 43 | return 0; 44 | } 45 | 46 | int LocalNetwork::removeInterface(const std::string& interface) { 47 | if (!hasInterface(interface)) { 48 | return 0; 49 | } 50 | if (int ret = RouteController::removeInterfaceFromLocalNetwork(mNetId, interface.c_str())) { 51 | ALOGE("failed to remove interface %s from local netId %u", interface.c_str(), mNetId); 52 | return ret; 53 | } 54 | mInterfaces.erase(interface); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /server/SoftapController.h: -------------------------------------------------------------------------------- 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 | #ifndef _SOFTAP_CONTROLLER_H 18 | #define _SOFTAP_CONTROLLER_H 19 | 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | 26 | #define SOFTAP_MAX_BUFFER_SIZE 4096 27 | #define AP_BSS_START_DELAY 200000 28 | #define AP_BSS_STOP_DELAY 500000 29 | #define AP_SET_CFG_DELAY 500000 30 | #define AP_DRIVER_START_DELAY 800000 31 | #define AP_CHANNEL_DEFAULT 6 32 | 33 | class SoftapController { 34 | public: 35 | SoftapController(); 36 | virtual ~SoftapController(); 37 | 38 | #ifdef LIBWPA_CLIENT_EXISTS 39 | int startSoftap(bool global_ctrl_iface, SocketClient *socketClient); 40 | #else 41 | int startSoftap(bool global_ctrl_iface = false); 42 | #endif 43 | int stopSoftap(); 44 | bool isSoftapStarted(); 45 | int setSoftap(int argc, char *argv[]); 46 | int fwReloadSoftap(int argc, char *argv[]); 47 | private: 48 | #ifdef LIBWPA_CLIENT_EXISTS 49 | pthread_t mThread; 50 | int mThreadErr; 51 | bool mHostapdFlag; 52 | SocketClient *mSocketClient; 53 | #endif 54 | pid_t mPid; 55 | bool generatePsk(char *ssid, char *passphrase, char *psk); 56 | #ifdef LIBWPA_CLIENT_EXISTS 57 | static void *threadStart(void *obj); 58 | #endif 59 | }; 60 | 61 | #endif 62 | -------------------------------------------------------------------------------- /server/NatController.h: -------------------------------------------------------------------------------- 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 | #ifndef _NAT_CONTROLLER_H 18 | #define _NAT_CONTROLLER_H 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | class NatController { 25 | public: 26 | NatController(); 27 | virtual ~NatController(); 28 | 29 | int enableNat(const char* intIface, const char* extIface); 30 | int disableNat(const char* intIface, const char* extIface); 31 | int setupIptablesHooks(); 32 | 33 | static const char* LOCAL_FORWARD; 34 | static const char* LOCAL_MANGLE_FORWARD; 35 | static const char* LOCAL_NAT_POSTROUTING; 36 | static const char* LOCAL_RAW_PREROUTING; 37 | static const char* LOCAL_TETHER_COUNTERS_CHAIN; 38 | 39 | // List of strings of interface pairs. 40 | std::list ifacePairList; 41 | 42 | private: 43 | int natCount; 44 | 45 | bool checkTetherCountingRuleExist(const char *pair_name); 46 | 47 | int setDefaults(); 48 | int runCmd(int argc, const char **argv); 49 | int setForwardRules(bool set, const char *intIface, const char *extIface); 50 | int setTetherCountingRules(bool add, const char *intIface, const char *extIface); 51 | 52 | // For testing. 53 | friend class NatControllerTest; 54 | static int (*execFunction)(int, char **, int *, bool, bool); 55 | }; 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /server/NetlinkManager.h: -------------------------------------------------------------------------------- 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 | #ifndef _NETLINKMANAGER_H 18 | #define _NETLINKMANAGER_H 19 | 20 | #include 21 | #include 22 | 23 | 24 | class NetlinkHandler; 25 | 26 | class NetlinkManager { 27 | private: 28 | static NetlinkManager *sInstance; 29 | 30 | private: 31 | SocketListener *mBroadcaster; 32 | NetlinkHandler *mUeventHandler; 33 | NetlinkHandler *mRouteHandler; 34 | NetlinkHandler *mQuotaHandler; 35 | NetlinkHandler *mStrictHandler; 36 | int mUeventSock; 37 | int mRouteSock; 38 | int mQuotaSock; 39 | int mStrictSock; 40 | 41 | public: 42 | virtual ~NetlinkManager(); 43 | 44 | int start(); 45 | int stop(); 46 | 47 | void setBroadcaster(SocketListener *sl) { mBroadcaster = sl; } 48 | SocketListener *getBroadcaster() { return mBroadcaster; } 49 | 50 | static NetlinkManager *Instance(); 51 | 52 | /* Group used by xt_quota2 */ 53 | static const int NFLOG_QUOTA_GROUP; 54 | /* Group used by StrictController rules */ 55 | static const int NETFILTER_STRICT_GROUP; 56 | 57 | private: 58 | NetlinkManager(); 59 | NetlinkHandler* setupSocket(int *sock, int netlinkFamily, int groups, 60 | int format, bool configNflog); 61 | }; 62 | #endif 63 | -------------------------------------------------------------------------------- /server/QtiDataController.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015-16, The Linux Foundation. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following 11 | disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | * Neither the name of The Linux Foundation nor the names of its 14 | contributors may be used to endorse or promote products derived 15 | from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED 18 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 19 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 20 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 21 | BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 24 | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 25 | WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 26 | OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN 27 | IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | * 29 | */ 30 | 31 | #ifndef _QTI_DATA_CONTROLLER_H 32 | #define _QTI_DATA_CONTROLLER_H 33 | 34 | #include 35 | 36 | #define NETID_INVALID UINT_MAX 37 | 38 | void initializeDataControllerLib(); 39 | int blockAllData(); 40 | int unblockAllData(); 41 | unsigned checkAppInWhitelist(SocketClient *cli); 42 | 43 | bool enableMms(char* uids); 44 | bool enableData(char* uids); 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /server/IptablesBaseTest.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 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 | * IptablesBaseTest.h - utility class for tests that use iptables 17 | */ 18 | 19 | #include 20 | 21 | #include "NetdConstants.h" 22 | 23 | class IptablesBaseTest : public ::testing::Test { 24 | public: 25 | IptablesBaseTest(); 26 | 27 | typedef std::vector> ExpectedIptablesCommands; 28 | 29 | static int fake_android_fork_exec(int argc, char* argv[], int *status, bool, bool); 30 | static int fake_android_fork_execvp(int argc, char* argv[], int *status, bool, bool); 31 | static int fakeExecIptables(IptablesTarget target, ...); 32 | static int fakeExecIptablesRestore(IptablesTarget target, const std::string& commands); 33 | static FILE *fake_popen(const char *cmd, const char *type); 34 | void expectIptablesCommands(const std::vector& expectedCmds); 35 | void expectIptablesCommands(const ExpectedIptablesCommands& expectedCmds); 36 | void expectIptablesCommands(const std::vector& snippets); 37 | void expectIptablesRestoreCommands(const std::vector& expectedCmds); 38 | void expectIptablesRestoreCommands(const ExpectedIptablesCommands& expectedCmds); 39 | 40 | protected: 41 | static std::vector sCmds; 42 | static ExpectedIptablesCommands sRestoreCmds; 43 | static std::deque sPopenContents; 44 | int expectIptablesCommand(IptablesTarget target, int pos, const std::string& cmd); 45 | }; 46 | -------------------------------------------------------------------------------- /server/Network.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_NETWORK_H 18 | #define NETD_SERVER_NETWORK_H 19 | 20 | #include "NetdConstants.h" 21 | 22 | #include 23 | #include 24 | 25 | // A Network represents a collection of interfaces participating as a single administrative unit. 26 | class Network { 27 | public: 28 | enum Type { 29 | DUMMY, 30 | LOCAL, 31 | PHYSICAL, 32 | VIRTUAL, 33 | }; 34 | 35 | // You MUST ensure that no interfaces are still assigned to this network, say by calling 36 | // clearInterfaces(), before deleting it. This is because interface removal may fail. If we 37 | // automatically removed interfaces in the destructor, you wouldn't know if it failed. 38 | virtual ~Network(); 39 | 40 | virtual Type getType() const = 0; 41 | unsigned getNetId() const; 42 | 43 | bool hasInterface(const std::string& interface) const; 44 | const std::set& getInterfaces() const; 45 | 46 | // These return 0 on success or negative errno on failure. 47 | virtual int addInterface(const std::string& interface) WARN_UNUSED_RESULT = 0; 48 | virtual int removeInterface(const std::string& interface) WARN_UNUSED_RESULT = 0; 49 | int clearInterfaces() WARN_UNUSED_RESULT; 50 | 51 | std::string toString() const; 52 | 53 | protected: 54 | explicit Network(unsigned netId); 55 | 56 | const unsigned mNetId; 57 | std::set mInterfaces; 58 | }; 59 | 60 | #endif // NETD_SERVER_NETWORK_H 61 | -------------------------------------------------------------------------------- /server/PhysicalNetwork.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_PHYSICAL_NETWORK_H 18 | #define NETD_SERVER_PHYSICAL_NETWORK_H 19 | 20 | #include "Network.h" 21 | #include "Permission.h" 22 | 23 | class PhysicalNetwork : public Network { 24 | public: 25 | class Delegate { 26 | public: 27 | virtual ~Delegate(); 28 | 29 | virtual int addFallthrough(const std::string& physicalInterface, 30 | Permission permission) WARN_UNUSED_RESULT = 0; 31 | virtual int removeFallthrough(const std::string& physicalInterface, 32 | Permission permission) WARN_UNUSED_RESULT = 0; 33 | }; 34 | 35 | PhysicalNetwork(unsigned netId, Delegate* delegate); 36 | virtual ~PhysicalNetwork(); 37 | 38 | // These refer to permissions that apps must have in order to use this network. 39 | Permission getPermission() const; 40 | int setPermission(Permission permission) WARN_UNUSED_RESULT; 41 | 42 | int addAsDefault() WARN_UNUSED_RESULT; 43 | int removeAsDefault() WARN_UNUSED_RESULT; 44 | 45 | private: 46 | Type getType() const override; 47 | int addInterface(const std::string& interface) override WARN_UNUSED_RESULT; 48 | int removeInterface(const std::string& interface) override WARN_UNUSED_RESULT; 49 | int destroySocketsLackingPermission(Permission permission); 50 | 51 | Delegate* const mDelegate; 52 | Permission mPermission; 53 | bool mIsDefault; 54 | }; 55 | 56 | #endif // NETD_SERVER_PHYSICAL_NETWORK_H 57 | -------------------------------------------------------------------------------- /server/TetherController.h: -------------------------------------------------------------------------------- 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 | #ifndef _TETHER_CONTROLLER_H 18 | #define _TETHER_CONTROLLER_H 19 | 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | 27 | class TetherController { 28 | private: 29 | std::list mInterfaces; 30 | // NetId to use for forwarded DNS queries. This may not be the default 31 | // network, e.g., in the case where we are tethering to a DUN APN. 32 | unsigned mDnsNetId; 33 | std::list mDnsForwarders; 34 | pid_t mDaemonPid; 35 | int mDaemonFd; 36 | std::set mForwardingRequests; 37 | 38 | public: 39 | TetherController(); 40 | virtual ~TetherController(); 41 | 42 | bool enableForwarding(const char* requester); 43 | bool disableForwarding(const char* requester); 44 | size_t forwardingRequestCount(); 45 | 46 | int startTethering(int num_addrs, char **dhcp_ranges); 47 | int stopTethering(); 48 | bool isTetheringStarted(); 49 | 50 | unsigned getDnsNetId(); 51 | int setDnsForwarders(unsigned netId, char **servers, int numServers); 52 | const std::list &getDnsForwarders() const; 53 | 54 | int tetherInterface(const char *interface); 55 | int untetherInterface(const char *interface); 56 | const std::list &getTetheredInterfaceList() const; 57 | bool applyDnsInterfaces(); 58 | 59 | private: 60 | bool setIpFwdEnabled(); 61 | }; 62 | 63 | #endif 64 | -------------------------------------------------------------------------------- /server/NetlinkHandler.h: -------------------------------------------------------------------------------- 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 | #ifndef _NETLINKHANDLER_H 18 | #define _NETLINKHANDLER_H 19 | 20 | #include 21 | #include 22 | #include "NetlinkManager.h" 23 | 24 | class NetlinkHandler: public NetlinkListener { 25 | NetlinkManager *mNm; 26 | 27 | public: 28 | NetlinkHandler(NetlinkManager *nm, int listenerSocket, int format); 29 | virtual ~NetlinkHandler(); 30 | 31 | int start(void); 32 | int stop(void); 33 | 34 | protected: 35 | virtual void onEvent(NetlinkEvent *evt); 36 | 37 | void notify(int code, const char *format, ...); 38 | void notifyInterfaceAdded(const char *name); 39 | void notifyInterfaceRemoved(const char *name); 40 | void notifyInterfaceChanged(const char *name, bool isUp); 41 | void notifyInterfaceLinkChanged(const char *name, bool isUp); 42 | void notifyQuotaLimitReached(const char *name, const char *iface); 43 | void notifyInterfaceClassActivity(const char *name, bool isActive, 44 | const char *timestamp, const char *uid); 45 | void notifyAddressChanged(NetlinkEvent::Action action, const char *addr, const char *iface, 46 | const char *flags, const char *scope); 47 | void notifyInterfaceDnsServers(const char *iface, const char *lifetime, 48 | const char *servers); 49 | void notifyRouteChange(NetlinkEvent::Action action, const char *route, const char *gateway, const char *iface); 50 | void notifyStrictCleartext(const char* uid, const char* hex); 51 | }; 52 | #endif 53 | -------------------------------------------------------------------------------- /server/binder/android/net/UidRange.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 | #ifndef NETD_SERVER_ANDROID_NET_UID_RANGE_H 18 | #define NETD_SERVER_ANDROID_NET_UID_RANGE_H 19 | 20 | #include 21 | 22 | namespace android { 23 | 24 | namespace net { 25 | 26 | /* 27 | * C++ implementation of UidRange, a contiguous range of UIDs. 28 | */ 29 | class UidRange : public Parcelable { 30 | public: 31 | UidRange() = default; 32 | virtual ~UidRange() = default; 33 | UidRange(const UidRange& range) = default; 34 | UidRange(int32_t start, int32_t stop); 35 | 36 | status_t writeToParcel(Parcel* parcel) const override; 37 | status_t readFromParcel(const Parcel* parcel) override; 38 | 39 | /* 40 | * Setters for UidRange start and stop UIDs. 41 | */ 42 | void setStart(int32_t uid); 43 | void setStop(int32_t uid); 44 | 45 | /* 46 | * Getters for UidRange start and stop UIDs. 47 | */ 48 | int32_t getStart() const; 49 | int32_t getStop() const; 50 | 51 | friend bool operator<(const UidRange& lhs, const UidRange& rhs) { 52 | return lhs.mStart != rhs.mStart ? (lhs.mStart < rhs.mStart) : (lhs.mStop < rhs.mStop); 53 | } 54 | 55 | friend bool operator==(const UidRange& lhs, const UidRange& rhs) { 56 | return (lhs.mStart == rhs.mStart && lhs.mStop == rhs.mStop); 57 | } 58 | 59 | friend bool operator!=(const UidRange& lhs, const UidRange& rhs) { 60 | return !(lhs == rhs); 61 | } 62 | 63 | private: 64 | int32_t mStart = -1; 65 | int32_t mStop = -1; 66 | }; 67 | 68 | } // namespace net 69 | 70 | } // namespace android 71 | 72 | #endif // NETD_SERVER_ANDROID_NET_UID_RANGE_H 73 | -------------------------------------------------------------------------------- /server/VirtualNetwork.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_VIRTUAL_NETWORK_H 18 | #define NETD_SERVER_VIRTUAL_NETWORK_H 19 | 20 | #include 21 | 22 | #include "Network.h" 23 | #include "UidRanges.h" 24 | 25 | // A VirtualNetwork may be "secure" or not. 26 | // 27 | // A secure VPN is the usual type of VPN that grabs the default route (and thus all user traffic). 28 | // Only a few privileged UIDs may skip the VPN and go directly to the underlying physical network. 29 | // 30 | // A non-secure VPN ("bypassable" VPN) also grabs all user traffic by default. But all apps are 31 | // permitted to skip it and pick any other network for their connections. 32 | class VirtualNetwork : public Network { 33 | public: 34 | VirtualNetwork(unsigned netId, bool hasDns, bool secure); 35 | virtual ~VirtualNetwork(); 36 | 37 | bool getHasDns() const; 38 | bool isSecure() const; 39 | bool appliesToUser(uid_t uid) const; 40 | 41 | int addUsers(const UidRanges& uidRanges, 42 | const std::set& protectableUsers) WARN_UNUSED_RESULT; 43 | int removeUsers(const UidRanges& uidRanges, 44 | const std::set& protectableUsers) WARN_UNUSED_RESULT; 45 | 46 | private: 47 | Type getType() const override; 48 | int addInterface(const std::string& interface) override WARN_UNUSED_RESULT; 49 | int removeInterface(const std::string& interface) override WARN_UNUSED_RESULT; 50 | int maybeCloseSockets(bool add, const UidRanges& uidRanges, 51 | const std::set& protectableUsers); 52 | 53 | const bool mHasDns; 54 | const bool mSecure; 55 | UidRanges mUidRanges; 56 | }; 57 | 58 | #endif // NETD_SERVER_VIRTUAL_NETWORK_H 59 | -------------------------------------------------------------------------------- /server/ResolverController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 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 | #ifndef _RESOLVER_CONTROLLER_H_ 18 | #define _RESOLVER_CONTROLLER_H_ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | struct __res_params; 25 | class DumpWriter; 26 | 27 | namespace android { 28 | namespace net { 29 | struct ResolverStats; 30 | } // namespace net 31 | } // namespace android 32 | 33 | class ResolverController { 34 | public: 35 | ResolverController() {}; 36 | 37 | virtual ~ResolverController() {}; 38 | 39 | // TODO: delete this function 40 | int setDnsServers(unsigned netId, const char* searchDomains, const char** servers, 41 | int numservers, const __res_params* params); 42 | 43 | int clearDnsServers(unsigned netid); 44 | 45 | int flushDnsCache(unsigned netid); 46 | 47 | int getDnsInfo(unsigned netId, std::vector* servers, 48 | std::vector* domains, __res_params* params, 49 | std::vector* stats); 50 | 51 | // Binder specific functions, which convert between the binder int/string arrays and the 52 | // actual data structures, and call setDnsServer() / getDnsInfo() for the actual processing. 53 | int setResolverConfiguration(int32_t netId, const std::vector& servers, 54 | const std::vector& domains, const std::vector& params); 55 | 56 | int getResolverInfo(int32_t netId, std::vector* servers, 57 | std::vector* domains, std::vector* params, 58 | std::vector* stats); 59 | void dump(DumpWriter& dw, unsigned netId); 60 | }; 61 | 62 | #endif /* _RESOLVER_CONTROLLER_H_ */ 63 | -------------------------------------------------------------------------------- /server/CleanSpec.mk: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2007 The Android Open Source Project 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # 15 | 16 | # If you don't need to do a full clean build but would like to touch 17 | # a file or delete some intermediate files, add a clean step to the end 18 | # of the list. These steps will only be run once, if they haven't been 19 | # run before. 20 | # 21 | # E.g.: 22 | # $(call add-clean-step, touch -c external/sqlite/sqlite3.h) 23 | # $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/STATIC_LIBRARIES/libz_intermediates) 24 | # 25 | # Always use "touch -c" and "rm -f" or "rm -rf" to gracefully deal with 26 | # files that are missing or have been moved. 27 | # 28 | # Use $(PRODUCT_OUT) to get to the "out/target/product/blah/" directory. 29 | # Use $(OUT_DIR) to refer to the "out" directory. 30 | # 31 | # If you need to re-do something that's already mentioned, just copy 32 | # the command and add it to the bottom of the list. E.g., if a change 33 | # that you made last week required touching a file and a change you 34 | # made today requires touching the same file, just copy the old 35 | # touch step and add it to the end of the list. 36 | # 37 | # ************************************************ 38 | # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST 39 | # ************************************************ 40 | 41 | # For example: 42 | #$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/AndroidTests_intermediates) 43 | #$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/core_intermediates) 44 | #$(call add-clean-step, find $(OUT_DIR) -type f -name "IGTalkSession*" -print0 | xargs -0 rm -f) 45 | #$(call add-clean-step, rm -rf $(PRODUCT_OUT)/data/*) 46 | 47 | # ************************************************ 48 | # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST 49 | # ************************************************ 50 | -------------------------------------------------------------------------------- /server/InterfaceController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _INTERFACE_CONTROLLER_H 18 | #define _INTERFACE_CONTROLLER_H 19 | 20 | #include 21 | 22 | class InterfaceController { 23 | public: 24 | static void initializeAll(); 25 | 26 | static int setEnableIPv6(const char *interface, const int on); 27 | static int setAcceptIPv6Ra(const char *interface, const int on); 28 | static int setAcceptIPv6Dad(const char *interface, const int on); 29 | static int setIPv6DadTransmits(const char *interface, const char *value); 30 | static int setIPv6PrivacyExtensions(const char *interface, const int on); 31 | static int setIPv6NdOffload(char* interface, const int on); 32 | static int setMtu(const char *interface, const char *mtu); 33 | static int addAddress(const char *interface, const char *addrString, int prefixLength); 34 | static int delAddress(const char *interface, const char *addrString, int prefixLength); 35 | 36 | // Read and write values in files of the form: 37 | // /proc/sys/net//// 38 | static int getParameter( 39 | const char *family, const char *which, const char *interface, const char *parameter, 40 | std::string *value); 41 | static int setParameter( 42 | const char *family, const char *which, const char *interface, const char *parameter, 43 | const char *value); 44 | 45 | private: 46 | static void setAcceptRA(const char* value); 47 | static void setAcceptRARouteTable(int tableOrOffset); 48 | static void setBaseReachableTimeMs(unsigned int millis); 49 | static void setIPv6OptimisticMode(const char *value); 50 | 51 | InterfaceController() = delete; 52 | ~InterfaceController() = delete; 53 | }; 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /include/Permission.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_INCLUDE_PERMISSION_H 18 | #define NETD_INCLUDE_PERMISSION_H 19 | 20 | // This enum represents the permissions we care about for networking. When applied to an app, it's 21 | // the permission the app (UID) has been granted. When applied to a network, it's the permission an 22 | // app must hold to be allowed to use the network. PERMISSION_NONE means "no special permission is 23 | // held by the app" or "no special permission is required to use the network". 24 | // 25 | // Permissions are flags that can be OR'ed together to represent combinations of permissions. 26 | // 27 | // PERMISSION_NONE is used for regular networks and apps, such as those that hold the 28 | // android.permission.INTERNET framework permission. 29 | // 30 | // PERMISSION_NETWORK is used for privileged networks and apps that can manipulate or access them, 31 | // such as those that hold the android.permission.CHANGE_NETWORK_STATE framework permission. 32 | // 33 | // PERMISSION_SYSTEM is used for system apps, such as those that are installed on the system 34 | // partition, those that hold the android.permission.CONNECTIVITY_INTERNAL framework permission and 35 | // those whose UID is less than FIRST_APPLICATION_UID. 36 | enum Permission { 37 | PERMISSION_NONE = 0x0, 38 | PERMISSION_NETWORK = 0x1, 39 | PERMISSION_SYSTEM = 0x3, // Includes PERMISSION_NETWORK. 40 | }; 41 | 42 | inline const char *permissionToName(Permission permission) { 43 | switch (permission) { 44 | case PERMISSION_NONE: return "NONE"; 45 | case PERMISSION_NETWORK: return "NETWORK"; 46 | case PERMISSION_SYSTEM: return "SYSTEM"; 47 | // No default statement. We want to see errors of the form: 48 | // "enumeration value 'PERMISSION_SYSTEM' not handled in switch [-Werror,-Wswitch]". 49 | } 50 | } 51 | 52 | #endif // NETD_INCLUDE_PERMISSION_H 53 | -------------------------------------------------------------------------------- /server/Network.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "Network.h" 18 | 19 | #define LOG_TAG "Netd" 20 | #include "log/log.h" 21 | 22 | #include 23 | #include 24 | 25 | Network::~Network() { 26 | if (!mInterfaces.empty()) { 27 | ALOGE("deleting network with netId %u without clearing its interfaces", mNetId); 28 | } 29 | } 30 | 31 | unsigned Network::getNetId() const { 32 | return mNetId; 33 | } 34 | 35 | bool Network::hasInterface(const std::string& interface) const { 36 | return mInterfaces.find(interface) != mInterfaces.end(); 37 | } 38 | 39 | const std::set& Network::getInterfaces() const { 40 | return mInterfaces; 41 | } 42 | 43 | int Network::clearInterfaces() { 44 | while (!mInterfaces.empty()) { 45 | // Make a copy of the string, so removeInterface() doesn't lose its parameter when it 46 | // removes the string from the set. 47 | std::string interface = *mInterfaces.begin(); 48 | if (int ret = removeInterface(interface)) { 49 | return ret; 50 | } 51 | } 52 | return 0; 53 | } 54 | 55 | std::string Network::toString() const { 56 | const char kSeparator[] = " "; 57 | std::stringstream repr; 58 | 59 | repr << mNetId; 60 | 61 | repr << kSeparator; 62 | switch (getType()) { 63 | case DUMMY: 64 | repr << "DUMMY"; 65 | break; 66 | case LOCAL: 67 | repr << "LOCAL"; 68 | break; 69 | case PHYSICAL: 70 | repr << "PHYSICAL"; 71 | break; 72 | case VIRTUAL: 73 | repr << "VIRTUAL"; 74 | break; 75 | default: 76 | repr << "unknown"; 77 | } 78 | 79 | if (mInterfaces.size() > 0) { 80 | repr << kSeparator << android::base::Join(mInterfaces, ","); 81 | } 82 | 83 | return repr.str(); 84 | } 85 | 86 | 87 | Network::Network(unsigned netId) : mNetId(netId) { 88 | } 89 | -------------------------------------------------------------------------------- /server/oem_iptables_hook.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #define LOG_TAG "OemIptablesHook" 26 | #include 27 | #include 28 | #include "NetdConstants.h" 29 | 30 | static int runIptablesCmd(int argc, const char **argv) { 31 | int res; 32 | 33 | res = android_fork_execvp(argc, (char **)argv, NULL, false, false); 34 | return res; 35 | } 36 | 37 | static bool oemCleanupHooks() { 38 | const char *cmd1[] = { 39 | IPTABLES_PATH, 40 | "-w", 41 | "-F", 42 | "oem_out" 43 | }; 44 | runIptablesCmd(ARRAY_SIZE(cmd1), cmd1); 45 | 46 | const char *cmd2[] = { 47 | IPTABLES_PATH, 48 | "-w", 49 | "-F", 50 | "oem_fwd" 51 | }; 52 | runIptablesCmd(ARRAY_SIZE(cmd2), cmd2); 53 | 54 | const char *cmd3[] = { 55 | IPTABLES_PATH, 56 | "-w", 57 | "-t", 58 | "nat", 59 | "-F", 60 | "oem_nat_pre" 61 | }; 62 | runIptablesCmd(ARRAY_SIZE(cmd3), cmd3); 63 | return true; 64 | } 65 | 66 | static bool oemInitChains() { 67 | int ret = system(OEM_SCRIPT_PATH); 68 | if ((-1 == ret) || (0 != WEXITSTATUS(ret))) { 69 | ALOGE("%s failed: %s", OEM_SCRIPT_PATH, strerror(errno)); 70 | oemCleanupHooks(); 71 | return false; 72 | } 73 | return true; 74 | } 75 | 76 | 77 | void setupOemIptablesHook() { 78 | if (0 == access(OEM_SCRIPT_PATH, R_OK | X_OK)) { 79 | // The call to oemCleanupHooks() is superfluous when done on bootup, 80 | // but is needed for the case where netd has crashed/stopped and is 81 | // restarted. 82 | if (oemCleanupHooks() && oemInitChains()) { 83 | ALOGI("OEM iptable hook installed."); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /server/binder/android/net/UidRange.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 "android/net/UidRange.h" 18 | 19 | #define LOG_TAG "UidRange" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | using android::BAD_VALUE; 27 | using android::NO_ERROR; 28 | using android::Parcel; 29 | using android::status_t; 30 | 31 | namespace android { 32 | 33 | namespace net { 34 | 35 | UidRange::UidRange(int32_t start, int32_t stop) { 36 | ALOG_ASSERT(start <= stop, "start UID must be less than or equal to stop UID"); 37 | mStart = start; 38 | mStop = stop; 39 | } 40 | 41 | status_t UidRange::writeToParcel(Parcel* parcel) const { 42 | /* 43 | * Keep implementation in sync with writeToParcel() in 44 | * frameworks/base/core/java/android/net/UidRange.java. 45 | */ 46 | if (status_t err = parcel->writeInt32(mStart)) { 47 | return err; 48 | } 49 | if (status_t err = parcel->writeInt32(mStop)) { 50 | return err; 51 | } 52 | return NO_ERROR; 53 | } 54 | 55 | status_t UidRange::readFromParcel(const Parcel* parcel) { 56 | /* 57 | * Keep implementation in sync with readFromParcel() in 58 | * frameworks/base/core/java/android/net/UidRange.java. 59 | */ 60 | if (status_t err = parcel->readInt32(&mStart)) { 61 | return err; 62 | } 63 | if (status_t err = parcel->readInt32(&mStop)) { 64 | return err; 65 | } 66 | if (mStart > mStop) return BAD_VALUE; 67 | return NO_ERROR; 68 | } 69 | 70 | void UidRange::setStart(int32_t uid) { 71 | if (mStop != -1) { 72 | ALOG_ASSERT(uid <= mStop, "start UID must be less than or equal to stop UID"); 73 | } 74 | mStart = uid; 75 | } 76 | 77 | void UidRange::setStop(int32_t uid) { 78 | if (mStart != -1) { 79 | ALOG_ASSERT(uid <= mStop, "stop UID must be greater than or equal to start UID"); 80 | } 81 | mStop = uid; 82 | } 83 | 84 | int32_t UidRange::getStart() const { 85 | return mStart; 86 | } 87 | 88 | int32_t UidRange::getStop() const { 89 | return mStop; 90 | } 91 | 92 | } // namespace net 93 | 94 | } // namespace android 95 | -------------------------------------------------------------------------------- /server/NetdNativeService.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2016, 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 | #ifndef _NETD_NATIVE_SERVICE_H_ 18 | #define _NETD_NATIVE_SERVICE_H_ 19 | 20 | #include 21 | 22 | #include 23 | 24 | #include "android/net/BnNetd.h" 25 | #include "android/net/UidRange.h" 26 | 27 | namespace android { 28 | namespace net { 29 | 30 | class NetdNativeService : public BinderService, public BnNetd { 31 | public: 32 | static status_t start(); 33 | static char const* getServiceName() { return "netd"; } 34 | virtual status_t dump(int fd, const Vector &args) override; 35 | 36 | binder::Status isAlive(bool *alive) override; 37 | binder::Status firewallReplaceUidChain( 38 | const String16& chainName, bool isWhitelist, 39 | const std::vector& uids, bool *ret) override; 40 | binder::Status bandwidthEnableDataSaver(bool enable, bool *ret) override; 41 | binder::Status networkRejectNonSecureVpn(bool enable, const std::vector& uids) 42 | override; 43 | binder::Status socketDestroy(const std::vector& uids, 44 | const std::vector& skipUids) override; 45 | binder::Status setResolverConfiguration(int32_t netId, const std::vector& servers, 46 | const std::vector& domains, const std::vector& params) override; 47 | binder::Status getResolverInfo(int32_t netId, std::vector* servers, 48 | std::vector* domains, std::vector* params, 49 | std::vector* stats) override; 50 | 51 | // Tethering-related commands. 52 | binder::Status tetherApplyDnsInterfaces(bool *ret) override; 53 | 54 | binder::Status interfaceAddAddress(const std::string &ifName, 55 | const std::string &addrString, int prefixLength) override; 56 | binder::Status interfaceDelAddress(const std::string &ifName, 57 | const std::string &addrString, int prefixLength) override; 58 | 59 | binder::Status setProcSysNet( 60 | int32_t family, int32_t which, const std::string &ifname, const std::string ¶meter, 61 | const std::string &value) override; 62 | }; 63 | 64 | } // namespace net 65 | } // namespace android 66 | 67 | #endif // _NETD_NATIVE_SERVICE_H_ 68 | -------------------------------------------------------------------------------- /client/FwmarkClient.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "FwmarkClient.h" 18 | 19 | #include "FwmarkCommand.h" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | namespace { 29 | 30 | const sockaddr_un FWMARK_SERVER_PATH = {AF_UNIX, "/dev/socket/fwmarkd"}; 31 | 32 | } // namespace 33 | 34 | bool FwmarkClient::shouldSetFwmark(int family) { 35 | return (family == AF_INET || family == AF_INET6) && !getenv("ANDROID_NO_USE_FWMARK_CLIENT"); 36 | } 37 | 38 | FwmarkClient::FwmarkClient() : mChannel(-1) { 39 | } 40 | 41 | FwmarkClient::~FwmarkClient() { 42 | if (mChannel >= 0) { 43 | close(mChannel); 44 | } 45 | } 46 | 47 | int FwmarkClient::send(FwmarkCommand* data, int fd) { 48 | mChannel = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); 49 | if (mChannel == -1) { 50 | return -errno; 51 | } 52 | 53 | if (TEMP_FAILURE_RETRY(connect(mChannel, reinterpret_cast(&FWMARK_SERVER_PATH), 54 | sizeof(FWMARK_SERVER_PATH))) == -1) { 55 | // If we are unable to connect to the fwmark server, assume there's no error. This protects 56 | // against future changes if the fwmark server goes away. 57 | return 0; 58 | } 59 | 60 | iovec iov; 61 | iov.iov_base = data; 62 | iov.iov_len = sizeof(*data); 63 | 64 | msghdr message; 65 | memset(&message, 0, sizeof(message)); 66 | message.msg_iov = &iov; 67 | message.msg_iovlen = 1; 68 | 69 | union { 70 | cmsghdr cmh; 71 | char cmsg[CMSG_SPACE(sizeof(fd))]; 72 | } cmsgu; 73 | 74 | if (data->cmdId != FwmarkCommand::QUERY_USER_ACCESS) { 75 | memset(cmsgu.cmsg, 0, sizeof(cmsgu.cmsg)); 76 | message.msg_control = cmsgu.cmsg; 77 | message.msg_controllen = sizeof(cmsgu.cmsg); 78 | 79 | cmsghdr* const cmsgh = CMSG_FIRSTHDR(&message); 80 | cmsgh->cmsg_len = CMSG_LEN(sizeof(fd)); 81 | cmsgh->cmsg_level = SOL_SOCKET; 82 | cmsgh->cmsg_type = SCM_RIGHTS; 83 | memcpy(CMSG_DATA(cmsgh), &fd, sizeof(fd)); 84 | } 85 | 86 | if (TEMP_FAILURE_RETRY(sendmsg(mChannel, &message, 0)) == -1) { 87 | return -errno; 88 | } 89 | 90 | int error = 0; 91 | 92 | if (TEMP_FAILURE_RETRY(recv(mChannel, &error, sizeof(error), 0)) == -1) { 93 | return -errno; 94 | } 95 | 96 | return error; 97 | } 98 | -------------------------------------------------------------------------------- /server/SockDiag.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 18 | #include 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | #include 26 | 27 | #include "Permission.h" 28 | #include "UidRanges.h" 29 | 30 | struct inet_diag_msg; 31 | class SockDiagTest; 32 | 33 | class SockDiag { 34 | 35 | public: 36 | static const int kBufferSize = 4096; 37 | 38 | // Callback function that is called once for every socket in the dump. A return value of true 39 | // means destroy the socket. 40 | typedef std::function DumpCallback; 41 | 42 | struct DestroyRequest { 43 | nlmsghdr nlh; 44 | inet_diag_req_v2 req; 45 | } __attribute__((__packed__)); 46 | 47 | SockDiag() : mSock(-1), mWriteSock(-1), mSocketsDestroyed(0) {} 48 | bool open(); 49 | virtual ~SockDiag() { closeSocks(); } 50 | 51 | int sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states); 52 | int sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr); 53 | int readDiagMsg(uint8_t proto, DumpCallback callback); 54 | int sockDestroy(uint8_t proto, const inet_diag_msg *); 55 | // Destroys all sockets on the given IPv4 or IPv6 address. 56 | int destroySockets(const char *addrstr); 57 | // Destroys all sockets for the given protocol and UID. 58 | int destroySockets(uint8_t proto, uid_t uid, bool excludeLoopback); 59 | // Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets for the given UID ranges. 60 | int destroySockets(const UidRanges& uidRanges, const std::set& skipUids, 61 | bool excludeLoopback); 62 | // Destroys all "live" (CONNECTED, SYN_SENT, SYN_RECV) TCP sockets that no longer have 63 | // the permissions required by the specified network. 64 | int destroySocketsLackingPermission(unsigned netId, Permission permission, 65 | bool excludeLoopback); 66 | 67 | private: 68 | friend class SockDiagTest; 69 | int mSock; 70 | int mWriteSock; 71 | int mSocketsDestroyed; 72 | int sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states, iovec *iov, int iovcnt); 73 | int destroySockets(uint8_t proto, int family, const char *addrstr); 74 | int destroyLiveSockets(DumpCallback destroy, const char *what, iovec *iov, int iovcnt); 75 | bool hasSocks() { return mSock != -1 && mWriteSock != -1; } 76 | void closeSocks() { close(mSock); close(mWriteSock); mSock = mWriteSock = -1; } 77 | static bool isLoopbackSocket(const inet_diag_msg *msg); 78 | }; 79 | -------------------------------------------------------------------------------- /server/FirewallController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _FIREWALL_CONTROLLER_H 18 | #define _FIREWALL_CONTROLLER_H 19 | 20 | #include 21 | #include 22 | 23 | #include 24 | 25 | #include "NetdConstants.h" 26 | 27 | enum FirewallRule { DENY, ALLOW }; 28 | 29 | // WHITELIST means the firewall denies all by default, uids must be explicitly ALLOWed 30 | // BLACKLIST means the firewall allows all by default, uids must be explicitly DENYed 31 | 32 | enum FirewallType { WHITELIST, BLACKLIST }; 33 | 34 | enum ChildChain { NONE, DOZABLE, STANDBY, POWERSAVE, INVALID_CHAIN }; 35 | 36 | #define PROTOCOL_TCP 6 37 | #define PROTOCOL_UDP 17 38 | 39 | /* 40 | * Simple firewall that drops all packets except those matching explicitly 41 | * defined ALLOW rules. 42 | * 43 | * Methods in this class must be called when holding a write lock on |lock|, and may not call 44 | * any other controller without explicitly managing that controller's lock. There are currently 45 | * no such methods. 46 | */ 47 | class FirewallController { 48 | public: 49 | FirewallController(); 50 | 51 | int setupIptablesHooks(void); 52 | 53 | int enableFirewall(FirewallType); 54 | int disableFirewall(void); 55 | int isFirewallEnabled(void); 56 | 57 | /* Match traffic going in/out over the given iface. */ 58 | int setInterfaceRule(const char*, FirewallRule); 59 | /* Match traffic coming-in-to or going-out-from given address. */ 60 | int setEgressSourceRule(const char*, FirewallRule); 61 | /* Match traffic coming-in-from or going-out-to given address, port, and protocol. */ 62 | int setEgressDestRule(const char*, int, int, FirewallRule); 63 | /* Match traffic owned by given UID. This is specific to a particular chain. */ 64 | int setUidRule(ChildChain, int, FirewallRule); 65 | 66 | int enableChildChains(ChildChain, bool); 67 | 68 | int replaceUidChain(const char*, bool, const std::vector&); 69 | 70 | static const char* TABLE; 71 | 72 | static const char* LOCAL_INPUT; 73 | static const char* LOCAL_OUTPUT; 74 | static const char* LOCAL_FORWARD; 75 | 76 | static const char* LOCAL_DOZABLE; 77 | static const char* LOCAL_STANDBY; 78 | static const char* LOCAL_POWERSAVE; 79 | 80 | static const char* ICMPV6_TYPES[]; 81 | 82 | android::RWLock lock; 83 | 84 | protected: 85 | friend class FirewallControllerTest; 86 | std::string makeUidRules(IptablesTarget target, const char *name, bool isWhitelist, 87 | const std::vector& uids); 88 | static int (*execIptables)(IptablesTarget target, ...); 89 | static int (*execIptablesSilently)(IptablesTarget target, ...); 90 | static int (*execIptablesRestore)(IptablesTarget target, const std::string& commands); 91 | 92 | private: 93 | FirewallType mFirewallType; 94 | int attachChain(const char*, const char*); 95 | int detachChain(const char*, const char*); 96 | int createChain(const char*, const char*, FirewallType); 97 | FirewallType getFirewallType(ChildChain); 98 | }; 99 | 100 | #endif 101 | -------------------------------------------------------------------------------- /server/NetdConstants.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _NETD_CONSTANTS_H 18 | #define _NETD_CONSTANTS_H 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | 28 | #include 29 | 30 | #include "utils/RWLock.h" 31 | 32 | const int PROTECT_MARK = 0x1; 33 | const int MAX_SYSTEM_UID = AID_APP - 1; 34 | 35 | extern const char * const IPTABLES_PATH; 36 | extern const char * const IP6TABLES_PATH; 37 | extern const char * const IP_PATH; 38 | extern const char * const TC_PATH; 39 | extern const char * const OEM_SCRIPT_PATH; 40 | extern const char * const ADD; 41 | extern const char * const DEL; 42 | 43 | enum IptablesTarget { V4, V6, V4V6 }; 44 | 45 | int execIptables(IptablesTarget target, ...); 46 | int execIptablesSilently(IptablesTarget target, ...); 47 | int execIptablesRestore(IptablesTarget target, const std::string& commands); 48 | bool isIfaceName(const char *name); 49 | int parsePrefix(const char *prefix, uint8_t *family, void *address, int size, uint8_t *prefixlen); 50 | 51 | #define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) 52 | 53 | #define __INT_STRLEN(i) sizeof(#i) 54 | #define _INT_STRLEN(i) __INT_STRLEN(i) 55 | #define INT32_STRLEN _INT_STRLEN(INT32_MIN) 56 | #define UINT32_STRLEN _INT_STRLEN(UINT32_MAX) 57 | #define UINT32_HEX_STRLEN sizeof("0x12345678") 58 | 59 | #define WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) 60 | 61 | const uid_t INVALID_UID = static_cast(-1); 62 | 63 | class Stopwatch { 64 | public: 65 | Stopwatch() : mStart(std::chrono::steady_clock::now()) {} 66 | virtual ~Stopwatch() {}; 67 | 68 | float timeTaken() const { 69 | using ms = std::chrono::duration>; 70 | return (std::chrono::duration_cast( 71 | std::chrono::steady_clock::now() - mStart)).count(); 72 | } 73 | 74 | private: 75 | std::chrono::time_point mStart; 76 | }; 77 | 78 | 79 | struct AddrinfoDeleter { 80 | void operator()(struct addrinfo* p) const { 81 | if (p != nullptr) { 82 | freeaddrinfo(p); 83 | } 84 | } 85 | }; 86 | 87 | typedef std::unique_ptr ScopedAddrinfo; 88 | 89 | 90 | struct IfaddrsDeleter { 91 | void operator()(struct ifaddrs *p) const { 92 | if (p != nullptr) { 93 | freeifaddrs(p); 94 | } 95 | } 96 | }; 97 | 98 | typedef std::unique_ptr ScopedIfaddrs; 99 | 100 | namespace android { 101 | namespace net { 102 | 103 | /** 104 | * This lock exists to make NetdNativeService RPCs (which come in on multiple Binder threads) 105 | * coexist with the commands in CommandListener.cpp. These are presumed not thread-safe because 106 | * CommandListener has only one user (NetworkManagementService), which is connected through a 107 | * FrameworkListener that passes in commands one at a time. 108 | */ 109 | extern android::RWLock gBigNetdLock; 110 | 111 | } // namespace net 112 | } // namespace android 113 | 114 | #endif // _NETD_CONSTANTS_H 115 | -------------------------------------------------------------------------------- /server/UidRanges.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "UidRanges.h" 18 | 19 | #include "NetdConstants.h" 20 | 21 | #include 22 | 23 | #include 24 | 25 | using android::base::StringAppendF; 26 | 27 | bool UidRanges::hasUid(uid_t uid) const { 28 | auto iter = std::lower_bound(mRanges.begin(), mRanges.end(), Range(uid, uid)); 29 | return (iter != mRanges.end() && iter->first == uid) || 30 | (iter != mRanges.begin() && (--iter)->second >= uid); 31 | } 32 | 33 | const std::vector& UidRanges::getRanges() const { 34 | return mRanges; 35 | } 36 | 37 | bool UidRanges::parseFrom(int argc, char* argv[]) { 38 | mRanges.clear(); 39 | for (int i = 0; i < argc; ++i) { 40 | if (!*argv[i]) { 41 | // The UID string is empty. 42 | return false; 43 | } 44 | char* endPtr; 45 | uid_t uidStart = strtoul(argv[i], &endPtr, 0); 46 | uid_t uidEnd; 47 | if (!*endPtr) { 48 | // Found a single UID. The range contains just the one UID. 49 | uidEnd = uidStart; 50 | } else if (*endPtr == '-') { 51 | if (!*++endPtr) { 52 | // Unexpected end of string. 53 | return false; 54 | } 55 | uidEnd = strtoul(endPtr, &endPtr, 0); 56 | if (*endPtr) { 57 | // Illegal trailing chars. 58 | return false; 59 | } 60 | if (uidEnd < uidStart) { 61 | // Invalid order. 62 | return false; 63 | } 64 | } else { 65 | // Not a single uid, not a range. Found some other illegal char. 66 | return false; 67 | } 68 | if (uidStart == INVALID_UID || uidEnd == INVALID_UID) { 69 | // Invalid UIDs. 70 | return false; 71 | } 72 | mRanges.push_back(Range(uidStart, uidEnd)); 73 | } 74 | std::sort(mRanges.begin(), mRanges.end()); 75 | return true; 76 | } 77 | 78 | UidRanges::UidRanges(const std::vector& ranges) { 79 | mRanges.resize(ranges.size()); 80 | std::transform(ranges.begin(), ranges.end(), mRanges.begin(), 81 | [](const android::net::UidRange& range) { 82 | return Range(range.getStart(), range.getStop()); 83 | }); 84 | std::sort(mRanges.begin(), mRanges.end()); 85 | } 86 | 87 | void UidRanges::add(const UidRanges& other) { 88 | auto middle = mRanges.insert(mRanges.end(), other.mRanges.begin(), other.mRanges.end()); 89 | std::inplace_merge(mRanges.begin(), middle, mRanges.end()); 90 | } 91 | 92 | void UidRanges::remove(const UidRanges& other) { 93 | auto end = std::set_difference(mRanges.begin(), mRanges.end(), other.mRanges.begin(), 94 | other.mRanges.end(), mRanges.begin()); 95 | mRanges.erase(end, mRanges.end()); 96 | } 97 | 98 | std::string UidRanges::toString() const { 99 | std::string s("UidRanges{ "); 100 | for (Range range : mRanges) { 101 | if (range.first != range.second) { 102 | StringAppendF(&s, "%u-%u ", range.first, range.second); 103 | } else { 104 | StringAppendF(&s, "%u ", range.first); 105 | } 106 | } 107 | StringAppendF(&s, "}"); 108 | return s; 109 | } 110 | -------------------------------------------------------------------------------- /server/ResponseCode.h: -------------------------------------------------------------------------------- 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 | #ifndef _RESPONSECODE_H 18 | #define _RESPONSECODE_H 19 | 20 | class ResponseCode { 21 | // Keep in sync with 22 | // frameworks/base/services/java/com/android/server/NetworkManagementService.java 23 | public: 24 | // 100 series - Requestion action was initiated; expect another reply 25 | // before proceeding with a new command. 26 | static const int ActionInitiated = 100; 27 | static const int InterfaceListResult = 110; 28 | static const int TetherInterfaceListResult = 111; 29 | static const int TetherDnsFwdTgtListResult = 112; 30 | static const int TtyListResult = 113; 31 | static const int TetheringStatsListResult = 114; 32 | static const int TetherDnsFwdNetIdResult = 115; 33 | 34 | // 200 series - Requested action has been successfully completed 35 | static const int CommandOkay = 200; 36 | static const int TetherStatusResult = 210; 37 | static const int IpFwdStatusResult = 211; 38 | static const int InterfaceGetCfgResult = 213; 39 | static const int SoftapStatusResult = 214; 40 | static const int UsbRNDISStatusResult = 215; 41 | static const int InterfaceRxCounterResult = 216; 42 | static const int InterfaceTxCounterResult = 217; 43 | static const int InterfaceRxThrottleResult = 218; 44 | static const int InterfaceTxThrottleResult = 219; 45 | static const int QuotaCounterResult = 220; 46 | static const int TetheringStatsResult = 221; 47 | static const int DnsProxyQueryResult = 222; 48 | static const int ClatdStatusResult = 223; 49 | 50 | // 400 series - The command was accepted but the requested action 51 | // did not take place. 52 | static const int OperationFailed = 400; 53 | static const int DnsProxyOperationFailed = 401; 54 | static const int ServiceStartFailed = 402; 55 | static const int ServiceStopFailed = 403; 56 | 57 | // 500 series - The command was not accepted and the requested 58 | // action did not take place. 59 | static const int CommandSyntaxError = 500; 60 | static const int CommandParameterError = 501; 61 | 62 | // 600 series - Unsolicited broadcasts 63 | static const int InterfaceChange = 600; 64 | static const int BandwidthControl = 601; 65 | static const int ServiceDiscoveryFailed = 602; 66 | static const int ServiceDiscoveryServiceAdded = 603; 67 | static const int ServiceDiscoveryServiceRemoved = 604; 68 | static const int ServiceRegistrationFailed = 605; 69 | static const int ServiceRegistrationSucceeded = 606; 70 | static const int ServiceResolveFailed = 607; 71 | static const int ServiceResolveSuccess = 608; 72 | static const int ServiceSetHostnameFailed = 609; 73 | static const int ServiceSetHostnameSuccess = 610; 74 | static const int ServiceGetAddrInfoFailed = 611; 75 | static const int ServiceGetAddrInfoSuccess = 612; 76 | static const int InterfaceClassActivity = 613; 77 | static const int InterfaceAddressChange = 614; 78 | static const int InterfaceDnsInfo = 615; 79 | static const int RouteChange = 616; 80 | static const int StrictCleartext = 617; 81 | static const int InterfaceMessage = 618; 82 | }; 83 | #endif 84 | -------------------------------------------------------------------------------- /server/VirtualNetwork.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "VirtualNetwork.h" 19 | 20 | #include "SockDiag.h" 21 | #include "RouteController.h" 22 | 23 | #define LOG_TAG "Netd" 24 | #include "log/log.h" 25 | 26 | VirtualNetwork::VirtualNetwork(unsigned netId, bool hasDns, bool secure) : 27 | Network(netId), mHasDns(hasDns), mSecure(secure) { 28 | } 29 | 30 | VirtualNetwork::~VirtualNetwork() { 31 | } 32 | 33 | bool VirtualNetwork::getHasDns() const { 34 | return mHasDns; 35 | } 36 | 37 | bool VirtualNetwork::isSecure() const { 38 | return mSecure; 39 | } 40 | 41 | bool VirtualNetwork::appliesToUser(uid_t uid) const { 42 | return mUidRanges.hasUid(uid); 43 | } 44 | 45 | 46 | int VirtualNetwork::maybeCloseSockets(bool add, const UidRanges& uidRanges, 47 | const std::set& protectableUsers) { 48 | if (!mSecure) { 49 | return 0; 50 | } 51 | 52 | SockDiag sd; 53 | if (!sd.open()) { 54 | return -EBADFD; 55 | } 56 | 57 | if (int ret = sd.destroySockets(uidRanges, protectableUsers, true /* excludeLoopback */)) { 58 | ALOGE("Failed to close sockets while %s %s to network %d: %s", 59 | add ? "adding" : "removing", uidRanges.toString().c_str(), mNetId, strerror(-ret)); 60 | return ret; 61 | } 62 | 63 | return 0; 64 | } 65 | 66 | int VirtualNetwork::addUsers(const UidRanges& uidRanges, const std::set& protectableUsers) { 67 | maybeCloseSockets(true, uidRanges, protectableUsers); 68 | 69 | for (const std::string& interface : mInterfaces) { 70 | if (int ret = RouteController::addUsersToVirtualNetwork(mNetId, interface.c_str(), mSecure, 71 | uidRanges)) { 72 | ALOGE("failed to add users on interface %s of netId %u", interface.c_str(), mNetId); 73 | return ret; 74 | } 75 | } 76 | mUidRanges.add(uidRanges); 77 | return 0; 78 | } 79 | 80 | int VirtualNetwork::removeUsers(const UidRanges& uidRanges, 81 | const std::set& protectableUsers) { 82 | maybeCloseSockets(false, uidRanges, protectableUsers); 83 | 84 | for (const std::string& interface : mInterfaces) { 85 | if (int ret = RouteController::removeUsersFromVirtualNetwork(mNetId, interface.c_str(), 86 | mSecure, uidRanges)) { 87 | ALOGE("failed to remove users on interface %s of netId %u", interface.c_str(), mNetId); 88 | return ret; 89 | } 90 | } 91 | mUidRanges.remove(uidRanges); 92 | return 0; 93 | } 94 | 95 | Network::Type VirtualNetwork::getType() const { 96 | return VIRTUAL; 97 | } 98 | 99 | int VirtualNetwork::addInterface(const std::string& interface) { 100 | if (hasInterface(interface)) { 101 | return 0; 102 | } 103 | if (int ret = RouteController::addInterfaceToVirtualNetwork(mNetId, interface.c_str(), mSecure, 104 | mUidRanges)) { 105 | ALOGE("failed to add interface %s to VPN netId %u", interface.c_str(), mNetId); 106 | return ret; 107 | } 108 | mInterfaces.insert(interface); 109 | return 0; 110 | } 111 | 112 | int VirtualNetwork::removeInterface(const std::string& interface) { 113 | if (!hasInterface(interface)) { 114 | return 0; 115 | } 116 | if (int ret = RouteController::removeInterfaceFromVirtualNetwork(mNetId, interface.c_str(), 117 | mSecure, mUidRanges)) { 118 | ALOGE("failed to remove interface %s from VPN netId %u", interface.c_str(), mNetId); 119 | return ret; 120 | } 121 | mInterfaces.erase(interface); 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /server/PppController.cpp: -------------------------------------------------------------------------------- 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 18 | #include 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include 28 | 29 | #include 30 | #include 31 | 32 | #define LOG_TAG "PppController" 33 | #include 34 | 35 | #include "PppController.h" 36 | 37 | PppController::PppController() { 38 | mTtys = new TtyCollection(); 39 | mPid = 0; 40 | } 41 | 42 | PppController::~PppController() { 43 | TtyCollection::iterator it; 44 | 45 | for (it = mTtys->begin(); it != mTtys->end(); ++it) { 46 | free(*it); 47 | } 48 | mTtys->clear(); 49 | } 50 | 51 | int PppController::attachPppd(const char *tty, struct in_addr local, 52 | struct in_addr remote, struct in_addr dns1, 53 | struct in_addr dns2) { 54 | pid_t pid; 55 | 56 | if (mPid) { 57 | ALOGE("Multiple PPPD instances not currently supported"); 58 | errno = EBUSY; 59 | return -1; 60 | } 61 | 62 | TtyCollection::iterator it; 63 | for (it = mTtys->begin(); it != mTtys->end(); ++it) { 64 | if (!strcmp(tty, *it)) { 65 | break; 66 | } 67 | } 68 | if (it == mTtys->end()) { 69 | ALOGE("Invalid tty '%s' specified", tty); 70 | errno = -EINVAL; 71 | return -1; 72 | } 73 | 74 | if ((pid = fork()) < 0) { 75 | ALOGE("fork failed (%s)", strerror(errno)); 76 | return -1; 77 | } 78 | 79 | if (!pid) { 80 | char *l = strdup(inet_ntoa(local)); 81 | char *r = strdup(inet_ntoa(remote)); 82 | char *d1 = strdup(inet_ntoa(dns1)); 83 | char *d2 = strdup(inet_ntoa(dns2)); 84 | char dev[32]; 85 | char *lr; 86 | 87 | asprintf(&lr, "%s:%s", l, r); 88 | free(l); 89 | free(r); 90 | 91 | snprintf(dev, sizeof(dev), "/dev/%s", tty); 92 | 93 | // TODO: Deal with pppd bailing out after 99999 seconds of being started 94 | // but not getting a connection 95 | if (execl("/system/bin/pppd", "/system/bin/pppd", "-detach", dev, "115200", 96 | lr, "ms-dns", d1, "ms-dns", d2, "lcp-max-configure", "99999", (char *) NULL)) { 97 | ALOGE("execl failed (%s)", strerror(errno)); 98 | } 99 | free(lr); 100 | free(d1); 101 | free(d2); 102 | ALOGE("Should never get here!"); 103 | return 0; 104 | } else { 105 | mPid = pid; 106 | } 107 | return 0; 108 | } 109 | 110 | int PppController::detachPppd(const char *tty) { 111 | 112 | if (mPid == 0) { 113 | ALOGE("PPPD already stopped"); 114 | return 0; 115 | } 116 | 117 | ALOGD("Stopping PPPD services on port %s", tty); 118 | kill(mPid, SIGTERM); 119 | waitpid(mPid, NULL, 0); 120 | mPid = 0; 121 | ALOGD("PPPD services on port %s stopped", tty); 122 | return 0; 123 | } 124 | 125 | TtyCollection *PppController::getTtyList() { 126 | updateTtyList(); 127 | return mTtys; 128 | } 129 | 130 | int PppController::updateTtyList() { 131 | TtyCollection::iterator it; 132 | 133 | for (it = mTtys->begin(); it != mTtys->end(); ++it) { 134 | free(*it); 135 | } 136 | mTtys->clear(); 137 | 138 | DIR *d = opendir("/sys/class/tty"); 139 | if (!d) { 140 | ALOGE("Error opening /sys/class/tty (%s)", strerror(errno)); 141 | return -1; 142 | } 143 | 144 | struct dirent *de; 145 | while ((de = readdir(d))) { 146 | if (de->d_name[0] == '.') 147 | continue; 148 | if ((!strncmp(de->d_name, "tty", 3)) && (strlen(de->d_name) > 3)) { 149 | mTtys->push_back(strdup(de->d_name)); 150 | } 151 | } 152 | closedir(d); 153 | return 0; 154 | } 155 | -------------------------------------------------------------------------------- /server/ClatdController.cpp: -------------------------------------------------------------------------------- 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 | #include 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #define LOG_TAG "ClatdController" 25 | #include 26 | 27 | #include 28 | 29 | #include "NetdConstants.h" 30 | #include "ClatdController.h" 31 | #include "Fwmark.h" 32 | #include "NetdConstants.h" 33 | #include "NetworkController.h" 34 | 35 | static const char* kClatdPath = "/system/bin/clatd"; 36 | 37 | ClatdController::ClatdController(NetworkController* controller) 38 | : mNetCtrl(controller) { 39 | } 40 | 41 | ClatdController::~ClatdController() { 42 | } 43 | 44 | // Returns the PID of the clatd running on interface |interface|, or 0 if clatd is not running on 45 | // |interface|. 46 | pid_t ClatdController::getClatdPid(char* interface) { 47 | auto it = mClatdPids.find(interface); 48 | return (it == mClatdPids.end() ? 0 : it->second); 49 | } 50 | 51 | int ClatdController::startClatd(char* interface) { 52 | pid_t pid = getClatdPid(interface); 53 | 54 | if (pid != 0) { 55 | ALOGE("clatd pid=%d already started on %s", pid, interface); 56 | errno = EBUSY; 57 | return -1; 58 | } 59 | 60 | // Pass in the interface, a netid to use for DNS lookups, and a fwmark for outgoing packets. 61 | unsigned netId = mNetCtrl->getNetworkForInterface(interface); 62 | if (netId == NETID_UNSET) { 63 | ALOGE("interface %s not assigned to any netId", interface); 64 | errno = ENODEV; 65 | return -1; 66 | } 67 | 68 | char netIdString[UINT32_STRLEN]; 69 | snprintf(netIdString, sizeof(netIdString), "%u", netId); 70 | 71 | Fwmark fwmark; 72 | fwmark.netId = netId; 73 | fwmark.explicitlySelected = true; 74 | fwmark.protectedFromVpn = true; 75 | fwmark.permission = PERMISSION_SYSTEM; 76 | 77 | char fwmarkString[UINT32_HEX_STRLEN]; 78 | snprintf(fwmarkString, sizeof(fwmarkString), "0x%x", fwmark.intValue); 79 | 80 | ALOGD("starting clatd on %s", interface); 81 | 82 | std::string progname("clatd-"); 83 | progname += interface; 84 | 85 | if ((pid = fork()) < 0) { 86 | ALOGE("fork failed (%s)", strerror(errno)); 87 | return -1; 88 | } 89 | 90 | if (!pid) { 91 | char *args[] = { 92 | (char *) progname.c_str(), 93 | (char *) "-i", 94 | interface, 95 | (char *) "-n", 96 | netIdString, 97 | (char *) "-m", 98 | fwmarkString, 99 | NULL 100 | }; 101 | 102 | if (execv(kClatdPath, args)) { 103 | ALOGE("execv failed (%s)", strerror(errno)); 104 | _exit(1); 105 | } 106 | ALOGE("Should never get here!"); 107 | _exit(1); 108 | } else { 109 | mClatdPids[interface] = pid; 110 | ALOGD("clatd started on %s", interface); 111 | } 112 | 113 | return 0; 114 | } 115 | 116 | int ClatdController::stopClatd(char* interface) { 117 | pid_t pid = getClatdPid(interface); 118 | 119 | if (pid == 0) { 120 | ALOGE("clatd already stopped"); 121 | return -1; 122 | } 123 | 124 | ALOGD("Stopping clatd pid=%d on %s", pid, interface); 125 | 126 | kill(pid, SIGTERM); 127 | waitpid(pid, NULL, 0); 128 | mClatdPids.erase(interface); 129 | 130 | ALOGD("clatd on %s stopped", interface); 131 | 132 | return 0; 133 | } 134 | 135 | bool ClatdController::isClatdStarted(char* interface) { 136 | pid_t waitpid_status; 137 | pid_t pid = getClatdPid(interface); 138 | if (pid == 0) { 139 | return false; 140 | } 141 | waitpid_status = waitpid(pid, NULL, WNOHANG); 142 | if (waitpid_status != 0) { 143 | mClatdPids.erase(interface); // child exited, don't call waitpid on it again 144 | } 145 | return waitpid_status == 0; // 0 while child is running 146 | } 147 | -------------------------------------------------------------------------------- /server/QtiDataController.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015-16, The Linux Foundation. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are 6 | met: 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following 11 | disclaimer in the documentation and/or other materials provided 12 | with the distribution. 13 | * Neither the name of The Linux Foundation nor the names of its 14 | contributors may be used to endorse or promote products derived 15 | from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED 18 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 19 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 20 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 21 | BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 22 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 24 | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 25 | WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 26 | OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN 27 | IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | * 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | #include "QtiDataController.h" 38 | #include "NetdConstants.h" 39 | 40 | 41 | void *_libDataHandle = NULL; 42 | void (*_initDataController) () = NULL; 43 | int (*_blockAllData) () = NULL; 44 | int (*_unblockAllData) () = NULL; 45 | unsigned (*_checkAppInWhitelist) (SocketClient *cli) = NULL; 46 | 47 | void *_libCsmDataHandle = NULL; 48 | void (*_initCsmDataCtl) () = NULL; 49 | bool (*_enableMms)(char *uids) = NULL; 50 | bool (*_enableData)(char *uids) = NULL; 51 | 52 | void initDataControllerLibrary() { 53 | if (!_libDataHandle) { 54 | _libDataHandle = dlopen("libdatactrl.so", RTLD_NOW); 55 | if (_libDataHandle) { 56 | *(void **)&_initDataController = 57 | dlsym(_libDataHandle, "initDataController"); 58 | *(void **)&_blockAllData = 59 | dlsym(_libDataHandle, "blockAllData"); 60 | *(void **)&_unblockAllData = 61 | dlsym(_libDataHandle, "unblockAllData"); 62 | *(void **)&_checkAppInWhitelist = 63 | dlsym(_libDataHandle, "checkAppInWhitelist"); 64 | ALOGI("Successfully loaded %s", "Zero Balance libdatacontroller"); 65 | } else { 66 | ALOGE("Failed to open libdatactrl, " 67 | "some features may not be present."); 68 | } 69 | } 70 | 71 | /**csm data*/ 72 | if (!_libCsmDataHandle) { 73 | _libCsmDataHandle = dlopen("libcsm_data.so", RTLD_NOW); 74 | if (_libCsmDataHandle) { 75 | *(void **)&_initCsmDataCtl = 76 | dlsym(_libCsmDataHandle, "initCsmDataCtl"); 77 | *(void **)&_enableMms = 78 | dlsym(_libCsmDataHandle, "enableMms"); 79 | *(void **)&_enableData = 80 | dlsym(_libCsmDataHandle, "enableData"); 81 | ALOGI("Successfully loaded %s", "libCsmDataHandle"); 82 | } else { 83 | ALOGE("Failed to open libcsm_data, " 84 | "some features may not be present."); 85 | } 86 | } 87 | } 88 | 89 | 90 | void initializeDataControllerLib() { 91 | initDataControllerLibrary(); 92 | if (_initDataController) _initDataController(); 93 | if (_initCsmDataCtl) _initCsmDataCtl(); 94 | } 95 | 96 | int blockAllData() { 97 | if (_blockAllData) return _blockAllData(); 98 | return -1; 99 | } 100 | 101 | int unblockAllData() { 102 | if (_unblockAllData) return _unblockAllData(); 103 | return -1; 104 | } 105 | 106 | unsigned checkAppInWhitelist(SocketClient *cli) { 107 | if (_checkAppInWhitelist) return _checkAppInWhitelist(cli); 108 | return 0; 109 | } 110 | 111 | bool enableMms(char *uids) { 112 | if (_enableMms) return _enableMms(uids); 113 | return -1; 114 | } 115 | 116 | bool enableData(char *uids) { 117 | if (_enableData) return _enableData(uids); 118 | return -1; 119 | } 120 | -------------------------------------------------------------------------------- /server/ResolverStats.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 | #ifndef _RESOLVER_STATS_H_ 18 | #define _RESOLVER_STATS_H_ 19 | 20 | #include 21 | 22 | namespace android { 23 | namespace net { 24 | 25 | struct ResolverStats { 26 | // Offsets into the per-server resolver stats as encoded in vector stats of 27 | // getResolverInfo() of Netd's binder interface. The stats are based on data reported by 28 | // android_net_res_stats_get_info_for_net(), the usability is calculated by applying 29 | // android_net_res_stats_get_usable_servers() to this data. 30 | enum ResolverStatsOffsets { 31 | STATS_SUCCESSES = 0, // # successes counted for this server 32 | STATS_ERRORS, // # errors 33 | STATS_TIMEOUTS, // # timeouts 34 | STATS_INTERNAL_ERRORS, // # internal errors 35 | STATS_RTT_AVG, // average round-trip-time 36 | STATS_LAST_SAMPLE_TIME, // time in s when the last sample was recorded 37 | STATS_USABLE, // whether the server is considered usable 38 | STATS_COUNT // total count of integers in the per-server data 39 | }; 40 | 41 | int successes {-1}; 42 | int errors {-1}; 43 | int timeouts {-1}; 44 | int internal_errors {-1}; 45 | int rtt_avg {-1}; 46 | time_t last_sample_time {0}; 47 | bool usable {false}; 48 | 49 | // Serialize the resolver stats to the end of |out|. 50 | void encode(std::vector* out) const; 51 | 52 | // Read the serialized resolverstats starting at |in[ofs]|. 53 | ssize_t decode(const std::vector& in, ssize_t ofs); 54 | 55 | // Serialize the contents of |stats| and append them to the end of |out|. Multiple arrays 56 | // can be written to the same output vector in sequence, however, the corresponding call 57 | // to decodeAll() will return the combined contents in one vector. 58 | static void encodeAll(const std::vector& stats, std::vector* out); 59 | 60 | // Decodes the serialized ResolverStats from |in| and appends them to stats. 61 | static bool decodeAll(const std::vector& in, std::vector* stats); 62 | }; 63 | 64 | 65 | inline void ResolverStats::encode(std::vector* out) const { 66 | size_t ofs = out->size(); 67 | out->resize(ofs + STATS_COUNT); 68 | int32_t* cur = &(*out)[ofs]; 69 | cur[STATS_SUCCESSES] = successes; 70 | cur[STATS_ERRORS] = errors; 71 | cur[STATS_TIMEOUTS] = timeouts; 72 | cur[STATS_INTERNAL_ERRORS] = internal_errors; 73 | cur[STATS_RTT_AVG] = rtt_avg; 74 | cur[STATS_LAST_SAMPLE_TIME] = last_sample_time; 75 | cur[STATS_USABLE] = usable; 76 | } 77 | 78 | // Read the serialized resolverstats starting at |in[ofs]|. 79 | inline ssize_t ResolverStats::decode(const std::vector& in, ssize_t ofs) { 80 | if (ofs < 0 || static_cast(ofs) + STATS_COUNT > in.size()) { 81 | return -1; 82 | } 83 | const int32_t* cur = &in[ofs]; 84 | successes = cur[STATS_SUCCESSES]; 85 | errors = cur[STATS_ERRORS]; 86 | timeouts = cur[STATS_TIMEOUTS]; 87 | internal_errors = cur[STATS_INTERNAL_ERRORS]; 88 | rtt_avg = cur[STATS_RTT_AVG]; 89 | last_sample_time = cur[STATS_LAST_SAMPLE_TIME]; 90 | usable = cur[STATS_USABLE]; 91 | return ofs + STATS_COUNT; 92 | } 93 | 94 | inline void ResolverStats::encodeAll(const std::vector& stats, 95 | std::vector* out) { 96 | for (const auto& s : stats) { 97 | s.encode(out); 98 | } 99 | } 100 | 101 | // TODO: Replace with a better representation, e.g. a Parcelable. 102 | inline bool ResolverStats::decodeAll(const std::vector& in, 103 | std::vector* stats) { 104 | ssize_t size = in.size(); 105 | if (size % STATS_COUNT) { 106 | return false; 107 | } 108 | stats->resize(size / STATS_COUNT); 109 | ssize_t ofs = 0; 110 | for (auto& s : *stats) { 111 | ofs = s.decode(in, ofs); 112 | if (ofs < 0) { 113 | return false; 114 | } 115 | } 116 | return true; 117 | } 118 | 119 | } // namespace net 120 | } // namespace android 121 | 122 | #endif /* _RESOLVER_STATS_H_ */ 123 | -------------------------------------------------------------------------------- /server/Android.mk: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2014 The Android Open Source Project 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | LOCAL_PATH := $(call my-dir) 16 | 17 | ### 18 | ### netd service AIDL interface. 19 | ### 20 | include $(CLEAR_VARS) 21 | 22 | LOCAL_CFLAGS := -Wall -Werror 23 | LOCAL_CLANG := true 24 | LOCAL_MODULE := libnetdaidl 25 | LOCAL_SHARED_LIBRARIES := \ 26 | libbinder \ 27 | libutils 28 | LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/binder 29 | LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/binder 30 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/binder 31 | LOCAL_SRC_FILES := \ 32 | binder/android/net/INetd.aidl \ 33 | binder/android/net/UidRange.cpp 34 | 35 | include $(BUILD_SHARED_LIBRARY) 36 | 37 | ### 38 | ### netd daemon. 39 | ### 40 | include $(CLEAR_VARS) 41 | 42 | LOCAL_C_INCLUDES := \ 43 | $(call include-path-for, libhardware_legacy)/hardware_legacy \ 44 | bionic/libc/dns/include \ 45 | external/mdnsresponder/mDNSShared \ 46 | system/netd/include \ 47 | 48 | LOCAL_CLANG := true 49 | LOCAL_CPPFLAGS := -std=c++11 -Wall -Werror 50 | LOCAL_MODULE := netd 51 | 52 | LOCAL_INIT_RC := netd.rc 53 | 54 | LOCAL_SHARED_LIBRARIES := \ 55 | libbinder \ 56 | libcrypto \ 57 | libcutils \ 58 | libdl \ 59 | libhardware_legacy \ 60 | liblog \ 61 | liblogwrap \ 62 | libmdnssd \ 63 | libnetdaidl \ 64 | libnetutils \ 65 | libnl \ 66 | libsysutils \ 67 | libbase \ 68 | libutils \ 69 | 70 | LOCAL_STATIC_LIBRARIES := \ 71 | libpcap \ 72 | 73 | LOCAL_SRC_FILES := \ 74 | BandwidthController.cpp \ 75 | ClatdController.cpp \ 76 | CommandListener.cpp \ 77 | Controllers.cpp \ 78 | DnsProxyListener.cpp \ 79 | DummyNetwork.cpp \ 80 | DumpWriter.cpp \ 81 | FirewallController.cpp \ 82 | FwmarkServer.cpp \ 83 | IdletimerController.cpp \ 84 | InterfaceController.cpp \ 85 | LocalNetwork.cpp \ 86 | MDnsSdListener.cpp \ 87 | NatController.cpp \ 88 | NetdCommand.cpp \ 89 | NetdConstants.cpp \ 90 | NetdNativeService.cpp \ 91 | NetlinkHandler.cpp \ 92 | NetlinkManager.cpp \ 93 | Network.cpp \ 94 | NetworkController.cpp \ 95 | PhysicalNetwork.cpp \ 96 | PppController.cpp \ 97 | ResolverController.cpp \ 98 | RouteController.cpp \ 99 | SockDiag.cpp \ 100 | SoftapController.cpp \ 101 | StrictController.cpp \ 102 | TetherController.cpp \ 103 | UidRanges.cpp \ 104 | VirtualNetwork.cpp \ 105 | main.cpp \ 106 | oem_iptables_hook.cpp \ 107 | binder/android/net/metrics/IDnsEventListener.aidl \ 108 | QtiDataController.cpp \ 109 | 110 | LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/binder 111 | 112 | ifeq ($(BOARD_USES_QCOM_HARDWARE),true) 113 | ifeq ($(BOARD_HAS_QCOM_WLAN), true) 114 | LOCAL_CFLAGS += -DQSAP_WLAN 115 | LOCAL_SHARED_LIBRARIES += libqsap_sdk 116 | LOCAL_C_INCLUDES += $(TARGET_OUT_HEADERS)/sdk/softap/include 117 | endif 118 | endif 119 | 120 | ifdef WPA_SUPPLICANT_VERSION 121 | LOCAL_CFLAGS += -DLIBWPA_CLIENT_EXISTS 122 | LOCAL_SHARED_LIBRARIES += libwpa_client 123 | LOCAL_C_INCLUDES += external/wpa_supplicant_8/src/common 124 | endif 125 | 126 | include $(BUILD_EXECUTABLE) 127 | 128 | 129 | ### 130 | ### ndc binary. 131 | ### 132 | include $(CLEAR_VARS) 133 | 134 | LOCAL_CFLAGS := -Wall -Werror 135 | LOCAL_CLANG := true 136 | LOCAL_MODULE := ndc 137 | LOCAL_SHARED_LIBRARIES := libcutils 138 | LOCAL_SRC_FILES := ndc.c 139 | 140 | include $(BUILD_EXECUTABLE) 141 | 142 | ### 143 | ### netd unit tests. 144 | ### 145 | include $(CLEAR_VARS) 146 | LOCAL_MODULE := netd_unit_test 147 | LOCAL_CFLAGS := -Wall -Werror -Wunused-parameter 148 | LOCAL_C_INCLUDES := \ 149 | system/netd/include \ 150 | system/netd/server \ 151 | system/netd/server/binder \ 152 | system/core/logwrapper/include \ 153 | 154 | LOCAL_SRC_FILES := \ 155 | NetdConstants.cpp IptablesBaseTest.cpp \ 156 | BandwidthController.cpp BandwidthControllerTest.cpp \ 157 | FirewallControllerTest.cpp FirewallController.cpp \ 158 | NatControllerTest.cpp NatController.cpp \ 159 | SockDiagTest.cpp SockDiag.cpp \ 160 | StrictController.cpp StrictControllerTest.cpp \ 161 | UidRanges.cpp \ 162 | 163 | LOCAL_MODULE_TAGS := tests 164 | LOCAL_SHARED_LIBRARIES := liblog libbase libcutils liblogwrap libsysutils 165 | include $(BUILD_NATIVE_TEST) 166 | 167 | -------------------------------------------------------------------------------- /server/RouteController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_ROUTE_CONTROLLER_H 18 | #define NETD_SERVER_ROUTE_CONTROLLER_H 19 | 20 | #include "NetdConstants.h" 21 | #include "Permission.h" 22 | 23 | #include 24 | 25 | class UidRanges; 26 | 27 | class RouteController { 28 | public: 29 | // How the routing table number is determined for route modification requests. 30 | enum TableType { 31 | INTERFACE, // Compute the table number based on the interface index. 32 | LOCAL_NETWORK, // A fixed table used for routes to directly-connected clients/peers. 33 | LEGACY_NETWORK, // Use a fixed table that's used to override the default network. 34 | LEGACY_SYSTEM, // A fixed table, only modifiable by system apps; overrides VPNs too. 35 | }; 36 | 37 | static const int ROUTE_TABLE_OFFSET_FROM_INDEX = 1000; 38 | 39 | static int Init(unsigned localNetId) WARN_UNUSED_RESULT; 40 | 41 | static int addInterfaceToLocalNetwork(unsigned netId, const char* interface) WARN_UNUSED_RESULT; 42 | static int removeInterfaceFromLocalNetwork(unsigned netId, 43 | const char* interface) WARN_UNUSED_RESULT; 44 | 45 | static int addInterfaceToPhysicalNetwork(unsigned netId, const char* interface, 46 | Permission permission) WARN_UNUSED_RESULT; 47 | static int removeInterfaceFromPhysicalNetwork(unsigned netId, const char* interface, 48 | Permission permission) WARN_UNUSED_RESULT; 49 | 50 | static int addInterfaceToVirtualNetwork(unsigned netId, const char* interface, bool secure, 51 | const UidRanges& uidRanges) WARN_UNUSED_RESULT; 52 | static int removeInterfaceFromVirtualNetwork(unsigned netId, const char* interface, bool secure, 53 | const UidRanges& uidRanges) WARN_UNUSED_RESULT; 54 | 55 | static int modifyPhysicalNetworkPermission(unsigned netId, const char* interface, 56 | Permission oldPermission, 57 | Permission newPermission) WARN_UNUSED_RESULT; 58 | 59 | static int addUsersToVirtualNetwork(unsigned netId, const char* interface, bool secure, 60 | const UidRanges& uidRanges) WARN_UNUSED_RESULT; 61 | static int removeUsersFromVirtualNetwork(unsigned netId, const char* interface, bool secure, 62 | const UidRanges& uidRanges) WARN_UNUSED_RESULT; 63 | 64 | static int addUsersToRejectNonSecureNetworkRule(const UidRanges& uidRanges) 65 | WARN_UNUSED_RESULT; 66 | static int removeUsersFromRejectNonSecureNetworkRule(const UidRanges& uidRanges) 67 | WARN_UNUSED_RESULT; 68 | 69 | static int addInterfaceToDefaultNetwork(const char* interface, 70 | Permission permission) WARN_UNUSED_RESULT; 71 | static int removeInterfaceFromDefaultNetwork(const char* interface, 72 | Permission permission) WARN_UNUSED_RESULT; 73 | 74 | // |nexthop| can be NULL (to indicate a directly-connected route), "unreachable" (to indicate a 75 | // route that's blocked), "throw" (to indicate the lack of a match), or a regular IP address. 76 | static int addRoute(const char* interface, const char* destination, const char* nexthop, 77 | TableType tableType) WARN_UNUSED_RESULT; 78 | static int removeRoute(const char* interface, const char* destination, const char* nexthop, 79 | TableType tableType) WARN_UNUSED_RESULT; 80 | 81 | static int enableTethering(const char* inputInterface, 82 | const char* outputInterface) WARN_UNUSED_RESULT; 83 | static int disableTethering(const char* inputInterface, 84 | const char* outputInterface) WARN_UNUSED_RESULT; 85 | 86 | static int addVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface, 87 | Permission permission) WARN_UNUSED_RESULT; 88 | static int removeVirtualNetworkFallthrough(unsigned vpnNetId, const char* physicalInterface, 89 | Permission permission) WARN_UNUSED_RESULT; 90 | }; 91 | 92 | #endif // NETD_SERVER_ROUTE_CONTROLLER_H 93 | -------------------------------------------------------------------------------- /server/StrictControllerTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 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 | * StrictControllerTest.cpp - unit tests for StrictController.cpp 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | #include 23 | 24 | #include 25 | 26 | #include "StrictController.h" 27 | #include "IptablesBaseTest.h" 28 | 29 | class StrictControllerTest : public IptablesBaseTest { 30 | public: 31 | StrictControllerTest() { 32 | StrictController::execIptables = fakeExecIptables; 33 | StrictController::execIptablesRestore = fakeExecIptablesRestore; 34 | } 35 | StrictController mStrictCtrl; 36 | }; 37 | 38 | TEST_F(StrictControllerTest, TestEnableStrict) { 39 | mStrictCtrl.enableStrict(); 40 | 41 | std::vector common = { 42 | "*filter", 43 | ":st_OUTPUT -", 44 | ":st_penalty_log -", 45 | ":st_penalty_reject -", 46 | ":st_clear_caught -", 47 | ":st_clear_detect -", 48 | "COMMIT\n\x04" 49 | }; 50 | 51 | std::vector v4 = { 52 | "*filter", 53 | "-A st_penalty_log -j CONNMARK --or-mark 0x1000000", 54 | "-A st_penalty_log -j NFLOG --nflog-group 0", 55 | "-A st_penalty_reject -j CONNMARK --or-mark 0x2000000", 56 | "-A st_penalty_reject -j NFLOG --nflog-group 0", 57 | "-A st_penalty_reject -j REJECT", 58 | "-A st_clear_detect -m connmark --mark 0x2000000/0x2000000 -j REJECT", 59 | "-A st_clear_detect -m connmark --mark 0x1000000/0x1000000 -j RETURN", 60 | "-A st_clear_detect -p tcp -m u32 --u32 \"" 61 | "0>>22&0x3C@ 12>>26&0x3C@ 0&0xFFFF0000=0x16030000 &&" 62 | "0>>22&0x3C@ 12>>26&0x3C@ 4&0x00FF0000=0x00010000" 63 | "\" -j CONNMARK --or-mark 0x1000000", 64 | "-A st_clear_detect -p udp -m u32 --u32 \"" 65 | "0>>22&0x3C@ 8&0xFFFF0000=0x16FE0000 &&" 66 | "0>>22&0x3C@ 20&0x00FF0000=0x00010000" 67 | "\" -j CONNMARK --or-mark 0x1000000", 68 | "-A st_clear_detect -m connmark --mark 0x1000000/0x1000000 -j RETURN", 69 | "-A st_clear_detect -p tcp -m state --state ESTABLISHED -m u32 --u32 " 70 | "\"0>>22&0x3C@ 12>>26&0x3C@ 0&0x0=0x0\" -j st_clear_caught", 71 | "-A st_clear_detect -p udp -j st_clear_caught", 72 | "COMMIT\n\x04" 73 | }; 74 | 75 | std::vector v6 = { 76 | "*filter", 77 | "-A st_penalty_log -j CONNMARK --or-mark 0x1000000", 78 | "-A st_penalty_log -j NFLOG --nflog-group 0", 79 | "-A st_penalty_reject -j CONNMARK --or-mark 0x2000000", 80 | "-A st_penalty_reject -j NFLOG --nflog-group 0", 81 | "-A st_penalty_reject -j REJECT", 82 | "-A st_clear_detect -m connmark --mark 0x2000000/0x2000000 -j REJECT", 83 | "-A st_clear_detect -m connmark --mark 0x1000000/0x1000000 -j RETURN", 84 | 85 | "-A st_clear_detect -p tcp -m u32 --u32 \"" 86 | "52>>26&0x3C@ 40&0xFFFF0000=0x16030000 &&" 87 | "52>>26&0x3C@ 44&0x00FF0000=0x00010000" 88 | "\" -j CONNMARK --or-mark 0x1000000", 89 | "-A st_clear_detect -p udp -m u32 --u32 \"" 90 | "48&0xFFFF0000=0x16FE0000 &&" 91 | "60&0x00FF0000=0x00010000" 92 | "\" -j CONNMARK --or-mark 0x1000000", 93 | "-A st_clear_detect -m connmark --mark 0x1000000/0x1000000 -j RETURN", 94 | "-A st_clear_detect -p tcp -m state --state ESTABLISHED -m u32 --u32 " 95 | "\"52>>26&0x3C@ 40&0x0=0x0\" -j st_clear_caught", 96 | "-A st_clear_detect -p udp -j st_clear_caught", 97 | "COMMIT\n\x04" 98 | }; 99 | 100 | std::string commandsCommon = android::base::Join(common, '\n'); 101 | std::string commands4 = android::base::Join(v4, '\n'); 102 | std::string commands6 = android::base::Join(v6, '\n'); 103 | 104 | std::vector> expected = { 105 | { V4V6, commandsCommon }, 106 | { V4, commands4 }, 107 | { V6, commands6 }, 108 | }; 109 | expectIptablesRestoreCommands(expected); 110 | } 111 | 112 | TEST_F(StrictControllerTest, TestDisableStrict) { 113 | mStrictCtrl.disableStrict(); 114 | 115 | const std::string expected = 116 | "*filter\n" 117 | ":st_OUTPUT -\n" 118 | ":st_penalty_log -\n" 119 | ":st_penalty_reject -\n" 120 | ":st_clear_caught -\n" 121 | ":st_clear_detect -\n" 122 | "COMMIT\n\x04"; 123 | expectIptablesRestoreCommands({ expected }); 124 | } 125 | -------------------------------------------------------------------------------- /tests/dns_responder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 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 requied 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 | 18 | #ifndef DNS_RESPONDER_H 19 | #define DNS_RESPONDER_H 20 | 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #include 31 | 32 | namespace test { 33 | 34 | struct DNSHeader; 35 | struct DNSQuestion; 36 | struct DNSRecord; 37 | 38 | /* 39 | * Simple DNS responder, which replies to queries with the registered response 40 | * for that type. Class is assumed to be IN. If no response is registered, the 41 | * default error response code is returned. 42 | */ 43 | class DNSResponder { 44 | public: 45 | DNSResponder(std::string listen_address, std::string listen_service, 46 | int poll_timeout_ms, uint16_t error_rcode, 47 | double response_probability); 48 | ~DNSResponder(); 49 | void addMapping(const char* name, ns_type type, const char* addr); 50 | void removeMapping(const char* name, ns_type type); 51 | void setResponseProbability(double response_probability); 52 | bool running() const; 53 | bool startServer(); 54 | bool stopServer(); 55 | const std::string& listen_address() const { 56 | return listen_address_; 57 | } 58 | const std::string& listen_service() const { 59 | return listen_service_; 60 | } 61 | std::vector> queries() const; 62 | void clearQueries(); 63 | 64 | private: 65 | // Key used for accessing mappings. 66 | struct QueryKey { 67 | std::string name; 68 | unsigned type; 69 | QueryKey(std::string n, unsigned t) : name(n), type(t) {} 70 | bool operator == (const QueryKey& o) const { 71 | return name == o.name && type == o.type; 72 | } 73 | bool operator < (const QueryKey& o) const { 74 | if (name < o.name) return true; 75 | if (name > o.name) return false; 76 | return type < o.type; 77 | } 78 | }; 79 | 80 | struct QueryKeyHash { 81 | size_t operator() (const QueryKey& key) const { 82 | return std::hash()(key.name) + 83 | static_cast(key.type); 84 | } 85 | }; 86 | 87 | // DNS request handler. 88 | void requestHandler(); 89 | 90 | // Parses and generates a response message for incoming DNS requests. 91 | // Returns false on parsing errors. 92 | bool handleDNSRequest(const char* buffer, ssize_t buffer_len, 93 | char* response, size_t* response_len) const; 94 | 95 | bool addAnswerRecords(const DNSQuestion& question, 96 | std::vector* answers) const; 97 | 98 | bool generateErrorResponse(DNSHeader* header, ns_rcode rcode, 99 | char* response, size_t* response_len) const; 100 | bool makeErrorResponse(DNSHeader* header, ns_rcode rcode, char* response, 101 | size_t* response_len) const; 102 | 103 | 104 | // Address and service to listen on, currently limited to UDP. 105 | const std::string listen_address_; 106 | const std::string listen_service_; 107 | // epoll_wait() timeout in ms. 108 | const int poll_timeout_ms_; 109 | // Error code to return for requests for an unknown name. 110 | const uint16_t error_rcode_; 111 | // Probability that a valid response is being sent instead of being sent 112 | // instead of returning error_rcode_. 113 | std::atomic response_probability_; 114 | 115 | // Mappings from (name, type) to registered response and the 116 | // mutex protecting them. 117 | std::unordered_map mappings_ 118 | GUARDED_BY(mappings_mutex_); 119 | // TODO(imaipi): enable GUARDED_BY(mappings_mutex_); 120 | std::mutex mappings_mutex_; 121 | // Query names received so far and the corresponding mutex. 122 | mutable std::vector> queries_ 123 | GUARDED_BY(queries_mutex_); 124 | mutable std::mutex queries_mutex_; 125 | // Socket on which the server is listening. 126 | int socket_; 127 | // File descriptor for epoll. 128 | int epoll_fd_; 129 | // Signal for request handler termination. 130 | std::atomic terminate_ GUARDED_BY(update_mutex_); 131 | // Thread for handling incoming threads. 132 | std::thread handler_thread_ GUARDED_BY(update_mutex_); 133 | std::mutex update_mutex_; 134 | }; 135 | 136 | } // namespace test 137 | 138 | #endif // DNS_RESPONDER_H 139 | -------------------------------------------------------------------------------- /server/MDnsSdListener.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012 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 | #ifndef _MDNSSDLISTENER_H__ 18 | #define _MDNSSDLISTENER_H__ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | #include "NetdCommand.h" 25 | 26 | // callbacks 27 | void MDnsSdListenerDiscoverCallback(DNSServiceRef sdRef, DNSServiceFlags flags, 28 | uint32_t interfaceIndex, DNSServiceErrorType errorCode, 29 | const char *serviceName, const char *regType, const char *replyDomain, 30 | void *inContext); 31 | 32 | void MDnsSdListenerRegisterCallback(DNSServiceRef sdRef, DNSServiceFlags flags, 33 | DNSServiceErrorType errorCode, const char *serviceName, const char *regType, 34 | const char *domain, void *inContext); 35 | 36 | void MDnsSdListenerResolveCallback(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interface, 37 | DNSServiceErrorType errorCode, const char *fullname, const char *hosttarget, uint16_t port, 38 | uint16_t txtLen, const unsigned char *txtRecord, void *inContext); 39 | 40 | void MDnsSdListenerSetHostnameCallback(DNSServiceRef, DNSServiceFlags flags, 41 | DNSServiceErrorType errorCode, const char *hostname, void *inContext); 42 | 43 | void MDnsSdListenerGetAddrInfoCallback(DNSServiceRef sdRef, DNSServiceFlags flags, 44 | uint32_t interface, DNSServiceErrorType errorCode, const char *hostname, 45 | const struct sockaddr *const sa, uint32_t ttl, void *inContext); 46 | 47 | #define RESCAN "1" 48 | 49 | class MDnsSdListener : public FrameworkListener { 50 | public: 51 | MDnsSdListener(); 52 | virtual ~MDnsSdListener() {} 53 | 54 | class Context { 55 | public: 56 | MDnsSdListener *mListener; 57 | int mRefNumber; 58 | 59 | Context(int refNumber, MDnsSdListener *m) { 60 | mRefNumber = refNumber; 61 | mListener = m; 62 | } 63 | 64 | ~Context() { 65 | } 66 | }; 67 | 68 | class Monitor { 69 | public: 70 | Monitor(); 71 | virtual ~Monitor() {} 72 | DNSServiceRef *allocateServiceRef(int id, Context *c); 73 | void startMonitoring(int id); 74 | DNSServiceRef *lookupServiceRef(int id); 75 | void freeServiceRef(int id); 76 | static void *threadStart(void *handler); 77 | int startService(); 78 | int stopService(); 79 | private: 80 | void run(); 81 | int rescan(); // returns the number of elements in the poll 82 | class Element { 83 | public: 84 | int mId; 85 | Element *mNext; 86 | DNSServiceRef mRef; 87 | Context *mContext; 88 | int mReady; 89 | Element(int id, Context *context) 90 | : mId(id), mNext(NULL), mContext(context), mReady(0) {} 91 | virtual ~Element() { delete(mContext); } 92 | }; 93 | Element *mHead; 94 | int mLiveCount; 95 | struct pollfd *mPollFds; 96 | DNSServiceRef **mPollRefs; 97 | int mPollSize; 98 | pthread_t mThread; 99 | int mCtrlSocketPair[2]; 100 | pthread_mutex_t mHeadMutex; 101 | }; 102 | 103 | class Handler : public NetdCommand { 104 | public: 105 | Handler(Monitor *m, MDnsSdListener *listener); 106 | virtual ~Handler(); 107 | int runCommand(SocketClient *c, int argc, char** argv); 108 | 109 | MDnsSdListener *mListener; // needed for broadcast purposes 110 | private: 111 | void stop(SocketClient *cli, int argc, char **argv, const char *str); 112 | 113 | void discover(SocketClient *cli, const char *iface, const char *regType, 114 | const char *domain, const int requestNumber, 115 | const int requestFlags); 116 | 117 | void serviceRegister(SocketClient *cli, int requestId, const char *interfaceName, 118 | const char *serviceName, const char *serviceType, const char *domain, 119 | const char *host, int port, int textLen, void *txtRecord); 120 | 121 | void resolveService(SocketClient *cli, int requestId, 122 | const char *interfaceName, const char *serviceName, const char *regType, 123 | const char *domain); 124 | 125 | void setHostname(SocketClient *cli, int requestId, const char *hostname); 126 | 127 | void getAddrInfo(SocketClient *cli, int requestId, const char *interfaceName, 128 | uint32_t protocol, const char *hostname); 129 | 130 | int ifaceNameToI(const char *iface); 131 | const char *iToIfaceName(int i); 132 | DNSServiceFlags iToFlags(int i); 133 | int flagsToI(DNSServiceFlags flags); 134 | Monitor *mMonitor; 135 | }; 136 | }; 137 | 138 | #endif 139 | -------------------------------------------------------------------------------- /server/main.cpp: -------------------------------------------------------------------------------- 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 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include 28 | 29 | #define LOG_TAG "Netd" 30 | 31 | #include "cutils/log.h" 32 | #include "utils/RWLock.h" 33 | 34 | #include 35 | #include 36 | #include 37 | 38 | #include "Controllers.h" 39 | #include "CommandListener.h" 40 | #include "NetdConstants.h" 41 | #include "NetdNativeService.h" 42 | #include "NetlinkManager.h" 43 | #include "DnsProxyListener.h" 44 | #include "MDnsSdListener.h" 45 | #include "FwmarkServer.h" 46 | 47 | using android::status_t; 48 | using android::sp; 49 | using android::IPCThreadState; 50 | using android::ProcessState; 51 | using android::defaultServiceManager; 52 | using android::net::NetdNativeService; 53 | 54 | static void blockSigpipe(); 55 | static void remove_pid_file(); 56 | static bool write_pid_file(); 57 | 58 | const char* const PID_FILE_PATH = "/data/misc/net/netd_pid"; 59 | const int PID_FILE_FLAGS = O_CREAT | O_TRUNC | O_WRONLY | O_NOFOLLOW | O_CLOEXEC; 60 | const mode_t PID_FILE_MODE = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; // mode 0644, rw-r--r-- 61 | 62 | android::RWLock android::net::gBigNetdLock; 63 | 64 | int main() { 65 | using android::net::gCtls; 66 | 67 | ALOGI("Netd 1.0 starting"); 68 | remove_pid_file(); 69 | 70 | blockSigpipe(); 71 | 72 | NetlinkManager *nm = NetlinkManager::Instance(); 73 | if (nm == nullptr) { 74 | ALOGE("Unable to create NetlinkManager"); 75 | exit(1); 76 | }; 77 | 78 | gCtls = new android::net::Controllers(); 79 | CommandListener cl; 80 | nm->setBroadcaster((SocketListener *) &cl); 81 | 82 | if (nm->start()) { 83 | ALOGE("Unable to start NetlinkManager (%s)", strerror(errno)); 84 | exit(1); 85 | } 86 | 87 | // Set local DNS mode, to prevent bionic from proxying 88 | // back to this service, recursively. 89 | setenv("ANDROID_DNS_MODE", "local", 1); 90 | DnsProxyListener dpl(&gCtls->netCtrl); 91 | if (dpl.startListener()) { 92 | ALOGE("Unable to start DnsProxyListener (%s)", strerror(errno)); 93 | exit(1); 94 | } 95 | 96 | MDnsSdListener mdnsl; 97 | if (mdnsl.startListener()) { 98 | ALOGE("Unable to start MDnsSdListener (%s)", strerror(errno)); 99 | exit(1); 100 | } 101 | 102 | FwmarkServer fwmarkServer(&gCtls->netCtrl); 103 | if (fwmarkServer.startListener()) { 104 | ALOGE("Unable to start FwmarkServer (%s)", strerror(errno)); 105 | exit(1); 106 | } 107 | 108 | status_t ret; 109 | if ((ret = NetdNativeService::start()) != android::OK) { 110 | ALOGE("Unable to start NetdNativeService: %d", ret); 111 | exit(1); 112 | } 113 | 114 | /* 115 | * Now that we're up, we can respond to commands. Starting the listener also tells 116 | * NetworkManagementService that we are up and that our binder interface is ready. 117 | */ 118 | if (cl.startListener()) { 119 | ALOGE("Unable to start CommandListener (%s)", strerror(errno)); 120 | exit(1); 121 | } 122 | 123 | write_pid_file(); 124 | 125 | IPCThreadState::self()->joinThreadPool(); 126 | 127 | ALOGI("Netd exiting"); 128 | 129 | remove_pid_file(); 130 | 131 | exit(0); 132 | } 133 | 134 | static bool write_pid_file() { 135 | char pid_buf[INT32_STRLEN]; 136 | snprintf(pid_buf, sizeof(pid_buf), "%d\n", (int) getpid()); 137 | 138 | int fd = open(PID_FILE_PATH, PID_FILE_FLAGS, PID_FILE_MODE); 139 | if (fd == -1) { 140 | ALOGE("Unable to create pid file (%s)", strerror(errno)); 141 | return false; 142 | } 143 | 144 | // File creation is affected by umask, so make sure the right mode bits are set. 145 | if (fchmod(fd, PID_FILE_MODE) == -1) { 146 | ALOGE("failed to set mode 0%o on %s (%s)", PID_FILE_MODE, PID_FILE_PATH, strerror(errno)); 147 | close(fd); 148 | remove_pid_file(); 149 | return false; 150 | } 151 | 152 | if (write(fd, pid_buf, strlen(pid_buf)) != (ssize_t)strlen(pid_buf)) { 153 | ALOGE("Unable to write to pid file (%s)", strerror(errno)); 154 | close(fd); 155 | remove_pid_file(); 156 | return false; 157 | } 158 | close(fd); 159 | return true; 160 | } 161 | 162 | static void remove_pid_file() { 163 | unlink(PID_FILE_PATH); 164 | } 165 | 166 | static void blockSigpipe() 167 | { 168 | sigset_t mask; 169 | 170 | sigemptyset(&mask); 171 | sigaddset(&mask, SIGPIPE); 172 | if (sigprocmask(SIG_BLOCK, &mask, NULL) != 0) 173 | ALOGW("WARNING: SIGPIPE not blocked\n"); 174 | } 175 | -------------------------------------------------------------------------------- /server/NetworkController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef NETD_SERVER_NETWORK_CONTROLLER_H 18 | #define NETD_SERVER_NETWORK_CONTROLLER_H 19 | 20 | #include "NetdConstants.h" 21 | #include "Permission.h" 22 | 23 | #include "utils/RWLock.h" 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | class DumpWriter; 32 | class Network; 33 | class UidRanges; 34 | class VirtualNetwork; 35 | 36 | /* 37 | * Keeps track of default, per-pid, and per-uid-range network selection, as 38 | * well as the mark associated with each network. Networks are identified 39 | * by netid. In all set* commands netid == 0 means "unspecified" and is 40 | * equivalent to clearing the mapping. 41 | */ 42 | class NetworkController { 43 | public: 44 | static const unsigned MIN_OEM_ID; 45 | static const unsigned MAX_OEM_ID; 46 | static const unsigned LOCAL_NET_ID; 47 | static const unsigned DUMMY_NET_ID; 48 | 49 | NetworkController(); 50 | 51 | unsigned getDefaultNetwork() const; 52 | int setDefaultNetwork(unsigned netId) WARN_UNUSED_RESULT; 53 | 54 | // Sets |*netId| to an appropriate NetId to use for DNS for the given user. Call with |*netId| 55 | // set to a non-NETID_UNSET value if the user already has indicated a preference. Returns the 56 | // fwmark value to set on the socket when performing the DNS request. 57 | uint32_t getNetworkForDns(unsigned* netId, uid_t uid) const; 58 | unsigned getNetworkForUser(uid_t uid) const; 59 | unsigned getNetworkForConnect(uid_t uid) const; 60 | void getNetworkContext(unsigned netId, uid_t uid, struct android_net_context* netcontext) const; 61 | unsigned getNetworkForInterface(const char* interface) const; 62 | bool isVirtualNetwork(unsigned netId) const; 63 | 64 | int createPhysicalNetwork(unsigned netId, Permission permission) WARN_UNUSED_RESULT; 65 | int createVirtualNetwork(unsigned netId, bool hasDns, bool secure) WARN_UNUSED_RESULT; 66 | int destroyNetwork(unsigned netId) WARN_UNUSED_RESULT; 67 | 68 | int addInterfaceToNetwork(unsigned netId, const char* interface) WARN_UNUSED_RESULT; 69 | int removeInterfaceFromNetwork(unsigned netId, const char* interface) WARN_UNUSED_RESULT; 70 | 71 | Permission getPermissionForUser(uid_t uid) const; 72 | void setPermissionForUsers(Permission permission, const std::vector& uids); 73 | int checkUserNetworkAccess(uid_t uid, unsigned netId) const; 74 | int setPermissionForNetworks(Permission permission, 75 | const std::vector& netIds) WARN_UNUSED_RESULT; 76 | 77 | int addUsersToNetwork(unsigned netId, const UidRanges& uidRanges) WARN_UNUSED_RESULT; 78 | int removeUsersFromNetwork(unsigned netId, const UidRanges& uidRanges) WARN_UNUSED_RESULT; 79 | 80 | // |nexthop| can be NULL (to indicate a directly-connected route), "unreachable" (to indicate a 81 | // route that's blocked), "throw" (to indicate the lack of a match), or a regular IP address. 82 | // 83 | // Routes are added to tables determined by the interface, so only |interface| is actually used. 84 | // |netId| is given only to sanity check that the interface has the correct netId. 85 | int addRoute(unsigned netId, const char* interface, const char* destination, 86 | const char* nexthop, bool legacy, uid_t uid) WARN_UNUSED_RESULT; 87 | int removeRoute(unsigned netId, const char* interface, const char* destination, 88 | const char* nexthop, bool legacy, uid_t uid) WARN_UNUSED_RESULT; 89 | 90 | bool canProtect(uid_t uid) const; 91 | void allowProtect(const std::vector& uids); 92 | void denyProtect(const std::vector& uids); 93 | 94 | void dump(DumpWriter& dw); 95 | 96 | private: 97 | bool isValidNetwork(unsigned netId) const; 98 | Network* getNetworkLocked(unsigned netId) const; 99 | VirtualNetwork* getVirtualNetworkForUserLocked(uid_t uid) const; 100 | Permission getPermissionForUserLocked(uid_t uid) const; 101 | int checkUserNetworkAccessLocked(uid_t uid, unsigned netId) const; 102 | 103 | int modifyRoute(unsigned netId, const char* interface, const char* destination, 104 | const char* nexthop, bool add, bool legacy, uid_t uid) WARN_UNUSED_RESULT; 105 | int modifyFallthroughLocked(unsigned vpnNetId, bool add) WARN_UNUSED_RESULT; 106 | 107 | class DelegateImpl; 108 | DelegateImpl* const mDelegateImpl; 109 | 110 | // mRWLock guards all accesses to mDefaultNetId, mNetworks, mUsers and mProtectableUsers. 111 | mutable android::RWLock mRWLock; 112 | unsigned mDefaultNetId; 113 | std::map mNetworks; // Map keys are NetIds. 114 | std::map mUsers; 115 | std::set mProtectableUsers; 116 | }; 117 | 118 | #endif // NETD_SERVER_NETWORK_CONTROLLER_H 119 | -------------------------------------------------------------------------------- /server/DnsProxyListener.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 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 | #ifndef _DNSPROXYLISTENER_H__ 18 | #define _DNSPROXYLISTENER_H__ 19 | 20 | #include // struct android_net_context 21 | #include 22 | #include 23 | 24 | #include "android/net/metrics/IDnsEventListener.h" 25 | #include "NetdCommand.h" 26 | 27 | class NetworkController; 28 | 29 | class DnsProxyListener : public FrameworkListener { 30 | public: 31 | explicit DnsProxyListener(const NetworkController* netCtrl); 32 | virtual ~DnsProxyListener() {} 33 | 34 | // Returns the binder reference to the DNS listener service, attempting to fetch it if we do not 35 | // have it already. This method mutates internal state without taking a lock and must only be 36 | // called on one thread. This is safe because we only call this in the runCommand methods of our 37 | // commands, which are only called by FrameworkListener::onDataAvailable, which is only called 38 | // from SocketListener::runListener, which is a single-threaded select loop. 39 | android::sp getDnsEventListener(); 40 | 41 | private: 42 | const NetworkController *mNetCtrl; 43 | android::sp mDnsEventListener; 44 | 45 | class GetAddrInfoCmd : public NetdCommand { 46 | public: 47 | GetAddrInfoCmd(DnsProxyListener* dnsProxyListener); 48 | virtual ~GetAddrInfoCmd() {} 49 | int runCommand(SocketClient *c, int argc, char** argv); 50 | private: 51 | DnsProxyListener* mDnsProxyListener; 52 | }; 53 | 54 | class GetAddrInfoHandler { 55 | public: 56 | // Note: All of host, service, and hints may be NULL 57 | GetAddrInfoHandler(SocketClient *c, 58 | char* host, 59 | char* service, 60 | struct addrinfo* hints, 61 | const struct android_net_context& netcontext, 62 | const android::sp& listener); 63 | ~GetAddrInfoHandler(); 64 | 65 | static void* threadStart(void* handler); 66 | void start(); 67 | 68 | private: 69 | void run(); 70 | SocketClient* mClient; // ref counted 71 | char* mHost; // owned 72 | char* mService; // owned 73 | struct addrinfo* mHints; // owned 74 | struct android_net_context mNetContext; 75 | android::sp mDnsEventListener; 76 | }; 77 | 78 | /* ------ gethostbyname ------*/ 79 | class GetHostByNameCmd : public NetdCommand { 80 | public: 81 | GetHostByNameCmd(DnsProxyListener* dnsProxyListener); 82 | virtual ~GetHostByNameCmd() {} 83 | int runCommand(SocketClient *c, int argc, char** argv); 84 | private: 85 | DnsProxyListener* mDnsProxyListener; 86 | }; 87 | 88 | class GetHostByNameHandler { 89 | public: 90 | GetHostByNameHandler(SocketClient *c, 91 | char *name, 92 | int af, 93 | unsigned netId, 94 | uint32_t mark, 95 | const android::sp& listener); 96 | ~GetHostByNameHandler(); 97 | static void* threadStart(void* handler); 98 | void start(); 99 | private: 100 | void run(); 101 | SocketClient* mClient; //ref counted 102 | char* mName; // owned 103 | int mAf; 104 | unsigned mNetId; 105 | uint32_t mMark; 106 | android::sp mDnsEventListener; 107 | }; 108 | 109 | /* ------ gethostbyaddr ------*/ 110 | class GetHostByAddrCmd : public NetdCommand { 111 | public: 112 | GetHostByAddrCmd(const DnsProxyListener* dnsProxyListener); 113 | virtual ~GetHostByAddrCmd() {} 114 | int runCommand(SocketClient *c, int argc, char** argv); 115 | private: 116 | const DnsProxyListener* mDnsProxyListener; 117 | }; 118 | 119 | class GetHostByAddrHandler { 120 | public: 121 | GetHostByAddrHandler(SocketClient *c, 122 | void* address, 123 | int addressLen, 124 | int addressFamily, 125 | unsigned netId, 126 | uint32_t mark); 127 | ~GetHostByAddrHandler(); 128 | 129 | static void* threadStart(void* handler); 130 | void start(); 131 | 132 | private: 133 | void run(); 134 | SocketClient* mClient; // ref counted 135 | void* mAddress; // address to lookup; owned 136 | int mAddressLen; // length of address to look up 137 | int mAddressFamily; // address family 138 | unsigned mNetId; 139 | uint32_t mMark; 140 | }; 141 | }; 142 | 143 | #endif 144 | -------------------------------------------------------------------------------- /server/IptablesBaseTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 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 | * IptablesBaseTest.cpp - utility class for tests that use iptables 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | 25 | #include 26 | 27 | #include "IptablesBaseTest.h" 28 | #include "NetdConstants.h" 29 | 30 | #define LOG_TAG "IptablesBaseTest" 31 | #include 32 | 33 | IptablesBaseTest::IptablesBaseTest() { 34 | sCmds.clear(); 35 | sRestoreCmds.clear(); 36 | } 37 | 38 | int IptablesBaseTest::fake_android_fork_exec(int argc, char* argv[], int *status, bool, bool) { 39 | std::string cmd = argv[0]; 40 | for (int i = 1; i < argc; i++) { 41 | if (argv[i] == NULL) break; // NatController likes to pass in invalid argc values. 42 | cmd += " "; 43 | cmd += argv[i]; 44 | } 45 | sCmds.push_back(cmd); 46 | if (status) { 47 | *status = 0; 48 | } 49 | return 0; 50 | } 51 | 52 | int IptablesBaseTest::fakeExecIptables(IptablesTarget target, ...) { 53 | std::string cmd = " -w"; 54 | va_list args; 55 | va_start(args, target); 56 | const char *arg; 57 | do { 58 | arg = va_arg(args, const char *); 59 | if (arg != nullptr) { 60 | cmd += " "; 61 | cmd += arg; 62 | } 63 | } while (arg); 64 | 65 | if (target == V4 || target == V4V6) { 66 | sCmds.push_back(IPTABLES_PATH + cmd); 67 | } 68 | if (target == V6 || target == V4V6) { 69 | sCmds.push_back(IP6TABLES_PATH + cmd); 70 | } 71 | 72 | return 0; 73 | } 74 | 75 | FILE *IptablesBaseTest::fake_popen(const char * /* cmd */, const char *type) { 76 | if (sPopenContents.empty() || strcmp(type, "r") != 0) { 77 | return NULL; 78 | } 79 | 80 | std::string realCmd = android::base::StringPrintf("echo '%s'", sPopenContents.front().c_str()); 81 | sPopenContents.pop_front(); 82 | return popen(realCmd.c_str(), "r"); 83 | } 84 | 85 | int IptablesBaseTest::fakeExecIptablesRestore(IptablesTarget target, const std::string& commands) { 86 | sRestoreCmds.push_back({ target, commands }); 87 | return 0; 88 | } 89 | 90 | int IptablesBaseTest::expectIptablesCommand(IptablesTarget target, int pos, 91 | const std::string& cmd) { 92 | 93 | if ((unsigned) pos >= sCmds.size()) { 94 | ADD_FAILURE() << "Expected too many iptables commands, want command " 95 | << pos + 1 << "/" << sCmds.size(); 96 | return -1; 97 | } 98 | 99 | if (target == V4 || target == V4V6) { 100 | EXPECT_EQ("/system/bin/iptables -w " + cmd, sCmds[pos++]); 101 | } 102 | if (target == V6 || target == V4V6) { 103 | EXPECT_EQ("/system/bin/ip6tables -w " + cmd, sCmds[pos++]); 104 | } 105 | 106 | return target == V4V6 ? 2 : 1; 107 | } 108 | 109 | void IptablesBaseTest::expectIptablesCommands(const std::vector& expectedCmds) { 110 | ExpectedIptablesCommands expected; 111 | for (auto cmd : expectedCmds) { 112 | expected.push_back({ V4V6, cmd }); 113 | } 114 | expectIptablesCommands(expected); 115 | } 116 | 117 | void IptablesBaseTest::expectIptablesCommands(const ExpectedIptablesCommands& expectedCmds) { 118 | size_t pos = 0; 119 | for (size_t i = 0; i < expectedCmds.size(); i ++) { 120 | auto target = expectedCmds[i].first; 121 | auto cmd = expectedCmds[i].second; 122 | int numConsumed = expectIptablesCommand(target, pos, cmd); 123 | if (numConsumed < 0) { 124 | // Read past the end of the array. 125 | break; 126 | } 127 | pos += numConsumed; 128 | } 129 | 130 | EXPECT_EQ(pos, sCmds.size()); 131 | sCmds.clear(); 132 | } 133 | 134 | void IptablesBaseTest::expectIptablesCommands( 135 | const std::vector& snippets) { 136 | ExpectedIptablesCommands expected; 137 | for (const auto& snippet: snippets) { 138 | expected.insert(expected.end(), snippet.begin(), snippet.end()); 139 | } 140 | expectIptablesCommands(expected); 141 | } 142 | 143 | void IptablesBaseTest::expectIptablesRestoreCommands(const std::vector& expectedCmds) { 144 | ExpectedIptablesCommands expected; 145 | for (auto cmd : expectedCmds) { 146 | expected.push_back({ V4V6, cmd }); 147 | } 148 | expectIptablesRestoreCommands(expected); 149 | } 150 | 151 | void IptablesBaseTest::expectIptablesRestoreCommands(const ExpectedIptablesCommands& expectedCmds) { 152 | EXPECT_EQ(expectedCmds.size(), sRestoreCmds.size()); 153 | for (size_t i = 0; i < expectedCmds.size(); i++) { 154 | EXPECT_EQ(expectedCmds[i], sRestoreCmds[i]) << 155 | "iptables-restore command " << i << " differs"; 156 | } 157 | sRestoreCmds.clear(); 158 | } 159 | 160 | std::vector IptablesBaseTest::sCmds = {}; 161 | IptablesBaseTest::ExpectedIptablesCommands IptablesBaseTest::sRestoreCmds = {}; 162 | std::deque IptablesBaseTest::sPopenContents = {}; 163 | -------------------------------------------------------------------------------- /server/CommandListener.h: -------------------------------------------------------------------------------- 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 | #ifndef _COMMANDLISTENER_H__ 18 | #define _COMMANDLISTENER_H__ 19 | 20 | #include 21 | #include "utils/RWLock.h" 22 | 23 | #include "NetdCommand.h" 24 | #include "NetdConstants.h" 25 | #include "NetworkController.h" 26 | #include "TetherController.h" 27 | #include "NatController.h" 28 | #include "PppController.h" 29 | #include "SoftapController.h" 30 | #include "BandwidthController.h" 31 | #include "IdletimerController.h" 32 | #include "InterfaceController.h" 33 | #include "ResolverController.h" 34 | #include "FirewallController.h" 35 | #include "ClatdController.h" 36 | #include "StrictController.h" 37 | 38 | class CommandListener : public FrameworkListener { 39 | public: 40 | CommandListener(); 41 | virtual ~CommandListener() {} 42 | 43 | private: 44 | void registerLockingCmd(FrameworkCommand *cmd, android::RWLock& lock); 45 | void registerLockingCmd(FrameworkCommand *cmd) { 46 | registerLockingCmd(cmd, android::net::gBigNetdLock); 47 | } 48 | 49 | class SoftapCmd : public NetdCommand { 50 | public: 51 | SoftapCmd(); 52 | virtual ~SoftapCmd() {} 53 | int runCommand(SocketClient *c, int argc, char ** argv); 54 | }; 55 | 56 | class InterfaceCmd : public NetdCommand { 57 | public: 58 | InterfaceCmd(); 59 | virtual ~InterfaceCmd() {} 60 | int runCommand(SocketClient *c, int argc, char ** argv); 61 | }; 62 | 63 | class IpFwdCmd : public NetdCommand { 64 | public: 65 | IpFwdCmd(); 66 | virtual ~IpFwdCmd() {} 67 | int runCommand(SocketClient *c, int argc, char ** argv); 68 | }; 69 | 70 | class TetherCmd : public NetdCommand { 71 | public: 72 | TetherCmd(); 73 | virtual ~TetherCmd() {} 74 | int runCommand(SocketClient *c, int argc, char ** argv); 75 | }; 76 | 77 | class NatCmd : public NetdCommand { 78 | public: 79 | NatCmd(); 80 | virtual ~NatCmd() {} 81 | int runCommand(SocketClient *c, int argc, char ** argv); 82 | }; 83 | 84 | class ListTtysCmd : public NetdCommand { 85 | public: 86 | ListTtysCmd(); 87 | virtual ~ListTtysCmd() {} 88 | int runCommand(SocketClient *c, int argc, char ** argv); 89 | }; 90 | 91 | class PppdCmd : public NetdCommand { 92 | public: 93 | PppdCmd(); 94 | virtual ~PppdCmd() {} 95 | int runCommand(SocketClient *c, int argc, char ** argv); 96 | }; 97 | 98 | class BandwidthControlCmd : public NetdCommand { 99 | public: 100 | BandwidthControlCmd(); 101 | virtual ~BandwidthControlCmd() {} 102 | int runCommand(SocketClient *c, int argc, char ** argv); 103 | protected: 104 | void sendGenericOkFail(SocketClient *cli, int cond); 105 | void sendGenericOpFailed(SocketClient *cli, const char *errMsg); 106 | void sendGenericSyntaxError(SocketClient *cli, const char *usageMsg); 107 | }; 108 | 109 | class IdletimerControlCmd : public NetdCommand { 110 | public: 111 | IdletimerControlCmd(); 112 | virtual ~IdletimerControlCmd() {} 113 | int runCommand(SocketClient *c, int argc, char ** argv); 114 | }; 115 | 116 | class ResolverCmd : public NetdCommand { 117 | public: 118 | ResolverCmd(); 119 | virtual ~ResolverCmd() {} 120 | int runCommand(SocketClient *c, int argc, char ** argv); 121 | 122 | private: 123 | bool parseAndExecuteSetNetDns(int netId, int argc, const char** argv); 124 | }; 125 | 126 | class FirewallCmd: public NetdCommand { 127 | public: 128 | FirewallCmd(); 129 | virtual ~FirewallCmd() {} 130 | int runCommand(SocketClient *c, int argc, char ** argv); 131 | protected: 132 | int sendGenericOkFail(SocketClient *cli, int cond); 133 | static FirewallRule parseRule(const char* arg); 134 | static FirewallType parseFirewallType(const char* arg); 135 | static ChildChain parseChildChain(const char* arg); 136 | }; 137 | 138 | class ClatdCmd : public NetdCommand { 139 | public: 140 | ClatdCmd(); 141 | virtual ~ClatdCmd() {} 142 | int runCommand(SocketClient *c, int argc, char ** argv); 143 | }; 144 | 145 | class StrictCmd : public NetdCommand { 146 | public: 147 | StrictCmd(); 148 | virtual ~StrictCmd() {} 149 | int runCommand(SocketClient *c, int argc, char ** argv); 150 | protected: 151 | int sendGenericOkFail(SocketClient *cli, int cond); 152 | static StrictPenalty parsePenalty(const char* arg); 153 | }; 154 | 155 | class NetworkCommand : public NetdCommand { 156 | public: 157 | NetworkCommand(); 158 | virtual ~NetworkCommand() {} 159 | int runCommand(SocketClient* client, int argc, char** argv); 160 | private: 161 | int syntaxError(SocketClient* cli, const char* message); 162 | int operationError(SocketClient* cli, const char* message, int ret); 163 | int success(SocketClient* cli); 164 | }; 165 | }; 166 | 167 | #endif 168 | -------------------------------------------------------------------------------- /server/NatControllerTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 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 | * NatControllerTest.cpp - unit tests for NatController.cpp 17 | */ 18 | 19 | #include 20 | #include 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include 28 | 29 | #include 30 | #include 31 | 32 | #include "NatController.h" 33 | #include "IptablesBaseTest.h" 34 | 35 | using android::base::StringPrintf; 36 | 37 | class NatControllerTest : public IptablesBaseTest { 38 | public: 39 | NatControllerTest() { 40 | NatController::execFunction = fake_android_fork_exec; 41 | } 42 | 43 | protected: 44 | NatController mNatCtrl; 45 | 46 | int setDefaults() { 47 | return mNatCtrl.setDefaults(); 48 | } 49 | 50 | const ExpectedIptablesCommands FLUSH_COMMANDS = { 51 | { V4V6, "-F natctrl_FORWARD" }, 52 | { V4, "-A natctrl_FORWARD -j DROP" }, 53 | { V4, "-t nat -F natctrl_nat_POSTROUTING" }, 54 | { V6, "-t raw -F natctrl_raw_PREROUTING" }, 55 | }; 56 | 57 | const ExpectedIptablesCommands SETUP_COMMANDS = { 58 | { V4V6, "-F natctrl_FORWARD" }, 59 | { V4, "-A natctrl_FORWARD -j DROP" }, 60 | { V4, "-t nat -F natctrl_nat_POSTROUTING" }, 61 | { V6, "-t raw -F natctrl_raw_PREROUTING" }, 62 | { V4V6, "-F natctrl_tether_counters" }, 63 | { V4V6, "-X natctrl_tether_counters" }, 64 | { V4V6, "-N natctrl_tether_counters" }, 65 | { V4, "-t mangle -A natctrl_mangle_FORWARD -p tcp --tcp-flags SYN SYN " 66 | "-j TCPMSS --clamp-mss-to-pmtu" }, 67 | }; 68 | 69 | const ExpectedIptablesCommands TWIDDLE_COMMANDS = { 70 | { V4, "-D natctrl_FORWARD -j DROP" }, 71 | { V4, "-A natctrl_FORWARD -j DROP" }, 72 | }; 73 | 74 | ExpectedIptablesCommands firstNatCommands(const char *extIf) { 75 | return { 76 | { V4, StringPrintf("-t nat -A natctrl_nat_POSTROUTING -o %s -j MASQUERADE", extIf) }, 77 | { V6, "-A natctrl_FORWARD -g natctrl_tether_counters" }, 78 | }; 79 | } 80 | 81 | ExpectedIptablesCommands startNatCommands(const char *intIf, const char *extIf) { 82 | return { 83 | { V4, StringPrintf("-A natctrl_FORWARD -i %s -o %s -m state --state" 84 | " ESTABLISHED,RELATED -g natctrl_tether_counters", extIf, intIf) }, 85 | { V4, StringPrintf("-A natctrl_FORWARD -i %s -o %s -m state --state INVALID -j DROP", 86 | intIf, extIf) }, 87 | { V4, StringPrintf("-A natctrl_FORWARD -i %s -o %s -g natctrl_tether_counters", 88 | intIf, extIf) }, 89 | { V6, StringPrintf("-t raw -A natctrl_raw_PREROUTING -i %s -m rpfilter --invert" 90 | " ! -s fe80::/64 -j DROP", intIf) }, 91 | { V4V6, StringPrintf("-A natctrl_tether_counters -i %s -o %s -j RETURN", 92 | intIf, extIf) }, 93 | { V4V6, StringPrintf("-A natctrl_tether_counters -i %s -o %s -j RETURN", 94 | extIf, intIf) }, 95 | }; 96 | } 97 | 98 | ExpectedIptablesCommands stopNatCommands(const char *intIf, const char *extIf) { 99 | return { 100 | { V4, StringPrintf("-D natctrl_FORWARD -i %s -o %s -m state --state" 101 | " ESTABLISHED,RELATED -g natctrl_tether_counters", extIf, intIf) }, 102 | { V4, StringPrintf("-D natctrl_FORWARD -i %s -o %s -m state --state INVALID -j DROP", 103 | intIf, extIf) }, 104 | { V4, StringPrintf("-D natctrl_FORWARD -i %s -o %s -g natctrl_tether_counters", 105 | intIf, extIf) }, 106 | { V6, StringPrintf("-t raw -D natctrl_raw_PREROUTING -i %s -m rpfilter --invert" 107 | " ! -s fe80::/64 -j DROP", intIf) }, 108 | }; 109 | } 110 | }; 111 | 112 | TEST_F(NatControllerTest, TestSetupIptablesHooks) { 113 | mNatCtrl.setupIptablesHooks(); 114 | expectIptablesCommands(SETUP_COMMANDS); 115 | } 116 | 117 | TEST_F(NatControllerTest, TestSetDefaults) { 118 | setDefaults(); 119 | expectIptablesCommands(FLUSH_COMMANDS); 120 | } 121 | 122 | TEST_F(NatControllerTest, TestAddAndRemoveNat) { 123 | 124 | std::vector startFirstNat = { 125 | firstNatCommands("rmnet0"), 126 | startNatCommands("wlan0", "rmnet0"), 127 | TWIDDLE_COMMANDS, 128 | }; 129 | mNatCtrl.enableNat("wlan0", "rmnet0"); 130 | expectIptablesCommands(startFirstNat); 131 | 132 | std::vector startOtherNat = { 133 | startNatCommands("usb0", "rmnet0"), 134 | TWIDDLE_COMMANDS, 135 | }; 136 | mNatCtrl.enableNat("usb0", "rmnet0"); 137 | expectIptablesCommands(startOtherNat); 138 | 139 | ExpectedIptablesCommands stopOtherNat = stopNatCommands("wlan0", "rmnet0"); 140 | mNatCtrl.disableNat("wlan0", "rmnet0"); 141 | expectIptablesCommands(stopOtherNat); 142 | 143 | std::vector stopLastNat = { 144 | stopNatCommands("usb0", "rmnet0"), 145 | FLUSH_COMMANDS, 146 | }; 147 | mNatCtrl.disableNat("usb0", "rmnet0"); 148 | expectIptablesCommands(stopLastNat); 149 | } 150 | -------------------------------------------------------------------------------- /server/ndc.c: -------------------------------------------------------------------------------- 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 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include 32 | #include 33 | 34 | static void usage(char *progname); 35 | static int do_monitor(int sock, int stop_after_cmd); 36 | static int do_cmd(int sock, int argc, char **argv); 37 | 38 | int main(int argc, char **argv) { 39 | int sock; 40 | int cmdOffset = 0; 41 | 42 | if (argc < 2) 43 | usage(argv[0]); 44 | 45 | // try interpreting the first arg as the socket name - if it fails go back to netd 46 | 47 | if ((sock = socket_local_client(argv[1], 48 | ANDROID_SOCKET_NAMESPACE_RESERVED, 49 | SOCK_STREAM)) < 0) { 50 | if ((sock = socket_local_client("netd", 51 | ANDROID_SOCKET_NAMESPACE_RESERVED, 52 | SOCK_STREAM)) < 0) { 53 | fprintf(stderr, "Error connecting (%s)\n", strerror(errno)); 54 | exit(4); 55 | } 56 | } else { 57 | if (argc < 3) usage(argv[0]); 58 | printf("Using alt socket %s\n", argv[1]); 59 | cmdOffset = 1; 60 | } 61 | 62 | if (!strcmp(argv[1+cmdOffset], "monitor")) 63 | exit(do_monitor(sock, 0)); 64 | exit(do_cmd(sock, argc-cmdOffset, &(argv[cmdOffset]))); 65 | } 66 | 67 | static int do_cmd(int sock, int argc, char **argv) { 68 | char *final_cmd; 69 | char *conv_ptr; 70 | int i; 71 | 72 | /* Check if 1st arg is cmd sequence number */ 73 | strtol(argv[1], &conv_ptr, 10); 74 | if (conv_ptr == argv[1]) { 75 | final_cmd = strdup("0 "); 76 | } else { 77 | final_cmd = strdup(""); 78 | } 79 | if (final_cmd == NULL) { 80 | int res = errno; 81 | perror("strdup failed"); 82 | return res; 83 | } 84 | 85 | for (i = 1; i < argc; i++) { 86 | if (strchr(argv[i], '"')) { 87 | perror("argument with embedded quotes not allowed"); 88 | free(final_cmd); 89 | return 1; 90 | } 91 | bool needs_quoting = strchr(argv[i], ' '); 92 | const char *format = needs_quoting ? "%s\"%s\"%s" : "%s%s%s"; 93 | char *tmp_final_cmd; 94 | 95 | if (asprintf(&tmp_final_cmd, format, final_cmd, argv[i], 96 | (i == (argc - 1)) ? "" : " ") < 0) { 97 | int res = errno; 98 | perror("failed asprintf"); 99 | free(final_cmd); 100 | return res; 101 | } 102 | free(final_cmd); 103 | final_cmd = tmp_final_cmd; 104 | } 105 | 106 | if (write(sock, final_cmd, strlen(final_cmd) + 1) < 0) { 107 | int res = errno; 108 | perror("write"); 109 | free(final_cmd); 110 | return res; 111 | } 112 | free(final_cmd); 113 | 114 | return do_monitor(sock, 1); 115 | } 116 | 117 | static int do_monitor(int sock, int stop_after_cmd) { 118 | char *buffer = malloc(4096); 119 | 120 | if (!stop_after_cmd) 121 | printf("[Connected to Netd]\n"); 122 | 123 | while(1) { 124 | fd_set read_fds; 125 | struct timeval to; 126 | int rc = 0; 127 | 128 | to.tv_sec = 10; 129 | to.tv_usec = 0; 130 | 131 | FD_ZERO(&read_fds); 132 | FD_SET(sock, &read_fds); 133 | 134 | if ((rc = select(sock +1, &read_fds, NULL, NULL, &to)) < 0) { 135 | int res = errno; 136 | fprintf(stderr, "Error in select (%s)\n", strerror(errno)); 137 | free(buffer); 138 | return res; 139 | } else if (!rc) { 140 | continue; 141 | fprintf(stderr, "[TIMEOUT]\n"); 142 | return ETIMEDOUT; 143 | } else if (FD_ISSET(sock, &read_fds)) { 144 | memset(buffer, 0, 4096); 145 | if ((rc = read(sock, buffer, 4096)) <= 0) { 146 | int res = errno; 147 | if (rc == 0) 148 | fprintf(stderr, "Lost connection to Netd - did it crash?\n"); 149 | else 150 | fprintf(stderr, "Error reading data (%s)\n", strerror(errno)); 151 | free(buffer); 152 | if (rc == 0) 153 | return ECONNRESET; 154 | return res; 155 | } 156 | 157 | int offset = 0; 158 | int i = 0; 159 | 160 | for (i = 0; i < rc; i++) { 161 | if (buffer[i] == '\0') { 162 | int code; 163 | char tmp[4]; 164 | 165 | strncpy(tmp, buffer + offset, 3); 166 | tmp[3] = '\0'; 167 | code = atoi(tmp); 168 | 169 | printf("%s\n", buffer + offset); 170 | if (stop_after_cmd) { 171 | if (code >= 200 && code < 600) 172 | return 0; 173 | } 174 | offset = i + 1; 175 | } 176 | } 177 | } 178 | } 179 | free(buffer); 180 | return 0; 181 | } 182 | 183 | static void usage(char *progname) { 184 | fprintf(stderr, "Usage: %s [] ([monitor] | ([] [arg ...]))\n", progname); 185 | exit(1); 186 | } 187 | -------------------------------------------------------------------------------- /server/NetlinkManager.cpp: -------------------------------------------------------------------------------- 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 18 | #include 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include 28 | 29 | #define LOG_TAG "Netd" 30 | 31 | #include 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include 39 | #include 40 | #include 41 | 42 | #include 43 | 44 | #include "NetlinkManager.h" 45 | #include "NetlinkHandler.h" 46 | 47 | #include "pcap-netfilter-linux-android.h" 48 | 49 | const int NetlinkManager::NFLOG_QUOTA_GROUP = 1; 50 | const int NetlinkManager::NETFILTER_STRICT_GROUP = 2; 51 | 52 | NetlinkManager *NetlinkManager::sInstance = NULL; 53 | 54 | NetlinkManager *NetlinkManager::Instance() { 55 | if (!sInstance) 56 | sInstance = new NetlinkManager(); 57 | return sInstance; 58 | } 59 | 60 | NetlinkManager::NetlinkManager() { 61 | mBroadcaster = NULL; 62 | } 63 | 64 | NetlinkManager::~NetlinkManager() { 65 | } 66 | 67 | NetlinkHandler *NetlinkManager::setupSocket(int *sock, int netlinkFamily, 68 | int groups, int format, bool configNflog) { 69 | 70 | struct sockaddr_nl nladdr; 71 | int sz = 64 * 1024; 72 | int on = 1; 73 | 74 | memset(&nladdr, 0, sizeof(nladdr)); 75 | nladdr.nl_family = AF_NETLINK; 76 | nladdr.nl_pid = getpid(); 77 | nladdr.nl_groups = groups; 78 | 79 | if ((*sock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, netlinkFamily)) < 0) { 80 | ALOGE("Unable to create netlink socket: %s", strerror(errno)); 81 | return NULL; 82 | } 83 | 84 | if (setsockopt(*sock, SOL_SOCKET, SO_RCVBUFFORCE, &sz, sizeof(sz)) < 0) { 85 | ALOGE("Unable to set uevent socket SO_RCVBUFFORCE option: %s", strerror(errno)); 86 | close(*sock); 87 | return NULL; 88 | } 89 | 90 | if (setsockopt(*sock, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on)) < 0) { 91 | SLOGE("Unable to set uevent socket SO_PASSCRED option: %s", strerror(errno)); 92 | close(*sock); 93 | return NULL; 94 | } 95 | 96 | if (bind(*sock, (struct sockaddr *) &nladdr, sizeof(nladdr)) < 0) { 97 | ALOGE("Unable to bind netlink socket: %s", strerror(errno)); 98 | close(*sock); 99 | return NULL; 100 | } 101 | 102 | if (configNflog) { 103 | if (android_nflog_send_config_cmd(*sock, 0, NFULNL_CFG_CMD_PF_UNBIND, AF_INET) < 0) { 104 | ALOGE("Failed NFULNL_CFG_CMD_PF_UNBIND: %s", strerror(errno)); 105 | return NULL; 106 | } 107 | if (android_nflog_send_config_cmd(*sock, 0, NFULNL_CFG_CMD_PF_BIND, AF_INET) < 0) { 108 | ALOGE("Failed NFULNL_CFG_CMD_PF_BIND: %s", strerror(errno)); 109 | return NULL; 110 | } 111 | if (android_nflog_send_config_cmd(*sock, 0, NFULNL_CFG_CMD_BIND, AF_UNSPEC) < 0) { 112 | ALOGE("Failed NFULNL_CFG_CMD_BIND: %s", strerror(errno)); 113 | return NULL; 114 | } 115 | } 116 | 117 | NetlinkHandler *handler = new NetlinkHandler(this, *sock, format); 118 | if (handler->start()) { 119 | ALOGE("Unable to start NetlinkHandler: %s", strerror(errno)); 120 | close(*sock); 121 | return NULL; 122 | } 123 | 124 | return handler; 125 | } 126 | 127 | int NetlinkManager::start() { 128 | if ((mUeventHandler = setupSocket(&mUeventSock, NETLINK_KOBJECT_UEVENT, 129 | 0xffffffff, NetlinkListener::NETLINK_FORMAT_ASCII, false)) == NULL) { 130 | return -1; 131 | } 132 | 133 | if ((mRouteHandler = setupSocket(&mRouteSock, NETLINK_ROUTE, 134 | RTMGRP_LINK | 135 | RTMGRP_IPV4_IFADDR | 136 | RTMGRP_IPV6_IFADDR | 137 | RTMGRP_IPV6_ROUTE | 138 | (1 << (RTNLGRP_ND_USEROPT - 1)), 139 | NetlinkListener::NETLINK_FORMAT_BINARY, false)) == NULL) { 140 | return -1; 141 | } 142 | 143 | if ((mQuotaHandler = setupSocket(&mQuotaSock, NETLINK_NFLOG, 144 | NFLOG_QUOTA_GROUP, NetlinkListener::NETLINK_FORMAT_BINARY, false)) == NULL) { 145 | ALOGW("Unable to open qlog quota socket, check if xt_quota2 can send via UeventHandler"); 146 | // TODO: return -1 once the emulator gets a new kernel. 147 | } 148 | 149 | if ((mStrictHandler = setupSocket(&mStrictSock, NETLINK_NETFILTER, 150 | 0, NetlinkListener::NETLINK_FORMAT_BINARY_UNICAST, true)) == NULL) { 151 | ALOGE("Unable to open strict socket"); 152 | // TODO: return -1 once the emulator gets a new kernel. 153 | } 154 | 155 | return 0; 156 | } 157 | 158 | int NetlinkManager::stop() { 159 | int status = 0; 160 | 161 | if (mUeventHandler->stop()) { 162 | ALOGE("Unable to stop uevent NetlinkHandler: %s", strerror(errno)); 163 | status = -1; 164 | } 165 | 166 | delete mUeventHandler; 167 | mUeventHandler = NULL; 168 | 169 | close(mUeventSock); 170 | mUeventSock = -1; 171 | 172 | if (mRouteHandler->stop()) { 173 | ALOGE("Unable to stop route NetlinkHandler: %s", strerror(errno)); 174 | status = -1; 175 | } 176 | 177 | delete mRouteHandler; 178 | mRouteHandler = NULL; 179 | 180 | close(mRouteSock); 181 | mRouteSock = -1; 182 | 183 | if (mQuotaHandler) { 184 | if (mQuotaHandler->stop()) { 185 | ALOGE("Unable to stop quota NetlinkHandler: %s", strerror(errno)); 186 | status = -1; 187 | } 188 | 189 | delete mQuotaHandler; 190 | mQuotaHandler = NULL; 191 | 192 | close(mQuotaSock); 193 | mQuotaSock = -1; 194 | } 195 | 196 | if (mStrictHandler) { 197 | if (mStrictHandler->stop()) { 198 | ALOGE("Unable to stop strict NetlinkHandler: %s", strerror(errno)); 199 | status = -1; 200 | } 201 | 202 | delete mStrictHandler; 203 | mStrictHandler = NULL; 204 | 205 | close(mStrictSock); 206 | mStrictSock = -1; 207 | } 208 | 209 | return status; 210 | } 211 | -------------------------------------------------------------------------------- /server/PhysicalNetwork.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "PhysicalNetwork.h" 18 | 19 | #include "RouteController.h" 20 | #include "SockDiag.h" 21 | 22 | #define LOG_TAG "Netd" 23 | #include "log/log.h" 24 | 25 | namespace { 26 | 27 | WARN_UNUSED_RESULT int addToDefault(unsigned netId, const std::string& interface, 28 | Permission permission, PhysicalNetwork::Delegate* delegate) { 29 | if (int ret = RouteController::addInterfaceToDefaultNetwork(interface.c_str(), permission)) { 30 | ALOGE("failed to add interface %s to default netId %u", interface.c_str(), netId); 31 | return ret; 32 | } 33 | if (int ret = delegate->addFallthrough(interface, permission)) { 34 | return ret; 35 | } 36 | return 0; 37 | } 38 | 39 | WARN_UNUSED_RESULT int removeFromDefault(unsigned netId, const std::string& interface, 40 | Permission permission, 41 | PhysicalNetwork::Delegate* delegate) { 42 | if (int ret = RouteController::removeInterfaceFromDefaultNetwork(interface.c_str(), 43 | permission)) { 44 | ALOGE("failed to remove interface %s from default netId %u", interface.c_str(), netId); 45 | return ret; 46 | } 47 | if (int ret = delegate->removeFallthrough(interface, permission)) { 48 | return ret; 49 | } 50 | return 0; 51 | } 52 | 53 | } // namespace 54 | 55 | PhysicalNetwork::Delegate::~Delegate() { 56 | } 57 | 58 | PhysicalNetwork::PhysicalNetwork(unsigned netId, PhysicalNetwork::Delegate* delegate) : 59 | Network(netId), mDelegate(delegate), mPermission(PERMISSION_NONE), mIsDefault(false) { 60 | } 61 | 62 | PhysicalNetwork::~PhysicalNetwork() { 63 | } 64 | 65 | Permission PhysicalNetwork::getPermission() const { 66 | return mPermission; 67 | } 68 | 69 | int PhysicalNetwork::destroySocketsLackingPermission(Permission permission) { 70 | if (permission == PERMISSION_NONE) return 0; 71 | 72 | SockDiag sd; 73 | if (!sd.open()) { 74 | ALOGE("Error closing sockets for netId %d permission change", mNetId); 75 | return -EBADFD; 76 | } 77 | if (int ret = sd.destroySocketsLackingPermission(mNetId, permission, 78 | true /* excludeLoopback */)) { 79 | ALOGE("Failed to close sockets changing netId %d to permission %d: %s", 80 | mNetId, permission, strerror(-ret)); 81 | return ret; 82 | } 83 | return 0; 84 | } 85 | 86 | int PhysicalNetwork::setPermission(Permission permission) { 87 | if (permission == mPermission) { 88 | return 0; 89 | } 90 | if (mInterfaces.empty()) { 91 | mPermission = permission; 92 | return 0; 93 | } 94 | 95 | destroySocketsLackingPermission(permission); 96 | for (const std::string& interface : mInterfaces) { 97 | if (int ret = RouteController::modifyPhysicalNetworkPermission(mNetId, interface.c_str(), 98 | mPermission, permission)) { 99 | ALOGE("failed to change permission on interface %s of netId %u from %x to %x", 100 | interface.c_str(), mNetId, mPermission, permission); 101 | return ret; 102 | } 103 | } 104 | if (mIsDefault) { 105 | for (const std::string& interface : mInterfaces) { 106 | if (int ret = addToDefault(mNetId, interface, permission, mDelegate)) { 107 | return ret; 108 | } 109 | if (int ret = removeFromDefault(mNetId, interface, mPermission, mDelegate)) { 110 | return ret; 111 | } 112 | } 113 | } 114 | // Destroy sockets again in case any were opened after we called destroySocketsLackingPermission 115 | // above and before we changed the permissions. These sockets won't be able to send any RST 116 | // packets because they are now no longer routed, but at least the apps will get errors. 117 | destroySocketsLackingPermission(permission); 118 | mPermission = permission; 119 | return 0; 120 | } 121 | 122 | int PhysicalNetwork::addAsDefault() { 123 | if (mIsDefault) { 124 | return 0; 125 | } 126 | for (const std::string& interface : mInterfaces) { 127 | if (int ret = addToDefault(mNetId, interface, mPermission, mDelegate)) { 128 | return ret; 129 | } 130 | } 131 | mIsDefault = true; 132 | return 0; 133 | } 134 | 135 | int PhysicalNetwork::removeAsDefault() { 136 | if (!mIsDefault) { 137 | return 0; 138 | } 139 | for (const std::string& interface : mInterfaces) { 140 | if (int ret = removeFromDefault(mNetId, interface, mPermission, mDelegate)) { 141 | return ret; 142 | } 143 | } 144 | mIsDefault = false; 145 | return 0; 146 | } 147 | 148 | Network::Type PhysicalNetwork::getType() const { 149 | return PHYSICAL; 150 | } 151 | 152 | int PhysicalNetwork::addInterface(const std::string& interface) { 153 | if (hasInterface(interface)) { 154 | return 0; 155 | } 156 | if (int ret = RouteController::addInterfaceToPhysicalNetwork(mNetId, interface.c_str(), 157 | mPermission)) { 158 | ALOGE("failed to add interface %s to netId %u", interface.c_str(), mNetId); 159 | return ret; 160 | } 161 | if (mIsDefault) { 162 | if (int ret = addToDefault(mNetId, interface, mPermission, mDelegate)) { 163 | return ret; 164 | } 165 | } 166 | mInterfaces.insert(interface); 167 | return 0; 168 | } 169 | 170 | int PhysicalNetwork::removeInterface(const std::string& interface) { 171 | if (!hasInterface(interface)) { 172 | return 0; 173 | } 174 | if (mIsDefault) { 175 | if (int ret = removeFromDefault(mNetId, interface, mPermission, mDelegate)) { 176 | return ret; 177 | } 178 | } 179 | // This step will flush the interface index from the cache in RouteController so it must be 180 | // done last as further requests to the RouteController regarding this interface will fail 181 | // to find the interface index in the cache in cases where the interface is already gone 182 | // (e.g. bt-pan). 183 | if (int ret = RouteController::removeInterfaceFromPhysicalNetwork(mNetId, interface.c_str(), 184 | mPermission)) { 185 | ALOGE("failed to remove interface %s from netId %u", interface.c_str(), mNetId); 186 | return ret; 187 | } 188 | mInterfaces.erase(interface); 189 | return 0; 190 | } 191 | -------------------------------------------------------------------------------- /client/NetdClient.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "NetdClient.h" 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | 25 | #include "Fwmark.h" 26 | #include "FwmarkClient.h" 27 | #include "FwmarkCommand.h" 28 | #include "resolv_netid.h" 29 | 30 | namespace { 31 | 32 | std::atomic_uint netIdForProcess(NETID_UNSET); 33 | std::atomic_uint netIdForResolv(NETID_UNSET); 34 | 35 | typedef int (*Accept4FunctionType)(int, sockaddr*, socklen_t*, int); 36 | typedef int (*ConnectFunctionType)(int, const sockaddr*, socklen_t); 37 | typedef int (*SocketFunctionType)(int, int, int); 38 | typedef unsigned (*NetIdForResolvFunctionType)(unsigned); 39 | 40 | // These variables are only modified at startup (when libc.so is loaded) and never afterwards, so 41 | // it's okay that they are read later at runtime without a lock. 42 | Accept4FunctionType libcAccept4 = 0; 43 | ConnectFunctionType libcConnect = 0; 44 | SocketFunctionType libcSocket = 0; 45 | 46 | int closeFdAndSetErrno(int fd, int error) { 47 | close(fd); 48 | errno = -error; 49 | return -1; 50 | } 51 | 52 | int netdClientAccept4(int sockfd, sockaddr* addr, socklen_t* addrlen, int flags) { 53 | int acceptedSocket = libcAccept4(sockfd, addr, addrlen, flags); 54 | if (acceptedSocket == -1) { 55 | return -1; 56 | } 57 | int family; 58 | if (addr) { 59 | family = addr->sa_family; 60 | } else { 61 | socklen_t familyLen = sizeof(family); 62 | if (getsockopt(acceptedSocket, SOL_SOCKET, SO_DOMAIN, &family, &familyLen) == -1) { 63 | return closeFdAndSetErrno(acceptedSocket, -errno); 64 | } 65 | } 66 | if (FwmarkClient::shouldSetFwmark(family)) { 67 | FwmarkCommand command = {FwmarkCommand::ON_ACCEPT, 0, 0}; 68 | if (int error = FwmarkClient().send(&command, acceptedSocket)) { 69 | return closeFdAndSetErrno(acceptedSocket, error); 70 | } 71 | } 72 | return acceptedSocket; 73 | } 74 | 75 | int netdClientConnect(int sockfd, const sockaddr* addr, socklen_t addrlen) { 76 | if (sockfd >= 0 && addr && FwmarkClient::shouldSetFwmark(addr->sa_family)) { 77 | FwmarkCommand command = {FwmarkCommand::ON_CONNECT, 0, 0}; 78 | if (int error = FwmarkClient().send(&command, sockfd)) { 79 | errno = -error; 80 | return -1; 81 | } 82 | } 83 | return libcConnect(sockfd, addr, addrlen); 84 | } 85 | 86 | int netdClientSocket(int domain, int type, int protocol) { 87 | int socketFd = libcSocket(domain, type, protocol); 88 | if (socketFd == -1) { 89 | return -1; 90 | } 91 | unsigned netId = netIdForProcess; 92 | if (netId != NETID_UNSET && FwmarkClient::shouldSetFwmark(domain)) { 93 | if (int error = setNetworkForSocket(netId, socketFd)) { 94 | return closeFdAndSetErrno(socketFd, error); 95 | } 96 | } 97 | return socketFd; 98 | } 99 | 100 | unsigned getNetworkForResolv(unsigned netId) { 101 | if (netId != NETID_UNSET) { 102 | return netId; 103 | } 104 | netId = netIdForProcess; 105 | if (netId != NETID_UNSET) { 106 | return netId; 107 | } 108 | return netIdForResolv; 109 | } 110 | 111 | int setNetworkForTarget(unsigned netId, std::atomic_uint* target) { 112 | if (netId == NETID_UNSET) { 113 | *target = netId; 114 | return 0; 115 | } 116 | // Verify that we are allowed to use |netId|, by creating a socket and trying to have it marked 117 | // with the netId. Call libcSocket() directly; else the socket creation (via netdClientSocket()) 118 | // might itself cause another check with the fwmark server, which would be wasteful. 119 | int socketFd; 120 | if (libcSocket) { 121 | socketFd = libcSocket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0); 122 | } else { 123 | socketFd = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0); 124 | } 125 | if (socketFd < 0) { 126 | return -errno; 127 | } 128 | int error = setNetworkForSocket(netId, socketFd); 129 | if (!error) { 130 | *target = netId; 131 | } 132 | close(socketFd); 133 | return error; 134 | } 135 | 136 | } // namespace 137 | 138 | // accept() just calls accept4(..., 0), so there's no need to handle accept() separately. 139 | extern "C" void netdClientInitAccept4(Accept4FunctionType* function) { 140 | if (function && *function) { 141 | libcAccept4 = *function; 142 | *function = netdClientAccept4; 143 | } 144 | } 145 | 146 | extern "C" void netdClientInitConnect(ConnectFunctionType* function) { 147 | if (function && *function) { 148 | libcConnect = *function; 149 | *function = netdClientConnect; 150 | } 151 | } 152 | 153 | extern "C" void netdClientInitSocket(SocketFunctionType* function) { 154 | if (function && *function) { 155 | libcSocket = *function; 156 | *function = netdClientSocket; 157 | } 158 | } 159 | 160 | extern "C" void netdClientInitNetIdForResolv(NetIdForResolvFunctionType* function) { 161 | if (function) { 162 | *function = getNetworkForResolv; 163 | } 164 | } 165 | 166 | extern "C" int getNetworkForSocket(unsigned* netId, int socketFd) { 167 | if (!netId || socketFd < 0) { 168 | return -EBADF; 169 | } 170 | Fwmark fwmark; 171 | socklen_t fwmarkLen = sizeof(fwmark.intValue); 172 | if (getsockopt(socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen) == -1) { 173 | return -errno; 174 | } 175 | *netId = fwmark.netId; 176 | return 0; 177 | } 178 | 179 | extern "C" unsigned getNetworkForProcess() { 180 | return netIdForProcess; 181 | } 182 | 183 | extern "C" int setNetworkForSocket(unsigned netId, int socketFd) { 184 | if (socketFd < 0) { 185 | return -EBADF; 186 | } 187 | FwmarkCommand command = {FwmarkCommand::SELECT_NETWORK, netId, 0}; 188 | return FwmarkClient().send(&command, socketFd); 189 | } 190 | 191 | extern "C" int setNetworkForProcess(unsigned netId) { 192 | return setNetworkForTarget(netId, &netIdForProcess); 193 | } 194 | 195 | extern "C" int setNetworkForResolv(unsigned netId) { 196 | return setNetworkForTarget(netId, &netIdForResolv); 197 | } 198 | 199 | extern "C" int protectFromVpn(int socketFd) { 200 | if (socketFd < 0) { 201 | return -EBADF; 202 | } 203 | FwmarkCommand command = {FwmarkCommand::PROTECT_FROM_VPN, 0, 0}; 204 | return FwmarkClient().send(&command, socketFd); 205 | } 206 | 207 | extern "C" int setNetworkForUser(uid_t uid, int socketFd) { 208 | if (socketFd < 0) { 209 | return -EBADF; 210 | } 211 | FwmarkCommand command = {FwmarkCommand::SELECT_FOR_USER, 0, uid}; 212 | return FwmarkClient().send(&command, socketFd); 213 | } 214 | 215 | extern "C" int queryUserAccess(uid_t uid, unsigned netId) { 216 | FwmarkCommand command = {FwmarkCommand::QUERY_USER_ACCESS, netId, uid}; 217 | return FwmarkClient().send(&command, -1); 218 | } 219 | -------------------------------------------------------------------------------- /server/FirewallControllerTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 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 | * FirewallControllerTest.cpp - unit tests for FirewallController.cpp 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | 25 | #include 26 | 27 | #include "FirewallController.h" 28 | #include "IptablesBaseTest.h" 29 | 30 | 31 | class FirewallControllerTest : public IptablesBaseTest { 32 | protected: 33 | FirewallControllerTest() { 34 | FirewallController::execIptables = fakeExecIptables; 35 | FirewallController::execIptablesSilently = fakeExecIptables; 36 | FirewallController::execIptablesRestore = fakeExecIptablesRestore; 37 | } 38 | FirewallController mFw; 39 | 40 | std::string makeUidRules(IptablesTarget a, const char* b, bool c, 41 | const std::vector& d) { 42 | return mFw.makeUidRules(a, b, c, d); 43 | } 44 | 45 | int createChain(const char* a, const char* b , FirewallType c) { 46 | return mFw.createChain(a, b, c); 47 | } 48 | }; 49 | 50 | 51 | TEST_F(FirewallControllerTest, TestCreateWhitelistChain) { 52 | ExpectedIptablesCommands expectedCommands = { 53 | { V4V6, "-t filter -D INPUT -j fw_whitelist" }, 54 | }; 55 | 56 | std::vector expectedRestore4 = { 57 | "*filter", 58 | ":fw_whitelist -", 59 | "-A fw_whitelist -i lo -o lo -j RETURN", 60 | "-A fw_whitelist -p tcp --tcp-flags RST RST -j RETURN", 61 | "-A fw_whitelist -m owner --uid-owner 0-9999 -j RETURN", 62 | "-A fw_whitelist -j DROP", 63 | "COMMIT\n\x04" 64 | }; 65 | std::vector expectedRestore6 = { 66 | "*filter", 67 | ":fw_whitelist -", 68 | "-A fw_whitelist -i lo -o lo -j RETURN", 69 | "-A fw_whitelist -p tcp --tcp-flags RST RST -j RETURN", 70 | "-A fw_whitelist -p icmpv6 --icmpv6-type packet-too-big -j RETURN", 71 | "-A fw_whitelist -p icmpv6 --icmpv6-type router-solicitation -j RETURN", 72 | "-A fw_whitelist -p icmpv6 --icmpv6-type router-advertisement -j RETURN", 73 | "-A fw_whitelist -p icmpv6 --icmpv6-type neighbour-solicitation -j RETURN", 74 | "-A fw_whitelist -p icmpv6 --icmpv6-type neighbour-advertisement -j RETURN", 75 | "-A fw_whitelist -p icmpv6 --icmpv6-type redirect -j RETURN", 76 | "-A fw_whitelist -m owner --uid-owner 0-9999 -j RETURN", 77 | "-A fw_whitelist -j DROP", 78 | "COMMIT\n\x04" 79 | }; 80 | std::vector> expectedRestoreCommands = { 81 | { V4, android::base::Join(expectedRestore4, '\n') }, 82 | { V6, android::base::Join(expectedRestore6, '\n') }, 83 | }; 84 | 85 | createChain("fw_whitelist", "INPUT", WHITELIST); 86 | expectIptablesCommands(expectedCommands); 87 | expectIptablesRestoreCommands(expectedRestoreCommands); 88 | } 89 | 90 | TEST_F(FirewallControllerTest, TestCreateBlacklistChain) { 91 | ExpectedIptablesCommands expectedCommands = { 92 | { V4V6, "-t filter -D INPUT -j fw_blacklist" }, 93 | }; 94 | 95 | std::vector expectedRestore = { 96 | "*filter", 97 | ":fw_blacklist -", 98 | "-A fw_blacklist -i lo -o lo -j RETURN", 99 | "-A fw_blacklist -p tcp --tcp-flags RST RST -j RETURN", 100 | "COMMIT\n\x04" 101 | }; 102 | std::vector> expectedRestoreCommands = { 103 | { V4, android::base::Join(expectedRestore, '\n') }, 104 | { V6, android::base::Join(expectedRestore, '\n') }, 105 | }; 106 | 107 | createChain("fw_blacklist", "INPUT", BLACKLIST); 108 | expectIptablesCommands(expectedCommands); 109 | expectIptablesRestoreCommands(expectedRestoreCommands); 110 | } 111 | 112 | TEST_F(FirewallControllerTest, TestSetStandbyRule) { 113 | ExpectedIptablesCommands expected = { 114 | { V4V6, "-D fw_standby -m owner --uid-owner 12345 -j DROP" } 115 | }; 116 | mFw.setUidRule(STANDBY, 12345, ALLOW); 117 | expectIptablesCommands(expected); 118 | 119 | expected = { 120 | { V4V6, "-A fw_standby -m owner --uid-owner 12345 -j DROP" } 121 | }; 122 | mFw.setUidRule(STANDBY, 12345, DENY); 123 | expectIptablesCommands(expected); 124 | } 125 | 126 | TEST_F(FirewallControllerTest, TestSetDozeRule) { 127 | ExpectedIptablesCommands expected = { 128 | { V4V6, "-I fw_dozable -m owner --uid-owner 54321 -j RETURN" } 129 | }; 130 | mFw.setUidRule(DOZABLE, 54321, ALLOW); 131 | expectIptablesCommands(expected); 132 | 133 | expected = { 134 | { V4V6, "-D fw_dozable -m owner --uid-owner 54321 -j RETURN" } 135 | }; 136 | mFw.setUidRule(DOZABLE, 54321, DENY); 137 | expectIptablesCommands(expected); 138 | } 139 | 140 | TEST_F(FirewallControllerTest, TestReplaceWhitelistUidRule) { 141 | std::string expected = 142 | "*filter\n" 143 | ":FW_whitechain -\n" 144 | "-A FW_whitechain -i lo -o lo -j RETURN\n" 145 | "-A FW_whitechain -p tcp --tcp-flags RST RST -j RETURN\n" 146 | "-A FW_whitechain -p icmpv6 --icmpv6-type packet-too-big -j RETURN\n" 147 | "-A FW_whitechain -p icmpv6 --icmpv6-type router-solicitation -j RETURN\n" 148 | "-A FW_whitechain -p icmpv6 --icmpv6-type router-advertisement -j RETURN\n" 149 | "-A FW_whitechain -p icmpv6 --icmpv6-type neighbour-solicitation -j RETURN\n" 150 | "-A FW_whitechain -p icmpv6 --icmpv6-type neighbour-advertisement -j RETURN\n" 151 | "-A FW_whitechain -p icmpv6 --icmpv6-type redirect -j RETURN\n" 152 | "-A FW_whitechain -m owner --uid-owner 0-9999 -j RETURN\n" 153 | "-A FW_whitechain -m owner --uid-owner 10023 -j RETURN\n" 154 | "-A FW_whitechain -m owner --uid-owner 10059 -j RETURN\n" 155 | "-A FW_whitechain -m owner --uid-owner 10124 -j RETURN\n" 156 | "-A FW_whitechain -m owner --uid-owner 10111 -j RETURN\n" 157 | "-A FW_whitechain -m owner --uid-owner 110122 -j RETURN\n" 158 | "-A FW_whitechain -m owner --uid-owner 210153 -j RETURN\n" 159 | "-A FW_whitechain -m owner --uid-owner 210024 -j RETURN\n" 160 | "-A FW_whitechain -j DROP\n" 161 | "COMMIT\n\x04"; 162 | 163 | std::vector uids = { 10023, 10059, 10124, 10111, 110122, 210153, 210024 }; 164 | EXPECT_EQ(expected, makeUidRules(V6, "FW_whitechain", true, uids)); 165 | } 166 | 167 | TEST_F(FirewallControllerTest, TestReplaceBlacklistUidRule) { 168 | std::string expected = 169 | "*filter\n" 170 | ":FW_blackchain -\n" 171 | "-A FW_blackchain -i lo -o lo -j RETURN\n" 172 | "-A FW_blackchain -p tcp --tcp-flags RST RST -j RETURN\n" 173 | "-A FW_blackchain -m owner --uid-owner 10023 -j DROP\n" 174 | "-A FW_blackchain -m owner --uid-owner 10059 -j DROP\n" 175 | "-A FW_blackchain -m owner --uid-owner 10124 -j DROP\n" 176 | "COMMIT\n\x04"; 177 | 178 | std::vector uids = { 10023, 10059, 10124 }; 179 | EXPECT_EQ(expected, makeUidRules(V4 ,"FW_blackchain", false, uids)); 180 | } 181 | --------------------------------------------------------------------------------