OpenVPN
crypto.h
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) 2002-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2026 Sentyron B.V. <openvpn@sentyron.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, see <https://www.gnu.org/licenses/>.
22 */
23
122#ifndef CRYPTO_H
123#define CRYPTO_H
124
125#include "crypto_backend.h"
126#include "basic.h"
127#include "buffer.h"
128#include "packet_id.h"
129#include "mtu.h"
130
136
137/*
138 * Defines a key type and key length for both cipher and HMAC.
139 */
141{
142 const char *cipher;
143 const char *digest;
144};
145
158
163{
166
168 unsigned int cipher_size;
169
172
174 unsigned int hmac_size;
175
179 uint16_t epoch;
180};
181
189void key_parameters_from_key(struct key_parameters *key_params, const struct key *key);
190
192{
194 uint16_t epoch;
195};
196
230
231#define KEY_DIRECTION_BIDIRECTIONAL 0 /* same keys for both directions */
232#define KEY_DIRECTION_NORMAL 1 /* encrypt with keys[0], decrypt with keys[1] */
233#define KEY_DIRECTION_INVERSE 2 /* encrypt with keys[1], decrypt with keys[0] */
234
239struct key2
240{
241 int n;
243 struct key keys[2];
247};
248
273
280{
286};
287
293{
304
307
310
316
325
328
332
347#define CO_PACKET_ID_LONG_FORM (1u << 0)
350#define CO_IGNORE_PACKET_ID (1u << 1)
356#define CO_MUTE_REPLAY_WARNINGS (1u << 2)
359#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1u << 3)
363#define CO_RESEND_WKC (1u << 4)
367#define CO_FORCE_TLSCRYPTV2_COOKIE (1u << 5)
371#define CO_USE_CC_EXIT_NOTIFY (1u << 6)
375#define CO_USE_DYNAMIC_TLS_CRYPT (1u << 7)
379#define CO_EPOCH_DATA_KEY_FORMAT (1u << 8)
386 unsigned int flags;
388};
389
390#define CRYPT_ERROR_EXIT(flags, format) \
391 do \
392 { \
393 msg(flags, "%s: " format, error_prefix); \
394 goto error_exit; \
395 } while (false)
396
397#define CRYPT_ERROR(format) CRYPT_ERROR_EXIT(D_CRYPT_ERRORS, format)
398#define CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format)
399
404#define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)
405
406#define RKF_MUST_SUCCEED (1 << 0)
407#define RKF_INLINE (1 << 1)
408void read_key_file(struct key2 *key2, const char *file, const unsigned int flags);
409
415int write_key_file(const int nkeys, const char *filename);
416
427void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool tls_mode,
428 bool warn);
429
430/*
431 * Key context functions
432 */
433
434void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt,
435 int enc, const char *prefix);
436
437void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key,
438 const struct key_type *kt, const char *name);
439
440void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key,
441 const struct key_type *kt, const char *name);
442
443void free_key_ctx(struct key_ctx *ctx);
444
445void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction,
446 const struct key_type *kt, const char *name);
447
448void free_key_ctx_bi(struct key_ctx_bi *ctx);
449
450
451/**************************************************************************/
481void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt);
482
483
517bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt,
518 const struct frame *frame, const uint8_t *ad_start);
519
533bool crypto_check_replay(struct crypto_options *opt, const struct packet_id_net *pin,
534 uint16_t epoch, const char *error_prefix, struct gc_arena *gc);
535
536
550size_t calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_size,
551 bool occ);
552
554unsigned int crypto_max_overhead(void);
555
563void write_pem_key_file(const char *filename, const char *key_name);
564
572bool generate_ephemeral_key(struct buffer *key, const char *pem_name);
573
584bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file,
585 bool key_inline);
586
587/*
588 * Message digest-based pseudo random number generator.
589 *
590 * If the PRNG was initialised with a certain message digest, uses the digest
591 * to calculate the next random number, and prevent depletion of the entropy
592 * pool.
593 *
594 * This PRNG is aimed at IV generation and similar miscellaneous tasks. Use
595 * \c rand_bytes() for higher-assurance functionality.
596 *
597 * Retrieves len bytes of pseudo random data, and places it in output.
598 *
599 * @param output Output buffer
600 * @param len Length of the output buffer
601 */
602void prng_bytes(uint8_t *output, int len);
603
610int64_t get_random(void);
611
613void print_cipher(const char *cipher);
614
615void test_crypto(struct crypto_options *co, const struct frame *f);
616
617
618/* key direction functions */
619
620void key_direction_state_init(struct key_direction_state *kds, int key_direction);
621
622void check_key2(struct key2 *key2);
623
624void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n);
625
626int ascii2keydirection(msglvl_t msglevel, const char *str);
627
628const char *keydirection2ascii(int kd, bool remote, bool humanreadable);
629
630/* print keys */
631void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0,
632 const char *prefix1);
633
634void crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi *ctx,
635 const char *key_file, bool key_inline, const int key_direction,
636 const char *key_name, const char *opt_name, struct key2 *keydata);
637
642void generate_test_crypto_random_key(const struct key_type *key_type, struct key_ctx_bi *ctx,
643 const char *key_name);
644
645/*
646 * Inline functions
647 */
648
653int memcmp_constant_time(const void *a, const void *b, size_t size);
654
655static inline bool
657{
658 return key->encrypt.cipher || key->encrypt.hmac || key->decrypt.cipher || key->decrypt.hmac;
659}
660
671const char *print_key_filename(const char *str, bool is_inline);
672
683static inline struct key_type
684create_kt(const char *cipher, const char *md, const char *optname)
685{
686 struct key_type kt;
687 kt.cipher = cipher;
688 kt.digest = md;
689
691 {
692 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.cipher);
693 return (struct key_type){ 0 };
694 }
695 if (md_defined(kt.digest) && !md_valid(kt.digest))
696 {
697 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.digest);
698 return (struct key_type){ 0 };
699 }
700
701 return kt;
702}
703
713uint64_t cipher_get_aead_limits(const char *ciphername);
714
718static inline bool
720{
721 /* Use 2**36, same as DTLS 1.3. Strictly speaking this only guarantees
722 * the security margin for packets up to 2^10 blocks (16384 bytes)
723 * but we accept slightly lower security bound for the edge
724 * of Chacha20-Poly1305 and packets over 16k as MTUs over 16k are
725 * extremely rarely used */
726 return ctx->failed_verifications > (1ull << 36);
727}
728
733static inline bool
735{
736 /* Use 2**35, half the amount after which we refuse to decrypt */
737 return ctx->failed_verifications > (1ull << 35);
738}
739
740
746#define AEAD_LIMIT_BLOCKSIZE 16
747
754bool check_tls_prf_working(void);
755
762static inline bool
763aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, int64_t higest_pid)
764{
765 /* This is the q + s <= p^(1/2) * 2^(129/2) - 1 calculation where
766 * q is the number of protected messages (highest_pid)
767 * s Total plaintext length in all messages (in blocks) */
768 return (limit > 0 && key_ctx->plaintext_blocks + (uint64_t)higest_pid > limit);
769}
770
771#endif /* CRYPTO_H */
Buffer management functions and garbage collection.
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1103
const char * print_key_filename(const char *str, bool is_inline)
To be used when printing a string that may contain inline data.
Definition crypto.c:1246
void check_key2(struct key2 *key2)
Definition crypto.c:1680
void prng_bytes(uint8_t *output, int len)
Definition crypto.c:1697
size_t calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_size, bool occ)
Calculate the maximum overhead that our encryption has on a packet.
Definition crypto.c:803
void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt, int enc, const char *prefix)
Definition crypto.c:996
void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0, const char *prefix1)
Prints the keys in a key2 structure.
Definition crypto.c:1149
static bool cipher_decrypt_verify_fail_exceeded(const struct key_ctx *ctx)
Check if the number of failed decryption is over the acceptable limit.
Definition crypto.h:719
void read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
Definition crypto.c:1320
void write_pem_key_file(const char *filename, const char *key_name)
Generate a server key with enough randomness to fill a key struct and write to file.
Definition crypto.c:1789
void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt, const char *name)
Definition crypto.c:1050
bool generate_ephemeral_key(struct buffer *key, const char *pem_name)
Generate ephermal key material into the key structure.
Definition crypto.c:1826
bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline)
Read key material from a PEM encoded files into the key structure.
Definition crypto.c:1844
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool tls_mode, bool warn)
Initialize a key_type structure with.
Definition crypto.c:875
int ascii2keydirection(msglvl_t msglevel, const char *str)
Definition crypto.c:1599
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition crypto.c:1581
const char * keydirection2ascii(int kd, bool remote, bool humanreadable)
Definition crypto.c:1622
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition crypto.c:1523
void test_crypto(struct crypto_options *co, const struct frame *f)
Definition crypto.c:1168
void key_parameters_from_key(struct key_parameters *key_params, const struct key *key)
Converts a struct key representation into a struct key_parameters representation.
Definition crypto.c:1158
void print_cipher(const char *cipher)
Print a cipher list entry.
Definition crypto.c:1717
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:345
void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction, const struct key_type *kt, const char *name)
Definition crypto.c:1062
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:734
bool check_tls_prf_working(void)
Checks if the current TLS library supports the TLS 1.0 PRF with MD5+SHA1 that OpenVPN uses when TLS K...
Definition crypto.c:1881
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1651
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
unsigned int crypto_max_overhead(void)
Return the worst-case OpenVPN crypto overhead (in bytes)
Definition crypto.c:850
int64_t get_random(void)
an analogue to the random() function, but use prng_bytes and also int64_t instead of long to avoid LL...
Definition crypto.c:1705
void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt, const char *name)
Definition crypto.c:1038
void generate_test_crypto_random_key(const struct key_type *key_type, struct key_ctx_bi *ctx, const char *key_name)
Generate a random key and initialise ctx to be used the in the crypto random test.
Definition crypto.c:1296
void crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi *ctx, const char *key_file, bool key_inline, const int key_direction, const char *key_name, const char *opt_name, struct key2 *keydata)
Definition crypto.c:1257
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:763
bool crypto_check_replay(struct crypto_options *opt, const struct packet_id_net *pin, uint16_t epoch, const char *error_prefix, struct gc_arena *gc)
Check packet ID for replay, and perform replay administration.
Definition crypto.c:376
static struct key_type create_kt(const char *cipher, const char *md, const char *optname)
Creates and validates an instance of struct key_type with the provided algs.
Definition crypto.h:684
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1084
static bool key_ctx_bi_defined(const struct key_ctx_bi *key)
Definition crypto.h:656
Data Channel Cryptography SSL library-specific backend interface.
static bool cipher_defined(const char *ciphername)
Checks if the cipher is defined and is not the null (none) cipher.
bool md_valid(const char *digest)
Return if a message digest parameters is valid given the name of the digest.
#define MAX_CIPHER_KEY_LENGTH
static bool cipher_valid(const char *ciphername)
Returns if the cipher is valid, based on the given cipher name.
#define MAX_HMAC_KEY_LENGTH
static bool md_defined(const char *mdname)
Checks if the cipher is defined and is not the null (none) cipher.
#define SHA256_DIGEST_LENGTH
#define OPENVPN_MAX_IV_LENGTH
Maximum length of an IV.
void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt)
Encrypt and HMAC sign a packet so that it can be sent as a data channel VPN tunnel packet to a remote...
Definition crypto.c:329
bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt, const struct frame *frame, const uint8_t *ad_start)
HMAC verify and decrypt a data channel packet received from a remote OpenVPN peer.
Definition crypto.c:779
#define msg(flags,...)
Definition error.h:152
unsigned int msglvl_t
Definition error.h:77
#define M_WARN
Definition error.h:92
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
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:303
struct key_type epoch_key_type
the key_type that is used to generate the epoch keys
Definition crypto.h:309
struct key_ctx epoch_retiring_data_receive_key
The old key before the sender switched to a new epoch data key.
Definition crypto.h:330
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:315
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:386
struct key_ctx * epoch_data_keys_future
Keeps the future epoch data keys for decryption.
Definition crypto.h:324
struct packet_id_persist * pid_persist
Persistent packet ID state for keeping state between successive OpenVPN process startups.
Definition crypto.h:342
uint16_t epoch_data_keys_future_count
number of keys stored in epoch_data_keys_future
Definition crypto.h:327
struct packet_id_rec epoch_retiring_key_pid_recv
Definition crypto.h:331
struct epoch_key epoch_key_recv
epoch_key used for the highest receive epoch keys
Definition crypto.h:306
uint16_t epoch
Definition crypto.h:194
Packet geometry parameters.
Definition mtu.h:113
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Container for bidirectional cipher and HMAC key material.
Definition crypto.h:240
int n
The number of key objects stored in the key2.keys array.
Definition crypto.h:241
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:243
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
size_t implicit_iv_len
The length of implicit_iv.
Definition crypto.h:218
uint8_t implicit_iv[OPENVPN_MAX_IV_LENGTH]
This implicit IV will be always XORed with the packet id that is sent on the wire to get the IV.
Definition crypto.h:216
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:228
uint64_t failed_verifications
number of failed verification using this cipher
Definition crypto.h:224
cipher_ctx_t * cipher
Generic cipher context.
Definition crypto.h:203
hmac_ctx_t * hmac
Generic HMAC context.
Definition crypto.h:204
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:222
Key ordering of the key2.keys array.
Definition crypto.h:259
int need_keys
The number of key objects necessary to support both sending and receiving.
Definition crypto.h:264
int in_key
Index into the key2.keys array for the receiving direction.
Definition crypto.h:262
int out_key
Index into the key2.keys array for the sending direction.
Definition crypto.h:260
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:163
unsigned int hmac_size
Number of bytes set in the HMac key material.
Definition crypto.h:174
uint16_t epoch
the epoch of the key.
Definition crypto.h:179
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:171
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:165
unsigned int cipher_size
Number of bytes set in the cipher key material.
Definition crypto.h:168
const char * cipher
const name of the cipher
Definition crypto.h:142
const char * digest
Message digest static parameters.
Definition crypto.h:143
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
Data structure for describing the packet id that is received/send to the network.
Definition packet_id.h:191
const char * filename
Definition packet_id.h:133
Wrapper struct to pass around SHA256 digests.
Definition crypto.h:133
uint8_t digest[SHA256_DIGEST_LENGTH]
Definition crypto.h:134
struct gc_arena gc
Definition test_ssl.c:138