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

#ifndef __ESL_H__
#define __ESL_H__

#if defined(__cplusplus)
extern "C" {
#endif

#include <iosctypes.h>
#include <iosccert.h>
#include <estypes.h>

#define ES_ROOT_CERT_SIZE          1280 
#define ES_RSA4096_RSA_CERT_SIZE   1024 
#define ES_RSA2048_RSA_CERT_SIZE   768 
#define ES_RSA2048_ECC_CERT_SIZE   576 
#define ES_ECC_ECC_CERT_SIZE       384 
#define ES_RSA4096_PUB_KEY_SIZE    512 
#define ES_RSA2048_PUB_KEY_SIZE    256 
#define ES_RSA_EXPONENT_SIZE       4
#define ES_ECC_PVT_KEY_SIZE        30 
#define ES_ECC_PUB_KEY_SIZE        60 

#define ES_MAX_TMD_SIZE            18916
#define ES_MIN_TMD_SIZE		   484    
#define ES_TICKET_SIZE             676 
#define ES_AES_KEY_SIZE            16 
#define ES_HASH_SIZE               20 

#define ES_ECC_RANDN_SIZE          30

#define ES_NAME_SIZE               64
#define ES_SIGNATURE_OFFSET        4
#define ES_SIG_PAD_SIZE            60 
#define ES_TMD_RESERVED_SIZE       62
#define ES_TICKET_RESERVED_SIZE    47

#define ES_AES_BUF_SIZE            16

/*
 * Defines for device data creation
 */
#define ES_RVL_PVT_DATA_SIZE ((160+128+32)/8)
#define ES_RVL_RAND_SIZE (128)
#define ES_RVL_DEVICE_DATA_SIZE (3*1024/8)

#define ES_NC_PVT_DATA_SIZE ((160+128)/8)
#define ES_NC_RAND_SIZE (384)
#define ES_NC_DEVICE_DATA_SIZE (4*1024/8)

/*
 * XXX Error codes private to esl, since esl uses ES error codes
 * its a bit awkward. Maybe we can put an ES_ERR_LAST in <estypes.h> and
 * reference host side error codes off that?
 */
#define ES_ERR_LAST ES_ERR_UNKNOWN
#define ES_ERR_PVT_DATA_SIZE ES_ERR_LAST-1
#define ES_ERR_RAND_DATA_SIZE ES_ERR_LAST-2
#define ES_ERR_DEVICE_DATA_SIZE ES_ERR_LAST-3

/* certificate routines */

/* 
 * Returns the cert data structure size. 
 *
 * Input:
 * sigType - signature type 
 * keyType - public key type 
 * 
 * Output:
 * size of certificate data structure
 *
 */
extern int ES_GetCertSize(IOSCCertSigType sigType, IOSCCertPubKeyType keyType);

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

    
/*
 * Return a pointer to the public key in the given certificate.  Also
 * returns the size of this public key through the keySize output
 * parameter.
 * Return NULL if the cert cannot be parsed.
 */
extern u8* ES_GetCertPubKey(const void* cert, u32* keySize);


/* 
 * Generate unsigned certificates: IOSCRootCert, IOSCRsa4096RsaCert, 
 * IOSCRsa2048RsaCert, IOSCRsa2048EccCert, or IOSCEccEccCert.
 *
 * Input:
 * certName   - certificate name
 * issuerName - certificate issuer name
 * sigType    - signature type, should be: 
 *              ES_SIG_RSA4096: 4096bits RSA signature
 *              ES_SIG_RSA2048: 2048bits RSA signature
 *              ES_SIG_ECC:     512bits padded ECC signature
 * pubKeyType - public key type, should be:
 *              ES_PUBKEY_RSA4096: "pubKey" should be 4096bits 
 *              ES_PUBKEY_RSA2048: "pubKey" should be 2048bits 
 *              ES_PUBKEY_ECC: "pubKey" should be 60bytes 
 * 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) 
 */
extern int ES_GenerateUnsignedCert(const char* certName, const char* issuerName, IOSCCertSigType sigType, IOSCCertPubKeyType keyType, const u8* pubKey, const u8* exponent, int exponentSizeInBytes, u32 date, void* cert);


/* 
 * Generate unsigned device certificate. This is an IOSCEccEccCert. Function
 * uses the generic ES_GenerateUnsignedCert call but simplifies things for the
 * caller who only wants to generate device certificates. 
 *
 * Input:
 * certName   - certificate name
 * issuerName - certificate issuer name
 * pubKey     - public key
 * date       - certificate expiration date
 * 
 * Output:
 * cert       - output unsigned certificate 
 *              (caller allocates - use ES_GetCertSize to determine size) 
 */
extern int ES_GenerateDeviceCert(const char* certName, const char* issuerName, const IOSCEccPublicKey* pubKey, const u32 date, IOSCEccEccCert* cert);

/*
 * Verify a signed device certificate
 *
 * Input:
 * cert       - device certificate, signed by manufacturing server
 * pubkey     - public key of manufacturing server
 *
 * Return value will be ES_ERR_OK, or ES_ERR_VERIFY_SIG_FAILED
 */
extern int ES_VerifyDeviceCert(IOSCEccEccCert *cert, IOSCEccPublicKey *pubKey);

/*
 * Generate Device Data. This comes in two flavors: ES_GenerateRvlDeviceData() and 
 * ES_GenerateNCDeviceData()
 *
 * Input:
 * pvtData        - private data, includes boot hash and common key
 * pvtDataSize    - size of private data - ES_RVL_PVT_DATA_SIZE or ES_NC_PVT_DATA_SIZE
 * randN          - random data for additional keys, must be different per call
 * randSize       - size of random data, should be 128 bytes - ES_RVL_RAND_SIZE 
 *                  or ES_NC_RAND_SIZE
 * pvtKey         - device private key
 * cert           - device certificate, must be signed
 * caName         - name of the CA that issued the manufacturing servers cert
 * deviceData     - buffer for output allocated by caller
 * deviceDataSize - size of the output buffer allocated by caller - ES_RVL_DEVICE_DATA_SIZE
 *                  or ES_NC_DEVICE_DATA_SIZE
 * 
 * Output:
 * Data is put in deviceData buffer
 *
 * Return values are ES_ERR_OK, or ES_ERR_PVT_DATA_SIZE, ES_ERR_RAND_DATA_SIZE, 
 * ES_ERR_DEVICE_DATA_SIZE if you didn't supply the correct amount of data or buffer
 *
 */
extern 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);
extern 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);

