/**
 * (C) 2007-22 - ntop.org and contributors
 * Copyright (C) 2023-25 Hamish Coleman
 * SPDX-License-Identifier: GPL-3.0-only
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not see see <http://www.gnu.org/licenses/>
 *
 */


#include <n3n/benchmark.h>
#include <n3n/logging.h>     // for traceEvent
#include <n3n/random.h>      // for n3n_rand
#include <n3n/transform.h>   // for n3n_transform_register
#include <stdint.h>          // for uint8_t
#include <stdlib.h>          // for calloc, free
#include <string.h>          // for memcpy, size_t, memset, memcmp, strlen
#include <sys/types.h>       // for u_char, ssize_t, time_t

#include "n2n.h"             // for n2n_trans_op_t
#include "n2n_define.h"
#include "n2n_typedefs.h"
#include "pearson.h"         // for pearson_hash_256
#include "tf.h"              // for TF_BLOCK_SIZE, tf_cbc_decrypt, tf_cbc_en...


// size of random value prepended to plaintext defaults to TF_BLOCK_SIZE;
// gradually abandoning security, lower values could be chosen;
// however, minimum transmission size with cipher text stealing scheme is one
// block; as network packets should be longer anyway, only low level programmer
// might encounter an issue with lower values here
#define TF_PREAMBLE_SIZE       (TF_BLOCK_SIZE)


// cbc mode is being used with random value prepended to plaintext
// instead of iv so, actual iv is tf_null_iv
const uint8_t tf_null_iv[TF_IV_SIZE] = { 0 };

typedef struct transop_tf {
    tf_context_t       *ctx;
} transop_tf_t;


static int transop_deinit_tf (n2n_trans_op_t *arg) {

    transop_tf_t *priv = (transop_tf_t *)arg->priv;

    if(priv) {
        if(priv->ctx)
            tf_deinit(priv->ctx);
        free(priv);
    }

    return 0;
}


// the Twofish packet format consists of
//
//  - a random TF_PREAMBLE_SIZE-sized value prepended to plaintext
//    encrypted together with the...
//  - ... payload data
//
//  [VV|DDDDDDDDDDDDDDDDDDDDD]
//  | <---- encrypted ---->  |
//
static int transop_encode_tf (n2n_trans_op_t *arg,
                              uint8_t *outbuf,
                              size_t out_len,
                              const uint8_t *inbuf,
                              size_t in_len,
                              const uint8_t *peer_mac) {

    transop_tf_t *priv = (transop_tf_t *)arg->priv;

    // the assembly buffer is a source for encrypting data
    // the whole contents of assembly are encrypted
    uint8_t assembly[N2N_PKT_BUF_SIZE];
    size_t idx = 0;
    int padded_len;
    uint8_t padding;
    uint8_t buf[TF_BLOCK_SIZE];

    if(in_len <= N2N_PKT_BUF_SIZE) {
        if((in_len + TF_PREAMBLE_SIZE + TF_BLOCK_SIZE) <= out_len) {
            traceEvent(TRACE_DEBUG, "transop_encode_tf %lu bytes plaintext", in_len);

            // full block sized random value (128 bit)
            *(uint64_t *)(&assembly[0]) = n3n_rand();
            *(uint64_t *)(&assembly[8]) = n3n_rand();

            // adjust for maybe differently chosen TF_PREAMBLE_SIZE
            idx = TF_PREAMBLE_SIZE;

            // the plaintext data
            memcpy((assembly + idx), inbuf, in_len);
            idx += in_len;

            // round up to next whole TF block size
            padded_len = (((idx - 1) / TF_BLOCK_SIZE) + 1) * TF_BLOCK_SIZE;
            padding = (padded_len-idx);

            // pad the following bytes with zero, fixed length (TF_BLOCK_SIZE) seems to compile
            // to slightly faster code than run-time dependant 'padding'
            memset(assembly + idx, 0, TF_BLOCK_SIZE);
            tf_cbc_encrypt(outbuf, assembly, padded_len, tf_null_iv, priv->ctx);

            if(padding) {
                // exchange last two cipher blocks
                memcpy(buf, outbuf + padded_len - TF_BLOCK_SIZE, TF_BLOCK_SIZE);
                memcpy(outbuf + padded_len - TF_BLOCK_SIZE, outbuf + padded_len - 2 * TF_BLOCK_SIZE, TF_BLOCK_SIZE);
                memcpy(outbuf + padded_len - 2 * TF_BLOCK_SIZE, buf, TF_BLOCK_SIZE);
            }
        } else
            traceEvent(TRACE_ERROR, "transop_encode_tf outbuf too small");
    } else
        traceEvent(TRACE_ERROR, "transop_encode_tf inbuf too big to encrypt");

    return idx;
}


