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