/*
 *               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 <unistd.h>
#include <limits.h>
#include <string.h>
#include <libgen.h>
#include <fcntl.h>
#include <errno.h>

#include <sys/stat.h>
#include <sys/types.h>

#include <netinet/in.h>

#include "root.h"
#include "esl.h"
#include "es_int.h"
#include "aes.h"
#include "sha1.h"
#include "utils.h"

#if !defined(__CYGWIN__)
#define O_BIN_RDONLY        (O_RDONLY)
#define O_BIN_CREAT_WRONLY  (O_CREAT|O_WRONLY)
#else
#define O_BIN_RDONLY        (O_BINARY|O_RDONLY)
#define O_BIN_CREAT_WRONLY  (O_BINARY|O_CREAT|O_WRONLY)
#endif

typedef struct
{
    u32 hdrSize;
    u8  wadType[2];
    u16 wadVersion;
    u32 certSize;
    u32 crlSize;
    u32 ticketSize;
    u32 tmdSize;
    u32 contentSize;
    u32 metaSize;
} WADHeader;

/* Common key for RVL development PKI */
static u8 commonKey1[] = {
    0xa1, 0x60, 0x4a, 0x6a, 0x71, 0x23, 0xb5, 0x29,
    0xae, 0x8b, 0xec, 0x32, 0xc8, 0x16, 0xfc, 0xaa
};

#if !defined(RVL_IRD)
/* Common key for NC development PKI */
static u8 commonKey2[] = {
    0x67, 0x45, 0x8b, 0x6b, 0xc6, 0x23, 0x7b, 0x32,
    0x69, 0x98, 0x3c, 0x64, 0x73, 0x48, 0x33, 0x66
};
#endif

static u8* commonKey = commonKey1;

static u8 buffer[4096];

void
Usage(char *prog)
{
#if !defined(RVL_IRD)
    fprintf(stderr, "Usage: %s <wad file> <directory> [rvl_devl|rvl_prod|nc_devl|nc_prod] [<input tmd file>]\n", basename(prog));
#else
    fprintf(stderr, "Usage: %s <wad file> <directory> [rvl_devl|rvl_prod] [<input tmd file>]\n", basename(prog));
#endif
    exit(-1);
}

int
readWadHeader(int fd, WADHeader *header)
{
    int rv;

    /* Read WAD header */
    if ((rv = read(fd, header, sizeof(WADHeader))) != sizeof(WADHeader)) {
        fprintf(stderr, "read: unable to read WAD header: %d != %d\n", rv, sizeof(WADHeader));
        return -1;
    }

    /* WAD files are stored in network byte order (big-endian) */
    header->hdrSize = ntohl(header->hdrSize);
    header->wadVersion = ntohs(header->wadVersion);
    header->certSize = ntohl(header->certSize);
    header->crlSize = ntohl(header->crlSize);
    header->ticketSize = ntohl(header->ticketSize);
    header->tmdSize = ntohl(header->tmdSize);
    header->contentSize = ntohl(header->contentSize);
    header->metaSize = ntohl(header->metaSize);

    /* Only support wad version 0 for now */
    if (header->hdrSize != sizeof(WADHeader) || header->wadVersion != 0) {
        fprintf(stderr, "invalid wad header: size=%d, version=%d\n", header->hdrSize, header->wadVersion);
        return -1;
    }

    return 0;
}


int
dumpFile(int ifd, char *base, char *suffix, int size)
{
    int rv = 0;
    char file[PATH_MAX];
    int ofd = -1;
    off_t pos;

    /* Round up to 64 byte offset in file */
    pos = lseek(ifd, 0, SEEK_CUR);
    lseek(ifd, (pos + 63) & ~63, SEEK_SET);

    /* Create destination file */
    snprintf(file, sizeof(file), "%s%s", base, suffix);
    if ((ofd = open(file, O_BIN_CREAT_WRONLY, 0644)) < 0) {
        fprintf(stderr, "open: cannot open '%s': %s\n", file, strerror(errno));
        rv = -1;
        goto end;
    }

    /* Copy portion out of WAD file a chunk at a time */
    while (size) {
        int chunk = size > sizeof(buffer) ? sizeof(buffer) : size;

        if ((rv = read(ifd, buffer, chunk)) != chunk) {
            fprintf(stderr, "read: unable to read %d bytes: %d\n", chunk, rv);
            rv = -1;
            goto end;
        }

        if ((rv = write(ofd, buffer, chunk)) != chunk) {
            fprintf(stderr, "write: unable to write %d bytes: %d\n", chunk, rv);
            rv = -1;
            goto end;
        }
        size -= chunk;
    }

    rv = 0;
end:
    if (ofd >= 0) close(ofd);
    return rv;   
}

