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