/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "es_int.h"
#include "rsautil.h"
#include "esl.h"
#include "es_utils.h"
#include "nvdata.h"

/* 
 * Returns the cert data structure size. 
 *
 * Input:
 * sigType - signature type 
 * keyType - public key type 
 *
 * Output:
 * size of certificate data structure
 *
 */
int
ES_GetCertSize(IOSCCertSigType sigType, IOSCCertPubKeyType keyType)
{
    switch (sigType) {
        case IOSC_SIG_RSA4096:
            switch (keyType) {
                case IOSC_PUBKEY_RSA4096: 
                    return sizeof(IOSCRootCert);
                case IOSC_PUBKEY_RSA2048:
                    return sizeof(IOSCRsa4096RsaCert);
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        case IOSC_SIG_RSA2048:
            switch (keyType) {
                case IOSC_PUBKEY_ECC: 
                    return sizeof(IOSCRsa2048EccCert);
                case IOSC_PUBKEY_RSA2048:
                    return sizeof(IOSCRsa2048RsaCert);
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        case IOSC_SIG_ECC:
            switch (keyType) {
                case IOSC_PUBKEY_ECC: 
                    return sizeof(IOSCEccEccCert);
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        default:
            return ES_ERR_INCORRECT_SIG_TYPE;
    }
}

/* 
 * Returns the cert issuer's name and the cert's name. 
 *
 * Input:
 * cert - certificate data
 *
 * Output:
 * issuerName - cert issuer name string (64bytes, caller allocates)
 * certName - cert name string (64bytes, caller allocates)
 *
 */
int
ES_GetCertNames(const void* cert, char* issuerName, char* certName)
{
    IOSCCertSigType sigType;
    IOSCCertPubKeyType keyType;
    char* pIssuer;
    char* pCert;

    sigType = ntohl(((IOSCSigRsa4096*)cert)->sigType);

    switch (sigType) {
        case IOSC_SIG_RSA4096:
            pIssuer = ((IOSCSigRsa4096*)cert)->issuer;
            pCert = ((IOSCRsa4096RsaCert*)cert)->head.name.serverId;
            break;
        case IOSC_SIG_RSA2048:
            pIssuer = ((IOSCSigRsa2048*)cert)->issuer;
            keyType = ntohl(((IOSCRsa2048RsaCert*)cert)->head.pubKeyType);
            switch (keyType) {
                case IOSC_PUBKEY_RSA2048:
                    pCert =  ((IOSCRsa2048RsaCert*)cert)->head.name.serverId;
                    break;
                case IOSC_PUBKEY_ECC: 
                    pCert =  ((IOSCRsa2048EccCert*)cert)->head.name.deviceId;
                    break;
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        case IOSC_SIG_ECC:
            pIssuer = ((IOSCSigEcc*)cert)->issuer;
            pCert = ((IOSCEccEccCert*)cert)->head.name.deviceId;
            break;
        default:
            return ES_ERR_INCORRECT_SIG_TYPE;
    }

    strncpy(issuerName, pIssuer, ES_NAME_SIZE);
    strncpy(certName, pCert, ES_NAME_SIZE);

    return ES_ERR_OK;
}


u8*
ES_GetCertPubKey(const void* cert, u32* keySize)
{
    IOSCCertSigType sigType;
    IOSCCertPubKeyType keyType;

    sigType = ntohl(((IOSCSigRsa4096*)cert)->sigType);

    switch (sigType) {
        case IOSC_SIG_RSA4096:
	    *keySize = sizeof(IOSCRsaPublicKey4096);
            return ((IOSCRootCert*)cert)->pubKey;
        case IOSC_SIG_RSA2048:
            keyType = ntohl(((IOSCRsa2048RsaCert*)cert)->head.pubKeyType);
            switch (keyType) {
                case IOSC_PUBKEY_RSA2048:
		    *keySize = sizeof(IOSCRsaPublicKey2048);
		    return ((IOSCRsa2048RsaCert*)cert)->pubKey;
                case IOSC_PUBKEY_ECC:
		    *keySize = sizeof(IOSCEccPublicKey);
		    return ((IOSCRsa2048EccCert*)cert)->pubKey;
                default:
                    return NULL;
            }
        case IOSC_SIG_ECC:
	    *keySize = sizeof(IOSCEccPublicKey);
	    return ((IOSCEccEccCert*)cert)->pubKey;
        default:
            return NULL;
    }
}

/* 
 * Generate unsigned certificates: IOSCRootCert, IOSCRsa4096RsaCert, 
 * IOSCRsa2048RsaCert, IOSCRsa2048EccCert, or IOSCEccEccCert.
 *
 * Input:
 * certName   - certificate name
 * issuerName - certificate issuer name
 * sigType    - signature type, should be: 
 *              IOSC_SIG_RSA4096: 4096bits RSA signature
 *              IOSC_SIG_RSA2048: 2048bits RSA signature
 *              IOSC_SIG_ECC:     512bits padded ECC signature
 * pubKeyType - public key type, should be:
 *              IOSC_PUBKEY_RSA4096: "pubKey" should be 4096bits 
 *              IOSC_PUBKEY_RSA2048: "pubKey" should be 2048bits 
 *              IOSC_PUBKEY_ECC: "pubKey" should be 512bits
 * pubKey     - public key
 * exponent   - public key exponent (only for RSA key types)
 * exponentSizeInBytes - exponent size (only for RSA key types) 
 * date       - certificate expiration date
 *
 * Output:
 * cert       - output unsigned certificate 
 *              (caller allocates - use ES_GetCertSize to determine size) 
 */
int
ES_GenerateUnsignedCert(const char* certName, const char* issuerName, IOSCCertSigType sigType, IOSCCertPubKeyType keyType, const u8* pubKey, const u8* exp, int expSizeInBytes, u32 date, void* cert)
{
    IOSCRootCert* p1;
    IOSCRsa4096RsaCert* p2;
    IOSCRsa2048RsaCert* p3;
    IOSCRsa2048EccCert* p4;
    IOSCEccEccCert* p5;
    IOSCRsaExponent exponent;
    int i, shift;

    if (strlen(certName)>=sizeof(IOSCName) || strlen(issuerName)>=sizeof(IOSCName)) 
        return ES_ERR_INVALID;

    /* Adjust exponent to insert leading zeroes */
    shift = sizeof(IOSCRsaExponent) - expSizeInBytes;
    for (i=sizeof(IOSCRsaExponent)-1; i>=0; i--) {
        if ((i-shift) >= 0) {
            exponent[i] = exp[i-shift];
        } else {
            exponent[i] = 0;
        }
    }

    switch (sigType) {
        case IOSC_SIG_RSA4096:
            switch (keyType) {
                case IOSC_PUBKEY_RSA4096: 
                    p1 = (IOSCRootCert*)cert;
                    memset(p1, 0, sizeof(IOSCRootCert));
                    p1->sig.sigType = htonl(sigType);
                    strcpy(p1->sig.issuer, issuerName);
                    p1->head.pubKeyType = htonl(keyType);
                    strcpy(p1->head.name.serverId, certName);
                    p1->head.date = htonl(date);
                    memcpy(p1->pubKey, pubKey, sizeof(IOSCRsaPublicKey4096));
                    memcpy(p1->exponent, exponent, sizeof(IOSCRsaExponent));
                    break;
                case IOSC_PUBKEY_RSA2048:
                    p2 = (IOSCRsa4096RsaCert*)cert;
                    memset(p2, 0, sizeof(IOSCRsa4096RsaCert));
                    p2->sig.sigType = htonl(sigType);
                    strcpy(p2->sig.issuer, issuerName);
                    p2->head.pubKeyType = htonl(keyType);
                    strcpy(p2->head.name.serverId, certName);
                    p2->head.date = htonl(date);
                    memcpy(p2->pubKey, pubKey, sizeof(IOSCRsaPublicKey2048));
                    memcpy(p2->exponent, exponent, sizeof(IOSCRsaExponent));
                    break;
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        case IOSC_SIG_RSA2048:
            switch (keyType) {
                case IOSC_PUBKEY_ECC: 
                    p4 = (IOSCRsa2048EccCert*)cert;
                    memset(p4, 0, sizeof(IOSCRsa2048EccCert));
                    p4->sig.sigType = htonl(sigType);
                    strcpy(p4->sig.issuer, issuerName);
                    p4->head.pubKeyType = htonl(keyType);
                    strcpy(p4->head.name.deviceId, certName);
                    p4->head.date = htonl(date);
                    memcpy(p4->pubKey, pubKey, sizeof(IOSCEccPublicKey));
                    break;
                case IOSC_PUBKEY_RSA2048:
                    p3 = (IOSCRsa2048RsaCert*)cert;
                    memset(p3, 0, sizeof(IOSCRsa2048RsaCert));
                    p3->sig.sigType = htonl(sigType);
                    strcpy(p3->sig.issuer, issuerName);
                    p3->head.pubKeyType = htonl(keyType);
                    strcpy(p3->head.name.serverId, certName);
                    p3->head.date = htonl(date);
                    memcpy(p3->pubKey, pubKey, sizeof(IOSCRsaPublicKey2048));
                    memcpy(p3->exponent, exponent, sizeof(IOSCRsaExponent));
                    break;
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        case IOSC_SIG_ECC:
            switch (keyType) {
                case IOSC_PUBKEY_ECC: 
                    p5 = (IOSCEccEccCert*)cert;
                    memset(p5, 0, sizeof(IOSCEccEccCert));
                    p5->sig.sigType = htonl(sigType);
                    strcpy(p5->sig.issuer, issuerName);
                    p5->head.pubKeyType = htonl(keyType);
                    strcpy(p5->head.name.deviceId, certName);
                    p5->head.date = htonl(date);
                    memcpy(p5->pubKey, pubKey, sizeof(IOSCEccPublicKey));
                    break;
                default:
                    return ES_ERR_INCORRECT_PUBKEY_TYPE;
            }
            break;
        default:
            return ES_ERR_INCORRECT_SIG_TYPE;
    }

    return ES_ERR_OK;
}

int 
ES_GenerateDeviceCert(const char* certName, const char* issuerName, const IOSCEccPublicKey* pubKey, 
                      const u32 date, IOSCEccEccCert* cert)
{

    return ES_GenerateUnsignedCert(certName, issuerName, IOSC_SIG_ECC, IOSC_PUBKEY_ECC, 
                                   (u8 *) pubKey, 0, 0, date, (void *) cert);

}

int 
ES_VerifyDeviceCert(IOSCEccEccCert *cert, IOSCEccPublicKey *pubKey)
{
    IOSCSha1Hash hash;
    SHA1Context sha;
    int headerSize = sizeof(IOSCCertSigType) + sizeof(IOSCEccSig) + 
        sizeof(IOSCEccPublicPad) + sizeof(IOSCSigDummy);
    u8 *data = (u8 *) cert;
    IOSCSigEcc mfrSigHead = cert->sig;

    SHA1Reset(&sha);
    SHA1Input(&sha, data+headerSize , sizeof(IOSCEccEccCert)-headerSize);
    SHA1Result(&sha, hash);

    if (CSL_VerifyEccSig(hash, *pubKey, mfrSigHead.sig) != CSL_OK) {
        return ES_ERR_VERIFY_SIG_FAILED;
    } else {
        return ES_ERR_OK;
    }
}


int
ES_VerifyEccSig(IOSCEccPublicKey pubKey, void* document, int documentSize,
		IOSCEccSig sig)
{
    IOSCSha1Hash hash;
    SHA1Context sha;

    SHA1Reset(&sha);
    SHA1Input(&sha, document, documentSize);
    SHA1Result(&sha, hash);

    if (CSL_VerifyEccSig(hash, pubKey, sig) != CSL_OK) {
        return ES_ERR_VERIFY_SIG_FAILED;
    } else {
        return ES_ERR_OK;
    }

}



int 
ES_GenerateRvlDeviceData(const u8* pvtData, const u32 pvtDataSize, const u8 *randN, 
                         const u32 randSize, const IOSCEccPrivateKey* pvtKey, 
                         const IOSCEccEccCert* cert, const IOSCServerId caName, 
                         u8* deviceData, const u32 deviceDataSize)
{
    u32 id;
    const char *name = cert->head.name.deviceId;
    const char *issuer = cert->sig.issuer;

    /* 
     * Check input parameters
     */
    if (pvtDataSize != ES_RVL_PVT_DATA_SIZE) {
        return ES_ERR_PVT_DATA_SIZE;
    }
    if (randSize < ES_RVL_RAND_SIZE) {
        return ES_ERR_RAND_DATA_SIZE;
    }
    if (deviceDataSize < ES_RVL_DEVICE_DATA_SIZE) {
        return ES_ERR_DEVICE_DATA_SIZE;
    }

    memset(deviceData, 0, deviceDataSize);
    memcpy(deviceData, pvtData, NV_RVL_BOOT1_HASH_SIZE+NV_RVL_COMMON_AES_KEY_SIZE);

    /*
     * Format of name is [NC,RV]
     */
    id = htonl(strtol(name + strnlen(name, sizeof(IOSCDeviceId)) - 8, NULL, 16));
    memcpy(deviceData + NV_RVL_DEVICE_ID_OFF, &id, sizeof(u32));

    /* Device private key */
    memcpy(deviceData + NV_RVL_DEVICE_ECDH_KEY_OFF, pvtKey, NV_RVL_DEVICE_ECDH_KEY_SIZE);

    /* All other device specific keys, from randoms */
    memcpy(deviceData + NV_RVL_SFS_HMAC_KEY_OFF, randN, NV_RVL_JTAG_ENABLE_OFF-
           NV_RVL_SFS_HMAC_KEY_OFF);
    /*
     * JTAG test enables
     */
    memcpy(deviceData + NV_RVL_JTAG_ENABLE_OFF, pvtData + ES_RVL_PVT_DATA_SIZE - 4, 
        NV_RVL_JTAG_ENABLE_SIZE);

    id = htonl(strtol(issuer + strnlen(issuer, sizeof(IOSCServerId)) - 8, NULL, 16));
    memcpy(deviceData + NV_RVL_MFR_ID_OFF, &id, sizeof(u32));

    id = htonl(strtol(caName + strnlen(caName, sizeof(IOSCServerId)) - 8, NULL, 16));
    memcpy(deviceData + NV_RVL_CA_ID_OFF, &id, sizeof(u32));

    memcpy(deviceData + NV_RVL_MFR_DATE_OFF, &cert->head.date, sizeof(u32));

    memcpy(deviceData + NV_RVL_MFR_SIGN_OFF, cert->sig.sig, NV_RVL_MFR_SIGN_SIZE);

    return ES_ERR_OK;
}

int 
ES_GenerateNCDeviceData(const u8* pvtData, const u32 pvtDataSize, const u8 *randN, const u32 randSize, 
                        const IOSCEccPrivateKey* pvtKey, const IOSCEccEccCert* cert, 
                        const IOSCServerId caName, u8* deviceData, const u32 deviceDataSize)
{
    u32 id;
    u32 date;
    int i, j;
    const char *name = cert->head.name.deviceId;
    const char *issuer = cert->sig.issuer;

    /* 
     * Check input parameters
     */
    if (pvtDataSize != ES_NC_PVT_DATA_SIZE) {
        return ES_ERR_PVT_DATA_SIZE;
    }
    if (randSize < ES_NC_RAND_SIZE) {
        return ES_ERR_RAND_DATA_SIZE;
    }
    if (deviceDataSize < ES_NC_DEVICE_DATA_SIZE) {
        return ES_ERR_DEVICE_DATA_SIZE;
    }

    memset(deviceData, 0, deviceDataSize);

    memcpy(deviceData, pvtData, NV_NC_BOOT1_HASH_SIZE);
    for (i=0; i<NV_NC_BOOT1_HASH_SIZE; i++) {
        if (pvtData[i] != 0) {
    	    for (j=0; j<NV_NC_BOOT1_HASH_SIZE; j++) {
        	deviceData[NV_NC_BOOT1_HASHC_OFF+i] = ~pvtData[j];
    	    }
            break;
	}
    }
    memcpy(deviceData+NV_NC_COMMON_AES_KEY_OFF, pvtData+NV_NC_BOOT1_HASH_SIZE, 
           NV_NC_COMMON_AES_KEY_SIZE);
    for (i=0; i<NV_NC_COMMON_AES_KEY_SIZE; i++) {
        deviceData[NV_NC_COMMON_AES_KEYC_OFF+i] = ~pvtData[NV_NC_BOOT1_HASH_SIZE+i];
    }

    /*
     * Format of name is [NC,RV]
     */
    id = strtol(name + strnlen(name, sizeof(IOSCDeviceId)) - 8, NULL, 16);
    memcpy(deviceData + NV_NC_DEVICE_ID_OFF, &id, sizeof(u32));
    id = ~id;
    memcpy(deviceData + NV_NC_DEVICE_IDC_OFF, &id, sizeof(u32));

    /* Device private key */
    memcpy(deviceData + NV_NC_DEVICE_ECDH_KEY_OFF, pvtKey, NV_NC_DEVICE_ECDH_KEY_SIZE);

    /* All other device specific keys, from randoms */
    memcpy(deviceData + NV_NC_SFS_HMAC_KEY_OFF, randN, NV_NC_MFR_ID_OFF-
           NV_NC_SFS_HMAC_KEY_OFF);

    id = strtol(issuer + strnlen(issuer, sizeof(IOSCServerId)) - 8, NULL, 16);
    memcpy(deviceData + NV_NC_MFR_ID_OFF, &id, sizeof(u32));

    id = strtol(caName + strnlen(caName, sizeof(IOSCServerId)) - 8, NULL, 16);
    memcpy(deviceData + NV_NC_CA_ID_OFF, &id, sizeof(u32));

    /* Date from cert is in big endian format */
    date = htonl(cert->head.date);
    memcpy(deviceData + NV_NC_MFR_DATE_OFF, &date, sizeof(u32));

    memcpy(deviceData + NV_NC_MFR_SIGN_OFF, cert->sig.sig, NV_NC_MFR_SIGN_SIZE);

    /* Fill the rest with randoms */
    memcpy(deviceData + NV_NC_RAND_OFF, randN+ES_NC_RAND_SIZE-NV_NC_RAND_SIZE, NV_NC_RAND_SIZE);

    return ES_ERR_OK;
}
