OpenVPN
crypto_epoch.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2024-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2024-2026 Arne Schwabe <arne@rfc2549.org>
10 *
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2
14 * as published by the Free Software Foundation.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, see <https://www.gnu.org/licenses/>.
23 */
24
25
26#ifdef HAVE_CONFIG_H
27#include "config.h"
28#endif
29
30#include <inttypes.h>
31#include <string.h>
32#include <stdlib.h>
33
34#include "crypto_backend.h"
35#include "packet_id.h"
36#include "crypto.h"
37#include "crypto_epoch.h"
38#include "buffer.h"
39#include "integer.h"
40
41void
42ovpn_hkdf_expand(const uint8_t *secret, const uint8_t *info, size_t info_len,
43 uint8_t *out, size_t out_len)
44{
46 hmac_ctx_init(hmac_ctx, secret, "SHA256");
47
48 ASSERT(info_len <= INT_MAX);
49
50 /* T(0) = empty string */
51 uint8_t t_prev[SHA256_DIGEST_LENGTH];
52
53 for (uint8_t block = 1; (block - 1u) * SHA256_DIGEST_LENGTH < out_len; block++)
54 {
56
57 /* calculate T(block) */
58 hmac_ctx_update(hmac_ctx, t_prev, block == 1 ? 0 : SHA256_DIGEST_LENGTH);
59 hmac_ctx_update(hmac_ctx, info, (int)info_len);
60 hmac_ctx_update(hmac_ctx, &block, 1);
61 hmac_ctx_final(hmac_ctx, t_prev);
62
63 /* Copy a full hmac output or remaining bytes */
64 size_t out_offset = (block - 1u) * SHA256_DIGEST_LENGTH;
65 size_t copylen = min_size(SHA256_DIGEST_LENGTH, out_len - out_offset);
66
67 memcpy(out + out_offset, t_prev, copylen);
68 }
71}
72
73bool
74ovpn_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t *label, size_t label_len,
75 const uint8_t *context, size_t context_len, uint8_t *out, size_t out_len)
76{
77 if (secret_len != 32 || label_len > 250 || context_len > 255 || label_len < 1)
78 {
79 /* Our current implementation is not a general purpose one
80 * and assumes that the secret size matches the size of the
81 * hash (SHA256) key. Also label length and context length
82 * need need to be in range */
83 return false;
84 }
85 ASSERT(out_len <= UINT16_MAX);
86
87 struct gc_arena gc = gc_new();
88 /* 2 byte for the outlen encoded as uint16, 5 bytes for "ovpn ",
89 * 1 byte for context len byte and 1 byte for label len byte */
90 const uint8_t *label_prefix = (const uint8_t *)("ovpn ");
91 uint8_t prefix_len = 5;
92
93 size_t hkdf_label_len = 2u + prefix_len + 1u + label_len + 1u + context_len;
94 struct buffer hkdf_label = alloc_buf_gc(hkdf_label_len, &gc);
95
96 buf_write_u16(&hkdf_label, (uint16_t)out_len);
97 buf_write_u8(&hkdf_label, prefix_len + (uint8_t)label_len);
98 buf_write(&hkdf_label, label_prefix, prefix_len);
99 buf_write(&hkdf_label, label, label_len);
100
101 buf_write_u8(&hkdf_label, (uint8_t)context_len);
102 if (context_len > 0)
103 {
104 buf_write(&hkdf_label, context, context_len);
105 }
106
107 ASSERT(buf_len(&hkdf_label) == (int)hkdf_label_len);
108
109 ovpn_hkdf_expand(secret, buf_bptr(&hkdf_label), hkdf_label_len, out, out_len);
110
111 gc_free(&gc);
112 return true;
113}
114
120static void
122{
123 struct epoch_key new_epoch_key = { 0 };
124 new_epoch_key.epoch = epoch_key->epoch + 1;
125 const uint8_t epoch_update_label[] = "datakey upd";
126 /* length of the array without extra \0 byte from the string */
127 const size_t epoch_update_label_len = sizeof(epoch_update_label) - 1;
128
129 /* E_N+1 = OVPN-Expand-Label(E_N, "datakey upd", "", 32) */
130 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_update_label,
131 epoch_update_label_len, NULL, 0, new_epoch_key.epoch_key,
132 sizeof(new_epoch_key.epoch_key));
133 *epoch_key = new_epoch_key;
134}
135
136void
138 const struct key_type *kt)
139{
140 key->hmac_size = cipher_kt_iv_size(kt->cipher);
141 key->cipher_size = cipher_kt_key_size(kt->cipher);
142
143 /* Generate data key from epoch key:
144 * K_i = OVPN-Expand-Label(E_i, "data_key", "", key_size)
145 * implicit_iv = OVPN-Expand-Label(E_i, "data_iv", "", implicit_iv_len)
146 */
147
148 const uint8_t epoch_data_key_label[] = "data_key";
149 /* length of the array without extra \0 byte from the string */
150 const size_t epoch_data_key_label_len = sizeof(epoch_data_key_label) - 1;
151
152 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_data_key_label,
153 epoch_data_key_label_len, NULL, 0, (uint8_t *)(&key->cipher),
154 key->cipher_size);
155
156 const uint8_t epoch_data_iv_label[] = "data_iv";
157 /* length of the array without extra \0 byte from the string */
158 const size_t epoch_data_iv_label_len = sizeof(epoch_data_iv_label) - 1;
159
160 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_data_iv_label,
161 epoch_data_iv_label_len, NULL, 0, (uint8_t *)(&key->hmac), key->hmac_size);
162 key->epoch = epoch_key->epoch;
163}
164
165static void
167{
168 /* Ensure that we are NEVER regenerating the same key that has already
169 * been generated. Since we also reset the packet ID counter this would be
170 * catastrophic as we would do IV reuse which breaks ciphers like AES-GCM */
172 char name[32] = { 0 };
173 snprintf(name, sizeof(name), "Epoch Data key %" PRIu16, co->epoch_key_send.epoch);
174
175 struct key_parameters send_key = { 0 };
176
178
179 init_key_bi_ctx_send(&co->key_ctx_bi.encrypt, &send_key, &co->epoch_key_type, name);
181 secure_memzero(&send_key, sizeof(send_key));
182}
183
184
185static void
187{
188 struct key_parameters recv_key = { 0 };
190
191 char name[32];
192
193 snprintf(name, sizeof(name), "Epoch Data key %" PRIu16, co->epoch_key_recv.epoch);
194
195 init_key_bi_ctx_recv(ctx, &recv_key, &co->epoch_key_type, name);
196 secure_memzero(&recv_key, sizeof(recv_key));
197}
198
199void
201{
202 /* We want the future receive keys to start just after the epoch of
203 * the currently used decryption key. */
205 uint16_t current_decrypt_epoch = co->key_ctx_bi.decrypt.epoch;
206
207 /* Either we have not generated any future keys yet (first initialisation)
208 * or the last index is the same as our current epoch key
209 * (last generated receive epoch key should match the epoch key).
210 *
211 * The last generated key might have been moved to the decrypt key already.
212 */
213 const struct key_ctx *highest_future_key =
215
216 ASSERT(co->epoch_key_recv.epoch == 1 || highest_future_key->epoch == co->epoch_key_recv.epoch
217 || current_decrypt_epoch == co->epoch_key_recv.epoch);
218
219 /* free the keys that are not used anymore */
220 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
221 {
222 /* Keys in future keys are always epoch > 1 if initialised */
223 if (co->epoch_data_keys_future[i].epoch > 0
224 && co->epoch_data_keys_future[i].epoch < current_decrypt_epoch)
225 {
226 /* Key is old, free it */
228 }
229 }
230
231 /* The current epoch_key_recv is the higest currently generated key */
232 uint16_t current_highest_key = co->epoch_key_recv.epoch;
233
234 /* The current highest generated epoch key should be either the last
235 * key in the future key array or been already moved the current decrypt
236 * key (and then all future keys need to be generated)*/
237 ASSERT(current_highest_key == highest_future_key->epoch
238 || current_highest_key == current_decrypt_epoch);
239
240 /* Calculate the number of keys that need to be generated,
241 * if no keys have been generated assume only the first key is defined */
242 uint16_t desired_highest_key = current_decrypt_epoch + co->epoch_data_keys_future_count;
243 uint16_t num_keys_generate = desired_highest_key - current_highest_key;
244
245 /* Move the old keys out of the way so the order of keys stays strictly
246 * monotonic and consecutive. */
247 /* first check that the destination we are going to overwrite is freed */
248 for (uint16_t i = 0; i < num_keys_generate; i++)
249 {
251 }
252 memmove(co->epoch_data_keys_future, co->epoch_data_keys_future + num_keys_generate,
253 (co->epoch_data_keys_future_count - num_keys_generate) * sizeof(struct key_ctx));
254
255 /* Clear and regenerate the array elements at the end */
256 for (uint16_t i = co->epoch_data_keys_future_count - num_keys_generate;
257 i < co->epoch_data_keys_future_count; i++)
258 {
261
263 }
264
265 /* Assert that all keys are initialised */
266 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
267 {
269 }
270}
271
272void
280
281void
282epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)
283{
284 /* Find the key of the new epoch in future keys */
285 uint16_t fki;
286 for (fki = 0; fki < co->epoch_data_keys_future_count; fki++)
287 {
288 if (co->epoch_data_keys_future[fki].epoch == new_epoch)
289 {
290 break;
291 }
292 }
293 /* we should only ever be called when we successfully decrypted/authenticated
294 * a packet from a peer, ie the epoch recv key *MUST* be in that
295 * array */
296 ASSERT(fki < co->epoch_data_keys_future_count);
297 ASSERT(co->epoch_data_keys_future[fki].epoch == new_epoch);
298
299 struct key_ctx *new_ctx = &co->epoch_data_keys_future[fki];
300
301 /* Check if the new recv key epoch is higher than the send key epoch. If
302 * yes we will replace the send key as well */
303 if (co->key_ctx_bi.encrypt.epoch < new_epoch)
304 {
306
307 /* Update the epoch_key for send to match the current key being used.
308 * This is a bit of extra work but since we are a maximum of
309 * epoch_data_keys_future_count keys behind (4 by default),
310 * a maximum 4 HMAC invocations are a small price to pay for not
311 * keeping all the old epoch keys around in future_keys
312 * array */
313 while (co->epoch_key_send.epoch < new_epoch)
314 {
316 }
318 }
319
320 /* Replace receive key */
324
325 co->key_ctx_bi.decrypt = *new_ctx;
326
327 /* Zero the old location instead to of free_key_ctx since we moved the keys
328 * and do not want to free the pointers in the old place */
329 memset(new_ctx, 0, sizeof(struct key_ctx));
330
331 /* Generate new future keys */
333}
334
335void
337{
338 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
339 {
341 }
342
343 free(co->epoch_data_keys_future);
348}
349
350void
352 const struct epoch_key *e1_send, const struct epoch_key *e1_recv,
353 uint16_t future_key_count)
354{
355 ASSERT(e1_send->epoch == 1 && e1_recv->epoch == 1);
356 co->epoch_key_recv = *e1_recv;
357 co->epoch_key_send = *e1_send;
358
361
364 co->key_ctx_bi.initialized = true;
365
366 co->epoch_data_keys_future_count = future_key_count;
369}
370
371struct key_ctx *
373{
374 /* Current decrypt key is the most likely one */
375 if (opt->key_ctx_bi.decrypt.epoch == epoch)
376 {
377 return &opt->key_ctx_bi.decrypt;
378 }
381 {
383 }
384 else if (epoch > opt->key_ctx_bi.decrypt.epoch
386 {
387 /* If we have reached the edge of the valid keys we do not return
388 * the key anymore since regenerating the new keys would move us
389 * over the window of valid keys and would need all kind of
390 * special casing, so we stop returning the key in this case */
391 if (epoch > (UINT16_MAX - opt->epoch_data_keys_future_count - 1))
392 {
393 return NULL;
394 }
395 else
396 {
397 /* Key in the range of future keys */
398 const int index = epoch - (opt->key_ctx_bi.decrypt.epoch + 1);
399
400 return &opt->epoch_data_keys_future[index];
401 }
402 }
403 else
404 {
405 return NULL;
406 }
407}
408
409
410void
412{
413 if (opt->epoch_key_send.epoch == UINT16_MAX)
414 {
415 /* limit of epoch keys reached, cannot move to a newer key anymore */
416 return;
417 }
418 if (opt->aead_usage_limit)
419 {
421 opt->packet_id.send.id))
422 {
423 /* Send key limit reached */
425 }
426 /* draft 8 of the aead usage limit still had but draft 9 complete
427 * dropped this statement:
428 *
429 * In particular, in two-party communication, one participant cannot
430 * regard apparent overuse of a key by other participants as
431 * being in error, when it could be that the other participant has
432 * better information about bounds.
433 *
434 * OpenVPN 2.x implements a compromise of not regarding this as an
435 * error but still accepting packets of the usage limit but tries to
436 * push the peer to a new epoch key by increasing our own key epoch
437 *
438 * Also try to push the sender to use a new key if we are the
439 * decryption fail warn limit.
440 * */
441 else if (opt->key_ctx_bi.encrypt.epoch == opt->key_ctx_bi.decrypt.epoch
443 opt->packet_id.rec.id)
445 {
446 /* Receive key limit reached. Increase our own send key to signal
447 * that we want to use a new epoch. Peer should then also move its
448 * key but is not required to do this */
450 }
451 }
452
454 {
456 }
457}
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
Buffer management functions and garbage collection.
static bool buf_write_u16(struct buffer *dest, uint16_t data)
Append a uint16_t to a buffer in network byte order.
Definition buffer.h:1302
static uint8_t * buf_bptr(struct buffer *buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:449
#define ALLOC_ARRAY_CLEAR(dptr, type, n)
Allocate and zero-initialise an array of n elements of the given type.
Definition buffer.h:2077
static int buf_len(const struct buffer *buf)
Return the length of the buffer content.
Definition buffer.h:462
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:748
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Append data to a buffer.
Definition buffer.h:1239
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Append a uint8_t to a buffer.
Definition buffer.h:1288
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key_params, const struct key_type *kt, const char *name)
Definition crypto.c:1035
uint64_t cipher_get_aead_limits(const char *ciphername)
Check if the cipher is an AEAD cipher and needs to be limited to a certain number of number of blocks...
Definition crypto.c:349
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1079
void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key_params, const struct key_type *kt, const char *name)
Definition crypto.c:1046
Data Channel Cryptography Module.
static bool aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, uint64_t higest_pid)
Checks if the usage limit for an AEAD cipher is reached.
Definition crypto.h:749
static bool cipher_decrypt_verify_fail_warn(const struct key_ctx *ctx)
Check if the number of failed decryption is approaching the limit and we should try to move to a new ...
Definition crypto.h:720
Data Channel Cryptography SSL library-specific backend interface.
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
hmac_ctx_t * hmac_ctx_new(void)
void hmac_ctx_reset(hmac_ctx_t *ctx)
void hmac_ctx_init(hmac_ctx_t *ctx, const uint8_t *key, const char *mdname)
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
unsigned int cipher_kt_iv_size(const char *ciphername)
Returns the size of the IV used by the cipher, in bytes, or 0 if no IV is used.
void hmac_ctx_free(hmac_ctx_t *ctx)
unsigned int cipher_kt_key_size(const char *ciphername)
Returns the size of keys used by the cipher, in bytes.
void hmac_ctx_cleanup(hmac_ctx_t *ctx)
void epoch_generate_future_receive_keys(struct crypto_options *co)
Generates and fills the epoch_data_keys_future with next valid future keys in crypto_options using th...
void epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)
This is called when the peer uses a new send key that is not the default key.
static void epoch_key_iterate(struct epoch_key *epoch_key)
Iterates the epoch key to make it E_n+1, ie increase the epoch by one and derive the new key material...
static void epoch_init_send_key_ctx(struct crypto_options *co)
void free_epoch_key_ctx(struct crypto_options *co)
Frees the extra data structures used by epoch keys in crypto_options.
bool ovpn_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t *label, size_t label_len, const uint8_t *context, size_t context_len, uint8_t *out, size_t out_len)
Variant of the RFC 8446 TLS 1.3 HKDF-Expand-Label function with the following differences/restriction...
void epoch_check_send_iterate(struct crypto_options *opt)
Checks if we need to iterate the send epoch key.
static void epoch_init_recv_key(struct key_ctx *ctx, struct crypto_options *co)
struct key_ctx * epoch_lookup_decrypt_key(struct crypto_options *opt, uint16_t epoch)
Using an epoch, this function will try to retrieve a decryption key context that matches that epoch f...
void epoch_init_key_ctx(struct crypto_options *co, const struct key_type *key_type, const struct epoch_key *e1_send, const struct epoch_key *e1_recv, uint16_t future_key_count)
Initialises data channel keys and internal structures for epoch data keys using the provided E0 epoch...
void epoch_data_key_derive(struct key_parameters *key, const struct epoch_key *epoch_key, const struct key_type *kt)
Generate a data channel key pair from the epoch key.
void ovpn_hkdf_expand(const uint8_t *secret, const uint8_t *info, size_t info_len, uint8_t *out, size_t out_len)
Implementation of the RFC5869 HKDF-Expand function with the following restrictions.
void epoch_iterate_send_key(struct crypto_options *co)
Updates the send key and send_epoch_key in cryptio_options->key_ctx_bi to use the next epoch.
struct hmac_ctx hmac_ctx_t
#define SHA256_DIGEST_LENGTH
static size_t min_size(size_t x, size_t y)
Definition integer.h:79
#define CLEAR(x)
Definition basic.h:32
#define ASSERT(x)
Definition error.h:221
void packet_id_move_recv(struct packet_id_rec *dest, struct packet_id_rec *src)
Move the packet id recv structure from src to dest.
Definition packet_id.c:109
static void reset_packet_id_send(struct packet_id_send *p)
Reset the current send packet id to its initial state.
Definition packet_id.h:243
#define PACKET_ID_EPOCH_MAX
Definition packet_id.h:47
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
Contains all state information for one tunnel.
Definition openvpn.h:445
Security parameter state for processing data channel packets.
Definition crypto.h:286
struct epoch_key epoch_key_send
last epoch_key used for generation of the current send data keys.
Definition crypto.h:296
struct key_type epoch_key_type
the key_type that is used to generate the epoch keys
Definition crypto.h:302
struct key_ctx epoch_retiring_data_receive_key
The old key before the sender switched to a new epoch data key.
Definition crypto.h:323
uint64_t aead_usage_limit
The limit for AEAD cipher, this is the sum of packets + blocks that are allowed to be used.
Definition crypto.h:308
struct key_ctx * epoch_data_keys_future
Keeps the future epoch data keys for decryption.
Definition crypto.h:317
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:287
uint16_t epoch_data_keys_future_count
number of keys stored in epoch_data_keys_future
Definition crypto.h:320
struct packet_id_rec epoch_retiring_key_pid_recv
Definition crypto.h:324
struct epoch_key epoch_key_recv
epoch_key used for the highest receive epoch keys
Definition crypto.h:299
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:326
uint8_t epoch_key[SHA256_DIGEST_LENGTH]
Definition crypto.h:186
uint16_t epoch
Definition crypto.h:187
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition crypto.h:273
bool initialized
Definition crypto.h:278
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition crypto.h:276
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:274
Container for one set of cipher and/or HMAC contexts.
Definition crypto.h:195
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:221
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:156
const char * cipher
const name of the cipher
Definition crypto.h:135
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:145
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:146
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:148
uint64_t id
Definition packet_id.h:117
struct seq_list * seq_list
Definition packet_id.h:122
uint64_t id
Definition packet_id.h:133
struct packet_id_send send
Definition packet_id.h:180
struct packet_id_rec rec
Definition packet_id.h:181
struct gc_arena gc
Definition test_ssl.c:138