/*
  This program is derived from a python program with the following copyright notice:

# BSD 2-Clause License
#
# Copyright (c) 2022, Quarkslab SAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>

#include <libtpms/tpm_library.h>
#include <libtpms/tpm_error.h>
#include <libtpms/tpm_memory.h>

int main(void)
{
    unsigned char *rbuffer = NULL;
    uint32_t rlength;
    uint32_t rtotal = 0;
    TPM_RESULT res;
    int ret = 1;
    uint32_t session_handle, errcode;
    unsigned char *cmd = NULL;

    unsigned char startup[] = {
        0x80, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00,
        0x01, 0x44, 0x00, 0x00
    };

    res = TPMLIB_ChooseTPMVersion(TPMLIB_TPM_VERSION_2);
    if (res) {
        fprintf(stderr, "TPMLIB_ChooseTPMVersion() failed: 0x%02x\n", res);
        goto exit;
    }

    res = TPMLIB_MainInit();
    if (res) {
        fprintf(stderr, "TPMLIB_MainInit() failed: 0x%02x\n", res);
        goto exit;
    }

    res = TPMLIB_Process(&rbuffer, &rlength, &rtotal, startup, sizeof(startup));
    if (res) {
        fprintf(stderr, "TPMLIB_Process(Startup) failed: 0x%02x\n",
                res);
        goto exit;
    }

    unsigned char tpm2_session_symmetric_xor[] = {
        0x80, 0x01,
        0x00, 0x00, 0x00, 0x3d,	// length
        0x00, 0x00, 0x01, 0x76,	// TPM_CC_StartAuthSession
        0x40, 0x00, 0x00, 0x07, // TPM_RH_NULL
        0x40, 0x00, 0x00, 0x07, // TPM_RH_NULL
        0x00, 0x20,	// nonceCaller length
        0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
        0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
        0x00, 0x00,	// encrypted salt length
        0x00,		// session type = TPM_SE_HMAC
        0x00, 0x0a,	// symmetric.algorithm = TPM_ALG_XOR
        0x00, 0x0b,	// symmetric.keyBits = TPM_ALG_SHA256
        0x00, 0x0b	// authHash = TPM_ALG_SHA256
    };

    res = TPMLIB_Process(&rbuffer, &rlength, &rtotal,
                         tpm2_session_symmetric_xor, sizeof(tpm2_session_symmetric_xor));
    if (res) {
        fprintf(stderr, "TPMLIB_Process(TPM2_StartAuthSession) failed: 0x%02x\n",
                res);
        goto exit;
    }

    if (rlength != 48) {
        fprintf(stderr, "Expected response is %u bytes, but got %u.\n",
                48, rlength);
        goto exit;
    }

    memcpy(&session_handle, &rbuffer[10], sizeof(session_handle));

    unsigned char tpm2_create_primary_oob_write_temp[] = {
        0x80, 0x02,
        0xff, 0xff, 0xff, 0xff,	// length
        0x00, 0x00, 0x01, 0x31,	// TPM_CC_CreatePrimary
        0x40, 0x00, 0x00, 0x01, // TPM_RH_OWNER
        0x00, 0x00, 0x00, 0x09, // length
        0xff, 0xff, 0xff, 0xff, // session handle
        0x00, 0x00,		// nonceSize
        0x20,			// sessionAttributes = decrypt
        0x00, 0x00,		// authorizationSize
        0xff, 0xff,             // ciphersize
    };

    uint32_t maxcmdsize = TPMLIB_SetBufferSize(0, NULL, NULL);
    if (maxcmdsize < sizeof(tpm2_create_primary_oob_write_temp)) {
        fprintf(stderr, "Command buffer of size %u would be to small.",
                maxcmdsize);
        goto exit;
    }

    cmd = malloc(maxcmdsize);
    if (!cmd) {
        fprintf(stderr, "Could not allocate %u bytes.\n", maxcmdsize);
        goto exit;
    }

    memset(cmd, 0x88, maxcmdsize);
    memcpy(cmd, tpm2_create_primary_oob_write_temp,
           sizeof(tpm2_create_primary_oob_write_temp));
    memcpy(&cmd[18], &session_handle, sizeof(session_handle));

    // cipher size with 2 bytes too many
    uint16_t val_be16 = htons(maxcmdsize - 0x1d + 2);
    memcpy(&cmd[27], &val_be16, sizeof(val_be16));

    // command size
    uint32_t val_be32 = htonl(maxcmdsize);
    memcpy(&cmd[2], &val_be32, sizeof(val_be32));

    res = TPMLIB_Process(&rbuffer, &rlength, &rtotal, cmd, maxcmdsize);
    if (res) {
        fprintf(stderr, "TPMLIB_Process(TPM2_CreatePrimary) failed: 0x%02x\n",
                res);
        goto exit;
    }

    if (rlength != 10) {
        fprintf(stderr, "Expected response is %u bytes, but got %u.\n",
                10, rlength);
        goto exit;
    }

    memcpy(&errcode, &rbuffer[6], sizeof(errcode));
    if (ntohl(errcode) != 0x995) {
        fprintf(stderr, "Unexpected error code 0x%x. Expected 0x995.\n",
                ntohl(errcode));
        goto exit;
    }

    ret = 0;

    fprintf(stdout, "OK\n");

exit:
    free(cmd);
    TPMLIB_Terminate();
    TPM_Free(rbuffer);

    return ret;
}
