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 Control Channel SSL/Data channel negotiation module
28 */
29
30#ifndef OPENVPN_SSL_H
31#define OPENVPN_SSL_H
32
33#if defined(ENABLE_CRYPTO) && defined(ENABLE_SSL)
34
35#include "basic.h"
36#include "common.h"
37#include "crypto.h"
38#include "packet_id.h"
39#include "session_id.h"
40#include "reliable.h"
41#include "socket.h"
42#include "mtu.h"
43#include "options.h"
44#include "plugin.h"
45
46#include "ssl_common.h"
47#include "ssl_verify.h"
48#include "ssl_backend.h"
49
50/* Used in the TLS PRF function */
51#define KEY_EXPANSION_ID "OpenVPN"
52
53/* packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one byte */
54#define P_KEY_ID_MASK                  0x07
55#define P_OPCODE_SHIFT                 3
56
57/* packet opcodes -- the V1 is intended to allow protocol changes in the future */
58#define P_CONTROL_HARD_RESET_CLIENT_V1 1     /* initial key from client, forget previous state */
59#define P_CONTROL_HARD_RESET_SERVER_V1 2     /* initial key from server, forget previous state */
60#define P_CONTROL_SOFT_RESET_V1        3     /* new key, graceful transition from old to new key */
61#define P_CONTROL_V1                   4     /* control channel packet (usually TLS ciphertext) */
62#define P_ACK_V1                       5     /* acknowledgement for packets received */
63#define P_DATA_V1                      6     /* data channel packet */
64
65/* indicates key_method >= 2 */
66#define P_CONTROL_HARD_RESET_CLIENT_V2 7     /* initial key from client, forget previous state */
67#define P_CONTROL_HARD_RESET_SERVER_V2 8     /* initial key from server, forget previous state */
68
69/* define the range of legal opcodes */
70#define P_FIRST_OPCODE                 1
71#define P_LAST_OPCODE                  8
72
73/* Should we aggregate TLS
74 * acknowledgements, and tack them onto
75 * control packets? */
76#define TLS_AGGREGATE_ACK
77
78/*
79 * If TLS_AGGREGATE_ACK, set the
80 * max number of acknowledgments that
81 * can "hitch a ride" on an outgoing
82 * non-P_ACK_V1 control packet.
83 */
84#define CONTROL_SEND_ACK_MAX 4
85
86/*
87 * Define number of buffers for send and receive in the reliability layer.
88 */
89#define TLS_RELIABLE_N_SEND_BUFFERS  4 /* also window size for reliablity layer */
90#define TLS_RELIABLE_N_REC_BUFFERS   8
91
92/*
93 * Various timeouts
94 */
95#define TLS_MULTI_REFRESH 15    /* call tls_multi_process once every n seconds */
96#define TLS_MULTI_HORIZON 2     /* call tls_multi_process frequently for n seconds after
97				   every packet sent/received action */
98
99/*
100 * The SSL/TLS worker thread will wait at most this many seconds for the
101 * interprocess communication pipe to the main thread to be ready to accept
102 * writes.
103 */
104#define TLS_MULTI_THREAD_SEND_TIMEOUT 5
105
106/* Interval that tls_multi_process should call tls_authentication_status */
107#define TLS_MULTI_AUTH_STATUS_INTERVAL 10
108
109/*
110 * Buffer sizes (also see mtu.h).
111 */
112
113/* Maximum length of OCC options string passed as part of auth handshake */
114#define TLS_OPTIONS_LEN 512
115
116/* Default field in X509 to be username */
117#define X509_USERNAME_FIELD_DEFAULT "CN"
118
119/*
120 * Range of key exchange methods
121 */
122#define KEY_METHOD_MIN 1
123#define KEY_METHOD_MAX 2
124
125/* key method taken from lower 4 bits */
126#define KEY_METHOD_MASK 0x0F
127
128/*
129 * Measure success rate of TLS handshakes, for debugging only
130 */
131/* #define MEASURE_TLS_HANDSHAKE_STATS */
132
133/*
134 * Used in --mode server mode to check tls-auth signature on initial
135 * packets received from new clients.
136 */
137struct tls_auth_standalone
138{
139  struct key_ctx_bi tls_auth_key;
140  struct crypto_options tls_auth_options;
141  struct frame frame;
142};
143
144/*
145 * Prepare the SSL library for use
146 */
147void init_ssl_lib (void);
148
149/*
150 * Free any internal state that the SSL library might have
151 */
152void free_ssl_lib (void);
153
154/**
155 * Build master SSL context object that serves for the whole of OpenVPN
156 * instantiation
157 */
158void init_ssl (const struct options *options, struct tls_root_ctx *ctx);
159
160/** @addtogroup control_processor
161 *  @{ */
162
163/** @name Functions for initialization and cleanup of tls_multi structures
164 *  @{ */
165
166/**
167 * Allocate and initialize a \c tls_multi structure.
168 * @ingroup control_processor
169 *
170 * This function allocates a new \c tls_multi structure, and performs some
171 * amount of initialization.  Afterwards, the \c tls_multi_init_finalize()
172 * function must be called to finalize the structure's initialization
173 * process.
174 *
175 * @param tls_options  - The configuration options to be used for this VPN
176 *                       tunnel.
177 *
178 * @return A newly allocated and initialized \c tls_multi structure.
179 */
180struct tls_multi *tls_multi_init (struct tls_options *tls_options);
181
182/**
183 * Finalize initialization of a \c tls_multi structure.
184 * @ingroup control_processor
185 *
186 * This function initializes the \c TM_ACTIVE \c tls_session, and in
187 * server mode also the \c TM_UNTRUSTED \c tls_session, associated with
188 * this \c tls_multi structure.  It also configures the control channel's
189 * \c frame structure based on the data channel's \c frame given in
190 * argument \a frame.
191 *
192 * @param multi        - The \c tls_multi structure of which to finalize
193 *                       initialization.
194 * @param frame        - The data channel's \c frame structure.
195 */
196void tls_multi_init_finalize(struct tls_multi *multi,
197			     const struct frame *frame);
198
199/*
200 * Initialize a standalone tls-auth verification object.
201 */
202struct tls_auth_standalone *tls_auth_standalone_init (struct tls_options *tls_options,
203						      struct gc_arena *gc);
204
205/*
206 * Finalize a standalone tls-auth verification object.
207 */
208void tls_auth_standalone_finalize (struct tls_auth_standalone *tas,
209				   const struct frame *frame);
210
211/*
212 * Set local and remote option compatibility strings.
213 * Used to verify compatibility of local and remote option
214 * sets.
215 */
216void tls_multi_init_set_options(struct tls_multi* multi,
217				const char *local,
218				const char *remote);
219
220/**
221 * Cleanup a \c tls_multi structure and free associated memory
222 * allocations.
223 * @ingroup control_processor
224 *
225 * This function cleans up a \c tls_multi structure.  This includes
226 * cleaning up all associated \c tls_session structures.
227 *
228 * @param multi        - The \c tls_multi structure to clean up in free.
229 * @param clear        - Whether the memory allocated for the \a multi
230 *                       object should be overwritten with 0s.
231 */
232void tls_multi_free (struct tls_multi *multi, bool clear);
233
234/** @} name Functions for initialization and cleanup of tls_multi structures */
235
236/** @} addtogroup control_processor */
237
238#define TLSMP_INACTIVE 0
239#define TLSMP_ACTIVE   1
240#define TLSMP_KILL     2
241
242/*
243 * Called by the top-level event loop.
244 *
245 * Basically decides if we should call tls_process for
246 * the active or untrusted sessions.
247 */
248int tls_multi_process (struct tls_multi *multi,
249		       struct buffer *to_link,
250		       struct link_socket_actual **to_link_addr,
251		       struct link_socket_info *to_link_socket_info,
252		       interval_t *wakeup);
253
254
255/**************************************************************************/
256/**
257 * Determine whether an incoming packet is a data channel or control
258 * channel packet, and process accordingly.
259 * @ingroup external_multiplexer
260 *
261 * When OpenVPN is in TLS mode, this is the first function to process an
262 * incoming packet.  It inspects the packet's one-byte header which
263 * contains the packet's opcode and key ID.  Depending on the opcode, the
264 * packet is processed as a data channel or as a control channel packet.
265 *
266 * @par Data channel packets
267 *
268 * If the opcode indicates the packet is a data channel packet, then the
269 * packet's key ID is used to find the local TLS state it is associated
270 * with.  This state is checked whether it is active, authenticated, and
271 * its remote peer is the source of this packet.  If these checks passed,
272 * the state's security parameters are loaded into the \a opt crypto
273 * options so that \p openvpn_decrypt() can later use them to authenticate
274 * and decrypt the packet.
275 *
276 * This function then returns false.  The \a buf buffer has not been
277 * modified, except for removing the header.
278 *
279 * @par Control channel packets
280 *
281 * If the opcode indicates the packet is a control channel packet, then
282 * this function will process it based on its plaintext header. depending
283 * on the packet's opcode and session ID this function determines if it is
284 * destined for an active TLS session, or whether a new TLS session should
285 * be started.  This function also initiates data channel session key
286 * renegotiation if the received opcode requests that.
287 *
288 * If the incoming packet is destined for an active TLS session, then the
289 * packet is inserted into the Reliability Layer and will be handled
290 * later.
291 *
292 * @param multi - The TLS multi structure associated with the VPN tunnel
293 *     of this packet.
294 * @param from - The source address of the packet.
295 * @param buf - A buffer structure containing the incoming packet.
296 * @param opt - A crypto options structure that will be loaded with the
297 *     appropriate security parameters to handle the packet if it is a
298 *     data channel packet.
299 *
300 * @return
301 * @li True if the packet is a control channel packet that has been
302 *     processed successfully.
303 * @li False if the packet is a data channel packet, or if an error
304 *     occurred during processing of a control channel packet.
305 */
306bool tls_pre_decrypt (struct tls_multi *multi,
307		      const struct link_socket_actual *from,
308		      struct buffer *buf,
309		      struct crypto_options *opt);
310
311
312/**************************************************************************/
313/** @name Functions for managing security parameter state for data channel packets
314 *  @{ */
315
316/**
317 * Inspect an incoming packet for which no VPN tunnel is active, and
318 * determine whether a new VPN tunnel should be created.
319 * @ingroup data_crypto
320 *
321 * This function receives the initial incoming packet from a client that
322 * wishes to establish a new VPN tunnel, and determines the packet is a
323 * valid initial packet.  It is only used when OpenVPN is running in
324 * server mode.
325 *
326 * The tests performed by this function are whether the packet's opcode is
327 * correct for establishing a new VPN tunnel, whether its key ID is 0, and
328 * whether its size is not too large.  This function also performs the
329 * initial HMAC firewall test, if configured to do so.
330 *
331 * The incoming packet and the local VPN tunnel state are not modified by
332 * this function.  Its sole purpose is to inspect the packet and determine
333 * whether a new VPN tunnel should be created.  If so, that new VPN tunnel
334 * instance will handle processing of the packet.
335 *
336 * @param tas - The standalone TLS authentication setting structure for
337 *     this process.
338 * @param from - The source address of the packet.
339 * @param buf - A buffer structure containing the incoming packet.
340 *
341 * @return
342 * @li True if the packet is valid and a new VPN tunnel should be created
343 *     for this client.
344 * @li False if the packet is not valid, did not pass the HMAC firewall
345 *     test, or some other error occurred.
346 */
347bool tls_pre_decrypt_lite (const struct tls_auth_standalone *tas,
348			   const struct link_socket_actual *from,
349			   const struct buffer *buf);
350
351
352/**
353 * Choose the appropriate security parameters with which to process an
354 * outgoing packet.
355 * @ingroup data_crypto
356 *
357 * If no appropriate security parameters can be found, or if some other
358 * error occurs, then the buffer is set to empty.
359 *
360 * @param multi - The TLS state for this packet's destination VPN tunnel.
361 * @param buf - The buffer containing the outgoing packet.
362 * @param opt - The crypto options structure into which the appropriate
363 *     security parameters should be loaded.
364 */
365void tls_pre_encrypt (struct tls_multi *multi,
366		      struct buffer *buf, struct crypto_options *opt);
367
368
369/**
370 * Prepend the one-byte OpenVPN header to the packet, and perform some
371 * accounting for the key state used.
372 * @ingroup data_crypto
373 *
374 * @param multi - The TLS state for this packet's destination VPN tunnel.
375 * @param buf - The buffer containing the outgoing packet.
376 */
377void tls_post_encrypt (struct tls_multi *multi, struct buffer *buf);
378
379/** @} name Functions for managing security parameter state for data channel packets */
380
381/*
382 * Setup private key file password. If auth_file is given, use the
383 * credentials stored in the file.
384 */
385void pem_password_setup (const char *auth_file);
386
387/*
388 * Setup authentication username and password. If auth_file is given, use the
389 * credentials stored in the file.
390 */
391void auth_user_pass_setup (const char *auth_file, const struct static_challenge_info *sc_info);
392
393/*
394 * Ensure that no caching is performed on authentication information
395 */
396void ssl_set_auth_nocache (void);
397
398/*
399 * Purge any stored authentication information, both for key files and tunnel
400 * authentication. If PCKS #11 is enabled, purge authentication for that too.
401 */
402void ssl_purge_auth (const bool auth_user_pass_only);
403
404void ssl_set_auth_token (const char *token);
405
406#ifdef ENABLE_CLIENT_CR
407/*
408 * ssl_get_auth_challenge will parse the server-pushed auth-failed
409 * reason string and return a dynamically allocated
410 * auth_challenge_info struct.
411 */
412void ssl_purge_auth_challenge (void);
413void ssl_put_auth_challenge (const char *cr_str);
414#endif
415
416/*
417 * Reserve any extra space required on frames.
418 */
419void tls_adjust_frame_parameters(struct frame *frame);
420
421/*
422 * Send a payload over the TLS control channel
423 */
424bool tls_send_payload (struct tls_multi *multi,
425		       const uint8_t *data,
426		       int size);
427
428/*
429 * Receive a payload through the TLS control channel
430 */
431bool tls_rec_payload (struct tls_multi *multi,
432		      struct buffer *buf);
433
434#ifdef MANAGEMENT_DEF_AUTH
435static inline char *
436tls_get_peer_info(const struct tls_multi *multi)
437{
438  return multi->peer_info;
439}
440#endif
441
442/*
443 * inline functions
444 */
445
446static inline bool
447tls_initial_packet_received (const struct tls_multi *multi)
448{
449  return multi->n_sessions > 0;
450}
451
452static inline bool
453tls_test_auth_deferred_interval (const struct tls_multi *multi)
454{
455  if (multi)
456    {
457      const struct key_state *ks = &multi->session[TM_ACTIVE].key[KS_PRIMARY];
458      return now < ks->auth_deferred_expire;
459    }
460  return false;
461}
462
463static inline int
464tls_test_payload_len (const struct tls_multi *multi)
465{
466  if (multi)
467    {
468      const struct key_state *ks = &multi->session[TM_ACTIVE].key[KS_PRIMARY];
469      if (ks->state >= S_ACTIVE)
470	return BLEN (&ks->plaintext_read_buf);
471    }
472  return 0;
473}
474
475static inline void
476tls_set_single_session (struct tls_multi *multi)
477{
478  if (multi)
479    multi->opt.single_session = true;
480}
481
482/*
483 * protocol_dump() flags
484 */
485#define PD_TLS_AUTH_HMAC_SIZE_MASK 0xFF
486#define PD_SHOW_DATA               (1<<8)
487#define PD_TLS                     (1<<9)
488#define PD_VERBOSE                 (1<<10)
489
490const char *protocol_dump (struct buffer *buffer,
491			   unsigned int flags,
492			   struct gc_arena *gc);
493
494/*
495 * debugging code
496 */
497
498#ifdef MEASURE_TLS_HANDSHAKE_STATS
499void show_tls_performance_stats(void);
500#endif
501
502/*#define EXTRACT_X509_FIELD_TEST*/
503void extract_x509_field_test (void);
504
505#endif /* ENABLE_CRYPTO && ENABLE_SSL */
506
507#endif
508