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_ECDSA_PRIVATE: return TYPE_AKEY_PRIVATE_EC;
99 case CKM::DataType::KEY_DSA_PUBLIC: return TYPE_AKEY_PUBLIC_DSA;
100 case CKM::DataType::KEY_RSA_PUBLIC: return TYPE_AKEY_PUBLIC_RSA;
101 case CKM::DataType::KEY_ECDSA_PUBLIC: return TYPE_AKEY_PUBLIC_EC;
103 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
104 "Data type could not be imported by tz-backend");
108 tz_ec toTzEc(CKM::ElipticCurve ec)
111 case CKM::ElipticCurve::prime192v1: return EC_NIST_P192;
112 case CKM::ElipticCurve::prime256v1: return EC_NIST_P256;
113 case CKM::ElipticCurve::secp384r1: return EC_NIST_P384;
114 default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "EC not supported by tz-backend");
118 tz_prf toTzPrf(CKM::KdfPrf prf)
121 case CKM::KdfPrf::HMAC_SHA256: return PRF_HMAC_SHA256;
122 case CKM::KdfPrf::HMAC_SHA384: return PRF_HMAC_SHA384;
123 case CKM::KdfPrf::HMAC_SHA512: return PRF_HMAC_SHA512;
124 default: ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "PRF not supported by tz-backend");
128 tz_kbkdf_mode toTzKbkdfMode(CKM::KbkdfMode mode)
131 case CKM::KbkdfMode::COUNTER: return KBKDF_MODE_COUNTER;
133 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported, "KBKDF mode not supported by tz-backend");
137 tz_kbkdf_ctr_loc toTzCtrLoc(CKM::KbkdfCounterLocation loc)
140 case CKM::KbkdfCounterLocation::BEFORE_FIXED: return KBKDF_LOC_BEFORE_FIXED;
141 case CKM::KbkdfCounterLocation::AFTER_FIXED: return KBKDF_LOC_AFTER_FIXED;
142 case CKM::KbkdfCounterLocation::MIDDLE_FIXED: return KBKDF_LOC_MIDDLE_FIXED;
144 ThrowErr(CKM::Exc::Crypto::DataTypeNotSupported,
145 "KBKDF counter location not supported by tz-backend");
154 namespace Internals {
158 tz_algo_type getGenSKeyType(AlgoType type)
162 case AlgoType::AES_GEN: return ALGO_AES_GEN;
163 default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
167 tz_algo_type getAlgType(AlgoType type)
171 case AlgoType::AES_CBC: return ALGO_AES_CBC;
172 case AlgoType::AES_CTR: return ALGO_AES_CTR;
173 case AlgoType::AES_CFB: return ALGO_AES_CFB;
174 case AlgoType::AES_GCM: return ALGO_AES_GCM;
175 case AlgoType::RSA_OAEP: return ALGO_RSA;
176 case AlgoType::RSA_SV: return ALGO_RSA_SV;
177 case AlgoType::DSA_SV: return ALGO_DSA_SV;
178 case AlgoType::ECDSA_SV: return ALGO_ECDSA_SV;
179 default: ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
183 tz_hash_type getHashType(HashAlgorithm hash)
187 case HashAlgorithm::SHA1: return HASH_SHA1;
188 case HashAlgorithm::SHA256: return HASH_SHA256;
189 case HashAlgorithm::SHA384: return HASH_SHA384;
190 case HashAlgorithm::SHA512: return HASH_SHA512;
192 ThrowErr(Exc::Crypto::OperationNotSupported, "Requested algorithm is not supported");
196 void decompose(const CryptoAlgorithm &alg,
198 uint32_t &ctrLenOrTagSizeBits,
202 algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
204 case AlgoType::AES_CTR:
205 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
206 ctrLenOrTagSizeBits = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
207 // counter length is in bits
208 if (ctrLenOrTagSizeBits != Params::DEFAULT_AES_IV_LEN * 8) {
209 LogError("CTR length invalid: " << std::to_string(ctrLenOrTagSizeBits));
210 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
213 case AlgoType::AES_CBC:
214 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
216 case AlgoType::AES_CFB:
217 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
219 case AlgoType::AES_GCM:
220 iv = unpack<RawBuffer>(alg, ParamName::ED_IV);
221 alg.getParam(ParamName::ED_TAG_LEN, ctrLenOrTagSizeBits);
222 alg.getParam(ParamName::ED_AAD, aad);
224 case AlgoType::RSA_OAEP:
227 ThrowErr(Exc::Crypto::InputParam, "Invalid decryption algorithm");
234 RawBuffer generateIV()
237 TrustZoneContext::Instance().generateIV(result);
241 void generateSKey(const CryptoAlgorithm &alg,
245 const RawBuffer &hash)
247 AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
248 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
252 ThrowErr(Exc::InputParam, "Key generation with password encryption requires an IV");
255 RawBuffer pwdBuf(pwd.begin(), pwd.end());
256 TrustZoneContext::Instance().generateSKeyPwd(getGenSKeyType(keyType),
260 TrustZoneContext::Instance().generateSKey(getGenSKeyType(keyType), keyBits,
266 AlgoType generateAKey(const CryptoAlgorithm &alg,
267 const Password &pubPwd,
268 const Password &privPwd,
269 const RawBuffer &pubPwdIv,
270 const RawBuffer &privPwdIv,
273 const RawBuffer &hashPriv,
274 const RawBuffer &hashPub)
276 AlgoType keyType = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
280 pubPwdBuf.assign(pubPwd.begin(), pubPwd.end());
282 RawBuffer privPwdBuf;
283 if (!privPwd.empty())
284 privPwdBuf.assign(privPwd.begin(), privPwd.end());
287 case AlgoType::RSA_GEN: {
288 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
289 TrustZoneContext::Instance().generateRSAKey(keyBits,
300 case AlgoType::DSA_GEN: {
301 int keyBits = unpack<int>(alg, ParamName::GEN_KEY_LEN);
305 generateDSAParams(keyBits, prime, subprime, base);
306 TrustZoneContext::Instance().generateDSAKey(keyBits,
320 case AlgoType::ECDSA_GEN: {
321 CKM::ElipticCurve ec = unpack<CKM::ElipticCurve>(alg, ParamName::GEN_EC);
322 TrustZoneContext::Instance().generateECKey(toTzEc(ec),
334 ThrowErr(Exc::Crypto::InputParam,
335 "Invalid algo type provided for generateAKey function");
342 void destroyKey(const RawBuffer &keyId)
344 TrustZoneContext::Instance().executeDestroy(keyId);
347 void importData(const Data &data,
348 const EncryptionParams &encData,
350 const RawBuffer &pwdIV,
352 const RawBuffer &hash)
355 const auto dataType = toTzDataType(data.type);
357 RawBuffer pwdBuf(pwd.begin(), pwd.end());
358 uint32_t keySizeBits = data.data.size() * 8;
359 TrustZoneContext::Instance().importData(dataType,
369 void importWrappedKey(const RawBuffer &wrappingKeyId,
370 const Pwd &wrappingKeyPwd,
371 const CryptoAlgorithm &alg,
372 const Data &encryptedKey,
373 const Password &encryptedKeyPassword,
374 const RawBuffer &encryptedKeyIV,
375 RawBuffer &encryptedKeyTag,
376 const RawBuffer &encryptedKeyId)
378 RawBuffer encryptedKeyPwdBuf(encryptedKeyPassword.begin(), encryptedKeyPassword.end());
381 uint32_t ctrLenOrTagSizeBits = 0;
384 decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad);
387 TrustZoneContext::Instance().importWrappedKey(wrappingKeyId,
393 toTzDataType(encryptedKey.type),
401 RawBuffer exportWrappedKey(const RawBuffer &wrappingKeyId,
402 const Pwd &wrappingKeyPwd,
403 const CryptoAlgorithm &alg,
404 const RawBuffer &keyToWrapId,
405 const Pwd &keyToWrapPwd)
408 uint32_t ctrLenOrTagSizeBits = 0;
411 decompose(alg, algo, ctrLenOrTagSizeBits, iv, aad);
414 return TrustZoneContext::Instance().exportWrappedKey(wrappingKeyId,
424 RawBuffer getData(const RawBuffer &dataId,
428 TrustZoneContext::Instance().getData(dataId,
434 void destroyData(const RawBuffer &dataId)
436 TrustZoneContext::Instance().destroyData(dataId);
439 BufferPair encryptDataAesGcm(const RawBuffer &keyId,
443 const RawBuffer &data,
444 const RawBuffer &aad)
449 TrustZoneContext::Instance().executeEncryptAE(keyId, pwd, iv, tagSize,
450 aad, data, result, tag);
452 return std::make_pair(result, tag);
455 RawBuffer encryptDataAesGcmPacked(const RawBuffer &keyId,
459 const RawBuffer &data,
460 const RawBuffer &aad)
462 auto pair = encryptDataAesGcm(keyId, pwd, iv, tagSize, data, aad);
463 std::copy(pair.second.begin(), pair.second.end(),
464 std::back_inserter(pair.first));
468 RawBuffer decryptDataAesGcm(const RawBuffer &keyId,
472 const RawBuffer &tag,
473 const RawBuffer &data,
474 const RawBuffer &aad)
478 TrustZoneContext::Instance().executeDecryptAE(keyId, pwd, iv, tagSizeBits,
479 tag, aad, data, result);
484 RawBuffer decryptDataAesGcmPacked(const RawBuffer &keyId,
488 const RawBuffer &data,
489 const RawBuffer &aad)
491 int tagSizeBytes = tagSizeBits / 8;
492 if (tagSizeBytes > static_cast<int>(data.size()))
493 ThrowErr(Exc::Crypto::InputParam, "Wrong size of tag");
495 auto tagPos = data.data() + data.size() - tagSizeBytes;
496 return decryptDataAesGcm(keyId,
500 RawBuffer(tagPos, data.data() + data.size()),
501 RawBuffer(data.data(), tagPos),
506 RawBuffer symmetricEncrypt(const RawBuffer &keyId,
508 const CryptoAlgorithm &alg,
509 const RawBuffer &data)
511 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
515 case AlgoType::AES_CTR: {
516 ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
517 // counter length is in bits
518 if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
519 LogError("CTR length invalid: " << std::to_string(ctrLen));
520 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
522 // no break here, we still need to slide down to executeCrypt
525 case AlgoType::AES_CBC:
526 case AlgoType::AES_CFB: {
528 TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
532 unpack<RawBuffer>(alg, ParamName::ED_IV),
537 case AlgoType::AES_GCM: {
538 int tagLenBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
539 alg.getParam(ParamName::ED_TAG_LEN, tagLenBits);
541 alg.getParam(ParamName::ED_AAD, aad);
542 return encryptDataAesGcmPacked(keyId,
544 unpack<RawBuffer>(alg, ParamName::ED_IV),
553 ThrowErr(Exc::Crypto::OperationNotSupported,
554 "Incorrect algorithm provided for symmetric crypto operation");
557 RawBuffer symmetricDecrypt(const RawBuffer &keyId,
559 const CryptoAlgorithm &alg,
560 const RawBuffer &data)
562 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
566 case AlgoType::AES_CTR: {
567 ctrLen = unpack<uint64_t>(alg, ParamName::ED_CTR_LEN);
568 // counter length is in bits
569 if (ctrLen != Params::DEFAULT_AES_IV_LEN * 8) {
570 LogError("CTR length invalid: " << std::to_string(ctrLen));
571 ThrowErr(Exc::Crypto::InputParam, "Invalid CTR length");
573 // no break here, we still need to slide down to executeCrypt
576 case AlgoType::AES_CBC:
577 case AlgoType::AES_CFB: {
579 TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
583 unpack<RawBuffer>(alg, ParamName::ED_IV),
588 case AlgoType::AES_GCM: {
589 int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
590 alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
592 alg.getParam(ParamName::ED_AAD, aad);
593 return decryptDataAesGcmPacked(keyId,
595 unpack<RawBuffer>(alg, ParamName::ED_IV),
604 ThrowErr(Exc::Crypto::OperationNotSupported,
605 "Incorrect algorithm provided for symmetric crypto operation");
608 RawBuffer asymmetricEncrypt(const RawBuffer &keyId,
610 const CryptoAlgorithm &alg,
611 const RawBuffer &data)
613 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
618 case AlgoType::RSA_OAEP: {
619 TrustZoneContext::Instance().executeCrypt(CMD_ENCRYPT,
623 result, // unused dummy
632 ThrowErr(Exc::Crypto::OperationNotSupported,
633 "Incorrect algorithm provided for asymmetric crypto operation");
636 RawBuffer asymmetricDecrypt(const RawBuffer &keyId,
638 const CryptoAlgorithm &alg,
639 const RawBuffer &cipher)
641 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
646 case AlgoType::RSA_OAEP: {
647 TrustZoneContext::Instance().executeCrypt(CMD_DECRYPT,
651 result, // unused dummy
660 ThrowErr(Exc::Crypto::OperationNotSupported,
661 "Incorrect algorithm provided for asymmetric crypto operation");
664 uint32_t initCipher(const RawBuffer &keyId,
666 const CryptoAlgorithm &alg,
669 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
673 case AlgoType::AES_GCM: {
674 int tagSizeBits = Params::DEFAULT_AES_GCM_TAG_LEN_BITS;
675 alg.getParam(ParamName::ED_TAG_LEN, tagSizeBits);
677 alg.getParam(ParamName::ED_AAD, aad);
678 return TrustZoneContext::Instance().initGcmCipher(encrypt ? CIPHER_ENCRYPT : CIPHER_DECRYPT,
681 unpack<RawBuffer>(alg, ParamName::ED_IV),
685 case AlgoType::AES_CBC:
686 case AlgoType::AES_CTR:
687 case AlgoType::AES_CFB:
688 // TODO optionally implement above modes as well
693 ThrowErr(Exc::Crypto::OperationNotSupported,
694 "Incorrect algorithm provided for symmetric crypto operation");
697 void addAAD(uint32_t opId,
698 const RawBuffer &aad)
700 TrustZoneContext::Instance().addGcmAAD(opId, aad);
703 RawBuffer updateCipher(uint32_t opId,
704 const RawBuffer &data)
706 return TrustZoneContext::Instance().updateGcmCipher(opId, data);
709 RawBuffer finalizeCipher(uint32_t opId,
710 const RawBuffer &data)
712 return TrustZoneContext::Instance().finalizeGcmCipher(opId, data);
715 RawBuffer sign(const RawBuffer &pkeyId,
717 const CryptoAlgorithm &alg,
718 const RawBuffer &message)
720 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
721 HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
722 if (algo != AlgoType::RSA_SV && hash == HashAlgorithm::NONE)
723 ThrowErr(Exc::Crypto::InputParam, "Only RSA supports no hash option");
726 TrustZoneContext::Instance().executeSign(getAlgType(algo),
735 int verify(const RawBuffer &pkeyId,
737 const CryptoAlgorithm &alg,
738 const RawBuffer &message,
739 const RawBuffer &signature)
741 AlgoType algo = unpack<AlgoType>(alg, ParamName::ALGO_TYPE);
742 HashAlgorithm hash = unpack<HashAlgorithm>(alg, ParamName::SV_HASH_ALGO);
743 if (algo != AlgoType::RSA_SV && hash == HashAlgorithm::NONE)
744 ThrowErr(Exc::Crypto::InputParam, "Only RSA supports no hash option");
746 return TrustZoneContext::Instance().executeVerify(getAlgType(algo),
754 void deriveECDH(const RawBuffer &prvKeyId,
755 const Pwd &prvKeyPwd,
756 const RawBuffer &pubKey,
757 const Password &secretPwd,
758 const RawBuffer &secretPwdIV,
759 RawBuffer &secretTag,
760 const RawBuffer &secretHash)
762 auto peerKey = std::make_shared<KeyImpl>(pubKey);
763 if (peerKey->getType() != KeyType::KEY_ECDSA_PUBLIC)
764 ThrowErr(Exc::Crypto::InputParam, "ECDH requires peer's public EC key");
765 auto peerEvp = peerKey->getEvpShPtr().get();
768 int subType = EVP_PKEY_type(EVP_PKEY_id(peerEvp));
769 if (subType != EVP_PKEY_EC)
770 ThrowErr(Exc::Crypto::InputParam, "Invalid key type: ", subType);
772 auto ecKey = EVP_PKEY_get0_EC_KEY(peerEvp);
774 ThrowErr(Exc::Crypto::InternalError, "Can't get EC key");
776 auto ecPoint = EC_KEY_get0_public_key(ecKey);
778 ThrowErr(Exc::Crypto::InternalError, "Can't get EC public key");
780 auto ecGroup = EC_KEY_get0_group(ecKey);
782 ThrowErr(Exc::Crypto::InternalError, "Can't get EC group");
784 BIGNUM *x = BN_new();
785 BIGNUM *y = BN_new();
786 if (!EC_POINT_get_affine_coordinates(ecGroup, ecPoint, x, y, NULL))
787 ThrowErr(Exc::Crypto::InternalError, "Failed to get EC pub key coordinates");
789 auto xBuf = extractBignumData(x);
790 auto yBuf = extractBignumData(y);
792 RawBuffer secretPwdBuf(secretPwd.begin(), secretPwd.end());
794 TrustZoneContext::Instance().executeEcdh(prvKeyId,
804 void deriveKBKDF(const RawBuffer &secretId,
805 const CryptoAlgorithm &alg,
806 const Password &keyPwd,
807 const RawBuffer &keyPwdIV,
809 const RawBuffer &keyHash)
811 RawBuffer label, context, fixed;
812 alg.getParam(ParamName::KBKDF_LABEL, label);
813 alg.getParam(ParamName::KBKDF_CONTEXT, context);
814 alg.getParam(ParamName::KBKDF_FIXED_INPUT, fixed);
815 auto prf = unpack<KdfPrf>(alg, ParamName::KDF_PRF);
816 auto mode = unpack<KbkdfMode>(alg, ParamName::KBKDF_MODE);
817 auto location = unpack<KbkdfCounterLocation>(alg, ParamName::KBKDF_COUNTER_LOCATION);
819 size_t rlen = 32, llen = 32, dummy;
820 alg.getParam(ParamName::KBKDF_RLEN, rlen);
821 alg.getParam(ParamName::KBKDF_LLEN, llen);
822 bool noSeparator = alg.getParam(ParamName::KBKDF_NO_SEPARATOR, dummy);
824 RawBuffer keyPwdBuf(keyPwd.begin(), keyPwd.end());
826 TrustZoneContext::Instance().executeKbkdf(secretId,
832 toTzCtrLoc(location),
843 } // namespace Internals
845 } // namespace Crypto