Merge "Beautified source code of appfw/src/base/utility" into tizen_2.2
[platform/framework/native/appfw.git] / src / security / cert / FSecCert_CertServer.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
3 //
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
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
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.
15 //
16 //
17 // @file                FSecCert_CertServer.cpp
18 // @brief               This file contains implementation of X509 Certificate Service APIs.
19 //
20 #include <stdio.h>
21 #include <string.h>
22 #include <stdlib.h>
23 #include <error.h>
24 #include <memory.h>
25 #include <new>
26 #include <sys/stat.h>
27 #include <assert.h>
28 #include <dirent.h>
29 #include <openssl/rsa.h>
30 #include <openssl/obj_mac.h>
31 #include <openssl/sha.h>
32 #include <openssl/evp.h>
33 #include <openssl/x509.h>
34 #include <openssl/pkcs12.h>
35 #include <unique_ptr.h>
36 #include <FBaseErrors.h>
37 #include <FIoDirectory.h>
38 #include <FIoDirEnumerator.h>
39 #include <FIoFileAttributes.h>
40 #include <FIoFile.h>
41 #include <FBaseString.h>
42 #include <FBaseByteBuffer.h>
43 #include <FBaseResult.h>
44 #include <FBaseSysLog.h>
45 #include "FSecCert_CertServer.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 result
63 _CertServer::InitializeDb(void)
64 {
65         result r = E_SUCCESS;
66         int certTrustTypes = 0;
67         int certCount = 0;
68
69         r = _CertServer::Initialize();
70         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Cert Manager initialisation failed.");
71
72         certTrustTypes = static_cast< int >(_CERT_TRUST_SIM_ROOT_CA | _CERT_TRUST_SIM_DOMAIN);
73
74         _CertServer::RemoveCerts(certTrustTypes);
75
76         // Install Certificates
77         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);
78
79         r = _CertServer::InsertCerts(certTrustTypes, &certCount);
80         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates.");
81
82         return r;
83 }
84
85 result
86 _CertServer::Initialize(void)
87 {
88         result r = E_SUCCESS;
89         _CertDbManager* pCertDb = null;
90
91         pCertDb = _CertDbManager::GetInstance();
92         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
93
94         if (!pCertDb->IsCertificateTablesCreated())
95         {
96                 r = pCertDb->CreateCertificateTables();
97                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to create certificate table.");
98         }
99
100         return r;
101 }
102
103 result
104 _CertServer::ReInitializeDb(void)
105 {
106         result r = E_SUCCESS;
107         int certTrustTypes = 0;
108         int certCount = 0;
109
110         r = _CertServer::Initialize();
111         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Db initialization failed.");
112
113         // Install Certificates
114         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);
115
116         r = _CertServer::InsertCerts(certTrustTypes, &certCount);
117         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to install certificates.");
118
119         return r;
120 }
121
122 void
123 _CertServer::RestoreRootCaIntegrity(void)
124 {
125         result r = E_SUCCESS;
126         r = _CertManager::CheckRootCaIntegrity();
127         SysTryLog(NID_SEC_CERT, !IsFailed(r), "[%s] Failed to restore the Root CA certificate DB.", GetErrorMessage(r));
128 }
129
130 result
131 _CertServer::DropTables(void)
132 {
133         result r = E_SUCCESS;
134         _CertDbManager* pCertDb = null;
135
136         pCertDb = _CertDbManager::GetInstance();
137         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
138
139         if (!pCertDb->IsCertificateTablesCreated())
140         {
141                 r = pCertDb->RemoveCertificateTables();
142                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table.");
143         }
144
145         return r;
146 }
147
148 result
149 _CertServer::ResetTables(void)
150 {
151         result r = E_SUCCESS;
152         _CertDbManager* pCertDb = null;
153
154         pCertDb = _CertDbManager::GetInstance();
155         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
156
157         if (!pCertDb->IsCertificateTablesCreated())
158         {
159                 r = pCertDb->ResetCertificateTables();
160                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate table.");
161         }
162
163         return r;
164 }
165
166 result
167 _CertServer::MasterReset(void)
168 {
169         _CertDbManager* pCertDb = null;
170
171         pCertDb = _CertDbManager::GetInstance();
172         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
173
174         pCertDb->RemoveAllUserCertificate();
175
176         _CertServer::RemoveCert(_CERT_TYPE_ROOT_CA);
177         _CertServer::RemoveCert(_CERT_TYPE_ROOT_DOMAIN1);
178         _CertServer::RemoveCert(_CERT_TYPE_ROOT_DOMAIN2);
179         _CertServer::RemoveCert(_CERT_TYPE_ROOT_DOMAIN3);
180         _CertServer::RemoveCert(_CERT_TYPE_ROOT_CA_BY_USER);
181         _CertServer::RemoveCert(_CERT_TYPE_INTERMIDIATE_CA);
182         _CertServer::RemoveCert(_CERT_TYPE_USER_CERT);
183         _CertServer::RemoveCert(_CERT_TYPE_OSP_CRITICAL1);
184         _CertServer::RemoveCert(_CERT_TYPE_OSP_CRITICAL2);
185         _CertServer::RemoveCert(_CERT_TYPE_OSP_CRITICAL3);
186         _CertServer::RemoveCert(_CERT_TYPE_OSP_CRITICAL4);
187         _CertServer::RemoveCert(_CERT_TYPE_OSP_CRITICAL5);
188         _CertServer::RemoveCert(_CERT_TYPE_OSP_PRELOAD_APP);
189         _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
190         _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
191         _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
192
193         return E_SUCCESS;
194 }
195
196 int
197 _CertServer::InsertCert(_CaCertType type)
198 {
199         result r = E_SUCCESS;
200         byte certBufData[_MAX_CERTIFICATE_SIZE] = {0, };
201         long fileSize = 0;
202         int count = 0;
203         int readCnt = 0;
204         _CertFormat certFormat = _CERT_UNKNOWN;
205         Directory dir;
206         Directory rootCertdir;
207         FileAttributes attr;
208         String rootCertificatePath;
209
210         ClearLastResult();
211
212         SysTryReturn(NID_SEC_CERT, type >= 0, -1, E_INVALID_ARG, "[E_INVALID_ARG] Invalid input parameter.");
213
214         switch (type)
215         {
216         case _CERT_TYPE_ROOT_CA:
217
218                 rootCertificatePath.Append(_CERT_SVC_DEFAULT_CERT_DIRECTORY);
219                 break;
220
221         case _CERT_TYPE_DEV_ROOT_DOMAIN1:
222                 rootCertificatePath.Append(_CERT_DOMAIN1_CERT_FILE_PATH);
223                 break;
224
225         case _CERT_TYPE_DEV_ROOT_DOMAIN2:
226                 rootCertificatePath.Append(_CERT_DOMAIN2_CERT_FILE_PATH);
227                 break;
228
229         case _CERT_TYPE_OSP_CRITICAL1:
230         //fall through
231         case _CERT_TYPE_OSP_CRITICAL2:
232         //fall through
233         case _CERT_TYPE_OSP_PRELOAD_APP:
234                 break;
235
236         default:
237                 break;
238         }
239         certFormat = _CERT_X509;
240
241         if (rootCertificatePath.GetLength() <= 0)
242         {
243                 SetLastResult(E_SUCCESS);
244                 return 0;
245         }
246
247         // Open the directory
248         String dirName(rootCertificatePath);
249
250         r = dir.Construct(dirName);
251         SysTryReturn(NID_SEC_CERT, !IsFailed(r), -1, r, "[%s] Failed to construct directory.", GetErrorMessage(r));
252
253         std::unique_ptr< DirEnumerator > pDirEnum(dir.ReadN());
254         SysTryReturn(NID_SEC_CRYPTO, pDirEnum != null, count, GetLastResult(), "[%s] Failed to get directory enumerator instance.", GetErrorMessage(GetLastResult()));
255
256         while (pDirEnum->MoveNext() == E_SUCCESS)
257         {
258                 String fileName;
259                 File file;
260
261                 DirEntry entry = pDirEnum->GetCurrentDirEntry();
262
263                 fileName.Append(dirName);
264                 fileName.Append(entry.GetName());
265                 if ((entry.GetName() == "..") || (entry.GetName() == "."))
266                 {
267                         continue;
268                 }
269
270                 r = file.Construct(fileName, L"r");
271                 if (!IsFailed(r))
272                 {
273                         r = File::GetAttributes(fileName, attr);
274                         if (!IsFailed(r))
275                         {
276                                 fileSize = attr.GetFileSize();
277                                 if (fileSize > 0 && fileSize < _MAX_CERTIFICATE_SIZE)
278                                 {
279                                         readCnt = file.Read(certBufData, fileSize);
280                                         r = GetLastResult();
281                                         if (!IsFailed(r) && readCnt == fileSize)
282                                         {
283                                                 _CertServer::InsertDefaultCaCertificate(type, certFormat, certBufData, readCnt);
284                                                 count++;
285                                                 fileSize = 0;
286                                                 readCnt = 0;
287                                         }
288                                 }
289                         }
290                 }
291         }
292
293         return count;
294 }
295
296 result
297 _CertServer::InsertCerts(int certTrustTypes, int* pCertCount)
298 {
299         result r = E_SUCCESS;
300         int certCount = 0;
301         int certTotalCount = 0;
302
303         SysTryReturnResult(NID_SEC_CERT, certTrustTypes != _CERT_TRUST_NONE, E_INVALID_ARG, "Invalid certificate trust type.");
304         SysTryReturnResult(NID_SEC_CERT, certTrustTypes > 0, E_INVALID_ARG, "Invalid certificate trust type.");
305
306         if (certTrustTypes & _CERT_TRUST_OSP_ROOT_CA)
307         {
308                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_PRELOAD_APP);
309                 if (certCount == -1)
310                 {
311                         r = E_SYSTEM;
312                 }
313                 else
314                 {
315                         certTotalCount += certCount;
316                 }
317                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_CRITICAL2);
318                 if (certCount == -1)
319                 {
320                         r = E_SYSTEM;
321                 }
322                 else
323                 {
324                         certTotalCount += certCount;
325                 }
326                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_CRITICAL1);
327                 if (certCount == -1)
328                 {
329                         r = E_SYSTEM;
330                 }
331                 else
332                 {
333                         certTotalCount += certCount;
334                 }
335                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_CRITICAL3);
336                 if (certCount == -1)
337                 {
338                         r = E_SYSTEM;
339                 }
340                 else
341                 {
342                         certTotalCount += certCount;
343                 }
344                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_CRITICAL4);
345                 if (certCount == -1)
346                 {
347                         r = E_SYSTEM;
348                 }
349                 else
350                 {
351                         certTotalCount += certCount;
352                 }
353                 certCount = _CertServer::InsertCert(_CERT_TYPE_OSP_CRITICAL5);
354                 if (certCount == -1)
355                 {
356                         r = E_SYSTEM;
357                 }
358                 else
359                 {
360                         certTotalCount += certCount;
361                 }
362         }
363         if (certTrustTypes & _CERT_TRUST_PHONE_ROOT_CA)
364         {
365                 //Install trusted by default certificates
366                 certCount = _CertServer::InsertCert(_CERT_TYPE_TRUSTED_CA);
367                 if (certCount == -1)
368                 {
369                         r = E_SYSTEM;
370                 }
371                 else
372                 {
373                         certTotalCount += certCount;
374                 }
375
376                 certCount = _CertServer::InsertCert(_CERT_TYPE_ROOT_CA);
377                 if (certCount == -1)
378                 {
379                         r = E_SYSTEM;
380                 }
381                 else
382                 {
383                         certTotalCount += certCount;
384                 }
385         }
386         if (certTrustTypes & _CERT_TRUST_PHONE_DOMAIN)
387         {
388                 certCount = _CertServer::InsertCert(_CERT_TYPE_ROOT_DOMAIN1);
389                 if (certCount == -1)
390                 {
391                         r = E_SYSTEM;
392                 }
393                 else
394                 {
395                         certTotalCount += certCount;
396                 }
397                 certCount = _CertServer::InsertCert(_CERT_TYPE_ROOT_DOMAIN2);
398                 if (certCount == -1)
399                 {
400                         r = E_SYSTEM;
401                 }
402                 else
403                 {
404                         certTotalCount += certCount;
405                 }
406                 certCount = _CertServer::InsertCert(_CERT_TYPE_ROOT_DOMAIN3);
407                 if (certCount == -1)
408                 {
409                         r = E_SYSTEM;
410                 }
411                 else
412                 {
413                         certTotalCount += certCount;
414                 }
415         }
416         if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN)
417         {
418                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
419                 if (certCount == -1)
420                 {
421                         r = E_SYSTEM;
422                 }
423                 else
424                 {
425                         certTotalCount += certCount;
426                 }
427                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
428                 if (certCount == -1)
429                 {
430                         r = E_SYSTEM;
431                 }
432                 else
433                 {
434                         certTotalCount += certCount;
435                 }
436                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
437                 if (certCount == -1)
438                 {
439                         r = E_SYSTEM;
440                 }
441                 else
442                 {
443                         certTotalCount += certCount;
444                 }
445         }
446         if (certTrustTypes & _CERT_TRUST_SIM_ROOT_CA)
447         {
448                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_CA);
449                 if (certCount == -1)
450                 {
451                         r = E_SYSTEM;
452                 }
453                 else
454                 {
455                         certTotalCount += certCount;
456                 }
457         }
458         if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA)
459         {
460                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_CA);
461                 if (certCount == -1)
462                 {
463                         r = E_SYSTEM;
464                 }
465                 else
466                 {
467                         certTotalCount += certCount;
468                 }
469         }
470         if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN)
471         {
472                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
473                 if (certCount == -1)
474                 {
475                         r = E_SYSTEM;
476                 }
477                 else
478                 {
479                         certTotalCount += certCount;
480                 }
481                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
482                 if (certCount == -1)
483                 {
484                         r = E_SYSTEM;
485                 }
486                 else
487                 {
488                         certTotalCount += certCount;
489                 }
490                 certCount = _CertServer::InsertCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
491                 if (certCount == -1)
492                 {
493                         r = E_SYSTEM;
494                 }
495                 else
496                 {
497                         certTotalCount += certCount;
498                 }
499         }
500
501         if (certTrustTypes & _CERT_TRUST_CSC_CA)
502         {
503                 certCount = _CertServer::InsertCert(_CERT_TYPE_CSC_ROOT_CA);
504                 if (certCount == -1)
505                 {
506                         r = E_SYSTEM;
507                 }
508                 else
509                 {
510                         certTotalCount += certCount;
511                 }
512                 certCount = _CertServer::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN1);
513                 if (certCount == -1)
514                 {
515                         r = E_SYSTEM;
516                 }
517                 else
518                 {
519                         certTotalCount += certCount;
520                 }
521                 certCount = _CertServer::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN2);
522                 if (certCount == -1)
523                 {
524                         r = E_SYSTEM;
525                 }
526                 else
527                 {
528                         certTotalCount += certCount;
529                 }
530                 certCount = _CertServer::InsertCert(_CERT_TYPE_CSC_ROOT_DOMAIN3);
531                 if (certCount == -1)
532                 {
533                         r = E_SYSTEM;
534                 }
535                 else
536                 {
537                         certTotalCount += certCount;
538                 }
539         }
540
541         if (pCertCount != null)
542         {
543                 *pCertCount = certTotalCount;
544         }
545
546         r = _CertManager::CreateCrtFile();
547         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
548
549         return r;
550 }
551
552 result
553 _CertServer::InsertDefaultCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen)
554 {
555         result r = E_SUCCESS;
556         _CertDbManager* pCertDb = null;
557
558         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer.");
559         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length.");
560         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
561         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
562
563         pCertDb = _CertDbManager::GetInstance();
564         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
565
566         r = pCertDb->InsertDefaultCaCertificateFromBuffer(type, format, pCertBuf, certLen);
567         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install default ca certiifcates.");
568
569         return r;
570 }
571
572 int
573 _CertServer::InsertUserCaCertificatesToRootDb(void)
574 {
575         result r = E_SUCCESS;
576         int certTrustTypes = 0;
577         int certCount = 0;
578
579         ClearLastResult();
580
581         certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN);
582
583         _CertServer::RemoveCerts(certTrustTypes);
584
585         r = _CertServer::InsertCerts(certTrustTypes, &certCount);
586         SysTryReturn(NID_SEC_CERT, !IsFailed(r), 0, E_SYSTEM, "[E_SYSTEM] Failed to install certificates.");
587
588         return certCount;
589 }
590
591 result
592 _CertServer::InsertCertificateChainContext(CertChainCtx pCertCtx)
593 {
594         result r = E_SUCCESS;
595         _CertDbManager* pCertDb = null;
596         _CertChain* pCertChain = null;
597
598         SysTryReturnResult(NID_SEC_CERT, pCertCtx != null, E_INVALID_ARG, "Invalid certificate chain context.");
599
600         pCertDb = _CertDbManager::GetInstance();
601         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
602
603         pCertChain = reinterpret_cast< _CertChain* >(pCertCtx);
604
605         r = pCertDb->InsertCertChain(_CERT_X509, pCertChain);
606         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));
607
608         r = _CertManager::CreateCrtFile();
609         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
610
611         return r;
612 }
613
614 result
615 _CertServer::InsertCaCertificate(_CaCertType type, _CertFormat format, byte* pCertBuf, int certLen)
616 {
617         result r = E_SUCCESS;
618         _CertDbManager* pCertDb = null;
619
620         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_INVALID_ARG, "Invalid certificate buffer.");
621         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid certificate length.");
622         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
623         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
624
625         pCertDb = _CertDbManager::GetInstance();
626         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
627
628         r = pCertDb->InsertCaCertificateFromBuffer(type, format, pCertBuf, certLen);
629         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install ca certificate from input buffer.");
630
631         r = _CertManager::CreateCrtFile();
632         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
633
634         return r;
635 }
636
637 result
638 _CertServer::InsertUserCaCertificate(_CertFormat format, char* pCert, int certLen)
639 {
640         result r = E_SUCCESS;
641
642         SysTryReturnResult(NID_SEC_CERT, pCert != null, E_INVALID_ARG, "Invalid input certificate buffer.");
643         SysTryReturnResult(NID_SEC_CERT, certLen > 0, E_INVALID_ARG, "Invalid input certificate length.");
644
645         _CertDbManager* pCertDb = _CertDbManager::GetInstance();
646         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
647
648         r = pCertDb->InsertCaCertificateFromBuffer(_CERT_TYPE_ROOT_CA_BY_USER, format, reinterpret_cast< byte* >(pCert), certLen);
649         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to install certificate from input buffer.");
650
651         r = _CertManager::CreateCrtFile();
652         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
653
654         return r;
655 }
656
657 result
658 _CertServer::InsertUserCaCertificate(byte* pFilePath)
659 {
660         result r = E_SUCCESS;
661         _CertFormat certFormat = _CERT_X509;
662         _CertDomainType res;
663         CertChainCtx certCtx = null;
664         File file;
665         FileAttributes attr;
666         int certLen = 0;
667         int readCnt = 0;
668         long fileSize = 0;
669         String fileName(reinterpret_cast< char* >(pFilePath));
670
671         SysTryReturnResult(NID_SEC_CERT, pFilePath != null, E_INVALID_ARG, "Invalid file path.");
672
673         r = File::GetAttributes(fileName, attr);
674
675         fileSize = attr.GetFileSize();
676         SysTryReturn(NID_SEC_CERT, fileSize > 0, r, r, "[%s] Failed to get file attributes.", GetErrorMessage(r));
677         SysTryReturn(NID_SEC_CERT, fileSize < _MAX_CERTIFICATE_SIZE, r, r, "[%s] File size exceeds maximum specified length.", GetErrorMessage(r));
678
679         r = file.Construct(fileName, L"r");
680         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to construct file.", GetErrorMessage(r));
681
682         std::unique_ptr< char[] > pCertBuf(new (std::nothrow) char[fileSize + 1]);
683         SysTryReturnResult(NID_SEC_CERT, pCertBuf != null, E_OUT_OF_MEMORY, "Allocating new char array failed.");
684         memset(pCertBuf.get(), 0, (fileSize + 1));
685
686         readCnt = file.Read(pCertBuf.get(), fileSize);
687         r = GetLastResult();
688         SysTryReturn(NID_SEC_CERT, (readCnt == fileSize) || (!IsFailed(r)), r, r, "[%s] Failed to read file.", GetErrorMessage(r));
689
690         certLen = readCnt;
691
692         r = _CertService::OpenContext(_CERT_CONTEXT_CERT, &certCtx);
693         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to open certificate context.");
694
695         r = _CertService::AddCertificate(certCtx, reinterpret_cast< byte* >(pCertBuf.get()), certLen);
696         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to add certificate to context.");
697
698         r = _CertService::VerifyChain(certCtx, &res);
699         SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_INVALID_CONDITION, E_INVALID_CONDITION, "[E_INVALID_CONDITION] Unable to verify certificate chain context.");
700
701         r = _CertServer::InsertUserCaCertificate(certFormat, pCertBuf.get(), certLen);
702         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.");
703
704         r = _CertManager::CreateCrtFile();
705         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r));
706
707 CATCH:
708
709         if (certCtx)
710         {
711                 _CertService::CloseContext(certCtx);
712         }
713
714         return r;
715 }
716
717 result
718 _CertServer::InsertUserCertChainPrivateKey(char* pCertChainBuffer, int certChainLength, char* pUserPrivateKey, int userPrivateKeyLength)
719 {
720         result r = E_SUCCESS;
721         _CertChain* pCertTempChain = null;
722         _CertPrivateKeyInfo* pPrivateKeyTempInfo = null;
723         _CertDbManager* pCertDb = null;
724
725         SysTryReturnResult(NID_SEC_CERT, pCertChainBuffer != null, E_INVALID_ARG, "Failed to insert user certificate chain.");
726         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Failed to insert user certificate chain.");
727
728         pCertDb = _CertDbManager::GetInstance();
729         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
730
731         r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pUserPrivateKey), userPrivateKeyLength, &pCertTempChain, &pPrivateKeyTempInfo);
732         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain buffer.", GetErrorMessage(r));
733
734         std::unique_ptr< _CertChain > pCertChain(pCertTempChain);
735         SysTryReturnResult(NID_SEC_CERT, pCertChain != null, E_SYSTEM, "Invalid certificate chain.");
736         pCertTempChain = null;
737
738         std::unique_ptr< _CertPrivateKeyInfo > pPrivateKeyInfo(pPrivateKeyTempInfo);
739         pPrivateKeyTempInfo = null;
740
741         r = pCertDb->InsertCertificateChain(_CERT_X509, pCertChain.get(), pPrivateKeyInfo.get());
742         SysTryReturn(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), r, r, "[%s] Failed to insert certificate chain.", GetErrorMessage(r));
743
744         r = _CertManager::CreateCrtFile();
745         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
746
747         return r;
748 }
749
750 result
751 _CertServer::InsertCertificateChainWithPrivateKey(char* pCertChainPrivateKeyBuffer, int certChainPrivateKeyLength)
752 {
753         result r = E_SUCCESS;
754         int privateKeyLen = 0;
755         int certChainLength = 0;
756         char* pCertChainBuffer = null;
757         _CertChain* pCertTempChain = null;
758         _CertDbManager* pCertDb = null;
759         _CertPrivateKeyInfo* pPrivateKeyTempInfo = null;
760
761         SysTryReturnResult(NID_SEC_CERT, pCertChainPrivateKeyBuffer != null, E_INVALID_ARG, "Invalid private key buffer.");
762         SysTryReturnResult(NID_SEC_CERT, certChainPrivateKeyLength > 0, E_INVALID_ARG, "Invalid private key length.");
763
764         privateKeyLen = _CertManager::GetBlockSize(reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer));
765         SysTryReturnResult(NID_SEC_CERT, privateKeyLen > 0, E_SYSTEM, "Failed to get private key length.");
766
767         pCertChainBuffer = pCertChainPrivateKeyBuffer + privateKeyLen;
768         certChainLength = certChainPrivateKeyLength - privateKeyLen;
769
770         SysTryReturnResult(NID_SEC_CERT, certChainLength > 0, E_INVALID_ARG, "Invalid private key length.");
771
772         pCertDb = _CertDbManager::GetInstance();
773         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
774
775         r = _CertManager::MakeParseAndVerifyCertChainBufferN(reinterpret_cast< byte* >(pCertChainBuffer), certChainLength, reinterpret_cast< byte* >(pCertChainPrivateKeyBuffer), privateKeyLen, &pCertTempChain, &pPrivateKeyTempInfo);
776         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse and verify certificate chain.", GetErrorMessage(r));
777
778         std::unique_ptr< _CertChain > pCertChain(pCertTempChain);
779         SysTryReturnResult(NID_SEC_CERT, pCertTempChain != null, E_SYSTEM, "Invalid certificate chain.");
780         pCertTempChain = null;
781
782         std::unique_ptr< _CertPrivateKeyInfo > pPrivateKeyInfo(pPrivateKeyTempInfo);
783         SysTryReturnResult(NID_SEC_CERT, pPrivateKeyTempInfo != null, E_SYSTEM, "Invalid private key info.");
784         pPrivateKeyTempInfo = null;
785
786         r = pCertDb->InsertCertificateChain(_CERT_X509, pCertChain.get(), pPrivateKeyInfo.get());
787         SysTryReturnResult(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), E_SYSTEM, "Failed to insert certificate chain");
788
789         r = _CertManager::CreateCrtFile();
790         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
791
792         return r;
793 }
794
795 result
796 _CertServer::InsertPkcs12Content(char* pPkcs12FilePath, char* pPkcs12ImportPassword)
797 {
798         result r = E_SUCCESS;
799         unsigned char* pTempPriKey = null;
800         unsigned char* pTempUserCertBuffer = null;
801         unsigned char* pTempCertBuffer = null;
802         std::unique_ptr< unsigned char[] > priKey;
803         std::unique_ptr< unsigned char[] > pCertChainBuffer;
804         std::unique_ptr< unsigned char > pCertBuffer;
805         std::unique_ptr< unsigned char > pUserCertBuffer;
806         int index = 0;
807         int curIndex = 0;
808         int priKeyLen = 0;
809         int userCertBufferLen = 0;
810         int certBufferLen = 0;
811         int certChainBufferLen = 0;
812         STACK_OF(X509)* pCaCertChain = null;
813         X509* pUserCert = null;
814         EVP_PKEY* pUserKey = null;
815         FILE* pFile = null;
816         PKCS12* pPkcs12Content = null;
817
818         SysTryReturnResult(NID_SEC_CERT, pPkcs12FilePath != null, E_INVALID_ARG, "Invalid pkcs12 file path.");
819         SysTryReturnResult(NID_SEC_CERT, pPkcs12ImportPassword != null, E_INVALID_ARG, "Invalid pkcs12 password buffer.");
820
821         pFile = fopen(pPkcs12FilePath, "rb");
822         SysTryReturnResult(NID_SEC_CERT, pFile != null, E_SYSTEM, "Pkcs#12 file open failed.");
823
824         pPkcs12Content = d2i_PKCS12_fp(pFile, (PKCS12**) null);
825         SysTryCatch(NID_SEC_CERT, pPkcs12Content != null, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 encoding failed.");
826
827         index = PKCS12_parse(pPkcs12Content, pPkcs12ImportPassword, &pUserKey, &pUserCert, &pCaCertChain);
828         SysTryCatch(NID_SEC_CERT, index != 0, r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Pkcs 12 parsing failed.");
829
830         if (pUserKey != null)
831         {
832                 priKeyLen = i2d_PrivateKey(pUserKey, &pTempPriKey);
833                 priKey = std::unique_ptr< unsigned char[] >(pTempPriKey);
834                 pTempPriKey = null;
835         }
836
837         userCertBufferLen = i2d_X509(pUserCert, &pTempUserCertBuffer);
838         pUserCertBuffer = std::unique_ptr< unsigned char >(pTempUserCertBuffer);
839         pTempUserCertBuffer = null;
840         certChainBufferLen = userCertBufferLen;
841
842         if (pCaCertChain && sk_num((_STACK*) pCaCertChain))
843         {
844                 for (index = 0; index < sk_X509_num(pCaCertChain); index++)
845                 {
846                         certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer);
847                         certChainBufferLen = certChainBufferLen + certBufferLen;
848                         pCertBuffer = std::unique_ptr< unsigned char >(pTempCertBuffer);
849                         pTempCertBuffer = null;
850                         certBufferLen = 0;
851                 }
852
853                 pCertChainBuffer = std::unique_ptr< unsigned char[] >(new (std::nothrow) unsigned char[certChainBufferLen]);
854                 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));
855
856                 memset(pCertChainBuffer.get(), 0, certChainBufferLen);
857                 memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen);
858                 curIndex = userCertBufferLen;
859
860                 for (index = 0; index < sk_X509_num(pCaCertChain); index++)
861                 {
862                         certBufferLen = i2d_X509(sk_X509_value(pCaCertChain, index), &pTempCertBuffer);
863                         pCertBuffer = std::unique_ptr< unsigned char >(pTempCertBuffer);
864                         pTempCertBuffer = null;
865                         memcpy((pCertChainBuffer.get() + curIndex), pCertBuffer.get(), certBufferLen);
866                         curIndex = curIndex + certBufferLen;
867                         certBufferLen = 0;
868                 }
869         }
870         else
871         {
872                 pCertChainBuffer = std::unique_ptr< unsigned char[] >(new (std::nothrow) unsigned char[certChainBufferLen]);
873                 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));
874
875                 memset(pCertChainBuffer.get(), 0, certChainBufferLen);
876                 memcpy(pCertChainBuffer.get(), pUserCertBuffer.get(), userCertBufferLen);
877         }
878
879         r = InsertUserCertChainPrivateKey(reinterpret_cast< char* >(pCertChainBuffer.get()), certChainBufferLen, reinterpret_cast< char* >(priKey.get()), priKeyLen);
880         SysTryCatch(NID_SEC_CERT, !(IsFailed(r) && r != E_FILE_ALREADY_EXIST), , r, "[%s] Failed to insert user certificate chain.", GetErrorMessage(r));
881
882         r = _CertManager::CreateCrtFile();
883         SysTryCatch(NID_SEC_CERT, !IsFailed(r), , r, "[%s] Failed to create crt file.", GetErrorMessage(r));
884
885 CATCH:
886         fclose(pFile);
887         PKCS12_free(pPkcs12Content);
888         EVP_PKEY_free(pUserKey);
889         X509_free(pUserCert);
890         sk_X509_free(pCaCertChain);
891         return r;
892 }
893
894 result
895 _CertServer::UpdateCaCertificate(_CaCertType type, char* pOldCert, int oldCertLen, char* pNewCert, int newCertLen) // if same certificate is in Db, replace the certificate using buffer2 and bufferLen2.
896 {
897         result r = E_SUCCESS;
898         _CertDbManager* pCertDb = null;
899         _CertFormat certFormat = _CERT_UNKNOWN;
900         int derCertBufferLengthOld = 0;
901         int derCertBufferLengthNew = 0;
902         byte* pDerCertOld = null;
903         byte* pDerCertNew = null;
904         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
905
906         SysTryReturnResult(NID_SEC_CERT, pOldCert != null, E_INVALID_ARG, "Invalid old certificate buffer.");
907         SysTryReturnResult(NID_SEC_CERT, oldCertLen > 0, E_INVALID_ARG, "Invalid old certificate length.");
908         SysTryReturnResult(NID_SEC_CERT, pNewCert != null, E_INVALID_ARG, "Invalid new certificate buffer.");
909         SysTryReturnResult(NID_SEC_CERT, newCertLen > 0, E_INVALID_ARG, "Invalid new certificate length.");
910         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
911         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
912
913         pCertDb = _CertDbManager::GetInstance();
914         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
915
916         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pOldCert), oldCertLen, &pDerCertOld, &derCertBufferLengthOld, &encodingType);
917         SysTryReturnResult(NID_SEC_CERT, pDerCertOld != null, E_SYSTEM, "Invalid old certificate buffer.");
918
919         std::unique_ptr< byte[] > pDerCertBufferOld(pDerCertOld);
920         SysTryReturnResult(NID_SEC_CERT, pDerCertBufferOld != null, E_INVALID_ARG, "Invalid old certificate buffer.");
921
922         pDerCertOld = null;
923         SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthOld > 0, E_SYSTEM, "Invalid old certificate length.");
924         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
925
926         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pNewCert), newCertLen, &pDerCertNew, &derCertBufferLengthNew, &encodingType);
927         SysTryReturnResult(NID_SEC_CERT, pDerCertNew != null, E_SYSTEM, "Invalid new certificate buffer.");
928
929         std::unique_ptr< byte[] > pDerCertBufferNew(pDerCertNew);
930         SysTryReturnResult(NID_SEC_CERT, pDerCertBufferNew != null, E_SYSTEM, "Invalid new certificate buffer.");
931
932         pDerCertNew = null;
933
934         SysTryReturnResult(NID_SEC_CERT, derCertBufferLengthNew > 0, E_SYSTEM, "Invalid new certificate length.");
935         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
936
937         r = pCertDb->UpdateCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBufferOld.get()), derCertBufferLengthOld, reinterpret_cast< byte* >(pDerCertBufferNew.get()), derCertBufferLengthNew);
938         if (r == E_DATA_NOT_FOUND)
939         {
940                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_OBJ_NOT_FOUND, "Certificate not found in db.");
941         }
942
943         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "An unexpected system error occurred.");
944
945         r = _CertManager::CreateCrtFile();
946         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
947
948         return r;
949 }
950
951 result
952 _CertServer::RemoveUserCertChainByCertId(int certId)
953 {
954         result r = E_SUCCESS;
955         _CertDbManager* pCertDb = null;
956
957         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
958
959         pCertDb = _CertDbManager::GetInstance();
960         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
961
962         r = pCertDb->RemoveCertificateChainByCertId(certId);
963         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete user certificate chain.");
964
965         r = _CertManager::CreateCrtFile();
966         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
967
968         return r;
969 }
970
971 result
972 _CertServer::RemoveUserCaCertificateByCertId(int certId)
973 {
974         result r = E_SUCCESS;
975         _CertDbManager* pCertDb = null;
976
977         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid certificate id.");
978
979         pCertDb = _CertDbManager::GetInstance();
980         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
981
982         r = pCertDb->RemoveUserCaCertificateByCertId(certId);
983         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete root ca certificate.");
984
985         r = _CertManager::CreateCrtFile();
986         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
987
988         return r;
989 }
990
991 result
992 _CertServer::RemoveCaCertificate(_CaCertType type, char* pBuffer, int bufLen) // if same certificate is in Db, remove the certificate.
993 {
994         result r = E_SUCCESS;
995         _CertDbManager* pCertDb = null;
996         _CertFormat certFormat = _CERT_UNKNOWN;
997         byte* pDerCert = null;
998         int derCertBufferLength = 0;
999         _CertEncodingType encodingType = _CERT_ENC_TYPE_UNKNOWN;
1000
1001         SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input certificate buffer.");
1002         SysTryReturnResult(NID_SEC_CERT, bufLen > 0, E_INVALID_ARG, "Invalid input certificate length.");
1003
1004         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1005         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1006
1007         pCertDb = _CertDbManager::GetInstance();
1008         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1009
1010         certFormat = _CertManager::GetEncodedCertBuffer(reinterpret_cast< byte* >(pBuffer), bufLen, &pDerCert, &derCertBufferLength, &encodingType);
1011         SysTryReturnResult(NID_SEC_CERT, pDerCert != null, E_SYSTEM, "Input certificate buffer.");
1012
1013         std::unique_ptr< byte[] > pDerCertBuffer(pDerCert);
1014         SysTryReturnResult(NID_SEC_CERT, pDerCertBuffer != null, E_SYSTEM, "Invalid certificate buffer.");
1015         pDerCert = null;
1016
1017         SysTryReturnResult(NID_SEC_CERT, derCertBufferLength > 0, E_SYSTEM, "Invalid certificate length.");
1018         SysTryReturnResult(NID_SEC_CERT, certFormat == _CERT_X509, E_SYSTEM, "Failed to find certificate format.");
1019
1020         r = pCertDb->RemoveCaCertificateFromBuffer(type, certFormat, reinterpret_cast< byte* >(pDerCertBuffer.get()), derCertBufferLength);
1021         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to remove Ca certificate.", GetErrorMessage(r));
1022
1023         r = _CertManager::CreateCrtFile();
1024         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1025
1026         return r;
1027 }
1028
1029 result
1030 _CertServer::RemoveCert(_CaCertType type)
1031 {
1032         result r = E_SUCCESS;
1033         _CertDbManager* pCertDb = null;
1034
1035         SysTryReturnResult(NID_SEC_CERT, type > _CERT_TYPE_NOT_BOUNDED, E_INVALID_ARG, "Invalid certificate type.");
1036         SysTryReturnResult(NID_SEC_CERT, type < _CERT_TYPE_MAX, E_INVALID_ARG, "Invalid certificate type.");
1037
1038         pCertDb = _CertDbManager::GetInstance();
1039         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1040
1041         r = pCertDb->RemoveCaCertificateByType(type);
1042         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to delete certificate of type %d", type);
1043
1044         r = _CertManager::CreateCrtFile();
1045         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1046
1047         return r;
1048 }
1049
1050 result
1051 _CertServer::RemoveCerts(int certTrustTypes)
1052 {
1053         result r = E_SUCCESS;
1054
1055         SysTryReturnResult(NID_SEC_CERT, certTrustTypes >= 0, E_INVALID_ARG, "Invalid certificate trust type.");
1056
1057         if (certTrustTypes & _CERT_TRUST_SIM_DOMAIN)
1058         {
1059                 r = _CertServer::RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN1);
1060                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1.");
1061
1062                 r = RemoveCert(_CERT_TYPE_SIM_ROOT_DOMAIN3);
1063                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3.");
1064         }
1065
1066         if (certTrustTypes & _CERT_TRUST_DEV_ROOT_CA)
1067         {
1068                 r = _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_CA);
1069                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove root ca certificate.");
1070         }
1071
1072         if (certTrustTypes & _CERT_TRUST_DEV_DOMAIN)
1073         {
1074                 r = _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN1);
1075                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain1.");
1076                 r = _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN2);
1077                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain2.");
1078                 r = _CertServer::RemoveCert(_CERT_TYPE_DEV_ROOT_DOMAIN3);
1079                 SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate for domain3.");
1080         }
1081
1082         r = _CertManager::CreateCrtFile();
1083         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1084
1085         return r;
1086 }
1087
1088 result
1089 _CertServer::RemoveUserCaCertificatesFromRootDb(void)
1090 {
1091         result r = E_SUCCESS;
1092         int certTrustTypes = 0;
1093
1094         certTrustTypes = static_cast< int >(_CERT_TRUST_DEV_ROOT_CA | _CERT_TRUST_DEV_DOMAIN);
1095
1096         r = _CertServer::RemoveCerts(static_cast< _CaCertType >(certTrustTypes));
1097         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to remove certificate.");
1098
1099         r = _CertManager::CreateCrtFile();
1100         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to create crt file.", GetErrorMessage(r));
1101
1102         return r;
1103 }
1104
1105 result
1106 _CertServer::GetUserCertChainByIssuerAndSubjectNameN(char* pIssuerName, int issuerNameLength, char* pSubjectName, int subjectNameLength, _CertificateListInfo*& pUserCertListInfoTypesRef)
1107 {
1108         result r = E_SUCCESS;
1109         _CertDbManager* pCertDb = null;
1110
1111         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_INVALID_ARG, "Invalid certificate's issuer name.");
1112         SysTryReturnResult(NID_SEC_CERT, issuerNameLength > 0, E_INVALID_ARG, "Invalid certificate's issuer name length.");
1113         SysTryReturnResult(NID_SEC_CERT, issuerNameLength < _MAX_ISSUER_SUBJECT_NAME_SIZE, E_INVALID_ARG, "Invalid certificate's issuer name length.");
1114         SysTryReturnResult(NID_SEC_CERT, pSubjectName != null, E_INVALID_ARG, "Invalid certificate's subject name.");
1115         SysTryReturnResult(NID_SEC_CERT, subjectNameLength > 0, E_INVALID_ARG, "Invalid certificate's subject name length.");
1116
1117         pCertDb = _CertDbManager::GetInstance();
1118         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1119
1120         r = pCertDb->GetUserCertificateChain(pIssuerName, issuerNameLength, pSubjectName, subjectNameLength, _CERT_ENC_TYPE_BINARY, &pUserCertListInfoTypesRef);
1121         SysTryReturnResult(NID_SEC_CERT, !IsFailed(r), E_SYSTEM, "Failed to get user certificate chain.");
1122
1123         return r;
1124 }
1125
1126 result
1127 _CertServer::GetUserCertificateByCertIdN(int certId, _CertEncodingType encodingType, _CertInfo*& pUserCertificateInfoRef)
1128 {
1129         result r = E_SUCCESS;
1130         _CertDbManager* pCertDb = null;
1131
1132         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
1133
1134         pCertDb = _CertDbManager::GetInstance();
1135         SysTryReturnResult(NID_SEC_CERT, pCertDb != null, E_SYSTEM, "Failed to get instance of certificate database manager.");
1136
1137         r = pCertDb->GetUserCertificateInfoByCertId(certId, encodingType, &pUserCertificateInfoRef);
1138         SysTryReturn(NID_SEC_CERT, pCertDb != null, r, r, "[%s]Failed to get user certificate by input cert identifier: (%d).", GetErrorMessage(r), certId);
1139
1140         return r;
1141 }
1142
1143 result
1144 _CertServer::GetUserCertFieldInfoByCertId(int certId, _CertFieldInfos* pCertFieldInfos)
1145 {
1146         result r = E_SUCCESS;
1147         _CertInfo* pCertInfo = null;
1148         CertificateHandle certificateHandle = null;
1149
1150         SysTryReturnResult(NID_SEC_CERT, pCertFieldInfos != null, E_INVALID_ARG, "Invalid input parameter.");
1151         SysTryReturnResult(NID_SEC_CERT, certId > 0, E_INVALID_ARG, "Invalid input parameter.");
1152
1153         r = GetUserCertificateByCertIdN(certId, _CERT_ENC_TYPE_BINARY, pCertInfo);
1154         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to get user certificate.", GetErrorMessage(r));
1155
1156         memset(pCertFieldInfos, 0, sizeof(*pCertFieldInfos));
1157
1158         if (pCertInfo != null && pCertInfo->certLength != 0)
1159         {
1160                 r = _CertService::OpenCertificate(reinterpret_cast< char* >(pCertInfo->certificate), pCertInfo->certLength, &certificateHandle);
1161                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to open certificate.");
1162
1163                 r = _CertService::GetCertInfo(certificateHandle, _CERT_FIELD_ALL, pCertFieldInfos);
1164                 SysTryCatch(NID_SEC_CERT, !IsFailed(r), r = E_SYSTEM, E_SYSTEM, "[E_SYSTEM] Failed to get certificate info.");
1165
1166                 pCertFieldInfos[0].certType = _CERT_TYPE_USER_CERT;
1167                 pCertFieldInfos[0].certFileId = pCertInfo->certId;
1168                 _CertService::CloseCertificate(&certificateHandle);
1169         }
1170
1171 CATCH:
1172         _CertService::FreeCertificateInfo(pCertInfo);
1173         _CertService::CloseCertificate(&certificateHandle);
1174         return r;
1175
1176 }
1177
1178 CertificateStoreCtx
1179 _CertServer::OpenCertificateStoreByType(_CaCertType type, int* pCount)
1180 {
1181         CertificateStoreCtx retCtx;
1182         int count = 0;
1183
1184         if (type == _CERT_TYPE_USER_CERT)
1185         {
1186                 retCtx = _CertManager::OpenUserCertificateStore(count);
1187         }
1188         else
1189         {
1190                 retCtx = _CertManager::OpenRootCaStore(type, count);
1191         }
1192
1193         if (pCount != null)
1194         {
1195                 *pCount = count;
1196         }
1197
1198         return retCtx;
1199 }
1200
1201 result
1202 _CertServer::CloseCertificateStore(CertificateStoreCtx certificateStoreCtx)
1203 {
1204         _CertRootList* pTemp = null;
1205
1206         SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid input parameter.");
1207
1208         std::unique_ptr< _CertRootCaInfo > pRootCa(reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx));
1209         SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_INVALID_ARG, "Allocating new _CertRootCaInfo failed.");
1210
1211         while (pRootCa->pRootList != null)
1212         {
1213                 pTemp = pRootCa->pRootList->pNext;
1214                 delete (pRootCa->pRootList);
1215                 pRootCa->pRootList = pTemp;
1216         }
1217         if (pRootCa->curPos)
1218         {
1219                 pRootCa->curPos = 0;
1220         }
1221
1222         return E_SUCCESS;
1223 }
1224
1225 int
1226 _CertServer::GetCertificateCount(CertificateStoreCtx certificateStoreCtx)
1227 {
1228         _CertRootCaInfo* pRootCa = null;
1229         int count = 0;
1230         _CertRootList* pTemp = null;
1231
1232         ClearLastResult();
1233
1234         if (certificateStoreCtx != null)
1235         {
1236                 pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx);
1237                 if (pRootCa->pRootList != null)
1238                 {
1239                         pTemp = pRootCa->pRootList;
1240                 }
1241                 else
1242                 {
1243                         return 0;
1244                 }
1245                 while (pTemp != null)
1246                 {
1247                         count++;
1248                         pTemp = pTemp->pNext;
1249                 }
1250         }
1251
1252         return count;
1253 }
1254
1255 result
1256 _CertServer::GetNextCertificate(CertificateStoreCtx certificateStoreCtx, int& curPos, char* pBuffer, int* pBufferLen)
1257 {
1258         _CertRootCaInfo* pRootCa = null;
1259         _CertRootList* pTemp = null;
1260         int count = 0;
1261
1262         SysTryReturnResult(NID_SEC_CERT, certificateStoreCtx != null, E_INVALID_ARG, "Invalid certificate store context.");
1263         SysTryReturnResult(NID_SEC_CERT, pBuffer != null, E_INVALID_ARG, "Invalid input buffer.");
1264         SysTryReturnResult(NID_SEC_CERT, pBufferLen != null, E_INVALID_ARG, "Invalid input buffer length.");
1265
1266         pRootCa = reinterpret_cast< _CertRootCaInfo* >(certificateStoreCtx);
1267         SysTryReturnResult(NID_SEC_CERT, pRootCa->pRootList != null, E_OBJ_NOT_FOUND, "Certificate list is empty.");
1268
1269         pTemp = pRootCa->pRootList;
1270
1271         while (count != curPos)
1272         {
1273                 count++;
1274                 SysTryReturnResult(NID_SEC_CERT, pTemp->pNext != null, E_OBJ_NOT_FOUND, "Certificate index not found.");
1275
1276                 pTemp = pTemp->pNext;
1277         }
1278
1279         pRootCa->pCurrRootList = pTemp;
1280         if (*pBufferLen > static_cast< int >(pRootCa->pCurrRootList->length))
1281         {
1282                 memcpy(pBuffer, pRootCa->pCurrRootList->certificate, pRootCa->pCurrRootList->length);
1283                 *pBufferLen = pRootCa->pCurrRootList->length;
1284         }
1285         else
1286         {
1287                 memcpy(pBuffer, pRootCa->pCurrRootList->certificate, *pBufferLen);
1288         }
1289
1290         curPos++;
1291
1292         return E_SUCCESS;
1293 }
1294
1295 } } } //Tizen::Security::Cert