]> git.ipfire.org Git - thirdparty/openvpn.git/blob - src/openvpn/crypto.h
show the right string for key-direction
[thirdparty/openvpn.git] / src / openvpn / crypto.h
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-2018 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2018 Fox Crypto B.V. <openvpn@fox-it.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, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24
25 /**
26 * @file Data Channel Cryptography Module
27 *
28 * @addtogroup data_crypto Data Channel Crypto module
29 *
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
40 * HMAC at all.
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").
48 *
49 * @par
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.
53 *
54 * @par
55 * \e Legenda \n
56 * <tt>[ xxx ]</tt> = unprotected \n
57 * <tt>[ - xxx - ]</tt> = authenticated \n
58 * <tt>[ * xxx * ]</tt> = encrypted and authenticated
59 *
60 * @par
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>
71 *
72 * @par
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.
79 *
80 * @par
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>
85 *
86 * @par
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.
93 *
94 * @par
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).
97 *
98 * @par
99 * In GCM mode, P_DATA_V2 headers (the opcode and peer-id) are also
100 * authenticated as Additional Data.
101 *
102 * @par
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>
109 *
110 * @par
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>
119 *
120 */
121
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
131 /** Wrapper struct to pass around SHA256 digests */
132 struct sha256_digest {
133 uint8_t digest[SHA256_DIGEST_LENGTH];
134 };
135
136 /*
137 * Defines a key type and key length for both cipher and HMAC.
138 */
139 struct key_type
140 {
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 */
145 };
146
147 /**
148 * Container for unidirectional cipher and HMAC %key material.
149 * @ingroup control_processor
150 */
151 struct key
152 {
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. */
157 };
158
159
160 /**
161 * Container for one set of cipher and/or HMAC contexts.
162 * @ingroup control_processor
163 */
164 struct key_ctx
165 {
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 */
171 };
172
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] */
176
177 /**
178 * Container for bidirectional cipher and HMAC %key material.
179 * @ingroup control_processor
180 */
181 struct key2
182 {
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
186 * material. */
187 };
188
189 /**
190 * %Key ordering of the \c key2.keys array.
191 * @ingroup control_processor
192 *
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.
197 */
198 struct key_direction_state
199 {
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
206 * receiving.
207 *
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
211 * keys. */
212 };
213
214 /**
215 * Container for two sets of OpenSSL cipher and/or HMAC contexts for both
216 * sending and receiving directions.
217 * @ingroup control_processor
218 */
219 struct key_ctx_bi
220 {
221 struct key_ctx encrypt; /**< Cipher and/or HMAC contexts for sending
222 * direction. */
223 struct key_ctx decrypt; /**< cipher and/or HMAC contexts for
224 * receiving direction. */
225 bool initialized;
226 };
227
228 /**
229 * Security parameter state for processing data channel packets.
230 * @ingroup data_crypto
231 */
232 struct crypto_options
233 {
234 struct key_ctx_bi key_ctx_bi;
235 /**< OpenSSL cipher and HMAC contexts for
236 * both sending and receiving
237 * directions. */
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. */
244
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
253 * client. */
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. */
259 };
260
261 #define CRYPT_ERROR(format) \
262 do { msg(D_CRYPT_ERRORS, "%s: " format, error_prefix); goto error_exit; } while (false)
263
264 /**
265 * Minimal IV length for AEAD mode ciphers (in bytes):
266 * 4-byte packet id + 8 bytes implicit IV.
267 */
268 #define OPENVPN_AEAD_MIN_IV_LEN (sizeof(packet_id_type) + 8)
269
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);
273
274 int write_key_file(const int nkeys, const char *filename);
275
276 int read_passphrase_hash(const char *passphrase_file,
277 const md_kt_t *digest,
278 uint8_t *output,
279 int len);
280
281 void generate_key_random(struct key *key, const struct key_type *kt);
282
283 void check_replay_consistency(const struct key_type *kt, bool packet_id);
284
285 bool check_key(struct key *key, const struct key_type *kt);
286
287 void fixup_key(struct key *key, const struct key_type *kt);
288
289 bool write_key(const struct key *key, const struct key_type *kt,
290 struct buffer *buf);
291
292 int read_key(struct key *key, const struct key_type *kt, struct buffer *buf);
293
294 /**
295 * Initialize a key_type structure with.
296 *
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.
305 */
306 void init_key_type(struct key_type *kt, const char *ciphername,
307 const char *authname, int keysize, bool tls_mode, bool warn);
308
309 /*
310 * Key context functions
311 */
312
313 void init_key_ctx(struct key_ctx *ctx, const struct key *key,
314 const struct key_type *kt, int enc,
315 const char *prefix);
316
317 void free_key_ctx(struct key_ctx *ctx);
318
319 void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2,
320 int key_direction, const struct key_type *kt,
321 const char *name);
322
323 void free_key_ctx_bi(struct key_ctx_bi *ctx);
324
325
326 /**************************************************************************/
327 /** @name Functions for performing security operations on data channel packets
328 * @{ */
329
330 /**
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
334 *
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.
339 *
340 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
341 * OpenSSL library to perform the actual security operations.
342 *
343 * If an error occurs during processing, then the \a buf %buffer is set to
344 * empty.
345 *
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.
350 *
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
354 * error occurred.
355 */
356 void openvpn_encrypt(struct buffer *buf, struct buffer work,
357 struct crypto_options *opt);
358
359
360 /**
361 * HMAC verify and decrypt a data channel packet received from a remote
362 * OpenVPN peer.
363 * @ingroup data_crypto
364 *
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.
369 *
370 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
371 * OpenSSL library to perform the actual security operations.
372 *
373 * If an error occurs during processing, then the \a buf %buffer is set to
374 * empty.
375 *
376 * @param buf - The %buffer containing the packet received from a
377 * remote OpenVPN peer on which to perform security
378 * operations.
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
382 * tunnel.
383 * @param ad_start - A pointer into buf, indicating from where to start
384 * authenticating additional data (AEAD mode only).
385 *
386 * @return
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
391 * an error occurred.
392 */
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);
396
397 /** @} name Functions for performing security operations on data channel packets */
398
399 /**
400 * Check packet ID for replay, and perform replay administration.
401 *
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.
406 *
407 * @return true if packet ID is validated to be not a replay, false otherwise.
408 */
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);
412
413
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,
417 bool packet_id,
418 bool packet_id_long_form);
419
420 /** Return the worst-case OpenVPN crypto overhead (in bytes) */
421 size_t crypto_max_overhead(void);
422
423 /* Minimum length of the nonce used by the PRNG */
424 #define NONCE_SECRET_LEN_MIN 16
425
426 /* Maximum length of the nonce used by the PRNG */
427 #define NONCE_SECRET_LEN_MAX 64
428
429 /** Number of bytes of random to allow before resetting the nonce */
430 #define PRNG_NONCE_RESET_BYTES 1024
431
432 /**
433 * Pseudo-random number generator initialisation.
434 * (see \c prng_rand_bytes())
435 *
436 * @param md_name Name of the message digest to use
437 * @param nonce_secret_len_param Length of the nonce to use
438 */
439 void prng_init(const char *md_name, const int nonce_secret_len_parm);
440
441 /*
442 * Message digest-based pseudo random number generator.
443 *
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
446 * pool.
447 *
448 * This PRNG is aimed at IV generation and similar miscellaneous tasks. Use
449 * \c rand_bytes() for higher-assurance functionality.
450 *
451 * Retrieves len bytes of pseudo random data, and places it in output.
452 *
453 * @param output Output buffer
454 * @param len Length of the output buffer
455 */
456 void prng_bytes(uint8_t *output, int len);
457
458 void prng_uninit(void);
459
460 void test_crypto(struct crypto_options *co, struct frame *f);
461
462
463 /* key direction functions */
464
465 void key_direction_state_init(struct key_direction_state *kds, int key_direction);
466
467 void verify_fix_key2(struct key2 *key2, const struct key_type *kt, const char *shared_secret_file);
468
469 void must_have_n_keys(const char *filename, const char *option, const struct key2 *key2, int n);
470
471 int ascii2keydirection(int msglevel, const char *str);
472
473 const char *keydirection2ascii(int kd, bool remote, bool humanreadable);
474
475 /* print keys */
476 void key2_print(const struct key2 *k,
477 const struct key_type *kt,
478 const char *prefix0,
479 const char *prefix1);
480
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);
484
485 /*
486 * Inline functions
487 */
488
489 /**
490 * As memcmp(), but constant-time.
491 * Returns 0 when data is equal, non-zero otherwise.
492 */
493 static inline int
494 memcmp_constant_time(const void *a, const void *b, size_t size)
495 {
496 const uint8_t *a1 = a;
497 const uint8_t *b1 = b;
498 int ret = 0;
499 size_t i;
500
501 for (i = 0; i < size; i++) {
502 ret |= *a1++ ^ *b1++;
503 }
504
505 return ret;
506 }
507
508 static inline bool
509 key_ctx_bi_defined(const struct key_ctx_bi *key)
510 {
511 return key->encrypt.cipher || key->encrypt.hmac || key->decrypt.cipher || key->decrypt.hmac;
512 }
513
514 #endif /* CRYPTO_H */