1 /*
2  * Copyright (c) 2024 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 #ifdef L2_STANDARD
17 #ifdef HUKS_ENABLE_UPGRADE_KEY_STORAGE_SECURE_LEVEL
18 #include "hks_upgrade.h"
19 #include "hks_log.h"
20 #include "hks_type.h"
21 #include "hks_osaccount_check.h"
22 
23 #include <atomic>
24 
25 #ifdef HAS_OS_ACCOUNT_PART
26 #include "os_account_manager.h"
27 #endif // HAS_OS_ACCOUNT_PART
28 
29 namespace {
30 static volatile std::atomic_bool g_isCeUpgradeSucc = false;
31 
HksIsOsAccountVerified(const int32_t userId)32 static bool HksIsOsAccountVerified(const int32_t userId)
33 {
34     bool isVerified = false;
35 #ifdef HAS_OS_ACCOUNT_PART
36     HKS_LOG_D("enter HksIsOsAccountVerified");
37     OHOS::AccountSA::OsAccountManager::IsOsAccountVerified(userId, isVerified);
38     if (!isVerified) {
39         HKS_LOG_E("os account verify failed, userid is : %" LOG_PUBLIC "d", userId);
40     }
41 #else
42     HKS_LOG_E("os account not support");
43 #endif
44     return isVerified;
45 }
46 }
47 
HksTransferFileIfNeed(const uint32_t storageLevel,const int32_t storeUserId)48 extern "C" void HksTransferFileIfNeed(const uint32_t storageLevel, const int32_t storeUserId)
49 {
50     bool flag = false;
51     bool equal = std::atomic_compare_exchange_strong(&g_isCeUpgradeSucc, &flag, true);
52     if (!equal) {
53         return;
54     }
55     HKS_LOG_I("never HksTransferFileIfNeed before, first time upgrade ce!");
56     if (storageLevel == HKS_AUTH_STORAGE_LEVEL_CE && HksIsOsAccountVerified(storeUserId)) {
57         OHOS::Security::Hks::HksUpgradeOnUserUnlock(storeUserId);
58     }
59 }
60 
61 #endif // HUKS_ENABLE_UPGRADE_KEY_STORAGE_SECURE_LEVEL
62 #endif // L2_STANDARD