2 * Copyright (c) 2017-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
18 * @author Krzysztof Dynowski (k.dynowski@samsung.com)
19 * @author Lukasz Kostyra (l.kostyra@samsung.com)
23 #include <generic-backend/exception.h>
24 #include <generic-backend/algo-validation.h>
25 #include <generic-backend/crypto-params.h>
26 #include <dpl/log/log.h>
28 #include <openssl/evp.h>
29 #include <openssl/dsa.h>
30 #include <openssl/ec.h>
31 #include <openssl/bio.h>
32 #include <openssl/bn.h>
34 #include <tz-backend/internals.h>
35 #include <tz-backend/tz-context.h>
36 #include <openssl-error-handler.h>
37 #include <km_ta_defines.h>
42 #ifndef __has_cpp_attribute
43 #define __has_cpp_attribute(_) 0
46 #if __has_cpp_attribute(fallthrough)
47 #define fallthru [[fallthrough]]
49 #define fallthru ((void)0)
54 CKM::RawBuffer extractBignumData(const BIGNUM* bn)
56 size_t size = static_cast<size_t>(BN_num_bytes(bn));
58 CKM::RawBuffer result(size);
59 int ret = BN_bn2bin(bn, result.data());
60 if (ret != static_cast<int>(size)) {
61 ThrowErr(CKM::Exc::Crypto::InternalError,
62 "Error while converting bignums - expected "
63 + std::to_string(size) + " bytes of data, got " + std::to_string(ret));
69 void generateDSAParams(const int sizeBits, CKM::RawBuffer &prime,
70 CKM::RawBuffer &subprime, CKM::RawBuffer &base)
72 auto dsa = uptr<DSA_free>(DSA_new());
74 ThrowErr(CKM::Exc::Crypto::InternalError,
75 "Failed to create DSA context for parameter gen");
78 if (DSA_generate_parameters_ex(dsa.get(), sizeBits, NULL, 0, NULL, NULL, NULL) == 0) {
79 ThrowErr(CKM::Exc::Crypto::InternalError,
80 "Failed to generate DSA params, err = " + std::to_string(ERR_get_error()));
83 // at this stage dsa->p, dsa->q & dsa->r should contain our params
84 // extract them into buffers
85 const BIGNUM *p, *q, *g;
86 DSA_get0_pqg(dsa.get(), &p, &q, &g);
87 prime = extractBignumData(p);
88 subprime = extractBignumData(q);
89 base = extractBignumData(g);
92 tz_data_type toTzDataType(const CKM::DataType dataType) {
94 case CKM::DataType::BINARY_DATA: return TYPE_GENERIC_SECRET;
95 case CKM::DataType::KEY_AES: return TYPE_SKEY;
96 case CKM::DataType::KEY_DSA_PRIVATE: return TYPE_AKEY_PRIVATE_DSA;
97 case CKM::DataType::KEY_RSA_PRIVATE: return TYPE_AKEY_PRIVATE_RSA;
98 case CKM::DataType::KEY_DSA_PUBLIC: return TYPE_AKEY_PUBLIC_DSA;
99 case CKM::DataType::KEY_RSA_PUBLIC: return TYPE_AKEY_PUBLIC_RSA;
101 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
102 "Data type could not be imported by tz-backend");
106 tz_ec toTzEc(CKM::ElipticCurve ec)
109 case CKM::ElipticCurve::prime192v1: return EC_NIST_P192;
110 case CKM::ElipticCurve::prime256v1: return EC_NIST_P256;
111 case CKM::ElipticCurve::secp384r1: return EC_NIST_P384;
112 default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "EC not supported by tz-backend");
116 tz_prf toTzPrf(CKM::KdfPrf prf)
119 case CKM::KdfPrf::HMAC_SHA256: return PRF_HMAC_SHA256;
120 case CKM::KdfPrf::HMAC_SHA384: return PRF_HMAC_SHA384;
121 case CKM::KdfPrf::HMAC_SHA512: return PRF_HMAC_SHA512;
122 default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "PRF not supported by tz-backend");
126 tz_kbkdf_mode toTzKbkdfMode(CKM::KbkdfMode mode)
129 case CKM::KbkdfMode::COUNTER: return KBKDF_MODE_COUNTER;
131 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "KBKDF mode not supported by tz-backend");
135 tz_kbkdf_ctr_loc toTzCtrLoc(CKM::KbkdfCounterLocation loc)
138 case CKM::KbkdfCounterLocation::BEFORE_FIXED: return KBKDF_LOC_BEFORE_FIXED;
139 case CKM::KbkdfCounterLocation::AFTER_FIXED: return KBKDF_LOC_AFTER_FIXED;
140 case CKM::KbkdfCounterLocation::MIDDLE_FIXED: return KBKDF_LOC_MIDDLE_FIXED;
142 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
143 "KBKDF counter location not supported by tz-backend");
152 namespace Internals {
156 tz_algo_type getGenSKeyType(AlgoType type)
160 case AlgoType::AES_GEN: return ALGO_AES_GEN;
161 default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
165 tz_algo_type getAlgType(AlgoType type)
169 case AlgoType::AES_CBC: return ALGO_AES_CBC;
170 case AlgoType::AES_CTR: return ALGO_AES_CTR;
171 case AlgoType::AES_CFB: return ALGO_AES_CFB;
172 case AlgoType::AES_GCM: return ALGO_AES_GCM;
173 case AlgoType::RSA_OAEP: return ALGO_RSA;
174 case AlgoType::RSA_SV: return ALGO_RSA_SV;
175 case AlgoType::DSA_SV: return ALGO_DSA_SV;
176 case AlgoType::ECDSA_SV: return ALGO_ECDSA_SV;
177 default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
181 tz_hash_type getHashType(HashAlgorithm hash)
185 case HashAlgorithm::SHA1: return HASH_SHA1;
186 case HashAlgorithm::SHA256: return HASH_SHA256;
187 case HashAlgorithm::SHA384: return HASH_SHA384;
188 case HashAlgorithm::SHA512: return HASH_SHA512;
190 ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
194 void decompose(const CryptoAlgorithm &alg,
196 uint32_t &ctrLenOrTagSizeBits,
200 algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
202 case AlgoType::AES_CTR:
203 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
204 ctrLenOrTagSizeBits = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
205 // counter length is in bits
206 if (ctrLenOrTagSizeBits != Params::DEFAULT_AES_IV_LEN * 8) {
207 LogError("CTR length invalid: " << std::to_string(ctrLenOrTagSizeBits));
208 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
211 case AlgoType::AES_CBC:
212 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
214 case AlgoType::AES_CFB:
215 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
217 case AlgoType::AES_GCM:
218 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
219 alg.getParam(ParamName::ED_TAG_LEN, ctrLenOrTagSizeBits);
220 alg.getParam(ParamName::ED_AAD, aad);
222 case AlgoType::RSA_OAEP:
225 ThrowErr(Exc::Crypto::InputParam, "Invalid decryption algorithm");
232 RawBuffer generateIV()
235 TrustZoneContext::Instance().generateIV(result);
239 void generateSKey(const CryptoAlgorithm &alg,
243 const RawBuffer &hash)
245 AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
246 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
250 ThrowErr(Exc::InputParam, "Key generation with password encryption requires an IV");
253 RawBuffer pwdBuf(pwd.begin(), pwd.end());
254 TrustZoneContext::Instance().generateSKeyPwd(getGenSKeyType(keyType),
258 TrustZoneContext::Instance().generateSKey(getGenSKeyType(keyType), keyBits,
264 AlgoType generateAKey(const CryptoAlgorithm &alg,
265 const Password &pubPwd,
266 const Password &privPwd,
267 const RawBuffer &pubPwdIv,
268 const RawBuffer &privPwdIv,
271 const RawBuffer &hashPriv,
272 const RawBuffer &hashPub)
274 AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
278 pubPwdBuf.assign(pubPwd.begin(), pubPwd.end());
280 RawBuffer privPwdBuf;
281 if (!privPwd.empty())
282 privPwdBuf.assign(privPwd.begin(), privPwd.end());
285 case AlgoType::RSA_GEN: {
286 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
287 TrustZoneContext::Instance().generateRSAKey(keyBits,
298 case AlgoType::DSA_GEN: {
299 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
303 generateDSAParams(keyBits, prime, subprime, base);
304 TrustZoneContext::Instance().generateDSAKey(keyBits,
318 case AlgoType::ECDSA_GEN: {
319 CKM::ElipticCurve ec = unpack<CKM::ElipticCurve>(alg, ParamName::GEN_EC);
320 TrustZoneContext::Instance().generateECKey(toTzEc(ec),
332 ThrowErr(Exc::Crypto::InputParam,
333 "Invalid algo type provided for generateAKey function");
340 void destroyKey(const RawBuffer &keyId)
342 TrustZoneContext::Instance().executeDestroy(keyId);
345 void importData(const Data &data,
346 const EncryptionParams &encData,
348 const RawBuffer &pwdIV,
350 const RawBuffer &hash)
353 const auto dataType = toTzDataType(data.type);
355 RawBuffer pwdBuf(pwd.begin(), pwd.end());
356 uint32_t keySizeBits = data.data.size() * 8;
357 TrustZoneContext::Instance().importData(dataType,
367 void importWrappedKey(const RawBuffer &wrappingKeyId,
368 const Pwd &wrappingKeyPwd,
369 const CryptoAlgorithm &alg,
370 const Data &encryptedKey,
371 const Password &encryptedKeyPassword,
372 const RawBuffer &encryptedKeyIV,
373 RawBuffer &encryptedKeyTag,
374 const RawBuffer &encryptedKeyId)
376 RawBuffer encryptedKeyPwdBuf(encryptedKeyPassword.begin(), encryptedKeyPassword.end());
379 uint32_t ctrLenOrTagSizeBits = 0;
382 decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad);
385 TrustZoneContext::Instance().importWrappedKey(wrappingKeyId,
391 toTzDataType(encryptedKey.type),
399 RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId,
400 const Pwd &wrappingKeyPwd,
401 const CryptoAlgorithm &alg,
402 const RawBuffer &keyToWrapId,
403 const Pwd &keyToWrapPwd)
406 uint32_t ctrLenOrTagSizeBits = 0;
409 decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad);
412 return TrustZoneContext::Instance().exportWrappedKey(wrappingKeyId,
422 RawBuffer getData(const RawBuffer &dataId,
426 TrustZoneContext::Instance().getData(dataId,
432 void destroyData(const RawBuffer &dataId)
434 TrustZoneContext::Instance().destroyData(dataId);
437 BufferPair encryptDataAesGcm(const RawBuffer &keyId,
441 const RawBuffer &data,
442 const RawBuffer &aad)
447 TrustZoneContext::Instance().executeEncryptAE(keyId, pwd, iv, tagSize,
448 aad, data, result, tag);
450 return std::make_pair(result, tag);
453 RawBuffer encryptDataAesGcmPacked(const RawBuffer &keyId,
457 const RawBuffer &data,
458 const RawBuffer &aad)
460 auto pair = encryptDataAesGcm(keyId, pwd, iv, tagSize, data, aad);
461 std::copy(pair.second.begin(), pair.second.end(),
462 std::back_inserter(pair.first));
466 RawBuffer decryptDataAesGcm(const RawBuffer &keyId,
470 const RawBuffer &tag,
471 const RawBuffer &data,
472 const RawBuffer &aad)
476 TrustZoneContext::Instance().executeDecryptAE(keyId, pwd, iv, tagSizeBits,
477 tag, aad, data, result);
482 RawBuffer decryptDataAesGcmPacked(const RawBuffer &keyId,
486 const RawBuffer &data,
487 const RawBuffer &aad)
489 int tagSizeBytes = tagSizeBits / 8;
490 if (tagSizeBytes > static_cast<int>(data.size()))
491 ThrowErr(Exc::Crypto::InputParam, "Wrong size of tag");
493 auto tagPos = data.data() + data.size() - tagSizeBytes;
494 return decryptDataAesGcm(keyId,
498 RawBuffer(tagPos, data.data() + data.size()),
499 RawBuffer(data.data(), tagPos),
504 RawBuffer symmetricEncrypt(const RawBuffer &keyId,
506 const CryptoAlgorithm &alg,
507 const RawBuffer &data)
509 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
513 case AlgoType::AES_CTR: {
514 ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
515 // counter length is in bits
516 if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
517 LogError("CTR length invalid: " << std::to_string(ctrLen));
518 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
520 // no break here, we still need to slide down to executeCrypt
523 case AlgoType::AES_CBC:
524 case AlgoType::AES_CFB: {
526 TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
530 unpack<RawBuffer>(alg, ParamName::ED_IV),
535 case AlgoType::AES_GCM: {
536 int tagLenBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
537 alg.getParam(ParamName::ED_TAG_LEN, tagLenBits);
539 alg.getParam(ParamName::ED_AAD, aad);
540 return encryptDataAesGcmPacked(keyId,
542 unpack<RawBuffer>(alg, ParamName::ED_IV),
551 ThrowErr(Exc::Crypto::OperationNotSupported,
552 "Incorrect algorithm provided for symmetric crypto operation");
555 RawBuffer symmetricDecrypt(const RawBuffer &keyId,
557 const CryptoAlgorithm &alg,
558 const RawBuffer &data)
560 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
564 case AlgoType::AES_CTR: {
565 ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
566 // counter length is in bits
567 if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
568 LogError("CTR length invalid: " << std::to_string(ctrLen));
569 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
571 // no break here, we still need to slide down to executeCrypt
574 case AlgoType::AES_CBC:
575 case AlgoType::AES_CFB: {
577 TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
581 unpack<RawBuffer>(alg, ParamName::ED_IV),
586 case AlgoType::AES_GCM: {
587 int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
588 alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
590 alg.getParam(ParamName::ED_AAD, aad);
591 return decryptDataAesGcmPacked(keyId,
593 unpack<RawBuffer>(alg, ParamName::ED_IV),
602 ThrowErr(Exc::Crypto::OperationNotSupported,
603 "Incorrect algorithm provided for symmetric crypto operation");
606 RawBuffer asymmetricEncrypt(const RawBuffer &keyId,
608 const CryptoAlgorithm &alg,
609 const RawBuffer &data)
611 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
616 case AlgoType::RSA_OAEP: {
617 TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
621 result, // unused dummy
630 ThrowErr(Exc::Crypto::OperationNotSupported,
631 "Incorrect algorithm provided for asymmetric crypto operation");
634 RawBuffer asymmetricDecrypt(const RawBuffer &keyId,
636 const CryptoAlgorithm &alg,
637 const RawBuffer &cipher)
639 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
644 case AlgoType::RSA_OAEP: {
645 TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
649 result, // unused dummy
658 ThrowErr(Exc::Crypto::OperationNotSupported,
659 "Incorrect algorithm provided for asymmetric crypto operation");
662 uint32_t initCipher(const RawBuffer &keyId,
664 const CryptoAlgorithm &alg,
667 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
671 case AlgoType::AES_GCM: {
672 int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
673 alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
675 alg.getParam(ParamName::ED_AAD, aad);
676 return TrustZoneContext::Instance().initGcmCipher(encrypt ? CIPHER_ENCRYPT : CIPHER_DECRYPT,
679 unpack<RawBuffer>(alg, ParamName::ED_IV),
683 case AlgoType::AES_CBC:
684 case AlgoType::AES_CTR:
685 case AlgoType::AES_CFB:
686 // TODO optionally implement above modes as well
691 ThrowErr(Exc::Crypto::OperationNotSupported,
692 "Incorrect algorithm provided for symmetric crypto operation");
695 void addAAD(uint32_t opId,
696 const RawBuffer &aad)
698 TrustZoneContext::Instance().addGcmAAD(opId, aad);
701 RawBuffer updateCipher(uint32_t opId,
702 const RawBuffer &data)
704 return TrustZoneContext::Instance().updateGcmCipher(opId, data);
707 RawBuffer finalizeCipher(uint32_t opId,
708 const RawBuffer &data)
710 return TrustZoneContext::Instance().finalizeGcmCipher(opId, data);
713 RawBuffer sign(const RawBuffer &pkeyId,
715 const CryptoAlgorithm &alg,
716 const RawBuffer &message)
718 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
719 HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
720 if (algo != AlgoType::RSA_SV && hash == HashAlgorithm::NONE)
721 ThrowErr(Exc::Crypto::InputParam, "Only RSA supports no hash option");
724 TrustZoneContext::Instance().executeSign(getAlgType(algo),
733 int verify(const RawBuffer &pkeyId,
735 const CryptoAlgorithm &alg,
736 const RawBuffer &message,
737 const RawBuffer &signature)
739 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
740 HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
741 if (algo != AlgoType::RSA_SV && hash == HashAlgorithm::NONE)
742 ThrowErr(Exc::Crypto::InputParam, "Only RSA supports no hash option");
744 return TrustZoneContext::Instance().executeVerify(getAlgType(algo),
752 void deriveECDH(const RawBuffer &prvKeyId,
753 const Pwd &prvKeyPwd,
754 const RawBuffer &pubKey,
755 const Password &secretPwd,
756 const RawBuffer &secretPwdIV,
757 RawBuffer &secretTag,
758 const RawBuffer &secretHash)
760 auto peerKey = std::make_shared<KeyImpl>(pubKey);
761 if (peerKey->getType() != KeyType::KEY_ECDSA_PUBLIC)
762 ThrowErr(Exc::Crypto::InputParam, "ECDH requires peer's public EC key");
763 auto peerEvp = peerKey->getEvpShPtr().get();
766 int subType = EVP_PKEY_type(EVP_PKEY_id(peerEvp));
767 if (subType != EVP_PKEY_EC)
768 ThrowErr(Exc::Crypto::InputParam, "Invalid key type: ", subType);
770 auto ecKey = EVP_PKEY_get0_EC_KEY(peerEvp);
772 ThrowErr(Exc::Crypto::InternalError, "Can't get EC key");
774 auto ecPoint = EC_KEY_get0_public_key(ecKey);
776 ThrowErr(Exc::Crypto::InternalError, "Can't get EC public key");
778 auto ecGroup = EC_KEY_get0_group(ecKey);
780 ThrowErr(Exc::Crypto::InternalError, "Can't get EC group");
782 BIGNUM *x = BN_new();
783 BIGNUM *y = BN_new();
784 if (!EC_POINT_get_affine_coordinates(ecGroup, ecPoint, x, y, NULL))
785 ThrowErr(Exc::Crypto::InternalError, "Failed to get EC pub key coordinates");
787 auto xBuf = extractBignumData(x);
788 auto yBuf = extractBignumData(y);
790 RawBuffer secretPwdBuf(secretPwd.begin(), secretPwd.end());
792 TrustZoneContext::Instance().executeEcdh(prvKeyId,
802 void deriveKBKDF(const RawBuffer &secretId,
803 const CryptoAlgorithm &alg,
804 const Password &keyPwd,
805 const RawBuffer &keyPwdIV,
807 const RawBuffer &keyHash)
809 RawBuffer label, context, fixed;
810 alg.getParam(ParamName::KBKDF_LABEL, label);
811 alg.getParam(ParamName::KBKDF_CONTEXT, context);
812 alg.getParam(ParamName::KBKDF_FIXED_INPUT, fixed);
813 auto prf = unpack<KdfPrf>(alg, ParamName::KDF_PRF);
814 auto mode = unpack<KbkdfMode>(alg, ParamName::KBKDF_MODE);
815 auto location = unpack<KbkdfCounterLocation>(alg, ParamName::KBKDF_COUNTER_LOCATION);
817 size_t rlen = 32, llen = 32, dummy;
818 alg.getParam(ParamName::KBKDF_RLEN, rlen);
819 alg.getParam(ParamName::KBKDF_LLEN, llen);
820 bool noSeparator = alg.getParam(ParamName::KBKDF_NO_SEPARATOR, dummy);
822 RawBuffer keyPwdBuf(keyPwd.begin(), keyPwd.end());
824 TrustZoneContext::Instance().executeKbkdf(secretId,
830 toTzCtrLoc(location),
841 } // namespace Internals
843 } // namespace Crypto