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