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
115#ifndef CRYPTO_H
116#define CRYPTO_H
117
118#include "crypto_backend.h"
119#include "basic.h"
120#include "buffer.h"
121#include "packet_id.h"
122#include "mtu.h"
123
129
130/*
131 * Defines a key type and key length for both cipher and HMAC.
132 */
134{
135 const char *cipher;
136 const char *digest;
137};
138
151
156{
159
161 unsigned int cipher_size;
162
165
167 unsigned int hmac_size;
168
172 uint16_t epoch;
173};
174
182void key_parameters_from_key(struct key_parameters *key_params, const struct key *key);
183
185{
187 uint16_t epoch;
188};
189
223
224#define KEY_DIRECTION_BIDIRECTIONAL 0 /* same keys for both directions */
225#define KEY_DIRECTION_NORMAL 1 /* encrypt with keys[0], decrypt with keys[1] */
226#define KEY_DIRECTION_INVERSE 2 /* encrypt with keys[1], decrypt with keys[0] */
227
232struct key2
233{
234 int n;
236 struct key keys[2];
240};
241
266
273{
279};
280
286{
297
300
303
309
318
321
325
335#define CO_PACKET_ID_LONG_FORM (1u << 0)
338#define CO_IGNORE_PACKET_ID (1u << 1)
344#define CO_MUTE_REPLAY_WARNINGS (1u << 2)
347#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1u << 3)
351#define CO_RESEND_WKC (1u << 4)
355#define CO_FORCE_TLSCRYPTV2_COOKIE (1u << 5)
359#define CO_USE_CC_EXIT_NOTIFY (1u << 6)
363#define CO_USE_DYNAMIC_TLS_CRYPT (1u << 7)
367#define CO_EPOCH_DATA_KEY_FORMAT (1u << 8)
374 unsigned int flags;
376};
377
378#define CRYPT_ERROR_EXIT(flags, format) \
379 do \
380 { \
381 msg(flags, "%s: " format, error_prefix); \
382 goto error_exit; \
383 } while (false)
384
385#define CRYPT_ERROR(format) CRYPT_ERROR_EXIT(D_CRYPT_ERRORS, format)
386#define CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format)
387
392#define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)
393
394#define RKF_MUST_SUCCEED (1 << 0)
395#define RKF_INLINE (1 << 1)
396void read_key_file(struct key2 *key2, const char *file, const unsigned int flags);
397
403int write_key_file(const int nkeys, const char *filename);
404
413void init_key_type(struct key_type *kt, const char *ciphername, const char *authname,
414 bool warn);
415
416/*
417 * Key context functions
418 */
419
420void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt,
421 int enc, const char *prefix);
422
423void init_key_bi_ctx_send(struct key_ctx *ctx, const struct key_parameters *key,
424 const struct key_type *kt, const char *name);
425
426void init_key_bi_ctx_recv(struct key_ctx *ctx, const struct key_parameters *key,
427 const struct key_type *kt, const char *name);
428
429void free_key_ctx(struct key_ctx *ctx);
430
431void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction,
432 const struct key_type *kt, const char *name);
433
434void free_key_ctx_bi(struct key_ctx_bi *ctx);
435
436
437/**************************************************************************/
467void openvpn_encrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt);
468
469
503bool openvpn_decrypt(struct buffer *buf, struct buffer work, struct crypto_options *opt,
504 const struct frame *frame, const uint8_t *ad_start);
505
519bool crypto_check_replay(struct crypto_options *opt, const struct packet_id_net *pin,
520 uint16_t epoch, const char *error_prefix, struct gc_arena *gc);
521
522
536size_t calculate_crypto_overhead(const struct key_type *kt, unsigned int pkt_id_size,
537 bool occ);
538
540unsigned int crypto_max_overhead(void);
541
549void write_pem_key_file(const char *filename, const char *key_name);
550
558bool generate_ephemeral_key(struct buffer *key, const char *pem_name);
559
570bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file,
571 bool key_inline);
572
573/*
574 * Message digest-based pseudo random number generator.
575 *
576 * If the PRNG was initialised with a certain message digest, uses the digest
577 * to calculate the next random number, and prevent depletion of the entropy
578 * pool.
579 *
580 * This PRNG is aimed at IV generation and similar miscellaneous tasks. Use
581 * \c rand_bytes() for higher-assurance functionality.
582 *
583 * Retrieves len bytes of pseudo random data, and places it in output.
584 *
585 * @param output Output buffer
586 * @param len Length of the output buffer
587 */
588void prng_bytes(uint8_t *output, int len);
589
596int64_t get_random(void);
597
599void print_cipher(const char *cipher);
600
601void test_crypto(struct crypto_options *co, const struct frame *f);
602
603
604/* key direction functions */
605
606void key_direction_state_init(struct key_direction_state *kds, int key_direction);
607
608void check_key2(struct key2 *key2);
609
610void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n);
611
612int ascii2keydirection(msglvl_t msglevel, const char *str);
613
614const char *keydirection2ascii(int kd, bool remote, bool humanreadable);
615
616/* print keys */
617void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0,
618 const char *prefix1);
619
620void crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi *ctx,
621 const char *key_file, bool key_inline, const int key_direction,
622 const char *key_name, const char *opt_name, struct key2 *keydata);
623
628void generate_test_crypto_random_key(const struct key_type *key_type, struct key_ctx_bi *ctx,
629 const char *key_name);
630
631/*
632 * Inline functions
633 */
634
639int memcmp_constant_time(const void *a, const void *b, size_t size);
640
641static inline bool
643{
644 return key->encrypt.cipher || key->encrypt.hmac || key->decrypt.cipher || key->decrypt.hmac;
645}
646
657const char *print_key_filename(const char *str, bool is_inline);
658
669static inline struct key_type
670create_kt(const char *cipher, const char *md, const char *optname)
671{
672 struct key_type kt;
673 kt.cipher = cipher;
674 kt.digest = md;
675
677 {
678 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.cipher);
679 return (struct key_type){ 0 };
680 }
681 if (md_defined(kt.digest) && !md_valid(kt.digest))
682 {
683 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.digest);
684 return (struct key_type){ 0 };
685 }
686
687 return kt;
688}
689
699uint64_t cipher_get_aead_limits(const char *ciphername);
700
704static inline bool
706{
707 /* Use 2**36, same as DTLS 1.3. Strictly speaking this only guarantees
708 * the security margin for packets up to 2^10 blocks (16384 bytes)
709 * but we accept slightly lower security bound for the edge
710 * of Chacha20-Poly1305 and packets over 16k as MTUs over 16k are
711 * extremely rarely used */
712 return ctx->failed_verifications > (1ull << 36);
713}
714
719static inline bool
721{
722 /* Use 2**35, half the amount after which we refuse to decrypt */
723 return ctx->failed_verifications > (1ull << 35);
724}
725
726
732#define AEAD_LIMIT_BLOCKSIZE 16
733
740bool check_tls_prf_working(void);
741
748static inline bool
749aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, uint64_t higest_pid)
750{
751 /* This is the q + s <= p^(1/2) * 2^(129/2) - 1 calculation where
752 * q is the number of protected messages (highest_pid)
753 * s Total plaintext length in all messages (in blocks) */
754 return (limit > 0 && key_ctx->plaintext_blocks + higest_pid > limit);
755}
756
757#endif /* CRYPTO_H */
Buffer management functions and garbage collection.
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1098
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:1240
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool warn)
Initialize a key_type structure with.
Definition crypto.c:872
void check_key2(struct key2 *key2)
Definition crypto.c:1678
void prng_bytes(uint8_t *output, int len)
Definition crypto.c:1695
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:800
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:993
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:1143
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:705
void read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
Definition crypto.c:1314
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:1787
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:1046
bool generate_ephemeral_key(struct buffer *key, const char *pem_name)
Generate ephermal key material into the key structure.
Definition crypto.c:1824
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:1842
int ascii2keydirection(msglvl_t msglevel, const char *str)
Definition crypto.c:1597
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition crypto.c:1579
const char * keydirection2ascii(int kd, bool remote, bool humanreadable)
Definition crypto.c:1620
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition crypto.c:1517
void test_crypto(struct crypto_options *co, const struct frame *f)
Definition crypto.c:1162
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:1152
void print_cipher(const char *cipher)
Print a cipher list entry.
Definition crypto.c:1715
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
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 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:1057
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
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:1879
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1649
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:847
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:1703
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:1035
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:1290
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:1251
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:380
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:670
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1079
static bool key_ctx_bi_defined(const struct key_ctx_bi *key)
Definition crypto.h:642
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:333
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:776
#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: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
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:374
struct key_ctx * epoch_data_keys_future
Keeps the future epoch data keys for decryption.
Definition crypto.h:317
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
uint16_t epoch
Definition crypto.h:187
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:233
int n
The number of key objects stored in the key2.keys array.
Definition crypto.h:234
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:236
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
size_t implicit_iv_len
The length of implicit_iv.
Definition crypto.h:211
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:209
uint16_t epoch
OpenVPN data channel epoch, this variable holds the epoch number this key belongs to.
Definition crypto.h:221
uint64_t failed_verifications
number of failed verification using this cipher
Definition crypto.h:217
cipher_ctx_t * cipher
Generic cipher context.
Definition crypto.h:196
hmac_ctx_t * hmac
Generic HMAC context.
Definition crypto.h:197
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:215
Key ordering of the key2.keys array.
Definition crypto.h:252
int need_keys
The number of key objects necessary to support both sending and receiving.
Definition crypto.h:257
int in_key
Index into the key2.keys array for the receiving direction.
Definition crypto.h:255
int out_key
Index into the key2.keys array for the sending direction.
Definition crypto.h:253
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:156
unsigned int hmac_size
Number of bytes set in the HMac key material.
Definition crypto.h:167
uint16_t epoch
the epoch of the key.
Definition crypto.h:172
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:164
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:158
unsigned int cipher_size
Number of bytes set in the cipher key material.
Definition crypto.h:161
const char * cipher
const name of the cipher
Definition crypto.h:135
const char * digest
Message digest static parameters.
Definition crypto.h:136
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
Data structure for describing the packet id that is received/send to the network.
Definition packet_id.h:171
Wrapper struct to pass around SHA256 digests.
Definition crypto.h:126
uint8_t digest[SHA256_DIGEST_LENGTH]
Definition crypto.h:127
struct gc_arena gc
Definition test_ssl.c:138