]>
git.ipfire.org Git - thirdparty/openvpn.git/blob - src/openvpn/crypto.h
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
8 * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.com>
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.
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.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * @file Data Channel Cryptography Module
28 * @addtogroup data_crypto Data Channel Crypto module
30 * @par Crypto packet formats
31 * The Data Channel Crypto module supports a number of crypto modes and
32 * configurable options. The actual packet format depends on these options. A
33 * Data Channel packet can consist of:
34 * - \b Opcode, one byte specifying the packet type (see @ref network_protocol
35 * "Network protocol").
36 * - \b Peer-id, if using the v2 data channel packet format (see @ref
37 * network_protocol "Network protocol").
38 * - \b HMAC, covering the ciphertext IV + ciphertext. The HMAC size depends
39 * on the \c \-\-auth option. If \c \-\-auth \c none is specified, there is no
41 * - \b Ciphertext \b IV. The IV size depends on the \c \-\-cipher option.
42 * - \b Packet \b ID, a 32-bit incrementing packet counter that provides replay
43 * protection (if not disabled by \c \-\-no-replay).
44 * - \b Timestamp, a 32-bit timestamp of the current time.
45 * - \b Payload, the plain text network packet to be encrypted (unless
46 * encryption is disabled by using \c \-\-cipher \c none). The payload might
47 * already be compressed (see @ref compression "Compression module").
50 * This section does not discuss the opcode and peer-id, since those do not
51 * depend on the data channel crypto. See @ref network_protocol
52 * "Network protocol" for more information on those.
56 * <tt>[ xxx ]</tt> = unprotected \n
57 * <tt>[ - xxx - ]</tt> = authenticated \n
58 * <tt>[ * xxx * ]</tt> = encrypted and authenticated
61 * <b>CBC data channel cypto format</b> \n
62 * In CBC mode, both TLS-mode and static key mode are supported. The IV
63 * consists of random bits to provide unpredictable IVs. \n
64 * <i>CBC IV format:</i> \n
65 * <tt> [ - random - ] </tt> \n
66 * <i>CBC data channel crypto format in TLS-mode:</i> \n
67 * <tt> [ HMAC ] [ - IV - ] [ * packet ID * ] [ * packet payload * ] </tt> \n
68 * <i>CBC data channel crypto format in static key mode:</i> \n
69 * <tt> [ HMAC ] [ - IV - ] [ * packet ID * ] [ * timestamp * ]
70 * [ * packet payload * ] </tt>
73 * <b>CFB/OFB data channel crypto format</b> \n
74 * CFB and OFB modes are only supported in TLS mode. In these modes, the IV
75 * consists of the packet counter and a timestamp. If the IV is more than 8
76 * bytes long, the remaining space is filled with zeroes. The packet counter may
77 * not roll over within a single TLS sessions. This results in a unique IV for
78 * each packet, as required by the CFB and OFB cipher modes.
81 * <i>CFB/OFB IV format:</i> \n
82 * <tt> [ - packet ID - ] [ - timestamp - ] [ - opt: zero-padding - ] </tt>\n
83 * <i>CFB/OFB data channel crypto format:</i> \n
84 * <tt> [ HMAC ] [ - IV - ] [ * packet payload * ] </tt>
87 * <b>GCM data channel crypto format</b> \n
88 * GCM modes are only supported in TLS mode. In these modes, the IV consists of
89 * the 32-bit packet counter followed by data from the HMAC key. The HMAC key
90 * can be used as IV, since in GCM and CCM modes the HMAC key is not used for
91 * the HMAC. The packet counter may not roll over within a single TLS sessions.
92 * This results in a unique IV for each packet, as required by GCM.
95 * The HMAC key data is pre-shared during the connection setup, and thus can be
96 * omitted in on-the-wire packets, saving 8 bytes per packet (for GCM and CCM).
99 * In GCM mode, P_DATA_V2 headers (the opcode and peer-id) are also
100 * authenticated as Additional Data.
103 * <i>GCM IV format:</i> \n
104 * <tt> [ - packet ID - ] [ - HMAC key data - ] </tt>\n
105 * <i>P_DATA_V1 GCM data channel crypto format:</i> \n
106 * <tt> [ opcode ] [ - packet ID - ] [ TAG ] [ * packet payload * ] </tt>
107 * <i>P_DATA_V2 GCM data channel crypto format:</i> \n
108 * <tt> [ - opcode/peer-id - ] [ - packet ID - ] [ TAG ] [ * packet payload * ] </tt>
111 * <b>No-crypto data channel format</b> \n
112 * In no-crypto mode (\c \-\-cipher \c none is specified), both TLS-mode and
113 * static key mode are supported. No encryption will be performed on the packet,
114 * but packets can still be authenticated. This mode does not require an IV.\n
115 * <i>No-crypto data channel crypto format in TLS-mode:</i> \n
116 * <tt> [ HMAC ] [ - packet ID - ] [ - packet payload - ] </tt> \n
117 * <i>No-crypto data channel crypto format in static key mode:</i> \n
118 * <tt> [ HMAC ] [ - packet ID - ] [ - timestamp - ] [ - packet payload - ] </tt>
125 #include "crypto_backend.h"
128 #include "packet_id.h"
131 /** Wrapper struct to pass around SHA256 digests */
132 struct sha256_digest
{
133 uint8_t digest
[SHA256_DIGEST_LENGTH
];
137 * Defines a key type and key length for both cipher and HMAC.
141 uint8_t cipher_length
; /**< Cipher length, in bytes */
142 uint8_t hmac_length
; /**< HMAC length, in bytes */
143 const cipher_kt_t
*cipher
; /**< Cipher static parameters */
144 const md_kt_t
*digest
; /**< Message digest static parameters */
148 * Container for unidirectional cipher and HMAC %key material.
149 * @ingroup control_processor
153 uint8_t cipher
[MAX_CIPHER_KEY_LENGTH
];
154 /**< %Key material for cipher operations. */
155 uint8_t hmac
[MAX_HMAC_KEY_LENGTH
];
156 /**< %Key material for HMAC operations. */
161 * Container for one set of cipher and/or HMAC contexts.
162 * @ingroup control_processor
166 cipher_ctx_t
*cipher
; /**< Generic cipher %context. */
167 hmac_ctx_t
*hmac
; /**< Generic HMAC %context. */
168 uint8_t implicit_iv
[OPENVPN_MAX_IV_LENGTH
];
169 /**< The implicit part of the IV */
170 size_t implicit_iv_len
; /**< The length of implicit_iv */
173 #define KEY_DIRECTION_BIDIRECTIONAL 0 /* same keys for both directions */
174 #define KEY_DIRECTION_NORMAL 1 /* encrypt with keys[0], decrypt with keys[1] */
175 #define KEY_DIRECTION_INVERSE 2 /* encrypt with keys[1], decrypt with keys[0] */
178 * Container for bidirectional cipher and HMAC %key material.
179 * @ingroup control_processor
183 int n
; /**< The number of \c key objects stored
184 * in the \c key2.keys array. */
185 struct key keys
[2]; /**< Two unidirectional sets of %key
190 * %Key ordering of the \c key2.keys array.
191 * @ingroup control_processor
193 * This structure takes care of correct ordering when using unidirectional
194 * or bidirectional %key material, and allows the same shared secret %key
195 * file to be loaded in the same way by client and server by having one of
196 * the hosts use an reversed ordering.
198 struct key_direction_state
200 int out_key
; /**< Index into the \c key2.keys array for
201 * the sending direction. */
202 int in_key
; /**< Index into the \c key2.keys array for
203 * the receiving direction. */
204 int need_keys
; /**< The number of key objects necessary
205 * to support both sending and
208 * This will be 1 if the same keys are
209 * used in both directions, or 2 if
210 * there are two sets of unidirectional
215 * Container for two sets of OpenSSL cipher and/or HMAC contexts for both
216 * sending and receiving directions.
217 * @ingroup control_processor
221 struct key_ctx encrypt
; /**< Cipher and/or HMAC contexts for sending
223 struct key_ctx decrypt
; /**< cipher and/or HMAC contexts for
224 * receiving direction. */
229 * Security parameter state for processing data channel packets.
230 * @ingroup data_crypto
232 struct crypto_options
234 struct key_ctx_bi key_ctx_bi
;
235 /**< OpenSSL cipher and HMAC contexts for
236 * both sending and receiving
238 struct packet_id packet_id
; /**< Current packet ID state for both
239 * sending and receiving directions. */
240 struct packet_id_persist
*pid_persist
;
241 /**< Persistent packet ID state for
242 * keeping state between successive
243 * OpenVPN process startups. */
245 #define CO_PACKET_ID_LONG_FORM (1<<0)
246 /**< Bit-flag indicating whether to use
247 * OpenVPN's long packet ID format. */
248 #define CO_IGNORE_PACKET_ID (1<<1)
249 /**< Bit-flag indicating whether to ignore
250 * the packet ID of a received packet.
251 * This flag is used during processing
252 * of the first packet received from a
254 #define CO_MUTE_REPLAY_WARNINGS (1<<2)
255 /**< Bit-flag indicating not to display
256 * replay warnings. */
257 unsigned int flags
; /**< Bit-flags determining behavior of
258 * security operation functions. */
261 #define CRYPT_ERROR(format) \
262 do { msg(D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
265 * Minimal IV length for AEAD mode ciphers (in bytes):
266 * 4-byte packet id + 8 bytes implicit IV.
268 #define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)
270 #define RKF_MUST_SUCCEED (1<<0)
271 #define RKF_INLINE (1<<1)
272 void read_key_file(struct key2
*key2
, const char *file
, const unsigned int flags
);
274 int write_key_file(const int nkeys
, const char *filename
);
276 int read_passphrase_hash(const char *passphrase_file
,
277 const md_kt_t
*digest
,
281 void generate_key_random(struct key
*key
, const struct key_type
*kt
);
283 void check_replay_consistency(const struct key_type
*kt
, bool packet_id
);
285 bool check_key(struct key
*key
, const struct key_type
*kt
);
287 void fixup_key(struct key
*key
, const struct key_type
*kt
);
289 bool write_key(const struct key
*key
, const struct key_type
*kt
,
292 int read_key(struct key
*key
, const struct key_type
*kt
, struct buffer
*buf
);
295 * Initialize a key_type structure with.
297 * @param kt The struct key_type to initialize
298 * @param ciphername The name of the cipher to use
299 * @param authname The name of the HMAC digest to use
300 * @param keysize The length of the cipher key to use, in bytes. Only valid
301 * for ciphers that support variable length keys.
302 * @param tls_mode Specifies wether we are running in TLS mode, which allows
303 * more ciphers than static key mode.
304 * @param warn Print warnings when null cipher / auth is used.
306 void init_key_type(struct key_type
*kt
, const char *ciphername
,
307 const char *authname
, int keysize
, bool tls_mode
, bool warn
);
310 * Key context functions
313 void init_key_ctx(struct key_ctx
*ctx
, const struct key
*key
,
314 const struct key_type
*kt
, int enc
,
317 void free_key_ctx(struct key_ctx
*ctx
);
319 void init_key_ctx_bi(struct key_ctx_bi
*ctx
, const struct key2
*key2
,
320 int key_direction
, const struct key_type
*kt
,
323 void free_key_ctx_bi(struct key_ctx_bi
*ctx
);
326 /**************************************************************************/
327 /** @name Functions for performing security operations on data channel packets
331 * Encrypt and HMAC sign a packet so that it can be sent as a data channel
332 * VPN tunnel packet to a remote OpenVPN peer.
333 * @ingroup data_crypto
335 * This function handles encryption and HMAC signing of a data channel
336 * packet before it is sent to its remote OpenVPN peer. It receives the
337 * necessary security parameters in the \a opt argument, which should have
338 * been set to the correct values by the \c tls_pre_encrypt() function.
340 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
341 * OpenSSL library to perform the actual security operations.
343 * If an error occurs during processing, then the \a buf %buffer is set to
346 * @param buf - The %buffer containing the packet on which to
347 * perform security operations.
348 * @param work - An initialized working %buffer.
349 * @param opt - The security parameter state for this VPN tunnel.
351 * @return This function returns void.\n On return, the \a buf argument
352 * will point to the resulting %buffer. This %buffer will either
353 * contain the processed packet ready for sending, or be empty if an
356 void openvpn_encrypt(struct buffer
*buf
, struct buffer work
,
357 struct crypto_options
*opt
);
361 * HMAC verify and decrypt a data channel packet received from a remote
363 * @ingroup data_crypto
365 * This function handles authenticating and decrypting a data channel
366 * packet received from a remote OpenVPN peer. It receives the necessary
367 * security parameters in the \a opt argument, which should have been set
368 * to the correct values by the \c tls_pre_decrypt() function.
370 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
371 * OpenSSL library to perform the actual security operations.
373 * If an error occurs during processing, then the \a buf %buffer is set to
376 * @param buf - The %buffer containing the packet received from a
377 * remote OpenVPN peer on which to perform security
379 * @param work - A working %buffer.
380 * @param opt - The security parameter state for this VPN tunnel.
381 * @param frame - The packet geometry parameters for this VPN
383 * @param ad_start - A pointer into buf, indicating from where to start
384 * authenticating additional data (AEAD mode only).
387 * @li True, if the packet was authenticated and decrypted successfully.
388 * @li False, if an error occurred. \n On return, the \a buf argument will
389 * point to the resulting %buffer. This %buffer will either contain
390 * the plaintext packet ready for further processing, or be empty if
393 bool openvpn_decrypt(struct buffer
*buf
, struct buffer work
,
394 struct crypto_options
*opt
, const struct frame
*frame
,
395 const uint8_t *ad_start
);
397 /** @} name Functions for performing security operations on data channel packets */
400 * Check packet ID for replay, and perform replay administration.
402 * @param opt Crypto options for this packet, contains replay state.
403 * @param pin Packet ID read from packet.
404 * @param error_prefix Prefix to use when printing error messages.
405 * @param gc Garbage collector to use.
407 * @return true if packet ID is validated to be not a replay, false otherwise.
409 bool crypto_check_replay(struct crypto_options
*opt
,
410 const struct packet_id_net
*pin
, const char *error_prefix
,
411 struct gc_arena
*gc
);
414 /** Calculate crypto overhead and adjust frame to account for that */
415 void crypto_adjust_frame_parameters(struct frame
*frame
,
416 const struct key_type
*kt
,
418 bool packet_id_long_form
);
420 /** Return the worst-case OpenVPN crypto overhead (in bytes) */
421 size_t crypto_max_overhead(void);
423 /* Minimum length of the nonce used by the PRNG */
424 #define NONCE_SECRET_LEN_MIN 16
426 /* Maximum length of the nonce used by the PRNG */
427 #define NONCE_SECRET_LEN_MAX 64
429 /** Number of bytes of random to allow before resetting the nonce */
430 #define PRNG_NONCE_RESET_BYTES 1024
433 * Pseudo-random number generator initialisation.
434 * (see \c prng_rand_bytes())
436 * @param md_name Name of the message digest to use
437 * @param nonce_secret_len_param Length of the nonce to use
439 void prng_init(const char *md_name
, const int nonce_secret_len_parm
);
442 * Message digest-based pseudo random number generator.
444 * If the PRNG was initialised with a certain message digest, uses the digest
445 * to calculate the next random number, and prevent depletion of the entropy
448 * This PRNG is aimed at IV generation and similar miscellaneous tasks. Use
449 * \c rand_bytes() for higher-assurance functionality.
451 * Retrieves len bytes of pseudo random data, and places it in output.
453 * @param output Output buffer
454 * @param len Length of the output buffer
456 void prng_bytes(uint8_t *output
, int len
);
458 void prng_uninit(void);
460 void test_crypto(struct crypto_options
*co
, struct frame
*f
);
463 /* key direction functions */
465 void key_direction_state_init(struct key_direction_state
*kds
, int key_direction
);
467 void verify_fix_key2(struct key2
*key2
, const struct key_type
*kt
, const char *shared_secret_file
);
469 void must_have_n_keys(const char *filename
, const char *option
, const struct key2
*key2
, int n
);
471 int ascii2keydirection(int msglevel
, const char *str
);
473 const char *keydirection2ascii(int kd
, bool remote
, bool humanreadable
);
476 void key2_print(const struct key2
*k
,
477 const struct key_type
*kt
,
479 const char *prefix1
);
481 void crypto_read_openvpn_key(const struct key_type
*key_type
,
482 struct key_ctx_bi
*ctx
, const char *key_file
, const char *key_inline
,
483 const int key_direction
, const char *key_name
, const char *opt_name
);
490 * As memcmp(), but constant-time.
491 * Returns 0 when data is equal, non-zero otherwise.
494 memcmp_constant_time(const void *a
, const void *b
, size_t size
)
496 const uint8_t *a1
= a
;
497 const uint8_t *b1
= b
;
501 for (i
= 0; i
< size
; i
++) {
502 ret
|= *a1
++ ^ *b1
++;
509 key_ctx_bi_defined(const struct key_ctx_bi
*key
)
511 return key
->encrypt
.cipher
|| key
->encrypt
.hmac
|| key
->decrypt
.cipher
|| key
->decrypt
.hmac
;
514 #endif /* CRYPTO_H */