// see transop_encode_tf for packet format
static int transop_decode_tf (n2n_trans_op_t *arg,
                              uint8_t *outbuf,
                              size_t out_len,
                              const uint8_t *inbuf,
                              size_t in_len,
                              const uint8_t *peer_mac) {


    transop_tf_t *priv = (transop_tf_t *)arg->priv;
    uint8_t assembly[N2N_PKT_BUF_SIZE];

    uint8_t rest;
    size_t penultimate_block;
    uint8_t buf[TF_BLOCK_SIZE];
    int len = -1;

    if(((in_len - TF_PREAMBLE_SIZE) <= N2N_PKT_BUF_SIZE) /* cipher text fits in assembly */
       && (in_len >= TF_PREAMBLE_SIZE)                   /* has at least random number */
       && (in_len >= TF_BLOCK_SIZE)) {                   /* minimum size requirement for cipher text stealing */

        traceEvent(TRACE_DEBUG, "transop_decode_tf %lu bytes ciphertext", in_len);

        rest = in_len % TF_BLOCK_SIZE;
        if(rest) { /* cipher text stealing */
            penultimate_block = ((in_len / TF_BLOCK_SIZE) - 1) * TF_BLOCK_SIZE;

            // everything normal up to penultimate block
            memcpy(assembly, inbuf, penultimate_block);

            // prepare new penultimate block in buf
            tf_ecb_decrypt(buf, inbuf + penultimate_block, priv->ctx);
            memcpy(buf, inbuf + in_len - rest, rest);

            // former penultimate block becomes new ultimate block
            memcpy(assembly + penultimate_block + TF_BLOCK_SIZE, inbuf + penultimate_block, TF_BLOCK_SIZE);

            // write new penultimate block from buf
            memcpy(assembly + penultimate_block, buf, TF_BLOCK_SIZE);

            // regular cbc decryption of the re-arranged ciphertext
            tf_cbc_decrypt(assembly, assembly, in_len + TF_BLOCK_SIZE - rest, tf_null_iv, priv->ctx);

            // check for expected zero padding and give a warning otherwise
            if(memcmp(assembly + in_len, tf_null_iv, TF_BLOCK_SIZE - rest)) {
                traceEvent(TRACE_WARNING, "transop_decode_tf payload decryption failed with unexpected cipher text stealing padding");
                return -1;
            }
        } else {
            // regular cbc decryption on multiple block-sized payload
            tf_cbc_decrypt(assembly, inbuf, in_len, tf_null_iv, priv->ctx);
        }
        len = in_len - TF_PREAMBLE_SIZE;
        memcpy(outbuf, assembly + TF_PREAMBLE_SIZE, len);
    } else
        traceEvent(TRACE_ERROR, "transop_decode_tf inbuf wrong size (%ul) to decrypt", in_len);

    return len;
}


static int setup_tf_key (transop_tf_t *priv, const uint8_t *password, ssize_t password_len) {

    unsigned char key[32];       /* tf key length, equals hash length */
    size_t key_size;

    // the input password always gets hashed to make a more unpredictable use of the key space
    // just think of usually reset MSB of ASCII coded password bytes
    pearson_hash_256(key, password, password_len);

    key_size = 32;                      /* 256 bit */

    // setup the key and have corresponding context created
    if(tf_init(key, key_size * 8, &(priv->ctx))) {
        traceEvent(TRACE_ERROR, "setup_tf_key %u-bit key setup unsuccessful", key_size * 8);
        return -1;
    }

    traceEvent(TRACE_DEBUG, "setup_tf_key %u-bit key setup completed", key_size * 8);

    return 0;
}


