summaryrefslogtreecommitdiff
path: root/src/manager/crypto/tz-backend/internals.cpp
blob: 7b7b9be1826a706ee0397f681dc9c484b8098922 (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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/*
 *  Copyright (c) 2017 - 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
 */
/*
 * @file       internals.h
 * @author     Krzysztof Dynowski (k.dynowski@samsung.com)
 * @author     Lukasz Kostyra (l.kostyra@samsung.com)
 * @version    1.0
 */

#include <generic-backend/exception.h>
#include <generic-backend/algo-validation.h>
#include <generic-backend/crypto-params.h>
#include <dpl/log/log.h>
#include <openssl/evp.h>
#include <openssl/dsa.h>
#include <openssl/bio.h>
#include <openssl/bn.h>

#include <tz-backend/internals.h>
#include <tz-backend/tz-context.h>
#include <openssl-error-handler.h>
#include <km_ta_defines.h>

#include <functional>

namespace {

using DSAPtr = std::unique_ptr<DSA, std::function<void(DSA*)>>;

CKM::RawBuffer extractBignumData(BIGNUM* bn)
{
	size_t size = static_cast<size_t>(BN_num_bytes(bn));

	CKM::RawBuffer result(size);
	int ret = BN_bn2bin(bn, result.data());
	if (ret != static_cast<int>(size)) {
		ThrowErr(CKM::Exc::Crypto::InternalError,
			"Error while converting bignums - expected "
			+ std::to_string(size) + " bytes of data, got " + std::to_string(ret));
	}

	return result;
}

void generateDSAParams(const int sizeBits, CKM::RawBuffer &prime,
					CKM::RawBuffer &subprime, CKM::RawBuffer &base)
{
	DSAPtr dsa(DSA_new(), DSA_free);
	if (!dsa) {
		ThrowErr(CKM::Exc::Crypto::InternalError,
			"Failed to create DSA context for parameter gen");
	}

	if (DSA_generate_parameters_ex(dsa.get(), sizeBits, NULL, 0, NULL, NULL, NULL) == 0) {
		ThrowErr(CKM::Exc::Crypto::InternalError,
			"Failed to generate DSA params, err = " + std::to_string(ERR_get_error()));
	}

	// at this stage dsa->p, dsa->q & dsa->r should contain our params
	// extract them into buffers
	prime = extractBignumData(dsa->p);
	subprime = extractBignumData(dsa->q);
	base = extractBignumData(dsa->g);
}

} // namespace

namespace CKM {
namespace Crypto {
namespace TZ {
namespace Internals {

tz_algo_type getGenSKeyType(AlgoType type)
{
	switch (type)
	{
	case AlgoType::AES_GEN:	return ALGO_AES_GEN;
	default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
	}
}

tz_algo_type getAlgType(AlgoType type)
{
	switch (type)
	{
	case AlgoType::AES_CBC: return ALGO_AES_CBC;
	case AlgoType::AES_CTR: return ALGO_AES_CTR;
	case AlgoType::AES_CFB: return ALGO_AES_CFB;
	case AlgoType::AES_GCM: return ALGO_AES_GCM;
	case AlgoType::RSA_OAEP: return ALGO_RSA;
	case AlgoType::RSA_SV: return ALGO_RSA_SV;
	case AlgoType::DSA_SV: return ALGO_DSA_SV;
	case AlgoType::ECDSA_SV: return ALGO_ECDSA_SV;
	default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
	};
}

tz_algo_type getAlgType(KeyType keyType)
{
	switch (keyType)
	{
	case KeyType::KEY_AES:
		return ALGO_AES_GEN;
	case KeyType::KEY_RSA_PUBLIC:
	case KeyType::KEY_RSA_PRIVATE:
		return ALGO_RSA_GEN;
	case KeyType::KEY_DSA_PUBLIC:
	case KeyType::KEY_DSA_PRIVATE:
		return ALGO_DSA_GEN;
	case KeyType::KEY_ECDSA_PUBLIC:
	case KeyType::KEY_ECDSA_PRIVATE:
		return ALGO_ECDSA_GEN;
	default:
		ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
	};
}

tz_hash_type getHashType(HashAlgorithm hash)
{
	switch (hash)
	{
	case HashAlgorithm::SHA1: return HASH_SHA1;
	case HashAlgorithm::SHA256: return HASH_SHA256;
	case HashAlgorithm::SHA384: return HASH_SHA384;
	case HashAlgorithm::SHA512: return HASH_SHA512;
	default:
		ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
	}
}

RawBuffer generateIV()
{
	RawBuffer result;
	TrustZoneContext::Instance().generateIV(result);
	return result;
}

Data generateSKey(const CryptoAlgorithm &alg,
				const Password &pwd,
				const RawBuffer &iv,
				RawBuffer &tag)
{
	AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);

	Data keyData;
	keyData.type = DataType(KeyType::KEY_AES);

	if (!pwd.empty()) {
		if (iv.empty()) {
			ThrowErr(Exc::InputParam, "Key generation with password encryption requires an IV");
		}

		RawBuffer pwdBuf(pwd.begin(), pwd.end());
		TrustZoneContext::Instance().generateSKeyPwd(getGenSKeyType(keyType),
													pwdBuf, iv, keyBits,
													keyData.data, tag);
	} else {
		TrustZoneContext::Instance().generateSKey(getGenSKeyType(keyType), keyBits,
												keyData.data);
	}

	return keyData;
}

DataPair generateAKey(const CryptoAlgorithm &alg,
					const Password &pubPwd,
					const Password &privPwd,
					const RawBuffer &pubPwdIv,
					const RawBuffer &privPwdIv,
					RawBuffer &pubTag,
					RawBuffer &privTag)
{
	AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);

	Data pubKeyData;
	Data privKeyData;

	RawBuffer pubPwdBuf;
	if (!pubPwd.empty())
		pubPwdBuf.assign(pubPwd.begin(), pubPwd.end());

	RawBuffer privPwdBuf;
	if (!privPwd.empty())
		privPwdBuf.assign(privPwd.begin(), privPwd.end());

	switch (keyType) {
	case AlgoType::RSA_GEN: {
		pubKeyData.type = DataType(KeyType::KEY_RSA_PUBLIC);
		privKeyData.type = DataType(KeyType::KEY_RSA_PRIVATE);

		TrustZoneContext::Instance().generateRSAKey(keyBits,
													pubPwdBuf,
													pubPwdIv,
													privPwdBuf,
													privPwdIv,
													pubKeyData.data,
													pubTag,
													privKeyData.data,
													privTag);
		break;
	}
	case AlgoType::DSA_GEN: {
		pubKeyData.type = DataType(KeyType::KEY_DSA_PUBLIC);
		privKeyData.type = DataType(KeyType::KEY_DSA_PRIVATE);

		RawBuffer prime;
		RawBuffer subprime;
		RawBuffer base;
		generateDSAParams(keyBits, prime, subprime, base);
		TrustZoneContext::Instance().generateDSAKey(keyBits,
													prime,
													subprime,
													base,
													pubPwdBuf,
													pubPwdIv,
													privPwdBuf,
													privPwdIv,
													pubKeyData.data,
													pubTag,
													privKeyData.data,
													privTag);
		break;
	}
	default: {
		ThrowErr(Exc::Crypto::InputParam,
			"Invalid algo type provided for generateAKey function");
	}
	}

	return DataPair(pubKeyData, privKeyData);
}

void destroyKey(const RawBuffer &key)
{
	TrustZoneContext::Instance().executeDestroy(key);
}

RawBuffer importData(const Data &data,
					 const EncryptionParams &encData,
					 const Password &pwd,
					 const RawBuffer &pwdIV,
					 RawBuffer &tag)
{

	uint32_t dataType;

	if (data.type.isSKey()) {
		dataType = TYPE_SKEY;
	} else if (data.type.isBinaryData()) {
		dataType = TYPE_GENERIC_SECRET;
	} else if (data.type.isKeyPrivate()) {
		dataType = TYPE_AKEY_PRIVATE;
	} else if (data.type.isKeyPublic()) {
		dataType = TYPE_AKEY_PUBLIC;
	} else {
		ThrowErr(Exc::Crypto::DataTypeNotSupported,
			"Data type could not be impoted by tz-backend");
	}

	RawBuffer result;

	RawBuffer pwdBuf(pwd.begin(), pwd.end());
	uint32_t keySizeBits = data.data.size() * 8;
	TrustZoneContext::Instance().importData(dataType,
										data.data,
										encData,
										pwdBuf,
										pwdIV,
										keySizeBits,
										Params::DERIVED_KEY_LENGTH_BITS,
										result,
										tag);
	return result;
}

RawBuffer getData(const RawBuffer &dataId,
				  const Pwd &pwd)
{
	RawBuffer result;
	TrustZoneContext::Instance().getData(dataId,
				 pwd,
				 result);
	return result;
}

void destroyData(const RawBuffer &dataId)
{
	TrustZoneContext::Instance().destroyData(dataId);
}

BufferPair encryptDataAesGcm(const RawBuffer &key,
							const Pwd &pwd,
							const RawBuffer &iv,
							int tagSize,
							const RawBuffer &data,
							const RawBuffer &aad)
{
	RawBuffer result;
	RawBuffer tag;

	TrustZoneContext::Instance().executeEncryptAE(key, pwd, iv, tagSize,
												aad, data, result, tag);

	return std::make_pair(result, tag);
}

RawBuffer encryptDataAesGcmPacked(const RawBuffer &key,
								const Pwd &pwd,
								const RawBuffer &iv,
								int tagSize,
								const RawBuffer &data,
								const RawBuffer &aad)
{
	auto pair = encryptDataAesGcm(key, pwd, iv, tagSize, data, aad);
	std::copy(pair.second.begin(), pair.second.end(),
			std::back_inserter(pair.first));
	return pair.first;
}

RawBuffer decryptDataAesGcm(const RawBuffer &key,
							const Pwd &pwd,
							const RawBuffer &iv,
							int tagSizeBits,
							const RawBuffer &tag,
							const RawBuffer &data,
							const RawBuffer &aad)
{
	RawBuffer result;

	TrustZoneContext::Instance().executeDecryptAE(key, pwd, iv, tagSizeBits,
												tag, aad, data, result);

	return result;
}

RawBuffer decryptDataAesGcmPacked(const RawBuffer &key,
								const Pwd &pwd,
								const RawBuffer &iv,
								int tagSizeBits,
								const RawBuffer &data,
								const RawBuffer &aad)
{
	int tagSizeBytes = tagSizeBits / 8;
	if (tagSizeBytes > static_cast<int>(data.size()))
		ThrowErr(Exc::Crypto::InputParam, "Wrong size of tag");

	auto tagPos = data.data() + data.size() - tagSizeBytes;
	return decryptDataAesGcm(key,
							pwd,
							iv,
							tagSizeBits,
							RawBuffer(tagPos, data.data() + data.size()),
							RawBuffer(data.data(), tagPos),
							aad);
}


RawBuffer symmetricEncrypt(const RawBuffer &key,
						const Pwd &pwd,
						const CryptoAlgorithm &alg,
						const RawBuffer &data)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	uint64_t ctrLen = 0;

	switch (algo) {
		case AlgoType::AES_CTR: {
			ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
			// counter length is in bits
			if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
				LogError("CTR length invalid: " << std::to_string(ctrLen));
				ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
			}
			// no break here, we still need to slide down to executeCrypt
		}
		case AlgoType::AES_CBC:
		case AlgoType::AES_CFB: {
			RawBuffer result;
			TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
													getAlgType(algo),
													key,
													pwd,
													unpack<RawBuffer>(alg, ParamName::ED_IV),
													data,
													result);
			return result;
		}
		case AlgoType::AES_GCM: {
			int tagLenBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
			alg.getParam(ParamName::ED_TAG_LEN, tagLenBits);
			RawBuffer aad;
			alg.getParam(ParamName::ED_AAD, aad);
			return encryptDataAesGcmPacked(key,
										pwd,
										unpack<RawBuffer>(alg, ParamName::ED_IV),
										tagLenBits,
										data,
										aad);
		}
		default:
			break;
	}

	ThrowErr(Exc::Crypto::OperationNotSupported,
				"Incorrect algorithm provided for symmetric crypto operation");
}