//TODO
extern int ES_GenerateUnsignedCrl();
extern int ES_DepositeCertStore();
extern int ES_VerifyCert();

/* TMD routines */

/*
 * return the TMD size in bytes given the number of contents in the title 
 *
 */
extern int ES_GetTmdSize(u16 numContents);

/* 
 * AES encrypt content file and compute hash 
 *
 * Input: 
 * contentFile - name of the raw content file
 * cid         - content ID for the content
 * cidx	       - TMD index for this content
 * titleKey    - 128 bit AES encryption key
 *
 * Output: 
 * hash        - 160bit SHA1 hash of the content (caller allocates)
 * the encrypted content file is written to <cid>.app
 */
extern int ES_EncryptContent(const char* contentFile, ESContentId cid, u16 cidx, const u8* titleAesKey, u8* hash);

/*
 * The next few calls and the following struct are for the "stream" version
 * of ES_EncryptContent using the init/update/fini model.
 */

typedef struct {
    IOSCAesIv   iv;
    SHA1Context sha;
    const u8*   titleKey;
    u8          inbuf[ES_AES_BUF_SIZE];
    u32         inbufSize;
} ESAesShaHandle;

/*
 * Initialize an ESAesShaHandle object for encryption.
 */
extern int ES_EncryptContentReset(ESAesShaHandle* handle, u16 cidx, const u8* titleKey);

/*
 * Encrypt the inbuf and write the output to outbuf.
 * inbuf:  pointer to the clear text buffer.
 * inSize:  # of bytes of clear text data in inbuf.
 * outbuf: point to the cipher text buffer for output.
 * outSize: # of bytes availabe in output.  Must not be smaller than
 * inSize.
 * Returns the number of bytes written to outbuf, or a negative error code.
 */
extern int ES_EncryptContentUpdate(ESAesShaHandle* handle, const u8* inbuf, u32 inSize, u8* outbuf, u32 outSize);


/*
 * Finalize the encryption.  Any unaligned/unpadded input will be padded
 * and encrypted into outbuf.  The SHA1 hash is also written to "hash".
 * Outbuf must be at least ES_ALIGN_CONTENT_SIZE bytes in size.
 * Returns the number of bytes written to outbuf, or a negative error code.
 */
extern int ES_EncryptContentFinal(ESAesShaHandle* handle, u8* outbuf, u32 outSize, u8* hash);



