2 // Open Service Platform
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
19 * @file FSecCert_CertDbManager.cpp
20 * @brief This file contains implementation of X509 Certificate Db Manager APIs.
31 #include <openssl/evp.h>
32 #include <openssl/pem.h>
33 #include <unique_ptr.h>
36 #include <FBaseSysLog.h>
37 #include <FBaseByteBuffer.h>
38 #include <FBaseResult.h>
39 #include <FBase_StringConverter.h>
40 #include "FSecCert_CertDbStore.h"
41 #include "FSecCert_CertFileStore.h"
42 #include "FSecCert_CertDbManager.h"
43 #include "FSecCert_Base64.h"
44 #include "FSecCert_CertService.h"
45 #include "FSecCert_CertManager.h"
47 using namespace Tizen::Base;
48 using namespace Tizen::Io;
50 namespace Tizen { namespace Security { namespace Cert
52 _CertDbManager* _CertDbManager::__pCertDb = null;
54 _CertDbManager::_CertDbManager(void)
58 _CertDbManager::~_CertDbManager(void)
63 _CertDbManager::Construct(void)
65 static _CertDbManager certDb;
71 _CertDbManager::GetInstance(void)
73 static pthread_once_t once_block = PTHREAD_ONCE_INIT;
74 if (__pCertDb == null)
76 pthread_once(&once_block, Construct);
83 _CertDbManager::CreateCertificateTables(void)
87 r = __caCertDbStore.CreateCertificateTables();
88 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database.");
94 _CertDbManager::IsCertificateTablesCreated(void)
98 r = __caCertDbStore.IsRootCaCertTableCreated();
101 SetLastResult(E_SYSTEM);
105 r = __userCertDbStore.IsUserCertTableCreated();
108 SetLastResult(E_SYSTEM);
116 _CertDbManager::ResetCertificateTables(void)
118 result r = E_SUCCESS;
120 r = __caCertDbStore.DropCertificateTables();
121 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database.");
123 r = __caCertDbStore.CreateCertificateTables();
124 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database.");
130 _CertDbManager::RemoveCertificateTables(void)
132 result r = E_SUCCESS;
133 r = __caCertDbStore.DropCertificateTables();
134 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
139 _CertDbManager::RemoveCaCertificateByType(_CaCertType certType)
141 result r = E_SUCCESS;
142 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
143 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
145 sprintf(condition, "certType = %d and installed = '%s'", certType, installed);
147 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
148 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
154 _CertDbManager::RemoveUserCertificateByCertId(int certId)
156 result r = E_SUCCESS;
157 _CertFileStore fileStore;
161 r = __userCertDbStore.RemoveCertificateById(certId);
162 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete user certificate in database.");
166 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, certFileName);
167 Tizen::Io::File::Remove(certFileName);
168 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyName);
169 Tizen::Io::File::Remove(keyName);
175 _CertDbManager::RemoveUserCaCertificateByCertId(int certId)
177 result r = E_SUCCESS;
178 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
179 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
181 sprintf(condition, "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed);
182 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
183 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
189 _CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
191 return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false);
195 _CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity)
197 result r = E_SUCCESS;
199 CaCertRecord certRecord = {0, };
200 _CertFileStore fileStore;
201 _CertFormat certBufFormat = _CERT_UNKNOWN;
202 _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
203 int lenSubjectName = 0;
204 int lenIssuerName = 0;
207 int derCertBufferLength = 0;
208 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
209 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
210 char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
211 char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
212 byte* pDerCert = null;
213 byte* pSerial = null;
214 _X509TbsCert* pTbsCert = null;
216 r = __caCertDbStore.IsRootCaCertTableCreated();
217 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
219 std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate());
220 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
222 certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType);
223 std::unique_ptr <byte[]> pDerCertBuffer(pDerCert);
225 SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer.");
226 SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format.");
227 SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length.");
229 r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
230 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
232 pTbsCert = pCert->GetTbsCertInstance();
233 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null,E_SYSTEM, "Failed to get certificate to be signed instance.");
235 lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
236 lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
238 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE,E_SYSTEM, "Subject name is more then maximum specified length.");
239 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
241 strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
242 strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
244 pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo));
245 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
247 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
252 memcpy(serialName, pSerial, lenSerialNo);
257 if (pCert->IsSelfSigned())
259 r = pCert->VerifySignature(null, 0);
260 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data.");
262 #ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE
263 //Open this code - if u want to support installation of Intermediate CA Certificate with verification using this API.(ideally it should check if installing intermediate CA) (09082011)
264 else if (pCert->IsCaCertificate())
266 std::unique_ptr <_CertChain> pCertChain (new (std::nothrow) _CertChain());
267 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
269 r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength);
270 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed.");
272 r = pCertChain->MoveHead();
273 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed.");
276 // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id
277 //(there are ECC certificate installation which we support for china model. hence these comments)
278 r = pCertChain->VerifyCertChainWithDb();
279 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain.");
283 #ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE
284 //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check)
287 return E_UNSUPPORTED_OPERATION;
293 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName);
296 return E_FILE_ALREADY_EXIST;
298 //Get the last installed certificate id from db table
299 __caCertDbStore.GetCurrentCertId(certId);
300 //Calculate the new (std::nothrow) certificate id for installation
302 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
304 memset(&certRecord, 0, sizeof(certRecord));
305 certRecord.certType = static_cast< int >(certType);
306 certRecord.certFormat = static_cast< int >(certFormat);
308 std::unique_ptr <char[]> pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
309 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
311 strcpy(certRecord.fileName, pFileName.get());
313 certRecord.subjectNameLen = lenSubjectName;
314 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
315 certRecord.issuerNameLen = lenIssuerName;
316 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
317 certRecord.parentCa = certId;
318 strcpy(certRecord.installed, installed);
319 memcpy(certRecord.serialNo, serialName, lenSerialNo);
320 certRecord.serialNoLen = lenSerialNo;
322 r = __caCertDbStore.InsertCaCertificate(&certRecord);
323 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
325 fileStore.SetFilePath(tempFileName);
327 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
328 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
335 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
337 result r = E_SUCCESS;
339 CaCertRecord certRecord = {0, };
340 CaCertRecord certRecord1 = {0, };
341 _CertFileStore fileStore;
342 _X509TbsCert* pTbsCert = null;
343 _X509TbsCert* pNewTbsCert = null;
344 int lenSubjectName = 0;
345 int lenNewSubjectName = 0;
346 int lenIssuerName = 0;
347 int lenNewIssuerName = 0;
348 int lenNewSerialNo = 0;
350 int subjNameB64len = 0;
351 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
352 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
353 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
354 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
355 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
356 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
357 byte* pNewSerial = null;
359 r = __caCertDbStore.IsRootCaCertTableCreated();
360 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
362 std::unique_ptr<_X509Certificate> pCert (new (std::nothrow) _X509Certificate());
363 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
365 r = pCert->Parse(pCurCertBuf, curCertLen);
366 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
368 pTbsCert = pCert->GetTbsCertInstance();
369 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
371 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
372 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
374 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
375 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
377 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
378 if (!IsFailed(r)) //checkit
380 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
381 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
383 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
385 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
386 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
388 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
389 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
390 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
392 certId = certRecord.parentCa;
394 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
395 fileStore.SetFilePath(tempFileName);
397 if (certFormat == _CERT_X509)
399 std::unique_ptr <_X509Certificate> pNewCert(new (std::nothrow) _X509Certificate());
400 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
402 r = pNewCert->Parse(pNewCertBuf, newCertLen);
403 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
405 pNewTbsCert = pNewCert->GetTbsCertInstance();
406 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
408 strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
409 strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName())));
411 lenNewSubjectName = strlen(newSubjectName);
412 lenNewIssuerName = strlen(newIssuerName);
414 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
415 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
417 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
423 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
426 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
427 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
429 certRecord1.certType = static_cast< int >(certType);
430 certRecord1.certFormat = static_cast< int >(certFormat);
432 std::unique_ptr <char[]> pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
433 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
435 strcpy(certRecord1.fileName, pFileName.get());
437 certRecord1.subjectNameLen = lenNewSubjectName;
438 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
439 certRecord1.issuerNameLen = lenIssuerName;
440 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
441 certRecord1.parentCa = certId;
442 strcpy(certRecord1.installed, certRecord.installed);
443 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
444 certRecord1.serialNoLen = lenNewSerialNo;
446 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
447 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
449 fileStore.DeleteFile();
451 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
452 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
453 //No need to update record as only file data changed.
458 return E_FILE_ALREADY_EXIST;
465 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
467 result r = E_SUCCESS;
468 _X509TbsCert* pTbsCert = null;
470 _CertFileStore fileStore;
473 //Check certType missing
475 r = __caCertDbStore.IsRootCaCertTableCreated();
476 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
478 std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate());
479 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
481 r = pCert->Parse(pCertBuf, certLen);
482 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
484 pTbsCert = pCert->GetTbsCertInstance();
485 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
487 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
488 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db.");
490 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
491 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
493 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
496 r = __caCertDbStore.RemoveCertificateById(certId);
497 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
500 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
501 Tizen::Io::File::Remove(fileName);
508 _CertDbManager::RemoveCertificateChainByCertId(int certId)
510 result r = E_SUCCESS;
511 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
512 UserCertRecord userCertRecord = {0, };
514 memset(&userCertRecord, 0, sizeof(userCertRecord));
515 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
517 sprintf(condition, "certId = %d", certId);
518 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
519 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
520 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
522 r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
523 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
530 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
532 result r = E_SUCCESS;
533 int subjNameB64len = 0;
534 int issuerB64len = 0;
535 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
536 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
537 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
538 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
539 CaCertRecord caCertRecord = {0, };
541 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
542 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
544 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
545 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
547 r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
548 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
550 memset(condition, 0, sizeof(condition));
552 if (pIssuerName != null && issuerNameSize > 0)
554 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
555 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
557 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
558 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
560 if (certType == _CERT_TYPE_NOT_BOUNDED)
562 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
566 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
571 if (certType == _CERT_TYPE_NOT_BOUNDED)
573 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
577 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
581 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
582 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
584 certId = caCertRecord.certId;
590 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
592 result r = E_SUCCESS;
593 int subjNameB64len = 0;
594 int issuerB64len = 0;
595 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
596 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
597 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
598 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
599 UserCertRecord userCertRecord = {0, };
601 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
602 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
604 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
605 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
607 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
608 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
610 memset(condition, 0, sizeof(condition));
612 if (pIssuerName != null && issuerNameSize > 0)
614 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
615 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
617 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
618 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
620 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
624 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
627 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
628 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
630 certId = userCertRecord.certId;
636 _CertDbManager::RemoveAllUserCertificate(void)
638 __userCertDbStore.DeleteUserCertFiles();
644 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
646 result r = E_SUCCESS;
647 CaCertRecord certRecord = {0, };
651 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
652 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
655 SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
656 SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
658 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
660 sprintf(condition, "parentCa = %d and installed = '%s'", devParentCA, installed);
661 //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
662 //delete only device certificate and return. We cannot disturb another chain.
663 __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
664 //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
667 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
668 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
672 //Now there is not two device certificate with same intermidiate CA,
673 //so go ahead to intermidiate CA and delete device certificate.
674 caParentCa = devParentCA;
675 caCertId = devCertId;
678 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
682 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
683 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
685 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
686 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
687 break; // break here next certificate has dependency
691 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
692 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
694 break; // break here next certificate has dependency
697 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
699 if (devCert) //If it is device certificate
701 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
702 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
704 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
705 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
707 else //If it is CA certificate and there is no dependency
709 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
710 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
712 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
714 caCertId = caParentCa; // Now look for next certificate in chain
715 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
716 sprintf(condition, "certId = %d and installed = '%s'", devParentCA, installed);
717 memset(&certRecord, 0, sizeof(certRecord));
718 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
719 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
720 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
722 caParentCa = certRecord.parentCa;
725 while (caCertId != caParentCa);
731 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
733 result r = E_SUCCESS;
734 CaCertRecord certRecord = {0, };
735 _CertificateListInfo* pHoldList = null;
736 _CertFileStore fileStore;
739 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
740 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
742 sprintf(condition, "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
744 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
745 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
746 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
748 std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
749 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
751 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
752 pCertList->pNext = null;
753 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
754 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
756 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
757 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
759 pCertList->length = certLength;
760 pCertList->certFileId = certRecord.certId;
761 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
762 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
765 pHoldList = pCertList.release();
766 *ppCertList = pHoldList;
768 while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
770 std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
771 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
773 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
775 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
776 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
778 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
779 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
781 pCertList->pNext = null;
782 pCertList->length = certLength;
783 pCertList->certFileId = certRecord.certId;
784 pCertList->format = (_CertFormat) certRecord.certFormat;
785 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
787 pHoldList->pNext = pCertList.release();
788 pHoldList = pHoldList->pNext;
800 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
802 result r = E_SUCCESS;
803 UserCertRecord certRecord = {0, };
804 _CertificateListInfo* pHoldList = null;
805 _CertFileStore fileStore;
808 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
809 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
813 sprintf(condition, "certFormat = %d and installed = '%s'", certFormat, installed);
815 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
816 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
817 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
819 std::unique_ptr<_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
820 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
822 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
823 pCertList->pNext = null;
825 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
826 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
828 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
829 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
831 pCertList->length = certLength;
832 pCertList->certFileId = certRecord.certId;
833 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
834 pCertList->certType = _CERT_TYPE_USER_CERT;
837 pHoldList = pCertList.release();
838 *ppCertList = pHoldList;
840 while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
842 std::unique_ptr<_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
843 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
845 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
847 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
848 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
850 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
851 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
853 pCertList->pNext = null;
854 pCertList->length = certLength;
855 pCertList->certFileId = certRecord.certId;
856 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
857 pCertList->certType = _CERT_TYPE_USER_CERT;
859 pHoldList->pNext = pCertList.release();
860 pHoldList = pHoldList->pNext;
871 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
873 result r = E_SUCCESS;
874 CaCertRecord certRecord = {0, };
875 _CertFileStore fileStore;
877 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
878 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
881 sprintf(condition, "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
883 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
884 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
886 std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
887 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
889 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
891 pCertList->pNext = null;
892 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
893 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
895 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
896 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
898 pCertList->length = certLength;
899 pCertList->certFileId = certRecord.certId;
900 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
901 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
903 *ppCertList = pCertList.release();
909 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
911 result r = E_SUCCESS;
912 _CertFileStore fileStore;
913 UserCertRecord certRecord = {0, };
916 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
917 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
921 SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
922 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
924 sprintf(condition, "certId = %d and installed = '%s'", certId, installed);
925 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
926 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
928 std::unique_ptr <_CertificateListInfo> pCertList (new (std::nothrow) _CertificateListInfo);
929 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
931 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
933 pCertList->pNext = null;
935 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
936 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
938 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
939 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
941 pCertList->length = certLength;
942 pCertList->certFileId = certRecord.certId;
943 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
944 pCertList->certType = _CERT_TYPE_USER_CERT;
946 std::unique_ptr <_CertPrivateKeyInfo> pPriKey (new (std::nothrow) _CertPrivateKeyInfo());
947 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
949 std::unique_ptr <byte[]> pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
950 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
952 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
954 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
955 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
957 r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
958 if (!IsFailed(r) && priKeyLen != 0)
960 byte* pPrivateTempKey = null;
961 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
963 pPrivateKey.reset(null);
965 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
966 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
968 std::unique_ptr<byte[]> pPrivateKeyAuto(pPrivateTempKey);
970 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
972 pCertList->priKeyLen = priKeyLen;
974 *ppCertList = pCertList.release();
980 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
982 result r = E_SUCCESS;
983 CaCertRecord certRecord = {0, };
984 _CertFileStore fileStore;
986 int issuerNameB64len = 0;
987 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
988 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
989 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
991 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
992 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
993 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
995 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
996 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
998 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1000 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1001 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1003 sprintf(condition, "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
1005 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1006 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1008 filePath = reinterpret_cast< char* >(certRecord.fileName);
1010 fileStore.SetFilePath(filePath);
1012 *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
1013 SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1015 r = fileStore.ReadFromFile(*ppCert, certLen);
1016 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1018 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1024 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1026 result r = E_SUCCESS;
1028 CaCertRecord certRecord = {0, };
1029 _CertFileStore fileStore;
1030 int issuerNameB64len = 0;
1031 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1032 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1033 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1035 SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1036 SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1037 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1038 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1039 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1041 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1042 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1044 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1046 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1047 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1049 sprintf(condition, "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1050 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1051 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1053 if (certRecord.certId == 0)
1058 filePath = static_cast< char* >(certRecord.fileName);
1059 fileStore.SetFilePath(filePath);
1061 std::unique_ptr <byte[]> pCert (new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1062 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1064 r = fileStore.ReadFromFile(pCert.get(), certLen);
1065 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1067 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1069 *ppCert = pCert.release();
1075 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1077 result r = E_SUCCESS;
1078 CaCertRecord certRecord = {0, };
1079 _CertFileStore fileStore;
1080 int subjectNameB64len = 0;
1081 int issuerNameB64len = 0;
1082 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1083 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1084 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1085 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1087 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1088 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1089 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1090 SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1092 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1093 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1095 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1097 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1098 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1100 subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1101 SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1103 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1104 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1105 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1107 sprintf(condition, "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1108 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1109 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1111 *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1116 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1118 result r = E_SUCCESS;
1119 _CertFileStore fileStore;
1122 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1124 if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1128 r = __userCertDbStore.RemoveCertificateById(certId);
1129 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1131 //Remove certificate file
1132 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1133 r = Tizen::Io::File::Remove(fileName);
1134 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1136 //Remove private key file
1137 //Don't check return type here as it is not necessary that private key is present.
1138 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1139 r = Tizen::Io::File::Remove(keyfileName);
1141 else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1143 r = __caCertDbStore.RemoveCertificateById(certId);
1144 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1146 //Remove certificate file
1147 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1148 r = Tizen::Io::File::Remove(fileName);
1149 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1155 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1157 result r = E_SUCCESS;
1158 String fileName(reinterpret_cast< char* >(pFilePath));
1159 FileAttributes attr;
1164 int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1167 SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1168 SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1169 SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1171 r = File::GetAttributes(fileName, attr);
1172 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1174 fileSize = attr.GetFileSize();
1175 SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1176 SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1179 r = file.Construct(fileName, L"r");
1180 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1182 std::unique_ptr <byte[]> pCertBuf (new (std::nothrow) byte[fileSize + 1]);
1183 SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1185 memset(pCertBuf.get(), 0, fileSize + 1);
1186 readCnt = file.Read(pCertBuf.get(), fileSize);
1187 r = GetLastResult();
1188 SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1191 std::unique_ptr <byte[]> pOutBuf (new (std::nothrow) byte[outLen]);
1192 SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1194 memset(pOutBuf.get(), 0, outLen);
1195 //As per OpenSSL APIs, it takes input as unsigned data types
1196 resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1197 SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1199 memcpy(pBuf, pOutBuf.get(), outLen);
1205 //User Certificate APIs
1208 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1210 result r = E_SUCCESS;
1211 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1212 int curCACertId = 0;
1213 int lastCACertId = 0;
1214 int curDevCertId = 0;
1215 bool updateUserParentCa = false;
1217 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1218 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1220 //Check for CA certificate table creation
1221 r = __caCertDbStore.IsRootCaCertTableCreated();
1222 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1225 //Check if the chain is valid or not
1226 r = pCertChain->Verify();
1227 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1229 r = pCertChain->MoveHead();
1230 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1232 if (certFormat == _CERT_X509)
1234 _X509Certificate* pCurCert = null;
1235 _X509Certificate* pUserCert = null;
1236 _X509TbsCert* pTbsCert = null;
1237 byte* pX509Buff = null;
1238 int x509BuffSize = 0;
1240 pUserCert = pCertChain->GetCurrentCertificate();
1241 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1243 pTbsCert = pUserCert->GetTbsCertInstance();
1244 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1246 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1247 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1249 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1250 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed insert user certificate chain.", GetErrorMessage(r));
1252 updateUserParentCa = true;
1254 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1255 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1257 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1259 //Insert certificate chain in CA certificate store
1260 while (pCertChain->MoveNext() == E_SUCCESS)
1263 pCurCert = pCertChain->GetCurrentCertificate();
1264 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1266 if (!pCurCert->IsSelfSigned())
1268 certType = _CERT_TYPE_INTERMIDIATE_CA;
1272 //This parameter need to pass from certificate manager about its type
1273 certType = _CERT_TYPE_ROOT_CA;
1276 pTbsCert = pCurCert->GetTbsCertInstance();
1277 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1279 if (E_SUCCESS != __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()))))
1284 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1285 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1287 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1288 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1290 // CA certificate already present or properly installed in CA certificate store,
1291 // get the certificate id of certificate
1292 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1293 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1294 curCACertId, certType);
1295 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1297 if (updateUserParentCa)
1299 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1300 updateUserParentCa = false;
1301 lastCACertId = curCACertId;
1305 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1306 lastCACertId = curCACertId;
1309 //If it is root certificate then its parent is itself
1310 if (pCurCert->IsSelfSigned())
1312 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1317 if (updateUserParentCa)
1319 r = pCertChain->MoveHead();
1320 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1322 pCurCert = pCertChain->GetCurrentCertificate();
1323 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1325 pTbsCert = pCurCert->GetTbsCertInstance();
1326 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1328 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1329 null, 0, curCACertId);
1330 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1332 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1333 updateUserParentCa = false;
1334 lastCACertId = curCACertId;
1336 else if (!pCurCert->IsSelfSigned())
1338 pTbsCert = pCurCert->GetTbsCertInstance();
1339 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1341 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1342 null, 0, curCACertId);
1343 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1345 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1346 lastCACertId = curCACertId;
1354 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1356 result r = E_SUCCESS;
1357 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1359 int curCACertId = 0;
1360 int lastCACertId = 0;
1361 int curDevCertId = 0;
1363 bool updateUserParentCa = false;
1364 byte* pPrvKey = null;
1365 std::unique_ptr <byte[]> pPrvKeyBuffer;
1367 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1368 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1370 r = __userCertDbStore.IsUserCertTableCreated();
1371 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1373 //Check for CA certificate table creation
1374 r = __caCertDbStore.IsRootCaCertTableCreated();
1375 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1377 //Check if the chain is valid or not
1378 r = pCertChain->Verify();
1379 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1381 r = pCertChain->MoveHead();
1382 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1384 if (certFormat == _CERT_X509)
1386 _X509Certificate* pCurCert = null;
1387 _X509Certificate* pUserCert = null;
1388 _X509TbsCert* pTbsCert = null;
1389 byte* pX509Buff = null;
1390 int x509BuffSize = 0;
1392 pUserCert = pCertChain->GetCurrentCertificate();
1393 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1395 pTbsCert = pUserCert->GetTbsCertInstance();
1396 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1398 byte* pSubjectName = pTbsCert->GetSubjectName();
1399 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1401 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1403 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1406 if (pPrivateKeyInfo != null)
1408 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1409 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1411 pPrvKeyBuffer = std::unique_ptr <byte[]> (pPrvKey);
1416 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1417 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1419 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1420 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1426 updateUserParentCa = true;
1428 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1429 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1431 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1433 if (pPrvKeyBuffer != null)
1435 _CertFileStore fileStore;
1436 String privateKeyFile;
1438 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1439 fileStore.SetFilePath(privateKeyFile);
1442 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1443 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1453 //Insert certificate chain in CA certificate store
1454 while (pCertChain->MoveNext() == E_SUCCESS)
1456 pCurCert = pCertChain->GetCurrentCertificate();
1457 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1459 if (!pCurCert->IsSelfSigned())
1461 certType = _CERT_TYPE_INTERMIDIATE_CA;
1465 //This parameter need to pass from certificate manager about its type
1466 certType = _CERT_TYPE_ROOT_CA;
1469 pTbsCert = pCurCert->GetTbsCertInstance();
1470 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1472 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1478 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1479 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1481 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1482 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1485 // CA certificate already present or properly install in CA certificate store,
1486 // get the certificate id of certificate
1488 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1489 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1490 curCACertId, certType);
1491 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1493 if (updateUserParentCa)
1495 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1496 updateUserParentCa = false;
1497 lastCACertId = curCACertId;
1501 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1502 lastCACertId = curCACertId;
1505 //If it is root certificate then its parent is itself
1506 if (pCurCert->IsSelfSigned())
1508 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1512 if (updateUserParentCa)
1514 r = pCertChain->MoveHead();
1515 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1517 pCurCert = pCertChain->GetCurrentCertificate();
1518 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1520 pTbsCert = pCurCert->GetTbsCertInstance();
1521 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1523 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1524 null, 0, curCACertId);
1525 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1527 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1528 updateUserParentCa = false;
1529 lastCACertId = curCACertId;
1531 else if (!pCurCert->IsSelfSigned())
1533 pTbsCert = pCurCert->GetTbsCertInstance();
1534 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1536 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1537 null, 0, curCACertId);
1538 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1540 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1541 lastCACertId = curCACertId;
1549 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1551 result r = E_SUCCESS;
1552 _X509TbsCert* pTbsCert = null;
1553 _CertFileStore fileStore;
1554 UserCertRecord certRecord = {0, };
1555 String privateKeyFile;
1556 String tempFileName;
1557 int lenSubjectName = 0;
1558 int lenIssuerName = 0;
1559 int lenSerialNo = 0;
1561 int keyIdB64Length = 0;
1562 char* pFileName = null;
1563 char* pPriKeyFileName = null;
1564 char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1565 char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1566 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1567 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1568 byte* pKeyId = null;
1569 byte* pSerial = null;
1571 //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1572 SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1573 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1574 SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1576 r = __userCertDbStore.IsUserCertTableCreated();
1577 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1579 std::unique_ptr <_X509Certificate> pCert (new (std::nothrow) _X509Certificate());
1580 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1582 r = pCert->Parse(pCertBuffer, certLength);
1583 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1585 pTbsCert = pCert->GetTbsCertInstance();
1586 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1588 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1589 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1591 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1592 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1594 strcpy(subjectNameBuffer, reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1595 strcpy(szIssuerName, reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1597 pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1598 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1600 if (pSerial != null)
1602 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1608 memcpy(serialName, pSerial, lenSerialNo);
1612 r = pCert->GetKeyIdN(&pKeyId);
1613 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1615 std::unique_ptr <byte[]> pKeyIdBuffer (pKeyId);
1617 keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1618 SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1620 std::unique_ptr <char[]> pId64 (new (std::nothrow) char[keyIdB64Length]);
1621 SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1623 memset(pId64.get(), 0, keyIdB64Length);
1624 r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1625 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1627 r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1628 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1630 //Get the last installed certificate id from db table
1631 __userCertDbStore.GetCurrentCertId(certId);
1633 //Calculate the new certificate id for installation
1634 certId = certId + 1;
1636 if (pPrivateKey != null)
1638 //Get file name for private key and store private key into file.
1639 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1643 pPriKeyFileName = null;
1647 //Get file name for certificate and write device certificate to file
1648 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1650 //Insert Record into Database
1651 //It is generated automatically by sequence
1652 memset(&certRecord, 0, sizeof(certRecord));
1654 memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1655 certRecord.certFormat = static_cast< int >(certFormat);
1657 pFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName);
1658 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1660 strcpy(certRecord.fileName, pFileName);
1661 certRecord.subjectNameLen = lenSubjectName;
1663 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1664 certRecord.issuerNameLen = lenIssuerName;
1665 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1667 pPriKeyFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile);
1668 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1670 strcpy(certRecord.prvKeyPath, pPriKeyFileName);
1671 certRecord.prvKeyLen = privateKeyLen;
1672 certRecord.parentCa = certId;
1673 strcpy(certRecord.installed, installedRecord);
1675 memcpy(certRecord.serialNo, serialName, lenSerialNo);
1677 certRecord.serialNoLen = lenSerialNo;
1679 r = __userCertDbStore.InsertUserCertificate(&certRecord);
1680 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1682 fileStore.SetFilePath(tempFileName);
1684 r = fileStore.WriteToFile(pCertBuffer, certLength);
1685 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1687 if (pPrivateKey != null)
1689 fileStore.SetFilePath(privateKeyFile);
1691 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1692 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1699 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1701 result r = E_SUCCESS;
1702 CaCertRecord certRecord = {0, };
1703 UserCertRecord userCertRecord = {0, };
1704 _CertificateListInfo* pHoldList = null;
1707 EVP_PKEY* pKey = null;
1709 int recordCount = 0;
1710 int subjectNameBase64Len = 0;
1716 int certificateBase64Len = 0;
1717 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1718 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1719 byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1720 byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1721 byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1722 bool isIssuerNameInList = false;
1724 subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1725 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1726 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1727 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1729 if ((pSubjectName != null) && (subjectNameLen > 0))
1731 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1732 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1733 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1734 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1735 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1739 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1740 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1741 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1742 sprintf(condition, "installed = '%s'", installedRecord);
1745 memset(&userCertRecord, 0, sizeof(userCertRecord));
1746 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1747 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1749 std::unique_ptr <_CertPrivateKeyInfo> pPriKey (new (std::nothrow) _CertPrivateKeyInfo());
1750 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1753 std::unique_ptr <_CertFileStore> pFileStore (new (std::nothrow) _CertFileStore());
1754 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1756 std::unique_ptr<_CertificateListInfo> pCertList(new (std::nothrow) _CertificateListInfo);
1757 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1759 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1761 pCertList->pNext = null;
1763 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1764 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1766 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1767 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1768 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1770 if (encodingType == _CERT_ENC_TYPE_PEM)
1772 const byte* pCertBuffer = pCertList->certificate;
1774 pBio = BIO_new(BIO_s_mem());
1775 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1777 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1778 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1780 readLength = PEM_write_bio_X509(pBio, pCert);
1781 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1783 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1785 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1786 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1788 pCertList->length = readLength;
1797 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1799 int certLen = _Base64::GetEncodedSize(pCertList->length);
1800 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1801 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1802 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1804 pCertList->length = certLen;
1807 std::unique_ptr <byte[]> pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1808 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1810 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1811 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1812 pCertList->certFileId = userCertRecord.certId;
1814 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1815 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1819 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1820 if (!IsFailed(r) && priKeyLen != 0)
1822 byte* pPrivateTempKey = null;
1823 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1824 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1826 pPrivateKey.reset(null);
1829 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1830 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1832 pPrivateKey = std::unique_ptr<byte[]>(pPrivateTempKey);
1834 if (encodingType == _CERT_ENC_TYPE_PEM)
1836 const byte* pKeyBuffer = pPrivateKey.get();
1837 pBio = BIO_new(BIO_s_mem());
1838 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1840 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1841 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1843 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1844 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1846 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1848 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1850 pCertList->priKeyLen = readLength;
1858 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1860 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1861 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1863 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1864 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1868 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1869 pCertList->priKeyLen = priKeyLen;
1873 pPrivateKey.reset(null);
1875 pHoldList = pCertList.release();
1876 *ppCertListInfoTypes = pHoldList;
1880 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1881 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1882 subNameLen = userCertRecord.issuerNameLen;
1886 subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1887 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1888 r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1889 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1890 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1892 if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1894 isIssuerNameInList = true;
1897 memset(&certRecord, 0, sizeof(certRecord));
1898 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1899 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1901 if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1903 std::unique_ptr<_CertificateListInfo> pCertList(new (std::nothrow) _CertificateListInfo());
1904 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1906 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1907 pCertList->pNext = null;
1909 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1910 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1912 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1913 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1914 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1916 if (encodingType == _CERT_ENC_TYPE_PEM)
1918 const byte* pCertBuffer = pCertList->certificate;
1920 pBio = BIO_new(BIO_s_mem());
1921 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1923 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1924 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1926 readLength = PEM_write_bio_X509(pBio, pCert);
1927 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1929 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1931 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1932 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1934 pCertList->length = readLength;
1942 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1944 int certLen = _Base64::GetEncodedSize(pCertList->length);
1945 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1946 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1947 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r),E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1948 pCertList->length = certLen;
1950 pCertList->format = (_CertFormat) certRecord.certFormat;
1951 pCertList->certType = (_CaCertType) certRecord.certType;
1952 pCertList->certFileId = certRecord.certId;
1954 pHoldList->pNext = pCertList.release();
1955 pHoldList = pHoldList->pNext;
1959 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1960 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1961 subNameLen = certRecord.issuerNameLen;
1965 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1967 if (!isIssuerNameInList)
1969 if (*ppCertListInfoTypes != null)
1971 _CertService::FreeCertList(*ppCertListInfoTypes);
1972 *ppCertListInfoTypes = null;
1975 memset(condition, 0, sizeof(condition));
1976 sprintf(condition, "installed = '%s'", installedRecord);
1980 memset(&userCertRecord, 0, sizeof(userCertRecord));
1981 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1982 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1984 curCertId = userCertRecord.certId;
1986 for (readLength = 0; readLength < count; readLength++)
1989 memset(&userCertRecord, 0, sizeof(userCertRecord));
1990 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1991 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1992 curCertId = userCertRecord.certId;
1997 while (isIssuerNameInList != true);
2010 EVP_PKEY_free(pKey);
2017 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2019 result r = E_SUCCESS;
2020 UserCertRecord userCertRecord = {0, };
2021 CaCertRecord caCertRecord = {0, };
2022 int subjNameB64len = 0;
2024 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2025 char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2026 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2028 subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2029 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2030 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2031 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2032 sprintf(conditonRecord, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2034 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2035 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2037 if (pPrivateKeyInfo != null)
2039 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2042 r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2043 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2045 parentCa = userCertRecord.parentCa;
2049 memset(&caCertRecord, 0, sizeof(caCertRecord));
2050 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2051 sprintf(conditonRecord, "certId = %d and installed = '%s'", parentCa, installedRecord);
2053 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2054 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2056 parentCa = caCertRecord.parentCa;
2057 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2059 r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2060 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2064 while (caCertRecord.certId != caCertRecord.parentCa);
2070 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2072 result r = E_SUCCESS;
2073 UserCertRecord userCertRecord = {0, };
2074 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2075 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2077 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2079 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2080 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2082 *pSubjectLength = userCertRecord.subjectNameLen;
2083 memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2084 *pIssuerLength = userCertRecord.issuerNameLen;
2085 memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2092 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2094 result r = E_SUCCESS;
2095 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2096 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2099 int certBufferLen = 0;
2100 int keyBufferLen = 0;
2101 int certificateBase64Len = 0;
2102 const byte* pCertBuffer = null;
2103 const byte* pKeyBuffer = null;
2104 byte* pPrivateTempKey = null;
2105 UserCertRecord certRecord = {0, };
2106 _CertFileStore fileStore;
2107 std::unique_ptr <_CertPrivateKeyInfo> pPriKey;
2110 EVP_PKEY* pKey = null;
2112 *ppUserCertInfo = null;
2114 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2115 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2117 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2118 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2120 std::unique_ptr <_CertInfo> pCertInfo (new (std::nothrow) _CertInfo);
2121 SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2123 memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2125 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2126 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2128 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2129 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2130 certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2132 if (encodingType == _CERT_ENC_TYPE_PEM)
2134 pBio = BIO_new(BIO_s_mem());
2135 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2137 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2138 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2140 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2141 certBufferLen = pCertInfo->certLength;
2143 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2144 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2146 readCount = PEM_write_bio_X509(pBio, pCert);
2147 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2149 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2150 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2151 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2153 pCertInfo->certLength = readCount;
2155 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2157 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2158 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2159 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2160 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2161 pCertInfo->certLength = certLen;
2163 pCertInfo->certId = certRecord.certId;
2164 pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2165 pCertInfo->certType = _CERT_TYPE_USER_CERT;
2167 if (certRecord.prvKeyLen > 0)
2169 pPriKey = std::unique_ptr <_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo());
2170 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2172 std::unique_ptr <byte[]> pPrivateKey (new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2173 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2175 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2176 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2177 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2179 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2180 if (!IsFailed(r) && priKeyLen != 0)
2182 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2184 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2188 pPrivateKey.reset(null);
2190 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2191 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2193 pPrivateKey = std::unique_ptr<byte[]>(pPrivateTempKey);
2195 if (encodingType == _CERT_ENC_TYPE_PEM)
2199 pBio = BIO_new(BIO_s_mem());
2200 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2202 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2203 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2205 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2206 keyBufferLen = priKeyLen;
2208 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2209 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2211 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2213 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2214 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2216 pCertInfo->privateKeyLen = readCount;
2218 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2220 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2221 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2222 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2223 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2228 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2229 pCertInfo->privateKeyLen = priKeyLen;
2234 *ppUserCertInfo = pCertInfo.release();
2238 if (encodingType == _CERT_ENC_TYPE_PEM)
2242 EVP_PKEY_free(pKey);
2251 } } } //Tizen::Security::Cert