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 = "fe80::";
40 } // namespace
41
NetVpnImpl(sptr<VpnConfig> config,const std::string & pkg,int32_t userId,std::vector<int32_t> & activeUserIds)42 NetVpnImpl::NetVpnImpl(sptr<VpnConfig> config, const std::string &pkg, int32_t userId, std::vector<int32_t> &activeUserIds)
43 : vpnConfig_(config), pkgName_(pkg), userId_(userId), activeUserIds_(activeUserIds)
44 {
45 netSupplierInfo_ = new (std::nothrow) NetSupplierInfo();
46 if (netSupplierInfo_ == nullptr) {
47 NETMGR_EXT_LOG_E("NetSupplierInfo new failed");
48 }
49 }
50
RegisterConnectStateChangedCb(std::shared_ptr<IVpnConnStateCb> callback)51 int32_t NetVpnImpl::RegisterConnectStateChangedCb(std::shared_ptr<IVpnConnStateCb> callback)
52 {
53 if (callback == nullptr) {
54 NETMGR_EXT_LOG_E("Register vpn connect callback is null.");
55 return NETMANAGER_EXT_ERR_INTERNAL;
56 }
57 connChangedCb_ = callback;
58 return NETMANAGER_EXT_SUCCESS;
59 }
60
NotifyConnectState(const VpnConnectState & state)61 void NetVpnImpl::NotifyConnectState(const VpnConnectState &state)
62 {
63 if (connChangedCb_ == nullptr) {
64 NETMGR_EXT_LOG_E("NotifyConnectState connect callback is null.");
65 return;
66 }
67 connChangedCb_->OnVpnConnStateChanged(state);
68 }
69
SetUp()70 int32_t NetVpnImpl::SetUp()
71 {
72 if (vpnConfig_ == nullptr) {
73 NETMGR_EXT_LOG_E("VpnConnect vpnConfig_ is nullptr");
74 return NETMANAGER_EXT_ERR_INTERNAL;
75 }
76 NETMGR_EXT_LOG_I("SetUp interface name:%{public}s", TUN_CARD_NAME);
77 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
78
79 auto &netConnClientIns = NetConnClient::GetInstance();
80 if (!RegisterNetSupplier(netConnClientIns)) {
81 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_REG_NET_SUPPLIER_ERROR,
82 "register Supplier failed");
83 return NETMANAGER_EXT_ERR_INTERNAL;
84 }
85
86 if (!UpdateNetSupplierInfo(netConnClientIns, true)) {
87 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_UPDATE_SUPPLIER_INFO_ERROR,
88 "update Supplier info failed");
89 return NETMANAGER_EXT_ERR_INTERNAL;
90 }
91
92 if (!UpdateNetLinkInfo(netConnClientIns)) {
93 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_UPDATE_NETLINK_INFO_ERROR,
94 "update link info failed");
95 return NETMANAGER_EXT_ERR_INTERNAL;
96 }
97
98 std::list<int32_t> netIdList;
99 netConnClientIns.GetNetIdByIdentifier(TUN_CARD_NAME, netIdList);
100 if (netIdList.size() == 0) {
101 NETMGR_EXT_LOG_E("get netId failed, netId list size is 0");
102 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_INTERNAL_ERROR, "get Net id failed");
103 return NETMANAGER_EXT_ERR_INTERNAL;
104 }
105 netId_ = *(netIdList.begin());
106 NETMGR_EXT_LOG_I("vpn network netid: %{public}d", netId_);
107
108 GenerateUidRanges(userId_, beginUids_, endUids_);
109
110 for (auto &elem : activeUserIds_) {
111 GenerateUidRanges(elem, beginUids_, endUids_);
112 }
113
114 if (NetsysController::GetInstance().NetworkAddUids(netId_, beginUids_, endUids_)) {
115 NETMGR_EXT_LOG_E("vpn set whitelist rule error");
116 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
117 "set app uid rule failed");
118 return NETMANAGER_EXT_ERR_INTERNAL;
119 }
120
121 NotifyConnectState(VpnConnectState::VPN_CONNECTED);
122 isVpnConnecting_ = true;
123 return NETMANAGER_EXT_SUCCESS;
124 }
125
ResumeUids()126 int32_t NetVpnImpl::ResumeUids()
127 {
128 if (!isVpnConnecting_) {
129 NETMGR_EXT_LOG_I("unecessary to resume uids");
130 return NETMANAGER_EXT_ERR_INTERNAL;
131 }
132
133 if (NetsysController::GetInstance().NetworkAddUids(netId_, beginUids_, endUids_)) {
134 NETMGR_EXT_LOG_E("vpn set whitelist rule error");
135 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
136 VpnHisysEvent::SendFaultEventConnSetting(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
137 "set app uid rule failed");
138 return NETMANAGER_EXT_ERR_INTERNAL;
139 }
140
141 return NETMANAGER_EXT_SUCCESS;
142 }
143
Destroy()144 int32_t NetVpnImpl::Destroy()
145 {
146 VpnEventType legacy = IsInternalVpn() ? VpnEventType::TYPE_LEGACY : VpnEventType::TYPE_EXTENDED;
147 if (NetsysController::GetInstance().NetworkDelUids(netId_, beginUids_, endUids_)) {
148 NETMGR_EXT_LOG_W("vpn remove whitelist rule error");
149 VpnHisysEvent::SendFaultEventConnDestroy(legacy, VpnEventErrorType::ERROR_SET_APP_UID_RULE_ERROR,
150 "remove app uid rule failed");
151 }
152
153 auto &netConnClientIns = NetConnClient::GetInstance();
154 DelNetLinkInfo(netConnClientIns);
155 UpdateNetSupplierInfo(netConnClientIns, false);
156 UnregisterNetSupplier(netConnClientIns);
157
158 NotifyConnectState(VpnConnectState::VPN_DISCONNECTED);
159 isVpnConnecting_ = false;
160 return NETMANAGER_EXT_SUCCESS;
161 }
162
RegisterNetSupplier(NetConnClient & netConnClientIns)163 bool NetVpnImpl::RegisterNetSupplier(NetConnClient &netConnClientIns)
164 {
165 if (netSupplierId_) {
166 NETMGR_EXT_LOG_E("NetSupplier [%{public}d] has been registered ", netSupplierId_);
167 return false;
168 }
169 std::set<NetCap> netCap;
170 netCap.insert(NET_CAPABILITY_INTERNET);
171 if (vpnConfig_->isMetered_ == false) {
172 netCap.insert(NET_CAPABILITY_NOT_METERED);
173 }
174 if (netConnClientIns.RegisterNetSupplier(BEARER_VPN, TUN_CARD_NAME, netCap, netSupplierId_) != NETMANAGER_SUCCESS) {
175 NETMGR_EXT_LOG_E("vpn netManager RegisterNetSupplier error.");
176 return false;
177 }
178 NETMGR_EXT_LOG_I("vpn RegisterNetSupplier netSupplierId_[%{public}d]", netSupplierId_);
179 return true;
180 }
181
UnregisterNetSupplier(NetConnClient & netConnClientIns)182 void NetVpnImpl::UnregisterNetSupplier(NetConnClient &netConnClientIns)
183 {
184 if (!netSupplierId_) {
185 NETMGR_EXT_LOG_E("NetSupplier [%{public}d] has been unregistered ", netSupplierId_);
186 return;
187 }
188 if (!netConnClientIns.UnregisterNetSupplier(netSupplierId_)) {
189 netSupplierId_ = 0;
190 }
191 }
192
UpdateNetSupplierInfo(NetConnClient & netConnClientIns,bool isAvailable)193 bool NetVpnImpl::UpdateNetSupplierInfo(NetConnClient &netConnClientIns, bool isAvailable)
194 {
195 if (!netSupplierId_) {
196 NETMGR_EXT_LOG_E("vpn UpdateNetSupplierInfo error, netSupplierId is zero");
197 return false;
198 }
199 if (netSupplierInfo_ == nullptr) {
200 NETMGR_EXT_LOG_E("vpn UpdateNetSupplierInfo netSupplierInfo_ is nullptr");
201 return false;
202 }
203 netSupplierInfo_->isAvailable_ = isAvailable;
204 netConnClientIns.UpdateNetSupplierInfo(netSupplierId_, netSupplierInfo_);
205 return true;
206 }
207
UpdateNetLinkInfo(NetConnClient & netConnClientIns)208 bool NetVpnImpl::UpdateNetLinkInfo(NetConnClient &netConnClientIns)
209 {
210 if (vpnConfig_ == nullptr) {
211 NETMGR_EXT_LOG_E("vpnConfig_ is nullptr");
212 return false;
213 }
214 sptr<NetLinkInfo> linkInfo = new (std::nothrow) NetLinkInfo();
215 if (linkInfo == nullptr) {
216 NETMGR_EXT_LOG_E("linkInfo is nullptr");
217 return false;
218 }
219
220 linkInfo->ifaceName_ = TUN_CARD_NAME;
221 linkInfo->netAddrList_.assign(vpnConfig_->addresses_.begin(), vpnConfig_->addresses_.end());
222
223 if (vpnConfig_->routes_.empty()) {
224 if (vpnConfig_->isAcceptIPv4_ == true) {
225 Route ipv4DefaultRoute;
226 SetIpv4DefaultRoute(ipv4DefaultRoute);
227 linkInfo->routeList_.emplace_back(ipv4DefaultRoute);
228 }
229 if (vpnConfig_->isAcceptIPv6_== true) {
230 Route ipv6DefaultRoute;
231 SetIpv6DefaultRoute(ipv6DefaultRoute);
232 linkInfo->routeList_.emplace_back(ipv6DefaultRoute);
233 }
234 } else {
235 linkInfo->routeList_.assign(vpnConfig_->routes_.begin(), vpnConfig_->routes_.end());
236 for (auto &route : linkInfo->routeList_) {
237 AdjustRouteInfo(route);
238 }
239 }
240
241 for (auto dnsServer : vpnConfig_->dnsAddresses_) {
242 INetAddr dns;
243 if (vpnConfig_->isAcceptIPv4_ == true) {
244 dns.type_ = INetAddr::IpType::IPV4;
245 } else {
246 dns.type_ = INetAddr::IpType::IPV6;
247 }
248 dns.address_ = dnsServer;
249 linkInfo->dnsList_.emplace_back(dns);
250 }
251
252 for (auto domain : vpnConfig_->searchDomains_) {
253 linkInfo->domain_.append(domain).append(" ");
254 }
255 linkInfo->mtu_ = vpnConfig_->mtu_;
256 netConnClientIns.UpdateNetLinkInfo(netSupplierId_, linkInfo);
257 return true;
258 }
259
SetIpv4DefaultRoute(Route & ipv4DefaultRoute)260 void NetVpnImpl::SetIpv4DefaultRoute(Route &ipv4DefaultRoute)
261 {
262 ipv4DefaultRoute.iface_ = TUN_CARD_NAME;
263 ipv4DefaultRoute.destination_.type_ = INetAddr::IPV4;
264 ipv4DefaultRoute.destination_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
265 ipv4DefaultRoute.destination_.prefixlen_ = CommonUtils::GetMaskLength(IPV4_DEFAULT_ROUTE_ADDR);
266 ipv4DefaultRoute.gateway_.address_ = IPV4_DEFAULT_ROUTE_ADDR;
267 }
268
SetIpv6DefaultRoute(Route & ipv6DefaultRoute)269 void NetVpnImpl::SetIpv6DefaultRoute(Route &ipv6DefaultRoute)
270 {
271 ipv6DefaultRoute.iface_ = TUN_CARD_NAME;
272 ipv6DefaultRoute.destination_.type_ = INetAddr::IPV6;
273 ipv6DefaultRoute.destination_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
274 ipv6DefaultRoute.destination_.prefixlen_ = CommonUtils::Ipv6PrefixLen(IPV6_DEFAULT_ROUTE_ADDR);
275 ipv6DefaultRoute.gateway_.address_ = IPV6_DEFAULT_ROUTE_ADDR;
276 }
277
DelNetLinkInfo(NetConnClient & netConnClientIns)278 void NetVpnImpl::DelNetLinkInfo(NetConnClient &netConnClientIns)
279 {
280 for (auto &route : vpnConfig_->routes_) {
281 AdjustRouteInfo(route);
282 std::string destAddress = route.destination_.address_ + "/" + std::to_string(route.destination_.prefixlen_);
283 NetsysController::GetInstance().NetworkRemoveRoute(netId_, route.iface_, destAddress, route.gateway_.address_);
284 }
285 }
286
AdjustRouteInfo(Route & route)287 void NetVpnImpl::AdjustRouteInfo(Route &route)
288 {
289 if (route.iface_.empty()) {
290 route.iface_ = TUN_CARD_NAME;
291 }
292 if (vpnConfig_->isAcceptIPv4_ == true) {
293 uint32_t maskUint = (0xFFFFFFFF << (IPV4_NET_MASK_MAX_LENGTH - route.destination_.prefixlen_));
294 uint32_t ipAddrUint = CommonUtils::ConvertIpv4Address(route.destination_.address_);
295 uint32_t subNetAddress = ipAddrUint & maskUint;
296 route.destination_.address_ = CommonUtils::ConvertIpv4Address(subNetAddress);
297 } else {
298 route.destination_.address_ = CommonUtils::GetIpv6Prefix(route.destination_.address_,
299 route.destination_.prefixlen_);
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