24474b9b7bb709f1d9d67c32052229b2702ad2aa
[platform/framework/native/appfw.git] / src / security / cert / FSecCert_CertService.cpp
1 //
2 // Open Service Platform
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 //
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 // @file                FSecCert_CertService.cpp
19 // @brief               This file contains implementation of X509 Certificate Service APIs.
20 //
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <error.h>
25 #include <memory.h>
26 #include <new>
27 #include <sys/stat.h>
28 #include <assert.h>
29 #include <dirent.h>
30 #include <openssl/rsa.h>
31 #include <openssl/obj_mac.h>
32 #include <openssl/sha.h>
33 #include <openssl/evp.h>
34 #include <openssl/x509.h>
35 #include <openssl/pkcs12.h>
36 #include <unique_ptr.h>
37 #include <FBaseErrors.h>
38 #include <FIoDirectory.h>
39 #include <FIoDirEnumerator.h>
40 #include <FIoFileAttributes.h>
41 #include <FIoFile.h>
42 #include <FBaseString.h>
43 #include <FBaseByteBuffer.h>
44 #include <FBaseResult.h>
45 #include <FBaseSysLog.h>
46 #include "FSecCert_CertService.h"
47 #include "FSecCert_CertManager.h"
48 #include "FSecCert_CertDbManager.h"
49 #include "FSecCert_Base64.h"
50 #include "FSecCert_CertFileStore.h"
51 #include "FSecCert_CertOidDef.h"
52 #include "FSecCert_Certificate.h"
53 #include "FSecCert_Base64.h"
54
55
56 using namespace Tizen::Io;
57 using namespace Tizen::Base;
58
59 namespace Tizen { namespace Security { namespace Cert
60 {
61
62 const String _CERT_MGR_BASE_DIRECTORY = L"/opt/usr/share/certs/";
63 const String _CERT_ROOT_CA_CERT_FILE_DIRECTORY = L"/opt/usr/share/certs/rootcert/";
64 const String _CERT_USER_CERT_FILE_DIRECTORY = L"/opt/usr/share/certs/usercert/";
65 const String _CERT_USER_PRIVKEY_FILE_DIRECTORY = L"/opt/usr/share/certs/usercert/key/";
66
67 const String _CERT_ROOT_CA_CERT_TABLE = L"/opt/usr/dbspace/.security-rootcert.db";
68 const String _CERT_USER_CERT_TABLE = L"/opt/usr/dbspace/.security-usercert.db";
69
70 const String _CERT_MGR_CRT_FILE_PATH = _CERT_MGR_BASE_DIRECTORY + L"ca-certificate.crt";
71 const String _TEMP_CERT_MGR_CRT_FILE_PATH = _CERT_MGR_BASE_DIRECTORY + L"tmp-ca-certificate.crt";
72
73 const String _CERT_DOMAIN1_CERT_FILE_PATH = L"/opt/share/cert-svc/certs/sim/thirdparty/";
74 const String _CERT_DOMAIN2_CERT_FILE_PATH = L"/opt/share/cert-svc/certs/sim/operator/";
75 const String _CERT_SVC_DEFAULT_CERT_DIRECTORY = L"/opt/share/cert-svc/certs/ssl/";
76
77 //Prefix definition for NAME Prefix
78 const char* _CERT_COMMON_NAME = "CN=";
79 const char* _CERT_ORG_UNIT_NAME = "OU=";
80 const char* _CERT_ORG_NAME = "O=";
81 const char* _CERT_LOCALITY_NAME = "L=";
82 const char* _CERT_STATE_OR_PROVINCE_NAME = "S=";
83 const char* _CERT_COUNTRY_NAME = "C=";
84 const char* _CERT_EMAIL_ADDRESS = "emailAddress=";
85 const char* _CERT_SERIAL_NUM = "SN=";
86 const char* _CERT_GIVEN_NAME = "GN=";
87 const char* _CERT_SUR_NAME = "SUN=";
88 const char* _CERT_STATE_OF_PROVINCE = "ST=";
89 const char* _CERT_DC = "_CERT_DC=";
90 const char* _CERT_TK_ISSUER_NAME = "Test";
91
92 result
93 _CertService::InitializeDb(void)
94 {
95         result r = E_SUCCESS;
96         int certTrustTypes = 0;
97         int certCount = 0;
98
99         r = _CertService::Initialize();
100         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Cert Manager initialisation failed.");
101
102         certTrustTypes = static_cast< int >(_CERT_TRUST_SIM_ROOT_CA | _CERT_TRUST_SIM_DOMAIN);
103
104         _CertService::RemoveCerts(certTrustTypes);
105
106         // Install Certificates
107         certTrustTypes = static_cast< int >(_CERT_TRUST_PHONE_ROOT_CA | _CERT_TRUST_PHONE_DOMAIN | _CERT_TRUST_OSP_ROOT_CA | _CERT_TRUST_SIM_DOMAIN | _CERT_TRUST_SIM_ROOT_CA);
108
109         r = _CertService::InsertCerts(certTrustTypes, &certCount);
110         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates.");
111
112         return r;
113 }
114
115 result
116 _CertService::ReInitializeDb(void)
117 {
118         result r = E_SUCCESS;
119         int certTrustTypes = 0;
120         int certCount = 0;
121
122         r = _CertService::Initialize();
123         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Db initialization failed.");
124
125         // Install Certificates
126         certTrustTypes = static_cast< int >(_CERT_TRUST_PHONE_ROOT_CA | _CERT_TRUST_PHONE_DOMAIN | _CERT_TRUST_OSP_ROOT_CA | _CERT_TRUST_SIM_DOMAIN | _CERT_TRUST_SIM_ROOT_CA);
127
128         r = _CertService::InsertCerts(certTrustTypes, &certCount);
129         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates.");
130
131         return r;
132 }
133
134 result
135 _CertService::Initialize(void)
136 {
137         result r = E_SUCCESS;
138         _CertDbManager* pCertDb = null;
139
140         pCertDb = _CertDbManager::GetInstance();
141         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
142
143         if (!pCertDb->IsCertificateTablesCreated())
144         {
145                 r = pCertDb->CreateCertificateTables();
146                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
147         }
148
149         return r;
150 }
151
152 result
153 _CertService::DropTables(void)
154 {
155         result r = E_SUCCESS;
156         _CertDbManager* pCertDb = null;
157
158         pCertDb = _CertDbManager::GetInstance();
159         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
160
161         if (!pCertDb->IsCertificateTablesCreated())
162         {
163                 r = pCertDb->RemoveCertificateTables();
164                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table.");
165         }
166
167         return r;
168 }
169
170 result
171 _CertService::ResetTables(void)
172 {
173         result r = E_SUCCESS;
174         _CertDbManager* pCertDb = null;
175
176         pCertDb = _CertDbManager::GetInstance();
177         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
178
179         if (!pCertDb->IsCertificateTablesCreated())
180         {
181                 r = pCertDb->ResetCertificateTables();
182                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table.");
183         }
184
185         return r;
186 }
187
188 result
189 _CertService::MasterReset(void)
190 {
191         _CertDbManager* pCertDb = null;
192
193         pCertDb = _CertDbManager::GetInstance();
194         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
195
196         pCertDb->RemoveAllUserCertificate();
197
198         _CertService::RemoveCert(_CERT_TYPE_ROOT_CA);
199         _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN1);
200         _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN2);
201         _CertService::RemoveCert(_CERT_TYPE_ROOT_DOMAIN3);
202         _CertService::RemoveCert(_CERT_TYPE_ROOT_CA_BY_USER);
203         _CertService::RemoveCert(_CERT_TYPE_INTERMIDIATE_CA);
204         _CertService::RemoveCert(_CERT_TYPE_USER_CERT);
205         _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL1);
206         _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL2);
207         _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL3);
208         _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL4);
209         _CertService::RemoveCert(_CERT_TYPE_OSP_CRITICAL5);
210         _CertService::RemoveCert(_CERT_TYPE_OSP_PRELOAD_APP);
211         _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
212         _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
213         _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
214
215         return E_SUCCESS;
216 }
217
218 int
219 _CertService::InsertCert(_CaCertType type)
220 {
221         result r = E_SUCCESS;
222         byte certBufData[_MAX_CERTIFICATE_SIZE] = {0, };
223         long fileSize = 0;
224         int count = 0;
225         int readCnt = 0;
226         _CertFormat certFormat = _CERT_UNKNOWN;
227         Directory dir;
228         Directory rootCertdir;
229         FileAttributes attr;
230         String rootCertificatePath;
231
232         ClearLastResult();
233
234         SysTryReturn(NID_SEC_CERT, type >= 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter.");
235
236         switch (type)
237         {
238         case _CERT_TYPE_ROOT_CA:
239
240                 rootCertificatePath.Append(_CERT_SVC_DEFAULT_CERT_DIRECTORY);
241                 break;
242
243         case _CERT_TYPE_DEV_ROOT_DOMAIN1:
244                 rootCertificatePath.Append(_CERT_DOMAIN1_CERT_FILE_PATH);
245                 break;
246
247         case _CERT_TYPE_DEV_ROOT_DOMAIN2:
248                 rootCertificatePath.Append(_CERT_DOMAIN2_CERT_FILE_PATH);
249                 break;
250
251         case _CERT_TYPE_OSP_CRITICAL1:
252                 //fall through
253         case _CERT_TYPE_OSP_CRITICAL2:
254                 //fall through
255         case _CERT_TYPE_OSP_PRELOAD_APP:
256                 break;
257
258         default:
259                 break;
260         }
261         certFormat = _CERT_X509;
262
263         if(rootCertificatePath.GetLength() <= 0)
264         {
265                 SetLastResult(E_SUCCESS);
266                 return 0;
267         }
268
269         // Open the directory
270         String dirName(rootCertificatePath);
271
272         r = dir.Construct(dirName);
273         SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, r, "[%s] Failed to construct directory.", GetErrorMessage(r));
274
275         std::unique_ptr<DirEnumerator> pDirEnum(dir.ReadN());
276         SysTryReturn(NID_SEC_CRYPTO, pDirEnum != null, count, GetLastResult(), "[%s] Failed to get directory enumerator instance.", GetErrorMessage(GetLastResult()));
277
278         while (pDirEnum->MoveNext() == E_SUCCESS)
279         {
280                 String fileName;
281                 File file;
282
283                 DirEntry entry = pDirEnum->GetCurrentDirEntry();
284
285                 fileName.Append(dirName);
286                 fileName.Append(entry.GetName());
287                 if ((entry.GetName() == "..") || (entry.GetName() == "."))
288                 {
289                         continue;
290                 }
291
292                 r = file.Construct(fileName, L"r");
293                 if (!IsFailed(r))
294                 {
295                         r = File::GetAttributes(fileName, attr);
296                         if (!IsFailed(r))
297                         {
298                                 fileSize = attr.GetFileSize();
299                                 if (fileSize > 0 && fileSize < _MAX_CERTIFICATE_SIZE)
300                                 {
301                                         readCnt = file.Read(certBufData, fileSize);
302                                         r = GetLastResult();
303                                         if (!IsFailed(r) && readCnt == fileSize)
304                                         {
305                                                 _CertService::InsertDefaultCaCertificate(type, certFormat, certBufData, readCnt);
306                                                 count++;
307                                                 fileSize = 0;
308                                                 readCnt = 0;
309                                         }
310                                 }
311                         }
312                 }
313         }
314
315         return count;
316 }
317
318 result
319 _CertService::InsertDefaultCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen)
320 {
321         result r = E_SUCCESS;
322         _CertDbManager* pCertDb = null;
323
324         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer.");
325         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length.");
326         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
327         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
328
329         pCertDb = _CertDbManager::GetInstance();
330         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
331
332         r = pCertDb->InsertDefaultCaCertificateFromBuffer(type, format, pCertBuf, certLen);
333         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install default ca certiifcates.");
334
335         return r;
336 }
337
338 result
339 _CertService::InsertCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen)
340 {
341         result r = E_SUCCESS;
342         _CertDbManager* pCertDb = null;
343
344         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer.");
345         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length.");
346         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
347         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
348
349         pCertDb = _CertDbManager::GetInstance();
350         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
351
352         r = pCertDb->InsertCaCertificateFromBuffer(type, format, pCertBuf, certLen);
353         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install ca certificate from input buffer.");
354
355         r = _CertManager::CreateCrtFile();
356         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
357
358         return r;
359 }
360
361 result
362 _CertService::RemoveCert(_CaCertType type)
363 {
364         result r = E_SUCCESS;
365         _CertDbManager* pCertDb = null;
366
367         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
368         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
369
370         pCertDb = _CertDbManager::GetInstance();
371         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
372
373         r = pCertDb->RemoveCaCertificateByType(type);
374         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate of type %d", type);
375
376         r = _CertManager::CreateCrtFile();
377         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
378
379         return r;
380 }
381
382 result
383 _CertService::OpenContext(_CertContextType type, CertChainCtx* pCertCtx)
384 {
385         return _CertManager::OpenContext(type, pCertCtx);
386 }
387
388
389 result
390 _CertService::AddCertificate(CertChainCtx certCtx, byte* pCertBuf, int certLen)
391 {
392         return _CertManager::AddCertificate(certCtx, pCertBuf, certLen);
393 }
394
395 result
396 _CertService::VerifyChain(CertChainCtx certCtx, _CertDomainType* pDomain)
397 {
398         result r = E_SUCCESS;
399
400         r = _CertManager::VerifyChain(certCtx, pDomain);
401
402         return r;
403 }
404
405 result
406 _CertService::VerifyCert(CertificateHandle certHandle, byte* pPublickey, int keyLen)
407 {
408         return _CertManager::VerifyCertificate(certHandle, pPublickey, keyLen);
409 }
410
411 result
412 _CertService::GetChainDepth(CertChainCtx certCtx, int* pDepth)
413 {
414         return _CertManager::GetChainDepth(certCtx, pDepth);
415 }
416
417 result
418 _CertService::GetNthCert(CertChainCtx certCtx, int nth, CertificateHandle* pCertHandle)
419 {
420         return _CertManager::GetNthCertificate(certCtx, nth, pCertHandle);
421 }
422
423
424 result
425 _CertService::GetCertBufferN(CertificateHandle certHandle, char*& pBuffer, int* pCertLen)
426 {
427         return _CertManager::GetCertBuffer(certHandle, &pBuffer, pCertLen);
428 }
429
430 result
431 _CertService::CloseContext(CertChainCtx certCtx)
432 {
433         return _CertManager::CloseContext(certCtx);
434 }
435
436 result
437 _CertService::OpenCertificate(char* pBuffer, int bufLen, CertificateHandle* pCertHandle)
438 {
439         result r = E_SUCCESS;
440         _CertFormat certFormat = _CERT_X509;
441         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
442         int derCertBufferLength = 0;
443         byte* pDerCert = null;
444
445         *pCertHandle = null;
446         SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input buffer.");
447         SysTryReturnResult(NID_SEC_CERT, bufLen > 0, E_INVALID_ARG, "Invalid input length.");
448
449         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pBuffer), bufLen, &pDerCert, &derCertBufferLength, &encodingType);
450         std::unique_ptr<byte[]> pDerCertBuffer(pDerCert);
451         pDerCert = null;
452
453         SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_INVALID_ARG, "Invalid certificate buffer.");
454         SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_INVALID_ARG, "Invalid certificate length.");
455         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
456
457         std::unique_ptr<_X509Certificate> pCert(new (std::nothrow) _X509Certificate());
458         SysTryReturnResult(NID_SEC_CRYPTO, pCert, E_OUT_OF_MEMORY, "Allocating new _X509Certificate failed.");
459
460         r = pCert->Parse(pDerCertBuffer.get(), derCertBufferLength);
461         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to allocate memory.", GetErrorMessage(r));
462
463         //Certificate format is X509 and Buffer is Binary
464
465         pCert->SetContextCertificate(false);
466         pCert->SetCertFormat(_CERT_X509);
467         *pCertHandle = reinterpret_cast< CertificateHandle >(pCert.release());
468
469         return r;
470 }
471
472
473 result
474 _CertService::CloseCertificate(CertificateHandle* pCertHandle)
475 {
476
477         SysTryReturnResult(NID_SEC_CERT, pCertHandle != null, E_INVALID_ARG, "Invalid parameter certificate handle.");
478
479         _Certificate* pTempCert = null;
480
481         pTempCert = static_cast< _Certificate* >(*pCertHandle);
482         SysTryReturnResult(NID_SEC_CERT, pTempCert != null, E_SYSTEM, "An unexpected system error occurred");
483
484         _CertFormat format = pTempCert->GetCertFormat();
485         SysTryReturnResult(NID_SEC_CERT, format == _CERT_X509, E_SYSTEM, "Failed to get certificate format.");
486
487         _X509Certificate* pCert = dynamic_cast< _X509Certificate* >(pTempCert);
488         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_SYSTEM, "An unexpected system error occurred.");
489         if (!pCert->IsContextCertificate())
490         {
491                 delete pCert;
492                 *pCertHandle = null;
493         }
494
495         return E_SUCCESS;
496 }
497
498 result
499 _CertService::GetCaCertificateId(CertificateHandle certHandle, _CaCertType certType, int& certId)
500 {
501         result r = E_SUCCESS;
502         _X509Certificate* pCert = static_cast< _X509Certificate* >(certHandle);
503         _X509TbsCert* pTbsCert = null;
504         _CertDbManager* pCertDb = null;
505
506         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid certificate handle, handle must not be null.");
507         SysTryReturnResult(NID_SEC_CERT, certType > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
508         SysTryReturnResult(NID_SEC_CERT, certType < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
509
510         pTbsCert = pCert->GetTbsCertInstance();
511         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
512
513         pCertDb = _CertDbManager::GetInstance();
514         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
515
516         r = pCertDb->GetCaCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
517                         pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
518                         certId, certType);
519         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get Ca certificate id of the certificate with subject name %s", GetErrorMessage(r), pTbsCert->GetSubjectName());
520
521         return r;
522
523 }
524
525 result
526 _CertService::GetUserCertificateId(CertificateHandle certHandle, int& certId)
527 {
528         result r = E_SUCCESS;
529         _X509Certificate* pCert = static_cast< _X509Certificate* >(certHandle);
530         _X509TbsCert* pTbsCert = null;
531         _CertDbManager* pCertDb = null;
532
533         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid certificate handle. handle must not be null");
534
535         pTbsCert = pCert->GetTbsCertInstance();
536         SysTryReturnResult(NID_SEC_CERT, pTbsCert != null, E_SYSTEM, "Failed to get certificate to be signed instance.");
537
538         pCertDb = _CertDbManager::GetInstance();
539         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
540
541         r = pCertDb->GetUserCertificateId(pTbsCert->GetSubjectName(), strlen(reinterpret_cast< char* >(pTbsCert->GetSubjectName())),
542                         pTbsCert->GetIssuerName(), strlen(reinterpret_cast< char* >(pTbsCert->GetIssuerName())),
543                         certId);
544         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed get ca certificate identifier with subject name %s.", GetErrorMessage(r), pTbsCert->GetSubjectName());
545
546         return r;
547 }
548
549 result
550 _CertService::GetCertInfo(CertificateHandle certHandle, _CertFieldType field, _CertFieldInfos* pCertInfo)
551 {
552         return _CertManager::GetCertInfo(certHandle, field, pCertInfo);
553 }
554
555 result
556 _CertService::FreeCertList(_CertificateListInfo* pCertList)
557 {
558         _CertificateListInfo* pTemp = null;
559         int count = 0;
560
561         SysTryReturnResult(NID_SEC_CERT, pCertList != null, E_INVALID_ARG, "Invalid certificate list.");
562
563         while (pCertList)
564         {
565                 pTemp = pCertList->pNext;
566                 delete (pCertList);
567                 pCertList = pTemp;
568                 count++;
569         }
570
571         return E_SUCCESS;
572 }
573
574 result
575 _CertService::FreeCertificateInfo(_CertInfo* pCertInfo)
576 {
577         delete pCertInfo;
578
579         return E_SUCCESS;
580 }
581
582 result
583 _CertService::GetCertListByFormatN(_CertFormat certFormat, _CertificateListInfo*& pCertList, int* pCount)
584 {
585         result r = E_SUCCESS;
586         _CertDbManager* pCertDb = null;
587
588         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
589         SysTryReturnResult(NID_SEC_CERT, pCount != null, E_INVALID_ARG, "Invalid certificate count.");
590
591         pCertDb = _CertDbManager::GetInstance();
592         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
593
594         r = pCertDb->GetCertificateListByFormat(certFormat, &pCertList, *pCount);
595         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate list.");
596
597         return r;
598 }
599
600 result
601 _CertService::GetCaCertListByCertIdN(int certId, _CertificateListInfo*& pCertList)
602 {
603         result r = E_SUCCESS;
604         _CertDbManager* pCertDb = null;
605
606         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
607
608         pCertDb = _CertDbManager::GetInstance();
609         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
610
611         r = pCertDb->GetCaCertificateListByCertId(certId, &pCertList);
612         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get ca certificate list.");
613
614         return r;
615 }
616
617 result
618 _CertService::RemoveCerts(int certTrustTypes)
619 {
620         result r = E_SUCCESS;
621
622         SysTryReturnResult(NID_SEC_CERT, certTrustTypes >= 0, E_INVALID_ARG, "Invalid certificate trust type.");
623
624         if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN)
625         {
626                 r = _CertService::RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN1);
627                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1.");
628
629                 r = RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN3);
630                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3.");
631         }
632
633         if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA)
634         {
635                 r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_CA);
636                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove root ca certificate.");
637         }
638
639         if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN)
640         {
641                 r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
642                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1.");
643                 r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
644                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain2.");
645                 r = _CertService::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
646                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3.");
647         }
648
649         r = _CertManager::CreateCrtFile();
650         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
651
652         return r;
653 }
654
655 result
656 _CertService::InsertCerts(int certTrustTypes, int* pCertCount)
657 {
658         result r = E_SUCCESS;
659         int certCount = 0;
660         int certTotalCount = 0;
661
662         SysTryReturnResult(NID_SEC_CERT, certTrustTypes != _CERT_TRUST_NONE, E_INVALID_ARG, "Invalid certificate trust type.");
663         SysTryReturnResult(NID_SEC_CERT, certTrustTypes > 0, E_INVALID_ARG, "Invalid certificate trust type.");
664
665         if (certTrustTypes & _CERT_TRUST_OSP_ROOT_CA)
666         {
667                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_PRELOAD_APP);
668                 if (certCount == -1)
669                 {
670                         r = E_SYSTEM;
671                 }
672                 else
673                 {
674                         certTotalCount += certCount;
675                 }
676                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL2);
677                 if (certCount == -1)
678                 {
679                         r = E_SYSTEM;
680                 }
681                 else
682                 {
683                         certTotalCount += certCount;
684                 }
685                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL1);
686                 if (certCount == -1)
687                 {
688                         r = E_SYSTEM;
689                 }
690                 else
691                 {
692                         certTotalCount += certCount;
693                 }
694                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL3);
695                 if (certCount == -1)
696                 {
697                         r = E_SYSTEM;
698                 }
699                 else
700                 {
701                         certTotalCount += certCount;
702                 }
703                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL4);
704                 if (certCount == -1)
705                 {
706                         r = E_SYSTEM;
707                 }
708                 else
709                 {
710                         certTotalCount += certCount;
711                 }
712                 certCount = _CertService::InsertCert(_CERT_TYPE_OSP_CRITICAL5);
713                 if (certCount == -1)
714                 {
715                         r = E_SYSTEM;
716                 }
717                 else
718                 {
719                         certTotalCount += certCount;
720                 }
721         }
722         if (certTrustTypes & _CERT_TRUST_PHONE_ROOT_CA)
723         {
724                 //Install trusted by default certificates
725                 certCount = _CertService::InsertCert(_CERT_TYPE_TRUSTED_CA);
726                 if (certCount == -1)
727                 {
728                         r = E_SYSTEM;
729                 }
730                 else
731                 {
732                         certTotalCount += certCount;
733                 }
734
735                 certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_CA);
736                 if (certCount == -1)
737                 {
738                         r = E_SYSTEM;
739                 }
740                 else
741                 {
742                         certTotalCount += certCount;
743                 }
744         }
745         if (certTrustTypes & _CERT_TRUST_PHONE_DOMAIN)
746         {
747                 certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN1);
748                 if (certCount == -1)
749                 {
750                         r = E_SYSTEM;
751                 }
752                 else
753                 {
754                         certTotalCount += certCount;
755                 }
756                 certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN2);
757                 if (certCount == -1)
758                 {
759                         r = E_SYSTEM;
760                 }
761                 else
762                 {
763                         certTotalCount += certCount;
764                 }
765                 certCount = _CertService::InsertCert(_CERT_TYPE_ROOT_DOMAIN3);
766                 if (certCount == -1)
767                 {
768                         r = E_SYSTEM;
769                 }
770                 else
771                 {
772                         certTotalCount += certCount;
773                 }
774         }
775         if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN)
776         {
777                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
778                 if (certCount == -1)
779                 {
780                         r = E_SYSTEM;
781                 }
782                 else
783                 {
784                         certTotalCount += certCount;
785                 }
786                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
787                 if (certCount == -1)
788                 {
789                         r = E_SYSTEM;
790                 }
791                 else
792                 {
793                         certTotalCount += certCount;
794                 }
795                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
796                 if (certCount == -1)
797                 {
798                         r = E_SYSTEM;
799                 }
800                 else
801                 {
802                         certTotalCount += certCount;
803                 }
804         }
805         if (certTrustTypes & _CERT_TRUST_SIM_ROOT_CA)
806         {
807                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_CA);
808                 if (certCount == -1)
809                 {
810                         r = E_SYSTEM;
811                 }
812                 else
813                 {
814                         certTotalCount += certCount;
815                 }
816         }
817         if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA)
818         {
819                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_CA);
820                 if (certCount == -1)
821                 {
822                         r = E_SYSTEM;
823                 }
824                 else
825                 {
826                         certTotalCount += certCount;
827                 }
828         }
829         if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN)
830         {
831                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
832                 if (certCount == -1)
833                 {
834                         r = E_SYSTEM;
835                 }
836                 else
837                 {
838                         certTotalCount += certCount;
839                 }
840                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
841                 if (certCount == -1)
842                 {
843                         r = E_SYSTEM;
844                 }
845                 else
846                 {
847                         certTotalCount += certCount;
848                 }
849                 certCount = _CertService::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
850                 if (certCount == -1)
851                 {
852                         r = E_SYSTEM;
853                 }
854                 else
855                 {
856                         certTotalCount += certCount;
857                 }
858         }
859
860         if (certTrustTypes & _CERT_TRUST_CSC_CA)
861         {
862                 certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_CA);
863                 if (certCount == -1)
864                 {
865                         r = E_SYSTEM;
866                 }
867                 else
868                 {
869                         certTotalCount += certCount;
870                 }
871                 certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN1);
872                 if (certCount == -1)
873                 {
874                         r = E_SYSTEM;
875                 }
876                 else
877                 {
878                         certTotalCount += certCount;
879                 }
880                 certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN2);
881                 if (certCount == -1)
882                 {
883                         r = E_SYSTEM;
884                 }
885                 else
886                 {
887                         certTotalCount += certCount;
888                 }
889                 certCount = _CertService::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN3);
890                 if (certCount == -1)
891                 {
892                         r = E_SYSTEM;
893                 }
894                 else
895                 {
896                         certTotalCount += certCount;
897                 }
898         }
899
900         if (pCertCount != null)
901         {
902                 *pCertCount = certTotalCount;
903         }
904
905         r = _CertManager::CreateCrtFile();
906         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
907
908         return r;
909 }
910
911 CertificateStoreCtx
912 _CertService::OpenCertificateStoreByType(_CaCertType type, int* pCount)
913 {
914         CertificateStoreCtx retCtx;
915         int count = 0;
916
917         if (type == _CERT_TYPE_USER_CERT)
918         {
919                 retCtx = _CertManager::OpenUserCertificateStore(count);
920         }
921         else
922         {
923                 retCtx = _CertManager::OpenRootCaStore(type, count);
924         }
925
926         if (pCount != null)
927         {
928                 *pCount = count;
929         }
930
931         return retCtx;
932 }
933
934 int
935 _CertService::GetCertificateCount(CertificateStoreCtx certificateStoreCtx)
936 {
937         _CertRootCaInfo* pRootCa = null;
938         int count = 0;
939         _CertRootList* pTemp = null;
940
941         ClearLastResult();
942
943         if (certificateStoreCtx != null)
944         {
945                 pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx);
946                 if (pRootCa->pRootList != null)
947                 {
948                         pTemp = pRootCa->pRootList;
949                 }
950                 else
951                 {
952                         return 0;
953                 }
954                 while (pTemp != null)
955                 {
956                         count++;
957                         pTemp = pTemp->pNext;
958                 }
959         }
960
961         return count;
962 }
963
964 result
965 _CertService::GetNextCertificate(CertificateStoreCtx certificateStoreCtx, char* pBuffer, int* pBufferLen)
966 {
967         _CertRootCaInfo* pRootCa = null;
968         _CertRootList* pTemp = null;
969         int count = 0;
970
971         SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid certificate store context.");
972         SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input buffer.");
973         SysTryReturnResult(NID_SEC_CERT, pBufferLen != null, E_INVALID_ARG, "Invalid input buffer length.");
974
975         pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx);
976         SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_OBJ_NOT_FOUND, "Certificate list is empty.");
977
978         pTemp = pRootCa->pRootList;
979
980         while (count != pRootCa->curPos)
981         {
982                 count++;
983                 SysTryReturnResult(NID_SEC_CERT, pTemp->pNext != null, E_OBJ_NOT_FOUND, "Certificate index not found.");
984
985                 pTemp = pTemp->pNext;
986         }
987
988         pRootCa->pCurrRootList = pTemp;
989         if (*pBufferLen > static_cast< int >(pRootCa->pCurrRootList->length))
990         {
991                 memcpy(pBuffer, pRootCa->pCurrRootList->certificate, pRootCa->pCurrRootList->length);
992                 *pBufferLen = pRootCa->pCurrRootList->length;
993         }
994         else
995         {
996                 memcpy(pBuffer, pRootCa->pCurrRootList->certificate, *pBufferLen);
997         }
998
999         pRootCa->curPos++;
1000
1001         return E_SUCCESS;
1002 }
1003
1004
1005 result
1006 _CertService::UpdateCaCertificate(_CaCertType type, char* pOldCert, int oldCertLen, char* pNewCert, int newCertLen) // if same certificate is in Db, replace the certificate using buffer2 and bufferLen2.
1007 {
1008         result r = E_SUCCESS;
1009         _CertDbManager* pCertDb = null;
1010         _CertFormat certFormat = _CERT_UNKNOWN;
1011         int derCertBufferLengthOld = 0;
1012         int derCertBufferLengthNew = 0;
1013         byte* pDerCertOld = null;
1014         byte* pDerCertNew = null;
1015         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
1016
1017         SysTryReturnResult(NID_SEC_CERT, pOldCert != null, E_INVALID_ARG, "Invalid old certificate buffer.");
1018         SysTryReturnResult(NID_SEC_CERT, oldCertLen > 0, E_INVALID_ARG, "Invalid old certificate length.");
1019         SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_INVALID_ARG, "Invalid new certificate buffer.");
1020         SysTryReturnResult(NID_SEC_CERT, newCertLen > 0, E_INVALID_ARG, "Invalid new certificate length.");
1021         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1022         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1023
1024         pCertDb = _CertDbManager::GetInstance();
1025         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1026
1027         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pOldCert), oldCertLen, &pDerCertOld, &derCertBufferLengthOld, &encodingType);
1028         SysTryReturnResult(NID_SEC_CERT, pDerCertOld != null, E_SYSTEM, "Invalid old certificate buffer.");
1029
1030         std::unique_ptr<byte[]>pDerCertBufferOld(pDerCertOld);
1031         SysTryReturnResult(NID_SEC_CERT, pDerCertBufferOld != null, E_INVALID_ARG, "Invalid old certificate buffer.");
1032
1033         pDerCertOld = null;
1034         SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthOld > 0, E_SYSTEM, "Invalid old certificate length.");
1035         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
1036
1037         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pNewCert), newCertLen, &pDerCertNew, &derCertBufferLengthNew, &encodingType);
1038         SysTryReturnResult(NID_SEC_CERT, pDerCertNew != null, E_SYSTEM, "Invalid new certificate buffer.");
1039
1040         std::unique_ptr<byte[]>pDerCertBufferNew(pDerCertNew);
1041         SysTryReturnResult(NID_SEC_CERT, pDerCertBufferNew != null, E_SYSTEM, "Invalid new certificate buffer.");
1042
1043         pDerCertNew = null;
1044
1045         SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthNew > 0, E_SYSTEM, "Invalid new certificate length.");
1046         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
1047
1048         r = pCertDb->UpdateCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBufferOld.get()), derCertBufferLengthOld, reinterpret_cast< byte* >(pDerCertBufferNew.get()), derCertBufferLengthNew);
1049         if (r == E_DATA_NOT_FOUND)
1050         {
1051                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db.");
1052         }
1053
1054         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "An unexpected system error occurred.");
1055
1056         r = _CertManager::CreateCrtFile();
1057         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1058
1059         return r;
1060 }
1061
1062
1063 result
1064 _CertService::RemoveCaCertificate(_CaCertType type, char* pBuffer, int bufLen) // if same certificate is in Db, remove the certificate.
1065 {
1066         result r = E_SUCCESS;
1067         _CertDbManager* pCertDb = null;
1068         _CertFormat certFormat = _CERT_UNKNOWN;
1069         byte* pDerCert = null;
1070         int derCertBufferLength = 0;
1071         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
1072
1073         SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input certificate buffer.");
1074         SysTryReturnResult(NID_SEC_CERT, bufLen > 0, E_INVALID_ARG, "Invalid input certificate length.");
1075
1076         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1077         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1078
1079         pCertDb = _CertDbManager::GetInstance();
1080         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1081
1082         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pBuffer), bufLen, &pDerCert, &derCertBufferLength, &encodingType);
1083         SysTryReturnResult(NID_SEC_CERT, pDerCert != null, E_SYSTEM, "Input certificate buffer.");
1084
1085         std::unique_ptr<byte[]>pDerCertBuffer(pDerCert);
1086         SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_SYSTEM, "Invalid certificate buffer.");
1087         pDerCert = null;
1088
1089         SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_SYSTEM, "Invalid certificate length.");
1090         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
1091
1092         r = pCertDb->RemoveCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBuffer.get()), derCertBufferLength);
1093         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to remove Ca certificate.", GetErrorMessage(r));
1094
1095         r = _CertManager::CreateCrtFile();
1096         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1097
1098         return r;
1099 }
1100
1101
1102 result
1103 _CertService::CloseCertificateStore(CertificateStoreCtx certificateStoreCtx)
1104 {
1105         _CertRootList* pTemp = null;
1106
1107         SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid input parameter.");
1108
1109         std::unique_ptr<_CertRootCaInfo> pRootCa(reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx));
1110         SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_INVALID_ARG, "Allocating new _CertRootCaInfo failed.");
1111
1112         while (pRootCa->pRootList != null)
1113         {
1114                 pTemp = pRootCa->pRootList->pNext;
1115                 delete (pRootCa->pRootList);
1116                 pRootCa->pRootList = pTemp;
1117         }
1118         if (pRootCa->curPos)
1119         {
1120                 pRootCa->curPos = 0;
1121         }
1122
1123         return E_SUCCESS;
1124 }
1125
1126 result
1127 _CertService::GetCertPublicKey(CertificateHandle certHandle, char* pBuffer, int* bufLen)
1128 {
1129         memset(pBuffer, 0, *bufLen);
1130         return _CertManager::GetPublicKey(certHandle, pBuffer, bufLen);
1131 }
1132
1133 result
1134 _CertService::GetCertSignature(CertificateHandle certHandle, char* pBuffer, int* bufLen)
1135 {
1136         memset(pBuffer, 0, *bufLen);
1137         return _CertManager::GetSignature(certHandle, pBuffer, bufLen);
1138 }
1139
1140 int
1141 _CertService::GetCertVersion(CertificateHandle certHandle)
1142 {
1143         ClearLastResult();
1144         return _CertManager::GetVersion(certHandle);
1145 }
1146
1147 result
1148 _CertService::CheckCertValidity(CertificateHandle certHandle, _CertValidityType* pValidity)
1149 {
1150         return _CertManager::GetValidity(certHandle, pValidity);
1151 }
1152
1153 result
1154 _CertService::CheckCertType(CertificateHandle certHandle, _CaCertType* certType)
1155 {
1156         return _CertManager::GetCertificateType(certHandle, certType);
1157 }
1158
1159 int
1160 _CertService::GetDomainCertInfoN(_CertFieldInfos*& pDcInfoRef)
1161 {
1162         result r = E_SUCCESS;
1163         std::unique_ptr<_CertFieldInfos[]> pDcInfo(null);
1164         CertificateHandle certHandle = null;
1165         _CertificateListInfo* pCertList = null;
1166         _CertificateListInfo* pHoldList = null;
1167         int totalCount = 0;
1168         int certId = 0;
1169
1170         ClearLastResult();
1171
1172         r = _CertService::GetCertListByFormatN(_CERT_X509, pCertList, &totalCount);
1173         SysTryReturn(NID_SEC_CERT, pCertList != null, -1, E_SYSTEM, "[E_SYSTEM] Get cert list failed.");
1174         SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, r, "[E_SYSTEM] An unexpected system error occurred.");
1175         SysTryReturn(NID_SEC_CERT, totalCount > 0, 0, E_SUCCESS, "[E_SUCCESS] No certificate found in store.");
1176
1177         pDcInfo = std::unique_ptr<_CertFieldInfos[]>(new (std::nothrow) _CertFieldInfos[totalCount]);
1178         SysTryCatch(NID_SEC_CERT, pDcInfo != null, certId = -1, r, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
1179
1180         memset(pDcInfo.get(), 0, sizeof(_CertFieldInfos) * totalCount);
1181         
1182         pHoldList = pCertList;
1183         while (pCertList != null && pCertList->length != 0)
1184         {
1185                 r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certHandle);
1186                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), certId = -1, E_SYSTEM, "[E_SYSTEM] Failed to open certificate.");
1187
1188                 r = _CertService::GetCertInfo(certHandle, _CERT_FIELD_ALL, &pDcInfo[certId]);
1189                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), certId = -1, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info.");
1190
1191                 pDcInfo[certId].certType = pCertList->certType;
1192                 pDcInfo[certId].certFileId = pCertList->certFileId;
1193                 certId++;
1194                 pCertList = pCertList->pNext;
1195                 _CertService::CloseCertificate(&certHandle);
1196         }
1197         _CertService::FreeCertList(pHoldList);
1198         pHoldList = null;
1199         pDcInfoRef = pDcInfo.release();
1200
1201         return certId;
1202
1203 CATCH:
1204         _CertService::CloseCertificate(&certHandle);
1205         _CertService::FreeCertList(pHoldList);
1206         pHoldList = null;
1207         return certId;
1208 }
1209
1210 result
1211 _CertService::GetCaCertInfoByCertId(int certId, _CertFieldInfos* pDcInfo)
1212 {
1213         result r = E_SUCCESS;
1214         _CertificateListInfo* pCertList = null;
1215         CertificateHandle certHandle = null;
1216
1217         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
1218         SysTryReturnResult(NID_SEC_CERT, pDcInfo != null, E_INVALID_ARG, "Invalid input parameter.");
1219
1220         r = _CertService::GetCaCertListByCertIdN(certId, pCertList);
1221         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate list.", GetErrorMessage(r));
1222
1223         memset(pDcInfo, 0, sizeof(*pDcInfo));
1224         if (pCertList != null && pCertList->length != 0)
1225         {
1226                 r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certHandle);
1227                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open certificate.");
1228
1229                 r = _CertService::GetCertInfo(certHandle, _CERT_FIELD_ALL, pDcInfo);
1230
1231                 pDcInfo[0].certType = pCertList->certType;
1232                 pDcInfo[0].certFileId = pCertList->certFileId;
1233                 _CertService::CloseCertificate(&certHandle);
1234         }
1235
1236 CATCH:
1237         CloseCertificate(&certHandle);
1238         FreeCertList(pCertList);
1239         return r;
1240 }
1241
1242 result
1243 _CertService::InsertUserCaCertificate(byte* pFilePath)
1244 {
1245         result r = E_SUCCESS;
1246         _CertFormat certFormat = _CERT_X509;
1247         _CertDomainType res;
1248         CertChainCtx certCtx = null;
1249         File file;
1250         FileAttributes attr;
1251         int certLen = 0;
1252         int readCnt = 0;
1253         long fileSize = 0;
1254         String fileName(reinterpret_cast< char* >(pFilePath));
1255
1256         SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid file path.");
1257
1258         r = File::GetAttributes(fileName, attr);
1259
1260         fileSize = attr.GetFileSize();
1261         SysTryReturn(NID_SEC_CERT, fileSize > 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
1262         SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
1263
1264         r = file.Construct(fileName, L"r");
1265         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct file.", GetErrorMessage(r));
1266
1267         std::unique_ptr<char[]> pCertBuf(new (std::nothrow) char[fileSize + 1]);
1268         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Allocating new char array failed.");
1269         memset(pCertBuf.get(), 0, (fileSize + 1));
1270
1271         readCnt = file.Read(pCertBuf.get(), fileSize);
1272         r = GetLastResult();
1273         SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
1274
1275         certLen = readCnt;
1276
1277         r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &certCtx);
1278         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to open certificate context.");
1279
1280         r = _CertService::AddCertificate(certCtx, reinterpret_cast< byte* >(pCertBuf.get()), certLen);
1281         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to add certificate to context.");
1282
1283         r = _CertService::VerifyChain(certCtx, &res);
1284         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to verify certificate chain context.");
1285
1286         r = _CertService::InsertUserCaCertificate(certFormat, pCertBuf.get(), certLen);
1287         SysTryCatch(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to insert user ca certificate context.");
1288
1289         r = _CertManager::CreateCrtFile();
1290         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1291
1292 CATCH:
1293
1294         if (certCtx)
1295         {
1296                 CloseContext(certCtx);
1297         }
1298
1299         return r;
1300 }
1301
1302 result
1303 _CertService::RemoveUserCaCertificateByCertId(int certId)
1304 {
1305         result r = E_SUCCESS;
1306         _CertDbManager* pCertDb = null;
1307
1308         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
1309
1310         pCertDb = _CertDbManager::GetInstance();
1311         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1312
1313         r = pCertDb->RemoveUserCaCertificateByCertId(certId);
1314         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete root ca certificate.");
1315
1316         r = _CertManager::CreateCrtFile();
1317         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1318
1319         return r;
1320 }
1321
1322 result
1323 _CertService::InsertUserCaCertificate(_CertFormat format, char* pCert, int certLen)
1324 {
1325         result r = E_SUCCESS;
1326
1327         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input certificate buffer.");
1328         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid input certificate length.");
1329
1330         _CertDbManager* pCertDb = _CertDbManager::GetInstance();
1331         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1332
1333         r = pCertDb->InsertCaCertificateFromBuffer(_CERT_TYPE_ROOT_CA_BY_USER, format, reinterpret_cast< byte* >(pCert), certLen);
1334         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install certificate from input buffer.");
1335
1336         r = _CertManager::CreateCrtFile();
1337         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1338
1339         return r;
1340 }
1341
1342 //User Certificate APIs
1343 int
1344 _CertService::InsertUserCaCertificatesToRootDb(void)
1345 {
1346         result r = E_SUCCESS;
1347         int certTrustTypes = 0;
1348         int certCount = 0;
1349
1350         ClearLastResult();
1351
1352         certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN);
1353
1354         _CertService::RemoveCerts(certTrustTypes);
1355
1356         r = _CertService::InsertCerts(certTrustTypes, &certCount);
1357         SysTryReturn(NID_SEC_CERT, !IsFailed(r), 0, E_SYSTEM, "[E_SYSTEM] Failed to install certificates.");
1358
1359         return certCount;
1360 }
1361
1362 result
1363 _CertService::RemoveUserCaCertificatesFromRootDb(void)
1364 {
1365         result r = E_SUCCESS;
1366         int certTrustTypes = 0;
1367
1368         certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN);
1369
1370         r = _CertService::RemoveCerts(static_cast< _CaCertType >(certTrustTypes));
1371         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate.");
1372
1373         r = _CertManager::CreateCrtFile();
1374         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1375
1376         return r;
1377 }
1378
1379 result
1380 _CertService::InsertUserCertChainPrivateKey(char* pCertChainBuffer, int certChainLength, char* pUserPrivateKey, int userPrivateKeyLength)
1381 {
1382         result r = E_SUCCESS;
1383         _CertChain* pCertTempChain = null;
1384         _CertPrivateKeyInfo* pPrivateKeyTempInfo = null;
1385         _CertDbManager* pCertDb = null;
1386
1387         SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Failed to insert user certificate chain.");
1388         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Failed to insert user certificate chain.");
1389
1390         pCertDb = _CertDbManager::GetInstance();
1391         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1392
1393         r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pUserPrivateKey), userPrivateKeyLength, &pCertTempChain, &pPrivateKeyTempInfo);
1394         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain buffer.", GetErrorMessage(r));
1395
1396         std::unique_ptr<_CertChain> pCertChain(pCertTempChain);
1397         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_SYSTEM, "Invalid certificate chain.");
1398         pCertTempChain = null;
1399
1400         std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo(pPrivateKeyTempInfo);
1401         pPrivateKeyTempInfo = null;
1402
1403         r = pCertDb->InsertCertificateChain(pCertChain->GetCertFormat(), pCertChain.get(), pPrivateKeyInfo.get());
1404         SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[%s] Failed to insert certificate chain.", GetErrorMessage(r));
1405
1406         r = _CertManager::CreateCrtFile();
1407         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1408
1409         return r;
1410 }
1411
1412 result
1413 _CertService::InsertCertificateChainWithPrivateKey(char* pCertChainPrivateKeyBuffer, int certChainPrivateKeyLength)
1414 {
1415         result r = E_SUCCESS;
1416         int privateKeyLen = 0;
1417         int certChainLength = 0;
1418         char* pCertChainBuffer = null;
1419         _CertChain* pCertTempChain = null;
1420         _CertDbManager* pCertDb = null;
1421         _CertPrivateKeyInfo* pPrivateKeyTempInfo = null;
1422
1423         SysTryReturnResult(NID_SEC_CERT, pCertChainPrivateKeyBuffer != null, E_INVALID_ARG, "Invalid private key buffer.");
1424         SysTryReturnResult(NID_SEC_CERT, certChainPrivateKeyLength > 0, E_INVALID_ARG, "Invalid private key length.");
1425
1426         privateKeyLen = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer));
1427         SysTryReturnResult(NID_SEC_CERT, privateKeyLen > 0, E_SYSTEM, "Failed to get private key length.");
1428
1429         pCertChainBuffer = pCertChainPrivateKeyBuffer + privateKeyLen;
1430         certChainLength = certChainPrivateKeyLength - privateKeyLen;
1431
1432         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid private key length.");
1433
1434         pCertDb = _CertDbManager::GetInstance();
1435         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1436
1437         r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer), privateKeyLen, &pCertTempChain, &pPrivateKeyTempInfo);
1438         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain.", GetErrorMessage(r));
1439
1440         std::unique_ptr<_CertChain> pCertChain(pCertTempChain);
1441         SysTryReturnResult(NID_SEC_CERT, pCertTempChain != null, E_SYSTEM, "Invalid certificate chain.");
1442         pCertTempChain = null;
1443
1444         std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo(pPrivateKeyTempInfo);
1445         SysTryReturnResult(NID_SEC_CERT, pPrivateKeyTempInfo != null, E_SYSTEM, "Invalid private key info.");
1446         pPrivateKeyTempInfo = null;
1447
1448         r = pCertDb->InsertCertificateChain(pCertChain->GetCertFormat(), pCertChain.get(), pPrivateKeyInfo.get());
1449         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to insert certificate chain");
1450
1451         r = _CertManager::CreateCrtFile();
1452         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1453
1454         return r;
1455 }
1456
1457 result
1458 _CertService::InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword)
1459 {
1460         result r = E_SUCCESS;
1461         unsigned char* pTempPriKey = null;
1462         unsigned char* pTempUserCertBuffer = null;
1463         unsigned char* pTempCertBuffer = null;
1464         std::unique_ptr<unsigned char[]> priKey;
1465         std::unique_ptr<unsigned char[]> pCertChainBuffer;
1466         std::unique_ptr<unsigned char> pCertBuffer;
1467         std::unique_ptr<unsigned char> pUserCertBuffer;
1468         int index = 0;
1469         int curIndex = 0;
1470         int priKeyLen = 0;
1471         int userCertBufferLen = 0;
1472         int certBufferLen = 0;
1473         int certChainBufferLen = 0;
1474         STACK_OF(X509)* pCaCertChain = null;
1475         X509* pUserCert = null;
1476         EVP_PKEY* pUserKey = null;
1477         FILE* pFile = null;
1478         PKCS12* pPkcs12Content = null;
1479
1480         SysTryReturnResult(NID_SEC_CERT, pPkcs12FilePath != null, E_INVALID_ARG, "Invalid pkcs12 file path.");
1481         SysTryReturnResult(NID_SEC_CERT, pPkcs12ImportPassword != null, E_INVALID_ARG, "Invalid pkcs12 password buffer.");
1482
1483         pFile = fopen(pPkcs12FilePath, "rb");
1484         SysTryReturnResult(NID_SEC_CERT, pFile != null, E_SYSTEM, "Pkcs#12 file open failed.");
1485
1486         pPkcs12Content = d2i_PKCS12_fp(pFile, (PKCS12**) null);
1487         SysTryCatch(NID_SEC_CERT, pPkcs12Content != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 encoding failed.");
1488
1489         index = PKCS12_parse(pPkcs12Content, pPkcs12ImportPassword, &pUserKey, &pUserCert, &pCaCertChain);
1490         SysTryCatch(NID_SEC_CERT, index != 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 parsing failed.");
1491
1492         if (pUserKey != null)
1493         {
1494                 priKeyLen = i2d_PrivateKey(pUserKey, &pTempPriKey);
1495                 priKey = std::unique_ptr<unsigned char[]>(pTempPriKey);
1496                 pTempPriKey = null;
1497         }
1498
1499         userCertBufferLen = i2d_X509(pUserCert, &pTempUserCertBuffer);
1500         pUserCertBuffer = std::unique_ptr<unsigned char>(pTempUserCertBuffer);
1501         pTempUserCertBuffer = null;
1502         certChainBufferLen = userCertBufferLen;
1503
1504         if (pCaCertChain && sk_num((_STACK*) pCaCertChain))
1505         {
1506                 for (index = 0; index < sk_X509_num(pCaCertChain); index++)
1507                 {
1508                         certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer);
1509                         certChainBufferLen = certChainBufferLen + certBufferLen;
1510                         pCertBuffer = std::unique_ptr<unsigned char> (pTempCertBuffer);
1511                         pTempCertBuffer = null;
1512                         certBufferLen = 0;
1513                 }
1514
1515                 pCertChainBuffer = std::unique_ptr<unsigned char[]> (new (std::nothrow) unsigned char[certChainBufferLen]);
1516                 SysTryCatch(NID_SEC_CERT, pCertChainBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Allocating new char array failed.", GetErrorMessage(E_OUT_OF_MEMORY));
1517
1518                 memset(pCertChainBuffer.get(), 0, certChainBufferLen);
1519                 memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen);
1520                 curIndex = userCertBufferLen;
1521
1522                 for (index = 0; index < sk_X509_num(pCaCertChain); index++)
1523                 {
1524                         certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer);
1525                         pCertBuffer = std::unique_ptr<unsigned char> (pTempCertBuffer);
1526                         pTempCertBuffer = null;
1527                         memcpy((pCertChainBuffer.get() + curIndex), pCertBuffer.get(), certBufferLen);
1528                         curIndex = curIndex + certBufferLen;
1529                         certBufferLen = 0;
1530                 }
1531         }
1532         else
1533         {
1534                 pCertChainBuffer = std::unique_ptr<unsigned char[]> (new (std::nothrow) unsigned char[certChainBufferLen]);
1535                 SysTryCatch(NID_SEC_CERT, pCertChainBuffer != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[%s] Allocating new char array failed.", GetErrorMessage(E_OUT_OF_MEMORY));
1536
1537                 memset(pCertChainBuffer.get(), 0, certChainBufferLen);
1538                 memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen);
1539         }
1540
1541         r = InsertUserCertChainPrivateKey(reinterpret_cast< char* >(pCertChainBuffer.get()), certChainBufferLen, reinterpret_cast< char* >(priKey.get()), priKeyLen);
1542         SysTryCatch(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), , r, "[%s] Failed to insert user certificate chain.", GetErrorMessage(r));
1543
1544         r = _CertManager::CreateCrtFile();
1545         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1546
1547 CATCH:
1548         fclose(pFile);
1549         PKCS12_free(pPkcs12Content);
1550         EVP_PKEY_free(pUserKey);
1551         X509_free(pUserCert);
1552         sk_X509_free(pCaCertChain);
1553         return r;
1554 }
1555
1556 result
1557 _CertService::GetParsedCertificateChainN(char* pCertChainBuffer, int certChainLength, CertChainCtx* pCertCtx)
1558 {
1559         result r = E_SUCCESS;
1560         CertChainCtx certChainCtx = null;
1561         char* pTmpBuf = null;
1562         int dataOffset = 0;
1563         int dataLength = 0;
1564         int bufSize = 0;
1565
1566         SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Invalid certificate chain buffer.");
1567         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid certificate chain length");
1568         SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context.");
1569
1570         r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &certChainCtx);
1571         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open context.");
1572
1573         bufSize = certChainLength;
1574
1575         pTmpBuf = pCertChainBuffer + dataOffset;
1576         dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf));
1577         SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get decoded block size.");
1578
1579         r = _CertService::AddCertificate(certChainCtx, reinterpret_cast< byte* >(pTmpBuf), dataLength);
1580         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to add certificate.");
1581
1582         dataOffset += dataLength;
1583
1584         while (dataOffset < bufSize)
1585         {
1586                 pTmpBuf = pCertChainBuffer + dataOffset;
1587                 dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf));
1588                 SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get decoded block size.");
1589
1590                 r = _CertService::AddCertificate(certChainCtx, reinterpret_cast< byte* >(pTmpBuf), dataLength);
1591                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to add certificate.");
1592
1593                 dataOffset += dataLength;
1594         }
1595
1596         *pCertCtx = certChainCtx;
1597         return r;
1598
1599 CATCH:
1600         CloseContext(certChainCtx);
1601         return r;
1602
1603 }
1604
1605 result
1606 _CertService::VerifyCertificateChain(CertChainCtx pCertCtx)
1607 {
1608         result r = E_SUCCESS;
1609         _CertChain* pCertChain = null;
1610
1611         SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context.");
1612
1613         pCertChain = reinterpret_cast< _CertChain* >(pCertCtx);
1614
1615         r = pCertChain->VerifyCertChainWithDb();
1616         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to verify certificate chain.", GetErrorMessage(r));
1617
1618         return r;
1619 }
1620
1621 result
1622 _CertService::InsertCertificateChainContext(CertChainCtx pCertCtx)
1623 {
1624         result r = E_SUCCESS;
1625         _CertDbManager* pCertDb = null;
1626         _CertChain* pCertChain = null;
1627
1628         SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context.");
1629
1630         pCertDb = _CertDbManager::GetInstance();
1631         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1632
1633         pCertChain = reinterpret_cast< _CertChain* >(pCertCtx);
1634
1635         r = pCertDb->InsertCertChain(_CERT_X509, pCertChain);
1636         SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && (r != E_OBJ_ALREADY_EXIST) && (r != E_FILE_ALREADY_EXIST)), r, r, "[%s] Failed to install certificate chain.", GetErrorMessage(r));
1637
1638         r = _CertManager::CreateCrtFile();
1639         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1640
1641         return r;
1642 }
1643
1644 result
1645 _CertService::MakeCertChainFromBufferN(char* pCertChainBuffer, int certChainLength, _CertRootList*& pCertChainListRef)
1646 {
1647         result r = E_SUCCESS;
1648         char* pTmpBuf = null;
1649         int dataOffset = 0;
1650         int dataLength = 0;
1651         int bufSize = 0;
1652         _CertRootList* pCertChainHead = null;
1653         _CertRootList* pCertChainCurrent = null;
1654
1655         SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Invalid certificate chain buffer.");
1656         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid certificate chain length.");
1657
1658         bufSize = certChainLength;
1659
1660         pTmpBuf = pCertChainBuffer + dataOffset;
1661         dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf));
1662         SysTryReturnResult(NID_SEC_CERT, dataLength > 0, E_SYSTEM, "Failed to get decoded block size.");
1663
1664         std::unique_ptr<_CertRootList> pCertChainList(new (std::nothrow) _CertRootList());
1665         SysTryReturnResult(NID_SEC_CERT, pCertChainList != null, E_OUT_OF_MEMORY, "Allocating new _CertRootList failed.");
1666
1667         memcpy(pCertChainList->certificate, pTmpBuf, dataLength);
1668         pCertChainList->length = dataLength;
1669         pCertChainList->format = _CERT_X509;
1670         pCertChainList->pNext = null;
1671
1672         pCertChainCurrent = pCertChainList.release();
1673         pCertChainHead = pCertChainCurrent;
1674         
1675         dataOffset += dataLength;
1676
1677         while (dataOffset < bufSize)
1678         {
1679                 pTmpBuf = pCertChainBuffer + dataOffset;
1680                 dataLength = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pTmpBuf));
1681                 SysTryCatch(NID_SEC_CERT, dataLength > 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM]Failed to get decoded block size.");
1682
1683                 std::unique_ptr<_CertRootList> pCertChainList (new (std::nothrow) _CertRootList());
1684                 SysTryCatch(NID_SEC_CERT, pCertChainList != null, r = E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY]Failed to allocate memory.");
1685
1686                 pCertChainList->pNext = null;
1687
1688                 memcpy(pCertChainList->certificate, pTmpBuf, dataLength);
1689                 pCertChainList->length = dataLength;
1690                 pCertChainList->format = _CERT_X509;
1691
1692                 pCertChainCurrent->pNext = pCertChainList.release();
1693
1694                 dataOffset += dataLength;
1695         }
1696
1697         pCertChainListRef = pCertChainHead;
1698
1699         return E_SUCCESS;
1700
1701 CATCH:
1702         FreeRootCertList(pCertChainHead);
1703         return r;
1704
1705 }
1706
1707 result
1708 _CertService::RemoveUserCertChainByCertId(int certId)
1709 {
1710         result r = E_SUCCESS;
1711         _CertDbManager* pCertDb = null;
1712
1713         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
1714
1715         pCertDb = _CertDbManager::GetInstance();
1716         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1717
1718         r = pCertDb->RemoveCertificateChainByCertId(certId);
1719         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete user certificate chain.");
1720
1721         r = _CertManager::CreateCrtFile();
1722         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1723
1724         return r;
1725 }
1726
1727 result
1728 _CertService::GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLength, char* pSubjectName, int subjectNameLength, _CertificateListInfo*& pUserCertListInfoTypesRef)
1729 {
1730         result r = E_SUCCESS;
1731         _CertDbManager* pCertDb = null;
1732
1733         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid certificate's issuer name.");
1734         SysTryReturnResult(NID_SEC_CERT, issuerNameLength > 0, E_INVALID_ARG, "Invalid certificate's issuer name length.");
1735         SysTryReturnResult(NID_SEC_CERT, issuerNameLength < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_INVALID_ARG, "Invalid certificate's issuer name length.");
1736         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid certificate's subject name.");
1737         SysTryReturnResult(NID_SEC_CERT, subjectNameLength > 0, E_INVALID_ARG, "Invalid certificate's subject name length.");
1738
1739         pCertDb = _CertDbManager::GetInstance();
1740         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1741
1742         r = pCertDb->GetUserCertificateChain(pIssuerName, issuerNameLength, pSubjectName, subjectNameLength, _CERT_ENC_TYPE_BINARY, &pUserCertListInfoTypesRef);
1743         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get user certificate chain.");
1744
1745         return r;
1746 }
1747
1748 result
1749 _CertService::GetUserCertChainBySubjectName(char* pSubjectName, int subjectNameLength, CertChainCtx* pCertChainCtx, PrivateKeyCtx* pPrivateKeyCtx)
1750 {
1751         result r = E_SUCCESS;
1752         _CertDbManager* pCertDb = null;
1753         std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo;
1754         _CertFormat certFormat = _CERT_X509;
1755
1756         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid certificate's subject name.");
1757         SysTryReturnResult(NID_SEC_CERT, subjectNameLength > 0, E_INVALID_ARG, "Invalid certificate's subject name length.");
1758         SysTryReturnResult(NID_SEC_CERT, subjectNameLength <= _MAX_ISSUER_SUBJECT_NAME_SIZE, E_INVALID_ARG, "Invalid certificate's subject name length.");
1759
1760         pCertDb = _CertDbManager::GetInstance();
1761         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1762
1763         std::unique_ptr<_CertChain> pCertChain(new (std::nothrow) _CertChain());
1764         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_OUT_OF_MEMORY, "Allocating new _CertChain failed.");
1765
1766         if (pPrivateKeyCtx != null)
1767         {
1768                 pPrivateKeyInfo = std::unique_ptr<_CertPrivateKeyInfo> (new (std::nothrow) _CertPrivateKeyInfo());
1769                 SysTryReturnResult(NID_SEC_CERT, pPrivateKeyInfo != null, E_OUT_OF_MEMORY, "Allocating new _CertPrivateKeyInfo failed.");
1770         }
1771
1772         r = pCertDb->GetUserCertificateChain(certFormat, pCertChain.get(), pPrivateKeyInfo.get(), reinterpret_cast< char* >(pSubjectName));
1773         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to extract certificate chain.");
1774
1775         if (pCertChainCtx != null)
1776         {
1777                 *pCertChainCtx = pCertChain.release();
1778         }
1779
1780         if (pPrivateKeyCtx != null)
1781         {
1782                 *pPrivateKeyCtx = pPrivateKeyInfo.release();
1783         }
1784
1785         return r;
1786
1787 }
1788
1789 result
1790 _CertService::GetUserCertListInfoTypesByFormatN(_CertFormat certFormat, _CertificateListInfo*& pUserCertListInfoTypesRef, int* pCount)
1791 {
1792         result r = E_SUCCESS;
1793         _CertDbManager* pCertDb = null;
1794
1795         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_INVALID_ARG, "Invalid certificate format.");
1796         SysTryReturnResult(NID_SEC_CERT, pCount != null, E_INVALID_ARG, "Invalid certificate format.");
1797
1798         pCertDb = _CertDbManager::GetInstance();
1799         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1800
1801         r = pCertDb->GetUserCertificateListByFormat(certFormat, &pUserCertListInfoTypesRef, *pCount);
1802         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get certificate list.", GetErrorMessage(r));
1803
1804         return r;
1805 }
1806
1807 result
1808 _CertService::GetUserCertificateByCertIdN(int certId, _CertEncodingType encodingType, _CertInfo*& pUserCertificateInfoRef)
1809 {
1810         result r = E_SUCCESS;
1811         _CertDbManager* pCertDb = null;
1812
1813         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
1814
1815         pCertDb = _CertDbManager::GetInstance();
1816         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1817
1818         r = pCertDb->GetUserCertificateInfoByCertId(certId, encodingType, &pUserCertificateInfoRef);
1819         SysTryReturn(NID_SEC_CERT, pCertDb != null, r, r, "[%s]Failed to get user certificate by input cert identifier: (%d).", GetErrorMessage(r), certId);
1820
1821         return r;
1822 }
1823
1824 int
1825 _CertService::GetUserCertFieldInfoN(_CertFieldInfos*& pCertFieldInfosRef)
1826 {
1827         result r = E_SUCCESS;
1828         int totalCount = 0;
1829         int certIdx = 0;
1830         _CertificateListInfo* pCertList = null;
1831         _CertificateListInfo* pHoldList = null;
1832         CertificateHandle certificateHandle = null;
1833
1834         ClearLastResult();
1835
1836         r = GetUserCertListInfoTypesByFormatN(_CERT_X509, pCertList, &totalCount);
1837         SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, E_SYSTEM, "[E_SYSTEM] Failed to get user certificate list info.");
1838         
1839         if (pCertList == null || totalCount == 0) // regard as the success in the case of 0
1840         {
1841                 SysLog(NID_SEC_CERT, "[E_SUCCESS] No user certificate in database.");
1842                 return 0;
1843         }
1844
1845         pHoldList = pCertList;
1846         
1847         std::unique_ptr<_CertFieldInfos[]> pDCInfo(new (std::nothrow) _CertFieldInfos[totalCount]);
1848         SysTryCatch(NID_SEC_CERT, pDCInfo != null, certIdx = -1, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
1849
1850         memset(pDCInfo.get(), 0, sizeof(_CertFieldInfos) * totalCount);
1851
1852         while (pCertList != null && pCertList->length > 0)
1853         {
1854                 r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertList->certificate), pCertList->length, &certificateHandle);
1855                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), certIdx = -1, E_SYSTEM, "[E_SYSTEM] Failed to open certificates.");
1856
1857                 r = _CertService::GetCertInfo(certificateHandle, _CERT_FIELD_ALL, &pDCInfo[certIdx]);
1858                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), certIdx = -1, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info.");
1859
1860                 pDCInfo[certIdx].certType = pCertList->certType;
1861                 pDCInfo[certIdx].certFileId = pCertList->certFileId;
1862                 certIdx++;
1863                 pCertList = pCertList->pNext;
1864                 _CertService::CloseCertificate(&certificateHandle);
1865         }
1866         
1867         pCertFieldInfosRef = pDCInfo.release();
1868         
1869         FreeCertList(pHoldList);
1870         SetLastResult(E_SUCCESS);
1871         return certIdx;
1872
1873 CATCH:
1874         FreeCertList(pHoldList);
1875         _CertService::CloseCertificate(&certificateHandle);
1876         return certIdx;
1877
1878 }
1879
1880 result
1881 _CertService::GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos)
1882 {
1883         result r = E_SUCCESS;
1884         _CertInfo* pCertInfo = null;
1885         CertificateHandle certificateHandle = null;
1886
1887         SysTryReturnResult(NID_SEC_CERT, pCertFieldInfos != null, E_INVALID_ARG, "Invalid input parameter.");
1888         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
1889
1890         r = GetUserCertificateByCertIdN(certId, _CERT_ENC_TYPE_BINARY, pCertInfo);
1891         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get user certificate.", GetErrorMessage(r));
1892
1893         memset(pCertFieldInfos, 0, sizeof(*pCertFieldInfos));
1894
1895         if (pCertInfo != null && pCertInfo->certLength != 0)
1896         {
1897                 r = OpenCertificate(reinterpret_cast< char* >(pCertInfo->certificate), pCertInfo->certLength, &certificateHandle);
1898                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open certificate.");
1899
1900                 r = GetCertInfo(certificateHandle, _CERT_FIELD_ALL, pCertFieldInfos);
1901                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info.");
1902
1903                 pCertFieldInfos[0].certType = _CERT_TYPE_USER_CERT;
1904                 pCertFieldInfos[0].certFileId = pCertInfo->certId;
1905                 CloseCertificate(&certificateHandle);
1906         }
1907
1908 CATCH:
1909         FreeCertificateInfo(pCertInfo);
1910         CloseCertificate(&certificateHandle);
1911         return r;
1912
1913 }
1914
1915 result
1916 _CertService::GetSubjectNameN(CertificateHandle certificateHandle, byte*& pSubjectNameRef, int* pSubjectNameLength)
1917 {
1918         result r = E_SUCCESS;
1919
1920         SysTryReturnResult(NID_SEC_CERT, certificateHandle != null, E_INVALID_ARG, "Invalid certificate handle.");
1921         SysTryReturnResult(NID_SEC_CERT, pSubjectNameLength != null, E_INVALID_ARG, "Invalid certificate's subject name length.");
1922
1923         r = _CertManager::GetCertificateIssuerNameN(certificateHandle, &pSubjectNameRef, pSubjectNameLength);
1924         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate's issuer name.");
1925
1926         return E_SUCCESS;
1927 }
1928
1929 result
1930 _CertService::GetIssuerNameN(CertificateHandle certificateHandle, byte*& pIssuerNameRef, int* pIssuerNameLength)
1931 {
1932         result r = E_SUCCESS;
1933
1934         SysTryReturnResult(NID_SEC_CERT, certificateHandle != null, E_INVALID_ARG, "Invalid input parameter.");
1935         SysTryReturnResult(NID_SEC_CERT, pIssuerNameLength != null, E_INVALID_ARG, "Invalid input parameter.");
1936
1937         r = _CertManager::GetCertificateSubjectNameN(certificateHandle, &pIssuerNameRef, pIssuerNameLength);
1938         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get certificate subject name.");
1939
1940         return E_SUCCESS;
1941 }
1942
1943 Tizen::Base::String
1944 _CertService::GetCertificateCrtFilePath(void)
1945 {
1946         return _CERT_MGR_CRT_FILE_PATH;
1947 }
1948
1949 result
1950 _CertService::FreeRootCertList(_CertRootList* pRootCertList)
1951 {
1952         result r = E_SUCCESS;
1953         _CertRootList* pTemp = null;
1954         SysTryReturnResult(NID_SEC_CERT, pRootCertList != null, E_INVALID_ARG, "Invalid input parameter.");
1955
1956         while (pRootCertList)
1957         {
1958                 pTemp = pRootCertList->pNext;
1959                 delete pRootCertList;
1960                 pRootCertList = pTemp;
1961         }
1962
1963         return r;
1964 }
1965
1966 result
1967 _CertService::ClosePrivateKeyContext(PrivateKeyCtx privateKeyCtx)
1968 {
1969
1970         std::unique_ptr<_CertPrivateKeyInfo> pPrivateKeyInfo (static_cast< _CertPrivateKeyInfo* >(privateKeyCtx));
1971         SysTryReturnResult(NID_SEC_CERT, pPrivateKeyInfo != null, E_INVALID_ARG, "Allocating new _CertPrivateKeyInfo failed.");
1972
1973         return E_SUCCESS;
1974 }
1975
1976
1977 } } } //Tizen::Security::Cert