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