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