summaryrefslogtreecommitdiff
path: root/src/manager/service/key-provider.cpp
blob: e89af1672226ff9020e9d0a82935ad7d83de4f15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*
 *  Copyright (c) 2014 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  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 <exception.h>
#include <key-provider.h>
#include <dpl/log/log.h>
#include <ckm/ckm-zero-memory.h>
#include <string.h>

#include <array>
#include <memory>

using namespace CKM;

namespace {

template<typename T>
RawBuffer toRawBuffer(const T &data)
{
	RawBuffer output;
	const unsigned char *ptr = reinterpret_cast<const unsigned char *>(&data);
	output.assign(ptr, ptr + sizeof(T));
	return output;
}

// You cannot use toRawBuffer template with pointers
template<typename T>
RawBuffer toRawBuffer(T *)
{
	class NoPointerAllowed {
		NoPointerAllowed() {}
	};
	NoPointerAllowed a;
	return RawBuffer();
}

typedef std::unique_ptr<EVP_CIPHER_CTX, decltype(&EVP_CIPHER_CTX_free)> CipherCtxPtr;

int encryptAes256Gcm(const unsigned char *plaintext,
                     int plaintext_len, const unsigned char *key, const unsigned char *iv,
                     unsigned char *ciphertext, unsigned char *tag)
{
	int len;
	int ciphertext_len = 0;

	CipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
	if (!ctx)
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptInit_ex(ctx.get(), NULL, NULL, key, iv))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_EncryptUpdate(ctx.get(), ciphertext, &len, plaintext, plaintext_len))
		return OPENSSL_ENGINE_ERROR;

	ciphertext_len = len;

	if (!EVP_EncryptFinal_ex(ctx.get(), ciphertext + len, &len))
		return OPENSSL_ENGINE_ERROR;

	ciphertext_len += len;

	if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, MAX_IV_SIZE, tag))
		return OPENSSL_ENGINE_ERROR;

	return ciphertext_len;
}

int decryptAes256Gcm(const unsigned char *ciphertext,
                     int ciphertext_len, unsigned char *tag, const unsigned char *key,
                     const unsigned char *iv, unsigned char *plaintext)
{
	int len;
	int plaintext_len;
	int ret;

	CipherCtxPtr ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
	if (!ctx)
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), NULL, NULL, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptInit_ex(ctx.get(), NULL, NULL, key, iv))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, MAX_IV_SIZE, NULL))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, MAX_IV_SIZE, tag))
		return OPENSSL_ENGINE_ERROR;

	if (!EVP_DecryptUpdate(ctx.get(), plaintext, &len, ciphertext, ciphertext_len))
		return OPENSSL_ENGINE_ERROR;

	plaintext_len = len;

	if (!(ret = EVP_DecryptFinal_ex(ctx.get(), plaintext + len, &len)))
		return OPENSSL_ENGINE_ERROR;

	if (ret > 0) {
		plaintext_len += len;
		return plaintext_len;
	} else {
		return -1;
	}
}

typedef std::array<uint8_t, MAX_KEY_SIZE> KeyData;

// derives a key used for DomainKEK encryption (aka PKEK1) from random salt & user password
KeyData makePKEK1(const KeyComponentsInfo& keyInfo, const Password &password)
{
	std::string concatPasswordClient(password.c_str());
	concatPasswordClient += std::string(keyInfo.client);

	KeyData key;
	if (!PKCS5_PBKDF2_HMAC_SHA1(concatPasswordClient.c_str(),
	                            concatPasswordClient.size(),
	                            keyInfo.salt,
	                            MAX_SALT_SIZE,
	                            PBKDF2_ITERATIONS,
	                            key.size(),
	                            key.data())) {
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}
	return key;
}

// derives a key (PKEK2) from DomainKEK and custom client string (may be a client id or uid)
KeyData makePKEK2(const uint8_t *domainKEK, const std::string &client)
{
	KeyData key;
	if (!PKCS5_PBKDF2_HMAC_SHA1(client.c_str(),
	                            client.size(),
	                            domainKEK,
	                            MAX_SALT_SIZE,
	                            PBKDF2_ITERATIONS,
	                            key.size(),
	                            key.data())) {
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}
	return key;
}

