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