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 dns.family_ = INetAddr::IpType::IPV4;
294 } else {
295 dns.type_ = INetAddr::IpType::IPV6;
296 dns.family_ = INetAddr::IpType::IPV6;
297 }
298 dns.address_ = dnsServer;
299 linkInfo->dnsList_.emplace_back(dns);
300 linkInfo->isUserDefinedDnsServer_ = true;
301 }
302
303 for (auto domain : vpnConfig_->searchDomains_) {
304 linkInfo->domain_.append(domain).append(" ");
305 }
306 linkInfo->mtu_ = vpnConfig_->mtu_;
307 NetConnClient::GetInstance().UpdateNetLinkInfo(netSupplierId_, linkInfo);
308 return true;
309 }
310
SetIpv4DefaultRoute(Route & ipv4DefaultRoute)311 void NetVpnImpl::SetIpv4DefaultRoute(Route &ipv4DefaultRoute)
312 {
313 ipv4DefaultRoute.iface_ = TUN_CARD_NAME;
314 ipv4DefaultRoute.destination_.type_ = INetAddr::IPV4;
315 ipv4DefaultRoute.destination_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
316 ipv4DefaultRoute.destination_.prefixlen_ = CommonUtils::GetMaskLength(IPV4_DEFAULT_ROUTE_ADDR);
317 ipv4DefaultRoute.gateway_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
318 }
319
SetIpv6DefaultRoute(Route & ipv6DefaultRoute)320 void NetVpnImpl::SetIpv6DefaultRoute(Route &ipv6DefaultRoute)
321 {
322 ipv6DefaultRoute.iface_ = TUN_CARD_NAME;
323 ipv6DefaultRoute.destination_.type_ = INetAddr::IPV6;
324 ipv6DefaultRoute.destination_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
325 ipv6DefaultRoute.destination_.prefixlen_ = CommonUtils::Ipv6PrefixLen(IPV6_DEFAULT_ROUTE_ADDR);
326 ipv6DefaultRoute.gateway_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
327 }
328
DelNetLinkInfo(NetConnClient & netConnClientIns)329 void NetVpnImpl::DelNetLinkInfo(NetConnClient &netConnClientIns)
330 {
331 for (auto &route : vpnConfig_->routes_) {
332 AdjustRouteInfo(route);
333 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
334 NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
335 }
336 }
337
AdjustRouteInfo(Route & route)338 void NetVpnImpl::AdjustRouteInfo(Route &route)
339 {
340 if (route.iface_.empty()) {
341 route.iface_ = TUN_CARD_NAME;
342 }
343 if (vpnConfig_->isAcceptIPv4_ == true) {
344 uint32_t maskUint = (0xFFFFFFFF << (IPV4_NET_MASK_MAX_LENGTH - route.destination_.prefixlen_));
345 uint32_t ipAddrUint = CommonUtils::ConvertIpv4Address(route.destination_.address_);
346 uint32_t subNetAddress = ipAddrUint & maskUint;
347 route.destination_.address_ = CommonUtils::ConvertIpv4Address(subNetAddress);
348 } else {
349 route.destination_.address_ = CommonUtils::GetIpv6Prefix(route.destination_.address_,
350 route.destination_.prefixlen_);
351 }
352 }
353
GenerateUidRangesByAcceptedApps(const std::set<int32_t> & uids,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)354 void NetVpnImpl::GenerateUidRangesByAcceptedApps(const std::set<int32_t> &uids, std::vector<int32_t> &beginUids,
355 std::vector<int32_t> &endUids)
356 {
357 int32_t start = INVALID_UID;
358 int32_t stop = INVALID_UID;
359 for (int32_t uid : uids) {
360 if (start == INVALID_UID) {
361 start = uid;
362 } else if (uid != stop + 1) {
363 beginUids.push_back(start);
364 endUids.push_back(stop);
365 start = uid;
366 }
367 stop = uid;
368 }
369 if (start != INVALID_UID) {
370 beginUids.push_back(start);
371 endUids.push_back(stop);
372 }
373 }
374
GenerateUidRangesByRefusedApps(int32_t userId,const std::set<int32_t> & uids,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)375 void NetVpnImpl::GenerateUidRangesByRefusedApps(int32_t userId, const std::set<int32_t> &uids, std::vector<int32_t> &beginUids,
376 std::vector<int32_t> &endUids)
377 {
378 int32_t start = userId * AppExecFwk::Constants::BASE_USER_RANGE;
379 int32_t stop = userId * AppExecFwk::Constants::BASE_USER_RANGE + AppExecFwk::Constants::MAX_APP_UID;
380 for (int32_t uid : uids) {
381 if (uid == start) {
382 start++;
383 } else {
384 beginUids.push_back(start);
385 endUids.push_back(uid - 1);
386 start = uid + 1;
387 }
388 }
389 if (start <= stop) {
390 beginUids.push_back(start);
391 endUids.push_back(stop);
392 }
393 }
394
GetAppsUids(int32_t userId,const std::vector<std::string> & applications)395 std::set<int32_t> NetVpnImpl::GetAppsUids(int32_t userId, const std::vector<std::string> &applications)
396 {
397 std::set<int32_t> uids;
398 auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
399 if (systemAbilityManager == nullptr) {
400 NETMGR_EXT_LOG_E("systemAbilityManager is null.");
401 return uids;
402 }
403 auto bundleMgrSa = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
404 if (bundleMgrSa == nullptr) {
405 NETMGR_EXT_LOG_E("bundleMgrSa is null.");
406 return uids;
407 }
408 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
409 if (bundleMgr == nullptr) {
410 NETMGR_EXT_LOG_E("iface_cast is null.");
411 return uids;
412 }
413
414 NETMGR_EXT_LOG_I("userId: %{public}d.", userId);
415 AppExecFwk::ApplicationFlag flags = AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO;
416 for (auto app : applications) {
417 AppExecFwk::ApplicationInfo appInfo;
418 if (bundleMgr->GetApplicationInfo(app, flags, userId, appInfo)) {
419 NETMGR_EXT_LOG_I("app: %{public}s success, uid=%{public}d.", app.c_str(), appInfo.uid);
420 uids.insert(appInfo.uid);
421 } else {
422 NETMGR_EXT_LOG_E("app: %{public}s error.", app.c_str());
423 }
424 }
425 NETMGR_EXT_LOG_I("uids.size: %{public}zd.", uids.size());
426 return uids;
427 }
428
GenerateUidRanges(int32_t userId,std::vector<int32_t> & beginUids,std::vector<int32_t> & endUids)429 int32_t NetVpnImpl::GenerateUidRanges(int32_t userId, std::vector<int32_t> &beginUids, std::vector<int32_t> &endUids)
430 {
431 NETMGR_EXT_LOG_I("GenerateUidRanges userId:%{public}d.", userId);
432 if (userId == AppExecFwk::Constants::INVALID_USERID) {
433 userId = AppExecFwk::Constants::START_USERID;
434 }
435 if (vpnConfig_->acceptedApplications_.size()) {
436 std::set<int32_t> uids = GetAppsUids(userId, vpnConfig_->acceptedApplications_);
437 GenerateUidRangesByAcceptedApps(uids, beginUids, endUids);
438 } else if (vpnConfig_->refusedApplications_.size()) {
439 std::set<int32_t> uids = GetAppsUids(userId, vpnConfig_->refusedApplications_);
440 GenerateUidRangesByRefusedApps(userId, uids, beginUids, endUids);
441 } else {
442 int32_t start = userId * AppExecFwk::Constants::BASE_USER_RANGE;
443 int32_t stop = userId * AppExecFwk::Constants::BASE_USER_RANGE + AppExecFwk::Constants::MAX_APP_UID;
444 beginUids.push_back(start);
445 endUids.push_back(stop);
446 NETMGR_EXT_LOG_I("GenerateUidRanges default all app, uid range: %{public}d -- %{public}d.", start, stop);
447 }
448 return NETMANAGER_EXT_SUCCESS;
449 }
450
451 } // namespace NetManagerStandard
452 } // namespace OHOS
453