summaryrefslogtreecommitdiff
path: root/src/manager/client/client-manager-impl.cpp
blob: 17b79b7adf34a4833b15c820a5e688214a869262 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
/* Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        client-manager-impl.cpp
 * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
 * @version     1.0
 * @brief       Manager implementation.
 */
#include <openssl/evp.h>

#include <dpl/serialization.h>
#include <dpl/log/log.h>

#include <crypto-init.h>
#include <client-manager-impl.h>
#include <client-common.h>
#include <message-buffer.h>
#include <protocols.h>
#include <key-impl.h>
#include <key-aes-impl.h>
#include <certificate-impl.h>

namespace CKM {

namespace {
template <class T>
int getCertChain(
    ServiceConnection & serviceConnection,
    LogicCommand command,
    int counter,
    const CertificateShPtr &certificate,
    const T &untrustedVector,
    const T &trustedVector,
    bool useTrustedSystemCertificates,
    CertificateShPtrVector &certificateChainVector)
{
    return try_catch([&] {
        MessageBuffer recv;
        auto send = MessageBuffer::Serialize(static_cast<int>(command),
                                             counter,
                                             certificate->getDER(),
                                             untrustedVector,
                                             trustedVector,
                                             useTrustedSystemCertificates);

        int retCode = serviceConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int retCommand;
        int retCounter;
        RawBufferVector rawBufferVector;
        recv.Deserialize(retCommand, retCounter, retCode, rawBufferVector);

        if ((counter != retCounter) || (static_cast<int>(command) != retCommand))
            return CKM_API_ERROR_UNKNOWN;

        if (retCode != CKM_API_SUCCESS)
            return retCode;

        for (auto &e: rawBufferVector) {
            CertificateShPtr cert(new CertificateImpl(e, DataFormat::FORM_DER));
            if (cert->empty())
                return CKM_API_ERROR_BAD_RESPONSE;
            certificateChainVector.push_back(cert);
        }

        return retCode;
    });
}

} // namespace anonymous

Manager::Impl::Impl()
  : m_counter(0),
    m_storageConnection(SERVICE_SOCKET_CKM_STORAGE),
    m_ocspConnection(SERVICE_SOCKET_OCSP),
    m_encryptionConnection(SERVICE_SOCKET_ENCRYPTION)
{
    initOpenSslOnce();
}


int Manager::Impl::saveBinaryData(
    const Alias &alias,
    DataType dataType,
    const RawBuffer &rawData,
    const Policy &policy)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        if (alias.empty() || rawData.empty())
            return CKM_API_ERROR_INPUT_PARAM;

        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
                                             my_counter,
                                             static_cast<int>(dataType),
                                             helper.getName(),
                                             helper.getLabel(),
                                             rawData,
                                             PolicySerializable(policy));

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        int opType;
        recv.Deserialize(command, counter, retCode, opType);

        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::saveKey(const Alias &alias, const KeyShPtr &key, const Policy &policy)
{
    if (key.get() == NULL)
        return CKM_API_ERROR_INPUT_PARAM;
    Try {
        return saveBinaryData(alias, DataType(key->getType()), key->getDER(), policy);
    } Catch(DataType::Exception::Base) {
        LogError("Error in key conversion. Could not convert KeyType::NONE to DBDataType!");
    }
    return CKM_API_ERROR_INPUT_PARAM;
}

int Manager::Impl::saveCertificate(
    const Alias &alias,
    const CertificateShPtr &cert,
    const Policy &policy)
{
    if (cert.get() == NULL)
        return CKM_API_ERROR_INPUT_PARAM;
    return saveBinaryData(alias, DataType::CERTIFICATE, cert->getDER(), policy);
}

int Manager::Impl::saveData(const Alias &alias, const RawBuffer &rawData, const Policy &policy)
{
    if (!policy.extractable)
        return CKM_API_ERROR_INPUT_PARAM;
    return saveBinaryData(alias, DataType::BINARY_DATA, rawData, policy);
}


int Manager::Impl::savePKCS12(
    const Alias & alias,
    const PKCS12ShPtr &pkcs,
    const Policy &keyPolicy,
    const Policy &certPolicy)
{
    if (alias.empty() || pkcs.get() == NULL)
        return CKM_API_ERROR_INPUT_PARAM;

    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE_PKCS12),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel(),
                                             PKCS12Serializable(*pkcs.get()),
                                             PolicySerializable(keyPolicy),
                                             PolicySerializable(certPolicy));

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);

        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::getPKCS12(const Alias &alias, PKCS12ShPtr &pkcs)
{
    return getPKCS12(alias, Password(), Password(), pkcs);
}

