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-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2024-2025 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, int info_len, uint8_t *out,
43 int out_len)
44{
45 hmac_ctx_t *hmac_ctx = hmac_ctx_new();
46 hmac_ctx_init(hmac_ctx, secret, "SHA256");
47
48 const int digest_size = SHA256_DIGEST_LENGTH;
49
50 /* T(0) = empty string */
51 uint8_t t_prev[SHA256_DIGEST_LENGTH];
52 int t_prev_len = 0;
53
54 for (uint8_t block = 1; (block - 1) * digest_size < out_len; block++)
55 {
56 hmac_ctx_reset(hmac_ctx);
57
58 /* calculate T(block) */
59 hmac_ctx_update(hmac_ctx, t_prev, t_prev_len);
60 hmac_ctx_update(hmac_ctx, info, info_len);
61 hmac_ctx_update(hmac_ctx, &block, 1);
62 hmac_ctx_final(hmac_ctx, t_prev);
63 t_prev_len = digest_size;
64
65 /* Copy a full hmac output or remaining bytes */
66 int out_offset = (block - 1) * digest_size;
67 int copylen = min_int(digest_size, out_len - out_offset);
68
69 memcpy(out + out_offset, t_prev, copylen);
70 }
71 hmac_ctx_cleanup(hmac_ctx);
72 hmac_ctx_free(hmac_ctx);
73}
74
75bool
76ovpn_expand_label(const uint8_t *secret, size_t secret_len, const uint8_t *label, size_t label_len,
77 const uint8_t *context, size_t context_len, uint8_t *out, uint16_t out_len)
78{
79 if (secret_len != 32 || label_len > 250 || context_len > 255 || label_len < 1)
80 {
81 /* Our current implementation is not a general purpose one
82 * and assumes that the secret size matches the size of the
83 * hash (SHA256) key. Also label length and context length
84 * need need to be in range */
85 return false;
86 }
87
88 struct gc_arena gc = gc_new();
89 /* 2 byte for the outlen encoded as uint16, 5 bytes for "ovpn ",
90 * 1 byte for context len byte and 1 byte for label len byte */
91 const uint8_t *label_prefix = (const uint8_t *)("ovpn ");
92 int prefix_len = 5;
93
94 int hkdf_label_len = 2 + prefix_len + 1 + label_len + 1 + context_len;
96
98 buf_write_u8(&hkdf_label, prefix_len + label_len);
99 buf_write(&hkdf_label, label_prefix, prefix_len);
101
103 if (context_len > 0)
104 {
106 }
107
109
111
112 gc_free(&gc);
113 return true;
114}
115
121static void
123{
124 struct epoch_key new_epoch_key = { 0 };
125 new_epoch_key.epoch = epoch_key->epoch + 1;
126 const uint8_t epoch_update_label[] = "datakey upd";
127 /* length of the array without extra \0 byte from the string */
128 const size_t epoch_update_label_len = sizeof(epoch_update_label) - 1;
129
130 /* E_N+1 = OVPN-Expand-Label(E_N, "datakey upd", "", 32) */
131 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_update_label,
132 epoch_update_label_len, NULL, 0, new_epoch_key.epoch_key,
133 sizeof(new_epoch_key.epoch_key));
134 *epoch_key = new_epoch_key;
135}
136
137void
139 const struct key_type *kt)
140{
141 key->hmac_size = cipher_kt_iv_size(kt->cipher);
142 key->cipher_size = cipher_kt_key_size(kt->cipher);
143
144 /* Generate data key from epoch key:
145 * K_i = OVPN-Expand-Label(E_i, "data_key", "", key_size)
146 * implicit_iv = OVPN-Expand-Label(E_i, "data_iv", "", implicit_iv_len)
147 */
148
149 const uint8_t epoch_data_key_label[] = "data_key";
150 /* length of the array without extra \0 byte from the string */
151 const size_t epoch_data_key_label_len = sizeof(epoch_data_key_label) - 1;
152
153 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_data_key_label,
154 epoch_data_key_label_len, NULL, 0, (uint8_t *)(&key->cipher),
155 key->cipher_size);
156
157 const uint8_t epoch_data_iv_label[] = "data_iv";
158 /* length of the array without extra \0 byte from the string */
159 const size_t epoch_data_iv_label_len = sizeof(epoch_data_iv_label) - 1;
160
161 ovpn_expand_label(epoch_key->epoch_key, sizeof(epoch_key->epoch_key), epoch_data_iv_label,
162 epoch_data_iv_label_len, NULL, 0, (uint8_t *)(&key->hmac), key->hmac_size);
163 key->epoch = epoch_key->epoch;
164}
165
166static void
168{
169 /* Ensure that we are NEVER regenerating the same key that has already
170 * been generated. Since we also reset the packet ID counter this would be
171 * catastrophic as we would do IV reuse which breaks ciphers like AES-GCM */
173 char name[32] = { 0 };
174 snprintf(name, sizeof(name), "Epoch Data key %" PRIu16, co->epoch_key_send.epoch);
175
176 struct key_parameters send_key = { 0 };
177
179
180 init_key_bi_ctx_send(&co->key_ctx_bi.encrypt, &send_key, &co->epoch_key_type, name);
182 CLEAR(send_key);
183}
184
185
186static void
188{
189 struct key_parameters recv_key = { 0 };
191
192 char name[32];
193
194 snprintf(name, sizeof(name), "Epoch Data key %" PRIu16, co->epoch_key_recv.epoch);
195
196 init_key_bi_ctx_recv(ctx, &recv_key, &co->epoch_key_type, name);
197 CLEAR(recv_key);
198}
199
200void
202{
203 /* We want the future receive keys to start just after the epoch of
204 * the currently used decryption key. */
206 uint16_t current_decrypt_epoch = co->key_ctx_bi.decrypt.epoch;
207
208 /* Either we have not generated any future keys yet (first initialisation)
209 * or the last index is the same as our current epoch key
210 * (last generated receive epoch key should match the epoch key) */
211 struct key_ctx *highest_future_key =
213
214 ASSERT(co->epoch_key_recv.epoch == 1 || highest_future_key->epoch == co->epoch_key_recv.epoch);
215
216 /* free the keys that are not used anymore */
217 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
218 {
219 /* Keys in future keys are always epoch > 1 if initialised */
220 if (co->epoch_data_keys_future[i].epoch > 0
221 && co->epoch_data_keys_future[i].epoch < current_decrypt_epoch)
222 {
223 /* Key is old, free it */
225 }
226 }
227
228 /* Calculate the number of keys that need to be generated,
229 * if no keys have been generated assume only the first key is defined */
230 uint16_t current_highest_key = highest_future_key->epoch ? highest_future_key->epoch : 1;
231 uint16_t desired_highest_key = current_decrypt_epoch + co->epoch_data_keys_future_count;
232 uint16_t num_keys_generate = desired_highest_key - current_highest_key;
233
234
235 /* Move the old keys out of the way so the order of keys stays strictly
236 * monotonic and consecutive. */
237 /* first check that the destination we are going to overwrite is freed */
238 for (uint16_t i = 0; i < num_keys_generate; i++)
239 {
241 }
242 memmove(co->epoch_data_keys_future, co->epoch_data_keys_future + num_keys_generate,
243 (co->epoch_data_keys_future_count - num_keys_generate) * sizeof(struct key_ctx));
244
245 /* Clear and regenerate the array elements at the end */
246 for (uint16_t i = co->epoch_data_keys_future_count - num_keys_generate;
248 {
251
253 }
254
255 /* Assert that all keys are initialised */
256 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
257 {
259 }
260}
261
262void
270
271void
272epoch_replace_update_recv_key(struct crypto_options *co, uint16_t new_epoch)
273{
274 /* Find the key of the new epoch in future keys */
275 uint16_t fki;
276 for (fki = 0; fki < co->epoch_data_keys_future_count; fki++)
277 {
278 if (co->epoch_data_keys_future[fki].epoch == new_epoch)
279 {
280 break;
281 }
282 }
283 /* we should only ever be called when we successfully decrypted/authenticated
284 * a packet from a peer, ie the epoch recv key *MUST* be in that
285 * array */
286 ASSERT(fki < co->epoch_data_keys_future_count);
287 ASSERT(co->epoch_data_keys_future[fki].epoch == new_epoch);
288
289 struct key_ctx *new_ctx = &co->epoch_data_keys_future[fki];
290
291 /* Check if the new recv key epoch is higher than the send key epoch. If
292 * yes we will replace the send key as well */
293 if (co->key_ctx_bi.encrypt.epoch < new_epoch)
294 {
296
297 /* Update the epoch_key for send to match the current key being used.
298 * This is a bit of extra work but since we are a maximum of 16
299 * keys behind, a maximum 16 HMAC invocations are a small price to
300 * pay for not keeping all the old epoch keys around in future_keys
301 * array */
302 while (co->epoch_key_send.epoch < new_epoch)
303 {
305 }
307 }
308
309 /* Replace receive key */
313
314 co->key_ctx_bi.decrypt = *new_ctx;
315
316 /* Zero the old location instead to of free_key_ctx since we moved the keys
317 * and do not want to free the pointers in the old place */
318 memset(new_ctx, 0, sizeof(struct key_ctx));
319
320 /* Generate new future keys */
322}
323
324void
326{
327 for (uint16_t i = 0; i < co->epoch_data_keys_future_count; i++)
328 {
330 }
331
332 free(co->epoch_data_keys_future);
337}
338
339void
341 const struct epoch_key *e1_send, const struct epoch_key *e1_recv,
342 uint16_t future_key_count)
343{
344 ASSERT(e1_send->epoch == 1 && e1_recv->epoch == 1);
345 co->epoch_key_recv = *e1_recv;
346 co->epoch_key_send = *e1_send;
347
350
353 co->key_ctx_bi.initialized = true;
354
355 co->epoch_data_keys_future_count = future_key_count;
358}
359
360struct key_ctx *
362{
363 /* Current decrypt key is the most likely one */
364 if (opt->key_ctx_bi.decrypt.epoch == epoch)
365 {
366 return &opt->key_ctx_bi.decrypt;
367 }
370 {
372 }
373 else if (epoch > opt->key_ctx_bi.decrypt.epoch
375 {
376 /* Key in the range of future keys */
377 int index = epoch - (opt->key_ctx_bi.decrypt.epoch + 1);
378
379 /* If we have reached the edge of the valid keys we do not return
380 * the key anymore since regenerating the new keys would move us
381 * over the window of valid keys and would need all kind of
382 * special casing, so we stop returning the key in this case */
383 if (epoch > (UINT16_MAX - opt->epoch_data_keys_future_count - 1))
384 {
385 return NULL;
386 }
387 else
388 {
389 return &opt->epoch_data_keys_future[index];
390 }
391 }
392 else
393 {
394 return NULL;
395 }
396}
397
398
399void
401{
402 if (opt->epoch_key_send.epoch == UINT16_MAX)
403 {
404 /* limit of epoch keys reached, cannot move to a newer key anymore */
405 return;
406 }
407 if (opt->aead_usage_limit)
408 {
410 opt->packet_id.send.id))
411 {
412 /* Send key limit reached */
414 }
415 /* draft 8 of the aead usage limit still had but draft 9 complete
416 * dropped this statement:
417 *
418 * In particular, in two-party communication, one participant cannot
419 * regard apparent overuse of a key by other participants as
420 * being in error, when it could be that the other participant has
421 * better information about bounds.
422 *
423 * OpenVPN 2.x implements a compromise of not regarding this as an
424 * error but still accepting packets of the usage limit but tries to
425 * push the peer to a new epoch key by increasing our own key epoch
426 *
427 * Also try to push the sender to use a new key if we are the
428 * decryption fail warn limit.
429 * */
430 else if (opt->key_ctx_bi.encrypt.epoch == opt->key_ctx_bi.decrypt.epoch
432 opt->packet_id.rec.id)
434 {
435 /* Receive key limit reached. Increase our own send key to signal
436 * that we want to use a new epoch. Peer should then also move its
437 * key but is not required to do this */
439 }
440 }
441
443 {
445 }
446}
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition buffer.c:89
static bool buf_write_u16(struct buffer *dest, uint16_t data)
Definition buffer.h:690
static uint8_t * buf_bptr(const struct buffer *buf)
Definition buffer.h:240
#define ALLOC_ARRAY_CLEAR(dptr, type, n)
Definition buffer.h:1058
static int buf_len(const struct buffer *buf)
Definition buffer.h:253
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Definition buffer.h:660
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Definition buffer.h:684
static void gc_free(struct gc_arena *a)
Definition buffer.h:1015
static struct gc_arena gc_new(void)
Definition buffer.h:1007
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:1032
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:338
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1075
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:1044
Data Channel Cryptography Module.
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:722
static bool aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, int64_t higest_pid)
Checks if the usage limit for an AEAD cipher is reached.
Definition crypto.h:751
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)
void hmac_ctx_free(hmac_ctx_t *ctx)
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.
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)
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, uint16_t out_len)
Variant of the RFC 8446 TLS 1.3 HKDF-Expand-Label function with the following differences/restriction...
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.
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, int info_len, uint8_t *out, int 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.
mbedtls_md_context_t hmac_ctx_t
Generic HMAC context.
#define SHA256_DIGEST_LENGTH
static int min_int(int x, int y)
Definition integer.h:105
#define CLEAR(x)
Definition basic.h:32
#define ASSERT(x)
Definition error.h:217
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:104
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:303
#define PACKET_ID_EPOCH_MAX
Definition packet_id.h:47
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:65
Contains all state information for one tunnel.
Definition openvpn.h:474
Security parameter state for processing data channel packets.
Definition crypto.h:293
struct epoch_key epoch_key_send
last epoch_key used for generation of the current send data keys.
Definition crypto.h:302
struct key_type epoch_key_type
the key_type that is used to generate the epoch keys
Definition crypto.h:308
struct key_ctx epoch_retiring_data_receive_key
The old key before the sender switched to a new epoch data key.
Definition crypto.h:328
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:313
struct key_ctx * epoch_data_keys_future
Keeps the future epoch data keys for decryption.
Definition crypto.h:322
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:294
uint16_t epoch_data_keys_future_count
number of keys stored in epoch_data_keys_future
Definition crypto.h:325
struct packet_id_rec epoch_retiring_key_pid_recv
Definition crypto.h:329
struct epoch_key epoch_key_recv
epoch_key used for the highest receive epoch keys
Definition crypto.h:305
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:331
uint8_t epoch_key[SHA256_DIGEST_LENGTH]
Definition crypto.h:193
uint16_t epoch
Definition crypto.h:194
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:116
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition crypto.h:280
bool initialized
Definition crypto.h:285
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition crypto.h:283
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:281
Container for one set of cipher and/or HMAC contexts.
Definition crypto.h:202
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:228
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:163
const char * cipher
const name of the cipher
Definition crypto.h:142
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:153
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:155
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:153
struct packet_id_send send
Definition packet_id.h:200
struct packet_id_rec rec
Definition packet_id.h:201
struct gc_arena gc
Definition test_ssl.c:154