void unwrapDomainKEK(const RawBuffer &wrappedDomainKEKbuffer,
                     const Password &password,
                     KeyAndInfoContainer &domainKEK)
{
	WrappedKeyAndInfoContainer wrappedDomainKEK(wrappedDomainKEKbuffer.data());

	KeyData PKEK1 = makePKEK1(wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo, password);

	int keyLength;
	if (0 > (keyLength = decryptAes256Gcm(wrappedDomainKEK.getWrappedKeyAndInfo().wrappedKey,
	                                      wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo.keyLength,
	                                      wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo.tag,
	                                      PKEK1.data(),
	                                      wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo.iv,
	                                      domainKEK.getKeyAndInfo().key)))
		ThrowErr(Exc::AuthenticationFailed, "DomainKEK decryption failed");

	domainKEK.setKeyInfo(&(wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo));
	domainKEK.setKeyInfoKeyLength(static_cast<unsigned int>(keyLength));
}

RawBuffer wrapDomainKEK(KeyAndInfoContainer &domainKEK, const Password &password)
{
	KeyData PKEK1 = makePKEK1(domainKEK.getKeyAndInfo().keyInfo, password);

	WrappedKeyAndInfoContainer wrappedDomainKEK = WrappedKeyAndInfoContainer();
	wrappedDomainKEK.setKeyInfo(&(domainKEK.getKeyAndInfo().keyInfo));

	int wrappedLength;
	if (0 > (wrappedLength = encryptAes256Gcm(domainKEK.getKeyAndInfo().key,
	                                          domainKEK.getKeyAndInfo().keyInfo.keyLength,
	                                          PKEK1.data(),
	                                          domainKEK.getKeyAndInfo().keyInfo.iv,
	                                          wrappedDomainKEK.getWrappedKeyAndInfo().wrappedKey,
	                                          wrappedDomainKEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError, "DomainKEK encryption failed");

	wrappedDomainKEK.setKeyInfoKeyLength(static_cast<unsigned int>(wrappedLength));
	return toRawBuffer(wrappedDomainKEK.getWrappedKeyAndInfo());
}

template <size_t N>
bool randomize(uint8_t (&array)[N])
{
	return RAND_bytes(array, N) == 1;
}

} // anonymous namespace

WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer()
{
	memset(&wrappedKeyAndInfo, 0, sizeof(WrappedKeyAndInfo));
}

WrappedKeyAndInfoContainer::WrappedKeyAndInfoContainer(const unsigned char
		*data)
{
	memcpy(&wrappedKeyAndInfo, data, sizeof(WrappedKeyAndInfo));

	if (wrappedKeyAndInfo.keyInfo.keyLength > sizeof(wrappedKeyAndInfo.wrappedKey)) {
		ThrowErr(Exc::InternalError,
		         "Wrapped key info is corrupted. Key length exceeds the size of the key buffer.");
	}

	size_t maxlen = sizeof(wrappedKeyAndInfo.keyInfo.client);
	if (strnlen(wrappedKeyAndInfo.keyInfo.client, maxlen) == maxlen) {
		ThrowErr(Exc::InternalError,
		         "Wrapped key info is corrupted. Client id is not NULL terminated.");
	}
}

WrappedKeyAndInfo &WrappedKeyAndInfoContainer::getWrappedKeyAndInfo()
{
	return wrappedKeyAndInfo;
}

void WrappedKeyAndInfoContainer::setKeyInfoKeyLength(const unsigned int length)
{
	wrappedKeyAndInfo.keyInfo.keyLength = length;
}

void WrappedKeyAndInfoContainer::setKeyInfoClient(const std::string resized_client)
{
	if (resized_client.size() >= sizeof(wrappedKeyAndInfo.keyInfo.client)) {
		ThrowErr(Exc::InternalError, "Client name too long");
	}

	strcpy(wrappedKeyAndInfo.keyInfo.client, resized_client.c_str());
}

void WrappedKeyAndInfoContainer::setKeyInfoSalt(const unsigned char *salt,
		const int size)
{
	memcpy(wrappedKeyAndInfo.keyInfo.salt, salt, size);
}

void WrappedKeyAndInfoContainer::setKeyInfo(const KeyComponentsInfo
		*keyComponentsInfo)
{
	memcpy(&(wrappedKeyAndInfo.keyInfo), keyComponentsInfo,
		   sizeof(KeyComponentsInfo));
}

WrappedKeyAndInfoContainer::~WrappedKeyAndInfoContainer()
{
}

KeyAndInfoContainer::KeyAndInfoContainer()
{
	memset(&keyAndInfo, 0, sizeof(KeyAndInfo));
}

KeyAndInfoContainer::KeyAndInfoContainer(const unsigned char *data)
{
	memcpy(&keyAndInfo, data, sizeof(KeyAndInfo));
}

KeyAndInfo &KeyAndInfoContainer::getKeyAndInfo()
{
	return keyAndInfo;
}

void KeyAndInfoContainer::setKeyInfoKeyLength(unsigned int length)
{
	keyAndInfo.keyInfo.keyLength = length;
}

void KeyAndInfoContainer::setKeyInfo(const KeyComponentsInfo *keyComponentsInfo)
{
	memcpy(&(keyAndInfo.keyInfo), keyComponentsInfo, sizeof(KeyComponentsInfo));
}

KeyAndInfoContainer::~KeyAndInfoContainer()
{
	// overwrite key
	ZeroMemory(reinterpret_cast<unsigned char*>(&keyAndInfo), sizeof(KeyAndInfo));
}

KeyProvider::KeyProvider() :
	m_domainKEK(NULL),
	m_isInitialized(false)
{
	LogDebug("Created empty KeyProvider");
}

KeyProvider::KeyProvider(
	const RawBuffer &domainKEKInWrapForm,
	const Password &password) :
	m_domainKEK(new KeyAndInfoContainer()),
	m_isInitialized(true)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!. Should not happened");

	if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << domainKEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store WrappedKeyAndInfo in KeyProvider Constructor");
	}

	unwrapDomainKEK(domainKEKInWrapForm, password, *m_domainKEK);
}

