/* ***************************************************************** *
 * 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.                                                        *
 * ***************************************************************** */

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <pkcs.h>
#include <crypto.h>
#include <crmsg.h>

#ifndef max
#define max(a,b)        ((a) < (b) ? (b) : (a))
#endif

#ifndef compare_oid
#define compare_oid(b, s)       memcmp(b.data, s, max(b.data_len, strlen(s)))
#endif

#define ASEncryptedCI(i)        as[i]->content.value.encryptedData.encryptedContentInfo

uint32
PFX::read(unsigned char *password, r_buffer_t &buf)
{
  buffer_t              contentType;
  buffer_t              p12Alg;
  buffer_t              bagType;
  buffer_t              pbeData;
  buffer_t              bagData;
  buffer_t              certType;
  buffer_t              kd;
  buffer_t              safe(ASN_SECRET);
  buffer_t              salt;
  buffer_t              certBuf;
  buffer_t              asBuf;
  buffer_t              encData;
  uint32                status = 0;
  uint32                asCount = 0;
  uint32                scCount = 0;
  uint32                scnt = 0;
  uint32                cnt = 0;
  uint32                tpLen;
  unsigned char         *tp = NULL;
  long                  version = 0;
  long                  icnt = 0;
  AuthenticatedSafes    as;
  PrivateKeyInfo        *key = NULL;
  KeyBag                kb;
  x509_certificate      *certPtr = NULL;
  CertBag               cb;
  pkcs_12PbeParams      pbe;
  
  if ((status = asn_sequence::read(buf)) != 0) {
    return status;
  }
  if (( status = this->version.get_value(version)) != 0) {
    return status;
  }
  // We only support V3 PKCS #12 files
  if (version != PKCS12_V3) {
    return CR_PKCS12_VERSION_UNSUP;
  }
  if ((status = this->authSafes.content.value.data.write(asBuf))) {
    return status;
  }
  if ((status = as.read(asBuf)) != 0) {
    return status;
  }
  asCount = as.get_child_count();
  if (asCount > 1) {
    return CR_PKCS12_MULTIPLE_AUTHSAFES_UNSUP;
  }
  for(cnt = 0; cnt < asCount ; cnt++) {
      contentType.clear();
      safe.clear();
      as[cnt]->contentType.display(contentType);
      if (compare_oid(contentType, PKCS7_ENCRYPTED_DATA_ID) == 0) {
        contentType.clear();
        ASEncryptedCI(cnt).contentType.display(contentType);
        p12Alg.clear();
        ASEncryptedCI(cnt).contentEncryptionAlgorithm.algorithm.
          display(p12Alg);
        pbeData.clear();
        ASEncryptedCI(cnt).contentEncryptionAlgorithm.parameters.
          write(pbeData);
        ASEncryptedCI(cnt).encryptedContent.get_value(tp, tpLen);
        encData.clear();
        encData.append(tp, tpLen);
        if ((status = pbe.read(pbeData))) {
          return status;
        }
        pbe.iterationCount.get_value(icnt);
        pbe.salt.get_value(tp, tpLen);
        salt.clear();
        salt.append(tp, tpLen);
        if ((status = CR_PKCS12_DecryptContent(p12Alg, salt, icnt, password, 
                                              encData, safe))) { 
          return status;
        }
      } else if (compare_oid(contentType, PKCS7_DATA_ID) == 0) {
        as[cnt]->content.value.data.get_value(tp, tpLen);
        safe.append(tp, tpLen);
      } else { // XXX 
        return CR_PKCS12_CONTENT_TYPE_UNSUP;
      }
      this->sc.empty();
      if ((status = this->sc.read(safe)) != 0) {
        return status;
      }
      scCount = this->sc.get_child_count();
      for(scnt = 0; scnt < scCount; scnt++) {
        bagType.clear();
        this->sc[scnt]->bagType.display(bagType);
        if (compare_oid(bagType, PKCS12_CERTBAG) == 0) {
          bagData.clear();
          if ((status = this->sc[scnt]->bagContent.value.write(bagData))) {
            return status;
          }
          if ((status = cb.read(bagData))) {
            return status;
          }
          certType.clear();
          cb.certType.display(certType);
          if (compare_oid(certType, PKCS9_CERTTYPE_X509) != 0) {
            return CR_PKCS12_CERTTYPE_UNSUP;
          }
          if ((status = cb.cert.value.write(certBuf))) {
            return status;
          }
          certPtr = certList.add_child();
          if ((status = certPtr->read(certBuf))) {
            return status;
          }
        } else if (compare_oid(bagType, PKCS12_SHROUDED_KEYBAG) == 0) {
          continue;
        } else if (compare_oid(bagType, PKCS12_KEYBAG) == 0) {
          bagData.clear();
          sc[0]->bagContent.value.write(bagData);
          if ((status = kb.read(bagData))) {
            return status;
          }
          kd.clear();
          kb.write(kd);
          key = keyList.add_child();
          key->read(kd);
        } else if (compare_oid(bagType, PKCS12_CRLBAG) == 0) {
          continue;
        } else if (compare_oid(bagType, PKCS12_SECRETBAG) == 0) {
          continue;
        } else if (compare_oid(bagType, PKCS12_SAFECONTENTSBAG) == 0) {
          continue;
        } else {
          return CR_PKCS12_BAG_TYPE_UNKNOWN;
        }
      }
  }
  return 0;
}

