/*

Copyright (c) 2007, Un Shyam
Copyright (c) 2011, 2014-2016, 2018-2022, Arvid Norberg
Copyright (c) 2016-2018, 2021, Alden Torres
Copyright (c) 2016, Andrei Kurushin
Copyright (c) 2016, 2018, Steven Siloti
All rights reserved.

You may use, distribute and modify this code under the terms of the BSD license,
see LICENSE file.
*/

#if !defined TORRENT_DISABLE_ENCRYPTION

#include <cstdint>
#include <cstring>
#include <algorithm>
#include <random>
#include <utility>

#if !defined TORRENT_USE_LIBCRYPTO || defined TORRENT_USE_WOLFSSL
#include "libtorrent/aux_/disable_warnings_push.hpp"
#include <boost/multiprecision/integer.hpp>
#include "libtorrent/aux_/disable_warnings_pop.hpp"
#endif

#if defined TORRENT_USE_LIBCRYPTO && !defined TORRENT_USE_WOLFSSL \
	&& defined BOOST_NO_CXX11_THREAD_LOCAL
#include <mutex>
#endif

#include "libtorrent/aux_/random.hpp"
#include "libtorrent/aux_/alloca.hpp"
#include "libtorrent/aux_/pe_crypto.hpp"
#include "libtorrent/aux_/throw.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/hasher.hpp"

#if defined TORRENT_USE_LIBCRYPTO && !defined TORRENT_USE_WOLFSSL \
	&& defined BOOST_NO_CXX11_THREAD_LOCAL
namespace {
	// if BN_CTX can't be thread_local, fall back to a single shared
	// instance protected by a mutex (see src/random.cpp for the same
	// fallback pattern used for the RNG state).
	std::mutex g_bn_ctx_mutex;
}
#endif

namespace libtorrent::aux {

#if defined TORRENT_USE_LIBCRYPTO && !defined TORRENT_USE_WOLFSSL

	dh_key_exchange::key_t const& dh_key_exchange::dh_prime()
	{
		static key_t const prime = [] {
			BIGNUM* p = nullptr;
			BN_hex2bn(&p,
				"FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B2251"
				"4A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C"
				"42E9A63A36210000000000090563");
			return key_t(p);
		}();
		return prime;
	}

	dh_key_exchange::key_t const& dh_key_exchange::two()
	{
		static key_t const val = [] {
			key_t v;
			if (!BN_set_word(v.get(), 2))
				aux::throw_ex<system_error>(errors::no_memory);
			return v;
		}();
		return val;
	}

	dh_key_exchange::key_t const& dh_key_exchange::dh_prime_minus_1()
	{
		static key_t const val = [] {
			key_t one;
			if (!BN_set_word(one.get(), 1))
				aux::throw_ex<system_error>(errors::no_memory);
			key_t v;
			if (!BN_sub(v.get(), dh_prime().get(), one.get()))
				aux::throw_ex<system_error>(errors::no_memory);
			return v;
		}();
		return val;
	}

	::BN_CTX* dh_key_exchange::ctx()
	{
		auto make_ctx = [] {
			std::unique_ptr<::BN_CTX, void (*)(::BN_CTX*)> ret(BN_CTX_new(), &BN_CTX_free);
			if (!ret)
				aux::throw_ex<system_error>(errors::no_memory);
			return ret;
		};
#ifdef BOOST_NO_CXX11_THREAD_LOCAL
		static std::unique_ptr<::BN_CTX, void (*)(::BN_CTX*)> shared_ctx = make_ctx();
#else
		thread_local static std::unique_ptr<::BN_CTX, void (*)(::BN_CTX*)> shared_ctx = make_ctx();
#endif
		return shared_ctx.get();
	}

