CKM: Max chunk size test
[platform/core/test/security-tests.git] / src / ckm / unprivileged / encryption-decryption.cpp
1 /*
2  *  Copyright (c) 2000 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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
15  */
16 /*
17  * @file       encryption-decryption.cpp
18  * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
19  * @version    1.0
20  */
21
22
23 #include <string>
24 #include <vector>
25 #include <unordered_map>
26 #include <thread>
27
28 #include <dpl/test/test_runner.h>
29 #include <ckm-common.h>
30 #include <ckmc/ckmc-manager.h>
31 #include <ckmc/ckmc-control.h>
32 #include <ckm/ckm-type.h>
33 #include <ckm/ckm-manager.h>
34 #include <encryption-decryption-env.h>
35
36 using namespace CKM;
37
38 namespace {
39
40 const char* PASSWORD = "test-password";
41 const uid_t UID = 5001;
42 const size_t CTR_DEFAULT_LEN = 16*8;
43 const size_t DEFAULT_IV_LEN = 16;
44 const size_t BUF_LEN = 86; // must be less than 1024/8-41 to support RSA OAEP 1024
45
46 // Environment
47 SyncApi g_syncApi;
48 AsyncApi g_asyncApi;
49 CipherApi g_cipherApi;
50
51 EncryptionApi* g_api = &g_syncApi;
52
53 EncryptionError apiEncrypt(ckmc_param_list_h params,
54                         const char *key_alias,
55                         const char *password,
56                         const ckmc_raw_buffer_s decrypted,
57                         ckmc_raw_buffer_s **ppencrypted) {
58     RUNNER_ASSERT_MSG(g_api, "No encryption API is connected");
59     return g_api->encrypt(params, key_alias, password, decrypted, ppencrypted);
60 }
61
62 inline CKM::Password _tostring(const char *str)
63 {
64     return (str == nullptr) ? Password() : Password(str);
65 }
66
67 inline CKM::Policy _toCkmPolicy(const ckmc_policy_s &policy, PolicyBackend backend)
68 {
69     return CKM::Policy(_tostring(policy.password), policy.extractable, backend);
70 }
71
72 EncryptionError apiDecrypt(ckmc_param_list_h params,
73                         const char *key_alias,
74                         const char *password,
75                         const ckmc_raw_buffer_s encrypted,
76                         ckmc_raw_buffer_s **ppdecrypted) {
77     RUNNER_ASSERT_MSG(g_api, "No encryption API is connected");
78     return g_api->decrypt(params, key_alias, password, encrypted, ppdecrypted);
79 }
80
81
82 template <typename F, typename... Args>
83 void assert_crypto_result(EncryptionError expected, F&& func, Args... args)
84 {
85     EncryptionError ret = func(args...);
86     RUNNER_ASSERT_MSG(ret == expected,
87                       "Expected: " << static_cast<int>(expected) <<
88                       " got: " << static_cast<int>(ret));
89 }
90
91 template <typename F, typename... Args>
92 void assert_crypto_positive(F&& func, Args... args)
93 {
94     assert_crypto_result(EncryptionError::SUCCESS, std::move(func), args...);
95 }
96
97 template <typename F, typename... Args>
98 void assert_crypto_invalid_param(F&& func, Args... args)
99 {
100     assert_crypto_result(EncryptionError::INVALID_PARAM, std::move(func), args...);
101 }
102
103 struct TagTest {
104     int tagLen;
105     EncryptionError expected;
106 };
107
108 struct KeyAliasPair
109 {
110     Alias prv;
111     Alias pub;
112 };
113
114 struct SyncEnv {
115     void init(const std::string&) {
116         g_api = &g_syncApi;
117     }
118
119     void finish() {
120         g_api = nullptr;
121     }
122
123     static std::string suffix() { return "_sync"; }
124 };
125
126 struct AsyncEnv {
127     void init(const std::string&) {
128         g_api = &g_asyncApi;
129     }
130
131     void finish() {
132         g_api = nullptr;
133     }
134
135     static std::string suffix() { return "_async"; }
136 };
137
138 struct CipherEnv {
139     void init(const std::string&) {
140         g_api = &g_cipherApi;
141     }
142
143     void finish() {
144         g_api = nullptr;
145     }
146
147     static std::string suffix() { return "_cipher"; }
148 };
149
150 struct Algo {
151     ckmc_algo_type_e type;
152     size_t keyLen;
153 };
154
155 std::unordered_map<size_t, std::vector<Alias>> g_symKeys;
156 std::unordered_map<size_t, std::vector<KeyAliasPair>> g_asymKeys;
157
158 enum KeyIdx {
159     PRIMARY = 0,
160     PASSWORD_PROTECTED = 1,
161
162     KEY_IDX_MAX
163 };
164
165 RawBufferPtr PLAIN_DATA;
166 RawBufferPtr BIG_DATA;
167 ckmc_raw_buffer_s* DEFAULT_IV;
168 ckmc_raw_buffer_s* IV1;
169 ckmc_raw_buffer_s* IV11;
170 ckmc_raw_buffer_s* IV12;
171 ckmc_raw_buffer_s* IV15;
172 ckmc_raw_buffer_s* IV17;
173 ckmc_raw_buffer_s* IV128;
174 ckmc_raw_buffer_s* AAD32;
175 ckmc_raw_buffer_s* AAD64;
176
177 KeyAliasPair getKey(const Algo& algo, KeyIdx idx)
178 {
179     if (algo.type == CKMC_ALGO_RSA_OAEP)
180         return g_asymKeys[algo.keyLen][idx];
181
182     KeyAliasPair pair;
183     pair.prv = g_symKeys[algo.keyLen][idx];
184     pair.pub = pair.prv;
185     return pair;
186 }
187
188 class EncGroupFixture: public DPL::Test::TestGroup
189 {
190 public:
191     void Init() override
192     {
193         remove_user_data(UID);
194         int ret = ckmc_unlock_user_key(UID, "db-pass");
195         if (ret != CKMC_ERROR_NONE)
196             RUNNER_ERROR_MSG("DB unlock failed: " << CKMCErrorToString(ret));
197
198         // Policy backend to use in subsequent operations (global for each test case)
199 #ifdef TZ_BACKEND
200         m_backend = PolicyBackend::FORCE_HARDWARE;
201 #else
202         m_backend = PolicyBackend::FORCE_SOFTWARE;
203 #endif
204
205         // generate keys
206         m_manager = Manager::create();
207         generateSymmetricKeys(128);
208         generateSymmetricKeys(192);
209         generateSymmetricKeys(256);
210         generateRsaKeys(1024);
211         generateRsaKeys(2048);
212         generateRsaKeys(4096);
213
214         PLAIN_DATA = create_raw_buffer(createRandomBufferCAPI(BUF_LEN));
215 #ifdef TZ_BACKEND
216         ckmc_backend_info_h info;
217         size_t size;
218         assert_positive(ckmc_get_backend_info, CKMC_BACKEND_TZ, &info);
219         assert_positive(ckmc_backend_get_max_chunk_size, info, &size);
220         BIG_DATA = create_raw_buffer(createRandomBufferCAPI(size));
221 #else
222         BIG_DATA = create_raw_buffer(createRandomBufferCAPI(500000));
223 #endif
224         DEFAULT_IV = createRandomBufferCAPI(DEFAULT_IV_LEN);
225         IV1 = createRandomBufferCAPI(1);
226         IV11 = createRandomBufferCAPI(11);
227         IV12 = createRandomBufferCAPI(12);
228         IV15 = createRandomBufferCAPI(15);
229         IV17 = createRandomBufferCAPI(17);
230         IV128 = createRandomBufferCAPI(128);
231         AAD32 = createRandomBufferCAPI(32);
232         AAD64 = createRandomBufferCAPI(64);
233     }
234
235     void generateSymmetricKeys(size_t bitLen)
236     {
237         for (int i = 0; i < KEY_IDX_MAX; i++)
238         {
239             Policy p(Password(), false, m_backend);
240             if (i == PASSWORD_PROTECTED)
241                 p.password.assign(PASSWORD);
242
243             std::string alias = std::string("skey_") + std::to_string(bitLen) + std::string("_") + std::to_string(i);
244             int ret = m_manager->createKeyAES(bitLen, alias, p);
245             if (ret != CKM_API_SUCCESS)
246                 RUNNER_ERROR_MSG("AES key creation failed");
247
248             g_symKeys[bitLen].push_back(alias);
249         }
250     }
251
252     void generateRsaKeys(size_t bitLen)
253     {
254         for (int i = 0; i < KEY_IDX_MAX; i++)
255         {
256             Policy prvPolicy(Password(), false, m_backend);
257             Policy pubPolicy(Password(), true, m_backend);
258             if (i == PASSWORD_PROTECTED) {
259                 prvPolicy.password.assign(PASSWORD);
260                 pubPolicy.password.assign(PASSWORD);
261             }
262
263             KeyAliasPair alias;
264             alias.prv = std::string("akey_") + std::to_string(bitLen) + std::string("_") + std::to_string(i);
265             alias.pub = std::string("pub") + alias.prv;
266             int ret = m_manager->createKeyPairRSA(bitLen, alias.prv, alias.pub, prvPolicy, pubPolicy);
267             if (ret != CKM_API_SUCCESS)
268                 RUNNER_ERROR_MSG("RSA key creation failed");
269
270             g_asymKeys[bitLen].push_back(alias);
271         }
272     }
273
274     void Finish() override
275     {
276         for (const auto &entry : g_asymKeys) {
277             for (const auto &keyPair : entry.second) {
278                 m_manager->removeAlias(keyPair.prv);
279                 m_manager->removeAlias(keyPair.pub);
280             }
281         }
282
283         for (const auto &entry : g_symKeys) {
284             for (const auto &key : entry.second) {
285                 m_manager->removeAlias(key);
286             }
287         }
288
289         BIG_DATA.reset();
290         PLAIN_DATA.reset();
291         ckmc_buffer_free(AAD64);
292         ckmc_buffer_free(AAD32);
293         ckmc_buffer_free(IV128);
294         ckmc_buffer_free(IV17);
295         ckmc_buffer_free(IV15);
296         ckmc_buffer_free(IV12);
297         ckmc_buffer_free(IV11);
298         ckmc_buffer_free(IV1);
299         ckmc_buffer_free(DEFAULT_IV);
300
301         int ret = ckmc_lock_user_key(UID);
302         if (ret != CKMC_ERROR_NONE)
303             RUNNER_ERROR_MSG("DB lock failed: " << CKMCErrorToString(ret));
304         remove_user_data(UID);
305     }
306 private:
307     ManagerShPtr m_manager;
308     PolicyBackend m_backend;
309 };
310
311 struct EncryptionResult
312 {
313     RawBufferPtr encrypted;
314     ParamListPtr params;
315     Alias prvKey;
316     Alias pubKey;
317 };
318
319 EncryptionResult encrypt(const Algo& algo,
320                          const RawBufferPtr& plain,
321                          const char* pass = nullptr)
322 {
323     EncryptionResult ret;
324     ckmc_raw_buffer_s* encrypted = nullptr;
325     KeyAliasPair aliases = getKey(algo, pass == nullptr ? PRIMARY : PASSWORD_PROTECTED);
326
327     ckmc_param_list_h handle = NULL;
328     assert_positive(ckmc_generate_new_params, algo.type, &handle);
329     ret.params = ParamListPtr(handle, ckmc_param_list_free);
330     setParam(ret.params, CKMC_PARAM_ED_IV, DEFAULT_IV);
331
332     assert_crypto_positive(apiEncrypt,
333                            ret.params.get(),
334                            aliases.pub.c_str(),
335                            pass,
336                            *plain.get(),
337                            &encrypted);
338
339     ret.encrypted = create_raw_buffer(encrypted);
340     ret.prvKey = aliases.prv;
341     ret.pubKey = aliases.pub;
342     return ret;
343 }
344
345 void testAllAlgorithms(const std::function<void(const Algo& algo)>& test)
346 {
347     test( { CKMC_ALGO_AES_CBC, 128 });
348     test( { CKMC_ALGO_AES_CBC, 192 });
349     test( { CKMC_ALGO_AES_CBC, 256 });
350     test( { CKMC_ALGO_AES_GCM, 128 });
351     test( { CKMC_ALGO_AES_GCM, 192 });
352     test( { CKMC_ALGO_AES_GCM, 256 });
353     test( { CKMC_ALGO_AES_CTR, 128 });
354     test( { CKMC_ALGO_AES_CTR, 192 });
355     test( { CKMC_ALGO_AES_CTR, 256 });
356     test( { CKMC_ALGO_AES_CFB, 128 });
357     test( { CKMC_ALGO_AES_CFB, 192 });
358     test( { CKMC_ALGO_AES_CFB, 256 });
359
360     if (!g_api->symmetricOnly()) {
361         test( { CKMC_ALGO_RSA_OAEP, 1024 });
362         test( { CKMC_ALGO_RSA_OAEP, 2048 });
363         test( { CKMC_ALGO_RSA_OAEP, 4096 });
364     }
365 }
366
367 void testNoIvEnc(const Algo& algo)
368 {
369     // prepare buffers
370     ckmc_raw_buffer_s* encrypted = nullptr;
371
372     // add key
373     KeyAliasPair aliases = getKey(algo, PRIMARY);
374
375     // param list with algo type only
376     ParamListPtr params = createParamListPtr();
377     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
378     assert_crypto_invalid_param(apiEncrypt,
379                                 params.get(),
380                                 aliases.pub.c_str(),
381                                 nullptr,
382                                 *PLAIN_DATA.get(),
383                                 &encrypted);
384 }
385
386 void testNoIvDec(const Algo& algo)
387 {
388     // prepare buffers
389     ckmc_raw_buffer_s* decrypted = nullptr;
390
391     // encrypt;
392     auto ret = encrypt(algo, PLAIN_DATA);
393
394     // param list with algo type only
395     ParamListPtr params = createParamListPtr();
396     setParam(params, CKMC_PARAM_ALGO_TYPE, algo.type);
397     assert_crypto_invalid_param(apiDecrypt,
398                                 params.get(),
399                                 ret.prvKey.c_str(),
400                                 nullptr,
401                                 *ret.encrypted.get(),
402                                 &decrypted);
403 }
404
405 void testInvalidIvEnc(const Algo& algo)
406 {
407     // prepare buffers
408     ckmc_raw_buffer_s* encryptedTmp = nullptr;
409
410     // add key
411     KeyAliasPair aliases = getKey(algo, PRIMARY);
412
413     // setup params
414     ckmc_param_list_h handle = NULL;
415     assert_positive(ckmc_generate_new_params, algo.type, &handle);
416     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
417
418     // invalid encryption
419     auto test = [&](){
420         assert_crypto_invalid_param(apiEncrypt,
421                                     params.get(),
422                                     aliases.pub.c_str(),
423                                     nullptr,
424                                     *PLAIN_DATA.get(),
425                                     &encryptedTmp);
426         ckmc_buffer_free(encryptedTmp);
427         encryptedTmp = nullptr;
428     };
429     // invalid iv size
430     setParam(params, CKMC_PARAM_ED_IV, IV15);
431     test();
432     setParam(params, CKMC_PARAM_ED_IV, IV17);
433     test();
434 };
435
436 void testInvalidIvDec(const Algo& algo)
437 {
438     // prepare buffers
439     ckmc_raw_buffer_s* decrypted = nullptr;
440
441     // valid encryption
442     auto ret = encrypt(algo, PLAIN_DATA);
443
444     // decryption
445     auto test2 = [&](){
446         assert_crypto_invalid_param(apiDecrypt,
447                                     ret.params.get(),
448                                     ret.prvKey.c_str(),
449                                     nullptr,
450                                     *ret.encrypted.get(),
451                                     &decrypted);
452         ckmc_buffer_free(decrypted);
453         decrypted = nullptr;
454     };
455
456     // invalid iv size
457     setParam(ret.params, CKMC_PARAM_ED_IV, IV15);
458     test2();
459     setParam(ret.params, CKMC_PARAM_ED_IV, IV17);
460     test2();
461 };
462
463 void encryptionWithCustomData(const Algo& algo, ckmc_param_name_e name)
464 {
465     // prepare buffers
466     ckmc_raw_buffer_s* encrypted = nullptr;
467     ckmc_raw_buffer_s* decrypted = nullptr;
468
469     // add key
470     KeyAliasPair aliases = getKey(algo, PRIMARY);
471
472     // setup params
473     ckmc_param_list_h handle = NULL;
474     assert_positive(ckmc_generate_new_params, algo.type, &handle);
475     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
476
477     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
478
479     // set AAD
480     setParam(params, name, AAD64);
481
482     // encrypt
483     assert_crypto_positive(apiEncrypt,
484                            params.get(),
485                            aliases.pub.c_str(),
486                            nullptr,
487                            *PLAIN_DATA.get(),
488                            &encrypted);
489     RawBufferPtr tmpEnc = create_raw_buffer(encrypted);
490
491     // decrypt
492     assert_crypto_positive(apiDecrypt,
493                            params.get(),
494                            aliases.prv.c_str(),
495                            nullptr,
496                            *tmpEnc.get(),
497                            &decrypted);
498     RawBufferPtr tmpDec = create_raw_buffer(decrypted);
499
500     // check
501     assert_buffers_equal(PLAIN_DATA.get(), tmpDec.get());
502     tmpDec.reset();
503     decrypted = nullptr;
504
505     // set wrong AAD
506     setParam(params, name, AAD32);
507
508     // decrypt
509     assert_crypto_result(EncryptionError::INVALID_PARAM,
510                          apiDecrypt,
511                          params.get(),
512                          aliases.prv.c_str(),
513                          nullptr,
514                          *tmpEnc.get(),
515                          &decrypted);
516 }
517
518 void testGcmIvSize(ckmc_raw_buffer_s* iv,
519                    const KeyAliasPair& aliases,
520                    EncryptionError error = EncryptionError::SUCCESS)
521 {
522     // prepare buffers
523     RawBufferPtr encrypted;
524     RawBufferPtr decrypted;
525     ckmc_raw_buffer_s* encryptedTmp = nullptr;
526     ckmc_raw_buffer_s* decryptedTmp = nullptr;
527
528     // setup params
529     ckmc_param_list_h handle = NULL;
530     assert_positive(ckmc_generate_new_params, CKMC_ALGO_AES_GCM, &handle);
531     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
532     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
533     setParam(params, CKMC_PARAM_ED_IV, iv);
534
535     // encryption
536     assert_crypto_result(error,
537                          apiEncrypt,
538                          params.get(),
539                          aliases.pub.c_str(),
540                          nullptr,
541                          *PLAIN_DATA.get(),
542                          &encryptedTmp);
543
544     if(error != EncryptionError::SUCCESS)
545         return;
546     encrypted = create_raw_buffer(encryptedTmp);
547
548     // decryption
549     assert_crypto_positive(apiDecrypt,
550                            params.get(),
551                            aliases.prv.c_str(),
552                            nullptr,
553                            *encrypted.get(),
554                            &decryptedTmp);
555     decrypted = create_raw_buffer(decryptedTmp);
556
557     assert_buffers_equal(PLAIN_DATA.get(), decrypted.get());
558 }
559
560 void testIntegrity(const Algo& algo)
561 {
562     // prepare buffers
563     ckmc_raw_buffer_s* decrypted = nullptr;
564
565     // encrypt
566     auto ret = encrypt(algo, PLAIN_DATA);
567
568     // break the encrypted data
569     ret.encrypted->data[BUF_LEN/2]++;
570
571     // no data integrity check
572     assert_crypto_positive(apiDecrypt,
573                            ret.params.get(),
574                            ret.prvKey.c_str(),
575                            nullptr,
576                            *ret.encrypted.get(),
577                            &decrypted);
578
579     RawBufferPtr tmp = create_raw_buffer(decrypted);
580     assert_buffers_equal(PLAIN_DATA.get(), decrypted, false);
581 }
582
583 void testCtrEncryptionInvalidLength(const Algo& algo)
584 {
585     // prepare buffers
586     ckmc_raw_buffer_s* encryptedTmp = nullptr;
587
588     // add AES CTR key
589     KeyAliasPair aliases = getKey(algo, PRIMARY);
590
591     // setup params
592     ckmc_param_list_h handle = NULL;
593     assert_positive(ckmc_generate_new_params, algo.type, &handle);
594     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
595     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
596
597     // encryption
598     auto test = [&](){
599         assert_crypto_invalid_param(apiEncrypt,
600                                     params.get(),
601                                     aliases.pub.c_str(),
602                                     nullptr,
603                                     *PLAIN_DATA.get(),
604                                     &encryptedTmp);
605         ckmc_buffer_free(encryptedTmp);
606         encryptedTmp = nullptr;
607     };
608     // invalid counter size
609     setParam(params, CKMC_PARAM_ED_CTR_LEN, 0ULL);
610     test();
611     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
612     test();
613 }
614
615 void testCtrEncryptionValidLength(const Algo& algo)
616 {
617     // prepare buffers
618     ckmc_raw_buffer_s* encryptedTmp = nullptr;
619
620     // add AES CTR key
621     KeyAliasPair aliases = getKey(algo, PRIMARY);
622
623     // setup params
624     ckmc_param_list_h handle = NULL;
625     assert_positive(ckmc_generate_new_params, algo.type, &handle);
626     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
627     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
628
629     // encryption
630     auto test = [&](){
631         assert_crypto_positive(apiEncrypt,
632                                params.get(),
633                                aliases.pub.c_str(),
634                                nullptr,
635                                *PLAIN_DATA.get(),
636                                &encryptedTmp);
637         ckmc_buffer_free(encryptedTmp);
638         encryptedTmp = nullptr;
639     };
640     // valid counter sizez
641     setParam(params, CKMC_PARAM_ED_CTR_LEN, 1);
642     test();
643     setParam(params, CKMC_PARAM_ED_CTR_LEN, 4);
644     test();
645     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
646     test();
647     setParam(params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
648     test();
649 }
650
651 void testCtrDecryptionInvalidLength(const Algo& algo)
652 {
653     // prepare buffers
654     ckmc_raw_buffer_s* decrypted = nullptr;
655
656     // add AES CTR key & encrypt
657     auto ret = encrypt(algo, PLAIN_DATA);
658
659     // decryption
660     auto test = [&](){
661         assert_crypto_invalid_param(apiDecrypt,
662                                     ret.params.get(),
663                                     ret.prvKey.c_str(),
664                                     nullptr,
665                                     *ret.encrypted.get(),
666                                     &decrypted);
667         ckmc_buffer_free(decrypted);
668         decrypted = nullptr;
669     };
670     // invalid counter size
671     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 0ULL);
672     test();
673     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN+1);
674     test();
675 }
676
677 void testCtrDecryptionValidLength(const Algo& algo)
678 {
679     // prepare buffers
680     ckmc_raw_buffer_s* decrypted = nullptr;
681
682     // add AES CTR key & encrypt
683     auto ret = encrypt(algo, PLAIN_DATA);
684
685     // decryption
686     auto test = [&](){
687         assert_crypto_positive(apiDecrypt,
688                                ret.params.get(),
689                                ret.prvKey.c_str(),
690                                nullptr,
691                                *ret.encrypted.get(),
692                                &decrypted);
693         ckmc_buffer_free(decrypted);
694         RawBufferPtr tmp = create_raw_buffer(decrypted);
695         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
696     };
697     // invalid counter size
698     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 1);
699     test();
700     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, 4);
701     test();
702     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN-1);
703     test();
704     setParam(ret.params, CKMC_PARAM_ED_CTR_LEN, CTR_DEFAULT_LEN);
705     test();
706 }
707
708 void testGcmEncryptionTagLen(const Algo& algo)
709 {
710     // prepare buffers
711     ckmc_raw_buffer_s* encryptedTmp = nullptr;
712
713     // add AES GCM key
714     KeyAliasPair aliases = getKey(algo, PRIMARY);
715
716     // setup params
717     ckmc_param_list_h handle = NULL;
718     assert_positive(ckmc_generate_new_params, algo.type, &handle);
719     ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
720     setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
721
722     std::vector<TagTest> testData = {
723             // illegal tag lengths
724             { -1,   EncryptionError::INVALID_PARAM },
725             { 0,    EncryptionError::INVALID_PARAM },
726             { 16,   EncryptionError::INVALID_PARAM },
727             { 48,   EncryptionError::INVALID_PARAM },
728             { 72,   EncryptionError::INVALID_PARAM },
729             { 100,  EncryptionError::INVALID_PARAM },
730             { 108,  EncryptionError::INVALID_PARAM },
731             { 116,  EncryptionError::INVALID_PARAM },
732             { 124,  EncryptionError::INVALID_PARAM },
733             { 256,  EncryptionError::INVALID_PARAM },
734 #ifdef TZ_BACKEND
735             { 32,   EncryptionError::INVALID_PARAM },
736             { 64,   EncryptionError::INVALID_PARAM },
737             // legal tag lengths
738 #else
739             // legal tag lengths
740             { 32,   EncryptionError::SUCCESS },
741             { 64,   EncryptionError::SUCCESS },
742 #endif
743
744             { 96,   EncryptionError::SUCCESS },
745             { 104,  EncryptionError::SUCCESS },
746             { 112,  EncryptionError::SUCCESS },
747             { 120,  EncryptionError::SUCCESS },
748             { 128,  EncryptionError::SUCCESS },
749     };
750
751     // encryption
752     for(const auto& it : testData)
753     {
754         setParam(params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
755         assert_crypto_result(it.expected,
756                              apiEncrypt,
757                              params.get(),
758                              aliases.pub.c_str(),
759                              nullptr,
760                              *PLAIN_DATA.get(),
761                              &encryptedTmp);
762         ckmc_buffer_free(encryptedTmp);
763         encryptedTmp = nullptr;
764     }
765 }
766
767 void testGcmDecryptionTagLen(const Algo& algo)
768 {
769     // prepare buffers
770     ckmc_raw_buffer_s* decrypted = nullptr;
771
772     // add AES GCM key & encrypt
773     auto ret = encrypt(algo, PLAIN_DATA);
774
775     std::vector<TagTest> testData = {
776             // illegal tag lengths
777             { -1,   EncryptionError::INVALID_PARAM },
778             { 0,    EncryptionError::INVALID_PARAM },
779             { 16,   EncryptionError::INVALID_PARAM },
780             { 48,   EncryptionError::INVALID_PARAM },
781             { 72,   EncryptionError::INVALID_PARAM },
782             { 100,  EncryptionError::INVALID_PARAM },
783             { 108,  EncryptionError::INVALID_PARAM },
784             { 116,  EncryptionError::INVALID_PARAM },
785             { 124,  EncryptionError::INVALID_PARAM },
786             { 256,  EncryptionError::INVALID_PARAM },
787             // legal tag lengths but different than the one used for encryption
788             { 32,   EncryptionError::INVALID_PARAM },
789             { 64,   EncryptionError::INVALID_PARAM },
790             { 96,   EncryptionError::INVALID_PARAM },
791             { 104,  EncryptionError::INVALID_PARAM },
792             { 112,  EncryptionError::INVALID_PARAM },
793             { 120,  EncryptionError::INVALID_PARAM },
794             // legal tag length that was actually used for encryption (default)
795             { 128,  EncryptionError::SUCCESS },
796     };
797
798     // decryption
799     for(const auto& it : testData)
800     {
801         setParam(ret.params, CKMC_PARAM_ED_TAG_LEN, it.tagLen);
802         assert_crypto_result(it.expected,
803                              apiDecrypt,
804                              ret.params.get(),
805                              ret.prvKey.c_str(),
806                              nullptr,
807                              *ret.encrypted.get(),
808                              &decrypted);
809         ckmc_buffer_free(decrypted);
810         decrypted = nullptr;
811     }
812 }
813
814 void testGcmWrongTag(const Algo& algo)
815 {
816     // prepare buffers
817     ckmc_raw_buffer_s* decrypted = nullptr;
818
819     // encrypt with AES GCM
820     auto ret = encrypt(algo, PLAIN_DATA);
821
822     // modify tag (last 16B of encrypted message)
823     ret.encrypted->data[ret.encrypted->size-1]++;
824
825     // EVP_CipherFinal fails because of an authentication error
826     assert_crypto_result(EncryptionError::INVALID_PARAM,
827                          apiDecrypt,
828                          ret.params.get(),
829                          ret.prvKey.c_str(),
830                          nullptr,
831                          *ret.encrypted.get(),
832                          &decrypted);
833 }
834
835 void testGcmDifferentIvSizes(const Algo& algo)
836 {
837     // add AES GCM key
838     KeyAliasPair aliases = getKey(algo, PRIMARY);
839
840     testGcmIvSize(IV1,   aliases);
841     testGcmIvSize(IV11,  aliases);
842     testGcmIvSize(IV12,  aliases);
843     testGcmIvSize(IV17,  aliases);
844     testGcmIvSize(IV128, aliases);
845 }
846
847 void testEncryptDecryptBigData(const Algo& algo)
848 {
849     // prepare buffers
850     ckmc_raw_buffer_s* decrypted = nullptr;
851
852     // encrypt
853     auto ret = encrypt(algo, BIG_DATA);
854
855     assert_positive(apiDecrypt,
856                     ret.params.get(),
857                     ret.prvKey.c_str(),
858                     nullptr,
859                     *ret.encrypted.get(),
860                     &decrypted);
861     RawBufferPtr tmp = create_raw_buffer(decrypted);
862
863     assert_buffers_equal(BIG_DATA.get(), decrypted);
864 }
865
866 void testEncryptDecryptDifferentKeys(const Algo& algo, bool success)
867 {
868     // prepare buffers
869     ckmc_raw_buffer_s* decrypted = nullptr;
870
871     // encrypt
872     auto ret = encrypt(algo, PLAIN_DATA);
873
874     // get different keys
875     KeyAliasPair differentKeys = getKey(algo, PASSWORD_PROTECTED);
876
877     if (success) {
878         // some algorithms don't verify key validity
879         assert_crypto_positive(apiDecrypt,
880                                ret.params.get(),
881                                differentKeys.prv.c_str(),
882                                PASSWORD,
883                                *ret.encrypted.get(),
884                                &decrypted);
885         RawBufferPtr tmp = create_raw_buffer(decrypted);
886
887         assert_buffers_equal(PLAIN_DATA.get(), decrypted, false);
888     } else {
889         assert_crypto_result(EncryptionError::INVALID_PARAM,
890                              apiDecrypt,
891                              ret.params.get(),
892                              differentKeys.prv.c_str(),
893                              PASSWORD,
894                              *ret.encrypted.get(),
895                              &decrypted);
896     }
897 }
898
899 void testRsaLongestData(const Algo& algo, size_t dataSize)
900 {
901     // prepare buffers
902     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
903     ckmc_raw_buffer_s* decrypted = nullptr;
904
905     // encrypt
906     auto ret = encrypt(algo, plain);
907
908     assert_crypto_positive(apiDecrypt,
909                            ret.params.get(),
910                            ret.prvKey.c_str(),
911                            nullptr,
912                            *ret.encrypted.get(),
913                            &decrypted);
914     RawBufferPtr tmp = create_raw_buffer(decrypted);
915
916     assert_buffers_equal(plain.get(), decrypted);
917 }
918
919 void testRsaDataTooLong(const Algo& algo, size_t dataSize)
920 {
921     // prepare buffers
922     RawBufferPtr plain = create_raw_buffer(createRandomBufferCAPI(dataSize));
923
924     // encrypt
925     EncryptionResult ret;
926     ckmc_raw_buffer_s* encrypted = nullptr;
927     KeyAliasPair aliases = getKey(algo, PRIMARY);
928
929     ckmc_param_list_h handle = NULL;
930     assert_positive(ckmc_generate_new_params, algo.type, &handle);
931     ret.params = ParamListPtr(handle, ckmc_param_list_free);
932     assert_crypto_result(EncryptionError::INVALID_PARAM,
933                          apiEncrypt,
934                          ret.params.get(),
935                          aliases.pub.c_str(),
936                          nullptr,
937                          *plain.get(),
938                          &encrypted);
939 }
940
941 std::pair<Alias, ParamListPtr> defaultGcmCipherSetup()
942 {
943     Algo algo = {CKMC_ALGO_AES_GCM, 256};
944     KeyAliasPair aliases = getKey(algo, PRIMARY);
945
946     ckmc_param_list_h handle = NULL;
947     assert_positive(ckmc_generate_new_params, algo.type, &handle);
948     auto params = ParamListPtr(handle, ckmc_param_list_free);
949     setParam(params, CKMC_PARAM_ED_IV, IV12);
950
951     return std::make_pair(aliases.prv, params);
952 }
953
954 } // namespace anonymous
955
956 RUNNER_TEST_GROUP_INIT_ENV(CKM_ENCRYPTION_DECRYPTION, EncGroupFixture);
957
958 /////////////////////////////////////////
959 // Generic encryption decryption tests
960 /////////////////////////////////////////
961
962 RUNNER_TEST_MULTIPLE(TED_0010_encrypt_invalid_param_list, SyncEnv, AsyncEnv, CipherEnv)
963 {
964     testAllAlgorithms([](const Algo& algo){
965         // prepare buffers
966         ckmc_raw_buffer_s* encrypted = nullptr;
967
968         // add key
969         KeyAliasPair aliases = getKey(algo, PRIMARY);
970
971         // null param list
972         assert_crypto_invalid_param(apiEncrypt,
973                                     nullptr,
974                                     aliases.pub.c_str(),
975                                     nullptr,
976                                     *PLAIN_DATA.get(),
977                                     &encrypted);
978
979         // empty param list
980         ParamListPtr params = createParamListPtr();
981         assert_crypto_invalid_param(apiEncrypt,
982                                     params.get(),
983                                     aliases.pub.c_str(),
984                                     nullptr,
985                                     *PLAIN_DATA.get(),
986                                     &encrypted);
987     });
988 }
989
990 RUNNER_TEST_MULTIPLE(TED_0020_encrypt_missing_key, SyncEnv, AsyncEnv, CipherEnv)
991 {
992     testAllAlgorithms([](const Algo& algo){
993         // prepare buffers
994         ckmc_raw_buffer_s* encrypted = nullptr;
995
996         // setup params
997         ckmc_param_list_h handle = NULL;
998         assert_positive(ckmc_generate_new_params, algo.type, &handle);
999         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1000         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1001
1002         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
1003                              apiEncrypt,
1004                              params.get(),
1005                              "non-existing-key-alias",
1006                              nullptr,
1007                              *PLAIN_DATA.get(),
1008                              &encrypted);
1009     });
1010 }
1011
1012 RUNNER_TEST_MULTIPLE(TED_0030_encrypt_no_plain_text, SyncEnv, AsyncEnv)
1013 {
1014     testAllAlgorithms([](const Algo& algo){
1015         // prepare buffers
1016         ckmc_raw_buffer_s plain = { nullptr, 0 };
1017         ckmc_raw_buffer_s* encrypted = nullptr;
1018
1019         // add key
1020         KeyAliasPair aliases = getKey(algo, PRIMARY);
1021
1022         // setup params
1023         ckmc_param_list_h handle = NULL;
1024         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1025         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1026         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1027
1028         assert_crypto_invalid_param(apiEncrypt,
1029                                     params.get(),
1030                                     aliases.pub.c_str(),
1031                                     nullptr,
1032                                     plain,
1033                                     &encrypted);
1034     });
1035 }
1036
1037 RUNNER_TEST_MULTIPLE(TED_0040_encrypt_no_output_buffer, SyncEnv, AsyncEnv)
1038 {
1039     testAllAlgorithms([](const Algo& algo){
1040         // prepare buffers
1041         ckmc_raw_buffer_s** encrypted = nullptr;
1042
1043         // add key
1044         KeyAliasPair aliases = getKey(algo, PRIMARY);
1045
1046         // setup params
1047         ckmc_param_list_h handle = NULL;
1048         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1049         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1050         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1051
1052         assert_crypto_invalid_param(apiEncrypt,
1053                                     params.get(),
1054                                     aliases.pub.c_str(),
1055                                     nullptr,
1056                                     *PLAIN_DATA.get(),
1057                                     encrypted);
1058     });
1059 }
1060
1061 RUNNER_TEST_MULTIPLE(TED_0110_decrypt_invalid_param_list, SyncEnv, AsyncEnv, CipherEnv)
1062 {
1063     testAllAlgorithms([](const Algo& algo){
1064         // prepare buffers
1065         ckmc_raw_buffer_s* decrypted = nullptr;
1066
1067         // encrypt;
1068         auto ret = encrypt(algo, PLAIN_DATA);
1069
1070         // null param list
1071         assert_crypto_invalid_param(apiDecrypt,
1072                                     nullptr,
1073                                     ret.prvKey.c_str(),
1074                                     nullptr,
1075                                     *ret.encrypted.get(),
1076                                     &decrypted);
1077
1078         // empty param list
1079         ParamListPtr params = createParamListPtr();
1080         assert_crypto_invalid_param(apiDecrypt,
1081                                     params.get(),
1082                                     ret.prvKey.c_str(),
1083                                     nullptr,
1084                                     *ret.encrypted.get(),
1085                                     &decrypted);
1086     });
1087 }
1088
1089 RUNNER_TEST_MULTIPLE(TED_0120_decrypt_missing_key, SyncEnv, AsyncEnv, CipherEnv)
1090 {
1091     testAllAlgorithms([](const Algo& algo){
1092         // prepare buffers
1093         ckmc_raw_buffer_s* decrypted = nullptr;
1094
1095         // encrypt
1096         auto ret = encrypt(algo, PLAIN_DATA);
1097
1098         // try to decrypt
1099         assert_crypto_result(EncryptionError::ALIAS_UNKNOWN,
1100                              apiDecrypt,
1101                              ret.params.get(),
1102                              "non-existent-key",
1103                              nullptr,
1104                              *ret.encrypted.get(),
1105                              &decrypted);
1106     });
1107 }
1108
1109 RUNNER_TEST_MULTIPLE(TED_0130_decrypt_no_encrypted_text, SyncEnv, AsyncEnv)
1110 {
1111     testAllAlgorithms([](const Algo& algo){
1112         // prepare buffers
1113         ckmc_raw_buffer_s encrypted = { nullptr, 0 };
1114         ckmc_raw_buffer_s* decrypted = nullptr;
1115
1116         // add key
1117         KeyAliasPair aliases = getKey(algo, PRIMARY);
1118
1119         // setup params
1120         ckmc_param_list_h handle = NULL;
1121         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1122         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1123         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1124
1125         assert_crypto_invalid_param(apiDecrypt,
1126                                     params.get(),
1127                                     aliases.prv.c_str(),
1128                                     nullptr,
1129                                     encrypted,
1130                                     &decrypted);
1131     });
1132 }
1133
1134 RUNNER_TEST_MULTIPLE(TED_0140_decrypt_no_output_buffer, SyncEnv, AsyncEnv)
1135 {
1136     testAllAlgorithms([](const Algo& algo){
1137         // prepare buffers
1138         ckmc_raw_buffer_s** decrypted = nullptr;
1139
1140         // encrypt
1141         auto ret = encrypt(algo, PLAIN_DATA);
1142
1143         assert_crypto_invalid_param(apiDecrypt,
1144                                     ret.params.get(),
1145                                     ret.prvKey.c_str(),
1146                                     nullptr,
1147                                     *ret.encrypted.get(),
1148                                     decrypted);
1149     });
1150 }
1151
1152 RUNNER_TEST_MULTIPLE(TED_0200_encrypt_decrypt_different_keys, SyncEnv, AsyncEnv, CipherEnv)
1153 {
1154     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 128}, false);
1155     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 192}, false);
1156     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_GCM, 256}, false);
1157     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 128}, true);
1158     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 192}, true);
1159     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CTR, 256}, true);
1160     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 128}, true);
1161     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 192}, true);
1162     testEncryptDecryptDifferentKeys({CKMC_ALGO_AES_CFB, 256}, true);
1163
1164     if (!g_api->symmetricOnly()) {
1165         testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 1024}, false);
1166         testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 2048}, false);
1167         testEncryptDecryptDifferentKeys({CKMC_ALGO_RSA_OAEP, 4096}, false);
1168     }
1169 }
1170
1171 RUNNER_TEST_MULTIPLE(TED_0300_encrypt_decrypt, SyncEnv, AsyncEnv, CipherEnv)
1172 {
1173     testAllAlgorithms([](const Algo& algo){
1174         // prepare buffers
1175         ckmc_raw_buffer_s* decrypted = nullptr;
1176
1177         // encrypt
1178         auto ret = encrypt(algo, PLAIN_DATA);
1179
1180         assert_crypto_positive(apiDecrypt,
1181                                ret.params.get(),
1182                                ret.prvKey.c_str(),
1183                                nullptr,
1184                                *ret.encrypted.get(),
1185                                &decrypted);
1186         RawBufferPtr tmp = create_raw_buffer(decrypted);
1187
1188         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
1189     });
1190 }
1191
1192 RUNNER_TEST_MULTIPLE(TED_0310_encrypt_decrypt_password, SyncEnv, AsyncEnv, CipherEnv)
1193 {
1194     testAllAlgorithms([](const Algo& algo){
1195         // prepare buffers
1196         ckmc_raw_buffer_s* decrypted = nullptr;
1197
1198         // encrypt
1199         auto ret = encrypt(algo, PLAIN_DATA, PASSWORD);
1200
1201         // wrong password
1202         assert_crypto_result(EncryptionError::AUTH_FAILED,
1203                              apiDecrypt,
1204                              ret.params.get(),
1205                              ret.prvKey.c_str(),
1206                              "wrong-password",
1207                              *ret.encrypted.get(),
1208                              &decrypted);
1209
1210         // correct password
1211         assert_crypto_positive(apiDecrypt,
1212                                ret.params.get(),
1213                                ret.prvKey.c_str(),
1214                                PASSWORD,
1215                                *ret.encrypted.get(),
1216                                &decrypted);
1217         RawBufferPtr tmp = create_raw_buffer(decrypted); // guarantees deletion
1218
1219         assert_buffers_equal(PLAIN_DATA.get(), decrypted);
1220     });
1221 }
1222
1223 // long test split into smaller ones
1224 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_128, SyncEnv, AsyncEnv, CipherEnv)
1225 {
1226     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 128});
1227 }
1228
1229 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_192, SyncEnv, AsyncEnv, CipherEnv)
1230 {
1231     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 192});
1232 }
1233
1234 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CBC_256, SyncEnv, AsyncEnv, CipherEnv)
1235 {
1236     testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256});
1237 }
1238
1239 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_128, SyncEnv, AsyncEnv, CipherEnv)
1240 {
1241     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 128});
1242 }
1243
1244 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_192, SyncEnv, AsyncEnv, CipherEnv)
1245 {
1246     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 192});
1247 }
1248
1249 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_GCM_256, SyncEnv, AsyncEnv, CipherEnv)
1250 {
1251     testEncryptDecryptBigData({CKMC_ALGO_AES_GCM, 256});
1252 }
1253
1254 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_128, SyncEnv, AsyncEnv, CipherEnv)
1255 {
1256     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 128});
1257 }
1258
1259 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_192, SyncEnv, AsyncEnv, CipherEnv)
1260 {
1261     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 192});
1262 }
1263
1264 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CTR_256, SyncEnv, AsyncEnv, CipherEnv)
1265 {
1266     testEncryptDecryptBigData({CKMC_ALGO_AES_CTR, 256});
1267 }
1268
1269 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_128, SyncEnv, AsyncEnv, CipherEnv)
1270 {
1271     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 128});
1272 }
1273
1274 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_192, SyncEnv, AsyncEnv, CipherEnv)
1275 {
1276     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 192});
1277 }
1278
1279 RUNNER_TEST_MULTIPLE(TED_0400_encrypt_decrypt_big_data_AES_CFB_256, SyncEnv, AsyncEnv, CipherEnv)
1280 {
1281     testEncryptDecryptBigData({CKMC_ALGO_AES_CFB, 256});
1282 }
1283
1284 /////////////////////////////////////////
1285 // Algorithm specific tests
1286 /////////////////////////////////////////
1287
1288 RUNNER_TEST_MULTIPLE(TED_1005_no_iv_enc, SyncEnv, AsyncEnv, CipherEnv)
1289 {
1290     testNoIvEnc({CKMC_ALGO_AES_CTR, 128});
1291     testNoIvEnc({CKMC_ALGO_AES_CTR, 192});
1292     testNoIvEnc({CKMC_ALGO_AES_CTR, 256});
1293     testNoIvEnc({CKMC_ALGO_AES_CBC, 128});
1294     testNoIvEnc({CKMC_ALGO_AES_CBC, 192});
1295     testNoIvEnc({CKMC_ALGO_AES_CBC, 256});
1296     testNoIvEnc({CKMC_ALGO_AES_CFB, 128});
1297     testNoIvEnc({CKMC_ALGO_AES_CFB, 192});
1298     testNoIvEnc({CKMC_ALGO_AES_CFB, 256});
1299     testNoIvEnc({CKMC_ALGO_AES_GCM, 128});
1300     testNoIvEnc({CKMC_ALGO_AES_GCM, 192});
1301     testNoIvEnc({CKMC_ALGO_AES_GCM, 256});
1302 }
1303
1304 RUNNER_TEST_MULTIPLE(TED_1010_invalid_iv_enc, SyncEnv, AsyncEnv, CipherEnv)
1305 {
1306     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 128});
1307     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 192});
1308     testInvalidIvEnc({CKMC_ALGO_AES_CTR, 256});
1309     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 128});
1310     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 192});
1311     testInvalidIvEnc({CKMC_ALGO_AES_CBC, 256});
1312     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 128});
1313     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 192});
1314     testInvalidIvEnc({CKMC_ALGO_AES_CFB, 256});
1315 }
1316
1317 RUNNER_TEST_MULTIPLE(TED_1015_no_iv_dec, SyncEnv, AsyncEnv, CipherEnv)
1318 {
1319     testNoIvDec({CKMC_ALGO_AES_CTR, 128});
1320     testNoIvDec({CKMC_ALGO_AES_CTR, 192});
1321     testNoIvDec({CKMC_ALGO_AES_CTR, 256});
1322     testNoIvDec({CKMC_ALGO_AES_CBC, 128});
1323     testNoIvDec({CKMC_ALGO_AES_CBC, 192});
1324     testNoIvDec({CKMC_ALGO_AES_CBC, 256});
1325     testNoIvDec({CKMC_ALGO_AES_CFB, 128});
1326     testNoIvDec({CKMC_ALGO_AES_CFB, 192});
1327     testNoIvDec({CKMC_ALGO_AES_CFB, 256});
1328     testNoIvDec({CKMC_ALGO_AES_GCM, 128});
1329     testNoIvDec({CKMC_ALGO_AES_GCM, 192});
1330     testNoIvDec({CKMC_ALGO_AES_GCM, 256});
1331 }
1332
1333 RUNNER_TEST_MULTIPLE(TED_1020_invalid_iv_dec, SyncEnv, AsyncEnv, CipherEnv)
1334 {
1335     testInvalidIvDec({CKMC_ALGO_AES_CTR, 128});
1336     testInvalidIvDec({CKMC_ALGO_AES_CTR, 192});
1337     testInvalidIvDec({CKMC_ALGO_AES_CTR, 256});
1338     testInvalidIvDec({CKMC_ALGO_AES_CBC, 128});
1339     testInvalidIvDec({CKMC_ALGO_AES_CBC, 192});
1340     testInvalidIvDec({CKMC_ALGO_AES_CBC, 256});
1341     testInvalidIvDec({CKMC_ALGO_AES_CFB, 128});
1342     testInvalidIvDec({CKMC_ALGO_AES_CFB, 192});
1343     testInvalidIvDec({CKMC_ALGO_AES_CFB, 256});
1344 }
1345
1346 RUNNER_TEST_MULTIPLE(TED_1050_data_integrity, SyncEnv, AsyncEnv, CipherEnv)
1347 {
1348     testIntegrity({CKMC_ALGO_AES_CTR, 128});
1349     testIntegrity({CKMC_ALGO_AES_CTR, 192});
1350     testIntegrity({CKMC_ALGO_AES_CTR, 256});
1351     testIntegrity({CKMC_ALGO_AES_CBC, 128});
1352     testIntegrity({CKMC_ALGO_AES_CBC, 192});
1353     testIntegrity({CKMC_ALGO_AES_CBC, 256});
1354     testIntegrity({CKMC_ALGO_AES_CFB, 128});
1355     testIntegrity({CKMC_ALGO_AES_CFB, 192});
1356     testIntegrity({CKMC_ALGO_AES_CFB, 256});
1357 }
1358
1359 RUNNER_TEST_MULTIPLE(TED_1100_ctr_encryption_invalid_length, SyncEnv, AsyncEnv, CipherEnv)
1360 {
1361     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1362     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1363     testCtrEncryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1364 }
1365
1366 RUNNER_TEST_MULTIPLE(TED_1105_ctr_encryption_valid_length, SyncEnv, AsyncEnv, CipherEnv)
1367 {
1368     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1369     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1370     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1371     testCtrEncryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1372 }
1373
1374 RUNNER_TEST_MULTIPLE(TED_1110_ctr_decryption_invalid_length, SyncEnv, AsyncEnv, CipherEnv)
1375 {
1376     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 128});
1377     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 192});
1378     testCtrDecryptionInvalidLength({CKMC_ALGO_AES_CTR, 256});
1379 }
1380
1381 RUNNER_TEST_MULTIPLE(TED_1115_ctr_decryption_valid_length, SyncEnv, AsyncEnv, CipherEnv)
1382 {
1383     RUNNER_IGNORED_MSG("Openssl supports only 128-bit AES CTR length");
1384     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 128});
1385     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 192});
1386     testCtrDecryptionValidLength({CKMC_ALGO_AES_CTR, 256});
1387 }
1388
1389 RUNNER_TEST_MULTIPLE(TED_1200_gcm_encryption_tag_len, SyncEnv, AsyncEnv, CipherEnv)
1390 {
1391     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1392     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1393     testGcmEncryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1394 }
1395
1396 RUNNER_TEST_MULTIPLE(TED_1210_gcm_decryption_tag_len, SyncEnv, AsyncEnv, CipherEnv)
1397 {
1398     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 128});
1399     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 192});
1400     testGcmDecryptionTagLen({CKMC_ALGO_AES_GCM, 256});
1401 }
1402
1403 RUNNER_TEST_MULTIPLE(TED_1230_gcm_wrong_tag, SyncEnv, AsyncEnv, CipherEnv)
1404 {
1405     testGcmWrongTag({CKMC_ALGO_AES_GCM, 128});
1406     testGcmWrongTag({CKMC_ALGO_AES_GCM, 192});
1407     testGcmWrongTag({CKMC_ALGO_AES_GCM, 256});
1408 }
1409
1410 RUNNER_TEST_MULTIPLE(TED_1240_gcm_different_iv_sizes, SyncEnv, AsyncEnv, CipherEnv)
1411 {
1412     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 128});
1413     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 192});
1414     testGcmDifferentIvSizes({CKMC_ALGO_AES_GCM, 256});
1415 }
1416
1417 RUNNER_TEST_MULTIPLE(TED_1250_gcm_aad, SyncEnv, AsyncEnv, CipherEnv)
1418 {
1419     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 128}, CKMC_PARAM_ED_AAD);
1420     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 192}, CKMC_PARAM_ED_AAD);
1421     encryptionWithCustomData({CKMC_ALGO_AES_GCM, 256}, CKMC_PARAM_ED_AAD);
1422 }
1423
1424 RUNNER_TEST_MULTIPLE(TED_1300_rsa_label, SyncEnv, AsyncEnv)
1425 {
1426     RUNNER_IGNORED_MSG("RSA-OAEP labels are not supported in openssl");
1427     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 1024}, CKMC_PARAM_ED_LABEL);
1428     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 2048}, CKMC_PARAM_ED_LABEL);
1429     encryptionWithCustomData({CKMC_ALGO_RSA_OAEP, 4096}, CKMC_PARAM_ED_LABEL);
1430 }
1431
1432 RUNNER_TEST_MULTIPLE(TED_1330_rsa_longest_data, SyncEnv, AsyncEnv)
1433 {
1434     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 1024}, 86);
1435     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 2048}, 214);
1436     testRsaLongestData({CKMC_ALGO_RSA_OAEP, 4096}, 470);
1437 }
1438
1439 RUNNER_TEST_MULTIPLE(TED_1350_rsa_data_too_long, SyncEnv, AsyncEnv)
1440 {
1441     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 1024}, 87);
1442     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 2048}, 215);
1443     testRsaDataTooLong({CKMC_ALGO_RSA_OAEP, 4096}, 471);
1444 }
1445
1446 /////////////////////////////////////////
1447 // Asynchronous only tests
1448 /////////////////////////////////////////
1449 RUNNER_TEST(TED_2000_enc_no_observer_async, AsyncEnv)
1450 {
1451     testAllAlgorithms([](const Algo& algo){
1452         // prepare buffers
1453         RawBuffer plain = createRandomBuffer(BUF_LEN);
1454
1455         // keys
1456         KeyAliasPair aliases = getKey(algo, PRIMARY);
1457
1458         // params
1459         ckmc_param_list_h handle = NULL;
1460         assert_positive(ckmc_generate_new_params, algo.type, &handle);
1461         ParamListPtr params = ParamListPtr(handle, ckmc_param_list_free);
1462         setParam(params, CKMC_PARAM_ED_IV, DEFAULT_IV);
1463
1464         // encrypt
1465         test_no_observer(&ManagerAsync::encrypt,
1466                          *reinterpret_cast<CryptoAlgorithm*>(params.get()),
1467                          aliases.pub,
1468                          Password(),
1469                          plain);
1470     });
1471 }
1472
1473 RUNNER_TEST(TED_2010_dec_no_observer_async, AsyncEnv)
1474 {
1475     testAllAlgorithms([](const Algo& algo){
1476         // encrypt
1477         auto ret = encrypt(algo, PLAIN_DATA);
1478         RawBuffer encrypted(ret.encrypted->data, ret.encrypted->data + ret.encrypted->size);
1479
1480         // decrypt
1481         test_no_observer(&ManagerAsync::decrypt,
1482                          *reinterpret_cast<CryptoAlgorithm*>(ret.params.get()),
1483                          ret.prvKey,
1484                          Password(),
1485                          encrypted);
1486     });
1487 }
1488
1489 /////////////////////////////////////////
1490 // Mulithreaded test for synchronous API
1491 /////////////////////////////////////////
1492 RUNNER_TEST_MULTIPLE(TED_3000_multiple_threads, SyncEnv, CipherEnv)
1493 {
1494     std::vector<std::thread> threads;
1495     threads.reserve(10);
1496     for(unsigned i = 0; i < 10;++i)
1497         threads.emplace_back([]{ testEncryptDecryptBigData({CKMC_ALGO_AES_CBC, 256}); });
1498     for (auto& thread : threads)
1499         thread.join();
1500 }
1501
1502 /////////////////////////////////////////
1503 // Cipher API only
1504 /////////////////////////////////////////
1505 RUNNER_TEST(TED_4000_cipher_missing_arguments)
1506 {
1507     ckmc_raw_buffer_s* encrypted = nullptr;
1508
1509     auto [alias, params] = defaultGcmCipherSetup();
1510
1511     ckmc_cipher_ctx_h ctx = nullptr;
1512     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1513     auto ctxPtr = create_cipher_ctx(ctx);
1514
1515     // no AAD
1516     assert_invalid_param(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1517
1518     // missing arguments
1519     assert_invalid_param(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, nullptr);
1520     assert_invalid_param(ckmc_cipher_update, nullptr, *PLAIN_DATA.get(), &encrypted);
1521     assert_invalid_param(ckmc_cipher_update, ctx, *PLAIN_DATA.get(), nullptr);
1522     assert_invalid_param(ckmc_cipher_finalize, nullptr, nullptr, &encrypted);
1523     assert_invalid_param(ckmc_cipher_finalize, nullptr, nullptr, nullptr);
1524 }
1525
1526 RUNNER_TEST(TED_4010_cipher_reinitialize_without_aad)
1527 {
1528     auto [alias, params] = defaultGcmCipherSetup();
1529
1530     ckmc_cipher_ctx_h ctx = nullptr;
1531     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1532     auto ctxPtr = create_cipher_ctx(ctx);
1533
1534     // no AAD
1535     assert_invalid_param(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1536 }
1537
1538 RUNNER_TEST(TED_4020_cipher_tag_during_encryption)
1539 {
1540     ckmc_raw_buffer_s* encrypted = nullptr;
1541
1542     auto [alias, params] = defaultGcmCipherSetup();
1543
1544     ckmc_cipher_ctx_h ctx = nullptr;
1545     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1546     auto ctxPtr = create_cipher_ctx(ctx);
1547
1548     // tag input during encryption
1549     assert_invalid_param(ckmc_cipher_finalize, ctx, PLAIN_DATA.get(), &encrypted);
1550 }
1551
1552 RUNNER_TEST(TED_4030_cipher_wrong_order)
1553 {
1554     ckmc_raw_buffer_s* encrypted = nullptr;
1555
1556     auto [alias, params] = defaultGcmCipherSetup();
1557
1558     ckmc_cipher_ctx_h ctx = nullptr;
1559     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1560     auto ctxPtr = create_cipher_ctx(ctx);
1561
1562     assert_positive(ckmc_cipher_update, ctx, *PLAIN_DATA.get(), &encrypted);
1563     ckmc_buffer_free(encrypted);
1564
1565     // initialize after update
1566     setParam(params, CKMC_PARAM_ED_AAD, AAD32);
1567     assert_invalid_param(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, nullptr);
1568
1569     assert_positive(ckmc_cipher_finalize, ctx, nullptr, &encrypted);
1570     ckmc_buffer_free(encrypted);
1571
1572     // initialize after finalize
1573     assert_invalid_param(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, nullptr);
1574
1575     // update after finalize
1576     assert_invalid_param(ckmc_cipher_update, ctx, *PLAIN_DATA.get(), &encrypted);
1577 }
1578
1579 RUNNER_TEST(TED_4040_cipher_gcm_aad_and_tag)
1580 {
1581     ckmc_raw_buffer_s* encrypted = nullptr;
1582
1583     auto [alias, params] = defaultGcmCipherSetup();
1584     setParam(params, CKMC_PARAM_ED_AAD, AAD32);
1585
1586     ckmc_cipher_ctx_h ctx = nullptr;
1587
1588     // encrypt
1589     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1590     auto ctxPtr = create_cipher_ctx(ctx);
1591
1592     // 2 more AAD chunks
1593     setParam(params, CKMC_PARAM_ED_AAD, AAD64);
1594     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1595     setParam(params, CKMC_PARAM_ED_AAD, AAD32);
1596     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, true, &ctx);
1597
1598     ckmc_raw_buffer_s* tag = nullptr;
1599
1600     assert_positive(ckmc_cipher_update, ctx, *PLAIN_DATA.get(), &encrypted);
1601     auto encryptedPtr = create_raw_buffer(encrypted);
1602     assert_positive(ckmc_cipher_finalize, ctx, nullptr, &tag);
1603
1604     ctxPtr.reset();
1605     ctx = nullptr;
1606
1607     ckmc_raw_buffer_s* decrypted = nullptr;
1608     ckmc_raw_buffer_s* empty = nullptr;
1609
1610     // decrypt with invalid AAD
1611     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1612     ctxPtr = create_cipher_ctx(ctx);
1613
1614     assert_positive(ckmc_cipher_update, ctx, *encrypted, &decrypted);
1615     ckmc_buffer_free(decrypted);
1616     assert_invalid_param(ckmc_cipher_finalize, ctx, tag, &empty);
1617
1618     ctxPtr.reset();
1619     ctx = nullptr;
1620
1621     // decrypt without TAG
1622     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1623     ctxPtr = create_cipher_ctx(ctx);
1624     setParam(params, CKMC_PARAM_ED_AAD, AAD64);
1625     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1626     setParam(params, CKMC_PARAM_ED_AAD, AAD32);
1627     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1628
1629     assert_positive(ckmc_cipher_update, ctx, *encrypted, &decrypted);
1630     ckmc_buffer_free(decrypted);
1631     assert_invalid_param(ckmc_cipher_finalize, ctx, nullptr, &empty);
1632
1633     ctxPtr.reset();
1634     ctx = nullptr;
1635
1636     // correct decrypt
1637     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1638     ctxPtr = create_cipher_ctx(ctx);
1639     setParam(params, CKMC_PARAM_ED_AAD, AAD64);
1640     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1641     setParam(params, CKMC_PARAM_ED_AAD, AAD32);
1642     assert_positive(ckmc_cipher_initialize, params.get(), alias.c_str(), nullptr, false, &ctx);
1643
1644     assert_positive(ckmc_cipher_update, ctx, *encrypted, &decrypted);
1645     auto decryptedPtr = create_raw_buffer(decrypted);
1646     assert_positive(ckmc_cipher_finalize, ctx, tag, &empty);
1647
1648     RUNNER_ASSERT(empty == nullptr);
1649
1650     assert_buffers_equal(PLAIN_DATA.get(), decrypted);
1651 }