Merge branch 'master' of gitee.com:openharmony/filemanagement_storage_service into master

Signed-off-by: ZhongLufu <zhonglufu@huawei.com>
This commit is contained in:
ZhongLufu 2024-09-25 03:27:20 +00:00 committed by Gitee
commit 3e6db13c2a
158 changed files with 7771 additions and 870 deletions

View File

@ -53,6 +53,7 @@
"huks",
"init",
"ipc",
"libmtp",
"media_library",
"napi",
"ntfs-3g",
@ -61,6 +62,7 @@
"samgr",
"screenlock_mgr",
"selinux_adapter",
"tee_client",
"os_account",
"openssl",
"user_auth_framework",

View File

@ -52,6 +52,11 @@ ohos_shared_library("storage_manager_acl") {
configs = [ ":private_config" ]
public_configs = [ ":public_config" ]
cflags = [
"-D_FORTIFY_SOURCE=2",
"-fstack-protector-strong",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",

View File

@ -56,6 +56,11 @@ ohos_shared_library("storage_manager_sa_proxy") {
configs = [ ":private_config" ]
public_configs = [ ":public_config" ]
cflags = [
"-D_FORTIFY_SOURCE=2",
"-fstack-protector-strong",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",

View File

@ -74,6 +74,14 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret) = 0;
virtual int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
return 0;
}
virtual int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) = 0;

View File

@ -64,6 +64,7 @@ namespace StorageManager {
CREATE_USER_KEYS,
DELETE_USER_KEYS,
UPDATE_USER_AUTH,
UPDATE_USER_AUTH_RECOVER_KEY,
ACTIVE_USER_KEY,
INACTIVE_USER_KEY,
LOCK_USER_SCREEN,

View File

@ -66,6 +66,11 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret) override;
int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText) override;
int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) override;

View File