	::BN_MONT_CTX* dh_key_exchange::mont()
	{
		auto make_mont = [] {
			std::unique_ptr<::BN_MONT_CTX, void (*)(::BN_MONT_CTX*)> ret(
				BN_MONT_CTX_new(), &BN_MONT_CTX_free);
			if (!ret || !BN_MONT_CTX_set(ret.get(), dh_prime().get(), ctx()))
				aux::throw_ex<system_error>(errors::no_memory);
			return ret;
		};
#ifdef BOOST_NO_CXX11_THREAD_LOCAL
		static std::unique_ptr<::BN_MONT_CTX, void (*)(::BN_MONT_CTX*)> shared_mont = make_mont();
#else
		thread_local static std::unique_ptr<::BN_MONT_CTX, void (*)(::BN_MONT_CTX*)> shared_mont =
			make_mont();
#endif
		return shared_mont.get();
	}

	std::array<char, 96> dh_key_exchange::export_key(key_t const& k)
	{
		std::array<char, 96> ret;
		auto* begin = reinterpret_cast<unsigned char*>(ret.data());
		int const len = BN_bn2bin(k.get(), begin);

		// TODO: it would be nice to be able to export to a fixed width field, so
		// we wouldn't have to shift it later
		if (len < 96)
		{
			std::memmove(begin + 96 - len, begin, aux::numeric_cast<std::size_t>(len));
			std::memset(begin, 0, aux::numeric_cast<std::size_t>(96 - len));
		}
		return ret;
	}

	// Set the prime P and the generator, generate local public key
	dh_key_exchange::dh_key_exchange()
	{
		aux::array<std::uint8_t, 20> random_key;
		aux::random_bytes({reinterpret_cast<char*>(random_key.data()),
			static_cast<std::ptrdiff_t>(random_key.size())});

		// create local key (random)
		if (!BN_bin2bn(random_key.data(), int(random_key.size()), m_dh_local_secret.get()))
			aux::throw_ex<system_error>(errors::no_memory);

		// key = (2 ^ secret) % prime
		key_t local_key;

		{
#ifdef BOOST_NO_CXX11_THREAD_LOCAL
			std::lock_guard<std::mutex> l(g_bn_ctx_mutex);
#endif
			if (!BN_mod_exp_mont(local_key.get(),
					two().get(),
					m_dh_local_secret.get(),
					dh_prime().get(),
					ctx(),
					mont()))
				aux::throw_ex<system_error>(errors::no_memory);
		}
		m_dh_local_key = export_key(local_key);
	}

	// compute shared secret given remote public key
	bool dh_key_exchange::compute_secret(std::uint8_t const* remote_pubkey)
	{
		TORRENT_ASSERT(remote_pubkey);
		key_t key;
		if (!BN_bin2bn(remote_pubkey, 96, key.get()))
			aux::throw_ex<system_error>(errors::no_memory);

		// reject degenerate public keys. Any value outside [2, p-2] produces
		// a shared secret in a small subgroup (0, 1, or +/-1), which
		// effectively defeats the key exchange and would allow a
		// man-in-the-middle to fix the shared secret.
		if (BN_cmp(key.get(), two().get()) < 0 || BN_cmp(key.get(), dh_prime_minus_1().get()) >= 0)
			return false;

		// shared_secret = (remote_pubkey ^ local_secret) % prime
		key_t secret;
		{
#ifdef BOOST_NO_CXX11_THREAD_LOCAL
			std::lock_guard<std::mutex> l(g_bn_ctx_mutex);
#endif
			if (!BN_mod_exp_mont(secret.get(),
					key.get(),
					m_dh_local_secret.get(),
					dh_prime().get(),
					ctx(),
					mont()))
				aux::throw_ex<system_error>(errors::no_memory);
		}
		m_dh_shared_secret = export_key(secret);

		static char const req3[4] = {'r', 'e', 'q', '3'};
		// calculate the xor mask for the obfuscated hash
		m_xor_mask = hasher(req3).update(m_dh_shared_secret).final();
		return true;
	}

#else // TORRENT_USE_LIBCRYPTO

	dh_key_exchange::key_t const& dh_key_exchange::dh_prime()
	{
		// TODO: it would be nice to get the literal working
		static key_t const prime(
			"0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A"
			"08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A6"
			"3A36210000000000090563");
		return prime;
	}

