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