2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 // Licensed under the Apache License, Version 2.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
18 * @file FSecCert_CertDbManager.cpp
19 * @brief This file contains implementation of X509 Certificate Db Manager APIs.
30 #include <openssl/evp.h>
31 #include <openssl/pem.h>
32 #include <unique_ptr.h>
35 #include <FBaseSysLog.h>
36 #include <FBaseByteBuffer.h>
37 #include <FBaseResult.h>
38 #include <FBase_StringConverter.h>
39 #include "FSecCert_CertDbStore.h"
40 #include "FSecCert_CertFileStore.h"
41 #include "FSecCert_CertDbManager.h"
42 #include "FSecCert_Base64.h"
43 #include "FSecCert_CertService.h"
44 #include "FSecCert_CertManager.h"
46 using namespace Tizen::Base;
47 using namespace Tizen::Io;
53 void operator ()(byte* c)
60 namespace Tizen { namespace Security { namespace Cert
62 _CertDbManager* _CertDbManager::__pCertDb = null;
64 _CertDbManager::_CertDbManager(void)
68 _CertDbManager::~_CertDbManager(void)
73 _CertDbManager::Construct(void)
75 static _CertDbManager certDb;
81 _CertDbManager::GetInstance(void)
83 static pthread_once_t once_block = PTHREAD_ONCE_INIT;
84 if (__pCertDb == null)
86 pthread_once(&once_block, Construct);
93 _CertDbManager::CreateCertificateTables(void)
97 r = __caCertDbStore.CreateCertificateTables();
98 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate tables in database.");
104 _CertDbManager::IsCertificateTablesCreated(void)
106 result r = E_SUCCESS;
108 r = __caCertDbStore.IsRootCaCertTableCreated();
111 SetLastResult(E_SYSTEM);
115 r = __userCertDbStore.IsUserCertTableCreated();
118 SetLastResult(E_SYSTEM);
126 _CertDbManager::ResetCertificateTables(void)
128 result r = E_SUCCESS;
130 r = __caCertDbStore.DropCertificateTables();
131 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to drop certificate tables in database.");
133 r = __caCertDbStore.CreateCertificateTables();
134 SysTryReturn(NID_SEC_CERT, !IsFailed(r), false, E_SYSTEM, "[E_SYSTEM] Failed to create certificate tables in database.");
140 _CertDbManager::RemoveCertificateTables(void)
142 result r = E_SUCCESS;
143 r = __caCertDbStore.DropCertificateTables();
144 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
149 _CertDbManager::RemoveCaCertificateByType(_CaCertType certType)
151 result r = E_SUCCESS;
152 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
153 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
155 sprintf(condition, "certType = %d and installed = '%s'", certType, installed);
157 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
158 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
164 _CertDbManager::RemoveUserCaCertificateByCertId(int certId)
166 result r = E_SUCCESS;
167 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
168 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
170 sprintf(condition, "certId = %d and certType = %d and installed = '%s'", certId, _CERT_TYPE_ROOT_CA_BY_USER, installed);
171 r = __caCertDbStore.RemoveAllCertificateByCondition(reinterpret_cast< byte* >(condition));
172 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete all the certificate tables in database.");
178 _CertDbManager::InsertDefaultCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
180 return InsertCaCertificateFromBuffer(certType, certFormat, pCertBuf, certLen, false);
184 _CertDbManager::InsertCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen, bool checkValidity)
186 result r = E_SUCCESS;
188 CaCertRecord certRecord = {0, };
189 _CertFileStore fileStore;
190 _CertFormat certBufFormat = _CERT_UNKNOWN;
191 _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
192 int lenSubjectName = 0;
193 int lenIssuerName = 0;
196 int derCertBufferLength = 0;
197 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
198 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
199 char subjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
200 char issuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
201 byte* pDerCert = null;
202 byte* pSerial = null;
203 _X509TbsCert* pTbsCert = null;
205 r = __caCertDbStore.IsRootCaCertTableCreated();
206 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
208 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
209 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
211 certBufFormat = _CertManager::GetEncodedCertBuffer(pCertBuf, certLen, &pDerCert, &derCertBufferLength, &encodingType);
212 std::unique_ptr< byte, ByteDeleter > pDerCertBuffer(pDerCert);
214 SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_CONDITION, "Input certificate buffer.");
215 SysTryReturnResult(NID_SEC_CERT, certBufFormat == _CERT_X509, E_INVALID_CONDITION, "Unsupported certificate format.");
216 SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_CONDITION, "Invalid certificate length.");
218 r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
219 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
221 pTbsCert = pCert->GetTbsCertInstance();
222 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
224 lenSubjectName = strlen(reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
225 lenIssuerName = strlen(reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
227 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
228 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name is more then maximum specified length.");
230 strcpy(subjectName, reinterpret_cast< const char* >(pTbsCert->GetSubjectName()));
231 strcpy(issuerName, reinterpret_cast< const char* >(pTbsCert->GetIssuerName()));
233 pTbsCert->GetSerialNumber(pSerial, reinterpret_cast< int& >(lenSerialNo));
234 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
236 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
241 memcpy(serialName, pSerial, lenSerialNo);
246 if (pCert->IsSelfSigned())
248 r = pCert->VerifySignature(null, 0);
249 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "Invalid data.");
251 #ifdef _CERT_VERIFY_AND_INSTALL_CERTIFICATE
252 //Open this code - if u want to support installation of Intermediate CA Certificate with verification using this API.(ideally it should check if installing intermediate CA) (09082011)
253 else if (pCert->IsCaCertificate())
255 std::unique_ptr< _CertChain > pCertChain(new (std::nothrow) _CertChain());
256 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
258 r = pCertChain->AddCertificate(certFormat, pDerCertBuffer.get(), derCertBufferLength);
259 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "AddCertificate failed.");
261 r = pCertChain->MoveHead();
262 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_CONTENT, "MoveHead failed.");
265 // It support only RSA, For ECC Certificate if you want to omit this, block this call or check as per algo id
266 //(there are ECC certificate installation which we support for china model. hence these comments)
267 r = pCertChain->VerifyCertChainWithDb();
268 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to verify certificate chain.");
272 #ifdef _CERT_INSTALL_ONLY_CA_CERTIFICATE
273 //Open this code - if u want to support only CA Certificate installation using this API.(ideally it should check)
276 return E_UNSUPPORTED_OPERATION;
282 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(subjectName), lenSubjectName);
285 return E_FILE_ALREADY_EXIST;
288 SysTryReturnResult(NID_SEC_CERT, r==E_DATA_NOT_FOUND, r, "Failed to check duplicate");
291 //Get the last installed certificate id from db table
292 __caCertDbStore.GetCurrentCertId(certId);
293 //Calculate the new (std::nothrow) certificate id for installation
295 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
297 memset(&certRecord, 0, sizeof(certRecord));
298 certRecord.certType = static_cast< int >(certType);
299 certRecord.certFormat = static_cast< int >(certFormat);
301 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
302 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
304 strcpy(certRecord.fileName, pFileName.get());
306 certRecord.subjectNameLen = lenSubjectName;
307 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
308 certRecord.issuerNameLen = lenIssuerName;
309 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
310 certRecord.parentCa = certId;
311 strcpy(certRecord.installed, installed);
312 memcpy(certRecord.serialNo, serialName, lenSerialNo);
313 certRecord.serialNoLen = lenSerialNo;
315 r = __caCertDbStore.InsertCaCertificate(&certRecord);
316 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
318 fileStore.SetFilePath(tempFileName);
320 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
321 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
328 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
330 result r = E_SUCCESS;
332 CaCertRecord certRecord = {0, };
333 CaCertRecord certRecord1 = {0, };
334 _CertFileStore fileStore;
335 _X509TbsCert* pTbsCert = null;
336 _X509TbsCert* pNewTbsCert = null;
337 int lenSubjectName = 0;
338 int lenNewSubjectName = 0;
339 int lenIssuerName = 0;
340 int lenNewIssuerName = 0;
341 int lenNewSerialNo = 0;
343 int subjNameB64len = 0;
344 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
345 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
346 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
347 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
348 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
349 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
350 byte* pNewSerial = null;
352 r = __caCertDbStore.IsRootCaCertTableCreated();
353 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
355 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
356 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
358 r = pCert->Parse(pCurCertBuf, curCertLen);
359 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
361 pTbsCert = pCert->GetTbsCertInstance();
362 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
364 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
365 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
367 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
368 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
370 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
371 if (!IsFailed(r)) //checkit
373 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
374 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
376 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
378 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
379 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
381 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
382 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
383 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
385 certId = certRecord.parentCa;
387 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
388 fileStore.SetFilePath(tempFileName);
390 if (certFormat == _CERT_X509)
392 std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
393 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
395 r = pNewCert->Parse(pNewCertBuf, newCertLen);
396 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
398 pNewTbsCert = pNewCert->GetTbsCertInstance();
399 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
401 strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
402 strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName())));
404 lenNewSubjectName = strlen(newSubjectName);
405 lenNewIssuerName = strlen(newIssuerName);
407 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
408 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
410 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
416 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
419 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
420 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
422 certRecord1.certType = static_cast< int >(certType);
423 certRecord1.certFormat = static_cast< int >(certFormat);
425 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
426 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
428 strcpy(certRecord1.fileName, pFileName.get());
430 certRecord1.subjectNameLen = lenNewSubjectName;
431 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
432 certRecord1.issuerNameLen = lenIssuerName;
433 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
434 certRecord1.parentCa = certId;
435 strcpy(certRecord1.installed, certRecord.installed);
436 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
437 certRecord1.serialNoLen = lenNewSerialNo;
439 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
440 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
442 fileStore.DeleteFile();
444 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
445 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
446 //No need to update record as only file data changed.
454 _CertDbManager::RemoveCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCertBuf, int certLen)
456 result r = E_SUCCESS;
457 _X509TbsCert* pTbsCert = null;
459 _CertFileStore fileStore;
462 //Check certType missing
464 r = __caCertDbStore.IsRootCaCertTableCreated();
465 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "No root certificate tables are create in databased.");
467 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
468 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
470 r = pCert->Parse(pCertBuf, certLen);
471 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Parsing failed.");
473 pTbsCert = pCert->GetTbsCertInstance();
474 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
476 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
477 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_OBJ_NOT_FOUND, "Certificate not found in db.");
478 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), r, "Propagated.");
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 r = __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1272 SysTryReturn(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, r, "[%s] Failed to check duplicate.", GetErrorMessage(r));
1277 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1278 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1280 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1281 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1284 // CA certificate already present or properly installed in CA certificate store,
1285 // get the certificate id of certificate
1286 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1287 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1288 curCACertId, certType);
1289 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1291 if (updateUserParentCa)
1293 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1294 updateUserParentCa = false;
1295 lastCACertId = curCACertId;
1299 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1300 lastCACertId = curCACertId;
1303 //If it is root certificate then its parent is itself
1304 if (pCurCert->IsSelfSigned())
1306 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1311 if (updateUserParentCa)
1313 r = pCertChain->MoveHead();
1314 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1316 pCurCert = pCertChain->GetCurrentCertificate();
1317 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1319 pTbsCert = pCurCert->GetTbsCertInstance();
1320 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1322 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1323 null, 0, curCACertId);
1324 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1326 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1327 updateUserParentCa = false;
1328 lastCACertId = curCACertId;
1330 else if (!pCurCert->IsSelfSigned())
1332 pTbsCert = pCurCert->GetTbsCertInstance();
1333 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1335 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1336 null, 0, curCACertId);
1337 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1339 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1340 lastCACertId = curCACertId;
1348 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1350 result r = E_SUCCESS;
1351 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1353 int curCACertId = 0;
1354 int lastCACertId = 0;
1355 int curDevCertId = 0;
1357 bool updateUserParentCa = false;
1358 byte* pPrvKey = null;
1359 std::unique_ptr< byte[] > pPrvKeyBuffer;
1361 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1362 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1364 r = __userCertDbStore.IsUserCertTableCreated();
1365 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1367 //Check for CA certificate table creation
1368 r = __caCertDbStore.IsRootCaCertTableCreated();
1369 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1371 //Check if the chain is valid or not
1372 r = pCertChain->Verify();
1373 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1375 r = pCertChain->MoveHead();
1376 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1378 if (certFormat == _CERT_X509)
1380 _X509Certificate* pCurCert = null;
1381 _X509Certificate* pUserCert = null;
1382 _X509TbsCert* pTbsCert = null;
1383 byte* pX509Buff = null;
1384 int x509BuffSize = 0;
1386 pUserCert = pCertChain->GetCurrentCertificate();
1387 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1389 pTbsCert = pUserCert->GetTbsCertInstance();
1390 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1392 byte* pSubjectName = pTbsCert->GetSubjectName();
1393 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1395 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1397 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1398 if (r == E_DATA_NOT_FOUND)
1400 if (pPrivateKeyInfo != null)
1402 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1403 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1405 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1410 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1411 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1413 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1414 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1420 updateUserParentCa = true;
1422 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1423 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1425 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1427 if (pPrvKeyBuffer != null)
1429 _CertFileStore fileStore;
1430 String privateKeyFile;
1432 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1433 fileStore.SetFilePath(privateKeyFile);
1436 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1437 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1447 if (pUserCert->IsSelfSigned())
1449 __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
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())));
1475 SysTryReturnResult(NID_SEC_CERT, r == E_DATA_NOT_FOUND, r, "Failed to check duplicate.");
1480 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1481 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1483 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1484 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1487 // CA certificate already present or properly install in CA certificate store,
1488 // get the certificate id of certificate
1490 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1491 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1492 curCACertId, certType);
1493 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1495 if (updateUserParentCa)
1497 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1498 updateUserParentCa = false;
1499 lastCACertId = curCACertId;
1503 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1504 lastCACertId = curCACertId;
1507 //If it is root certificate then its parent is itself
1508 if (pCurCert->IsSelfSigned())
1510 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1514 if (updateUserParentCa)
1516 r = pCertChain->MoveHead();
1517 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1519 pCurCert = pCertChain->GetCurrentCertificate();
1520 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1522 pTbsCert = pCurCert->GetTbsCertInstance();
1523 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1525 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1526 null, 0, curCACertId);
1527 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1529 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1530 updateUserParentCa = false;
1531 lastCACertId = curCACertId;
1533 else if (!pCurCert->IsSelfSigned())
1535 pTbsCert = pCurCert->GetTbsCertInstance();
1536 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1538 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1539 null, 0, curCACertId);
1540 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1542 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1543 lastCACertId = curCACertId;
1551 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1553 result r = E_SUCCESS;
1554 _X509TbsCert* pTbsCert = null;
1555 _CertFileStore fileStore;
1556 UserCertRecord certRecord = {0, };
1557 String privateKeyFile;
1558 String tempFileName;
1559 int lenSubjectName = 0;
1560 int lenIssuerName = 0;
1561 int lenSerialNo = 0;
1563 int keyIdB64Length = 0;
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.");
1629 SysTryReturnResult(NID_SEC_CERT, r==E_DATA_NOT_FOUND, r, "Failed to check duplicate");
1631 //Get the last installed certificate id from db table
1632 __userCertDbStore.GetCurrentCertId(certId);
1634 //Calculate the new certificate id for installation
1635 certId = certId + 1;
1637 if (pPrivateKey != null)
1639 //Get file name for private key and store private key into file.
1640 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
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 std::unique_ptr< char > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
1658 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1660 strcpy(certRecord.fileName, pFileName.get());
1661 certRecord.subjectNameLen = lenSubjectName;
1663 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1664 certRecord.issuerNameLen = lenIssuerName;
1665 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1667 std::unique_ptr< char > pPriKeyFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile));
1668 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1670 strcpy(certRecord.prvKeyPath, pPriKeyFileName.get());
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 SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_SYSTEM, "Certificate length is invalid.");
1801 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1802 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1803 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1805 pCertList->length = certLen;
1808 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
1809 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1811 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
1812 pCertList->format = static_cast< _CertFormat >(userCertRecord.certFormat);
1813 pCertList->certFileId = userCertRecord.certId;
1815 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_PRIVATE_KEY);
1816 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1820 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
1821 if (!IsFailed(r) && priKeyLen != 0)
1823 byte* pPrivateTempKey = null;
1824 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
1825 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
1827 pPrivateKey.reset(null);
1830 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
1831 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
1833 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
1835 if (encodingType == _CERT_ENC_TYPE_PEM)
1837 const byte* pKeyBuffer = pPrivateKey.get();
1838 pBio = BIO_new(BIO_s_mem());
1839 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1841 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, priKeyLen);
1842 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
1844 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
1845 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key to bio conversion failed");
1847 readLength = BIO_read(pBio, pCertList->privatekey, pCertList->priKeyLen);
1849 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
1851 pCertList->priKeyLen = readLength;
1859 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1861 pCertList->priKeyLen = _Base64::GetEncodedSize(priKeyLen);
1862 memset(pCertList->privatekey, 0, sizeof(pCertList->privatekey));
1864 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertList->privatekey), pCertList->priKeyLen);
1865 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1869 memcpy(pCertList->privatekey, pPrivateKey.get(), priKeyLen);
1870 pCertList->priKeyLen = priKeyLen;
1874 pPrivateKey.reset(null);
1876 pHoldList = pCertList.release();
1877 *ppCertListInfoTypes = pHoldList;
1881 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1882 memcpy(subName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
1883 subNameLen = userCertRecord.issuerNameLen;
1887 subjectNameBase64Len = _Base64::GetEncodedSize(subNameLen);
1888 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1889 r = _Base64::Encode(reinterpret_cast< byte* >(subName), subNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1890 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to encode data in base 64 encoding.", GetErrorMessage(r));
1891 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1893 if (strcmp(reinterpret_cast< char* >(issuerNameBase64), reinterpret_cast< char* >(subjectNameBase64)) == 0)
1895 isIssuerNameInList = true;
1898 memset(&certRecord, 0, sizeof(certRecord));
1899 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1900 SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1902 if (strcmp(certRecord.issuerName, certRecord.subjectName) != 0)
1904 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo());
1905 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1907 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1908 pCertList->pNext = null;
1910 r = pFileStore->SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
1911 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1913 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1914 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1915 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1917 if (encodingType == _CERT_ENC_TYPE_PEM)
1919 const byte* pCertBuffer = pCertList->certificate;
1921 pBio = BIO_new(BIO_s_mem());
1922 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1924 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1925 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1927 readLength = PEM_write_bio_X509(pBio, pCert);
1928 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1930 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1932 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1933 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1935 pCertList->length = readLength;
1943 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1945 int certLen = _Base64::GetEncodedSize(pCertList->length);
1946 memset(pCertList->certificate + pCertList->length, 0, sizeof(pCertList->certificate) - pCertList->length);
1947 r = _Base64::Encode(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length, reinterpret_cast< char* >(pCertList->certificate), certLen);
1948 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1949 pCertList->length = certLen;
1951 pCertList->format = (_CertFormat) certRecord.certFormat;
1952 pCertList->certType = (_CaCertType) certRecord.certType;
1953 pCertList->certFileId = certRecord.certId;
1955 pHoldList->pNext = pCertList.release();
1956 pHoldList = pHoldList->pNext;
1960 memset(subName, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE);
1961 memcpy(subName, certRecord.issuerName, certRecord.issuerNameLen);
1962 subNameLen = certRecord.issuerNameLen;
1966 while (strcmp(certRecord.issuerName, certRecord.subjectName));
1968 if (!isIssuerNameInList)
1970 if (*ppCertListInfoTypes != null)
1972 _CertService::FreeCertList(*ppCertListInfoTypes);
1973 *ppCertListInfoTypes = null;
1976 memset(condition, 0, sizeof(condition));
1977 sprintf(condition, "installed = '%s'", installedRecord);
1981 memset(&userCertRecord, 0, sizeof(userCertRecord));
1982 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1983 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1985 curCertId = userCertRecord.certId;
1987 for (readLength = 0; readLength < count; readLength++)
1990 memset(&userCertRecord, 0, sizeof(userCertRecord));
1991 r = __userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &userCertRecord, curCertId);
1992 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate records.", GetErrorMessage(r));
1993 curCertId = userCertRecord.certId;
1998 while (isIssuerNameInList != true);
2011 EVP_PKEY_free(pKey);
2018 _CertDbManager::GetUserCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo, char* pSubjectName)
2020 result r = E_SUCCESS;
2021 UserCertRecord userCertRecord = {0, };
2022 CaCertRecord caCertRecord = {0, };
2023 int subjNameB64len = 0;
2025 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
2026 char conditonRecord[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
2027 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2029 subjNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
2030 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
2031 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjNameB64len);
2032 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2033 sprintf(conditonRecord, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
2035 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &userCertRecord);
2036 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2038 if (pPrivateKeyInfo != null)
2040 pPrivateKeyInfo->SetPrivateKey(userCertRecord.prvKeyPath);
2043 r = pCertChain->AddCertificate(certFormat, userCertRecord.fileName);
2044 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] AddCertificate failed.", GetErrorMessage(r));
2046 parentCa = userCertRecord.parentCa;
2050 memset(&caCertRecord, 0, sizeof(caCertRecord));
2051 memset(conditonRecord, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
2052 sprintf(conditonRecord, "certId = %d and installed = '%s'", parentCa, installedRecord);
2054 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(conditonRecord), &caCertRecord);
2055 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2057 parentCa = caCertRecord.parentCa;
2058 if (caCertRecord.certId != caCertRecord.parentCa) //Exclude root certificate from the chain
2060 r = pCertChain->AddCertificate(certFormat, caCertRecord.fileName);
2061 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to add certificate in chain.", GetErrorMessage(r));
2065 while (caCertRecord.certId != caCertRecord.parentCa);
2071 _CertDbManager::GetUserCertificateInfoByCertId(int certId, int* pSubjectLength, byte* pSubjectName, int* pIssuerLength, byte* pIssuerName)
2073 result r = E_SUCCESS;
2074 UserCertRecord userCertRecord = {0, };
2075 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2076 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2078 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2080 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
2081 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2083 *pSubjectLength = userCertRecord.subjectNameLen;
2084 memcpy(pSubjectName, userCertRecord.subjectName, userCertRecord.subjectNameLen);
2085 *pIssuerLength = userCertRecord.issuerNameLen;
2086 memcpy(pIssuerName, userCertRecord.issuerName, userCertRecord.issuerNameLen);
2093 _CertDbManager::GetUserCertificateInfoByCertId(int certId, _CertEncodingType encodingType, _CertInfo** ppUserCertInfo)
2095 result r = E_SUCCESS;
2096 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
2097 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
2100 int certBufferLen = 0;
2101 int keyBufferLen = 0;
2102 int certificateBase64Len = 0;
2103 const byte* pCertBuffer = null;
2104 const byte* pKeyBuffer = null;
2105 byte* pPrivateTempKey = null;
2106 UserCertRecord certRecord = {0, };
2107 _CertFileStore fileStore;
2108 std::unique_ptr< _CertPrivateKeyInfo > pPriKey;
2111 EVP_PKEY* pKey = null;
2113 *ppUserCertInfo = null;
2115 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
2116 sprintf(condition, "certId = %d and installed = '%s'", certId, installedRecord);
2118 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
2119 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
2121 std::unique_ptr< _CertInfo > pCertInfo(new (std::nothrow) _CertInfo);
2122 SysTryCatch(NID_SEC_CERT, pCertInfo != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2124 memset(pCertInfo.get(), 0, sizeof(*pCertInfo.get()));
2126 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
2127 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to set file handle.", GetErrorMessage(r));
2129 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength);
2130 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[%s] Failed to read from file.", GetErrorMessage(r));
2131 certificateBase64Len = _Base64::GetEncodedSize(pCertInfo->certLength);
2133 if (encodingType == _CERT_ENC_TYPE_PEM)
2135 pBio = BIO_new(BIO_s_mem());
2136 SysTryCatch(NID_SEC_CERT, pBio != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2138 pCertBuffer = new (std::nothrow) byte[pCertInfo->certLength];
2139 SysTryCatch(NID_SEC_CERT, pCertBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2141 memcpy((void*) pCertBuffer, pCertInfo->certificate, pCertInfo->certLength);
2142 certBufferLen = pCertInfo->certLength;
2144 pCert = d2i_X509(null, &pCertBuffer, certBufferLen);
2145 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
2147 readCount = PEM_write_bio_X509(pBio, pCert);
2148 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2150 pCertInfo->certLength = certificateBase64Len + (2 * _MAX_PEM_HEADER);
2151 readCount = BIO_read(pBio, pCertInfo->certificate, pCertInfo->certLength);
2152 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
2154 pCertInfo->certLength = readCount;
2156 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2158 int certLen = _Base64::GetEncodedSize(pCertInfo->certLength);
2159 memset(pCertInfo->certificate + pCertInfo->certLength, 0, sizeof(pCertInfo->certificate) - pCertInfo->certLength);
2160 r = _Base64::Encode(reinterpret_cast< byte* >(pCertInfo->certificate), pCertInfo->certLength, reinterpret_cast< char* >(pCertInfo->certificate), certLen);
2161 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2162 pCertInfo->certLength = certLen;
2164 pCertInfo->certId = certRecord.certId;
2165 pCertInfo->certFormat = (_CertFormat) certRecord.certFormat;
2166 pCertInfo->certType = _CERT_TYPE_USER_CERT;
2168 if (certRecord.prvKeyLen > 0)
2170 pPriKey = std::unique_ptr< _CertPrivateKeyInfo >(new (std::nothrow) _CertPrivateKeyInfo());
2171 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2173 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
2174 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2176 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
2177 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
2178 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
2180 r = fileStore.ReadFromFile(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen);
2181 if (!IsFailed(r) && priKeyLen != 0)
2183 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
2185 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen) + _MAX_PEM_HEADER;
2189 pPrivateKey.reset(null);
2191 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
2192 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2194 pPrivateKey = std::unique_ptr< byte[] >(pPrivateTempKey);
2196 if (encodingType == _CERT_ENC_TYPE_PEM)
2200 pBio = BIO_new(BIO_s_mem());
2201 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
2203 pKeyBuffer = new (std::nothrow) byte[priKeyLen];
2204 SysTryCatch(NID_SEC_CERT, pKeyBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
2206 memcpy((void*) pKeyBuffer, pPrivateKey.get(), priKeyLen);
2207 keyBufferLen = priKeyLen;
2209 pKey = d2i_PrivateKey(EVP_PKEY_RSA, null, &pKeyBuffer, keyBufferLen);
2210 SysTryCatch(NID_SEC_CERT, pKey != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private key conversion failed");
2212 PEM_write_bio_PrivateKey(pBio, pKey, null, null, 0, 0, null);
2214 readCount = BIO_read(pBio, pCertInfo->privatekey, pCertInfo->privateKeyLen);
2215 SysTryCatch(NID_SEC_CERT, readCount > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Private Key conversion failed");
2217 pCertInfo->privateKeyLen = readCount;
2219 else if (encodingType == _CERT_ENC_TYPE_BASE64)
2221 pCertInfo->privateKeyLen = _Base64::GetEncodedSize(priKeyLen);
2222 memset(pCertInfo->privatekey, 0, sizeof(pCertInfo->privatekey));
2223 r = _Base64::Encode(reinterpret_cast< byte* >(pPrivateKey.get()), priKeyLen, reinterpret_cast< char* >(pCertInfo->privatekey), pCertInfo->privateKeyLen);
2224 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
2229 memcpy(pCertInfo->privatekey, pPrivateKey.get(), priKeyLen);
2230 pCertInfo->privateKeyLen = priKeyLen;
2235 *ppUserCertInfo = pCertInfo.release();
2239 if (encodingType == _CERT_ENC_TYPE_PEM)
2243 EVP_PKEY_free(pKey);
2250 } } } //Tizen::Security::Cert