// Twofish initialization function
int n2n_transop_tf_init (const n2n_edge_conf_t *conf, n2n_trans_op_t *ttt) {

    transop_tf_t *priv;
    const u_char *encrypt_key = (const u_char *)conf->encrypt_key;
    size_t encrypt_key_len = strlen(conf->encrypt_key);

    memset(ttt, 0, sizeof(*ttt));
    ttt->transform_id = N2N_TRANSFORM_ID_TWOFISH;

    ttt->deinit       = transop_deinit_tf;
    ttt->fwd          = transop_encode_tf;
    ttt->rev          = transop_decode_tf;

    priv = (transop_tf_t*)calloc(1, sizeof(transop_tf_t));
    if(!priv) {
        traceEvent(TRACE_ERROR, "n2n_transop_tf_cbc_init cannot allocate transop_tf_t memory");
        return -1;
    }
    ttt->priv = priv;

    // setup the cipher and key
    return setup_tf_key(priv, encrypt_key, encrypt_key_len);
}

struct bench_ctx {
    transop_tf_t priv;
    // for encryption, want to be able to test the largest expected MTU + IV
    // for decryption, just need to worry about the MTU
    uint8_t iv[TF_PREAMBLE_SIZE];
    uint8_t outbuf[2048 + TF_PREAMBLE_SIZE];
    ssize_t outbuf_size;
};

static void *bench_setup (void *const _ctx) {
    struct bench_ctx *ctx = (struct bench_ctx *)_ctx;

    const char *key = "just_a_test_key_for_benchmarks";
    const ssize_t key_len = sizeof(key);
    setup_tf_key(&ctx->priv, (unsigned char *)key, key_len);

    // Set one constant IV to use for all benchmark testing
    // chosen by a fair roll of the dice
    uint8_t iv[] = {
        0x86,0xfa,0xe8,0x7a,0x5b,0xbc,0xa9,0xb7,
        0x6e,0xc7,0xdb,0xdf,0xff,0xfb,0x56,0x24,
    };
    memcpy(&ctx->iv, &iv, sizeof(iv));
    return ctx;
}

static void bench_teardown (void *_ctx) {
    struct bench_ctx *ctx = (struct bench_ctx *)_ctx;
    tf_deinit(ctx->priv.ctx);
}

static const ssize_t bench_encr_run (
    void *_ctx,
    const void *data_in,
    const ssize_t data_in_size,
    ssize_t *bytes_in
) {
    struct bench_ctx *ctx = (struct bench_ctx *)_ctx;

    // TODO: refactor to call transop_encode_cc20() directly

    uint8_t assembly[N2N_PKT_BUF_SIZE];
    uint8_t buf[TF_BLOCK_SIZE];

    // First, populate our static test "IV"
    *(uint64_t *)(&assembly[0]) = *(uint64_t *)&ctx->iv[0];
    *(uint64_t *)(&assembly[8]) = *(uint64_t *)&ctx->iv[8];

    ssize_t idx = TF_PREAMBLE_SIZE;

    // the plaintext data
    memcpy(&assembly[idx], data_in, data_in_size);
    idx += data_in_size;

    // round up to next whole TF block size
    ssize_t padded_len = (((idx - 1) / TF_BLOCK_SIZE) + 1) * TF_BLOCK_SIZE;
    ssize_t padding = (padded_len-idx);

    // Add padding
    memset(&assembly[idx], 0, TF_BLOCK_SIZE);

    tf_cbc_encrypt(
        (unsigned char *)&ctx->outbuf,
        assembly,
        padded_len,
        tf_null_iv,
        ctx->priv.ctx
    );

    if(padding) {
        // exchange last two cipher blocks
        memcpy(
            buf,
            &ctx->outbuf[padded_len - TF_BLOCK_SIZE],
            TF_BLOCK_SIZE
        );
        memcpy(
            &ctx->outbuf[padded_len - TF_BLOCK_SIZE],
            &ctx->outbuf[padded_len - 2 * TF_BLOCK_SIZE],
            TF_BLOCK_SIZE
        );
        memcpy(
            &ctx->outbuf[padded_len - 2 * TF_BLOCK_SIZE],
            buf,
            TF_BLOCK_SIZE
        );
    }

    *bytes_in = data_in_size;
    ctx->outbuf_size = padded_len;
    return ctx->outbuf_size;
}

