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