int
dumpContents(int ifd, char *dir, ESTicket *ticket, ESTitleMeta *tmd)
{
    int rv = 0;
    int ofd = -1;
    u16 numContents = tmd->head.numContents;
    u16 i;
    CSLOSAesKey iv;
    CSLOSAesKey titleKey;
    SHA1Context sha;
    IOSCSha1Hash hash;
    char buffer[16], obuffer[16];

    /* Decrypt titleKey with commonKey */
    memset(iv, 0, sizeof(iv));
    memcpy(iv, &ticket->titleId, sizeof(ESTitleId));
    aes_SwDecrypt(commonKey, iv, ticket->titleKey, sizeof(CSLOSAesKey), titleKey);

    /* Decrypt each piece of content */
    for (i = 0; i < numContents; ++i) {
        off_t pos;
        char file[PATH_MAX];
        ESContentMeta *c = tmd->contents + i;
        u64 size = c->size;

        /* Set IV to content index */
        u16 idx = htons(c->index);
        memset(iv, 0, sizeof(iv));
        memcpy(iv, &idx, sizeof(idx));

        /* Reset per-content hash */
        SHA1Reset(&sha);

        /* Round up to 64 bytes */
        pos = lseek(ifd, 0, SEEK_CUR);
        lseek(ifd, (pos + 63) & ~63, SEEK_SET);

        /* Create output file */
        snprintf(file, sizeof(file), "%s/%03d", dir, c->index);
        if ((ofd = open(file, O_BIN_CREAT_WRONLY, 0644)) < 0) {
            fprintf(stderr, "open: cannot open '%s': %s\n", file, strerror(errno));
            rv = -1;
            goto end;
        }

        /* Iterate over file a chunk at a time */
        while (size) {
            int chunk = size > sizeof(buffer) ? sizeof(buffer) : size;

            /* Read encrypted chunk */
            if ((rv = read(ifd, buffer, sizeof(buffer))) != sizeof(buffer)) {
                fprintf(stderr, "read: unable to read %d bytes: %d\n", chunk, rv);
                rv = -1;
                goto end;
            }

            /* Decrypt chunk and update IV */
            aes_SwDecrypt(titleKey, iv, buffer, sizeof(buffer), obuffer);
            memcpy(iv, buffer + chunk - sizeof(IOSCAesIv), sizeof(IOSCAesIv));

            /* Hash decrypted chunk */
            SHA1Input(&sha, obuffer, chunk);

            /* Write decrypted chunk */
            if ((rv = write(ofd, obuffer, chunk)) != chunk) {
                fprintf(stderr, "write: unable to write %d bytes: %d\n", chunk, rv);
                rv = -1;
                goto end;
            }
            size -= chunk;
        }
        /* Compare computed hash result with stored hash in the tmd */
        SHA1Result(&sha, hash);
        if (memcmp(hash, c->hash, sizeof(hash))) {
            fprintf(stderr, "hash mismatch for content %d\n", i);
            rv = -1;
            goto end;
        }
        close(ofd);
        ofd = -1;
    }

    rv = 0;

end:
    if (ofd >= 0) close(ofd);
    return rv;   
}

int
swapTicket(ESTicket *ticket)
{
    /* titleId is the only field we look at */
    ticket->titleId = ntohll(ticket->titleId);
    return 0;
}

