1 /*
2 * Copyright (c) 2021-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 "usb_right_manager.h"
17
18 #include <algorithm>
19 #include <semaphore.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22
23 #include "ability_manager_client.h"
24 #include "accesstoken_kit.h"
25 #include "bundle_mgr_interface.h"
26 #include "common_event_manager.h"
27 #include "common_event_support.h"
28 #include "ipc_skeleton.h"
29 #include "iservice_registry.h"
30 #include "os_account_manager.h"
31 #include "string_ex.h"
32 #include "system_ability_definition.h"
33 #include "tokenid_kit.h"
34 #include "usb_errors.h"
35 #include "usb_right_db_helper.h"
36 #include "usb_napi_errors.h"
37 #include "usb_srv_support.h"
38 #include "usb_service.h"
39 #include "parameters.h"
40
41 using namespace OHOS::AppExecFwk;
42 using namespace OHOS::EventFwk;
43 using namespace OHOS::Security::AccessToken;
44
45 namespace OHOS {
46 namespace USB {
47
48 constexpr int32_t PARAM_BUF_LEN = 128;
49 constexpr int32_t USB_RIGHT_USERID_INVALID = -1;
50 constexpr int32_t USB_RIGHT_USERID_DEFAULT = 100;
51 constexpr int32_t USB_RIGHT_USERID_CONSOLE = 0;
52 constexpr int32_t MAX_RETRY_TIMES = 30;
53 constexpr int32_t RETRY_INTERVAL_SECONDS = 1;
54 const std::string USB_MANAGE_ACCESS_USB_DEVICE = "ohos.permission.MANAGE_USB_CONFIG";
55 const std::string DEVELOPERMODE_STATE = "const.security.developermode.state";
56 enum UsbRightTightUpChoose : uint32_t {
57 TIGHT_UP_USB_RIGHT_RECORD_NONE = 0,
58 TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED = 1 << 0,
59 TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED = 1 << 1,
60 TIGHT_UP_USB_RIGHT_RECORD_EXPIRED = 1 << 2,
61 TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED = 1 << 3,
62 };
63
64 constexpr uint32_t TIGHT_UP_USB_RIGHT_RECORD_ALL =
65 (TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED | TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED |
66 TIGHT_UP_USB_RIGHT_RECORD_EXPIRED | TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED);
67
68 sem_t UsbRightManager::waitDialogDisappear_ {0};
69
70 class RightSubscriber : public CommonEventSubscriber {
71 public:
RightSubscriber(const CommonEventSubscribeInfo & sp)72 explicit RightSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp) {}
73
OnReceiveEvent(const CommonEventData & data)74 void OnReceiveEvent(const CommonEventData &data) override
75 {
76 auto &want = data.GetWant();
77 std::string wantAction = want.GetAction();
78
79 USB_HILOGD(MODULE_USB_SERVICE, "%{public}s wantAction %{public}s", __func__, wantAction.c_str());
80 if (wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED ||
81 wantAction == CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED ||
82 wantAction == CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED) {
83 int32_t uid = want.GetParams().GetIntParam("userId", USB_RIGHT_USERID_DEFAULT);
84 std::string bundleName = want.GetBundle();
85 int32_t ret = UsbRightManager::CleanUpRightAppUninstalled(uid, bundleName);
86 USB_HILOGD(MODULE_USB_SERVICE,
87 "recv event uninstall: event=%{public}s bunndleName=%{public}s uid=%{public}d, delete_ret=%{public}d",
88 wantAction.c_str(), bundleName.c_str(), uid, ret);
89 } else if (wantAction == CommonEventSupport::COMMON_EVENT_UID_REMOVED ||
90 wantAction == CommonEventSupport::COMMON_EVENT_USER_REMOVED) {
91 int32_t totalUsers = 0;
92 int32_t deleteUsers = 0;
93 int32_t ret = UsbRightManager::CleanUpRightUserDeleted(totalUsers, deleteUsers);
94 USB_HILOGD(MODULE_USB_SERVICE,
95 "recv event user delete: event=%{public}s, delete detail[%{public}d/%{public}d]: %{public}d",
96 wantAction.c_str(), deleteUsers, totalUsers, ret);
97 } else if (wantAction == CommonEventSupport::COMMON_EVENT_USER_STOPPED) {
98 int32_t uid = data.GetCode();
99 int32_t ret = UsbRightManager::CleanUpRightUserStopped(uid);
100 USB_HILOGD(MODULE_USB_SERVICE, "on user %{public}d stopped, ret=%{public}d", uid, ret);
101 } else if (wantAction == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
102 USB_HILOGI(MODULE_USB_SERVICE, "recv user switched.");
103 auto usbService = UsbService::GetGlobalInstance();
104 if (usbService != nullptr) {
105 usbService->UserChangeProcess();
106 }
107 }
108 }
109 };
110
Init()111 int32_t UsbRightManager::Init()
112 {
113 USB_HILOGI(MODULE_USB_SERVICE, "subscriber app/bundle remove event and uid/user remove event");
114 MatchingSkills matchingSkills;
115 /* subscribe app/bundle remove event, need permission: ohos.permission.LISTEN_BUNDLE_CHANGE */
116 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
117 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BUNDLE_REMOVED);
118 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_FULLY_REMOVED);
119 /* subscribe uid/user remove event */
120 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_UID_REMOVED);
121 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
122 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_STOPPED);
123
124 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
125 CommonEventSubscribeInfo subscriberInfo(matchingSkills);
126 std::shared_ptr<RightSubscriber> subscriber = std::make_shared<RightSubscriber>(subscriberInfo);
127 int32_t retryTimes = 0;
128 while (retryTimes < MAX_RETRY_TIMES) {
129 retryTimes++;
130 bool ret = CommonEventManager::SubscribeCommonEvent(subscriber);
131 if (!ret) {
132 USB_HILOGW(MODULE_USB_SERVICE, "subscriber event for right manager failed: %{public}d", ret);
133 sleep(RETRY_INTERVAL_SECONDS);
134 continue;
135 }
136 return UEC_OK;
137 }
138 return UEC_SERVICE_INNER_ERR;
139 }
140
HasRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)141 bool UsbRightManager::HasRight(const std::string &deviceName, const std::string &bundleName,
142 const std::string &tokenId, const int32_t &userId)
143 {
144 USB_HILOGI(MODULE_USB_SERVICE, "HasRight: uid=%{public}d app=%{public}s",
145 userId, bundleName.c_str());
146 if (userId == USB_RIGHT_USERID_CONSOLE) {
147 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
148 return true;
149 }
150 uint64_t nowTime = GetCurrentTimestamp();
151 (void)TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_EXPIRED);
152 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
153 // no record or expired record: expired true, has right false, add right next time
154 // valid record: expired false, has right true, no need add right
155 if (helper == nullptr) {
156 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
157 return false;
158 }
159 return !helper->IsRecordExpired(userId, deviceName, bundleName, tokenId, nowTime);
160 }
161
RequestRight(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)162 int32_t UsbRightManager::RequestRight(const std::string &busDev, const std::string &deviceName,
163 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
164 {
165 USB_HILOGD(MODULE_USB_SERVICE, "RequestRight: busdev=%{private}s app=%{public}s", busDev.c_str(),
166 bundleName.c_str());
167 if (HasRight(deviceName, bundleName, tokenId, userId)) {
168 USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
169 return UEC_OK;
170 }
171 if (!GetUserAgreementByDiag(busDev, deviceName, bundleName, tokenId, userId)) {
172 USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
173 return UEC_SERVICE_PERMISSION_DENIED;
174 }
175 return UEC_OK;
176 }
177
RequestRight(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId,const int32_t & userId,bool & result)178 int32_t UsbRightManager::RequestRight(const USBAccessory &access, const std::string &seriaValue,
179 const std::string &bundleName, const std::string &tokenId, const int32_t &userId, bool &result)
180 {
181 USB_HILOGD(MODULE_USB_SERVICE, "RequestAccessoryRight: seriaValue=%{public}s app=%{public}s",
182 seriaValue.c_str(), bundleName.c_str());
183 if (HasRight(seriaValue, bundleName, tokenId, userId)) {
184 USB_HILOGW(MODULE_USB_SERVICE, "device has Right ");
185 result = true;
186 return UEC_OK;
187 }
188 if (!GetUserAgreementByDiag(access, seriaValue, bundleName, tokenId, userId)) {
189 USB_HILOGW(MODULE_USB_SERVICE, "user don't agree");
190 result = false;
191 return UEC_OK;
192 }
193 result = true;
194 return UEC_OK;
195 }
196
AddDeviceRight(const std::string & deviceName,const std::string & tokenIdStr)197 bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &tokenIdStr)
198 {
199 if (!IsAllDigits(tokenIdStr)) {
200 USB_HILOGE(MODULE_USB_SERVICE, "tokenIdStr invalid");
201 return false;
202 }
203 /* already checked system app/hap when call */
204 uint32_t tokenId = stoul(tokenIdStr);
205 HapTokenInfo hapTokenInfoRes;
206 int32_t ret = AccessTokenKit::GetHapTokenInfo((AccessTokenID) tokenId, hapTokenInfoRes);
207 if (ret != UEC_OK) {
208 USB_HILOGE(MODULE_USB_SERVICE, "GetHapTokenInfo failed:ret:%{public}d", ret);
209 return false;
210 }
211 int32_t uid = hapTokenInfoRes.userID;
212 if (uid == USB_RIGHT_USERID_CONSOLE) {
213 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
214 return true;
215 }
216 uint64_t installTime = GetCurrentTimestamp();
217 uint64_t updateTime = GetCurrentTimestamp();
218 if (!GetBundleInstallAndUpdateTime(uid, hapTokenInfoRes.bundleName, installTime, updateTime)) {
219 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}d", uid);
220 }
221 struct UsbRightAppInfo info;
222 info.uid = uid;
223 info.installTime = installTime;
224 info.updateTime = updateTime;
225 info.requestTime = GetCurrentTimestamp();
226 info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
227
228 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
229 if (helper == nullptr) {
230 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
231 return false;
232 }
233 ret = helper->AddOrUpdateRightRecord(uid, deviceName, hapTokenInfoRes.bundleName, tokenIdStr, info);
234 if (ret < 0) {
235 USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}d, ret=%{public}d",
236 deviceName.c_str(), uid, ret);
237 return false;
238 }
239 return true;
240 }
241
AddDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)242 bool UsbRightManager::AddDeviceRight(const std::string &deviceName, const std::string &bundleName,
243 const std::string &tokenId, const int32_t &userId)
244 {
245 /* already checked system app/hap when call */
246 if (userId == USB_RIGHT_USERID_CONSOLE) {
247 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
248 return true;
249 }
250 uint64_t installTime = GetCurrentTimestamp();
251 uint64_t updateTime = GetCurrentTimestamp();
252 if (!GetBundleInstallAndUpdateTime(userId, bundleName, installTime, updateTime)) {
253 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: %{public}s/%{public}d",
254 bundleName.c_str(), userId);
255 }
256 struct UsbRightAppInfo info;
257 info.uid = userId;
258 info.installTime = installTime;
259 info.updateTime = updateTime;
260 info.requestTime = GetCurrentTimestamp();
261 info.validPeriod = USB_RIGHT_VALID_PERIOD_SET;
262
263 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
264 if (helper == nullptr) {
265 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
266 return false;
267 }
268 auto ret = helper->AddOrUpdateRightRecord(userId, deviceName, bundleName, tokenId, info);
269 if (ret < 0) {
270 USB_HILOGE(MODULE_USB_SERVICE, "add or update failed: %{public}s/%{public}s/%{public}d, ret=%{public}d",
271 deviceName.c_str(), bundleName.c_str(), userId, ret);
272 return false;
273 }
274 return true;
275 }
276
RemoveDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)277 bool UsbRightManager::RemoveDeviceRight(const std::string &deviceName, const std::string &bundleName,
278 const std::string &tokenId, const int32_t &userId)
279 {
280 if (userId == USB_RIGHT_USERID_CONSOLE) {
281 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
282 return true;
283 }
284 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
285 if (helper == nullptr) {
286 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
287 return false;
288 }
289 int32_t ret = helper->DeleteRightRecord(userId, deviceName, bundleName, tokenId);
290 if (ret < 0) {
291 USB_HILOGE(MODULE_USB_SERVICE, "delete failed: %{public}s/%{public}s/%{public}d", deviceName.c_str(),
292 bundleName.c_str(), userId);
293 return false;
294 }
295 return true;
296 }
297
CancelDeviceRight(const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)298 int32_t UsbRightManager::CancelDeviceRight(const std::string &deviceName, const std::string &bundleName,
299 const std::string &tokenId, const int32_t &userId)
300 {
301 if (userId == USB_RIGHT_USERID_CONSOLE) {
302 USB_HILOGW(MODULE_USB_SERVICE, "console called, bypass");
303 return UEC_SERVICE_INVALID_VALUE;
304 }
305 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
306 if (helper == nullptr) {
307 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
308 return UEC_SERVICE_INNER_ERR;
309 }
310 int32_t ret = helper->DeleteRightRecord(userId, deviceName, bundleName, tokenId);
311 if (ret < 0) {
312 USB_HILOGW(MODULE_USB_SERVICE, "delete failed: %{public}s/%{public}s/%{public}d", deviceName.c_str(),
313 bundleName.c_str(), userId);
314 return UEC_OK;
315 }
316 return UEC_OK;
317 }
318
RemoveDeviceAllRight(const std::string & deviceName)319 bool UsbRightManager::RemoveDeviceAllRight(const std::string &deviceName)
320 {
321 USB_HILOGD(MODULE_USB_SERVICE, "device %{private}s detached, process right", deviceName.c_str());
322 CleanUpRightTemporaryExpired(deviceName);
323 TidyUpRight(TIGHT_UP_USB_RIGHT_RECORD_ALL);
324 return true;
325 }
326
ShowUsbDialog(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId)327 bool UsbRightManager::ShowUsbDialog(
328 const std::string &busDev, const std::string &deviceName, const std::string &bundleName, const std::string &tokenId)
329 {
330 auto abmc = AAFwk::AbilityManagerClient::GetInstance();
331 if (abmc == nullptr) {
332 USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed");
333 return false;
334 }
335
336 std::string appName;
337 if (!GetAppName(bundleName, appName)) {
338 appName = bundleName;
339 }
340
341 std::string productName;
342 if (!GetProductName(busDev, productName)) {
343 productName = busDev;
344 }
345
346 AAFwk::Want want;
347 want.SetElementName("com.usb.right", "UsbServiceExtAbility");
348 want.SetParam("bundleName", bundleName);
349 want.SetParam("deviceName", busDev);
350 want.SetParam("tokenId", tokenId);
351 want.SetParam("appName", appName);
352 want.SetParam("productName", productName);
353
354 sptr<UsbAbilityConn> usbAbilityConn_ = new (std::nothrow) UsbAbilityConn();
355 if (usbAbilityConn_ == nullptr) {
356 USB_HILOGE(MODULE_SERVICE, "new (std::nothrow) UsbAbilityConn() failed");
357 return false;
358 }
359 sem_init(&waitDialogDisappear_, 1, 0);
360 auto ret = abmc->ConnectAbility(want, usbAbilityConn_, -1);
361 if (ret != UEC_OK) {
362 USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
363 return false;
364 }
365 /* Waiting for the user to click */
366 sem_wait(&waitDialogDisappear_);
367 return true;
368 }
369
GetAccessoryName(const USBAccessory & access,std::string & accessName)370 bool UsbRightManager::GetAccessoryName(const USBAccessory &access, std::string &accessName)
371 {
372 accessName = access.GetProduct();
373 return true;
374 }
375
ShowUsbDialog(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId)376 bool UsbRightManager::ShowUsbDialog(const USBAccessory &access, const std::string &seriaValue,
377 const std::string &bundleName, const std::string &tokenId)
378 {
379 auto abmc = AAFwk::AbilityManagerClient::GetInstance();
380 if (abmc == nullptr) {
381 USB_HILOGE(MODULE_USB_SERVICE, "GetInstance failed");
382 return false;
383 }
384
385 std::string appName;
386 if (!GetAppName(bundleName, appName)) {
387 appName = bundleName;
388 }
389
390 std::string accessoryName;
391 if (!GetAccessoryName(access, accessoryName)) {
392 accessoryName = seriaValue;
393 }
394
395 AAFwk::Want want;
396 want.SetElementName("com.usb.right", "UsbServiceExtAbility");
397 want.SetParam("bundleName", bundleName);
398 want.SetParam("deviceName", seriaValue);
399 want.SetParam("tokenId", tokenId);
400 want.SetParam("appName", appName);
401 want.SetParam("productName", accessoryName);
402 want.SetParam("accessory", access.GetJsonString());
403
404 sptr<UsbAbilityConn> usbAbilityConn_ = new (std::nothrow) UsbAbilityConn();
405 if (usbAbilityConn_ == nullptr) {
406 USB_HILOGE(MODULE_SERVICE, "new (std::nothrow) UsbAbilityConn() failed");
407 return false;
408 }
409 sem_init(&waitDialogDisappear_, 1, 0);
410 auto ret = abmc->ConnectAbility(want, usbAbilityConn_, -1);
411 if (ret != UEC_OK) {
412 USB_HILOGE(MODULE_SERVICE, "connectAbility failed %{public}d", ret);
413 return false;
414 }
415 /* Waiting for the user to click */
416 sem_wait(&waitDialogDisappear_);
417 return true;
418 }
419
GetUserAgreementByDiag(const std::string & busDev,const std::string & deviceName,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)420 bool UsbRightManager::GetUserAgreementByDiag(const std::string &busDev, const std::string &deviceName,
421 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
422 {
423 #ifdef USB_RIGHT_TEST
424 return true;
425 #endif
426 /* There can only be one dialog at a time */
427 std::lock_guard<std::mutex> guard(dialogRunning_);
428 if (!ShowUsbDialog(busDev, deviceName, bundleName, tokenId)) {
429 USB_HILOGE(MODULE_USB_SERVICE, "ShowUsbDialog failed");
430 return false;
431 }
432
433 return HasRight(deviceName, bundleName, tokenId, userId);
434 }
435
GetUserAgreementByDiag(const USBAccessory & access,const std::string & seriaValue,const std::string & bundleName,const std::string & tokenId,const int32_t & userId)436 bool UsbRightManager::GetUserAgreementByDiag(const USBAccessory &access, const std::string &seriaValue,
437 const std::string &bundleName, const std::string &tokenId, const int32_t &userId)
438 {
439 /* There can only be one dialog at a time */
440 std::lock_guard<std::mutex> guard(dialogRunning_);
441 if (!ShowUsbDialog(access, seriaValue, bundleName, tokenId)) {
442 USB_HILOGE(MODULE_USB_SERVICE, "ShowUsbDialog failed");
443 return false;
444 }
445
446 return HasRight(seriaValue, bundleName, tokenId, userId);
447 }
448
GetBundleMgr()449 sptr<IBundleMgr> UsbRightManager::GetBundleMgr()
450 {
451 auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
452 if (sam == nullptr) {
453 USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbilityManager return nullptr");
454 return nullptr;
455 }
456 auto bundleMgrSa = sam->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
457 if (bundleMgrSa == nullptr) {
458 USB_HILOGW(MODULE_USB_SERVICE, "GetSystemAbility return nullptr");
459 return nullptr;
460 }
461 auto bundleMgr = iface_cast<IBundleMgr>(bundleMgrSa);
462 if (bundleMgr == nullptr) {
463 USB_HILOGW(MODULE_USB_SERVICE, "iface_cast return nullptr");
464 }
465 return bundleMgr;
466 }
467
GetBundleResMgr()468 sptr<IBundleResource> UsbRightManager::GetBundleResMgr()
469 {
470 auto bundleMgr = GetBundleMgr();
471 if (bundleMgr == nullptr) {
472 return nullptr;
473 }
474 return bundleMgr->GetBundleResourceProxy();
475 }
476
GetAppName(const std::string & bundleName,std::string & appName)477 bool UsbRightManager::GetAppName(const std::string &bundleName, std::string &appName)
478 {
479 auto resMgr = GetBundleResMgr();
480 if (resMgr == nullptr) {
481 USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res mgr failed");
482 return false;
483 }
484
485 BundleResourceInfo info;
486 auto ret = resMgr->GetBundleResourceInfo(bundleName, (uint32_t)ResourceFlag::GET_RESOURCE_INFO_WITH_LABEL, info);
487 if (ret != ERR_OK) {
488 USB_HILOGE(MODULE_USB_SERVICE, "GetAppName: get res info failed: %{public}d", ret);
489 return false;
490 }
491 appName = info.label;
492 return true;
493 }
494
GetProductName(const std::string & devName,std::string & productName)495 bool UsbRightManager::GetProductName(const std::string &devName, std::string &productName)
496 {
497 auto usbService = UsbService::GetGlobalInstance();
498 if (usbService == nullptr) {
499 return false;
500 }
501 return usbService->GetDeviceProductName(devName, productName);
502 }
503
IsSystemAppOrSa()504 bool UsbRightManager::IsSystemAppOrSa()
505 {
506 uint64_t tokenid = IPCSkeleton::GetCallingFullTokenID();
507 bool isSystemApp = TokenIdKit::IsSystemAppByFullTokenID(tokenid);
508 if (isSystemApp) {
509 return true;
510 }
511
512 AccessTokenID accessTokenId = IPCSkeleton::GetCallingTokenID();
513 ATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(accessTokenId);
514 if (tokenType == TOKEN_NATIVE) {
515 return true;
516 }
517
518 USB_HILOGW(MODULE_USB_SERVICE, "neither system app nor sa");
519 return false;
520 }
521
VerifyPermission()522 bool UsbRightManager::VerifyPermission()
523 {
524 AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID();
525 int32_t ret = AccessTokenKit::VerifyAccessToken(tokenId, USB_MANAGE_ACCESS_USB_DEVICE);
526 if (ret == PermissionState::PERMISSION_DENIED) {
527 USB_HILOGW(MODULE_USB_SERVICE, "no permission");
528 return false;
529 }
530 return true;
531 }
532
IsAppInstalled(int32_t uid,const std::string & bundleName)533 bool UsbRightManager::IsAppInstalled(int32_t uid, const std::string &bundleName)
534 {
535 auto bundleMgr = GetBundleMgr();
536 if (bundleMgr == nullptr) {
537 USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
538 return false;
539 }
540 ApplicationInfo appInfo;
541 if (!bundleMgr->GetApplicationInfo(bundleName, GET_BASIC_APPLICATION_INFO, uid, appInfo)) {
542 USB_HILOGE(MODULE_USB_SERVICE, "BundleMgr GetApplicationInfo failed");
543 return false;
544 }
545 return true;
546 }
547
GetBundleInstallAndUpdateTime(int32_t uid,const std::string & bundleName,uint64_t & installTime,uint64_t & updateTime)548 bool UsbRightManager::GetBundleInstallAndUpdateTime(
549 int32_t uid, const std::string &bundleName, uint64_t &installTime, uint64_t &updateTime)
550 {
551 BundleInfo bundleInfo;
552 auto bundleMgr = GetBundleMgr();
553 if (bundleMgr == nullptr) {
554 USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr is nullptr, return false");
555 return false;
556 }
557 if (!bundleMgr->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, uid)) {
558 USB_HILOGW(MODULE_USB_SERVICE, "BundleMgr GetBundleInfo(uid) failed");
559 return false;
560 }
561 installTime = static_cast<uint64_t>(bundleInfo.installTime);
562 updateTime = static_cast<uint64_t>(bundleInfo.updateTime);
563 return true;
564 }
565
GetCurrentTimestamp()566 uint64_t UsbRightManager::GetCurrentTimestamp()
567 {
568 int64_t time =
569 std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
570 return static_cast<uint64_t>(time);
571 }
572
GetCurrentUserId(int32_t & uid)573 void UsbRightManager::GetCurrentUserId(int32_t &uid)
574 {
575 int32_t ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), uid);
576 if (ret != UEC_OK) {
577 USB_HILOGE(MODULE_USB_SERVICE, "GetOsAccountLocalIdFromUid failed: %{public}d, set to defult", ret);
578 uid = USB_RIGHT_USERID_DEFAULT; /* default user id */
579 }
580 USB_HILOGD(MODULE_USB_SERVICE, "usb get userid success: %{public}d, uid: %{public}d", ret, uid);
581 }
582
IsOsAccountExists(int32_t id,bool & isAccountExists)583 int32_t UsbRightManager::IsOsAccountExists(int32_t id, bool &isAccountExists)
584 {
585 int32_t ret = AccountSA::OsAccountManager::IsOsAccountExists(id, isAccountExists);
586 if (ret != UEC_OK) {
587 USB_HILOGE(MODULE_USB_SERVICE, " api IsOsAccountExists failed: ret=%{public}d id=%{public}d", ret, id);
588 return USB_RIGHT_FAILURE;
589 }
590 return USB_RIGHT_OK;
591 }
592
HasSetFuncRight(int32_t functions)593 int32_t UsbRightManager::HasSetFuncRight(int32_t functions)
594 {
595 if (!(IsSystemAppOrSa() && VerifyPermission())) {
596 return UEC_SERVICE_PERMISSION_DENIED_SYSAPI;
597 }
598 if (!(static_cast<uint32_t>(functions) & UsbSrvSupport::FUNCTION_HDC)) {
599 return UEC_OK;
600 }
601 USB_HILOGI(MODULE_USB_SERVICE, "Set up function permission validation");
602 char paramValue[PARAM_BUF_LEN] = { 0 };
603 int32_t ret = GetParameter("persist.hdc.control", "true", paramValue, sizeof(paramValue));
604 if (ret < 0) {
605 USB_HILOGW(MODULE_USB_SERVICE, "GetParameter fail");
606 }
607 ret = strcmp(paramValue, "true");
608 if (ret != 0) {
609 USB_HILOGE(MODULE_USB_SERVICE, "HDC setup failed");
610 return UEC_SERVICE_PERMISSION_CHECK_HDC;
611 }
612 if (!OHOS::system::GetBoolParameter(DEVELOPERMODE_STATE, false)) {
613 USB_HILOGE(MODULE_USB_SERVICE, "Developer mode unabled, FUNCTION_HDC cannot be set");
614 return UEC_SERVICE_PERMISSION_CHECK_HDC;
615 }
616 return UEC_OK;
617 }
618
CleanUpRightExpired(std::vector<std::string> & devices)619 int32_t UsbRightManager::CleanUpRightExpired(std::vector<std::string> &devices)
620 {
621 USB_HILOGD(MODULE_USB_SERVICE, "clean up expired right: size=%{public}zu", devices.size());
622 size_t len = devices.size();
623 int32_t ret = USB_RIGHT_OK;
624 for (size_t i = 0; i < len; i++) {
625 std::string dev = devices.at(i);
626 ret = CleanUpRightTemporaryExpired(dev);
627 if (ret != USB_RIGHT_OK) {
628 USB_HILOGE(MODULE_USB_SERVICE,
629 "failed(%{public}zu/%{public}zu): delete temporary expiried record, dev=%{private}s", i, len,
630 dev.c_str());
631 continue;
632 }
633 }
634 int32_t uid = USB_RIGHT_USERID_INVALID;
635 GetCurrentUserId(uid);
636 ret = CleanUpRightNormalExpired(uid);
637 if (ret != USB_RIGHT_OK) {
638 USB_HILOGE(MODULE_USB_SERVICE, "delete expired record with uid(%{public}d) failed: %{public}d", uid, ret);
639 }
640 return ret;
641 }
642
CleanUpRightAppUninstalled(int32_t uid,int32_t & totalApps,int32_t & deleteApps)643 int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, int32_t &totalApps, int32_t &deleteApps)
644 {
645 std::vector<std::string> apps;
646 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
647 if (helper == nullptr) {
648 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
649 return false;
650 }
651 int32_t ret = helper->QueryRightRecordApps(uid, apps);
652 if (ret <= 0) {
653 /* error or empty record */
654 return USB_RIGHT_NOP;
655 }
656 totalApps = static_cast<int32_t>(apps.size());
657 deleteApps = 0;
658 for (int32_t i = 0; i < totalApps; i++) {
659 std::string app = apps.at(i);
660 if (!IsAppInstalled(uid, app)) {
661 ret = helper->DeleteAppRightRecord(uid, app);
662 if (ret != USB_RIGHT_OK) {
663 USB_HILOGW(MODULE_USB_SERVICE, "clean failed: app=%{public}s, ret=%{public}d", app.c_str(), ret);
664 continue;
665 }
666 deleteApps++;
667 }
668 }
669 USB_HILOGD(MODULE_USB_SERVICE, "clean uninstall app record[%{public}d/%{public}d]: uid=%{public}d", deleteApps,
670 totalApps, uid);
671 return ret;
672 }
673
CleanUpRightAppUninstalled(int32_t uid,const std::string & bundleName)674 int32_t UsbRightManager::CleanUpRightAppUninstalled(int32_t uid, const std::string &bundleName)
675 {
676 std::vector<std::string> apps;
677 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
678 if (helper == nullptr) {
679 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
680 return false;
681 }
682 int32_t ret = helper->QueryRightRecordApps(uid, apps);
683 if (ret <= 0) {
684 /* error or empty record */
685 return USB_RIGHT_NOP;
686 }
687 int32_t index = 0;
688 if (!StringVectorFound(apps, bundleName, index)) {
689 /* app not in record, ignore */
690 return USB_RIGHT_NOP;
691 }
692 ret = helper->DeleteAppRightRecord(uid, apps.at(index));
693 USB_HILOGD(MODULE_USB_SERVICE, "clean[%{public}d/%{public}zu]: uid=%{public}d, app=%{public}s, ret=%{public}d",
694 index, apps.size(), uid, bundleName.c_str(), ret);
695 return ret;
696 }
697
StringVectorSortAndUniq(std::vector<std::string> & strings)698 void UsbRightManager::StringVectorSortAndUniq(std::vector<std::string> &strings)
699 {
700 sort(strings.begin(), strings.end());
701 auto last = unique(strings.begin(), strings.end());
702 strings.erase(last, strings.end());
703 }
704
StringVectorFound(const std::vector<std::string> & strings,const std::string & value,int32_t & index)705 bool UsbRightManager::StringVectorFound(
706 const std::vector<std::string> &strings, const std::string &value, int32_t &index)
707 {
708 size_t len = strings.size();
709 for (size_t i = 0; i < len; i++) {
710 if (value == strings.at(i)) {
711 index = static_cast<int32_t>(i);
712 return true;
713 }
714 }
715 return false;
716 }
717
CleanUpRightAppReinstalled(int32_t uid,uint32_t & totalApps,uint32_t & deleteApps)718 int32_t UsbRightManager::CleanUpRightAppReinstalled(int32_t uid, uint32_t &totalApps, uint32_t &deleteApps)
719 {
720 std::vector<std::string> apps;
721 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
722 if (helper == nullptr) {
723 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
724 return false;
725 }
726 int32_t ret = helper->QueryRightRecordApps(uid, apps);
727 if (ret <= 0) {
728 USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
729 return USB_RIGHT_NOP;
730 }
731 StringVectorSortAndUniq(apps);
732 deleteApps = 0;
733 totalApps = apps.size();
734 std::vector<std::string> deleteBundleNames;
735 for (size_t i = 0; i < apps.size(); i++) {
736 std::string bundleName = apps.at(i);
737 std::vector<struct UsbRightAppInfo> infos;
738 ret = helper->QueryAppRightRecord(uid, bundleName, infos);
739 if (ret < 0) {
740 USB_HILOGE(MODULE_USB_SERVICE, "query app info %{public}s failed: %{public}d", bundleName.c_str(), ret);
741 return USB_RIGHT_FAILURE;
742 }
743 uint64_t installTime = 0;
744 uint64_t updateTime = 0;
745 if (!GetBundleInstallAndUpdateTime(uid, bundleName, installTime, updateTime)) {
746 USB_HILOGE(MODULE_USB_SERVICE, "get app install time and update time failed: app=%{public}s uid=%{public}d",
747 bundleName.c_str(), uid);
748 return USB_RIGHT_FAILURE;
749 }
750 for (size_t j = 0; j < infos.size(); j++) {
751 struct UsbRightAppInfo info = infos.at(j);
752 if (info.installTime != installTime) {
753 deleteBundleNames.push_back(bundleName);
754 break;
755 }
756 }
757 }
758 StringVectorSortAndUniq(deleteBundleNames);
759 ret = helper->DeleteAppsRightRecord(uid, deleteBundleNames);
760 if (ret != USB_RIGHT_OK) {
761 USB_HILOGE(MODULE_USB_SERVICE, "delete apps failed: %{public}d", ret);
762 } else {
763 deleteApps = deleteBundleNames.size();
764 }
765 return ret;
766 }
767
CleanUpRightUserDeleted(int32_t & totalUsers,int32_t & deleteUsers)768 int32_t UsbRightManager::CleanUpRightUserDeleted(int32_t &totalUsers, int32_t &deleteUsers)
769 {
770 std::vector<std::string> rightRecordUids;
771 bool isAccountExists = false;
772 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
773 if (helper == nullptr) {
774 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
775 return false;
776 }
777 int32_t ret = helper->QueryRightRecordUids(rightRecordUids);
778 if (ret <= 0) {
779 USB_HILOGE(MODULE_USB_SERVICE, "query apps failed or empty: %{public}d", ret);
780 return USB_RIGHT_NOP;
781 }
782 size_t len = rightRecordUids.size();
783 deleteUsers = 0;
784 for (size_t i = 0; i < len; i++) {
785 int32_t uid = 0;
786 if (!StrToInt(rightRecordUids.at(i), uid)) {
787 USB_HILOGE(MODULE_USB_SERVICE, "convert failed: %{public}s", rightRecordUids.at(i).c_str());
788 continue;
789 }
790 ret = IsOsAccountExists(uid, isAccountExists);
791 if (ret != USB_RIGHT_OK) {
792 USB_HILOGE(MODULE_USB_SERVICE, "call IsOsAccountExists failed: %{public}d", ret);
793 continue;
794 }
795 if (!isAccountExists) {
796 ret = helper->DeleteUidRightRecord(uid);
797 USB_HILOGE(MODULE_USB_SERVICE, "detecte delete uid=%{public}d: %{public}d", uid, ret);
798 deleteUsers++;
799 }
800 USB_HILOGD(MODULE_USB_SERVICE, "uid exist, ignore: %{public}d", uid);
801 }
802 totalUsers = static_cast<int32_t>(rightRecordUids.size());
803 return USB_RIGHT_OK;
804 }
805
CleanUpRightUserStopped(int32_t uid)806 int32_t UsbRightManager::CleanUpRightUserStopped(int32_t uid)
807 {
808 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
809 if (helper == nullptr) {
810 USB_HILOGE(MODULE_USB_SERVICE, "CleanUpRightUserStopped %{public}d: helper is null", uid);
811 return false;
812 }
813
814 return helper->DeleteUidRightRecord(uid);
815 }
816
CleanUpRightTemporaryExpired(const std::string & deviceName)817 int32_t UsbRightManager::CleanUpRightTemporaryExpired(const std::string &deviceName)
818 {
819 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
820 if (helper == nullptr) {
821 USB_HILOGE(MODULE_USB_SERVICE, "helper is nullptr, false");
822 return false;
823 }
824 int32_t ret = helper->DeleteValidPeriodRightRecord(USB_RIGHT_VALID_PERIOD_MIN, deviceName);
825 if (ret != USB_RIGHT_OK) {
826 USB_HILOGE(MODULE_USB_SERVICE, "failed: delete temporary expiried record: dev=%{private}s", deviceName.c_str());
827 }
828 return ret;
829 }
830
CleanUpRightNormalExpired(int32_t uid)831 int32_t UsbRightManager::CleanUpRightNormalExpired(int32_t uid)
832 {
833 uint64_t nowTime = GetCurrentTimestamp();
834 std::shared_ptr<UsbRightDbHelper> helper = UsbRightDbHelper::GetInstance();
835 int32_t ret = helper->DeleteNormalExpiredRightRecord(uid, nowTime);
836 if (ret != USB_RIGHT_OK) {
837 USB_HILOGD(MODULE_USB_SERVICE, "failed: clean up expired record at %{public}" PRIu64 "", nowTime);
838 }
839 return ret;
840 }
841
TidyUpRight(uint32_t choose)842 int32_t UsbRightManager::TidyUpRight(uint32_t choose)
843 {
844 if (choose == TIGHT_UP_USB_RIGHT_RECORD_NONE) {
845 /* ignore */
846 return USB_RIGHT_NOP;
847 }
848 if ((choose | TIGHT_UP_USB_RIGHT_RECORD_ALL) != TIGHT_UP_USB_RIGHT_RECORD_ALL) {
849 USB_HILOGE(MODULE_USB_SERVICE, "choose invalid");
850 return UEC_SERVICE_INVALID_VALUE;
851 }
852 int32_t uid = USB_RIGHT_USERID_INVALID;
853 GetCurrentUserId(uid);
854 if (uid == USB_RIGHT_USERID_CONSOLE) {
855 USB_HILOGE(MODULE_USB_SERVICE, "console called, bypass");
856 return true;
857 }
858 int32_t ret = 0;
859 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_UNINSTALLED) != 0) {
860 int32_t totalUninstalledApps = 0;
861 int32_t deleteUninstalledApps = 0;
862 ret = CleanUpRightAppUninstalled(uid, totalUninstalledApps, deleteUninstalledApps);
863 USB_HILOGD(MODULE_USB_SERVICE, "delete app uninstalled record[%{public}d/%{public}d]: %{public}d",
864 deleteUninstalledApps, totalUninstalledApps, ret);
865 }
866 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_USER_DELETED) != 0) {
867 int32_t totalUsers = 0;
868 int32_t deleteUsers = 0;
869 ret = CleanUpRightUserDeleted(totalUsers, deleteUsers);
870 USB_HILOGD(MODULE_USB_SERVICE, "delete user deleted record[%{public}d/%{public}d]: %{public}d", deleteUsers,
871 totalUsers, ret);
872 }
873 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_EXPIRED) != 0) {
874 ret = CleanUpRightNormalExpired(uid);
875 USB_HILOGD(MODULE_USB_SERVICE, "delete expired record: %{public}d", ret);
876 }
877 if ((choose & TIGHT_UP_USB_RIGHT_RECORD_APP_REINSTALLED) != 0) {
878 uint32_t totalReinstalledApps = 0;
879 uint32_t deleteReinstalledApps = 0;
880 ret = CleanUpRightAppReinstalled(uid, totalReinstalledApps, deleteReinstalledApps);
881 USB_HILOGD(MODULE_USB_SERVICE, "delete app reinstalled record[%{public}u/%{public}u]: %{public}d",
882 deleteReinstalledApps, totalReinstalledApps, ret);
883 }
884 return ret;
885 }
886
IsAllDigits(const std::string & bundleName)887 bool UsbRightManager::IsAllDigits(const std::string &bundleName)
888 {
889 size_t len = bundleName.length();
890 for (size_t i = 0; i < len; i++) {
891 if (!isdigit(bundleName[i])) {
892 return false;
893 }
894 }
895 return true;
896 }
897 } // namespace USB
898 } // namespace OHOS
899