/***************************************************************************
 * Copyright 1998 International Business Machines Corporation. All Rights
 * Reserved.
 *
 * Please read this carefully.  Your use of this reference implementation of
 * certain of the IETF public-key infrastructure specifications ("Software")
 * indicates your acceptance of the following.  If you do not agree to the
 * following, do not install or use any of the Software.
 *
 * Permission to use, reproduce, distribute and create derivative works from
 * the Software ("Software Derivative Works"), and to distribute such Software
 * Derivative Works is hereby granted to you by International Business
 * Machines Corporation ("IBM").  This permission includes a license under the
 * patents of IBM that are necessarily infringed by your use of the Software
 * as provided by IBM.
 *
 * IBM licenses the Software to you on an "AS IS" basis, without warranty of
 * any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES OR CONDITIONS,
 * EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, NON INFRINGEMENT AND FITNESS
 * FOR A PARTICULAR PURPOSE.  You are solely responsible for determining the
 * appropriateness of using this Software and assume all risks associated with
 * the use of this Software, including but not limited to the risks of program
 * errors, damage to or loss of data, programs or equipment, and
 * unavailability or interruption of operations.
 *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL,
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC CONSEQUENTIAL DAMAGES
 * (INCLUDING LOST PROFITS OR SAVINGS), EVEN IF IBM HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.  IBM will not be liable for the loss of, or
 * damage to, your records or data, or any damages claimed by you based on a
 * third party claim.
 *
 * IBM wishes to obtain your feedback to assist in improving the Software. You
 * grant IBM a world-wide, royalty-free right to use, copy, distribute,
 * sublicense and prepare derivative works based upon any feedback, including
 * materials, error corrections, Software Derivatives, enhancements,
 * suggestions and the like that you provide to IBM relating to the Software
 * (this does not include products for which you charge a royalty and
 * distribute to IBM under other terms and conditions).
 *
 * You agree to distribute the Software and any Software Derivatives under a
 * license agreement that: 1) is sufficient to notify all licensees of the
 * Software and Software Derivatives that IBM assumes no liability for any
 * claim that may arise regarding the Software or Software Derivatives, and 2)
 * that disclaims all warranties, both express and implied, from IBM regarding
 * the Software and Software Derivatives.  (If you include this Agreement with
 * any distribution of the Software or Software Derivatives you will have met
 * this requirement.)  You agree that you will not delete any copyright
 * notices in the Software.
 *
 * This Agreement is the exclusive statement of your rights in the Software as
 * provided by IBM.   Except for the rights granted to you in the second
 * paragraph above, You are not granted any other patent rights, including but
 * not limited to the right to make combinations of the Software with products
 * that infringe IBM patents. You agree to comply with all applicable laws and
 * regulations, including all export and import laws and regulation.  This
 * Agreement is governed by the laws of the State of New York.  This Agreement
 * supersedes all other communications, understandings or agreements we may
 * have had prior to this Agreement.
 ****************************************************************************/

//------------------------------------------------------------
// includes
//------------------------------------------------------------

#include "functiontrace.h"
#include "pkixcertcrl.h"


// utility accessors for legacy PKCS-9 EmailAttribute check

bool
pkix_certificate::containsEmailAddress()
{
   if (!_init) init();
   return _isEmailAddressPresent;
}
   
bool
pkix_certificate::areDuplicateExtensionsPresent()
{
   if (!_init) init();
   return _areDuplicateExtensionsPresent;
}

// utiliy acccessors for PKIX tbsCertficate fields

bool pkix_certificate::isSubjectNull() 
{ 
   if (!_init) init();
   return _subjectIsNull;
}

bool pkix_certificate::isIssuerNull() 
{ 
   if (!_init) init();
   return _isIssuerNull;
}

bool pkix_certificate::isIssuerUniqueIDPresent()
{ 
   if (!_init) init();
   return _isIssuerUniqueIDPresent;
}

bool pkix_certificate::isSubjectUniqueIDPresent()
{ 
   if (!_init) init();
   return _isSubjectUniqueIDPresent;
}

bool pkix_certificate::isExtensionsPresent()
{ 
   if (!_init) init();
   return _isExtensionsPresent;
}

   
// utility accessors for PKIX extensions

bool pkix_certificate::isAuthorityKeyIdentifierPresent() 
{ 
   if (!_init) init();
   return _isAuthorityKeyIdentifierPresent;
}

bool pkix_certificate::isSubjectKeyIdentifierPresent() 
{ 
   if (!_init) init();
   return _isSubjectKeyIdentifierPresent;
}

bool pkix_certificate::isKeyUsagePresent() 
{ 
   if (!_init) init();
   return _isKeyUsagePresent;
}

