/*
 *               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 <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include <netinet/in.h>

#include "esl.h"
#include "es_int.h"
#include "utils.h"
#include "rsautil.h"

#if !defined(__CYGWIN__)
static struct option __longOptions[] = {
    {"IN", 1, 0, 'I'},         /* input cert file to be verified */
    {"OUT", 1, 0, 'O'},        /* output cert and RSA file */
    {"type", 1, 0, 't'},       /* type of cert to be created */
    {"name", 1, 0, 'n'},       /* id/name of the cert */
    {"issuerCert", 1, 0, 'c'}, /* issuer cert file */
    {"issuerRsa", 1, 0, 'r'},  /* issuer rsa data file */
    {"inputRsa", 1, 0, 'i'},   /* input rsa data file */
    {"exponent", 1, 0, 'e'},   /* RSA exponent */
    {"devPvt", 1, 0, 'd'},     /* device's ECC private key file */
    {"print", 0, 0, 'p'},      /* verify cert and dump fields of cert file */
    {"size", 0, 0, 's'},       /* print out sizes of various certs */
    {"help", 0, 0, 'h'},       /* print usage */
    {0, 0, 0, 0}
};
#endif

static char* __options = "I:O:t:n:c:r:i:e:d:psh";

static char* __inCertFile = NULL;
static const char* __issuerCertFile = NULL;
static const char* __issuerRsaFile = NULL;
static const char* __inputRsaFile = NULL;
static const char* __privKeyFile = NULL;
static char __outRsaFile[PATH_MAX];
static char __outCertFile[PATH_MAX];
static char __type = 0;
static char __pre[2];
static u32 __id = 0;
static int __create = 0;
static int __dump = 0;
static void* __cert = NULL;
static u32 __expIn = 0;

static void
usage(const char* progName)
{
    fprintf(stderr, "usage: %s\n", progName);
    fprintf(stderr,
        " -I, --IN <file>         - input cert file to be verified.\n"
        " -O, --OUT <file>        - generate cert to <file>.cert\n"
        "                           if it's RSA cert, RSA data to <file>.rsa\n"
        " -t, --type <r|a|x|p|m|d|D|T>\n" 
        "                         - create cert for Root(r), CA(a), \n"
        "                           ticketing server(x), publishing server(p)\n"
        "                           manufacturing server(m), nc(d), ng(D), or twl(T).\n"
        " -n, --name <id>         - id/name for the cert.\n"
        " -c, --issuerCert <file> - issuer cert file.\n"
        " -r, --issuerRsa <file>  - issuer RSA data file.\n"
        " -i, --inputRsa <file>   - input RSA data file.\n"
        " -e, --exponent <number> - RSA key exponent.\n"
        " -d, --devPvt <file>     - device's ECC private key file.\n"
        " -p, --print             - verify cert & dump fields of cert file.\n"
        " -s, --size              - print out sizes of various certs.\n"
        " -h, --help              - print this message.\n");
    exit(1);
} 


