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 #define LOG_TAG "Netd"
18 
19 #include <cinttypes>
20 #include <numeric>
21 #include <set>
22 #include <string>
23 #include <tuple>
24 #include <vector>
25 
26 #include <android-base/file.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 #include <binder/IPCThreadState.h>
30 #include <binder/IServiceManager.h>
31 #include <binder/Status.h>
32 #include <cutils/properties.h>
33 #include <log/log.h>
34 #include <netdutils/DumpWriter.h>
35 #include <netdutils/Utils.h>
36 #include <utils/Errors.h>
37 #include <utils/String16.h>
38 
39 #include "Controllers.h"
40 #include "Fwmark.h"
41 #include "InterfaceController.h"
42 #include "NetdNativeService.h"
43 #include "OemNetdListener.h"
44 #include "Permission.h"
45 #include "Process.h"
46 #include "RouteController.h"
47 #include "SockDiag.h"
48 #include "UidRanges.h"
49 #include "android/net/BnNetd.h"
50 #include "binder_utils/BinderUtil.h"
51 #include "binder_utils/NetdPermissions.h"
52 #include "netid_client.h"  // NETID_UNSET
53 
54 using android::base::StringPrintf;
55 using android::base::WriteStringToFile;
56 using android::net::TetherStatsParcel;
57 using android::net::UidRangeParcel;
58 using android::net::netd::aidl::NativeUidRangeConfig;
59 using android::netdutils::DumpWriter;
60 using android::netdutils::getIfaceNames;
61 using android::netdutils::ScopedIndent;
62 using android::os::ParcelFileDescriptor;
63 
64 namespace android {
65 namespace net {
66 
67 namespace {
68 const char OPT_SHORT[] = "--short";
69 
70 #define ENFORCE_ANY_PERMISSION(...)                                \
71     do {                                                           \
72         binder::Status status = checkAnyPermission({__VA_ARGS__}); \
73         if (!status.isOk()) {                                      \
74             return status;                                         \
75         }                                                          \
76     } while (0)
77 
78 #define NETD_LOCKING_RPC(lock, ... /* permissions */) \
79     ENFORCE_ANY_PERMISSION(__VA_ARGS__);              \
80     std::lock_guard _lock(lock);
81 
82 #define NETD_BIG_LOCK_RPC(... /* permissions */) NETD_LOCKING_RPC(gBigNetdLock, __VA_ARGS__)
83 
84 #define RETURN_BINDER_STATUS_IF_NOT_OK(logEntry, res) \
85     do {                                              \
86         if (!isOk((res))) {                           \
87             logErrorStatus((logEntry), (res));        \
88             return asBinderStatus((res));             \
89         }                                             \
90     } while (0)
91 
92 #define ENFORCE_NETWORK_STACK_PERMISSIONS() \
93     ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK)
94 
logErrorStatus(netdutils::LogEntry & logEntry,const netdutils::Status & status)95 void logErrorStatus(netdutils::LogEntry& logEntry, const netdutils::Status& status) {
96     gLog.log(logEntry.returns(status.code()).withAutomaticDuration());
97 }
98 
asBinderStatus(const netdutils::Status & status)99 binder::Status asBinderStatus(const netdutils::Status& status) {
100     if (isOk(status)) {
101         return binder::Status::ok();
102     }
103     return binder::Status::fromServiceSpecificError(status.code(), status.msg().c_str());
104 }
105 
106 template <typename T>
asBinderStatus(const base::Result<T> result)107 binder::Status asBinderStatus(const base::Result<T> result) {
108     if (result.ok()) return binder::Status::ok();
109 
110     return binder::Status::fromServiceSpecificError(result.error().code(),
111                                                     result.error().message().c_str());
112 }
113 
contains(const Vector<String16> & words,const String16 & word)114 bool contains(const Vector<String16>& words, const String16& word) {
115     for (const auto& w : words) {
116         if (w == word) return true;
117     }
118 
119     return false;
120 }
121 
122 }  // namespace
123 
NetdNativeService()124 NetdNativeService::NetdNativeService() {
125     // register log callback to BnNetd::logFunc
126     BnNetd::logFunc = [](const auto& log) {
127         binderCallLogFn(log, [](const std::string& msg) { gLog.info("%s", msg.c_str()); });
128     };
129 }
130 
start()131 status_t NetdNativeService::start() {
132     IPCThreadState::self()->disableBackgroundScheduling(true);
133     const status_t ret = BinderService<NetdNativeService>::publish();
134     if (ret != android::OK) {
135         return ret;
136     }
137     sp<ProcessState> ps(ProcessState::self());
138     ps->startThreadPool();
139     ps->giveThreadPoolName();
140 
141     return android::OK;
142 }
143 
dump(int fd,const Vector<String16> & args)144 status_t NetdNativeService::dump(int fd, const Vector<String16> &args) {
145     const binder::Status dump_permission = checkAnyPermission({PERM_DUMP});
146     if (!dump_permission.isOk()) {
147         const String8 msg(dump_permission.toString8());
148         write(fd, msg.c_str(), msg.size());
149         return PERMISSION_DENIED;
150     }
151 
152     // This method does not grab any locks. If individual classes need locking
153     // their dump() methods MUST handle locking appropriately.
154 
155     DumpWriter dw(fd);
156 
157     if (!args.isEmpty() && args[0] == TcpSocketMonitor::DUMP_KEYWORD) {
158       dw.blankline();
159       gCtls->tcpSocketMonitor.dump(dw);
160       dw.blankline();
161       return NO_ERROR;
162     }
163 
164     process::dump(dw);
165     dw.blankline();
166     gCtls->netCtrl.dump(dw);
167     dw.blankline();
168 
169     gCtls->xfrmCtrl.dump(dw);
170     dw.blankline();
171 
172     gCtls->tetherCtrl.dump(dw);
173     dw.blankline();
174 
175     {
176         ScopedIndent indentLog(dw);
177         if (contains(args, String16(OPT_SHORT))) {
178             dw.println("Log: <omitted>");
179         } else {
180             dw.println("Log:");
181             ScopedIndent indentLogEntries(dw);
182             gLog.forEachEntry([&dw](const std::string& entry) mutable { dw.println(entry); });
183         }
184         dw.blankline();
185     }
186 
187     {
188         ScopedIndent indentLog(dw);
189         if (contains(args, String16(OPT_SHORT))) {
190             dw.println("UnsolicitedLog: <omitted>");
191         } else {
192             dw.println("UnsolicitedLog:");
193             ScopedIndent indentLogEntries(dw);
194             gUnsolicitedLog.forEachEntry(
195                     [&dw](const std::string& entry) mutable { dw.println(entry); });
196         }
197         dw.blankline();
198     }
199 
200     return NO_ERROR;
201 }
202 
isAlive(bool * alive)203 binder::Status NetdNativeService::isAlive(bool *alive) {
204     NETD_BIG_LOCK_RPC(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
205 
206     *alive = true;
207 
208     return binder::Status::ok();
209 }
210 
firewallReplaceUidChain(const std::string &,bool,const std::vector<int32_t> &,bool *)211 binder::Status NetdNativeService::firewallReplaceUidChain(const std::string&, bool,
212                                                           const std::vector<int32_t>&, bool*) {
213     DEPRECATED;
214 }
215 
bandwidthEnableDataSaver(bool enable,bool * ret)216 binder::Status NetdNativeService::bandwidthEnableDataSaver(bool enable, bool *ret) {
217     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
218     int err = gCtls->bandwidthCtrl.enableDataSaver(enable);
219     *ret = (err == 0);
220     return binder::Status::ok();
221 }
222 
bandwidthSetInterfaceQuota(const std::string & ifName,int64_t bytes)223 binder::Status NetdNativeService::bandwidthSetInterfaceQuota(const std::string& ifName,
224                                                              int64_t bytes) {
225     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
226     int res = gCtls->bandwidthCtrl.setInterfaceQuota(ifName, bytes);
227     return statusFromErrcode(res);
228 }
229 
bandwidthRemoveInterfaceQuota(const std::string & ifName)230 binder::Status NetdNativeService::bandwidthRemoveInterfaceQuota(const std::string& ifName) {
231     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
232     int res = gCtls->bandwidthCtrl.removeInterfaceQuota(ifName);
233     return statusFromErrcode(res);
234 }
235 
bandwidthSetInterfaceAlert(const std::string & ifName,int64_t bytes)236 binder::Status NetdNativeService::bandwidthSetInterfaceAlert(const std::string& ifName,
237                                                              int64_t bytes) {
238     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
239     int res = gCtls->bandwidthCtrl.setInterfaceAlert(ifName, bytes);
240     return statusFromErrcode(res);
241 }
242 
bandwidthRemoveInterfaceAlert(const std::string & ifName)243 binder::Status NetdNativeService::bandwidthRemoveInterfaceAlert(const std::string& ifName) {
244     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
245     int res = gCtls->bandwidthCtrl.removeInterfaceAlert(ifName);
246     return statusFromErrcode(res);
247 }
248 
bandwidthSetGlobalAlert(int64_t bytes)249 binder::Status NetdNativeService::bandwidthSetGlobalAlert(int64_t bytes) {
250     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
251     int res = gCtls->bandwidthCtrl.setGlobalAlert(bytes);
252     return statusFromErrcode(res);
253 }
254 
bandwidthAddNaughtyApp(int32_t)255 binder::Status NetdNativeService::bandwidthAddNaughtyApp(int32_t) {
256     DEPRECATED;
257 }
258 
bandwidthRemoveNaughtyApp(int32_t)259 binder::Status NetdNativeService::bandwidthRemoveNaughtyApp(int32_t) {
260     DEPRECATED;
261 }
262 
bandwidthAddNiceApp(int32_t)263 binder::Status NetdNativeService::bandwidthAddNiceApp(int32_t) {
264     DEPRECATED;
265 }
266 
bandwidthRemoveNiceApp(int32_t)267 binder::Status NetdNativeService::bandwidthRemoveNiceApp(int32_t) {
268     DEPRECATED;
269 }
270 
271 // TODO: Remove this function when there are no users. Currently, it is still used by DNS resolver
272 // tests.
networkCreatePhysical(int32_t netId,int32_t permission)273 binder::Status NetdNativeService::networkCreatePhysical(int32_t netId, int32_t permission) {
274     ENFORCE_NETWORK_STACK_PERMISSIONS();
275     int ret = gCtls->netCtrl.createPhysicalNetwork(netId, convertPermission(permission),
276                                                    false /* local */);
277     return statusFromErrcode(ret);
278 }
279 
280 // TODO: Remove this function when there are no users. Currently, it is still used by DNS resolver
281 // tests.
networkCreateVpn(int32_t netId,bool secure)282 binder::Status NetdNativeService::networkCreateVpn(int32_t netId, bool secure) {
283     ENFORCE_NETWORK_STACK_PERMISSIONS();
284     // The value of vpnType does not matter here, because it is not used in AOSP and is only
285     // implemented by OEMs. Also, the RPC is going to deprecate. Just pick a value defined in INetd
286     // as default.
287     int ret = gCtls->netCtrl.createVirtualNetwork(netId, secure, NativeVpnType::LEGACY,
288                                                   false /* excludeLocalRoutes */);
289     return statusFromErrcode(ret);
290 }
291 
networkCreate(const NativeNetworkConfig & config)292 binder::Status NetdNativeService::networkCreate(const NativeNetworkConfig& config) {
293     ENFORCE_NETWORK_STACK_PERMISSIONS();
294     int ret = -EINVAL;
295     if (config.networkType == NativeNetworkType::PHYSICAL) {
296         ret = gCtls->netCtrl.createPhysicalNetwork(
297                 config.netId, convertPermission(config.permission), false /* isLocalNetwork */);
298     } else if (config.networkType == NativeNetworkType::PHYSICAL_LOCAL) {
299         ret = gCtls->netCtrl.createPhysicalNetwork(
300                 config.netId, convertPermission(config.permission), true /* isLocalNetwork */);
301     } else if (config.networkType == NativeNetworkType::VIRTUAL) {
302         ret = gCtls->netCtrl.createVirtualNetwork(config.netId, config.secure, config.vpnType,
303                                                   config.excludeLocalRoutes);
304     }
305     return statusFromErrcode(ret);
306 }
307 
networkDestroy(int32_t netId)308 binder::Status NetdNativeService::networkDestroy(int32_t netId) {
309     ENFORCE_NETWORK_STACK_PERMISSIONS();
310     // NetworkController::destroyNetwork is thread-safe.
311     const int ret = gCtls->netCtrl.destroyNetwork(netId);
312     return statusFromErrcode(ret);
313 }
314 
networkAddInterface(int32_t netId,const std::string & iface)315 binder::Status NetdNativeService::networkAddInterface(int32_t netId, const std::string& iface) {
316     ENFORCE_NETWORK_STACK_PERMISSIONS();
317     int ret = gCtls->netCtrl.addInterfaceToNetwork(netId, iface.c_str());
318     return statusFromErrcode(ret);
319 }
320 
networkRemoveInterface(int32_t netId,const std::string & iface)321 binder::Status NetdNativeService::networkRemoveInterface(int32_t netId, const std::string& iface) {
322     ENFORCE_NETWORK_STACK_PERMISSIONS();
323     int ret = gCtls->netCtrl.removeInterfaceFromNetwork(netId, iface.c_str());
324     return statusFromErrcode(ret);
325 }
326 
networkAddUidRanges(int32_t netId,const std::vector<UidRangeParcel> & uidRangeArray)327 binder::Status NetdNativeService::networkAddUidRanges(
328         int32_t netId, const std::vector<UidRangeParcel>& uidRangeArray) {
329     // NetworkController::addUsersToNetwork is thread-safe.
330     ENFORCE_NETWORK_STACK_PERMISSIONS();
331     int ret = gCtls->netCtrl.addUsersToNetwork(netId, UidRanges(uidRangeArray),
332                                                UidRanges::SUB_PRIORITY_HIGHEST);
333     return statusFromErrcode(ret);
334 }
335 
networkRemoveUidRanges(int32_t netId,const std::vector<UidRangeParcel> & uidRangeArray)336 binder::Status NetdNativeService::networkRemoveUidRanges(
337         int32_t netId, const std::vector<UidRangeParcel>& uidRangeArray) {
338     // NetworkController::removeUsersFromNetwork is thread-safe.
339     ENFORCE_NETWORK_STACK_PERMISSIONS();
340     int ret = gCtls->netCtrl.removeUsersFromNetwork(netId, UidRanges(uidRangeArray),
341                                                     UidRanges::SUB_PRIORITY_HIGHEST);
342     return statusFromErrcode(ret);
343 }
344 
networkAddUidRangesParcel(const NativeUidRangeConfig & config)345 binder::Status NetdNativeService::networkAddUidRangesParcel(const NativeUidRangeConfig& config) {
346     ENFORCE_NETWORK_STACK_PERMISSIONS();
347     int ret = gCtls->netCtrl.addUsersToNetwork(config.netId, UidRanges(config.uidRanges),
348                                                config.subPriority);
349     return statusFromErrcode(ret);
350 }
351 
networkRemoveUidRangesParcel(const NativeUidRangeConfig & config)352 binder::Status NetdNativeService::networkRemoveUidRangesParcel(const NativeUidRangeConfig& config) {
353     ENFORCE_NETWORK_STACK_PERMISSIONS();
354     int ret = gCtls->netCtrl.removeUsersFromNetwork(config.netId, UidRanges(config.uidRanges),
355                                                     config.subPriority);
356     return statusFromErrcode(ret);
357 }
358 
networkRejectNonSecureVpn(bool add,const std::vector<UidRangeParcel> & uidRangeArray)359 binder::Status NetdNativeService::networkRejectNonSecureVpn(
360         bool add, const std::vector<UidRangeParcel>& uidRangeArray) {
361     // TODO: elsewhere RouteController is only used from the tethering and network controllers, so
362     // it should be possible to use the same lock as NetworkController. However, every call through
363     // the CommandListener "network" command will need to hold this lock too, not just the ones that
364     // read/modify network internal state (that is sufficient for ::dump() because it doesn't
365     // look at routes, but it's not enough here).
366     NETD_BIG_LOCK_RPC(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
367     UidRanges uidRanges(uidRangeArray);
368 
369     int err;
370     if (add) {
371         err = RouteController::addUsersToRejectNonSecureNetworkRule(uidRanges);
372     } else {
373         err = RouteController::removeUsersFromRejectNonSecureNetworkRule(uidRanges);
374     }
375     return statusFromErrcode(err);
376 }
377 
socketDestroy(const std::vector<UidRangeParcel> & uids,const std::vector<int32_t> & skipUids)378 binder::Status NetdNativeService::socketDestroy(const std::vector<UidRangeParcel>& uids,
379                                                 const std::vector<int32_t>& skipUids) {
380     ENFORCE_NETWORK_STACK_PERMISSIONS();
381 
382     SockDiag sd;
383     if (!sd.open()) {
384         return binder::Status::fromServiceSpecificError(EIO,
385                 String8("Could not open SOCK_DIAG socket"));
386     }
387 
388     UidRanges uidRanges(uids);
389     int err = sd.destroySockets(uidRanges, std::set<uid_t>(skipUids.begin(), skipUids.end()),
390                                 true /* excludeLoopback */);
391     if (err) {
392         return binder::Status::fromServiceSpecificError(-err,
393                 String8::format("destroySockets: %s", strerror(-err)));
394     }
395     return binder::Status::ok();
396 }
397 
tetherApplyDnsInterfaces(bool * ret)398 binder::Status NetdNativeService::tetherApplyDnsInterfaces(bool *ret) {
399     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
400     *ret = gCtls->tetherCtrl.applyDnsInterfaces();
401     return binder::Status::ok();
402 }
403 
404 namespace {
405 
406 constexpr const int UNUSED_IFINDEX = 0;
407 
tetherAddStatsByInterface(TetherController::TetherStats * tetherStatsParcel,const TetherController::TetherStats & tetherStats)408 void tetherAddStatsByInterface(TetherController::TetherStats* tetherStatsParcel,
409                                const TetherController::TetherStats& tetherStats) {
410     if (tetherStatsParcel->extIface == tetherStats.extIface) {
411         tetherStatsParcel->rxBytes += tetherStats.rxBytes;
412         tetherStatsParcel->rxPackets += tetherStats.rxPackets;
413         tetherStatsParcel->txBytes += tetherStats.txBytes;
414         tetherStatsParcel->txPackets += tetherStats.txPackets;
415     }
416 }
417 
toTetherStatsParcel(const TetherController::TetherStats & stats)418 TetherStatsParcel toTetherStatsParcel(const TetherController::TetherStats& stats) {
419     TetherStatsParcel result;
420     result.iface = stats.extIface;
421     result.rxBytes = stats.rxBytes;
422     result.rxPackets = stats.rxPackets;
423     result.txBytes = stats.txBytes;
424     result.txPackets = stats.txPackets;
425     result.ifIndex = UNUSED_IFINDEX;
426     return result;
427 }
428 
setTetherStatsParcelVecByInterface(std::vector<TetherStatsParcel> * tetherStatsVec,const TetherController::TetherStatsList & statsList)429 void setTetherStatsParcelVecByInterface(std::vector<TetherStatsParcel>* tetherStatsVec,
430                                         const TetherController::TetherStatsList& statsList) {
431     std::map<std::string, TetherController::TetherStats> statsMap;
432     for (const auto& stats : statsList) {
433         auto iter = statsMap.find(stats.extIface);
434         if (iter != statsMap.end()) {
435             tetherAddStatsByInterface(&(iter->second), stats);
436         } else {
437             statsMap.insert(
438                     std::pair<std::string, TetherController::TetherStats>(stats.extIface, stats));
439         }
440     }
441     for (auto iter = statsMap.begin(); iter != statsMap.end(); iter++) {
442         tetherStatsVec->push_back(toTetherStatsParcel(iter->second));
443     }
444 }
445 
tetherStatsParcelVecToStringVec(std::vector<TetherStatsParcel> * tVec)446 std::vector<std::string> tetherStatsParcelVecToStringVec(std::vector<TetherStatsParcel>* tVec) {
447     std::vector<std::string> result;
448     for (const auto& t : *tVec) {
449         result.push_back(StringPrintf("%s:%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64,
450                                       t.iface.c_str(), t.rxBytes, t.rxPackets, t.txBytes,
451                                       t.txPackets));
452     }
453     return result;
454 }
455 
456 }  // namespace
457 
tetherGetStats(std::vector<TetherStatsParcel> * tetherStatsParcelVec)458 binder::Status NetdNativeService::tetherGetStats(
459         std::vector<TetherStatsParcel>* tetherStatsParcelVec) {
460     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
461     const auto& statsList = gCtls->tetherCtrl.getTetherStats();
462     if (!isOk(statsList)) {
463         return asBinderStatus(statsList);
464     }
465     setTetherStatsParcelVecByInterface(tetherStatsParcelVec, statsList.value());
466     auto statsResults = tetherStatsParcelVecToStringVec(tetherStatsParcelVec);
467     return binder::Status::ok();
468 }
469 
interfaceAddAddress(const std::string & ifName,const std::string & addrString,int prefixLength)470 binder::Status NetdNativeService::interfaceAddAddress(const std::string &ifName,
471         const std::string &addrString, int prefixLength) {
472     ENFORCE_NETWORK_STACK_PERMISSIONS();
473     const int err = InterfaceController::addAddress(
474             ifName.c_str(), addrString.c_str(), prefixLength);
475     if (err != 0) {
476         return binder::Status::fromServiceSpecificError(-err,
477                 String8::format("InterfaceController error: %s", strerror(-err)));
478     }
479     return binder::Status::ok();
480 }
481 
interfaceDelAddress(const std::string & ifName,const std::string & addrString,int prefixLength)482 binder::Status NetdNativeService::interfaceDelAddress(const std::string &ifName,
483         const std::string &addrString, int prefixLength) {
484     ENFORCE_NETWORK_STACK_PERMISSIONS();
485     const int err = InterfaceController::delAddress(
486             ifName.c_str(), addrString.c_str(), prefixLength);
487     if (err != 0) {
488         return binder::Status::fromServiceSpecificError(-err,
489                 String8::format("InterfaceController error: %s", strerror(-err)));
490     }
491     return binder::Status::ok();
492 }
493 
494 namespace {
495 
getPathComponents(int32_t ipversion,int32_t category)496 std::tuple<binder::Status, const char*, const char*> getPathComponents(int32_t ipversion,
497                                                                        int32_t category) {
498     const char* ipversionStr = nullptr;
499     switch (ipversion) {
500         case INetd::IPV4:
501             ipversionStr = "ipv4";
502             break;
503         case INetd::IPV6:
504             ipversionStr = "ipv6";
505             break;
506         default:
507             return {binder::Status::fromServiceSpecificError(EAFNOSUPPORT, "Bad IP version"),
508                     nullptr, nullptr};
509     }
510 
511     const char* whichStr = nullptr;
512     switch (category) {
513         case INetd::CONF:
514             whichStr = "conf";
515             break;
516         case INetd::NEIGH:
517             whichStr = "neigh";
518             break;
519         default:
520             return {binder::Status::fromServiceSpecificError(EINVAL, "Bad category"), nullptr,
521                     nullptr};
522     }
523 
524     return {binder::Status::ok(), ipversionStr, whichStr};
525 }
526 
527 }  // namespace
528 
getProcSysNet(int32_t ipversion,int32_t which,const std::string & ifname,const std::string & parameter,std::string * value)529 binder::Status NetdNativeService::getProcSysNet(int32_t ipversion, int32_t which,
530                                                 const std::string& ifname,
531                                                 const std::string& parameter, std::string* value) {
532     ENFORCE_NETWORK_STACK_PERMISSIONS();
533     const auto pathParts = getPathComponents(ipversion, which);
534     const auto& pathStatus = std::get<0>(pathParts);
535     if (!pathStatus.isOk()) {
536         return pathStatus;
537     }
538 
539     const int err = InterfaceController::getParameter(std::get<1>(pathParts),
540                                                       std::get<2>(pathParts), ifname.c_str(),
541                                                       parameter.c_str(), value);
542     return statusFromErrcode(err);
543 }
544 
setProcSysNet(int32_t ipversion,int32_t which,const std::string & ifname,const std::string & parameter,const std::string & value)545 binder::Status NetdNativeService::setProcSysNet(int32_t ipversion, int32_t which,
546                                                 const std::string& ifname,
547                                                 const std::string& parameter,
548                                                 const std::string& value) {
549     ENFORCE_NETWORK_STACK_PERMISSIONS();
550     const auto pathParts = getPathComponents(ipversion, which);
551     const auto& pathStatus = std::get<0>(pathParts);
552     if (!pathStatus.isOk()) {
553         return pathStatus;
554     }
555 
556     const int err = InterfaceController::setParameter(std::get<1>(pathParts),
557                                                       std::get<2>(pathParts), ifname.c_str(),
558                                                       parameter.c_str(), value.c_str());
559     return statusFromErrcode(err);
560 }
561 
ipSecSetEncapSocketOwner(const ParcelFileDescriptor & socket,int newUid)562 binder::Status NetdNativeService::ipSecSetEncapSocketOwner(const ParcelFileDescriptor& socket,
563                                                            int newUid) {
564     ENFORCE_NETWORK_STACK_PERMISSIONS();
565 
566     uid_t callerUid = IPCThreadState::self()->getCallingUid();
567     return asBinderStatus(
568             gCtls->xfrmCtrl.ipSecSetEncapSocketOwner(socket.get(), newUid, callerUid));
569 }
570 
ipSecAllocateSpi(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t inSpi,int32_t * outSpi)571 binder::Status NetdNativeService::ipSecAllocateSpi(
572         int32_t transformId,
573         const std::string& sourceAddress,
574         const std::string& destinationAddress,
575         int32_t inSpi,
576         int32_t* outSpi) {
577     // Necessary locking done in IpSecService and kernel
578     ENFORCE_NETWORK_STACK_PERMISSIONS();
579     return asBinderStatus(gCtls->xfrmCtrl.ipSecAllocateSpi(
580                     transformId,
581                     sourceAddress,
582                     destinationAddress,
583                     inSpi,
584                     outSpi));
585 }
586 
ipSecAddSecurityAssociation(int32_t transformId,int32_t mode,const std::string & sourceAddress,const std::string & destinationAddress,int32_t underlyingNetId,int32_t spi,int32_t markValue,int32_t markMask,const std::string & authAlgo,const std::vector<uint8_t> & authKey,int32_t authTruncBits,const std::string & cryptAlgo,const std::vector<uint8_t> & cryptKey,int32_t cryptTruncBits,const std::string & aeadAlgo,const std::vector<uint8_t> & aeadKey,int32_t aeadIcvBits,int32_t encapType,int32_t encapLocalPort,int32_t encapRemotePort,int32_t interfaceId)587 binder::Status NetdNativeService::ipSecAddSecurityAssociation(
588         int32_t transformId, int32_t mode, const std::string& sourceAddress,
589         const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi,
590         int32_t markValue, int32_t markMask, const std::string& authAlgo,
591         const std::vector<uint8_t>& authKey, int32_t authTruncBits, const std::string& cryptAlgo,
592         const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits, const std::string& aeadAlgo,
593         const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits, int32_t encapType,
594         int32_t encapLocalPort, int32_t encapRemotePort, int32_t interfaceId) {
595     // Necessary locking done in IpSecService and kernel
596     ENFORCE_NETWORK_STACK_PERMISSIONS();
597     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddSecurityAssociation(
598             transformId, mode, sourceAddress, destinationAddress, underlyingNetId, spi, markValue,
599             markMask, authAlgo, authKey, authTruncBits, cryptAlgo, cryptKey, cryptTruncBits,
600             aeadAlgo, aeadKey, aeadIcvBits, encapType, encapLocalPort, encapRemotePort,
601             interfaceId));
602 }
603 
ipSecDeleteSecurityAssociation(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)604 binder::Status NetdNativeService::ipSecDeleteSecurityAssociation(
605         int32_t transformId, const std::string& sourceAddress,
606         const std::string& destinationAddress, int32_t spi, int32_t markValue, int32_t markMask,
607         int32_t interfaceId) {
608     // Necessary locking done in IpSecService and kernel
609     ENFORCE_NETWORK_STACK_PERMISSIONS();
610     return asBinderStatus(gCtls->xfrmCtrl.ipSecDeleteSecurityAssociation(
611             transformId, sourceAddress, destinationAddress, spi, markValue, markMask, interfaceId));
612 }
613 
ipSecApplyTransportModeTransform(const ParcelFileDescriptor & socket,int32_t transformId,int32_t direction,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi)614 binder::Status NetdNativeService::ipSecApplyTransportModeTransform(
615         const ParcelFileDescriptor& socket, int32_t transformId, int32_t direction,
616         const std::string& sourceAddress, const std::string& destinationAddress, int32_t spi) {
617     // Necessary locking done in IpSecService and kernel
618     ENFORCE_NETWORK_STACK_PERMISSIONS();
619     return asBinderStatus(gCtls->xfrmCtrl.ipSecApplyTransportModeTransform(
620             socket.get(), transformId, direction, sourceAddress, destinationAddress, spi));
621 }
622 
ipSecRemoveTransportModeTransform(const ParcelFileDescriptor & socket)623 binder::Status NetdNativeService::ipSecRemoveTransportModeTransform(
624         const ParcelFileDescriptor& socket) {
625     // Necessary locking done in IpSecService and kernel
626     ENFORCE_NETWORK_STACK_PERMISSIONS();
627     return asBinderStatus(gCtls->xfrmCtrl.ipSecRemoveTransportModeTransform(socket.get()));
628 }
629 
ipSecAddSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)630 binder::Status NetdNativeService::ipSecAddSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
631                                                          int32_t direction,
632                                                          const std::string& tmplSrcAddress,
633                                                          const std::string& tmplDstAddress,
634                                                          int32_t spi, int32_t markValue,
635                                                          int32_t markMask, int32_t interfaceId) {
636     // Necessary locking done in IpSecService and kernel
637     ENFORCE_NETWORK_STACK_PERMISSIONS();
638     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddSecurityPolicy(
639             transformId, selAddrFamily, direction, tmplSrcAddress, tmplDstAddress, spi, markValue,
640             markMask, interfaceId));
641 }
642 
ipSecUpdateSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)643 binder::Status NetdNativeService::ipSecUpdateSecurityPolicy(
644         int32_t transformId, int32_t selAddrFamily, int32_t direction,
645         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
646         int32_t markValue, int32_t markMask, int32_t interfaceId) {
647     // Necessary locking done in IpSecService and kernel
648     ENFORCE_NETWORK_STACK_PERMISSIONS();
649     return asBinderStatus(gCtls->xfrmCtrl.ipSecUpdateSecurityPolicy(
650             transformId, selAddrFamily, direction, tmplSrcAddress, tmplDstAddress, spi, markValue,
651             markMask, interfaceId));
652 }
653 
ipSecDeleteSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,int32_t markValue,int32_t markMask,int32_t interfaceId)654 binder::Status NetdNativeService::ipSecDeleteSecurityPolicy(int32_t transformId,
655                                                             int32_t selAddrFamily,
656                                                             int32_t direction, int32_t markValue,
657                                                             int32_t markMask, int32_t interfaceId) {
658     // Necessary locking done in IpSecService and kernel
659     ENFORCE_NETWORK_STACK_PERMISSIONS();
660     return asBinderStatus(gCtls->xfrmCtrl.ipSecDeleteSecurityPolicy(
661             transformId, selAddrFamily, direction, markValue, markMask, interfaceId));
662 }
663 
ipSecAddTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t iKey,int32_t oKey,int32_t interfaceId)664 binder::Status NetdNativeService::ipSecAddTunnelInterface(const std::string& deviceName,
665                                                           const std::string& localAddress,
666                                                           const std::string& remoteAddress,
667                                                           int32_t iKey, int32_t oKey,
668                                                           int32_t interfaceId) {
669     // Necessary locking done in IpSecService and kernel
670     ENFORCE_NETWORK_STACK_PERMISSIONS();
671     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddTunnelInterface(
672             deviceName, localAddress, remoteAddress, iKey, oKey, interfaceId, false));
673 }
674 
ipSecUpdateTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t iKey,int32_t oKey,int32_t interfaceId)675 binder::Status NetdNativeService::ipSecUpdateTunnelInterface(const std::string& deviceName,
676                                                              const std::string& localAddress,
677                                                              const std::string& remoteAddress,
678                                                              int32_t iKey, int32_t oKey,
679                                                              int32_t interfaceId) {
680     // Necessary locking done in IpSecService and kernel
681     ENFORCE_NETWORK_STACK_PERMISSIONS();
682     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddTunnelInterface(
683             deviceName, localAddress, remoteAddress, iKey, oKey, interfaceId, true));
684 }
685 
ipSecRemoveTunnelInterface(const std::string & deviceName)686 binder::Status NetdNativeService::ipSecRemoveTunnelInterface(const std::string& deviceName) {
687     // Necessary locking done in IpSecService and kernel
688     ENFORCE_NETWORK_STACK_PERMISSIONS();
689     return asBinderStatus(gCtls->xfrmCtrl.ipSecRemoveTunnelInterface(deviceName));
690 }
691 
ipSecMigrate(const IpSecMigrateInfoParcel & migrateInfo)692 binder::Status NetdNativeService::ipSecMigrate(const IpSecMigrateInfoParcel& migrateInfo) {
693     // Necessary locking done in IpSecService and kernel
694     ENFORCE_NETWORK_STACK_PERMISSIONS();
695     return asBinderStatus(gCtls->xfrmCtrl.ipSecMigrate(
696             migrateInfo.requestId, migrateInfo.selAddrFamily, migrateInfo.direction,
697             migrateInfo.oldSourceAddress, migrateInfo.oldDestinationAddress,
698             migrateInfo.newSourceAddress, migrateInfo.newDestinationAddress,
699             migrateInfo.interfaceId));
700 }
701 
setIPv6AddrGenMode(const std::string & ifName,int32_t mode)702 binder::Status NetdNativeService::setIPv6AddrGenMode(const std::string& ifName,
703                                                      int32_t mode) {
704     ENFORCE_NETWORK_STACK_PERMISSIONS();
705     return asBinderStatus(InterfaceController::setIPv6AddrGenMode(ifName, mode));
706 }
707 
wakeupAddInterface(const std::string & ifName,const std::string & prefix,int32_t mark,int32_t mask)708 binder::Status NetdNativeService::wakeupAddInterface(const std::string& ifName,
709                                                      const std::string& prefix, int32_t mark,
710                                                      int32_t mask) {
711     ENFORCE_NETWORK_STACK_PERMISSIONS();
712     return asBinderStatus(gCtls->wakeupCtrl.addInterface(ifName, prefix, mark, mask));
713 }
714 
wakeupDelInterface(const std::string & ifName,const std::string & prefix,int32_t mark,int32_t mask)715 binder::Status NetdNativeService::wakeupDelInterface(const std::string& ifName,
716                                                      const std::string& prefix, int32_t mark,
717                                                      int32_t mask) {
718     ENFORCE_NETWORK_STACK_PERMISSIONS();
719     return asBinderStatus(gCtls->wakeupCtrl.delInterface(ifName, prefix, mark, mask));
720 }
721 
trafficSwapActiveStatsMap()722 binder::Status NetdNativeService::trafficSwapActiveStatsMap() {
723     DEPRECATED;
724 }
725 
idletimerAddInterface(const std::string & ifName,int32_t timeout,const std::string & classLabel)726 binder::Status NetdNativeService::idletimerAddInterface(const std::string& ifName, int32_t timeout,
727                                                         const std::string& classLabel) {
728     NETD_LOCKING_RPC(gCtls->idletimerCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
729     int res =
730             gCtls->idletimerCtrl.addInterfaceIdletimer(ifName.c_str(), timeout, classLabel.c_str());
731     return statusFromErrcode(res);
732 }
733 
idletimerRemoveInterface(const std::string & ifName,int32_t timeout,const std::string & classLabel)734 binder::Status NetdNativeService::idletimerRemoveInterface(const std::string& ifName,
735                                                            int32_t timeout,
736                                                            const std::string& classLabel) {
737     NETD_LOCKING_RPC(gCtls->idletimerCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
738     int res = gCtls->idletimerCtrl.removeInterfaceIdletimer(ifName.c_str(), timeout,
739                                                             classLabel.c_str());
740     return statusFromErrcode(res);
741 }
742 
strictUidCleartextPenalty(int32_t uid,int32_t policyPenalty)743 binder::Status NetdNativeService::strictUidCleartextPenalty(int32_t uid, int32_t policyPenalty) {
744     NETD_LOCKING_RPC(gCtls->strictCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
745     StrictPenalty penalty;
746     switch (policyPenalty) {
747         case INetd::PENALTY_POLICY_REJECT:
748             penalty = REJECT;
749             break;
750         case INetd::PENALTY_POLICY_LOG:
751             penalty = LOG;
752             break;
753         case INetd::PENALTY_POLICY_ACCEPT:
754             penalty = ACCEPT;
755             break;
756         default:
757             return statusFromErrcode(-EINVAL);
758             break;
759     }
760     int res = gCtls->strictCtrl.setUidCleartextPenalty((uid_t) uid, penalty);
761     return statusFromErrcode(res);
762 }
763 
clatdStart(const std::string &,const std::string &,std::string *)764 binder::Status NetdNativeService::clatdStart(const std::string& /* ifName */,
765                                              const std::string& /* nat64Prefix */,
766                                              std::string* /* v6Addr */) {
767     DEPRECATED;
768 }
769 
clatdStop(const std::string &)770 binder::Status NetdNativeService::clatdStop(const std::string& /* ifName */) {
771     DEPRECATED;
772 }
773 
ipfwdEnabled(bool * status)774 binder::Status NetdNativeService::ipfwdEnabled(bool* status) {
775     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
776     *status = (gCtls->tetherCtrl.getIpfwdRequesterList().size() > 0) ? true : false;
777     return binder::Status::ok();
778 }
779 
ipfwdGetRequesterList(std::vector<std::string> * requesterList)780 binder::Status NetdNativeService::ipfwdGetRequesterList(std::vector<std::string>* requesterList) {
781     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
782     for (const auto& requester : gCtls->tetherCtrl.getIpfwdRequesterList()) {
783         requesterList->push_back(requester);
784     }
785     return binder::Status::ok();
786 }
787 
ipfwdEnableForwarding(const std::string & requester)788 binder::Status NetdNativeService::ipfwdEnableForwarding(const std::string& requester) {
789     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
790     int res = (gCtls->tetherCtrl.enableForwarding(requester.c_str())) ? 0 : -EREMOTEIO;
791     return statusFromErrcode(res);
792 }
793 
ipfwdDisableForwarding(const std::string & requester)794 binder::Status NetdNativeService::ipfwdDisableForwarding(const std::string& requester) {
795     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
796     int res = (gCtls->tetherCtrl.disableForwarding(requester.c_str())) ? 0 : -EREMOTEIO;
797     return statusFromErrcode(res);
798 }
799 
ipfwdAddInterfaceForward(const std::string & fromIface,const std::string & toIface)800 binder::Status NetdNativeService::ipfwdAddInterfaceForward(const std::string& fromIface,
801                                                            const std::string& toIface) {
802     ENFORCE_NETWORK_STACK_PERMISSIONS();
803     int res = RouteController::enableTethering(fromIface.c_str(), toIface.c_str());
804     return statusFromErrcode(res);
805 }
806 
ipfwdRemoveInterfaceForward(const std::string & fromIface,const std::string & toIface)807 binder::Status NetdNativeService::ipfwdRemoveInterfaceForward(const std::string& fromIface,
808                                                               const std::string& toIface) {
809     ENFORCE_NETWORK_STACK_PERMISSIONS();
810     int res = RouteController::disableTethering(fromIface.c_str(), toIface.c_str());
811     return statusFromErrcode(res);
812 }
813 
814 namespace {
815 
addCurlyBrackets(const std::string & s)816 std::string addCurlyBrackets(const std::string& s) {
817     return "{" + s + "}";
818 }
819 
820 }  // namespace
821 
interfaceGetList(std::vector<std::string> * interfaceListResult)822 binder::Status NetdNativeService::interfaceGetList(std::vector<std::string>* interfaceListResult) {
823     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
824     const auto& ifaceList = getIfaceNames();
825 
826     interfaceListResult->clear();
827     interfaceListResult->reserve(ifaceList.value().size());
828     interfaceListResult->insert(end(*interfaceListResult), begin(ifaceList.value()),
829                                 end(ifaceList.value()));
830 
831     return binder::Status::ok();
832 }
833 
interfaceConfigurationParcelToString(const InterfaceConfigurationParcel & cfg)834 std::string interfaceConfigurationParcelToString(const InterfaceConfigurationParcel& cfg) {
835     std::vector<std::string> result{cfg.ifName, cfg.hwAddr, cfg.ipv4Addr,
836                                     std::to_string(cfg.prefixLength)};
837     result.insert(end(result), begin(cfg.flags), end(cfg.flags));
838     return addCurlyBrackets(base::Join(result, ", "));
839 }
840 
interfaceGetCfg(const std::string & ifName,InterfaceConfigurationParcel * interfaceGetCfgResult)841 binder::Status NetdNativeService::interfaceGetCfg(
842         const std::string& ifName, InterfaceConfigurationParcel* interfaceGetCfgResult) {
843     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
844     auto entry = gLog.newEntry().prettyFunction(__PRETTY_FUNCTION__).arg(ifName);
845 
846     const auto& cfgRes = InterfaceController::getCfg(ifName);
847     RETURN_BINDER_STATUS_IF_NOT_OK(entry, cfgRes);
848 
849     *interfaceGetCfgResult = cfgRes.value();
850     gLog.log(entry.returns(interfaceConfigurationParcelToString(*interfaceGetCfgResult))
851                      .withAutomaticDuration());
852     return binder::Status::ok();
853 }
854 
interfaceSetCfg(const InterfaceConfigurationParcel & cfg)855 binder::Status NetdNativeService::interfaceSetCfg(const InterfaceConfigurationParcel& cfg) {
856     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
857     auto entry = gLog.newEntry()
858                          .prettyFunction(__PRETTY_FUNCTION__)
859                          .arg(interfaceConfigurationParcelToString(cfg));
860 
861     const auto& res = InterfaceController::setCfg(cfg);
862     RETURN_BINDER_STATUS_IF_NOT_OK(entry, res);
863 
864     gLog.log(entry.withAutomaticDuration());
865     return binder::Status::ok();
866 }
867 
interfaceSetIPv6PrivacyExtensions(const std::string & ifName,bool enable)868 binder::Status NetdNativeService::interfaceSetIPv6PrivacyExtensions(const std::string& ifName,
869                                                                     bool enable) {
870     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
871     int res = InterfaceController::setIPv6PrivacyExtensions(ifName.c_str(), enable);
872     return statusFromErrcode(res);
873 }
874 
interfaceClearAddrs(const std::string & ifName)875 binder::Status NetdNativeService::interfaceClearAddrs(const std::string& ifName) {
876     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
877     int res = InterfaceController::clearAddrs(ifName.c_str());
878     return statusFromErrcode(res);
879 }
880 
interfaceSetEnableIPv6(const std::string & ifName,bool enable)881 binder::Status NetdNativeService::interfaceSetEnableIPv6(const std::string& ifName, bool enable) {
882     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
883     int res = InterfaceController::setEnableIPv6(ifName.c_str(), enable);
884     return statusFromErrcode(res);
885 }
886 
interfaceSetMtu(const std::string & ifName,int32_t mtuValue)887 binder::Status NetdNativeService::interfaceSetMtu(const std::string& ifName, int32_t mtuValue) {
888     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
889     std::string mtu = std::to_string(mtuValue);
890     int res = InterfaceController::setMtu(ifName.c_str(), mtu.c_str());
891     return statusFromErrcode(res);
892 }
893 
tetherStart(const std::vector<std::string> & dhcpRanges)894 binder::Status NetdNativeService::tetherStart(const std::vector<std::string>& dhcpRanges) {
895     TetherConfigParcel config;
896     config.usingLegacyDnsProxy = true;
897     config.dhcpRanges = dhcpRanges;
898     return tetherStartWithConfiguration(config);
899 }
900 
tetherStartWithConfiguration(const TetherConfigParcel & config)901 binder::Status NetdNativeService::tetherStartWithConfiguration(const TetherConfigParcel& config) {
902     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
903     if (config.dhcpRanges.size() % 2 == 1) {
904         return statusFromErrcode(-EINVAL);
905     }
906     // TODO: Pass TetherConfigParcel directly.
907     int res = gCtls->tetherCtrl.startTethering(config.usingLegacyDnsProxy, config.dhcpRanges);
908     return statusFromErrcode(res);
909 }
910 
tetherStop()911 binder::Status NetdNativeService::tetherStop() {
912     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
913     int res = gCtls->tetherCtrl.stopTethering();
914     return statusFromErrcode(res);
915 }
916 
tetherIsEnabled(bool * enabled)917 binder::Status NetdNativeService::tetherIsEnabled(bool* enabled) {
918     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
919     *enabled = gCtls->tetherCtrl.isTetheringStarted();
920     return binder::Status::ok();
921 }
922 
tetherInterfaceAdd(const std::string & ifName)923 binder::Status NetdNativeService::tetherInterfaceAdd(const std::string& ifName) {
924     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
925     int res = gCtls->tetherCtrl.tetherInterface(ifName.c_str());
926     return statusFromErrcode(res);
927 }
928 
tetherInterfaceRemove(const std::string & ifName)929 binder::Status NetdNativeService::tetherInterfaceRemove(const std::string& ifName) {
930     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
931     int res = gCtls->tetherCtrl.untetherInterface(ifName.c_str());
932     return statusFromErrcode(res);
933 }
934 
tetherInterfaceList(std::vector<std::string> * ifList)935 binder::Status NetdNativeService::tetherInterfaceList(std::vector<std::string>* ifList) {
936     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
937     for (const auto& ifname : gCtls->tetherCtrl.getTetheredInterfaceList()) {
938         ifList->push_back(ifname);
939     }
940     return binder::Status::ok();
941 }
942 
tetherDnsSet(int32_t netId,const std::vector<std::string> & dnsAddrs)943 binder::Status NetdNativeService::tetherDnsSet(int32_t netId,
944                                                const std::vector<std::string>& dnsAddrs) {
945     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
946     int res = gCtls->tetherCtrl.setDnsForwarders(netId, dnsAddrs);
947     return statusFromErrcode(res);
948 }
949 
tetherDnsList(std::vector<std::string> * dnsList)950 binder::Status NetdNativeService::tetherDnsList(std::vector<std::string>* dnsList) {
951     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
952     for (const auto& fwdr : gCtls->tetherCtrl.getDnsForwarders()) {
953         dnsList->push_back(fwdr);
954     }
955     return binder::Status::ok();
956 }
957 
networkAddRouteParcel(int32_t netId,const RouteInfoParcel & route)958 binder::Status NetdNativeService::networkAddRouteParcel(int32_t netId,
959                                                         const RouteInfoParcel& route) {
960     // Public methods of NetworkController are thread-safe.
961     ENFORCE_NETWORK_STACK_PERMISSIONS();
962     bool legacy = false;
963     uid_t uid = 0;  // UID is only meaningful for legacy routes.
964 
965     // convert Parcel to parameters
966     int res = gCtls->netCtrl.addRoute(netId, route.ifName.c_str(), route.destination.c_str(),
967                                       route.nextHop.empty() ? nullptr : route.nextHop.c_str(),
968                                       legacy, uid, route.mtu);
969     return statusFromErrcode(res);
970 }
971 
networkUpdateRouteParcel(int32_t netId,const RouteInfoParcel & route)972 binder::Status NetdNativeService::networkUpdateRouteParcel(int32_t netId,
973                                                            const RouteInfoParcel& route) {
974     // Public methods of NetworkController are thread-safe.
975     ENFORCE_NETWORK_STACK_PERMISSIONS();
976     bool legacy = false;
977     uid_t uid = 0;  // UID is only meaningful for legacy routes.
978 
979     // convert Parcel to parameters
980     int res = gCtls->netCtrl.updateRoute(netId, route.ifName.c_str(), route.destination.c_str(),
981                                          route.nextHop.empty() ? nullptr : route.nextHop.c_str(),
982                                          legacy, uid, route.mtu);
983     return statusFromErrcode(res);
984 }
985 
networkRemoveRouteParcel(int32_t netId,const RouteInfoParcel & route)986 binder::Status NetdNativeService::networkRemoveRouteParcel(int32_t netId,
987                                                            const RouteInfoParcel& route) {
988     return networkRemoveRoute(netId, route.ifName, route.destination, route.nextHop);
989 }
990 
networkAddRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)991 binder::Status NetdNativeService::networkAddRoute(int32_t netId, const std::string& ifName,
992                                                   const std::string& destination,
993                                                   const std::string& nextHop) {
994     // Public methods of NetworkController are thread-safe.
995     ENFORCE_NETWORK_STACK_PERMISSIONS();
996     bool legacy = false;
997     uid_t uid = 0;  // UID is only meaningful for legacy routes.
998     int res = gCtls->netCtrl.addRoute(netId, ifName.c_str(), destination.c_str(),
999                                       nextHop.empty() ? nullptr : nextHop.c_str(), legacy, uid, 0);
1000     return statusFromErrcode(res);
1001 }
1002 
networkRemoveRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)1003 binder::Status NetdNativeService::networkRemoveRoute(int32_t netId, const std::string& ifName,
1004                                                      const std::string& destination,
1005                                                      const std::string& nextHop) {
1006     ENFORCE_NETWORK_STACK_PERMISSIONS();
1007     bool legacy = false;
1008     uid_t uid = 0;  // UID is only meaningful for legacy routes.
1009     int res = gCtls->netCtrl.removeRoute(netId, ifName.c_str(), destination.c_str(),
1010                                          nextHop.empty() ? nullptr : nextHop.c_str(), legacy, uid);
1011     return statusFromErrcode(res);
1012 }
1013 
networkAddLegacyRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop,int32_t uid)1014 binder::Status NetdNativeService::networkAddLegacyRoute(int32_t netId, const std::string& ifName,
1015                                                         const std::string& destination,
1016                                                         const std::string& nextHop, int32_t uid) {
1017     ENFORCE_NETWORK_STACK_PERMISSIONS();
1018     bool legacy = true;
1019     int res = gCtls->netCtrl.addRoute(netId, ifName.c_str(), destination.c_str(),
1020                                       nextHop.empty() ? nullptr : nextHop.c_str(), legacy,
1021                                       (uid_t)uid, 0);
1022     return statusFromErrcode(res);
1023 }
1024 
networkRemoveLegacyRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop,int32_t uid)1025 binder::Status NetdNativeService::networkRemoveLegacyRoute(int32_t netId, const std::string& ifName,
1026                                                            const std::string& destination,
1027                                                            const std::string& nextHop,
1028                                                            int32_t uid) {
1029     ENFORCE_NETWORK_STACK_PERMISSIONS();
1030     bool legacy = true;
1031     int res = gCtls->netCtrl.removeRoute(netId, ifName.c_str(), destination.c_str(),
1032                                          nextHop.empty() ? nullptr : nextHop.c_str(), legacy,
1033                                          (uid_t) uid);
1034     return statusFromErrcode(res);
1035 }
1036 
networkGetDefault(int32_t * netId)1037 binder::Status NetdNativeService::networkGetDefault(int32_t* netId) {
1038     ENFORCE_NETWORK_STACK_PERMISSIONS();
1039     *netId = gCtls->netCtrl.getDefaultNetwork();
1040     return binder::Status::ok();
1041 }
1042 
networkSetDefault(int32_t netId)1043 binder::Status NetdNativeService::networkSetDefault(int32_t netId) {
1044     ENFORCE_NETWORK_STACK_PERMISSIONS();
1045     int res = gCtls->netCtrl.setDefaultNetwork(netId);
1046     return statusFromErrcode(res);
1047 }
1048 
networkClearDefault()1049 binder::Status NetdNativeService::networkClearDefault() {
1050     ENFORCE_NETWORK_STACK_PERMISSIONS();
1051     unsigned netId = NETID_UNSET;
1052     int res = gCtls->netCtrl.setDefaultNetwork(netId);
1053     return statusFromErrcode(res);
1054 }
1055 
intsToUids(const std::vector<int32_t> & intUids)1056 std::vector<uid_t> NetdNativeService::intsToUids(const std::vector<int32_t>& intUids) {
1057     return {begin(intUids), end(intUids)};
1058 }
1059 
convertPermission(int32_t permission)1060 Permission NetdNativeService::convertPermission(int32_t permission) {
1061     switch (permission) {
1062         case INetd::PERMISSION_NETWORK:
1063             return Permission::PERMISSION_NETWORK;
1064         case INetd::PERMISSION_SYSTEM:
1065             return Permission::PERMISSION_SYSTEM;
1066         default:
1067             return Permission::PERMISSION_NONE;
1068     }
1069 }
1070 
networkSetPermissionForNetwork(int32_t netId,int32_t permission)1071 binder::Status NetdNativeService::networkSetPermissionForNetwork(int32_t netId,
1072                                                                  int32_t permission) {
1073     ENFORCE_NETWORK_STACK_PERMISSIONS();
1074     std::vector<unsigned> netIds = {(unsigned) netId};
1075     int res = gCtls->netCtrl.setPermissionForNetworks(convertPermission(permission), netIds);
1076     return statusFromErrcode(res);
1077 }
1078 
networkSetPermissionForUser(int32_t permission,const std::vector<int32_t> & uids)1079 binder::Status NetdNativeService::networkSetPermissionForUser(int32_t permission,
1080                                                               const std::vector<int32_t>& uids) {
1081     ENFORCE_NETWORK_STACK_PERMISSIONS();
1082     gCtls->netCtrl.setPermissionForUsers(convertPermission(permission), intsToUids(uids));
1083     return binder::Status::ok();
1084 }
1085 
networkClearPermissionForUser(const std::vector<int32_t> & uids)1086 binder::Status NetdNativeService::networkClearPermissionForUser(const std::vector<int32_t>& uids) {
1087     ENFORCE_NETWORK_STACK_PERMISSIONS();
1088     Permission permission = Permission::PERMISSION_NONE;
1089     gCtls->netCtrl.setPermissionForUsers(permission, intsToUids(uids));
1090     return binder::Status::ok();
1091 }
1092 
networkSetProtectAllow(int32_t uid)1093 binder::Status NetdNativeService::networkSetProtectAllow(int32_t uid) {
1094     ENFORCE_NETWORK_STACK_PERMISSIONS();
1095     gCtls->netCtrl.allowProtect((uid_t)uid, NETID_UNSET);
1096     return binder::Status::ok();
1097 }
1098 
networkSetProtectDeny(int32_t uid)1099 binder::Status NetdNativeService::networkSetProtectDeny(int32_t uid) {
1100     ENFORCE_NETWORK_STACK_PERMISSIONS();
1101     gCtls->netCtrl.denyProtect((uid_t)uid, NETID_UNSET);
1102     return binder::Status::ok();
1103 }
1104 
networkCanProtect(int32_t uid,bool * ret)1105 binder::Status NetdNativeService::networkCanProtect(int32_t uid, bool* ret) {
1106     ENFORCE_NETWORK_STACK_PERMISSIONS();
1107     *ret = gCtls->netCtrl.canProtect((uid_t)uid, NETID_UNSET);
1108     return binder::Status::ok();
1109 }
1110 
networkAllowBypassVpnOnNetwork(bool allow,int32_t uid,int32_t netId)1111 binder::Status NetdNativeService::networkAllowBypassVpnOnNetwork(bool allow, int32_t uid,
1112                                                                  int32_t netId) {
1113     ENFORCE_NETWORK_STACK_PERMISSIONS();
1114     int err;
1115     if (allow) {
1116         err = gCtls->netCtrl.allowProtect((uid_t)uid, netId);
1117     } else {
1118         err = gCtls->netCtrl.denyProtect((uid_t)uid, netId);
1119     }
1120     return statusFromErrcode(err);
1121 }
1122 
trafficSetNetPermForUids(int32_t,const std::vector<int32_t> &)1123 binder::Status NetdNativeService::trafficSetNetPermForUids(int32_t, const std::vector<int32_t>&) {
1124     DEPRECATED;
1125 }
1126 
firewallSetFirewallType(int32_t firewallType)1127 binder::Status NetdNativeService::firewallSetFirewallType(int32_t firewallType) {
1128     NETD_LOCKING_RPC(gCtls->firewallCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1129     auto type = static_cast<FirewallType>(firewallType);
1130 
1131     int res = gCtls->firewallCtrl.setFirewallType(type);
1132     return statusFromErrcode(res);
1133 }
1134 
firewallSetInterfaceRule(const std::string & ifName,int32_t firewallRule)1135 binder::Status NetdNativeService::firewallSetInterfaceRule(const std::string& ifName,
1136                                                            int32_t firewallRule) {
1137     NETD_LOCKING_RPC(gCtls->firewallCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1138     auto rule = static_cast<FirewallRule>(firewallRule);
1139 
1140     int res = gCtls->firewallCtrl.setInterfaceRule(ifName.c_str(), rule);
1141     return statusFromErrcode(res);
1142 }
1143 
firewallSetUidRule(int32_t,int32_t,int32_t)1144 binder::Status NetdNativeService::firewallSetUidRule(int32_t, int32_t, int32_t) {
1145     DEPRECATED;
1146 }
1147 
firewallEnableChildChain(int32_t,bool)1148 binder::Status NetdNativeService::firewallEnableChildChain(int32_t, bool) {
1149     DEPRECATED;
1150 }
1151 
firewallAddUidInterfaceRules(const std::string &,const std::vector<int32_t> &)1152 binder::Status NetdNativeService::firewallAddUidInterfaceRules(const std::string&,
1153                                                                const std::vector<int32_t>&) {
1154     DEPRECATED;
1155 }
1156 
firewallRemoveUidInterfaceRules(const std::vector<int32_t> &)1157 binder::Status NetdNativeService::firewallRemoveUidInterfaceRules(const std::vector<int32_t>&) {
1158     DEPRECATED;
1159 }
1160 
tetherAddForward(const std::string & intIface,const std::string & extIface)1161 binder::Status NetdNativeService::tetherAddForward(const std::string& intIface,
1162                                                    const std::string& extIface) {
1163     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1164 
1165     int res = gCtls->tetherCtrl.enableNat(intIface.c_str(), extIface.c_str());
1166     return statusFromErrcode(res);
1167 }
1168 
tetherRemoveForward(const std::string & intIface,const std::string & extIface)1169 binder::Status NetdNativeService::tetherRemoveForward(const std::string& intIface,
1170                                                       const std::string& extIface) {
1171     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1172     int res = gCtls->tetherCtrl.disableNat(intIface.c_str(), extIface.c_str());
1173     return statusFromErrcode(res);
1174 }
1175 
setTcpRWmemorySize(const std::string & rmemValues,const std::string & wmemValues)1176 binder::Status NetdNativeService::setTcpRWmemorySize(const std::string& rmemValues,
1177                                                      const std::string& wmemValues) {
1178     ENFORCE_NETWORK_STACK_PERMISSIONS();
1179     if (!WriteStringToFile(rmemValues, TCP_RMEM_PROC_FILE)) {
1180         int ret = -errno;
1181         return statusFromErrcode(ret);
1182     }
1183 
1184     if (!WriteStringToFile(wmemValues, TCP_WMEM_PROC_FILE)) {
1185         int ret = -errno;
1186         return statusFromErrcode(ret);
1187     }
1188     return binder::Status::ok();
1189 }
1190 
registerUnsolicitedEventListener(const android::sp<android::net::INetdUnsolicitedEventListener> & listener)1191 binder::Status NetdNativeService::registerUnsolicitedEventListener(
1192         const android::sp<android::net::INetdUnsolicitedEventListener>& listener) {
1193     ENFORCE_NETWORK_STACK_PERMISSIONS();
1194     gCtls->eventReporter.registerUnsolEventListener(listener);
1195     return binder::Status::ok();
1196 }
1197 
getOemNetd(android::sp<android::IBinder> * listener)1198 binder::Status NetdNativeService::getOemNetd(android::sp<android::IBinder>* listener) {
1199     ENFORCE_NETWORK_STACK_PERMISSIONS();
1200     *listener = com::android::internal::net::OemNetdListener::getListener();
1201 
1202     return binder::Status::ok();
1203 }
1204 
getFwmarkForNetwork(int32_t netId,MarkMaskParcel * markMask)1205 binder::Status NetdNativeService::getFwmarkForNetwork(int32_t netId, MarkMaskParcel* markMask) {
1206     ENFORCE_NETWORK_STACK_PERMISSIONS();
1207 
1208     Fwmark fwmark;
1209     fwmark.netId = netId;
1210     markMask->mask = FWMARK_NET_ID_MASK;
1211     markMask->mark = fwmark.intValue;
1212     return binder::Status::ok();
1213 }
1214 
tetherOffloadRuleAdd(const TetherOffloadRuleParcel &)1215 binder::Status NetdNativeService::tetherOffloadRuleAdd(const TetherOffloadRuleParcel& /* rule */) {
1216     DEPRECATED;
1217 }
1218 
tetherOffloadRuleRemove(const TetherOffloadRuleParcel &)1219 binder::Status NetdNativeService::tetherOffloadRuleRemove(
1220         const TetherOffloadRuleParcel& /* rule */) {
1221     DEPRECATED;
1222 }
1223 
tetherOffloadGetStats(std::vector<TetherStatsParcel> *)1224 binder::Status NetdNativeService::tetherOffloadGetStats(
1225         std::vector<TetherStatsParcel>* /* tetherStatsParcelVec */) {
1226     DEPRECATED;
1227 }
1228 
tetherOffloadSetInterfaceQuota(int,int64_t)1229 binder::Status NetdNativeService::tetherOffloadSetInterfaceQuota(int /* ifIndex */,
1230                                                                  int64_t /* quotaBytes */) {
1231     DEPRECATED;
1232 }
1233 
tetherOffloadGetAndClearStats(int,android::net::TetherStatsParcel *)1234 binder::Status NetdNativeService::tetherOffloadGetAndClearStats(
1235         int /* ifIndex */, android::net::TetherStatsParcel* /* tetherStats */) {
1236     DEPRECATED;
1237 }
1238 
setNetworkAllowlist(const std::vector<NativeUidRangeConfig> & rangeConfigs)1239 binder::Status NetdNativeService::setNetworkAllowlist(
1240         const std::vector<NativeUidRangeConfig>& rangeConfigs) {
1241     ENFORCE_NETWORK_STACK_PERMISSIONS();
1242     return statusFromErrcode(gCtls->netCtrl.setNetworkAllowlist(rangeConfigs));
1243 }
1244 
1245 }  // namespace net
1246 }  // namespace android
1247