bool pkix_certificate::isPrivateKeyUsagePeriodPresent() 
{ 
   if (!_init) init();
   return _isPrivateKeyUsagePeriodPresent;
}


bool pkix_certificate::isCertificatePoliciesPresent()  
{ 
   if (!_init) init();
   return _isCertificatePoliciesPresent;
}

bool pkix_certificate::isPolicyMappingsPresent() 
{ 
   if (!_init) init();
   return _isPolicyMappingsPresent;
}

bool pkix_certificate::isSubjectAlternativeNamePresent() 
{ 
   if (!_init) init();
   return _isSubjectAlternativeNamePresent;
}

bool pkix_certificate::isIssuerAlternativeNamePresent() 
{ 
   if (!_init) init();
   return _isIssuerAlternativeNamePresent;
}

bool pkix_certificate::isBasicConstraintsPresent() 
{ 
   if (!_init) init();
   return _isBasicConstraintsPresent;
}

bool pkix_certificate::isNameConstraintsPresent() 
{ 
   if (!_init) init();
   return _isNameConstraintsPresent;
}

bool pkix_certificate::isPolicyConstraintsPresent() 
{ 
   if (!_init) init();
   return _isPolicyConstraintsPresent;
}

bool pkix_certificate::isCRLDistributionPointsPresent() 
{ 
   if (!_init) init();
   return _isCRLDistributionPointsPresent;
}

bool pkix_certificate::isAuthorityKeyIdentifierCritical() 
{ 
   if (!_init) init();
   return _isAuthorityKeyIdentifierCritical;
}

bool pkix_certificate::isSubjectKeyIdentifierCritical() 
{ 
   if (!_init) init();
   return _isSubjectKeyIdentifierCritical;
}

bool pkix_certificate::isKeyUsageCritical() 
{ 
   if (!_init) init();
   return _isKeyUsageCritical;
}

bool pkix_certificate::isPrivateKeyUsagePeriodCritical() 
{ 
   if (!_init) init();
   return _isPrivateKeyUsagePeriodCritical;
}

bool pkix_certificate::isCertificatePoliciesCritical()  
{ 
   if (!_init) init();
   return _isCertificatePoliciesCritical;
}

bool pkix_certificate::isPolicyMappingsCritical() 
{ 
   if (!_init) init();
   return _isPolicyMappingsCritical;
}

bool pkix_certificate::isSubjectAlternativeNameCritical() 
{ 
   if (!_init) init();
   return _isSubjectAlternativeNameCritical;
}

bool pkix_certificate::isIssuerAlternativeNameCritical() 
{ 
   if (!_init) init();
   return _isIssuerAlternativeNameCritical;
}

bool pkix_certificate::isBasicConstraintsCritical() 
{ 
   if (!_init) init();
   return _isBasicConstraintsCritical;
}

bool pkix_certificate::isNameConstraintsCritical() 
{ 
   if (!_init) init();
   return _isNameConstraintsCritical;
}

bool pkix_certificate::isPolicyConstraintsCritical() 
{ 
   if (!_init) init();
   return _isPolicyConstraintsCritical;
}

bool pkix_certificate::isCRLDistributionPointsCritical() 
{ 
   if (!_init) init();
   return _isCRLDistributionPointsCritical;
}