	std::array<char, 96> dh_key_exchange::export_key(key_t const& k)
	{
		std::array<char, 96> ret;
		auto* begin = reinterpret_cast<std::uint8_t*>(ret.data());
		std::uint8_t* end = mp::export_bits(k, begin, 8);

		// TODO: it would be nice to be able to export to a fixed width field, so
		// we wouldn't have to shift it later
		if (end < begin + 96)
		{
			int const len = int(end - begin);
#if defined __GNUC__ && __GNUC__ == 12
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-overflow"
#endif
			std::memmove(begin + 96 - len, begin, aux::numeric_cast<std::size_t>(len));
#if defined __GNUC__ && __GNUC__ == 12
#pragma GCC diagnostic pop
#endif
			std::memset(begin, 0, aux::numeric_cast<std::size_t>(96 - len));
		}
		return ret;
	}

	// Set the prime P and the generator, generate local public key
	dh_key_exchange::dh_key_exchange()
	{
		aux::array<std::uint8_t, 20> random_key;
		aux::random_bytes({reinterpret_cast<char*>(random_key.data())
			, static_cast<std::ptrdiff_t>(random_key.size())});

		// create local key (random)
		mp::import_bits(m_dh_local_secret, random_key.begin(), random_key.end());

		// key = (2 ^ secret) % prime
		key_t const local_key = mp::powm(key_t(2), m_dh_local_secret, dh_prime());
		m_dh_local_key = export_key(local_key);
	}

	// compute shared secret given remote public key
	bool dh_key_exchange::compute_secret(std::uint8_t const* remote_pubkey)
	{
		TORRENT_ASSERT(remote_pubkey);
		key_t key;
		mp::import_bits(key, remote_pubkey, remote_pubkey + 96);

		// reject degenerate public keys. Any value outside [2, p-2] produces
		// a shared secret in a small subgroup (0, 1, or +/-1), which
		// effectively defeats the key exchange and would allow a
		// man-in-the-middle to fix the shared secret.
		if (key < key_t(2) || key >= dh_prime() - 1)
			return false;

		// shared_secret = (remote_pubkey ^ local_secret) % prime
		key_t const secret = mp::powm(key, m_dh_local_secret, dh_prime());
		m_dh_shared_secret = export_key(secret);

		static char const req3[4] = {'r', 'e', 'q', '3'};
		// calculate the xor mask for the obfuscated hash
		m_xor_mask = hasher(req3).update(m_dh_shared_secret).final();
		return true;
	}

#endif // TORRENT_USE_LIBCRYPTO

	void rc4_init(const unsigned char* in, std::size_t len, rc4* state);
	std::size_t rc4_encrypt(unsigned char* out, std::size_t outlen, rc4* state);

	std::tuple<int, span<span<char const>>>
	encryption_handler::encrypt(
		span<span<char>> iovec)
	{
		TORRENT_ASSERT(!m_send_barriers.empty());
		TORRENT_ASSERT(m_send_barriers.front().enc_handler);

		int to_process = m_send_barriers.front().next;

		span<span<char>> bufs;
		bool need_destruct = false;
		if (to_process != INT_MAX)
		{
			TORRENT_ALLOCA(abufs, span<char>, iovec.size());
			bufs = abufs;
			need_destruct = true;
			int num_bufs = 0;
			for (int i = 0; to_process > 0 && i < iovec.size(); ++i)
			{
				++num_bufs;
				int const size = int(iovec[i].size());
				if (to_process < size)
				{
					new (&bufs[i]) span<char>(
						iovec[i].data(), to_process);
					to_process = 0;
				}
				else
				{
					new (&bufs[i]) span<char>(iovec[i]);
					to_process -= size;
				}
			}
			bufs = bufs.first(num_bufs);
		}
		else
		{
			bufs = iovec;
		}

		int next_barrier = 0;
		span<span<char const>> out_iovec;
		if (!bufs.empty())
		{
			std::tie(next_barrier, out_iovec)
				= m_send_barriers.front().enc_handler->encrypt(bufs);
		}

		if (m_send_barriers.front().next != INT_MAX)
		{
			// to_process holds the difference between the size of the buffers
			// and the bytes left to the next barrier
			// if it's zero then pop the barrier
			// otherwise update the number of bytes remaining to the next barrier
			if (to_process == 0)
			{
				if (m_send_barriers.size() == 1)
				{
					// transitioning back to plaintext
					next_barrier = INT_MAX;
				}
				m_send_barriers.pop_front();
			}
			else
			{
				m_send_barriers.front().next = to_process;
			}
		}

#if TORRENT_USE_ASSERTS
		if (next_barrier != INT_MAX && next_barrier != 0)
		{
			int payload = 0;
			for (auto buf : bufs)
				payload += int(buf.size());

			int overhead = 0;
			for (auto buf : out_iovec)
				overhead += int(buf.size());
			TORRENT_ASSERT(overhead + payload == next_barrier);
		}
#endif
		if (need_destruct)
		{
			for (auto buf : bufs)
				buf.~span<char>();
		}
		return std::make_tuple(next_barrier, out_iovec);
	}