static void
processOptions(int argc, char* argv[])
{
    if (argc==1) 
        usage(argv[0]);

    while (1) {
#if defined(__CYGWIN__)
        int ch = getopt(argc, argv, __options);
#else
        int ch = getopt_long_only(argc, argv, __options, __longOptions, 0);
#endif
        if (ch == -1) break;

        switch (ch) {
            case 'I':
                __inCertFile = optarg;
                break;
            case 'O':
                __create = 1;
                sprintf(__outCertFile, "%s.cert", optarg);
                sprintf(__outRsaFile, "%s.rsa", optarg);
                break;
            case 't':
                __type = *optarg;
                break;
            case 'n':
                __id = strtoul(optarg, 0, 0);
                break;
            case 'e':
                __expIn = strtoul(optarg, 0, 0);
                break;
            case 'c':
                __issuerCertFile = optarg;
                break;
            case 'r':
                __issuerRsaFile = optarg;
                break;
            case 'i':
                __inputRsaFile = optarg;
                break;
            case 'd':
                __privKeyFile = optarg;
                break;
            case 'p':
                __dump = 1;
                break;
            case 's': 
                printf("sizeof IOSCSigRsa4096: %dbytes; size of IOSCRootCert: %d bytes, %s ES_ROOT_CERT_SIZE\n", sizeof(IOSCSigRsa4096), sizeof(IOSCRootCert), sizeof(IOSCRootCert)==ES_ROOT_CERT_SIZE ? "same as" : "different from" );
                printf("sizeof IOSCSigRsa4096: %dbytes; size of IOSCRsa4096RsaCert: %d bytes, %s ES_RSA4096_RSA_CERT_SIZE\n", sizeof(IOSCSigRsa4096), sizeof(IOSCRsa4096RsaCert), sizeof(IOSCRsa4096RsaCert)==ES_RSA4096_RSA_CERT_SIZE ? "same as" : "different from" );
                printf("sizeof IOSCSigRsa2048: %dbytes; size of IOSCRsa2048RsaCert: %d bytes, %s ES_RSA2048_RSA_CERT_SIZE\n", sizeof(IOSCSigRsa2048), sizeof(IOSCRsa2048RsaCert), sizeof(IOSCRsa2048RsaCert)==ES_RSA2048_RSA_CERT_SIZE ? "same as": "different from" );
                printf("sizeof IOSCSigRsa2048: %dbytes; size of IOSCRsa2048EccCert: %d bytes, %s ES_RSA2048_ECC_CERT_SIZE\n", sizeof(IOSCSigRsa2048), sizeof(IOSCRsa2048EccCert), sizeof(IOSCRsa2048EccCert)==ES_RSA2048_ECC_CERT_SIZE ? "same as": "different from");
                printf("sizeof IOSCSigEcc: %dbytes; size of IOSCEccEccCert: %d bytes, %s ES_ECC_ECC_CERT_SIZE\n", sizeof(IOSCSigEcc), sizeof(IOSCEccEccCert), sizeof(IOSCEccEccCert)==ES_ECC_ECC_CERT_SIZE ? "same as": "different from");
                exit(0); 
            default:
                usage(argv[0]);
                break;
        }
    }

    if (__inCertFile==NULL && !__create) {
        fprintf(stderr, "provide input cert file using -I or create a new one using -O\n");
        usage(argv[0]);
    }
    if (__create) {
        if (__type==0) {
            fprintf(stderr, "cert type undefined\n");
            usage(argv[0]);
        } 
        if (__type!='r') {
            if (__issuerRsaFile==NULL) {
                fprintf(stderr, "issuer RSA data file undefined.\n");
                usage(argv[0]);
            }
            if (__issuerCertFile==NULL) {
                fprintf(stderr, "issuer cert file undefined.\n");
                usage(argv[0]);
            }
            if (__id==0) {
                fprintf(stderr, "cert ID undefined.\n");
                usage(argv[0]);
            } 
        } 
        if (__type!='d' && __type!='D' && __type!='T' && __type!='m' && __inputRsaFile==NULL) {
            if (__expIn==0) {
                fprintf(stderr, "RSA exponent undefined.\n");
                usage(argv[0]);
            } 
        }
    }

    switch (__type) {
        case 'r':
            sprintf(__pre, "%s", ES_ROOT_NAME);
            break;
        case 'a':
            sprintf(__pre, "%s", ES_CA_PREFIX);
            break;
        case 'x':
            sprintf(__pre, "%s", ES_XS_PREFIX);
            break;
        case 'p':
            sprintf(__pre, "%s", ES_CP_PREFIX);
            break;
        case 'm':
            sprintf(__pre, "%s", ES_MS_PREFIX);
            break;
        case 'd':
            sprintf(__pre, "%s", ES_NC_PREFIX);
            break;
        case 'D':
            sprintf(__pre, "%s", ES_NG_PREFIX);
            break;
        case 'T':
            sprintf(__pre, "%s", ES_TW_PREFIX);
            break;
    }
}

