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-2010 OpenVPN Technologies, Inc. <sales@openvpn.net>
9 *  Copyright (C) 2010 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
21 *  along with this program (see the file COPYING included with this
22 *  distribution); if not, write to the Free Software Foundation, Inc.,
23 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 */
25
26/**
27 * @file Data Channel Cryptography Module
28 */
29
30#ifndef CRYPTO_H
31#define CRYPTO_H
32
33#ifdef ENABLE_CRYPTO
34
35#define ALLOW_NON_CBC_CIPHERS
36
37#include "crypto_backend.h"
38#include "basic.h"
39#include "buffer.h"
40#include "packet_id.h"
41#include "mtu.h"
42
43/*
44 * Defines a key type and key length for both cipher and HMAC.
45 */
46struct key_type
47{
48  uint8_t cipher_length; 	/**< Cipher length, in bytes */
49  uint8_t hmac_length;		/**< HMAC length, in bytes */
50  const cipher_kt_t *cipher;	/**< Cipher static parameters */
51  const md_kt_t *digest;	/**< Message digest static parameters */
52};
53
54/**
55 * Container for unidirectional cipher and HMAC %key material.
56 * @ingroup control_processor
57 */
58struct key
59{
60  uint8_t cipher[MAX_CIPHER_KEY_LENGTH];
61                                /**< %Key material for cipher operations. */
62  uint8_t hmac[MAX_HMAC_KEY_LENGTH];
63                                /**< %Key material for HMAC operations. */
64};
65
66
67/**
68 * Container for one set of OpenSSL cipher and/or HMAC contexts.
69 * @ingroup control_processor
70 */
71struct key_ctx
72{
73  cipher_ctx_t *cipher;      	/**< Generic cipher %context. */
74  hmac_ctx_t *hmac;               /**< Generic HMAC %context. */
75};
76
77#define KEY_DIRECTION_BIDIRECTIONAL 0 /* same keys for both directions */
78#define KEY_DIRECTION_NORMAL        1 /* encrypt with keys[0], decrypt with keys[1] */
79#define KEY_DIRECTION_INVERSE       2 /* encrypt with keys[1], decrypt with keys[0] */
80
81/**
82 * Container for bidirectional cipher and HMAC %key material.
83 * @ingroup control_processor
84 */
85struct key2
86{
87  int n;                        /**< The number of \c key objects stored
88                                 *   in the \c key2.keys array. */
89  struct key keys[2];           /**< Two unidirectional sets of %key
90                                 *   material. */
91};
92
93/**
94 * %Key ordering of the \c key2.keys array.
95 * @ingroup control_processor
96 *
97 * This structure takes care of correct ordering when using unidirectional
98 * or bidirectional %key material, and allows the same shared secret %key
99 * file to be loaded in the same way by client and server by having one of
100 * the hosts use an reversed ordering.
101 */
102struct key_direction_state
103{
104  int out_key;                  /**< Index into the \c key2.keys array for
105                                 *   the sending direction. */
106  int in_key;                   /**< Index into the \c key2.keys array for
107                                 *   the receiving direction. */
108  int need_keys;                /**< The number of key objects necessary
109                                 *   to support both sending and
110                                 *   receiving.
111                                 *
112                                 *   This will be 1 if the same keys are
113                                 *   used in both directions, or 2 if
114                                 *   there are two sets of unidirectional
115                                 *   keys. */
116};
117
118/**
119 * Container for two sets of OpenSSL cipher and/or HMAC contexts for both
120 * sending and receiving directions.
121 * @ingroup control_processor
122 */
123struct key_ctx_bi
124{
125  struct key_ctx encrypt;       /**< OpenSSL cipher and/or HMAC contexts
126                                 *   for sending direction. */
127  struct key_ctx decrypt;       /**< OpenSSL cipher and/or HMAC contexts
128                                 *   for receiving direction. */
129};
130
131/**
132 * Security parameter state for processing data channel packets.
133 * @ingroup data_crypto
134 */
135struct crypto_options
136{
137  struct key_ctx_bi *key_ctx_bi;
138                                /**< OpenSSL cipher and HMAC contexts for
139                                 *   both sending and receiving
140                                 *   directions. */
141  struct packet_id *packet_id;  /**< Current packet ID state for both
142                                 *   sending and receiving directions. */
143  struct packet_id_persist *pid_persist;
144                                /**< Persistent packet ID state for
145                                 *   keeping state between successive
146                                 *   OpenVPN process startups. */
147
148# define CO_PACKET_ID_LONG_FORM  (1<<0)
149                                /**< Bit-flag indicating whether to use
150                                 *   OpenVPN's long packet ID format. */
151# define CO_USE_IV               (1<<1)
152                                /**< Bit-flag indicating whether to
153                                 *   generate a pseudo-random IV for each
154                                 *   packet being encrypted. */
155# define CO_IGNORE_PACKET_ID     (1<<2)
156                                /**< Bit-flag indicating whether to ignore
157                                 *   the packet ID of a received packet.
158                                 *   This flag is used during processing
159                                 *   of the first packet received from a
160                                 *   client. */
161# define CO_MUTE_REPLAY_WARNINGS (1<<3)
162                                /**< Bit-flag indicating not to display
163                                 *   replay warnings. */
164  unsigned int flags;           /**< Bit-flags determining behavior of
165                                 *   security operation functions. */
166};
167
168#define RKF_MUST_SUCCEED (1<<0)
169#define RKF_INLINE       (1<<1)
170void read_key_file (struct key2 *key2, const char *file, const unsigned int flags);
171
172int write_key_file (const int nkeys, const char *filename);
173
174int read_passphrase_hash (const char *passphrase_file,
175			  const md_kt_t *digest,
176			  uint8_t *output,
177			  int len);
178
179void generate_key_random (struct key *key, const struct key_type *kt);
180
181void check_replay_iv_consistency(const struct key_type *kt, bool packet_id, bool use_iv);
182
183bool check_key (struct key *key, const struct key_type *kt);
184
185void fixup_key (struct key *key, const struct key_type *kt);
186
187bool write_key (const struct key *key, const struct key_type *kt,
188		struct buffer *buf);
189
190int read_key (struct key *key, const struct key_type *kt, struct buffer *buf);
191
192bool cfb_ofb_mode (const struct key_type* kt);
193
194void init_key_type (struct key_type *kt, const char *ciphername,
195    bool ciphername_defined, const char *authname, bool authname_defined,
196    int keysize, bool cfb_ofb_allowed, bool warn);
197
198/*
199 * Key context functions
200 */
201
202void init_key_ctx (struct key_ctx *ctx, struct key *key,
203		   const struct key_type *kt, int enc,
204		   const char *prefix);
205
206void free_key_ctx (struct key_ctx *ctx);
207
208void free_key_ctx_bi (struct key_ctx_bi *ctx);
209
210
211/**************************************************************************/
212/** @name Functions for performing security operations on data channel packets
213 *  @{ */
214
215/**
216 * Encrypt and HMAC sign a packet so that it can be sent as a data channel
217 * VPN tunnel packet to a remote OpenVPN peer.
218 * @ingroup data_crypto
219 *
220 * This function handles encryption and HMAC signing of a data channel
221 * packet before it is sent to its remote OpenVPN peer.  It receives the
222 * necessary security parameters in the \a opt argument, which should have
223 * been set to the correct values by the \c tls_pre_encrypt() function.
224 *
225 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
226 * OpenSSL library to perform the actual security operations.
227 *
228 * If an error occurs during processing, then the \a buf %buffer is set to
229 * empty.
230 *
231 * @param buf          - The %buffer containing the packet on which to
232 *                       perform security operations.
233 * @param work         - A working %buffer.
234 * @param opt          - The security parameter state for this VPN tunnel.
235 * @param frame        - The packet geometry parameters for this VPN
236 *                       tunnel.
237 * @return This function returns void.\n On return, the \a buf argument
238 *     will point to the resulting %buffer.  This %buffer will either
239 *     contain the processed packet ready for sending, or be empty if an
240 *     error occurred.
241 */
242void openvpn_encrypt (struct buffer *buf, struct buffer work,
243		      const struct crypto_options *opt,
244		      const struct frame* frame);
245
246
247/**
248 * HMAC verify and decrypt a data channel packet received from a remote
249 * OpenVPN peer.
250 * @ingroup data_crypto
251 *
252 * This function handles authenticating and decrypting a data channel
253 * packet received from a remote OpenVPN peer.  It receives the necessary
254 * security parameters in the \a opt argument, which should have been set
255 * to the correct values by the \c tls_pre_decrypt() function.
256 *
257 * This function calls the \c EVP_Cipher* and \c HMAC_* functions of the
258 * OpenSSL library to perform the actual security operations.
259 *
260 * If an error occurs during processing, then the \a buf %buffer is set to
261 * empty.
262 *
263 * @param buf          - The %buffer containing the packet received from a
264 *                       remote OpenVPN peer on which to perform security
265 *                       operations.
266 * @param work         - A working %buffer.
267 * @param opt          - The security parameter state for this VPN tunnel.
268 * @param frame        - The packet geometry parameters for this VPN
269 *                       tunnel.
270 *
271 * @return
272 * @li True, if the packet was authenticated and decrypted successfully.
273 * @li False, if an error occurred. \n On return, the \a buf argument will
274 *     point to the resulting %buffer.  This %buffer will either contain
275 *     the plaintext packet ready for further processing, or be empty if
276 *     an error occurred.
277 */
278bool openvpn_decrypt (struct buffer *buf, struct buffer work,
279		      const struct crypto_options *opt,
280		      const struct frame* frame);
281
282/** @} name Functions for performing security operations on data channel packets */
283
284void crypto_adjust_frame_parameters(struct frame *frame,
285				    const struct key_type* kt,
286				    bool cipher_defined,
287				    bool use_iv,
288				    bool packet_id,
289				    bool packet_id_long_form);
290
291
292/* Minimum length of the nonce used by the PRNG */
293#define NONCE_SECRET_LEN_MIN 16
294
295/* Maximum length of the nonce used by the PRNG */
296#define NONCE_SECRET_LEN_MAX 64
297
298/** Number of bytes of random to allow before resetting the nonce */
299#define PRNG_NONCE_RESET_BYTES 1024
300
301/**
302 * Pseudo-random number generator initialisation.
303 * (see \c prng_rand_bytes())
304 *
305 * @param md_name			Name of the message digest to use
306 * @param nonce_secret_len_param	Length of the nonce to use
307 */
308void prng_init (const char *md_name, const int nonce_secret_len_parm);
309
310/*
311 * Message digest-based pseudo random number generator.
312 *
313 * If the PRNG was initialised with a certain message digest, uses the digest
314 * to calculate the next random number, and prevent depletion of the entropy
315 * pool.
316 *
317 * This PRNG is aimed at IV generation and similar miscellaneous tasks. Use
318 * \c rand_bytes() for higher-assurance functionality.
319 *
320 * Retrieves len bytes of pseudo random data, and places it in output.
321 *
322 * @param output	Output buffer
323 * @param len		Length of the output buffer
324 */
325void prng_bytes (uint8_t *output, int len);
326
327void prng_uninit ();
328
329void test_crypto (const struct crypto_options *co, struct frame* f);
330
331
332/* key direction functions */
333
334void key_direction_state_init (struct key_direction_state *kds, int key_direction);
335
336void verify_fix_key2 (struct key2 *key2, const struct key_type *kt, const char *shared_secret_file);
337
338void must_have_n_keys (const char *filename, const char *option, const struct key2 *key2, int n);
339
340int ascii2keydirection (int msglevel, const char *str);
341
342const char *keydirection2ascii (int kd, bool remote);
343
344/* print keys */
345void key2_print (const struct key2* k,
346		 const struct key_type *kt,
347		 const char* prefix0,
348		 const char* prefix1);
349
350#ifdef ENABLE_SSL
351
352#define GHK_INLINE  (1<<0)
353void get_tls_handshake_key (const struct key_type *key_type,
354			    struct key_ctx_bi *ctx,
355			    const char *passphrase_file,
356			    const int key_direction,
357			    const unsigned int flags);
358
359#else
360
361void init_ssl_lib (void);
362void free_ssl_lib (void);
363
364#endif /* ENABLE_SSL */
365
366/*
367 * md5 functions
368 */
369
370struct md5_state {
371  md_ctx_t ctx;
372};
373
374struct md5_digest {
375  uint8_t digest [MD5_DIGEST_LENGTH];
376};
377
378const char *md5sum(uint8_t *buf, int len, int n_print_chars, struct gc_arena *gc);
379void md5_state_init (struct md5_state *s);
380void md5_state_update (struct md5_state *s, void *data, size_t len);
381void md5_state_final (struct md5_state *s, struct md5_digest *out);
382void md5_digest_clear (struct md5_digest *digest);
383bool md5_digest_defined (const struct md5_digest *digest);
384bool md5_digest_equal (const struct md5_digest *d1, const struct md5_digest *d2);
385
386/*
387 * Inline functions
388 */
389
390static inline bool
391key_ctx_bi_defined(const struct key_ctx_bi* key)
392{
393  return key->encrypt.cipher || key->encrypt.hmac || key->decrypt.cipher || key->decrypt.hmac;
394}
395
396
397#endif /* ENABLE_CRYPTO */
398#endif /* CRYPTO_H */
399