KeyProvider &KeyProvider::operator=(KeyProvider &&second)
{
	LogDebug("Moving KeyProvider");

	if (this == &second)
		return *this;

	m_isInitialized = second.m_isInitialized;
	m_domainKEK = second.m_domainKEK;
	second.m_isInitialized = false;
	second.m_domainKEK = NULL;
	return *this;
}

KeyProvider::KeyProvider(KeyProvider &&second)
{
	LogDebug("Moving KeyProvider");
	m_isInitialized = second.m_isInitialized;
	m_domainKEK = second.m_domainKEK;
	second.m_isInitialized = false;
	second.m_domainKEK = NULL;
}

bool KeyProvider::isInitialized()
{
	return m_isInitialized;
}

RawBuffer KeyProvider::getPureDomainKEK()
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	// TODO secure
	return RawBuffer(m_domainKEK->getKeyAndInfo().key,
					 (m_domainKEK->getKeyAndInfo().key) +
					 m_domainKEK->getKeyAndInfo().keyInfo.keyLength);
}

RawBuffer KeyProvider::getWrappedDomainKEK(const Password &password)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	return wrapDomainKEK(*m_domainKEK, password);
}


RawBuffer KeyProvider::getPureDEK(const RawBuffer &DEKInWrapForm)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	if (DEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << DEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store "
				 "WrappedKeyAndInfo in KeyProvider::getPureDEK");
	}

	KeyAndInfoContainer kmcDEK = KeyAndInfoContainer();
	WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer(
			DEKInWrapForm.data());

	KeyData PKEK2 = makePKEK2(m_domainKEK->getKeyAndInfo().key,
	                          wkmcDEK.getWrappedKeyAndInfo().keyInfo.client);

	int keyLength;
	if (0 > (keyLength = decryptAes256Gcm(
							 wkmcDEK.getWrappedKeyAndInfo().wrappedKey,
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.keyLength,
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag,
							 PKEK2.data(),
							 wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
							 kmcDEK.getKeyAndInfo().key)))
		ThrowErr(Exc::InternalError,
				 "UnwrapDEK Failed in KeyProvider::getPureDEK");

	kmcDEK.setKeyInfoKeyLength((unsigned int)keyLength);

	LogDebug("getPureDEK SUCCESS");
	return RawBuffer(
			   kmcDEK.getKeyAndInfo().key,
			   (kmcDEK.getKeyAndInfo().key) + kmcDEK.getKeyAndInfo().keyInfo.keyLength);
}

