summaryrefslogtreecommitdiff
path: root/src/channel.cpp
blob: f5cfb9c93bb447ebf429717a220d20b034c04f07 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#include "channel.h"

#include <algorithm>
#include <stdexcept>

using std::remove_const;
using std::runtime_error;

using namespace erebos;

Ref ChannelRequestData::store(const Storage & st) const
{
	vector<Record::Item> items;

	for (const auto & p : peers)
		items.emplace_back("peer", p);
	items.emplace_back("enc", "aes-128-gcm");
	items.emplace_back("key", key);

	return st.storeObject(Record(std::move(items)));
}

ChannelRequestData ChannelRequestData::load(const Ref & ref)
{
	if (auto rec = ref->asRecord()) {
		remove_const<decltype(peers)>::type peers;
		for (const auto & i : rec->items("peer"))
			if (auto p = i.as<Signed<IdentityData>>())
				peers.push_back(*p);

		if (rec->item("enc").asText() == "aes-128-gcm")
			if (auto key = rec->item("key").as<PublicKexKey>())
				return ChannelRequestData {
					.peers = std::move(peers),
					.key = *key,
				};
	}

	return ChannelRequestData {
		.peers = {},
		.key = Stored<PublicKexKey>::load(ref.storage().zref()),
	};
}

Ref ChannelAcceptData::store(const Storage & st) const
{
	vector<Record::Item> items;

	items.emplace_back("req", request);
	items.emplace_back("enc", "aes-128-gcm");
	items.emplace_back("key", key);

	return st.storeObject(Record(std::move(items)));
}

ChannelAcceptData ChannelAcceptData::load(const Ref & ref)
{
	if (auto rec = ref->asRecord())
		if (rec->item("enc").asText() == "aes-128-gcm")
			return ChannelAcceptData {
				.request = *rec->item("req").as<ChannelRequest>(),
				.key = *rec->item("key").as<PublicKexKey>(),
			};

	return ChannelAcceptData {
		.request = Stored<ChannelRequest>::load(ref.storage().zref()),
		.key = Stored<PublicKexKey>::load(ref.storage().zref()),
	};
}

unique_ptr<Channel> ChannelAcceptData::channel() const
{
	if (auto secret = SecretKexKey::load(key))
		return make_unique<Channel>(
			request->data->peers,
			secret->dh(*request->data->key),
			false
		);

	if (auto secret = SecretKexKey::load(request->data->key))
		return make_unique<Channel>(
			request->data->peers,
			secret->dh(*key),
			true
		);

	throw runtime_error("failed to load secret DH key");
}


Stored<ChannelRequest> Channel::generateRequest(const Storage & st,
		const Identity & self, const Identity & peer)
{
	auto signKey = SecretKey::load(self.keyMessage());
	if (!signKey)
		throw runtime_error("failed to load own message key");

	return signKey->sign(st.store(ChannelRequestData {
		.peers = self.ref()->digest() < peer.ref()->digest() ?
			vector<Stored<Signed<IdentityData>>> {
				Stored<Signed<IdentityData>>::load(*self.ref()),
				Stored<Signed<IdentityData>>::load(*peer.ref()),
			} :
			vector<Stored<Signed<IdentityData>>> {
				Stored<Signed<IdentityData>>::load(*peer.ref()),
				Stored<Signed<IdentityData>>::load(*self.ref()),
			},
		.key = SecretKexKey::generate(st).pub(),
	}));
}

optional<Stored<ChannelAccept>> Channel::acceptRequest(const Identity & self,
		const Identity & peer, const Stored<ChannelRequest> & request)
{
	if (!request->isSignedBy(peer.keyMessage()))
		return nullopt;

	auto & peers = request->data->peers;
	if (peers.size() != 2 ||
			std::none_of(peers.begin(), peers.end(), [&self](const auto & x)
				{ return x.ref().digest() == self.ref()->digest(); }) ||
			std::none_of(peers.begin(), peers.end(), [&peer](const auto & x)
				{ return x.ref().digest() == peer.ref()->digest(); }))
		return nullopt;

	auto & st = request.ref().storage();

	auto signKey = SecretKey::load(self.keyMessage());
	if (!signKey)
		throw runtime_error("failed to load own message key");

	return signKey->sign(st.store(ChannelAcceptData {
		.request = request,
		.key = SecretKexKey::generate(st).pub(),
	}));
}

vector<uint8_t> Channel::encrypt(const vector<uint8_t> & plain)
{
	vector<uint8_t> res(plain.size() + 8 + 16 + 16);
	array<uint8_t, 12> iv;

	uint64_t beCount = htobe64(nonceCounter++);
	std::copy_n(&beCount, 6, res.begin());
	std::copy_n(nonceFixedOur.begin(), 6, iv.begin());
	std::copy_n(res.begin() + 2, 6, iv.begin() + 6);

	const unique_ptr<EVP_CIPHER_CTX, void(*)(EVP_CIPHER_CTX*)>
		ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
	EVP_EncryptInit_ex(ctx.get(), EVP_aes_128_gcm(),
			nullptr, key.data(), iv.data());

	int outl = 0;
	uint8_t * cur = res.data() + 8;

	if (EVP_EncryptUpdate(ctx.get(), cur, &outl, plain.data(), plain.size()) != 1)
		throw runtime_error("failed to encrypt data");
	cur += outl;

	if (EVP_EncryptFinal(ctx.get(), cur, &outl) != 1)
		throw runtime_error("failed to encrypt data");
	cur += outl;

	EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, 16, cur);
	cur += 16;

	res.resize(cur - res.data());
	return res;
}

optional<vector<uint8_t>> Channel::decrypt(const vector<uint8_t> & ctext)
{
	vector<uint8_t> res(ctext.size());
	array<uint8_t, 12> iv;

	std::copy_n(nonceFixedPeer.begin(), 6, iv.begin());
	std::copy_n(ctext.begin() + 2, 6, iv.begin() + 6);

	const unique_ptr<EVP_CIPHER_CTX, void(*)(EVP_CIPHER_CTX*)>
		ctx(EVP_CIPHER_CTX_new(), EVP_CIPHER_CTX_free);
	EVP_DecryptInit_ex(ctx.get(), EVP_aes_128_gcm(),
			nullptr, key.data(), iv.data());

	int outl = 0;
	uint8_t * cur = res.data();

	if (EVP_DecryptUpdate(ctx.get(), cur, &outl,
				ctext.data() + 8, ctext.size() - 8 - 16) != 1)
		return nullopt;
	cur += outl;

	if (!EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, 16,
				(void *) (ctext.data() + ctext.size() - 16)))
		return nullopt;

	if (EVP_DecryptFinal_ex(ctx.get(), cur, &outl) != 1)
		return nullopt;
	cur += outl;

	res.resize(cur - res.data());
	return res;
}