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 *
10 *  This program is free software; you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License version 2
12 *  as published by the Free Software Foundation.
13 *
14 *  This program is distributed in the hope that it will be useful,
15 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 *  GNU General Public License for more details.
18 *
19 *  You should have received a copy of the GNU General Public License
20 *  along with this program (see the file COPYING included with this
21 *  distribution); if not, write to the Free Software Foundation, Inc.,
22 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23 */
24
25#ifndef OPENVPN_H
26#define OPENVPN_H
27
28#include "buffer.h"
29#include "options.h"
30#include "socket.h"
31#include "crypto.h"
32#include "ssl.h"
33#include "packet_id.h"
34#include "lzo.h"
35#include "tun.h"
36#include "interval.h"
37#include "status.h"
38#include "fragment.h"
39#include "shaper.h"
40#include "route.h"
41#include "proxy.h"
42#include "socks.h"
43#include "sig.h"
44#include "misc.h"
45#include "mbuf.h"
46#include "pool.h"
47#include "plugin.h"
48#include "manage.h"
49#include "pf.h"
50
51/*
52 * Our global key schedules, packaged thusly
53 * to facilitate --persist-key.
54 */
55
56struct key_schedule
57{
58#ifdef ENABLE_CRYPTO
59  /* which cipher, HMAC digest, and key sizes are we using? */
60  struct key_type key_type;
61
62  /* pre-shared static key, read from a file */
63  struct key_ctx_bi static_key;
64
65#ifdef ENABLE_SSL
66  /* our global SSL context */
67  struct tls_root_ctx ssl_ctx;
68
69  /* optional authentication HMAC key for TLS control channel */
70  struct key_ctx_bi tls_auth_key;
71
72#endif				/* ENABLE_SSL */
73#else				/* ENABLE_CRYPTO */
74  int dummy;
75#endif				/* ENABLE_CRYPTO */
76};
77
78/*
79 * struct packet_id_persist should be empty if we are not
80 * building with crypto.
81 */
82#ifndef PACKET_ID_H
83struct packet_id_persist
84{
85  int dummy;
86};
87static inline void
88packet_id_persist_init (struct packet_id_persist *p)
89{
90}
91#endif
92
93/*
94 * Packet processing buffers.
95 */
96struct context_buffers
97{
98  /* miscellaneous buffer, used by ping, occ, etc. */
99  struct buffer aux_buf;
100
101  /* workspace buffers used by crypto routines */
102#ifdef ENABLE_CRYPTO
103  struct buffer encrypt_buf;
104  struct buffer decrypt_buf;
105#endif
106
107  /* workspace buffers for LZO compression */
108#ifdef ENABLE_LZO
109  struct buffer lzo_compress_buf;
110  struct buffer lzo_decompress_buf;
111#endif
112
113  /*
114   * Buffers used to read from TUN device
115   * and TCP/UDP port.
116   */
117  struct buffer read_link_buf;
118  struct buffer read_tun_buf;
119};
120
121/*
122 * always-persistent context variables
123 */
124struct context_persist
125{
126  int restart_sleep_seconds;
127};
128
129
130/**************************************************************************/
131/**
132 * Level 0 %context containing information related to the OpenVPN process.
133 *
134 * Level 0 state is initialized once at program startup, and then remains
135 * throughout the lifetime of the OpenVPN process.  This structure
136 * contains information related to the process's PID, user, and group.
137 */
138struct context_0
139{
140  /* workspace for get_pid_file/write_pid */
141  struct pid_state pid_state;
142
143  /* workspace for --user/--group */
144  bool uid_gid_specified;
145  bool uid_gid_set;
146  struct platform_state_user platform_state_user;
147  struct platform_state_group platform_state_group;
148};
149
150
151/**
152 * Level 1 %context containing state that persists across \c SIGUSR1
153 * restarts.
154 *
155 * Level 1 state is reset on \c SIGHUP restarts.  This structure is
156 * initialized for every iteration of the \c main() function's outer \c
157 * SIGHUP loop, but persists over iteration of that function's inner \c
158 * SIGUSR1 loop.
159 */
160struct context_1
161{
162  struct link_socket_addr link_socket_addr;
163                                /**< Local and remote addresses on the
164                                 *   external network. */
165
166  /* tunnel session keys */
167  struct key_schedule ks;
168
169  /* persist crypto sequence number to/from file */
170  struct packet_id_persist pid_persist;
171
172  struct tuntap *tuntap;        /**< Tun/tap virtual network interface. */
173  bool tuntap_owned;            /**< Whether the tun/tap interface should
174                                 *   be cleaned up when this %context is
175                                 *   cleaned up. */
176
177  struct route_list *route_list;
178                                /**< List of routing information. See the
179                                 *   \c --route command line option. */
180
181  /* list of --route-ipv6 directives */
182  struct route_ipv6_list *route_ipv6_list;
183
184  /* --status file */
185  struct status_output *status_output;
186  bool status_output_owned;
187
188#ifdef ENABLE_HTTP_PROXY
189  /* HTTP proxy object */
190  struct http_proxy_info *http_proxy;
191  bool http_proxy_owned;
192#endif
193
194#ifdef ENABLE_SOCKS
195  /* SOCKS proxy object */
196  struct socks_proxy_info *socks_proxy;
197  bool socks_proxy_owned;
198#endif
199
200#if P2MP
201
202#if P2MP_SERVER
203  /* persist --ifconfig-pool db to file */
204  struct ifconfig_pool_persist *ifconfig_pool_persist;
205  bool ifconfig_pool_persist_owned;
206#endif
207
208  /* if client mode, hash of option strings we pulled from server */
209  struct md5_digest pulled_options_digest_save;
210                                /**< Hash of option strings received from the
211                                 *   remote OpenVPN server.  Only used in
212                                 *   client-mode. */
213
214  struct user_pass *auth_user_pass;
215                                /**< Username and password for
216                                 *   authentication. */
217#endif
218};
219
220/**
221 * Level 2 %context containing state that is reset on both \c SIGHUP and
222 * \c SIGUSR1 restarts.
223 *
224 * This structure is initialized at the top of the \c
225 * tunnel_point_to_point(), \c tunnel_server_udp_single_threaded(), and \c
226 * tunnel_server_tcp() functions.  In other words, it is reset for every
227 * iteration of the \c main() function's inner \c SIGUSR1 loop.
228 */
229struct context_2
230{
231  struct gc_arena gc;           /**< Garbage collection arena for
232                                 *   allocations done in the level 2 scope
233                                 *   of this context_2 structure. */
234
235  /* our global wait events */
236  struct event_set *event_set;
237  int event_set_max;
238  bool event_set_owned;
239
240  /* event flags returned by io_wait */
241# define SOCKET_READ       (1<<0)
242# define SOCKET_WRITE      (1<<1)
243# define TUN_READ          (1<<2)
244# define TUN_WRITE         (1<<3)
245# define ES_ERROR          (1<<4)
246# define ES_TIMEOUT        (1<<5)
247# ifdef ENABLE_MANAGEMENT
248#  define MANAGEMENT_READ  (1<<6)
249#  define MANAGEMENT_WRITE (1<<7)
250# endif
251
252  unsigned int event_set_status;
253
254  struct link_socket *link_socket;	 /* socket used for TCP/UDP connection to remote */
255  bool link_socket_owned;
256  struct link_socket_info *link_socket_info;
257  const struct link_socket *accept_from; /* possibly do accept() on a parent link_socket */
258
259  struct link_socket_actual *to_link_addr;	/* IP address of remote */
260  struct link_socket_actual from;               /* address of incoming datagram */
261
262  /* MTU frame parameters */
263  struct frame frame;
264
265#ifdef ENABLE_FRAGMENT
266  /* Object to handle advanced MTU negotiation and datagram fragmentation */
267  struct fragment_master *fragment;
268  struct frame frame_fragment;
269  struct frame frame_fragment_omit;
270#endif
271
272#ifdef ENABLE_FEATURE_SHAPER
273  /*
274   * Traffic shaper object.
275   */
276  struct shaper shaper;
277#endif
278
279  /*
280   * Statistics
281   */
282  counter_type tun_read_bytes;
283  counter_type tun_write_bytes;
284  counter_type link_read_bytes;
285  counter_type link_read_bytes_auth;
286  counter_type link_write_bytes;
287#ifdef PACKET_TRUNCATION_CHECK
288  counter_type n_trunc_tun_read;
289  counter_type n_trunc_tun_write;
290  counter_type n_trunc_pre_encrypt;
291  counter_type n_trunc_post_decrypt;
292#endif
293
294  /*
295   * Timer objects for ping and inactivity
296   * timeout features.
297   */
298  struct event_timeout wait_for_connect;
299  struct event_timeout ping_send_interval;
300  struct event_timeout ping_rec_interval;
301
302  /* --inactive */
303  struct event_timeout inactivity_interval;
304  int inactivity_bytes;
305
306#ifdef ENABLE_OCC
307  /* the option strings must match across peers */
308  char *options_string_local;
309  char *options_string_remote;
310
311  int occ_op;			/* INIT to -1 */
312  int occ_n_tries;
313  struct event_timeout occ_interval;
314#endif
315
316  /*
317   * Keep track of maximum packet size received so far
318   * (of authenticated packets).
319   */
320  int original_recv_size;	/* temporary */
321  int max_recv_size_local;	/* max packet size received */
322  int max_recv_size_remote;	/* max packet size received by remote */
323  int max_send_size_local;	/* max packet size sent */
324  int max_send_size_remote;	/* max packet size sent by remote */
325
326#ifdef ENABLE_OCC
327  /* remote wants us to send back a load test packet of this size */
328  int occ_mtu_load_size;
329
330  struct event_timeout occ_mtu_load_test_interval;
331  int occ_mtu_load_n_tries;
332#endif
333
334#ifdef ENABLE_CRYPTO
335
336  /*
337   * TLS-mode crypto objects.
338   */
339#ifdef ENABLE_SSL
340
341  struct tls_multi *tls_multi;  /**< TLS state structure for this VPN
342                                 *   tunnel. */
343
344  struct tls_auth_standalone *tls_auth_standalone;
345                                /**< TLS state structure required for the
346                                 *   initial authentication of a client's
347                                 *   connection attempt.  This structure
348                                 *   is used by the \c
349                                 *   tls_pre_decrypt_lite() function when
350                                 *   it performs the HMAC firewall check
351                                 *   on the first connection packet
352                                 *   received from a new client.  See the
353                                 *   \c --tls-auth commandline option. */
354
355  /* used to optimize calls to tls_multi_process */
356  struct interval tmp_int;
357
358  /* throw this signal on TLS errors */
359  int tls_exit_signal;
360
361#endif /* ENABLE_SSL */
362
363  struct crypto_options crypto_options;
364                                /**< Security parameters and crypto state
365                                 *   used by the \link data_crypto Data
366                                 *   Channel Crypto module\endlink to
367                                 *   process data channel packet. */
368
369  /* used to keep track of data channel packet sequence numbers */
370  struct packet_id packet_id;
371  struct event_timeout packet_id_persist_interval;
372
373#endif /* ENABLE_CRYPTO */
374
375#ifdef ENABLE_LZO
376  struct lzo_compress_workspace lzo_compwork;
377                                /**< Compression workspace used by the
378                                 *   \link compression Data Channel
379                                 *   Compression module\endlink. */
380#endif
381
382  /*
383   * Buffers used for packet processing.
384   */
385  struct context_buffers *buffers;
386  bool buffers_owned; /* if true, we should free all buffers on close */
387
388  /*
389   * These buffers don't actually allocate storage, they are used
390   * as pointers to the allocated buffers in
391   * struct context_buffers.
392   */
393  struct buffer buf;
394  struct buffer to_tun;
395  struct buffer to_link;
396
397  /*
398   * IPv4 TUN device?
399   */
400  bool ipv4_tun;
401
402  /* should we print R|W|r|w to console on packet transfers? */
403  bool log_rw;
404
405  /* route stuff */
406  struct event_timeout route_wakeup;
407  struct event_timeout route_wakeup_expire;
408
409  /* did we open tun/tap dev during this cycle? */
410  bool did_open_tun;
411
412  /*
413   * Event loop info
414   */
415
416  /* how long to wait on link/tun read before we will need to be serviced */
417  struct timeval timeval;
418
419  /* next wakeup for processing coarse timers (>1 sec resolution) */
420  time_t coarse_timer_wakeup;
421
422  /* maintain a random delta to add to timeouts to avoid contexts
423     waking up simultaneously */
424  time_t update_timeout_random_component;
425  struct timeval timeout_random_component;
426
427  /* indicates that the do_up_delay function has run */
428  bool do_up_ran;
429
430#ifdef ENABLE_OCC
431  /* indicates that we have received a SIGTERM when
432     options->explicit_exit_notification is enabled,
433     but we have not exited yet */
434  time_t explicit_exit_notification_time_wait;
435  struct event_timeout explicit_exit_notification_interval;
436#endif
437
438  /* environmental variables to pass to scripts */
439  struct env_set *es;
440  bool es_owned;
441
442  /* don't wait for TUN/TAP/UDP to be ready to accept write */
443  bool fast_io;
444
445#if P2MP
446
447#if P2MP_SERVER
448  /* --ifconfig endpoints to be pushed to client */
449  bool push_reply_deferred;
450  bool push_ifconfig_defined;
451  time_t sent_push_reply_expiry;
452  in_addr_t push_ifconfig_local;
453  in_addr_t push_ifconfig_remote_netmask;
454#ifdef ENABLE_CLIENT_NAT
455  in_addr_t push_ifconfig_local_alias;
456#endif
457
458  bool            push_ifconfig_ipv6_defined;
459  struct in6_addr push_ifconfig_ipv6_local;
460  int             push_ifconfig_ipv6_netbits;
461  struct in6_addr push_ifconfig_ipv6_remote;
462
463  /* client authentication state, CAS_SUCCEEDED must be 0 */
464# define CAS_SUCCEEDED 0
465# define CAS_PENDING   1
466# define CAS_FAILED    2
467# define CAS_PARTIAL   3 /* at least one client-connect script/plugin
468			    succeeded while a later one in the chain failed */
469  int context_auth;
470#endif
471
472  struct event_timeout push_request_interval;
473  int n_sent_push_requests;
474  bool did_pre_pull_restore;
475
476  /* hash of pulled options, so we can compare when options change */
477  bool pulled_options_md5_init_done;
478  struct md5_state pulled_options_state;
479  struct md5_digest pulled_options_digest;
480
481  struct event_timeout server_poll_interval;
482
483  struct event_timeout scheduled_exit;
484  int scheduled_exit_signal;
485#endif
486
487  /* packet filter */
488#ifdef ENABLE_PF
489  struct pf_context pf;
490#endif
491
492#ifdef MANAGEMENT_DEF_AUTH
493  struct man_def_auth_context mda_context;
494#endif
495};
496
497
498/**
499 * Contains all state information for one tunnel.
500 *
501 * This structure represents one VPN tunnel.  It is used to store state
502 * information related to a VPN tunnel, but also includes process-wide
503 * data, such as configuration options.
504 *
505 * The @ref tunnel_state "Structure of VPN tunnel state storage" related
506 * page describes how this structure is used in client-mode and
507 * server-mode.
508 */
509struct context
510{
511  struct options options;       /**< Options loaded from command line or
512                                 *   configuration file. */
513
514  bool first_time;              /**< True on the first iteration of
515                                 *   OpenVPN's main loop. */
516
517  /* context modes */
518# define CM_P2P            0 /* standalone point-to-point session or client */
519# define CM_TOP            1 /* top level of a multi-client or point-to-multipoint server */
520# define CM_TOP_CLONE      2 /* clone of a CM_TOP context for one thread */
521# define CM_CHILD_UDP      3 /* child context of a CM_TOP or CM_THREAD */
522# define CM_CHILD_TCP      4 /* child context of a CM_TOP or CM_THREAD */
523  int mode;                     /**< Role of this context within the
524                                 *   OpenVPN process.  Valid values are \c
525                                 *   CM_P2P, \c CM_TOP, \c CM_TOP_CLONE,
526                                 *   \c CM_CHILD_UDP, and \c CM_CHILD_TCP. */
527
528  struct gc_arena gc;           /**< Garbage collection arena for
529                                 *   allocations done in the scope of this
530                                 *   context structure. */
531
532  struct env_set *es;           /**< Set of environment variables. */
533
534  struct signal_info *sig;      /**< Internal error signaling object. */
535
536  struct plugin_list *plugins;  /**< List of plug-ins. */
537  bool plugins_owned;           /**< Whether the plug-ins should be
538                                 *   cleaned up when this %context is
539                                 *   cleaned up. */
540
541  bool did_we_daemonize;        /**< Whether demonization has already
542                                 *   taken place. */
543
544  struct context_persist persist;
545                                /**< Persistent %context. */
546  struct context_0 *c0;         /**< Level 0 %context. */
547  struct context_1 c1;          /**< Level 1 %context. */
548  struct context_2 c2;          /**< Level 2 %context. */
549};
550
551/*
552 * Check for a signal when inside an event loop
553 */
554#define EVENT_LOOP_CHECK_SIGNAL(c, func, arg)   \
555      if (IS_SIG (c))                           \
556	{                                       \
557	  const int brk = func (arg);           \
558	  perf_pop ();                          \
559	  if (brk)                              \
560	    break;                              \
561	  else                                  \
562	    continue;                           \
563	}
564
565/*
566 * Macros for referencing objects which may not
567 * have been compiled in.
568 */
569
570#if defined(ENABLE_CRYPTO) && defined(ENABLE_SSL)
571#define TLS_MODE(c) ((c)->c2.tls_multi != NULL)
572#define PROTO_DUMP_FLAGS (check_debug_level (D_LINK_RW_VERBOSE) ? (PD_SHOW_DATA|PD_VERBOSE) : 0)
573#define PROTO_DUMP(buf, gc) protocol_dump((buf), \
574				      PROTO_DUMP_FLAGS | \
575				      (c->c2.tls_multi ? PD_TLS : 0) | \
576				      (c->options.tls_auth_file ? c->c1.ks.key_type.hmac_length : 0), \
577				      gc)
578#else
579#define TLS_MODE(c) (false)
580#define PROTO_DUMP(buf, gc) format_hex (BPTR (buf), BLEN (buf), 80, gc)
581#endif
582
583#ifdef ENABLE_CRYPTO
584#define MD5SUM(buf, len, gc) md5sum((buf), (len), 0, (gc))
585#else
586#define MD5SUM(buf, len, gc) "[unavailable]"
587#endif
588
589#ifdef ENABLE_CRYPTO
590#define CIPHER_ENABLED(c) (c->c1.ks.key_type.cipher != NULL)
591#else
592#define CIPHER_ENABLED(c) (false)
593#endif
594
595#endif
596