add HASH_NONE and NO_PADDING algo for createSignature and verifySignature
[platform/core/security/key-manager.git] / src / manager / service / ckm-logic.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 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        ckm-logic.cpp
18  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version     1.0
20  * @brief       Sample service implementation.
21  */
22 #include <dpl/serialization.h>
23 #include <dpl/log/log.h>
24 #include <ckm/ckm-error.h>
25 #include <ckm/ckm-type.h>
26 #include <key-provider.h>
27 #include <file-system.h>
28 #include <CryptoService.h>
29 #include <ckm-logic.h>
30 #include <key-impl.h>
31
32 namespace {
33 const char * const CERT_SYSTEM_DIR = "/etc/ssl/certs";
34 } // anonymous namespace
35
36 namespace CKM {
37
38 CKMLogic::CKMLogic()
39 {
40     int retCode = FileSystem::init();
41     // TODO what can I do when init went wrong? exit(-1) ??
42     if (retCode) {
43         LogError("Fatal error in FileSystem::init()");
44     }
45
46     if (CKM_API_SUCCESS != m_certStore.setSystemCertificateDir(CERT_SYSTEM_DIR)) {
47         LogError("Fatal error in CertificateStore::setSystemCertificateDir. Chain creation will not work");
48     }
49 }
50
51 CKMLogic::~CKMLogic(){}
52
53 RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password) {
54     // TODO try catch for all errors that should be supported by error code
55     int retCode = CKM_API_SUCCESS;
56
57     try {
58         if (0 == m_userDataMap.count(user) || !(m_userDataMap[user].keyProvider.isInitialized())) {
59             auto &handle = m_userDataMap[user];
60             FileSystem fs(user);
61             auto wrappedDomainKEK = fs.getDKEK();
62
63             if (wrappedDomainKEK.empty()) {
64                 wrappedDomainKEK = KeyProvider::generateDomainKEK(std::to_string(user), password);
65                 fs.saveDKEK(wrappedDomainKEK);
66             }
67
68             handle.keyProvider = KeyProvider(wrappedDomainKEK, password);
69
70             auto wrappedDatabaseDEK = fs.getDBDEK();
71
72             if (wrappedDatabaseDEK.empty()) {
73                 wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
74                 fs.saveDBDEK(wrappedDatabaseDEK);
75             }
76
77             RawBuffer key = handle.keyProvider.getPureDEK(wrappedDatabaseDEK);
78             handle.database = DBCrypto(fs.getDBPath(), key);
79             handle.crypto = CryptoLogic();
80
81             // remove data of removed apps during locked state
82             AppLabelVector removedApps = fs.clearRemovedsApps();
83             for(auto& appSmackLabel : removedApps) {
84                 handle.database.deleteKey(appSmackLabel);
85             }
86
87             // TODO wipe key
88         }
89     } catch (const KeyProvider::Exception::PassWordError &e) {
90         LogError("Incorrect Password " << e.GetMessage());
91         retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
92     } catch (const KeyProvider::Exception::Base &e) {
93         LogError("Error in KeyProvider " << e.GetMessage());
94         retCode = CKM_API_ERROR_SERVER_ERROR;
95     } catch (const CryptoLogic::Exception::Base &e) {
96         LogError("CryptoLogic error: " << e.GetMessage());
97         retCode = CKM_API_ERROR_SERVER_ERROR;
98     } catch (const CKM::Exception &e) {
99         LogError("CKM::Exception: " << e.GetMessage());
100         retCode = CKM_API_ERROR_SERVER_ERROR;
101     }
102
103     if(retCode != CKM_API_SUCCESS) {
104         // When not successful, UserData in m_userDataMap should be erased.
105         // Because other operations make decision based on the existence of UserData in m_userDataMap.
106         m_userDataMap.erase(user);
107     }
108
109     MessageBuffer response;
110     Serialization::Serialize(response, retCode);
111     return response.Pop();
112 }
113
114 RawBuffer CKMLogic::lockUserKey(uid_t user) {
115     int retCode = CKM_API_SUCCESS;
116     // TODO try catch for all errors that should be supported by error code
117     m_userDataMap.erase(user);
118
119     MessageBuffer response;
120     Serialization::Serialize(response, retCode);
121     return response.Pop();
122 }
123
124 RawBuffer CKMLogic::removeUserData(uid_t user) {
125     int retCode = CKM_API_SUCCESS;
126     // TODO try catch for all errors that should be supported by error code
127     m_userDataMap.erase(user);
128
129     FileSystem fs(user);
130     fs.removeUserData();
131
132     MessageBuffer response;
133     Serialization::Serialize(response, retCode);
134     return response.Pop();
135 }
136
137 RawBuffer CKMLogic::changeUserPassword(
138     uid_t user,
139     const Password &oldPassword,
140     const Password &newPassword)
141 {
142     int retCode = CKM_API_SUCCESS;
143     try {
144         FileSystem fs(user);
145         auto wrappedDomainKEK = fs.getDKEK();
146         if (wrappedDomainKEK.empty()) {
147             retCode = CKM_API_ERROR_BAD_REQUEST;
148         } else {
149             wrappedDomainKEK = KeyProvider::reencrypt(wrappedDomainKEK, oldPassword, newPassword);
150             fs.saveDKEK(wrappedDomainKEK);
151         }
152     } catch (const KeyProvider::Exception::PassWordError &e) {
153         LogError("Incorrect Password " << e.GetMessage());
154         retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
155     } catch (const KeyProvider::Exception::Base &e) {
156         LogError("Error in KeyProvider " << e.GetMessage());
157         retCode = CKM_API_ERROR_SERVER_ERROR;
158     } catch (const CKM::Exception &e) {
159         LogError("CKM::Exception: " << e.GetMessage());
160         retCode = CKM_API_ERROR_SERVER_ERROR;
161     }
162
163     MessageBuffer response;
164     Serialization::Serialize(response, retCode);
165     return response.Pop();
166 }
167
168 RawBuffer CKMLogic::resetUserPassword(
169     uid_t user,
170     const Password &newPassword)
171 {
172     int retCode = CKM_API_SUCCESS;
173     // TODO try-catch
174     if (0 == m_userDataMap.count(user)) {
175         retCode = CKM_API_ERROR_BAD_REQUEST;
176     } else {
177         auto &handler = m_userDataMap[user];
178         FileSystem fs(user);
179         fs.saveDKEK(handler.keyProvider.getWrappedDomainKEK(newPassword));
180     }
181
182     MessageBuffer response;
183     Serialization::Serialize(response, retCode);
184     return response.Pop();
185 }
186
187 RawBuffer CKMLogic::removeApplicationData(const std::string &smackLabel) {
188     int retCode = CKM_API_SUCCESS;
189
190     try {
191
192         if (smackLabel.empty()) {
193             retCode = CKM_API_ERROR_INPUT_PARAM;
194         } else {
195             UidVector uids = FileSystem::getUIDsFromDBFile();
196             for (auto userId : uids) {
197                 if (0 == m_userDataMap.count(userId)) {
198                     FileSystem fs(userId);
199                     fs.addRemovedApp(smackLabel);
200                 } else {
201                     auto &handle = m_userDataMap[userId];
202                     handle.database.deleteKey(smackLabel);
203                 }
204             }
205         }
206
207     } catch (const DBCrypto::Exception::InternalError &e) {
208         LogError("DBCrypto couldn't remove data: " << e.GetMessage());
209         retCode = CKM_API_ERROR_DB_ERROR;
210     } catch (const DBCrypto::Exception::TransactionError &e) {
211         LogError("DBCrypto transaction failed with message " << e.GetMessage());
212         retCode = CKM_API_ERROR_DB_ERROR;
213     }
214
215     MessageBuffer response;
216     Serialization::Serialize(response, retCode);
217     return response.Pop();
218 }
219
220 int CKMLogic::saveDataHelper(
221     Credentials &cred,
222     DBDataType dataType,
223     const Alias &alias,
224     const RawBuffer &key,
225     const PolicySerializable &policy)
226 {
227     if (0 == m_userDataMap.count(cred.uid))
228         return CKM_API_ERROR_DB_LOCKED;
229
230     DBRow row = { alias, cred.smackLabel,
231          policy.extractable, dataType, DBCMAlgType::NONE,
232          0, RawBuffer(), static_cast<int>(key.size()), key, RawBuffer() };
233
234     auto &handler = m_userDataMap[cred.uid];
235     DBCrypto::Transaction transaction(&handler.database);
236     if (!handler.crypto.haveKey(cred.smackLabel)) {
237         RawBuffer key;
238         auto key_optional = handler.database.getKey(cred.smackLabel);
239         if(!key_optional) {
240             LogDebug("No Key in database found. Generating new one for label: "
241                     << cred.smackLabel);
242             key = handler.keyProvider.generateDEK(cred.smackLabel);
243             handler.database.saveKey(cred.smackLabel, key);
244         } else {
245             LogDebug("Key from DB");
246             key = *key_optional;
247         }
248
249         key = handler.keyProvider.getPureDEK(key);
250         handler.crypto.pushKey(cred.smackLabel, key);
251     }
252     handler.crypto.encryptRow(policy.password, row);
253     handler.database.saveDBRow(row);
254     transaction.commit();
255     return CKM_API_SUCCESS;
256 }
257
258 RawBuffer CKMLogic::saveData(
259     Credentials &cred,
260     int commandId,
261     DBDataType dataType,
262     const Alias &alias,
263     const RawBuffer &key,
264     const PolicySerializable &policy)
265 {
266     int retCode = CKM_API_SUCCESS;
267     try {
268         retCode = saveDataHelper(cred, dataType, alias, key, policy);
269         LogDebug("SaveDataHelper returned: " << retCode);
270     } catch (const KeyProvider::Exception::Base &e) {
271         LogError("KeyProvider failed with message: " << e.GetMessage());
272         retCode = CKM_API_ERROR_SERVER_ERROR;
273     } catch (const CryptoLogic::Exception::Base &e) {
274         LogError("CryptoLogic failed with message: " << e.GetMessage());
275         retCode = CKM_API_ERROR_SERVER_ERROR;
276     } catch (const DBCrypto::Exception::InternalError &e) {
277         LogError("DBCrypto failed with message: " << e.GetMessage());
278         retCode = CKM_API_ERROR_DB_ERROR;
279     } catch (const DBCrypto::Exception::AliasExists &e) {
280         LogError("DBCrypto couldn't save duplicate alias");
281         retCode = CKM_API_ERROR_DB_ALIAS_EXISTS;
282     } catch (const DBCrypto::Exception::TransactionError &e) {
283         LogError("DBCrypto transaction failed with message " << e.GetMessage());
284         retCode = CKM_API_ERROR_DB_ERROR;
285     }
286
287     MessageBuffer response;
288     Serialization::Serialize(response, static_cast<int>(LogicCommand::SAVE));
289     Serialization::Serialize(response, commandId);
290     Serialization::Serialize(response, retCode);
291     Serialization::Serialize(response, static_cast<int>(dataType));
292
293     return response.Pop();
294 }
295
296 RawBuffer CKMLogic::removeData(
297     Credentials &cred,
298     int commandId,
299     DBDataType dataType,
300     const Alias &alias)
301 {
302     int retCode = CKM_API_SUCCESS;
303
304     if (0 < m_userDataMap.count(cred.uid)) {
305         Try {
306             auto erased = m_userDataMap[cred.uid].database.deleteDBRow(alias, cred.smackLabel);
307             // check if the data existed or not
308             if(!erased) {
309                 LogError("No row for given alias and label");
310                 retCode = CKM_API_ERROR_DB_ALIAS_UNKNOWN;
311             }
312         } Catch (CKM::Exception) {
313             LogError("Error in deleting row!");
314             retCode = CKM_API_ERROR_DB_ERROR;
315         }
316     } else {
317         retCode = CKM_API_ERROR_DB_LOCKED;
318     }
319
320     MessageBuffer response;
321     Serialization::Serialize(response, static_cast<int>(LogicCommand::REMOVE));
322     Serialization::Serialize(response, commandId);
323     Serialization::Serialize(response, retCode);
324     Serialization::Serialize(response, static_cast<int>(dataType));
325
326     return response.Pop();
327 }
328
329 int CKMLogic::getDataHelper(
330     Credentials &cred,
331     DBDataType dataType,
332     const Alias &alias,
333     const Password &password,
334     DBRow &row)
335 {
336
337     if (0 == m_userDataMap.count(cred.uid))
338         return CKM_API_ERROR_DB_LOCKED;
339
340     auto &handler = m_userDataMap[cred.uid];
341
342     DBCrypto::DBRowOptional row_optional;
343     if (dataType == DBDataType::CERTIFICATE || dataType == DBDataType::BINARY_DATA) {
344         row_optional = handler.database.getDBRow(alias, cred.smackLabel, dataType);
345     } else if ((static_cast<int>(dataType) >= static_cast<int>(DBDataType::DB_KEY_FIRST))
346             && (static_cast<int>(dataType) <= static_cast<int>(DBDataType::DB_KEY_LAST)))
347     {
348         row_optional = handler.database.getKeyDBRow(alias, cred.smackLabel);
349     } else {
350         LogError("Unknown type of requested data" << (int)dataType);
351         return CKM_API_ERROR_BAD_REQUEST;
352     }
353     if(!row_optional) {
354         LogError("No row for given alias, label and type");
355         return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
356     } else {
357         row = *row_optional;
358     }
359
360     if (!handler.crypto.haveKey(row.smackLabel)) {
361         RawBuffer key;
362         auto key_optional = handler.database.getKey(row.smackLabel);
363         if(!key_optional) {
364             LogError("No key for given label in database");
365             return CKM_API_ERROR_DB_ERROR;
366         }
367         key = *key_optional;
368         key = handler.keyProvider.getPureDEK(key);
369         handler.crypto.pushKey(cred.smackLabel, key);
370     }
371     handler.crypto.decryptRow(password, row);
372
373     return CKM_API_SUCCESS;
374 }
375
376 RawBuffer CKMLogic::getData(
377     Credentials &cred,
378     int commandId,
379     DBDataType dataType,
380     const Alias &alias,
381     const Password &password)
382 {
383     int retCode = CKM_API_SUCCESS;
384     DBRow row;
385
386     try {
387         retCode = getDataHelper(cred, dataType, alias, password, row);
388     } catch (const KeyProvider::Exception::Base &e) {
389         LogError("KeyProvider failed with error: " << e.GetMessage());
390         retCode = CKM_API_ERROR_SERVER_ERROR;
391     } catch (const CryptoLogic::Exception::Base &e) {
392         LogError("CryptoLogic failed with message: " << e.GetMessage());
393         retCode = CKM_API_ERROR_SERVER_ERROR;
394     } catch (const DBCrypto::Exception::Base &e) {
395         LogError("DBCrypto failed with message: " << e.GetMessage());
396         retCode = CKM_API_ERROR_DB_ERROR;
397     }
398
399     if (CKM_API_SUCCESS != retCode) {
400         row.data.clear();
401         row.dataType = dataType;
402     }
403
404     if ((CKM_API_SUCCESS == retCode) && (row.exportable == 0)) {
405         row.data.clear();
406         retCode = CKM_API_ERROR_NOT_EXPORTABLE;
407     }
408
409     MessageBuffer response;
410     Serialization::Serialize(response, static_cast<int>(LogicCommand::GET));
411     Serialization::Serialize(response, commandId);
412     Serialization::Serialize(response, retCode);
413     Serialization::Serialize(response, static_cast<int>(row.dataType));
414     Serialization::Serialize(response, row.data);
415     return response.Pop();
416 }
417
418 RawBuffer CKMLogic::getDataList(
419     Credentials &cred,
420     int commandId,
421     DBDataType dataType)
422 {
423     int retCode = CKM_API_SUCCESS;
424     AliasVector aliasVector;
425
426     if (0 < m_userDataMap.count(cred.uid)) {
427         auto &handler = m_userDataMap[cred.uid];
428         Try {
429             if (dataType == DBDataType::CERTIFICATE || dataType == DBDataType::BINARY_DATA) {
430                 handler.database.getAliases(dataType, cred.smackLabel, aliasVector);
431             } else {
432                 handler.database.getKeyAliases(cred.smackLabel, aliasVector);
433             }
434         } Catch (CKM::Exception) {
435             LogError("Failed to get aliases");
436             retCode = CKM_API_ERROR_DB_ERROR;
437         }
438     } else {
439         retCode = CKM_API_ERROR_DB_LOCKED;
440     }
441
442     MessageBuffer response;
443     Serialization::Serialize(response, static_cast<int>(LogicCommand::GET_LIST));
444     Serialization::Serialize(response, commandId);
445     Serialization::Serialize(response, retCode);
446     Serialization::Serialize(response, static_cast<int>(dataType));
447     Serialization::Serialize(response, aliasVector);
448     return response.Pop();
449 }
450
451
452 int CKMLogic::createKeyPairHelper(
453     Credentials &cred,
454     const KeyType key_type,
455     const int additional_param,
456     const Alias &aliasPrivate,
457     const Alias &aliasPublic,
458     const PolicySerializable &policyPrivate,
459     const PolicySerializable &policyPublic)
460 {
461     if (0 >= m_userDataMap.count(cred.uid))
462         return CKM_API_ERROR_DB_LOCKED;
463
464     auto &handler = m_userDataMap[cred.uid];
465     KeyImpl prv, pub;
466     int retCode;
467     switch(key_type)
468     {
469         case KeyType::KEY_RSA_PUBLIC:
470         case KeyType::KEY_RSA_PRIVATE:
471             retCode = CryptoService::createKeyPairRSA(additional_param, prv, pub);
472             break;
473
474         case KeyType::KEY_DSA_PUBLIC:
475         case KeyType::KEY_DSA_PRIVATE:
476             retCode = CryptoService::createKeyPairDSA(additional_param, prv, pub);
477             break;
478
479         case KeyType::KEY_ECDSA_PUBLIC:
480         case KeyType::KEY_ECDSA_PRIVATE:
481             retCode = CryptoService::createKeyPairECDSA(static_cast<ElipticCurve>(additional_param), prv, pub);
482             break;
483
484         default:
485             return CKM_API_ERROR_INPUT_PARAM;
486     }
487
488     if (CKM_CRYPTO_CREATEKEY_SUCCESS != retCode)
489     {
490         LogDebug("CryptoService error with code: " << retCode);
491         return CKM_API_ERROR_SERVER_ERROR; // TODO error code
492     }
493
494     DBCrypto::Transaction transaction(&handler.database);
495     retCode = saveDataHelper(cred,
496                             toDBDataType(prv.getType()),
497                             aliasPrivate,
498                             prv.getDER(),
499                             policyPrivate);
500
501     if (CKM_API_SUCCESS != retCode)
502         return retCode;
503
504     retCode = saveDataHelper(cred,
505                             toDBDataType(pub.getType()),
506                             aliasPublic,
507                             pub.getDER(),
508                             policyPublic);
509
510     if (CKM_API_SUCCESS != retCode)
511         return retCode;
512
513     transaction.commit();
514
515     return retCode;
516 }
517
518 RawBuffer CKMLogic::createKeyPair(
519     Credentials &cred,
520     LogicCommand protocol_cmd,
521     int commandId,
522     const int additional_param,
523     const Alias &aliasPrivate,
524     const Alias &aliasPublic,
525     const PolicySerializable &policyPrivate,
526     const PolicySerializable &policyPublic)
527 {
528     int retCode = CKM_API_SUCCESS;
529
530     KeyType key_type = KeyType::KEY_NONE;
531     switch(protocol_cmd)
532     {
533         case LogicCommand::CREATE_KEY_PAIR_RSA:
534             key_type = KeyType::KEY_RSA_PUBLIC;
535             break;
536         case LogicCommand::CREATE_KEY_PAIR_DSA:
537             key_type = KeyType::KEY_DSA_PUBLIC;
538             break;
539         case LogicCommand::CREATE_KEY_PAIR_ECDSA:
540             key_type = KeyType::KEY_ECDSA_PUBLIC;
541             break;
542         default:
543             break;
544     }
545
546     try {
547         retCode = createKeyPairHelper(
548                         cred,
549                         key_type,
550                         additional_param,
551                         aliasPrivate,
552                         aliasPublic,
553                         policyPrivate,
554                         policyPublic);
555
556     } catch (DBCrypto::Exception::AliasExists &e) {
557         LogDebug("DBCrypto error: alias exists: " << e.GetMessage());
558         retCode = CKM_API_ERROR_DB_ALIAS_EXISTS;
559     } catch (DBCrypto::Exception::TransactionError &e) {
560         LogDebug("DBCrypto error: transaction error: " << e.GetMessage());
561         retCode = CKM_API_ERROR_DB_ERROR;
562     } catch (CKM::CryptoLogic::Exception::Base &e) {
563         LogDebug("CryptoLogic error: " << e.GetMessage());
564         retCode = CKM_API_ERROR_SERVER_ERROR;
565     } catch (DBCrypto::Exception::InternalError &e) {
566         LogDebug("DBCrypto internal error: " << e.GetMessage());
567         retCode = CKM_API_ERROR_DB_ERROR;
568     }
569
570     MessageBuffer response;
571     Serialization::Serialize(response, static_cast<int>(protocol_cmd));
572     Serialization::Serialize(response, commandId);
573     Serialization::Serialize(response, retCode);
574
575     return response.Pop();
576 }
577
578 RawBuffer CKMLogic::getCertificateChain(
579     Credentials &cred,
580     int commandId,
581     const RawBuffer &certificate,
582     const RawBufferVector &untrustedRawCertVector)
583 {
584     (void)cred;
585
586     CertificateImpl cert(certificate, DataFormat::FORM_DER);
587     CertificateImplVector untrustedCertVector;
588     CertificateImplVector chainVector;
589     RawBufferVector chainRawVector;
590
591     for (auto &e: untrustedRawCertVector)
592         untrustedCertVector.push_back(CertificateImpl(e, DataFormat::FORM_DER));
593
594     LogDebug("Cert is empty: " << cert.empty());
595
596     int retCode = m_certStore.verifyCertificate(cert, untrustedCertVector, chainVector);
597
598     if (retCode == CKM_API_SUCCESS) {
599         for (auto &e : chainVector)
600             chainRawVector.push_back(e.getDER());
601     }
602
603     MessageBuffer response;
604     Serialization::Serialize(response, static_cast<int>(LogicCommand::GET_CHAIN_CERT));
605     Serialization::Serialize(response, commandId);
606     Serialization::Serialize(response, retCode);
607     Serialization::Serialize(response, chainRawVector);
608     return response.Pop();
609 }
610
611 RawBuffer CKMLogic::getCertificateChain(
612     Credentials &cred,
613     int commandId,
614     const RawBuffer &certificate,
615     const AliasVector &aliasVector)
616 {
617     int retCode = CKM_API_SUCCESS;
618     RawBufferVector chainRawVector;
619     try {
620         CertificateImpl cert(certificate, DataFormat::FORM_DER);
621         CertificateImplVector untrustedCertVector;
622         CertificateImplVector chainVector;
623         DBRow row;
624
625         if (cert.empty()) {
626             retCode = CKM_API_ERROR_SERVER_ERROR;
627             goto senderror;
628         }
629
630         for (auto &i: aliasVector) {
631             retCode = getDataHelper(cred, DBDataType::CERTIFICATE, i, Password(), row);
632
633             if (retCode != CKM_API_SUCCESS)
634                 goto senderror;
635
636             untrustedCertVector.push_back(CertificateImpl(row.data, DataFormat::FORM_DER));
637         }
638
639         retCode = m_certStore.verifyCertificate(cert, untrustedCertVector, chainVector);
640
641         if (retCode != CKM_API_SUCCESS)
642             goto senderror;
643
644         for (auto &i: chainVector)
645             chainRawVector.push_back(i.getDER());
646
647     } catch (const CryptoLogic::Exception::Base &e) {
648         LogError("DBCyptorModule failed with message: " << e.GetMessage());
649         retCode = CKM_API_ERROR_SERVER_ERROR;
650     } catch (const DBCrypto::Exception::Base &e) {
651         LogError("DBCrypto failed with message: " << e.GetMessage());
652         retCode = CKM_API_ERROR_DB_ERROR;
653     } catch (...) {
654         LogError("Unknown error.");
655     }
656
657 senderror:
658     MessageBuffer response;
659     Serialization::Serialize(response, static_cast<int>(LogicCommand::GET_CHAIN_ALIAS));
660     Serialization::Serialize(response, commandId);
661     Serialization::Serialize(response, retCode);
662     Serialization::Serialize(response, chainRawVector);
663     return response.Pop();
664 }
665
666 RawBuffer CKMLogic::createSignature(
667         Credentials &cred,
668         int commandId,
669         const Alias &privateKeyAlias,
670         const Password &password,           // password for private_key
671         const RawBuffer &message,
672         const HashAlgorithm hash,
673         const RSAPaddingAlgorithm padding)
674 {
675     DBRow row;
676     CryptoService cs;
677     RawBuffer signature;
678
679     int retCode = CKM_API_SUCCESS;
680
681     try {
682         do {
683             retCode = getDataHelper(cred, DBDataType::DB_KEY_FIRST, privateKeyAlias, password, row);
684             if (CKM_API_SUCCESS != retCode) {
685                 LogError("getDataHelper return error");
686                 break;
687             }
688
689             KeyImpl keyParsed(row.data, Password());
690             if (keyParsed.empty())
691                 retCode = CKM_API_ERROR_SERVER_ERROR;
692             else
693                 retCode = cs.createSignature(keyParsed, message, hash, padding, signature);
694         } while(0);
695     } catch (const KeyProvider::Exception::Base &e) {
696         LogError("KeyProvider failed with message: " << e.GetMessage());
697         retCode = CKM_API_ERROR_SERVER_ERROR;
698     } catch (const CryptoLogic::Exception::Base &e) {
699         LogError("CryptoLogic failed with message: " << e.GetMessage());
700         retCode = CKM_API_ERROR_SERVER_ERROR;
701     } catch (const DBCrypto::Exception::Base &e) {
702         LogError("DBCrypto failed with message: " << e.GetMessage());
703         retCode = CKM_API_ERROR_DB_ERROR;
704     } catch (const CKM::Exception &e) {
705         LogError("Unknown CKM::Exception: " << e.GetMessage());
706         retCode = CKM_API_ERROR_SERVER_ERROR;
707     }
708
709     MessageBuffer response;
710     Serialization::Serialize(response, static_cast<int>(LogicCommand::CREATE_SIGNATURE));
711     Serialization::Serialize(response, commandId);
712     Serialization::Serialize(response, retCode);
713     Serialization::Serialize(response, signature);
714     return response.Pop();
715 }
716
717 RawBuffer CKMLogic::verifySignature(
718         Credentials &cred,
719         int commandId,
720         const Alias &publicKeyOrCertAlias,
721         const Password &password,           // password for public_key (optional)
722         const RawBuffer &message,
723         const RawBuffer &signature,
724         const HashAlgorithm hash,
725         const RSAPaddingAlgorithm padding)
726 {
727     int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
728
729     try {
730         do {
731             CryptoService cs;
732             DBRow row;
733             KeyImpl key;
734
735             retCode = getDataHelper(cred, DBDataType::DB_KEY_FIRST, publicKeyOrCertAlias, password, row);
736
737             if (retCode == CKM_API_SUCCESS) {
738                 key = KeyImpl(row.data);
739             } else if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
740                 retCode = getDataHelper(cred, DBDataType::CERTIFICATE, publicKeyOrCertAlias, password, row);
741                 if (retCode != CKM_API_SUCCESS)
742                     break;
743                 CertificateImpl cert(row.data, DataFormat::FORM_DER);
744                 key = cert.getKeyImpl();
745             } else {
746                 break;
747             }
748
749             if (key.empty()) {
750                 retCode = CKM_API_ERROR_SERVER_ERROR;
751                 break;
752             }
753
754             retCode = cs.verifySignature(key, message, signature, hash, padding);
755         } while(0);
756     } catch (const CryptoService::Exception::Crypto_internal &e) {
757         LogError("KeyProvider failed with message: " << e.GetMessage());
758         retCode = CKM_API_ERROR_SERVER_ERROR;
759     } catch (const CryptoService::Exception::opensslError &e) {
760         LogError("KeyProvider failed with message: " << e.GetMessage());
761         retCode = CKM_API_ERROR_SERVER_ERROR;
762     } catch (const KeyProvider::Exception::Base &e) {
763         LogError("KeyProvider failed with error: " << e.GetMessage());
764         retCode = CKM_API_ERROR_SERVER_ERROR;
765     } catch (const CryptoLogic::Exception::Base &e) {
766         LogError("CryptoLogic failed with message: " << e.GetMessage());
767         retCode = CKM_API_ERROR_SERVER_ERROR;
768     } catch (const DBCrypto::Exception::Base &e) {
769         LogError("DBCrypto failed with message: " << e.GetMessage());
770         retCode = CKM_API_ERROR_DB_ERROR;
771     } catch (const CKM::Exception &e) {
772         LogError("Unknown CKM::Exception: " << e.GetMessage());
773         retCode = CKM_API_ERROR_SERVER_ERROR;
774     }
775
776     MessageBuffer response;
777     Serialization::Serialize(response, static_cast<int>(LogicCommand::VERIFY_SIGNATURE));
778     Serialization::Serialize(response, commandId);
779     Serialization::Serialize(response, retCode);
780
781     return response.Pop();
782 }
783 } // namespace CKM
784