RawBuffer KeyProvider::generateDEK(const std::string &client)
{
	if (!m_isInitialized)
		ThrowErr(Exc::InternalError, "Object not initialized!");

	WrappedKeyAndInfoContainer wkmcDEK = WrappedKeyAndInfoContainer();
	std::string resized_client;

	if (client.length() < MAX_CLIENT_ID_SIZE)
		resized_client = client;
	else
		resized_client = client.substr(0, MAX_CLIENT_ID_SIZE - 1);

	uint8_t key[MAX_KEY_SIZE];

	if (!randomize(key) || !randomize(wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv))
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");

	KeyData PKEK2 = makePKEK2(m_domainKEK->getKeyAndInfo().key, resized_client);

	int wrappedKeyLength;
	if (0 > (wrappedKeyLength = encryptAes256Gcm(key,
	                                             m_domainKEK->getKeyAndInfo().keyInfo.keyLength,
	                                             PKEK2.data(),
	                                             wkmcDEK.getWrappedKeyAndInfo().keyInfo.iv,
	                                             wkmcDEK.getWrappedKeyAndInfo().wrappedKey,
	                                             wkmcDEK.getWrappedKeyAndInfo().keyInfo.tag)))
		ThrowErr(Exc::InternalError, "GenerateDEK Failed in KeyProvider::generateDEK");

	wkmcDEK.setKeyInfoKeyLength((unsigned int)wrappedKeyLength);
	wkmcDEK.setKeyInfoClient(resized_client);

	LogDebug("GenerateDEK Success");
	return toRawBuffer(wkmcDEK.getWrappedKeyAndInfo());
}

RawBuffer KeyProvider::reencrypt(
	const RawBuffer &domainKEKInWrapForm,
	const Password &oldPass,
	const Password &newPass)
{
	if (domainKEKInWrapForm.size() != sizeof(WrappedKeyAndInfo)) {
		LogError("input size:" << domainKEKInWrapForm.size()
				 << " Expected: " << sizeof(WrappedKeyAndInfo));
		ThrowErr(Exc::InternalError,
				 "buffer doesn't have proper size to store "
				 "WrappedKeyAndInfo in KeyProvider::reencrypt");
	}

	KeyAndInfoContainer domainKEK;
	unwrapDomainKEK(domainKEKInWrapForm, oldPass, domainKEK);
	return wrapDomainKEK(domainKEK, newPass);
}

RawBuffer KeyProvider::generateDomainKEK(
	const std::string &user,
	const Password &userPassword)
{
	WrappedKeyAndInfoContainer wkmcDKEK = WrappedKeyAndInfoContainer();

	KeyAndInfoContainer domainKEK;

	if (!randomize(domainKEK.getKeyAndInfo().keyInfo.salt) ||
		!randomize(domainKEK.getKeyAndInfo().key) ||
	    !randomize(domainKEK.getKeyAndInfo().keyInfo.iv)) {
		ThrowErr(Exc::InternalError, "OPENSSL_ENGINE_ERROR");
	}

	domainKEK.setKeyInfoKeyLength(sizeof(domainKEK.getKeyAndInfo().key));

	if (user.size() >= sizeof(domainKEK.getKeyAndInfo().keyInfo.client)) {
		ThrowErr(Exc::InternalError, "Client name too long");
	}
	strcpy(domainKEK.getKeyAndInfo().keyInfo.client, user.c_str());

	return wrapDomainKEK(domainKEK, userPassword);
}

int KeyProvider::initializeLibrary()
{
	LogDebug("initializeLibrary Success");
	return SUCCESS;
}

int KeyProvider::closeLibrary()
{
	LogDebug("closeLibrary Success");
	return SUCCESS;
}

KeyProvider::~KeyProvider()
{
	LogDebug("KeyProvider Destructor");
}