static void 
generateCert()
{
    u8* rsaData = NULL;
    u32 keySize=0, expSize=0;
    CSLOSRsaExponent exp;
    CSLOSRsaPublicKey4096 pubKey1;
    CSLOSRsaPublicKey2048 pubKey2;
    CSLOSEccPublicKey pubKey3;
    CSLOSEccPrivateKey privKey;
    CSLOSEccPrivateKey randN;
    IOSCRsa4096RsaCert issuerCert;
    IOSCName name;
    IOSCName issuerName;
    int i=0, size=0;
    FILE *fptr;

    memset(name, 0, sizeof(IOSCName));
    memset(issuerName, 0, sizeof(IOSCName));

    switch (__type) {
        case 'r':
            if (__inputRsaFile!=NULL) {
                fptr=fopen(__inputRsaFile, "rb");
                rsaData = RUTIL_ReadRsaKeyPair(fptr, NULL);
                fclose(fptr);
            } else {
                rsaData = RUTIL_GenerateRsaKeyPair(ES_RSA_ROOT_KEY_SIZE, __expIn);
            }
            RUTIL_GetPublicKey(rsaData, pubKey1, &keySize);
            RUTIL_GetExponent(rsaData, exp, &expSize);
            
            /* generate unsigned cert */
            size = ES_ROOT_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            ES_GenerateUnsignedCert(ES_ROOT_NAME, ES_ROOT_NAME, IOSC_SIG_RSA4096, IOSC_PUBKEY_RSA4096, pubKey1, exp, expSize, 0, __cert);

            /* ROOT cert no signature */
            break;
        case 'a':
            if (__inputRsaFile!=NULL) {
                fptr=fopen(__inputRsaFile, "rb");
                rsaData = RUTIL_ReadRsaKeyPair(fptr, NULL);
                fclose(fptr);
            } else {
                rsaData = RUTIL_GenerateRsaKeyPair(ES_RSA_SIGNER_KEY_SIZE, __expIn);
            }
            RUTIL_GetPublicKey(rsaData, pubKey2, &keySize);
            RUTIL_GetExponent(rsaData, exp, &expSize);

            /* generate unsigned cert */
            size = ES_RSA4096_RSA_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            sprintf(name, "%s%08x", ES_CA_PREFIX, __id);
            ES_GenerateUnsignedCert(name, ES_ROOT_NAME, IOSC_SIG_RSA4096, IOSC_PUBKEY_RSA2048, pubKey2, exp, expSize, 0, __cert);

            /* sign */
            if (utilFillSig(__issuerRsaFile, sizeof(CSLOSRsaSig4096), __cert, sizeof(IOSCRsa4096RsaCert))!=ES_ERR_OK) {
                fprintf(stderr, "signing cert failed\n");
                goto out;
            }
            break;
        case 'x':
            /* generate RSA key pair */
            if (__inputRsaFile!=NULL) {
                fptr=fopen(__inputRsaFile, "rb");
                rsaData = RUTIL_ReadRsaKeyPair(fptr, NULL);
                fclose(fptr);
            } else {
                rsaData = RUTIL_GenerateRsaKeyPair(ES_RSA_SIGNER_KEY_SIZE, __expIn);
            }
            RUTIL_GetPublicKey(rsaData, pubKey2, &keySize);
            RUTIL_GetExponent(rsaData, exp, &expSize);

            /* generate unsigned cert */
            size = ES_RSA2048_RSA_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            sprintf(name, "%s%08x", ES_XS_PREFIX, __id);
            utilFread(__issuerCertFile, (u8*)(&issuerCert), sizeof(IOSCRsa4096RsaCert));
            sprintf(issuerName, "%s-%s", issuerCert.sig.issuer, issuerCert.head.name.serverId);
            ES_GenerateUnsignedCert(name, issuerName, IOSC_SIG_RSA2048, IOSC_PUBKEY_RSA2048, pubKey2, exp, expSize, 0, __cert);

            /* sign */
            if (utilFillSig(__issuerRsaFile, sizeof(CSLOSRsaSig2048), __cert, sizeof(IOSCRsa2048RsaCert))!=ES_ERR_OK) {
                fprintf(stderr, "signing cert failed\n");
                goto out;
            }
            break;
        case 'p':
            /* generate RSA key pair */
            if (__inputRsaFile!=NULL) {
                fptr=fopen(__inputRsaFile, "rb");
                rsaData = RUTIL_ReadRsaKeyPair(fptr, NULL);
                fclose(fptr);
            } else {
                rsaData = RUTIL_GenerateRsaKeyPair(ES_RSA_SIGNER_KEY_SIZE, __expIn);
            }
            RUTIL_GetPublicKey(rsaData, pubKey2, &keySize);
            RUTIL_GetExponent(rsaData, exp, &expSize);

            /* generate unsigned cert */
            size = ES_RSA2048_RSA_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            sprintf(name, "%s%08x", ES_CP_PREFIX, __id);
            utilFread(__issuerCertFile, (u8*)(&issuerCert), sizeof(IOSCRsa4096RsaCert));
            sprintf(issuerName, "%s-%s", issuerCert.sig.issuer, issuerCert.head.name.serverId);
            ES_GenerateUnsignedCert(name, issuerName, IOSC_SIG_RSA2048, IOSC_PUBKEY_RSA2048, pubKey2, exp, expSize, 0, __cert);

            /* sign */
            if (utilFillSig(__issuerRsaFile, sizeof(CSLOSRsaSig2048), __cert, sizeof(IOSCRsa2048RsaCert))!=ES_ERR_OK) {
                fprintf(stderr, "signing cert failed\n");
                goto out;
            }
            break;
        case 'm':
            /* generate ECC key pair */
            if (__privKeyFile!=NULL) {
                utilFread(__privKeyFile, (u8*)&privKey, sizeof(CSLOSEccPrivateKey));
                CSL_GenerateEccPublicKey(privKey, pubKey3); 
            } else {
                for (i=0; i<sizeof(CSLOSEccPrivateKey); i++) {
                    randN[i] = rand();
                }
                ES_GenerateEccKeyPair(randN, privKey, pubKey3);
            }

            /* generate unsigned cert */
            size = ES_RSA2048_ECC_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            sprintf(name, "%s%08x", ES_MS_PREFIX, __id);
            utilFread(__issuerCertFile, (u8*)(&issuerCert), sizeof(IOSCRsa4096RsaCert));
            sprintf(issuerName, "%s-%s", issuerCert.sig.issuer, issuerCert.head.name.serverId);
            ES_GenerateUnsignedCert(name, issuerName, IOSC_SIG_RSA2048, IOSC_PUBKEY_ECC, pubKey3, NULL, 0, 0, __cert);

            /* sign */
            if (utilFillSig(__issuerRsaFile, sizeof(CSLOSRsaSig2048), __cert, sizeof(IOSCRsa2048EccCert))!=ES_ERR_OK) {
                fprintf(stderr, "signing cert failed\n");
                goto out;
            }
            break;
        case 'd':
        case 'D':
        case 'T':
            /* generate Ecc key pair */
            if (__privKeyFile!=NULL) {
                utilFread(__privKeyFile, (u8*)&privKey, sizeof(CSLOSEccPrivateKey));
                CSL_GenerateEccPublicKey(privKey, pubKey3); 
            } else {
                for (i=0; i<sizeof(CSLOSEccPrivateKey); i++) {
                    randN[i] = rand();
                }
                ES_GenerateEccKeyPair(randN, privKey, pubKey3);
            }

            /* generate unsigned cert */
            size = ES_ECC_ECC_CERT_SIZE;
            __cert = malloc(sizeof(u8)*size);
            sprintf(name, "%s%08x", __pre, __id);
            utilFread(__issuerCertFile, (u8*)(&issuerCert), sizeof(IOSCRsa2048EccCert));
            sprintf(issuerName, "%s-%s", ((IOSCRsa2048EccCert*)(&issuerCert))->sig.issuer, ((IOSCRsa2048EccCert*)(&issuerCert))->head.name.serverId);
            ES_GenerateUnsignedCert(name, issuerName, IOSC_SIG_ECC, IOSC_PUBKEY_ECC, pubKey3, NULL, 0, 0, __cert);

            /* sign */
            if (utilFillEccSig(__issuerRsaFile, __cert, sizeof(IOSCEccEccCert))!=ES_ERR_OK) {
                fprintf(stderr, "signing cert failed\n");
                goto out;
            }
            break;
        default:
            return;
    }

    /* write cert file */
    utilFwrite(__outCertFile, __cert, size);
    printf("cert saved to %s\n", __outCertFile);
out:
    if (__cert!=NULL) {
        free(__cert);
    }

    /* save RSA data */
    if (__type!='d' && __type!='D' && __type!='T' && __type!='m') {
        fptr = fopen(__outRsaFile, "wb");
        RUTIL_SaveRsaKeyPair(fptr, NULL, rsaData);
        fclose(fptr);
        RUTIL_FreeRsaKeyPair(rsaData);
        printf("RSA data file saved to %s\n", __outRsaFile);
    } else if (__privKeyFile==NULL) {
        char* str = strstr(__outRsaFile, ".rsa");
        sprintf(str, ".pvtKey");
        utilFwrite(__outRsaFile, privKey, sizeof(CSLOSEccPrivateKey));
        printf("ECC private key saved to %s\n", __outRsaFile);
    }
}

