]> git.ipfire.org Git - thirdparty/openvpn.git/blame - init.c
Renamed sample-keys/tmp-ca.crt to ca.crt.
[thirdparty/openvpn.git] / init.c
CommitLineData
6fbf66fa
JY
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-2005 OpenVPN Solutions LLC <info@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#ifdef WIN32
26#include "config-win32.h"
27#else
28#include "config.h"
29#endif
30
31#include "syshead.h"
32
33#include "win32.h"
34#include "init.h"
35#include "sig.h"
36#include "occ.h"
37#include "list.h"
38#include "otime.h"
39#include "pool.h"
40#include "gremlin.h"
41
42#include "memdbg.h"
43
44#include "occ-inline.h"
45
46/*
47 * Crypto initialization flags
48 */
49#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
50#define CF_INIT_TLS_MULTI (1<<1)
51#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
52
53static void do_init_first_time (struct context *c);
54
55void
56context_clear (struct context *c)
57{
58 CLEAR (*c);
59}
60
61void
62context_clear_1 (struct context *c)
63{
64 CLEAR (c->c1);
65}
66
67void
68context_clear_2 (struct context *c)
69{
70 CLEAR (c->c2);
71}
72
73void
74context_clear_all_except_first_time (struct context *c)
75{
76 const bool first_time_save = c->first_time;
77 context_clear (c);
78 c->first_time = first_time_save;
79}
80
81/*
82 * Initialize and possibly randomize remote list.
83 */
84static void
85init_remote_list (struct context *c)
86{
87 c->c1.remote_list = NULL;
88
89 if (c->options.remote_list)
90 {
91 struct remote_list *l;
92 ALLOC_OBJ_GC (c->c1.remote_list, struct remote_list, &c->gc);
93 l = c->c1.remote_list;
94 *l = *c->options.remote_list;
95 l->current = -1;
96 if (c->options.remote_random)
97 remote_list_randomize (l);
98 }
99}
100
101void
102context_init_1 (struct context *c)
103{
104 context_clear_1 (c);
105
106 packet_id_persist_init (&c->c1.pid_persist);
107 init_remote_list (c);
108
109#if defined(USE_CRYPTO) && defined(USE_SSL)
110 /* Certificate password input */
111 if (c->options.key_pass_file)
112 pem_password_setup (c->options.key_pass_file);
113#endif
114
115#if P2MP
116 /* Auth user/pass input */
117 if (c->options.auth_user_pass_file)
118 {
119 auth_user_pass_setup (c->options.auth_user_pass_file);
120 }
121#endif
122
123#ifdef ENABLE_HTTP_PROXY
124 if (c->options.http_proxy_options)
125 {
126 /* Possible HTTP proxy user/pass input */
127 c->c1.http_proxy = new_http_proxy (c->options.http_proxy_options,
128 &c->gc);
129 }
130#endif
131
132#ifdef ENABLE_SOCKS
133 if (c->options.socks_proxy_server)
134 {
135 c->c1.socks_proxy = new_socks_proxy (c->options.socks_proxy_server,
136 c->options.socks_proxy_port,
137 c->options.socks_proxy_retry,
138 &c->gc);
139 }
140#endif
141}
142
143void
144context_gc_free (struct context *c)
145{
146 gc_free (&c->c2.gc);
147 gc_free (&c->options.gc);
148 gc_free (&c->gc);
149}
150
151bool
152init_static (void)
153{
154#if defined(USE_CRYPTO) && defined(DMALLOC)
155 openssl_dmalloc_init ();
156#endif
157
158 init_random_seed (); /* init random() function, only used as
159 source for weak random numbers */
160 error_reset (); /* initialize error.c */
161 reset_check_status (); /* initialize status check code in socket.c */
162
163#ifdef WIN32
164 init_win32 ();
165#endif
166
167#ifdef OPENVPN_DEBUG_COMMAND_LINE
168 {
169 int i;
170 for (i = 0; i < argc; ++i)
171 msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
172 }
173#endif
174
175 update_time ();
176
177#ifdef USE_CRYPTO
178 init_ssl_lib ();
179
180 /* init PRNG used for IV generation */
181 /* When forking, copy this to more places in the code to avoid fork
182 random-state predictability */
183 prng_init ();
184#endif
185
186#ifdef PID_TEST
187 packet_id_interactive_test (); /* test the sequence number code */
188 return false;
189#endif
190
191#ifdef SCHEDULE_TEST
192 schedule_test ();
193 return false;
194#endif
195
196#ifdef LIST_TEST
197 list_test ();
198 return false;
199#endif
200
201#ifdef IFCONFIG_POOL_TEST
202 ifconfig_pool_test (0x0A010004, 0x0A0100FF);
203 return false;
204#endif
205
206#ifdef CHARACTER_CLASS_DEBUG
207 character_class_debug ();
208 return false;
209#endif
210
211#ifdef EXTRACT_X509_FIELD_TEST
212 extract_x509_field_test ();
213 return false;
214#endif
215
216 return true;
217}
218
219void
220uninit_static (void)
221{
222 openvpn_thread_cleanup ();
223
224#ifdef USE_CRYPTO
225 free_ssl_lib ();
226#endif
227
228#if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(USE_CRYPTO) && defined(USE_SSL)
229 show_tls_performance_stats ();
230#endif
231}
232
233void
234init_verb_mute (struct context *c, unsigned int flags)
235{
236 if (flags & IVM_LEVEL_1)
237 {
238 /* set verbosity and mute levels */
239 set_check_status (D_LINK_ERRORS, D_READ_WRITE);
240 set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
241 set_mute_cutoff (c->options.mute);
242 }
243
244 /* special D_LOG_RW mode */
245 if (flags & IVM_LEVEL_2)
246 c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
247}
248
249/*
250 * Possibly set --dev based on --dev-node.
251 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
252 * set --dev to tun.
253 */
254void
255init_options_dev (struct options *options)
256{
257 if (!options->dev)
258 options->dev = dev_component_in_dev_node (options->dev_node);
259}
260
261bool
262print_openssl_info (const struct options *options)
263{
264 /*
265 * OpenSSL info print mode?
266 */
267#ifdef USE_CRYPTO
268 if (options->show_ciphers || options->show_digests || options->show_engines
269#ifdef USE_SSL
270 || options->show_tls_ciphers
271#endif
272 )
273 {
274 if (options->show_ciphers)
275 show_available_ciphers ();
276 if (options->show_digests)
277 show_available_digests ();
278 if (options->show_engines)
279 show_available_engines ();
280#ifdef USE_SSL
281 if (options->show_tls_ciphers)
282 show_available_tls_ciphers ();
283#endif
284 return true;
285 }
286#endif
287 return false;
288}
289
290/*
291 * Static pre-shared key generation mode?
292 */
293bool
294do_genkey (const struct options * options)
295{
296#ifdef USE_CRYPTO
297 if (options->genkey)
298 {
299 int nbits_written;
300
301 notnull (options->shared_secret_file,
302 "shared secret output file (--secret)");
303
304 if (options->mlock) /* should we disable paging? */
305 do_mlockall (true);
306
307 nbits_written = write_key_file (2, options->shared_secret_file);
308
309 msg (D_GENKEY | M_NOPREFIX,
310 "Randomly generated %d bit key written to %s", nbits_written,
311 options->shared_secret_file);
312 return true;
313 }
314#endif
315 return false;
316}
317
318/*
319 * Persistent TUN/TAP device management mode?
320 */
321bool
322do_persist_tuntap (const struct options *options)
323{
324#ifdef TUNSETPERSIST
325 if (options->persist_config)
326 {
327 /* sanity check on options for --mktun or --rmtun */
328 notnull (options->dev, "TUN/TAP device (--dev)");
329 if (options->remote_list || options->ifconfig_local
330 || options->ifconfig_remote_netmask
331#ifdef USE_CRYPTO
332 || options->shared_secret_file
333#ifdef USE_SSL
334 || options->tls_server || options->tls_client
335#endif
336#endif
337 )
338 msg (M_FATAL|M_OPTERR,
339 "options --mktun or --rmtun should only be used together with --dev");
340 tuncfg (options->dev, options->dev_type, options->dev_node,
341 options->tun_ipv6, options->persist_mode);
342 return true;
343 }
344#endif
345 return false;
346}
347
348/*
349 * Should we become a daemon?
350 * Return true if we did it.
351 */
352static bool
353possibly_become_daemon (const struct options *options, const bool first_time)
354{
355 bool ret = false;
356 if (first_time && options->daemon)
357 {
358 ASSERT (!options->inetd);
359 if (daemon (options->cd_dir != NULL, options->log) < 0)
360 msg (M_ERR, "daemon() failed");
361 if (options->log)
362 set_std_files_to_null (true);
363 ret = true;
364 }
365 return ret;
366}
367
368/*
369 * Actually do UID/GID downgrade, and chroot, if requested.
370 */
371static void
372do_uid_gid_chroot (struct context *c, bool no_delay)
373{
374 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
375
376 if (c->first_time && !c->c2.uid_gid_set)
377 {
378 /* chroot if requested */
379 if (c->options.chroot_dir)
380 {
381 if (no_delay)
382 do_chroot (c->options.chroot_dir);
383 else
384 msg (M_INFO, "NOTE: chroot %s", why_not);
385 }
386
387 /* set user and/or group that we want to setuid/setgid to */
388 if (no_delay)
389 {
390 set_group (&c->c2.group_state);
391 set_user (&c->c2.user_state);
392 c->c2.uid_gid_set = true;
393 }
394 else if (c->c2.uid_gid_specified)
395 {
396 msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
397 }
398 }
399}
400
401/*
402 * Return common name in a way that is formatted for
403 * prepending to msg() output.
404 */
405const char *
406format_common_name (struct context *c, struct gc_arena *gc)
407{
408 struct buffer out = alloc_buf_gc (256, gc);
409#if defined(USE_CRYPTO) && defined(USE_SSL)
410 if (c->c2.tls_multi)
411 {
412 buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
413 }
414#endif
415 return BSTR (&out);
416}
417
418void
419pre_setup (const struct options *options)
420{
421#ifdef WIN32
422 if (options->exit_event_name)
423 {
424 win32_signal_open (&win32_signal,
425 WSO_FORCE_SERVICE,
426 options->exit_event_name,
427 options->exit_event_initial_state);
428 }
429 else
430 {
431 win32_signal_open (&win32_signal,
432 WSO_FORCE_CONSOLE,
433 NULL,
434 false);
435
436 /* put a title on the top window bar */
437 if (win32_signal.mode == WSO_MODE_CONSOLE)
438 {
439 window_title_save (&window_title);
440 window_title_generate (options->config);
441 }
442 }
443#endif
444}
445
446void
447reset_coarse_timers (struct context *c)
448{
449 c->c2.coarse_timer_wakeup = 0;
450}
451
452/*
453 * Initialize timers
454 */
455static void
456do_init_timers (struct context *c, bool deferred)
457{
458 update_time ();
459 reset_coarse_timers (c);
460
461 /* initialize inactivity timeout */
462 if (c->options.inactivity_timeout)
463 event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
464
465 /* initialize pings */
466
467 if (c->options.ping_send_timeout)
468 event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
469
470 if (c->options.ping_rec_timeout)
471 event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
472
473 if (!deferred)
474 {
475 /* initialize connection establishment timer */
476 event_timeout_init (&c->c2.wait_for_connect, 1, now);
477
478#ifdef ENABLE_OCC
479 /* initialize occ timers */
480
481 if (c->options.occ
482 && !TLS_MODE (c)
483 && c->c2.options_string_local && c->c2.options_string_remote)
484 event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
485
486 if (c->options.mtu_test)
487 event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
488#endif
489
490 /* initialize packet_id persistence timer */
491#ifdef USE_CRYPTO
492 if (c->options.packet_id_file)
493 event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);
494#endif
495
496#if defined(USE_CRYPTO) && defined(USE_SSL)
497 /* initialize tmp_int optimization that limits the number of times we call
498 tls_multi_process in the main event loop */
499 interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
500#endif
501 }
502}
503
504/*
505 * Initialize traffic shaper.
506 */
507static void
508do_init_traffic_shaper (struct context *c)
509{
510#ifdef HAVE_GETTIMEOFDAY
511 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
512 if (c->options.shaper)
513 {
514 shaper_init (&c->c2.shaper, c->options.shaper);
515 shaper_msg (&c->c2.shaper);
516 }
517#endif
518}
519
520/*
521 * Allocate a route list structure if at least one
522 * --route option was specified.
523 */
524static void
525do_alloc_route_list (struct context *c)
526{
527 if (c->options.routes && !c->c1.route_list)
528 c->c1.route_list = new_route_list (&c->gc);
529}
530
531
532/*
533 * Initialize the route list, resolving any DNS names in route
534 * options and saving routes in the environment.
535 */
536static void
537do_init_route_list (const struct options *options,
538 struct route_list *route_list,
539 const struct link_socket_info *link_socket_info,
540 bool fatal,
541 struct env_set *es)
542{
543 const char *gw = NULL;
544 int dev = dev_type_enum (options->dev, options->dev_type);
545
3c7f2f55 546 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
6fbf66fa
JY
547 gw = options->ifconfig_remote_netmask;
548 if (options->route_default_gateway)
549 gw = options->route_default_gateway;
550
551 if (!init_route_list (route_list,
552 options->routes,
553 gw,
554 link_socket_current_remote (link_socket_info),
555 es))
556 {
557 if (fatal)
558 openvpn_exit (OPENVPN_EXIT_STATUS_ERROR); /* exit point */
559 }
560 else
561 {
562 /* copy routes to environment */
563 setenv_routes (es, route_list);
564 }
565}
566
567/*
568 * Called after all initialization has been completed.
569 */
570void
571initialization_sequence_completed (struct context *c, const unsigned int flags)
572{
573 static const char message[] = "Initialization Sequence Completed";
574
575 /* If we delayed UID/GID downgrade or chroot, do it now */
576 do_uid_gid_chroot (c, true);
577
578 /* Test if errors */
579 if (flags & ISC_ERRORS)
580#ifdef WIN32
581 msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
582#else
583 msg (M_INFO, "%s With Errors", message);
584#endif
585 else
586 msg (M_INFO, "%s", message);
587
588 /* Flag remote_list that we initialized */
589 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0 && c->c1.remote_list && c->c1.remote_list->len > 1)
590 c->c1.remote_list->no_advance = true;
591
592#ifdef ENABLE_MANAGEMENT
593 /* Tell management interface that we initialized */
594 if (management)
595 {
596 in_addr_t tun_local = 0;
597 const char *detail = "SUCCESS";
598 if (c->c1.tuntap)
599 tun_local = c->c1.tuntap->local;
600 if (flags & ISC_ERRORS)
601 detail = "ERROR";
602 management_set_state (management,
603 OPENVPN_STATE_CONNECTED,
604 detail,
605 tun_local);
606 if (tun_local)
607 management_post_tunnel_open (management, tun_local);
608 }
609#endif
610
611}
612
613/*
614 * Possibly add routes and/or call route-up script
615 * based on options.
616 */
617void
618do_route (const struct options *options,
619 struct route_list *route_list,
620 const struct tuntap *tt,
621 const struct plugin_list *plugins,
622 struct env_set *es)
623{
624 if (!options->route_noexec && route_list)
625 add_routes (route_list, tt, ROUTE_OPTION_FLAGS (options), es);
626
627 if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
628 {
3c7f2f55 629 if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es))
6fbf66fa
JY
630 msg (M_WARN, "WARNING: route-up plugin call failed");
631 }
632
633 if (options->route_script)
634 {
635 setenv_str (es, "script_type", "route-up");
636 system_check (options->route_script, es, S_SCRIPT, "Route script failed");
637 }
638
639#ifdef WIN32
640 if (options->show_net_up)
641 {
642 show_routes (M_INFO|M_NOPREFIX);
643 show_adapters (M_INFO|M_NOPREFIX);
644 }
645 else if (check_debug_level (D_SHOW_NET))
646 {
647 show_routes (D_SHOW_NET|M_NOPREFIX);
648 show_adapters (D_SHOW_NET|M_NOPREFIX);
649 }
650#endif
651}
652
653/*
654 * Save current pulled options string in the c1 context store, so we can
655 * compare against it after possible future restarts.
656 */
657#if P2MP
658static void
659save_pulled_options_string (struct context *c, const char *newstring)
660{
661 if (c->c1.pulled_options_string_save)
662 free (c->c1.pulled_options_string_save);
663
664 c->c1.pulled_options_string_save = NULL;
665
666 if (newstring)
667 c->c1.pulled_options_string_save = string_alloc (newstring, NULL);
668}
669#endif
670
671/*
672 * initialize tun/tap device object
673 */
674static void
675do_init_tun (struct context *c)
676{
677 c->c1.tuntap = init_tun (c->options.dev,
678 c->options.dev_type,
3c7f2f55 679 c->options.topology,
6fbf66fa
JY
680 c->options.ifconfig_local,
681 c->options.ifconfig_remote_netmask,
682 addr_host (&c->c1.link_socket_addr.local),
683 addr_host (&c->c1.link_socket_addr.remote),
684 !c->options.ifconfig_nowarn,
685 c->c2.es);
686
687 init_tun_post (c->c1.tuntap,
688 &c->c2.frame,
689 &c->options.tuntap_options);
690
691 c->c1.tuntap_owned = true;
692}
693
694/*
695 * Open tun/tap device, ifconfig, call up script, etc.
696 */
697
698static bool
699do_open_tun (struct context *c)
700{
701 struct gc_arena gc = gc_new ();
702 bool ret = false;
703
704 c->c2.ipv4_tun = (!c->options.tun_ipv6
705 && is_dev_type (c->options.dev, c->options.dev_type, "tun"));
706
707 if (!c->c1.tuntap)
708 {
709 /* initialize (but do not open) tun/tap object */
710 do_init_tun (c);
711
712 /* allocate route list structure */
713 do_alloc_route_list (c);
714
715 /* parse and resolve the route option list */
3c7f2f55 716 if (c->options.routes && c->c1.route_list && c->c2.link_socket)
6fbf66fa
JY
717 do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
718
719 /* do ifconfig */
720 if (!c->options.ifconfig_noexec
721 && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
722 {
723 /* guess actual tun/tap unit number that will be returned
724 by open_tun */
725 const char *guess = guess_tuntap_dev (c->options.dev,
726 c->options.dev_type,
727 c->options.dev_node,
728 &gc);
729 do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
730 }
731
732 /* open the tun device */
733 open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
734 c->options.tun_ipv6, c->c1.tuntap);
735
736 /* do ifconfig */
737 if (!c->options.ifconfig_noexec
738 && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
739 {
740 do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
741 }
742
743 /* run the up script */
744 run_up_down (c->options.up_script,
3c7f2f55 745 c->plugins,
6fbf66fa
JY
746 OPENVPN_PLUGIN_UP,
747 c->c1.tuntap->actual_name,
748 TUN_MTU_SIZE (&c->c2.frame),
749 EXPANDED_SIZE (&c->c2.frame),
750 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
751 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
752 "init",
753 NULL,
754 "up",
755 c->c2.es);
756
757 /* possibly add routes */
758 if (!c->options.route_delay_defined)
3c7f2f55 759 do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
6fbf66fa
JY
760
761 /*
762 * Did tun/tap driver give us an MTU?
763 */
764 if (c->c1.tuntap->post_open_mtu)
765 frame_set_mtu_dynamic (&c->c2.frame,
766 c->c1.tuntap->post_open_mtu,
767 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
768
769 ret = true;
770 }
771 else
772 {
773 msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
774 c->c1.tuntap->actual_name);
775
776 /* run the up script if user specified --up-restart */
777 if (c->options.up_restart)
778 run_up_down (c->options.up_script,
3c7f2f55 779 c->plugins,
6fbf66fa
JY
780 OPENVPN_PLUGIN_UP,
781 c->c1.tuntap->actual_name,
782 TUN_MTU_SIZE (&c->c2.frame),
783 EXPANDED_SIZE (&c->c2.frame),
784 print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
785 print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
786 "restart",
787 NULL,
788 "up",
789 c->c2.es);
790 }
791 gc_free (&gc);
792 return ret;
793}
794
795/*
796 * Close TUN/TAP device
797 */
798
799static void
800do_close_tun_simple (struct context *c)
801{
802 msg (D_CLOSE, "Closing TUN/TAP interface");
803 close_tun (c->c1.tuntap);
804 c->c1.tuntap = NULL;
805 c->c1.tuntap_owned = false;
806#if P2MP
807 save_pulled_options_string (c, NULL); /* delete C1-saved pulled_options_string */
808#endif
809}
810
811static void
812do_close_tun (struct context *c, bool force)
813{
814 struct gc_arena gc = gc_new ();
815 if (c->c1.tuntap && c->c1.tuntap_owned)
816 {
817 const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
818 const in_addr_t local = c->c1.tuntap->local;
819 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
820
821 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
822 {
823#ifdef ENABLE_MANAGEMENT
824 /* tell management layer we are about to close the TUN/TAP device */
825 if (management)
826 management_pre_tunnel_close (management);
827#endif
828
829 /* delete any routes we added */
830 if (c->c1.route_list)
831 delete_routes (c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
832
833 /* actually close tun/tap device based on --down-pre flag */
834 if (!c->options.down_pre)
835 do_close_tun_simple (c);
836
837 /* Run the down script -- note that it will run at reduced
838 privilege if, for example, "--user nobody" was used. */
839 run_up_down (c->options.down_script,
3c7f2f55 840 c->plugins,
6fbf66fa
JY
841 OPENVPN_PLUGIN_DOWN,
842 tuntap_actual,
843 TUN_MTU_SIZE (&c->c2.frame),
844 EXPANDED_SIZE (&c->c2.frame),
845 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
846 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
847 "init",
848 signal_description (c->sig->signal_received,
849 c->sig->signal_text),
850 "down",
851 c->c2.es);
852
853 /* actually close tun/tap device based on --down-pre flag */
854 if (c->options.down_pre)
855 do_close_tun_simple (c);
856 }
857 else
858 {
859 /* run the down script on this restart if --up-restart was specified */
860 if (c->options.up_restart)
861 run_up_down (c->options.down_script,
3c7f2f55 862 c->plugins,
6fbf66fa
JY
863 OPENVPN_PLUGIN_DOWN,
864 tuntap_actual,
865 TUN_MTU_SIZE (&c->c2.frame),
866 EXPANDED_SIZE (&c->c2.frame),
867 print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
868 print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
869 "restart",
870 signal_description (c->sig->signal_received,
871 c->sig->signal_text),
872 "down",
873 c->c2.es);
874 }
875 }
876 gc_free (&gc);
877}
878
879/*
880 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
881 */
882
883void
884do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
885{
886 if (!c->c2.do_up_ran)
887 {
888 reset_coarse_timers (c);
889
890 if (pulled_options && option_types_found)
891 do_deferred_options (c, option_types_found);
892
893 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
894 if (c->options.up_delay || PULL_DEFINED (&c->options))
895 {
896 c->c2.did_open_tun = do_open_tun (c);
897 update_time ();
898
899#if P2MP
900 /*
901 * Was tun interface object persisted from previous restart iteration,
902 * and if so did pulled options string change from previous iteration?
903 */
904 if (!c->c2.did_open_tun
905 && PULL_DEFINED (&c->options)
906 && c->c1.tuntap
907 && (!c->c1.pulled_options_string_save || !c->c2.pulled_options_string
908 || strcmp (c->c1.pulled_options_string_save, c->c2.pulled_options_string)))
909 {
910 /* if so, close tun, delete routes, then reinitialize tun and add routes */
911 msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
912 do_close_tun (c, true);
913 openvpn_sleep (1);
914 c->c2.did_open_tun = do_open_tun (c);
915 update_time ();
916 }
917#endif
918 }
919
920 if (c->c2.did_open_tun)
921 {
922#if P2MP
923 save_pulled_options_string (c, c->c2.pulled_options_string);
924#endif
925
926 /* if --route-delay was specified, start timer */
927 if (c->options.route_delay_defined)
928 {
929 event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
930 event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
931 }
932 else
933 {
934 initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
935 }
936 }
937 else if (c->options.mode == MODE_POINT_TO_POINT)
938 {
939 initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
940 }
941
942 c->c2.do_up_ran = true;
943 }
944}
945
946/*
947 * These are the option categories which will be accepted by pull.
948 */
949unsigned int
3c7f2f55 950pull_permission_mask (const struct context *c)
6fbf66fa 951{
3c7f2f55
JY
952 unsigned int flags =
953 OPT_P_UP
954 | OPT_P_ROUTE_EXTRAS
955 | OPT_P_IPWIN32
956 | OPT_P_SETENV
957 | OPT_P_SHAPER
958 | OPT_P_TIMER
959 | OPT_P_PERSIST
960 | OPT_P_MESSAGES
961 | OPT_P_EXPLICIT_NOTIFY
962 | OPT_P_ECHO
963 | OPT_P_PULL_MODE;
964
965 if (!c->options.route_nopull)
966 flags |= OPT_P_ROUTE;
967
968 return flags;
6fbf66fa
JY
969}
970
971/*
972 * Handle non-tun-related pulled options.
973 */
974void
975do_deferred_options (struct context *c, const unsigned int found)
976{
977 if (found & OPT_P_MESSAGES)
978 {
979 init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
980 msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
981 }
982 if (found & OPT_P_TIMER)
983 {
984 do_init_timers (c, true);
985 msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
986 }
987
988#ifdef ENABLE_OCC
989 if (found & OPT_P_EXPLICIT_NOTIFY)
990 {
991 if (c->options.proto != PROTO_UDPv4 && c->options.explicit_exit_notification)
992 {
993 msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
994 c->options.explicit_exit_notification = 0;
995 }
996 else
997 msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
998 }
999#endif
1000
1001 if (found & OPT_P_SHAPER)
1002 {
1003 msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
1004 do_init_traffic_shaper (c);
1005 }
1006
1007 if (found & OPT_P_PERSIST)
1008 msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
1009 if (found & OPT_P_UP)
1010 msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
1011 if (found & OPT_P_ROUTE)
1012 msg (D_PUSH, "OPTIONS IMPORT: route options modified");
3c7f2f55
JY
1013 if (found & OPT_P_ROUTE_EXTRAS)
1014 msg (D_PUSH, "OPTIONS IMPORT: route-related options modified");
6fbf66fa
JY
1015 if (found & OPT_P_IPWIN32)
1016 msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
1017 if (found & OPT_P_SETENV)
1018 msg (D_PUSH, "OPTIONS IMPORT: environment modified");
1019}
1020
1021/*
1022 * Possible hold on initialization
1023 */
1024static bool
1025do_hold (struct context *c)
1026{
1027#ifdef ENABLE_MANAGEMENT
1028 if (management)
1029 {
1030 /* if c is defined, daemonize before hold */
1031 if (c && c->options.daemon && management_would_hold (management))
1032 do_init_first_time (c);
1033
1034 /* block until management hold is released */
1035 if (management_hold (management))
1036 return true;
1037 }
1038#endif
1039 return false;
1040}
1041
1042/*
1043 * Sleep before restart.
1044 */
1045static void
1046socket_restart_pause (struct context *c)
1047{
1048 bool proxy = false;
1049 int sec = 2;
1050
1051#ifdef ENABLE_HTTP_PROXY
1052 if (c->options.http_proxy_options)
1053 proxy = true;
1054#endif
1055#ifdef ENABLE_SOCKS
1056 if (c->options.socks_proxy_server)
1057 proxy = true;
1058#endif
1059
1060 switch (c->options.proto)
1061 {
1062 case PROTO_UDPv4:
1063 if (proxy)
1064 sec = c->options.connect_retry_seconds;
1065 break;
1066 case PROTO_TCPv4_SERVER:
1067 sec = 1;
1068 break;
1069 case PROTO_TCPv4_CLIENT:
1070 sec = c->options.connect_retry_seconds;
1071 break;
1072 }
1073
1074#ifdef ENABLE_DEBUG
1075 if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
1076 sec = 0;
1077#endif
1078
1079#if P2MP
1080 if (auth_retry_get () == AR_NOINTERACT)
1081 sec = 10;
1082#endif
1083
1084 if (do_hold (NULL))
1085 sec = 0;
1086
1087 if (sec)
1088 {
1089 msg (D_RESTART, "Restart pause, %d second(s)", sec);
1090 openvpn_sleep (sec);
1091 }
1092}
1093
1094/*
1095 * Do a possible pause on context_2 initialization.
1096 */
1097static void
1098do_startup_pause (struct context *c)
1099{
1100 if (!c->first_time)
1101 socket_restart_pause (c);
1102 else
1103 do_hold (NULL);
1104}
1105
1106/*
1107 * Finalize MTU parameters based on command line or config file options.
1108 */
1109static void
1110frame_finalize_options (struct context *c, const struct options *o)
1111{
1112 if (!o)
1113 o = &c->options;
1114
1115 /*
1116 * Set adjustment factor for buffer alignment when no
1117 * cipher is used.
1118 */
1119 if (!CIPHER_ENABLED (c))
1120 {
1121 frame_align_to_extra_frame (&c->c2.frame);
1122 frame_or_align_flags (&c->c2.frame,
1123 FRAME_HEADROOM_MARKER_FRAGMENT
1124 |FRAME_HEADROOM_MARKER_READ_LINK
1125 |FRAME_HEADROOM_MARKER_READ_STREAM);
1126 }
1127
1128 frame_finalize (&c->c2.frame,
1129 o->link_mtu_defined,
1130 o->link_mtu,
1131 o->tun_mtu_defined,
1132 o->tun_mtu);
1133}
1134
1135/*
1136 * Free a key schedule, including OpenSSL components.
1137 */
1138static void
1139key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
1140{
1141#ifdef USE_CRYPTO
1142 free_key_ctx_bi (&ks->static_key);
1143#ifdef USE_SSL
1144 if (ks->ssl_ctx && free_ssl_ctx)
1145 {
1146 SSL_CTX_free (ks->ssl_ctx);
1147 free_key_ctx_bi (&ks->tls_auth_key);
1148 }
1149#endif /* USE_SSL */
1150#endif /* USE_CRYPTO */
1151 CLEAR (*ks);
1152}
1153
1154#ifdef USE_CRYPTO
1155
1156static void
1157init_crypto_pre (struct context *c, const unsigned int flags)
1158{
1159 if (c->options.engine)
1160 init_crypto_lib_engine (c->options.engine);
1161
1162 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
1163 {
1164 /* load a persisted packet-id for cross-session replay-protection */
1165 if (c->options.packet_id_file)
1166 packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
1167 }
1168
1169 /* Initialize crypto options */
1170
1171 if (c->options.use_iv)
1172 c->c2.crypto_options.flags |= CO_USE_IV;
1173
1174 if (c->options.mute_replay_warnings)
1175 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
1176}
1177
1178/*
1179 * Static Key Mode (using a pre-shared key)
1180 */
1181static void
1182do_init_crypto_static (struct context *c, const unsigned int flags)
1183{
1184 const struct options *options = &c->options;
1185 ASSERT (options->shared_secret_file);
1186
1187 init_crypto_pre (c, flags);
1188
1189 /* Initialize packet ID tracking */
1190 if (options->replay)
1191 {
1192 packet_id_init (&c->c2.packet_id, options->replay_window,
1193 options->replay_time);
1194 c->c2.crypto_options.packet_id = &c->c2.packet_id;
1195 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
1196 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
1197 packet_id_persist_load_obj (&c->c1.pid_persist,
1198 c->c2.crypto_options.packet_id);
1199 }
1200
1201 if (!key_ctx_bi_defined (&c->c1.ks.static_key))
1202 {
1203 struct key2 key2;
1204 struct key_direction_state kds;
1205
1206 /* Get cipher & hash algorithms */
1207 init_key_type (&c->c1.ks.key_type, options->ciphername,
1208 options->ciphername_defined, options->authname,
1209 options->authname_defined, options->keysize,
1210 options->test_crypto, true);
1211
1212 /* Read cipher and hmac keys from shared secret file */
1213 read_key_file (&key2, options->shared_secret_file, true);
1214
1215 /* Check for and fix highly unlikely key problems */
1216 verify_fix_key2 (&key2, &c->c1.ks.key_type,
1217 options->shared_secret_file);
1218
1219 /* Initialize OpenSSL key objects */
1220 key_direction_state_init (&kds, options->key_direction);
1221 must_have_n_keys (options->shared_secret_file, "secret", &key2,
1222 kds.need_keys);
1223 init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
1224 &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
1225 init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
1226 &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
1227
1228 /* Erase the temporary copy of key */
1229 CLEAR (key2);
1230 }
1231 else
1232 {
1233 msg (M_INFO, "Re-using pre-shared static key");
1234 }
1235
1236 /* Get key schedule */
1237 c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
1238
1239 /* Compute MTU parameters */
1240 crypto_adjust_frame_parameters (&c->c2.frame,
1241 &c->c1.ks.key_type,
1242 options->ciphername_defined,
1243 options->use_iv, options->replay, true);
1244
1245 /* Sanity check on IV, sequence number, and cipher mode options */
1246 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1247 options->use_iv);
1248}
1249
1250#ifdef USE_SSL
1251
1252/*
1253 * Initialize the persistent component of OpenVPN's TLS mode,
1254 * which is preserved across SIGUSR1 resets.
1255 */
1256static void
1257do_init_crypto_tls_c1 (struct context *c)
1258{
1259 const struct options *options = &c->options;
1260
1261 if (!c->c1.ks.ssl_ctx)
1262 {
1263 /*
1264 * Initialize the OpenSSL library's global
1265 * SSL context.
1266 */
1267 c->c1.ks.ssl_ctx = init_ssl (options);
1268 if (!c->c1.ks.ssl_ctx)
1269 {
1270#if P2MP
1271 switch (auth_retry_get ())
1272 {
1273 case AR_NONE:
1274 msg (M_FATAL, "Error: private key password verification failed");
1275 break;
1276 case AR_INTERACT:
1277 ssl_purge_auth ();
1278 case AR_NOINTERACT:
1279 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
1280 break;
1281 default:
1282 ASSERT (0);
1283 }
1284 c->sig->signal_text = "private-key-password-failure";
1285 return;
1286#else
1287 msg (M_FATAL, "Error: private key password verification failed");
1288#endif
1289 }
1290
1291 /* Get cipher & hash algorithms */
1292 init_key_type (&c->c1.ks.key_type, options->ciphername,
1293 options->ciphername_defined, options->authname,
1294 options->authname_defined, options->keysize, true, true);
1295
1296 /* TLS handshake authentication (--tls-auth) */
1297 if (options->tls_auth_file)
1298 get_tls_handshake_key (&c->c1.ks.key_type,
1299 &c->c1.ks.tls_auth_key,
1300 options->tls_auth_file,
1301 options->key_direction);
1302 }
1303 else
1304 {
1305 msg (M_INFO, "Re-using SSL/TLS context");
1306 }
1307}
1308
1309static void
1310do_init_crypto_tls (struct context *c, const unsigned int flags)
1311{
1312 const struct options *options = &c->options;
1313 struct tls_options to;
1314 bool packet_id_long_form;
1315
1316 ASSERT (options->tls_server || options->tls_client);
1317 ASSERT (!options->test_crypto);
1318
1319 init_crypto_pre (c, flags);
1320
1321 /* Make sure we are either a TLS client or server but not both */
1322 ASSERT (options->tls_server == !options->tls_client);
1323
1324 /* initialize persistent component */
1325 do_init_crypto_tls_c1 (c);
1326 if (IS_SIG (c))
1327 return;
1328
1329 /* Sanity check on IV, sequence number, and cipher mode options */
1330 check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
1331 options->use_iv);
1332
1333 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
1334 packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
1335
1336 /* Compute MTU parameters */
1337 crypto_adjust_frame_parameters (&c->c2.frame,
1338 &c->c1.ks.key_type,
1339 options->ciphername_defined,
1340 options->use_iv,
1341 options->replay, packet_id_long_form);
1342 tls_adjust_frame_parameters (&c->c2.frame);
1343
1344 /* Set all command-line TLS-related options */
1345 CLEAR (to);
1346
1347 to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
1348 if (packet_id_long_form)
1349 to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
1350
1351 to.ssl_ctx = c->c1.ks.ssl_ctx;
1352 to.key_type = c->c1.ks.key_type;
1353 to.server = options->tls_server;
1354 to.key_method = options->key_method;
1355 to.replay = options->replay;
1356 to.replay_window = options->replay_window;
1357 to.replay_time = options->replay_time;
1358 to.transition_window = options->transition_window;
1359 to.handshake_window = options->handshake_window;
1360 to.packet_timeout = options->tls_timeout;
1361 to.renegotiate_bytes = options->renegotiate_bytes;
1362 to.renegotiate_packets = options->renegotiate_packets;
1363 to.renegotiate_seconds = options->renegotiate_seconds;
1364 to.single_session = options->single_session;
1365
1366#ifdef ENABLE_OCC
1367 to.disable_occ = !options->occ;
1368#endif
1369
1370 to.verify_command = options->tls_verify;
1371 to.verify_x509name = options->tls_remote;
1372 to.crl_file = options->crl_file;
1373 to.ns_cert_type = options->ns_cert_type;
1374 to.es = c->c2.es;
1375
1376#ifdef ENABLE_DEBUG
1377 to.gremlin = c->options.gremlin;
1378#endif
1379
3c7f2f55 1380 to.plugins = c->plugins;
6fbf66fa
JY
1381
1382#if P2MP_SERVER
1383 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
1384 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
1385 to.tmp_dir = options->tmp_dir;
1386 to.username_as_common_name = options->username_as_common_name;
1387 if (options->ccd_exclusive)
1388 to.client_config_dir_exclusive = options->client_config_dir;
1389#endif
1390
1391 /* TLS handshake authentication (--tls-auth) */
1392 if (options->tls_auth_file)
1393 {
1394 to.tls_auth_key = c->c1.ks.tls_auth_key;
1395 to.tls_auth.pid_persist = &c->c1.pid_persist;
1396 to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
1397 crypto_adjust_frame_parameters (&to.frame,
1398 &c->c1.ks.key_type,
1399 false, false, true, true);
1400 }
1401
1402 /* If we are running over TCP, allow for
1403 length prefix */
1404 socket_adjust_frame_parameters (&to.frame, options->proto);
1405
1406 /*
1407 * Initialize OpenVPN's master TLS-mode object.
1408 */
1409 if (flags & CF_INIT_TLS_MULTI)
1410 c->c2.tls_multi = tls_multi_init (&to);
1411
1412 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
1413 c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
1414}
1415
1416static void
1417do_init_finalize_tls_frame (struct context *c)
1418{
1419 if (c->c2.tls_multi)
1420 {
1421 tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
1422 ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
1423 EXPANDED_SIZE (&c->c2.frame));
1424 frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
1425 "Control Channel MTU parms");
1426 }
1427 if (c->c2.tls_auth_standalone)
1428 {
1429 tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
1430 frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
1431 "TLS-Auth MTU parms");
1432 }
1433}
1434
1435#endif /* USE_SSL */
1436#endif /* USE_CRYPTO */
1437
1438#ifdef USE_CRYPTO
1439/*
1440 * No encryption or authentication.
1441 */
1442static void
1443do_init_crypto_none (const struct context *c)
1444{
1445 ASSERT (!c->options.test_crypto);
1446 msg (M_WARN,
1447 "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1448}
1449#endif
1450
1451static void
1452do_init_crypto (struct context *c, const unsigned int flags)
1453{
1454#ifdef USE_CRYPTO
1455 if (c->options.shared_secret_file)
1456 do_init_crypto_static (c, flags);
1457#ifdef USE_SSL
1458 else if (c->options.tls_server || c->options.tls_client)
1459 do_init_crypto_tls (c, flags);
1460#endif
1461 else /* no encryption or authentication. */
1462 do_init_crypto_none (c);
1463#else /* USE_CRYPTO */
1464 msg (M_WARN,
1465 "******* WARNING *******: " PACKAGE_NAME
1466 " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
1467#endif /* USE_CRYPTO */
1468}
1469
1470static void
1471do_init_frame (struct context *c)
1472{
1473#ifdef USE_LZO
1474 /*
1475 * Initialize LZO compression library.
1476 */
1477 if (c->options.comp_lzo)
1478 {
1479 lzo_adjust_frame_parameters (&c->c2.frame);
1480
1481 /*
1482 * LZO usage affects buffer alignment.
1483 */
1484 if (CIPHER_ENABLED (c))
1485 {
1486 frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
1487 frame_or_align_flags (&c->c2.frame,
1488 FRAME_HEADROOM_MARKER_FRAGMENT
1489 |FRAME_HEADROOM_MARKER_DECRYPT);
1490 }
1491
1492#ifdef ENABLE_FRAGMENT
1493 lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
1494#endif
1495 }
1496#endif
1497
1498#ifdef ENABLE_SOCKS
1499 /*
1500 * Adjust frame size for UDP Socks support.
1501 */
1502 if (c->options.socks_proxy_server)
1503 socks_adjust_frame_parameters (&c->c2.frame, c->options.proto);
1504#endif
1505
1506 /*
1507 * Adjust frame size based on the --tun-mtu-extra parameter.
1508 */
1509 if (c->options.tun_mtu_extra_defined)
1510 tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
1511
1512 /*
1513 * Adjust frame size based on link socket parameters.
1514 * (Since TCP is a stream protocol, we need to insert
1515 * a packet length uint16_t in the buffer.)
1516 */
1517 socket_adjust_frame_parameters (&c->c2.frame, c->options.proto);
1518
1519 /*
1520 * Fill in the blanks in the frame parameters structure,
1521 * make sure values are rational, etc.
1522 */
1523 frame_finalize_options (c, NULL);
1524
1525#ifdef ENABLE_FRAGMENT
1526 /*
1527 * Set frame parameter for fragment code. This is necessary because
1528 * the fragmentation code deals with payloads which have already been
1529 * passed through the compression code.
1530 */
1531 c->c2.frame_fragment = c->c2.frame;
1532 frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
1533#endif
1534
1535#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
1536 /*
1537 * MTU advisories
1538 */
1539 if (c->options.fragment && c->options.mtu_test)
1540 msg (M_WARN,
1541 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
1542#endif
1543
1544#ifdef ENABLE_FRAGMENT
1545 if ((c->options.mssfix || c->options.fragment)
1546 && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
1547 msg (M_WARN,
1548 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
1549 ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
1550#endif
1551}
1552
1553static void
1554do_option_warnings (struct context *c)
1555{
1556 const struct options *o = &c->options;
1557
1558#if 1 /* JYFIXME -- port warning */
1559 if (!o->port_option_used && (o->local_port == OPENVPN_PORT && o->remote_port == OPENVPN_PORT))
1560 msg (M_WARN, "IMPORTANT: OpenVPN's default port number is now %d, based on an official port number assignment by IANA. OpenVPN 2.0-beta16 and earlier used 5000 as the default port.",
1561 OPENVPN_PORT);
1562#endif
1563
1564 if (o->ping_send_timeout && !o->ping_rec_timeout)
1565 msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
1566
1567 if ((o->username || o->groupname || o->chroot_dir) && (!o->persist_tun || !o->persist_key))
1568 msg (M_WARN, "WARNING: you are using user/group/chroot without persist-key/persist-tun -- this may cause restarts to fail");
1569
1570#if P2MP
1571 if (o->pull && o->ifconfig_local && c->first_time)
1572 msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
1573
1574#if P2MP_SERVER
1575 if (o->mode == MODE_SERVER)
1576 {
1577 if (o->duplicate_cn && o->client_config_dir)
1578 msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
1579 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
1580 msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
1581 if (!o->keepalive_ping || !o->keepalive_timeout)
1582 msg (M_WARN, "WARNING: --keepalive option is missing from server config");
1583 }
1584#endif
1585#endif
1586
1587#ifdef USE_CRYPTO
1588 if (!o->replay)
1589 msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
1590 if (!o->use_iv)
1591 msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
1592
1593#ifdef USE_SSL
1594 if (o->tls_client
1595 && !o->tls_verify
1596 && !o->tls_remote
1597 && !(o->ns_cert_type & NS_SSL_SERVER))
1598 msg (M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
1599#endif
1600
1601#endif
1602}
1603
1604static void
1605do_init_frame_tls (struct context *c)
1606{
1607#if defined(USE_CRYPTO) && defined(USE_SSL)
1608 do_init_finalize_tls_frame (c);
1609#endif
1610}
1611
1612struct context_buffers *
1613init_context_buffers (const struct frame *frame)
1614{
1615 struct context_buffers *b;
1616
1617 ALLOC_OBJ_CLEAR (b, struct context_buffers);
1618
1619 b->read_link_buf = alloc_buf (BUF_SIZE (frame));
1620 b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
1621
1622 b->aux_buf = alloc_buf (BUF_SIZE (frame));
1623
1624#ifdef USE_CRYPTO
1625 b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
1626 b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
1627#endif
1628
1629#ifdef USE_LZO
1630 b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
1631 b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
1632#endif
1633
1634 return b;
1635}
1636
1637void
1638free_context_buffers (struct context_buffers *b)
1639{
1640 if (b)
1641 {
1642 free_buf (&b->read_link_buf);
1643 free_buf (&b->read_tun_buf);
1644 free_buf (&b->aux_buf);
1645
1646#ifdef USE_LZO
1647 free_buf (&b->lzo_compress_buf);
1648 free_buf (&b->lzo_decompress_buf);
1649#endif
1650
1651#ifdef USE_CRYPTO
1652 free_buf (&b->encrypt_buf);
1653 free_buf (&b->decrypt_buf);
1654#endif
1655
1656 free (b);
1657 }
1658}
1659
1660/*
1661 * Now that we know all frame parameters, initialize
1662 * our buffers.
1663 */
1664static void
1665do_init_buffers (struct context *c)
1666{
1667 c->c2.buffers = init_context_buffers (&c->c2.frame);
1668 c->c2.buffers_owned = true;
1669}
1670
1671#ifdef ENABLE_FRAGMENT
1672/*
1673 * Fragmenting code has buffers to initialize
1674 * once frame parameters are known.
1675 */
1676static void
1677do_init_fragment (struct context *c)
1678{
1679 ASSERT (c->options.fragment);
1680 frame_set_mtu_dynamic (&c->c2.frame_fragment,
1681 c->options.fragment, SET_MTU_UPPER_BOUND);
1682 fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
1683}
1684#endif
1685
1686/*
1687 * Set the --mssfix option.
1688 */
1689static void
1690do_init_mssfix (struct context *c)
1691{
1692 if (c->options.mssfix)
1693 {
1694 frame_set_mtu_dynamic (&c->c2.frame,
1695 c->options.mssfix, SET_MTU_UPPER_BOUND);
1696 }
1697}
1698
1699/*
1700 * Allocate our socket object.
1701 */
1702static void
1703do_link_socket_new (struct context *c)
1704{
1705 ASSERT (!c->c2.link_socket);
1706 c->c2.link_socket = link_socket_new ();
1707 c->c2.link_socket_owned = true;
1708}
1709
1710/*
1711 * bind the TCP/UDP socket
1712 */
1713static void
1714do_init_socket_1 (struct context *c, int mode)
1715{
1716 link_socket_init_phase1 (c->c2.link_socket,
1717 c->options.local,
1718 c->c1.remote_list,
1719 c->options.local_port,
1720 c->options.proto,
1721 mode,
1722 c->c2.accept_from,
1723#ifdef ENABLE_HTTP_PROXY
1724 c->c1.http_proxy,
1725#endif
1726#ifdef ENABLE_SOCKS
1727 c->c1.socks_proxy,
1728#endif
1729#ifdef ENABLE_DEBUG
1730 c->options.gremlin,
1731#endif
1732 c->options.bind_local,
1733 c->options.remote_float,
1734 c->options.inetd,
1735 &c->c1.link_socket_addr,
1736 c->options.ipchange,
3c7f2f55 1737 c->plugins,
6fbf66fa
JY
1738 c->options.resolve_retry_seconds,
1739 c->options.connect_retry_seconds,
1740 c->options.mtu_discover_type,
1741 c->options.rcvbuf,
1742 c->options.sndbuf);
1743}
1744
1745/*
1746 * finalize the TCP/UDP socket
1747 */
1748static void
1749do_init_socket_2 (struct context *c)
1750{
1751 link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
1752 &c->sig->signal_received);
1753}
1754
1755/*
1756 * Print MTU INFO
1757 */
1758static void
1759do_print_data_channel_mtu_parms (struct context *c)
1760{
1761 frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
1762#ifdef ENABLE_FRAGMENT
1763 if (c->c2.fragment)
1764 frame_print (&c->c2.frame_fragment, D_MTU_INFO,
1765 "Fragmentation MTU parms");
1766#endif
1767}
1768
1769#ifdef ENABLE_OCC
1770/*
1771 * Get local and remote options compatibility strings.
1772 */
1773static void
1774do_compute_occ_strings (struct context *c)
1775{
1776 struct gc_arena gc = gc_new ();
1777
1778 c->c2.options_string_local =
1779 options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
1780 c->c2.options_string_remote =
1781 options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
1782
1783 msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
1784 msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
1785 c->c2.options_string_remote);
1786
1787#ifdef USE_CRYPTO
1788 msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
1789 options_string_version (c->c2.options_string_local, &gc),
1790 md5sum ((uint8_t*)c->c2.options_string_local,
1791 strlen (c->c2.options_string_local), 9, &gc));
1792 msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
1793 options_string_version (c->c2.options_string_remote, &gc),
1794 md5sum ((uint8_t*)c->c2.options_string_remote,
1795 strlen (c->c2.options_string_remote), 9, &gc));
1796#endif
1797
1798#if defined(USE_CRYPTO) && defined(USE_SSL)
1799 if (c->c2.tls_multi)
1800 tls_multi_init_set_options (c->c2.tls_multi,
1801 c->c2.options_string_local,
1802 c->c2.options_string_remote);
1803#endif
1804
1805 gc_free (&gc);
1806}
1807#endif
1808
1809/*
1810 * These things can only be executed once per program instantiation.
1811 * Set up for possible UID/GID downgrade, but don't do it yet.
1812 * Daemonize if requested.
1813 */
1814static void
1815do_init_first_time (struct context *c)
1816{
1817 if (c->first_time && !c->c2.did_we_daemonize)
1818 {
1819 /* get user and/or group that we want to setuid/setgid to */
1820 c->c2.uid_gid_specified =
1821 get_group (c->options.groupname, &c->c2.group_state) |
1822 get_user (c->options.username, &c->c2.user_state);
1823
1824 /* get --writepid file descriptor */
1825 get_pid_file (c->options.writepid, &c->c2.pid_state);
1826
1827 /* become a daemon if --daemon */
1828 c->c2.did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
1829
1830 /* should we disable paging? */
1831 if (c->options.mlock && c->c2.did_we_daemonize)
1832 do_mlockall (true); /* call again in case we daemonized */
1833
1834 /* save process ID in a file */
1835 write_pid (&c->c2.pid_state);
1836
1837 /* should we change scheduling priority? */
1838 set_nice (c->options.nice);
1839 }
1840}
1841
1842/*
1843 * If xinetd/inetd mode, don't allow restart.
1844 */
1845static void
1846do_close_check_if_restart_permitted (struct context *c)
1847{
1848 if (c->options.inetd
1849 && (c->sig->signal_received == SIGHUP
1850 || c->sig->signal_received == SIGUSR1))
1851 {
1852 c->sig->signal_received = SIGTERM;
1853 msg (M_INFO,
1854 PACKAGE_NAME
1855 " started by inetd/xinetd cannot restart... Exiting.");
1856 }
1857}
1858
1859/*
1860 * free buffers
1861 */
1862static void
1863do_close_free_buf (struct context *c)
1864{
1865 if (c->c2.buffers_owned)
1866 {
1867 free_context_buffers (c->c2.buffers);
1868 c->c2.buffers = NULL;
1869 c->c2.buffers_owned = false;
1870 }
1871}
1872
1873/*
1874 * close TLS
1875 */
1876static void
1877do_close_tls (struct context *c)
1878{
1879#if defined(USE_CRYPTO) && defined(USE_SSL)
1880 if (c->c2.tls_multi)
1881 {
1882 tls_multi_free (c->c2.tls_multi, true);
1883 c->c2.tls_multi = NULL;
1884 }
1885
1886#ifdef ENABLE_OCC
1887 /* free options compatibility strings */
1888 if (c->c2.options_string_local)
1889 free (c->c2.options_string_local);
1890 if (c->c2.options_string_remote)
1891 free (c->c2.options_string_remote);
1892 c->c2.options_string_local = c->c2.options_string_remote = NULL;
1893#endif
1894#endif
1895}
1896
1897/*
1898 * Free key schedules
1899 */
1900static void
1901do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
1902{
1903 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
1904 key_schedule_free (&c->c1.ks, free_ssl_ctx);
1905}
1906
1907/*
1908 * Close TCP/UDP connection
1909 */
1910static void
1911do_close_link_socket (struct context *c)
1912{
1913 if (c->c2.link_socket && c->c2.link_socket_owned)
1914 {
1915 link_socket_close (c->c2.link_socket);
1916 c->c2.link_socket = NULL;
1917 }
1918
1919 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
1920 {
1921 CLEAR (c->c1.link_socket_addr.remote);
1922 CLEAR (c->c1.link_socket_addr.actual);
1923 }
1924
1925 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
1926 CLEAR (c->c1.link_socket_addr.local);
1927}
1928
1929/*
1930 * Close packet-id persistance file
1931 */
1932static void
1933do_close_packet_id (struct context *c)
1934{
1935#ifdef USE_CRYPTO
1936 packet_id_free (&c->c2.packet_id);
1937 packet_id_persist_save (&c->c1.pid_persist);
1938 if (!(c->sig->signal_received == SIGUSR1))
1939 packet_id_persist_close (&c->c1.pid_persist);
1940#endif
1941}
1942
1943#ifdef ENABLE_FRAGMENT
1944/*
1945 * Close fragmentation handler.
1946 */
1947static void
1948do_close_fragment (struct context *c)
1949{
1950 if (c->c2.fragment)
1951 {
1952 fragment_free (c->c2.fragment);
1953 c->c2.fragment = NULL;
1954 }
1955}
1956#endif
1957
1958/*
1959 * Open and close our event objects.
1960 */
1961
1962static void
1963do_event_set_init (struct context *c,
1964 bool need_us_timeout)
1965{
1966 unsigned int flags = 0;
1967
1968 c->c2.event_set_max = BASE_N_EVENTS;
1969
1970 flags |= EVENT_METHOD_FAST;
1971
1972 if (need_us_timeout)
1973 flags |= EVENT_METHOD_US_TIMEOUT;
1974
1975 c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
1976 c->c2.event_set_owned = true;
1977}
1978
1979static void
1980do_close_event_set (struct context *c)
1981{
1982 if (c->c2.event_set && c->c2.event_set_owned)
1983 {
1984 event_free (c->c2.event_set);
1985 c->c2.event_set = NULL;
1986 c->c2.event_set_owned = false;
1987 }
1988}
1989
1990/*
1991 * Open and close --status file
1992 */
1993
1994static void
1995do_open_status_output (struct context *c)
1996{
1997 if (!c->c1.status_output)
1998 {
1999 c->c1.status_output = status_open (c->options.status_file,
2000 c->options.status_file_update_freq,
2001 -1,
2002 NULL,
2003 STATUS_OUTPUT_WRITE);
2004 c->c1.status_output_owned = true;
2005 }
2006}
2007
2008static void
2009do_close_status_output (struct context *c)
2010{
2011 if (!(c->sig->signal_received == SIGUSR1))
2012 {
2013 if (c->c1.status_output_owned && c->c1.status_output)
2014 {
2015 status_close (c->c1.status_output);
2016 c->c1.status_output = NULL;
2017 c->c1.status_output_owned = false;
2018 }
2019 }
2020}
2021
2022/*
2023 * Handle ifconfig-pool persistance object.
2024 */
2025static void
2026do_open_ifconfig_pool_persist (struct context *c)
2027{
2028#if P2MP_SERVER
2029 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
2030 {
2031 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
2032 c->options.ifconfig_pool_persist_refresh_freq);
2033 c->c1.ifconfig_pool_persist_owned = true;
2034 }
2035#endif
2036}
2037
2038static void
2039do_close_ifconfig_pool_persist (struct context *c)
2040{
2041#if P2MP_SERVER
2042 if (!(c->sig->signal_received == SIGUSR1))
2043 {
2044 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
2045 {
2046 ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
2047 c->c1.ifconfig_pool_persist = NULL;
2048 c->c1.ifconfig_pool_persist_owned = false;
2049 }
2050 }
2051#endif
2052}
2053
2054/*
2055 * Inherit environmental variables
2056 */
2057
2058static void
2059do_inherit_env (struct context *c, const struct env_set *src)
2060{
2061 c->c2.es = env_set_create (&c->c2.gc);
2062 env_set_inherit (c->c2.es, src);
2063}
2064
2065/*
2066 * Fast I/O setup. Fast I/O is an optimization which only works
2067 * if all of the following are true:
2068 *
2069 * (1) The platform is not Windows
2070 * (2) --proto udp is enabled
2071 * (3) --shaper is disabled
2072 */
2073static void
2074do_setup_fast_io (struct context *c)
2075{
2076 if (c->options.fast_io)
2077 {
2078#ifdef WIN32
2079 msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
2080#else
2081 if (c->options.proto != PROTO_UDPv4)
2082 msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
2083 else
2084 {
2085 if (c->options.shaper)
2086 msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
2087 else
2088 {
2089 c->c2.fast_io = true;
2090 }
2091 }
2092#endif
2093 }
2094}
2095
2096static void
2097do_signal_on_tls_errors (struct context *c)
2098{
2099#if defined(USE_CRYPTO) && defined(USE_SSL)
2100 if (c->options.tls_exit)
2101 c->c2.tls_exit_signal = SIGTERM;
2102 else
2103 c->c2.tls_exit_signal = SIGUSR1;
2104#endif
2105}
2106
3c7f2f55 2107#ifdef ENABLE_PLUGIN
6fbf66fa 2108
3c7f2f55
JY
2109void
2110open_plugins (struct context *c, const bool import_options)
6fbf66fa 2111{
3c7f2f55 2112 if (c->options.plugin_list && !c->plugins)
6fbf66fa 2113 {
3c7f2f55
JY
2114 if (import_options)
2115 {
2116 struct plugin_return pr, config;
2117 plugin_return_init (&pr);
2118 c->plugins = plugin_list_open (c->options.plugin_list, &pr, c->c2.es);
2119 c->plugins_owned = true;
2120 plugin_return_get_column (&pr, &config, "config");
2121 if (plugin_return_defined (&config))
2122 {
2123 int i;
2124 for (i = 0; i < config.n; ++i)
2125 {
2126 unsigned int option_types_found = 0;
2127 if (config.list[i] && config.list[i]->value)
2128 options_plugin_import (&c->options,
2129 config.list[i]->value,
2130 D_IMPORT_ERRORS|M_OPTERR,
2131 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
2132 &option_types_found,
2133 c->es);
2134 }
2135 }
2136 plugin_return_free (&pr);
2137 }
2138 else
2139 {
2140 c->plugins = plugin_list_open (c->options.plugin_list, NULL, c->c2.es);
2141 c->plugins_owned = true;
2142 }
6fbf66fa 2143 }
6fbf66fa
JY
2144}
2145
2146static void
2147do_close_plugins (struct context *c)
2148{
3c7f2f55 2149 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 2150 {
3c7f2f55
JY
2151 plugin_list_close (c->plugins);
2152 c->plugins = NULL;
2153 c->plugins_owned = false;
6fbf66fa 2154 }
6fbf66fa
JY
2155}
2156
3c7f2f55
JY
2157static void
2158do_inherit_plugins (struct context *c, const struct context *src)
2159{
2160 if (!c->plugins && src->plugins)
2161 {
2162 c->plugins = plugin_list_inherit (src->plugins);
2163 c->plugins_owned = true;
2164 }
2165}
2166
2167#endif
2168
6fbf66fa
JY
2169#ifdef ENABLE_MANAGEMENT
2170
2171static void
2172management_callback_status_p2p (void *arg, const int version, struct status_output *so)
2173{
2174 struct context *c = (struct context *) arg;
2175 print_status (c, so);
2176}
2177
2178void
2179management_show_net_callback (void *arg, const int msglevel)
2180{
2181#ifdef WIN32
2182 show_routes (msglevel);
2183 show_adapters (msglevel);
2184 msg (msglevel, "END");
2185#else
2186 msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
2187#endif
2188}
2189
2190#endif
2191
2192void
2193init_management_callback_p2p (struct context *c)
2194{
2195#ifdef ENABLE_MANAGEMENT
2196 if (management)
2197 {
2198 struct management_callback cb;
2199 CLEAR (cb);
2200 cb.arg = c;
2201 cb.status = management_callback_status_p2p;
2202 cb.show_net = management_show_net_callback;
2203 management_set_callback (management, &cb);
2204 }
2205#endif
2206}
2207
2208#ifdef ENABLE_MANAGEMENT
2209
2210void
2211init_management (struct context *c)
2212{
2213 if (!management)
2214 management = management_init ();
2215}
2216
2217bool
2218open_management (struct context *c)
2219{
2220 /* initialize management layer */
2221 if (management)
2222 {
2223 if (c->options.management_addr)
2224 {
2225 if (management_open (management,
2226 c->options.management_addr,
2227 c->options.management_port,
2228 c->options.management_user_pass,
2229 c->options.mode == MODE_SERVER,
2230 c->options.management_query_passwords,
2231 c->options.management_log_history_cache,
2232 c->options.management_echo_buffer_size,
2233 c->options.management_state_buffer_size,
2234 c->options.management_hold))
2235 {
2236 management_set_state (management,
2237 OPENVPN_STATE_CONNECTING,
2238 NULL,
2239 (in_addr_t)0);
2240 }
2241
2242 /* possible wait */
2243 do_hold (c);
2244 if (IS_SIG (c))
2245 {
2246 msg (M_WARN, "Signal received from management interface, exiting");
2247 return false;
2248 }
2249 }
2250 else
2251 close_management ();
2252 }
2253 return true;
2254}
2255
2256void
2257close_management (void)
2258{
2259 if (management)
2260 {
2261 management_close (management);
2262 management = NULL;
2263 }
2264}
2265
2266#endif
2267
2268
2269void
2270uninit_management_callback (void)
2271{
2272#ifdef ENABLE_MANAGEMENT
2273 if (management)
2274 {
2275 management_clear_callback (management);
2276 }
2277#endif
2278}
2279
2280/*
2281 * Initialize a tunnel instance, handle pre and post-init
2282 * signal settings.
2283 */
2284void
2285init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
2286{
2287 pre_init_signal_catch ();
2288 init_instance (c, env, flags);
2289 post_init_signal_catch ();
2290}
2291
2292/*
2293 * Initialize a tunnel instance.
2294 */
2295void
2296init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
2297{
2298 const struct options *options = &c->options;
2299 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
2300 int link_socket_mode = LS_MODE_DEFAULT;
2301
2302 /* init garbage collection level */
2303 gc_init (&c->c2.gc);
2304
2305 /* signals caught here will abort */
2306 c->sig->signal_received = 0;
2307 c->sig->signal_text = NULL;
2308 c->sig->hard = false;
2309
2310 /* link_socket_mode allows CM_CHILD_TCP
2311 instances to inherit acceptable fds
2312 from a top-level parent */
2313 if (c->options.proto == PROTO_TCPv4_SERVER)
2314 {
2315 if (c->mode == CM_TOP)
2316 link_socket_mode = LS_MODE_TCP_LISTEN;
2317 else if (c->mode == CM_CHILD_TCP)
2318 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
2319 }
2320
2321 /* should we disable paging? */
2322 if (c->first_time && options->mlock)
2323 do_mlockall (true);
2324
2325 /* possible sleep or management hold if restart */
2326 if (c->mode == CM_P2P || c->mode == CM_TOP)
2327 {
2328 do_startup_pause (c);
2329 if (IS_SIG (c))
2330 goto sig;
2331 }
2332
2333 /* initialize context level 2 --verb/--mute parms */
2334 init_verb_mute (c, IVM_LEVEL_2);
2335
2336 /* set error message delay for non-server modes */
2337 if (c->mode == CM_P2P)
2338 set_check_status_error_delay (P2P_ERROR_DELAY_MS);
2339
2340 /* warn about inconsistent options */
2341 if (c->mode == CM_P2P || c->mode == CM_TOP)
2342 do_option_warnings (c);
2343
2344 /* inherit environmental variables */
2345 if (env)
2346 do_inherit_env (c, env);
2347
3c7f2f55 2348#ifdef ENABLE_PLUGIN
6fbf66fa
JY
2349 /* initialize plugins */
2350 if (c->mode == CM_P2P || c->mode == CM_TOP)
3c7f2f55
JY
2351 open_plugins (c, false);
2352#endif
6fbf66fa
JY
2353
2354 /* should we enable fast I/O? */
2355 if (c->mode == CM_P2P || c->mode == CM_TOP)
2356 do_setup_fast_io (c);
2357
2358 /* should we throw a signal on TLS errors? */
2359 do_signal_on_tls_errors (c);
2360
2361 /* open --status file */
2362 if (c->mode == CM_P2P || c->mode == CM_TOP)
2363 do_open_status_output (c);
2364
2365 /* open --ifconfig-pool-persist file */
2366 if (c->mode == CM_TOP)
2367 do_open_ifconfig_pool_persist (c);
2368
2369#ifdef ENABLE_OCC
2370 /* reset OCC state */
2371 if (c->mode == CM_P2P || child)
2372 c->c2.occ_op = occ_reset_op ();
2373#endif
2374
2375 /* our wait-for-i/o objects, different for posix vs. win32 */
2376 if (c->mode == CM_P2P)
2377 do_event_set_init (c, SHAPER_DEFINED (&c->options));
2378 else if (c->mode == CM_CHILD_TCP)
2379 do_event_set_init (c, false);
2380
2381 /* allocate our socket object */
2382 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2383 do_link_socket_new (c);
2384
2385#ifdef ENABLE_FRAGMENT
2386 /* initialize internal fragmentation object */
2387 if (options->fragment && (c->mode == CM_P2P || child))
2388 c->c2.fragment = fragment_init (&c->c2.frame);
2389#endif
2390
2391 /* init crypto layer */
2392 {
2393 unsigned int crypto_flags = 0;
2394 if (c->mode == CM_TOP)
2395 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
2396 else if (c->mode == CM_P2P)
2397 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
2398 else if (child)
2399 crypto_flags = CF_INIT_TLS_MULTI;
2400 do_init_crypto (c, crypto_flags);
2401 if (IS_SIG (c))
2402 goto sig;
2403 }
2404
2405#ifdef USE_LZO
2406 /* initialize LZO compression library. */
2407 if (options->comp_lzo && (c->mode == CM_P2P || child))
2408 lzo_compress_init (&c->c2.lzo_compwork, options->comp_lzo_adaptive);
2409#endif
2410
2411 /* initialize MTU variables */
2412 do_init_frame (c);
2413
2414 /* initialize TLS MTU variables */
2415 do_init_frame_tls (c);
2416
2417 /* init workspace buffers whose size is derived from frame size */
2418 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
2419 do_init_buffers (c);
2420
2421#ifdef ENABLE_FRAGMENT
2422 /* initialize internal fragmentation capability with known frame size */
2423 if (options->fragment && (c->mode == CM_P2P || child))
2424 do_init_fragment (c);
2425#endif
2426
2427 /* initialize dynamic MTU variable */
2428 do_init_mssfix (c);
2429
2430 /* bind the TCP/UDP socket */
2431 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2432 do_init_socket_1 (c, link_socket_mode);
2433
2434 /* initialize tun/tap device object,
2435 open tun/tap device, ifconfig, run up script, etc. */
2436 if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
2437 c->c2.did_open_tun = do_open_tun (c);
2438
2439 /* print MTU info */
2440 do_print_data_channel_mtu_parms (c);
2441
2442#ifdef ENABLE_OCC
2443 /* get local and remote options compatibility strings */
2444 if (c->mode == CM_P2P || child)
2445 do_compute_occ_strings (c);
2446#endif
2447
2448 /* initialize output speed limiter */
2449 if (c->mode == CM_P2P)
2450 do_init_traffic_shaper (c);
2451
2452 /* do one-time inits, and possibily become a daemon here */
2453 do_init_first_time (c);
2454
2455 /*
2456 * Actually do UID/GID downgrade, and chroot, if requested.
2457 * May be delayed by --client, --pull, or --up-delay.
2458 */
2459 do_uid_gid_chroot (c, c->c2.did_open_tun);
2460
2461 /* finalize the TCP/UDP socket */
2462 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
2463 do_init_socket_2 (c);
2464
2465 /* initialize timers */
2466 if (c->mode == CM_P2P || child)
2467 do_init_timers (c, false);
2468
2469 /* Check for signals */
2470 if (IS_SIG (c))
2471 goto sig;
2472
2473 return;
2474
2475 sig:
2476 c->sig->signal_text = "init_instance";
2477 close_context (c, -1, flags);
2478 return;
2479}
2480
2481/*
2482 * Close a tunnel instance.
2483 */
2484void
2485close_instance (struct context *c)
2486{
2487 /* close event objects */
2488 do_close_event_set (c);
2489
2490 if (c->mode == CM_P2P
2491 || c->mode == CM_CHILD_TCP
2492 || c->mode == CM_CHILD_UDP
2493 || c->mode == CM_TOP)
2494 {
2495 /* if xinetd/inetd mode, don't allow restart */
2496 do_close_check_if_restart_permitted (c);
2497
2498#ifdef USE_LZO
2499 if (c->options.comp_lzo)
2500 lzo_compress_uninit (&c->c2.lzo_compwork);
2501#endif
2502
2503 /* free buffers */
2504 do_close_free_buf (c);
2505
2506 /* close TLS */
2507 do_close_tls (c);
2508
2509 /* free key schedules */
2510 do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
2511
2512 /* close TCP/UDP connection */
2513 do_close_link_socket (c);
2514
2515 /* close TUN/TAP device */
2516 do_close_tun (c, false);
2517
3c7f2f55 2518#ifdef ENABLE_PLUGIN
6fbf66fa
JY
2519 /* call plugin close functions and unload */
2520 do_close_plugins (c);
3c7f2f55 2521#endif
6fbf66fa
JY
2522
2523 /* close packet-id persistance file */
2524 do_close_packet_id (c);
2525
2526 /* close --status file */
2527 do_close_status_output (c);
2528
2529#ifdef ENABLE_FRAGMENT
2530 /* close fragmentation handler */
2531 do_close_fragment (c);
2532#endif
2533
2534 /* close --ifconfig-pool-persist obj */
2535 do_close_ifconfig_pool_persist (c);
2536
2537 /* garbage collect */
2538 gc_free (&c->c2.gc);
2539 }
2540}
2541
2542void
2543inherit_context_child (struct context *dest,
2544 const struct context *src)
2545{
2546 CLEAR (*dest);
2547
2548 switch (src->options.proto)
2549 {
2550 case PROTO_UDPv4:
2551 dest->mode = CM_CHILD_UDP;
2552 break;
2553 case PROTO_TCPv4_SERVER:
2554 dest->mode = CM_CHILD_TCP;
2555 break;
2556 default:
2557 ASSERT (0);
2558 }
2559
2560 dest->first_time = false;
2561
2562 dest->gc = gc_new ();
2563
2564 ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
2565
2566 /* c1 init */
2567 packet_id_persist_init (&dest->c1.pid_persist);
2568
2569#ifdef USE_CRYPTO
2570 dest->c1.ks.key_type = src->c1.ks.key_type;
2571#ifdef USE_SSL
2572 /* inherit SSL context */
2573 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
2574 dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
2575#endif
2576#endif
2577
2578 /* options */
2579 dest->options = src->options;
2580 options_detach (&dest->options);
2581
2582 if (dest->mode == CM_CHILD_TCP)
2583 {
2584 /*
2585 * The CM_TOP context does the socket listen(),
2586 * and the CM_CHILD_TCP context does the accept().
2587 */
2588 dest->c2.accept_from = src->c2.link_socket;
2589 }
2590
3c7f2f55 2591#ifdef ENABLE_PLUGIN
6fbf66fa 2592 /* inherit plugins */
3c7f2f55
JY
2593 do_inherit_plugins (dest, src);
2594#endif
6fbf66fa
JY
2595
2596 /* context init */
2597 init_instance (dest, src->c2.es, CC_USR1_TO_HUP | CC_GC_FREE);
2598 if (IS_SIG (dest))
2599 return;
2600
2601 /* inherit tun/tap interface object */
2602 dest->c1.tuntap = src->c1.tuntap;
2603
2604 /* UDP inherits some extra things which TCP does not */
2605 if (dest->mode == CM_CHILD_UDP)
2606 {
2607 /* inherit buffers */
2608 dest->c2.buffers = src->c2.buffers;
2609
2610 /* inherit parent link_socket and tuntap */
2611 dest->c2.link_socket = src->c2.link_socket;
2612
2613 ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
2614 *dest->c2.link_socket_info = src->c2.link_socket->info;
2615
2616 /* locally override some link_socket_info fields */
2617 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
2618 dest->c2.link_socket_info->connection_established = false;
2619 }
2620}
2621
2622void
2623inherit_context_top (struct context *dest,
2624 const struct context *src)
2625{
2626 /* copy parent */
2627 *dest = *src;
2628
2629 /*
2630 * CM_TOP_CLONE will prevent close_instance from freeing or closing
2631 * resources owned by the parent.
2632 *
2633 * Also note that CM_TOP_CLONE context objects are
2634 * closed by multi_top_free in multi.c.
2635 */
2636 dest->mode = CM_TOP_CLONE;
2637
2638 dest->first_time = false;
2639
2640 options_detach (&dest->options);
2641 gc_detach (&dest->gc);
2642 gc_detach (&dest->c2.gc);
2643
3c7f2f55
JY
2644 /* detach plugins */
2645 dest->plugins_owned = false;
2646
6fbf66fa
JY
2647#if defined(USE_CRYPTO) && defined(USE_SSL)
2648 dest->c2.tls_multi = NULL;
2649#endif
2650
3c7f2f55 2651 /* detach c1 ownership */
6fbf66fa
JY
2652 dest->c1.tuntap_owned = false;
2653 dest->c1.status_output_owned = false;
2654#if P2MP_SERVER
2655 dest->c1.ifconfig_pool_persist_owned = false;
2656#endif
3c7f2f55
JY
2657
2658 /* detach c2 ownership */
6fbf66fa
JY
2659 dest->c2.event_set_owned = false;
2660 dest->c2.link_socket_owned = false;
2661 dest->c2.buffers_owned = false;
2662
2663 dest->c2.event_set = NULL;
2664 if (src->options.proto == PROTO_UDPv4)
2665 do_event_set_init (dest, false);
2666}
2667
2668void
2669close_context (struct context *c, int sig, unsigned int flags)
2670{
2671 if (sig >= 0)
2672 c->sig->signal_received = sig;
2673
2674 if (c->sig->signal_received == SIGUSR1)
2675 {
2676 if ((flags & CC_USR1_TO_HUP)
2677 || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
2678 c->sig->signal_received = SIGHUP;
2679 }
2680
2681 close_instance (c);
2682
2683 if (flags & CC_GC_FREE)
2684 context_gc_free (c);
2685}
2686
2687#ifdef USE_CRYPTO
2688
2689static void
2690test_malloc (void)
2691{
2692 int i, j;
2693 msg (M_INFO, "Multithreaded malloc test...");
2694 for (i = 0; i < 25; ++i)
2695 {
2696 struct gc_arena gc = gc_new ();
2697 const int limit = get_random () & 0x03FF;
2698 for (j = 0; j < limit; ++j)
2699 {
2700 gc_malloc (get_random () & 0x03FF, false, &gc);
2701 }
2702 gc_free (&gc);
2703 }
2704}
2705
2706/*
2707 * Do a loopback test
2708 * on the crypto subsystem.
2709 */
2710static void *
2711test_crypto_thread (void *arg)
2712{
2713 struct context *c = (struct context *) arg;
2714 const struct options *options = &c->options;
2715#if defined(USE_PTHREAD)
2716 struct context *child = NULL;
2717 openvpn_thread_t child_id = 0;
2718#endif
2719
2720 ASSERT (options->test_crypto);
2721 init_verb_mute (c, IVM_LEVEL_1);
2722 context_init_1 (c);
2723 do_init_crypto_static (c, 0);
2724
2725#if defined(USE_PTHREAD)
2726 {
2727 if (c->first_time && options->n_threads > 1)
2728 {
2729 if (options->n_threads > 2)
2730 msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
2731 openvpn_thread_init ();
2732 ALLOC_OBJ (child, struct context);
2733 context_clear (child);
2734 child->options = *options;
2735 options_detach (&child->options);
2736 child->first_time = false;
2737 child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
2738 }
2739 }
2740#endif
2741 frame_finalize_options (c, options);
2742
2743#if defined(USE_PTHREAD)
2744 if (options->n_threads == 2)
2745 test_malloc ();
2746#endif
2747
2748 test_crypto (&c->c2.crypto_options, &c->c2.frame);
2749
2750 key_schedule_free (&c->c1.ks, true);
2751 packet_id_free (&c->c2.packet_id);
2752
2753#if defined(USE_PTHREAD)
2754 if (c->first_time && options->n_threads > 1)
2755 openvpn_thread_join (child_id);
2756 if (child)
2757 free (child);
2758#endif
2759 context_gc_free (c);
2760 return NULL;
2761}
2762
2763#endif
2764
2765bool
2766do_test_crypto (const struct options *o)
2767{
2768#ifdef USE_CRYPTO
2769 if (o->test_crypto)
2770 {
2771 struct context c;
2772
2773 /* print version number */
2774 msg (M_INFO, "%s", title_string);
2775
3c7f2f55 2776 context_clear (&c);
6fbf66fa
JY
2777 c.options = *o;
2778 options_detach (&c.options);
2779 c.first_time = true;
2780 test_crypto_thread ((void *) &c);
2781 return true;
2782 }
2783#endif
2784 return false;
2785}