static const ssize_t bench_decr_run (
    void *_ctx,
    const void *data_in,
    const ssize_t data_in_size,
    ssize_t *bytes_in
) {
    struct bench_ctx *ctx = (struct bench_ctx *)_ctx;

    // TODO: refactor to call transop_decode_cc20() directly

    uint8_t assembly[N2N_PKT_BUF_SIZE];
    const unsigned char *bytes = (unsigned char *)data_in;

    uint8_t rest = data_in_size % TF_BLOCK_SIZE;
    if(rest) { /* cipher text stealing */
        uint8_t buf[TF_BLOCK_SIZE];
        ssize_t penultimate_block =
            ((data_in_size / TF_BLOCK_SIZE) - 1) * TF_BLOCK_SIZE;

        // everything normal up to penultimate block
        memcpy(assembly, bytes, penultimate_block);

        // prepare new penultimate block in buf
        tf_ecb_decrypt(buf, &bytes[penultimate_block], ctx->priv.ctx);
        memcpy(buf, &bytes[data_in_size - rest], rest);

        // former penultimate block becomes new ultimate block
        memcpy(
            &assembly[penultimate_block + TF_BLOCK_SIZE],
            &bytes[penultimate_block],
            TF_BLOCK_SIZE
        );

        // write new penultimate block from buf
        memcpy(&assembly[penultimate_block], buf, TF_BLOCK_SIZE);

        // regular cbc decryption of the re-arranged ciphertext
        tf_cbc_decrypt(
            assembly,
            assembly,
            data_in_size + TF_BLOCK_SIZE - rest,
            tf_null_iv,
            ctx->priv.ctx
        );

        // check for expected zero padding and give a warning otherwise
        if(memcmp(&assembly[data_in_size], tf_null_iv, TF_BLOCK_SIZE - rest)) {
            traceEvent(TRACE_WARNING, "transop_decode_aes payload decryption failed with unexpected cipher text stealing padding");
            exit(1);
        }
    } else {
        // regular cbc decryption on multiple block-sized payload
        tf_cbc_decrypt(
            assembly,
            data_in,
            data_in_size,
            tf_null_iv,
            ctx->priv.ctx
        );
    }
    ctx->outbuf_size = data_in_size - TF_PREAMBLE_SIZE;
    memcpy(ctx->outbuf, &assembly[TF_PREAMBLE_SIZE], ctx->outbuf_size);

    *bytes_in = data_in_size;
    return ctx->outbuf_size;
}

static const void *const bench_get_output (void *const _ctx) {
    struct bench_ctx *ctx = (struct bench_ctx *)_ctx;
    return &ctx->outbuf;
}

static struct bench_item bench_encr = {
    .name = "tf_encr",
    .ctx_size = sizeof(struct bench_ctx),
    .setup = bench_setup,
    .run = bench_encr_run,
    .get_output = bench_get_output,
    .teardown = bench_teardown,
    .data_in = test_data_32x16,
    .data_out = test_data_tf,
};

static struct bench_item bench_decr = {
    .name = "tf_decr",
    .ctx_size = sizeof(struct bench_ctx),
    .setup = bench_setup,
    .run = bench_decr_run,
    .get_output = bench_get_output,
    .teardown = bench_teardown,
    .data_in = test_data_tf,
    .data_out = test_data_32x16,
};

static struct n3n_transform transform = {
    .name = "Twofish",
    .id = N2N_TRANSFORM_ID_TWOFISH,
};

void n3n_initfuncs_transform_twofish () {
    n3n_transform_register(&transform);
    n3n_benchmark_register(&bench_decr);
    n3n_benchmark_register(&bench_encr);
}