int
swapTmd(ESTitleMeta *tmd)
{
    u32 i, n;

    /* For each piece of content, swap from big-endian to host-endian */
    n = tmd->head.numContents = ntohs(tmd->head.numContents);
    for (i = 0; i < n; ++i) {
        ESContentMeta *c = tmd->contents + i;
        c->cid = ntohl(c->cid);
        c->index = ntohs(c->index);
        c->size = ntohll(c->size);
    }
    return 0;
}

int 
findCert(const char* id, const void* certList, u32 certListSize, void** cert, u32* certSize, char** certIssuer)
{
    ESError rv = ES_ERR_ISSUER_NOT_FOUND;
    u8* ptr = (u8*)certList;
    IOSCCertSigType sigType;
    IOSCCertPubKeyType keyType;
    char* pIssuer;
    char* pCert;
    IOSCName name;

    while (ptr<((u8*)certList+certListSize)) {

        sigType = ntohl(((IOSCSigRsa4096*)ptr)->sigType);
        switch (sigType) {
            case IOSC_SIG_RSA4096:
                pIssuer = ((IOSCSigRsa4096*)ptr)->issuer;
                pCert = ((IOSCRsa4096RsaCert*)ptr)->head.name.serverId;
                *certSize = sizeof(IOSCRsa4096RsaCert);
                break;
            case IOSC_SIG_RSA2048:
                pIssuer = ((IOSCSigRsa2048*)ptr)->issuer;
                keyType = ntohl(((IOSCRsa2048RsaCert*)ptr)->head.pubKeyType);
                switch (keyType) {
                    case IOSC_PUBKEY_RSA2048:
                        pCert =  ((IOSCRsa2048RsaCert*)ptr)->head.name.serverId;
                        *certSize = sizeof(IOSCRsa2048RsaCert);
                        break;
                    case IOSC_PUBKEY_ECC:
                        pCert =  ((IOSCRsa2048EccCert*)ptr)->head.name.serverId;
                        *certSize = sizeof(IOSCRsa2048EccCert);
                        break;
                    default:
                        rv = ES_ERR_INCORRECT_PUBKEY_TYPE;
                        fprintf(stderr, "cannot find cert: %d\n", rv);
                        goto out;
                }
                break;
            case IOSC_SIG_ECC:
                pIssuer = ((IOSCSigEcc*)ptr)->issuer;
                pCert = ((IOSCEccEccCert*)ptr)->head.name.deviceId;
                *certSize = sizeof(IOSCEccEccCert);
                break;
            default:
                rv = ES_ERR_INCORRECT_SIG_TYPE;
                fprintf(stderr, "cannot find cert: %d\n", rv);
                goto out;
        }

        snprintf(name, sizeof(IOSCName), "%s-%s", pIssuer, pCert);
        if (!strncmp(id, name, sizeof(IOSCName))) {
            *cert = ptr;
            *certIssuer = pIssuer;
            rv = ES_ERR_OK;
            break;
        }

        ptr += (*certSize);
    }

out:
    if (rv!=ES_ERR_OK) {
        *certSize = 0;
        *cert = NULL;
        *certIssuer = NULL;
    }
    return rv;
}

