1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "conn_manager.h"
17 
18 #include <linux/if_ether.h>
19 #include <net/if.h>
20 #include <ifaddrs.h>
21 #include <string>
22 
23 #include "bpf_def.h"
24 #include "bpf_mapper.h"
25 #include "bpf_path.h"
26 #include "local_network.h"
27 #include "netlink_socket_diag.h"
28 #include "net_manager_constants.h"
29 #include "netlink_socket_diag.h"
30 #include "netmanager_base_common_utils.h"
31 #include "netnative_log_wrapper.h"
32 #include "physical_network.h"
33 #include "virtual_network.h"
34 #include "securec.h"
35 #include "bpf_ring_buffer.h"
36 
37 namespace OHOS {
38 namespace nmd {
39 using namespace NetManagerStandard;
40 namespace {
41 constexpr int32_t INTERFACE_UNSET = -1;
42 constexpr int32_t LOCAL_NET_ID = 99;
43 } // namespace
44 
ConnManager()45 ConnManager::ConnManager()
46 {
47     networks_.EnsureInsert(LOCAL_NET_ID, std::make_shared<LocalNetwork>(LOCAL_NET_ID));
48     defaultNetId_ = 0;
49     needReinitRouteFlag_ = false;
50 }
51 
~ConnManager()52 ConnManager::~ConnManager()
53 {
54     networks_.Clear();
55 }
56 
SetInternetPermission(uint32_t uid, uint8_t allow, uint8_t isBroker)57 int32_t ConnManager::SetInternetPermission(uint32_t uid, uint8_t allow, uint8_t isBroker)
58 {
59     // 0 means root
60     if (uid == 0) {
61         return NETMANAGER_ERROR;
62     }
63     if (isBroker) {
64         BpfMapper<sock_permission_key, sock_permission_value> permissionMap(BROKER_SOCKET_PERMISSION_MAP_PATH,
65                                                                             BPF_F_WRONLY);
66         if (!permissionMap.IsValid()) {
67             return NETMANAGER_ERROR;
68         }
69         // 0 means no permission
70         if (permissionMap.Write(uid, allow, 0) != 0) {
71             return NETMANAGER_ERROR;
72         }
73 
74         return NETMANAGER_SUCCESS;
75     }
76     BpfMapper<sock_permission_key, sock_permission_value> permissionMap(OH_SOCKET_PERMISSION_MAP_PATH, BPF_F_WRONLY);
77     if (!permissionMap.IsValid()) {
78         return NETMANAGER_ERROR;
79     }
80     // 0 means no permission
81     if (permissionMap.Write(uid, allow, 0) != 0) {
82         return NETMANAGER_ERROR;
83     }
84 
85     return NETMANAGER_SUCCESS;
86 }
87 
CreatePhysicalNetwork(uint16_t netId, NetworkPermission permission)88 int32_t ConnManager::CreatePhysicalNetwork(uint16_t netId, NetworkPermission permission)
89 {
90     if (needReinitRouteFlag_) {
91         std::set<int32_t> netIds;
92         networks_.Iterate([&netIds](int32_t id, std::shared_ptr<NetsysNetwork> &NetsysNetworkPtr) {
93             if (id == LOCAL_NET_ID || NetsysNetworkPtr == nullptr) {
94                 return;
95             }
96             netIds.insert(NetsysNetworkPtr->GetNetId());
97         });
98 
99         for (auto netId : netIds) {
100             std::string interfaceName;
101             {
102                 std::lock_guard<std::mutex> lock(interfaceNameMutex_);
103                 interfaceName = physicalInterfaceName_[netId];
104             }
105             RemoveInterfaceFromNetwork(netId, interfaceName);
106             DestroyNetwork(netId);
107         }
108         needReinitRouteFlag_ = false;
109     }
110     std::shared_ptr<NetsysNetwork> network = std::make_shared<PhysicalNetwork>(netId, permission);
111     networks_.EnsureInsert(netId, network);
112     return NETMANAGER_SUCCESS;
113 }
114 
CreateVirtualNetwork(uint16_t netId, bool hasDns)115 int32_t ConnManager::CreateVirtualNetwork(uint16_t netId, bool hasDns)
116 {
117     networks_.EnsureInsert(netId, std::make_shared<VirtualNetwork>(netId, hasDns));
118     return NETMANAGER_SUCCESS;
119 }
120 
DestroyNetwork(int32_t netId)121 int32_t ConnManager::DestroyNetwork(int32_t netId)
122 {
123     if (netId == LOCAL_NET_ID) {
124         NETNATIVE_LOGE("Cannot destroy local network");
125         return NETMANAGER_ERROR;
126     }
127     const auto &net = FindNetworkById(netId);
128     if (std::get<0>(net)) {
129         std::shared_ptr<NetsysNetwork> nw = std::get<1>(net);
130         if (defaultNetId_ == netId) {
131             if (nw->IsPhysical()) {
132                 static_cast<PhysicalNetwork *>(nw.get())->RemoveDefault();
133             }
134             defaultNetId_ = 0;
135         }
136         nw->ClearInterfaces();
137     }
138     networks_.Erase(netId);
139     return NETMANAGER_SUCCESS;
140 }
141 
SetDefaultNetwork(int32_t netId)142 int32_t ConnManager::SetDefaultNetwork(int32_t netId)
143 {
144     if (defaultNetId_ == netId) {
145         return NETMANAGER_SUCCESS;
146     }
147 
148     // check if this network exists
149     const auto &net = FindNetworkById(netId);
150     if (std::get<0>(net)) {
151         std::shared_ptr<NetsysNetwork> nw = std::get<1>(net);
152         if (!nw->IsPhysical()) {
153             NETNATIVE_LOGE("SetDefaultNetwork fail, network :%{public}d is not physical ", netId);
154             return NETMANAGER_ERROR;
155         }
156         static_cast<PhysicalNetwork *>(nw.get())->AddDefault();
157     }
158 
159     if (defaultNetId_ != 0) {
160         const auto &defaultNet = FindNetworkById(defaultNetId_);
161         if (std::get<0>(defaultNet)) {
162             std::shared_ptr<NetsysNetwork> nw = std::get<1>(defaultNet);
163             if (!nw->IsPhysical()) {
164                 NETNATIVE_LOGE("SetDefaultNetwork fail, defaultNetId_ :%{public}d is not physical", defaultNetId_);
165                 return NETMANAGER_ERROR;
166             }
167             static_cast<PhysicalNetwork *>(nw.get())->RemoveDefault();
168         }
169     }
170     defaultNetId_ = netId;
171     return NETMANAGER_SUCCESS;
172 }
173 
ClearDefaultNetwork()174 int32_t ConnManager::ClearDefaultNetwork()
175 {
176     if (defaultNetId_ != 0) {
177         const auto &net = FindNetworkById(defaultNetId_);
178         if (std::get<0>(net)) {
179             std::shared_ptr<NetsysNetwork> nw = std::get<1>(net);
180             if (!nw->IsPhysical()) {
181                 NETNATIVE_LOGE("ClearDefaultNetwork fail, defaultNetId_ :%{public}d is not physical", defaultNetId_);
182                 return NETMANAGER_ERROR;
183             }
184             static_cast<PhysicalNetwork *>(nw.get())->RemoveDefault();
185         }
186     }
187     defaultNetId_ = 0;
188     return NETMANAGER_SUCCESS;
189 }
190 
FindNetworkById(int32_t netId)191 std::tuple<bool, std::shared_ptr<NetsysNetwork>> ConnManager::FindNetworkById(int32_t netId)
192 {
193     NETNATIVE_LOG_D("Entry ConnManager::FindNetworkById netId:%{public}d", netId);
194     std::shared_ptr<NetsysNetwork> netsysNetworkPtr;
195     bool ret = networks_.Find(netId, netsysNetworkPtr);
196     if (ret) {
197         return std::make_tuple(true, netsysNetworkPtr);
198     }
199     return std::make_tuple<bool, std::shared_ptr<NetsysNetwork>>(false, nullptr);
200 }
201 
GetDefaultNetwork() const202 int32_t ConnManager::GetDefaultNetwork() const
203 {
204     return defaultNetId_;
205 }
206 
GetNetworkForInterface(int32_t netId, std::string &interfaceName)207 int32_t ConnManager::GetNetworkForInterface(int32_t netId, std::string &interfaceName)
208 {
209     NETNATIVE_LOG_D("Entry ConnManager::GetNetworkForInterface interfaceName:%{public}s", interfaceName.c_str());
210     std::map<int32_t, std::shared_ptr<NetsysNetwork>>::iterator it;
211     int32_t InterfaceId = INTERFACE_UNSET;
212     bool isInternalNetId = IsInternalNetId(netId);
213     networks_.Iterate([&InterfaceId, &interfaceName, isInternalNetId]
214         (int32_t id, std::shared_ptr<NetsysNetwork> &NetsysNetworkPtr) {
215         if (IsInternalNetId(id) != isInternalNetId) {
216             return;
217         }
218         if (InterfaceId != INTERFACE_UNSET) {
219             return;
220         }
221         if (NetsysNetworkPtr != nullptr) {
222             if (NetsysNetworkPtr->ExistInterface(interfaceName)) {
223                 InterfaceId = id;
224             }
225         }
226     });
227     return InterfaceId;
228 }
229 
AddInterfaceToNetwork(int32_t netId, std::string &interfaceName, NetManagerStandard::NetBearType netBearerType)230 int32_t ConnManager::AddInterfaceToNetwork(int32_t netId, std::string &interfaceName,
231                                            NetManagerStandard::NetBearType netBearerType)
232 {
233     NETNATIVE_LOG_D(
234         "Entry ConnManager::AddInterfaceToNetwork netId:%{public}d, interfaceName:%{public}s, netBearerType: "
235         "%{public}u",
236         netId, interfaceName.c_str(), netBearerType);
237     int32_t alreadySetNetId = GetNetworkForInterface(netId, interfaceName);
238     if ((alreadySetNetId != netId) && (alreadySetNetId != INTERFACE_UNSET)) {
239         NETNATIVE_LOGE("AddInterfaceToNetwork failed alreadySetNetId:%{public}d", alreadySetNetId);
240         return NETMANAGER_ERROR;
241     }
242 
243     const auto &net = FindNetworkById(netId);
244     if (std::get<0>(net)) {
245         // Create Map Table to establish the relationship betweet netId and the id about interfaceName.
246         BpfMapper<net_index, net_interface_name_id> netIdAndIfaceMap(NET_INDEX_AND_IFACE_MAP_PATH, BPF_ANY);
247         if (netIdAndIfaceMap.IsValid()) {
248             net_interface_name_id v = {0};
249             if (netBearerType == BEARER_WIFI) {
250                 v = NETWORK_BEARER_TYPE_WIFI;
251             } else if (netBearerType == BEARER_CELLULAR) {
252                 v = NETWORK_BEARER_TYPE_CELLULAR;
253             } else {
254                 v = NETWORK_BEARER_TYPE_INITIAL;
255             }
256 
257             if (netIdAndIfaceMap.Write(netId, v, 0) != 0) {
258                 NETNATIVE_LOGE("netIdAndIfaceMap add error: netId:%{public}d, interfaceName:%{public}s", netId,
259                     interfaceName.c_str());
260             }
261         }
262         std::shared_ptr<NetsysNetwork> nw = std::get<1>(net);
263         if (nw->IsPhysical()) {
264             std::lock_guard<std::mutex> lock(interfaceNameMutex_);
265             physicalInterfaceName_[netId] = interfaceName;
266         }
267         return nw->AddInterface(interfaceName);
268     }
269     return NETMANAGER_ERROR;
270 }
271 
RemoveInterfaceFromNetwork(int32_t netId, std::string &interfaceName)272 int32_t ConnManager::RemoveInterfaceFromNetwork(int32_t netId, std::string &interfaceName)
273 {
274     int32_t alreadySetNetId = GetNetworkForInterface(netId, interfaceName);
275     if ((alreadySetNetId != netId) || (alreadySetNetId == INTERFACE_UNSET)) {
276         return NETMANAGER_SUCCESS;
277     } else if (alreadySetNetId == netId) {
278         const auto &net = FindNetworkById(netId);
279         if (std::get<0>(net)) {
280             std::shared_ptr<NetsysNetwork> nw = std::get<1>(net);
281             int32_t ret = nw->RemoveInterface(interfaceName);
282             if (nw->IsPhysical()) {
283                 std::lock_guard<std::mutex> lock(interfaceNameMutex_);
284                 physicalInterfaceName_.erase(netId);
285             }
286 
287             BpfMapper<net_index, net_interface_name_id> netIdAndIfaceMap(NET_INDEX_AND_IFACE_MAP_PATH, BPF_ANY);
288             if (netIdAndIfaceMap.IsValid() && netIdAndIfaceMap.Delete(netId) != 0) {
289                 NETNATIVE_LOGE("netIdAndIfaceMap remove error: netId:%{public}d, interfaceName:%{public}s", netId,
290                                interfaceName.c_str());
291             }
292             return ret;
293         }
294     }
295     return NETMANAGER_SUCCESS;
296 }
297 
ReinitRoute()298 int32_t ConnManager::ReinitRoute()
299 {
300     NETNATIVE_LOG_D("ConnManager::ReInitRoute");
301     needReinitRouteFlag_ = true;
302     return NETMANAGER_SUCCESS;
303 }
304 
AddRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop, bool& routeRepeat)305 int32_t ConnManager::AddRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop,
306                               bool& routeRepeat)
307 {
308     return RouteManager::AddRoute(GetTableType(netId), interfaceName, destination, nextHop, routeRepeat);
309 }
310 
RemoveRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop)311 int32_t ConnManager::RemoveRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop)
312 {
313     return RouteManager::RemoveRoute(GetTableType(netId), interfaceName, destination, nextHop);
314 }
315 
UpdateRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop)316 int32_t ConnManager::UpdateRoute(int32_t netId, std::string interfaceName, std::string destination, std::string nextHop)
317 {
318     return RouteManager::UpdateRoute(GetTableType(netId), interfaceName, destination, nextHop);
319 }
320 
GetTableType(int32_t netId)321 RouteManager::TableType ConnManager::GetTableType(int32_t netId)
322 {
323     if (netId == LOCAL_NET_ID) {
324         return RouteManager::LOCAL_NETWORK;
325     } else if (FindVirtualNetwork(netId) != nullptr) {
326         return RouteManager::VPN_NETWORK;
327     } else if (NetManagerStandard::IsInternalNetId(netId)) {
328         return RouteManager::INTERNAL_DEFAULT;
329     } else {
330         return RouteManager::INTERFACE;
331     }
332 }
333 
GetFwmarkForNetwork(int32_t netId)334 int32_t ConnManager::GetFwmarkForNetwork(int32_t netId)
335 {
336     return NETMANAGER_ERROR;
337 }
338 
SetPermissionForNetwork(int32_t netId, NetworkPermission permission)339 int32_t ConnManager::SetPermissionForNetwork(int32_t netId, NetworkPermission permission)
340 {
341     return NETMANAGER_ERROR;
342 }
343 
FindVirtualNetwork(int32_t netId)344 std::shared_ptr<NetsysNetwork> ConnManager::FindVirtualNetwork(int32_t netId)
345 {
346     if (netId == LOCAL_NET_ID) {
347         return nullptr;
348     }
349     std::shared_ptr<NetsysNetwork> netsysNetworkPtr = nullptr;
350     auto ret = networks_.Find(netId, netsysNetworkPtr);
351     if (!ret || netsysNetworkPtr == nullptr) {
352         NETNATIVE_LOGE("invalid netId:%{public}d or nw is null.", netId);
353         return nullptr;
354     }
355     if (netsysNetworkPtr->IsPhysical()) {
356         return nullptr;
357     }
358     return netsysNetworkPtr;
359 }
360 
AddUidsToNetwork(int32_t netId, const std::vector<NetManagerStandard::UidRange> &uidRanges)361 int32_t ConnManager::AddUidsToNetwork(int32_t netId, const std::vector<NetManagerStandard::UidRange> &uidRanges)
362 {
363     auto netsysNetwork = FindVirtualNetwork(netId);
364     if (netsysNetwork == nullptr) {
365         NETNATIVE_LOGE("cannot add uids to non-virtual network with netId:%{public}d", netId);
366         return NETMANAGER_ERROR;
367     }
368     return static_cast<VirtualNetwork *>(netsysNetwork.get())->AddUids(uidRanges);
369 }
370 
RemoveUidsFromNetwork(int32_t netId, const std::vector<NetManagerStandard::UidRange> &uidRanges)371 int32_t ConnManager::RemoveUidsFromNetwork(int32_t netId, const std::vector<NetManagerStandard::UidRange> &uidRanges)
372 {
373     auto netsysNetwork = FindVirtualNetwork(netId);
374     if (netsysNetwork == nullptr) {
375         NETNATIVE_LOGE("cannot remove uids from non-virtual network with netId:%{public}d", netId);
376         return NETMANAGER_ERROR;
377     }
378     return static_cast<VirtualNetwork *>(netsysNetwork.get())->RemoveUids(uidRanges);
379 }
380 
GetDumpInfos(std::string &infos)381 void ConnManager::GetDumpInfos(std::string &infos)
382 {
383     static const std::string TAB = "  ";
384     infos.append("Netsys connect manager :\n");
385     infos.append(TAB + "default NetId: " + std::to_string(defaultNetId_) + "\n");
386     networks_.Iterate([&infos](int32_t id, std::shared_ptr<NetsysNetwork> &NetsysNetworkPtr) {
387         infos.append(TAB + "NetId:" + std::to_string(id));
388         std::string interfaces = TAB + "interfaces: {";
389         for (const auto &interface : NetsysNetworkPtr->GetAllInterface()) {
390             interfaces.append(interface + ", ");
391         }
392         infos.append(interfaces + "}\n");
393     });
394 }
395 
SetNetworkAccessPolicy(uint32_t uid, NetManagerStandard::NetworkAccessPolicy policy, bool reconfirmFlag, bool isBroker)396 int32_t ConnManager::SetNetworkAccessPolicy(uint32_t uid, NetManagerStandard::NetworkAccessPolicy policy,
397                                             bool reconfirmFlag, bool isBroker)
398 {
399     NETNATIVE_LOGI("SetNetworkAccessPolicy isBroker: %{public}d", isBroker);
400 
401     if (isBroker) {
402         BpfMapper<app_uid_key, app_uid_key> brokerUidAccessPolicyMap(BROKER_UID_ACCESS_POLICY_MAP_PATH, BPF_F_WRONLY);
403         if (!brokerUidAccessPolicyMap.IsValid()) {
404             return NETMANAGER_ERROR;
405         }
406         // 0 means no permission
407         app_uid_key v = {0};
408         v = uid;
409         if (brokerUidAccessPolicyMap.Write(DEFAULT_BROKER_UID_KEY, v, 0) != 0) {
410             NETNATIVE_LOGE("SetNetworkAccessPolicy Write brokerUidAccessPolicyMap err");
411             return NETMANAGER_ERROR;
412         }
413 
414         NETNATIVE_LOG_D("SetNetworkAccessPolicy brokerUidAccessPolicyMap: %{public}d", isBroker);
415     }
416 
417     BpfMapper<app_uid_key, uid_access_policy_value> uidAccessPolicyMap(APP_UID_PERMISSION_MAP_PATH, BPF_ANY);
418     if (!uidAccessPolicyMap.IsValid()) {
419         NETNATIVE_LOGE("SetNetworkAccessPolicy uidAccessPolicyMap not exist.");
420         return NETMANAGER_ERROR;
421     }
422 
423     uid_access_policy_value v = {0};
424     uid_access_policy_value v2 = {0};
425     (void)uidAccessPolicyMap.Read(uid, v);
426 
427     v.configSetFromFlag = reconfirmFlag;
428     v.diagAckFlag = 0;
429     v.wifiPolicy = policy.wifiAllow;
430     v.cellularPolicy = policy.cellularAllow;
431 
432     if (uidAccessPolicyMap.Write(uid, v, 0) != 0) {
433         NETNATIVE_LOGE("SetNetworkAccessPolicy Write uidAccessPolicyMap err");
434         return NETMANAGER_ERROR;
435     }
436 
437     (void)uidAccessPolicyMap.Read(uid, v2);
438     NETNATIVE_LOG_D(
439         "SetNetworkAccessPolicy Read uid:%{public}u, wifi:%{public}u, cellular:%{public}u, reconfirmFlag:%{public}u",
440         uid, v2.wifiPolicy, v2.cellularPolicy, v2.configSetFromFlag);
441     return NETMANAGER_SUCCESS;
442 }
443 
DeleteNetworkAccessPolicy(uint32_t uid)444 int32_t ConnManager::DeleteNetworkAccessPolicy(uint32_t uid)
445 {
446     BpfMapper<app_uid_key, uid_access_policy_value> uidAccessPolicyMap(APP_UID_PERMISSION_MAP_PATH, BPF_ANY);
447     if (!uidAccessPolicyMap.IsValid()) {
448         NETNATIVE_LOGE("uidAccessPolicyMap not exist");
449         return NETMANAGER_ERROR;
450     }
451 
452     if (uidAccessPolicyMap.Delete(uid) != 0) {
453         NETNATIVE_LOGE("DeleteNetworkAccessPolicy err");
454         return NETMANAGER_ERROR;
455     }
456 
457     return NETMANAGER_SUCCESS;
458 }
459 
NotifyNetBearerTypeChange(std::set<NetManagerStandard::NetBearType> bearerTypes)460 int32_t ConnManager::NotifyNetBearerTypeChange(std::set<NetManagerStandard::NetBearType> bearerTypes)
461 {
462     NETNATIVE_LOG_D("NotifyNetBearerTypeChange");
463     BpfMapper<net_bear_id_key, net_bear_type_map_value> NetBearerTypeMap(NET_BEAR_TYPE_MAP_PATH, BPF_ANY);
464     if (!NetBearerTypeMap.IsValid()) {
465         NETNATIVE_LOGE("NetBearerTypeMap not exist");
466         return NETMANAGER_ERROR;
467     }
468 
469     // -1 means invalid
470     int32_t netbearerType = -1;
471     for (const auto& bearerType : bearerTypes) {
472         if (bearerType == BEARER_CELLULAR) {
473             netbearerType = NETWORK_BEARER_TYPE_CELLULAR;
474         }
475         if (bearerType == BEARER_WIFI) {
476             netbearerType = NETWORK_BEARER_TYPE_WIFI;
477         }
478     }
479     NETNATIVE_LOGI("NotifyNetBearerTypeChange Type: %{public}d", static_cast<int32_t>(netbearerType));
480 
481     net_bear_type_map_value v = 0;
482     int32_t ret = NetBearerTypeMap.Read(0, v);
483 
484     net_bear_id_key key = DEFAULT_NETWORK_BEARER_MAP_KEY;
485     // -1 means current bearer independent network access.
486     if (netbearerType != -1 &&
487         (((ret == NETSYS_SUCCESS) && (static_cast<int32_t>(v) != netbearerType)) || (ret != NETSYS_SUCCESS))) {
488         v = netbearerType;
489         if (NetBearerTypeMap.Write(key, v, 0) != 0) {
490             NETNATIVE_LOGE("Could not update NetBearerTypeMap");
491             return NETMANAGER_ERROR;
492         }
493     }
494 
495     return NETMANAGER_SUCCESS;
496 }
497 
CloseSocketsUid(const std::string &ipAddr, uint32_t uid)498 int ConnManager::CloseSocketsUid(const std::string &ipAddr, uint32_t uid)
499 {
500     NetLinkSocketDiag socketDiag;
501     socketDiag.DestroyLiveSocketsWithUid(ipAddr, uid);
502     return NETMANAGER_SUCCESS;
503 }
504 } // namespace nmd
505 } // namespace OHOS
506