int Manager::Impl::getPKCS12(const Alias &alias, const Password &keyPass, const Password &certPass, PKCS12ShPtr &pkcs)
{
    if (alias.empty())
        return CKM_API_ERROR_INPUT_PARAM;

    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_PKCS12),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel(),
                                             keyPass,
                                             certPass);

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        PKCS12Serializable gotPkcs;
        recv.Deserialize(command, counter, retCode, gotPkcs);

        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        pkcs = std::make_shared<PKCS12Impl>(std::move(gotPkcs));

        return retCode;
    });
}


int Manager::Impl::removeAlias(const Alias &alias)
{
    if (alias.empty())
        return CKM_API_ERROR_INPUT_PARAM;

    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel());

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);

        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::getBinaryData(
    const Alias &alias,
    DataType sendDataType,
    const Password &password,
    DataType &recvDataType,
    RawBuffer &rawData)
{
    if (alias.empty())
        return CKM_API_ERROR_INPUT_PARAM;

    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
                                             my_counter,
                                             static_cast<int>(sendDataType),
                                             helper.getName(),
                                             helper.getLabel(),
                                             password);

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        int tmpDataType;
        recv.Deserialize(command, counter, retCode, tmpDataType, rawData);
        recvDataType = DataType(tmpDataType);

        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::getKey(const Alias &alias, const Password &password, KeyShPtr &key)
{
    DataType recvDataType;
    RawBuffer rawData;

    int retCode = getBinaryData(
        alias,
        DataType::KEY_RSA_PUBLIC,
        password,
        recvDataType,
        rawData);

    if (retCode != CKM_API_SUCCESS)
        return retCode;

    KeyShPtr keyParsed;
    if (DataType::KEY_AES == recvDataType)
        keyParsed = KeyShPtr(new KeyAESImpl(rawData));
    else
        keyParsed = KeyShPtr(new KeyImpl(rawData));

    if (keyParsed->empty()) {
        LogDebug("Key empty - failed to parse!");
        return CKM_API_ERROR_BAD_RESPONSE;
    }

    key = keyParsed;

    return CKM_API_SUCCESS;
}

int Manager::Impl::getCertificate(const Alias &alias, const Password &password, CertificateShPtr &cert)
{
    DataType recvDataType;
    RawBuffer rawData;

    int retCode = getBinaryData(
        alias,
        DataType::CERTIFICATE,
        password,
        recvDataType,
        rawData);

    if (retCode != CKM_API_SUCCESS)
        return retCode;

    if (recvDataType != DataType::CERTIFICATE)
        return CKM_API_ERROR_BAD_RESPONSE;

    CertificateShPtr certParsed(new CertificateImpl(rawData, DataFormat::FORM_DER));

    if (certParsed->empty())
        return CKM_API_ERROR_BAD_RESPONSE;

    cert = certParsed;

    return CKM_API_SUCCESS;
}

int Manager::Impl::getData(const Alias &alias, const Password &password, RawBuffer &rawData)
{
    DataType recvDataType = DataType::BINARY_DATA;

    int retCode = getBinaryData(
        alias,
        DataType::BINARY_DATA,
        password,
        recvDataType,
        rawData);

    if (retCode != CKM_API_SUCCESS)
        return retCode;

    if (recvDataType != DataType::BINARY_DATA)
        return CKM_API_ERROR_BAD_RESPONSE;

    return CKM_API_SUCCESS;
}

int Manager::Impl::getBinaryDataAliasVector(DataType dataType, AliasVector &aliasVector)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_LIST),
                                             my_counter,
                                             static_cast<int>(dataType));

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        int tmpDataType;
        LabelNameVector labelNameVector;
        recv.Deserialize(command, counter, retCode, tmpDataType, labelNameVector);
        if ((command != static_cast<int>(LogicCommand::GET_LIST)) || (counter != my_counter))
            return CKM_API_ERROR_UNKNOWN;

        for (const auto &it : labelNameVector)
            aliasVector.push_back(AliasSupport::merge(it.first, it.second));

        return retCode;
    });
}

int Manager::Impl::getKeyAliasVector(AliasVector &aliasVector)
{
    // in fact datatype has no meaning here - if not certificate or binary data
    // then manager decides to list all between DB_KEY_FIRST and DB_KEY_LAST
    return getBinaryDataAliasVector(DataType::DB_KEY_LAST, aliasVector);
}

int Manager::Impl::getCertificateAliasVector(AliasVector &aliasVector)
{
    return getBinaryDataAliasVector(DataType::CERTIFICATE, aliasVector);
}