static void
dumpCert(char* args) 
{
    IOSCCertSigType st;
    IOSCCertPubKeyType pt=0;
    u8* ptr=NULL;
    int i;
    struct stat statBuf;
    char *file=NULL;
    int sigSize=0, keySize, size=0;

    /* get cert */
    if (__create) {
        stat(__outCertFile, &statBuf);
        file = __outCertFile;
    } else if (__inCertFile) {
        stat(__inCertFile, &statBuf);
        file = __inCertFile;
    } else {
        fprintf(stderr, "specify input cert file using -I or create new cert file using -O\n");
        usage(args);
    }
    __cert = malloc(sizeof(IOSCRootCert));
    memset(__cert, 0, sizeof(IOSCRootCert));
    utilFread(file, (u8*)__cert, statBuf.st_size);

    st = ntohl(*((u32*)__cert));
    switch (st) {
        case IOSC_SIG_RSA4096:
            pt = ntohl(((IOSCRsa4096RsaCert*)__cert)->head.pubKeyType);
            switch (pt) {
                case IOSC_PUBKEY_RSA4096: 
                    sigSize = 0;
                    keySize = sizeof(CSLOSRsaPublicKey4096);
                    utilDumpCert1(__cert, IOSCRootCert);
                    utilDumpCert2(__cert, IOSCRootCert);
                    size = sizeof(IOSCRootCert);
                    break;
                case IOSC_PUBKEY_RSA2048:
                    sigSize = sizeof(CSLOSRsaSig4096);
                    keySize = sizeof(CSLOSRsaPublicKey2048);
                    utilDumpCert1(__cert, IOSCRsa4096RsaCert);
                    utilDumpCert2(__cert, IOSCRsa4096RsaCert);
                    size = sizeof(IOSCRsa4096RsaCert);
                    break;
                default:
                    break;
            }
            break;
        case IOSC_SIG_RSA2048:
            pt = ntohl(((IOSCRsa2048RsaCert*)__cert)->head.pubKeyType);
            switch (pt) {
                case IOSC_PUBKEY_ECC: 
                    sigSize = sizeof(CSLOSRsaSig2048);
                    keySize = sizeof(CSLOSEccPublicKey);
                    utilDumpCert1(__cert, IOSCRsa2048EccCert);
                    size = sizeof(IOSCRsa2048EccCert);
                    break;
                case IOSC_PUBKEY_RSA2048:
                    sigSize = sizeof(CSLOSRsaSig2048);
                    keySize = sizeof(CSLOSRsaPublicKey2048);
                    utilDumpCert1(__cert, IOSCRsa2048RsaCert);
                    utilDumpCert2(__cert, IOSCRsa2048RsaCert);
                    size = sizeof(IOSCRsa2048RsaCert);
                    break;
                default:
                    break;
            }
            break;
        case IOSC_SIG_ECC:
            pt = ntohl(((IOSCEccEccCert*)__cert)->head.pubKeyType);
            switch (pt) {
                case IOSC_PUBKEY_ECC: 
                    sigSize = sizeof(CSLOSEccSig);
                    keySize = sizeof(CSLOSEccPublicKey);
                    utilDumpCert1(__cert, IOSCEccEccCert);
                    size = sizeof(IOSCEccEccCert);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }

    if (__issuerCertFile!=NULL) {
        if ( utilVerify(__issuerCertFile, sigSize, __cert, size)!=ES_ERR_OK)
            printf("cert verify failed\n");
        else
            printf("cert verify successful\n");
    }
    free(__cert);
}

int
main(int argc, char* argv[])
{
    processOptions(argc, argv);

    if (__create) {
        generateCert();
    }

    if (__dump) {
        dumpCert(argv[0]);
    }

    return 0;
}
