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