1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define LOG_TAG "keystore"
18 
19 #include "keystore_utils.h"
20 
21 #include <errno.h>
22 #include <string.h>
23 #include <unistd.h>
24 
25 #include <log/log.h>
26 #include <private/android_filesystem_config.h>
27 #include <private/android_logger.h>
28 
29 #include <log/log_event_list.h>
30 
31 #include <keystore/keymaster_types.h>
32 #include <keystore/keystore_client.h>
33 
34 #include <android-base/logging.h>
35 #include <android-base/unique_fd.h>
36 
37 #include "blob.h"
38 
readFully(int fd,uint8_t * data,size_t size)39 size_t readFully(int fd, uint8_t* data, size_t size) {
40     size_t remaining = size;
41     while (remaining > 0) {
42         ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, remaining));
43         if (n <= 0) {
44             return size - remaining;
45         }
46         data += n;
47         remaining -= n;
48     }
49     return size;
50 }
51 
writeFully(int fd,uint8_t * data,size_t size)52 size_t writeFully(int fd, uint8_t* data, size_t size) {
53     size_t remaining = size;
54     while (remaining > 0) {
55         ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, remaining));
56         if (n < 0) {
57             ALOGW("write failed: %s", strerror(errno));
58             return size - remaining;
59         }
60         data += n;
61         remaining -= n;
62     }
63     if (TEMP_FAILURE_RETRY(fsync(fd)) == -1) {
64         ALOGW("fsync failed: %s", strerror(errno));
65         return -1;
66     }
67     return size;
68 }
69 
getContainingDirectory(const std::string & filename)70 std::string getContainingDirectory(const std::string& filename) {
71     std::string containing_dir;
72     size_t last_pos;
73     size_t pos = std::string::npos;
74 
75     __builtin_add_overflow(filename.size(), -1, &last_pos);
76 
77     // strip all trailing '/'
78     while ((pos = filename.find_last_of('/', last_pos)) == last_pos && pos != 0) {
79         --last_pos;
80     }
81 
82     if (pos == 0) {
83         containing_dir = "/";
84     } else if (pos == std::string::npos) {
85         containing_dir = ".";
86     } else {
87         containing_dir = filename.substr(0, pos);
88     }
89 
90     return containing_dir;
91 }
92 
fsyncDirectory(const std::string & path)93 void fsyncDirectory(const std::string& path) {
94     android::base::unique_fd dir_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_DIRECTORY | O_RDONLY)));
95 
96     if (dir_fd < 0) {
97         LOG(WARNING) << "Could not open dir: " << path << " error: " << strerror(errno);
98         return;
99     }
100 
101     if (TEMP_FAILURE_RETRY(fsync(dir_fd)) == -1) {
102         LOG(WARNING) << "Failed to fsync the directory " << path << " error: " << strerror(errno);
103     }
104 
105     return;
106 }
107 
add_legacy_key_authorizations(int keyType,keystore::AuthorizationSet * params)108 void add_legacy_key_authorizations(int keyType, keystore::AuthorizationSet* params) {
109     using namespace keystore;
110     params->push_back(TAG_PURPOSE, KeyPurpose::SIGN);
111     params->push_back(TAG_PURPOSE, KeyPurpose::VERIFY);
112     params->push_back(TAG_PURPOSE, KeyPurpose::ENCRYPT);
113     params->push_back(TAG_PURPOSE, KeyPurpose::DECRYPT);
114     params->push_back(TAG_PADDING, PaddingMode::NONE);
115     if (keyType == EVP_PKEY_RSA) {
116         params->push_back(TAG_PADDING, PaddingMode::RSA_PKCS1_1_5_SIGN);
117         params->push_back(TAG_PADDING, PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
118         params->push_back(TAG_PADDING, PaddingMode::RSA_PSS);
119         params->push_back(TAG_PADDING, PaddingMode::RSA_OAEP);
120     }
121     params->push_back(TAG_DIGEST, Digest::NONE);
122     params->push_back(TAG_DIGEST, Digest::MD5);
123     params->push_back(TAG_DIGEST, Digest::SHA1);
124     params->push_back(TAG_DIGEST, Digest::SHA_2_224);
125     params->push_back(TAG_DIGEST, Digest::SHA_2_256);
126     params->push_back(TAG_DIGEST, Digest::SHA_2_384);
127     params->push_back(TAG_DIGEST, Digest::SHA_2_512);
128     params->push_back(TAG_NO_AUTH_REQUIRED);
129     params->push_back(TAG_ORIGINATION_EXPIRE_DATETIME, LLONG_MAX);
130     params->push_back(TAG_USAGE_EXPIRE_DATETIME, LLONG_MAX);
131     params->push_back(TAG_ACTIVE_DATETIME, 0);
132 }
133 
get_app_id(uid_t uid)134 uid_t get_app_id(uid_t uid) {
135     return uid % AID_USER;
136 }
137 
get_user_id(uid_t uid)138 uid_t get_user_id(uid_t uid) {
139     return uid / AID_USER;
140 }
141 
log_key_integrity_violation(const char * name,uid_t uid)142 void log_key_integrity_violation(const char* name, uid_t uid) {
143     if (!__android_log_security()) return;
144     android_log_event_list(SEC_TAG_KEY_INTEGRITY_VIOLATION)
145         << name << int32_t(uid) << LOG_ID_SECURITY;
146 }
147 
148 namespace keystore {
149 
blob2hidlVec(const Blob & blob)150 hidl_vec<uint8_t> blob2hidlVec(const Blob& blob) {
151     hidl_vec<uint8_t> result(blob.getValue(), blob.getValue() + blob.getLength());
152     return result;
153 }
154 
flagsToSecurityLevel(int32_t flags)155 SecurityLevel flagsToSecurityLevel(int32_t flags) {
156     switch (flags & (KEYSTORE_FLAG_FALLBACK | KEYSTORE_FLAG_STRONGBOX)) {
157     case KEYSTORE_FLAG_FALLBACK:
158     // treating Strongbox flag as "don't care" if Fallback is set
159     case (KEYSTORE_FLAG_FALLBACK | KEYSTORE_FLAG_STRONGBOX):
160         return SecurityLevel::SOFTWARE;
161     case KEYSTORE_FLAG_STRONGBOX:
162         return SecurityLevel::STRONGBOX;
163     default:
164         return SecurityLevel::TRUSTED_ENVIRONMENT;
165     }
166 }
167 
securityLevelToFlags(SecurityLevel secLevel)168 uint32_t securityLevelToFlags(SecurityLevel secLevel) {
169     switch (secLevel) {
170     case SecurityLevel::SOFTWARE:
171         return KEYSTORE_FLAG_FALLBACK;
172     case SecurityLevel::STRONGBOX:
173         return KEYSTORE_FLAG_STRONGBOX;
174     default:
175         return 0;
176     }
177 }
178 
179 }  // namespace keystore
180