2 * Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
19 #include <openssl/rand.h>
20 #include <openssl/err.h>
21 #include <openssl/evp.h>
22 #include <openssl/sha.h>
24 #include <key-provider.h>
25 #include <ckm/ckm-zero-memory.h>
29 #include <crypto-backend.h>
30 #ifdef SE_BACKEND_ENABLED
31 #include <se-backend/internals.h>
37 constexpr int PBKDF2_ITERATIONS = 4096;
38 constexpr uint32_t KEYCOMPONENT_VERSION = 2;
39 constexpr int OPENSSL_ENGINE_ERROR = -4;
42 RawBuffer toRawBuffer(const T &data)
45 const unsigned char *ptr = reinterpret_cast<const unsigned char *>(&data);
46 output.assign(ptr, ptr + sizeof(T));
50 // You cannot use toRawBuffer template with pointers
52 RawBuffer toRawBuffer(T *)
54 class NoPointerAllowed {
61 int encryptAes256Gcm(const unsigned char *plaintext,
62 int plaintext_len, const unsigned char *key, const unsigned char *iv,
63 unsigned char *ciphertext, unsigned char *tag)
66 int ciphertext_len = 0;
68 auto ctx = uptr<EVP_CIPHER_CTX_free>(EVP_CIPHER_CTX_new());
70 return OPENSSL_ENGINE_ERROR;
72 if (!EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
73 return OPENSSL_ENGINE_ERROR;
75 if (!EVP_EncryptInit_ex(ctx.get(), NULL, NULL, key, iv))
76 return OPENSSL_ENGINE_ERROR;
78 if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
79 return OPENSSL_ENGINE_ERROR;
81 if (!EVP_EncryptUpdate(ctx.get(), ciphertext, &len, plaintext, plaintext_len))
82 return OPENSSL_ENGINE_ERROR;
86 if (!EVP_EncryptFinal_ex(ctx.get(), ciphertext + len, &len))
87 return OPENSSL_ENGINE_ERROR;
89 ciphertext_len += len;
91 if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, MAX_IV_SIZE, tag))
92 return OPENSSL_ENGINE_ERROR;
94 return ciphertext_len;
97 int decryptAes256Gcm(const unsigned char *ciphertext,
98 int ciphertext_len, unsigned char *tag, const unsigned char *key,
99 const unsigned char *iv, unsigned char *plaintext)
105 auto ctx = uptr<EVP_CIPHER_CTX_free>(EVP_CIPHER_CTX_new());
107 return OPENSSL_ENGINE_ERROR;
109 if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
110 return OPENSSL_ENGINE_ERROR;
112 if (!EVP_DecryptInit_ex(ctx.get(), NULL, NULL, key, iv))
113 return OPENSSL_ENGINE_ERROR;
115 if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
116 return OPENSSL_ENGINE_ERROR;
118 if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, MAX_IV_SIZE, tag))
119 return OPENSSL_ENGINE_ERROR;
121 if (!EVP_DecryptUpdate(ctx.get(), plaintext, &len, ciphertext, ciphertext_len))
122 return OPENSSL_ENGINE_ERROR;
126 if (!(ret = EVP_DecryptFinal_ex(ctx.get(), plaintext + len, &len)))
127 return OPENSSL_ENGINE_ERROR;
130 plaintext_len += len;
131 return plaintext_len;
137 typedef std::array<uint8_t, MAX_KEY_SIZE> KeyData;
139 KeyData PBKDF(const std::string& pass, const unsigned char *salt, int saltlen)
142 if (!PKCS5_PBKDF2_HMAC_SHA1(pass.c_str(),
149 ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
154 // derives a key used for DomainKEK encryption (aka PKEK1) from random salt & user password
155 KeyData makePKEK1(const DomainKEKInfo& domainKEKInfo, const Password &password)
157 std::string concatPasswordClient(password.c_str());
158 concatPasswordClient += std::string(domainKEKInfo.client);
160 if (domainKEKInfo.version != KEYCOMPONENT_VERSION)
161 ThrowErr(Exc::InternalError, "It's not expected version");
164 if (domainKEKInfo.backend == (int)CryptoBackend::SecureElement) {
165 #if SE_BACKEND_ENABLED
166 salt = Crypto::SE::Internals::encryptWithDbpKey((unsigned char*)domainKEKInfo.salt,
168 (unsigned char*)domainKEKInfo.iv,
171 ThrowErr(Exc::InternalError, "It's not expected backend");
173 } else if (domainKEKInfo.backend == (int)CryptoBackend::OpenSSL) {
174 salt = RawBuffer(domainKEKInfo.salt, domainKEKInfo.salt + MAX_SALT_SIZE);
176 ThrowErr(Exc::InternalError, "It's not expected backend");
179 return PBKDF(concatPasswordClient, salt.data(), salt.size());
182 // derives a key (PKEK2) from DomainKEK and custom client string (may be a client id or uid)
183 KeyData makePKEK2(const uint8_t *domainKEK, const std::string &client)
185 return PBKDF(client, domainKEK, MAX_SALT_SIZE);
188 void unwrapDomainKEK(const RawBuffer &wrappedDomainKEKbuffer,
189 const Password &password,
190 DomainKEKAndInfo &domainKEK)
192 DomainKEKAndInfo wrappedDomainKEK(wrappedDomainKEKbuffer);
193 KeyData PKEK1 = makePKEK1(wrappedDomainKEK.info, password);
196 if (0 > (keyLength = decryptAes256Gcm(wrappedDomainKEK.key,
197 wrappedDomainKEK.info.keyLength,
198 wrappedDomainKEK.info.tag,
200 wrappedDomainKEK.info.iv,
202 ThrowErr(Exc::AuthenticationFailed, "DomainKEK decryption failed");
204 domainKEK.setKeyInfo(wrappedDomainKEK.info);
205 domainKEK.info.keyLength = static_cast<uint32_t>(keyLength);
208 RawBuffer wrapDomainKEK(DomainKEKAndInfo &domainKEK, const Password &password)
210 KeyData PKEK1 = makePKEK1(domainKEK.info, password);
212 DomainKEKAndInfo wrappedDomainKEK;
213 wrappedDomainKEK.setKeyInfo(domainKEK.info);
216 if (0 > (wrappedLength = encryptAes256Gcm(domainKEK.key,
217 domainKEK.info.keyLength,
220 wrappedDomainKEK.key,
221 wrappedDomainKEK.info.tag)))
222 ThrowErr(Exc::InternalError, "DomainKEK encryption failed");
224 wrappedDomainKEK.info.keyLength = static_cast<uint32_t>(wrappedLength);
225 return toRawBuffer(wrappedDomainKEK);
229 bool randomize(uint8_t (&array)[N])
231 return RAND_bytes(array, N) == 1;
234 } // anonymous namespace
236 KeyProvider::KeyProvider() :
238 m_isInitialized(false)
240 LogDebug("Created empty KeyProvider");
243 KeyProvider::KeyProvider(
244 const RawBuffer &domainKEKInWrapForm,
245 const Password &password) :
246 m_domainKEK(new DomainKEKAndInfo()),
247 m_isInitialized(true)
249 if (domainKEKInWrapForm.size() != sizeof(DomainKEKAndInfo)) {
250 LogWarning("Input size:" << domainKEKInWrapForm.size()
251 << " Expected: " << sizeof(DomainKEKAndInfo));
252 LogWarning("Buffer doesn't have proper size to store DomainKEKAndInfo in KeyProvider"
254 m_isInitialized = false;
258 unwrapDomainKEK(domainKEKInWrapForm, password, *m_domainKEK);
261 KeyProvider &KeyProvider::operator=(KeyProvider &&second)
263 LogDebug("Moving KeyProvider");
268 m_isInitialized = second.m_isInitialized;
269 m_domainKEK = second.m_domainKEK;
270 second.m_isInitialized = false;
271 second.m_domainKEK = NULL;
275 KeyProvider::KeyProvider(KeyProvider &&second)
277 LogDebug("Moving KeyProvider");
278 m_isInitialized = second.m_isInitialized;
279 m_domainKEK = second.m_domainKEK;
280 second.m_isInitialized = false;
281 second.m_domainKEK = NULL;
284 bool KeyProvider::isInitialized() const
286 return m_isInitialized;
289 RawBuffer KeyProvider::getPureDomainKEK() const
291 if (!m_isInitialized)
292 ThrowErr(Exc::InternalError, "Object not initialized!");
295 return RawBuffer(m_domainKEK->key, m_domainKEK->key + m_domainKEK->info.keyLength);
298 RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password) const
300 if (!m_isInitialized)
301 ThrowErr(Exc::InternalError, "Object not initialized!");
303 return wrapDomainKEK(*m_domainKEK, password);
306 RawBuffer KeyProvider::getPureDEK(const RawBuffer &wrappedDEKbuffer) const
308 if (!m_isInitialized)
309 ThrowErr(Exc::InternalError, "Object not initialized!");
311 if (wrappedDEKbuffer.size() != sizeof(DEKAndInfo)) {
312 LogError("input size:" << wrappedDEKbuffer.size() << " Expected: " << sizeof(DEKAndInfo));
314 ThrowErr(Exc::InternalError,
315 "buffer doesn't have proper size to store KeyAndInfo in KeyProvider::getPureDEK");
319 DEKAndInfo wrappedDEK(wrappedDEKbuffer);
321 KeyData PKEK2 = makePKEK2(m_domainKEK->key, wrappedDEK.info.client);
324 if (0 > (keyLength = decryptAes256Gcm(wrappedDEK.key,
325 wrappedDEK.info.keyLength,
330 ThrowErr(Exc::InternalError, "UnwrapDEK Failed in KeyProvider::getPureDEK");
332 DEK.info.keyLength = static_cast<uint32_t>(keyLength);
334 LogDebug("getPureDEK SUCCESS");
335 return RawBuffer(DEK.key, DEK.key + DEK.info.keyLength);
338 RawBuffer KeyProvider::generateDEK(const std::string &client) const
340 if (!m_isInitialized)
341 ThrowErr(Exc::InternalError, "Object not initialized!");
343 DEKAndInfo wrappedDEK;
344 std::string resized_client;
346 if (client.length() < MAX_CLIENT_ID_SIZE)
347 resized_client = client;
349 resized_client = client.substr(0, MAX_CLIENT_ID_SIZE - 1);
351 uint8_t DEK[MAX_KEY_SIZE];
353 if (!randomize(DEK) || !randomize(wrappedDEK.info.iv))
354 ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
356 KeyData PKEK2 = makePKEK2(m_domainKEK->key, resized_client);
358 int wrappedKeyLength;
359 if (0 > (wrappedKeyLength = encryptAes256Gcm(DEK,
364 wrappedDEK.info.tag)))
365 ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK");
367 wrappedDEK.info.keyLength = static_cast<uint32_t>(wrappedKeyLength);
368 wrappedDEK.setKeyInfoClient(resized_client);
370 LogDebug("GenerateDEK Success");
371 return toRawBuffer(wrappedDEK);
374 void KeyProvider::migrateDomainKEK(const RawBuffer &wrappedDomainKEKbuffer,
375 const Password &password)
377 DEKAndInfo wrappedOldDomainKEK(wrappedDomainKEKbuffer);
379 std::string concatPasswordClient(password.c_str());
380 concatPasswordClient += std::string(wrappedOldDomainKEK.info.client);
382 KeyData PKEK1 = PBKDF(concatPasswordClient, wrappedOldDomainKEK.info.salt, MAX_SALT_SIZE);
385 if (0 > (keyLength = decryptAes256Gcm(wrappedOldDomainKEK.key,
386 wrappedOldDomainKEK.info.keyLength,
387 wrappedOldDomainKEK.info.tag,
389 wrappedOldDomainKEK.info.iv,
391 ThrowErr(Exc::AuthenticationFailed, "DomainKEK decryption failed");
393 DomainKEKInfo info(wrappedOldDomainKEK.info);
394 info.version = KEYCOMPONENT_VERSION;
395 info.backend = static_cast<uint32_t>(CryptoBackend::OpenSSL);
396 #ifdef SE_BACKEND_ENABLED
397 info.backend = static_cast<uint32_t>(CryptoBackend::SecureElement);
399 m_domainKEK->setKeyInfo(info);
401 m_domainKEK->info.keyLength = static_cast<uint32_t>(keyLength);
402 m_isInitialized = true;
403 LogDebug("Migrate DomainKEK Success");
406 RawBuffer KeyProvider::generateDomainKEK(const std::string &user, const Password &userPassword)
408 DomainKEKAndInfo domainKEK;
410 if (!randomize(domainKEK.info.salt) ||
411 !randomize(domainKEK.key) ||
412 !randomize(domainKEK.info.iv)) {
413 ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
416 domainKEK.info.version = KEYCOMPONENT_VERSION;
417 domainKEK.info.backend = static_cast<uint32_t>(CryptoBackend::OpenSSL);
418 #ifdef SE_BACKEND_ENABLED
419 domainKEK.info.backend = static_cast<uint32_t>(CryptoBackend::SecureElement);
421 domainKEK.info.keyLength = sizeof(domainKEK.key);
422 domainKEK.setKeyInfoClient(user);
424 return wrapDomainKEK(domainKEK, userPassword);