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