1 /*
2 * Copyright (c) 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 "net_vpn_impl.h"
17
18 #include <list>
19
20 #include "bundle_mgr_client.h"
21 #include "ipc_skeleton.h"
22 #include "iservice_registry.h"
23 #include "os_account_manager.h"
24 #include "system_ability_definition.h"
25
26 #include "net_conn_client.h"
27 #include "net_manager_constants.h"
28 #include "net_manager_ext_constants.h"
29 #include "netmanager_base_common_utils.h"
30 #include "netmgr_ext_log_wrapper.h"
31 #include "netsys_controller.h"
32
33 namespace OHOS {
34 namespace NetManagerStandard {
35 namespace {
36 constexpr int32_t INVALID_UID = -1;
37 constexpr int32_t IPV4_NET_MASK_MAX_LENGTH = 32;
38 constexpr const char *IPV4_DEFAULT_ROUTE_ADDR = "0.0.0.0";
39 constexpr const char *IPV6_DEFAULT_ROUTE_ADDR = "";
40 constexpr const char *IPV6_ROUTE_ADDR = "fe80::";
41 } // namespace
42
NetVpnImpl(sptr<VpnConfig> config,const std::string & pkg,int32_t userId,std::vector<int32_t> & activeUserIds)43 NetVpnImpl::NetVpnImpl(sptr<VpnConfig> config, const std::string &pkg, int32_t userId, std::vector<int32_t> &activeUserIds)
44 : vpnConfig_(config), pkgName_(pkg), userId_(userId), activeUserIds_(activeUserIds)
45 {
46 netSupplierInfo_ = new (std::nothrow) NetSupplierInfo();
47 if (netSupplierInfo_ == nullptr) {
48 NETMGR_EXT_LOG_E("NetSupplierInfo new failed");
49 }
50 }
51
RegisterConnectStateChangedCb(std::shared_ptr<IVpnConnStateCb> callback)52 int32_t NetVpnImpl::RegisterConnectStateChangedCb(std::shared_ptr<IVpnConnStateCb> callback)
53 {
54 if (callback == nullptr) {
55 NETMGR_EXT_LOG_E("Register vpn connect callback is null.");
56 return NETMANAGER_EXT_ERR_INTERNAL;
57 }
58 connChangedCb_ = callback;
59 return NETMANAGER_EXT_SUCCESS;
60 }
61
NotifyConnectState(const VpnConnectState & state)62 void NetVpnImpl::NotifyConnectState(const VpnConnectState &state)
63 {
64 if (connChangedCb_ == nullptr) {
65 NETMGR_EXT_LOG_E("NotifyConnectState connect callback is null.");
66 return;
67 }
68 connChangedCb_->OnVpnConnStateChanged(state);
69 }
70
SetUp()71 int32_t NetVpnImpl::SetUp()
72 {
73 if (vpnConfig_ == nullptr) {
74 NETMGR_EXT_LOG_E("VpnConnect vpnConfig_ is nullptr");
75 return NETMANAGER_EXT_ERR_INTERNAL;
76 }
77 NETMGR_EXT_LOG_I("SetUp interface name:%{public}s", TUN_CARD_NAME);
78 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
79
80 auto &netConnClientIns = NetConnClient::GetInstance();
81 if (!RegisterNetSupplier(netConnClientIns)) {
82 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_REG_NET_SUPPLIER_ERROR,
83 "register Supplier failed");
84 return NETMANAGER_EXT_ERR_INTERNAL;
85 }
86
87 if (!UpdateNetSupplierInfo(netConnClientIns, true)) {
88 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_UPDATE_SUPPLIER_INFO_ERROR,
89 "update Supplier info failed");
90 return NETMANAGER_EXT_ERR_INTERNAL;
91 }
92
93 if (!UpdateNetLinkInfo(netConnClientIns)) {
94 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_UPDATE_NETLINK_INFO_ERROR,
95 "update link info failed");
96 return NETMANAGER_EXT_ERR_INTERNAL;
97 }
98
99 std::list<int32_t> netIdList;
100 netConnClientIns.GetNetIdByIdentifier(TUN_CARD_NAME, netIdList);
101 if (netIdList.size() == 0) {
102 NETMGR_EXT_LOG_E("get netId failed, netId list size is 0");
103 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_INTERNAL_ERROR, "get Net id failed");
104 return NETMANAGER_EXT_ERR_INTERNAL;
105 }
106 netId_ = *(netIdList.begin());
107 NETMGR_EXT_LOG_I("vpn network netid: %{public}d", netId_);
108
109 GenerateUidRanges(userId_, beginUids_, endUids_);
110
111 for (auto &elem : activeUserIds_) {
112 GenerateUidRanges(elem, beginUids_, endUids_);
113 }
114
115 if (NetsysController::GetInstance().NetworkAddUids(netId_, beginUids_, endUids_)) {
116 NETMGR_EXT_LOG_E("vpn set whitelist rule error");
117 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
118 "set app uid rule failed");
119 return NETMANAGER_EXT_ERR_INTERNAL;
120 }
121
122 NotifyConnectState(VpnConnectState::VPN_CONNECTED);
123 isVpnConnecting_ = true;
124 return NETMANAGER_EXT_SUCCESS;
125 }
126
ResumeUids()127 int32_t NetVpnImpl::ResumeUids()
128 {
129 if (!isVpnConnecting_) {
130 NETMGR_EXT_LOG_I("unecessary to resume uids");
131 return NETMANAGER_EXT_ERR_INTERNAL;
132 }
133
134 if (NetsysController::GetInstance().NetworkAddUids(netId_, beginUids_, endUids_)) {
135 NETMGR_EXT_LOG_E("vpn set whitelist rule error");
136 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
137 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
138 "set app uid rule failed");
139 return NETMANAGER_EXT_ERR_INTERNAL;
140 }
141
142 return NETMANAGER_EXT_SUCCESS;
143 }
144
Destroy()145 int32_t NetVpnImpl::Destroy()
146 {
147 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
148 if (NetsysController::GetInstance().NetworkDelUids(netId_, beginUids_, endUids_)) {
149 NETMGR_EXT_LOG_W("vpn remove whitelist rule error");
150 VpnHisysEvent::SendFaultEventConnDestroy(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
151 "remove app uid rule failed");
152 }
153
154 auto &netConnClientIns = NetConnClient::GetInstance();
155 DelNetLinkInfo(netConnClientIns);
156 UpdateNetSupplierInfo(netConnClientIns, false);
157 UnregisterNetSupplier(netConnClientIns);
158
159 NotifyConnectState(VpnConnectState::VPN_DISCONNECTED);
160 isVpnConnecting_ = false;
161 return NETMANAGER_EXT_SUCCESS;
162 }
163
RegisterNetSupplier(NetConnClient & netConnClientIns)164 bool NetVpnImpl::RegisterNetSupplier(NetConnClient &netConnClientIns)
165 {
166 if (netSupplierId_) {
167 NETMGR_EXT_LOG_E("NetSupplier [%{public}d] has been registered ", netSupplierId_);
168 return false;
169 }
170 std::set<NetCap> netCap;
171 netCap.insert(NET_CAPABILITY_INTERNET);
172 if (vpnConfig_->isMetered_ == false) {
173 netCap.insert(NET_CAPABILITY_NOT_METERED);
174 }
175 if (netConnClientIns.RegisterNetSupplier(BEARER_VPN, TUN_CARD_NAME, netCap, netSupplierId_) != NETMANAGER_SUCCESS) {
176 NETMGR_EXT_LOG_E("vpn netManager RegisterNetSupplier error.");
177 return false;
178 }
179 NETMGR_EXT_LOG_I("vpn RegisterNetSupplier netSupplierId_[%{public}d]", netSupplierId_);
180 return true;
181 }
182
UnregisterNetSupplier(NetConnClient & netConnClientIns)183 void NetVpnImpl::UnregisterNetSupplier(NetConnClient &netConnClientIns)
184 {
185 if (!netSupplierId_) {
186 NETMGR_EXT_LOG_E("NetSupplier [%{public}d] has been unregistered ", netSupplierId_);
187 return;
188 }
189 if (!netConnClientIns.UnregisterNetSupplier(netSupplierId_)) {
190 netSupplierId_ = 0;
191 }
192 }
193
UpdateNetSupplierInfo(NetConnClient & netConnClientIns,bool isAvailable)194 bool NetVpnImpl::UpdateNetSupplierInfo(NetConnClient &netConnClientIns, bool isAvailable)
195 {
196 if (!netSupplierId_) {
197 NETMGR_EXT_LOG_E("vpn UpdateNetSupplierInfo error, netSupplierId is zero");
198 return false;
199 }
200 if (netSupplierInfo_ == nullptr) {
201 NETMGR_EXT_LOG_E("vpn UpdateNetSupplierInfo netSupplierInfo_ is nullptr");
202 return false;
203 }
204 netSupplierInfo_->isAvailable_ = isAvailable;
205 netConnClientIns.UpdateNetSupplierInfo(netSupplierId_, netSupplierInfo_);
206 return true;
207 }
208
UpdateNetLinkInfo(NetConnClient & netConnClientIns)209 bool NetVpnImpl::UpdateNetLinkInfo(NetConnClient &netConnClientIns)
210 {
211 if (vpnConfig_ == nullptr) {
212 NETMGR_EXT_LOG_E("vpnConfig_ is nullptr");
213 return false;
214 }
215 sptr<NetLinkInfo> linkInfo = new (std::nothrow) NetLinkInfo();
216 if (linkInfo == nullptr) {
217 NETMGR_EXT_LOG_E("linkInfo is nullptr");
218 return false;
219 }
220
221 linkInfo->ifaceName_ = TUN_CARD_NAME;
222 linkInfo->netAddrList_.assign(vpnConfig_->addresses_.begin(), vpnConfig_->addresses_.end());
223
224 if (vpnConfig_->routes_.empty()) {
225 if (vpnConfig_->isAcceptIPv4_ == true) {
226 Route ipv4DefaultRoute;
227 SetIpv4DefaultRoute(ipv4DefaultRoute);
228 linkInfo->routeList_.emplace_back(ipv4DefaultRoute);
229 }
230 if (vpnConfig_->isAcceptIPv6_== true) {
231 Route ipv6DefaultRoute;
232 SetIpv6DefaultRoute(ipv6DefaultRoute);
233 linkInfo->routeList_.emplace_back(ipv6DefaultRoute);
234 }
235 } else {
236 linkInfo->routeList_.assign(vpnConfig_->routes_.begin(), vpnConfig_->routes_.end());
237 for (auto &route : linkInfo->routeList_) {
238 AdjustRouteInfo(route);
239 }
240 }
241
242 for (auto dnsServer : vpnConfig_->dnsAddresses_) {
243 INetAddr dns;
244 if (vpnConfig_->isAcceptIPv4_ == true) {
245 dns.type_ = INetAddr::IpType::IPV4;
246 } else {
247 dns.type_ = INetAddr::IpType::IPV6;
248 }
249 dns.address_ = dnsServer;
250 linkInfo->dnsList_.emplace_back(dns);
251 }
252
253 for (auto domain : vpnConfig_->searchDomains_) {
254 linkInfo->domain_.append(domain).append(" ");
255 }
256 linkInfo->mtu_ = vpnConfig_->mtu_;
257 netConnClientIns.UpdateNetLinkInfo(netSupplierId_, linkInfo);
258 return true;
259 }
260
SetIpv4DefaultRoute(Route & ipv4DefaultRoute)261 void NetVpnImpl::SetIpv4DefaultRoute(Route &ipv4DefaultRoute)
262 {
263 ipv4DefaultRoute.iface_ = TUN_CARD_NAME;
264 ipv4DefaultRoute.destination_.type_ = INetAddr::IPV4;
265 ipv4DefaultRoute.destination_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
266 ipv4DefaultRoute.destination_.prefixlen_ = CommonUtils::GetMaskLength(IPV4_DEFAULT_ROUTE_ADDR);
267 ipv4DefaultRoute.gateway_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
268 }
269
SetIpv6DefaultRoute(Route & ipv6DefaultRoute)270 void NetVpnImpl::SetIpv6DefaultRoute(Route &ipv6DefaultRoute)
271 {
272 ipv6DefaultRoute.iface_ = TUN_CARD_NAME;
273 ipv6DefaultRoute.destination_.type_ = INetAddr::IPV6;
274 ipv6DefaultRoute.destination_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
275 ipv6DefaultRoute.destination_.prefixlen_ = CommonUtils::GetMaskLength(IPV6_DEFAULT_ROUTE_ADDR);
276 ipv6DefaultRoute.gateway_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
277 }
278
DelNetLinkInfo(NetConnClient & netConnClientIns)279 void NetVpnImpl::DelNetLinkInfo(NetConnClient &netConnClientIns)
280 {
281 for (auto &route : vpnConfig_->routes_) {
282 AdjustRouteInfo(route);
283 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
284 NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
285 }
286 }
287
AdjustRouteInfo(Route & route)288 void NetVpnImpl::AdjustRouteInfo(Route &route)
289 {
290 if (route.iface_.empty()) {
291 route.iface_ = TUN_CARD_NAME;
292 }
293 if (vpnConfig_->isAcceptIPv4_ == true) {
294 uint32_t maskUint = (0xFFFFFFFF << (IPV4_NET_MASK_MAX_LENGTH - route.destination_.prefixlen_));
295 uint32_t ipAddrUint = CommonUtils::ConvertIpv4Address(route.destination_.address_);
296 uint32_t subNetAddress = ipAddrUint & maskUint;
297 route.destination_.address_ = CommonUtils::ConvertIpv4Address(subNetAddress);
298 } else {
299 route.destination_.address_ = IPV6_ROUTE_ADDR;
300 }
301 }
302
GenerateUidRangesByAcceptedApps(const std::set<int32_t> & uids,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)303 void NetVpnImpl::GenerateUidRangesByAcceptedApps(const std::set<int32_t> &uids, std::vector<int32_t> &beginUids,
304 std::vector<int32_t> &endUids)
305 {
306 int32_t start = INVALID_UID;
307 int32_t stop = INVALID_UID;
308 for (int32_t uid : uids) {
309 if (start == INVALID_UID) {
310 start = uid;
311 } else if (uid != stop + 1) {
312 beginUids.push_back(start);
313 endUids.push_back(stop);
314 start = uid;
315 }
316 stop = uid;
317 }
318 if (start != INVALID_UID) {
319 beginUids.push_back(start);
320 endUids.push_back(stop);
321 }
322 }
323
GenerateUidRangesByRefusedApps(int32_t userId,const std::set<int32_t> & uids,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)324 void NetVpnImpl::GenerateUidRangesByRefusedApps(int32_t userId, const std::set<int32_t> &uids, std::vector<int32_t> &beginUids,
325 std::vector<int32_t> &endUids)
326 {
327 int32_t start = userId * AppExecFwk::Constants::BASE_USER_RANGE;
328 int32_t stop = userId * AppExecFwk::Constants::BASE_USER_RANGE + AppExecFwk::Constants::MAX_APP_UID;
329 for (int32_t uid : uids) {
330 if (uid == start) {
331 start++;
332 } else {
333 beginUids.push_back(start);
334 endUids.push_back(uid - 1);
335 start = uid + 1;
336 }
337 }
338 if (start <= stop) {
339 beginUids.push_back(start);
340 endUids.push_back(stop);
341 }
342 }
343
GetAppsUids(int32_t userId,const std::vector<std::string> & applications)344 std::set<int32_t> NetVpnImpl::GetAppsUids(int32_t userId, const std::vector<std::string> &applications)
345 {
346 std::set<int32_t> uids;
347 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
348 if (systemAbilityManager == nullptr) {
349 NETMGR_EXT_LOG_E("systemAbilityManager is null.");
350 return uids;
351 }
352 auto bundleMgrSa = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
353 if (bundleMgrSa == nullptr) {
354 NETMGR_EXT_LOG_E("bundleMgrSa is null.");
355 return uids;
356 }
357 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
358 if (bundleMgr == nullptr) {
359 NETMGR_EXT_LOG_E("iface_cast is null.");
360 return uids;
361 }
362
363 NETMGR_EXT_LOG_I("userId: %{public}d.", userId);
364 AppExecFwk::ApplicationFlag flags = AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO;
365 for (auto app : applications) {
366 AppExecFwk::ApplicationInfo appInfo;
367 if (bundleMgr->GetApplicationInfo(app, flags, userId, appInfo)) {
368 NETMGR_EXT_LOG_I("app: %{public}s success, uid=%{public}d.", app.c_str(), appInfo.uid);
369 uids.insert(appInfo.uid);
370 } else {
371 NETMGR_EXT_LOG_E("app: %{public}s error.", app.c_str());
372 }
373 }
374 NETMGR_EXT_LOG_I("uids.size: %{public}zd.", uids.size());
375 return uids;
376 }
377
GenerateUidRanges(int32_t userId,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)378 int32_t NetVpnImpl::GenerateUidRanges(int32_t userId, std::vector<int32_t> &beginUids, std::vector<int32_t> &endUids)
379 {
380 NETMGR_EXT_LOG_I("GenerateUidRanges userId:%{public}d.", userId);
381 if (userId == AppExecFwk::Constants::INVALID_USERID) {
382 userId = AppExecFwk::Constants::START_USERID;
383 }
384 if (vpnConfig_->acceptedApplications_.size()) {
385 std::set<int32_t> uids = GetAppsUids(userId, vpnConfig_->acceptedApplications_);
386 GenerateUidRangesByAcceptedApps(uids, beginUids, endUids);
387 } else if (vpnConfig_->refusedApplications_.size()) {
388 std::set<int32_t> uids = GetAppsUids(userId, vpnConfig_->refusedApplications_);
389 GenerateUidRangesByRefusedApps(userId, uids, beginUids, endUids);
390 } else {
391 int32_t start = userId * AppExecFwk::Constants::BASE_USER_RANGE;
392 int32_t stop = userId * AppExecFwk::Constants::BASE_USER_RANGE + AppExecFwk::Constants::MAX_APP_UID;
393 beginUids.push_back(start);
394 endUids.push_back(stop);
395 NETMGR_EXT_LOG_I("GenerateUidRanges default all app, uid range: %{public}d -- %{public}d.", start, stop);
396 }
397 return NETMANAGER_EXT_SUCCESS;
398 }
399
400 } // namespace NetManagerStandard
401 } // namespace OHOS
402