int 
verifyContainer(char* certList, int certListSize, u8* rootKey, char* containerFile, int containerSize)
{
    int rv = ES_ERR_OK;
    u8* certs = NULL;
    u8* data = NULL;
    char* prefix = NULL;
    char* caId;
    char* issuerId;
    char* rootId;
    IOSCRsa4096RsaCert* caCert = NULL;
    IOSCRsa2048RsaCert* issuerCert = NULL;
    u32 issuerCertSize = 0;
    u32 caCertSize = 0;

    certs = malloc(sizeof(u8)*certListSize);
    utilFread(certList, certs, certListSize);

    data = malloc(sizeof(u8*)*containerSize);
    utilFread(containerFile, data, containerSize);
    if (strstr(containerFile, ".tik")!=NULL) {
        issuerId = ((ESTicket*)data)->sig.issuer;
        prefix = ES_XS_PREFIX;
    } else if (strstr(containerFile, ".tmd")!=NULL) {
        issuerId = ((ESTitleMeta*)data)->sig.issuer;
        prefix = ES_CP_PREFIX;
    } else {
        fprintf(stderr, "invalid file suffix, has to be .tik or .tmd\n");
        rv = ES_ERR_INVALID;
        goto out;
    }

    /* find issuer cert */
    if ((rv=findCert(issuerId, certs, certListSize, (void**)&issuerCert, &issuerCertSize, &caId))!=ES_ERR_OK) {
        fprintf(stderr, "cannot find issuer cert %d\n", rv);
        goto out;
    }

    /* find CA cert */
    if ((rv=findCert(caId, certs, certListSize, (void**)&caCert, &caCertSize, &rootId))!=ES_ERR_OK) {
        fprintf(stderr, "cannot find CA cert %d\n", rv);
        goto out;
    }

    /* check issuer cert name */
    if (strncmp(issuerCert->head.name.serverId, prefix, 2)!=0) {
        fprintf(stderr, "issuer cert name wrong\n");
        rv = ES_ERR_INVALID;
        goto out;
    }

    /* verify CA cert */
    if (rootKey!=NULL && (rv=utilVerify2(rootKey, sizeof(CSLOSRsaPublicKey4096), sizeof(CSLOSRsaSig4096), (u8*)caCert, caCertSize, 0))!=ES_ERR_OK) {
        fprintf(stderr, "failed verifying CA cert %d\n", rv);
        goto out;
    }

    /* verify issuer cert */
    if ((rv=utilVerify2(caCert, sizeof(IOSCRsa4096RsaCert), sizeof(CSLOSRsaSig2048), (u8*)issuerCert, issuerCertSize, 1))!=ES_ERR_OK) {
        fprintf(stderr, "failed verifying issuer cert %d\n", rv);
        goto out;
    }

    /* verify container */
    if ((rv=utilVerify2(issuerCert, sizeof(IOSCRsa2048RsaCert), sizeof(CSLOSRsaSig2048), data, containerSize, 1))!=ES_ERR_OK) {
        fprintf(stderr, "failed verifying container data %d\n", rv);
        goto out;
    }

out:
    free(certs);
    free(data);
    return rv;
}