int Manager::Impl::getDataAliasVector(AliasVector &aliasVector)
{
    return getBinaryDataAliasVector(DataType::BINARY_DATA, aliasVector);
}

int Manager::Impl::createKeyPairRSA(
    const int size,
    const Alias &privateKeyAlias,
    const Alias &publicKeyAlias,
    const Policy &policyPrivateKey,
    const Policy &policyPublicKey)
{
    return this->createKeyPair(CKM::KeyType::KEY_RSA_PUBLIC, size, privateKeyAlias, publicKeyAlias, policyPrivateKey, policyPublicKey);
}

int Manager::Impl::createKeyPairDSA(
    const int size,
    const Alias &privateKeyAlias,
    const Alias &publicKeyAlias,
    const Policy &policyPrivateKey,
    const Policy &policyPublicKey)
{
    return this->createKeyPair(CKM::KeyType::KEY_DSA_PUBLIC, size, privateKeyAlias, publicKeyAlias, policyPrivateKey, policyPublicKey);
}

int Manager::Impl::createKeyPairECDSA(
    ElipticCurve type,
    const Alias &privateKeyAlias,
    const Alias &publicKeyAlias,
    const Policy &policyPrivateKey,
    const Policy &policyPublicKey)
{
    return this->createKeyPair(CKM::KeyType::KEY_ECDSA_PUBLIC, static_cast<int>(type), privateKeyAlias, publicKeyAlias, policyPrivateKey, policyPublicKey);
}

int Manager::Impl::createKeyAES(
    const int size,
    const Alias &keyAlias,
    const Policy &policyKey)
{
    // proceed with sending request
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport aliasHelper(keyAlias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
                                             my_counter,
                                             static_cast<int>(size),
                                             PolicySerializable(policyKey),
                                             aliasHelper.getName(),
                                             aliasHelper.getLabel());

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);
        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}


