aboutsummaryrefslogtreecommitdiff
path: root/src/zenhorde/hordetransportaes.h
blob: a1800c684cc9ffb5afa37123987fa27c0349a9ef (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "hordetransport.h"

#include <cstdint>
#include <memory>
#include <vector>

namespace asio {
class io_context;
}

namespace zen::horde {

/** Async AES-256-GCM encrypted transport wrapper.
 *
 *  Wraps an AsyncComputeTransport, encrypting outgoing and decrypting incoming
 *  data using AES-256-GCM. The nonce is mutated per message using the Horde
 *  nonce mangling scheme: n32[0]++; n32[1]--; n32[2] = n32[0] ^ n32[1].
 *
 *  Wire format per encrypted message:
 *    [plaintext length (4B little-endian)][nonce (12B)][ciphertext][GCM tag (16B)]
 *
 *  Uses BCrypt on Windows and OpenSSL EVP on Linux/macOS (selected at compile time).
 *
 *  Thread safety: all operations must be serialized by the caller (e.g. via a strand).
 */
class AsyncAesComputeTransport final : public AsyncComputeTransport
{
public:
	AsyncAesComputeTransport(const uint8_t (&Key)[KeySize],
							 std::unique_ptr<AsyncComputeTransport> InnerTransport,
							 asio::io_context&						IoContext);
	~AsyncAesComputeTransport() override;

	bool IsValid() const override;
	void AsyncWrite(const void* Data, size_t Size, AsyncIoHandler Handler) override;
	void AsyncRead(void* Data, size_t Size, AsyncIoHandler Handler) override;
	void Close() override;

private:
	void DoRecvMessage(uint8_t* Dest, size_t Size, AsyncIoHandler Handler);

	struct CryptoContext;

	std::unique_ptr<CryptoContext>		   m_Crypto;
	std::unique_ptr<AsyncComputeTransport> m_Inner;
	asio::io_context&					   m_IoContext;
	std::vector<uint8_t>				   m_EncryptBuffer;
	std::vector<uint8_t>				   m_DecryptBuffer;
	std::vector<uint8_t>				   m_RemainingData;
	size_t								   m_RemainingOffset = 0;
	bool								   m_IsClosed		 = false;
};

}  // namespace zen::horde