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;
287 //Get the last installed certificate id from db table
288 __caCertDbStore.GetCurrentCertId(certId);
289 //Calculate the new (std::nothrow) certificate id for installation
291 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
293 memset(&certRecord, 0, sizeof(certRecord));
294 certRecord.certType = static_cast< int >(certType);
295 certRecord.certFormat = static_cast< int >(certFormat);
297 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
298 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get file attributes.");
300 strcpy(certRecord.fileName, pFileName.get());
302 certRecord.subjectNameLen = lenSubjectName;
303 memcpy(certRecord.subjectName, subjectName, lenSubjectName);
304 certRecord.issuerNameLen = lenIssuerName;
305 memcpy(certRecord.issuerName, issuerName, lenIssuerName);
306 certRecord.parentCa = certId;
307 strcpy(certRecord.installed, installed);
308 memcpy(certRecord.serialNo, serialName, lenSerialNo);
309 certRecord.serialNoLen = lenSerialNo;
311 r = __caCertDbStore.InsertCaCertificate(&certRecord);
312 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Certificate record insertion failed.", GetErrorMessage(r));
314 fileStore.SetFilePath(tempFileName);
316 r = fileStore.WriteToFile(pDerCertBuffer.get(), derCertBufferLength);
317 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path inaccessible.");
324 _CertDbManager::UpdateCaCertificateFromBuffer(_CaCertType certType, _CertFormat certFormat, byte* pCurCertBuf, int curCertLen, byte* pNewCertBuf, int newCertLen)
326 result r = E_SUCCESS;
328 CaCertRecord certRecord = {0, };
329 CaCertRecord certRecord1 = {0, };
330 _CertFileStore fileStore;
331 _X509TbsCert* pTbsCert = null;
332 _X509TbsCert* pNewTbsCert = null;
333 int lenSubjectName = 0;
334 int lenNewSubjectName = 0;
335 int lenIssuerName = 0;
336 int lenNewIssuerName = 0;
337 int lenNewSerialNo = 0;
339 int subjNameB64len = 0;
340 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
341 char newSubjectName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
342 char newIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
343 char newSerialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
344 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
345 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
346 byte* pNewSerial = null;
348 r = __caCertDbStore.IsRootCaCertTableCreated();
349 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Root certificate tables are not created in database.");
351 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
352 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
354 r = pCert->Parse(pCurCertBuf, curCertLen);
355 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Parse failed.");
357 pTbsCert = pCert->GetTbsCertInstance();
358 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
360 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
361 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
363 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
364 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name exceeds allowable length.");
366 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), lenSubjectName);
367 if (!IsFailed(r)) //checkit
369 subjNameB64len = _Base64::GetEncodedSize(lenSubjectName);
370 SysTryReturnResult(NID_SEC_CERT, subjNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
372 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
374 r = _Base64::Encode(pTbsCert->GetSubjectName(), lenSubjectName, subjectNameBase64, subjNameB64len);
375 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
377 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
378 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
379 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
381 certId = certRecord.parentCa;
383 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, tempFileName);
384 fileStore.SetFilePath(tempFileName);
386 if (certFormat == _CERT_X509)
388 std::unique_ptr< _X509Certificate > pNewCert(new (std::nothrow) _X509Certificate());
389 SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
391 r = pNewCert->Parse(pNewCertBuf, newCertLen);
392 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
394 pNewTbsCert = pNewCert->GetTbsCertInstance();
395 SysTryReturnResult(NID_SEC_CERT, pNewTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
397 strcpy(newSubjectName, reinterpret_cast< const char* >(pNewTbsCert->GetSubjectName()));
398 strcpy(newIssuerName, reinterpret_cast< const char* >((pNewTbsCert->GetIssuerName())));
400 lenNewSubjectName = strlen(newSubjectName);
401 lenNewIssuerName = strlen(newIssuerName);
403 pNewTbsCert->GetSerialNumber(pNewSerial, reinterpret_cast< int& >(lenNewSerialNo));
404 if ((lenNewSerialNo <= 0) || (lenNewSerialNo > _MAX_SERIAL_NUMBER_SIZE))
406 memset(pNewSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
412 memcpy(newSerialName, pNewSerial, lenNewSerialNo);
415 SysTryReturnResult(NID_SEC_CERT, lenNewSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
416 SysTryReturnResult(NID_SEC_CERT, lenNewIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_SYSTEM, "Subject name length exceeds specified length.");
418 certRecord1.certType = static_cast< int >(certType);
419 certRecord1.certFormat = static_cast< int >(certFormat);
421 std::unique_ptr< char[] > pFileName(Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName));
422 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_OPERATION_FAILED, "Failed to get file name.");
424 strcpy(certRecord1.fileName, pFileName.get());
426 certRecord1.subjectNameLen = lenNewSubjectName;
427 memcpy(certRecord1.subjectName, newSubjectName, lenNewSubjectName);
428 certRecord1.issuerNameLen = lenIssuerName;
429 memcpy(certRecord1.issuerName, newIssuerName, lenNewIssuerName);
430 certRecord1.parentCa = certId;
431 strcpy(certRecord1.installed, certRecord.installed);
432 memcpy(certRecord1.serialNo, newSerialName, lenNewSerialNo);
433 certRecord1.serialNoLen = lenNewSerialNo;
435 r = __caCertDbStore.UpdateCaCertificate(&certRecord, &certRecord1);
436 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to update ca certificate.");
438 fileStore.DeleteFile();
440 r = fileStore.WriteToFile(pNewCertBuf, newCertLen);
441 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Path does not exist.");
442 //No need to update record as only file data changed.
447 return E_FILE_ALREADY_EXIST;
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, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db.");
479 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
480 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
482 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate id.", GetErrorMessage(r));
485 r = __caCertDbStore.RemoveCertificateById(certId);
486 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate with certificate id (%d).", certId);
489 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
490 Tizen::Io::File::Remove(fileName);
497 _CertDbManager::RemoveCertificateChainByCertId(int certId)
499 result r = E_SUCCESS;
500 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
501 UserCertRecord userCertRecord = {0, };
503 memset(&userCertRecord, 0, sizeof(userCertRecord));
504 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
506 sprintf(condition, "certId = %d", certId);
507 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
508 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
509 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
511 r = DeleteCertificateChain(userCertRecord.certId, userCertRecord.parentCa);
512 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "File deletion failed for certificate Id (%d).", certId);
519 _CertDbManager::GetCaCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId, _CaCertType certType)
521 result r = E_SUCCESS;
522 int subjNameB64len = 0;
523 int issuerB64len = 0;
524 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
525 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
526 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
527 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
528 CaCertRecord caCertRecord = {0, };
530 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
531 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
533 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
534 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
536 r = _Base64::Encode(pSubjectName, subjectNameSize, subjectNameBase64, subjNameB64len);
537 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
539 memset(condition, 0, sizeof(condition));
541 if (pIssuerName != null && issuerNameSize > 0)
543 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
544 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
546 r = _Base64::Encode(pIssuerName, issuerNameSize, issuerNameBase64, issuerB64len);
547 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
549 if (certType == _CERT_TYPE_NOT_BOUNDED)
551 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
555 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, issuerNameBase64, certType, installed);
560 if (certType == _CERT_TYPE_NOT_BOUNDED)
562 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
566 sprintf(condition, "subjectName = '%s' and certType = %d and installed = '%s'", subjectNameBase64, certType, installed);
570 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &caCertRecord);
571 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
573 certId = caCertRecord.certId;
579 _CertDbManager::GetUserCertificateId(byte* pSubjectName, int subjectNameSize, byte* pIssuerName, int issuerNameSize, int& certId)
581 result r = E_SUCCESS;
582 int subjNameB64len = 0;
583 int issuerB64len = 0;
584 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
585 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
586 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
587 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
588 UserCertRecord userCertRecord = {0, };
590 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid subject name.");
591 SysTryReturnResult(NID_SEC_CERT, subjectNameSize > 0, E_INVALID_ARG, "Invalid subject name length.");
593 subjNameB64len = _Base64::GetEncodedSize(subjectNameSize);
594 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
596 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameSize, subjectNameBase64, subjNameB64len);
597 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
599 memset(condition, 0, sizeof(condition));
601 if (pIssuerName != null && issuerNameSize > 0)
603 issuerB64len = _Base64::GetEncodedSize(issuerNameSize);
604 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
606 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameSize, issuerNameBase64, issuerB64len);
607 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
609 sprintf(condition, "subjectName = '%s' and issuerName = '%s' and installed = '%s'", subjectNameBase64, issuerNameBase64, installed);
613 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installed);
616 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
617 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
619 certId = userCertRecord.certId;
625 _CertDbManager::RemoveAllUserCertificate(void)
627 __userCertDbStore.DeleteUserCertFiles();
633 _CertDbManager::DeleteCertificateChain(int devCertId, int devParentCA)
635 result r = E_SUCCESS;
636 CaCertRecord certRecord = {0, };
640 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
641 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0, };
644 SysTryReturnResult(NID_SEC_CERT, devCertId > 0, E_INVALID_ARG, "Invalid input argument.");
645 SysTryReturnResult(NID_SEC_CERT, devParentCA > 0, E_INVALID_ARG, "Invalid input argument.");
647 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
649 sprintf(condition, "parentCa = %d and installed = '%s'", devParentCA, installed);
650 //Check if any other device certificate has same parent as of referred device certificare. If it is yes then we
651 //delete only device certificate and return. We cannot disturb another chain.
652 __userCertDbStore.GetCountByCondition(reinterpret_cast< byte* >(&condition), recCount);
653 //More than one device certificate found which is referring same intermidiate CA or ROOT CA. So just delete device certificate and return.
656 r = DeleteCertificateByIdNTableName(devCertId, _CERT_USER_CERT_TABLE);
657 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
661 //Now there is not two device certificate with same intermidiate CA,
662 //so go ahead to intermidiate CA and delete device certificate.
663 caParentCa = devParentCA;
664 caCertId = devCertId;
667 if (__caCertDbStore.CheckIfSameParent(caParentCa) == E_SUCCESS)
671 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
672 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
674 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
675 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
676 break; // break here next certificate has dependency
680 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
681 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate.");
683 break; // break here next certificate has dependency
686 else // The caCertId's parent is no more parent of any other certificate so delete caCertId from Db.
688 if (devCert) //If it is device certificate
690 r = DeleteCertificateByIdNTableName(caCertId, _CERT_USER_CERT_TABLE);
691 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OPERATION_FAILED, "Failed to delete certificate table.");
693 devCert = false; //Device certificate is deleted here now go to CA certificate for deletion
694 SysLog(NID_SEC_CERT, "Device certificate is deleted here now go to CA certificate for deletion.");
696 else //If it is CA certificate and there is no dependency
698 r = DeleteCertificateByIdNTableName(caCertId, _CERT_ROOT_CA_CERT_TABLE);
699 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate table.");
701 SysLog(NID_SEC_CERT, "It is CA certificate and there is no dependency.");
703 caCertId = caParentCa; // Now look for next certificate in chain
704 memset(condition, 0, _MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE);
705 sprintf(condition, "certId = %d and installed = '%s'", devParentCA, installed);
706 memset(&certRecord, 0, sizeof(certRecord));
707 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
708 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
709 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
711 caParentCa = certRecord.parentCa;
714 while (caCertId != caParentCa);
720 _CertDbManager::GetCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
722 result r = E_SUCCESS;
723 CaCertRecord certRecord = {0, };
724 _CertificateListInfo* pHoldList = null;
725 _CertFileStore fileStore;
728 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
729 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
731 sprintf(condition, "certFormat = %d and certType != %d and installed = '%s'", certFormat, _CERT_TYPE_INTERMIDIATE_CA, installed);
733 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
734 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
735 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
737 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
738 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
740 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
741 pCertList->pNext = null;
742 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
743 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
745 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
746 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
748 pCertList->length = certLength;
749 pCertList->certFileId = certRecord.certId;
750 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
751 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
754 pHoldList = pCertList.release();
755 *ppCertList = pHoldList;
757 while (__caCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
759 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
760 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
762 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
764 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
765 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
767 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
768 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
770 pCertList->pNext = null;
771 pCertList->length = certLength;
772 pCertList->certFileId = certRecord.certId;
773 pCertList->format = (_CertFormat) certRecord.certFormat;
774 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
776 pHoldList->pNext = pCertList.release();
777 pHoldList = pHoldList->pNext;
789 _CertDbManager::GetUserCertificateListByFormat(_CertFormat certFormat, _CertificateListInfo** ppCertList, int& count)
791 result r = E_SUCCESS;
792 UserCertRecord certRecord = {0, };
793 _CertificateListInfo* pHoldList = null;
794 _CertFileStore fileStore;
797 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
798 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
802 sprintf(condition, "certFormat = %d and installed = '%s'", certFormat, installed);
804 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
805 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r) || r == E_DATA_NOT_FOUND, E_SYSTEM, "Failed to get certificate record.");
806 SysTryReturnResult(NID_SEC_CERT, r != E_DATA_NOT_FOUND, E_SUCCESS, "No such record found.");
808 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
809 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
811 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
812 pCertList->pNext = null;
814 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
815 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
817 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
818 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
820 pCertList->length = certLength;
821 pCertList->certFileId = certRecord.certId;
822 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
823 pCertList->certType = _CERT_TYPE_USER_CERT;
826 pHoldList = pCertList.release();
827 *ppCertList = pHoldList;
829 while (__userCertDbStore.GetNextRecordByCondition(reinterpret_cast< byte* >(condition), &certRecord, certRecord.certId) == E_SUCCESS)
831 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
832 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
834 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
836 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
837 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
839 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
840 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
842 pCertList->pNext = null;
843 pCertList->length = certLength;
844 pCertList->certFileId = certRecord.certId;
845 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
846 pCertList->certType = _CERT_TYPE_USER_CERT;
848 pHoldList->pNext = pCertList.release();
849 pHoldList = pHoldList->pNext;
860 _CertDbManager::GetCaCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
862 result r = E_SUCCESS;
863 CaCertRecord certRecord = {0, };
864 _CertFileStore fileStore;
866 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
867 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
870 sprintf(condition, "certId = %d and certType != %d and installed = '%s'", certId, _CERT_TYPE_INTERMIDIATE_CA, installed);
872 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
873 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
875 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
876 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
878 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
880 pCertList->pNext = null;
881 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_CA_CERT);
882 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
884 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
885 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
887 pCertList->length = certLength;
888 pCertList->certFileId = certRecord.certId;
889 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
890 pCertList->certType = static_cast< _CaCertType >(certRecord.certType);
892 *ppCertList = pCertList.release();
898 _CertDbManager::GetUserCertificateListByCertId(int certId, _CertificateListInfo** ppCertList)
900 result r = E_SUCCESS;
901 _CertFileStore fileStore;
902 UserCertRecord certRecord = {0, };
905 char condition[_MAX_TYPE_CONST_SIZE] = {0, };
906 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
910 SysTryReturnResult(NID_SEC_CERT, ppCertList != null, E_INVALID_ARG, "Invalid input arguments.");
911 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input arguments.");
913 sprintf(condition, "certId = %d and installed = '%s'", certId, installed);
914 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
915 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
917 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
918 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
920 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
922 pCertList->pNext = null;
924 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_USER_CERT);
925 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
927 r = fileStore.ReadFromFile(pCertList->certificate, certLength);
928 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
930 pCertList->length = certLength;
931 pCertList->certFileId = certRecord.certId;
932 pCertList->format = static_cast< _CertFormat >(certRecord.certFormat);
933 pCertList->certType = _CERT_TYPE_USER_CERT;
935 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
936 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
938 std::unique_ptr< byte[] > pPrivateKey(new (std::nothrow) byte[_MAX_CERT_PRIVATE_KEY_SIZE]);
939 SysTryReturnResult(NID_SEC_CERT, pPrivateKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
941 memset(pPrivateKey.get(), 0, _MAX_CERT_PRIVATE_KEY_SIZE);
943 r = fileStore.SetFileHandle(certRecord.certId, _CERT_PATH_PRIVATE_KEY);
944 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
946 r = fileStore.ReadFromFile(pPrivateKey.get(), priKeyLen);
947 if (!IsFailed(r) && priKeyLen != 0)
949 byte* pPrivateTempKey = null;
950 pPriKey->SetPrivateKey(priKeyLen, pPrivateKey.get());
952 pPrivateKey.reset(null);
954 pPriKey->GetPkcs8EncDecKeyN(priKeyLen, &pPrivateTempKey, 0);
955 SysTryReturnResult(NID_SEC_CERT, pPrivateTempKey != null, E_SYSTEM, "Failed to get private key buffer.");
957 std::unique_ptr< byte[] > pPrivateKeyAuto(pPrivateTempKey);
959 memcpy(pCertList->privatekey, pPrivateTempKey, priKeyLen);
961 pCertList->priKeyLen = priKeyLen;
963 *ppCertList = pCertList.release();
969 _CertDbManager::FindIssuerCertificateAndTypeN(_CertFormat certFormat, char* pIssuerName, byte** ppCert, int& certLen, _CaCertType& certType)
971 result r = E_SUCCESS;
972 CaCertRecord certRecord = {0, };
973 _CertFileStore fileStore;
975 int issuerNameB64len = 0;
976 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_OFFSET_CONST_SIZE] = {0, };
977 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
978 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
980 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
981 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
982 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
984 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
985 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
987 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
989 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
990 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
992 sprintf(condition, "subjectName = '%s' and certFormat = %d and installed = '%s'", issuerNameBase64, certFormat, installed);
994 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
995 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
997 filePath = reinterpret_cast< char* >(certRecord.fileName);
999 fileStore.SetFilePath(filePath);
1001 *ppCert = new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE];
1002 SysTryReturnResult(NID_SEC_CERT, *ppCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1004 r = fileStore.ReadFromFile(*ppCert, certLen);
1005 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1007 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1013 _CertDbManager::FindIssuerCertificateByTypeN(_CertFormat certFormat, _CaCertType certType, char* pIssuerName, byte** ppCert, int& certLen)
1015 result r = E_SUCCESS;
1017 CaCertRecord certRecord = {0, };
1018 _CertFileStore fileStore;
1019 int issuerNameB64len = 0;
1020 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_CONDITION_SIZE] = {0, };
1021 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_NAME_OFFSET] = {0, };
1022 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1024 SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1025 SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1026 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1027 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1028 SysTryReturnResult(NID_SEC_CERT, ppCert != null, E_INVALID_ARG, "Invalid input arguments.");
1030 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1031 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to get encoded size.");
1033 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1035 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1036 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1038 sprintf(condition, "subjectName = '%s' and certFormat = %d and certType = %d and installed = '%s'", issuerNameBase64, certFormat, certType, installed);
1039 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1040 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1042 if (certRecord.certId == 0)
1047 filePath = static_cast< char* >(certRecord.fileName);
1048 fileStore.SetFilePath(filePath);
1050 std::unique_ptr< byte[] > pCert(new (std::nothrow) byte[_MAX_CERTIFICATE_SIZE]);
1051 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1053 r = fileStore.ReadFromFile(pCert.get(), certLen);
1054 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to read from file.", GetErrorMessage(r));
1056 certType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1058 *ppCert = pCert.release();
1064 _CertDbManager::FindCertType(_CertFormat certFormat, char* pIssuerName, char* pSubjectName, _CaCertType* pCertType)
1066 result r = E_SUCCESS;
1067 CaCertRecord certRecord = {0, };
1068 _CertFileStore fileStore;
1069 int subjectNameB64len = 0;
1070 int issuerNameB64len = 0;
1071 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_CONDITION_CONST_SIZE] = {0, };
1072 char subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1073 char issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1074 char installed[_MAX_TYPE_RECORD_SIZE] = "T\0";
1076 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1077 SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid input arguments.");
1078 SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid input arguments.");
1079 SysTryReturnResult(NID_SEC_CERT, pCertType != null, E_INVALID_ARG, "Invalid input arguments.");
1081 issuerNameB64len = _Base64::GetEncodedSize(strlen(pIssuerName));
1082 SysTryReturnResult(NID_SEC_CERT, issuerNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1084 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1086 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), strlen(pIssuerName), issuerNameBase64, issuerNameB64len);
1087 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1089 subjectNameB64len = _Base64::GetEncodedSize(strlen(pSubjectName));
1090 SysTryReturnResult(NID_SEC_CERT, subjectNameB64len >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1092 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1093 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), strlen(pSubjectName), subjectNameBase64, subjectNameB64len);
1094 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1096 sprintf(condition, "certFormat = %d and issuerName = '%s' and subjectName = '%s' and installed = '%s'", certFormat, issuerNameBase64, subjectNameBase64, installed);
1097 r = __caCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &certRecord);
1098 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate record.", GetErrorMessage(r));
1100 *pCertType = static_cast< _CaCertType >(certRecord.certType); //Get the type of certificate
1105 _CertDbManager::DeleteCertificateByIdNTableName(int certId, String tableName)
1107 result r = E_SUCCESS;
1108 _CertFileStore fileStore;
1111 SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input argument.");
1113 if (tableName.CompareTo(_CERT_USER_CERT_TABLE) == 0)
1117 r = __userCertDbStore.RemoveCertificateById(certId);
1118 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Error in deleting certificate.");
1120 //Remove certificate file
1121 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, fileName);
1122 r = Tizen::Io::File::Remove(fileName);
1123 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1125 //Remove private key file
1126 //Don't check return type here as it is not necessary that private key is present.
1127 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, keyfileName);
1128 r = Tizen::Io::File::Remove(keyfileName);
1130 else if (tableName.CompareTo(_CERT_ROOT_CA_CERT_TABLE) == 0)
1132 r = __caCertDbStore.RemoveCertificateById(certId);
1133 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Delete certificate failed.");
1135 //Remove certificate file
1136 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_CA_CERT, fileName);
1137 r = Tizen::Io::File::Remove(fileName);
1138 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_FILE_NOT_FOUND, "Error in deleting file.");
1144 _CertDbManager::GetHashOfCertFile(byte* pFilePath, int* pLen, char* pBuf)
1146 result r = E_SUCCESS;
1147 String fileName(reinterpret_cast< char* >(pFilePath));
1148 FileAttributes attr;
1153 int outLen = _MAX_CERT_SHA1_DIGEST_SIZE;
1156 SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid inpur arguments.");
1157 SysTryReturnResult(NID_SEC_CERT, pLen != null, E_INVALID_ARG, "Invalid inpur arguments.");
1158 SysTryReturnResult(NID_SEC_CERT, pBuf != null, E_INVALID_ARG, "Invalid inpur arguments.");
1160 r = File::GetAttributes(fileName, attr);
1161 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get attributes.");
1163 fileSize = attr.GetFileSize();
1164 SysTryReturn(NID_SEC_CERT, fileSize >= 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1165 SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1168 r = file.Construct(fileName, L"r");
1169 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to construct file.");
1171 std::unique_ptr< byte[] > pCertBuf(new (std::nothrow) byte[fileSize + 1]);
1172 SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1174 memset(pCertBuf.get(), 0, fileSize + 1);
1175 readCnt = file.Read(pCertBuf.get(), fileSize);
1176 r = GetLastResult();
1177 SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1180 std::unique_ptr< byte[] > pOutBuf(new (std::nothrow) byte[outLen]);
1181 SysTryReturnResult(NID_SEC_CERT, pOutBuf != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1183 memset(pOutBuf.get(), 0, outLen);
1184 //As per OpenSSL APIs, it takes input as unsigned data types
1185 resValue = EVP_Digest(pCertBuf.get(), static_cast< int >(certLen), pOutBuf.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
1186 SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to create digest.");
1188 memcpy(pBuf, pOutBuf.get(), outLen);
1194 //User Certificate APIs
1197 _CertDbManager::InsertCertChain(_CertFormat certFormat, _CertChain* pCertChain)
1199 result r = E_SUCCESS;
1200 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1201 int curCACertId = 0;
1202 int lastCACertId = 0;
1203 int curDevCertId = 0;
1204 bool updateUserParentCa = false;
1206 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1207 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1209 //Check for CA certificate table creation
1210 r = __caCertDbStore.IsRootCaCertTableCreated();
1211 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Certificate table are not not created.");
1214 //Check if the chain is valid or not
1215 r = pCertChain->Verify();
1216 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INVALID_ARG, "Invalid certificate chain.");
1218 r = pCertChain->MoveHead();
1219 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1221 if (certFormat == _CERT_X509)
1223 _X509Certificate* pCurCert = null;
1224 _X509Certificate* pUserCert = null;
1225 _X509TbsCert* pTbsCert = null;
1226 byte* pX509Buff = null;
1227 int x509BuffSize = 0;
1229 pUserCert = pCertChain->GetCurrentCertificate();
1230 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1232 pTbsCert = pUserCert->GetTbsCertInstance();
1233 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1235 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1236 SysTryReturn(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate buffer.");
1238 r = InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, null, 0);
1239 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));
1241 updateUserParentCa = true;
1243 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1244 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1246 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1248 //Insert certificate chain in CA certificate store
1249 while (pCertChain->MoveNext() == E_SUCCESS)
1252 pCurCert = pCertChain->GetCurrentCertificate();
1253 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1255 if (!pCurCert->IsSelfSigned())
1257 certType = _CERT_TYPE_INTERMIDIATE_CA;
1261 //This parameter need to pass from certificate manager about its type
1262 certType = _CERT_TYPE_ROOT_CA;
1265 pTbsCert = pCurCert->GetTbsCertInstance();
1266 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1268 if (E_SUCCESS != __caCertDbStore.CheckDuplicateCertificate(certType, reinterpret_cast< byte* >(pTbsCert->GetSubjectName()), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()))))
1273 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1274 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1276 r = InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1277 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1279 // CA certificate already present or properly installed in CA certificate store,
1280 // get the certificate id of certificate
1281 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1282 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1283 curCACertId, certType);
1284 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1286 if (updateUserParentCa)
1288 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1289 updateUserParentCa = false;
1290 lastCACertId = curCACertId;
1294 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1295 lastCACertId = curCACertId;
1298 //If it is root certificate then its parent is itself
1299 if (pCurCert->IsSelfSigned())
1301 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1306 if (updateUserParentCa)
1308 r = pCertChain->MoveHead();
1309 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1311 pCurCert = pCertChain->GetCurrentCertificate();
1312 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1314 pTbsCert = pCurCert->GetTbsCertInstance();
1315 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1317 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1318 null, 0, curCACertId);
1319 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1321 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1322 updateUserParentCa = false;
1323 lastCACertId = curCACertId;
1325 else if (!pCurCert->IsSelfSigned())
1327 pTbsCert = pCurCert->GetTbsCertInstance();
1328 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1330 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1331 null, 0, curCACertId);
1332 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1334 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1335 lastCACertId = curCACertId;
1343 _CertDbManager::InsertCertificateChain(_CertFormat certFormat, _CertChain* pCertChain, _CertPrivateKeyInfo* pPrivateKeyInfo)
1345 result r = E_SUCCESS;
1346 _CaCertType certType = _CERT_TYPE_NOT_BOUNDED;
1348 int curCACertId = 0;
1349 int lastCACertId = 0;
1350 int curDevCertId = 0;
1352 bool updateUserParentCa = false;
1353 byte* pPrvKey = null;
1354 std::unique_ptr< byte[] > pPrvKeyBuffer;
1356 SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_INVALID_ARG, "Invalid input parameter.");
1357 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1359 r = __userCertDbStore.IsUserCertTableCreated();
1360 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1362 //Check for CA certificate table creation
1363 r = __caCertDbStore.IsRootCaCertTableCreated();
1364 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
1366 //Check if the chain is valid or not
1367 r = pCertChain->Verify();
1368 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate.", GetErrorMessage(r));
1370 r = pCertChain->MoveHead();
1371 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1373 if (certFormat == _CERT_X509)
1375 _X509Certificate* pCurCert = null;
1376 _X509Certificate* pUserCert = null;
1377 _X509TbsCert* pTbsCert = null;
1378 byte* pX509Buff = null;
1379 int x509BuffSize = 0;
1381 pUserCert = pCertChain->GetCurrentCertificate();
1382 SysTryReturnResult(NID_SEC_CERT, pUserCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1384 pTbsCert = pUserCert->GetTbsCertInstance();
1385 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1387 byte* pSubjectName = pTbsCert->GetSubjectName();
1388 SysTryReturn(NID_SEC_CERT, pSubjectName != null, E_OBJ_NOT_FOUND, E_OBJ_NOT_FOUND, "[E_OBJ_NOT_FOUND] Subjectname not present.");
1390 int subjectNameLen = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1392 r = __userCertDbStore.CheckDuplicateCertificate(pSubjectName, subjectNameLen);
1395 if (pPrivateKeyInfo != null)
1397 pPrivateKeyInfo->GetPkcs8EncDecKeyN(prvKeyLen, &pPrvKey, 1);
1398 SysTryReturnResult(NID_SEC_CERT, prvKeyLen > 0, E_INVALID_KEY, "Invalid key length .");
1400 pPrvKeyBuffer = std::unique_ptr< byte[] >(pPrvKey);
1405 pUserCert->GetCertBuffer(pX509Buff, x509BuffSize);
1406 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1408 r = _CertDbManager::InsertUserCertificateFromBuffer(certFormat, pX509Buff, x509BuffSize, pPrvKeyBuffer.get(), static_cast< int >(prvKeyLen));
1409 if (IsFailed(r) && r != E_OBJ_ALREADY_EXIST && r != E_FILE_ALREADY_EXIST)
1415 updateUserParentCa = true;
1417 r = GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1418 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1420 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get user certificate id.", GetErrorMessage(r));
1422 if (pPrvKeyBuffer != null)
1424 _CertFileStore fileStore;
1425 String privateKeyFile;
1427 fileStore.GetFileNameFromHandle(curDevCertId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1428 fileStore.SetFilePath(privateKeyFile);
1431 r = fileStore.WriteToFile(pPrvKeyBuffer.get(), prvKeyLen);
1432 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1442 if (pUserCert->IsSelfSigned())
1444 __userCertDbStore.UpdateParentCa(curDevCertId, curDevCertId);
1448 //Insert certificate chain in CA certificate store
1449 while (pCertChain->MoveNext() == E_SUCCESS)
1451 pCurCert = pCertChain->GetCurrentCertificate();
1452 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1454 if (!pCurCert->IsSelfSigned())
1456 certType = _CERT_TYPE_INTERMIDIATE_CA;
1460 //This parameter need to pass from certificate manager about its type
1461 certType = _CERT_TYPE_ROOT_CA;
1464 pTbsCert = pCurCert->GetTbsCertInstance();
1465 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1467 r = __caCertDbStore.CheckDuplicateCertificate(certType, pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())));
1473 pCurCert->GetCertBuffer(pX509Buff, x509BuffSize);
1474 SysTryReturnResult(NID_SEC_CERT, pX509Buff != null, E_SYSTEM, "Failed to get certificate buffer.");
1476 r = _CertDbManager::InsertCaCertificateFromBuffer(certType, certFormat, pX509Buff, x509BuffSize);
1477 SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[E_SYSTEM] Failed to insert ca certificate.");
1480 // CA certificate already present or properly install in CA certificate store,
1481 // get the certificate id of certificate
1483 r = GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
1484 pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1485 curCACertId, certType);
1486 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1488 if (updateUserParentCa)
1490 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1491 updateUserParentCa = false;
1492 lastCACertId = curCACertId;
1496 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1497 lastCACertId = curCACertId;
1500 //If it is root certificate then its parent is itself
1501 if (pCurCert->IsSelfSigned())
1503 __caCertDbStore.UpdateParentCa(curCACertId, curCACertId);
1507 if (updateUserParentCa)
1509 r = pCertChain->MoveHead();
1510 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to move head in certificate chain.");
1512 pCurCert = pCertChain->GetCurrentCertificate();
1513 SysTryReturnResult(NID_SEC_CERT, pCurCert != null, E_SYSTEM, "Failed to get certificate from chain, broken certificate chain.");
1515 pTbsCert = pCurCert->GetTbsCertInstance();
1516 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1518 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1519 null, 0, curCACertId);
1520 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1522 __userCertDbStore.UpdateParentCa(curDevCertId, curCACertId);
1523 updateUserParentCa = false;
1524 lastCACertId = curCACertId;
1526 else if (!pCurCert->IsSelfSigned())
1528 pTbsCert = pCurCert->GetTbsCertInstance();
1529 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1531 r = GetCaCertificateId(pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
1532 null, 0, curCACertId);
1533 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id.", GetErrorMessage(r));
1535 __caCertDbStore.UpdateParentCa(lastCACertId, curCACertId);
1536 lastCACertId = curCACertId;
1544 _CertDbManager::InsertUserCertificateFromBuffer(_CertFormat certFormat, byte* pCertBuffer, int certLength, byte* pPrivateKey, int privateKeyLen, int parentCa)
1546 result r = E_SUCCESS;
1547 _X509TbsCert* pTbsCert = null;
1548 _CertFileStore fileStore;
1549 UserCertRecord certRecord = {0, };
1550 String privateKeyFile;
1551 String tempFileName;
1552 int lenSubjectName = 0;
1553 int lenIssuerName = 0;
1554 int lenSerialNo = 0;
1556 int keyIdB64Length = 0;
1557 char* pFileName = null;
1558 char* pPriKeyFileName = null;
1559 char subjectNameBuffer[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1560 char szIssuerName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1561 char serialName[_MAX_SERIAL_NUMBER_SIZE] = {0, };
1562 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1563 byte* pKeyId = null;
1564 byte* pSerial = null;
1566 //pPrivateKey, privateKeyLen, parentca are optional parameter, no need to sanity check for them.
1567 SysTryReturnResult(NID_SEC_CERT, pCertBuffer != null, E_INVALID_ARG, "Invalid input parameter.");
1568 SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1569 SysTryReturnResult(NID_SEC_CERT, certLength > 0, E_INVALID_ARG, "Invalid input parameter.");
1571 r = __userCertDbStore.IsUserCertTableCreated();
1572 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create user certificate.");
1574 std::unique_ptr< _X509Certificate > pCert(new (std::nothrow) _X509Certificate());
1575 SysTryReturnResult(NID_SEC_CERT, pCert != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1577 r = pCert->Parse(pCertBuffer, certLength);
1578 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Parsing failed.", GetErrorMessage(r));
1580 pTbsCert = pCert->GetTbsCertInstance();
1581 SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
1583 lenSubjectName = strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1584 lenIssuerName = strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1586 SysTryReturnResult(NID_SEC_CERT, lenSubjectName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1587 SysTryReturnResult(NID_SEC_CERT, lenIssuerName < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_DATABASE, "Length is greater than maximum allowed length.");
1589 strcpy(subjectNameBuffer, reinterpret_cast< char* >(pTbsCert->GetSubjectName()));
1590 strcpy(szIssuerName, reinterpret_cast< char* >(pTbsCert->GetIssuerName()));
1592 pTbsCert->GetSerialNumber(pSerial, static_cast< int& >(lenSerialNo));
1593 if ((lenSerialNo <= 0) || (lenSerialNo > _MAX_SERIAL_NUMBER_SIZE))
1595 if (pSerial != null)
1597 memset(pSerial, 0, _MAX_SERIAL_NUMBER_SIZE);
1603 memcpy(serialName, pSerial, lenSerialNo);
1607 r = pCert->GetKeyIdN(&pKeyId);
1608 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Failed to get key Id.");
1610 std::unique_ptr< byte[] > pKeyIdBuffer(pKeyId);
1612 keyIdB64Length = _Base64::GetEncodedSize(_MAX_CERT_SHA1_DIGEST_SIZE);
1613 SysTryReturnResult(NID_SEC_CERT, keyIdB64Length >= 0, E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1615 std::unique_ptr< char[] > pId64(new (std::nothrow) char[keyIdB64Length]);
1616 SysTryReturnResult(NID_SEC_CERT, pId64 != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1618 memset(pId64.get(), 0, keyIdB64Length);
1619 r = _Base64::Encode(reinterpret_cast< byte* >(pKeyIdBuffer.get()), _MAX_CERT_SHA1_DIGEST_SIZE, pId64.get(), keyIdB64Length);
1620 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DECODING_FAILED, "Decoding failed.");
1622 r = __userCertDbStore.CheckDuplicateCertificate(reinterpret_cast< byte* >(subjectNameBuffer), lenSubjectName);
1623 SysTryReturnResult(NID_SEC_CERT, IsFailed(r), E_FILE_ALREADY_EXIST, "File already exists.");
1625 //Get the last installed certificate id from db table
1626 __userCertDbStore.GetCurrentCertId(certId);
1628 //Calculate the new certificate id for installation
1629 certId = certId + 1;
1631 if (pPrivateKey != null)
1633 //Get file name for private key and store private key into file.
1634 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_PRIVATE_KEY, privateKeyFile);
1638 pPriKeyFileName = null;
1642 //Get file name for certificate and write device certificate to file
1643 fileStore.GetFileNameFromHandle(certId, _CERT_PATH_USER_CERT, tempFileName);
1645 //Insert Record into Database
1646 //It is generated automatically by sequence
1647 memset(&certRecord, 0, sizeof(certRecord));
1649 memcpy(certRecord.certPubKeyHash, pId64.get(), keyIdB64Length); //Base64 encoded device id
1650 certRecord.certFormat = static_cast< int >(certFormat);
1652 pFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(tempFileName);
1653 SysTryReturnResult(NID_SEC_CERT, pFileName != null, E_SYSTEM, "Failed to get attributes.");
1655 strcpy(certRecord.fileName, pFileName);
1656 certRecord.subjectNameLen = lenSubjectName;
1658 memcpy(certRecord.subjectName, subjectNameBuffer, lenSubjectName);
1659 certRecord.issuerNameLen = lenIssuerName;
1660 memcpy(certRecord.issuerName, szIssuerName, lenIssuerName);
1662 pPriKeyFileName = Tizen::Base::_StringConverter::CopyToCharArrayN(privateKeyFile);
1663 SysTryReturnResult(NID_SEC_CERT, pPriKeyFileName != null, E_SYSTEM, "Failed to get attributes.");
1665 strcpy(certRecord.prvKeyPath, pPriKeyFileName);
1666 certRecord.prvKeyLen = privateKeyLen;
1667 certRecord.parentCa = certId;
1668 strcpy(certRecord.installed, installedRecord);
1670 memcpy(certRecord.serialNo, serialName, lenSerialNo);
1672 certRecord.serialNoLen = lenSerialNo;
1674 r = __userCertDbStore.InsertUserCertificate(&certRecord);
1675 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_DATABASE, "Failed to insert user certificate.");
1677 fileStore.SetFilePath(tempFileName);
1679 r = fileStore.WriteToFile(pCertBuffer, certLength);
1680 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1682 if (pPrivateKey != null)
1684 fileStore.SetFilePath(privateKeyFile);
1686 r = fileStore.WriteToFile(pPrivateKey, privateKeyLen);
1687 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_INACCESSIBLE_PATH, "Failed to write in file.");
1694 _CertDbManager::GetUserCertificateChain(char* pIssuerName, int issuerNameLen, char* pSubjectName, int subjectNameLen, _CertEncodingType encodingType, _CertificateListInfo** ppCertListInfoTypes)
1696 result r = E_SUCCESS;
1697 CaCertRecord certRecord = {0, };
1698 UserCertRecord userCertRecord = {0, };
1699 _CertificateListInfo* pHoldList = null;
1702 EVP_PKEY* pKey = null;
1704 int recordCount = 0;
1705 int subjectNameBase64Len = 0;
1711 int certificateBase64Len = 0;
1712 char installedRecord[_MAX_TYPE_RECORD_SIZE] = "T\0";
1713 char condition[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_SUBJECT_OFFSET_SIZE] = {0};
1714 byte issuerNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1715 byte subjectNameBase64[_MAX_ISSUER_SUBJECT_NAME_SIZE + _MAX_ISSUER_OFFSET_SIZE] = {0, };
1716 byte subName[_MAX_ISSUER_SUBJECT_NAME_SIZE] = {0, };
1717 bool isIssuerNameInList = false;
1719 subjectNameBase64Len = _Base64::GetEncodedSize(issuerNameLen);
1720 memset(issuerNameBase64, 0, sizeof(issuerNameBase64));
1721 r = _Base64::Encode(reinterpret_cast< byte* >(pIssuerName), issuerNameLen, reinterpret_cast< char* >(issuerNameBase64), subjectNameBase64Len);
1722 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1724 if ((pSubjectName != null) && (subjectNameLen > 0))
1726 subjectNameBase64Len = _Base64::GetEncodedSize(subjectNameLen);
1727 memset(subjectNameBase64, 0, sizeof(subjectNameBase64));
1728 r = _Base64::Encode(reinterpret_cast< byte* >(pSubjectName), subjectNameLen, reinterpret_cast< char* >(subjectNameBase64), subjectNameBase64Len);
1729 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_ENCODING_FAILED, "Failed to encode data in base 64 encoding.");
1730 sprintf(condition, "subjectName = '%s' and installed = '%s'", subjectNameBase64, installedRecord);
1734 r = __userCertDbStore.GetNumberOfCertificates(recordCount);
1735 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates.", GetErrorMessage(r));
1736 SysTryReturnResult(NID_SEC_CERT, recordCount > 0, E_OBJ_NOT_FOUND, "Failed to get certificate records.");
1737 sprintf(condition, "installed = '%s'", installedRecord);
1740 memset(&userCertRecord, 0, sizeof(userCertRecord));
1741 r = __userCertDbStore.GetFirstRecordByConditions(reinterpret_cast< byte* >(condition), &userCertRecord);
1742 SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificates record.", GetErrorMessage(r));
1744 std::unique_ptr< _CertPrivateKeyInfo > pPriKey(new (std::nothrow) _CertPrivateKeyInfo());
1745 SysTryReturnResult(NID_SEC_CERT, pPriKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1748 std::unique_ptr< _CertFileStore > pFileStore(new (std::nothrow) _CertFileStore());
1749 SysTryReturnResult(NID_SEC_CERT, pFileStore != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1751 std::unique_ptr< _CertificateListInfo > pCertList(new (std::nothrow) _CertificateListInfo);
1752 SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1754 memset(pCertList.get(), 0, sizeof(*pCertList.get()));
1756 pCertList->pNext = null;
1758 r = pFileStore->SetFileHandle(userCertRecord.certId, _CERT_PATH_USER_CERT);
1759 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to set file handle.");
1761 r = pFileStore->ReadFromFile(reinterpret_cast< byte* >(pCertList->certificate), pCertList->length);
1762 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to read from file.");
1763 certificateBase64Len = _Base64::GetEncodedSize(pCertList->length);
1765 if (encodingType == _CERT_ENC_TYPE_PEM)
1767 const byte* pCertBuffer = pCertList->certificate;
1769 pBio = BIO_new(BIO_s_mem());
1770 SysTryReturnResult(NID_SEC_CERT, pBio != null, E_OUT_OF_MEMORY, "Failed to allocate memory.");
1772 pCert = d2i_X509(null, &pCertBuffer, pCertList->length);
1773 SysTryCatch(NID_SEC_CERT, pCert != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate convertion failed.");
1775 readLength = PEM_write_bio_X509(pBio, pCert);
1776 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1778 pCertList->length = certificateBase64Len + (2 * _MAX_PEM_HEADER);
1780 readLength = BIO_read(pBio, pCertList->certificate, pCertList->length);
1781 SysTryCatch(NID_SEC_CERT, readLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Certificate conversion failed");
1783 pCertList->length = readLength;
1792 else if (encodingType == _CERT_ENC_TYPE_BASE64)
1794 int certLen = _Base64::GetEncodedSize(pCertList->length);
1795 SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_SYSTEM, "Certificate length is invalid.");
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