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;
54 void operator ()(byte* c)
61 namespace Tizen { namespace Security { namespace Cert
63 _CertDbManager* _CertDbManager::__pCertDb = null;
65 _CertDbManager::_CertDbManager(void)
69 _CertDbManager::~_CertDbManager(void)
74 _CertDbManager::Construct(void)
76 static _CertDbManager certDb;
82 _CertDbManager::GetInstance(void)
84 static pthread_once_t once_block = PTHREAD_ONCE_INIT;
85 if (__pCertDb == null)
87 pthread_once(&once_block, Construct);
94 _CertDbManager::CreateCertificateTables(void)
98 r = __caCertDbStore.CreateCertificateTables();
99 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database.");
105 _CertDbManager::IsCertificateTablesCreated(void)
107 result r = E_SUCCESS;
109 r = __caCertDbStore.IsRootCaCertTableCreated();
112 SetLastResult(E_SYSTEM);
116 r = __userCertDbStore.IsUserCertTableCreated();
119 SetLastResult(E_SYSTEM);
127 _CertDbManager::ResetCertificateTables(void)
129 result r = E_SUCCESS;
131 r = __caCertDbStore.DropCertificateTables();
132 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database.");
134 r = __caCertDbStore.CreateCertificateTables();
135 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database.");
141 _CertDbManager::RemoveCertificateTables(void)
143 result r = E_SUCCESS;
144 r = __caCertDbStore.DropCertificateTables();
145 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
150 _CertDbManager::RemoveCaCertificateByType(_CaCertType certType)
152 result r = E_SUCCESS;
153 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
154 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
156 sprintf(condition, "certType = %d and installed = '%s'", certType, installed);
158 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
159 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
165 _CertDbManager::RemoveUserCaCertificateByCertId(int certId)
167 result r = E_SUCCESS;
168 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
169 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
171 sprintf(condition, "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed);
172 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
173 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
179 _CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
181 return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false);
185 _CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity)
187 result r = E_SUCCESS;
189 CaCertRecord certRecord = {0, };
190 _CertFileStore fileStore;
191 _CertFormat certBufFormat = _CERT_UNKNOWN;
192 _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
193 int lenSubjectName = 0;
194 int lenIssuerName = 0;
197 int derCertBufferLength = 0;
198 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
199 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
200 char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
201 char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
202 byte* pDerCert = null;
203 byte* pSerial = null;
204 _X509TbsCert* pTbsCert = null;
206 r = __caCertDbStore.IsRootCaCertTableCreated();
207 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
209 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
210 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
212 certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType);
213 std::unique_ptr< byte, ByteDeleter > pDerCertBuffer(pDerCert);
215 SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer.");
216 SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format.");
217 SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length.");
219 r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
220 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
222 pTbsCert = pCert->GetTbsCertInstance();
223 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
225 lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
226 lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
228 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
229 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
231 strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
232 strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
234 pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo));
235 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
237 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
242 memcpy(serialName, pSerial, lenSerialNo);
247 if (pCert->IsSelfSigned())
249 r = pCert->VerifySignature(null, 0);
250 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data.");
252 #ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE
253 //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)
254 else if (pCert->IsCaCertificate())
256 std::unique_ptr< _CertChain > pCertChain(new (std::nothrow) _CertChain());
257 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
259 r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength);
260 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed.");
262 r = pCertChain->MoveHead();
263 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed.");
266 // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id
267 //(there are ECC certificate installation which we support for china model. hence these comments)
268 r = pCertChain->VerifyCertChainWithDb();
269 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain.");
273 #ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE
274 //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check)
277 return E_UNSUPPORTED_OPERATION;
283 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName);
286 return E_FILE_ALREADY_EXIST;
288 //Get the last installed certificate id from db table
289 __caCertDbStore.GetCurrentCertId(certId);
290 //Calculate the new (std::nothrow) certificate id for installation
292 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
294 memset(&certRecord, 0, sizeof(certRecord));
295 certRecord.certType = static_cast< int >(certType);
296 certRecord.certFormat = static_cast< int >(certFormat);
298 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
299 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
301 strcpy(certRecord.fileName, pFileName.get());
303 certRecord.subjectNameLen = lenSubjectName;
304 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
305 certRecord.issuerNameLen = lenIssuerName;
306 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
307 certRecord.parentCa = certId;
308 strcpy(certRecord.installed, installed);
309 memcpy(certRecord.serialNo, serialName, lenSerialNo);
310 certRecord.serialNoLen = lenSerialNo;
312 r = __caCertDbStore.InsertCaCertificate(&certRecord);
313 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
315 fileStore.SetFilePath(tempFileName);
317 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
318 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
325 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
327 result r = E_SUCCESS;
329 CaCertRecord certRecord = {0, };
330 CaCertRecord certRecord1 = {0, };
331 _CertFileStore fileStore;
332 _X509TbsCert* pTbsCert = null;
333 _X509TbsCert* pNewTbsCert = null;
334 int lenSubjectName = 0;
335 int lenNewSubjectName = 0;
336 int lenIssuerName = 0;
337 int lenNewIssuerName = 0;
338 int lenNewSerialNo = 0;
340 int subjNameB64len = 0;
341 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
342 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
343 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
344 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
345 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
346 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
347 byte* pNewSerial = null;
349 r = __caCertDbStore.IsRootCaCertTableCreated();
350 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
352 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
353 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
355 r = pCert->Parse(pCurCertBuf, curCertLen);
356 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
358 pTbsCert = pCert->GetTbsCertInstance();
359 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
361 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
362 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
364 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
365 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
367 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
368 if (!IsFailed(r)) //checkit
370 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
371 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
373 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
375 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
376 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
378 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
379 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
380 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
382 certId = certRecord.parentCa;
384 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
385 fileStore.SetFilePath(tempFileName);
387 if (certFormat == _CERT_X509)
389 std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
390 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
392 r = pNewCert->Parse(pNewCertBuf, newCertLen);
393 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
395 pNewTbsCert = pNewCert->GetTbsCertInstance();
396 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
398 strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
399 strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName())));
401 lenNewSubjectName = strlen(newSubjectName);
402 lenNewIssuerName = strlen(newIssuerName);
404 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
405 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
407 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
413 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
416 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
417 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
419 certRecord1.certType = static_cast< int >(certType);
420 certRecord1.certFormat = static_cast< int >(certFormat);
422 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
423 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
425 strcpy(certRecord1.fileName, pFileName.get());
427 certRecord1.subjectNameLen = lenNewSubjectName;
428 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
429 certRecord1.issuerNameLen = lenIssuerName;
430 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
431 certRecord1.parentCa = certId;
432 strcpy(certRecord1.installed, certRecord.installed);
433 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
434 certRecord1.serialNoLen = lenNewSerialNo;
436 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
437 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
439 fileStore.DeleteFile();
441 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
442 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
443 //No need to update record as only file data changed.
448 return E_FILE_ALREADY_EXIST;
455 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
457 result r = E_SUCCESS;
458 _X509TbsCert* pTbsCert = null;
460 _CertFileStore fileStore;
463 //Check certType missing
465 r = __caCertDbStore.IsRootCaCertTableCreated();
466 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
468 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
469 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
471 r = pCert->Parse(pCertBuf, certLen);
472 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
474 pTbsCert = pCert->GetTbsCertInstance();
475 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
477 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
478 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db.");
480 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
481 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
483 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
486 r = __caCertDbStore.RemoveCertificateById(certId);
487 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
490 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
491 Tizen::Io::File::Remove(fileName);
498 _CertDbManager::RemoveCertificateChainByCertId(int certId)
500 result r = E_SUCCESS;
501 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
502 UserCertRecord userCertRecord = {0, };
504 memset(&userCertRecord, 0, sizeof(userCertRecord));
505 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
507 sprintf(condition, "certId = %d", certId);
508 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
509 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
510 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
512 r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
513 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
520 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
522 result r = E_SUCCESS;
523 int subjNameB64len = 0;
524 int issuerB64len = 0;
525 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
526 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
527 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
528 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
529 CaCertRecord caCertRecord = {0, };
531 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
532 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
534 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
535 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
537 r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
538 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
540 memset(condition, 0, sizeof(condition));
542 if (pIssuerName != null && issuerNameSize > 0)
544 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
545 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
547 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
548 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
550 if (certType == _CERT_TYPE_NOT_BOUNDED)
552 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
556 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
561 if (certType == _CERT_TYPE_NOT_BOUNDED)
563 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
567 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
571 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
572 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
574 certId = caCertRecord.certId;
580 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
582 result r = E_SUCCESS;
583 int subjNameB64len = 0;
584 int issuerB64len = 0;
585 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
586 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
587 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
588 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
589 UserCertRecord userCertRecord = {0, };
591 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
592 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
594 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
595 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
597 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
598 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
600 memset(condition, 0, sizeof(condition));
602 if (pIssuerName != null && issuerNameSize > 0)
604 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
605 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
607 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
608 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
610 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
614 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
617 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
618 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
620 certId = userCertRecord.certId;
626 _CertDbManager::RemoveAllUserCertificate(void)
628 __userCertDbStore.DeleteUserCertFiles();
634 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
636 result r = E_SUCCESS;
637 CaCertRecord certRecord = {0, };
641 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
642 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
645 SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
646 SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
648 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
650 sprintf(condition, "parentCa = %d and installed = '%s'", devParentCA, installed);
651 //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
652 //delete only device certificate and return. We cannot disturb another chain.
653 __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
654 //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
657 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
658 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
662 //Now there is not two device certificate with same intermidiate CA,
663 //so go ahead to intermidiate CA and delete device certificate.
664 caParentCa = devParentCA;
665 caCertId = devCertId;
668 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
672 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
673 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
675 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
676 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
677 break; // break here next certificate has dependency
681 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
682 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
684 break; // break here next certificate has dependency
687 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
689 if (devCert) //If it is device certificate
691 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
692 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
694 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
695 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
697 else //If it is CA certificate and there is no dependency
699 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
700 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
702 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
704 caCertId = caParentCa; // Now look for next certificate in chain
705 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
706 sprintf(condition, "certId = %d and installed = '%s'", devParentCA, installed);
707 memset(&certRecord, 0, sizeof(certRecord));
708 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
709 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
710 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
712 caParentCa = certRecord.parentCa;
715 while (caCertId != caParentCa);
721 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
723 result r = E_SUCCESS;
724 CaCertRecord certRecord = {0, };
725 _CertificateListInfo* pHoldList = null;
726 _CertFileStore fileStore;
729 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
730 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
732 sprintf(condition, "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
734 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
735 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
736 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
738 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
739 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
741 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
742 pCertList->pNext = null;
743 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
744 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
746 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
747 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
749 pCertList->length = certLength;
750 pCertList->certFileId = certRecord.certId;
751 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
752 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
755 pHoldList = pCertList.release();
756 *ppCertList = pHoldList;
758 while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
760 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
761 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
763 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
765 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
766 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
768 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
769 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
771 pCertList->pNext = null;
772 pCertList->length = certLength;
773 pCertList->certFileId = certRecord.certId;
774 pCertList->format = (_CertFormat) certRecord.certFormat;
775 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
777 pHoldList->pNext = pCertList.release();
778 pHoldList = pHoldList->pNext;
790 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
792 result r = E_SUCCESS;
793 UserCertRecord certRecord = {0, };
794 _CertificateListInfo* pHoldList = null;
795 _CertFileStore fileStore;
798 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
799 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
803 sprintf(condition, "certFormat = %d and installed = '%s'", certFormat, installed);
805 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
806 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
807 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
809 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
810 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
812 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
813 pCertList->pNext = null;
815 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
816 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
818 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
819 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
821 pCertList->length = certLength;
822 pCertList->certFileId = certRecord.certId;
823 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
824 pCertList->certType = _CERT_TYPE_USER_CERT;
827 pHoldList = pCertList.release();
828 *ppCertList = pHoldList;
830 while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
832 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
833 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
835 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
837 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
838 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
840 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
841 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
843 pCertList->pNext = null;
844 pCertList->length = certLength;
845 pCertList->certFileId = certRecord.certId;
846 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
847 pCertList->certType = _CERT_TYPE_USER_CERT;
849 pHoldList->pNext = pCertList.release();
850 pHoldList = pHoldList->pNext;
861 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
863 result r = E_SUCCESS;
864 CaCertRecord certRecord = {0, };
865 _CertFileStore fileStore;
867 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
868 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
871 sprintf(condition, "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
873 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
874 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
876 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
877 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
879 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
881 pCertList->pNext = null;
882 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
883 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
885 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
886 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
888 pCertList->length = certLength;
889 pCertList->certFileId = certRecord.certId;
890 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
891 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
893 *ppCertList = pCertList.release();
899 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
901 result r = E_SUCCESS;
902 _CertFileStore fileStore;
903 UserCertRecord certRecord = {0, };
906 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
907 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
911 SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
912 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
914 sprintf(condition, "certId = %d and installed = '%s'", certId, installed);
915 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
916 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
918 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
919 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
921 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
923 pCertList->pNext = null;
925 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
926 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
928 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
929 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
931 pCertList->length = certLength;
932 pCertList->certFileId = certRecord.certId;
933 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
934 pCertList->certType = _CERT_TYPE_USER_CERT;
936 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
937 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
939 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
940 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
942 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
944 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
945 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
947 r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
948 if (!IsFailed(r) && priKeyLen != 0)
950 byte* pPrivateTempKey = null;
951 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
953 pPrivateKey.reset(null);
955 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
956 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
958 std::unique_ptr< byte[] > pPrivateKeyAuto(pPrivateTempKey);
960 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
962 pCertList->priKeyLen = priKeyLen;
964 *ppCertList = pCertList.release();
970 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
972 result r = E_SUCCESS;
973 CaCertRecord certRecord = {0, };
974 _CertFileStore fileStore;
976 int issuerNameB64len = 0;
977 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
978 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
979 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
981 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
982 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
983 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
985 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
986 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
988 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
990 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
991 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
993 sprintf(condition, "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
995 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
996 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
998 filePath = reinterpret_cast< char* >(certRecord.fileName);
1000 fileStore.SetFilePath(filePath);
1002 *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
1003 SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1005 r = fileStore.ReadFromFile(*ppCert, certLen);
1006 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1008 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1014 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1016 result r = E_SUCCESS;
1018 CaCertRecord certRecord = {0, };
1019 _CertFileStore fileStore;
1020 int issuerNameB64len = 0;
1021 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1022 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1023 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1025 SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1026 SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1027 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1028 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1029 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1031 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1032 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1034 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1036 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1037 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1039 sprintf(condition, "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1040 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1041 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1043 if (certRecord.certId == 0)
1048 filePath = static_cast< char* >(certRecord.fileName);
1049 fileStore.SetFilePath(filePath);
1051 std::unique_ptr< byte[] > pCert(new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1052 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1054 r = fileStore.ReadFromFile(pCert.get(), certLen);
1055 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1057 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1059 *ppCert = pCert.release();
1065 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1067 result r = E_SUCCESS;
1068 CaCertRecord certRecord = {0, };
1069 _CertFileStore fileStore;
1070 int subjectNameB64len = 0;
1071 int issuerNameB64len = 0;
1072 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1073 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1074 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1075 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1077 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1078 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1079 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1080 SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1082 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1083 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1085 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1087 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1088 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1090 subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1091 SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1093 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1094 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1095 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1097 sprintf(condition, "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1098 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1099 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1101 *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1106 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1108 result r = E_SUCCESS;
1109 _CertFileStore fileStore;
1112 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1114 if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1118 r = __userCertDbStore.RemoveCertificateById(certId);
1119 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1121 //Remove certificate file
1122 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1123 r = Tizen::Io::File::Remove(fileName);
1124 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1126 //Remove private key file
1127 //Don't check return type here as it is not necessary that private key is present.
1128 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1129 r = Tizen::Io::File::Remove(keyfileName);
1131 else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1133 r = __caCertDbStore.RemoveCertificateById(certId);
1134 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1136 //Remove certificate file
1137 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1138 r = Tizen::Io::File::Remove(fileName);
1139 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1145 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1147 result r = E_SUCCESS;
1148 String fileName(reinterpret_cast< char* >(pFilePath));
1149 FileAttributes attr;
1154 int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1157 SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1158 SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1159 SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1161 r = File::GetAttributes(fileName, attr);
1162 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1164 fileSize = attr.GetFileSize();
1165 SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1166 SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1169 r = file.Construct(fileName, L"r");
1170 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1172 std::unique_ptr< byte[] > pCertBuf(new (std::nothrow) byte[fileSize + 1]);
1173 SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1175 memset(pCertBuf.get(), 0, fileSize + 1);
1176 readCnt = file.Read(pCertBuf.get(), fileSize);
1177 r = GetLastResult();
1178 SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1181 std::unique_ptr< byte[] > pOutBuf(new (std::nothrow) byte[outLen]);
1182 SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1184 memset(pOutBuf.get(), 0, outLen);
1185 //As per OpenSSL APIs, it takes input as unsigned data types
1186 resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1187 SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1189 memcpy(pBuf, pOutBuf.get(), outLen);
1195 //User Certificate APIs
1198 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1200 result r = E_SUCCESS;
1201 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1202 int curCACertId = 0;
1203 int lastCACertId = 0;
1204 int curDevCertId = 0;
1205 bool updateUserParentCa = false;
1207 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1208 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1210 //Check for CA certificate table creation
1211 r = __caCertDbStore.IsRootCaCertTableCreated();
1212 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1215 //Check if the chain is valid or not
1216 r = pCertChain->Verify();
1217 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1219 r = pCertChain->MoveHead();
1220 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1222 if (certFormat == _CERT_X509)
1224 _X509Certificate* pCurCert = null;
1225 _X509Certificate* pUserCert = null;
1226 _X509TbsCert* pTbsCert = null;
1227 byte* pX509Buff = null;
1228 int x509BuffSize = 0;
1230 pUserCert = pCertChain->GetCurrentCertificate();
1231 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1233 pTbsCert = pUserCert->GetTbsCertInstance();
1234 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1236 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1237 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1239 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1240 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed insert user certificate chain.", GetErrorMessage(r));
1242 updateUserParentCa = true;
1244 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1245 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1247 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1249 //Insert certificate chain in CA certificate store
1250 while (pCertChain->MoveNext() == E_SUCCESS)
1253 pCurCert = pCertChain->GetCurrentCertificate();
1254 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1256 if (!pCurCert->IsSelfSigned())
1258 certType = _CERT_TYPE_INTERMIDIATE_CA;
1262 //This parameter need to pass from certificate manager about its type
1263 certType = _CERT_TYPE_ROOT_CA;
1266 pTbsCert = pCurCert->GetTbsCertInstance();
1267 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1269 if (E_SUCCESS != __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()))))
1274 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1275 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1277 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1278 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1280 // CA certificate already present or properly installed in CA certificate store,
1281 // get the certificate id of certificate
1282 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1283 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1284 curCACertId, certType);
1285 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1287 if (updateUserParentCa)
1289 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1290 updateUserParentCa = false;
1291 lastCACertId = curCACertId;
1295 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1296 lastCACertId = curCACertId;
1299 //If it is root certificate then its parent is itself
1300 if (pCurCert->IsSelfSigned())
1302 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1307 if (updateUserParentCa)
1309 r = pCertChain->MoveHead();
1310 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1312 pCurCert = pCertChain->GetCurrentCertificate();
1313 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1315 pTbsCert = pCurCert->GetTbsCertInstance();
1316 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1318 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1319 null, 0, curCACertId);
1320 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1322 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1323 updateUserParentCa = false;
1324 lastCACertId = curCACertId;
1326 else if (!pCurCert->IsSelfSigned())
1328 pTbsCert = pCurCert->GetTbsCertInstance();
1329 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1331 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1332 null, 0, curCACertId);
1333 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1335 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1336 lastCACertId = curCACertId;
1344 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1346 result r = E_SUCCESS;
1347 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1349 int curCACertId = 0;
1350 int lastCACertId = 0;
1351 int curDevCertId = 0;
1353 bool updateUserParentCa = false;
1354 byte* pPrvKey = null;
1355 std::unique_ptr< byte[] > pPrvKeyBuffer;
1357 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1358 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1360 r = __userCertDbStore.IsUserCertTableCreated();
1361 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1363 //Check for CA certificate table creation
1364 r = __caCertDbStore.IsRootCaCertTableCreated();
1365 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1367 //Check if the chain is valid or not
1368 r = pCertChain->Verify();
1369 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1371 r = pCertChain->MoveHead();
1372 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1374 if (certFormat == _CERT_X509)
1376 _X509Certificate* pCurCert = null;
1377 _X509Certificate* pUserCert = null;
1378 _X509TbsCert* pTbsCert = null;
1379 byte* pX509Buff = null;
1380 int x509BuffSize = 0;
1382 pUserCert = pCertChain->GetCurrentCertificate();
1383 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1385 pTbsCert = pUserCert->GetTbsCertInstance();
1386 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1388 byte* pSubjectName = pTbsCert->GetSubjectName();
1389 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1391 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1393 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1396 if (pPrivateKeyInfo != null)
1398 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1399 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1401 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1406 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1407 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1409 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1410 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1416 updateUserParentCa = true;
1418 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1419 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1421 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1423 if (pPrvKeyBuffer != null)
1425 _CertFileStore fileStore;
1426 String privateKeyFile;
1428 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1429 fileStore.SetFilePath(privateKeyFile);
1432 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1433 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1443 if (pUserCert->IsSelfSigned())
1445 __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
1449 //Insert certificate chain in CA certificate store
1450 while (pCertChain->MoveNext() == E_SUCCESS)
1452 pCurCert = pCertChain->GetCurrentCertificate();
1453 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1455 if (!pCurCert->IsSelfSigned())
1457 certType = _CERT_TYPE_INTERMIDIATE_CA;
1461 //This parameter need to pass from certificate manager about its type
1462 certType = _CERT_TYPE_ROOT_CA;
1465 pTbsCert = pCurCert->GetTbsCertInstance();
1466 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1468 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1474 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1475 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1477 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1478 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1481 // CA certificate already present or properly install in CA certificate store,
1482 // get the certificate id of certificate
1484 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1485 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1486 curCACertId, certType);
1487 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1489 if (updateUserParentCa)
1491 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1492 updateUserParentCa = false;
1493 lastCACertId = curCACertId;
1497 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1498 lastCACertId = curCACertId;
1501 //If it is root certificate then its parent is itself
1502 if (pCurCert->IsSelfSigned())
1504 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1508 if (updateUserParentCa)
1510 r = pCertChain->MoveHead();
1511 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1513 pCurCert = pCertChain->GetCurrentCertificate();
1514 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1516 pTbsCert = pCurCert->GetTbsCertInstance();
1517 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1519 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1520 null, 0, curCACertId);
1521 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1523 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1524 updateUserParentCa = false;
1525 lastCACertId = curCACertId;
1527 else if (!pCurCert->IsSelfSigned())
1529 pTbsCert = pCurCert->GetTbsCertInstance();
1530 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1532 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1533 null, 0, curCACertId);
1534 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1536 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1537 lastCACertId = curCACertId;
1545 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1547 result r = E_SUCCESS;
1548 _X509TbsCert* pTbsCert = null;
1549 _CertFileStore fileStore;
1550 UserCertRecord certRecord = {0, };
1551 String privateKeyFile;
1552 String tempFileName;
1553 int lenSubjectName = 0;
1554 int lenIssuerName = 0;
1555 int lenSerialNo = 0;
1557 int keyIdB64Length = 0;
1558 char* pFileName = null;
1559 char* pPriKeyFileName = null;
1560 char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1561 char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1562 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1563 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1564 byte* pKeyId = null;
1565 byte* pSerial = null;
1567 //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1568 SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1569 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1570 SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1572 r = __userCertDbStore.IsUserCertTableCreated();
1573 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1575 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
1576 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1578 r = pCert->Parse(pCertBuffer, certLength);
1579 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1581 pTbsCert = pCert->GetTbsCertInstance();
1582 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1584 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1585 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1587 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1588 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1590 strcpy(subjectNameBuffer, reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1591 strcpy(szIssuerName, reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1593 pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1594 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1596 if (pSerial != null)
1598 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1604 memcpy(serialName, pSerial, lenSerialNo);
1608 r = pCert->GetKeyIdN(&pKeyId);
1609 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1611 std::unique_ptr< byte[] > pKeyIdBuffer(pKeyId);
1613 keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1614 SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1616 std::unique_ptr< char[] > pId64(new (std::nothrow) char[keyIdB64Length]);
1617 SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1619 memset(pId64.get(), 0, keyIdB64Length);
1620 r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1621 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1623 r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1624 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1626 //Get the last installed certificate id from db table
1627 __userCertDbStore.GetCurrentCertId(certId);
1629 //Calculate the new certificate id for installation
1630 certId = certId + 1;
1632 if (pPrivateKey != null)
1634 //Get file name for private key and store private key into file.
1635 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1639 pPriKeyFileName = null;
1643 //Get file name for certificate and write device certificate to file
1644 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1646 //Insert Record into Database
1647 //It is generated automatically by sequence
1648 memset(&certRecord, 0, sizeof(certRecord));
1650 memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1651 certRecord.certFormat = static_cast< int >(certFormat);
1653 pFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName);
1654 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1656 strcpy(certRecord.fileName, pFileName);
1657 certRecord.subjectNameLen = lenSubjectName;
1659 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1660 certRecord.issuerNameLen = lenIssuerName;
1661 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1663 pPriKeyFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile);
1664 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1666 strcpy(certRecord.prvKeyPath, pPriKeyFileName);
1667 certRecord.prvKeyLen = privateKeyLen;
1668 certRecord.parentCa = certId;
1669 strcpy(certRecord.installed, installedRecord);
1671 memcpy(certRecord.serialNo, serialName, lenSerialNo);
1673 certRecord.serialNoLen = lenSerialNo;
1675 r = __userCertDbStore.InsertUserCertificate(&certRecord);
1676 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1678 fileStore.SetFilePath(tempFileName);
1680 r = fileStore.WriteToFile(pCertBuffer, certLength);
1681 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1683 if (pPrivateKey != null)
1685 fileStore.SetFilePath(privateKeyFile);
1687 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1688 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1695 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1697 result r = E_SUCCESS;
1698 CaCertRecord certRecord = {0, };
1699 UserCertRecord userCertRecord = {0, };
1700 _CertificateListInfo* pHoldList = null;
1703 EVP_PKEY* pKey = null;
1705 int recordCount = 0;
1706 int subjectNameBase64Len = 0;
1712 int certificateBase64Len = 0;
1713 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1714 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1715 byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1716 byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1717 byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1718 bool isIssuerNameInList = false;
1720 subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1721 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1722 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1723 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1725 if ((pSubjectName != null) && (subjectNameLen > 0))
1727 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1728 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1729 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1730 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1731 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1735 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1736 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1737 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1738 sprintf(condition, "installed = '%s'", installedRecord);
1741 memset(&userCertRecord, 0, sizeof(userCertRecord));
1742 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1743 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1745 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
1746 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1749 std::unique_ptr< _CertFileStore > pFileStore(new (std::nothrow) _CertFileStore());
1750 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1752 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
1753 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1755 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1757 pCertList->pNext = null;
1759 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1760 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1762 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1763 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1764 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1766 if (encodingType == _CERT_ENC_TYPE_PEM)
1768 const byte* pCertBuffer = pCertList->certificate;
1770 pBio = BIO_new(BIO_s_mem());
1771 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1773 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1774 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1776 readLength = PEM_write_bio_X509(pBio, pCert);
1777 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1779 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1781 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1782 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1784 pCertList->length = readLength;
1793 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1795 int certLen = _Base64::GetEncodedSize(pCertList->length);
1796 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1797 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1798 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1800 pCertList->length = certLen;
1803 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1804 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1806 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1807 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1808 pCertList->certFileId = userCertRecord.certId;
1810 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1811 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1815 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1816 if (!IsFailed(r) && priKeyLen != 0)
1818 byte* pPrivateTempKey = null;
1819 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1820 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1822 pPrivateKey.reset(null);
1825 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1826 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1828 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
1830 if (encodingType == _CERT_ENC_TYPE_PEM)
1832 const byte* pKeyBuffer = pPrivateKey.get();
1833 pBio = BIO_new(BIO_s_mem());
1834 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1836 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1837 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1839 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1840 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1842 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1844 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1846 pCertList->priKeyLen = readLength;
1854 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1856 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1857 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1859 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1860 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1864 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1865 pCertList->priKeyLen = priKeyLen;
1869 pPrivateKey.reset(null);
1871 pHoldList = pCertList.release();
1872 *ppCertListInfoTypes = pHoldList;
1876 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1877 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1878 subNameLen = userCertRecord.issuerNameLen;
1882 subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1883 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1884 r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1885 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1886 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1888 if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1890 isIssuerNameInList = true;
1893 memset(&certRecord, 0, sizeof(certRecord));
1894 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1895 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1897 if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1899 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo());
1900 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1902 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1903 pCertList->pNext = null;
1905 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1906 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1908 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1909 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1910 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1912 if (encodingType == _CERT_ENC_TYPE_PEM)
1914 const byte* pCertBuffer = pCertList->certificate;
1916 pBio = BIO_new(BIO_s_mem());
1917 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1919 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1920 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1922 readLength = PEM_write_bio_X509(pBio, pCert);
1923 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1925 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1927 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1928 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1930 pCertList->length = readLength;
1938 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1940 int certLen = _Base64::GetEncodedSize(pCertList->length);
1941 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1942 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1943 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1944 pCertList->length = certLen;
1946 pCertList->format = (_CertFormat) certRecord.certFormat;
1947 pCertList->certType = (_CaCertType) certRecord.certType;
1948 pCertList->certFileId = certRecord.certId;
1950 pHoldList->pNext = pCertList.release();
1951 pHoldList = pHoldList->pNext;
1955 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1956 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1957 subNameLen = certRecord.issuerNameLen;
1961 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1963 if (!isIssuerNameInList)
1965 if (*ppCertListInfoTypes != null)
1967 _CertService::FreeCertList(*ppCertListInfoTypes);
1968 *ppCertListInfoTypes = null;
1971 memset(condition, 0, sizeof(condition));
1972 sprintf(condition, "installed = '%s'", installedRecord);
1976 memset(&userCertRecord, 0, sizeof(userCertRecord));
1977 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1978 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1980 curCertId = userCertRecord.certId;
1982 for (readLength = 0; readLength < count; readLength++)
1985 memset(&userCertRecord, 0, sizeof(userCertRecord));
1986 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1987 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1988 curCertId = userCertRecord.certId;
1993 while (isIssuerNameInList != true);
2006 EVP_PKEY_free(pKey);
2013 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2015 result r = E_SUCCESS;
2016 UserCertRecord userCertRecord = {0, };
2017 CaCertRecord caCertRecord = {0, };
2018 int subjNameB64len = 0;
2020 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2021 char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2022 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2024 subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2025 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2026 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2027 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2028 sprintf(conditonRecord, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2030 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2031 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2033 if (pPrivateKeyInfo != null)
2035 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2038 r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2039 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2041 parentCa = userCertRecord.parentCa;
2045 memset(&caCertRecord, 0, sizeof(caCertRecord));
2046 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2047 sprintf(conditonRecord, "certId = %d and installed = '%s'", parentCa, installedRecord);
2049 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2050 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2052 parentCa = caCertRecord.parentCa;
2053 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2055 r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2056 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2060 while (caCertRecord.certId != caCertRecord.parentCa);
2066 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2068 result r = E_SUCCESS;
2069 UserCertRecord userCertRecord = {0, };
2070 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2071 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2073 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2075 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2076 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2078 *pSubjectLength = userCertRecord.subjectNameLen;
2079 memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2080 *pIssuerLength = userCertRecord.issuerNameLen;
2081 memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2088 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2090 result r = E_SUCCESS;
2091 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2092 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2095 int certBufferLen = 0;
2096 int keyBufferLen = 0;
2097 int certificateBase64Len = 0;
2098 const byte* pCertBuffer = null;
2099 const byte* pKeyBuffer = null;
2100 byte* pPrivateTempKey = null;
2101 UserCertRecord certRecord = {0, };
2102 _CertFileStore fileStore;
2103 std::unique_ptr< _CertPrivateKeyInfo > pPriKey;
2106 EVP_PKEY* pKey = null;
2108 *ppUserCertInfo = null;
2110 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2111 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2113 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2114 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2116 std::unique_ptr< _CertInfo > pCertInfo(new (std::nothrow) _CertInfo);
2117 SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2119 memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2121 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2122 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2124 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2125 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2126 certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2128 if (encodingType == _CERT_ENC_TYPE_PEM)
2130 pBio = BIO_new(BIO_s_mem());
2131 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2133 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2134 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2136 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2137 certBufferLen = pCertInfo->certLength;
2139 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2140 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2142 readCount = PEM_write_bio_X509(pBio, pCert);
2143 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2145 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2146 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2147 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2149 pCertInfo->certLength = readCount;
2151 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2153 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2154 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2155 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2156 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2157 pCertInfo->certLength = certLen;
2159 pCertInfo->certId = certRecord.certId;
2160 pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2161 pCertInfo->certType = _CERT_TYPE_USER_CERT;
2163 if (certRecord.prvKeyLen > 0)
2165 pPriKey = std::unique_ptr< _CertPrivateKeyInfo >(new (std::nothrow) _CertPrivateKeyInfo());
2166 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2168 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2169 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2171 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2172 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2173 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2175 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2176 if (!IsFailed(r) && priKeyLen != 0)
2178 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2180 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2184 pPrivateKey.reset(null);
2186 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2187 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2189 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
2191 if (encodingType == _CERT_ENC_TYPE_PEM)
2195 pBio = BIO_new(BIO_s_mem());
2196 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2198 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2199 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2201 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2202 keyBufferLen = priKeyLen;
2204 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2205 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2207 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2209 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2210 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2212 pCertInfo->privateKeyLen = readCount;
2214 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2216 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2217 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2218 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2219 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2224 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2225 pCertInfo->privateKeyLen = priKeyLen;
2230 *ppUserCertInfo = pCertInfo.release();
2234 if (encodingType == _CERT_ENC_TYPE_PEM)
2238 EVP_PKEY_free(pKey);
2247 } } } //Tizen::Security::Cert