Merge "Added support for Event creation in worker thread" into tizen
[platform/framework/native/appfw.git] / src / security / cert / FSecCert_CertDbManager.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
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 /**
18  * @file                FSecCert_CertDbManager.cpp
19  * @brief               This file contains implementation of X509 Certificate Db Manager APIs.
20 */
21
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <error.h>
26 #include <new>
27 #include <sys/stat.h>
28 #include <assert.h>
29 #include <dirent.h>
30 #include <openssl/evp.h>
31 #include <openssl/pem.h>
32 #include <unique_ptr.h>
33 #include <pthread.h>
34 #include <FIoFile.h>
35 #include <FBaseSysLog.h>
36 #include <FBaseByteBuffer.h>
37 #include <FBaseResult.h>
38 #include <FBase_StringConverter.h>
39 #include "FSecCert_CertDbStore.h"
40 #include "FSecCert_CertFileStore.h"
41 #include "FSecCert_CertDbManager.h"
42 #include "FSecCert_Base64.h"
43 #include "FSecCert_CertService.h"
44 #include "FSecCert_CertManager.h"
45
46 using namespace Tizen::Base;
47 using namespace Tizen::Io;
48
49 namespace
50 {
51 struct ByteDeleter
52 {
53         void operator ()(byte* c)
54         {
55                 free(c);
56         }
57 };
58 }
59
60 namespace Tizen { namespace Security { namespace Cert
61 {
62 _CertDbManager* _CertDbManager::__pCertDb = null;
63
64 _CertDbManager::_CertDbManager(void)
65 {
66 }
67
68 _CertDbManager::~_CertDbManager(void)
69 {
70 }
71
72 void
73 _CertDbManager::Construct(void)
74 {
75         static _CertDbManager certDb;
76         __pCertDb = &certDb;
77 }
78
79
80 _CertDbManager*
81 _CertDbManager::GetInstance(void)
82 {
83         static pthread_once_t once_block = PTHREAD_ONCE_INIT;
84         if (__pCertDb == null)
85         {
86                 pthread_once(&once_block, Construct);
87         }
88
89         return __pCertDb;
90 }
91
92 result
93 _CertDbManager::CreateCertificateTables(void)
94 {
95         result r = E_SUCCESS;
96
97         r = __caCertDbStore.CreateCertificateTables();
98         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database.");
99
100         return E_SUCCESS;
101 }
102
103 bool
104 _CertDbManager::IsCertificateTablesCreated(void)
105 {
106         result r = E_SUCCESS;
107
108         r = __caCertDbStore.IsRootCaCertTableCreated();
109         if (r != E_SUCCESS)
110         {
111                 SetLastResult(E_SYSTEM);
112                 return false;
113         }
114
115         r = __userCertDbStore.IsUserCertTableCreated();
116         if (r != E_SUCCESS)
117         {
118                 SetLastResult(E_SYSTEM);
119                 return false;
120         }
121
122         return true;
123 }
124
125 result
126 _CertDbManager::ResetCertificateTables(void)
127 {
128         result r = E_SUCCESS;
129
130         r = __caCertDbStore.DropCertificateTables();
131         SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database.");
132
133         r = __caCertDbStore.CreateCertificateTables();
134         SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database.");
135
136         return E_SUCCESS;
137 }
138
139 result
140 _CertDbManager::RemoveCertificateTables(void)
141 {
142         result r = E_SUCCESS;
143         r = __caCertDbStore.DropCertificateTables();
144         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
145         return E_SUCCESS;
146 }
147
148 result
149 _CertDbManager::RemoveCaCertificateByType(_CaCertType certType)
150 {
151         result r = E_SUCCESS;
152         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
153         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
154
155         snprintf(condition, sizeof(condition), "certType = %d and installed = '%s'", certType, installed);
156
157         r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
158         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
159
160         return E_SUCCESS;
161 }
162
163 result
164 _CertDbManager::RemoveUserCaCertificateByCertId(int certId)
165 {
166         result r = E_SUCCESS;
167         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
168         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
169
170         snprintf(condition, sizeof(condition), "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed);
171         r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
172         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
173
174         return E_SUCCESS;
175 }
176
177 result
178 _CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
179 {
180         return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false);
181 }
182
183 result
184 _CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity)
185 {
186         result r = E_SUCCESS;
187         String tempFileName;
188         CaCertRecord certRecord = {0, };
189         _CertFileStore fileStore;
190         _CertFormat certBufFormat = _CERT_UNKNOWN;
191         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
192         int lenSubjectName = 0;
193         int lenIssuerName = 0;
194         int lenSerialNo = 0;
195         int certId = 0;
196         int derCertBufferLength = 0;
197         char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
198         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
199         char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
200         char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
201         byte* pDerCert = null;
202         byte* pSerial = null;
203         _X509TbsCert* pTbsCert = null;
204
205         r = __caCertDbStore.IsRootCaCertTableCreated();
206         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
207
208         std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
209         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
210
211         certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType);
212         std::unique_ptr< byte, ByteDeleter > pDerCertBuffer(pDerCert);
213         pDerCert = null;
214         SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer.");
215         SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format.");
216         SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length.");
217
218         r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
219         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
220
221         pTbsCert = pCert->GetTbsCertInstance();
222         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
223
224         lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
225         lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
226
227         SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
228         SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
229
230         snprintf(subjectName, sizeof(subjectName), "%s", reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
231         snprintf(issuerName, sizeof(issuerName), "%s", reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
232
233         pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo));
234         if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
235         {
236                 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
237                 lenSerialNo = 1;
238         }
239         else
240         {
241                 memcpy(serialName, pSerial, lenSerialNo);
242         }
243
244         if (checkValidity)
245         {
246                 if (pCert->IsSelfSigned())
247                 {
248                         r = pCert->VerifySignature(null, 0);
249                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data.");
250                 }
251 #ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE
252                 //Open this code - if u want to support installation of Intermediate CA Certificate with verification using this API.(ideally it should check if installing intermediate CA) (09082011)
253                 else if (pCert->IsCaCertificate())
254                 {
255                         std::unique_ptr< _CertChain > pCertChain(new (std::nothrow) _CertChain());
256                         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
257
258                         r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength);
259                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed.");
260
261                         r = pCertChain->MoveHead();
262                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed.");
263
264
265                         // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id
266                         //(there are ECC certificate installation which we support for china model. hence these comments)
267                         r = pCertChain->VerifyCertChainWithDb();
268                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain.");
269                 }
270 #endif
271
272 #ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE
273                 //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check)
274                 else
275                 {
276                         return E_UNSUPPORTED_OPERATION;
277                 }
278 #endif
279
280         }
281
282         r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName);
283         if (!IsFailed(r))
284         {
285                 return E_FILE_ALREADY_EXIST;
286         }
287
288         SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate");
289
290
291         //Get the last installed certificate id from db table
292         __caCertDbStore.GetCurrentCertId(certId);
293         //Calculate the new (std::nothrow) certificate id for installation
294         certId = certId + 1;
295         fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
296
297         memset(&certRecord, 0, sizeof(certRecord));
298         certRecord.certType = static_cast< int >(certType);
299         certRecord.certFormat = static_cast< int >(certFormat);
300
301         std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
302         SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
303
304         int len = strlen(pFileName.get());
305         snprintf(certRecord.fileName, sizeof(certRecord.fileName), "%s", pFileName.get());
306
307         certRecord.subjectNameLen = lenSubjectName;
308         memcpy(certRecord.subjectName, subjectName, lenSubjectName);
309         certRecord.issuerNameLen = lenIssuerName;
310         memcpy(certRecord.issuerName, issuerName, lenIssuerName);
311         certRecord.parentCa = certId;
312         strcpy(certRecord.installed, installed);
313         memcpy(certRecord.serialNo, serialName, lenSerialNo);
314         certRecord.serialNoLen = lenSerialNo;
315
316         r = __caCertDbStore.InsertCaCertificate(&certRecord);
317         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
318
319         fileStore.SetFilePath(tempFileName);
320
321         r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
322         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
323
324         return r;
325
326 }
327
328 result
329 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
330 {
331         result r = E_SUCCESS;
332         String tempFileName;
333         CaCertRecord certRecord = {0, };
334         CaCertRecord certRecord1 = {0, };
335         _CertFileStore fileStore;
336         _X509TbsCert* pTbsCert = null;
337         _X509TbsCert* pNewTbsCert = null;
338         int lenSubjectName = 0;
339         int lenNewSubjectName = 0;
340         int lenIssuerName = 0;
341         int lenNewIssuerName = 0;
342         int lenNewSerialNo = 0;
343         int certId = 0;
344         int subjNameB64len = 0;
345         char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
346         char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
347         char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
348         char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
349         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
350         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
351         byte* pNewSerial = null;
352
353         r = __caCertDbStore.IsRootCaCertTableCreated();
354         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
355
356         std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
357         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
358
359         r = pCert->Parse(pCurCertBuf, curCertLen);
360         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
361
362         pTbsCert = pCert->GetTbsCertInstance();
363         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
364
365         lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
366         lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
367
368         SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
369         SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
370
371         r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
372         if (!IsFailed(r)) //checkit
373         {
374                 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
375                 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
376
377                 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
378
379                 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
380                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
381
382                 snprintf(condition, sizeof(condition), "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
383                 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
384                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
385
386                 certId = certRecord.parentCa;
387
388                 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
389                 fileStore.SetFilePath(tempFileName);
390
391                 if (certFormat == _CERT_X509)
392                 {
393                         std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
394                         SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
395
396                         r = pNewCert->Parse(pNewCertBuf, newCertLen);
397                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
398
399                         pNewTbsCert = pNewCert->GetTbsCertInstance();
400                         SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
401
402                         snprintf(newSubjectName, sizeof(newSubjectName), "%s", reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
403                         snprintf(newIssuerName, sizeof(newIssuerName), "%s", reinterpret_cast< const char* >(pNewTbsCert->GetIssuerName()));
404
405                         lenNewSubjectName = strlen(newSubjectName);
406                         lenNewIssuerName = strlen(newIssuerName);
407
408                         pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
409                         if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
410                         {
411                                 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
412                                 lenNewSerialNo = 1;
413
414                         }
415                         else
416                         {
417                                 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
418                         }
419
420                         SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
421                         SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
422                 }
423                 certRecord1.certType = static_cast< int >(certType);
424                 certRecord1.certFormat = static_cast< int >(certFormat);
425
426                 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
427                 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
428
429                 int len = strlen(pFileName.get());
430                 snprintf(certRecord1.fileName, sizeof(certRecord1.fileName), "%s", pFileName.get());
431
432                 certRecord1.subjectNameLen = lenNewSubjectName;
433                 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
434                 certRecord1.issuerNameLen = lenIssuerName;
435                 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
436                 certRecord1.parentCa = certId;
437                 strcpy(certRecord1.installed, certRecord.installed);
438                 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
439                 certRecord1.serialNoLen = lenNewSerialNo;
440
441                 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
442                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
443
444                 fileStore.DeleteFile();
445
446                 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
447                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
448                 //No need to update record as only file data changed.
449                 return E_SUCCESS;
450         }
451
452         return r;
453 }
454
455 result
456 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
457 {
458         result r = E_SUCCESS;
459         _X509TbsCert* pTbsCert = null;
460         String fileName;
461         _CertFileStore fileStore;
462         int certId = 0;
463
464         //Check certType missing
465
466         r = __caCertDbStore.IsRootCaCertTableCreated();
467         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
468
469         std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
470         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
471
472         r = pCert->Parse(pCertBuf, certLen);
473         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
474
475         pTbsCert = pCert->GetTbsCertInstance();
476         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
477
478         r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
479         SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_OBJ_NOT_FOUND, "Certificate not found in db.");
480         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), r, "Propagated.");
481
482         r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
483                                                    pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
484                                                    certId, certType);
485         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
486
487
488         r = __caCertDbStore.RemoveCertificateById(certId);
489         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
490
491         //Delete File
492         fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
493         Tizen::Io::File::Remove(fileName);
494
495         return r;
496 }
497
498
499 result
500 _CertDbManager::RemoveCertificateChainByCertId(int certId)
501 {
502         result r = E_SUCCESS;
503         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
504         UserCertRecord userCertRecord = {0, };
505
506         memset(&userCertRecord, 0, sizeof(userCertRecord));
507         memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
508
509         snprintf(condition, sizeof(condition), "certId = %d", certId);
510         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
511         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
512         SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
513
514         r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
515         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
516
517         return r;
518 }
519
520
521 result
522 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
523 {
524         result r = E_SUCCESS;
525         int subjNameB64len = 0;
526         int issuerB64len = 0;
527         char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
528         char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
529         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
530         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
531         CaCertRecord caCertRecord = {0, };
532
533         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
534         SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
535
536         subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
537         memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
538
539         r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
540         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
541
542         memset(condition, 0, sizeof(condition));
543
544         if (pIssuerName != null && issuerNameSize > 0)
545         {
546                 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
547                 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
548
549                 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
550                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
551
552                 if (certType == _CERT_TYPE_NOT_BOUNDED)
553                 {
554                         snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
555                 }
556                 else
557                 {
558                         snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
559                 }
560         }
561         else
562         {
563                 if (certType == _CERT_TYPE_NOT_BOUNDED)
564                 {
565                         snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
566                 }
567                 else
568                 {
569                         snprintf(condition, sizeof(condition), "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
570                 }
571         }
572
573         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
574         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
575
576         certId = caCertRecord.certId;
577
578         return E_SUCCESS;
579 }
580
581 result
582 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
583 {
584         result r = E_SUCCESS;
585         int subjNameB64len = 0;
586         int issuerB64len = 0;
587         char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
588         char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
589         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
590         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
591         UserCertRecord userCertRecord = {0, };
592
593         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
594         SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
595
596         subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
597         memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
598
599         r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
600         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
601
602         memset(condition, 0, sizeof(condition));
603
604         if (pIssuerName != null && issuerNameSize > 0)
605         {
606                 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
607                 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
608
609                 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
610                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
611
612                 snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
613         }
614         else
615         {
616                 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
617         }
618
619         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
620         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
621
622         certId = userCertRecord.certId;
623
624         return E_SUCCESS;
625 }
626
627 result
628 _CertDbManager::RemoveAllUserCertificate(void)
629 {
630         __userCertDbStore.DeleteUserCertFiles();
631
632         return E_SUCCESS;
633 }
634
635 result
636 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
637 {
638         result r = E_SUCCESS;
639         CaCertRecord certRecord = {0, };
640         int recCount = 0;
641         int caCertId = 0;
642         int caParentCa = 0;
643         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
644         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
645         bool devCert = true;
646
647         SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
648         SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
649
650         memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
651
652         snprintf(condition, sizeof(condition), "parentCa = %d and installed = '%s'", devParentCA, installed);
653
654         //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
655         //delete only device certificate and return. We cannot disturb another chain.
656         __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
657         //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
658         if (recCount > 1)
659         {
660                 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
661                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
662
663                 return E_SUCCESS;
664         }
665         //Now there is not two device certificate with same intermidiate CA,
666         //so go ahead to intermidiate CA and delete device certificate.
667         caParentCa = devParentCA;
668         caCertId = devCertId;
669         do
670         {
671                 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
672                 {
673                         if (devCert)
674                         {
675                                 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
676                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
677
678                                 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
679                                 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
680                                 break; // break here next certificate has dependency
681                         }
682                         else
683                         {
684                                 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
685                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
686
687                                 break; // break here next certificate has dependency
688                         }
689                 }
690                 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
691                 {
692                         if (devCert) //If it is device certificate
693                         {
694                                 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
695                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
696
697                                 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
698                                 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
699                         }
700                         else //If it is CA certificate and there is no dependency
701                         {
702                                 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
703                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
704
705                                 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
706                         }
707                         caCertId = caParentCa; // Now look for next certificate in chain
708                         memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
709                         snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", devParentCA, installed);
710                         memset(&certRecord, 0, sizeof(certRecord));
711                         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
712                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
713                         SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
714
715                         caParentCa = certRecord.parentCa;
716                 }
717         }
718         while (caCertId != caParentCa);
719
720         return E_SUCCESS;
721 }
722
723 result
724 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
725 {
726         result r = E_SUCCESS;
727         CaCertRecord certRecord = {0, };
728         _CertificateListInfo* pHoldList = null;
729         _CertFileStore fileStore;
730         int certCount = 0;
731         int certLength = 0;
732         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
733         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
734
735         snprintf(condition, sizeof(condition), "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
736
737         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
738         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
739         SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
740
741         std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
742         SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
743
744         memset(pCertList.get(), 0, sizeof(*pCertList.get()));
745         pCertList->pNext = null;
746         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
747         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
748
749         r = fileStore.ReadFromFile(pCertList->certificate, certLength);
750         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
751
752         pCertList->length = certLength;
753         pCertList->certFileId = certRecord.certId;
754         pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
755         pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
756         certCount++;
757
758         pHoldList = pCertList.release();
759         *ppCertList = pHoldList;
760
761         while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
762         {
763                 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
764                 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
765
766                 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
767
768                 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
769                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
770
771                 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
772                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
773
774                 pCertList->pNext = null;
775                 pCertList->length = certLength;
776                 pCertList->certFileId = certRecord.certId;
777                 pCertList->format = (_CertFormat) certRecord.certFormat;
778                 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
779
780                 pHoldList->pNext = pCertList.release();
781                 pHoldList = pHoldList->pNext;
782
783                 certCount++;
784         }
785
786         count = certCount;
787
788
789         return r;
790 }
791
792 result
793 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
794 {
795         result r = E_SUCCESS;
796         UserCertRecord certRecord = {0, };
797         _CertificateListInfo* pHoldList = null;
798         _CertFileStore fileStore;
799         int certCount = 0;
800         int certLength = 0;
801         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
802         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
803
804         *ppCertList = null;
805
806         snprintf(condition, sizeof(condition), "certFormat = %d and installed = '%s'", certFormat, installed);
807
808         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
809         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
810         SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
811
812         std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
813         SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
814
815         memset(pCertList.get(), 0, sizeof(*pCertList.get()));
816         pCertList->pNext = null;
817
818         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
819         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
820
821         r = fileStore.ReadFromFile(pCertList->certificate, certLength);
822         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
823
824         pCertList->length = certLength;
825         pCertList->certFileId = certRecord.certId;
826         pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
827         pCertList->certType = _CERT_TYPE_USER_CERT;
828         certCount++;
829
830         pHoldList = pCertList.release();
831         *ppCertList = pHoldList;
832
833         while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
834         {
835                 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
836                 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
837
838                 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
839
840                 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
841                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
842
843                 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
844                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
845
846                 pCertList->pNext = null;
847                 pCertList->length = certLength;
848                 pCertList->certFileId = certRecord.certId;
849                 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
850                 pCertList->certType = _CERT_TYPE_USER_CERT;
851
852                 pHoldList->pNext = pCertList.release();
853                 pHoldList = pHoldList->pNext;
854
855                 certCount++;
856         }
857
858         count = certCount;
859
860         return E_SUCCESS;
861 }
862
863 result
864 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
865 {
866         result r = E_SUCCESS;
867         CaCertRecord certRecord = {0, };
868         _CertFileStore fileStore;
869         int certLength = 0;
870         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
871         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
872
873         *ppCertList = null;
874         snprintf(condition, sizeof(condition), "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
875
876         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
877         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
878
879         std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
880         SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
881
882         memset(pCertList.get(), 0, sizeof(*pCertList.get()));
883
884         pCertList->pNext = null;
885         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
886         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
887
888         r = fileStore.ReadFromFile(pCertList->certificate, certLength);
889         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
890
891         pCertList->length = certLength;
892         pCertList->certFileId = certRecord.certId;
893         pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
894         pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
895
896         *ppCertList = pCertList.release();
897
898         return r;
899 }
900
901 result
902 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
903 {
904         result r = E_SUCCESS;
905         _CertFileStore fileStore;
906         UserCertRecord certRecord = {0, };
907         int priKeyLen = 0;
908         int certLength = 0;
909         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
910         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
911
912         *ppCertList = null;
913
914         SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
915         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
916
917         snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installed);
918         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
919         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
920
921         std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
922         SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
923
924         memset(pCertList.get(), 0, sizeof(*pCertList.get()));
925
926         pCertList->pNext = null;
927
928         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
929         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
930
931         r = fileStore.ReadFromFile(pCertList->certificate, certLength);
932         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
933
934         pCertList->length = certLength;
935         pCertList->certFileId = certRecord.certId;
936         pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
937         pCertList->certType = _CERT_TYPE_USER_CERT;
938
939         std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
940         SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
941
942         std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
943         SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
944
945         memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
946
947         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
948         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
949
950         r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
951         if (!IsFailed(r) && priKeyLen != 0)
952         {
953                 byte* pPrivateTempKey = null;
954                 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
955
956                 pPrivateKey.reset(null);
957
958                 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
959                 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
960
961                 std::unique_ptr< byte[] > pPrivateKeyAuto(pPrivateTempKey);
962
963                 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
964         }
965         pCertList->priKeyLen = priKeyLen;
966
967         *ppCertList = pCertList.release();
968
969         return r;
970 }
971
972 result
973 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
974 {
975         result r = E_SUCCESS;
976         CaCertRecord certRecord = {0, };
977         _CertFileStore fileStore;
978         String filePath;
979         int issuerNameB64len = 0;
980         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
981         char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
982         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
983
984         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
985         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
986         SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
987
988         issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
989         SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
990
991         memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
992
993         r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
994         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
995
996         snprintf(condition, sizeof(condition), "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
997
998         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
999         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1000
1001         filePath = reinterpret_cast< char* >(certRecord.fileName);
1002
1003         fileStore.SetFilePath(filePath);
1004
1005         *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
1006         SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1007
1008         r = fileStore.ReadFromFile(*ppCert, certLen);
1009         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1010
1011         certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1012
1013         return r;
1014 }
1015
1016 result
1017 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1018 {
1019         result r = E_SUCCESS;
1020         String filePath;
1021         CaCertRecord certRecord = {0, };
1022         _CertFileStore fileStore;
1023         int issuerNameB64len = 0;
1024         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1025         char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1026         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1027
1028         SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1029         SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1030         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1031         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1032         SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1033
1034         issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1035         SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1036
1037         memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1038
1039         r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1040         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1041
1042         snprintf(condition, sizeof(condition), "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1043         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1044         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1045
1046         if (certRecord.certId == 0)
1047         {
1048                 return E_SUCCESS;
1049         }
1050
1051         filePath = static_cast< char* >(certRecord.fileName);
1052         fileStore.SetFilePath(filePath);
1053
1054         std::unique_ptr< byte[] > pCert(new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1055         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1056
1057         r = fileStore.ReadFromFile(pCert.get(), certLen);
1058         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1059
1060         certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1061
1062         *ppCert = pCert.release();
1063
1064         return r;
1065 }
1066
1067 result
1068 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1069 {
1070         result r = E_SUCCESS;
1071         CaCertRecord certRecord = {0, };
1072         _CertFileStore fileStore;
1073         int subjectNameB64len = 0;
1074         int issuerNameB64len = 0;
1075         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1076         char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1077         char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1078         char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1079
1080         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1081         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1082         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1083         SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1084
1085         issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1086         SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1087
1088         memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1089
1090         r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1091         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1092
1093         subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1094         SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1095
1096         memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1097         r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1098         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1099
1100         snprintf(condition, sizeof(condition), "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1101         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1102         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1103
1104         *pCertType = static_cast< _CaCertType >(certRecord.certType);  //Get the type of certificate
1105         return E_SUCCESS;
1106 }
1107
1108 result
1109 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1110 {
1111         result r = E_SUCCESS;
1112         _CertFileStore fileStore;
1113         String fileName;
1114
1115         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1116
1117         if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1118         {
1119                 String keyfileName;
1120
1121                 r = __userCertDbStore.RemoveCertificateById(certId);
1122                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1123
1124                 //Remove certificate file
1125                 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1126                 r = Tizen::Io::File::Remove(fileName);
1127                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1128
1129                 //Remove private key file
1130                 //Don't check return type here as it is not necessary that private key is present.
1131                 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1132                 r = Tizen::Io::File::Remove(keyfileName);
1133         }
1134         else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1135         {
1136                 r = __caCertDbStore.RemoveCertificateById(certId);
1137                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1138
1139                 //Remove certificate file
1140                 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1141                 r = Tizen::Io::File::Remove(fileName);
1142                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1143         }
1144         return E_SUCCESS;
1145 }
1146
1147 result
1148 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1149 {
1150         result r = E_SUCCESS;
1151         String fileName(reinterpret_cast< char* >(pFilePath));
1152         FileAttributes attr;
1153         File file;
1154         long fileSize = 0;
1155         int readCnt = 0;
1156         int certLen = 0;
1157         int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1158         int resValue = 0;
1159
1160         SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1161         SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1162         SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1163
1164         r = File::GetAttributes(fileName, attr);
1165         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1166
1167         fileSize = attr.GetFileSize();
1168         SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1169         SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1170
1171         // Open file
1172         r = file.Construct(fileName, L"r");
1173         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1174
1175         std::unique_ptr< byte[] > pCertBuf(new (std::nothrow) byte[fileSize + 1]);
1176         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1177
1178         memset(pCertBuf.get(), 0, fileSize + 1);
1179         readCnt = file.Read(pCertBuf.get(), fileSize);
1180         r = GetLastResult();
1181         SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1182
1183         certLen = readCnt;
1184         std::unique_ptr< byte[] > pOutBuf(new (std::nothrow) byte[outLen]);
1185         SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1186
1187         memset(pOutBuf.get(), 0, outLen);
1188         //As per OpenSSL APIs, it takes input as unsigned data types
1189         resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1190         SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1191
1192         memcpy(pBuf, pOutBuf.get(), outLen);
1193         *pLen = outLen;
1194
1195         return r;
1196 }
1197
1198 //User Certificate APIs
1199
1200 result
1201 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1202 {
1203         result r = E_SUCCESS;
1204         _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1205         int curCACertId = 0;
1206         int lastCACertId = 0;
1207         int curDevCertId = 0;
1208         bool updateUserParentCa = false;
1209
1210         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1211         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1212
1213         //Check for CA certificate table creation
1214         r = __caCertDbStore.IsRootCaCertTableCreated();
1215         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1216
1217
1218         //Check if the chain is valid or not
1219         r = pCertChain->Verify();
1220         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1221
1222         r = pCertChain->MoveHead();
1223         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1224
1225         if (certFormat == _CERT_X509)
1226         {
1227                 _X509Certificate* pCurCert = null;
1228                 _X509Certificate* pUserCert = null;
1229                 _X509TbsCert* pTbsCert = null;
1230                 byte* pX509Buff = null;
1231                 int x509BuffSize = 0;
1232
1233                 pUserCert = pCertChain->GetCurrentCertificate();
1234                 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1235
1236                 pTbsCert = pUserCert->GetTbsCertInstance();
1237                 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1238
1239                 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1240                 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1241
1242                 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1243                 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed insert user certificate chain.", GetErrorMessage(r));
1244
1245                 updateUserParentCa = true;
1246
1247                 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1248                                                                  pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1249                                                                  curDevCertId);
1250                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1251
1252                 //Insert certificate chain in CA certificate store
1253                 while (pCertChain->MoveNext() == E_SUCCESS)
1254                 {
1255
1256                         pCurCert = pCertChain->GetCurrentCertificate();
1257                         SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1258
1259                         if (!pCurCert->IsSelfSigned())
1260                         {
1261                                 certType = _CERT_TYPE_INTERMIDIATE_CA;
1262                         }
1263                         else
1264                         {
1265                                 //This parameter need to pass from certificate manager about its type
1266                                 certType = _CERT_TYPE_ROOT_CA;
1267                         }
1268
1269                         pTbsCert = pCurCert->GetTbsCertInstance();
1270                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1271
1272                         r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1273                         if (r != E_SUCCESS)
1274                         {
1275                                 SysTryReturn(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, r, "[%s] Failed to check duplicate.", GetErrorMessage(r));
1276
1277                                 pX509Buff = null;
1278                                 x509BuffSize = 0;
1279
1280                                 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1281                                 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1282
1283                                 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1284                                 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1285                         }
1286
1287                         // CA certificate already present or properly installed in CA certificate store,
1288                         // get the certificate id of certificate
1289                         r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1290                                                                    pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1291                                                                    curCACertId, certType);
1292                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1293
1294                         if (updateUserParentCa)
1295                         {
1296                                 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1297                                 updateUserParentCa = false;
1298                                 lastCACertId = curCACertId;
1299                         }
1300                         else
1301                         {
1302                                 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1303                                 lastCACertId = curCACertId;
1304                         }
1305
1306                         //If it is root certificate then its parent is itself
1307                         if (pCurCert->IsSelfSigned())
1308                         {
1309                                 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1310                         }
1311
1312                 } //end of while
1313
1314                 if (updateUserParentCa)
1315                 {
1316                         r = pCertChain->MoveHead();
1317                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1318
1319                         pCurCert = pCertChain->GetCurrentCertificate();
1320                         SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1321
1322                         pTbsCert = pCurCert->GetTbsCertInstance();
1323                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1324
1325                         r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1326                                                                    null, 0, curCACertId);
1327                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1328
1329                         __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1330                         updateUserParentCa = false;
1331                         lastCACertId = curCACertId;
1332                 }
1333                 else if (!pCurCert->IsSelfSigned())
1334                 {
1335                         pTbsCert = pCurCert->GetTbsCertInstance();
1336                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1337
1338                         r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1339                                                                    null, 0, curCACertId);
1340                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1341
1342                         __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1343                         lastCACertId = curCACertId;
1344                 }
1345         }
1346
1347         return r;
1348 }
1349
1350 result
1351 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1352 {
1353         result r = E_SUCCESS;
1354         _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1355         int prvKeyLen = 0;
1356         int curCACertId = 0;
1357         int lastCACertId = 0;
1358         int curDevCertId = 0;
1359
1360         bool updateUserParentCa = false;
1361         byte* pPrvKey = null;
1362         std::unique_ptr< byte[] > pPrvKeyBuffer;
1363
1364         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1365         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1366
1367         r = __userCertDbStore.IsUserCertTableCreated();
1368         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1369
1370         //Check for CA certificate table creation
1371         r = __caCertDbStore.IsRootCaCertTableCreated();
1372         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1373
1374         //Check if the chain is valid or not
1375         r = pCertChain->Verify();
1376         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1377
1378         r = pCertChain->MoveHead();
1379         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1380
1381         if (certFormat == _CERT_X509)
1382         {
1383                 _X509Certificate* pCurCert = null;
1384                 _X509Certificate* pUserCert = null;
1385                 _X509TbsCert* pTbsCert = null;
1386                 byte* pX509Buff = null;
1387                 int x509BuffSize = 0;
1388
1389                 pUserCert = pCertChain->GetCurrentCertificate();
1390                 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1391
1392                 pTbsCert = pUserCert->GetTbsCertInstance();
1393                 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1394
1395                 byte* pSubjectName = pTbsCert->GetSubjectName();
1396                 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1397
1398                 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1399
1400                 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1401                 if (r == E_DATA_NOT_FOUND)
1402                 {
1403                         if (pPrivateKeyInfo != null)
1404                         {
1405                                 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1406                                 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1407
1408                                 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1409                                 pPrvKey = null;
1410
1411                         }
1412
1413                         pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1414                         SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1415
1416                         r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1417                         if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1418                         {
1419                                 return r;
1420                         }
1421                         else
1422                         {
1423                                 updateUserParentCa = true;
1424
1425                                 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1426                                                                                  pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1427                                                                                  curDevCertId);
1428                                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1429
1430                                 if (pPrvKeyBuffer != null)
1431                                 {
1432                                         _CertFileStore fileStore;
1433                                         String privateKeyFile;
1434
1435                                         fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1436                                         fileStore.SetFilePath(privateKeyFile);
1437
1438
1439                                         r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1440                                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1441
1442                                 }
1443                         }
1444                 }
1445                 else
1446                 {
1447                         return r;
1448                 }
1449
1450                 if (pUserCert->IsSelfSigned())
1451                 {
1452                         __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
1453                         return r;
1454                 }
1455
1456                 //Insert certificate chain in CA certificate store
1457                 while (pCertChain->MoveNext() == E_SUCCESS)
1458                 {
1459                         pCurCert = pCertChain->GetCurrentCertificate();
1460                         SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1461
1462                         if (!pCurCert->IsSelfSigned())
1463                         {
1464                                 certType = _CERT_TYPE_INTERMIDIATE_CA;
1465                         }
1466                         else
1467                         {
1468                                 //This parameter need to pass from certificate manager about its type
1469                                 certType = _CERT_TYPE_ROOT_CA;
1470                         }
1471
1472                         pTbsCert = pCurCert->GetTbsCertInstance();
1473                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1474
1475                         r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1476                         if (r != E_SUCCESS)
1477                         {
1478                                 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate.");
1479
1480                                 pX509Buff = null;
1481                                 x509BuffSize = 0;
1482
1483                                 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1484                                 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1485
1486                                 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1487                                 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1488
1489                         }
1490                         // CA certificate already present or properly install in CA certificate store,
1491                         // get the certificate id of certificate
1492
1493                         r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1494                                                                    pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1495                                                                    curCACertId, certType);
1496                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1497
1498                         if (updateUserParentCa)
1499                         {
1500                                 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1501                                 updateUserParentCa = false;
1502                                 lastCACertId = curCACertId;
1503                         }
1504                         else
1505                         {
1506                                 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1507                                 lastCACertId = curCACertId;
1508                         }
1509
1510                         //If it is root certificate then its parent is itself
1511                         if (pCurCert->IsSelfSigned())
1512                         {
1513                                 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1514                         }
1515                 }
1516
1517                 if (updateUserParentCa)
1518                 {
1519                         r = pCertChain->MoveHead();
1520                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1521
1522                         pCurCert = pCertChain->GetCurrentCertificate();
1523                         SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1524
1525                         pTbsCert = pCurCert->GetTbsCertInstance();
1526                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1527
1528                         r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1529                                                                    null, 0, curCACertId);
1530                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1531
1532                         __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1533                         updateUserParentCa = false;
1534                         lastCACertId = curCACertId;
1535                 }
1536                 else if (!pCurCert->IsSelfSigned())
1537                 {
1538                         pTbsCert = pCurCert->GetTbsCertInstance();
1539                         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1540
1541                         r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1542                                                                    null, 0, curCACertId);
1543                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1544
1545                         __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1546                         lastCACertId = curCACertId;
1547                 }
1548         }
1549
1550         return r;
1551 }
1552
1553 result
1554 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1555 {
1556         result r = E_SUCCESS;
1557         _X509TbsCert* pTbsCert = null;
1558         _CertFileStore fileStore;
1559         UserCertRecord certRecord = {0, };
1560         String privateKeyFile;
1561         String tempFileName;
1562         int lenSubjectName = 0;
1563         int lenIssuerName = 0;
1564         int lenSerialNo = 0;
1565         int certId = 0;
1566         int keyIdB64Length = 0;
1567         char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1568         char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1569         char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1570         char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1571         byte* pKeyId = null;
1572         byte* pSerial = null;
1573
1574         //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1575         SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1576         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1577         SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1578
1579         r = __userCertDbStore.IsUserCertTableCreated();
1580         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1581
1582         std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
1583         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1584
1585         r = pCert->Parse(pCertBuffer, certLength);
1586         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1587
1588         pTbsCert = pCert->GetTbsCertInstance();
1589         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1590
1591         lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1592         lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1593
1594         SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1595         SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1596
1597         snprintf(subjectNameBuffer, sizeof(subjectNameBuffer), "%s", reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1598         snprintf(szIssuerName, sizeof(szIssuerName), "%s", reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1599
1600         pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1601         if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1602         {
1603                 if (pSerial != null)
1604                 {
1605                         memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1606                         lenSerialNo = 1;
1607                 }
1608         }
1609         else
1610         {
1611                 memcpy(serialName, pSerial, lenSerialNo);
1612         }
1613
1614         //Get Device ID
1615         r = pCert->GetKeyIdN(&pKeyId);
1616         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1617
1618         std::unique_ptr< byte[] > pKeyIdBuffer(pKeyId);
1619
1620         keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1621         SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1622
1623         std::unique_ptr< char[] > pId64(new (std::nothrow) char[keyIdB64Length]);
1624         SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1625
1626         memset(pId64.get(), 0, keyIdB64Length);
1627         r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1628         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1629
1630         r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1631         SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1632         SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate");
1633
1634         //Get the last installed certificate id from db table
1635         __userCertDbStore.GetCurrentCertId(certId);
1636
1637         //Calculate the new certificate id for installation
1638         certId = certId + 1;
1639
1640         if (pPrivateKey != null)
1641         {
1642                 //Get file name for private key and store private key into file.
1643                 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1644         }
1645         else
1646         {
1647                 privateKeyLen = 0;
1648         }
1649
1650         //Get file name for certificate and write device certificate to file
1651         fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1652
1653         //Insert Record into Database
1654         //It is generated automatically by sequence
1655         memset(&certRecord, 0, sizeof(certRecord));
1656
1657         memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1658         certRecord.certFormat = static_cast< int >(certFormat);
1659
1660         std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
1661         SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1662
1663         int len = strlen(pFileName.get());
1664         snprintf(certRecord.fileName, sizeof(certRecord.fileName), "%s", pFileName.get());
1665
1666         certRecord.subjectNameLen = lenSubjectName;
1667
1668         memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1669         certRecord.issuerNameLen = lenIssuerName;
1670         memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1671
1672         std::unique_ptr< char[] > pPriKeyFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile));
1673         SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1674
1675         len = strlen(pPriKeyFileName.get());
1676         snprintf(certRecord.prvKeyPath, sizeof(certRecord.prvKeyPath), "%s", pPriKeyFileName.get());
1677         certRecord.prvKeyLen = privateKeyLen;
1678         certRecord.parentCa = certId;
1679         strcpy(certRecord.installed, installedRecord);
1680
1681         memcpy(certRecord.serialNo, serialName, lenSerialNo);
1682
1683         certRecord.serialNoLen = lenSerialNo;
1684
1685         r = __userCertDbStore.InsertUserCertificate(&certRecord);
1686         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1687
1688         fileStore.SetFilePath(tempFileName);
1689
1690         r = fileStore.WriteToFile(pCertBuffer, certLength);
1691         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1692
1693         if (pPrivateKey != null)
1694         {
1695                 fileStore.SetFilePath(privateKeyFile);
1696
1697                 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1698                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1699         }
1700
1701         return r;
1702 }
1703
1704 result
1705 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1706 {
1707         result r = E_SUCCESS;
1708         CaCertRecord certRecord = {0, };
1709         UserCertRecord userCertRecord = {0, };
1710         _CertificateListInfo* pHoldList = null;
1711         BIO* pBio = null;
1712         X509* pCert = null;
1713         EVP_PKEY* pKey = null;
1714         int certCount = 0;
1715         int recordCount = 0;
1716         int subjectNameBase64Len = 0;
1717         int count = 0;
1718         int readLength = 0;
1719         int priKeyLen = 0;
1720         int subNameLen = 0;
1721         int curCertId = 0;
1722         int certificateBase64Len = 0;
1723         char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1724         char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1725         byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1726         byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1727         byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1728         bool isIssuerNameInList = false;
1729
1730         subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1731         memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1732         r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1733         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1734
1735         if ((pSubjectName != null) && (subjectNameLen > 0))
1736         {
1737                 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1738                 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1739                 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1740                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1741                 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1742         }
1743         else
1744         {
1745                 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1746                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1747                 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1748                 snprintf(condition, sizeof(condition), "installed = '%s'", installedRecord);
1749         }
1750
1751         memset(&userCertRecord, 0, sizeof(userCertRecord));
1752         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1753         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1754
1755         std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
1756         SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1757         do
1758         {
1759                 std::unique_ptr< _CertFileStore > pFileStore(new (std::nothrow) _CertFileStore());
1760                 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1761
1762                 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
1763                 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1764
1765                 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1766
1767                 pCertList->pNext = null;
1768
1769                 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1770                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1771
1772                 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1773                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1774                 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1775
1776                 if (encodingType == _CERT_ENC_TYPE_PEM)
1777                 {
1778                         const byte* pCertBuffer = pCertList->certificate;
1779
1780                         pBio = BIO_new(BIO_s_mem());
1781                         SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1782
1783                         pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1784                         SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1785
1786                         readLength = PEM_write_bio_X509(pBio, pCert);
1787                         SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1788
1789                         pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1790
1791                         readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1792                         SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1793
1794                         pCertList->length = readLength;
1795
1796                         BIO_free(pBio);
1797                         pBio = null;
1798
1799                         X509_free(pCert);
1800                         pCert = null;
1801
1802                 }
1803                 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1804                 {
1805                         int certLen = _Base64::GetEncodedSize(pCertList->length);
1806                         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_SYSTEM, "Certificate length is invalid.");
1807                         memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1808                         r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1809                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1810
1811                         pCertList->length = certLen;
1812                 }
1813
1814                 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1815                 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1816
1817                 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1818                 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1819                 pCertList->certFileId = userCertRecord.certId;
1820
1821                 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1822                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1823
1824                 priKeyLen = 0;
1825
1826                 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1827                 if (!IsFailed(r) && priKeyLen != 0)
1828                 {
1829                         byte* pPrivateTempKey = null;
1830                         pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1831                         pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1832
1833                         pPrivateKey.reset(null);
1834                         priKeyLen = 0;
1835
1836                         pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1837                         SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1838
1839                         pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
1840
1841                         if (encodingType == _CERT_ENC_TYPE_PEM)
1842                         {
1843                                 const byte* pKeyBuffer = pPrivateKey.get();
1844                                 pBio = BIO_new(BIO_s_mem());
1845                                 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1846
1847                                 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1848                                 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1849
1850                                 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1851                                 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1852
1853                                 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1854
1855                                 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1856
1857                                 pCertList->priKeyLen = readLength;
1858
1859                                 BIO_free(pBio);
1860                                 pBio = null;
1861
1862                                 X509_free(pCert);
1863                                 pCert = null;
1864                         }
1865                         else if (encodingType == _CERT_ENC_TYPE_BASE64)
1866                         {
1867                                 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1868                                 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1869
1870                                 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1871                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1872                         }
1873                         else
1874                         {
1875                                 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1876                                 pCertList->priKeyLen = priKeyLen;
1877                         }
1878                 }
1879
1880                 pPrivateKey.reset(null);
1881
1882                 pHoldList = pCertList.release();
1883                 *ppCertListInfoTypes = pHoldList;
1884
1885                 certCount++;
1886
1887                 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1888                 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1889                 subNameLen = userCertRecord.issuerNameLen;
1890
1891                 do
1892                 {
1893                         subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1894                         memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1895                         r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1896                         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1897                         snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1898
1899                         if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1900                         {
1901                                 isIssuerNameInList = true;
1902                         }
1903
1904                         memset(&certRecord, 0, sizeof(certRecord));
1905                         r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1906                         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1907
1908                         if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1909                         {
1910                                 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo());
1911                                 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1912
1913                                 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1914                                 pCertList->pNext = null;
1915
1916                                 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1917                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1918
1919                                 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1920                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1921                                 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1922
1923                                 if (encodingType == _CERT_ENC_TYPE_PEM)
1924                                 {
1925                                         const byte* pCertBuffer = pCertList->certificate;
1926
1927                                         pBio = BIO_new(BIO_s_mem());
1928                                         SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1929
1930                                         pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1931                                         SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1932
1933                                         readLength = PEM_write_bio_X509(pBio, pCert);
1934                                         SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1935
1936                                         pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1937
1938                                         readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1939                                         SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1940
1941                                         pCertList->length = readLength;
1942
1943                                         BIO_free(pBio);
1944                                         pBio = null;
1945
1946                                         X509_free(pCert);
1947                                         pCert = null;
1948                                 }
1949                                 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1950                                 {
1951                                         int certLen = _Base64::GetEncodedSize(pCertList->length);
1952                                         memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1953                                         r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1954                                         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1955                                         pCertList->length = certLen;
1956                                 }
1957                                 pCertList->format = (_CertFormat) certRecord.certFormat;
1958                                 pCertList->certType = (_CaCertType) certRecord.certType;
1959                                 pCertList->certFileId = certRecord.certId;
1960
1961                                 pHoldList->pNext = pCertList.release();
1962                                 pHoldList = pHoldList->pNext;
1963
1964                                 certCount++;
1965
1966                                 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1967                                 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1968                                 subNameLen = certRecord.issuerNameLen;
1969                         }
1970
1971                 }
1972                 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1973
1974                 if (!isIssuerNameInList)
1975                 {
1976                         if (*ppCertListInfoTypes != null)
1977                         {
1978                                 _CertService::FreeCertList(*ppCertListInfoTypes);
1979                                 *ppCertListInfoTypes = null;
1980                         }
1981
1982                         memset(condition, 0, sizeof(condition));
1983                         snprintf(condition, sizeof(condition), "installed = '%s'", installedRecord);
1984
1985                         count++;
1986
1987                         memset(&userCertRecord, 0, sizeof(userCertRecord));
1988                         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1989                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1990
1991                         curCertId = userCertRecord.certId;
1992
1993                         for (readLength = 0; readLength < count; readLength++)
1994                         {
1995
1996                                 memset(&userCertRecord, 0, sizeof(userCertRecord));
1997                                 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1998                                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1999                                 curCertId = userCertRecord.certId;
2000                         }
2001                 }
2002
2003         }
2004         while (isIssuerNameInList != true);
2005
2006 CATCH:
2007         if (pBio != null)
2008         {
2009                 BIO_free(pBio);
2010         }
2011         if (pCert != null)
2012         {
2013                 X509_free(pCert);
2014         }
2015         if (pKey != null)
2016         {
2017                 EVP_PKEY_free(pKey);
2018         }
2019
2020         return r;
2021 }
2022
2023 result
2024 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2025 {
2026         result r = E_SUCCESS;
2027         UserCertRecord userCertRecord = {0, };
2028         CaCertRecord caCertRecord = {0, };
2029         int subjNameB64len = 0;
2030         int parentCa = 0;
2031         char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2032         char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2033         char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2034
2035         subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2036         memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2037         r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2038         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2039         snprintf(conditonRecord, sizeof(conditonRecord), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2040
2041         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2042         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2043
2044         if (pPrivateKeyInfo != null)
2045         {
2046                 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2047         }
2048
2049         r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2050         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2051
2052         parentCa = userCertRecord.parentCa;
2053
2054         do
2055         {
2056                 memset(&caCertRecord, 0, sizeof(caCertRecord));
2057                 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2058                 snprintf(conditonRecord, sizeof(conditonRecord), "certId = %d and installed = '%s'", parentCa, installedRecord);
2059
2060                 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2061                 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2062
2063                 parentCa = caCertRecord.parentCa;
2064                 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2065                 {
2066                         r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2067                         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2068                 }
2069
2070         }
2071         while (caCertRecord.certId != caCertRecord.parentCa);
2072
2073         return E_SUCCESS;
2074 }
2075
2076 result
2077 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2078 {
2079         result r = E_SUCCESS;
2080         UserCertRecord userCertRecord = {0, };
2081         char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2082         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2083
2084         snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installedRecord);
2085
2086         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2087         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2088
2089         *pSubjectLength = userCertRecord.subjectNameLen;
2090         memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2091         *pIssuerLength = userCertRecord.issuerNameLen;
2092         memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2093
2094         return E_SUCCESS;
2095
2096 }
2097
2098 result
2099 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2100 {
2101         result r = E_SUCCESS;
2102         char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2103         char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2104         int priKeyLen = 0;
2105         int readCount = 0;
2106         int certBufferLen = 0;
2107         int keyBufferLen = 0;
2108         int certificateBase64Len = 0;
2109         const byte* pCertBuffer = null;
2110         const byte* pKeyBuffer = null;
2111         byte* pPrivateTempKey = null;
2112         UserCertRecord certRecord = {0, };
2113         _CertFileStore fileStore;
2114         std::unique_ptr< _CertPrivateKeyInfo > pPriKey;
2115         BIO* pBio = null;
2116         X509* pCert = null;
2117         EVP_PKEY* pKey = null;
2118
2119         *ppUserCertInfo = null;
2120
2121         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2122         snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installedRecord);
2123
2124         r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2125         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2126
2127         std::unique_ptr< _CertInfo > pCertInfo(new (std::nothrow) _CertInfo);
2128         SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2129
2130         memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2131
2132         r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2133         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2134
2135         r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2136         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2137         certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2138
2139         if (encodingType == _CERT_ENC_TYPE_PEM)
2140         {
2141                 pBio = BIO_new(BIO_s_mem());
2142                 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2143
2144                 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2145                 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2146
2147                 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2148                 certBufferLen = pCertInfo->certLength;
2149
2150                 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2151                 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2152
2153                 readCount = PEM_write_bio_X509(pBio, pCert);
2154                 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2155
2156                 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2157                 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2158                 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2159
2160                 pCertInfo->certLength = readCount;
2161         }
2162         else if (encodingType == _CERT_ENC_TYPE_BASE64)
2163         {
2164                 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2165                 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2166                 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2167                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2168                 pCertInfo->certLength = certLen;
2169         }
2170         pCertInfo->certId = certRecord.certId;
2171         pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2172         pCertInfo->certType = _CERT_TYPE_USER_CERT;
2173
2174         if (certRecord.prvKeyLen > 0)
2175         {
2176                 pPriKey = std::unique_ptr< _CertPrivateKeyInfo >(new (std::nothrow) _CertPrivateKeyInfo());
2177                 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2178
2179                 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2180                 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2181
2182                 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2183                 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2184                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2185
2186                 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2187                 if (!IsFailed(r) && priKeyLen != 0)
2188                 {
2189                         pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2190
2191                         pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2192
2193                         priKeyLen = 0;
2194
2195                         pPrivateKey.reset(null);
2196
2197                         pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2198                         SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2199
2200                         pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
2201
2202                         if (encodingType == _CERT_ENC_TYPE_PEM)
2203                         {
2204                                 BIO_free(pBio);
2205
2206                                 pBio = BIO_new(BIO_s_mem());
2207                                 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2208
2209                                 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2210                                 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2211
2212                                 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2213                                 keyBufferLen = priKeyLen;
2214
2215                                 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2216                                 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2217
2218                                 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2219
2220                                 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2221                                 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2222
2223                                 pCertInfo->privateKeyLen = readCount;
2224                         }
2225                         else if (encodingType == _CERT_ENC_TYPE_BASE64)
2226                         {
2227                                 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2228                                 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2229                                 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2230                                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2231
2232                         }
2233                         else
2234                         {
2235                                 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2236                                 pCertInfo->privateKeyLen = priKeyLen;
2237                         }
2238                 }
2239         }
2240
2241         *ppUserCertInfo = pCertInfo.release();
2242
2243 CATCH:
2244
2245         if (encodingType == _CERT_ENC_TYPE_PEM)
2246         {
2247                 BIO_free(pBio);
2248                 X509_free(pCert);
2249                 EVP_PKEY_free(pKey);
2250         }
2251
2252         return r;
2253 }
2254
2255
2256 } } } //Tizen::Security::Cert