int
crackWad(char *wadFile, char *dir, u8* rootKey, char* inTmdFile)
{
    int ifd = -1;
    int rv = 0;
    WADHeader header;
    char base[PATH_MAX];
    char *p;
    ESTicket *ticket = NULL;
    ESTitleMeta *tmd = NULL;
    ESTitleMeta *inTmd = NULL;
    u8* certs = NULL;
    char certFile[PATH_MAX];
    char ticketFile[PATH_MAX];
    char tmdFile[PATH_MAX];

    /* Open WAD file */
    if ((ifd = open(wadFile, O_BIN_RDONLY)) < 0) {
        fprintf(stderr, "open: cannot open '%s': %s\n", wadFile, strerror(errno));
        rv = -1;
        goto end;
    }

    /* Read and parse header */
    if (readWadHeader(ifd, &header) < 0) {
        rv = -1;
        goto end;
    }

    /* Create destination directory */
    if (mkdir(dir, 0777) < 0) {
        fprintf(stderr, "mkdir: cannot create directory '%s': %s\n", dir, strerror(errno));
        rv = -1;
        goto end;
    }

    snprintf(base, sizeof(base), "%s/%s", dir, basename(wadFile));
    if ((p = strrchr(base, '.')) != NULL) {
        *p = 0;
    }

    /* Allocate ticket and tmd data structures based on WAD header */
    if ((ticket = (ESTicket *)malloc(header.ticketSize)) == NULL ||
        (tmd = (ESTitleMeta *)malloc(header.tmdSize)) == NULL ||
        (certs = malloc(header.certSize)) == NULL) {
        fprintf(stderr, "unable to allocate ticket, tmd and cert structures\n");
        rv = -1;
        goto end;
    }

    /* Dump files */
    if (dumpFile(ifd, base, ".cert" , header.certSize) ||
        dumpFile(ifd, base, ".crl" , header.crlSize) ||
        dumpFile(ifd, base, ".tik" , header.ticketSize) ||
        memcpy(ticket, buffer, header.ticketSize) != ticket ||
        dumpFile(ifd, base, ".tmd" , header.tmdSize) ||
        memcpy(tmd, buffer, header.tmdSize) != tmd ||
        swapTmd(tmd) ||
        dumpContents(ifd, dir, ticket, tmd) ||
        dumpFile(ifd, base, ".meta" , header.metaSize)) {
        rv = -1;
        goto end;
    }

    snprintf(certFile, sizeof(certFile), "%s.cert", base);
    snprintf(ticketFile, sizeof(ticketFile), "%s.tik", base);
    snprintf(tmdFile, sizeof(tmdFile), "%s.tmd", base);

    /* verify ticket */
    if ((rv=verifyContainer(certFile, header.certSize, rootKey, ticketFile, header.ticketSize))!=ES_ERR_OK) {
        fprintf(stderr, "failed verify ticket %d\n", rv);
        goto end;
    }

    /* verify tmd */
    if ((rv=verifyContainer(certFile, header.certSize, rootKey, tmdFile, header.tmdSize))!=ES_ERR_OK) {
        fprintf(stderr, "failed verify tmd %d\n", rv);
        goto end;
    }

    /* check tmd fields with input tmd */
    if (inTmdFile!=NULL) {
        inTmd = malloc(header.tmdSize);
        utilFread(inTmdFile, (u8*)inTmd, header.tmdSize);
        utilFread(tmdFile, (u8*)tmd, header.tmdSize);
        if (tmd->head.sysVersion!=inTmd->head.sysVersion || 
            tmd->head.type!=inTmd->head.type || 
            tmd->head.titleId!=inTmd->head.titleId ||
            tmd->head.groupId!=inTmd->head.groupId ||
            tmd->head.accessRights!=inTmd->head.accessRights || 
            tmd->head.titleVersion!=inTmd->head.titleVersion || 
            tmd->head.numContents!=inTmd->head.numContents || 
            tmd->head.bootIndex!=inTmd->head.bootIndex || 
            memcmp(tmd->head.reserved, inTmd->head.reserved, sizeof(ESTmdReserved))!=0 ) {
            fprintf(stderr, "output TMD inconsistent with input TMD\n"); 
            rv = -1;
            goto end;
        }
    }

end:
    if (ifd >= 0) close(ifd);
    if (ticket) free(ticket);
    if (tmd) free(tmd);
    if (inTmd) free(inTmd);

    return rv;
}

int
main(int argc, char *argv[])
{
    u8 key1[] = RVL_DEVEL_PKI_MOD;
    u8 key2[] = RVL_PROD_PKI_MOD;
#if !defined(RVL_IRD)
    u8 key3[] = NC_BETA_PKI_MOD;
    u8 key4[] = NC_PROD_PKI_MOD;
    u8* keys[4] = {key1, key2, key3, key4};
    char* pki[] = {"rvl_devl", "rvl_prod", "nc_devl", "nc_prod"};
#else
    u8* keys[2] = {key1, key2};
    char* pki[] = {"rvl_devl", "rvl_prod"};
#endif
    u8* rootKey = NULL;
    int i;

    if (argc<3 || argc>5) {
        Usage(argv[0]);
    }
    
    switch (argc) {
        case 3: 
            return crackWad(argv[1], argv[2], NULL, NULL);
        case 4:
#if !defined(RVL_IRD)
            if (!strcmp(argv[3], pki[2])) {
                commonKey = commonKey2;
            }
            for (i=0; i<4; i++) {
                if (!strcmp(argv[3], pki[i])) {
                    rootKey = keys[i];
                    break;
                }
            }
#else
            for (i=0; i<2; i++) {
                if (!strcmp(argv[3], pki[i])) {
                    rootKey = keys[i];
                    break;
                }
            }
#endif
        case 5: 
            return crackWad(argv[1], argv[2], rootKey, argv[4]);
        default: 
            return -1;
    }
}