/*
 * Generate unsigned TMD for a given title. 
 * 
 * Input: 
 * tmdView          - ESTmdView for the list of content IDs & attributes
 * caCrlVersion     - CA CRL version
 * signerCrlVersion - server (XS, CP, MS) CRL version
 * sysVersion        - system softare version
 * rights           - the title's rights to the device
 * bootIndex        - content index for boot content
 * hash             - array of 160bit SHA1 hash for the contents
 * signerCertName   - conetent publishing server's cert name
 * signerCertIssuerName       
 *                  - content publishing server cert issuer's name
 *
 * Output:
 * tmd              - unsigned TMD data structure (caller allocates)
 */
extern int ES_GenerateUnsignedTmd(const ESTmdView* tmdView, ESVersion caCrlVersion, ESVersion signerCrlVersion, ESSysVersion sysVersion, u32 rights, u16 bootIndex, const u8* hash, const char* signerCertName, const char* signerCertIssuerName, void* tmd);

/* 
 * Generate content publisher common key encrypted title key, to be stored 
 * in eTicket.
 *
 * Input
 * commonKey - 128bit AES encryption key from content publishing server
 * titleId   - title ID for the title
 * titleKey  - 128bit AES encryption key used for encrypting the title
 * 
 * Output
 * outKey    - 128bit encrypted title key (caller allocates)
 */
extern int ES_CpEncryptTitleKey(const u8* commonAesKey, ESTitleId titleId, const u8* titleAesKey, u8* outAesKey);

/* eTicket routines */

/* 
 * Generate ECC public/private key pair from input random number.
 *
 * Input:
 * randN  - 30bytes random number, use ES_ECC_RANDN_SIZE
 *
 * Output:
 * pvtKey - 30bytes ECC private key (caller allocates)
 * pubKey - 60bytes ECC public key (caller allocates)
 */
extern int ES_GenerateEccKeyPair(u8* randN, u8* pvtEccKey, u8* pubEccKey);


/*
 * Verify a document against a ECC signature.
 * return ES_ERR_OK if verification is successful.
 */
extern int ES_VerifyEccSig(IOSCEccPublicKey pubKey, void* document,
			   int documentSize, IOSCEccSig sig);

/*
 * Generate unsigned non-personalized eTicket for a given title 
 * and a given device. 
 *
 * Input: 
 * tktView             - ESTicketView for the eTicket
 * caCrlVersion        - CA CRL version
 * signerCrlVersion    - server (XS, CP, MS) CRL version
 * encryptedTitleKey   - common key encrypted titkeKey from CP server
 * serverPubKey        - ticketing server's ECC public key
 * signerCertName      - ticketing server's cert name
 * signerCertIssuerName- ticketing server cert issuer's name
 *
 * Output:
 * ticket              - unsigned, non-personalized eTicket (caller allocates)
 *
 * If serverPubKey is NULL, the eTicket generated is not intended to be  
 * personalized. 
 */
extern int ES_GenerateUnsignedCommonTicket(const ESTicketView *tktView, ESVersion caCrlVersion, ESVersion signerCrlVersion, const u8* encryptedTitkeAesKey, const u8* serverPubEccKey, const char* signerCertName, const char* signerCertIssuerName, void* ticket);

/* 
 * Re-encrypts the titleKey in a signed eTicket, using the computed shared
 * key from the server and the device. 
 *
 * Input: 
 * ticket       - signed eTicket
 * serverPvtKey - ticketing server's ECC private Key
 * devicePubKey - device's ECC private Key
 *
 * Output: 
 * the titleKey in "ticket" is overwritten by the re-encrypted value. 
 */ 
extern int ES_PersonalizeSignedTicket(void* ticket, const u8* serverPvtEccKey, const u8* devicePubEccKey);

/*
 * Returns the default cidx mask
 *
 * Output:
 * mask - cidx mask (64 bytes) with first 32 bytes 0xff, 
 *        and the next 32 bytes 0. 
 *        It covers the first 256 pieces of content.
 */
extern void ES_GetDefaultCidxMask(ESCidxMask mask);

/* 
 * Returns the cidx mask OR'ed with the input content index
 *
 * Input: 
 * cidxList - list of content indices
 * numIdx   - number of content indices
 *
 * Output: 
 * mask - cidx mask (64 bytes, caller allocates) 
 */
extern void ES_MakeCidxMask(ESCidxMask mask, u16* cidxList, int numIdx);

/* 
 * Returns the sysAccessMask OR'ed with the input content index
 *
 * Input: 
 * cidxList - list of content indices
 * numIdx   - number of content indices
 *
 * Output: 
 * mask - sys access mask (2 bytes, caller allocates) 
 */