RawBuffer symmetricDecrypt(const RawBuffer &key,
						const Pwd &pwd,
						const CryptoAlgorithm &alg,
						const RawBuffer &data)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	uint64_t ctrLen = 0;

	switch (algo) {
		case AlgoType::AES_CTR: {
			ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
			// counter length is in bits
			if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
				LogError("CTR length invalid: " << std::to_string(ctrLen));
				ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
			}
			// no break here, we still need to slide down to executeCrypt
		}
		case AlgoType::AES_CBC:
		case AlgoType::AES_CFB: {
			RawBuffer result;
			TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
													getAlgType(algo),
													key,
													pwd,
													unpack<RawBuffer>(alg, ParamName::ED_IV),
													data,
													result);
			return result;
		}
		case AlgoType::AES_GCM: {
			int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
			alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
			RawBuffer aad;
			alg.getParam(ParamName::ED_AAD, aad);
			return decryptDataAesGcmPacked(key,
										pwd,
										unpack<RawBuffer>(alg, ParamName::ED_IV),
										tagSizeBits,
										data,
										aad);
		}
		default:
			break;
	}

	ThrowErr(Exc::Crypto::OperationNotSupported,
				"Incorrect algorithm provided for symmetric crypto operation");
}

RawBuffer asymmetricEncrypt(const RawBuffer &key,
							const Pwd &pwd,
							const CryptoAlgorithm &alg,
							const RawBuffer &data)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	RawBuffer result;

	switch (algo)
	{
	case AlgoType::RSA_OAEP: {
		TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
												getAlgType(algo),
												key,
												pwd,
												unpack<RawBuffer>(alg, ParamName::ED_IV),
												data,
												result);
		return result;
	}
	default:
		break;
	}

	ThrowErr(Exc::Crypto::OperationNotSupported,
				"Incorrect algorithm provided for asymmetric crypto operation");
}

