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 "networkvpn_service.h"
17
18 #include <cerrno>
19 #include <ctime>
20 #include <fcntl.h>
21 #include <sys/socket.h>
22 #include <sys/stat.h>
23 #include <sys/types.h>
24 #include <sys/un.h>
25 #include <unistd.h>
26
27 #include "ipc_skeleton.h"
28 #include "securec.h"
29 #include "system_ability_definition.h"
30
31 #include "extended_vpn_ctl.h"
32 #include "net_event_report.h"
33 #include "net_manager_center.h"
34 #include "net_manager_constants.h"
35 #include "net_manager_ext_constants.h"
36 #include "netmanager_base_permission.h"
37 #include "netmgr_ext_log_wrapper.h"
38 #include "netsys_controller.h"
39 #include "networkvpn_hisysevent.h"
40
41 namespace OHOS {
42 namespace NetManagerStandard {
43 constexpr int32_t MAX_CALLBACK_COUNT = 128;
44 constexpr const char *NET_ACTIVATE_WORK_THREAD = "VPN_CALLBACK_WORK_THREAD";
45
46 const bool REGISTER_LOCAL_RESULT_NETVPN =
47 SystemAbility::MakeAndRegisterAbility(&Singleton<NetworkVpnService>::GetInstance());
48
NetworkVpnService()49 NetworkVpnService::NetworkVpnService() : SystemAbility(COMM_VPN_MANAGER_SYS_ABILITY_ID, true) {}
50 NetworkVpnService::~NetworkVpnService() = default;
51
OnStart()52 void NetworkVpnService::OnStart()
53 {
54 if (state_ == STATE_RUNNING) {
55 NETMGR_EXT_LOG_D("OnStart Vpn Service state is already running");
56 return;
57 }
58 if (!Init()) {
59 NETMGR_EXT_LOG_E("OnStart Vpn init failed");
60 VpnHisysEvent::SendFaultEvent(VpnEventType::TYPE_UNKNOWN, VpnEventOperator::OPERATION_START_SA,
61 VpnEventErrorType::ERROR_INTERNAL_ERROR, "Start Vpn Service failed");
62 return;
63 }
64 state_ = STATE_RUNNING;
65 NETMGR_EXT_LOG_I("OnStart vpn successful");
66 }
67
OnStop()68 void NetworkVpnService::OnStop()
69 {
70 state_ = STATE_STOPPED;
71 isServicePublished_ = false;
72
73 if (policyCallRunner_) {
74 policyCallRunner_->Stop();
75 }
76 NETMGR_EXT_LOG_I("OnStop vpn successful");
77 }
78
Dump(int32_t fd,const std::vector<std::u16string> & args)79 int32_t NetworkVpnService::Dump(int32_t fd, const std::vector<std::u16string> &args)
80 {
81 std::string result;
82 GetDumpMessage(result);
83 NETMGR_EXT_LOG_I("Vpn dump fd: %{public}d, content: %{public}s", fd, result.c_str());
84 int32_t ret = dprintf(fd, "%s\n", result.c_str());
85 if (ret < 0) {
86 NETMGR_EXT_LOG_E("dprintf failed, errno[%{public}d]", errno);
87 return NETMANAGER_EXT_ERR_INTERNAL;
88 }
89 return NETMANAGER_EXT_SUCCESS;
90 }
91
Init()92 bool NetworkVpnService::Init()
93 {
94 if (!REGISTER_LOCAL_RESULT_NETVPN) {
95 NETMGR_EXT_LOG_E("Register to local sa manager failed");
96 return false;
97 }
98 if (!isServicePublished_) {
99 if (!Publish(&Singleton<NetworkVpnService>::GetInstance())) {
100 NETMGR_EXT_LOG_E("Register to sa manager failed");
101 return false;
102 }
103 isServicePublished_ = true;
104 }
105
106 if (!vpnConnCallback_) {
107 vpnConnCallback_ = std::make_shared<VpnConnStateCb>(*this);
108 }
109
110 if (!policyCallHandler_) {
111 policyCallRunner_ = AppExecFwk::EventRunner::Create(NET_ACTIVATE_WORK_THREAD);
112 policyCallHandler_ = std::make_shared<AppExecFwk::EventHandler>(policyCallRunner_);
113 }
114 return true;
115 }
116
GetDumpMessage(std::string & message)117 void NetworkVpnService::GetDumpMessage(std::string &message)
118 {
119 message.append("Net Vpn Info:\n");
120 if (vpnObj_ != nullptr) {
121 const auto &config = vpnObj_->GetVpnConfig();
122 std::string isLegacy = (config->isLegacy_) ? "true" : "false";
123 message.append("\tisLegacy: " + isLegacy + "\n");
124 message.append("\tPackageName: " + vpnObj_->GetVpnPkg() + "\n");
125 message.append("\tinterface: " + vpnObj_->GetInterfaceName() + "\n");
126 message.append("\tstate: connected\n");
127 } else {
128 message.append("\tstate: disconnected\n");
129 }
130 message.append("\tend.\n");
131 }
132
OnVpnConnStateChanged(const VpnConnectState & state)133 void NetworkVpnService::VpnConnStateCb::OnVpnConnStateChanged(const VpnConnectState &state)
134 {
135 NETMGR_EXT_LOG_I("receive new vpn connect state[%{public}d].", static_cast<uint32_t>(state));
136 if (vpnService_.policyCallHandler_) {
137 vpnService_.policyCallHandler_->PostSyncTask([this, &state]() {
138 std::for_each(vpnService_.vpnEventCallbacks_.begin(), vpnService_.vpnEventCallbacks_.end(),
139 [&state](const auto &callback) {
140 callback->OnVpnStateChanged((VpnConnectState::VPN_CONNECTED == state) ? true : false);
141 });
142 });
143 }
144 }
145
OnVpnMultiUserSetUp()146 void NetworkVpnService::OnVpnMultiUserSetUp()
147 {
148 NETMGR_EXT_LOG_I("user multiple execute set up.");
149 if (policyCallHandler_) {
150 policyCallHandler_->PostSyncTask([this]() {
151 std::for_each(vpnEventCallbacks_.begin(), vpnEventCallbacks_.end(),
152 [](const auto &callback) { callback->OnVpnMultiUserSetUp(); });
153 });
154 }
155 }
156
Prepare(bool & isExistVpn,bool & isRun,std::string & pkg)157 int32_t NetworkVpnService::Prepare(bool &isExistVpn, bool &isRun, std::string &pkg)
158 {
159 isRun = false;
160 isExistVpn = false;
161 if (vpnObj_ != nullptr) {
162 isExistVpn = true;
163 isRun = vpnObj_->IsVpnConnecting();
164 pkg = vpnObj_->GetVpnPkg();
165 }
166 NETMGR_EXT_LOG_I("NetworkVpnService Prepare successfully");
167 return NETMANAGER_EXT_SUCCESS;
168 }
169
SetUpVpn(const sptr<VpnConfig> & config)170 int32_t NetworkVpnService::SetUpVpn(const sptr<VpnConfig> &config)
171 {
172 int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
173 int32_t ret = CheckCurrentAccountType(userId);
174 if (NETMANAGER_EXT_SUCCESS != ret) {
175 return ret;
176 }
177
178 if (vpnObj_ != nullptr) {
179 if (vpnObj_->GetUserId() == userId) {
180 NETMGR_EXT_LOG_W("vpn exist already, please execute destory first");
181 return NETWORKVPN_ERROR_VPN_EXIST;
182 } else {
183 OnVpnMultiUserSetUp();
184 vpnObj_->Destroy();
185 }
186 }
187
188 vpnObj_ = std::make_shared<ExtendedVpnCtl>(config, "", userId);
189 if (vpnObj_->RegisterConnectStateChangedCb(vpnConnCallback_) != NETMANAGER_EXT_SUCCESS) {
190 NETMGR_EXT_LOG_E("SetUpVpn register internal callback fail.");
191 return NETMANAGER_EXT_ERR_INTERNAL;
192 }
193 NETMGR_EXT_LOG_I("NetworkVpnService SetUp");
194 return vpnObj_->SetUp();
195 }
196
Protect()197 int32_t NetworkVpnService::Protect()
198 {
199 /*
200 * Only permission verification is performed and
201 * the protected socket implements fwmark_service in the netsys process.
202 */
203 NETMGR_EXT_LOG_I("Protect vpn tunnel successfully.");
204 return NETMANAGER_EXT_SUCCESS;
205 }
206
DestroyVpn()207 int32_t NetworkVpnService::DestroyVpn()
208 {
209 int32_t userId = AppExecFwk::Constants::UNSPECIFIED_USERID;
210 int32_t ret = CheckCurrentAccountType(userId);
211 if (NETMANAGER_EXT_SUCCESS != ret) {
212 return ret;
213 }
214
215 if ((vpnObj_ != nullptr) && (vpnObj_->Destroy() != NETMANAGER_EXT_SUCCESS)) {
216 NETMGR_EXT_LOG_E("destroy vpn is failed");
217 return NETMANAGER_EXT_ERR_INTERNAL;
218 }
219 vpnObj_ = nullptr;
220 NETMGR_EXT_LOG_I("Destroy vpn successfully.");
221 return NETMANAGER_EXT_SUCCESS;
222 }
223
RegisterVpnEvent(const sptr<IVpnEventCallback> callback)224 int32_t NetworkVpnService::RegisterVpnEvent(const sptr<IVpnEventCallback> callback)
225 {
226 int32_t ret = NETMANAGER_EXT_ERR_OPERATION_FAILED;
227 if (policyCallHandler_) {
228 policyCallHandler_->PostSyncTask([this, &callback, &ret]() { ret = SyncRegisterVpnEvent(callback); });
229 }
230 return ret;
231 }
232
UnregisterVpnEvent(const sptr<IVpnEventCallback> callback)233 int32_t NetworkVpnService::UnregisterVpnEvent(const sptr<IVpnEventCallback> callback)
234 {
235 int32_t ret = NETMANAGER_EXT_ERR_OPERATION_FAILED;
236 if (policyCallHandler_) {
237 policyCallHandler_->PostSyncTask([this, &callback, &ret]() { ret = SyncUnregisterVpnEvent(callback); });
238 }
239 return ret;
240 }
241
CreateVpnConnection()242 int32_t NetworkVpnService::CreateVpnConnection()
243 {
244 /*
245 * Only permission verification is performed
246 */
247 NETMGR_EXT_LOG_I("CreateVpnConnection successfully.");
248 return NETMANAGER_EXT_SUCCESS;
249 }
250
CheckCurrentAccountType(int32_t & userId)251 int32_t NetworkVpnService::CheckCurrentAccountType(int32_t &userId)
252 {
253 int32_t uid = IPCSkeleton::GetCallingUid();
254 if (AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId) != ERR_OK) {
255 NETMGR_EXT_LOG_E("GetOsAccountLocalIdFromUid error, uid: %{public}d.", uid);
256 return NETMANAGER_EXT_ERR_INTERNAL;
257 }
258
259 std::vector<int32_t> activeUserIds;
260 if (AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeUserIds) != ERR_OK) {
261 NETMGR_EXT_LOG_E("QueryActiveOsAccountIds error.");
262 return NETMANAGER_EXT_ERR_INTERNAL;
263 }
264
265 auto itr = std::find_if(activeUserIds.begin(), activeUserIds.end(),
266 [userId](const int32_t &elem) { return (elem == userId) ? true : false; });
267 if (itr == activeUserIds.end()) {
268 NETMGR_EXT_LOG_E("userId: %{public}d is not active user. activeUserIds.size: %{public}zd", userId,
269 activeUserIds.size());
270 return NETWORKVPN_ERROR_REFUSE_CREATE_VPN;
271 }
272
273 AccountSA::OsAccountInfo accountInfo;
274 if (AccountSA::OsAccountManager::QueryOsAccountById(userId, accountInfo) != ERR_OK) {
275 NETMGR_EXT_LOG_E("QueryOsAccountById error, userId: %{public}d.", userId);
276 return NETMANAGER_EXT_ERR_INTERNAL;
277 }
278
279 if (accountInfo.GetType() == AccountSA::OsAccountType::GUEST) {
280 NETMGR_EXT_LOG_E("The guest user cannot execute the VPN interface.");
281 return NETWORKVPN_ERROR_REFUSE_CREATE_VPN;
282 }
283 return NETMANAGER_EXT_SUCCESS;
284 }
285
SyncRegisterVpnEvent(const sptr<IVpnEventCallback> callback)286 int32_t NetworkVpnService::SyncRegisterVpnEvent(const sptr<IVpnEventCallback> callback)
287 {
288 for (auto iterCb = vpnEventCallbacks_.begin(); iterCb != vpnEventCallbacks_.end(); iterCb++) {
289 if ((*iterCb)->AsObject().GetRefPtr() == callback->AsObject().GetRefPtr()) {
290 NETMGR_EXT_LOG_E("Register vpn event callback failed, callback already exists");
291 return NETMANAGER_EXT_ERR_OPERATION_FAILED;
292 }
293 }
294
295 if (vpnEventCallbacks_.size() >= MAX_CALLBACK_COUNT) {
296 NETMGR_EXT_LOG_E("callback above max count, return error.");
297 return NETMANAGER_EXT_ERR_PARAMETER_ERROR;
298 }
299
300 vpnEventCallbacks_.push_back(callback);
301 NETMGR_EXT_LOG_I("Register vpn event callback successfully");
302 return NETMANAGER_EXT_SUCCESS;
303 }
304
SyncUnregisterVpnEvent(const sptr<IVpnEventCallback> callback)305 int32_t NetworkVpnService::SyncUnregisterVpnEvent(const sptr<IVpnEventCallback> callback)
306 {
307 for (auto iter = vpnEventCallbacks_.begin(); iter != vpnEventCallbacks_.end(); ++iter) {
308 if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
309 vpnEventCallbacks_.erase(iter);
310 NETMGR_EXT_LOG_I("Unregister vpn event successfully.");
311 return NETMANAGER_EXT_SUCCESS;
312 }
313 }
314 NETMGR_EXT_LOG_E("Unregister vpn event callback is does not exist.");
315 return NETMANAGER_EXT_ERR_OPERATION_FAILED;
316 }
317
318 } // namespace NetManagerStandard
319 } // namespace OHOS
320