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