2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 // Licensed under the Apache License, Version 2.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
18 * @file FSecCert_CertDbManager.cpp
19 * @brief This file contains implementation of X509 Certificate Db Manager APIs.
30 #include <openssl/evp.h>
31 #include <openssl/pem.h>
32 #include <unique_ptr.h>
35 #include <FBaseSysLog.h>
36 #include <FBaseByteBuffer.h>
37 #include <FBaseResult.h>
38 #include <FBase_StringConverter.h>
39 #include "FSecCert_CertDbStore.h"
40 #include "FSecCert_CertFileStore.h"
41 #include "FSecCert_CertDbManager.h"
42 #include "FSecCert_Base64.h"
43 #include "FSecCert_CertService.h"
44 #include "FSecCert_CertManager.h"
46 using namespace Tizen::Base;
47 using namespace Tizen::Io;
53 void operator ()(byte* c)
60 namespace Tizen { namespace Security { namespace Cert
62 _CertDbManager* _CertDbManager::__pCertDb = null;
64 _CertDbManager::_CertDbManager(void)
68 _CertDbManager::~_CertDbManager(void)
73 _CertDbManager::Construct(void)
75 static _CertDbManager certDb;
81 _CertDbManager::GetInstance(void)
83 static pthread_once_t once_block = PTHREAD_ONCE_INIT;
84 if (__pCertDb == null)
86 pthread_once(&once_block, Construct);
93 _CertDbManager::CreateCertificateTables(void)
97 r = __caCertDbStore.CreateCertificateTables();
98 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database.");
104 _CertDbManager::IsCertificateTablesCreated(void)
106 result r = E_SUCCESS;
108 r = __caCertDbStore.IsRootCaCertTableCreated();
111 SetLastResult(E_SYSTEM);
115 r = __userCertDbStore.IsUserCertTableCreated();
118 SetLastResult(E_SYSTEM);
126 _CertDbManager::ResetCertificateTables(void)
128 result r = E_SUCCESS;
130 r = __caCertDbStore.DropCertificateTables();
131 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database.");
133 r = __caCertDbStore.CreateCertificateTables();
134 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database.");
140 _CertDbManager::RemoveCertificateTables(void)
142 result r = E_SUCCESS;
143 r = __caCertDbStore.DropCertificateTables();
144 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
149 _CertDbManager::RemoveCaCertificateByType(_CaCertType certType)
151 result r = E_SUCCESS;
152 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
153 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
155 sprintf(condition, "certType = %d and installed = '%s'", certType, installed);
157 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
158 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
164 _CertDbManager::RemoveUserCaCertificateByCertId(int certId)
166 result r = E_SUCCESS;
167 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
168 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
170 sprintf(condition, "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed);
171 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
172 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
178 _CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
180 return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false);
184 _CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity)
186 result r = E_SUCCESS;
188 CaCertRecord certRecord = {0, };
189 _CertFileStore fileStore;
190 _CertFormat certBufFormat = _CERT_UNKNOWN;
191 _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
192 int lenSubjectName = 0;
193 int lenIssuerName = 0;
196 int derCertBufferLength = 0;
197 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
198 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
199 char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
200 char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
201 byte* pDerCert = null;
202 byte* pSerial = null;
203 _X509TbsCert* pTbsCert = null;
205 r = __caCertDbStore.IsRootCaCertTableCreated();
206 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
208 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
209 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
211 certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType);
212 std::unique_ptr< byte, ByteDeleter > pDerCertBuffer(pDerCert);
214 SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer.");
215 SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format.");
216 SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length.");
218 r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
219 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
221 pTbsCert = pCert->GetTbsCertInstance();
222 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
224 lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
225 lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
227 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
228 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
230 strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
231 strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
233 pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo));
234 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
236 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
241 memcpy(serialName, pSerial, lenSerialNo);
246 if (pCert->IsSelfSigned())
248 r = pCert->VerifySignature(null, 0);
249 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data.");
251 #ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE
252 //Open this code - if u want to support installation of Intermediate CA Certificate with verification using this API.(ideally it should check if installing intermediate CA) (09082011)
253 else if (pCert->IsCaCertificate())
255 std::unique_ptr< _CertChain > pCertChain(new (std::nothrow) _CertChain());
256 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
258 r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength);
259 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed.");
261 r = pCertChain->MoveHead();
262 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed.");
265 // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id
266 //(there are ECC certificate installation which we support for china model. hence these comments)
267 r = pCertChain->VerifyCertChainWithDb();
268 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain.");
272 #ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE
273 //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check)
276 return E_UNSUPPORTED_OPERATION;
282 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName);
283 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
284 SysTryReturnResult(NID_SEC_CERT, r==E_DATA_NOT_FOUND, r, "Failed to check duplicate");
286 //Get the last installed certificate id from db table
287 __caCertDbStore.GetCurrentCertId(certId);
288 //Calculate the new (std::nothrow) certificate id for installation
290 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
292 memset(&certRecord, 0, sizeof(certRecord));
293 certRecord.certType = static_cast< int >(certType);
294 certRecord.certFormat = static_cast< int >(certFormat);
296 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
297 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
299 strcpy(certRecord.fileName, pFileName.get());
301 certRecord.subjectNameLen = lenSubjectName;
302 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
303 certRecord.issuerNameLen = lenIssuerName;
304 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
305 certRecord.parentCa = certId;
306 strcpy(certRecord.installed, installed);
307 memcpy(certRecord.serialNo, serialName, lenSerialNo);
308 certRecord.serialNoLen = lenSerialNo;
310 r = __caCertDbStore.InsertCaCertificate(&certRecord);
311 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
313 fileStore.SetFilePath(tempFileName);
315 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
316 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
323 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
325 result r = E_SUCCESS;
327 CaCertRecord certRecord = {0, };
328 CaCertRecord certRecord1 = {0, };
329 _CertFileStore fileStore;
330 _X509TbsCert* pTbsCert = null;
331 _X509TbsCert* pNewTbsCert = null;
332 int lenSubjectName = 0;
333 int lenNewSubjectName = 0;
334 int lenIssuerName = 0;
335 int lenNewIssuerName = 0;
336 int lenNewSerialNo = 0;
338 int subjNameB64len = 0;
339 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
340 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
341 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
342 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
343 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
344 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
345 byte* pNewSerial = null;
347 r = __caCertDbStore.IsRootCaCertTableCreated();
348 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
350 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
351 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
353 r = pCert->Parse(pCurCertBuf, curCertLen);
354 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
356 pTbsCert = pCert->GetTbsCertInstance();
357 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
359 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
360 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
362 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
363 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
365 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
366 if (!IsFailed(r)) //checkit
368 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
369 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
371 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
373 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
374 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
376 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
377 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
378 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
380 certId = certRecord.parentCa;
382 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
383 fileStore.SetFilePath(tempFileName);
385 if (certFormat == _CERT_X509)
387 std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
388 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
390 r = pNewCert->Parse(pNewCertBuf, newCertLen);
391 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
393 pNewTbsCert = pNewCert->GetTbsCertInstance();
394 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
396 strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
397 strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName())));
399 lenNewSubjectName = strlen(newSubjectName);
400 lenNewIssuerName = strlen(newIssuerName);
402 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
403 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
405 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
411 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
414 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
415 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
417 certRecord1.certType = static_cast< int >(certType);
418 certRecord1.certFormat = static_cast< int >(certFormat);
420 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
421 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
423 strcpy(certRecord1.fileName, pFileName.get());
425 certRecord1.subjectNameLen = lenNewSubjectName;
426 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
427 certRecord1.issuerNameLen = lenIssuerName;
428 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
429 certRecord1.parentCa = certId;
430 strcpy(certRecord1.installed, certRecord.installed);
431 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
432 certRecord1.serialNoLen = lenNewSerialNo;
434 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
435 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
437 fileStore.DeleteFile();
439 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
440 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
441 //No need to update record as only file data changed.
449 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
451 result r = E_SUCCESS;
452 _X509TbsCert* pTbsCert = null;
454 _CertFileStore fileStore;
457 //Check certType missing
459 r = __caCertDbStore.IsRootCaCertTableCreated();
460 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
462 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
463 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
465 r = pCert->Parse(pCertBuf, certLen);
466 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
468 pTbsCert = pCert->GetTbsCertInstance();
469 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
471 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
472 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_OBJ_NOT_FOUND, "Certificate not found in db.");
473 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), r, "Propagated.");
475 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
476 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
478 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
481 r = __caCertDbStore.RemoveCertificateById(certId);
482 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
485 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
486 Tizen::Io::File::Remove(fileName);
493 _CertDbManager::RemoveCertificateChainByCertId(int certId)
495 result r = E_SUCCESS;
496 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
497 UserCertRecord userCertRecord = {0, };
499 memset(&userCertRecord, 0, sizeof(userCertRecord));
500 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
502 sprintf(condition, "certId = %d", certId);
503 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
504 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
505 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
507 r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
508 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
515 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
517 result r = E_SUCCESS;
518 int subjNameB64len = 0;
519 int issuerB64len = 0;
520 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
521 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
522 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
523 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
524 CaCertRecord caCertRecord = {0, };
526 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
527 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
529 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
530 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
532 r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
533 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
535 memset(condition, 0, sizeof(condition));
537 if (pIssuerName != null && issuerNameSize > 0)
539 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
540 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
542 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
543 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
545 if (certType == _CERT_TYPE_NOT_BOUNDED)
547 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
551 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
556 if (certType == _CERT_TYPE_NOT_BOUNDED)
558 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
562 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
566 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
567 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
569 certId = caCertRecord.certId;
575 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
577 result r = E_SUCCESS;
578 int subjNameB64len = 0;
579 int issuerB64len = 0;
580 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
581 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
582 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
583 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
584 UserCertRecord userCertRecord = {0, };
586 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
587 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
589 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
590 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
592 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
593 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
595 memset(condition, 0, sizeof(condition));
597 if (pIssuerName != null && issuerNameSize > 0)
599 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
600 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
602 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
603 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
605 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
609 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
612 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
613 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
615 certId = userCertRecord.certId;
621 _CertDbManager::RemoveAllUserCertificate(void)
623 __userCertDbStore.DeleteUserCertFiles();
629 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
631 result r = E_SUCCESS;
632 CaCertRecord certRecord = {0, };
636 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
637 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
640 SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
641 SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
643 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
645 sprintf(condition, "parentCa = %d and installed = '%s'", devParentCA, installed);
646 //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
647 //delete only device certificate and return. We cannot disturb another chain.
648 __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
649 //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
652 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
653 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
657 //Now there is not two device certificate with same intermidiate CA,
658 //so go ahead to intermidiate CA and delete device certificate.
659 caParentCa = devParentCA;
660 caCertId = devCertId;
663 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
667 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
668 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
670 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
671 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
672 break; // break here next certificate has dependency
676 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
677 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
679 break; // break here next certificate has dependency
682 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
684 if (devCert) //If it is device certificate
686 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
687 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
689 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
690 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
692 else //If it is CA certificate and there is no dependency
694 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
695 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
697 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
699 caCertId = caParentCa; // Now look for next certificate in chain
700 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
701 sprintf(condition, "certId = %d and installed = '%s'", devParentCA, installed);
702 memset(&certRecord, 0, sizeof(certRecord));
703 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
704 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
705 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
707 caParentCa = certRecord.parentCa;
710 while (caCertId != caParentCa);
716 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
718 result r = E_SUCCESS;
719 CaCertRecord certRecord = {0, };
720 _CertificateListInfo* pHoldList = null;
721 _CertFileStore fileStore;
724 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
725 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
727 sprintf(condition, "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
729 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
730 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
731 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
733 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
734 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
736 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
737 pCertList->pNext = null;
738 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
739 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
741 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
742 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
744 pCertList->length = certLength;
745 pCertList->certFileId = certRecord.certId;
746 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
747 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
750 pHoldList = pCertList.release();
751 *ppCertList = pHoldList;
753 while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
755 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
756 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
758 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
760 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
761 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
763 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
764 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
766 pCertList->pNext = null;
767 pCertList->length = certLength;
768 pCertList->certFileId = certRecord.certId;
769 pCertList->format = (_CertFormat) certRecord.certFormat;
770 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
772 pHoldList->pNext = pCertList.release();
773 pHoldList = pHoldList->pNext;
785 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
787 result r = E_SUCCESS;
788 UserCertRecord certRecord = {0, };
789 _CertificateListInfo* pHoldList = null;
790 _CertFileStore fileStore;
793 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
794 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
798 sprintf(condition, "certFormat = %d and installed = '%s'", certFormat, installed);
800 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
801 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
802 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
804 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
805 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
807 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
808 pCertList->pNext = null;
810 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
811 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
813 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
814 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
816 pCertList->length = certLength;
817 pCertList->certFileId = certRecord.certId;
818 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
819 pCertList->certType = _CERT_TYPE_USER_CERT;
822 pHoldList = pCertList.release();
823 *ppCertList = pHoldList;
825 while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
827 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
828 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
830 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
832 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
833 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
835 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
836 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
838 pCertList->pNext = null;
839 pCertList->length = certLength;
840 pCertList->certFileId = certRecord.certId;
841 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
842 pCertList->certType = _CERT_TYPE_USER_CERT;
844 pHoldList->pNext = pCertList.release();
845 pHoldList = pHoldList->pNext;
856 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
858 result r = E_SUCCESS;
859 CaCertRecord certRecord = {0, };
860 _CertFileStore fileStore;
862 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
863 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
866 sprintf(condition, "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
868 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
869 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
871 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
872 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
874 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
876 pCertList->pNext = null;
877 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
878 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
880 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
881 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
883 pCertList->length = certLength;
884 pCertList->certFileId = certRecord.certId;
885 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
886 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
888 *ppCertList = pCertList.release();
894 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
896 result r = E_SUCCESS;
897 _CertFileStore fileStore;
898 UserCertRecord certRecord = {0, };
901 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
902 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
906 SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
907 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
909 sprintf(condition, "certId = %d and installed = '%s'", certId, installed);
910 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
911 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
913 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
914 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
916 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
918 pCertList->pNext = null;
920 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
921 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
923 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
924 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
926 pCertList->length = certLength;
927 pCertList->certFileId = certRecord.certId;
928 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
929 pCertList->certType = _CERT_TYPE_USER_CERT;
931 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
932 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
934 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
935 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
937 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
939 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
940 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
942 r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
943 if (!IsFailed(r) && priKeyLen != 0)
945 byte* pPrivateTempKey = null;
946 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
948 pPrivateKey.reset(null);
950 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
951 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
953 std::unique_ptr< byte[] > pPrivateKeyAuto(pPrivateTempKey);
955 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
957 pCertList->priKeyLen = priKeyLen;
959 *ppCertList = pCertList.release();
965 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
967 result r = E_SUCCESS;
968 CaCertRecord certRecord = {0, };
969 _CertFileStore fileStore;
971 int issuerNameB64len = 0;
972 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
973 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
974 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
976 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
977 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
978 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
980 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
981 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
983 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
985 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
986 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
988 sprintf(condition, "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
990 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
991 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
993 filePath = reinterpret_cast< char* >(certRecord.fileName);
995 fileStore.SetFilePath(filePath);
997 *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
998 SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1000 r = fileStore.ReadFromFile(*ppCert, certLen);
1001 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1003 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1009 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1011 result r = E_SUCCESS;
1013 CaCertRecord certRecord = {0, };
1014 _CertFileStore fileStore;
1015 int issuerNameB64len = 0;
1016 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1017 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1018 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1020 SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1021 SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1022 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1023 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1024 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1026 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1027 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1029 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1031 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1032 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1034 sprintf(condition, "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1035 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1036 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1038 if (certRecord.certId == 0)
1043 filePath = static_cast< char* >(certRecord.fileName);
1044 fileStore.SetFilePath(filePath);
1046 std::unique_ptr< byte[] > pCert(new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1047 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1049 r = fileStore.ReadFromFile(pCert.get(), certLen);
1050 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1052 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1054 *ppCert = pCert.release();
1060 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1062 result r = E_SUCCESS;
1063 CaCertRecord certRecord = {0, };
1064 _CertFileStore fileStore;
1065 int subjectNameB64len = 0;
1066 int issuerNameB64len = 0;
1067 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1068 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1069 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1070 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1072 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1073 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1074 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1075 SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1077 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1078 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1080 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1082 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1083 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1085 subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1086 SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1088 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1089 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1090 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1092 sprintf(condition, "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1093 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1094 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1096 *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1101 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1103 result r = E_SUCCESS;
1104 _CertFileStore fileStore;
1107 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1109 if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1113 r = __userCertDbStore.RemoveCertificateById(certId);
1114 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1116 //Remove certificate file
1117 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1118 r = Tizen::Io::File::Remove(fileName);
1119 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1121 //Remove private key file
1122 //Don't check return type here as it is not necessary that private key is present.
1123 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1124 r = Tizen::Io::File::Remove(keyfileName);
1126 else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1128 r = __caCertDbStore.RemoveCertificateById(certId);
1129 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1131 //Remove certificate file
1132 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1133 r = Tizen::Io::File::Remove(fileName);
1134 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1140 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1142 result r = E_SUCCESS;
1143 String fileName(reinterpret_cast< char* >(pFilePath));
1144 FileAttributes attr;
1149 int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1152 SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1153 SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1154 SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1156 r = File::GetAttributes(fileName, attr);
1157 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1159 fileSize = attr.GetFileSize();
1160 SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1161 SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1164 r = file.Construct(fileName, L"r");
1165 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1167 std::unique_ptr< byte[] > pCertBuf(new (std::nothrow) byte[fileSize + 1]);
1168 SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1170 memset(pCertBuf.get(), 0, fileSize + 1);
1171 readCnt = file.Read(pCertBuf.get(), fileSize);
1172 r = GetLastResult();
1173 SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1176 std::unique_ptr< byte[] > pOutBuf(new (std::nothrow) byte[outLen]);
1177 SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1179 memset(pOutBuf.get(), 0, outLen);
1180 //As per OpenSSL APIs, it takes input as unsigned data types
1181 resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1182 SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1184 memcpy(pBuf, pOutBuf.get(), outLen);
1190 //User Certificate APIs
1193 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1195 result r = E_SUCCESS;
1196 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1197 int curCACertId = 0;
1198 int lastCACertId = 0;
1199 int curDevCertId = 0;
1200 bool updateUserParentCa = false;
1202 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1203 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1205 //Check for CA certificate table creation
1206 r = __caCertDbStore.IsRootCaCertTableCreated();
1207 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1210 //Check if the chain is valid or not
1211 r = pCertChain->Verify();
1212 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1214 r = pCertChain->MoveHead();
1215 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1217 if (certFormat == _CERT_X509)
1219 _X509Certificate* pCurCert = null;
1220 _X509Certificate* pUserCert = null;
1221 _X509TbsCert* pTbsCert = null;
1222 byte* pX509Buff = null;
1223 int x509BuffSize = 0;
1225 pUserCert = pCertChain->GetCurrentCertificate();
1226 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1228 pTbsCert = pUserCert->GetTbsCertInstance();
1229 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1231 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1232 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1234 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1235 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed insert user certificate chain.", GetErrorMessage(r));
1237 updateUserParentCa = true;
1239 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1240 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1242 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1244 //Insert certificate chain in CA certificate store
1245 while (pCertChain->MoveNext() == E_SUCCESS)
1248 pCurCert = pCertChain->GetCurrentCertificate();
1249 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1251 if (!pCurCert->IsSelfSigned())
1253 certType = _CERT_TYPE_INTERMIDIATE_CA;
1257 //This parameter need to pass from certificate manager about its type
1258 certType = _CERT_TYPE_ROOT_CA;
1261 pTbsCert = pCurCert->GetTbsCertInstance();
1262 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1264 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1267 SysTryReturn(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, r, "[%s] Failed to check duplicate.", GetErrorMessage(r));
1272 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1273 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1275 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1276 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1279 // CA certificate already present or properly installed in CA certificate store,
1280 // get the certificate id of certificate
1281 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1282 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1283 curCACertId, certType);
1284 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1286 if (updateUserParentCa)
1288 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1289 updateUserParentCa = false;
1290 lastCACertId = curCACertId;
1294 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1295 lastCACertId = curCACertId;
1298 //If it is root certificate then its parent is itself
1299 if (pCurCert->IsSelfSigned())
1301 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1306 if (updateUserParentCa)
1308 r = pCertChain->MoveHead();
1309 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1311 pCurCert = pCertChain->GetCurrentCertificate();
1312 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1314 pTbsCert = pCurCert->GetTbsCertInstance();
1315 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1317 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1318 null, 0, curCACertId);
1319 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1321 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1322 updateUserParentCa = false;
1323 lastCACertId = curCACertId;
1325 else if (!pCurCert->IsSelfSigned())
1327 pTbsCert = pCurCert->GetTbsCertInstance();
1328 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1330 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1331 null, 0, curCACertId);
1332 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1334 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1335 lastCACertId = curCACertId;
1343 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1345 result r = E_SUCCESS;
1346 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1348 int curCACertId = 0;
1349 int lastCACertId = 0;
1350 int curDevCertId = 0;
1352 bool updateUserParentCa = false;
1353 byte* pPrvKey = null;
1354 std::unique_ptr< byte[] > pPrvKeyBuffer;
1356 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1357 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1359 r = __userCertDbStore.IsUserCertTableCreated();
1360 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1362 //Check for CA certificate table creation
1363 r = __caCertDbStore.IsRootCaCertTableCreated();
1364 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1366 //Check if the chain is valid or not
1367 r = pCertChain->Verify();
1368 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1370 r = pCertChain->MoveHead();
1371 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1373 if (certFormat == _CERT_X509)
1375 _X509Certificate* pCurCert = null;
1376 _X509Certificate* pUserCert = null;
1377 _X509TbsCert* pTbsCert = null;
1378 byte* pX509Buff = null;
1379 int x509BuffSize = 0;
1381 pUserCert = pCertChain->GetCurrentCertificate();
1382 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1384 pTbsCert = pUserCert->GetTbsCertInstance();
1385 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1387 byte* pSubjectName = pTbsCert->GetSubjectName();
1388 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1390 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1392 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1393 if (r == E_DATA_NOT_FOUND)
1395 if (pPrivateKeyInfo != null)
1397 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1398 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1400 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1405 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1406 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1408 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1409 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1415 updateUserParentCa = true;
1417 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1418 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1420 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1422 if (pPrvKeyBuffer != null)
1424 _CertFileStore fileStore;
1425 String privateKeyFile;
1427 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1428 fileStore.SetFilePath(privateKeyFile);
1431 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1432 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1442 if (pUserCert->IsSelfSigned())
1444 __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
1448 //Insert certificate chain in CA certificate store
1449 while (pCertChain->MoveNext() == E_SUCCESS)
1451 pCurCert = pCertChain->GetCurrentCertificate();
1452 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1454 if (!pCurCert->IsSelfSigned())
1456 certType = _CERT_TYPE_INTERMIDIATE_CA;
1460 //This parameter need to pass from certificate manager about its type
1461 certType = _CERT_TYPE_ROOT_CA;
1464 pTbsCert = pCurCert->GetTbsCertInstance();
1465 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1467 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1470 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate.");
1475 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1476 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1478 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1479 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1482 // CA certificate already present or properly install in CA certificate store,
1483 // get the certificate id of certificate
1485 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1486 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1487 curCACertId, certType);
1488 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1490 if (updateUserParentCa)
1492 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1493 updateUserParentCa = false;
1494 lastCACertId = curCACertId;
1498 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1499 lastCACertId = curCACertId;
1502 //If it is root certificate then its parent is itself
1503 if (pCurCert->IsSelfSigned())
1505 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1509 if (updateUserParentCa)
1511 r = pCertChain->MoveHead();
1512 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1514 pCurCert = pCertChain->GetCurrentCertificate();
1515 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1517 pTbsCert = pCurCert->GetTbsCertInstance();
1518 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1520 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1521 null, 0, curCACertId);
1522 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1524 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1525 updateUserParentCa = false;
1526 lastCACertId = curCACertId;
1528 else if (!pCurCert->IsSelfSigned())
1530 pTbsCert = pCurCert->GetTbsCertInstance();
1531 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1533 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1534 null, 0, curCACertId);
1535 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1537 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1538 lastCACertId = curCACertId;
1546 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1548 result r = E_SUCCESS;
1549 _X509TbsCert* pTbsCert = null;
1550 _CertFileStore fileStore;
1551 UserCertRecord certRecord = {0, };
1552 String privateKeyFile;
1553 String tempFileName;
1554 int lenSubjectName = 0;
1555 int lenIssuerName = 0;
1556 int lenSerialNo = 0;
1558 int keyIdB64Length = 0;
1559 char* pFileName = null;
1560 char* pPriKeyFileName = null;
1561 char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1562 char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1563 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1564 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1565 byte* pKeyId = null;
1566 byte* pSerial = null;
1568 //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1569 SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1570 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1571 SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1573 r = __userCertDbStore.IsUserCertTableCreated();
1574 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1576 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
1577 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1579 r = pCert->Parse(pCertBuffer, certLength);
1580 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1582 pTbsCert = pCert->GetTbsCertInstance();
1583 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1585 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1586 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1588 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1589 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1591 strcpy(subjectNameBuffer, reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1592 strcpy(szIssuerName, reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1594 pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1595 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1597 if (pSerial != null)
1599 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1605 memcpy(serialName, pSerial, lenSerialNo);
1609 r = pCert->GetKeyIdN(&pKeyId);
1610 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1612 std::unique_ptr< byte[] > pKeyIdBuffer(pKeyId);
1614 keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1615 SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1617 std::unique_ptr< char[] > pId64(new (std::nothrow) char[keyIdB64Length]);
1618 SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1620 memset(pId64.get(), 0, keyIdB64Length);
1621 r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1622 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1624 r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1625 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1626 SysTryReturnResult(NID_SEC_CERT, r==E_DATA_NOT_FOUND, r, "Failed to check duplicate");
1628 //Get the last installed certificate id from db table
1629 __userCertDbStore.GetCurrentCertId(certId);
1631 //Calculate the new certificate id for installation
1632 certId = certId + 1;
1634 if (pPrivateKey != null)
1636 //Get file name for private key and store private key into file.
1637 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1641 pPriKeyFileName = null;
1645 //Get file name for certificate and write device certificate to file
1646 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1648 //Insert Record into Database
1649 //It is generated automatically by sequence
1650 memset(&certRecord, 0, sizeof(certRecord));
1652 memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1653 certRecord.certFormat = static_cast< int >(certFormat);
1655 pFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName);
1656 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1658 strcpy(certRecord.fileName, pFileName);
1659 certRecord.subjectNameLen = lenSubjectName;
1661 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1662 certRecord.issuerNameLen = lenIssuerName;
1663 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1665 pPriKeyFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile);
1666 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1668 strcpy(certRecord.prvKeyPath, pPriKeyFileName);
1669 certRecord.prvKeyLen = privateKeyLen;
1670 certRecord.parentCa = certId;
1671 strcpy(certRecord.installed, installedRecord);
1673 memcpy(certRecord.serialNo, serialName, lenSerialNo);
1675 certRecord.serialNoLen = lenSerialNo;
1677 r = __userCertDbStore.InsertUserCertificate(&certRecord);
1678 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1680 fileStore.SetFilePath(tempFileName);
1682 r = fileStore.WriteToFile(pCertBuffer, certLength);
1683 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1685 if (pPrivateKey != null)
1687 fileStore.SetFilePath(privateKeyFile);
1689 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1690 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1697 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1699 result r = E_SUCCESS;
1700 CaCertRecord certRecord = {0, };
1701 UserCertRecord userCertRecord = {0, };
1702 _CertificateListInfo* pHoldList = null;
1705 EVP_PKEY* pKey = null;
1707 int recordCount = 0;
1708 int subjectNameBase64Len = 0;
1714 int certificateBase64Len = 0;
1715 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1716 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1717 byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1718 byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1719 byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1720 bool isIssuerNameInList = false;
1722 subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1723 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1724 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1725 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1727 if ((pSubjectName != null) && (subjectNameLen > 0))
1729 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1730 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1731 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1732 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1733 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1737 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1738 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1739 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1740 sprintf(condition, "installed = '%s'", installedRecord);
1743 memset(&userCertRecord, 0, sizeof(userCertRecord));
1744 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1745 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1747 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
1748 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1751 std::unique_ptr< _CertFileStore > pFileStore(new (std::nothrow) _CertFileStore());
1752 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1754 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
1755 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1757 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1759 pCertList->pNext = null;
1761 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1762 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1764 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1765 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1766 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1768 if (encodingType == _CERT_ENC_TYPE_PEM)
1770 const byte* pCertBuffer = pCertList->certificate;
1772 pBio = BIO_new(BIO_s_mem());
1773 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1775 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1776 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1778 readLength = PEM_write_bio_X509(pBio, pCert);
1779 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1781 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1783 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1784 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1786 pCertList->length = readLength;
1795 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1797 int certLen = _Base64::GetEncodedSize(pCertList->length);
1798 SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_SYSTEM, "Certificate length is invalid.");
1799 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1800 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1801 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1803 pCertList->length = certLen;
1806 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1807 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1809 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1810 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1811 pCertList->certFileId = userCertRecord.certId;
1813 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1814 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1818 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1819 if (!IsFailed(r) && priKeyLen != 0)
1821 byte* pPrivateTempKey = null;
1822 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1823 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1825 pPrivateKey.reset(null);
1828 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1829 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1831 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
1833 if (encodingType == _CERT_ENC_TYPE_PEM)
1835 const byte* pKeyBuffer = pPrivateKey.get();
1836 pBio = BIO_new(BIO_s_mem());
1837 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1839 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1840 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1842 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1843 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1845 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1847 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1849 pCertList->priKeyLen = readLength;
1857 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1859 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1860 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1862 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1863 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1867 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1868 pCertList->priKeyLen = priKeyLen;
1872 pPrivateKey.reset(null);
1874 pHoldList = pCertList.release();
1875 *ppCertListInfoTypes = pHoldList;
1879 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1880 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1881 subNameLen = userCertRecord.issuerNameLen;
1885 subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1886 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1887 r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1888 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1889 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1891 if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1893 isIssuerNameInList = true;
1896 memset(&certRecord, 0, sizeof(certRecord));
1897 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1898 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1900 if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1902 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo());
1903 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1905 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1906 pCertList->pNext = null;
1908 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1909 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1911 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1912 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1913 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1915 if (encodingType == _CERT_ENC_TYPE_PEM)
1917 const byte* pCertBuffer = pCertList->certificate;
1919 pBio = BIO_new(BIO_s_mem());
1920 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1922 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1923 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1925 readLength = PEM_write_bio_X509(pBio, pCert);
1926 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1928 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1930 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1931 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1933 pCertList->length = readLength;
1941 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1943 int certLen = _Base64::GetEncodedSize(pCertList->length);
1944 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1945 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1946 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1947 pCertList->length = certLen;
1949 pCertList->format = (_CertFormat) certRecord.certFormat;
1950 pCertList->certType = (_CaCertType) certRecord.certType;
1951 pCertList->certFileId = certRecord.certId;
1953 pHoldList->pNext = pCertList.release();
1954 pHoldList = pHoldList->pNext;
1958 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1959 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1960 subNameLen = certRecord.issuerNameLen;
1964 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1966 if (!isIssuerNameInList)
1968 if (*ppCertListInfoTypes != null)
1970 _CertService::FreeCertList(*ppCertListInfoTypes);
1971 *ppCertListInfoTypes = null;
1974 memset(condition, 0, sizeof(condition));
1975 sprintf(condition, "installed = '%s'", installedRecord);
1979 memset(&userCertRecord, 0, sizeof(userCertRecord));
1980 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1981 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1983 curCertId = userCertRecord.certId;
1985 for (readLength = 0; readLength < count; readLength++)
1988 memset(&userCertRecord, 0, sizeof(userCertRecord));
1989 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1990 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1991 curCertId = userCertRecord.certId;
1996 while (isIssuerNameInList != true);
2009 EVP_PKEY_free(pKey);
2016 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2018 result r = E_SUCCESS;
2019 UserCertRecord userCertRecord = {0, };
2020 CaCertRecord caCertRecord = {0, };
2021 int subjNameB64len = 0;
2023 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2024 char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2025 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2027 subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2028 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2029 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2030 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2031 sprintf(conditonRecord, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2033 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2034 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2036 if (pPrivateKeyInfo != null)
2038 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2041 r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2042 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2044 parentCa = userCertRecord.parentCa;
2048 memset(&caCertRecord, 0, sizeof(caCertRecord));
2049 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2050 sprintf(conditonRecord, "certId = %d and installed = '%s'", parentCa, installedRecord);
2052 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2053 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2055 parentCa = caCertRecord.parentCa;
2056 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2058 r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2059 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2063 while (caCertRecord.certId != caCertRecord.parentCa);
2069 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2071 result r = E_SUCCESS;
2072 UserCertRecord userCertRecord = {0, };
2073 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2074 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2076 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2078 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2079 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2081 *pSubjectLength = userCertRecord.subjectNameLen;
2082 memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2083 *pIssuerLength = userCertRecord.issuerNameLen;
2084 memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2091 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2093 result r = E_SUCCESS;
2094 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2095 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2098 int certBufferLen = 0;
2099 int keyBufferLen = 0;
2100 int certificateBase64Len = 0;
2101 const byte* pCertBuffer = null;
2102 const byte* pKeyBuffer = null;
2103 byte* pPrivateTempKey = null;
2104 UserCertRecord certRecord = {0, };
2105 _CertFileStore fileStore;
2106 std::unique_ptr< _CertPrivateKeyInfo > pPriKey;
2109 EVP_PKEY* pKey = null;
2111 *ppUserCertInfo = null;
2113 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2114 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2116 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2117 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2119 std::unique_ptr< _CertInfo > pCertInfo(new (std::nothrow) _CertInfo);
2120 SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2122 memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2124 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2125 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2127 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2128 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2129 certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2131 if (encodingType == _CERT_ENC_TYPE_PEM)
2133 pBio = BIO_new(BIO_s_mem());
2134 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2136 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2137 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2139 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2140 certBufferLen = pCertInfo->certLength;
2142 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2143 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2145 readCount = PEM_write_bio_X509(pBio, pCert);
2146 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2148 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2149 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2150 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2152 pCertInfo->certLength = readCount;
2154 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2156 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2157 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2158 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2159 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2160 pCertInfo->certLength = certLen;
2162 pCertInfo->certId = certRecord.certId;
2163 pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2164 pCertInfo->certType = _CERT_TYPE_USER_CERT;
2166 if (certRecord.prvKeyLen > 0)
2168 pPriKey = std::unique_ptr< _CertPrivateKeyInfo >(new (std::nothrow) _CertPrivateKeyInfo());
2169 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2171 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2172 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2174 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2175 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2176 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2178 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2179 if (!IsFailed(r) && priKeyLen != 0)
2181 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2183 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2187 pPrivateKey.reset(null);
2189 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2190 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2192 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
2194 if (encodingType == _CERT_ENC_TYPE_PEM)
2198 pBio = BIO_new(BIO_s_mem());
2199 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2201 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2202 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2204 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2205 keyBufferLen = priKeyLen;
2207 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2208 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2210 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2212 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2213 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2215 pCertInfo->privateKeyLen = readCount;
2217 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2219 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2220 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2221 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2222 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2227 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2228 pCertInfo->privateKeyLen = priKeyLen;
2233 *ppUserCertInfo = pCertInfo.release();
2237 if (encodingType == _CERT_ENC_TYPE_PEM)
2241 EVP_PKEY_free(pKey);
2248 } } } //Tizen::Security::Cert