uint32
PFX::write(unsigned char *password, buffer_t &buf)
{
  uint32        status;
  buffer_t      scBuf;
  buffer_t      salt;
  buffer_t      macKey;
  buffer_t      macOut;

  do {
    if ((status = sc.write(scBuf))) {
      break;
    }
    if (!this->version.is_present()) {
      if ((status = this->version.set_value(PKCS12_V3))) {
        break;
      }
    }
    if ((status = this->authSafes.contentType.set_value("pkcs7-data"))) {
      break;
    }
    this->authSafes.content.value.select(0);
    if ((status = this->authSafes.content.value.data.
         set_value(scBuf.data, scBuf.data_len))) {
      break;
    }
#if 0
    if ((status = CR_PKCS12_generate_salt(salt))) {
      break;
    }
    if ((status = CR_PKCS12_makekey(password, salt, MAC, 1, 160, macKey))) {
      break;
    }
    if ((status = this->macData.macSalt.set_value(salt.data, salt.data_len))) {
      break;
    }
    if ((status = CR_HMACWithSHA1(asBuf, macKey, macOut))) {
      break;
    }
    if ((status = this->macData.mac.digest.set_value(macOut.data, 
                                                     macOut.data_len))) {
      break;
    }
    if ((status = this->macData.mac.digestAlgorithm.algorithm.
         set_value("hmac-sha1"))) {
      break;
    }
#endif
    if ((status = asn_sequence::write(buf)) != 0) {
      return status;
    }
  } while(0);
  return status;
}

uint32
PFX::add_cert(const x509_certificate *cert) 
{
  uint32        status;
  SafeBag       *newBag = NULL;
  CertBag       certBag;
  buffer_t      certBuf;
  buffer_t      bagBuf;
  x509_certificate      *newCert = NULL;
  
  do {
    if ((newBag = sc.add_child()) == NULL) {
      throw "Out of memory adding cert bag";
    }
    if ((status = newBag->bagType.set_value("pkcs12-certbag"))) {
      break;
    }
    if ((status = certBag.certType.set_value("X509-Certificate"))) {
      break;
    }
    if ((status = cert->write(certBuf))) {
      break;
    }
    if ((status = certBag.cert.value.set_value(certBuf.data, 
                                               certBuf.data_len))) {
      break;
    }
    if ((status = certBag.write(bagBuf))) {
      break;
    }
    if ((status = newBag->bagContent.value.read(bagBuf))) {
      break;
    }
    if ((newCert = this->certList.add_child()) == NULL) {
      throw "Out of memory in PKCS #12 add_cert";
    }
    certBuf.clear();
    if ((status = cert->write(certBuf))) {
      break;
    }
    if ((status = newCert->read(certBuf))) {
      break;
    }
  } while(0);
  return status;
}

uint32
PFX::add_key(const PrivateKeyInfo *key) 
{
  uint32                status;
  SafeBag               *newBag = NULL;
  PrivateKeyInfo        *newKey = NULL;
  KeyBag                keyBag(ASN_SECRET);
  buffer_t              keyBuf(ASN_SECRET);
  buffer_t              bagBuf(ASN_SECRET);
  asn_octetstring       keyString(ASN_SECRET);
  
  do {
    if ((newBag = sc.add_child()) == NULL) {
      throw "Out of memory adding key bag";
    }
    if ((status = newBag->bagType.set_value("pkcs12-keybag"))) {
      break;
    }
    if ((status = key->write(keyBuf))) {
      break;
    }
    if ((status = keyBag.read(keyBuf))) {
      break;
    }
    if ((status = keyBag.write(bagBuf))) {
      break;
    }
    if ((status = newBag->bagContent.value.read(bagBuf))) {
      break;
    }
    if ((newKey = this->keyList.add_child()) == NULL) {
      throw "Out of memory in PKCS #12 add_key";
    }
    keyBuf.clear();
    if ((status = key->write(keyBuf))) {
      break;
    }
    if ((status = newKey->read(keyBuf))) {
      break;
    }
  } while(0);
  return status;
}

uint32
PFX::get_certs(CertList &cl)
{
  uint32        status;
  buffer_t      certBuf;

  do {
    if ((status = certList.write(certBuf))) {
      break;
    }
    if ((status = cl.read(certBuf))) {
      break;
    }
  } while(0);
  return status;
}

uint32
PFX::get_keys(KeyList &kl)
{
  uint32        status;
  buffer_t      keyBuf(ASN_SECRET);

  do {
    if ((status = keyList.write(keyBuf))) {
      break;
    }
    if ((status = kl.read(keyBuf))) {
      break;
    }
  } while(0);
  return status;
}

uint32
PFX::write_file(const utf8String filename, const utf8String password)
{
  FILE          *fp;
  buffer_t      outBuf;
  uint32        status;

  if ((status = this->write(password, outBuf))) {
    return status;
  }
  if ((fp = fopen((char *) filename, "wb")) == NULL) {
    return CR_PKCS12_FILE_OPEN_WRITE_FAILED;
  }
  if ((fwrite(outBuf.data, outBuf.data_len, 1, fp)) != 1) {
    return CR_PKCS12_FILE_WRITE_FAILED;
  }
  fclose(fp);
  return 0;
}

uint32
PFX::read_file(const utf8String filename, const utf8String password)
{
  unsigned char         *tp = NULL;
  uint32                size;
  FILE                  *fp;
  r_buffer_t            inBuf;

  if ((fp = fopen((char *) filename, "rb")) == NULL) {
    return CR_PKCS12_FILE_OPEN_READ_FAILED;;
  }
  fseek(fp, 0L, SEEK_END);
  size = ftell(fp);
  rewind(fp);
  if ((tp = (unsigned char *) malloc(size)) == NULL) {
    throw "out of memory in PKCS #12 file read";
  }
  memset(tp, 0, size);
  if (fread(tp, size, 1, fp) != 1) {
    return CR_PKCS12_FILE_READ_FAILED;
  }
  fclose(fp);
  inBuf.data = tp;
  inBuf.data_len = size;
  return  this->read(password, inBuf);
}