	int encryption_handler::decrypt(aux::crypto_receive_buffer& recv_buffer
		, std::size_t& bytes_transferred)
	{
		TORRENT_ASSERT(!is_recv_plaintext());
		int consume = 0;
		if (recv_buffer.crypto_packet_finished())
		{
			span<char> wr_buf = recv_buffer.mutable_buffer(int(bytes_transferred));
			int produce = 0;
			int packet_size = 0;
			std::tie(consume, produce, packet_size) = m_dec_handler->decrypt(wr_buf);
			TORRENT_ASSERT(packet_size || produce);
			TORRENT_ASSERT(packet_size >= 0);
			TORRENT_ASSERT(produce >= 0);
			bytes_transferred = std::size_t(produce);
			if (packet_size)
				recv_buffer.crypto_cut(consume, packet_size);
		}
		else
			bytes_transferred = 0;
		return consume;
	}

	bool encryption_handler::switch_send_crypto(std::shared_ptr<crypto_plugin> crypto
		, int pending_encryption)
	{
		bool place_barrier = false;
		if (!m_send_barriers.empty())
		{
			auto const end = std::prev(m_send_barriers.end());
			for (auto b = m_send_barriers.begin(); b != end; ++b)
				pending_encryption -= b->next;
			TORRENT_ASSERT(pending_encryption >= 0);
			m_send_barriers.back().next = pending_encryption;
		}
		else if (crypto)
			place_barrier = true;

		if (crypto)
			m_send_barriers.emplace_back(crypto, INT_MAX);

		return place_barrier;
	}

	void encryption_handler::switch_recv_crypto(std::shared_ptr<crypto_plugin> crypto
		, aux::crypto_receive_buffer& recv_buffer)
	{
		m_dec_handler = crypto;
		int packet_size = 0;
		if (crypto)
		{
			int consume = 0;
			int produce = 0;
			std::vector<span<char>> wr_buf;
			std::tie(consume, produce, packet_size) = crypto->decrypt(wr_buf);
			TORRENT_ASSERT(wr_buf.empty());
			TORRENT_ASSERT(consume == 0);
			TORRENT_ASSERT(produce == 0);
		}
		recv_buffer.crypto_reset(packet_size);
	}

	void rc4_handler::set_incoming_key(span<char const> key)
	{
		m_decrypt = true;
		rc4_init(reinterpret_cast<unsigned char const*>(key.data())
			, std::size_t(key.size()), &m_rc4_incoming);
		// Discard first 1024 bytes
		char buf[1024];
		span<char> vec(buf, sizeof(buf));
		decrypt(vec);
	}

	void rc4_handler::set_outgoing_key(span<char const> key)
	{
		m_encrypt = true;
		rc4_init(reinterpret_cast<unsigned char const*>(key.data())
			, std::size_t(key.size()), &m_rc4_outgoing);
		// Discard first 1024 bytes
		char buf[1024];
		span<char> vec(buf, sizeof(buf));
		encrypt(vec);
	}

