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 snprintf(condition, sizeof(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 snprintf(condition, sizeof(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 snprintf(subjectName, sizeof(subjectName), "%s", reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
231 snprintf(issuerName, sizeof(issuerName), "%s", 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);
285 return E_FILE_ALREADY_EXIST;
288 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate");
291 //Get the last installed certificate id from db table
292 __caCertDbStore.GetCurrentCertId(certId);
293 //Calculate the new (std::nothrow) certificate id for installation
295 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
297 memset(&certRecord, 0, sizeof(certRecord));
298 certRecord.certType = static_cast< int >(certType);
299 certRecord.certFormat = static_cast< int >(certFormat);
301 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
302 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
304 int len = strlen(pFileName.get());
305 snprintf(certRecord.fileName, sizeof(certRecord.fileName), "%s", pFileName.get());
307 certRecord.subjectNameLen = lenSubjectName;
308 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
309 certRecord.issuerNameLen = lenIssuerName;
310 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
311 certRecord.parentCa = certId;
312 strcpy(certRecord.installed, installed);
313 memcpy(certRecord.serialNo, serialName, lenSerialNo);
314 certRecord.serialNoLen = lenSerialNo;
316 r = __caCertDbStore.InsertCaCertificate(&certRecord);
317 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
319 fileStore.SetFilePath(tempFileName);
321 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
322 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
329 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
331 result r = E_SUCCESS;
333 CaCertRecord certRecord = {0, };
334 CaCertRecord certRecord1 = {0, };
335 _CertFileStore fileStore;
336 _X509TbsCert* pTbsCert = null;
337 _X509TbsCert* pNewTbsCert = null;
338 int lenSubjectName = 0;
339 int lenNewSubjectName = 0;
340 int lenIssuerName = 0;
341 int lenNewIssuerName = 0;
342 int lenNewSerialNo = 0;
344 int subjNameB64len = 0;
345 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
346 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
347 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
348 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
349 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
350 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
351 byte* pNewSerial = null;
353 r = __caCertDbStore.IsRootCaCertTableCreated();
354 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
356 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
357 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
359 r = pCert->Parse(pCurCertBuf, curCertLen);
360 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
362 pTbsCert = pCert->GetTbsCertInstance();
363 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
365 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
366 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
368 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
369 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
371 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
372 if (!IsFailed(r)) //checkit
374 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
375 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
377 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
379 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
380 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
382 snprintf(condition, sizeof(condition), "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
383 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
384 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
386 certId = certRecord.parentCa;
388 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
389 fileStore.SetFilePath(tempFileName);
391 if (certFormat == _CERT_X509)
393 std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
394 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
396 r = pNewCert->Parse(pNewCertBuf, newCertLen);
397 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
399 pNewTbsCert = pNewCert->GetTbsCertInstance();
400 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
402 snprintf(newSubjectName, sizeof(newSubjectName), "%s", reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
403 snprintf(newIssuerName, sizeof(newIssuerName), "%s", reinterpret_cast< const char* >(pNewTbsCert->GetIssuerName()));
405 lenNewSubjectName = strlen(newSubjectName);
406 lenNewIssuerName = strlen(newIssuerName);
408 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
409 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
411 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
417 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
420 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
421 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
423 certRecord1.certType = static_cast< int >(certType);
424 certRecord1.certFormat = static_cast< int >(certFormat);
426 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
427 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
429 int len = strlen(pFileName.get());
430 snprintf(certRecord1.fileName, sizeof(certRecord1.fileName), "%s", pFileName.get());
432 certRecord1.subjectNameLen = lenNewSubjectName;
433 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
434 certRecord1.issuerNameLen = lenIssuerName;
435 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
436 certRecord1.parentCa = certId;
437 strcpy(certRecord1.installed, certRecord.installed);
438 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
439 certRecord1.serialNoLen = lenNewSerialNo;
441 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
442 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
444 fileStore.DeleteFile();
446 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
447 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
448 //No need to update record as only file data changed.
456 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
458 result r = E_SUCCESS;
459 _X509TbsCert* pTbsCert = null;
461 _CertFileStore fileStore;
464 //Check certType missing
466 r = __caCertDbStore.IsRootCaCertTableCreated();
467 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
469 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
470 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
472 r = pCert->Parse(pCertBuf, certLen);
473 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
475 pTbsCert = pCert->GetTbsCertInstance();
476 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
478 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
479 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_OBJ_NOT_FOUND, "Certificate not found in db.");
480 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), r, "Propagated.");
482 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
483 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
485 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
488 r = __caCertDbStore.RemoveCertificateById(certId);
489 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
492 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
493 Tizen::Io::File::Remove(fileName);
500 _CertDbManager::RemoveCertificateChainByCertId(int certId)
502 result r = E_SUCCESS;
503 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
504 UserCertRecord userCertRecord = {0, };
506 memset(&userCertRecord, 0, sizeof(userCertRecord));
507 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
509 snprintf(condition, sizeof(condition), "certId = %d", certId);
510 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
511 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
512 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
514 r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
515 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
522 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
524 result r = E_SUCCESS;
525 int subjNameB64len = 0;
526 int issuerB64len = 0;
527 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
528 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
529 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
530 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
531 CaCertRecord caCertRecord = {0, };
533 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
534 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
536 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
537 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
539 r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
540 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
542 memset(condition, 0, sizeof(condition));
544 if (pIssuerName != null && issuerNameSize > 0)
546 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
547 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
549 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
550 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
552 if (certType == _CERT_TYPE_NOT_BOUNDED)
554 snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
558 snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
563 if (certType == _CERT_TYPE_NOT_BOUNDED)
565 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
569 snprintf(condition, sizeof(condition), "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
573 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
574 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
576 certId = caCertRecord.certId;
582 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
584 result r = E_SUCCESS;
585 int subjNameB64len = 0;
586 int issuerB64len = 0;
587 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
588 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
589 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
590 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
591 UserCertRecord userCertRecord = {0, };
593 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
594 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
596 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
597 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
599 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
600 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
602 memset(condition, 0, sizeof(condition));
604 if (pIssuerName != null && issuerNameSize > 0)
606 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
607 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
609 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
610 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
612 snprintf(condition, sizeof(condition), "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
616 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
619 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
620 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
622 certId = userCertRecord.certId;
628 _CertDbManager::RemoveAllUserCertificate(void)
630 __userCertDbStore.DeleteUserCertFiles();
636 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
638 result r = E_SUCCESS;
639 CaCertRecord certRecord = {0, };
643 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
644 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
647 SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
648 SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
650 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
652 snprintf(condition, sizeof(condition), "parentCa = %d and installed = '%s'", devParentCA, installed);
654 //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
655 //delete only device certificate and return. We cannot disturb another chain.
656 __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
657 //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
660 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
661 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
665 //Now there is not two device certificate with same intermidiate CA,
666 //so go ahead to intermidiate CA and delete device certificate.
667 caParentCa = devParentCA;
668 caCertId = devCertId;
671 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
675 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
676 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
678 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
679 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
680 break; // break here next certificate has dependency
684 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
685 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
687 break; // break here next certificate has dependency
690 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
692 if (devCert) //If it is device certificate
694 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
695 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
697 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
698 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
700 else //If it is CA certificate and there is no dependency
702 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
703 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
705 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
707 caCertId = caParentCa; // Now look for next certificate in chain
708 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
709 snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", devParentCA, installed);
710 memset(&certRecord, 0, sizeof(certRecord));
711 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
712 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
713 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
715 caParentCa = certRecord.parentCa;
718 while (caCertId != caParentCa);
724 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
726 result r = E_SUCCESS;
727 CaCertRecord certRecord = {0, };
728 _CertificateListInfo* pHoldList = null;
729 _CertFileStore fileStore;
732 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
733 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
735 snprintf(condition, sizeof(condition), "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
737 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
738 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
739 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
741 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
742 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
744 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
745 pCertList->pNext = null;
746 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
747 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
749 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
750 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
752 pCertList->length = certLength;
753 pCertList->certFileId = certRecord.certId;
754 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
755 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
758 pHoldList = pCertList.release();
759 *ppCertList = pHoldList;
761 while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
763 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
764 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
766 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
768 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
769 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
771 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
772 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
774 pCertList->pNext = null;
775 pCertList->length = certLength;
776 pCertList->certFileId = certRecord.certId;
777 pCertList->format = (_CertFormat) certRecord.certFormat;
778 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
780 pHoldList->pNext = pCertList.release();
781 pHoldList = pHoldList->pNext;
793 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
795 result r = E_SUCCESS;
796 UserCertRecord certRecord = {0, };
797 _CertificateListInfo* pHoldList = null;
798 _CertFileStore fileStore;
801 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
802 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
806 snprintf(condition, sizeof(condition), "certFormat = %d and installed = '%s'", certFormat, installed);
808 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
809 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
810 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
812 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
813 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
815 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
816 pCertList->pNext = null;
818 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
819 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
821 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
822 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
824 pCertList->length = certLength;
825 pCertList->certFileId = certRecord.certId;
826 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
827 pCertList->certType = _CERT_TYPE_USER_CERT;
830 pHoldList = pCertList.release();
831 *ppCertList = pHoldList;
833 while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
835 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
836 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
838 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
840 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
841 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
843 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
844 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
846 pCertList->pNext = null;
847 pCertList->length = certLength;
848 pCertList->certFileId = certRecord.certId;
849 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
850 pCertList->certType = _CERT_TYPE_USER_CERT;
852 pHoldList->pNext = pCertList.release();
853 pHoldList = pHoldList->pNext;
864 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
866 result r = E_SUCCESS;
867 CaCertRecord certRecord = {0, };
868 _CertFileStore fileStore;
870 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
871 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
874 snprintf(condition, sizeof(condition), "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
876 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
877 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
879 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
880 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
882 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
884 pCertList->pNext = null;
885 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
886 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
888 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
889 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
891 pCertList->length = certLength;
892 pCertList->certFileId = certRecord.certId;
893 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
894 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
896 *ppCertList = pCertList.release();
902 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
904 result r = E_SUCCESS;
905 _CertFileStore fileStore;
906 UserCertRecord certRecord = {0, };
909 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
910 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
914 SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
915 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
917 snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installed);
918 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
919 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
921 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
922 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
924 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
926 pCertList->pNext = null;
928 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
929 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
931 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
932 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
934 pCertList->length = certLength;
935 pCertList->certFileId = certRecord.certId;
936 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
937 pCertList->certType = _CERT_TYPE_USER_CERT;
939 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
940 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
942 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
943 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
945 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
947 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
948 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
950 r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
951 if (!IsFailed(r) && priKeyLen != 0)
953 byte* pPrivateTempKey = null;
954 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
956 pPrivateKey.reset(null);
958 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
959 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
961 std::unique_ptr< byte[] > pPrivateKeyAuto(pPrivateTempKey);
963 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
965 pCertList->priKeyLen = priKeyLen;
967 *ppCertList = pCertList.release();
973 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
975 result r = E_SUCCESS;
976 CaCertRecord certRecord = {0, };
977 _CertFileStore fileStore;
979 int issuerNameB64len = 0;
980 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
981 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
982 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
984 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
985 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
986 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
988 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
989 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
991 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
993 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
994 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
996 snprintf(condition, sizeof(condition), "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
998 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
999 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1001 filePath = reinterpret_cast< char* >(certRecord.fileName);
1003 fileStore.SetFilePath(filePath);
1005 *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
1006 SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1008 r = fileStore.ReadFromFile(*ppCert, certLen);
1009 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1011 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1017 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1019 result r = E_SUCCESS;
1021 CaCertRecord certRecord = {0, };
1022 _CertFileStore fileStore;
1023 int issuerNameB64len = 0;
1024 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1025 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1026 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1028 SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1029 SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1030 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1031 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1032 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1034 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1035 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1037 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1039 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1040 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1042 snprintf(condition, sizeof(condition), "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1043 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1044 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1046 if (certRecord.certId == 0)
1051 filePath = static_cast< char* >(certRecord.fileName);
1052 fileStore.SetFilePath(filePath);
1054 std::unique_ptr< byte[] > pCert(new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1055 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1057 r = fileStore.ReadFromFile(pCert.get(), certLen);
1058 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1060 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1062 *ppCert = pCert.release();
1068 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1070 result r = E_SUCCESS;
1071 CaCertRecord certRecord = {0, };
1072 _CertFileStore fileStore;
1073 int subjectNameB64len = 0;
1074 int issuerNameB64len = 0;
1075 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1076 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1077 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1078 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1080 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1081 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1082 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1083 SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1085 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1086 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1088 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1090 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1091 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1093 subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1094 SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1096 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1097 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1098 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1100 snprintf(condition, sizeof(condition), "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1101 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1102 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1104 *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1109 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1111 result r = E_SUCCESS;
1112 _CertFileStore fileStore;
1115 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1117 if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1121 r = __userCertDbStore.RemoveCertificateById(certId);
1122 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1124 //Remove certificate file
1125 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1126 r = Tizen::Io::File::Remove(fileName);
1127 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1129 //Remove private key file
1130 //Don't check return type here as it is not necessary that private key is present.
1131 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1132 r = Tizen::Io::File::Remove(keyfileName);
1134 else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1136 r = __caCertDbStore.RemoveCertificateById(certId);
1137 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1139 //Remove certificate file
1140 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1141 r = Tizen::Io::File::Remove(fileName);
1142 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1148 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1150 result r = E_SUCCESS;
1151 String fileName(reinterpret_cast< char* >(pFilePath));
1152 FileAttributes attr;
1157 int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1160 SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1161 SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1162 SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1164 r = File::GetAttributes(fileName, attr);
1165 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1167 fileSize = attr.GetFileSize();
1168 SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1169 SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1172 r = file.Construct(fileName, L"r");
1173 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1175 std::unique_ptr< byte[] > pCertBuf(new (std::nothrow) byte[fileSize + 1]);
1176 SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1178 memset(pCertBuf.get(), 0, fileSize + 1);
1179 readCnt = file.Read(pCertBuf.get(), fileSize);
1180 r = GetLastResult();
1181 SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1184 std::unique_ptr< byte[] > pOutBuf(new (std::nothrow) byte[outLen]);
1185 SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1187 memset(pOutBuf.get(), 0, outLen);
1188 //As per OpenSSL APIs, it takes input as unsigned data types
1189 resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1190 SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1192 memcpy(pBuf, pOutBuf.get(), outLen);
1198 //User Certificate APIs
1201 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1203 result r = E_SUCCESS;
1204 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1205 int curCACertId = 0;
1206 int lastCACertId = 0;
1207 int curDevCertId = 0;
1208 bool updateUserParentCa = false;
1210 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1211 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1213 //Check for CA certificate table creation
1214 r = __caCertDbStore.IsRootCaCertTableCreated();
1215 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1218 //Check if the chain is valid or not
1219 r = pCertChain->Verify();
1220 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1222 r = pCertChain->MoveHead();
1223 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1225 if (certFormat == _CERT_X509)
1227 _X509Certificate* pCurCert = null;
1228 _X509Certificate* pUserCert = null;
1229 _X509TbsCert* pTbsCert = null;
1230 byte* pX509Buff = null;
1231 int x509BuffSize = 0;
1233 pUserCert = pCertChain->GetCurrentCertificate();
1234 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1236 pTbsCert = pUserCert->GetTbsCertInstance();
1237 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1239 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1240 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1242 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1243 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));
1245 updateUserParentCa = true;
1247 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1248 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1250 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1252 //Insert certificate chain in CA certificate store
1253 while (pCertChain->MoveNext() == E_SUCCESS)
1256 pCurCert = pCertChain->GetCurrentCertificate();
1257 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1259 if (!pCurCert->IsSelfSigned())
1261 certType = _CERT_TYPE_INTERMIDIATE_CA;
1265 //This parameter need to pass from certificate manager about its type
1266 certType = _CERT_TYPE_ROOT_CA;
1269 pTbsCert = pCurCert->GetTbsCertInstance();
1270 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1272 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1275 SysTryReturn(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, r, "[%s] Failed to check duplicate.", GetErrorMessage(r));
1280 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1281 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1283 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1284 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1287 // CA certificate already present or properly installed in CA certificate store,
1288 // get the certificate id of certificate
1289 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1290 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1291 curCACertId, certType);
1292 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1294 if (updateUserParentCa)
1296 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1297 updateUserParentCa = false;
1298 lastCACertId = curCACertId;
1302 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1303 lastCACertId = curCACertId;
1306 //If it is root certificate then its parent is itself
1307 if (pCurCert->IsSelfSigned())
1309 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1314 if (updateUserParentCa)
1316 r = pCertChain->MoveHead();
1317 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1319 pCurCert = pCertChain->GetCurrentCertificate();
1320 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1322 pTbsCert = pCurCert->GetTbsCertInstance();
1323 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1325 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1326 null, 0, curCACertId);
1327 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1329 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1330 updateUserParentCa = false;
1331 lastCACertId = curCACertId;
1333 else if (!pCurCert->IsSelfSigned())
1335 pTbsCert = pCurCert->GetTbsCertInstance();
1336 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1338 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1339 null, 0, curCACertId);
1340 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1342 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1343 lastCACertId = curCACertId;
1351 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1353 result r = E_SUCCESS;
1354 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1356 int curCACertId = 0;
1357 int lastCACertId = 0;
1358 int curDevCertId = 0;
1360 bool updateUserParentCa = false;
1361 byte* pPrvKey = null;
1362 std::unique_ptr< byte[] > pPrvKeyBuffer;
1364 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1365 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1367 r = __userCertDbStore.IsUserCertTableCreated();
1368 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1370 //Check for CA certificate table creation
1371 r = __caCertDbStore.IsRootCaCertTableCreated();
1372 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1374 //Check if the chain is valid or not
1375 r = pCertChain->Verify();
1376 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1378 r = pCertChain->MoveHead();
1379 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1381 if (certFormat == _CERT_X509)
1383 _X509Certificate* pCurCert = null;
1384 _X509Certificate* pUserCert = null;
1385 _X509TbsCert* pTbsCert = null;
1386 byte* pX509Buff = null;
1387 int x509BuffSize = 0;
1389 pUserCert = pCertChain->GetCurrentCertificate();
1390 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1392 pTbsCert = pUserCert->GetTbsCertInstance();
1393 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1395 byte* pSubjectName = pTbsCert->GetSubjectName();
1396 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1398 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1400 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1401 if (r == E_DATA_NOT_FOUND)
1403 if (pPrivateKeyInfo != null)
1405 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1406 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1408 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1413 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1414 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1416 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1417 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1423 updateUserParentCa = true;
1425 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1426 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1428 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1430 if (pPrvKeyBuffer != null)
1432 _CertFileStore fileStore;
1433 String privateKeyFile;
1435 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1436 fileStore.SetFilePath(privateKeyFile);
1439 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1440 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1450 if (pUserCert->IsSelfSigned())
1452 __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
1456 //Insert certificate chain in CA certificate store
1457 while (pCertChain->MoveNext() == E_SUCCESS)
1459 pCurCert = pCertChain->GetCurrentCertificate();
1460 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1462 if (!pCurCert->IsSelfSigned())
1464 certType = _CERT_TYPE_INTERMIDIATE_CA;
1468 //This parameter need to pass from certificate manager about its type
1469 certType = _CERT_TYPE_ROOT_CA;
1472 pTbsCert = pCurCert->GetTbsCertInstance();
1473 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1475 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1478 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate.");
1483 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1484 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1486 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1487 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1490 // CA certificate already present or properly install in CA certificate store,
1491 // get the certificate id of certificate
1493 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1494 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1495 curCACertId, certType);
1496 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1498 if (updateUserParentCa)
1500 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1501 updateUserParentCa = false;
1502 lastCACertId = curCACertId;
1506 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1507 lastCACertId = curCACertId;
1510 //If it is root certificate then its parent is itself
1511 if (pCurCert->IsSelfSigned())
1513 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1517 if (updateUserParentCa)
1519 r = pCertChain->MoveHead();
1520 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1522 pCurCert = pCertChain->GetCurrentCertificate();
1523 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1525 pTbsCert = pCurCert->GetTbsCertInstance();
1526 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1528 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1529 null, 0, curCACertId);
1530 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1532 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1533 updateUserParentCa = false;
1534 lastCACertId = curCACertId;
1536 else if (!pCurCert->IsSelfSigned())
1538 pTbsCert = pCurCert->GetTbsCertInstance();
1539 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1541 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1542 null, 0, curCACertId);
1543 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1545 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1546 lastCACertId = curCACertId;
1554 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1556 result r = E_SUCCESS;
1557 _X509TbsCert* pTbsCert = null;
1558 _CertFileStore fileStore;
1559 UserCertRecord certRecord = {0, };
1560 String privateKeyFile;
1561 String tempFileName;
1562 int lenSubjectName = 0;
1563 int lenIssuerName = 0;
1564 int lenSerialNo = 0;
1566 int keyIdB64Length = 0;
1567 char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1568 char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1569 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1570 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1571 byte* pKeyId = null;
1572 byte* pSerial = null;
1574 //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1575 SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1576 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1577 SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1579 r = __userCertDbStore.IsUserCertTableCreated();
1580 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1582 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
1583 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1585 r = pCert->Parse(pCertBuffer, certLength);
1586 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1588 pTbsCert = pCert->GetTbsCertInstance();
1589 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1591 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1592 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1594 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1595 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1597 snprintf(subjectNameBuffer, sizeof(subjectNameBuffer), "%s", reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1598 snprintf(szIssuerName, sizeof(szIssuerName), "%s", reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1600 pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1601 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1603 if (pSerial != null)
1605 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1611 memcpy(serialName, pSerial, lenSerialNo);
1615 r = pCert->GetKeyIdN(&pKeyId);
1616 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1618 std::unique_ptr< byte[] > pKeyIdBuffer(pKeyId);
1620 keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1621 SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1623 std::unique_ptr< char[] > pId64(new (std::nothrow) char[keyIdB64Length]);
1624 SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1626 memset(pId64.get(), 0, keyIdB64Length);
1627 r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1628 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1630 r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1631 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1632 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate");
1634 //Get the last installed certificate id from db table
1635 __userCertDbStore.GetCurrentCertId(certId);
1637 //Calculate the new certificate id for installation
1638 certId = certId + 1;
1640 if (pPrivateKey != null)
1642 //Get file name for private key and store private key into file.
1643 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1650 //Get file name for certificate and write device certificate to file
1651 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1653 //Insert Record into Database
1654 //It is generated automatically by sequence
1655 memset(&certRecord, 0, sizeof(certRecord));
1657 memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1658 certRecord.certFormat = static_cast< int >(certFormat);
1660 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
1661 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1663 int len = strlen(pFileName.get());
1664 snprintf(certRecord.fileName, sizeof(certRecord.fileName), "%s", pFileName.get());
1666 certRecord.subjectNameLen = lenSubjectName;
1668 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1669 certRecord.issuerNameLen = lenIssuerName;
1670 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1672 std::unique_ptr< char[] > pPriKeyFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile));
1673 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1675 len = strlen(pPriKeyFileName.get());
1676 snprintf(certRecord.prvKeyPath, sizeof(certRecord.prvKeyPath), "%s", pPriKeyFileName.get());
1677 certRecord.prvKeyLen = privateKeyLen;
1678 certRecord.parentCa = certId;
1679 strcpy(certRecord.installed, installedRecord);
1681 memcpy(certRecord.serialNo, serialName, lenSerialNo);
1683 certRecord.serialNoLen = lenSerialNo;
1685 r = __userCertDbStore.InsertUserCertificate(&certRecord);
1686 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1688 fileStore.SetFilePath(tempFileName);
1690 r = fileStore.WriteToFile(pCertBuffer, certLength);
1691 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1693 if (pPrivateKey != null)
1695 fileStore.SetFilePath(privateKeyFile);
1697 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1698 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1705 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1707 result r = E_SUCCESS;
1708 CaCertRecord certRecord = {0, };
1709 UserCertRecord userCertRecord = {0, };
1710 _CertificateListInfo* pHoldList = null;
1713 EVP_PKEY* pKey = null;
1715 int recordCount = 0;
1716 int subjectNameBase64Len = 0;
1722 int certificateBase64Len = 0;
1723 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1724 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1725 byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1726 byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1727 byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1728 bool isIssuerNameInList = false;
1730 subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1731 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1732 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1733 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1735 if ((pSubjectName != null) && (subjectNameLen > 0))
1737 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1738 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1739 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1740 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1741 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1745 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1746 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1747 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1748 snprintf(condition, sizeof(condition), "installed = '%s'", installedRecord);
1751 memset(&userCertRecord, 0, sizeof(userCertRecord));
1752 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1753 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1755 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
1756 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1759 std::unique_ptr< _CertFileStore > pFileStore(new (std::nothrow) _CertFileStore());
1760 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1762 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
1763 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1765 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1767 pCertList->pNext = null;
1769 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1770 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1772 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1773 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1774 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1776 if (encodingType == _CERT_ENC_TYPE_PEM)
1778 const byte* pCertBuffer = pCertList->certificate;
1780 pBio = BIO_new(BIO_s_mem());
1781 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1783 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1784 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1786 readLength = PEM_write_bio_X509(pBio, pCert);
1787 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1789 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1791 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1792 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1794 pCertList->length = readLength;
1803 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1805 int certLen = _Base64::GetEncodedSize(pCertList->length);
1806 SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_SYSTEM, "Certificate length is invalid.");
1807 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1808 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1809 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1811 pCertList->length = certLen;
1814 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1815 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1817 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1818 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1819 pCertList->certFileId = userCertRecord.certId;
1821 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1822 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1826 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1827 if (!IsFailed(r) && priKeyLen != 0)
1829 byte* pPrivateTempKey = null;
1830 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1831 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1833 pPrivateKey.reset(null);
1836 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1837 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1839 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
1841 if (encodingType == _CERT_ENC_TYPE_PEM)
1843 const byte* pKeyBuffer = pPrivateKey.get();
1844 pBio = BIO_new(BIO_s_mem());
1845 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1847 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1848 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1850 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1851 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1853 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1855 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1857 pCertList->priKeyLen = readLength;
1865 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1867 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1868 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1870 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1871 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1875 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1876 pCertList->priKeyLen = priKeyLen;
1880 pPrivateKey.reset(null);
1882 pHoldList = pCertList.release();
1883 *ppCertListInfoTypes = pHoldList;
1887 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1888 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1889 subNameLen = userCertRecord.issuerNameLen;
1893 subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1894 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1895 r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1896 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1897 snprintf(condition, sizeof(condition), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1899 if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1901 isIssuerNameInList = true;
1904 memset(&certRecord, 0, sizeof(certRecord));
1905 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1906 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1908 if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1910 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo());
1911 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1913 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1914 pCertList->pNext = null;
1916 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1917 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1919 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1920 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1921 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1923 if (encodingType == _CERT_ENC_TYPE_PEM)
1925 const byte* pCertBuffer = pCertList->certificate;
1927 pBio = BIO_new(BIO_s_mem());
1928 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1930 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1931 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1933 readLength = PEM_write_bio_X509(pBio, pCert);
1934 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1936 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1938 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1939 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1941 pCertList->length = readLength;
1949 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1951 int certLen = _Base64::GetEncodedSize(pCertList->length);
1952 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1953 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1954 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1955 pCertList->length = certLen;
1957 pCertList->format = (_CertFormat) certRecord.certFormat;
1958 pCertList->certType = (_CaCertType) certRecord.certType;
1959 pCertList->certFileId = certRecord.certId;
1961 pHoldList->pNext = pCertList.release();
1962 pHoldList = pHoldList->pNext;
1966 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1967 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1968 subNameLen = certRecord.issuerNameLen;
1972 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1974 if (!isIssuerNameInList)
1976 if (*ppCertListInfoTypes != null)
1978 _CertService::FreeCertList(*ppCertListInfoTypes);
1979 *ppCertListInfoTypes = null;
1982 memset(condition, 0, sizeof(condition));
1983 snprintf(condition, sizeof(condition), "installed = '%s'", installedRecord);
1987 memset(&userCertRecord, 0, sizeof(userCertRecord));
1988 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1989 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1991 curCertId = userCertRecord.certId;
1993 for (readLength = 0; readLength < count; readLength++)
1996 memset(&userCertRecord, 0, sizeof(userCertRecord));
1997 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1998 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1999 curCertId = userCertRecord.certId;
2004 while (isIssuerNameInList != true);
2017 EVP_PKEY_free(pKey);
2024 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2026 result r = E_SUCCESS;
2027 UserCertRecord userCertRecord = {0, };
2028 CaCertRecord caCertRecord = {0, };
2029 int subjNameB64len = 0;
2031 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2032 char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2033 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2035 subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2036 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2037 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2038 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2039 snprintf(conditonRecord, sizeof(conditonRecord), "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2041 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2042 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2044 if (pPrivateKeyInfo != null)
2046 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2049 r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2050 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2052 parentCa = userCertRecord.parentCa;
2056 memset(&caCertRecord, 0, sizeof(caCertRecord));
2057 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2058 snprintf(conditonRecord, sizeof(conditonRecord), "certId = %d and installed = '%s'", parentCa, installedRecord);
2060 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2061 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2063 parentCa = caCertRecord.parentCa;
2064 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2066 r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2067 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2071 while (caCertRecord.certId != caCertRecord.parentCa);
2077 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2079 result r = E_SUCCESS;
2080 UserCertRecord userCertRecord = {0, };
2081 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2082 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2084 snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installedRecord);
2086 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2087 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2089 *pSubjectLength = userCertRecord.subjectNameLen;
2090 memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2091 *pIssuerLength = userCertRecord.issuerNameLen;
2092 memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2099 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2101 result r = E_SUCCESS;
2102 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2103 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2106 int certBufferLen = 0;
2107 int keyBufferLen = 0;
2108 int certificateBase64Len = 0;
2109 const byte* pCertBuffer = null;
2110 const byte* pKeyBuffer = null;
2111 byte* pPrivateTempKey = null;
2112 UserCertRecord certRecord = {0, };
2113 _CertFileStore fileStore;
2114 std::unique_ptr< _CertPrivateKeyInfo > pPriKey;
2117 EVP_PKEY* pKey = null;
2119 *ppUserCertInfo = null;
2121 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2122 snprintf(condition, sizeof(condition), "certId = %d and installed = '%s'", certId, installedRecord);
2124 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2125 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2127 std::unique_ptr< _CertInfo > pCertInfo(new (std::nothrow) _CertInfo);
2128 SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2130 memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2132 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2133 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2135 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2136 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2137 certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2139 if (encodingType == _CERT_ENC_TYPE_PEM)
2141 pBio = BIO_new(BIO_s_mem());
2142 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2144 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2145 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2147 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2148 certBufferLen = pCertInfo->certLength;
2150 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2151 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2153 readCount = PEM_write_bio_X509(pBio, pCert);
2154 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2156 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2157 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2158 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2160 pCertInfo->certLength = readCount;
2162 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2164 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2165 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2166 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2167 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2168 pCertInfo->certLength = certLen;
2170 pCertInfo->certId = certRecord.certId;
2171 pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2172 pCertInfo->certType = _CERT_TYPE_USER_CERT;
2174 if (certRecord.prvKeyLen > 0)
2176 pPriKey = std::unique_ptr< _CertPrivateKeyInfo >(new (std::nothrow) _CertPrivateKeyInfo());
2177 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2179 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2180 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2182 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2183 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2184 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2186 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2187 if (!IsFailed(r) && priKeyLen != 0)
2189 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2191 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2195 pPrivateKey.reset(null);
2197 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2198 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2200 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
2202 if (encodingType == _CERT_ENC_TYPE_PEM)
2206 pBio = BIO_new(BIO_s_mem());
2207 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2209 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2210 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2212 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2213 keyBufferLen = priKeyLen;
2215 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2216 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2218 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2220 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2221 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2223 pCertInfo->privateKeyLen = readCount;
2225 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2227 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2228 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2229 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2230 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2235 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2236 pCertInfo->privateKeyLen = priKeyLen;
2241 *ppUserCertInfo = pCertInfo.release();
2245 if (encodingType == _CERT_ENC_TYPE_PEM)
2249 EVP_PKEY_free(pKey);
2256 } } } //Tizen::Security::Cert