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