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