	std::tuple<int, span<span<char const>>>
	rc4_handler::encrypt(span<span<char>> bufs)
	{
		span<span<char const>> empty;
		if (!m_encrypt) return std::make_tuple(0, empty);
		if (bufs.empty()) return std::make_tuple(0, empty);

		int bytes_processed = 0;
		for (auto& buf : bufs)
		{
			int const len = int(buf.size());

			TORRENT_ASSERT(len >= 0);
			if (len == 0) continue;

			auto* const pos = reinterpret_cast<unsigned char*>(buf.data());
			TORRENT_ASSERT(pos);

			bytes_processed += len;
			rc4_encrypt(pos, std::uint32_t(len), &m_rc4_outgoing);
		}
		return std::make_tuple(bytes_processed, empty);
	}

	std::tuple<int, int, int> rc4_handler::decrypt(span<span<char>> bufs)
	{
		if (!m_decrypt) return std::make_tuple(0, 0, 0);

		int bytes_processed = 0;
		for (auto& buf : bufs)
		{
			auto* const pos = reinterpret_cast<unsigned char*>(buf.data());
			int const len = int(buf.size());

			TORRENT_ASSERT(len >= 0);
			TORRENT_ASSERT(pos);

			bytes_processed += len;
			rc4_encrypt(pos, std::uint32_t(len), &m_rc4_incoming);
		}
		return std::make_tuple(0, bytes_processed, 0);
	}

// All this code is based on libTomCrypt (http://www.libtomcrypt.com/)
// this library is public domain and has been specially
// tailored for libtorrent by Arvid Norberg

	void rc4_init(unsigned char const* in, std::size_t len, rc4* state)
	{
		constexpr std::size_t key_size = 256;

		TORRENT_ASSERT(state != nullptr);
		TORRENT_ASSERT(len > 0);
		TORRENT_ASSERT(len <= key_size);
		if (len > key_size)
			len = key_size;

		// make RC4 perm and shuffle. the key is read directly out of "in"
		// (wrapping every keylen bytes), instead of first being copied byte by
		// byte into state->buf and then back out again
		for (int i = 0; i < int(key_size); ++i)
			state->buf[i] = std::uint32_t(i);

		// skip mixing the key in for len == 0, rather than dereferencing
		// "in" (an empty span's data() pointer isn't guaranteed to point
		// at valid memory). buf is left as the identity permutation --
		// not meaningful RC4 state, but safe
		if (len > 0)
		{
			int j = 0;
			for (int i = 0; i < int(key_size); ++i)
			{
				j = (j + int(state->buf[i]) + int(in[i % int(len)])) & 0xff;
				std::swap(state->buf[i], state->buf[j]);
			}
		}
		state->x = 0;
		state->y = 0;
	}

	std::size_t rc4_encrypt(unsigned char* out, std::size_t outlen, rc4* state)
	{
		TORRENT_ASSERT(out != nullptr);
		TORRENT_ASSERT(state != nullptr);

		std::size_t const n = outlen;
		auto x = std::uint8_t(state->x);
		auto y = std::uint8_t(state->y);
		std::uint32_t* const s = state->buf.data();

		auto const step = [&]() -> std::uint8_t {
			x = std::uint8_t(x + 1);
			y = std::uint8_t(y + s[x]);
			std::swap(s[x], s[y]);
			auto const idx = std::uint8_t(s[x] + s[y]);
			return std::uint8_t(s[idx]);
		};

		// generate 8 keystream bytes at a time into a local buffer, and XOR
		// them against the output in a single 64-bit operation, rather than
		// doing a separate byte-sized load/xor/store for every output byte
		while (outlen >= 8)
		{
			// write each keystream byte directly into keystream's own
			// storage (well-defined: any object's representation can be
			// written through an unsigned char pointer) instead of
			// staging it through a separate array and a second memcpy.
			// this preserves byte position exactly like memcpy does, so
			// it doesn't depend on host endianness
			std::uint64_t keystream;
			auto* const ks = reinterpret_cast<unsigned char*>(&keystream);
			for (int i = 0; i < 8; ++i)
				ks[i] = step();

			std::uint64_t block;
			std::memcpy(&block, out, 8);
			block ^= keystream;
			std::memcpy(out, &block, 8);

			out += 8;
			outlen -= 8;
		}

		while (outlen--)
			*out++ ^= step();

		state->x = x;
		state->y = y;
		return n;
	}

} // namespace libtorrent::aux

#endif // TORRENT_DISABLE_ENCRYPTION