RawBuffer asymmetricDecrypt(const RawBuffer &key,
							const Pwd &pwd,
							const CryptoAlgorithm &alg,
							const RawBuffer &cipher)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	RawBuffer result;

	switch (algo)
	{
	case AlgoType::RSA_OAEP: {
		TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
												getAlgType(algo),
												key,
												pwd,
												unpack<RawBuffer>(alg, ParamName::ED_IV),
												cipher,
												result);
		return result;
	}
	default:
		break;
	}

	ThrowErr(Exc::Crypto::OperationNotSupported,
				"Incorrect algorithm provided for asymmetric crypto operation");
}

RawBuffer sign(const RawBuffer &pkey,
			const Pwd &pwd,
			const CryptoAlgorithm &alg,
			const RawBuffer &message)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
	RawBuffer signature;
	TrustZoneContext::Instance().executeSign(getAlgType(algo),
											getHashType(hash),
											pkey,
											pwd,
											message,
											signature);
	return signature;
}

int verify(const RawBuffer &pkey,
		const Pwd &pwd,
		const CryptoAlgorithm &alg,
		const RawBuffer &message,
		const RawBuffer &signature)
{
	AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
	HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
	return TrustZoneContext::Instance().executeVerify(getAlgType(algo),
													getHashType(hash),
													pkey,
													pwd,
													message,
													signature);
}

} // namespace Internals
} // namespace TZ
} // namespace Crypto
} // namespace CKM