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-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.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
169
172
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{
303
306
309
314
323
326
330
345#define CO_PACKET_ID_LONG_FORM (1u << 0)
348#define CO_IGNORE_PACKET_ID (1u << 1)
354#define CO_MUTE_REPLAY_WARNINGS (1u << 2)
357#define CO_USE_TLS_KEY_MATERIAL_EXPORT (1u << 3)
361#define CO_RESEND_WKC (1u << 4)
365#define CO_FORCE_TLSCRYPTV2_COOKIE (1u << 5)
369#define CO_USE_CC_EXIT_NOTIFY (1u << 6)
373#define CO_USE_DYNAMIC_TLS_CRYPT (1u << 7)
377#define CO_EPOCH_DATA_KEY_FORMAT (1u << 8)
384 unsigned int flags;
386};
387
388#define CRYPT_ERROR_EXIT(flags, format) \
389 do \
390 { \
391 msg(flags, "%s: " format, error_prefix); \
392 goto error_exit; \
393 } while (false)
394
395#define CRYPT_ERROR(format) CRYPT_ERROR_EXIT(D_CRYPT_ERRORS, format)
396#define CRYPT_DROP(format) CRYPT_ERROR_EXIT(D_MULTI_DROPPED, format)
397
402#define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)
403
404#define RKF_MUST_SUCCEED (1 << 0)
405#define RKF_INLINE (1 << 1)
406void read_key_file(struct key2 *key2, const char *file, const unsigned int flags);
407
413int write_key_file(const int nkeys, const char *filename);
414
415bool check_key(struct key *key, const struct key_type *kt);
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
550unsigned int 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
604/* an analogue to the random() function, but use prng_bytes */
605long int get_random(void);
606
608void print_cipher(const char *cipher);
609
610void test_crypto(struct crypto_options *co, struct frame *f);
611
612
613/* key direction functions */
614
615void key_direction_state_init(struct key_direction_state *kds, int key_direction);
616
617void verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file);
618
619void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n);
620
621int ascii2keydirection(int msglevel, const char *str);
622
623const char *keydirection2ascii(int kd, bool remote, bool humanreadable);
624
625/* print keys */
626void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0,
627 const char *prefix1);
628
629void crypto_read_openvpn_key(const struct key_type *key_type, struct key_ctx_bi *ctx,
630 const char *key_file, bool key_inline, const int key_direction,
631 const char *key_name, const char *opt_name, struct key2 *keydata);
632
633/*
634 * Inline functions
635 */
636
641int memcmp_constant_time(const void *a, const void *b, size_t size);
642
643static inline bool
645{
646 return key->encrypt.cipher || key->encrypt.hmac || key->decrypt.cipher || key->decrypt.hmac;
647}
648
659const char *print_key_filename(const char *str, bool is_inline);
660
671static inline struct key_type
672create_kt(const char *cipher, const char *md, const char *optname)
673{
674 struct key_type kt;
675 kt.cipher = cipher;
676 kt.digest = md;
677
679 {
680 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.cipher);
681 return (struct key_type){ 0 };
682 }
683 if (md_defined(kt.digest) && !md_valid(kt.digest))
684 {
685 msg(M_WARN, "ERROR: --%s requires %s support.", optname, kt.digest);
686 return (struct key_type){ 0 };
687 }
688
689 return kt;
690}
691
701uint64_t cipher_get_aead_limits(const char *ciphername);
702
706static inline bool
708{
709 /* Use 2**36, same as DTLS 1.3. Strictly speaking this only guarantees
710 * the security margin for packets up to 2^10 blocks (16384 bytes)
711 * but we accept slightly lower security bound for the edge
712 * of Chacha20-Poly1305 and packets over 16k as MTUs over 16k are
713 * extremely rarely used */
714 return ctx->failed_verifications > (1ull << 36);
715}
716
721static inline bool
723{
724 /* Use 2**35, half the amount after which we refuse to decrypt */
725 return ctx->failed_verifications > (1ull << 35);
726}
727
728
734#define AEAD_LIMIT_BLOCKSIZE 16
735
742bool check_tls_prf_working(void);
743
750static inline bool
751aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, int64_t higest_pid)
752{
753 /* This is the q + s <= p^(1/2) * 2^(129/2) - 1 calculation where
754 * q is the number of protected messages (highest_pid)
755 * s Total plaintext length in all messages (in blocks) */
756 return (limit > 0 && key_ctx->plaintext_blocks + (uint64_t)higest_pid > limit);
757}
758
759#endif /* CRYPTO_H */
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1094
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:1273
void prng_bytes(uint8_t *output, int len)
Definition crypto.c:1709
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:990
unsigned int 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:797
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:1174
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:707
void verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file)
Definition crypto.c:1693
void read_key_file(struct key2 *key2, const char *file, const unsigned int flags)
Definition crypto.c:1335
long int get_random(void)
Definition crypto.c:1716
void test_crypto(struct crypto_options *co, struct frame *f)
Definition crypto.c:1193
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:1803
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:1044
bool generate_ephemeral_key(struct buffer *key, const char *pem_name)
Generate ephermal key material into the key structure.
Definition crypto.c:1840
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:1858
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:869
int ascii2keydirection(int msglevel, const char *str)
Definition crypto.c:1612
void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n)
Definition crypto.c:1594
const char * keydirection2ascii(int kd, bool remote, bool humanreadable)
Definition crypto.c:1635
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition crypto.c:1536
bool check_key(struct key *key, const struct key_type *kt)
Definition crypto.c:1120
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:1183
void print_cipher(const char *cipher)
Print a cipher list entry.
Definition crypto.c:1728
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 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:1056
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
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:1895
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1664
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:844
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:1032
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:1284
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
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:369
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:672
void free_key_ctx(struct key_ctx *ctx)
Definition crypto.c:1075
static bool key_ctx_bi_defined(const struct key_ctx_bi *key)
Definition crypto.h:644
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.
mbedtls_cipher_context_t cipher_ctx_t
Generic cipher context.
mbedtls_md_context_t hmac_ctx_t
Generic HMAC context.
#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:322
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:773
#define msg(flags,...)
Definition error.h:150
#define M_WARN
Definition error.h:90
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
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
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:384
struct key_ctx * epoch_data_keys_future
Keeps the future epoch data keys for decryption.
Definition crypto.h:322
struct packet_id_persist * pid_persist
Persistent packet ID state for keeping state between successive OpenVPN process startups.
Definition crypto.h:340
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
uint16_t epoch
Definition crypto.h:194
Packet geometry parameters.
Definition mtu.h:103
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:116
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
int hmac_size
Number of bytes set in the HMac key material.
Definition crypto.h:174
int cipher_size
Number of bytes set in the cipher key material.
Definition crypto.h:168
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
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:154