-
Notifications
You must be signed in to change notification settings - Fork 405
/
Copy pathcrypto_aead.hpp
414 lines (346 loc) · 13.3 KB
/
crypto_aead.hpp
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
// OpenVPN AEAD data channel interface
#ifndef OPENVPN_CRYPTO_CRYPTO_AEAD_H
#define OPENVPN_CRYPTO_CRYPTO_AEAD_H
#include <cstring> // for std::memcpy, std::memset
#include <openvpn/common/size.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/clamp_typerange.hpp>
#include <openvpn/buffer/buffer.hpp>
#include <openvpn/frame/frame.hpp>
#include <openvpn/crypto/static_key.hpp>
#include <openvpn/crypto/packet_id_data.hpp>
#include <openvpn/log/sessionstats.hpp>
#include <openvpn/crypto/cryptodc.hpp>
// Sample AES-GCM head:
// 48000001 00000005 7e7046bd 444a7e28 cc6387b1 64a4d6c1 380275a...
// [ OP32 ] [seq # ] [ auth tag ] [ payload ... ]
// [4-byte
// IV head]
using openvpn::numeric_util::clamp_to_default;
namespace openvpn::AEAD {
OPENVPN_EXCEPTION(aead_error);
template <typename CRYPTO_API>
class Crypto : public CryptoDCInstance
{
class Nonce
{
public:
Nonce()
{
static_assert(4 + CRYPTO_API::CipherContextAEAD::IV_LEN == sizeof(data),
"AEAD IV_LEN inconsistency");
ad_op32 = false;
std::memset(data, 0, sizeof(data));
}
/**
* Sets the IV tail for AEAD operations
*
* The IV for AEAD ciphers (both AES-GCM and Chacha20-Poly1305) consists of 96 bits/12 bytes
* (It then gets concatenated with internal 32 bits for block counter to form a 128 bit counter for the
* encryption).
*
* Since we only use 4 bytes (32 bit packet ID) or 8 bytes (64 bit packet ID) on the wire, we
* fill out the rest of the IV with pseudorandom bytes that come from of the negotiated key for the
* HMAC key (this key is not used by AEAD ciphers, so we reuse it for this purpose in AEAD mode).
*/
void set_tail(const StaticKey &sk, bool use64bitcounter)
{
size_t implicit_iv_len = use64bitcounter ? 4 : 8;
if (sk.size() < implicit_iv_len)
throw aead_error("insufficient key material for nonce tail");
/* 4 bytes opcode + 4-8 bytes on wire IV */
size_t implicit_iv_offset = data_offset_pkt_id + (12 - implicit_iv_len);
std::memcpy(data + implicit_iv_offset, sk.data(), implicit_iv_len);
}
// for encrypt
Nonce(const Nonce &ref, PacketIDDataSend &pid_send, const unsigned char *op32)
{
/** Copy op code and tail of packet ID */
std::memcpy(data, ref.data, sizeof(data));
Buffer buf(data + data_offset_pkt_id, PacketIDData::long_id_size, false);
pid_send.write_next(buf);
if (op32)
{
ad_op32 = true;
std::memcpy(data, op32, op32_size);
}
else
ad_op32 = false;
}
// for encrypt
void prepend_ad(Buffer &buf, const PacketIDDataSend &pid_send) const
{
buf.prepend(data + data_offset_pkt_id, pid_send.length());
}
// for decrypt
Nonce(const Nonce &ref, const PacketIDDataReceive &recv_pid, Buffer &buf, const unsigned char *op32)
{
/* Copy opcode and tail of packet ID */
std::memcpy(data, ref.data, sizeof(data));
/* copy dynamic packet of IV into */
buf.read(data + data_offset_pkt_id, recv_pid.length());
if (op32)
{
ad_op32 = true;
std::memcpy(data, op32, op32_size);
}
else
ad_op32 = false;
}
// for decrypt
bool verify_packet_id(PacketIDDataReceive &pid_recv, const PacketIDControl::time_t now)
{
Buffer buf(data + data_offset_pkt_id, PacketIDData::long_id_size, true);
const PacketIDData pid = pid_recv.read_next(buf);
return pid_recv.test_add(pid, now); // verify packet ID
}
const unsigned char *iv() const
{
return data + data_offset_pkt_id;
}
const unsigned char *ad() const
{
return ad_op32 ? data : data + data_offset_pkt_id;
}
size_t ad_len(const PacketIDDataSend &pid_send) const
{
return (ad_op32 ? op32_size : 0) + pid_send.length();
}
size_t ad_len(const PacketIDDataReceive &pid_recv) const
{
return (ad_op32 ? op32_size : 0) + pid_recv.length();
}
private:
bool ad_op32; // true if AD (authenticated data) includes op32 opcode
// Sample data:
// [ OP32 (optional) ] [ pkt ID ] [ nonce tail ]
// [ 48 00 00 01 ] [ 00 00 00 05 ] [ 7f 45 64 db 33 5b 6c 29 ]
unsigned char data[16];
static constexpr std::size_t data_offset_pkt_id = 4;
static constexpr std::size_t op32_size = 4;
};
struct Encrypt
{
typename CRYPTO_API::CipherContextAEAD impl;
Nonce nonce;
PacketIDDataSend pid_send{false};
BufferAllocated work;
};
struct Decrypt
{
typename CRYPTO_API::CipherContextAEAD impl;
Nonce nonce;
PacketIDDataReceive pid_recv{};
BufferAllocated work;
};
public:
typedef CryptoDCInstance Base;
Crypto(SSLLib::Ctx libctx_arg,
CryptoDCSettingsData dc_settings_data,
const Frame::Ptr &frame_arg,
const SessionStats::Ptr &stats_arg)
: dc_settings(dc_settings_data),
frame(frame_arg),
stats(stats_arg),
libctx(libctx_arg)
{
}
// Encrypt/Decrypt
// returns true if packet ID is close to wrapping
bool encrypt(BufferAllocated &buf, const unsigned char *op32) override
{
// only process non-null packets
if (buf.size())
{
// build nonce/IV/AD
Nonce nonce(e.nonce, e.pid_send, op32);
// encrypt to work buf
frame->prepare(Frame::ENCRYPT_WORK, e.work);
if (e.work.max_size() < buf.size())
throw aead_error("encrypt work buffer too small");
unsigned char *work_data = e.work.write_alloc(buf.size());
unsigned char *auth_tag;
unsigned char *auth_tag_tmp = nullptr;
// alloc auth tag in buffer where it needs to be
// Create a temporary auth tag at the end if the implementation and mode require it
if (dc_settings.aeadTagAtTheEnd())
{
auth_tag = e.work.write_alloc(CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
}
else
{
auth_tag = e.work.prepend_alloc(CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
if (e.impl.requires_authtag_at_end())
{
auth_tag_tmp = e.work.write_alloc(CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
}
}
// encrypt
e.impl.encrypt(buf.data(), work_data, buf.size(), nonce.iv(), auth_tag, nonce.ad(), nonce.ad_len(e.pid_send));
if (auth_tag_tmp)
{
/* move the auth tag to the front */
std::memcpy(auth_tag, auth_tag_tmp, CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
/* Ignore the auth tag at the end */
e.work.inc_size(-CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
}
buf.swap(e.work);
// prepend additional data
nonce.prepend_ad(buf, e.pid_send);
}
return e.pid_send.wrap_warning();
}
Error::Type decrypt(BufferAllocated &buf, const std::time_t now, const unsigned char *op32) override
{
// only process non-null packets
if (buf.size())
{
// get nonce/IV/AD
Nonce nonce(d.nonce, d.pid_recv, buf, op32);
// get auth tag if it is at the front. If the auth tag is at the end
// the decrypt function will just treat it as part of the input
unsigned char *auth_tag = nullptr;
if (!dc_settings.aeadTagAtTheEnd())
{
auth_tag = buf.read_alloc(CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
}
// initialize work buffer.
frame->prepare(Frame::DECRYPT_WORK, d.work);
if (d.work.max_size() < buf.size())
throw aead_error("decrypt work buffer too small");
if (auth_tag && e.impl.requires_authtag_at_end())
{
unsigned char *auth_tag_end = buf.write_alloc(CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
std::memcpy(auth_tag_end, auth_tag, CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
auth_tag = nullptr;
}
// decrypt from buf -> work
if (!d.impl.decrypt(buf.c_data(), d.work.data(), buf.size(), nonce.iv(), auth_tag, nonce.ad(), nonce.ad_len(d.pid_recv)))
{
buf.reset_size();
return Error::DECRYPT_ERROR;
}
if (dc_settings.aeadTagAtTheEnd() || e.impl.requires_authtag_at_end())
{
d.work.set_size(buf.size() - CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN);
}
else
{
d.work.set_size(buf.size());
}
// verify packet ID
if (!nonce.verify_packet_id(d.pid_recv, now))
{
buf.reset_size();
return Error::REPLAY_ERROR;
}
// return cleartext result in buf
buf.swap(d.work);
}
return Error::SUCCESS;
}
// Initialization
// TODO: clamp_to_default probably will cause an error further along if triggered, investigate
void init_cipher(StaticKey &&encrypt_key, StaticKey &&decrypt_key) override
{
e.impl.init(libctx,
dc_settings.cipher(),
encrypt_key.data(),
clamp_to_default<unsigned int>(encrypt_key.size(), 0),
CRYPTO_API::CipherContextAEAD::ENCRYPT);
d.impl.init(libctx,
dc_settings.cipher(),
decrypt_key.data(),
clamp_to_default<unsigned int>(decrypt_key.size(), 0),
CRYPTO_API::CipherContextAEAD::DECRYPT);
}
void init_hmac(StaticKey &&encrypt_key,
StaticKey &&decrypt_key) override
{
e.nonce.set_tail(encrypt_key, dc_settings.use64bitPktCounter());
d.nonce.set_tail(decrypt_key, dc_settings.use64bitPktCounter());
}
void init_pid(const char *recv_name,
const int recv_unit,
const SessionStats::Ptr &recv_stats_arg) override
{
e.pid_send = PacketIDDataSend{dc_settings.use64bitPktCounter()};
d.pid_recv.init(recv_name, recv_unit, dc_settings.use64bitPktCounter(), recv_stats_arg);
}
// Indicate whether or not cipher/digest is defined
unsigned int defined() const override
{
unsigned int ret = CRYPTO_DEFINED;
// AEAD mode doesn't use HMAC, but we still indicate HMAC_DEFINED
// because we want to use the HMAC keying material for the AEAD nonce tail.
if (CryptoAlgs::defined(dc_settings.cipher()))
ret |= (CIPHER_DEFINED | HMAC_DEFINED);
return ret;
}
bool consider_compression(const CompressContext &comp_ctx) override
{
return true;
}
// Rekeying
void rekey(const typename Base::RekeyType type) override
{
}
private:
CryptoDCSettingsData dc_settings;
Frame::Ptr frame;
SessionStats::Ptr stats;
SSLLib::Ctx libctx;
Encrypt e;
Decrypt d;
};
template <typename CRYPTO_API>
class CryptoContext : public CryptoDCContext
{
public:
typedef RCPtr<CryptoContext> Ptr;
CryptoContext(SSLLib::Ctx libctx_arg,
CryptoDCSettingsData dc_settings_data,
const Frame::Ptr &frame_arg,
const SessionStats::Ptr &stats_arg)
: CryptoDCContext(dc_settings_data.key_derivation()),
dc_settings(std::move(dc_settings_data)),
frame(frame_arg),
stats(stats_arg),
libctx(libctx_arg)
{
/* Check if the cipher is legal for AEAD and otherwise throw */
legal_dc_cipher(dc_settings.cipher());
dc_settings.set_digest(CryptoAlgs::NONE);
}
CryptoDCInstance::Ptr new_obj(const unsigned int key_id) override
{
return new Crypto<CRYPTO_API>(libctx, dc_settings, frame, stats);
}
// cipher/HMAC/key info
CryptoDCSettingsData crypto_info() override
{
return dc_settings;
}
// Info for ProtoContext::link_mtu_adjust
size_t encap_overhead() const override
{
return CRYPTO_API::CipherContextAEAD::AUTH_TAG_LEN;
}
private:
CryptoDCSettingsData dc_settings;
Frame::Ptr frame;
SessionStats::Ptr stats;
SSLLib::Ctx libctx;
};
} // namespace openvpn::AEAD
#endif