Fix self-signed p12 certificate installation issue.
[platform/framework/native/appfw.git] / src / security / cert / FSecCert_Certificate.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 /**
18  * @file                FSecCert_Certificate.cpp
19  * @brief               This file contains implementation of X509 Certificate.
20 */
21
22 #include <stdio.h>
23 #include <string.h>
24 #include <stdlib.h>
25 #include <error.h>
26 #include <memory.h>
27 #include <new>
28 #include <sys/stat.h>
29 #include <assert.h>
30 #include <dirent.h>
31 #include <openssl/sha.h>
32 #include <openssl/evp.h>
33 #include <openssl/x509.h>
34 #include <openssl/x509v3.h>
35 #include <FBaseByteBuffer.h>
36 #include <FBaseResult.h>
37 #include <FSysSystemTime.h>
38 #include <FBaseSysLog.h>
39 #include "FSecCert_Certificate.h"
40 #include "FSecCert_CertOidDef.h"
41
42 using namespace Tizen::Base;
43 using namespace Tizen::System;
44
45 namespace Tizen { namespace Security { namespace Cert
46 {
47
48
49 //  _X509CertSubPublicKeyInfo class
50 _X509CertSubPublicKeyInfo::_X509CertSubPublicKeyInfo(void)
51         : __pPubKeyAlg(null)
52         , __publicKey(null)
53         , __publicKeySize(0)
54 {
55
56 }
57
58 _X509CertSubPublicKeyInfo::_X509CertSubPublicKeyInfo(const char* pAlg, int keyLen, byte* pPubKey)
59         : __pPubKeyAlg(null)
60         , __publicKey(null)
61         , __publicKeySize(0)
62 {
63         // MAY need alg ID check.
64         SetPubKeyAlgoId(pAlg);
65
66         // pubKey MUST DER-decoded BIT STRING
67         SetPubKey(keyLen, pPubKey);
68 }
69
70 _X509CertSubPublicKeyInfo::~_X509CertSubPublicKeyInfo(void)
71 {
72 }
73
74 result
75 _X509CertSubPublicKeyInfo::GetPubKeyN(int& keyLen, byte** ppPubKey)
76 {
77         keyLen = 0;
78         *ppPubKey = null;
79
80         SysTryReturnResult(NID_SEC_CERT, __publicKeySize > 0, E_SYSTEM, "Public key is not set as public key length is 0.");
81         SysTryReturnResult(NID_SEC_CERT, __publicKey != null, E_SYSTEM, "Public key is not set.");
82
83         keyLen = __publicKeySize;
84         *ppPubKey = new (std::nothrow) byte[keyLen + 1];
85         SysTryReturnResult(NID_SEC_CERT, *ppPubKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
86
87         memset(*ppPubKey, 0, keyLen + 1);
88         memcpy(*ppPubKey, __publicKey.get(), keyLen);
89
90         return E_SUCCESS;
91 }
92
93 result
94 _X509CertSubPublicKeyInfo::SetPubKey(int keyLen, byte* pPubKey)
95 {
96         __publicKey.reset(null);
97
98         __publicKey = std::unique_ptr< byte[] >(new (std::nothrow) byte[keyLen + 1]);
99         SysTryReturnResult(NID_SEC_CERT, __publicKey != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
100
101         memcpy(__publicKey.get(), pPubKey, keyLen);
102         __publicKey[keyLen] = 0x00;
103         __publicKeySize = keyLen;
104
105         return E_SUCCESS;
106 }
107
108 char*
109 _X509CertSubPublicKeyInfo::GetPubKeyAlgoId()
110 {
111         return __pPubKeyAlg.get();
112 }
113
114 result
115 _X509CertSubPublicKeyInfo::SetPubKeyAlgoId(const char* pPubKeyAlgoId)
116 {
117         __pPubKeyAlg.reset(null);
118
119         if (pPubKeyAlgoId)
120         {
121                 int algSize = strlen(pPubKeyAlgoId);
122
123                 __pPubKeyAlg = std::unique_ptr< char[] >(new (std::nothrow) char[algSize + 1]);
124                 SysTryReturnResult(NID_SEC_CERT, __pPubKeyAlg != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
125
126                 memcpy(__pPubKeyAlg.get(), pPubKeyAlgoId, algSize);
127                 __pPubKeyAlg[algSize] = 0x00;
128         }
129
130         return E_SUCCESS;
131 }
132
133
134 // _X509CertValidity class
135 _X509CertValidity::_X509CertValidity(void)
136 {
137 }
138
139 _X509CertValidity::_X509CertValidity(byte* pNotBefore, byte* pNotAfter)
140 {
141         SetTimes(pNotBefore, pNotAfter);
142 }
143
144 _X509CertValidity::~_X509CertValidity(void)
145 {
146 }
147
148 result
149 _X509CertValidity::GetValidity(Tizen::Base::DateTime& drmTime)
150 {
151         char validityFrom[_MAX_CERT_VALIDITY_SIZE + 1];
152         char validityTo[_MAX_CERT_VALIDITY_SIZE + 1];
153         char current[_MAX_CERT_VALIDITY_SIZE + 1];
154         Tizen::Base::DateTime notAfter;
155         Tizen::Base::DateTime notBefore;
156
157         __notAfter.ConvertToDateTime(notAfter);
158         __notBefore.ConvertToDateTime(notBefore);
159
160         _CertTime::FormatDateTime(notBefore, validityFrom);
161
162         //notBefore Format (Tizen::Base::DateTime::YYYYMMDD_HHMMSS, validityFrom)
163         _CertTime::FormatDateTime(drmTime, current);
164
165         //drmTime Format (Tizen::Base::DateTime::YYYYMMDD_HHMMSS, current)
166         _CertTime::FormatDateTime(notAfter, validityTo);
167
168         //notAfter Format(Tizen::Base::DateTime::YYYYMMDD_HHMMSS, validityTo)
169
170         if (drmTime <= notAfter && drmTime >= notBefore)
171         {
172                 return E_SUCCESS;
173         }
174
175         return E_SYSTEM;
176 }
177
178 result
179 _X509CertValidity::SetTimes(byte* pNotBefore, byte* pNotAfter)
180 {
181         _CertTime::_CertTimeType beforeTimeType = _CertTime::CERT_TIME_UTC;
182         _CertTime::_CertTimeType afterTimeType = _CertTime::CERT_TIME_UTC;
183
184         if (strlen(reinterpret_cast< const char* >(pNotBefore)) == static_cast< int >(_MAX_CERT_TIME_LEN))
185         {
186                 beforeTimeType = _CertTime::CERT_TIME_GENERAL;
187         }
188
189         if (strlen(reinterpret_cast< const char* >(pNotBefore)) == static_cast< int >(_MAX_CERT_TIME_LEN))
190         {
191                 afterTimeType = _CertTime::CERT_TIME_GENERAL;
192         }
193
194         __notBefore.SetTime(beforeTimeType, pNotBefore);
195         __notAfter.SetTime(afterTimeType, pNotAfter);
196         return E_SUCCESS;
197 }
198
199 result
200 _X509CertValidity::GetBeforeTimes(Tizen::Base::DateTime& notBefore)
201 {
202         __notBefore.ConvertToDateTime(notBefore);
203         return E_SUCCESS;
204 }
205
206 result
207 _X509CertValidity::GetAfterTimes(Tizen::Base::DateTime& notAfter)
208 {
209         __notAfter.ConvertToDateTime(notAfter);
210         return E_SUCCESS;
211 }
212
213
214 // _X509TbsCert class
215 _X509TbsCert::_X509TbsCert(void)
216         : __version(3)
217         , __serialNumberLen(null)
218         , __pIssuer(null)
219         , __pSubject(null)
220         , __pSignatureAlgoId(null)
221 {
222         memset(__serialNumber, 0, _MAX_SERIAL_NUMBER_SIZE);
223 }
224
225 _X509TbsCert::~_X509TbsCert(void)
226 {
227 }
228
229 // Version
230 void
231 _X509TbsCert::SetVersion(byte* pVersion, int len)
232 {
233         __version = pVersion[0] + 1;   // MUST be 3
234 }
235
236 void
237 _X509TbsCert::SetVersion(int version)
238 {
239         __version = version;
240 }
241
242 int
243 _X509TbsCert::GetVersion(void)
244 {
245         return __version;
246 }
247
248 // CertificateSerialNumber
249 void
250 _X509TbsCert::SetSerialNumber(byte* pSerial, int len)
251 {
252         memcpy(__serialNumber, pSerial, len);
253         __serialNumberLen = len;
254 }
255
256 result
257 _X509TbsCert::GetSerialNumber(byte*& pSerial, int& len)
258 {
259         pSerial = __serialNumber;
260         len = __serialNumberLen;
261
262         return E_SUCCESS;
263 }
264
265 // AlgorithmIdentifier
266 result
267 _X509TbsCert::SetSignatureAlgoId(const char* pAlgoId)
268 {
269         __pSignatureAlgoId.reset(null);
270
271         if (pAlgoId)
272         {
273                 int sigLen = strlen(pAlgoId);
274
275                 __pSignatureAlgoId = std::unique_ptr< char[] >(new (std::nothrow) char[sigLen + 1]);
276                 SysTryReturnResult(NID_SEC_CERT, __pSignatureAlgoId != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
277
278                 memcpy(__pSignatureAlgoId.get(), pAlgoId, sigLen);
279                 __pSignatureAlgoId[sigLen] = 0x00;
280         }
281
282         return E_SUCCESS;
283
284 }
285
286 char*
287 _X509TbsCert::GetSignatureAlgoId(void)
288 {
289         return __pSignatureAlgoId.get();
290 }
291
292 // Issuer Name
293 result
294 _X509TbsCert::SetIssuerName(byte* pName)
295 {
296         __pIssuer.reset(null);
297
298         if (pName != null)
299         {
300                 int len = strlen(reinterpret_cast< const char* >(pName));
301
302                 __pIssuer = std::unique_ptr< byte[] >(new (std::nothrow) byte[len + 1]);
303                 SysTryReturnResult(NID_SEC_CERT, __pIssuer != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
304
305                 memset(__pIssuer.get(), 0, len + 1);
306                 strcpy(reinterpret_cast< char* >(__pIssuer.get()), reinterpret_cast< const char* >(pName));
307         }
308
309         return E_SUCCESS;
310 }
311
312 byte*
313 _X509TbsCert::GetIssuerName(void)
314 {
315         return __pIssuer.get();
316 }
317
318 // Validity
319 result
320 _X509TbsCert::SetValidity(byte* pNotBefore, byte* pNotAfter)
321 {
322         return __validity.SetTimes(pNotBefore, pNotAfter);
323 }
324
325 result
326 _X509TbsCert::GetValidity()
327 {
328         Tizen::Base::DateTime curTime;
329
330         Tizen::System::SystemTime::GetCurrentTime(UTC_TIME, curTime);
331
332         return __validity.GetValidity(curTime);
333 }
334
335 result
336 _X509TbsCert::GetBeforeTimes(Tizen::Base::DateTime& notBefore)
337 {
338         __validity.GetBeforeTimes(notBefore);
339         return E_SUCCESS;
340 }
341
342 result
343 _X509TbsCert::GetAfterTimes(Tizen::Base::DateTime& notAfter)
344 {
345         return __validity.GetAfterTimes(notAfter);
346 }
347
348 // Subject Name
349 result
350 _X509TbsCert::SetSubjectName(byte* pName)
351 {
352         __pSubject.reset(null);
353
354         if (pName != null)
355         {
356                 int len = strlen(reinterpret_cast< const char* >(pName));
357
358                 __pSubject = std::unique_ptr< byte[] >(new (std::nothrow) byte[len + 1]);
359                 SysTryReturnResult(NID_SEC_CERT, __pSubject != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
360
361                 memset(__pSubject.get(), 0, len + 1);
362                 strcpy(reinterpret_cast< char* >(__pSubject.get()), reinterpret_cast< const char* >(pName));
363         }
364
365         return E_SUCCESS;
366 }
367
368 byte*
369 _X509TbsCert::GetSubjectName()
370 {
371         return __pSubject.get();
372 }
373
374
375 // Subject Public Key Info
376 result
377 _X509TbsCert::SetPublicKeyInfo(int keyLen, byte* pPubKey)
378 {
379         return __subPubKeyInfo.SetPubKey(keyLen, pPubKey);
380 }
381
382 result
383 _X509TbsCert::GetPublicKeyInfoN(int& keyLen, byte** ppPubKey)
384 {
385         return __subPubKeyInfo.GetPubKeyN(keyLen, ppPubKey);
386 }
387
388 result
389 _X509TbsCert::SetPublicKeyAlgoIdInfo(const char* pPubKeyAlgoId)
390 {
391         return __subPubKeyInfo.SetPubKeyAlgoId(pPubKeyAlgoId);
392 }
393
394 char*
395 _X509TbsCert::GetPublicKeyAlgoIdInfo()
396 {
397         return __subPubKeyInfo.GetPubKeyAlgoId();
398 }
399
400 //Extensions
401 result
402 _X509TbsCert::AddExtension(byte* pOid, bool critical, byte* pValue, int len)
403 {
404         if (pOid && pValue)
405         {
406                 __extension.AddExt(pOid, critical, pValue, len);
407                 return E_SUCCESS;
408         }
409
410         return E_INVALID_ARG;
411 }
412
413 _CertExtension*
414 _X509TbsCert::GetCertExtension()
415 {
416         return &__extension;
417 }
418
419 // _Certificate class
420 _Certificate::_Certificate(void)
421 {
422         __certFormat = _CERT_X509;
423 }
424
425 _Certificate::~_Certificate()
426 {
427         //Empty body
428 }
429
430 result
431 _Certificate::ParseObject(void)
432 {
433         return E_UNSUPPORTED_OPERATION;
434 }
435
436 result
437 _Certificate::GetKeyIdN(byte** ppKeyid)
438 {
439         return E_UNSUPPORTED_OPERATION;
440 }
441
442 bool
443 _Certificate::IsSelfSigned(void)
444 {
445         return false;
446 }
447
448 _CertFormat
449 _Certificate::GetCertFormat(void)
450 {
451         return __certFormat;
452 }
453
454 void
455 _Certificate::SetCertFormat(_CertFormat certFormat)
456 {
457         __certFormat = certFormat;
458 }
459
460 //
461 // _X509Certificate class
462 //
463 _X509Certificate::_X509Certificate(void)
464         : __contextCert(false)
465         , __isCaCert(false)
466         , __x509IsSelfSign(false)
467         , __pX509Certificate(null)
468 {
469         SetCertFormat(_CERT_X509);
470 }
471
472 _X509TbsCert*
473 _X509Certificate::GetTbsCertInstance(void)
474 {
475         return &__tbsCert;
476 }
477
478 _CertSignature*
479 _X509Certificate::GetSignInstance(void)
480 {
481         return &__signautreInfo;
482 }
483
484 _X509Certificate::~_X509Certificate(void)
485 {
486
487         if (__pX509Certificate != null)
488         {
489                 X509_free(static_cast< X509* >(__pX509Certificate));
490         }
491
492 }
493
494 bool
495 _X509Certificate::IsCaCertificate()
496 {
497         return __isCaCert;
498 }
499
500
501 result
502 _X509Certificate::GetKeyIdN(byte** ppKeyid)
503 {
504         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
505         byte* pPublicKey = null;
506         int len = 0;
507         int outLen = SHA_DIGEST_LENGTH;
508         int resValue = 0;
509
510         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
511
512         pPublicKey = pX509Certificate->cert_info->key->public_key->data;
513         len = pX509Certificate->cert_info->key->public_key->length;
514
515         if (pPublicKey[0] == 0x00)
516         {
517                 pPublicKey++;
518                 len--;
519         }
520
521         std::unique_ptr< byte[] > pKeyId(new (std::nothrow) byte[SHA_DIGEST_LENGTH + 1]);
522         SysTryReturnResult(NID_SEC_CERT, pKeyId != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
523
524         memset(pKeyId.get(), 0, SHA_DIGEST_LENGTH + 1);
525         //As per OpenSSL APIs, it takes input as unsigned data types
526         resValue = EVP_Digest(pPublicKey, len, pKeyId.get(), reinterpret_cast< unsigned int* >(&outLen), EVP_sha1(), 0);
527         SysTryReturnResult(NID_SEC_CERT, resValue == 1, E_SYSTEM, "Failed to calculate digest hash.");
528         *ppKeyid = pKeyId.release();
529
530         return E_SUCCESS;
531 }
532
533 result
534 _X509Certificate::GetCertBuffer(byte*& pBuf, int& bufSize)
535 {
536         SysTryReturnResult(NID_SEC_CERT, _pX509Buff != null, E_SYSTEM, "Initial parameters are not set");
537
538         pBuf = _pX509Buff.get();
539         bufSize = _x509BuffSize;
540         return E_SUCCESS;
541 }
542
543 result
544 _X509Certificate::GetIssuerBuffer(byte*& pBuf, int& bufSize)
545 {
546         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
547         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
548
549         pBuf = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->issuer, null, 0));
550         bufSize = strlen(reinterpret_cast< char* >(pBuf));
551         return E_SUCCESS;
552 }
553
554 result
555 _X509Certificate::GetSubjectNameBuffer(byte*& pBuf, int& bufSize)
556 {
557         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
558         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
559
560         pBuf = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->subject, null, 0));
561         bufSize = strlen(reinterpret_cast< char* >(pBuf));
562         return E_SUCCESS;
563 }
564
565 bool
566 _X509Certificate::IsSelfSigned(void)
567 {
568         return __x509IsSelfSign;
569 }
570
571 void*
572 _X509Certificate::GetX509CertObject()
573 {
574         return __pX509Certificate;
575 }
576
577 bool
578 _X509Certificate::IsIssuer(Tizen::Security::Cert::_X509Certificate* pIssuerCert)
579 {
580         SysTryReturnResult(NID_SEC_CERT, pIssuerCert != null, E_INVALID_ARG, "Invalid input parameters issuer certificate.");
581
582         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
583         X509* pX509IssuerCertificate = static_cast< X509* >(pIssuerCert->__pX509Certificate);
584
585         SysTryReturnResult(NID_SEC_CERT, pX509IssuerCertificate != null, E_INVALID_ARG, "Invalid input parameters issuer certificate.");
586         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
587
588         if (X509_check_issued(pX509IssuerCertificate, pX509Certificate) == X509_V_OK)
589         {
590                 return true;
591         }
592
593         return false;
594 }
595
596 bool
597 _X509Certificate::IsContextCertificate(void)
598 {
599         return __contextCert;
600 }
601
602 void
603 _X509Certificate::SetContextCertificate(bool contextCert)
604 {
605         __contextCert = contextCert;
606 }
607
608 result
609 _X509Certificate::VerifySignature(byte* pPublicKey, int keySize)
610 {
611         result r = E_SUCCESS;
612         EVP_PKEY* pKey = null;
613         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
614         const unsigned char* pPublicKeyBuffer = const_cast< const unsigned char* >(pPublicKey);
615
616         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
617
618         if (pPublicKeyBuffer != null && keySize > 0)
619         {
620                 pKey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &pPublicKeyBuffer, keySize);
621         }
622         else //check if self signed
623         {
624                 pKey = X509_get_pubkey(pX509Certificate);
625         }
626
627         SysTryReturnResult(NID_SEC_CERT, pKey != null, E_SYSTEM, "Public key could not be constructed.");
628
629         if (X509_verify(pX509Certificate, pKey) <= 0)
630         {
631                 SysTryReturnResult(NID_SEC_CERT, false, E_SYSTEM, "Openssl X509 certificate verify function failed.");
632         }
633
634
635         return r;
636 }
637
638 // Get Total length
639
640 // Get TBSCertificate length
641 result
642 _X509Certificate::ParseTbsCertHeader(void)
643 {
644         if (ParseVersion() != E_SUCCESS)
645         {
646                 return E_PARSING_FAILED;
647         }
648
649         if (ParseSerialNumber() != E_SUCCESS)
650         {
651                 return E_PARSING_FAILED;
652         }
653
654         if (ParseAlgorithmIdentifier() != E_SUCCESS)
655         {
656                 return E_PARSING_FAILED;
657         }
658
659         if (ParseIssuerName() != E_SUCCESS)
660         {
661                 return E_PARSING_FAILED;
662         }
663
664         if (ParseValidity() != E_SUCCESS)
665         {
666                 return E_PARSING_FAILED;
667         }
668
669         if (ParseSubjectName() != E_SUCCESS)
670         {
671                 return E_PARSING_FAILED;
672         }
673
674
675         if (ParseSubjectPublicKeyInfo() != E_SUCCESS)
676         {
677                 return E_PARSING_FAILED;
678         }
679
680         if (ParseExtensions() != E_SUCCESS)
681         {
682                 return E_PARSING_FAILED;
683         }
684         return E_SUCCESS;
685 }
686
687
688 //  Get Header Info
689 //   version                  [0]  Version DEFAULT v1
690 //   Version ::= INTEGER {v1(0), v2(1), v3(2)}
691
692 result
693 _X509Certificate::ParseVersion(void)
694 {
695         int version = 0;
696         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
697         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
698
699
700         version = ASN1_INTEGER_get(pX509Certificate->cert_info->version) + 1;   // default is 0 --> version 1
701         __tbsCert.SetVersion(version);
702
703         return E_SUCCESS;
704 }
705
706 //   CertificateSerialNumber ::= INTEGER
707 result
708 _X509Certificate::ParseSerialNumber(void)
709 {
710         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
711         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
712
713         __tbsCert.SetSerialNumber(pX509Certificate->cert_info->serialNumber->data, pX509Certificate->cert_info->serialNumber->length);
714         return E_SUCCESS;
715 }
716
717
718 //   AlgorithmIdentifier ::= SEQUENCE {
719 //     algorithm   ALGORITHM.&id({SupportedAlgorithms}),
720 //     parameters  ALGORITHM.&Type({SupportedAlgorithms}{@algorithm}) OPTIONAL
721 //   }
722 //   1.2.840.113549.1.1.5 - SHA1RSA
723
724 result
725 _X509Certificate::ParseAlgorithmIdentifier(void)
726 {
727         const char* pAlgorithmIdentifier = null;
728         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
729         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
730
731         pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->cert_info->signature->algorithm));
732
733         return __tbsCert.SetSignatureAlgoId(pAlgorithmIdentifier);
734 }
735
736 // SEQUENCE > [SET > SEQUENCE > [OID > VALUE]]
737
738 result
739 _X509Certificate::ParseIssuerName(void)
740 {
741         byte* pName = null;
742         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
743         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
744
745         pName = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->issuer, null, 0));
746         SysTryReturnResult(NID_SEC_CERT, pName != null, E_PARSING_FAILED, "Failed to get certificate issuer name.");
747
748         __tbsCert.SetIssuerName(pName);
749         free(pName);
750         return E_SUCCESS;
751 }
752
753 //   Validity ::= SEQUENCE {notBefore  Time,
754 //                          notAfter   Time
755 //   }
756 //   Time ::= CHOICE {utcTime          UTCTime,
757 //                    generalizedTime  GeneralizedTime
758 //   }
759
760 result
761 _X509Certificate::ParseValidity(void)
762 {
763         result r = E_SUCCESS;
764         ASN1_GENERALIZEDTIME* timeNotBefore = NULL;
765         ASN1_GENERALIZEDTIME* timeNotAfter = NULL;
766         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
767         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
768
769
770         ASN1_TIME_to_generalizedtime(pX509Certificate->cert_info->validity->notBefore, &timeNotBefore);
771         ASN1_TIME_to_generalizedtime(pX509Certificate->cert_info->validity->notAfter, &timeNotAfter);
772
773         std::unique_ptr< byte[] > pNotBefore(new (std::nothrow) byte[timeNotBefore->length + 1]);
774         SysTryReturnResult(NID_SEC_CERT, pNotBefore != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
775
776         memcpy(pNotBefore.get(), timeNotBefore->data, timeNotBefore->length);
777         pNotBefore[timeNotBefore->length] = 0x00;
778
779         // get Time
780
781         std::unique_ptr< byte[] > pNotAfter(new (std::nothrow) byte[timeNotAfter->length + 1]);
782         SysTryReturnResult(NID_SEC_CERT, pNotAfter != null, E_OUT_OF_MEMORY, "Failed to allocate memory");
783
784         memcpy(pNotAfter.get(), timeNotAfter->data, timeNotAfter->length);
785         pNotAfter[timeNotAfter->length] = 0x00;
786
787         __tbsCert.SetValidity(pNotBefore.get(), pNotAfter.get());
788
789         return r;
790 }
791
792 // SEQUENCE > [SET > SEQUENCE > [OID > VALUE]]+
793 result
794 _X509Certificate::ParseSubjectName(void)
795 {
796         result r = E_SUCCESS;
797         byte* pSubject = null;
798         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
799         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
800
801         pSubject = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->subject, null, 0));
802         SysTryReturnResult(NID_SEC_CERT, pSubject != null, E_PARSING_FAILED, "Failed to get certificate subject name.");
803
804         __tbsCert.SetSubjectName(pSubject);
805
806         byte* pIssuerName = null;
807
808         pIssuerName = reinterpret_cast< byte* >(X509_NAME_oneline(pX509Certificate->cert_info->issuer, null, 0));
809         SysTryReturnResult(NID_SEC_CERT, pIssuerName != null, E_PARSING_FAILED, "Failed to get certificate issuer name.");
810
811         if (strcmp(reinterpret_cast< const char* >(pSubject), reinterpret_cast< const char* >(pIssuerName)) == 0)
812         {
813                 __x509IsSelfSign = true;
814         }
815         else
816         {
817                 __x509IsSelfSign = false;
818         }
819
820         free(pSubject);
821         free(pIssuerName);
822         return r;
823 }
824
825
826 //  SubjectPublicKeyInfo ::= SEQUENCE {
827 //    algorithm         AlgorithmIdentifier,
828 //    subjectPublicKey  BIT STRING
829 //  }
830 //  AlgorithmIdentifier ::= SEQUENCE {
831 //    algorithm   ALGORITHM.&id({SupportedAlgorithms}),
832 //    parameters  ALGORITHM.&Type({SupportedAlgorithms}{@algorithm}) OPTIONAL
833
834 result
835 _X509Certificate::ParseSubjectPublicKeyInfo(void)
836 {
837         result r = E_SUCCESS;
838         const char* pAlgorithmIdentifier = null;
839         byte* pPubKey = null;
840         int pubKeyLen = 0;
841         EVP_PKEY* pKey = null;
842         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
843         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
844
845         pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->cert_info->key->algor->algorithm));
846         __tbsCert.SetPublicKeyAlgoIdInfo(pAlgorithmIdentifier);
847
848         /* get public key */
849         pKey = X509_get_pubkey(pX509Certificate);
850         SysTryReturnResult(NID_SEC_CERT, pKey != null, E_PARSING_FAILED, "Failed to get certificate public key.");
851
852         pubKeyLen = i2d_PublicKey(pKey, &pPubKey);
853
854         __tbsCert.SetPublicKeyInfo(pubKeyLen, pPubKey);
855
856         OPENSSL_free(pPubKey);
857         EVP_PKEY_free(pKey);
858         return r;
859 }
860
861 /**
862   Extensions ::= SEQUENCE OF Extension
863   Extension ::= SEQUENCE {
864     extnId     EXTENSION.&id({ExtensionSet}),
865     critical   BOOLEAN DEFAULT false,
866     extnValue  OCTET STRING-- contains a DER encoding of a value of type &ExtnType
867   -- for the extension object identified by extnId
868   }
869  */
870 result
871 _X509Certificate::ParseExtensions(void)
872 {
873         byte* pValue = null;
874         byte* pOid = null;
875         bool critical = false;
876         int fieldCount = 0;
877         int extLen = 0;
878         int count = 0;
879         X509_EXTENSION* pExt = NULL;
880         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
881         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
882
883         if (pX509Certificate->cert_info->extensions == null)
884         {
885                 return E_SUCCESS;
886         }
887
888         fieldCount = sk_X509_EXTENSION_num(pX509Certificate->cert_info->extensions);
889
890         for (count = 0; count < fieldCount; count++)
891         {
892                 pExt = sk_X509_EXTENSION_value(pX509Certificate->cert_info->extensions, count);
893
894                 if (pExt != null)
895                 {
896                         pOid = reinterpret_cast< byte* >(const_cast< char* >(OBJ_nid2ln(OBJ_obj2nid(pExt->object))));
897
898                         critical = pExt->critical;
899                         pValue = pExt->value->data;
900                         extLen = pExt->value->length;
901
902
903                         if (pOid != null)
904                         {
905                                 __tbsCert.AddExtension(pOid, critical, pValue, extLen);
906                         }
907                 }
908
909         } // End of while loop
910
911         return E_SUCCESS;
912
913 }
914
915 result
916 _X509Certificate::ParseSignature(void)
917 {
918         result r = E_SUCCESS;
919         const char* pAlgorithmIdentifier = null;
920         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
921         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_SYSTEM, "Initial parameters are not set");
922
923         pAlgorithmIdentifier = OBJ_nid2ln(OBJ_obj2nid(pX509Certificate->sig_alg->algorithm));
924         SysTryReturnResult(NID_SEC_CERT, pAlgorithmIdentifier != null, E_SYSTEM, "Signature algorithm not present in certificate.");
925         SysTryReturnResult(NID_SEC_CERT, pX509Certificate->signature->data != null, E_SYSTEM, "Signature data not present in certificate.");
926
927         __signautreInfo.SetSignature(pAlgorithmIdentifier, pX509Certificate->signature->length, pX509Certificate->signature->data);
928
929         return r;
930 }
931
932 result
933 _X509Certificate::ParseRun(void)
934 {
935         result r = E_PARSING_FAILED;
936
937         r = ParseTbsCertHeader();
938         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse tbs certificate.", GetErrorMessage(r));
939
940         r = ParseSignature();
941         SysTryReturn(NID_SEC_CERT, !IsFailed(r), r, r, "[%s] Failed to parse cert signature.", GetErrorMessage(r));
942
943         return r;
944 }
945
946 result
947 _X509Certificate::ParseObject(void)
948 {
949         X509* pX509Certificate = static_cast< X509* >(__pX509Certificate);
950         const unsigned char* pX509Buff = const_cast< const unsigned char* >(_pX509Buff.get());
951
952         SysAssertf(pX509Buff != null, "Not yet constructed. Reconstructor the object.");
953
954         if (pX509Certificate != null)
955         {
956                 X509_free(pX509Certificate);
957                 __pX509Certificate = null;
958         }
959
960         d2i_X509(&pX509Certificate, &pX509Buff, _x509BuffSize);
961         SysTryReturnResult(NID_SEC_CERT, pX509Certificate != null, E_PARSING_FAILED, "Failed to parse certificate.");
962
963         __pX509Certificate = pX509Certificate;
964
965         if (X509_check_ca(pX509Certificate) > 0)
966         {
967                 __isCaCert = true;
968         }
969
970
971         return ParseRun();
972 }
973
974 } } } //Tizen::Security::Cert