int Manager::Impl::createKeyPair(
    const KeyType key_type,
    const int     additional_param,
    const Alias  &privateKeyAlias,
    const Alias  &publicKeyAlias,
    const Policy &policyPrivateKey,
    const Policy &policyPublicKey)
{
    // input type check
    CryptoAlgorithm keyGenAlgorithm;
    switch (key_type) {
        case KeyType::KEY_RSA_PUBLIC:
        case KeyType::KEY_RSA_PRIVATE:
            keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::RSA_GEN);
            keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, additional_param);
            break;

        case KeyType::KEY_DSA_PUBLIC:
        case KeyType::KEY_DSA_PRIVATE:
            keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::DSA_GEN);
            keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, additional_param);
            break;

        case KeyType::KEY_ECDSA_PUBLIC:
        case KeyType::KEY_ECDSA_PRIVATE:
            keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::ECDSA_GEN);
            keyGenAlgorithm.setParam(ParamName::GEN_EC, additional_param);
            break;

        default:
            return CKM_API_ERROR_INPUT_PARAM;
    }

    // proceed with sending request
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport privateHelper(privateKeyAlias);
        AliasSupport publicHelper(publicKeyAlias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
                                             my_counter,
                                             CryptoAlgorithmSerializable(keyGenAlgorithm),
                                             PolicySerializable(policyPrivateKey),
                                             PolicySerializable(policyPublicKey),
                                             privateHelper.getName(),
                                             privateHelper.getLabel(),
                                             publicHelper.getName(),
                                             publicHelper.getLabel());

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);
        if (counter != my_counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::getCertificateChain(
    const CertificateShPtr &certificate,
    const CertificateShPtrVector &untrustedCertificates,
    const CertificateShPtrVector &trustedCertificates,
    bool useTrustedSystemCertificates,
    CertificateShPtrVector &certificateChainVector)
{
    RawBufferVector untrustedVector;
    RawBufferVector trustedVector;

    if (!certificate || certificate->empty())
        return CKM_API_ERROR_INPUT_PARAM;

    for (auto &e: untrustedCertificates)
        untrustedVector.push_back(e->getDER());

    for (auto &e: trustedCertificates)
        trustedVector.push_back(e->getDER());

    return getCertChain(
            m_storageConnection,
            LogicCommand::GET_CHAIN_CERT,
            ++m_counter,
            certificate,
            untrustedVector,
            trustedVector,
            useTrustedSystemCertificates,
            certificateChainVector);
}

int Manager::Impl::getCertificateChain(
    const CertificateShPtr &certificate,
    const AliasVector &untrustedCertificates,
    const AliasVector &trustedCertificates,
    bool useTrustedSystemCertificates,
    CertificateShPtrVector &certificateChainVector)
{
    LabelNameVector untrustedVector;
    LabelNameVector trustedVector;

    if (!certificate || certificate->empty())
        return CKM_API_ERROR_INPUT_PARAM;

    for (auto &e: untrustedCertificates) {
        AliasSupport helper(e);
        untrustedVector.push_back(std::make_pair(helper.getLabel(), helper.getName()));
    }
    for (auto &e: trustedCertificates) {
        AliasSupport helper(e);
        trustedVector.push_back(std::make_pair(helper.getLabel(), helper.getName()));
    }

    return getCertChain(
            m_storageConnection,
            LogicCommand::GET_CHAIN_ALIAS,
            ++m_counter,
            certificate,
            untrustedVector,
            trustedVector,
            useTrustedSystemCertificates,
            certificateChainVector);
}

int Manager::Impl::createSignature(
    const Alias &privateKeyAlias,
    const Password &password,           // password for private_key
    const RawBuffer &message,
    const CryptoAlgorithm &cAlgorithm,
    RawBuffer &signature)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(privateKeyAlias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_SIGNATURE),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel(),
                                             password,
                                             message,
                                             CryptoAlgorithmSerializable(cAlgorithm));

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode, signature);

        if ((command != static_cast<int>(LogicCommand::CREATE_SIGNATURE))
            || (counter != my_counter))
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::verifySignature(
    const Alias &publicKeyOrCertAlias,
    const Password &password,           // password for public_key (optional)
    const RawBuffer &message,
    const RawBuffer &signature,
    const CryptoAlgorithm &cAlg)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(publicKeyOrCertAlias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::VERIFY_SIGNATURE),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel(),
                                             password,
                                             message,
                                             signature,
                                             CryptoAlgorithmSerializable(cAlg));

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);

        if ((command != static_cast<int>(LogicCommand::VERIFY_SIGNATURE))
            || (counter != my_counter))
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::ocspCheck(const CertificateShPtrVector &certChain, int &ocspStatus)
{
    return try_catch([&] {
        int my_counter = ++m_counter;
        MessageBuffer recv;

        RawBufferVector rawCertChain;
        for (auto &e: certChain) {
            if (!e || e->empty()) {
                LogError("Empty certificate");
                return CKM_API_ERROR_INPUT_PARAM;
            }
            rawCertChain.push_back(e->getDER());
        }

        auto send = MessageBuffer::Serialize(my_counter, rawCertChain);

        int retCode = m_ocspConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int counter;
        recv.Deserialize(counter, retCode, ocspStatus);

        if (my_counter != counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::setPermission(const Alias &alias,
                               const Label &accessor,
                               PermissionMask permissionMask)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(alias);
        auto send = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SET_PERMISSION),
                                             my_counter,
                                             helper.getName(),
                                             helper.getLabel(),
                                             accessor,
                                             permissionMask);

        int retCode = m_storageConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int command;
        int counter;
        recv.Deserialize(command, counter, retCode);

        if (my_counter != counter)
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::crypt(EncryptionCommand command,
          const CryptoAlgorithm &algo,
          const Alias &keyAlias,
          const Password &password,
          const RawBuffer& input,
          RawBuffer& output)
{
    int my_counter = ++m_counter;

    return try_catch([&] {
        MessageBuffer recv;
        AliasSupport helper(keyAlias);
        CryptoAlgorithmSerializable cas(algo);
        auto send = MessageBuffer::Serialize(static_cast<int>(command),
                                             my_counter,
                                             cas,
                                             helper.getName(),
                                             helper.getLabel(),
                                             password,
                                             input);

        int retCode = m_encryptionConnection.processRequest(send.Pop(), recv);
        if (CKM_API_SUCCESS != retCode)
            return retCode;

        int retCommand;
        int counter;
        recv.Deserialize(retCommand, counter, retCode, output);

        if (my_counter != counter || retCommand != static_cast<int>(command))
            return CKM_API_ERROR_UNKNOWN;

        return retCode;
    });
}

int Manager::Impl::encrypt(const CryptoAlgorithm &algo,
            const Alias &keyAlias,
            const Password &password,
            const RawBuffer& plain,
            RawBuffer& encrypted)
{
    return crypt(EncryptionCommand::ENCRYPT, algo, keyAlias, password, plain, encrypted);
}

int Manager::Impl::decrypt(const CryptoAlgorithm &algo,
                         const Alias &keyAlias,
                         const Password &password,
                         const RawBuffer& encrypted,
                         RawBuffer& decrypted)
{
    return crypt(EncryptionCommand::DECRYPT, algo, keyAlias, password, encrypted, decrypted);
}

} // namespace CKM