extern int ES_MakeSysAccessMask(ESSysAccessMask mask, u16* cidxList, int numIdx);

/* 
 * Returns the cidx mask with bits (startIdx -> startIdx+numIdx-1)
 * OR'ed together 
 *
 * Input: 
 * startIdx - starting content index 
 * numIdx   - number of content indexes 
 *  
 * Output: 
 * mask - cidx mask (64 bytes, caller allocates) 
 */
extern void ES_SetMaskBits(ESCidxMask mask, u16 startIdx, int numIdx);

/* ------------------------------------------------------------------------- */
/*                       Disk encryption functions                           */
/* ------------------------------------------------------------------------- */

#define DATA_PER_H0                     1024
#define H0_PER_H1                       31
#define H1_PER_H2                       8
#define H0_PER_SUPERBLOCK               (H0_PER_H1 * H1_PER_H2 * H2_PER_SUPERBLOCK)
#define H1_PER_SUPERBLOCK               (H1_PER_H2 * H2_PER_SUPERBLOCK)
#define H2_PER_SUPERBLOCK               8
#define SUBBLOCK_SIZE                   1024
#define DVD_BLOCK_SIZE                  (32 * SUBBLOCK_SIZE)
#define DVD_DATA_BYTES_PER_BLOCK        (31 * SUBBLOCK_SIZE)
#define BLOCKS_PER_SUPERBLOCK           64
#define DVD_DATA_BYTES_PER_SUPERBLOCK        (DVD_DATA_BYTES_PER_BLOCK * BLOCKS_PER_SUPERBLOCK)
#define H0_PAD_BYTES                    20
#define H1_PAD_BYTES                    32
#define H2_PAD_BYTES                    32
#define H3_SIZE                         (96 * 1024)
#define ES_AES_IV_SIZE                  16
/*
 * Offset to the last 16 bytes of the H2 hash in the hash subblock
 * H0 size (w/pad) + H1 size (w/pad) + H2 size (no pad) - the 16
 */
#define DVD_DATA_IV_OFFSET (640 + 192 + 160 - 16)

/*
 * DISK_BUF_SIZE is a function of the hierarchical hashing.
 * The contents of the hash subblock depend on the data in
 * 64 data blocks.  There are 31K bytes in each data block.
 */

#define ES_AES_DISK_BUF_SIZE         (BLOCKS_PER_SUPERBLOCK * DVD_DATA_BYTES_PER_BLOCK)
#define ES_AES_DISK_OUTPUT_BUF_SIZE  (BLOCKS_PER_SUPERBLOCK * DVD_BLOCK_SIZE)
typedef struct {
    IOSCAesIv   iv;
    SHA1Context sha;
    const u8*   titleKey;
    u8          inbuf[ES_AES_DISK_BUF_SIZE];
    u32         inbufSize;
    u8          h3Buf[H3_SIZE];
    u32         h3Index;        /* Index to next free byte in h3Buf */
} ESDiskAesShaHandle;

/*
 * Initialize an ESDiskAesShaHandle object for encryption.
 * Returns either ES_ERR_ENCRYPTION_FAILED or ES_ERR_OK
 */
extern int ES_DiskEncryptContentReset(ESDiskAesShaHandle* handle, u16 cidx,
                                      const u8* titleKey);

/*
 * Encrypt the inbuf and write the output to outbuf.
 * inbuf:  pointer to the clear text buffer.
 * inSize:  # of bytes of clear text data in inbuf.
 *         Must be <= ES_AES_DISK_BUF_SIZE
 * outbuf: point to the cipher text buffer for output.
 * outSize: # of bytes availabe in output.
 *          Must be >= ES_AES_DISK_OUTPUT_BUF_SIZE
 * Returns the number of bytes written to outbuf, or a negative error code.
 */
extern int ES_DiskEncryptContentUpdate(ESDiskAesShaHandle *handle,
                                       const u8* inbuf,
                                       u32 inSize, u8* outbuf, u32 outSize);


/*
 * Finalize the encryption.  Any remaininginput will be 
 * encrypted into outbuf.  The H4 hash is also written to "hash".
 * Outbuf must be at least ES_AES_DISK_OUTPUT_BUF_SIZE bytes in size.
 * Returns the number of bytes written to outbuf, or a negative error code.
 */
extern int ES_DiskEncryptContentFinal(ESDiskAesShaHandle* handle,
                                      u8* outbuf, u32 outSize, u8* hash);

/* ------------------------------------------------------------------------- */
#if defined(__cplusplus)
}
#endif

#endif /* __ESL_H__ */