int pkix_certificate::init()
{
   TPTRACE(jonahtp_trace_info, "void pkix_certificate::init()");

   int status = 0;

   _init = true;

   if ( tbsCertificate.subject.get_child_count() == 0)
      _subjectIsNull = true;
   if ( tbsCertificate.issuer.get_child_count() == 0)
      _isIssuerNull = true;
   if ( tbsCertificate.issuerUniqueID.is_present() )
      _isIssuerUniqueIDPresent = true;
   if ( tbsCertificate.subjectUniqueID.is_present() )
      _isSubjectUniqueIDPresent = true;

   if (!_subjectIsNull)
   {
      if ((status = populate_emailAddress()) != 0)
         return status;
   }

   // Extensions checking

   if ( tbsCertificate.extensions.is_present() )
      _isExtensionsPresent = true;

   if ( !_isExtensionsPresent )
      return status;

   // TO DO: calculate _areDuplicateExtensionsPresent properly

   // Known X.509/PKIX certificate extensions

   unsigned long AuthorityKeyIdentifier_val[4]     = {2,5,29,35};
   unsigned long SubjectKeyIdentifier_val[4]       = {2,5,29,14};
   unsigned long KeyUsage_val[4]                   = {2,5,29,15};
   unsigned long PrivateKeyUsagePeriod_val[4]      = {2,5,29,16};
   unsigned long CertificatePolicies_val[4]        = {2,5,29,32};
   unsigned long PolicyMappings_val[4]             = {2,5,29,33};
   unsigned long SubjectAlternativeName_val[4]     = {2,5,29,17};
   unsigned long IssuerAlternativeName_val[4]      = {2,5,29,18};
   unsigned long BasicConstraints_val[4]           = {2,5,29,19};
   unsigned long NameConstraints_val[4]            = {2,5,29,30};
   unsigned long PolicyConstraints_val[4]          = {2,5,29,36};
   unsigned long CRLDistributionPoints_val[4]      = {2,5,29,31};

// These extensions are not in x509.h yet and are not supported for August?      
// unsigned long ExtendedKeyUsage_val[4]           = {2,5,29,37};
// unsigned long SubjectDirectoryAttributes_val[4] = {2,5,29, 9};
// unsigned long AuthorityInfoAccess_val[9]        = {1,3,6,1,5,5,7,1,1};

   // variables to hold encoding extracted from x509_extension
   unsigned char* p;
   uint32         bc;
   r_buffer_t     encoding;

   int children = tbsCertificate.extensions.value.get_child_count();
   for (int i = 0; i < children ; i++)
   {
      x509_Extension* child = tbsCertificate.extensions.value[i];

      //------------------------------------------------------------
      // AuthorityKeyIdentifier
      //------------------------------------------------------------
      if (child->extnID.is_equal(AuthorityKeyIdentifier_val, 4))
      {
         _isAuthorityKeyIdentifierPresent = true;
         child->critical.get_value(_isAuthorityKeyIdentifierCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XAuthorityKeyIdentifier.read(encoding)) != 0)
            return status;
      }
      //------------------------------------------------------------
      // SubjectKeyIdentifier
      //------------------------------------------------------------
      else if (child->extnID.is_equal(SubjectKeyIdentifier_val, 4))
      {
         _isSubjectKeyIdentifierPresent = true;
         child->critical.get_value(_isSubjectKeyIdentifierCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XSubjectKeyIdentifier.read(encoding)) != 0)
            return status;
      }
      //------------------------------------------------------------
      // KeyUsage
      //------------------------------------------------------------
      else if (child->extnID.is_equal(KeyUsage_val, 4))
      {
         _isKeyUsagePresent = true;
         child->critical.get_value(_isKeyUsageCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XKeyUsage.read(encoding)) != 0)
            return status;
      }
      //------------------------------------------------------------
      // PrivateKeyUsagePeriod
      //------------------------------------------------------------
      else if (child->extnID.is_equal(PrivateKeyUsagePeriod_val, 4))
      {
         _isPrivateKeyUsagePeriodPresent = true;
         child->critical.get_value(_isPrivateKeyUsagePeriodCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XPrivateKeyUsagePeriod.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // CertificatePolicies
      //------------------------------------------------------------
      else if (child->extnID.is_equal(CertificatePolicies_val, 4))
      {
         _isCertificatePoliciesPresent = true;
         child->critical.get_value(_isCertificatePoliciesCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XCertificatePolicies.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // PolicyMappings
      //------------------------------------------------------------
      else if (child->extnID.is_equal(PolicyMappings_val, 4))
      {
         _isPolicyMappingsPresent = true;
         child->critical.get_value(_isPolicyMappingsCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XPolicyMappings.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // SubjectAlternativeName
      //------------------------------------------------------------
      else if (child->extnID.is_equal(SubjectAlternativeName_val, 4))
      {
         _isSubjectAlternativeNamePresent = true;
         child->critical.get_value(_isSubjectAlternativeNameCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XsubjectAltName.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // IssuerAlternativeName
      //------------------------------------------------------------
      else if (child->extnID.is_equal(IssuerAlternativeName_val, 4))
      {
         _isIssuerAlternativeNamePresent = true;
         child->critical.get_value(_isIssuerAlternativeNameCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XIssuerAltName.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // BasicConstraints
      //------------------------------------------------------------
      else if (child->extnID.is_equal(BasicConstraints_val, 4))
      {
         _isBasicConstraintsPresent = true;
         child->critical.get_value(_isBasicConstraintsCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XBasicConstraints.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // NameConstraints
      //------------------------------------------------------------
      else if (child->extnID.is_equal(NameConstraints_val, 4))
      {
         _isNameConstraintsPresent = true;
         child->critical.get_value(_isNameConstraintsCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _XNameConstraints.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // PolicyConstraints
      //------------------------------------------------------------
      else if (child->extnID.is_equal(PolicyConstraints_val, 4))
      {
         _isPolicyConstraintsPresent = true;
         child->critical.get_value(_isPolicyConstraintsCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _PolicyConstraint.read(encoding)) != 0)
            return status;
      }  
      //------------------------------------------------------------
      // CRLDistributionPoints
      //------------------------------------------------------------
      else if (child->extnID.is_equal(CRLDistributionPoints_val, 4))
      {
         _isCRLDistributionPointsPresent = true;
         child->critical.get_value(_isCRLDistributionPointsCritical);
         if ((status = child->extnValue.get_value(p, bc)) != 0)
            return status;
         encoding.data = p; encoding.data_len = bc;
         if ((status = _CRLDistributionPoints.read(encoding)) != 0)
            return status;
      }
   }
   return status;
}


// email accessor

GeneralName& 
pkix_certificate::emailAddress()
{
   if (!_init) init();
   return _emailAddress;
}


// extension accessors

XAuthorityKeyIdentifier& 
pkix_certificate::authorityKeyIdentifier()     
{
   if (!_init) init();
   return _XAuthorityKeyIdentifier;
}

XSubjectKeyIdentifier&
pkix_certificate::subjectKeyIdentifier()     
{
   if (!_init) init();
   return _XSubjectKeyIdentifier;
}

XKeyUsage&
pkix_certificate::keyUsage()     
{
   if (!_init) init();
   return _XKeyUsage;
}

XPrivateKeyUsagePeriod&
pkix_certificate::privateKeyUsagePeriod()     
{
   if (!_init) init();
   return _XPrivateKeyUsagePeriod;
}

XCertificatePolicies&
pkix_certificate::certificatePolicies()     
{
   if (!_init) init();
   return _XCertificatePolicies;
}

XPolicyMappings&
pkix_certificate::policyMappings()     
{
   if (!_init) init();
   return _XPolicyMappings;
}

XsubjectAltName&
pkix_certificate::subjectAltName()     
{
   if (!_init) init();
   return _XsubjectAltName;
}

XIssuerAltName&
pkix_certificate::issuerAltName()     
{
   if (!_init) init();
   return _XIssuerAltName;
}

XBasicConstraints&
pkix_certificate::basicConstraints()     
{
   if (!_init) init();
   return _XBasicConstraints;
}

XNameConstraints&
pkix_certificate::nameConstraints()     
{
   if (!_init) init();
   return _XNameConstraints;
}

PolicyConstraint&
pkix_certificate::policyConstraints()     
{
   if (!_init) init();
   return _PolicyConstraint;
}

CRLDistributionPoints&
pkix_certificate::cRLDistributionPoints()     
{
   if (!_init) init();
   return _CRLDistributionPoints;
}

int 
pkix_certificate::populate_emailAddress()
{
   int status = 0;

   unsigned long EmailAddress_val[] = {1,2,840,113549,1,9,1};

   // look for email attribute in certificate subject name; 
   // it must be a IA5String, no cheating

   for (int i = 0; i < tbsCertificate.subject.get_child_count(); i++)
   {
      asn_RDN* rdnPtr = tbsCertificate.subject.get_child(i);
      for (int j = 0; j < rdnPtr->get_child_count(); j++)
      {
         asn_AVA* atvPtr = rdnPtr->get_child(j);
         if ( atvPtr->attr.is_equal(EmailAddress_val,7) && 
              atvPtr->value.get_codeset() == IA5_STRING_TAG)
         {
            buffer_t copyBuffer;
            if ((status = atvPtr->value.write(copyBuffer)) != 0)
               return status;
            asn_x500name nameCopy;
            if ((status = nameCopy.read(copyBuffer)) != 0)
               return status;
            nameCopy.set_tag(1); 
            nameCopy.set_class(CLASS_CONTEXT_SPECIFIC);
            copyBuffer.clear();
            if ((status = nameCopy.write(copyBuffer)) != 0)
               return status;
            if ((status = _emailAddress.read(copyBuffer)) != 0)
               return status;
            _isEmailAddressPresent = true;
         }
      }
   }

   return status;
}


// TO DO: write same code for pkx_crl
// Known X.509/PKIX CRL extensions
//   unsigned long CRLNumber_val[4]                  = {2,5,29,20};
//   unsigned long ReasonCode_val[4]                 = {2,5,29,21};
//   unsigned long InstructionCode_val[4]            = {2,5,29,23};
//   unsigned long InvalidityDate_val[4]             = {2,5,29,24};
//   unsigned long DeltaCRLIndicator_val[4]          = {2,5,29,27};
//   unsigned long IssuingDistributionPoint_val[4]   = {2,5,29,28};
//   unsigned long CertificateIssuer_val[4]          = {2,5,29,29};