@ -41,6 +41,11 @@ ohos_shared_library("storagestatistics") {
"${storage_service_path}/services/common/include",
]
cflags = [
"-D_FORTIFY_SOURCE=2",
"-fstack-protector-strong",
]
sources = [
"${storage_service_path}/services/storage_manager/kits_impl/src/storage_manager_connect.cpp",
"${storage_service_path}/services/storage_manager/kits_impl/src/storage_statistics_n_exporter.cpp",
@ -84,6 +89,11 @@ ohos_shared_library("volumemanager") {
"${storage_service_path}/services/common/include",
]
cflags = [
"-D_FORTIFY_SOURCE=2",
"-fstack-protector-strong",
]
sources = [
"${storage_service_path}/services/storage_manager/kits_impl/src/storage_manager_connect.cpp",
"${storage_service_path}/services/storage_manager/kits_impl/src/volumemanager_n_exporter.cpp",

View File

@ -54,6 +54,7 @@ enum ErrNo {
E_DIFF_UID_GID,
E_PARAMS_INVAL,
E_ACTIVE_EL2_FAILED,
E_CLEAR_KEY_FAILED,
};
enum JsErrCode {

View File

@ -125,6 +125,7 @@ ohos_executable("storage_daemon") {
"hisysevent:libhisysevent",
"init:libbegetutil",
"ipc:ipc_single",
"os_account:os_account_innerkits",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
]
@ -155,6 +156,16 @@ ohos_executable("storage_daemon") {
external_deps += [ "selinux_adapter:librestorecon" ]
}
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
if (support_open_source_libmtp) {
defines += [ "SUPPORT_OPEN_SOURCE_LIBMTP" ]
external_deps += [ "libmtp:libmtp" ]
}
ldflags = [
"-Wl,-z,max-page-size=4096",
"-Wl,-z,separate-code",
@ -253,6 +264,11 @@ ohos_shared_library("storage_common_utils") {
"LOG_DOMAIN = 0xD004301",
]
cflags = [
"-D_FORTIFY_SOURCE=2",
"-fstack-protector-strong",
]
sources = [
"./utils/disk_utils.cpp",
"./utils/file_utils.cpp",
@ -337,6 +353,7 @@ group("storage_daemon_unit_test") {
"crypto/test/fscrypt_key_v1_ext_test:fscrypt_key_v1_ext_test",
"crypto/test/iam_client_test:iam_client_test",
"crypto/test/iam_client_user_auth_framework_test:iam_client_user_auth_framework_test",
"crypto/test/key_backup_test:key_backup_test",
"crypto/test/key_manager_test:key_manager_test",
"file_sharing/test:file_sharing_test",
"ipc/test:storage_daemon_ipc_test",

View File

@ -44,6 +44,11 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret);
static int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText);
static int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret);

View File

@ -271,6 +271,26 @@ int32_t StorageDaemonClient::UpdateUserAuth(uint32_t userId, uint64_t secureUid,
return client->UpdateUserAuth(userId, secureUid, token, oldSecret, newSecret);
}
int32_t StorageDaemonClient::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
if (!CheckServiceStatus(STORAGE_SERVICE_FLAG)) {
LOGE("service check failed");
return -EAGAIN;
}
sptr<IStorageDaemon> client = GetStorageDaemonProxy();
if (client == nullptr) {
LOGE("get storage daemon service failed");
return -EAGAIN;
}
return client->UpdateUseAuthWithRecoveryKey(authToken, newSecret, secureUid, userId, plainText);
}
int32_t StorageDaemonClient::ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret)

View File

@ -37,6 +37,7 @@ ohos_unittest("storage_daemon_clt_test") {
"${storage_daemon_path}/include",
"${storage_daemon_path}/client/include",
"${storage_daemon_path}/utils/test/common",
"${storage_manager_path}/include",
"${storage_service_common_path}/include",
]
@ -44,6 +45,7 @@ ohos_unittest("storage_daemon_clt_test") {
"${storage_daemon_path}/client/storage_daemon_client.cpp",
"${storage_daemon_path}/client/test/storage_daemon_client_test.cpp",
"${storage_daemon_path}/utils/test/common/help_utils.cpp",
"${storage_manager_path}/mock/storage_daemon_proxy_mock.cpp",
]
deps = [
@ -58,7 +60,6 @@ ohos_unittest("storage_daemon_clt_test") {
"init:libbegetutil",
"ipc:ipc_single",
"samgr:samgr_proxy",
"storage_service:storage_manager_sa_proxy",
]
}

View File

@ -15,6 +15,8 @@
#include <gtest/gtest.h>
#include "directory_ex.h"
#include "storage_daemon_client.h"
#include "ipc/istorage_daemon.h"
#include "storage_service_errno.h"
@ -134,8 +136,15 @@ HWTEST_F(StorageDaemonClientTest, Storage_Service_StorageDaemonClientTest_MountD
std::string relativePath = "account";
std::string networkId = "testnetworkid";
std::string deviceId = "testdevid";
std::string path = "/mnt/data/" + std::to_string(userId) + "/hmdfs/";
OHOS::ForceRemoveDirectory(path);
int32_t ret = storageDaemonClient_->MountDfsDocs(userId, relativePath, networkId, deviceId);
EXPECT_EQ(ret, E_MOUNT);
EXPECT_EQ(ret, E_OK);
OHOS::ForceCreateDirectory(path);
ret = storageDaemonClient_->MountDfsDocs(userId, relativePath, networkId, deviceId);
EXPECT_EQ(ret, E_OK);
OHOS::ForceRemoveDirectory(path);
GTEST_LOG_(INFO) << "Storage_Service_StorageDaemonClientTest_MountDfsDocs_001 end";
}
@ -156,7 +165,7 @@ HWTEST_F(StorageDaemonClientTest, Storage_Service_StorageDaemonClientTest_UMount
std::string networkId = "testnetworkid";
std::string deviceId = "testdevid";
int32_t ret = storageDaemonClient_->UMountDfsDocs(userId, relativePath, networkId, deviceId);
EXPECT_EQ(ret, E_UMOUNT);
EXPECT_EQ(ret, E_OK);
GTEST_LOG_(INFO) << "Storage_Service_StorageDaemonClientTest_UMountDfsDocs_001 end";
}
@ -299,10 +308,10 @@ HWTEST_F(StorageDaemonClientTest, Storage_Service_StorageDaemonClientTest_Genera
std::string keyId = "keyId";
int32_t ret = storageDaemonClient_->GenerateAppkey(userid, appUid, keyId);
EXPECT_EQ(ret, -ENOENT);
EXPECT_EQ(ret, E_OK);
ret = storageDaemonClient_->DeleteAppkey(userid, keyId);
EXPECT_EQ(ret, -ENOENT);
EXPECT_EQ(ret, E_OK);
GTEST_LOG_(INFO) << "Storage_Service_StorageDaemonClientTest_GenerateAppkey_001 end";
}

View File

@ -51,8 +51,10 @@ ohos_static_library("libsdcrypto") {
"src/huks_master.cpp",
"src/iam_client.cpp",
"src/key_backup.cpp",
"src/key_crypto_utils.cpp",
"src/key_manager.cpp",
"src/openssl_crypto.cpp",
"src/recover_manager.cpp",
]
defines = [
@ -78,6 +80,7 @@ ohos_static_library("libsdcrypto") {
"init:libbegetutil",
"ipc:ipc_single",
"openssl:libcrypto_shared",
"os_account:os_account_innerkits",
"samgr:samgr_proxy",
]
@ -91,6 +94,16 @@ ohos_static_library("libsdcrypto") {
external_deps += [ "user_auth_framework:userauth_client" ]
}
if (enable_tee_client) {
defines += [ "RECOVER_KEY_TEE_ENVIRONMENT" ]
external_deps += [ "tee_client:libteec" ]
}
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
subsystem_name = "filemanagement"
part_name = "storage_service"
}

View File

@ -17,8 +17,10 @@
#include <fcntl.h>
#include <fstream>
#include <cstdio>
#include <string>
#include <unistd.h>
#include <dirent.h>
#include "directory_ex.h"
#include "fbex.h"
@ -37,6 +39,8 @@ namespace {
const std::string PATH_LATEST_BACKUP = "/latest_bak";
const std::string PATH_KEY_VERSION = "/version_";
const std::string PATH_KEY_TEMP = "/temp";
const std::string PATH_NEED_RESTORE_SUFFIX = "/latest/need_restore";
const std::string PATH_USER_EL1_DIR = "/data/service/el1/public/storage_daemon/sd/el1/";
#ifndef F2FS_IOCTL_MAGIC
#define F2FS_IOCTL_MAGIC 0xf5
@ -81,7 +85,7 @@ static void DoTempStore(const KeyContext &sourceCtx, KeyContext &targetCtx)
bool BaseKey::InitKey(bool needGenerateKey)
{
LOGD("enter");
LOGI("enter");
if (keyInfo_.version == FSCRYPT_INVALID || keyInfo_.version > KeyCtrlGetFscryptVersion(MNT_DATA.c_str())) {
LOGE("invalid version %{public}u", keyInfo_.version);
return false;
@ -109,7 +113,7 @@ bool BaseKey::SaveKeyBlob(const KeyBlob &blob, const std::string &path)
LOGE("blob is empty");
return false;
}
LOGD("enter %{public}s, size=%{public}d", path.c_str(), blob.size);
LOGI("enter %{public}s, size=%{public}d", path.c_str(), blob.size);
return WriteFileSync(path.c_str(), blob.data.get(), blob.size);
}
@ -123,7 +127,7 @@ bool BaseKey::GenerateAndSaveKeyBlob(KeyBlob &blob, const std::string &path, con
bool BaseKey::LoadKeyBlob(KeyBlob &blob, const std::string &path, const uint32_t size = 0)
{
LOGD("enter %{public}s, size=%{public}d", path.c_str(), size);
LOGI("enter %{public}s, size=%{public}d", path.c_str(), size);
std::ifstream file(path, std::ios::binary);
if (file.fail()) {
LOGE("open %{public}s failed, errno %{public}d", path.c_str(), errno);
@ -164,7 +168,7 @@ int BaseKey::GetCandidateVersion() const
}
}
}
LOGD("candidate key version is %{public}d", candidate);
LOGI("candidate key version is %{public}d", candidate);
return candidate;
}
@ -193,7 +197,7 @@ bool BaseKey::StoreKey(const UserAuth &auth, bool needGenerateShield)
bool BaseKey::StoreKey(const UserAuth &auth)
#endif
{
LOGD("enter");
LOGI("enter");
auto pathTemp = dir_ + PATH_KEY_TEMP;
#ifdef USER_CRYPTO_MIGRATE_KEY
if (DoStoreKey(auth, needGenerateShield)) {
@ -354,7 +358,7 @@ bool BaseKey::LoadAndSaveShield(const UserAuth &auth, const std::string &pathShi
// update the latest and do cleanups.
bool BaseKey::UpdateKey(const std::string &keypath)
{
LOGD("enter");
LOGI("enter");
auto candidate = keypath.empty() ? GetCandidateDir() : keypath;
if (candidate.empty()) {
LOGE("no candidate dir");
@ -371,7 +375,7 @@ bool BaseKey::UpdateKey(const std::string &keypath)
pathLatestBak.c_str()) != 0) {
LOGE("backup the latest fail errno:%{public}d", errno);
}
LOGD("backup the latest success");
LOGI("backup the latest success");
}
// rename {candidate} to latest
@ -390,7 +394,7 @@ bool BaseKey::UpdateKey(const std::string &keypath)
SyncKeyDir();
return false;
}
LOGD("rename candidate %{public}s to latest success", candidate.c_str());
LOGI("rename candidate %{public}s to latest success", candidate.c_str());
// cleanup backup and other versions
std::vector<std::string> files;
@ -473,7 +477,7 @@ bool BaseKey::EncryptEceSece(const UserAuth &auth, const uint32_t keyType, KeyCo
bool BaseKey::RestoreKey(const UserAuth &auth)
{
LOGD("enter");
LOGI("enter");
auto candidate = GetCandidateDir();
if (candidate.empty()) {
// no candidate dir, just restore from the latest
@ -512,7 +516,7 @@ bool BaseKey::RestoreKey(const UserAuth &auth)
bool BaseKey::DoRestoreKeyEx(const UserAuth &auth, const std::string &keyPath)
{
LOGD("enter restore key ex");
LOGI("enter restore key ex");
if (!DoRestoreKey(auth, keyPath)) {
LOGE("First restore failed !");
return false;
@ -556,7 +560,7 @@ bool BaseKey::DoRestoreKeyEx(const UserAuth &auth, const std::string &keyPath)
bool BaseKey::DoRestoreKeyOld(const UserAuth &auth, const std::string &path)
{
LOGD("enter, path = %{public}s", path.c_str());
LOGI("enter, path = %{public}s", path.c_str());
const std::string NEED_UPDATE_PATH = dir_ + PATH_LATEST + SUFFIX_NEED_UPDATE;
if (!auth.secret.IsEmpty() && FileExists(NEED_UPDATE_PATH)) {
keyEncryptType_ = KeyEncryptType::KEY_CRYPT_OPENSSL;
@ -664,6 +668,12 @@ bool BaseKey::DoRestoreKeyCeEceSece(const UserAuth &auth, const std::string &pat
bool BaseKey::DoRestoreKey(const UserAuth &auth, const std::string &path)
{
auto ver = KeyCtrlLoadVersion(dir_.c_str());
if (ver == FSCRYPT_INVALID || ver != keyInfo_.version) {
LOGE("RestoreKey fail. bad version loaded %{public}u not expected %{public}u", ver, keyInfo_.version);
return false;
}
std::string encryptType;
LoadStringFromFile(path + SUFFIX_NEED_UPDATE, encryptType);
LOGI("encrypt type : %{public}s, keyInfo empty: %{public}u", encryptType.c_str(), keyInfo_.key.IsEmpty());
@ -691,6 +701,10 @@ bool BaseKey::DoUpdateRestore(const UserAuth &auth, const std::string &keyPath)
LOGE("Restore old failed !");
return false;
}
if (std::filesystem::exists(dir_ + PATH_NEED_RESTORE_SUFFIX) && !auth.token.IsEmpty()) {
LOGE("Double 2 single, skip huks -> huks-openssl !");
return true;
}
uint64_t secureUid = { 0 };
if (!IamClient::GetInstance().GetSecureUid(GetIdFromDir(), secureUid)) {
LOGE("Get secure uid form iam failed, use default value.");
@ -758,17 +772,42 @@ bool BaseKey::Decrypt(const UserAuth &auth)
bool BaseKey::ClearKey(const std::string &mnt)
{
LOGD("enter, dir_ = %{public}s", dir_.c_str());
InactiveKey(USER_DESTROY, mnt);
LOGI("enter, dir_ = %{public}s", dir_.c_str());
bool ret = InactiveKey(USER_DESTROY, mnt);
if (!ret) {
LOGE("InactiveKey failed.");
}
keyInfo_.key.Clear();
WipingActionDir(dir_);
std::string backupDir;
KeyBackup::GetInstance().GetBackupDir(dir_, backupDir);
WipingActionDir(backupDir);
KeyBackup::GetInstance().RemoveNode(backupDir);
OHOS::ForceRemoveDirectory(backupDir);
return OHOS::ForceRemoveDirectory(dir_);
// use F2FS_IOC_SEC_TRIM_FILE
bool needClearFlag = true;
#ifdef USER_CRYPTO_MIGRATE_KEY
std::string elNeedRestorePath = PATH_USER_EL1_DIR + std::to_string(GetIdFromDir()) + PATH_NEED_RESTORE_SUFFIX;
if (std::filesystem::exists(elNeedRestorePath)) {
needClearFlag = false;
LOGI("needRestore flag exist, do not remove secret.");
}
#endif
if (needClearFlag) {
LOGI("do clear key.");
if (!IsDir(dir_)) {
LOGE("dir not exist, do not need to remove dir");
return ret;
}
WipingActionDir(dir_);
std::string backupDir;
KeyBackup::GetInstance().GetBackupDir(dir_, backupDir);
WipingActionDir(backupDir);
KeyBackup::GetInstance().RemoveNode(backupDir);
LOGI("force remove backupDir, %{public}s.", backupDir.c_str());
OHOS::ForceRemoveDirectory(backupDir);
LOGI("force remove dir_, %{public}s.", dir_.c_str());
bool removeRet = OHOS::ForceRemoveDirectory(dir_);
if (!removeRet) {
LOGE("ForceRemoveDirectory failed.");
return removeRet;
}
// use F2FS_IOC_SEC_TRIM_FILE
}
return ret;
}
void BaseKey::WipingActionDir(std::string &path)
@ -777,7 +816,12 @@ void BaseKey::WipingActionDir(std::string &path)
LOGI("WipingActionDir path.c_str() is %{public}s", path.c_str());
OpenSubFile(path.c_str(), fileList);
for (const auto &it: fileList) {
int fd = open(it.c_str(), O_WRONLY | O_CLOEXEC);
FILE *f = fopen(it.c_str(), "w");
if (f == nullptr) {
LOGE("open %{public}s failed, errno %{public}u", it.c_str(), errno);
return;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open %{public}s failed, errno %{public}u", it.c_str(), errno);
return;
@ -805,13 +849,18 @@ void BaseKey::WipingActionDir(std::string &path)
LOGE("F2FS_IOC_SET_PIN_FILE ioctl is %{public}u", ret);
}
LOGI("WipingActionDir success");
close(fd);
(void)fclose(f);
}
}
void BaseKey::SyncKeyDir() const
{
int fd = open(dir_.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
DIR *dir = opendir(dir_.c_str());
if (dir == nullptr) {
LOGE("open %{public}s failed, errno %{public}u", dir_.c_str(), errno);
return;
}
int fd = dirfd(dir);
if (fd < 0) {
LOGE("open %{public}s failed, errno %{public}d", dir_.c_str(), errno);
sync();
@ -823,7 +872,7 @@ void BaseKey::SyncKeyDir() const
sync();
}
LOGI("syncfs end");
(void)close(fd);
(void)closedir(dir);
}
bool BaseKey::UpgradeKeys()
@ -856,10 +905,17 @@ bool BaseKey::GetOriginKey(KeyBlob &originKey)
return true;
}
void BaseKey::SetOriginKey(KeyBlob &originKey)
{
LOGI("enter");
keyInfo_.key = std::move(originKey);
return;
}
bool BaseKey::EncryptKeyBlob(const UserAuth &auth, const std::string &keyPath, KeyBlob &planKey,
KeyBlob &encryptedKey)
{
LOGD("enter");
LOGI("enter");
KeyContext keyCtx;
if (!MkDirRecurse(keyPath, S_IRWXU)) {
LOGE("MkDirRecurse failed!");
@ -885,14 +941,14 @@ bool BaseKey::EncryptKeyBlob(const UserAuth &auth, const std::string &keyPath, K
CombKeyBlob(keyCtx.rndEnc, keyCtx.nonce, encryptedKey);
ClearKeyContext(keyCtx);
LOGD("finish");
LOGI("finish");
return true;
}
bool BaseKey::DecryptKeyBlob(const UserAuth &auth, const std::string &keyPath, KeyBlob &planKey,
KeyBlob &decryptedKey)
{
LOGD("enter");
LOGI("enter");
KeyContext keyCtx;
auto candidate = GetCandidateDir();
std::string path = candidate.empty() ? keyPath : candidate;
@ -920,7 +976,7 @@ bool BaseKey::DecryptKeyBlob(const UserAuth &auth, const std::string &keyPath, K
decryptedKey = std::move(planKeyInfo.key);
planKeyInfo.key.Clear();
ClearKeyContext(keyCtx);
LOGD("finish");
LOGI("finish");
return true;
}
@ -928,7 +984,7 @@ bool BaseKey::RenameKeyPath(const std::string &keyPath)
{
// rename keypath/temp/ to keypath/version_xx/
auto candidate = GetNextCandidateDir();
LOGD("rename %{public}s to %{public}s", keyPath.c_str(), candidate.c_str());
LOGI("rename %{public}s to %{public}s", keyPath.c_str(), candidate.c_str());
if (rename(keyPath.c_str(), candidate.c_str()) != 0) {
LOGE("rename %{public}s to %{public}s failed!", keyPath.c_str(), candidate.c_str());
return false;
@ -968,7 +1024,7 @@ void BaseKey::ClearMemoryKeyCtx()
void BaseKey::ClearKeyContext(KeyContext &keyCtx)
{
LOGD("enter clear");
LOGI("enter clear");
keyCtx.aad.Clear();
keyCtx.nonce.Clear();
keyCtx.shield.Clear();

View File

@ -28,7 +28,7 @@ const std::string CLEAR_TASK_NAME = "clear_ece_sece_key";
DelayHandler::DelayHandler(uint32_t userId) : userId_(userId) {}
DelayHandler::~DelayHandler()
{
LOGD("DelayHandler Destructor.");
LOGI("DelayHandler Destructor.");
std::unique_lock<std::mutex> lock(eventMutex_);
if ((eventHandler_ != nullptr) && (eventHandler_->GetEventRunner() != nullptr)) {
eventHandler_->RemoveAllEvents();

View File

@ -19,6 +19,8 @@
#include <cstdio>
#include <fcntl.h>
#include <securec.h>
#include <cstdio>
#include <dirent.h>
#include <string>
#include <sys/ioctl.h>
#include <unistd.h>
@ -143,7 +145,17 @@ int FBEX::InstallEL5KeyToKernel(uint32_t userIdSingle, uint32_t userIdDouble, ui
bool &isSupport, bool &isNeedEncryptClassE)
{
LOGI("InstallEL5KeyToKernel enter, userId: %{public}d, flag: %{public}u", userIdDouble, flag);
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
isSupport = false;
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -159,7 +171,7 @@ int FBEX::InstallEL5KeyToKernel(uint32_t userIdSingle, uint32_t userIdDouble, ui
if (static_cast<uint32_t>(fbeRet) == FILE_ENCRY_ERROR_UECE_ALREADY_CREATED) {
LOGE("class uece has already create, ret: 0x%{public}x, errno: %{public}d", fbeRet, errno);
isNeedEncryptClassE = false;
close(fd);
(void)fclose(f);
return 0;
}
int ret = 0;
@ -167,7 +179,7 @@ int FBEX::InstallEL5KeyToKernel(uint32_t userIdSingle, uint32_t userIdDouble, ui
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", fbeRet, errno);
ret = -errno;
}
close(fd);
(void)fclose(f);
LOGI("InstallEL5KeyToKernel success");
return ret;
}
@ -180,7 +192,12 @@ int FBEX::InstallKeyToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint32
return -EINVAL;
}
int fd = open(FBEX_CMD_PATH, O_RDWR);
FILE *f = fopen(FBEX_CMD_PATH, "r+");
if (f == nullptr) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
@ -190,22 +207,23 @@ int FBEX::InstallKeyToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint32
auto err = memcpy_s(ops.iv, sizeof(ops.iv), iv, size);
if (err != EOK) {
LOGE("memcpy failed %{public}d", err);
close(fd);
(void)fclose(f);
return 0;
}
int ret = ioctl(fd, FBEX_IOC_ADD_IV, &ops);
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
close(fd);
(void)fclose(f);
return ret;
}
close(fd);
(void)fclose(f);
auto errops = memcpy_s(iv, size, ops.iv, sizeof(ops.iv));
if (errops != EOK) {
LOGE("memcpy failed %{public}d", errops);
return 0;
}
(void)memset_s(&ops.iv, sizeof(ops.iv), 0, sizeof(ops.iv));
LOGI("InstallKeyToKernel success");
return ret;
}
@ -218,7 +236,12 @@ int FBEX::UninstallOrLockUserKeyToKernel(uint32_t userId, uint32_t type, uint8_t
return -EINVAL;
}
int fd = open(FBEX_CMD_PATH, O_RDWR);
FILE *f = fopen(FBEX_CMD_PATH, "r+");
if (f == nullptr) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
@ -228,14 +251,14 @@ int FBEX::UninstallOrLockUserKeyToKernel(uint32_t userId, uint32_t type, uint8_t
auto err = memcpy_s(ops.iv, sizeof(ops.iv), iv, size);
if (err != EOK) {
LOGE("memcpy failed %{public}d", err);
close(fd);
(void)fclose(f);
return 0;
}
int ret = ioctl(fd, destroy ? FBEX_IOC_DEL_IV : FBEX_IOC_USER_LOGOUT, &ops);
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
}
close(fd);
(void)fclose(f);
LOGI("success");
return ret;
}
@ -243,7 +266,16 @@ int FBEX::UninstallOrLockUserKeyToKernel(uint32_t userId, uint32_t type, uint8_t
int FBEX::DeleteClassEPinCode(uint32_t userIdSingle, uint32_t userIdDouble)
{
LOGI("enter, userId: %{public}d", userIdDouble);
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -259,7 +291,7 @@ int FBEX::DeleteClassEPinCode(uint32_t userIdSingle, uint32_t userIdDouble)
LOGE("ioctl fbex_cmd failed, fbeRet: 0x%{public}x, errno: %{public}d", fbeRet, errno);
ret = -errno;
}
close(fd);
(void)fclose(f);
LOGI("success");
return ret;
}
@ -267,7 +299,17 @@ int FBEX::DeleteClassEPinCode(uint32_t userIdSingle, uint32_t userIdDouble)
int FBEX::ChangePinCodeClassE(uint32_t userIdSingle, uint32_t userIdDouble, bool &isFbeSupport)
{
LOGI("enter, userId: %{public}d", userIdDouble);
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
isFbeSupport = false;
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -283,7 +325,7 @@ int FBEX::ChangePinCodeClassE(uint32_t userIdSingle, uint32_t userIdDouble, bool
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
ret = -errno;
}
close(fd);
(void)fclose(f);
LOGI("change pincode classE finish.");
return ret;
}
@ -293,7 +335,12 @@ int FBEX::LockScreenToKernel(uint32_t userId)
{
LOGI("enter, userId: %{public}d", userId);
int fd = open(FBEX_CMD_PATH, O_RDWR);
FILE *f = fopen(FBEX_CMD_PATH, "r+");
if (f == nullptr) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
@ -305,7 +352,7 @@ int FBEX::LockScreenToKernel(uint32_t userId)
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
}
close(fd);
(void)fclose(f);
LOGI("success");
return ret;
}
@ -314,7 +361,17 @@ int FBEX::GenerateAppkey(UserIdToFbeStr &userIdToFbe, uint32_t hashId, std::uniq
uint32_t size)
{
LOGI("GenerateAppkey enter");
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
appKey.reset(nullptr);
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -330,7 +387,7 @@ int FBEX::GenerateAppkey(UserIdToFbeStr &userIdToFbe, uint32_t hashId, std::uniq
auto fbeRet = ioctl(fd, FBEX_ADD_APPKEY2, &ops);
if (fbeRet != 0) {
LOGE("ioctl fbex_cmd failed, fbeRet: 0x%{public}x, errno: %{public}d", fbeRet, errno);
close(fd);
(void)fclose(f);
return -errno;
}
@ -339,7 +396,7 @@ int FBEX::GenerateAppkey(UserIdToFbeStr &userIdToFbe, uint32_t hashId, std::uniq
LOGE("memcpy failed %{public}d", err);
return 0;
}
close(fd);
(void)fclose(f);
LOGI("success");
return 0;
}
@ -347,9 +404,19 @@ int FBEX::GenerateAppkey(UserIdToFbeStr &userIdToFbe, uint32_t hashId, std::uniq
// for el5
int FBEX::LockUece(uint32_t userIdSingle, uint32_t userIdDouble, bool &isFbeSupport)
{
LOGD("enter, userId: %{public}d", userIdDouble);
LOGI("enter, userId: %{public}d", userIdDouble);
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
isFbeSupport = false;
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -364,8 +431,8 @@ int FBEX::LockUece(uint32_t userIdSingle, uint32_t userIdDouble, bool &isFbeSupp
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
}
close(fd);
LOGD("success");
(void)fclose(f);
LOGI("success");
return ret;
}
@ -377,7 +444,12 @@ int FBEX::UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint
return -EINVAL;
}
int fd = open(FBEX_CMD_PATH, O_RDWR);
FILE *f = fopen(FBEX_CMD_PATH, "r+");
if (f == nullptr) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
@ -388,16 +460,16 @@ int FBEX::UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint
auto err = memcpy_s(ops.iv, sizeof(ops.iv), iv, size);
if (err != EOK) {
LOGE("memcpy failed %{public}d", err);
close(fd);
(void)fclose(f);
return 0;
}
int ret = ioctl(fd, FBEX_IOC_UNLOCK_SCREEN, &ops);
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
close(fd);
(void)fclose(f);
return ret;
}
close(fd);
(void)fclose(f);
auto errops = memcpy_s(iv, size, ops.iv, sizeof(ops.iv));
if (errops != EOK) {
@ -408,19 +480,26 @@ int FBEX::UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint
return ret;
}
int FBEX::ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uint8_t *eBuffer,
int FBEX::ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, std::unique_ptr<uint8_t[]> &eBuffer,
uint32_t length, bool &isFbeSupport)
{
LOGI("enter, userId: %{public}d, status: %{public}u", userIdToFbe.userIds[DOUBLE_ID_INDEX], status);
if (!CheckReadBuffValid(eBuffer, length, status)) {
if (!CheckReadBuffValid(eBuffer.get(), length, status)) {
LOGE("read e secret param invalid");
return -EINVAL;
}
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
isFbeSupport = false;
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
isFbeSupport = false;
return 0;
}
@ -429,34 +508,43 @@ int FBEX::ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uint
}
uint32_t bufferSize = AES_256_HASH_RANDOM_SIZE + GCM_MAC_BYTES + GCM_NONCE_BYTES;
FbeOptsE ops{ .userIdDouble = userIdToFbe.userIds[DOUBLE_ID_INDEX],
.userIdSingle = userIdToFbe.userIds[SINGLE_ID_INDEX],
.status = status, .length = bufferSize };
auto err = memcpy_s(ops.eBuffer, sizeof(ops.eBuffer), eBuffer, length);
.userIdSingle = userIdToFbe.userIds[SINGLE_ID_INDEX], .status = status, .length = bufferSize };
auto err = memcpy_s(ops.eBuffer, sizeof(ops.eBuffer), eBuffer.get(), length);
if (err != EOK) {
LOGE("memcpy failed %{public}d", err);
close(fd);
(void)fclose(f);
return 0;
}
auto ret = ioctl(fd, FBEX_READ_CLASS_E, &ops);
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
close(fd);
(void)fclose(f);
return -errno;
}
close(fd);
(void)fclose(f);
if (ops.length == 0) {
(void)memset_s(eBuffer.get(), sizeof(eBuffer.get()), 0, sizeof(eBuffer.get()));
eBuffer.reset(nullptr);
LOGE("ops length is 0, skip");
return 0;
}
UnlockSendSecret(status, bufferSize, length, eBuffer.get(), ops.eBuffer);
LOGI("ReadESecretToKernel success");
return 0;
}
int FBEX::UnlockSendSecret(uint32_t status, uint32_t bufferSize, uint32_t length, uint8_t *eBuffer, uint8_t *opseBuffer)
{
if (status == UNLOCK_STATUS) {
bufferSize = AES_256_HASH_RANDOM_SIZE + GCM_MAC_BYTES + GCM_NONCE_BYTES;
} else {
bufferSize = AES_256_HASH_RANDOM_SIZE;
}
auto errBuffer = memcpy_s(eBuffer, length, ops.eBuffer, bufferSize);
auto errBuffer = memcpy_s(eBuffer, length, opseBuffer, bufferSize);
if (errBuffer != EOK) {
LOGE("memcpy failed %{public}d", errBuffer);
return 0;
}
LOGI("ReadESecretToKernel success");
return 0;
}
@ -468,7 +556,16 @@ int FBEX::WriteESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uin
return -EINVAL;
}
int fd = open(FBEX_UECE_PATH, O_RDWR);
FILE *f = fopen(FBEX_UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
return 0;
}
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("fbex_uece does not exist, fbe not support this command!");
@ -484,16 +581,16 @@ int FBEX::WriteESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uin
auto err = memcpy_s(ops.eBuffer, sizeof(ops.eBuffer), eBuffer, length);
if (err != EOK) {
LOGE("memcpy failed %{public}d", err);
close(fd);
(void)fclose(f);
return 0;
}
auto ret = ioctl(fd, FBEX_WRITE_CLASS_E, &ops);
if (ret != 0) {
LOGE("ioctl fbex_cmd failed, ret: 0x%{public}x, errno: %{public}d", ret, errno);
close(fd);
(void)fclose(f);
return -errno;
}
close(fd);
(void)fclose(f);
LOGI("success");
return 0;
}
@ -507,7 +604,12 @@ bool FBEX::IsMspReady()
int FBEX::GetStatus()
{
int fd = open(FBEX_CMD_PATH, O_RDWR);
FILE *f = fopen(FBEX_CMD_PATH, "r+");
if (f == nullptr) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("open fbex_cmd failed, errno: %{public}d", errno);
return -errno;
@ -515,7 +617,7 @@ int FBEX::GetStatus()
FbeOpts ops;
int ret = ioctl(fd, FBEX_IOC_STATUS_REPORT, &ops);
close(fd);
(void)fclose(f);
return ret;
}
} // namespace StorageDaemon

View File

@ -18,6 +18,8 @@
#include <fcntl.h>
#include <openssl/sha.h>
#include <unistd.h>
#include <cstdio>
#include <dirent.h>
#include "file_ex.h"
#include "key_backup.h"
@ -85,7 +87,7 @@ bool FscryptKeyV1::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string
LOGE("GenerateAppKeyDesc failed");
return false;
}
if (!InstallKeyForAppKeyToKeyring(reinterpret_cast<uint32_t *>(appKey.data.get()))) {
if (!InstallKeyForAppKeyToKeyring(appKey)) {
LOGE("InstallKeyForAppKeyToKeyring failed");
return false;
}
@ -96,14 +98,13 @@ bool FscryptKeyV1::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string
return true;
}
bool FscryptKeyV1::InstallKeyForAppKeyToKeyring(uint32_t *appKey)
bool FscryptKeyV1::InstallKeyForAppKeyToKeyring(KeyBlob &appKey)
{
LOGI("InstallKeyForAppKeyToKeyring enter");
EncryptAsdpKey fskey;
const size_t keySize = sizeof(*appKey);
fskey.size = keySize;
fskey.size = appKey.size;
fskey.version = 0;
auto err = memcpy_s(fskey.raw, FSCRYPT_MAX_KEY_SIZE, appKey, keySize);
auto err = memcpy_s(fskey.raw, FSCRYPT_MAX_KEY_SIZE, appKey.data.get(), appKey.size);
if (err != EOK) {
LOGE("memcpy failed ret %{public}d", err);
return false;
@ -140,7 +141,7 @@ bool FscryptKeyV1::DeleteAppkey(const std::string KeyId)
LOGE("FscryptKeyV1 Delete Appkey2 failed");
return false;
}
LOGD("success");
LOGI("success");
return true;
}
@ -232,11 +233,11 @@ bool FscryptKeyV1::DecryptClassE(const UserAuth &auth, bool &isSupport, uint32_t
LOGI("enter");
KeyBlob eSecretFBE(AES_256_HASH_RANDOM_SIZE + GCM_MAC_BYTES + GCM_NONCE_BYTES);
bool isFbeSupport = true;
if (!fscryptV1Ext.ReadClassE(status, eSecretFBE.data.get(), eSecretFBE.size, isFbeSupport)) {
if (!fscryptV1Ext.ReadClassE(status, eSecretFBE.data, eSecretFBE.size, isFbeSupport)) {
LOGE("fscryptV1Ext ReadClassE failed");
return false;
}
if (auth.token.IsEmpty() && auth.secret.IsEmpty()) {
if ((auth.token.IsEmpty() && auth.secret.IsEmpty()) || eSecretFBE.IsEmpty()) {
LOGE("Token and secret is invalid, do not deal.");
eSecretFBE.Clear();
return true;
@ -269,7 +270,7 @@ bool FscryptKeyV1::EncryptClassE(const UserAuth &auth, bool &isSupport, uint32_t
LOGI("enter");
KeyBlob eSecretFBE(AES_256_HASH_RANDOM_SIZE);
bool isFbeSupport = true;
if (!fscryptV1Ext.ReadClassE(status, eSecretFBE.data.get(), eSecretFBE.size, isFbeSupport)) {
if (!fscryptV1Ext.ReadClassE(status, eSecretFBE.data, eSecretFBE.size, isFbeSupport)) {
LOGE("fscryptV1Ext ReadClassE failed");
return false;
}
@ -382,10 +383,10 @@ bool FscryptKeyV1::InstallEceSeceKeyToKeyring(uint32_t sdpClass)
bool FscryptKeyV1::InactiveKey(uint32_t flag, const std::string &mnt)
{
(void)mnt;
LOGD("enter");
LOGI("enter");
bool ret = true;
if (!UninstallKeyToKeyring()) {
if (!keyInfo_.keyDesc.IsEmpty() && !UninstallKeyToKeyring()) {
LOGE("UninstallKeyToKeyring failed");
ret = false;
}
@ -394,13 +395,17 @@ bool FscryptKeyV1::InactiveKey(uint32_t flag, const std::string &mnt)
ret = false;
}
DropCachesIfNeed();
LOGD("finish");
LOGI("finish");
return ret;
}
void FscryptKeyV1::DropCachesIfNeed()
{
int fd = open(MNT_DATA.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
DIR *dir = opendir(MNT_DATA.c_str());
if (dir == nullptr) {
sync();
}
int fd = dirfd(dir);
if (fd < 0 || syncfs(fd)) {
sync();
}
@ -408,7 +413,7 @@ void FscryptKeyV1::DropCachesIfNeed()
if (!SaveStringToFile("/proc/sys/vm/drop_caches", "2")) {
LOGE("Failed to drop cache during key eviction");
}
(void)close(fd);
(void)closedir(dir);
LOGI("drop cache success");
}
@ -416,7 +421,7 @@ bool FscryptKeyV1::LockUserScreen(uint32_t flag, uint32_t sdpClass, const std::s
{
uint32_t elType;
(void)mnt;
LOGD("enter");
LOGI("enter");
bool ret = true;
if (!fscryptV1Ext.LockUserScreenExt(flag, elType)) {
LOGE("fscryptV1Ext InactiveKeyExt failed");
@ -428,19 +433,19 @@ bool FscryptKeyV1::LockUserScreen(uint32_t flag, uint32_t sdpClass, const std::s
ret = false;
}
}
LOGD("finish");
LOGI("finish");
return ret;
}
bool FscryptKeyV1::LockUece(bool &isFbeSupport)
{
LOGD("enter");
LOGI("enter");
bool ret = true;
if (!fscryptV1Ext.LockUeceExt(isFbeSupport)) {
LOGE("fscryptV1Ext InactiveKeyExt failed");
ret = false;
}
LOGD("finish");
LOGI("finish");
return ret;
}

View File

@ -70,7 +70,7 @@ bool FscryptKeyV1Ext::ActiveKeyExt(uint32_t flag, uint8_t *iv, uint32_t size, ui
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t user = GetMappedUserId(userId_, type_);
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, user);
// iv buffer returns derived keys
@ -89,7 +89,7 @@ bool FscryptKeyV1Ext::UnlockUserScreenExt(uint32_t flag, uint8_t *iv, uint32_t s
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t user = GetMappedUserId(userId_, type_);
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, user);
if (FBEX::UnlockScreenToKernel(user, type_, iv, size)) {
@ -104,7 +104,7 @@ bool FscryptKeyV1Ext::GenerateAppkey(uint32_t user, uint32_t hashId, std::unique
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
LOGI("map userId %{public}u to %{public}u", userId_, user);
// 0--single id, 1--double id
UserIdToFbeStr userIdToFbe = { .userIds = { userId_, GetMappedUserId(userId_, type_) }, .size = USER_ID_SIZE };
@ -120,7 +120,7 @@ bool FscryptKeyV1Ext::AddClassE(bool &isNeedEncryptClassE, bool &isSupport, uint
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t userIdDouble = GetMappedUserId(userId_, type_);
LOGI("map userId %{public}u to %{public}u", userId_, userIdDouble);
if (FBEX::InstallEL5KeyToKernel(userId_, userIdDouble, status, isSupport, isNeedEncryptClassE)) {
@ -135,7 +135,7 @@ bool FscryptKeyV1Ext::DeleteClassEPinCode(uint32_t userId)
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t userIdDouble = GetMappedUserId(userId_, type_);
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, userIdDouble);
if (FBEX::DeleteClassEPinCode(userId_, userIdDouble)) {
@ -159,12 +159,13 @@ bool FscryptKeyV1Ext::ChangePinCodeClassE(uint32_t userId, bool &isFbeSupport)
return true;
}
bool FscryptKeyV1Ext::ReadClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length, bool &isFbeSupport)
bool FscryptKeyV1Ext::ReadClassE(uint32_t status, std::unique_ptr<uint8_t[]> &classEBuffer, uint32_t length,
bool &isFbeSupport)
{
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
// 0--single id, 1--double id
UserIdToFbeStr userIdToFbe = { .userIds = { userId_, GetMappedUserId(userId_, type_) }, .size = USER_ID_SIZE };
LOGI("type_: %{public}u, userId %{public}u to %{public}u", type_, userId_, userIdToFbe.userIds[DOUBLE_ID_INDEX]);
@ -180,7 +181,7 @@ bool FscryptKeyV1Ext::WriteClassE(uint32_t status, uint8_t *classEBuffer, uint32
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
// 0--single id, 1--double id
UserIdToFbeStr userIdToFbe = { .userIds = { userId_, GetMappedUserId(userId_, type_) }, .size = USER_ID_SIZE };
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u",
@ -198,10 +199,10 @@ bool FscryptKeyV1Ext::InactiveKeyExt(uint32_t flag)
return true;
}
LOGD("enter");
LOGI("enter");
bool destroy = !!flag;
if ((type_ != TYPE_EL2) && !destroy) {
LOGD("not el2, no need to inactive");
LOGI("not el2, no need to inactive");
return true;
}
uint8_t buf[FBEX_IV_SIZE] = {0};
@ -225,9 +226,9 @@ bool FscryptKeyV1Ext::LockUserScreenExt(uint32_t flag, uint32_t &elType)
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t user = GetMappedUserId(userId_, type_);
LOGD("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, user);
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, user);
if (FBEX::LockScreenToKernel(user)) {
LOGE("LockScreenToKernel failed, userId %{public}d", user);
return false;
@ -242,9 +243,9 @@ bool FscryptKeyV1Ext::LockUeceExt(bool &isFbeSupport)
if (!FBEX::IsFBEXSupported()) {
return true;
}
LOGD("enter");
LOGI("enter");
uint32_t userIdDouble = GetMappedUserId(userId_, type_);
LOGD("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, userIdDouble);
LOGI("type_ is %{public}u, map userId %{public}u to %{public}u", type_, userId_, userIdDouble);
if (FBEX::LockUece(userId_, userIdDouble, isFbeSupport)) {
LOGE("LockUeceExt failed, userId");
return false;

View File

@ -23,7 +23,7 @@ namespace StorageDaemon {
#ifdef SUPPORT_FSCRYPT_V2
bool FscryptKeyV2::ActiveKey(uint32_t flag, const std::string &mnt)
{
LOGD("enter");
LOGI("enter");
if (keyInfo_.key.IsEmpty()) {
LOGE("rawkey is null");
return false;
@ -52,20 +52,25 @@ bool FscryptKeyV2::ActiveKey(uint32_t flag, const std::string &mnt)
LOGE("memcpy_s failed ret %{public}d", ret);
return false;
}
(void)memset_s(&arg, sizeof(arg), 0, sizeof(arg));
LOGD("success. key_id len:%{public}d, data(hex):%{private}s", keyInfo_.keyId.size,
LOGI("success. key_id len:%{public}d, data(hex):%{private}s", keyInfo_.keyId.size,
keyInfo_.keyId.ToString().c_str());
if (!SaveKeyBlob(keyInfo_.keyId, dir_ + PATH_KEYID)) {
return false;
}
keyInfo_.key.Clear();
LOGD("success");
LOGI("success");
return true;
}
bool FscryptKeyV2::InactiveKey(uint32_t flag, const std::string &mnt)
{
LOGD("enter");
LOGI("enter");
if (keyInfo_.keyId.size == 0) {
LOGE("keyId size is 0");
return true;
}
if (keyInfo_.keyId.size != FSCRYPT_KEY_IDENTIFIER_SIZE) {
LOGE("keyId is invalid, %{public}u", keyInfo_.keyId.size);
return false;
@ -90,7 +95,7 @@ bool FscryptKeyV2::InactiveKey(uint32_t flag, const std::string &mnt)
LOGE("Some files using this key are still in-use");
}
LOGD("success");
LOGI("success");
keyInfo_.keyId.Clear();
return true;
}

View File

@ -21,30 +21,30 @@
#include <openssl/sha.h>
#include "hks_param.h"
#include "key_crypto_utils.h"
#include "storage_service_log.h"
namespace OHOS {
namespace StorageDaemon {
HuksMaster::HuksMaster()
{
LOGD("enter");
LOGI("enter");
HdiCreate();
HdiModuleInit();
LOGD("finish");
LOGI("finish");
}
HuksMaster::~HuksMaster()
{
LOGD("enter");
LOGI("enter");
HdiModuleDestroy();
HdiDestroy();
LOGD("finish");
LOGI("finish");
}
bool HuksMaster::HdiCreate()
{
LOGD("enter");
LOGI("enter");
if (hdiHandle_ != nullptr || halDevice_ != nullptr) {
return true;
}
@ -70,13 +70,13 @@ bool HuksMaster::HdiCreate()
hdiHandle_ = nullptr;
return false;
}
LOGD("success");
LOGI("success");
return true;
}
void HuksMaster::HdiDestroy()
{
LOGD("enter");
LOGI("enter");
if (hdiHandle_ == nullptr) {
LOGI("hdiHandle_ is nullptr, already destroyed");
return;
@ -90,12 +90,12 @@ void HuksMaster::HdiDestroy()
dlclose(hdiHandle_);
hdiHandle_ = nullptr;
halDevice_ = nullptr;
LOGD("finish");
LOGI("finish");
}
int HuksMaster::HdiModuleInit()
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -114,7 +114,7 @@ int HuksMaster::HdiModuleInit()
int HuksMaster::HdiModuleDestroy()
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -134,7 +134,7 @@ int HuksMaster::HdiModuleDestroy()
int HuksMaster::HdiGenerateKey(const HksBlob &keyAlias, const HksParamSet *paramSetIn,
HksBlob &keyOut)
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -156,7 +156,7 @@ int HuksMaster::HdiGenerateKey(const HksBlob &keyAlias, const HksParamSet *param
int HuksMaster::HdiAccessInit(const HksBlob &key, const HksParamSet *paramSet,
HksBlob &handle, HksBlob &token)
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -176,7 +176,7 @@ int HuksMaster::HdiAccessInit(const HksBlob &key, const HksParamSet *paramSet,
int HuksMaster::HdiAccessFinish(const HksBlob &handle, const HksParamSet *paramSet,
const HksBlob &inData, HksBlob &outData)
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -195,7 +195,7 @@ int HuksMaster::HdiAccessFinish(const HksBlob &handle, const HksParamSet *paramS
int HuksMaster::HdiAccessUpgradeKey(const HksBlob &oldKey, const HksParamSet *paramSet, struct HksBlob &newKey)
{
LOGD("enter");
LOGI("enter");
if (halDevice_ == nullptr) {
LOGE("halDevice_ is nullptr");
return HKS_ERROR_NULL_POINTER;
@ -214,7 +214,7 @@ int HuksMaster::HdiAccessUpgradeKey(const HksBlob &oldKey, const HksParamSet *pa
KeyBlob HuksMaster::GenerateRandomKey(uint32_t keyLen)
{
LOGD("enter, size %{public}d", keyLen);
LOGI("enter, size %{public}d", keyLen);
KeyBlob out(keyLen);
if (out.IsEmpty()) {
return out;
@ -265,7 +265,7 @@ static const HksParam g_generateKeyParam[] = {
bool HuksMaster::GenerateKey(const UserAuth &auth, KeyBlob &keyOut)
{
LOGD("enter");
LOGI("enter");
HksParamSet *paramSet = nullptr;
int ret = HKS_SUCCESS;
@ -559,6 +559,10 @@ bool HuksMaster::HuksHalTripleStage(HksParamSet *paramSet1, const HksParamSet *p
ret = HdiAccessFinish(hksHandle, paramSet2, hksIn, hksOut);
if (ret != HKS_SUCCESS) {
if (ret == HKS_ERROR_KEY_AUTH_TIME_OUT) {
StorageService::KeyCryptoUtils::ForceLockUserScreen();
LOGE("HdiAccessFinish failed because authToken timeout, force lock user screen.");
}
LOGE("HdiAccessFinish failed ret %{public}d", ret);
return false;
}
@ -604,7 +608,7 @@ bool HuksMaster::EncryptKeyEx(const UserAuth &auth, const KeyBlob &rnd, KeyConte
bool HuksMaster::EncryptKey(KeyContext &ctx, const UserAuth &auth, const KeyInfo &key, bool isNeedNewNonce)
{
LOGD("enter");
LOGI("enter");
if (ctx.shield.IsEmpty()) {
LOGE("bad shield input, size %{public}d", ctx.shield.size);
return false;
@ -631,13 +635,13 @@ bool HuksMaster::EncryptKey(KeyContext &ctx, const UserAuth &auth, const KeyInfo
LOGE("HuksHalTripleStage failed");
}
HksFreeParamSet(&paramSet2);
LOGD("finish");
LOGI("finish");
return ret;
}
bool HuksMaster::DecryptKey(KeyContext &ctx, const UserAuth &auth, KeyInfo &key, bool isNeedNewNonce)
{
LOGD("enter");
LOGI("enter");
if (ctx.shield.IsEmpty()) {
LOGE("bad shield input, size %{public}d", ctx.shield.size);
return false;

View File

@ -20,13 +20,12 @@ namespace OHOS {
namespace StorageDaemon {
IamClient::IamClient()
{
LOGD("enter");
secureUidStatus_ = FAILED;
LOGI("enter");
}
IamClient::~IamClient()
{
LOGD("enter");
LOGI("enter");
}
#ifdef USER_AUTH_FRAMEWORK

View File

@ -389,7 +389,7 @@ int32_t KeyBackup::CopySameFilesToTempDir(const std::string &backupDir, std::str
int32_t KeyBackup::CreateTempDirForMixFiles(const std::string &backupDir, std::string &tempDir)
{
int32_t pos = backupDir.rfind("/");
auto pos = backupDir.rfind("/");
std::string parentDir = backupDir.substr(0, pos);
tempDir = parentDir + "/temp";
@ -442,16 +442,21 @@ void KeyBackup::CheckAndFixFiles(const std::string &from, const std::string &to)
void KeyBackup::FsyncDirectory(const std::string &dirName)
{
LOGI("sync directory dirName %s", dirName.c_str());
UniqueFd fd(open(dirName.c_str(), O_RDONLY | O_CLOEXEC));
std::string realPath;
if (!GetRealPath(dirName, realPath)) {
return;
}
UniqueFd fd(open(realPath.c_str(), O_RDONLY | O_CLOEXEC));
if (fd < 0) {
LOGE("failed to open %s", dirName.c_str());
LOGE("failed to open %s", realPath.c_str());
return;
}
if (fsync(fd) == -1) {
if (errno == EROFS || errno == EINVAL) {
LOGE("file system does not support sync, dirName: %s", dirName.c_str());
LOGE("file system does not support sync, dirName: %s", realPath.c_str());
} else {
LOGE("sync failed: %s", dirName.c_str());
LOGE("sync failed: %s", realPath.c_str());
}
}
return;
@ -479,9 +484,13 @@ int32_t KeyBackup::MkdirParent(const std::string &pathName, mode_t mode)
void KeyBackup::CleanFile(const std::string &path)
{
LOGI("clean file path %s", path.c_str());
int fd = open(path.c_str(), O_WRONLY);
std::string realPath;
if (!GetRealPath(path, realPath)) {
return;
}
int fd = open(realPath.c_str(), O_WRONLY);
if (fd < 0) {
LOGE("open %s failed", path.c_str());
LOGE("open %s failed", realPath.c_str());
return;
}
@ -490,10 +499,10 @@ void KeyBackup::CleanFile(const std::string &path)
lseek(fd, 0, SEEK_SET);
if (write(fd, data.c_str(), data.size()) < 0) {
LOGE("failed to write file %s", path.c_str());
LOGE("failed to write file %s", realPath.c_str());
}
if (fsync(fd) == -1) {
LOGE("failed to sync file %s", path.c_str());
LOGE("failed to sync file %s", realPath.c_str());
}
close(fd);
return;

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "key_crypto_utils.h"
#include "os_account_manager.h"
#ifdef ENABLE_SCREENLOCK_MANAGER
#include "screenlock_manager.h"
#endif
#include "storage_service_log.h"
namespace OHOS {
namespace StorageService {
void KeyCryptoUtils::ForceLockUserScreen()
{
LOGI("KeyCryptoUtils::ForceLockUserScreen");
#ifdef ENABLE_SCREENLOCK_MANAGER
std::vector<int32_t> ids;
int32_t ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
if (ret != ERR_OK || ids.empty()) {
LOGE("Query active userid failed, ret = %{public}u", ret);
return;
}
ret = AccountSA::OsAccountManager::SetOsAccountIsVerified(ids[0], false);
if (ret != ERR_OK) {
LOGE("Set os account IsVerified status failed, ret = %{public}u", ret);
return;
}
int reasonFlag = static_cast<int>(ScreenLock::StrongAuthReasonFlags::ACTIVE_REQUEST);
ret = ScreenLock::ScreenLockManager::GetInstance()->RequestStrongAuth(reasonFlag, ids[0]);
if (ret != ScreenLock::E_SCREENLOCK_OK) {
LOGE("Request strong auth by screen lock manager failed.");
return;
}
ret = ScreenLock::ScreenLockManager::GetInstance()->Lock(ids[0]);
if (ret != ScreenLock::E_SCREENLOCK_OK) {
LOGE("Lock user screen by screen lock manager failed.");
return;
}
LOGI("Force lock user screen and request strong auth success for userId = %{public}d.", ids[0]);
#endif
}
}
}

View File

@ -18,6 +18,7 @@
#include <fcntl.h>
#include <filesystem>
#include <string>
#include <cstdio>
#include "base_key.h"
#include "directory_ex.h"
@ -28,6 +29,7 @@
#include "libfscrypt/fscrypt_control.h"
#include "libfscrypt/key_control.h"
#include "parameter.h"
#include "recover_manager.h"
#include "storage_service_constant.h"
#include "storage_service_errno.h"
#include "storage_service_log.h"
@ -101,7 +103,7 @@ int KeyManager::RestoreDeviceKey(const std::string &dir)
{
LOGI("enter");
if (globalEl1Key_ != nullptr) {
LOGD("device key has existed");
LOGI("device key has existed");
return 0;
}
@ -144,7 +146,7 @@ int KeyManager::InitGlobalDeviceKey(void)
std::lock_guard<std::mutex> lock(keyMutex_);
if (hasGlobalDeviceKey_ || globalEl1Key_ != nullptr) {
LOGD("glabal device el1 have existed");
LOGI("glabal device el1 have existed");
return 0;
}
@ -170,7 +172,7 @@ int KeyManager::GenerateAndInstallUserKey(uint32_t userId, const std::string &di
{
LOGI("enter");
if (HasElkey(userId, type)) {
LOGD("The user %{public}u el %{public}u have existed", userId, type);
LOGI("The user %{public}u el %{public}u have existed", userId, type);
return 0;
}
auto elKey = GetBaseKey(dir);
@ -250,7 +252,7 @@ int KeyManager::RestoreUserKey(uint32_t userId, const std::string &dir, const Us
{
LOGI("enter");
if (HasElkey(userId, type)) {
LOGD("The user %{public}u el %{public}u have existed", userId, type);
LOGI("The user %{public}u el %{public}u have existed", userId, type);
return 0;
}
@ -296,31 +298,31 @@ bool KeyManager::HasElkey(uint32_t userId, KeyType type)
switch (type) {
case EL1_KEY:
if (userEl1Key_.find(userId) != userEl1Key_.end()) {
LOGD("user el1 key has existed");
LOGI("user el1 key has existed");
return true;
}
break;
case EL2_KEY:
if (userEl2Key_.find(userId) != userEl2Key_.end()) {
LOGD("user el2 key has existed");
LOGI("user el2 key has existed");
return true;
}
break;
case EL3_KEY:
if (userEl3Key_.find(userId) != userEl3Key_.end()) {
LOGD("user el3 key has existed");
LOGI("user el3 key has existed");
return true;
}
break;
case EL4_KEY:
if (userEl4Key_.find(userId) != userEl4Key_.end()) {
LOGD("user el4 key has existed");
LOGI("user el4 key has existed");
return true;
}
break;
case EL5_KEY:
if (userEl5Key_.find(userId) != userEl5Key_.end()) {
LOGD("user el5 key has existed");
LOGI("user el5 key has existed");
return true;
}
break;
@ -488,7 +490,7 @@ int KeyManager::GenerateUserKeys(unsigned int user, uint32_t flags)
std::lock_guard<std::mutex> lock(keyMutex_);
if ((!IsDir(USER_EL1_DIR)) || (!IsDir(USER_EL2_DIR)) || (!IsDir(USER_EL3_DIR)) ||
(!IsDir(USER_EL4_DIR)) || (!IsDir(USER_EL5_DIR))) {
LOGD("El storage dir is not existed");
LOGI("El storage dir is not existed");
return -ENOENT;
}
int ret = GenerateElxAndInstallUserKey(user);
@ -583,56 +585,67 @@ int KeyManager::GenerateUserKeyByType(unsigned int user, KeyType type,
}
int KeyManager::DoDeleteUserCeEceSeceKeys(unsigned int user,
const std::string USER_DIR,
const std::string userDir,
std::map<unsigned int, std::shared_ptr<BaseKey>> &userElKey_)
{
LOGI("enter, userDir is %{public}s", userDir.c_str());
int ret = 0;
auto it = userElKey_.find(user);
if (it != userElKey_.end()) {
auto elKey = it->second;
elKey->ClearKey();
if (!elKey->ClearKey()) {
LOGE("clear key failed");
ret = -E_CLEAR_KEY_FAILED;
}
userElKey_.erase(user);
saveLockScreenStatus.erase(user);
} else {
std::string elPath = USER_DIR + "/" + std::to_string(user);
std::string elPath = userDir + "/" + std::to_string(user);
std::shared_ptr<BaseKey> elKey = GetBaseKey(elPath);
if (elKey == nullptr) {
LOGE("Malloc el1 Basekey memory failed");
return -ENOMEM;
}
if (!elKey->ClearKey()) {
LOGE("Delete el1 key failed");
ret = -EFAULT;
LOGE("clear key failed");
ret = -E_CLEAR_KEY_FAILED;
}
}
LOGI("end, ret is %{public}d", ret);
return ret;
}
int KeyManager::DoDeleteUserKeys(unsigned int user)
{
int ret = 0;
ret = DoDeleteUserCeEceSeceKeys(user, USER_EL1_DIR, userEl1Key_);
if (ret != 0) {
int errCode = 0;
int deleteRet = DoDeleteUserCeEceSeceKeys(user, USER_EL1_DIR, userEl1Key_);
if (deleteRet != 0) {
LOGE("Delete el1 key failed");
errCode = deleteRet;
}
ret = DoDeleteUserCeEceSeceKeys(user, USER_EL2_DIR, userEl2Key_);
if (ret != 0) {
deleteRet = DoDeleteUserCeEceSeceKeys(user, USER_EL2_DIR, userEl2Key_);
if (deleteRet != 0) {
LOGE("Delete el2 key failed");
errCode = deleteRet;
}
ret = DoDeleteUserCeEceSeceKeys(user, USER_EL3_DIR, userEl3Key_);
if (ret != 0) {
deleteRet = DoDeleteUserCeEceSeceKeys(user, USER_EL3_DIR, userEl3Key_);
if (deleteRet != 0) {
LOGE("Delete el3 key failed");
errCode = deleteRet;
}
ret = DoDeleteUserCeEceSeceKeys(user, USER_EL4_DIR, userEl4Key_);
if (ret != 0) {
deleteRet = DoDeleteUserCeEceSeceKeys(user, USER_EL4_DIR, userEl4Key_);
if (deleteRet != 0) {
LOGE("Delete el4 key failed");
errCode = deleteRet;
}
ret = DoDeleteUserCeEceSeceKeys(user, USER_EL5_DIR, userEl5Key_);
if (ret != 0) {
LOGE("Delete el5 key failed");
ret = -EFAULT;
if (IsUeceSupportWithErrno() != ENOENT) {
deleteRet = DoDeleteUserCeEceSeceKeys(user, USER_EL5_DIR, userEl5Key_);
if (deleteRet != 0) {
LOGE("Delete el5 key failed");
errCode = deleteRet;
}
}
return ret;
return errCode;
}
int KeyManager::DeleteUserKeys(unsigned int user)
@ -644,7 +657,7 @@ int KeyManager::DeleteUserKeys(unsigned int user)
std::lock_guard<std::mutex> lock(keyMutex_);
int ret = DoDeleteUserKeys(user);
LOGI("delete user key end");
LOGI("delete user key end, ret is %{public}d", ret);
auto userTask = userLockScreenTask_.find(user);
if (userTask != userLockScreenTask_.end()) {
@ -702,6 +715,58 @@ int KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &userTo
return ret;
}
int32_t KeyManager::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret, uint64_t secureUid, uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
LOGI("enter UpdateUseAuthWithRecoveryKey start, user:%{public}d", userId);
// 解密 C类 B类 A类
std::string el2Path = USER_EL2_DIR + "/" + std::to_string(userId);
std::string el3Path = USER_EL3_DIR + "/" + std::to_string(userId);
std::string el4Path = USER_EL4_DIR + "/" + std::to_string(userId);
std::vector<std::string> elKeyDirs = {el2Path, el3Path, el4Path};
uint32_t i = 0;
for (const auto &elxKeyDir : elKeyDirs) {
if (!IsDir(elxKeyDir)) {
LOGE("Have not found type %{publicc}s", elxKeyDir.c_str());
return -EOPNOTSUPP;
}
std::shared_ptr<BaseKey> elxKey = GetBaseKey(elxKeyDir);
if (elxKey == nullptr) {
LOGE("load elx key failed , key path is %{public}s", elxKeyDir.c_str());
return -EOPNOTSUPP;
}
if (plainText.size() < elKeyDirs.size()) {
LOGE("plain text size error");
return -EFAULT;
}
KeyBlob originKey(plainText[i]);
elxKey->SetOriginKey(originKey);
i++;
if (elxKey->StoreKey({authToken, newSecret, secureUid}) == false) {
LOGE("Store key error");
return -EFAULT;
}
}
if (IsUeceSupport()) {
std::shared_ptr<BaseKey> el5Key = GetBaseKey(USER_EL5_DIR + "/" + std::to_string(userId));
bool tempUeceSupport = true;
UserAuth userAuth = {.token = authToken, .secret = newSecret, .secureUid = secureUid};
if (!el5Key->EncryptClassE(userAuth, tempUeceSupport, userId, USER_ADD_AUTH)) {
el5Key->ClearKey();
LOGE("user %{public}u Encrypt E fail", userId);
return -EFAULT;
}
if (!el5Key->LockUece(tempUeceSupport)) {
LOGE("lock user %{public}u key failed !", userId);
}
}
return E_OK;
}
int KeyManager::UpdateESecret(unsigned int user, struct UserTokenSecret &tokenSecret)
{
LOGI("UpdateESecret enter");
@ -1033,7 +1098,6 @@ bool KeyManager::GetUserDelayHandler(uint32_t userId, std::shared_ptr<DelayHandl
LOGI("enter");
auto iterTask = userLockScreenTask_.find(userId);
if (iterTask == userLockScreenTask_.end()) {
std::shared_ptr<DelayHandler> lockScreenTask = std::make_shared<DelayHandler>(userId);
userLockScreenTask_[userId] = std::make_shared<DelayHandler>(userId);
}
delayHandler = userLockScreenTask_[userId];
@ -1074,7 +1138,8 @@ int KeyManager::ActiveElXUserKey(unsigned int user,
return -EFAULT;
}
std::string NEED_UPDATE_PATH = keyDir + PATH_LATEST + SUFFIX_NEED_UPDATE;
if (!FileExists(NEED_UPDATE_PATH) && (elKey->StoreKey(auth) == false)) {
std::string NEED_RESTORE_PATH = keyDir + PATH_LATEST + SUFFIX_NEED_RESTORE;
if (!FileExists(NEED_RESTORE_PATH) && !FileExists(NEED_UPDATE_PATH) && (elKey->StoreKey(auth) == false)) {
LOGE("Store el failed");
return -EFAULT;
}
@ -1180,17 +1245,24 @@ int KeyManager::GetLockScreenStatus(uint32_t user, bool &lockScreenStatus)
int KeyManager::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string &keyId)
{
std::lock_guard<std::mutex> lock(keyMutex_);
if (!IsUserCeDecrypt(userId)) {
LOGE("user ce does not decrypt, skip");
if (!IsUeceSupport()) {
LOGI("Not support uece !");
return -ENOTSUP;
}
if (userEl4Key_.find(userId) == userEl4Key_.end()) {
LOGE("userEl4Key_ has not existed");
if (!IsUserCeDecrypt(userId)) {
LOGE("user ce does not decrypt, skip");
return -ENOENT;
}
GetUserElKey(userId, EL4_KEY);
}
auto el4Key = userEl4Key_[userId];
if (el4Key == nullptr) {
LOGE("el4Key_ is nullptr");
return -ENOENT;
}
auto el2Key = GetUserElKey(userId, EL2_KEY);
if (el2Key == nullptr) {
LOGE("userEl2Key_ has not existed");
return -ENOENT;
}
if (!el2Key->GenerateAppkey(userId, hashId, keyId)) {
if (el4Key->GenerateAppkey(userId, hashId, keyId) == false) {
LOGE("Failed to generate Appkey2");
return -EFAULT;
}
@ -1200,16 +1272,20 @@ int KeyManager::GenerateAppkey(uint32_t userId, uint32_t hashId, std::string &ke
int KeyManager::DeleteAppkey(uint32_t userId, const std::string keyId)
{
std::lock_guard<std::mutex> lock(keyMutex_);
if (!IsUserCeDecrypt(userId)) {
LOGE("user ce does not decrypt, skip");
if (userEl4Key_.find(userId) == userEl4Key_.end()) {
LOGE("userEl4Key_ has not existed");
if (!IsUserCeDecrypt(userId)) {
LOGE("user ce does not decrypt, skip");
return -ENOENT;
}
GetUserElKey(userId, EL4_KEY);
}
auto el4Key = userEl4Key_[userId];
if (el4Key == nullptr) {
LOGE("el4Key_ is nullptr");
return -ENOENT;
}
auto el2Key = GetUserElKey(userId, EL2_KEY);
if (el2Key == nullptr) {
LOGE("userEl2Key_ has not existed");
return -ENOENT;
}
if (!el2Key->DeleteAppkey(keyId)) {
if (el4Key->DeleteAppkey(keyId) == false) {
LOGE("Failed to delete Appkey2");
return -EFAULT;
}
@ -1220,13 +1296,51 @@ int KeyManager::CreateRecoverKey(uint32_t userId, uint32_t userType, const std::
const std::vector<uint8_t> &secret)
{
LOGI("enter");
LOGI("userId %{public}u, userType%{public}u", userId, userType);
std::string globalUserEl1Path = USER_EL1_DIR + "/" + std::to_string(GLOBAL_USER_ID);
std::string el1Path = USER_EL1_DIR + "/" + std::to_string(userId);
std::string el2Path = USER_EL2_DIR + "/" + std::to_string(userId);
std::string el3Path = USER_EL3_DIR + "/" + std::to_string(userId);
std::string el4Path = USER_EL4_DIR + "/" + std::to_string(userId);
std::vector<std::string> elKeyDirs = { DEVICE_EL1_DIR, globalUserEl1Path, el1Path, el2Path, el3Path, el4Path };
std::vector<KeyBlob> originKeys;
for (const auto &elxKeyDir : elKeyDirs) {
if (!IsDir(elxKeyDir)) {
LOGE("Have not found type %{public}s el", elxKeyDir.c_str());
return -ENOENT;
}
std::shared_ptr<BaseKey> elxKey = GetBaseKey(elxKeyDir);
if (elxKey == nullptr) {
LOGE("load elx key failed , key path is %{public}s", elxKeyDir.c_str());
return -EOPNOTSUPP;
}
UserAuth auth = { token, secret };
if ((elxKey->RestoreKey(auth) == false) && (elxKey->RestoreKey(NULL_KEY_AUTH) == false)) {
LOGE("Restore el failed");
return -EFAULT;
}
KeyBlob originKey;
if (!elxKey->GetOriginKey(originKey)) {
LOGE("get origin key failed !");
return -ENOENT;
}
originKeys.push_back(std::move(originKey));
}
if (RecoveryManager::GetInstance().CreateRecoverKey(userId, userType, token, secret, originKeys) != E_OK) {
LOGE("Create recovery key failed !");
return -ENOENT;
}
originKeys.clear();
return E_OK;
}
int KeyManager::SetRecoverKey(const std::vector<uint8_t> &key)
{
LOGI("enter");
std::vector<KeyBlob> originIvs;
if (RecoveryManager::GetInstance().SetRecoverKey(key) != E_OK) {
LOGE("Set recovery key filed !");
return -ENOENT;
}
return E_OK;
}
@ -1252,9 +1366,23 @@ int KeyManager::UnlockUserAppKeys(uint32_t userId, bool needGetAllAppKey)
}
LOGI("get User Appkeys success.");
}
int ret = GenerateAndLoadAppKeyInfo(userId, keyInfo);
if (ret != E_OK) {
LOGE("UnlockUserAppKeys fail.");
return ret;
}
#endif
LOGI("UnlockUserAppKeys success!");
return E_OK;
}
#ifdef EL5_FILEKEY_MANAGER
int KeyManager::GenerateAndLoadAppKeyInfo(uint32_t userId, const std::vector<std::pair<int, std::string>> &keyInfo)
{
std::vector<std::pair<std::string, bool>> loadInfos;
if (keyInfo.size() == 0) {
LOGE("The keyInfo is empty!");
return 0;
return E_OK;
}
if (userEl5Key_.find(userId) == userEl5Key_.end()) {
LOGE("userEl5Key_ has not existed");
@ -1266,10 +1394,12 @@ int KeyManager::UnlockUserAppKeys(uint32_t userId, bool needGetAllAppKey)
if (elKey->GenerateAppkey(userId, keyInfoAppUid.first, keyId) == false) {
LOGE("Failed to Generate Appkey2!");
loadInfos.push_back(std::make_pair(keyInfoAppUid.second, false));
continue;
}
if (keyInfoAppUid.second != keyId) {
LOGE("The keyId check fails!");
loadInfos.push_back(std::make_pair(keyInfoAppUid.second, false));
continue;
}
loadInfos.push_back(std::make_pair(keyInfoAppUid.second, true));
}
@ -1277,10 +1407,9 @@ int KeyManager::UnlockUserAppKeys(uint32_t userId, bool needGetAllAppKey)
LOGE("Change User Appkeys LoadInfo fail.");
return -EFAULT;
}
#endif
LOGI("UnlockUserAppKeys success!");
return E_OK;
}
#endif
int KeyManager::InActiveUserKey(unsigned int user)
{
@ -1330,7 +1459,7 @@ int KeyManager::InactiveUserElKey(unsigned int user, std::map<unsigned int, std:
int KeyManager::LockUserScreen(uint32_t user)
{
LOGD("start");
LOGI("start");
std::lock_guard<std::mutex> lock(keyMutex_);
if (!IsUserCeDecrypt(user)) {
LOGE("user ce does not decrypt, skip");
@ -1358,7 +1487,8 @@ int KeyManager::LockUserScreen(uint32_t user)
}
auto el5Key = GetUserElKey(user, EL5_KEY);
if (el5Key != nullptr && saveESecretStatus[user] && !el5Key->LockUece(saveESecretStatus[user])) {
saveESecretStatus[user] = true;
if (el5Key != nullptr && !el5Key->LockUece(saveESecretStatus[user])) {
LOGE("lock user %{public}u el5 key failed !", user);
}
auto el4Key = GetUserElKey(user, EL4_KEY);
@ -1429,14 +1559,14 @@ int KeyManager::getEceSeceKeyPath(unsigned int user, KeyType type, std::string &
{
if (type == EL3_KEY) {
if (userEl3Key_.find(user) == userEl3Key_.end()) {
LOGD("Have not found user %{public}u el3 key, not enable el3", user);
LOGI("Have not found user %{public}u el3 key, not enable el3", user);
return -ENOENT;
}
eceSeceKeyPath = userEl3Key_[user]->GetDir();
}
if (type == EL4_KEY) {
if (userEl4Key_.find(user) == userEl4Key_.end()) {
LOGD("Have not found user %{public}u el4 key, not enable el4", user);
LOGI("Have not found user %{public}u el4 key, not enable el4", user);
return -ENOENT;
}
eceSeceKeyPath = userEl4Key_[user]->GetDir();
@ -1498,7 +1628,15 @@ int KeyManager::UpdateKeyContext(uint32_t userId)
bool KeyManager::IsUeceSupport()
{
int fd = open(UECE_PATH, O_RDWR);
FILE *f = fopen(UECE_PATH, "r+");
if (f == nullptr) {
if (errno == ENOENT) {
LOGE("uece does not support !");
}
LOGE("open uece failed, errno : %{public}d", errno);
return false;
}
int fd = fileno(f);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("uece does not support !");
@ -1506,11 +1644,27 @@ bool KeyManager::IsUeceSupport()
LOGE("open uece failed, errno : %{public}d", errno);
return false;
}
close(fd);
(void)fclose(f);
LOGI("uece is support.");
return true;
}
int KeyManager::IsUeceSupportWithErrno()
{
int fd = open(UECE_PATH, O_RDWR);
if (fd < 0) {
if (errno == ENOENT) {
LOGE("uece does not support !");
return ENOENT;
}
LOGE("open uece failed, errno : %{public}d", errno);
return errno;
}
close(fd);
LOGI("uece is support.");
return E_OK;
}
int KeyManager::UpgradeKeys(const std::vector<FileList> &dirInfo)
{
for (const auto &it : dirInfo) {
@ -1597,7 +1751,12 @@ int KeyManager::RestoreUserKey(uint32_t userId, KeyType type)
LOGE("dir not exist");
return -ENOENT;
}
return RestoreUserKey(userId, dir, NULL_KEY_AUTH, type);
int32_t ret = RestoreUserKey(userId, dir, NULL_KEY_AUTH, type);
if (ret == 0 && type != EL1_KEY) {
saveLockScreenStatus[userId] = true;
LOGI("user is %{public}u , saveLockScreenStatus", userId);
}
return ret;
}
#endif
} // namespace StorageDaemon

View File

@ -0,0 +1,361 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "recover_manager.h"
#include <openssl/sha.h>
#include <unistd.h>
#include "storage_service_log.h"
namespace OHOS {
namespace StorageDaemon {
static const std::string CRYPTO_NAME_PREFIXES[] = {"ext4", "f2fs", "fscrypt"};
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
constexpr static uint32_t TEE_PARAM_INDEX_0 = 0;
constexpr static uint32_t TEE_PARAM_INDEX_1 = 1;
constexpr static int SESSION_START_DEFAULT = 1;
constexpr int MAX_RETRY_COUNT = 3;
constexpr int RETRY_INTERVAL = 100 * 1000; // 100ms
#endif
RecoveryManager::RecoveryManager()
{
LOGI("enter");
isSessionOpened = false;
}
RecoveryManager::~RecoveryManager()
{
LOGI("enter");
}
int RecoveryManager::CreateRecoverKey(uint32_t userId,
uint32_t userType,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret,
const std::vector<KeyBlob> &originIv)
{
LOGI("enter");
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
TEEC_Context createKeyContext = {};
TEEC_Session createKeySession = {};
if (!OpenSession(createKeyContext, createKeySession)) {
LOGE("Open session failed !");
return -EFAULT;
}
uint32_t createKeyOrigin = 0;
TEEC_Operation operation = { 0 };
operation.started = SESSION_START_DEFAULT;
operation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE, TEEC_NONE);
CreateRecoverKeyStr recoverKeyStr = {
.userType = userType,
.userId = userId,
.authTokenLen = static_cast<uint32_t>(token.empty() ? 0 : AUTH_TOKEN_LEN)
};
if (!token.empty()) {
auto err = memcpy_s(recoverKeyStr.authToken, AUTH_TOKEN_LEN, token.data(), token.size());
if (err != EOK) {
LOGE("memcpy failed err %{public}d", err);
CloseSession(createKeyContext, createKeySession);
return -EFAULT;
}
}
for (size_t i = 0; i < originIv.size(); ++i) {
auto err = memcpy_s(recoverKeyStr.rndToTee[i], RND_AND_KEY2_LEN, originIv[i].data.get(), originIv[i].size);
if (err != EOK) {
LOGE("memcpy failed err %{public}d, index: %{public}zu", err, i);
CloseSession(createKeyContext, createKeySession);
return -EFAULT;
}
}
operation.params[TEE_PARAM_INDEX_0].tmpref.buffer = static_cast<void *>(&recoverKeyStr);
operation.params[TEE_PARAM_INDEX_0].tmpref.size = sizeof(recoverKeyStr);
TEEC_Result ret = TEEC_InvokeCommand(&createKeySession, TaCmdId::RK_CMD_ID_GEN_RECOVERY_KEY,
&operation, &createKeyOrigin);
LOGI("InvokeCmd ret: %{public}d, origin: %{public}d", ret, createKeyOrigin);
if (ret != TEEC_SUCCESS) {
LOGE("InvokeCmd failed, ret: %{public}d, origin: %{public}d", ret, createKeyOrigin);
CloseSession(createKeyContext, createKeySession);
return -EFAULT;
}
CloseSession(createKeyContext, createKeySession);
#endif
LOGI("success");
return 0;
}
int RecoveryManager::SetRecoverKey(const std::vector<uint8_t> &key)
{
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
SetRecoverKeyStr setRecoverKeyStr;
if (SetRecoverKeyToTee(key, setRecoverKeyStr) != 0) {
LOGE("Set recover key to tee failed !");
return -EFAULT;
}
if (sizeof(setRecoverKeyStr.key2FromTee) != sizeof(setRecoverKeyStr.rndFromTee)) {
LOGE("key2 size dose not match iv size !");
return -EFAULT;
}
int rndNum = sizeof(setRecoverKeyStr.rndFromTee) / RND_AND_KEY2_LEN;
int key2Num = sizeof(setRecoverKeyStr.key2FromTee) / RND_AND_KEY2_LEN;
if (rndNum != RND_AND_KEY2_NUMS || key2Num != RND_AND_KEY2_NUMS) {
LOGE("rnd and key2 num is not match ! rndNum: %{public}d, key2Num: %{public}d", rndNum, key2Num);
return -EFAULT;
}
for (int i = 0; i < rndNum; ++i) {
uint8_t *key2 = setRecoverKeyStr.key2FromTee[i];
uint8_t *originIv = setRecoverKeyStr.rndFromTee[i];
std::vector<uint8_t> key2Data(key2, key2 + RND_AND_KEY2_LEN);
std::vector<uint8_t> ivData(originIv, originIv + RND_AND_KEY2_LEN);
KeyBlob ivBlob(ivData);
KeyBlob key2Blob(key2Data);
KeyBlob keyDesc;
if (!GenerateKeyDesc(ivBlob, keyDesc)) {
LOGE("Generate key desc failed !");
return -ENOENT;
}
if (!InstallKeyDescToKeyring(ELX_TYPE_ARR[i], key2Blob, keyDesc)) {
ivBlob.Clear();
keyDesc.Clear();
key2Blob.Clear();
LOGE("install type %{public}d to keyring failed !", ELX_TYPE_ARR[i]);
return -ENOENT;
}
ivBlob.Clear();
keyDesc.Clear();
key2Blob.Clear();
}
#endif
LOGI("succeed");
return 0;
}
int RecoveryManager::SetRecoverKeyToTee(const std::vector<uint8_t> &key, SetRecoverKeyStr &setRecoverKeyStr)
{
LOGI("enter");
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
TEEC_Context setKeyContext = {};
TEEC_Session setKeySession = {};
if (!OpenSession(setKeyContext, setKeySession)) {
LOGE("Open session failed !");
return -EFAULT;
}
TEEC_Operation operation = { 0 };
operation.started = SESSION_START_DEFAULT;
operation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_OUTPUT, TEEC_NONE, TEEC_NONE);
uint32_t setKeyOrigin;
operation.params[TEE_PARAM_INDEX_0].tmpref.buffer = static_cast<void *>(const_cast<unsigned char *>(key.data()));
operation.params[TEE_PARAM_INDEX_0].tmpref.size = key.size();
operation.params[TEE_PARAM_INDEX_1].tmpref.buffer = static_cast<void *>(&setRecoverKeyStr);
operation.params[TEE_PARAM_INDEX_1].tmpref.size = sizeof(setRecoverKeyStr);
TEEC_Result ret = TEEC_InvokeCommand(&setKeySession, TaCmdId::RK_CMD_ID_DECRYPT_CLASS_KEY, &operation,
&setKeyOrigin);
LOGI("InvokeCmd ret: %{public}d, origin: %{public}d", ret, setKeyOrigin);
if (ret != TEEC_SUCCESS) {
LOGE("InvokeCmd failed, ret: %{public}d, origin: %{public}d", ret, setKeyOrigin);
CloseSession(setKeyContext, setKeySession);
return -EFAULT;
}
CloseSession(setKeyContext, setKeySession);
#endif
return 0;
}
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
bool RecoveryManager::OpenSession(TEEC_Context &context, TEEC_Session &session)
{
LOGI("enter");
if (isSessionOpened) {
LOGE("Tee session has Opened !");
return true;
}
TEEC_Result ret = TEEC_InitializeContext(NULL, &context);
if (ret != TEEC_SUCCESS) {
LOGE("recovery tee ctx init failed !");
TEEC_FinalizeContext(&context);
isSessionOpened = false;
return false;
}
TEEC_Operation operation;
LOGI("Prepare session operation.");
operation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, TEEC_NONE);
if (memset_s(&operation, sizeof(TEEC_Operation), 0, sizeof(TEEC_Operation)) != EOK) {
LOGE("[OpenSession] memset_s failed !");
TEEC_FinalizeContext(&context);
isSessionOpened = false;
return false;
}
LOGI("Prepare open session.");
operation.started = SESSION_START_DEFAULT;
operation.paramTypes = TEEC_PARAM_TYPES(TEEC_NONE, TEEC_NONE, TEEC_NONE, TEEC_NONE);
uint32_t retErr = 0;
uint32_t retryCount = 0;
while (retryCount < MAX_RETRY_COUNT) {
ret = TEEC_OpenSession(&context, &session, recoverUuid_, TEEC_LOGIN_IDENTIFY, nullptr, &operation, &retErr);
if (ret == TEEC_SUCCESS) {
LOGI("Open session success, has try %{public}u times.", retryCount);
break;
}
retryCount++;
LOGE("has retry %{public}d times, ret: %{public}d", retryCount, ret);
usleep(RETRY_INTERVAL);
}
if (ret != TEEC_SUCCESS) {
LOGE("open session failed !");
CloseSession(context, session);
return false;
}
isSessionOpened = true;
LOGI("open session success");
return true;
}
void RecoveryManager::CloseSession(TEEC_Context &context, TEEC_Session &session)
{
TEEC_CloseSession(&session);
TEEC_FinalizeContext(&context);
isSessionOpened = false;
LOGI("close session success");
}
#endif
bool RecoveryManager::GenerateKeyDesc(const KeyBlob &ivBlob, KeyBlob &keyDesc)
{
LOGI("enter");
if (ivBlob.IsEmpty()) {
LOGE("key is empty");
return false;
}
SHA512_CTX c;
SHA512_Init(&c);
SHA512_Update(&c, ivBlob.data.get(), ivBlob.size);
uint8_t keyRef1[SHA512_DIGEST_LENGTH] = { 0 };
SHA512_Final(keyRef1, &c);
SHA512_Init(&c);
SHA512_Update(&c, keyRef1, SHA512_DIGEST_LENGTH);
uint8_t keyRef2[SHA512_DIGEST_LENGTH] = { 0 };
SHA512_Final(keyRef2, &c);
static_assert(SHA512_DIGEST_LENGTH >= CRYPTO_KEY_DESC_SIZE, "Hash too short for descriptor");
keyDesc.Alloc(CRYPTO_KEY_DESC_SIZE);
auto err = memcpy_s(keyDesc.data.get(), keyDesc.size, keyRef2, CRYPTO_KEY_DESC_SIZE);
if (err != EOK) {
LOGE("memcpy failed ret %{public}d", err);
return false;
}
LOGI("succeed");
return true;
}
bool RecoveryManager::InstallKeyDescToKeyring(size_t keyType, const KeyBlob &key2Blob, const KeyBlob &keyDesc)
{
if (keyType == USER_EL3 || keyType == USER_EL4) {
uint32_t sdpClass;
if (keyType == USER_EL3) {
sdpClass = FSCRYPT_SDP_SECE_CLASS;
} else {
sdpClass = FSCRYPT_SDP_ECE_CLASS;
}
if (!InstallEceSece(sdpClass, key2Blob, keyDesc)) {
LOGE("InstallKeyDescToKeyring failed");
return false;
}
} else {
if (!InstallDeCe(key2Blob, keyDesc)) {
LOGE("InstallKeyToKeyring failed");
return false;
}
}
return true;
}
bool RecoveryManager::InstallDeCe(const KeyBlob &key2Blob, const KeyBlob &keyDesc)
{
fscrypt_key fskey;
fskey.mode = FS_ENCRYPTION_MODE_AES_256_XTS;
fskey.size = key2Blob.size;
auto err = memcpy_s(fskey.raw, FS_MAX_KEY_SIZE, key2Blob.data.get(), key2Blob.size);
if (err != EOK) {
LOGE("memcpy failed ret %{public}d", err);
return false;
}
key_serial_t krid = KeyCtrlSearch(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
if (krid == -1) {
LOGI("no session keyring for fscrypt");
krid = KeyCtrlAddKey("keyring", "fscrypt", KEY_SPEC_SESSION_KEYRING);
if (krid == -1) {
LOGE("failed to add session keyring");
return false;
}
}
for (auto prefix : CRYPTO_NAME_PREFIXES) {
std::string keyref = prefix + ":" + keyDesc.ToString();
LOGI("InstallDeCe: prefix: %{public}s", prefix.c_str());
key_serial_t ks = KeyCtrlAddKeyEx("logon", keyref.c_str(), &fskey, krid);
if (ks == -1) {
// Addkey failed, need to process the error
LOGE("Failed to AddKey %{public}s to keyring, errno %{public}d", prefix.c_str(), errno);
}
}
LOGI("success");
return true;
}
bool RecoveryManager::InstallEceSece(uint32_t sdpClass, const KeyBlob &key2Blob, const KeyBlob &keyDesc)
{
EncryptionKeySdp fskey;
if (key2Blob.size != sizeof(fskey.raw)) {
LOGE("Wrong key size is %{public}d", key2Blob.size);
return false;
}
fskey.mode = EXT4_ENCRYPTION_MODE_AES_256_XTS;
auto err = memcpy_s(fskey.raw, sizeof(fskey.raw), key2Blob.data.get(), key2Blob.size);
if (err != EOK) {
LOGE("memcpy failed ret %{public}d", err);
return false;
}
fskey.size = EXT4_AES_256_XTS_KEY_SIZE_TO_KEYRING;
fskey.sdpClass = sdpClass;
fskey.version = 0;
key_serial_t krid = KeyCtrlSearch(KEY_SPEC_SESSION_KEYRING, "keyring", "fscrypt", 0);
if (krid == -1) {
LOGI("no session keyring for fscrypt");
krid = KeyCtrlAddKey("keyring", "fscrypt", KEY_SPEC_SESSION_KEYRING);
if (krid == -1) {
LOGE("failed to add session keyring");
return false;
}
}
for (auto prefix : CRYPTO_NAME_PREFIXES) {
std::string keyref = prefix + ":" + keyDesc.ToString();
key_serial_t ks = KeyCtrlAddKeySdp("logon", keyref.c_str(), &fskey, krid);
if (ks == -1) {
// Addkey failed, need to process the error
LOGE("Failed to AddKey %{public}s into keyring, errno %{public}d", prefix.c_str(), errno);
}
}
LOGI("success");
return true;
}
} // namespace StorageDaemon
} // namespace HOHS

View File

@ -55,7 +55,18 @@ ohos_moduletest("CryptoSubTest") {
"huks:libhukssdk",
"init:libbegetutil",
"ipc:ipc_single",
"os_account:os_account_innerkits",
]
if (enable_tee_client) {
defines += [ "RECOVER_KEY_TEE_ENVIRONMENT" ]
external_deps += [ "tee_client:libteec" ]
}
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
}
group("crypto_test") {

View File

@ -58,8 +58,8 @@ const int32_t PARAMS_SIZE_1 = 1;
const int32_t PARAMS_SIZE_2 = 2;
const int32_t PARAMS_SIZE_3 = 3;
const int32_t PARAMS_SIZE_4 = 4;
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
OHOS::StorageDaemon::FscryptKeyV2 g_testKeyV2 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
auto g_testKeyV2 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV2>(TEST_KEYPATH);
}
namespace OHOS::StorageDaemon {
@ -148,13 +148,13 @@ int32_t CryptoKeyTest::ExecSdcBinary(std::vector<std::string> params, int isCryp
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_init, TestSize.Level1)
{
EXPECT_TRUE(g_testKeyV1.InitKey(true));
EXPECT_FALSE(g_testKeyV1.InitKey(true)); // rawkey not empty
EXPECT_TRUE(g_testKeyV1->InitKey(true));
EXPECT_FALSE(g_testKeyV1->InitKey(true)); // rawkey not empty
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1.keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1.keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1.keyInfo_.key.data.get());
g_testKeyV1.keyInfo_.key.Clear();
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1->keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1->keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1->keyInfo_.key.data.get());
g_testKeyV1->keyInfo_.key.Clear();
}
/**
@ -169,15 +169,15 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_init, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
EXPECT_TRUE(g_testKeyV2.InitKey(true));
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2.keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV2.keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV2.keyInfo_.key.data.get());
g_testKeyV2.keyInfo_.key.Clear();
EXPECT_TRUE(g_testKeyV2->InitKey(true));
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2->keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV2->keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV2->keyInfo_.key.data.get());
g_testKeyV2->keyInfo_.key.Clear();
#else
EXPECT_FALSE(g_testKeyV2.InitKey(true));
EXPECT_FALSE(g_testKeyV2.ActiveKey());
EXPECT_FALSE(g_testKeyV2.InactiveKey());
EXPECT_FALSE(g_testKeyV2->InitKey(true));
EXPECT_FALSE(g_testKeyV2->ActiveKey());
EXPECT_FALSE(g_testKeyV2->InactiveKey());
#endif
}
@ -190,8 +190,8 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_init, TestSize.Level1)
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_store, TestSize.Level1)
{
#ifndef CRYPTO_TEST
EXPECT_TRUE(g_testKeyV1.InitKey(true));
g_testKeyV1.StoreKey(emptyUserAuth);
EXPECT_TRUE(g_testKeyV1->InitKey(true));
g_testKeyV1->StoreKey(emptyUserAuth);
std::string buf {};
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD);
@ -203,8 +203,8 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_store, TestSize.Level1)
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_ENCRYPTED);
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_ENCRYPTED, buf);
#else
EXPECT_TRUE(g_testKeyV1.InitKey(true));
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->InitKey(true));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
std::string buf {};
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
@ -243,10 +243,10 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_store, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
g_testKeyV2.ClearKey();
EXPECT_TRUE(g_testKeyV2.InitKey(true));
EXPECT_TRUE(g_testKeyV2.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2.StoreKey(emptyUserAuth));
g_testKeyV2->ClearKey();
EXPECT_TRUE(g_testKeyV2->InitKey(true));
EXPECT_TRUE(g_testKeyV2->StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SECDISC));
@ -273,7 +273,7 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_update, TestSize.Level1)
return;
}
std::string buf {};
EXPECT_TRUE(g_testKeyV2.UpdateKey());
EXPECT_TRUE(g_testKeyV2->UpdateKey());
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD));
@ -296,9 +296,9 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_restore_fail_wrong_version, TestSize.Leve
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
g_testKeyV1.keyInfo_.key.Clear();
g_testKeyV1->keyInfo_.key.Clear();
// the version loaded is v2, not expected v1.
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth));
}
#endif
@ -310,36 +310,36 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_restore_fail_wrong_version, TestSize.Leve
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_restore, TestSize.Level1)
{
g_testKeyV1.ClearKey();
EXPECT_TRUE(g_testKeyV1.InitKey(true));
g_testKeyV1->ClearKey();
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1.UpdateKey();
g_testKeyV1.RestoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
g_testKeyV1->UpdateKey();
g_testKeyV1->RestoreKey(emptyUserAuth);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1.keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1.keyInfo_.key.data.get());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1.keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1->keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1->keyInfo_.key.data.get());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1->keyInfo_.version);
OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SECDISC, "bad secdesc");
#else
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1.UpdateKey());
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->UpdateKey());
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1.keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1.keyInfo_.key.data.get());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1.keyInfo_.version);
EXPECT_EQ(CRYPTO_AES_256_XTS_KEY_SIZE, g_testKeyV1->keyInfo_.key.size);
EXPECT_NE(nullptr, g_testKeyV1->keyInfo_.key.data.get());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1->keyInfo_.version);
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SECDISC, "bad secdesc"));
#endif
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth)); // should decrypt failed
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth)); // should decrypt failed
remove(std::string(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SECDISC).c_str());
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth));
remove(std::string(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD).c_str());
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth));
remove(std::string(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_ENCRYPTED).c_str());
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth));
remove(std::string(TEST_KEYPATH + "/fscrypt_version").c_str());
EXPECT_FALSE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->RestoreKey(emptyUserAuth));
}
/**
@ -350,23 +350,23 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_restore, TestSize.Level1)
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_active, TestSize.Level1)
{
g_testKeyV1.ClearKey();
EXPECT_FALSE(g_testKeyV1.ActiveKey()); // active empty key should fail
EXPECT_TRUE(g_testKeyV1.InitKey(true));
g_testKeyV1->ClearKey();
EXPECT_FALSE(g_testKeyV1->ActiveKey()); // active empty key should fail
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
#else
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
#endif
EXPECT_FALSE(g_testKeyV1.keyInfo_.key.IsEmpty());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1.keyInfo_.version);
EXPECT_FALSE(g_testKeyV1->keyInfo_.key.IsEmpty());
EXPECT_EQ(FSCRYPT_V1, g_testKeyV1->keyInfo_.version);
EXPECT_TRUE(g_testKeyV1.ActiveKey(FIRST_CREATE_KEY));
EXPECT_TRUE(g_testKeyV1->ActiveKey(FIRST_CREATE_KEY));
// raw key should be erase after install to kernel.
EXPECT_TRUE(g_testKeyV1.keyInfo_.key.IsEmpty());
EXPECT_TRUE(g_testKeyV1.keyInfo_.keyId.IsEmpty());
EXPECT_TRUE(g_testKeyV1->keyInfo_.key.IsEmpty());
EXPECT_TRUE(g_testKeyV1->keyInfo_.keyId.IsEmpty());
// key desc saved in memory for later clear key.
EXPECT_FALSE(g_testKeyV1.keyInfo_.keyDesc.IsEmpty());
EXPECT_FALSE(g_testKeyV1->keyInfo_.keyDesc.IsEmpty());
// v1 key installed, and key_desc was saved on disk.
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + PATH_KEYDESC));
@ -385,8 +385,8 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_active, TestSize.Level1)
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_clear, TestSize.Level1)
{
EXPECT_TRUE(g_testKeyV1.ClearKey());
EXPECT_TRUE(g_testKeyV1.keyInfo_.key.IsEmpty());
EXPECT_TRUE(g_testKeyV1->ClearKey());
EXPECT_TRUE(g_testKeyV1->keyInfo_.key.IsEmpty());
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + PATH_KEYDESC));
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + PATH_FSCRYPT_VER));
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD));
@ -400,19 +400,19 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_clear, TestSize.Level1)
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_policy_set, TestSize.Level1)
{
EXPECT_TRUE(g_testKeyV1.InitKey(true));
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
#else
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
#endif
EXPECT_TRUE(g_testKeyV1.ActiveKey(FIRST_CREATE_KEY));
EXPECT_TRUE(g_testKeyV1->ActiveKey(FIRST_CREATE_KEY));
FscryptPolicy arg;
(void)memset_s(&arg, sizeof(arg), 0, sizeof(arg));
arg.v1.version = FSCRYPT_POLICY_V1;
(void)memcpy_s(arg.v1.master_key_descriptor, FSCRYPT_KEY_DESCRIPTOR_SIZE, g_testKeyV1.keyInfo_.keyDesc.data.get(),
g_testKeyV1.keyInfo_.keyDesc.size);
(void)memcpy_s(arg.v1.master_key_descriptor, FSCRYPT_KEY_DESCRIPTOR_SIZE, g_testKeyV1->keyInfo_.keyDesc.data.get(),
g_testKeyV1->keyInfo_.keyDesc.size);
arg.v1.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
arg.v1.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
arg.v1.flags = FSCRYPT_POLICY_FLAGS_PAD_32;
@ -456,7 +456,7 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_policy_get, TestSize.Level1)
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_key_inactive, TestSize.Level1)
{
EXPECT_TRUE(g_testKeyV1.InactiveKey(USER_DESTROY));
EXPECT_TRUE(g_testKeyV1->InactiveKey(USER_DESTROY));
#ifdef SUPPORT_FSCRYPT_V2
EXPECT_FALSE(OHOS::ForceCreateDirectory(TEST_DIR_LEGACY + "/test_dir1"));
@ -477,15 +477,16 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_active, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
g_testKeyV2.ClearKey();
EXPECT_TRUE(g_testKeyV2.InitKey(true));
EXPECT_TRUE(g_testKeyV2.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2.ActiveKey());
g_testKeyV2->ClearKey();
EXPECT_TRUE(g_testKeyV2->InitKey(true));
EXPECT_TRUE(g_testKeyV2->StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2->UpdateKey());
EXPECT_TRUE(g_testKeyV2->ActiveKey());
// raw key should be erase after install to kernel.
EXPECT_TRUE(g_testKeyV2.keyInfo_.key.IsEmpty());
EXPECT_TRUE(g_testKeyV2.keyInfo_.keyDesc.IsEmpty());
EXPECT_EQ(static_cast<unsigned int>(FSCRYPT_KEY_IDENTIFIER_SIZE), g_testKeyV2.keyInfo_.keyId.size);
EXPECT_TRUE(g_testKeyV2->keyInfo_.key.IsEmpty());
EXPECT_TRUE(g_testKeyV2->keyInfo_.keyDesc.IsEmpty());
EXPECT_EQ(static_cast<unsigned int>(FSCRYPT_KEY_IDENTIFIER_SIZE), g_testKeyV2->keyInfo_.keyId.size);
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + PATH_KEYID));
}
@ -500,12 +501,12 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_policy_set, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2.keyInfo_.version);
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2->keyInfo_.version);
FscryptPolicy arg;
(void)memset_s(&arg, sizeof(arg), 0, sizeof(arg));
arg.v2.version = FSCRYPT_POLICY_V2;
(void)memcpy_s(arg.v2.master_key_identifier, FSCRYPT_KEY_IDENTIFIER_SIZE, g_testKeyV2.keyInfo_.keyId.data.get(),
g_testKeyV2.keyInfo_.keyId.size);
(void)memcpy_s(arg.v2.master_key_identifier, FSCRYPT_KEY_IDENTIFIER_SIZE, g_testKeyV2->keyInfo_.keyId.data.get(),
g_testKeyV2->keyInfo_.keyId.size);
arg.v2.contents_encryption_mode = FSCRYPT_MODE_AES_256_XTS;
arg.v2.filenames_encryption_mode = FSCRYPT_MODE_AES_256_CTS;
arg.v2.flags = FSCRYPT_POLICY_FLAGS_PAD_32;
@ -554,7 +555,7 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_policy_inactive, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
EXPECT_TRUE(g_testKeyV2.InactiveKey());
EXPECT_TRUE(g_testKeyV2->InactiveKey());
// When the v2 policy removed, the files are encrypted.
EXPECT_FALSE(OHOS::FileExists(TEST_DIR_V2 + "/test_dir"));
EXPECT_FALSE(OHOS::FileExists(TEST_DIR_V2 + "/test_file1"));
@ -572,16 +573,16 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_policy_restore, TestSize.Level1)
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
EXPECT_TRUE(g_testKeyV2.RestoreKey(emptyUserAuth));
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2.keyInfo_.version);
EXPECT_TRUE(g_testKeyV2.ActiveKey());
EXPECT_TRUE(g_testKeyV2->RestoreKey(emptyUserAuth));
EXPECT_EQ(FSCRYPT_V2, g_testKeyV2->keyInfo_.version);
EXPECT_TRUE(g_testKeyV2->ActiveKey());
// the files is decrypted now
EXPECT_TRUE(OHOS::FileExists(TEST_DIR_V2 + "/test_dir"));
EXPECT_TRUE(OHOS::FileExists(TEST_DIR_V2 + "/test_file1"));
EXPECT_TRUE(OHOS::FileExists(TEST_DIR_V2 + "/test_file2"));
EXPECT_TRUE(g_testKeyV2.ClearKey());
EXPECT_TRUE(g_testKeyV2->ClearKey());
}
/**
@ -595,24 +596,24 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_load_and_set_policy_default, TestSize.Lev
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
g_testKeyV2.ClearKey();
EXPECT_TRUE(g_testKeyV2.InitKey(true));
EXPECT_TRUE(g_testKeyV2.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2.ActiveKey());
g_testKeyV2->ClearKey();
EXPECT_TRUE(g_testKeyV2->InitKey(true));
EXPECT_TRUE(g_testKeyV2->StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2->ActiveKey());
EXPECT_EQ(0, SetFscryptSysparam("2:aes-256-cts:aes-256-xts"));
EXPECT_EQ(0, InitFscryptPolicy());
OHOS::ForceRemoveDirectory(TEST_DIR_V2);
OHOS::ForceCreateDirectory(TEST_DIR_V2);
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV2.GetDir().c_str(), TEST_DIR_V2.c_str()));
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV2->GetDir().c_str(), TEST_DIR_V2.c_str()));
EXPECT_TRUE(OHOS::ForceCreateDirectory(TEST_DIR_V2 + "/test_dir"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_V2 + "/test_file1", "hello, world!\n"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_V2 + "/test_file2", "AA"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_V2 + "/111111111111111111111111111111111111111111111111", "AA"));
EXPECT_TRUE(g_testKeyV2.ClearKey());
EXPECT_TRUE(g_testKeyV2->ClearKey());
}
#endif
@ -624,28 +625,28 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_load_and_set_policy_default, TestSize.Lev
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_v1_load_and_set_policy_default, TestSize.Level1)
{
g_testKeyV1.ClearKey();
EXPECT_TRUE(g_testKeyV1.InitKey(true));
g_testKeyV1->ClearKey();
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
#else
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
#endif
EXPECT_TRUE(g_testKeyV1.ActiveKey(FIRST_CREATE_KEY));
EXPECT_TRUE(g_testKeyV1->ActiveKey(FIRST_CREATE_KEY));
EXPECT_EQ(0, SetFscryptSysparam("1:aes-256-cts:aes-256-xts"));
EXPECT_EQ(0, InitFscryptPolicy());
OHOS::ForceRemoveDirectory(TEST_DIR_LEGACY);
OHOS::ForceCreateDirectory(TEST_DIR_LEGACY);
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV1.GetDir().c_str(), TEST_DIR_LEGACY.c_str()));
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV1->GetDir().c_str(), TEST_DIR_LEGACY.c_str()));
EXPECT_TRUE(OHOS::ForceCreateDirectory(TEST_DIR_LEGACY + "/test_dir"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_LEGACY + "/test_file1", "hello, world!\n"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_LEGACY + "/test_file2", "AA"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_LEGACY + "/111111111111111111111111111111111111111111111111", "AA"));
EXPECT_TRUE(g_testKeyV1.ClearKey());
EXPECT_TRUE(g_testKeyV1->ClearKey());
}
/**
@ -656,28 +657,28 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v1_load_and_set_policy_default, TestSize.Lev
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_1, TestSize.Level1)
{
EXPECT_TRUE(g_testKeyV1.InitKey(true));
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
// storekey to version 0
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD);
std::string keyShieldV0;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0);
// storekey to version 1
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD);
std::string keyShieldV1;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD, keyShieldV1);
// storekey to version 2
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION2 + PATH_SHIELD);
std::string keyShieldV2;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION2 + PATH_SHIELD, keyShieldV2);
// updatekey will rename version 2 to latest
g_testKeyV1.UpdateKey();
g_testKeyV1->UpdateKey();
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD);
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP + PATH_SHIELD));
std::string keyShieldLatest;
@ -685,27 +686,27 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_1, TestSize.Level1)
EXPECT_EQ(keyShieldLatest, keyShieldV2);
#else
// storekey to version 0
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
std::string keyShieldV0;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0));
// storekey to version 1
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD));
std::string keyShieldV1;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD, keyShieldV1));
EXPECT_NE(keyShieldV0, keyShieldV1);
// storekey to version 2
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION2 + PATH_SHIELD));
std::string keyShieldV2;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION2 + PATH_SHIELD, keyShieldV2));
EXPECT_NE(keyShieldV1, keyShieldV2);
// updatekey will rename version 2 to latest
EXPECT_TRUE(g_testKeyV1.UpdateKey());
EXPECT_TRUE(g_testKeyV1->UpdateKey());
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD));
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP + PATH_SHIELD));
std::string keyShieldLatest;
@ -723,44 +724,44 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_1, TestSize.Level1)
HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_2, TestSize.Level1)
{
#ifndef CRYPTO_TEST
g_testKeyV1.RestoreKey(emptyUserAuth);
g_testKeyV1->RestoreKey(emptyUserAuth);
// storekey to version 0
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD);
std::string keyShieldV0;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0);
// storekey to version 1
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD);
std::string keyShieldV1;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD, keyShieldV1);
// restorekey will decrypt from versions and rename first success one to latest
g_testKeyV1.RestoreKey(emptyUserAuth);
g_testKeyV1->RestoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD);
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP + PATH_SHIELD));
std::string keyShieldLatest;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD, keyShieldLatest);
EXPECT_EQ(keyShieldLatest, keyShieldV1);
#else
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
// storekey to version 0
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
std::string keyShieldV0;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0));
// storekey to version 1
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD));
std::string keyShieldV1;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION1 + PATH_SHIELD, keyShieldV1));
// restorekey will decrypt from versions and rename first success one to latest
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST + PATH_SHIELD));
EXPECT_FALSE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP + PATH_SHIELD));
std::string keyShieldLatest;
@ -779,7 +780,7 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_3, TestSize.Level1)
{
#ifndef CRYPTO_TEST
// storekey to version 0
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD);
std::string keyShieldV0A;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0A);
@ -787,21 +788,21 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_3, TestSize.Level1)
// latest dir broken, not affect restore and update operation
OHOS::ForceRemoveDirectory(TEST_KEYPATH + TEST_KEYDIR_LATEST);
OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST, "latest is a file");
g_testKeyV1.RestoreKey(emptyUserAuth);
g_testKeyV1->RestoreKey(emptyUserAuth);
OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD);
std::string keyShieldV0B;
OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0B);
EXPECT_TRUE(keyShieldV0A == keyShieldV0B);
g_testKeyV1.RestoreKey(emptyUserAuth);
EXPECT_FALSE(g_testKeyV1.UpdateKey());
g_testKeyV1->RestoreKey(emptyUserAuth);
EXPECT_FALSE(g_testKeyV1->UpdateKey());
// latest dir backup also broken, not affect restore and update operation
OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP, "latest_backup is a file");
EXPECT_FALSE(g_testKeyV1.UpdateKey());
g_testKeyV1.RestoreKey(emptyUserAuth);
EXPECT_FALSE(g_testKeyV1->UpdateKey());
g_testKeyV1->RestoreKey(emptyUserAuth);
#else
// storekey to version 0
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
std::string keyShieldV0A;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0A));
@ -809,18 +810,18 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_storekey_version_test_3, TestSize.Level1)
// latest dir broken, not affect restore and update operation
OHOS::ForceRemoveDirectory(TEST_KEYPATH + TEST_KEYDIR_LATEST);
OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST, "latest is a file");
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
EXPECT_TRUE(OHOS::FileExists(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD));
std::string keyShieldV0B;
EXPECT_TRUE(OHOS::LoadStringFromFile(TEST_KEYPATH + TEST_KEYDIR_VERSION0 + PATH_SHIELD, keyShieldV0B));
EXPECT_TRUE(keyShieldV0A == keyShieldV0B);
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1.UpdateKey());
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->UpdateKey());
// latest dir backup also broken, not affect restore and update operation
OHOS::SaveStringToFile(TEST_KEYPATH + TEST_KEYDIR_LATEST_BACKUP, "latest_backup is a file");
EXPECT_FALSE(g_testKeyV1.UpdateKey());
EXPECT_TRUE(g_testKeyV1.RestoreKey(emptyUserAuth));
EXPECT_FALSE(g_testKeyV1->UpdateKey());
EXPECT_TRUE(g_testKeyV1->RestoreKey(emptyUserAuth));
#endif
}
@ -836,17 +837,17 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_load_and_set_policy_padding_4, TestSize.L
if (KeyCtrlGetFscryptVersion(TEST_MNT.c_str()) == FSCRYPT_V1) {
return;
}
g_testKeyV2.ClearKey();
EXPECT_TRUE(g_testKeyV2.InitKey(true));
EXPECT_TRUE(g_testKeyV2.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2.ActiveKey());
g_testKeyV2->ClearKey();
EXPECT_TRUE(g_testKeyV2->InitKey(true));
EXPECT_TRUE(g_testKeyV2->StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV2->ActiveKey());
EXPECT_EQ(0, SetFscryptSysparam("2:aes-256-cts:aes-256-xts"));
EXPECT_EQ(0, InitFscryptPolicy());
OHOS::ForceRemoveDirectory(TEST_DIR_V2);
OHOS::ForceCreateDirectory(TEST_DIR_V2);
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV2.GetDir().c_str(), TEST_DIR_V2.c_str()));
EXPECT_EQ(0, LoadAndSetPolicy(g_testKeyV2->GetDir().c_str(), TEST_DIR_V2.c_str()));
EXPECT_TRUE(OHOS::ForceCreateDirectory(TEST_DIR_V2 + "/test_dir"));
EXPECT_TRUE(OHOS::SaveStringToFile(TEST_DIR_V2 + "/test_file1", "hello, world!\n"));
@ -861,7 +862,7 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_v2_load_and_set_policy_padding_4, TestSize.L
EXPECT_EQ(FSCRYPT_MODE_AES_256_CTS, arg.policy.v2.filenames_encryption_mode);
EXPECT_EQ(FSCRYPT_MODE_AES_256_XTS, arg.policy.v2.contents_encryption_mode);
EXPECT_TRUE(g_testKeyV2.ClearKey());
EXPECT_TRUE(g_testKeyV2->ClearKey());
}
#endif
@ -923,7 +924,7 @@ HWTEST_F(CryptoKeyTest, key_manager_generate_delete_user_keys, TestSize.Level1)
EXPECT_EQ(-ENOENT, KeyManager::GetInstance()->UpdateKeyContext(userId));
EXPECT_EQ(-ENOENT, KeyManager::GetInstance()->InActiveUserKey(userId));
EXPECT_EQ(-EFAULT, KeyManager::GetInstance()->ActiveUserKey(userId, {}, {}));
EXPECT_EQ(-EFAULT, KeyManager::GetInstance()->DeleteUserKeys(userId));
EXPECT_EQ(0, KeyManager::GetInstance()->DeleteUserKeys(userId));
}
/**
@ -934,12 +935,12 @@ HWTEST_F(CryptoKeyTest, key_manager_generate_delete_user_keys, TestSize.Level1)
*/
HWTEST_F(CryptoKeyTest, fscrypt_key_secure_access_control, TestSize.Level1)
{
g_testKeyV1.ClearKey();
EXPECT_TRUE(g_testKeyV1.InitKey(true));
g_testKeyV1->ClearKey();
EXPECT_TRUE(g_testKeyV1->InitKey(true));
#ifndef CRYPTO_TEST
g_testKeyV1.StoreKey(emptyUserAuth);
g_testKeyV1->StoreKey(emptyUserAuth);
#else
EXPECT_TRUE(g_testKeyV1.StoreKey(emptyUserAuth));
EXPECT_TRUE(g_testKeyV1->StoreKey(emptyUserAuth));
#endif
std::string token = "bad_token";
std::string secret = "bad_secret";
@ -949,8 +950,8 @@ HWTEST_F(CryptoKeyTest, fscrypt_key_secure_access_control, TestSize.Level1)
.token = badToken,
.secret = badSecret
};
EXPECT_FALSE(g_testKeyV1.RestoreKey(badUserAuth));
EXPECT_TRUE(g_testKeyV1.ClearKey());
EXPECT_FALSE(g_testKeyV1->RestoreKey(badUserAuth));
EXPECT_TRUE(g_testKeyV1->ClearKey());
}
/**
@ -1243,6 +1244,84 @@ HWTEST_F(CryptoKeyTest, fscrypt_sdc_filecrypt_006, TestSize.Level1)
params.clear();
}
HWTEST_F(CryptoKeyTest, fscrypt_sdc_filecrypt_007, TestSize.Level1)
{
std::vector<std::string> params;
// test sdc Get_unlock_status
params.clear();
params.push_back("Get_unlock_status");
params.push_back("id");
params.push_back("01234567890abcd");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("Get_unlock_status");
params.push_back("10");
params.push_back("01234567890abcd");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("Get_unlock_status");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("Get_unlock_status");
params.push_back("10");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
}
HWTEST_F(CryptoKeyTest, fscrypt_sdc_filecrypt_008, TestSize.Level1)
{
std::vector<std::string> params;
// test sdc create_recover_key
params.clear();
params.push_back("create_recover_key");
params.push_back("id");
params.push_back("01234567890abcd");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("create_recover_key");
params.push_back("10");
params.push_back("01234567890abcd");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("create_recover_key");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("create_recover_key");
params.push_back("10");
params.push_back("11");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
}
HWTEST_F(CryptoKeyTest, fscrypt_sdc_filecrypt_009, TestSize.Level1)
{
std::vector<std::string> params;
// test sdc set_recover_key
params.clear();
params.push_back("set_recover_key");
params.push_back("id");
params.push_back("01234567890abcd");
params.push_back("01234567890abcd");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("set_recover_key");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
params.push_back("set_recover_key");
params.push_back("10");
params.push_back("11");
EXPECT_EQ(0, CryptoKeyTest::ExecSdcBinary(params, 1));
params.clear();
}
/**
* @tc.name: libfscrypt api test
* @tc.desc: Verify the libfscrypt interface.

View File

@ -42,7 +42,13 @@ ohos_unittest("CryptoTest") {
"hilog:libhilog",
"huks:libhukssdk",
"init:libbegetutil",
"os_account:os_account_innerkits",
]
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
}
group("crypto_test") {

View File

@ -22,6 +22,7 @@
#include "directory_ex.h"
#include "fbex.h"
#include "file_ex.h"
#include "key_blob.h"
#include "storage_service_errno.h"
using namespace testing::ext;
@ -350,34 +351,34 @@ HWTEST_F(FbexTest, ReadESecretToKernel, TestSize.Level1)
uint32_t status = PARAMS_1;
bool isFbeSupport = true;
EXPECT_EQ(fbex.ReadESecretToKernel(userIdToFbe, status, nullptr, VALID_SIZE, isFbeSupport), -EINVAL);
std::unique_ptr<uint8_t []> nullBuffer;
EXPECT_EQ(fbex.ReadESecretToKernel(userIdToFbe, status, nullBuffer, VALID_SIZE, isFbeSupport), -EINVAL);
status = UNLOCK_STATUS;
int ret = fbex.ReadESecretToKernel(userIdToFbe, status, nullptr, VALID_SIZE, isFbeSupport);
int ret = fbex.ReadESecretToKernel(userIdToFbe, status, nullBuffer, VALID_SIZE, isFbeSupport);
EXPECT_EQ(ret, -EINVAL);
uint8_t *eBuffer = new uint8_t[VALID_SIZE];
KeyBlob eBuffer(VALID_SIZE);
isFbeSupport = true;
OHOS::ForceRemoveDirectory(FBEX_UECE_PATH);
OHOS::ForceCreateDirectory(FBEX_UECE_PATH);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer, VALID_SIZE, isFbeSupport);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer.data, VALID_SIZE, isFbeSupport);
EXPECT_NE(ret, 0);
EXPECT_EQ(isFbeSupport, true);
isFbeSupport = true;
OHOS::ForceRemoveDirectory(FBEX_UECE_PATH);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer, VALID_SIZE, isFbeSupport);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer.data, VALID_SIZE, isFbeSupport);
EXPECT_EQ(ret, 0);
EXPECT_EQ(isFbeSupport, false);
isFbeSupport = true;
std::ofstream file(FBEX_UECE_PATH);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer, VALID_SIZE, isFbeSupport);
ret = fbex.ReadESecretToKernel(userIdToFbe, status, eBuffer.data, VALID_SIZE, isFbeSupport);
EXPECT_NE(ret, 0);
EXPECT_EQ(isFbeSupport, true);
EXPECT_TRUE(OHOS::RemoveFile(FBEX_UECE_PATH));
delete[] eBuffer;
eBuffer = nullptr;
eBuffer.Clear();
GTEST_LOG_(INFO) << "fbex_ReadESecretToKernel end";
}

View File

@ -319,20 +319,20 @@ HWTEST_F(FscryptKeyV1ExtTest, FscryptKeyV1Ext_ReadClassE_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "FscryptKeyV1Ext_ReadClassE_001 end";
bool isFbeSupport;
uint8_t classEBuffer;
std::unique_ptr<uint8_t[]> classEBuffer;
FscryptKeyV1Ext ext;
ext.userId_ = 100;
ext.type_ = TYPE_EL2;
EXPECT_CALL(*fbexMock_, IsFBEXSupported()).WillOnce(Return(false));
EXPECT_EQ(ext.ReadClassE(0, &classEBuffer, 1, isFbeSupport), true);
EXPECT_EQ(ext.ReadClassE(0, classEBuffer, 1, isFbeSupport), true);
EXPECT_CALL(*fbexMock_, IsFBEXSupported()).WillOnce(Return(true));
EXPECT_CALL(*fbexMock_, ReadESecretToKernel(_, _, _, _, _)).WillOnce(Return(0));
EXPECT_EQ(ext.ReadClassE(0, &classEBuffer, 1, isFbeSupport), true);
EXPECT_EQ(ext.ReadClassE(0, classEBuffer, 1, isFbeSupport), true);
EXPECT_CALL(*fbexMock_, IsFBEXSupported()).WillOnce(Return(true));
EXPECT_CALL(*fbexMock_, ReadESecretToKernel(_, _, _, _, _)).WillOnce(Return(1));
EXPECT_EQ(ext.ReadClassE(0, &classEBuffer, 1, isFbeSupport), false);
EXPECT_EQ(ext.ReadClassE(0, classEBuffer, 1, isFbeSupport), false);
GTEST_LOG_(INFO) << "FscryptKeyV1Ext_ReadClassE_001 end";
}

View File

@ -46,6 +46,7 @@ ohos_moduletest("FscryptKeyV1Test") {
"${storage_daemon_path}/crypto/src/huks_master.cpp",
"${storage_daemon_path}/crypto/src/iam_client.cpp",
"${storage_daemon_path}/crypto/src/key_backup.cpp",
"${storage_daemon_path}/crypto/src/key_crypto_utils.cpp",
"${storage_daemon_path}/crypto/src/key_manager.cpp",
"${storage_daemon_path}/crypto/src/openssl_crypto.cpp",
"${storage_daemon_path}/crypto/test/fscrypt_v1_test/fscrypt_key_v1_test.cpp",
@ -73,13 +74,23 @@ ohos_moduletest("FscryptKeyV1Test") {
"init:libbegetutil",
"ipc:ipc_single",
"openssl:libcrypto_shared",
"os_account:os_account_innerkits",
"samgr:samgr_proxy",
]
if (enable_tee_client) {
defines += [ "RECOVER_KEY_TEE_ENVIRONMENT" ]
external_deps += [ "tee_client:libteec" ]
}
if (enable_user_auth_framework) {
defines += [ "USER_AUTH_FRAMEWORK" ]
external_deps += [ "user_auth_framework:userauth_client" ]
}
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
}
group("fscrypt_key_v1_test") {

View File

@ -76,12 +76,12 @@ void FscryptKeyV1Test::TearDown(void)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_GenerateAppKeyDesc, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_GenerateAppKeyDesc start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
KeyBlob appKey;
EXPECT_FALSE(g_testKeyV1.GenerateAppKeyDesc(appKey));
EXPECT_FALSE(g_testKeyV1->GenerateAppKeyDesc(appKey));
KeyBlob appKey1(FBEX_KEYID_SIZE);
EXPECT_TRUE(g_testKeyV1.GenerateAppKeyDesc(appKey1));
EXPECT_TRUE(g_testKeyV1->GenerateAppKeyDesc(appKey1));
GTEST_LOG_(INFO) << "fscrypt_key_v1_GenerateAppKeyDesc end";
}
@ -94,13 +94,13 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_GenerateAppKeyDesc, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_LockUece, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_LockUece start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
bool isFbeSupport = true;
EXPECT_CALL(*fscryptKeyExtMock_, LockUeceExt(_)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.LockUece(isFbeSupport));
EXPECT_FALSE(g_testKeyV1->LockUece(isFbeSupport));
EXPECT_CALL(*fscryptKeyExtMock_, LockUeceExt(_)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.LockUece(isFbeSupport));
EXPECT_TRUE(g_testKeyV1->LockUece(isFbeSupport));
GTEST_LOG_(INFO) << "fscrypt_key_v1_LockUece end";
}
@ -113,14 +113,14 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_LockUece, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_ChangePinCodeClassE, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_ChangePinCodeClassE start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
bool isFbeSupport = true;
uint32_t userId = 100;
EXPECT_CALL(*fscryptKeyExtMock_, ChangePinCodeClassE(_, _)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.ChangePinCodeClassE(isFbeSupport, userId));
EXPECT_TRUE(g_testKeyV1->ChangePinCodeClassE(isFbeSupport, userId));
EXPECT_CALL(*fscryptKeyExtMock_, ChangePinCodeClassE(_, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.ChangePinCodeClassE(isFbeSupport, userId));
EXPECT_FALSE(g_testKeyV1->ChangePinCodeClassE(isFbeSupport, userId));
GTEST_LOG_(INFO) << "fscrypt_key_v1_ChangePinCodeClassE end";
}
@ -133,13 +133,13 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_ChangePinCodeClassE, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DeleteClassEPinCode, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_DeleteClassEPinCode start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t userId = 100;
EXPECT_CALL(*fscryptKeyExtMock_, DeleteClassEPinCode(_)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.DeleteClassEPinCode(userId));
EXPECT_TRUE(g_testKeyV1->DeleteClassEPinCode(userId));
EXPECT_CALL(*fscryptKeyExtMock_, DeleteClassEPinCode(_)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.DeleteClassEPinCode(userId));
EXPECT_FALSE(g_testKeyV1->DeleteClassEPinCode(userId));
GTEST_LOG_(INFO) << "fscrypt_key_v1_DeleteClassEPinCode end";
}
@ -152,16 +152,16 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DeleteClassEPinCode, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_AddClassE, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_AddClassE start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t status = 100;
bool isSupport = true;
bool isNeedEncryptClassE = true;
EXPECT_CALL(*fscryptKeyExtMock_, AddClassE(_, _, _)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.AddClassE(isNeedEncryptClassE, isSupport, status));
EXPECT_TRUE(g_testKeyV1->AddClassE(isNeedEncryptClassE, isSupport, status));
EXPECT_CALL(*fscryptKeyExtMock_, AddClassE(_, _, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.AddClassE(isNeedEncryptClassE, isSupport, status));
EXPECT_FALSE(g_testKeyV1->AddClassE(isNeedEncryptClassE, isSupport, status));
GTEST_LOG_(INFO) << "fscrypt_key_v1_AddClassE end";
}
@ -174,12 +174,12 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_AddClassE, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DeleteAppkey, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_DeleteAppkey start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
std::string KeyId = "";
EXPECT_FALSE(g_testKeyV1.DeleteAppkey(KeyId));
EXPECT_FALSE(g_testKeyV1->DeleteAppkey(KeyId));
KeyId = "test";
EXPECT_FALSE(g_testKeyV1.DeleteAppkey(KeyId));
EXPECT_TRUE(g_testKeyV1->DeleteAppkey(KeyId));
GTEST_LOG_(INFO) << "fscrypt_key_v1_DeleteAppkey end";
}
@ -192,12 +192,12 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DeleteAppkey, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_UninstallKeyForAppKeyToKeyring, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_UninstallKeyForAppKeyToKeyring start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
std::string keyId = "";
EXPECT_FALSE(g_testKeyV1.UninstallKeyForAppKeyToKeyring(keyId));
EXPECT_FALSE(g_testKeyV1->UninstallKeyForAppKeyToKeyring(keyId));
keyId = "test";
EXPECT_FALSE(g_testKeyV1.UninstallKeyForAppKeyToKeyring(keyId));
EXPECT_TRUE(g_testKeyV1->UninstallKeyForAppKeyToKeyring(keyId));
GTEST_LOG_(INFO) << "fscrypt_key_v1_UninstallKeyForAppKeyToKeyring end";
}
@ -210,16 +210,14 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_UninstallKeyForAppKeyToKeyring, TestSi
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_InstallKeyForAppKeyToKeyring, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_InstallKeyForAppKeyToKeyring start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
uint32_t *appKeyraw = new uint32_t[17];
EXPECT_FALSE(g_testKeyV1.InstallKeyForAppKeyToKeyring(appKeyraw));
delete[] appKeyraw;
appKeyraw = nullptr;
uint32_t *appKey = new uint32_t[10];
EXPECT_FALSE(g_testKeyV1.InstallKeyForAppKeyToKeyring(appKey));
delete[] appKey;
appKey = nullptr;
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
KeyBlob appKeyRaw(17);
EXPECT_FALSE(g_testKeyV1->InstallKeyForAppKeyToKeyring(appKeyRaw));
appKeyRaw.Clear();
KeyBlob appKey(10);
EXPECT_FALSE(g_testKeyV1->InstallKeyForAppKeyToKeyring(appKey));
appKey.Clear();
GTEST_LOG_(INFO) << "fscrypt_key_v1_InstallKeyForAppKeyToKeyring end";
}
@ -232,25 +230,28 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_InstallKeyForAppKeyToKeyring, TestSize
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_UnlockUserScreen, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_UnlockUserScreen start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t flag = 1;
uint32_t sdpClass = 1;
const std::string mnt = "test";
EXPECT_FALSE(g_testKeyV1.UnlockUserScreen(flag, sdpClass, mnt));
g_testKeyV1.keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_FALSE(g_testKeyV1->UnlockUserScreen(flag, sdpClass, mnt));
g_testKeyV1->keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_CALL(*fscryptKeyExtMock_, UnlockUserScreenExt(_, _, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.UnlockUserScreen(flag, sdpClass, mnt));
EXPECT_FALSE(g_testKeyV1->UnlockUserScreen(flag, sdpClass, mnt));
g_testKeyV1.ClearKey();
g_testKeyV1.keyInfo_.key.Alloc(TEST_KEYID_SIZE);
g_testKeyV1->ClearKey();
g_testKeyV1->keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_CALL(*fscryptKeyExtMock_, UnlockUserScreenExt(_, _, _)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.UnlockUserScreen(flag, sdpClass, mnt));
EXPECT_TRUE(g_testKeyV1->UnlockUserScreen(flag, sdpClass, mnt));
sdpClass = 2;
g_testKeyV1->ClearKey();
g_testKeyV1->keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_CALL(*fscryptKeyExtMock_, UnlockUserScreenExt(_, _, _)).WillOnce(Return(true));
EXPECT_FALSE(g_testKeyV1.UnlockUserScreen(flag, sdpClass, mnt));
EXPECT_FALSE(g_testKeyV1->UnlockUserScreen(flag, sdpClass, mnt));
g_testKeyV1->ClearKey();
GTEST_LOG_(INFO) << "fscrypt_key_v1_UnlockUserScreen end";
}
@ -263,16 +264,16 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_UnlockUserScreen, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_GenerateAppkey, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_GenerateAppkey start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t userId = 100;
uint32_t hashId = 2;
std::string keyDesc = "test";
EXPECT_CALL(*fscryptKeyExtMock_, GenerateAppkey(_, _, _, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.GenerateAppkey(userId, hashId, keyDesc));
EXPECT_FALSE(g_testKeyV1->GenerateAppkey(userId, hashId, keyDesc));
EXPECT_CALL(*fscryptKeyExtMock_, GenerateAppkey(_, _, _, _)).WillOnce(Return(true));
EXPECT_FALSE(g_testKeyV1.GenerateAppkey(userId, hashId, keyDesc));
EXPECT_FALSE(g_testKeyV1->GenerateAppkey(userId, hashId, keyDesc));
GTEST_LOG_(INFO) << "fscrypt_key_v1_GenerateAppkey end";
}
@ -285,25 +286,25 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_GenerateAppkey, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_LockUserScreen, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_LockUserScreen start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t flag = 1;
uint32_t sdpClass = 2;
uint32_t elType = TYPE_EL4;
EXPECT_CALL(*fscryptKeyExtMock_, SetElType()).WillOnce(Return(elType));
EXPECT_CALL(*fscryptKeyExtMock_, LockUserScreenExt(_, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.LockUserScreen(flag, sdpClass, TEST_MNT));
EXPECT_FALSE(g_testKeyV1->LockUserScreen(flag, sdpClass, TEST_MNT));
elType = TYPE_EL4;
g_testKeyV1.keyInfo_.keyDesc.Clear();
g_testKeyV1->keyInfo_.keyDesc.Clear();
EXPECT_CALL(*fscryptKeyExtMock_, SetElType()).WillOnce(Return(elType));
EXPECT_CALL(*fscryptKeyExtMock_, LockUserScreenExt(_, _)).WillOnce(Return(true));
EXPECT_FALSE(g_testKeyV1.LockUserScreen(flag, sdpClass, TEST_MNT));
EXPECT_FALSE(g_testKeyV1->LockUserScreen(flag, sdpClass, TEST_MNT));
elType = TYPE_EL1;
EXPECT_CALL(*fscryptKeyExtMock_, SetElType()).WillOnce(Return(elType));
EXPECT_CALL(*fscryptKeyExtMock_, LockUserScreenExt(_, _)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.LockUserScreen(flag, sdpClass, TEST_MNT));
EXPECT_TRUE(g_testKeyV1->LockUserScreen(flag, sdpClass, TEST_MNT));
GTEST_LOG_(INFO) << "fscrypt_key_v1_LockUserScreen end";
}
@ -316,20 +317,20 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_LockUserScreen, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_InstallEceSeceKeyToKeyring, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_InstallEceSeceKeyToKeyring start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
uint32_t sdpClass = 2;
EXPECT_FALSE(g_testKeyV1.InstallEceSeceKeyToKeyring(sdpClass));
EXPECT_FALSE(g_testKeyV1->InstallEceSeceKeyToKeyring(sdpClass));
g_testKeyV1.keyInfo_.key.Clear();
g_testKeyV1.keyInfo_.keyDesc.Clear();
g_testKeyV1.keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_FALSE(g_testKeyV1.InstallEceSeceKeyToKeyring(sdpClass));
g_testKeyV1->keyInfo_.key.Clear();
g_testKeyV1->keyInfo_.keyDesc.Clear();
g_testKeyV1->keyInfo_.key.Alloc(TEST_KEYID_SIZE);
EXPECT_FALSE(g_testKeyV1->InstallEceSeceKeyToKeyring(sdpClass));
g_testKeyV1.keyInfo_.key.Clear();
g_testKeyV1.keyInfo_.keyDesc.Clear();
g_testKeyV1.keyInfo_.key.Alloc(TEST_KEYID_SIZE);
g_testKeyV1.keyInfo_.keyDesc.Alloc(TEST_KEYID_SIZE);
EXPECT_FALSE(g_testKeyV1.InstallEceSeceKeyToKeyring(sdpClass));
g_testKeyV1->keyInfo_.key.Clear();
g_testKeyV1->keyInfo_.keyDesc.Clear();
g_testKeyV1->keyInfo_.key.Alloc(TEST_KEYID_SIZE);
g_testKeyV1->keyInfo_.keyDesc.Alloc(TEST_KEYID_SIZE);
EXPECT_FALSE(g_testKeyV1->InstallEceSeceKeyToKeyring(sdpClass));
GTEST_LOG_(INFO) << "fscrypt_key_v1_InstallEceSeceKeyToKeyring end";
}
@ -342,22 +343,22 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_InstallEceSeceKeyToKeyring, TestSize.L
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DecryptClassE, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_DecryptClassE start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
bool isSupport = true;
uint32_t user = 1;
uint32_t status = 1;
EXPECT_CALL(*fscryptKeyExtMock_, ReadClassE(_, _, _, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.DecryptClassE(emptyUserAuth, isSupport, user, status));
EXPECT_FALSE(g_testKeyV1->DecryptClassE(emptyUserAuth, isSupport, user, status));
g_testKeyV1.ClearKey();
g_testKeyV1->ClearKey();
EXPECT_CALL(*fscryptKeyExtMock_, ReadClassE(_, _, _, _)).WillOnce(Return(true));
EXPECT_TRUE(g_testKeyV1.DecryptClassE(emptyUserAuth, isSupport, user, status));
EXPECT_TRUE(g_testKeyV1->DecryptClassE(emptyUserAuth, isSupport, user, status));
g_testKeyV1.ClearKey();
g_testKeyV1->ClearKey();
const UserAuth auth{KeyBlob(8), KeyBlob(8), 0};
EXPECT_CALL(*fscryptKeyExtMock_, ReadClassE(_, _, _, _)).WillOnce(Return(true));
EXPECT_FALSE(g_testKeyV1.DecryptClassE(auth, isSupport, user, status));
EXPECT_FALSE(g_testKeyV1->DecryptClassE(auth, isSupport, user, status));
GTEST_LOG_(INFO) << "fscrypt_key_v1_DecryptClassE end";
}
@ -370,13 +371,13 @@ HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_DecryptClassE, TestSize.Level1)
HWTEST_F(FscryptKeyV1Test, fscrypt_key_v1_EncryptClassE, TestSize.Level1)
{
GTEST_LOG_(INFO) << "fscrypt_key_v1_EncryptClassE start";
OHOS::StorageDaemon::FscryptKeyV1 g_testKeyV1 {TEST_KEYPATH};
auto g_testKeyV1 = std::make_shared<OHOS::StorageDaemon::FscryptKeyV1>(TEST_KEYPATH);
bool isSupport = true;
uint32_t user = 1;
uint32_t status = 1;
EXPECT_CALL(*fscryptKeyExtMock_, ReadClassE(_, _, _, _)).WillOnce(Return(false));
EXPECT_FALSE(g_testKeyV1.EncryptClassE(emptyUserAuth, isSupport, user, status));
EXPECT_FALSE(g_testKeyV1->EncryptClassE(emptyUserAuth, isSupport, user, status));
GTEST_LOG_(INFO) << "fscrypt_key_v1_EncryptClassE end";
}
} // OHOS::StorageDaemon

View File

@ -69,7 +69,13 @@ ohos_moduletest("FscryptKeyV2Test") {
"huks:libhukssdk",
"init:libbegetutil",
"ipc:ipc_single",
"os_account:os_account_innerkits",
]
if (enable_screenlock_manager) {
defines += [ "ENABLE_SCREENLOCK_MANAGER" ]
external_deps += [ "screenlock_mgr:screenlock_client" ]
}
}
group("fscrypt_key_v2_test") {

View File

@ -39,11 +39,13 @@ ohos_unittest("IamClientTest") {
sources = [
"${storage_daemon_path}/crypto/src/iam_client.cpp",
"${storage_daemon_path}/mock/user_idm_client_impl_mock.cpp",
"iam_client_test.cpp",
]
deps = [
"${storage_daemon_path}/libfscrypt:libfscryptutils",
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]

View File

@ -19,9 +19,11 @@
#include "iam_client.h"
#include "storage_service_errno.h"
#include "user_idm_client_impl_mock.h"
using namespace testing::ext;
using namespace testing;
using namespace std;
namespace OHOS::StorageDaemon {
class IamClientTest : public testing::Test {
@ -30,16 +32,21 @@ public:
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static inline shared_ptr<UserIdmClientMoc> userIdmClientImplMock_ = nullptr;
};
void IamClientTest::SetUpTestCase(void)
{
GTEST_LOG_(INFO) << "SetUpTestCase";
userIdmClientImplMock_ = make_shared<UserIdmClientMoc>();
UserIdmClientMoc::userIdmClientMoc = userIdmClientImplMock_;
}
void IamClientTest::TearDownTestCase(void)
{
GTEST_LOG_(INFO) << "TearDownTestCase";
UserIdmClientMoc::userIdmClientMoc = nullptr;
userIdmClientImplMock_ = nullptr;
}
void IamClientTest::SetUp(void)
@ -63,12 +70,37 @@ HWTEST_F(IamClientTest, iam_client_GetSecureUid, TestSize.Level1)
GTEST_LOG_(INFO) << "iam_client_GetSecureUid start";
uint32_t userId = 100;
uint64_t secureUid = 1;
#ifdef USER_AUTH_FRAMEWORK
EXPECT_CALL(*userIdmClientImplMock_, GetSecUserInfo(_, _))
.WillOnce(Return(UserIam::UserAuth::ResultCode::SUCCESS));
#endif
IamClient &client = IamClient::GetInstance();
EXPECT_TRUE(client.GetSecureUid(userId, secureUid));
EXPECT_EQ(secureUid, 0);
GTEST_LOG_(INFO) << "iam_client_GetSecureUid end";
}
#ifdef USER_AUTH_FRAMEWORK
/**
* @tc.name: iam_client_GetSecureUid
* @tc.desc: Verify the iam_client GetSecureUid.
* @tc.type: FUNC
* @tc.require: AR000GK0BP
*/
HWTEST_F(IamClientTest, iam_client_GetSecureUid_failed, TestSize.Level1)
{
GTEST_LOG_(INFO) << "iam_client_GetSecureUid_failed start";
uint32_t userId = 100;
uint64_t secureUid = 1;
EXPECT_CALL(*userIdmClientImplMock_, GetSecUserInfo(_, _))
.WillOnce(Return(UserIam::UserAuth::ResultCode::FAIL));
IamClient &client = IamClient::GetInstance();
EXPECT_FALSE(client.GetSecureUid(userId, secureUid));
GTEST_LOG_(INFO) << "iam_client_GetSecureUid_failed end";
}
#endif
/**
* @tc.name: iam_client_NotifyGetSecureUid
* @tc.desc: Verify the iam_client NotifyGetSecureUid.

View File

@ -0,0 +1,61 @@
# Copyright (C) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/test.gni")
import("//foundation/filemanagement/storage_service/storage_service_aafwk.gni")
ohos_unittest("KeyBackupTest") {
branch_protector_ret = "pac_ret"
sanitize = {
integer_overflow = true
cfi = true
cfi_cross_dso = true
debug = false
blocklist = "${storage_service_path}/cfi_blocklist.txt"
}
module_out_path = "storage_service/storage_daemon"
defines = [
"STORAGE_LOG_TAG = \"StorageDaemon\"",
"LOG_DOMAIN = 0xD004301",
"USER_CRYPTO_MIGRATE_KEY",
"private = public",
]
include_dirs = [
"${storage_daemon_path}/include/crypto",
"${storage_service_common_path}/include",
]
sources = [
"${storage_daemon_path}/crypto/src/key_backup.cpp",
"key_backup_test.cpp",
]
deps = [
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
deps += [ "${storage_daemon_path}:storage_common_utils" ]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"huks:libhukssdk",
]
}
group("key_backup_test") {
testonly = true
deps = [ ":KeyBackupTest" ]
}

View File

@ -0,0 +1,133 @@
/*
* Copyright (C) 2022-2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "key_backup.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "directory_ex.h"
using namespace std;
using namespace testing::ext;
using namespace testing;
namespace OHOS::StorageDaemon {
constexpr static mode_t DEFAULT_WRITE_FILE_PERM = 0644;
constexpr static uint32_t MAX_FILE_NUM = 5;
constexpr uint32_t INVALID_LOOP_NUM = 0xFFFFFFFF;
class KeyBackupTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void KeyBackupTest::SetUpTestCase(void)
{
GTEST_LOG_(INFO) << "SetUpTestCase Start";
}
void KeyBackupTest::TearDownTestCase(void)
{
GTEST_LOG_(INFO) << "TearDownTestCase Start";
}
void KeyBackupTest::SetUp(void)
{
GTEST_LOG_(INFO) << "SetUp Start";
}
void KeyBackupTest::TearDown(void)
{
GTEST_LOG_(INFO) << "TearDown Start";
}
/**
* @tc.name: KeyBackup_GetBackupDir_000
* @tc.desc: Verify the GetBackupDir function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyBackupTest, KeyBackup_GetBackupDir_000, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyBackup_GetBackupDir_000 Start";
std::string origDir = DEVICE_EL1_DIR;
std::string backupDir;
EXPECT_EQ(KeyBackup::GetInstance().GetBackupDir(origDir, backupDir), 0);
EXPECT_EQ(backupDir, DEVICE_EL1_DIR + BACKUP_NAME);
origDir = "test";
backupDir.clear();
EXPECT_EQ(KeyBackup::GetInstance().GetBackupDir(origDir, backupDir), -1);
EXPECT_EQ(backupDir, "");
origDir = "/test";
EXPECT_EQ(KeyBackup::GetInstance().GetBackupDir(origDir, backupDir), -1);
EXPECT_EQ(backupDir, "");
origDir = "test/path/";
EXPECT_EQ(KeyBackup::GetInstance().GetBackupDir(origDir, backupDir), 0);
EXPECT_EQ(backupDir, "test/path_bak/");
GTEST_LOG_(INFO) << "KeyBackup_GetBackupDir_000 end";
}
/**
* @tc.name: KeyBackup_GetLoopMaxNum_001
* @tc.desc: Verify the GetLoopMaxNum function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyBackupTest, KeyBackup_GetLoopMaxNum_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyBackup_GetLoopMaxNum_001 Start";
EXPECT_EQ(KeyBackup::GetInstance().GetLoopMaxNum(MAX_FILE_NUM + 1), INVALID_LOOP_NUM);
EXPECT_EQ(KeyBackup::GetInstance().GetLoopMaxNum(MAX_FILE_NUM), 31);
GTEST_LOG_(INFO) << "KeyBackup_GetLoopMaxNum_001 end";
}
/**
* @tc.name: KeyBackup_HandleCopyDir_001
* @tc.desc: Verify the HandleCopyDir function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyBackupTest, KeyBackup_HandleCopyDir_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyBackup_HandleCopyDir_001 Start";
string toPath = "/data/test/KeyBackup/test3";
string fromPath = "/data/test/KeyBackup/test2/";
EXPECT_FALSE(access(toPath.c_str(), F_OK) == 0);
EXPECT_FALSE(access(fromPath.c_str(), F_OK) == 0);
EXPECT_EQ(KeyBackup::GetInstance().HandleCopyDir(fromPath, toPath), -1);
string baseDir = "/data/test/KeyBackup/";
EXPECT_EQ(KeyBackup::GetInstance().MkdirParent(baseDir, DEFAULT_WRITE_FILE_PERM), 0);
EXPECT_EQ(KeyBackup::GetInstance().HandleCopyDir(fromPath, toPath), 0);
EXPECT_EQ(KeyBackup::GetInstance().MkdirParent(fromPath, DEFAULT_WRITE_FILE_PERM), 0);
EXPECT_TRUE(access(fromPath.c_str(), F_OK) == 0);
EXPECT_EQ(KeyBackup::GetInstance().HandleCopyDir(fromPath, toPath), 0);
struct FileAttr attr;
struct FileAttr attr2;
EXPECT_EQ(KeyBackup::GetInstance().GetAttr(toPath, attr), 0);
EXPECT_EQ(KeyBackup::GetInstance().GetAttr(fromPath, attr2), 0);
EXPECT_EQ(attr.mode, attr2.mode);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(baseDir));
EXPECT_FALSE(access(baseDir.c_str(), F_OK) == 0);
GTEST_LOG_(INFO) << "KeyBackup_HandleCopyDir_001 end";
}
}

View File

@ -43,6 +43,13 @@ int32_t KeyManager::UpdateUserAuth(unsigned int user, struct UserTokenSecret &us
return E_OK;
}
int32_t KeyManager::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret, uint64_t secureUid, uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
return E_OK;
}
int32_t KeyManager::ActiveUserKey(unsigned int user, const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret)
{
@ -85,6 +92,17 @@ int32_t KeyManager::UnlockUserAppKeys(uint32_t userId, bool needGetAllAppKey)
return E_OK;
}
int32_t KeyManager::CreateRecoverKey(uint32_t userId, uint32_t userType, const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret)
{
return E_OK;
}
int32_t KeyManager::SetRecoverKey(const std::vector<uint8_t> &key)
{
return E_OK;
}
int32_t KeyManager::SetDirectoryElPolicy(unsigned int user, KeyType type,
const std::vector<FileList> &vec)
{

View File

@ -47,6 +47,7 @@ ohos_unittest("KeyManagerTest") {
"${storage_daemon_path}/crypto/src/iam_client.cpp",
"${storage_daemon_path}/crypto/src/key_backup.cpp",
"${storage_daemon_path}/crypto/src/key_manager.cpp",
"${storage_daemon_path}/crypto/src/recover_manager.cpp",
"${storage_daemon_path}/mock/base_key_mock.cpp",
"${storage_daemon_path}/mock/fscrypt_control_mock.cpp",
"${storage_daemon_path}/mock/fscrypt_key_v2_mock.cpp",
@ -60,6 +61,74 @@ ohos_unittest("KeyManagerTest") {
"//third_party/googletest:gtest_main",
]
deps += [ "${storage_daemon_path}:storage_common_utils" ]
external_deps = [
"c_utils:utils",
"eventhandler:libeventhandler",
"hilog:libhilog",
"hisysevent:libhisysevent",
"huks:libhukssdk",
"init:libbegetutil",
"ipc:ipc_single",
"openssl:libcrypto_shared",
]
if (enable_user_auth_framework) {
defines += [ "USER_AUTH_FRAMEWORK" ]
external_deps += [ "user_auth_framework:userauth_client" ]
}
}
ohos_unittest("KeyManagerSupTest") {
branch_protector_ret = "pac_ret"
sanitize = {
integer_overflow = true
cfi = true
cfi_cross_dso = true
debug = false
blocklist = "${storage_service_path}/cfi_blocklist.txt"
}
module_out_path = "storage_service/storage_daemon"
defines = [
"STORAGE_LOG_TAG = \"StorageDaemon\"",
"LOG_DOMAIN = 0xD004301",
"USER_CRYPTO_MIGRATE_KEY",
"private = public",
]
include_dirs = [
"${storage_daemon_path}/include",
"${storage_daemon_path}/include/crypto",
"${storage_daemon_path}/include/libfscrypt",
"${storage_daemon_path}/include/mock",
"${storage_daemon_path}/include/user",
"${storage_service_common_path}/include",
]
sources = [
"${storage_daemon_path}/crypto/src/crypto_delay_handler.cpp",
"${storage_daemon_path}/crypto/src/fbex.cpp",
"${storage_daemon_path}/crypto/src/fscrypt_key_v1.cpp",
"${storage_daemon_path}/crypto/src/fscrypt_key_v1_ext.cpp",
"${storage_daemon_path}/crypto/src/iam_client.cpp",
"${storage_daemon_path}/crypto/src/key_backup.cpp",
"${storage_daemon_path}/crypto/src/key_manager.cpp",
"${storage_daemon_path}/crypto/src/recover_manager.cpp",
"${storage_daemon_path}/mock/base_key_mock.cpp",
"${storage_daemon_path}/mock/fscrypt_control_mock.cpp",
"${storage_daemon_path}/mock/fscrypt_key_v2_mock.cpp",
"${storage_daemon_path}/mock/key_control_mock.cpp",
"${storage_daemon_path}/mock/mount_manager_mock.cpp",
"key_manager_sup_test.cpp",
]
deps = [
"//third_party/googletest:gmock_main",
"//third_party/googletest:gtest_main",
]
deps += [
"${storage_daemon_path}:storage_common_utils",
#"${storage_daemon_path}/libfscrypt:libfscryptutils",
@ -84,5 +153,8 @@ ohos_unittest("KeyManagerTest") {
group("key_manager_test") {
testonly = true
deps = [ ":KeyManagerTest" ]
deps = [
":KeyManagerSupTest",
":KeyManagerTest",
]
}

View File

@ -0,0 +1,218 @@
/*
* Copyright (C) 2022-2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "key_manager.h"
#include <fcntl.h>
#include <fstream>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <memory>
#include <string>
#include <vector>
#include "base_key_mock.h"
#include "directory_ex.h"
#include "fscrypt_control_mock.h"
#include "fscrypt_key_v2_mock.h"
#include "fscrypt_key_v2.h"
#include "key_control_mock.h"
#include "fscrypt_key_v2.h"
#include "mount_manager_mock.h"
#include "storage_service_errno.h"
#include "utils/file_utils.h"
using namespace std;
using namespace testing::ext;
using namespace testing;
namespace {
constexpr const char *UECE_PATH = "/dev/fbex_uece";
}
namespace OHOS::StorageDaemon {
class KeyManagerSupTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
static inline shared_ptr<MountManagerMoc> mountManagerMoc_ = nullptr;
static inline shared_ptr<FscryptKeyV2Moc> fscryptKeyMock_ = nullptr;
static inline shared_ptr<KeyControlMoc> keyControlMock_ = nullptr;
static inline shared_ptr<BaseKeyMoc> baseKeyMock_ = nullptr;
static inline shared_ptr<FscryptControlMoc> fscryptControlMock_ = nullptr;
};
void KeyManagerSupTest::SetUpTestCase(void)
{
GTEST_LOG_(INFO) << "SetUpTestCase Start";
mountManagerMoc_ = make_shared<MountManagerMoc>();
MountManagerMoc::mountManagerMoc = mountManagerMoc_;
fscryptKeyMock_ = make_shared<FscryptKeyV2Moc>();
FscryptKeyV2Moc::fscryptKeyV2Moc = fscryptKeyMock_;
fscryptControlMock_ = make_shared<FscryptControlMoc>();
FscryptControlMoc::fscryptControlMoc = fscryptControlMock_;
keyControlMock_ = make_shared<KeyControlMoc>();
KeyControlMoc::keyControlMoc = keyControlMock_;
baseKeyMock_ = make_shared<BaseKeyMoc>();
BaseKeyMoc::baseKeyMoc = baseKeyMock_;
}
void KeyManagerSupTest::TearDownTestCase(void)
{
GTEST_LOG_(INFO) << "TearDownTestCase Start";
MountManagerMoc::mountManagerMoc = nullptr;
mountManagerMoc_ = nullptr;
FscryptKeyV2Moc::fscryptKeyV2Moc = nullptr;
fscryptKeyMock_ = nullptr;
FscryptControlMoc::fscryptControlMoc = nullptr;
fscryptControlMock_ = nullptr;
KeyControlMoc::keyControlMoc = nullptr;
keyControlMock_ = nullptr;
BaseKeyMoc::baseKeyMoc = nullptr;
baseKeyMock_ = nullptr;
}
void KeyManagerSupTest::SetUp(void)
{
GTEST_LOG_(INFO) << "SetUp Start";
}
void KeyManagerSupTest::TearDown(void)
{
GTEST_LOG_(INFO) << "TearDown Start";
}
/**
* @tc.name: KeyManager_GetFileEncryptStatus_000
* @tc.desc: Verify the GetFileEncryptStatus function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerSupTest, KeyManager_GetFileEncryptStatus_000, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_GetFileEncryptStatus_000 Start";
unsigned int userId = 1;
bool isEncrypted;
EXPECT_EQ(KeyManager::GetInstance()->GetFileEncryptStatus(userId, isEncrypted), E_OK);
EXPECT_EQ(isEncrypted, true);
string basePath = "/data/app/el2/" + to_string(userId);
string path = basePath + "/base";
EXPECT_TRUE(OHOS::ForceCreateDirectory(path));
EXPECT_CALL(*mountManagerMoc_, CheckMountFileByUser(_)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->GetFileEncryptStatus(userId, isEncrypted), E_OK);
EXPECT_EQ(isEncrypted, true);
EXPECT_CALL(*mountManagerMoc_, CheckMountFileByUser(_)).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->GetFileEncryptStatus(userId, isEncrypted), E_OK);
EXPECT_EQ(isEncrypted, false);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(basePath));
GTEST_LOG_(INFO) << "KeyManager_GetFileEncryptStatus_000 end";
}
/**
* @tc.name: KeyManager_GenerateAppkey_001
* @tc.desc: Verify the GenerateAppkey function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerSupTest, KeyManager_GenerateAppkey_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_GenerateAppkey_001 Start";
unsigned int user = 800;
string keyId;
bool existUece = true;
if (access(UECE_PATH, F_OK) != 0) {
existUece = false;
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -ENOTSUP);
std::ofstream file(UECE_PATH);
EXPECT_GT(open(UECE_PATH, O_RDWR), 0);
}
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->userEl4Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -ENOENT);
string basePath = "/data/app/el2/" + to_string(user);
string path = basePath + "/base";
EXPECT_TRUE(OHOS::ForceCreateDirectory(path));
EXPECT_CALL(*mountManagerMoc_, CheckMountFileByUser(_)).WillOnce(Return(true));
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL4_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*fscryptKeyMock_, GenerateAppkey(_, _, _)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -EFAULT);
EXPECT_CALL(*fscryptKeyMock_, GenerateAppkey(_, _, _)).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), 0);
KeyManager::GetInstance()->userEl4Key_.erase(user);
KeyManager::GetInstance()->userEl4Key_[user] = nullptr;
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -ENOENT);
KeyManager::GetInstance()->userEl4Key_.erase(user);
EXPECT_CALL(*mountManagerMoc_, CheckMountFileByUser(_)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -ENOENT);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(basePath));
ASSERT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
if (!existUece) {
OHOS::RemoveFile(UECE_PATH);
}
GTEST_LOG_(INFO) << "KeyManager_GenerateAppkey_001 end";
}
/**
* @tc.name: KeyManager_DeleteAppkey_001
* @tc.desc: Verify the DeleteAppkey function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerSupTest, KeyManager_DeleteAppkey_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_DeleteAppkey_001 Start";
unsigned int user = 800;
string keyId;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->userEl4Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(user, keyId), -ENOENT);
string basePath = "/data/app/el2/" + to_string(user);
string path = basePath + "/base";
EXPECT_TRUE(OHOS::ForceCreateDirectory(path));
EXPECT_CALL(*mountManagerMoc_, CheckMountFileByUser(_)).WillOnce(Return(true));
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL4_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*fscryptKeyMock_, DeleteAppkey(_)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(user, keyId), -EFAULT);
EXPECT_CALL(*fscryptKeyMock_, DeleteAppkey(_)).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(user, keyId), 0);
KeyManager::GetInstance()->userEl4Key_.erase(user);
KeyManager::GetInstance()->userEl4Key_[user] = nullptr;
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(user, keyId), -ENOENT);
KeyManager::GetInstance()->userEl4Key_.erase(user);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(basePath));
ASSERT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
GTEST_LOG_(INFO) << "KeyManager_DeleteAppkey_001 end";
}
}

View File

@ -282,7 +282,7 @@ HWTEST_F(KeyManagerTest, KeyManager_ActiveCeSceSeceUserKey_001, TestSize.Level1)
KeyManager::GetInstance()->userEl2Key_[user] = tmpKey;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->ActiveCeSceSeceUserKey(user, EL2_KEY, token, secret), 0);
int eL6Key = 6;
KeyType type = static_cast<KeyType>(eL6Key);
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
@ -324,7 +324,7 @@ HWTEST_F(KeyManagerTest, KeyManager_ActiveCeSceSeceUserKey_002, TestSize.Level1)
unsigned int user = 1;
std::vector<uint8_t> token = {};
std::vector<uint8_t> secret = {};
std::string keyUeceDir = UECE_DIR + "/" + std::to_string(user);
std::string keyDir = USER_EL5_DIR + "/" + std::to_string(user);
EXPECT_TRUE(OHOS::ForceCreateDirectory(keyDir));
@ -467,7 +467,7 @@ HWTEST_F(KeyManagerTest, KeyManager_SetDirectoryElPolicy, TestSize.Level1)
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->SetDirectoryElPolicy(user, type, vec), -ENOENT);
std::shared_ptr<BaseKey> tmpKey = std::dynamic_pointer_cast<BaseKey>(std::make_shared<FscryptKeyV2>("test"));
KeyManager::GetInstance()->userEl1Key_[user] = tmpKey;
vec.push_back({1, "/test"});
@ -561,8 +561,38 @@ HWTEST_F(KeyManagerTest, KeyManager_UpdateKeyContext, TestSize.Level1)
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).Times(3).WillOnce(Return(false))\
.WillOnce(Return(false)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->UpdateKeyContext(userId), 0);
GTEST_LOG_(INFO) << "KeyManager_UpdateKeyContextt end";
}
/**
* @tc.name: KeyManager_UpdateKeyContext_001
* @tc.desc: Verify the UpdateKeyContext function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerTest, KeyManager_UpdateKeyContext_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_UpdateKeyContext_001 Start";
uint32_t userId = 1;
KeyManager::GetInstance()->userEl5Key_.erase(userId);
KeyManager::GetInstance()->saveESecretStatus[userId] = false;
auto fd = open(UECE_PATH, O_RDWR);
bool exist = true;
if (fd < 0) {
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).Times(3).WillOnce(Return(false))\
.WillOnce(Return(false)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->UpdateKeyContext(userId), 0);
close(fd);
exist = false;
fd = open(UECE_PATH, O_RDWR | O_CREAT);
ASSERT_TRUE(fd != -1) << "UpdateKeyContext Create File Failed!" << errno;;
close(fd);
}
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).Times(3).WillOnce(Return(false))\
.WillOnce(Return(false)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->UpdateKeyContext(userId), 0);
KeyManager::GetInstance()->saveESecretStatus[userId] = true;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).Times(4).WillOnce(Return(false))\
.WillOnce(Return(false)).WillOnce(Return(false)).WillOnce(Return(true));
@ -572,7 +602,12 @@ HWTEST_F(KeyManagerTest, KeyManager_UpdateKeyContext, TestSize.Level1)
.WillOnce(Return(false)).WillOnce(Return(false)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->UpdateKeyContext(userId), 0);
KeyManager::GetInstance()->saveESecretStatus.erase(userId);
GTEST_LOG_(INFO) << "KeyManager_UpdateKeyContextt end";
if (!exist) {
auto ret = unlink(UECE_PATH);
ASSERT_TRUE(ret != -1) << "Failed to delete file in KeyManager_UpdateKeyContext_001! " << errno;
}
GTEST_LOG_(INFO) << "KeyManager_UpdateKeyContext_001 end";
}
/**
@ -607,7 +642,7 @@ HWTEST_F(KeyManagerTest, KeyManager_RestoreUserKey_000, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_RestoreUserKey_000 Start";
uint32_t userId = 1;
KeyType type = EL1_KEY;
#ifdef USER_CRYPTO_MIGRATE_KEY
int eL6Key = 6;
type = static_cast<KeyType>(eL6Key);
@ -914,16 +949,22 @@ HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_001, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_001 Start";
unsigned int user = 800;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->SaveUserElKey(user, EL1_KEY, elKey);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
KeyManager::GetInstance()->userEl1Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
KeyManager::GetInstance()->SaveUserElKey(user, static_cast<KeyType>(0), elKey);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, static_cast<KeyType>(0)), nullptr);
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL1_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_INVALID));
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
KeyManager::GetInstance()->userEl1Key_.erase(user);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_001 end";
}
@ -938,12 +979,21 @@ HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_002, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_002 Start";
unsigned int user = 800;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->SaveUserElKey(user, EL2_KEY, elKey);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
KeyManager::GetInstance()->userEl2Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL2_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_INVALID));
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
KeyManager::GetInstance()->userEl2Key_.erase(user);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_002 end";
}
@ -959,12 +1009,21 @@ HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_003, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_003 Start";
unsigned int user = 800;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->SaveUserElKey(user, EL3_KEY, elKey);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
KeyManager::GetInstance()->userEl3Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL3_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_INVALID));
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
KeyManager::GetInstance()->userEl3Key_.erase(user);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_003 end";
}
@ -980,12 +1039,21 @@ HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_004, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_004 Start";
unsigned int user = 800;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->SaveUserElKey(user, EL4_KEY, elKey);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
KeyManager::GetInstance()->userEl4Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL4_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_INVALID));
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
KeyManager::GetInstance()->userEl4Key_.erase(user);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_004 end";
}
@ -1001,16 +1069,39 @@ HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_005, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_005 Start";
unsigned int user = 800;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
KeyManager::GetInstance()->SaveUserElKey(user, EL5_KEY, elKey);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL1_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL2_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL3_KEY), nullptr);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL4_KEY), nullptr);
KeyManager::GetInstance()->userEl5Key_.erase(user);
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
string keyDir = KeyManager::GetInstance()->GetKeyDirByUserAndType(user, EL5_KEY);
ASSERT_TRUE(OHOS::ForceCreateDirectory(keyDir));
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_INVALID));
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_NE(KeyManager::GetInstance()->GetUserElKey(user, EL5_KEY), nullptr);
EXPECT_TRUE(OHOS::ForceRemoveDirectory(keyDir));
KeyManager::GetInstance()->userEl5Key_.erase(user);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_005 end";
}
/**
* @tc.name: KeyManager_SaveUserElKey_006
* @tc.desc: Verify the SaveUserElKey function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerTest, KeyManager_SaveUserElKey_006, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_006 Start";
unsigned int user = 800;
EXPECT_EQ(KeyManager::GetInstance()->GetUserElKey(user, static_cast<KeyType>(0)), nullptr);
GTEST_LOG_(INFO) << "KeyManager_SaveUserElKey_006 end";
}
/**
* @tc.name: KeyManager_GetUserDelayHandler_001
* @tc.desc: Verify the GetUserDelayHandler function.
@ -1050,78 +1141,6 @@ HWTEST_F(KeyManagerTest, KeyManager_GetLockScreenStatus_001, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_GetLockScreenStatus_001 end";
}
/**
* @tc.name: KeyManager_GenerateAppkey_001
* @tc.desc: Verify the GenerateAppkey function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerTest, KeyManager_GenerateAppkey_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_GenerateAppkey_001 Start";
unsigned int user = 800;
string keyId;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(user, 100, keyId), -ENOENT);
unsigned int userExist = 100;
auto el2Key = KeyManager::GetInstance()->GetUserElKey(userExist, EL2_KEY);
bool exist = true;
if (el2Key == nullptr) {
exist = false;
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(userExist, 100, keyId), -ENOENT);
KeyManager::GetInstance()->SaveUserElKey(userExist, EL2_KEY, elKey);
}
EXPECT_CALL(*fscryptKeyMock_, GenerateAppkey(_, _, _)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(userExist, 100, keyId), -EFAULT);
EXPECT_CALL(*fscryptKeyMock_, GenerateAppkey(_, _, _)).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->GenerateAppkey(userExist, 100, keyId), 0);
if (!exist) {
KeyManager::GetInstance()->userEl2Key_.erase(userExist);
}
GTEST_LOG_(INFO) << "KeyManager_GenerateAppkey_001 end";
}
/**
* @tc.name: KeyManager_DeleteAppkey_001
* @tc.desc: Verify the DeleteAppkey function.
* @tc.type: FUNC
* @tc.require: IAHHWW
*/
HWTEST_F(KeyManagerTest, KeyManager_DeleteAppkey_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_DeleteAppkey_001 Start";
unsigned int user = 800;
string keyId;
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(user, keyId), -ENOENT);
unsigned int userExist = 100;
auto el2Key = KeyManager::GetInstance()->GetUserElKey(userExist, EL2_KEY);
bool exist = true;
if (el2Key == nullptr) {
exist = false;
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(userExist, keyId), -ENOENT);
KeyManager::GetInstance()->SaveUserElKey(userExist, EL2_KEY, elKey);
}
EXPECT_CALL(*fscryptKeyMock_, DeleteAppkey(_)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(userExist, keyId), -EFAULT);
EXPECT_CALL(*fscryptKeyMock_, DeleteAppkey(_)).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->DeleteAppkey(userExist, keyId), 0);
if (!exist) {
KeyManager::GetInstance()->userEl2Key_.erase(userExist);
}
GTEST_LOG_(INFO) << "KeyManager_DeleteAppkey_001 end";
}
/**
* @tc.name: KeyManager_InactiveUserElKey_001
* @tc.desc: Verify the InactiveUserElKey function.
@ -1138,7 +1157,7 @@ HWTEST_F(KeyManagerTest, KeyManager_InactiveUserElKey_001, TestSize.Level1)
shared_ptr<FscryptKeyV2> elKey = make_shared<FscryptKeyV2>("/data/test");
userElxKey_[user] = elKey;
EXPECT_CALL(*fscryptKeyMock_, InactiveKey(_, _)).WillOnce(Return(false));
EXPECT_EQ(KeyManager::GetInstance()->InactiveUserElKey(user, userElxKey_), -EFAULT);
@ -1273,7 +1292,7 @@ HWTEST_F(KeyManagerTest, KeyManager_SetDirectoryElPolicy_001, TestSize.Level1)
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->SetDirectoryElPolicy(user, EL1_KEY, vec), -ENOENT);
KeyManager::GetInstance()->userEl1Key_[user] = elKey;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_CALL(*fscryptControlMock_, LoadAndSetPolicy(_, _)).WillOnce(Return(-1));
@ -1302,7 +1321,7 @@ HWTEST_F(KeyManagerTest, KeyManager_SetDirectoryElPolicy_002, TestSize.Level1)
vec.push_back(file);
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->SetDirectoryElPolicy(user, EL2_KEY, vec), -ENOENT);
KeyManager::GetInstance()->userEl2Key_[user] = elKey;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_CALL(*fscryptControlMock_, LoadAndSetPolicy(_, _)).WillOnce(Return(0));
@ -1328,7 +1347,7 @@ HWTEST_F(KeyManagerTest, KeyManager_SetDirectoryElPolicy_003, TestSize.Level1)
KeyManager::GetInstance()->userEl2Key_[user] = elKey;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_EQ(KeyManager::GetInstance()->SetDirectoryElPolicy(user, EL3_KEY, vec), -ENOENT);
KeyManager::GetInstance()->userEl3Key_[user] = elKey;
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_CALL(*fscryptControlMock_, LoadAndSetPolicy(_, _)).WillOnce(Return(0));
@ -1552,34 +1571,6 @@ HWTEST_F(KeyManagerTest, KeyManager_ProcUpgradeKey_002, TestSize.Level1)
GTEST_LOG_(INFO) << "KeyManager_ProcUpgradeKey_0200 end";
}
/**
* @tc.name: KeyManager_InitGlobalUserKeys_001
* @tc.desc: Verify the KeyManager InitGlobalUserKeys function.
* @tc.type: FUNC
* @tc.require: SR000H0CM9
*/
HWTEST_F(KeyManagerTest, KeyManager_InitGlobalUserKeys_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "KeyManager_InitGlobalUserKeys_0100 start";
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(false));
auto ret = KeyManager::GetInstance()->InitGlobalUserKeys();
EXPECT_EQ(ret, 0);
EXPECT_CALL(*fscryptControlMock_, GetFscryptVersionFromPolicy()).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*keyControlMock_, KeyCtrlGetFscryptVersion(_)).WillOnce(Return(FSCRYPT_V2));
EXPECT_CALL(*fscryptControlMock_, KeyCtrlHasFscryptSyspara()).WillOnce(Return(true));
EXPECT_CALL(*baseKeyMock_, InitKey(_)).WillOnce(Return(true));
#ifdef USER_CRYPTO_MIGRATE_KEY
EXPECT_CALL(*baseKeyMock_, StoreKey(_, _)).WillOnce(Return(false));
#else
EXPECT_CALL(*baseKeyMock_, StoreKey(_)).WillOnce(Return(false));
#endif
EXPECT_CALL(*baseKeyMock_, ClearKey(_)).WillOnce(Return(true));
ret = KeyManager::GetInstance()->InitGlobalUserKeys();
EXPECT_NE(ret, 0);
GTEST_LOG_(INFO) << "KeyManager_InitGlobalUserKeys_0100 end";
}
/**
* @tc.name: KeyManager_GenerateUserKeys_001
* @tc.desc: Verify the KeyManager GenerateUserKeys function.

View File

@ -59,7 +59,8 @@ bool FscryptKeyV1Ext::ChangePinCodeClassE(uint32_t userId, bool &isFbeSupport)
return IFscryptKeyV1Ext::fscryptKeyV1ExtMock->ChangePinCodeClassE(userId, isFbeSupport);
}
bool FscryptKeyV1Ext::ReadClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length, bool &isFbeSupport)
bool FscryptKeyV1Ext::ReadClassE(uint32_t status, std::unique_ptr<uint8_t[]> &classEBuffer, uint32_t length,
bool &isFbeSupport)
{
return IFscryptKeyV1Ext::fscryptKeyV1ExtMock->ReadClassE(status, classEBuffer, length, isFbeSupport);
}

View File

@ -27,7 +27,8 @@ public:
virtual ~IFscryptKeyV1Ext() = default;
virtual bool LockUeceExt(bool &isFbeSupport) = 0;
virtual bool LockUserScreenExt(uint32_t flag, uint32_t &elType) = 0;
virtual bool ReadClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length, bool &isFbeSupport) = 0;
virtual bool ReadClassE(uint32_t status, std::unique_ptr<uint8_t[]> &classEBuffer, uint32_t length,
bool &isFbeSupport) = 0;
virtual bool WriteClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length) = 0;
virtual bool ChangePinCodeClassE(uint32_t userId, bool &isFbeSupport) = 0;
virtual bool AddClassE(bool &isNeedEncryptClassE, bool &isSupport, uint32_t status) = 0;
@ -43,7 +44,7 @@ class FscryptKeyV1ExtMock : public IFscryptKeyV1Ext {
public:
MOCK_METHOD1(LockUeceExt, bool(bool &));
MOCK_METHOD2(LockUserScreenExt, bool(uint32_t, uint32_t &));
MOCK_METHOD4(ReadClassE, bool(uint32_t, uint8_t *, uint32_t, bool &));
MOCK_METHOD4(ReadClassE, bool(uint32_t, std::unique_ptr<uint8_t[]> &, uint32_t, bool &));
MOCK_METHOD3(WriteClassE, bool(uint32_t, uint8_t *, uint32_t));
MOCK_METHOD2(ChangePinCodeClassE, bool(uint32_t, bool &));
MOCK_METHOD3(AddClassE, bool(bool &, bool &, uint32_t));

View File

@ -186,11 +186,14 @@ int DiskInfo::ReadPartition()
LOGE("Invaild maxVolumes: %{public}d", maxVolumes);
return E_ERR;
}
int res = Destroy();
if (res != E_OK) {
LOGE("Destroy failed in ReadPartition");
}
std::vector<std::string> cmd;
std::vector<std::string> output;
std::vector<std::string> lines;
int res;
cmd.push_back(SGDISK_PATH);
cmd.push_back(SGDISK_DUMP_CMD);
@ -207,12 +210,12 @@ int DiskInfo::ReadPartition()
lines.push_back(tmp);
}
std::vector<std::string> hmfsLines;
if (lines.size() > MIN_LINES) {
auto userdataIt = std::find_if(lines.begin(), lines.end(), [](const std::string &str) {
return str.find("userdata") != std::string::npos;
});
if (userdataIt != lines.end()) {
std::vector<std::string> hmfsLines;
hmfsLines.push_back(lines.front());
hmfsLines.push_back(*userdataIt);
status = sScan;
@ -225,8 +228,8 @@ int DiskInfo::ReadPartition()
bool DiskInfo::CreateMBRVolume(int32_t type, dev_t dev)
{
// FAT16 || NTFS/EXFAT || W95 FAT32 || W95 FAT32 || W95 FAT16 || EFI FAT32
if (type == 0x06 || type == 0x07 || type == 0x0b || type == 0x0c || type == 0x0e || type == 0x1b) {
// FAT16 || NTFS/EXFAT || W95 FAT32 || W95 FAT32 || W95 FAT16 || EFI FAT32 || EXT 2/3/4
if (type == 0x06 || type == 0x07 || type == 0x0b || type == 0x0c || type == 0x0e || type == 0x1b || type == 0x83) {
if (CreateVolume(dev) == E_OK) {
return true;
}

View File

@ -71,7 +71,7 @@ void DiskManager::HandleDiskEvent(NetlinkData *data)
break;
}
case NetlinkData::Actions::CHANGE: {
ChangeDisk(device);
ChangeDisk(device, data);
LOGI("Handle Disk Change Event");
break;
}
@ -128,18 +128,25 @@ void DiskManager::CreateDisk(std::shared_ptr<DiskInfo> &diskInfo)
LOGE("Create DiskInfo failed");
return;
}
disk_.push_back(diskInfo);
}
void DiskManager::ChangeDisk(dev_t device)
void DiskManager::ChangeDisk(dev_t device, NetlinkData *data)
{
for (auto &diskInfo : disk_) {
if ((diskInfo != nullptr) && (diskInfo->GetDevice() == device)) {
diskInfo->ReadMetadata();
diskInfo->ReadPartition();
return;
}
}
auto diskInfo = MatchConfig(data);
if (diskInfo == nullptr) {
LOGI("Can't match config, devPath is %{public}s", data->GetDevpath().c_str());
} else {
CreateDisk(diskInfo);
LOGI("Handle Disk Add Event");
}
}
void DiskManager::DestroyDisk(dev_t device)

View File

@ -197,13 +197,13 @@ HWTEST_F(DiskManagerTest, Storage_Service_DiskManagerTest_ChangeDisk_001, TestSi
\0DEVPATH=/devices/platform/fe2b0000.dwmmc/*\0SUBSYSTEM=input\0SEQNUM=1064\0\
\0PHYSDEVPATH=/devices/pci0000:00/0000:00:1d.1/usb2/2?2/2?2:1.0\0\
\0PHYSDEVBUS=usb\0PHYSDEVDRIVER=usbhid\0MAJOR=13\0MINOR=34\0"};
auto data = std::make_unique<NetlinkData>();
data->Decode(msg);
unsigned int major = std::stoi(data->GetParam("MAJOR"));
unsigned int minor = std::stoi(data->GetParam("MINOR"));
auto nlData = std::make_unique<NetlinkData>();
nlData->Decode(msg);
NetlinkData *data = nlData.get();
unsigned int major = (unsigned int)std::stoi(data->GetParam("MAJOR"));
unsigned int minor = (unsigned int)std::stoi(data->GetParam("MINOR"));
dev_t device = makedev(major, minor);
diskManager->ChangeDisk(device);
diskManager->ChangeDisk(device, data);
GTEST_LOG_(INFO) << "Storage_Service_DiskManagerTest_ChangeDisk_001 end";
}

View File

@ -12,30 +12,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include <sys/xattr.h>
#include "file_sharing/acl.h"
#include "storage_service_log.h"
#include "utils/file_utils.h"
#include "file_sharing/file_sharing.h"
namespace OHOS {
namespace StorageDaemon {
namespace {
const std::string FSCRYPT_EL1_PUBLIC = "/data/service/el1/public";
const std::string STORAGE_DAEMON_DIR = FSCRYPT_EL1_PUBLIC + "/storage_daemon";
const std::string FILE_SHARING_DIR = STORAGE_DAEMON_DIR + "/share";
const std::string PUBLIC_DIR = FILE_SHARING_DIR + "/public";
constexpr mode_t STORAGE_DAEMON_DIR_MODE = 0711;
constexpr mode_t FILE_SHARING_DIR_MODE = 0750;
constexpr mode_t PUBLIC_DIR_MODE = 02770;
constexpr uid_t FILE_MANAGER_UID = 1006;
constexpr gid_t FILE_MANAGER_GID = 1006;
constexpr uid_t ROOT_UID = 0;
constexpr gid_t ROOT_GID = 0;
}
int SetupFileSharingDir()
{
if (!IsDir(FSCRYPT_EL1_PUBLIC)) {
@ -43,37 +23,102 @@ int SetupFileSharingDir()
return -1;
}
bool success = PrepareDir(STORAGE_DAEMON_DIR, STORAGE_DAEMON_DIR_MODE,
ROOT_UID, ROOT_GID);
if (!success) {
LOGE("Failed to properly set up directory of storage daemon");
std::string fsShareParam = GetFileShareDefineParameter();
if (PrepareFileSharingDir(fsShareParam) != 0) {
LOGE("Failed to prepare file sharing directory of storage daemon");
return -1;
}
success = PrepareDir(FILE_SHARING_DIR, FILE_SHARING_DIR_MODE,
FILE_MANAGER_UID, FILE_MANAGER_GID);
return SetupDirAcl(fsShareParam);
}
int PrepareFileSharingDir(const std::string &fsShareParam)
{
bool success = PrepareDir(STORAGE_DAEMON_EL1_DIR, STORAGE_DAEMON_DIR_MODE, ROOT_UID, ROOT_GID);
if (!success) {
LOGE("Failed to properly set up directory of file sharing");
LOGE("Prepare directory of storage daemon failed, path = %{public}s", STORAGE_DAEMON_EL1_DIR.c_str());
return -1;
}
success = PrepareDir(PUBLIC_DIR, PUBLIC_DIR_MODE,
FILE_MANAGER_UID, FILE_MANAGER_GID);
if (!success) {
LOGE("Failed to properly set up directory of public file sharing");
return -1;
if (fsShareParam == TOB_SCENE || fsShareParam == TOD_SCENE) {
success = PrepareDir(SHARE_TOB_DIR, SHARE_TOB_DIR_MODE, SHARE_TOB_UID, SHARE_TOB_GID);
if (!success) {
LOGE("Prepare directory for path = %{public}s failed, fsShareParam = %{public}s",
SHARE_TOB_DIR.c_str(), fsShareParam.c_str());
return -1;
}
}
/* Skip setting default ACL if it's been done */
if (getxattr(PUBLIC_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) > 0) {
return 0;
if (fsShareParam == TOC_SCENE || fsShareParam == TOD_SCENE) {
success = PrepareDir(FILE_SHARING_DIR, FILE_SHARING_DIR_MODE, FILE_MANAGER_UID, FILE_MANAGER_GID);
if (!success) {
LOGE("Prepare directory for path = %{public}s failed, fsShareParam = %{public}s",
FILE_SHARING_DIR.c_str(), fsShareParam.c_str());
return -1;
}
success = PrepareDir(PUBLIC_DIR, PUBLIC_DIR_MODE, FILE_MANAGER_UID, FILE_MANAGER_GID);
if (!success) {
LOGE("Prepare directory for path = %{public}s failed, fsShareParam = %{public}s",
PUBLIC_DIR.c_str(), fsShareParam.c_str());
return -1;
}
}
LOGI("Prepare file sharing directory success");
return 0;
}
int SetupDirAcl(const std::string &fsShareParam)
{
if (fsShareParam == TOB_SCENE || fsShareParam == TOD_SCENE) {
if (getxattr(SHARE_TOB_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) <= 0) {
int rc = AclSetDefault(SHARE_TOB_DIR, "g:7017:rwx");
if (rc != 0) {
LOGE("Set acl for dir = %{public}s failed, fsShareParam = %{public}s",
SHARE_TOB_DIR.c_str(), fsShareParam.c_str());
return -1;
}
}
}
/*
* We have to use numeric id (1006) instead of character string ("file_manager")
* here due to the name-id mismatch in the in-house system.
*/
return AclSetDefault(PUBLIC_DIR, "g:1006:rwx");
if (fsShareParam == TOC_SCENE || fsShareParam == TOD_SCENE) {
if (getxattr(PUBLIC_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) <= 0) {
int rc = AclSetDefault(PUBLIC_DIR, "g:1006:rwx");
if (rc != 0) {
LOGE("Set acl for dir = %{public}s failed, fsShareParam = %{public}s",
PUBLIC_DIR.c_str(), fsShareParam.c_str());
return -1;
}
}
}
LOGI("Set acl success");
return 0;
}
std::string GetFileShareDefineParameter()
{
char fsShareParam[] = "2c_share";
int ret = GetParameter(SHARE_DIR_ENABLE_PARAMETER, "", fsShareParam, MAX_FS_DEFINE_VAL_LEN);
if (ret <= 0) {
LOGE("GetParameter name = %{public}s error, ret = %{public}d, return default value",
SHARE_DIR_ENABLE_PARAMETER, ret);
return TOC_SCENE;
}
if ((strlen(fsShareParam) == 0) || (strlen(fsShareParam) > MAX_FS_DEFINE_VAL_LEN)) {
LOGE("GetParameter success, but fsShareParam = %{public}s is invalid, return default value",
fsShareParam);
return TOC_SCENE;
}
if ((fsShareParam != TOB_SCENE) && (fsShareParam != TOC_SCENE) && (fsShareParam != TOD_SCENE)) {
LOGE("GetParameter success, but fsShareParam = %{public}s is not expected, return default value",
fsShareParam);
return TOC_SCENE;
}
LOGI("GetParameter success, fsShareParam = %{public}s", fsShareParam);
return fsShareParam;
}
} // namespace StorageDaemon
} // namespace OHOS

View File

@ -59,10 +59,44 @@ ohos_moduletest("SetAclTest") {
]
}
ohos_moduletest("FileSharingTest") {
module_out_path = "storage_service/storage_daemon"
defines = [
"STORAGE_LOG_TAG = \"StorageDaemon\"",
"LOG_DOMAIN = 0xD004301",
]
include_dirs = [
"../../file_sharing",
"../../include",
"${storage_service_common_path}/include",
]
sources = [
"../src/acl.cpp",
"../src/file_sharing.cpp",
"../src/setacl.cpp",
"filesharing_test.cpp",
]
deps = [
"${storage_daemon_path}:storage_common_utils",
"//third_party/googletest:gtest_main",
]
external_deps = [
"c_utils:utils",
"hilog:libhilog",
"init:libbegetutil",
]
}
group("file_sharing_test") {
testonly = true
deps = [
":AclTest",
":FileSharingTest",
":SetAclTest",
]
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <sys/xattr.h>
#include "file_sharing/acl.h"
#include "file_sharing/file_sharing.h"
#include "parameter.h"
#include "utils/file_utils.h"
using namespace testing::ext;
using namespace OHOS::StorageDaemon;
namespace {
class FileSharingTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void FileSharingTest::SetUpTestCase(void)
{
// input testsuit setup stepsetup invoked before all testcases
}
void FileSharingTest::TearDownTestCase(void)
{
// input testsuit teardown stepteardown invoked after all testcases
}
void FileSharingTest::SetUp(void)
{
// input testcase setup stepsetup invoked before each testcases
}
void FileSharingTest::TearDown(void)
{
// input testcase teardown stepteardown invoked after each testcases
}
/**
* @tc.name: FileSharingTest_001
* @tc.desc: Verify that SetupFile() works as expected
* @tc.type: FUNC
*/
HWTEST_F(FileSharingTest, file_sharing_test_001, TestSize.Level1)
{
GTEST_LOG_(INFO) << "FileSharingTest_001 starts";
int rc = PrepareFileSharingDir(TOB_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(IsDir(SHARE_TOB_DIR));
rc = SetupDirAcl(TOB_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(getxattr(SHARE_TOB_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) > 0);
EXPECT_TRUE(RmDirRecurse(SHARE_TOB_DIR));
GTEST_LOG_(INFO) << "FileSharingTest_001 ends";
}
/**
* @tc.name: FileSharingTest_002
* @tc.desc: Verify that SetupFile() works as expected
* @tc.type: FUNC
*/
HWTEST_F(FileSharingTest, file_sharing_test_002, TestSize.Level1)
{
GTEST_LOG_(INFO) << "FileSharingTest_002 starts";
int rc = PrepareFileSharingDir(TOC_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(IsDir(PUBLIC_DIR));
EXPECT_TRUE(IsDir(FILE_SHARING_DIR));
rc = SetupDirAcl(TOC_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(getxattr(PUBLIC_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) > 0);
EXPECT_TRUE(RmDirRecurse(PUBLIC_DIR));
EXPECT_TRUE(RmDirRecurse(FILE_SHARING_DIR));
GTEST_LOG_(INFO) << "FileSharingTest_002 ends";
}
/**
* @tc.name: FileSharingTest_003
* @tc.desc: Verify that SetupFile() works as expected
* @tc.type: FUNC
*/
HWTEST_F(FileSharingTest, file_sharing_test_003, TestSize.Level1)
{
GTEST_LOG_(INFO) << "FileSharingTest_003 starts";
int rc = PrepareFileSharingDir(TOD_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(IsDir(SHARE_TOB_DIR));
EXPECT_TRUE(IsDir(PUBLIC_DIR));
EXPECT_TRUE(IsDir(FILE_SHARING_DIR));
rc = SetupDirAcl(TOD_SCENE);
EXPECT_EQ(rc, 0);
EXPECT_TRUE(getxattr(SHARE_TOB_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) > 0);
EXPECT_TRUE(getxattr(PUBLIC_DIR.c_str(), ACL_XATTR_DEFAULT, nullptr, 0) > 0);
EXPECT_TRUE(RmDirRecurse(SHARE_TOB_DIR));
EXPECT_TRUE(RmDirRecurse(PUBLIC_DIR));
EXPECT_TRUE(RmDirRecurse(FILE_SHARING_DIR));
GTEST_LOG_(INFO) << "FileSharingTest_003 ends";
}
}

View File

@ -30,6 +30,7 @@ const uint32_t USER_UNLOCK = 0x2;
const uint32_t USER_ADD_AUTH = 0x0;
const uint32_t USER_CHANGE_AUTH = 0x1;
const std::string SUFFIX_NEED_UPDATE = "/need_update";
const std::string SUFFIX_NEED_RESTORE = "/need_restore";
const std::vector<uint8_t> NULL_SECRET = { '!' };
class BaseKey : public std::enable_shared_from_this<BaseKey> {
public:
@ -67,6 +68,8 @@ public:
void WipingActionDir(std::string &path);
bool UpgradeKeys();
bool GetOriginKey(KeyBlob &originKey);
void SetOriginKey(KeyBlob &originKey);
KeyInfo keyInfo_;
std::string GetDir() const
{

View File

@ -53,10 +53,12 @@ public:
static int LockScreenToKernel(uint32_t userId);
static int UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint32_t size);
static int ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status,
uint8_t *eBuffer, uint32_t length, bool &isFbeSupport);
std::unique_ptr<uint8_t[]> &eBuffer, uint32_t length, bool &isFbeSupport);
static int WriteESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uint8_t *eBuffer, uint32_t length);
static bool IsMspReady();
static int GetStatus();
static int UnlockSendSecret(uint32_t status, uint32_t bufferSize, uint32_t length, uint8_t *eBuffer,
uint8_t *opseBuffer);
static int InstallEL5KeyToKernel(uint32_t userIdSingle, uint32_t userIdDouble, uint8_t flag,
bool &isSupport, bool &isNeedEncryptClassE);
static int DeleteClassEPinCode(uint32_t userIdSingle, uint32_t userIdDouble);

View File

@ -52,7 +52,7 @@ private:
bool InstallEceSeceKeyToKeyring(uint32_t sdpClass);
bool UninstallKeyToKeyring();
FscryptKeyV1Ext fscryptV1Ext;
bool InstallKeyForAppKeyToKeyring(uint32_t *keyId);
bool InstallKeyForAppKeyToKeyring(KeyBlob &appKey);
bool UninstallKeyForAppKeyToKeyring(const std::string keyId);
bool GenerateAppKeyDesc(KeyBlob appKey);
};

View File

@ -38,7 +38,7 @@ public:
bool AddClassE(bool &isNeedEncryptClassE, bool &isSupport, uint32_t status);
bool DeleteClassEPinCode(uint32_t userId);
bool ChangePinCodeClassE(uint32_t userId, bool &isFbeSupport);
bool ReadClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length, bool &isFbeSupport);
bool ReadClassE(uint32_t status, std::unique_ptr<uint8_t[]> &classEBuffer, uint32_t length, bool &isFbeSupport);
bool WriteClassE(uint32_t status, uint8_t *classEBuffer, uint32_t length);
bool GenerateAppkey(uint32_t userId, uint32_t appUid, std::unique_ptr<uint8_t[]> &keyId, uint32_t size);
bool LockUeceExt(bool &isFbeSupport);

View File

@ -100,8 +100,8 @@ private:
IamClient(const IamClient &) = delete;
IamClient &operator=(const IamClient &) = delete;
SecUserInfoState secUserInfoState_;
UserSecStatus secureUidStatus_;
SecUserInfoState secUserInfoState_ = SEC_USER_INFO_FAILED;
UserSecStatus secureUidStatus_ = FAILED;
std::condition_variable iamCon_;
std::mutex iamMutex_;
};

View File

@ -91,7 +91,7 @@ private:
private:
constexpr static mode_t DEFAULT_DIR_PERM = 0700;
constexpr static mode_t DEFAULT_WRITE_FILE_PERM = 0666;
constexpr static mode_t DEFAULT_WRITE_FILE_PERM = 0644;
constexpr static uint32_t MAX_FILE_NUM = 5;
};
} // namespace StorageDaemon

View File

@ -0,0 +1,31 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef OHOS_KEY_CRYPTO_UTILS_H
#define OHOS_KEY_CRYPTO_UTILS_H
#include <string>
namespace OHOS {
namespace StorageService {
class KeyCryptoUtils {
public:
static void ForceLockUserScreen();
};
} // namespace StorageService
} // namespace OHOS
#endif // OHOS_KEY_CRYPTO_UTILS_H

View File

@ -63,6 +63,11 @@ public:
KeyType type);
#endif
int UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText);
int ActiveUserKey(unsigned int user, const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret);
int ActiveCeSceSeceUserKey(unsigned int user, KeyType type, const std::vector<uint8_t> &token,
@ -107,7 +112,7 @@ private:
int InitUserElkeyStorageDir(void);
bool HasElkey(uint32_t userId, KeyType type);
int DoDeleteUserKeys(unsigned int user);
int DoDeleteUserCeEceSeceKeys(unsigned int user, const std::string USER_DIR,
int DoDeleteUserCeEceSeceKeys(unsigned int user, const std::string userDir,
std::map<unsigned int, std::shared_ptr<BaseKey>> &userElKey_);
int UpgradeKeys(const std::vector<FileList> &dirInfo);
int UpdateESecret(unsigned int user, struct UserTokenSecret &tokenSecret);
@ -128,11 +133,16 @@ private:
int CheckAndDeleteEmptyEl5Directory(std::string keyDir, unsigned int user);
bool GetUserDelayHandler(uint32_t userId, std::shared_ptr<DelayHandler> &delayHandler);
bool IsUeceSupport();
int IsUeceSupportWithErrno();
bool IsUserCeDecrypt(uint32_t userId);
bool UnlockEceSece(uint32_t user, const std::vector<uint8_t> &token, const std::vector<uint8_t> &secret, int &ret);
bool UnlockUece(uint32_t user, const std::vector<uint8_t> &token, const std::vector<uint8_t> &secret, int &ret);
void CheckAndClearTokenInfo(uint32_t user);
#ifdef EL5_FILEKEY_MANAGER
int GenerateAndLoadAppKeyInfo(uint32_t userId, const std::vector<std::pair<int, std::string>> &keyInfo);
#endif
std::map<unsigned int, std::shared_ptr<BaseKey>> userEl1Key_;
std::map<unsigned int, std::shared_ptr<BaseKey>> userEl2Key_;
std::map<unsigned int, std::shared_ptr<BaseKey>> userEl3Key_;

View File

@ -0,0 +1,106 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STORAGE_DAEMON_CRYPTO_KEY_RECOVER_MANAGER_H
#define STORAGE_DAEMON_CRYPTO_KEY_RECOVER_MANAGER_H
#include <vector>
#include "fbex.h"
#include "key_blob.h"
#include "libfscrypt/key_control.h"
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
#include "tee_client_api.h"
#endif
namespace OHOS {
namespace StorageDaemon {
const int RND_AND_KEY2_LEN = 64;
const int RND_AND_KEY2_NUMS = 6; // 0-Device EL1, 1-Global User EL1, 2-User EL1, 3-User EL2, 4-User EL3, 5-User EL4
const int AUTH_TOKEN_LEN = 280;
const uint32_t ELX_TYPE_ARR[] = { TYPE_GLOBAL_EL1, USERID_GLOBAL_EL1, TYPE_EL1,
TYPE_EL2, TYPE_EL3, TYPE_EL4 };
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
static TEEC_UUID recoverTaUuid = { 0x9449c83f, 0x2fa6, 0x485b, { 0x83, 0xff, 0x77, 0x14, 0x4f, 0xff, 0x66, 0xb4 } };
#endif
struct CreateRecoverKeyStr {
uint32_t userType;
uint32_t userId;
uint32_t authTokenLen;
uint8_t authToken[AUTH_TOKEN_LEN];
uint8_t rndToTee[RND_AND_KEY2_NUMS][RND_AND_KEY2_LEN];
};
struct SetRecoverKeyStr {
uint8_t rndFromTee[RND_AND_KEY2_NUMS][RND_AND_KEY2_LEN];
uint8_t key2FromTee[RND_AND_KEY2_NUMS][RND_AND_KEY2_LEN];
};
enum TaCmdId {
RK_CMD_ID_GEN_RECOVERY_KEY = 0x1000A003,
RK_CMD_ID_DECRYPT_CLASS_KEY = 0x1000A008,
};
const size_t DEVICE_EL1 = 0;
const size_t GLOBAL_USER_EL1 = 1;
const size_t USER_EL1 = 2;
const size_t USER_EL2 = 3;
const size_t USER_EL3 = 4;
const size_t USER_EL4 = 5;
class RecoveryManager {
public:
static RecoveryManager &GetInstance()
{
static RecoveryManager instance;
return instance;
}
int CreateRecoverKey(uint32_t userId,
uint32_t userType,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret,
const std::vector<KeyBlob> &originIv);
int SetRecoverKey(const std::vector<uint8_t> &key);
private:
RecoveryManager();
~RecoveryManager();
RecoveryManager(const RecoveryManager &) = delete;
RecoveryManager &operator=(const RecoveryManager &) = delete;
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
bool OpenSession(TEEC_Context &context, TEEC_Session &session);
void CloseSession(TEEC_Context &context, TEEC_Session &session);
#endif
int SetRecoverKeyToTee(const std::vector<uint8_t> &key, SetRecoverKeyStr &setRecoverKeyStr);
bool GenerateKeyDesc(const KeyBlob &key2Blob, KeyBlob &originKey2);
bool InstallKeyDescToKeyring(size_t keyType, const KeyBlob &key2Blob, const KeyBlob &keyDesc);
bool InstallDeCe(const KeyBlob &key2Blob, const KeyBlob &keyDesc);
bool InstallEceSece(uint32_t sdpClass, const KeyBlob &key2Blob, const KeyBlob &keyDesc);
#ifdef RECOVER_KEY_TEE_ENVIRONMENT
TEEC_UUID *recoverUuid_ = &recoverTaUuid;
#endif
bool isSessionOpened;
};
} // namespace StorageDaemon
} // namespace OHOS
#endif //STORAGE_DAEMON_CRYPTO_KEY_RECOVER_MANAGER_H

View File

@ -37,7 +37,7 @@ public:
virtual ~DiskManager();
void CreateDisk(std::shared_ptr<DiskInfo> &diskInfo);
void DestroyDisk(dev_t device);
void ChangeDisk(dev_t device);
void ChangeDisk(dev_t device, NetlinkData *data);
std::shared_ptr<DiskInfo> GetDisk(dev_t device);
void HandleDiskEvent(NetlinkData *data);
int32_t HandlePartition(std::string diskId);

View File

@ -15,9 +15,42 @@
#ifndef OHOS_STORAGE_DAEMON_FILE_SHARING_H
#define OHOS_STORAGE_DAEMON_FILE_SHARING_H
#include <string>
#include <sys/xattr.h>
#include "file_sharing/acl.h"
#include "parameter.h"
#include "storage_service_log.h"
#include "utils/file_utils.h"
namespace OHOS {
namespace StorageDaemon {
const std::string FSCRYPT_EL1_PUBLIC = "/data/service/el1/public";
const std::string STORAGE_DAEMON_EL1_DIR = FSCRYPT_EL1_PUBLIC + "/storage_daemon";
const std::string FILE_SHARING_DIR = STORAGE_DAEMON_EL1_DIR + "/share";
const std::string PUBLIC_DIR = FILE_SHARING_DIR + "/public";
const std::string SHARE_TOB_DIR = STORAGE_DAEMON_EL1_DIR + "/share_tob";
const std::string TOB_SCENE = "2b_share";
const std::string TOC_SCENE = "2c_share";
const std::string TOD_SCENE = "2c2b_share";
static const char *SHARE_DIR_ENABLE_PARAMETER = "const.file_transfer.fs_share_dir_define";
constexpr int32_t MAX_FS_DEFINE_VAL_LEN = 16;
constexpr mode_t STORAGE_DAEMON_DIR_MODE = 0711;
constexpr mode_t FILE_SHARING_DIR_MODE = 0750;
constexpr mode_t PUBLIC_DIR_MODE = 02770;
constexpr mode_t SHARE_TOB_DIR_MODE = 0770;
constexpr uid_t FILE_MANAGER_UID = 1006;
constexpr gid_t FILE_MANAGER_GID = 1006;
constexpr uid_t ROOT_UID = 0;
constexpr gid_t ROOT_GID = 0;
constexpr uid_t SHARE_TOB_UID = 7017;
constexpr gid_t SHARE_TOB_GID = 7017;
int SetupFileSharingDir();
int PrepareFileSharingDir(const std::string &fsShareParam);
int SetupDirAcl(const std::string &fsShareParam);
std::string GetFileShareDefineParameter();
} // namespace StorageDaemon
} // namespace OHOS

View File

@ -55,6 +55,11 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret) = 0;
virtual int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText) = 0;
virtual int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) = 0;

View File

@ -59,6 +59,11 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret) override;
virtual int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText) override;
virtual int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) override;

View File

@ -40,6 +40,7 @@ namespace StorageDaemon {
CREATE_USER_KEYS,
DELETE_USER_KEYS,
UPDATE_USER_AUTH,
UPDATE_USER_AUTH_RECOVER_KEY,
ACTIVE_USER_KEY,
INACTIVE_USER_KEY,
UPDATE_KEY_CONTEXT,

View File

@ -48,6 +48,11 @@ public:
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &oldSecret,
const std::vector<uint8_t> &newSecret) override;
virtual int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText) override;
virtual int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) override;

View File

@ -58,6 +58,7 @@ private:
int32_t HandleGenerateUserKeys(MessageParcel &data, MessageParcel &reply);
int32_t HandleDeleteUserKeys(MessageParcel &data, MessageParcel &reply);
int32_t HandleUpdateUserAuth(MessageParcel &data, MessageParcel &reply);
int32_t HandleUpdateUseAuthWithRecoveryKey(MessageParcel &data, MessageParcel &reply);
int32_t HandleActiveUserKey(MessageParcel &data, MessageParcel &reply);
int32_t HandleInactiveUserKey(MessageParcel &data, MessageParcel &reply);
int32_t HandleUpdateKeyContext(MessageParcel &data, MessageParcel &reply);

View File

@ -31,7 +31,7 @@ public:
virtual int UninstallOrLockUserKeyToKernel(uint32_t, uint32_t, uint8_t *, uint32_t, bool) = 0;
virtual int LockScreenToKernel(uint32_t userId) = 0;
virtual int UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint32_t size) = 0;
virtual int ReadESecretToKernel(UserIdToFbeStr &, uint32_t, uint8_t *, uint32_t, bool &) = 0;
virtual int ReadESecretToKernel(UserIdToFbeStr &, uint32_t, std::unique_ptr<uint8_t[]> &, uint32_t, bool &) = 0;
virtual int WriteESecretToKernel(UserIdToFbeStr &, uint32_t, uint8_t *, uint32_t length) = 0;
virtual bool IsMspReady() = 0;
virtual int GetStatus() = 0;
@ -51,7 +51,7 @@ public:
MOCK_METHOD5(UninstallOrLockUserKeyToKernel, int(uint32_t, uint32_t, uint8_t *, uint32_t, bool));
MOCK_METHOD1(LockScreenToKernel, int(uint32_t userId));
MOCK_METHOD4(UnlockScreenToKernel, int(uint32_t userId, uint32_t type, uint8_t *iv, uint32_t size));
MOCK_METHOD5(ReadESecretToKernel, int(UserIdToFbeStr &, uint32_t, uint8_t *, uint32_t, bool &));
MOCK_METHOD5(ReadESecretToKernel, int(UserIdToFbeStr &, uint32_t, std::unique_ptr<uint8_t[]> &, uint32_t, bool &));
MOCK_METHOD4(WriteESecretToKernel, int(UserIdToFbeStr &, uint32_t, uint8_t *, uint32_t length));
MOCK_METHOD0(IsMspReady, bool());
MOCK_METHOD0(GetStatus, int());

View File

@ -0,0 +1,40 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STORAGE_DAEMON_FBEX_MOCK_H
#define STORAGE_DAEMON_FBEX_MOCK_H
#include <gmock/gmock.h>
#include <memory>
#include "mount_manager.h"
namespace OHOS {
namespace StorageDaemon {
class IMountManagerMoc {
public:
virtual ~IMountManagerMoc() = default;
public:
virtual bool CheckMountFileByUser(int32_t userId) = 0;
public:
static inline std::shared_ptr<IMountManagerMoc> mountManagerMoc = nullptr;
};
class MountManagerMoc : public IMountManagerMoc {
public:
MOCK_METHOD1(CheckMountFileByUser, bool(int32_t userId));
};
}
}
#endif

View File

@ -0,0 +1,72 @@
/*
* Copyright (C) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef STORAGE_DAEMON_USER_IDM_CLIENT_MOCK_H
#define STORAGE_DAEMON_USER_IDM_CLIENT_MOCK_H
#include <gmock/gmock.h>
#include <memory>
#include "user_idm_client.h"
#include "user_idm_client_impl.h"
namespace OHOS {
namespace StorageDaemon {
using namespace OHOS::UserIam::UserAuth;
class IUserIdmClientMoc {
public:
virtual ~IUserIdmClientMoc() = default;
public:
virtual std::vector<uint8_t> OpenSession(int32_t userId) = 0;
virtual void CloseSession(int32_t userId) = 0;
virtual void AddCredential(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
virtual void UpdateCredential(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
virtual int32_t Cancel(int32_t userId) = 0;
virtual void DeleteCredential(int32_t userId, uint64_t credentialId, const std::vector<uint8_t> &authToken,
const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
virtual void DeleteUser(int32_t userId, const std::vector<uint8_t> &authToken,
const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
virtual int32_t EraseUser(int32_t userId, const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
virtual int32_t GetCredentialInfo(int32_t userId, AuthType authType,
const std::shared_ptr<GetCredentialInfoCallback> &callback) = 0;
virtual int32_t GetSecUserInfo(int32_t userId, const std::shared_ptr<GetSecUserInfoCallback> &callback) = 0;
virtual void ClearRedundancyCredential(const std::shared_ptr<UserIdmClientCallback> &callback) = 0;
public:
static inline std::shared_ptr<IUserIdmClientMoc> userIdmClientMoc = nullptr;
};
class UserIdmClientMoc : public IUserIdmClientMoc {
public:
MOCK_METHOD1(OpenSession, std::vector<uint8_t>(int32_t userId));
MOCK_METHOD1(CloseSession, void(int32_t userId));
MOCK_METHOD3(AddCredential, void(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback));
MOCK_METHOD3(UpdateCredential, void(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback));
MOCK_METHOD1(Cancel, int32_t(int32_t userId));
MOCK_METHOD4(DeleteCredential, void(int32_t userId, uint64_t credentialId,
const std::vector<uint8_t> &authToken, const std::shared_ptr<UserIdmClientCallback> &callback));
MOCK_METHOD3(DeleteUser, void(int32_t userId, const std::vector<uint8_t> &authToken,
const std::shared_ptr<UserIdmClientCallback> &callback));
MOCK_METHOD2(EraseUser, int32_t(int32_t userId, const std::shared_ptr<UserIdmClientCallback> &callback));
MOCK_METHOD3(GetCredentialInfo, int32_t(int32_t userId, AuthType authType,
const std::shared_ptr<GetCredentialInfoCallback> &callback));
MOCK_METHOD2(GetSecUserInfo, int32_t(int32_t userId, const std::shared_ptr<GetSecUserInfoCallback> &callback));
MOCK_METHOD1(ClearRedundancyCredential, void(const std::shared_ptr<UserIdmClientCallback> &callback));
};
}
}
#endif

View File

@ -49,6 +49,7 @@ constexpr uid_t OID_DFS_SHARE = 3822;
constexpr uid_t OID_TEE = 6668;
constexpr uid_t OID_DEVICE_AUTH = 3333;
constexpr uid_t OID_HUKS = 3510;
constexpr uid_t OID_ASSET = 6226;
constexpr uid_t OID_DDMS = 3012;
constexpr uid_t OID_HWID = 7008;
constexpr uid_t OID_HEALTH_SPORT = 7259;
@ -57,6 +58,8 @@ constexpr uid_t OID_RSS = 1096;
constexpr uid_t OID_HIVIEW = 1201;
constexpr uid_t OID_PARENT_CONTROL = 7007;
constexpr uid_t OID_ACCOUNT = 3058;
constexpr uid_t OID_COLLABORATION_FWK = 5520;
constexpr uid_t OID_AV_SESSION = 6700;
constexpr uid_t USER_ID_BASE = 200000;
class MountManager final {

View File

@ -53,6 +53,10 @@ void ChownRecursion(const std::string &dir, uid_t uid, gid_t gid);
int IsSameGidUid(const std::string &dir, uid_t uid, gid_t gid);
void MoveFileManagerData(const std::string &filesPath);
void OpenSubFile(const std::string &path, std::vector<std::string> &dirInfo);
void DelTemp(const std::string &path);
bool IsTempFolder(const std::string &path, const std::string &sub);
bool DeleteFile(const std::string &path);
std::vector<std::string> Split(std::string str, std::string pattern);
}
}

View File

@ -54,11 +54,12 @@ private:
const std::string devPathDir_ = "/dev/block/%s";
const std::string mountPathDir_ = "/mnt/data/external/%s";
std::vector<std::string> supportMountType_ = { "ext2", "ext3", "ext4", "ntfs", "exfat", "vfat", "hmfs" };
std::vector<std::string> supportMountType_ = { "ext2", "ext3", "ext4", "ntfs", "exfat", "vfat", "hmfs", "f2fs" };
std::map<std::string, std::string> supportFormatType_ = {{"exfat", "mkfs.exfat"}, {"vfat", "newfs_msdos"}};
int32_t ReadMetadata();
int32_t DoMount4Ext(uint32_t mountFlags);
int32_t DoMount4Hmfs(uint32_t mountFlags);
int32_t DoMount4Ntfs(uint32_t mountFlags);
int32_t DoMount4Exfat(uint32_t mountFlags);
int32_t DoMount4OtherType(uint32_t mountFlags);

View File

@ -284,7 +284,9 @@ int32_t StorageDaemon::RestoreOneUserKey(int32_t userId, KeyType type)
PrepareUeceDir(userId);
}
if (userId < StorageService::START_APP_CLONE_USER_ID || userId > StorageService::MAX_APP_CLONE_USER_ID) {
(void)remove(elNeedRestorePath.c_str());
if (type != EL1_KEY) {
(void)remove(elNeedRestorePath.c_str());
}
}
if (type == EL4_KEY) {
UserManager::GetInstance()->CreateBundleDataDir(userId);
@ -344,29 +346,32 @@ int32_t StorageDaemon::PrepareUserDirs(int32_t userId, uint32_t flags)
int32_t StorageDaemon::DestroyUserDirs(int32_t userId, uint32_t flags)
{
int32_t errCode = 0;
//CRYPTO_FLAG_EL3 destroy el3, CRYPTO_FLAG_EL4 destroy el4
flags = flags | IStorageDaemon::CRYPTO_FLAG_EL3 | IStorageDaemon::CRYPTO_FLAG_EL4 | IStorageDaemon::CRYPTO_FLAG_EL5;
int32_t ret = UserManager::GetInstance()->DestroyUserDirs(userId, flags);
if (ret != E_OK) {
int32_t destroyUserRet = UserManager::GetInstance()->DestroyUserDirs(userId, flags);
if (destroyUserRet != E_OK) {
errCode = destroyUserRet;
LOGW("Destroy user %{public}d dirs failed, please check", userId);
StorageService::StorageRadar::GetInstance().RecordFuctionResult(
"DestroyUserDirs", BizScene::USER_MOUNT_MANAGER, BizStage::BIZ_STAGE_REMOVE_USER, "EL1", ret);
StorageService::StorageRadar::GetInstance().RecordFuctionResult("DestroyUserDirs", BizScene::USER_MOUNT_MANAGER,
BizStage::BIZ_STAGE_REMOVE_USER, "EL1", errCode);
AuditLog storageAuditLog = { false, "FAILED TO DestroyUserDirs", "DEL", "DestroyUserDirs", 1, "FAIL" };
HiAudit::GetInstance().Write(storageAuditLog);
}
#ifdef USER_CRYPTO_MANAGER
ret = KeyManager::GetInstance()->DeleteUserKeys(userId);
if (ret != E_OK) {
destroyUserRet = KeyManager::GetInstance()->DeleteUserKeys(userId);
if (destroyUserRet != E_OK) {
errCode = destroyUserRet;
LOGW("DeleteUserKeys failed, please check");
StorageService::StorageRadar::GetInstance().RecordFuctionResult(
"DeleteUserKeys", BizScene::USER_MOUNT_MANAGER, BizStage::BIZ_STAGE_REMOVE_USER, "EL1", ret);
"DeleteUserKeys", BizScene::USER_MOUNT_MANAGER, BizStage::BIZ_STAGE_REMOVE_USER, "EL1", errCode);
AuditLog storageAuditLog = { false, "FAILED TO DeleteUserKeys", "DEL", "DeleteUserKeys", 1, "FAIL" };
HiAudit::GetInstance().Write(storageAuditLog);
}
return ret;
return errCode;
#else
return ret;
return errCode;
#endif
}
@ -405,6 +410,16 @@ int32_t StorageDaemon::StopUser(int32_t userId)
int32_t StorageDaemon::CompleteAddUser(int32_t userId)
{
LOGI("CompleteAddUser enter.");
#ifdef USER_CRYPTO_MIGRATE_KEY
std::string elNeedRestorePath = GetNeedRestoreFilePathByType(userId, EL1_KEY);
if (elNeedRestorePath.empty() || !std::filesystem::exists(elNeedRestorePath)) {
return E_OK;
}
(void)remove(elNeedRestorePath.c_str());
LOGI("CompleteAddUser remove el1 needRestore flag");
StorageService::StorageRadar::GetInstance().RecordFuctionResult(
"CompleteAddUser", BizScene::USER_MOUNT_MANAGER, BizStage::BIZ_STAGE_GENERATE_USER_KEYS, "EL1", E_OK);
#endif
return E_OK;
}
@ -528,6 +543,20 @@ int32_t StorageDaemon::UpdateUserAuth(uint32_t userId, uint64_t secureUid,
#endif
}
int32_t StorageDaemon::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
LOGI("begin to UpdateUseAuthWithRecoveryKey");
#ifdef USER_CRYPTO_MANAGER
return KeyManager::GetInstance()->UpdateUseAuthWithRecoveryKey(authToken, newSecret, secureUid, userId, plainText);
#else
return E_OK;
#endif
}
#ifdef USER_CRYPTO_MIGRATE_KEY
int32_t StorageDaemon::PrepareUserDirsAndUpdateUserAuth(uint32_t userId, KeyType type,
const std::vector<uint8_t> &token, const std::vector<uint8_t> &secret)
@ -888,7 +917,7 @@ int32_t StorageDaemon::CreateRecoverKey(uint32_t userId,
{
LOGI("begin to CreateRecoverKey");
#ifdef USER_CRYPTO_MANAGER
return E_OK;
return KeyManager::GetInstance()->CreateRecoverKey(userId, userType, token, secret);
#else
return E_OK;
#endif
@ -898,7 +927,7 @@ int32_t StorageDaemon::SetRecoverKey(const std::vector<uint8_t> &key)
{
LOGI("begin to SetRecoverKey");
#ifdef USER_CRYPTO_MANAGER
return E_OK;
return KeyManager::GetInstance()->SetRecoverKey(key);
#else
return E_OK;
#endif

View File

@ -416,6 +416,47 @@ int32_t StorageDaemonProxy::UpdateUserAuth(uint32_t userId, uint64_t secureUid,
return reply.ReadInt32();
}
int32_t StorageDaemonProxy::UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
if (!data.WriteInterfaceToken(StorageDaemonProxy::GetDescriptor())) {
return E_WRITE_DESCRIPTOR_ERR;
}
if (!data.WriteUint32(userId)) {
return E_WRITE_PARCEL_ERR;
}
if (!data.WriteUint64(secureUid)) {
return E_WRITE_PARCEL_ERR;
}
if (!data.WriteUInt8Vector(authToken)) {
return E_WRITE_PARCEL_ERR;
}
if (!data.WriteUInt8Vector(newSecret)) {
return E_WRITE_PARCEL_ERR;
}
for (uint32_t i = 0; i < plainText.size(); i++) {
if (!data.WriteUInt8Vector(plainText[i])) {
return E_WRITE_PARCEL_ERR;
}
}
int err = SendRequest(static_cast<int32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH_RECOVER_KEY), data, reply,
option);
if (err != E_OK) {
return err;
}
return reply.ReadInt32();
}
int32_t StorageDaemonProxy::ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret)

View File

@ -58,6 +58,8 @@ StorageDaemonStub::StorageDaemonStub()
&StorageDaemonStub::HandleDeleteUserKeys;
opToInterfaceMap_[static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH)] =
&StorageDaemonStub::HandleUpdateUserAuth;
opToInterfaceMap_[static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH_RECOVER_KEY)] =
&StorageDaemonStub::HandleUpdateUseAuthWithRecoveryKey;
opToInterfaceMap_[static_cast<uint32_t>(StorageDaemonInterfaceCode::ACTIVE_USER_KEY)] =
&StorageDaemonStub::HandleActiveUserKey;
opToInterfaceMap_[static_cast<uint32_t>(StorageDaemonInterfaceCode::INACTIVE_USER_KEY)] =
@ -100,10 +102,8 @@ StorageDaemonStub::StorageDaemonStub()
&StorageDaemonStub::HandleSetRecoverKey;
}
int32_t StorageDaemonStub::OnRemoteRequest(uint32_t code,
MessageParcel &data,
MessageParcel &reply,
MessageOption &option)
int32_t StorageDaemonStub::OnRemoteRequest(uint32_t code, MessageParcel &data,
MessageParcel &reply, MessageOption &option)
{
if (data.ReadInterfaceToken() != GetDescriptor()) {
return E_PERMISSION_DENIED;
@ -127,10 +127,13 @@ int32_t StorageDaemonStub::OnRemoteRequest(uint32_t code,
case static_cast<uint32_t>(StorageDaemonInterfaceCode::CREATE_USER_KEYS):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::DELETE_USER_KEYS):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH_RECOVER_KEY):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::ACTIVE_USER_KEY):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::INACTIVE_USER_KEY):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::LOCK_USER_SCREEN):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UNLOCK_USER_SCREEN):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::CREATE_RECOVER_KEY):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::SET_RECOVER_KEY):
return OnRemoteRequestForUser(code, data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::LOCK_SCREEN_STATUS):
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_KEY_CONTEXT):
@ -198,6 +201,8 @@ int32_t StorageDaemonStub::OnRemoteRequestForUser(uint32_t code, MessageParcel &
return HandleDeleteUserKeys(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH):
return HandleUpdateUserAuth(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH_RECOVER_KEY):
return HandleUpdateUseAuthWithRecoveryKey(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::ACTIVE_USER_KEY):
return HandleActiveUserKey(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::INACTIVE_USER_KEY):
@ -206,6 +211,10 @@ int32_t StorageDaemonStub::OnRemoteRequestForUser(uint32_t code, MessageParcel &
return HandleLockUserScreen(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::UNLOCK_USER_SCREEN):
return HandleUnlockUserScreen(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::CREATE_RECOVER_KEY):
return HandleCreateRecoverKey(data, reply);
case static_cast<uint32_t>(StorageDaemonInterfaceCode::SET_RECOVER_KEY):
return HandleSetRecoverKey(data, reply);
default:
LOGE("Cannot response request %d: unknown tranction", code);
return E_SYS_ERR;
@ -457,6 +466,31 @@ int32_t StorageDaemonStub::HandleUpdateUserAuth(MessageParcel &data, MessageParc
return E_OK;
}
int32_t StorageDaemonStub::HandleUpdateUseAuthWithRecoveryKey(MessageParcel &data, MessageParcel &reply)
{
uint32_t userId = data.ReadUint32();
uint64_t secureUid = data.ReadUint64();
std::vector<uint8_t> token;
std::vector<uint8_t> newSecret;
data.ReadUInt8Vector(&token);
data.ReadUInt8Vector(&newSecret);
std::vector<std::vector<uint8_t>> plainText;
const int CKEY_NUMS = 6;
for (uint32_t i = 0; i < CKEY_NUMS; i++) {
std::vector<uint8_t> iv;
data.ReadUInt8Vector(&iv);
plainText.push_back(iv);
}
int err = UpdateUseAuthWithRecoveryKey(token, newSecret, secureUid, userId, plainText);
if (!reply.WriteInt32(err)) {
return E_WRITE_REPLY_ERR;
}
return E_OK;
}
int32_t StorageDaemonStub::HandleActiveUserKey(MessageParcel &data, MessageParcel &reply)
{
uint32_t userId = data.ReadUint32();

View File

@ -586,7 +586,7 @@ HWTEST_F(StorageDaemonProxyTest, StorageDaemonProxyTest_CreateRecoverKey_001, Te
EXPECT_CALL(*mock_, SendRequest(testing::_, testing::_, testing::_, testing::_))
.Times(1)
.WillOnce(testing::Invoke(mock_.GetRefPtr(), &StorageDaemonServiceMock::InvokeSendRequest));
int32_t ret = proxy_->CreateRecoverKey(USER_ID1, 10, {}, {});
int32_t ret = proxy_->CreateRecoverKey(USER_ID1, 100, {}, {});
ASSERT_TRUE(ret == E_OK);
ASSERT_TRUE(static_cast<int32_t>(StorageDaemonInterfaceCode::CREATE_RECOVER_KEY) == mock_->code_);

View File

@ -133,6 +133,15 @@ public:
return E_OK;
}
virtual int32_t UpdateUseAuthWithRecoveryKey(const std::vector<uint8_t> &authToken,
const std::vector<uint8_t> &newSecret,
uint64_t secureUid,
uint32_t userId,
std::vector<std::vector<uint8_t>> &plainText)
{
return E_OK;
}
virtual int32_t ActiveUserKey(uint32_t userId,
const std::vector<uint8_t> &token,
const std::vector<uint8_t> &secret) override

View File

@ -44,6 +44,8 @@ public:
MOCK_METHOD1(DeleteUserKeys, int32_t(uint32_t));
MOCK_METHOD5(UpdateUserAuth, int32_t(uint32_t, uint64_t, const std::vector<uint8_t> &,
const std::vector<uint8_t> &, const std::vector<uint8_t> &));
MOCK_METHOD5(UpdateUseAuthWithRecoveryKey, int32_t(const std::vector<uint8_t> &,
const std::vector<uint8_t> &, uint64_t, uint32_t, std::vector<std::vector<uint8_t>> &));
MOCK_METHOD3(ActiveUserKey, int32_t (uint32_t, const std::vector<uint8_t> &, const std::vector<uint8_t> &));
MOCK_METHOD1(InactiveUserKey, int32_t (uint32_t));
MOCK_METHOD1(UpdateKeyContext, int32_t (uint32_t));

View File

@ -49,6 +49,7 @@ namespace {
static_cast<int32_t>(StorageDaemonInterfaceCode::CREATE_USER_KEYS),
static_cast<int32_t>(StorageDaemonInterfaceCode::DELETE_USER_KEYS),
static_cast<int32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH),
static_cast<int32_t>(StorageDaemonInterfaceCode::UPDATE_USER_AUTH_RECOVER_KEY),
static_cast<int32_t>(StorageDaemonInterfaceCode::ACTIVE_USER_KEY),
static_cast<int32_t>(StorageDaemonInterfaceCode::INACTIVE_USER_KEY),
static_cast<int32_t>(StorageDaemonInterfaceCode::UPDATE_KEY_CONTEXT),

View File

@ -20,6 +20,8 @@
#include <mntent.h>
#include <unordered_map>
#include "directory_ex.h"
#include "crypto/app_clone_key_manager.h"
#include "ipc/istorage_daemon.h"
#include "ipc/storage_daemon.h"
@ -311,8 +313,17 @@ HWTEST_F(StorageDaemonTest, Storage_Manager_StorageDaemonTest_MountDfsDocs_001,
std::string relativePath = "account";
std::string networkId = "testnetworkid";
std::string deviceId = "testdevid";
std::string path = "/mnt/data/" + std::to_string(userId) + "/hmdfs/";
OHOS::ForceRemoveDirectory(path);
auto ret = storageDaemon_->MountDfsDocs(userId, relativePath, networkId, deviceId);
EXPECT_EQ(ret, E_PREPARE_DIR);
OHOS::ForceCreateDirectory(path);
ret = storageDaemon_->MountDfsDocs(userId, relativePath, networkId, deviceId);
EXPECT_EQ(ret, E_MOUNT);
OHOS::ForceRemoveDirectory(path);
GTEST_LOG_(INFO) << "Storage_Manager_StorageDaemonTest_MountDfsDocs_001 end";
}

View File

@ -17,6 +17,7 @@
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <sys/stat.h>
#include <sys/types.h>
@ -284,18 +285,23 @@ static int ReadKeyFile(const char *path, char *buf, size_t len)
return -EFAULT;
}
int fd = open(realPath, O_RDONLY);
FILE *f = fopen(realPath, "r");
free(realPath);
if (f == NULL) {
LOGE("key file read open failed");
return -EFAULT;
}
int fd = fileno(f);
if (fd < 0) {
LOGE("key file read open failed");
return -EFAULT;
}
if (read(fd, buf, len) != (ssize_t)len) {
LOGE("bad file content");
(void)close(fd);
(void)fclose(f);
return -EBADF;
}
(void)close(fd);
(void)fclose(f);
return 0;
}

View File

@ -109,7 +109,7 @@ char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxIt
while (p != NULL) {
if (count > itemCounts - 1) {
itemCounts += (itemCounts / 2) + 1; // 2 Request to increase the original memory by half.
LOGD("Too many items,expand size");
LOGI("Too many items,expand size");
char **expand = (char **)malloc(sizeof(char*) * itemCounts);
FSCRYPT_ERROR_CHECK(expand != NULL, FreeStringVector(items, count);
@ -118,7 +118,7 @@ char **SplitStringExt(char *buffer, const char *del, int *returnCount, int maxIt
if (ret != 0) {
FreeStringVector(items, count);
FreeStringVector(expand, itemCounts);
LOGD("Too many items,expand size");
LOGI("Too many items,expand size");
return NULL;
}
items = expand;

View File

@ -240,4 +240,4 @@ uint8_t KeyCtrlLoadVersion(const char *keyPath)
LOGE("bad version content");
return FSCRYPT_INVALID;
}
}

View File

@ -1,4 +1,3 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -1,4 +1,3 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
@ -74,7 +73,7 @@ int FBEX::UnlockScreenToKernel(uint32_t userId, uint32_t type, uint8_t *iv, uint
return IFbexMoc::fbexMoc->UnlockScreenToKernel(userId, type, iv, size);
}
int FBEX::ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, uint8_t *eBuffer,
int FBEX::ReadESecretToKernel(UserIdToFbeStr &userIdToFbe, uint32_t status, std::unique_ptr<uint8_t[]> &eBuffer,
uint32_t length, bool &isFbeSupport)
{
return IFbexMoc::fbexMoc->ReadESecretToKernel(userIdToFbe, status, eBuffer, length, isFbeSupport);

View File

@ -1,4 +1,3 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -1,4 +1,3 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -1,4 +1,3 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mount_manager_mock.h"
using namespace std;
using namespace OHOS::StorageDaemon;
std::shared_ptr<MountManager> MountManager::instance_ = nullptr;
MountManager::MountManager()
{}
std::shared_ptr<MountManager> MountManager::GetInstance()
{
static std::once_flag onceFlag;
std::call_once(onceFlag, [&]() { instance_ = std::make_shared<MountManager>(); });
return instance_;
}
bool MountManager::CheckMountFileByUser(int32_t userId)
{
return IMountManagerMoc::mountManagerMoc->CheckMountFileByUser(userId);
}

View File

@ -0,0 +1,91 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "user_idm_client_impl_mock.h"
using namespace std;
using namespace OHOS::StorageDaemon;
using namespace OHOS::UserIam::UserAuth;
UserIdmClientImpl &UserIdmClientImpl::Instance()
{
static UserIdmClientImpl impl;
return impl;
}
UserIdmClient &UserIdmClient::GetInstance()
{
return UserIdmClientImpl::Instance();
}
int32_t UserIdmClientImpl::GetSecUserInfo(int32_t userId, const std::shared_ptr<GetSecUserInfoCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->GetSecUserInfo(userId, callback);
}
std::vector<uint8_t> UserIdmClientImpl::OpenSession(int32_t userId)
{
return IUserIdmClientMoc::userIdmClientMoc->OpenSession(userId);
}
void UserIdmClientImpl::CloseSession(int32_t userId)
{
return IUserIdmClientMoc::userIdmClientMoc->CloseSession(userId);
}
void UserIdmClientImpl::AddCredential(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->AddCredential(userId, para, callback);
}
void UserIdmClientImpl::UpdateCredential(int32_t userId, const CredentialParameters &para,
const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->UpdateCredential(userId, para, callback);
}
int32_t UserIdmClientImpl::Cancel(int32_t userId)
{
return IUserIdmClientMoc::userIdmClientMoc->Cancel(userId);
}
void UserIdmClientImpl::DeleteCredential(int32_t userId, uint64_t credentialId,
const std::vector<uint8_t> &authToken, const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->DeleteCredential(userId, credentialId, authToken, callback);
}
void UserIdmClientImpl::DeleteUser(int32_t userId, const std::vector<uint8_t> &authToken,
const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->DeleteUser(userId, authToken, callback);
}
int32_t UserIdmClientImpl::EraseUser(int32_t userId, const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->EraseUser(userId, callback);
}
int32_t UserIdmClientImpl::GetCredentialInfo(int32_t userId, AuthType authType,
const std::shared_ptr<GetCredentialInfoCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->GetCredentialInfo(userId, authType, callback);
}
void UserIdmClientImpl::ClearRedundancyCredential(const std::shared_ptr<UserIdmClientCallback> &callback)
{
return IUserIdmClientMoc::userIdmClientMoc->ClearRedundancyCredential(callback);
}

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the `fdatasync' function. */
#ifndef CONFIG_H
#define CONFIG_H
#define HAVE_FDATASYNC 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the `mtp' library (-lmtp). */
#define HAVE_LIBMTP 1
/* Check device capabilities */
#undef HAVE_LIBMTP_CHECK_CAPABILITY
/* Define to 1 if you have the <libmtp.h> header file. */
#define HAVE_LIBMTP_H 1
/* Have libusb 1.0 */
#define HAVE_LIBUSB1 /* */
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Name of package */
#define PACKAGE "simple-mtpfs"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "peter@hatina.eu"
/* Define to the full name of this package. */
#define PACKAGE_NAME "simple-mtpfs"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "simple-mtpfs 0.4.0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "simple-mtpfs"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.4.0"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Directory for temporary files */
#define TMPDIR "/tmp"
/* USB device path format string */
#define USB_DEVPATH "/dev/bus/usb/%u/%u"
/* Version number of package */
#define VERSION "0.4.0"
#endif //CONFIG_H

View File

@ -0,0 +1,97 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_FUSE_H
#define MTPFS_FUSE_H
#include "fuse.h"
#include <singleton.h>
#include "mtpfs_mtp_device.h"
#include "mtpfs_tmp_files_pool.h"
#include "mtpfs_type_tmp_file.h"
using namespace OHOS;
class MtpFileSystem {
DECLARE_DELAYED_SINGLETON(MtpFileSystem);
private:
struct MtpFileSystemOptions {
public:
int good_;
int verBose_;
int enableMove_;
int deviceNo_;
char *deviceFile_;
char *mountPoint_;
MtpFileSystemOptions();
~MtpFileSystemOptions();
static int OptProc(void *data, const char *arg, int key, struct fuse_args *outargs);
};
enum {
KEY_ENABLE_MOVE,
KEY_DEVICE_NO,
KEY_LIST_DEVICES,
KEY_VERBOSE,
KEY_VERSION,
KEY_HELP
};
public:
bool ParseOptions(int argc, char **argv);
bool Exec();
bool IsGood() const
{
return options_.good_;
}
int GetAttr(const char *path, struct stat *buf, struct fuse_file_info  *fi);
int MkNod(const char *path, mode_t mode, dev_t dev);
int MkDir(const char *path, mode_t mode);
int UnLink(const char *path);
int RmDir(const char *path);
int ReName(const char *path, const char *newpath, unsigned int flags);
int ChMods(const char *path, mode_t mode, struct fuse_file_info  *fi);
int Chown(const char *path, uid_t uid, gid_t gid, struct fuse_file_info  *fi);
int UTimens(const char *path, const struct timespec tv[2], struct fuse_file_info  *fi);
int Open(const char *path, struct fuse_file_info *fileInfo);
int Read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int Write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fileInfo);
int Statfs(const char *path, struct statvfs *statInfo);
int Flush(const char *path, struct fuse_file_info *fileInfo);
int Release(const char *path, struct fuse_file_info *fileInfo);
int FSync(const char *path, int datasync, struct fuse_file_info *fi);
int OpenDir(const char *path, struct fuse_file_info *fileInfo);
int ReadDir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fileInfo,
enum fuse_readdir_flags flag);
int ReleaseDir(const char *path, struct fuse_file_info *fileInfo);
int FSyncDir(const char *path, int datasync, struct fuse_file_info *fileInfo);
int Truncate(const char *path, off_t offset, struct fuse_file_info *fileInfo);
void *Init(struct fuse_conn_info *conn, struct fuse_config  *cfg);
int Create(const char *path, mode_t mode, fuse_file_info *fileInfo);
private:
bool HasPartialObjectSupport();
bool ParseOptionsInner();
struct fuse_args args_;
struct fuse_operations fuseOperations_;
MtpFsTmpFilesPool tmpFilesPool_;
MtpFileSystemOptions options_;
MtpFsDevice device_;
};
#endif // MTPFS_FUSE_H

View File

@ -0,0 +1,24 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_LIBMTP_H
#define MTPFS_LIBMTP_H
#include <libmtp.h>
extern "C" {
void LIBMTPFreeFilesAndFolders(LIBMTP_file_t **files);
}
#endif // MTPFS_LIBMTP_H

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_MTP_DEVICE_H
#define MTPFS_MTP_DEVICE_H
#include "mtpfs_type_dir.h"
#include "mtpfs_type_file.h"
class MtpFsDevice {
public:
class Capabilities {
public:
Capabilities() : getPartialObject_(false), sendPartialObject_(false), editObjects_(false) {}
void SetCanGetPartialObject(bool b)
{
getPartialObject_ = b;
}
void SetCanSendPartialobject(bool b)
{
sendPartialObject_ = b;
}
void SetCanEditObjects(bool b)
{
editObjects_ = b;
}
bool CanGetPartialObject() const
{
return getPartialObject_;
}
bool CanSendPartialObject() const
{
return sendPartialObject_;
}
bool CanEditObjects() const
{
return editObjects_;
}
private:
bool getPartialObject_;
bool sendPartialObject_;
bool editObjects_;
};
MtpFsDevice();
~MtpFsDevice();
bool Connect(LIBMTP_raw_device_t *dev);
bool Connect(int devNo = 0);
bool Connect(const std::string &devFile);
void Disconnect();
void EnableMove(bool e = true)
{
moveEnabled_ = e;
}
uint64_t StorageTotalSize() const;
uint64_t StorageFreeSize() const;
int DirCreateNew(const std::string &path);
int DirRemove(const std::string &path);
int DirReName(const std::string &oldPath, const std::string &newPath);
const MtpFsTypeDir *DirFetchContent(std::string path);
int ReName(const std::string &oldPath, const std::string &newPath);
int FileRead(const std::string &path, char *buf, size_t size, off_t offset);
int FileWrite(const std::string &path, const char *buf, size_t size, off_t offset);
int FilePull(const std::string &src, const std::string &dst);
int FilePush(const std::string &src, const std::string &dst);
int FileRemove(const std::string &path);
int FileRename(const std::string &oldPath, const std::string &newPath);
Capabilities GetCapabilities() const;
private:
void CriticalEnter()
{
deviceMutex_.lock();
}
void CriticalLeave()
{
deviceMutex_.unlock();
}
bool EnumStorages();
static Capabilities GetCapabilities(const MtpFsDevice &device);
bool ConnectPriv(int devNo, const std::string &devFile);
bool ConnectPrivJudgeErr(LIBMTP_error_number_t err);
bool ConnectPrivInner();
const void HandleDir(LIBMTP_file_t *content, MtpFsTypeDir *dir);
void HandleDevNum(const std::string &devFile, int &devNo, int rawDevicesCnt, LIBMTP_raw_device_t *rawDevices);
int ReNameInner(const std::string &oldPath, const std::string &newPath);
private:
LIBMTP_mtpdevice_t *device_;
Capabilities capabilities_;
std::mutex deviceMutex_;
MtpFsTypeDir rootDir_;
bool moveEnabled_;
static uint32_t rootNode_;
};
#endif // MTPFS_MTP_DEVICE_H

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_SHA_H
#define MTPFS_SHA_H
#include <string>
class MtpFsSha {
public:
MtpFsSha();
void Update(const std::string &s);
void Update(std::istream &is);
std::string Final();
static std::string SumString(const std::string &str);
private:
typedef unsigned long int uint32; /* just needs to be at least 32bit */
typedef unsigned long long uint64; /* just needs to be at least 64bit */
static const unsigned int DIGEST_INTS = 5; /* number of 32bit integers per MtpFsSha digest */
static const unsigned int BLOCK_INTS = 16; /* number of 32bit integers per MtpFsSha block */
static const unsigned int BLOCK_BYTES = BLOCK_INTS * 4;
uint32 digest_[DIGEST_INTS];
std::string buffer_;
uint64 transforms_;
void Reset();
void Transform(uint32 block[BLOCK_BYTES]);
static void BufferToBlock(const std::string &buffer, uint32 block[BLOCK_BYTES]);
static void Read(std::istream &is, std::string &s, const int max);
};
#endif

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_TMP_FILES_POOL_H
#define MTPFS_TMP_FILES_POOL_H
#include "mtpfs_type_tmp_file.h"
class MtpFsTmpFilesPool {
public:
MtpFsTmpFilesPool();
~MtpFsTmpFilesPool();
void SetTmpDir(const std::string &tmpDir)
{
tmpDir_ = tmpDir;
}
void AddFile(const MtpFsTypeTmpFile &tmp)
{
pool_.insert(tmp);
}
void RemoveFile(const std::string &path);
bool Empty() const
{
return pool_.size();
}
const MtpFsTypeTmpFile *GetFile(const std::string &path) const;
std::string MakeTmpPath(const std::string &pathDevice) const;
bool CreateTmpDir();
bool RemoveTmpDir();
private:
std::string tmpDir_;
std::set<MtpFsTypeTmpFile> pool_;
};
#endif // MTPFS_TMP_FILES_POOL_H

View File

@ -0,0 +1,101 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_TYPE_BASIC_H
#define MTPFS_TYPE_BASIC_H
#include <string>
#include <cstdint>
class MtpFsTypeBasic {
public:
MtpFsTypeBasic() : id_(0), parentId_(0), storageId_(0), name_() {}
MtpFsTypeBasic(uint32_t id, uint32_t parentId, uint32_t storageId, const std::string &name)
: id_(id), parentId_(parentId), storageId_(storageId), name_(name)
{}
MtpFsTypeBasic(const MtpFsTypeBasic &copy)
: id_(copy.id_), parentId_(copy.parentId_), storageId_(copy.storageId_), name_(copy.name_)
{}
uint32_t Id() const
{
return id_;
}
uint32_t ParentId() const
{
return parentId_;
}
uint32_t StorageId() const
{
return storageId_;
}
std::string Name() const
{
return name_;
}
void SetId(uint32_t id)
{
id_ = id;
}
void SetParent(uint32_t parentId)
{
parentId_ = parentId;
}
void SetStorage(uint32_t storageId)
{
storageId_ = storageId;
}
void SetName(const std::string &name)
{
name_ = name;
}
MtpFsTypeBasic &operator = (const MtpFsTypeBasic &rhs)
{
id_ = rhs.id_;
parentId_ = rhs.parentId_;
storageId_ = rhs.storageId_;
name_ = rhs.name_;
return *this;
}
bool operator == (const std::string &rhs) const
{
return name_ == rhs;
}
bool operator == (const MtpFsTypeBasic &rhs) const
{
return name_ == rhs.name_;
}
bool operator < (const std::string &rhs) const
{
return name_ < rhs;
}
bool operator < (const MtpFsTypeBasic &rhs) const
{
return name_ < rhs.name_;
}
protected:
uint32_t id_;
uint32_t parentId_;
uint32_t storageId_;
std::string name_;
};
#endif // MTPFS_TYPE_BASIC_H

View File

@ -0,0 +1,120 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_TYPE_DIR_H
#define MTPFS_TYPE_DIR_H
#include <mutex>
#include <set>
#include <string>
#include "mtpfs_type_basic.h"
#include "mtpfs_type_file.h"
class MtpFsTypeDir : public MtpFsTypeBasic {
public:
MtpFsTypeDir();
MtpFsTypeDir(uint32_t id, uint32_t parentId, uint32_t storageId, const std::string &name);
MtpFsTypeDir(LIBMTP_file_t *file);
MtpFsTypeDir(const MtpFsTypeDir &copy);
void EnterCritical() const
{
accessMutex_.lock();
}
void LeaveCritical() const
{
accessMutex_.unlock();
}
void Clear()
{
dirs_.clear();
files_.clear();
}
void SetFetched(bool f = true)
{
fetched_ = f;
}
bool IsFetched() const
{
return fetched_;
}
void AddDir(const MtpFsTypeDir &dir);
void AddFile(const MtpFsTypeFile &file);
bool RemoveDir(const MtpFsTypeDir &dir);
bool RemoveFile(const MtpFsTypeFile &file);
bool ReplaceFile(const MtpFsTypeFile &oldFile, const MtpFsTypeFile &newFile);
std::set<MtpFsTypeDir>::size_type DirCount() const
{
return dirs_.size();
}
std::set<MtpFsTypeFile>::size_type FileCount() const
{
return files_.size();
}
const MtpFsTypeDir *Dir(const std::string &name) const;
const MtpFsTypeFile *File(const std::string &name) const;
std::set<MtpFsTypeDir> Dirs() const
{
return dirs_;
}
std::set<MtpFsTypeFile> Files() const
{
return files_;
}
bool IsEmpty() const
{
return dirs_.empty() && files_.empty();
}
time_t ModificationDate() const
{
return modifyDate_;
}
void SetModificationDate(time_t modifyDate)
{
modifyDate_ = modifyDate;
}
LIBMTP_folder_t *ToLIBMTPFolder() const;
MtpFsTypeDir &operator = (const MtpFsTypeDir &rhs);
bool operator == (const std::string &rhs) const
{
return MtpFsTypeBasic::operator == (rhs);
}
bool operator == (const MtpFsTypeDir &rhs) const
{
return MtpFsTypeBasic::operator == (rhs);
}
bool operator < (const std::string &rhs) const
{
return MtpFsTypeBasic::operator < (rhs);
}
bool operator < (const MtpFsTypeDir &rhs) const
{
return MtpFsTypeBasic::operator < (rhs);
}
private:
std::set<MtpFsTypeDir> dirs_;
std::set<MtpFsTypeFile> files_;
mutable std::mutex accessMutex_;
bool fetched_;
time_t modifyDate_;
};
#endif // MTPFS_TYPE_DIR_H

View File

@ -0,0 +1,73 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_TYPE_FILE_H
#define MTPFS_TYPE_FILE_H
#include <libmtp.h>
#include "mtpfs_type_basic.h"
class MtpFsTypeFile : public MtpFsTypeBasic {
public:
MtpFsTypeFile();
MtpFsTypeFile(uint32_t id, uint32_t parentId, uint32_t storageId, const std::string &name, uint64_t size,
time_t modifyDate);
MtpFsTypeFile(LIBMTP_file_t *file);
MtpFsTypeFile(const MtpFsTypeFile &copy);
uint64_t Size() const
{
return size_;
}
time_t ModificationDate() const
{
return modifyDate_;
}
void SetSize(uint64_t size)
{
size_ = size;
}
void SetModificationDate(time_t modifyDate)
{
modifyDate_ = modifyDate;
}
LIBMTP_file_t *ToLIBMTPFile() const;
MtpFsTypeFile &operator = (const MtpFsTypeFile &rhs);
bool operator == (const std::string &rhs) const
{
return MtpFsTypeBasic::operator == (rhs);
}
bool operator == (const MtpFsTypeFile &rhs) const
{
return MtpFsTypeBasic::operator == (rhs);
}
bool operator < (const std::string &rhs) const
{
return MtpFsTypeBasic::operator < (rhs);
}
bool operator < (const MtpFsTypeFile &rhs) const
{
return MtpFsTypeBasic::operator < (rhs);
}
private:
uint64_t size_;
time_t modifyDate_;
};
#endif // MTPFS_TYPE_FILE_H

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2024 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MTPFS_TYPE_TMP_FILE_H
#define MTPFS_TYPE_TMP_FILE_H
#include <set>
#include <string>
#include "mtpfs_type_file.h"
class MtpFsTypeTmpFile {
public:
MtpFsTypeTmpFile();
MtpFsTypeTmpFile(const MtpFsTypeTmpFile &copy);
MtpFsTypeTmpFile(const std::string &pathDevice, const std::string &pathTmp, int fileDesc, bool modified = false);
std::string PathDevice() const
{
return pathDevice_;
}
std::string PathTmp() const
{
return pathTmp_;
}
bool IsModified() const
{
return modified_;
}
void SetModified(bool modified = true)
{
modified_ = modified;
}
std::set<int> FileDescriptors() const
{
return fileDescriptors_;
}
void AddFileDescriptor(int fd)
{
fileDescriptors_.insert(fd);
}
bool HasFileDescriptor(int fd);
void RemoveFileDescriptor(int fd);
int RefCnt() const
{
return fileDescriptors_.size();
}
MtpFsTypeTmpFile &operator = (const MtpFsTypeTmpFile &rhs);
bool operator == (const MtpFsTypeTmpFile &rhs) const
{
return pathDevice_ == rhs.pathDevice_;
}
bool operator == (const std::string &path) const
{
return pathDevice_ == path;
}
bool operator < (const MtpFsTypeTmpFile &rhs) const
{
return pathDevice_ < rhs.pathDevice_;
}
bool operator < (const std::string &path) const
{
return pathDevice_ < path;
}
private:
std::string pathDevice_;
std::string pathTmp_;
std::set<int> fileDescriptors_;
bool modified_;
};
#endif // MTPFS_TYPE_TMP_FILE_H

Some files were not shown because too many files have changed in this diff Show More