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