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