]> git.ipfire.org Git - thirdparty/openvpn.git/blame - src/openvpn/init.c
pf: restyle pf_c2c/addr_test() to make them 'struct context' agnostic
[thirdparty/openvpn.git] / src / openvpn / 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 *
49979459 8 * Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
6fbf66fa
JY
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 *
caa54ac3
DS
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
6fbf66fa
JY
22 */
23
c110b289
ABL
24#ifdef HAVE_CONFIG_H
25#include "config.h"
26#elif defined(_MSC_VER)
27#include "config-msvc.h"
28#endif
29
6fbf66fa
JY
30#include "syshead.h"
31
c5931897
CH
32#ifdef ENABLE_SYSTEMD
33#include <systemd/sd-daemon.h>
34#endif
35
6fbf66fa
JY
36#include "win32.h"
37#include "init.h"
bf97c00f 38#include "run_command.h"
6fbf66fa
JY
39#include "sig.h"
40#include "occ.h"
41#include "list.h"
42#include "otime.h"
43#include "pool.h"
44#include "gremlin.h"
ce98fd24 45#include "pkcs11.h"
6add6b2f 46#include "ps.h"
e12fe286 47#include "lladdr.h"
e7a65dfb 48#include "ping.h"
ffea644c 49#include "mstats.h"
63dc03d0 50#include "ssl_verify.h"
c6e24fa3 51#include "tls_crypt.h"
2191c471 52#include "forward-inline.h"
6fbf66fa
JY
53
54#include "memdbg.h"
55
56#include "occ-inline.h"
57
0c9eb1d3
JY
58static struct context *static_context; /* GLOBAL */
59
6fbf66fa
JY
60/*
61 * Crypto initialization flags
62 */
63#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
64#define CF_INIT_TLS_MULTI (1<<1)
65#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
66
81d882d5 67static void do_init_first_time(struct context *c);
6fbf66fa
JY
68
69void
81d882d5 70context_clear(struct context *c)
6fbf66fa 71{
81d882d5 72 CLEAR(*c);
6fbf66fa
JY
73}
74
75void
81d882d5 76context_clear_1(struct context *c)
6fbf66fa 77{
81d882d5 78 CLEAR(c->c1);
6fbf66fa
JY
79}
80
81void
81d882d5 82context_clear_2(struct context *c)
6fbf66fa 83{
81d882d5 84 CLEAR(c->c2);
6fbf66fa
JY
85}
86
87void
81d882d5 88context_clear_all_except_first_time(struct context *c)
6fbf66fa 89{
81d882d5
DS
90 const bool first_time_save = c->first_time;
91 const struct context_persist cpsave = c->persist;
92 context_clear(c);
93 c->first_time = first_time_save;
94 c->persist = cpsave;
6fbf66fa
JY
95}
96
4a9d1d70
SK
97/*
98 * Pass tunnel endpoint and MTU parms to a user-supplied script.
99 * Used to execute the up/down script/plugins.
100 */
101static void
102run_up_down(const char *command,
103 const struct plugin_list *plugins,
104 int plugin_type,
105 const char *arg,
106#ifdef _WIN32
107 DWORD adapter_index,
108#endif
109 const char *dev_type,
110 int tun_mtu,
111 int link_mtu,
112 const char *ifconfig_local,
113 const char *ifconfig_remote,
114 const char *context,
115 const char *signal_text,
116 const char *script_type,
117 struct env_set *es)
118{
119 struct gc_arena gc = gc_new();
120
121 if (signal_text)
122 {
123 setenv_str(es, "signal", signal_text);
124 }
125 setenv_str(es, "script_context", context);
126 setenv_int(es, "tun_mtu", tun_mtu);
127 setenv_int(es, "link_mtu", link_mtu);
128 setenv_str(es, "dev", arg);
129 if (dev_type)
130 {
131 setenv_str(es, "dev_type", dev_type);
132 }
133#ifdef _WIN32
134 setenv_int(es, "dev_idx", adapter_index);
135#endif
136
137 if (!ifconfig_local)
138 {
139 ifconfig_local = "";
140 }
141 if (!ifconfig_remote)
142 {
143 ifconfig_remote = "";
144 }
145 if (!context)
146 {
147 context = "";
148 }
149
150 if (plugin_defined(plugins, plugin_type))
151 {
152 struct argv argv = argv_new();
153 ASSERT(arg);
154 argv_printf(&argv,
155 "%s %d %d %s %s %s",
156 arg,
157 tun_mtu, link_mtu,
158 ifconfig_local, ifconfig_remote,
159 context);
160
161 if (plugin_call(plugins, plugin_type, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
162 {
163 msg(M_FATAL, "ERROR: up/down plugin call failed");
164 }
165
166 argv_reset(&argv);
167 }
168
169 if (command)
170 {
171 struct argv argv = argv_new();
172 ASSERT(arg);
173 setenv_str(es, "script_type", script_type);
174 argv_parse_cmd(&argv, command);
175 argv_printf_cat(&argv, "%s %d %d %s %s %s", arg, tun_mtu, link_mtu,
176 ifconfig_local, ifconfig_remote, context);
177 argv_msg(M_INFO, &argv);
178 openvpn_run_script(&argv, es, S_FATAL, "--up/--down");
179 argv_reset(&argv);
180 }
181
182 gc_free(&gc);
183}
184
6fbf66fa 185/*
4e9a51d7
JY
186 * Should be called after options->ce is modified at the top
187 * of a SIGUSR1 restart.
6fbf66fa
JY
188 */
189static void
81d882d5 190update_options_ce_post(struct options *options)
6fbf66fa 191{
4e9a51d7 192#if P2MP
81d882d5
DS
193 /*
194 * In pull mode, we usually import --ping/--ping-restart parameters from
195 * the server. However we should also set an initial default --ping-restart
196 * for the period of time before we pull the --ping-restart parameter
197 * from the server.
198 */
199 if (options->pull
200 && options->ping_rec_timeout_action == PING_UNDEF
201 && proto_is_dgram(options->ce.proto))
4e9a51d7 202 {
81d882d5
DS
203 options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
204 options->ping_rec_timeout_action = PING_RESTART;
4e9a51d7
JY
205 }
206#endif
4e9a51d7 207}
6fbf66fa 208
af1bf85a 209#ifdef ENABLE_MANAGEMENT
3cf6c932 210static bool
81d882d5 211management_callback_proxy_cmd(void *arg, const char **p)
3cf6c932 212{
81d882d5
DS
213 struct context *c = arg;
214 struct connection_entry *ce = &c->options.ce;
215 struct gc_arena *gc = &c->c2.gc;
216 bool ret = false;
3cf6c932 217
81d882d5
DS
218 update_time();
219 if (streq(p[1], "NONE"))
220 {
221 ret = true;
222 }
223 else if (p[2] && p[3])
af1bf85a 224 {
81d882d5 225 if (streq(p[1], "HTTP"))
af1bf85a 226 {
81d882d5
DS
227 struct http_proxy_options *ho;
228 if (ce->proto != PROTO_TCP && ce->proto != PROTO_TCP_CLIENT)
e719a053 229 {
81d882d5
DS
230 msg(M_WARN, "HTTP proxy support only works for TCP based connections");
231 return false;
af1bf85a 232 }
81d882d5
DS
233 ho = init_http_proxy_options_once(&ce->http_proxy_options, gc);
234 ho->server = string_alloc(p[2], gc);
235 ho->port = string_alloc(p[3], gc);
236 ho->auth_retry = (p[4] && streq(p[4], "nct") ? PAR_NCT : PAR_ALL);
237 ret = true;
af1bf85a 238 }
81d882d5 239 else if (streq(p[1], "SOCKS"))
af1bf85a 240 {
81d882d5 241 ce->socks_proxy_server = string_alloc(p[2], gc);
aa9d3a5b 242 ce->socks_proxy_port = string_alloc(p[3], gc);
81d882d5 243 ret = true;
af1bf85a 244 }
3cf6c932 245 }
81d882d5
DS
246 else
247 {
248 msg(M_WARN, "Bad proxy command");
249 }
3cf6c932 250
81d882d5 251 ce->flags &= ~CE_MAN_QUERY_PROXY;
3cf6c932 252
81d882d5 253 return ret;
3cf6c932
JY
254}
255
256static bool
81d882d5
DS
257ce_management_query_proxy(struct context *c)
258{
259 const struct connection_list *l = c->options.connection_list;
260 struct connection_entry *ce = &c->options.ce;
261 struct gc_arena gc;
262 bool ret = true;
263
264 update_time();
265 if (management)
266 {
267 gc = gc_new();
268 {
269 struct buffer out = alloc_buf_gc(256, &gc);
270 buf_printf(&out, ">PROXY:%u,%s,%s", (l ? l->current : 0) + 1,
271 (proto_is_udp(ce->proto) ? "UDP" : "TCP"), np(ce->remote));
272 management_notify_generic(management, BSTR(&out));
273 }
274 ce->flags |= CE_MAN_QUERY_PROXY;
275 while (ce->flags & CE_MAN_QUERY_PROXY)
276 {
277 management_event_loop_n_seconds(management, 1);
278 if (IS_SIG(c))
af1bf85a 279 {
81d882d5
DS
280 ret = false;
281 break;
af1bf85a
HH
282 }
283 }
81d882d5 284 gc_free(&gc);
3cf6c932 285 }
af1bf85a 286
81d882d5 287 return ret;
3cf6c932
JY
288}
289
3cf6c932 290
54561af6 291static bool
81d882d5
DS
292management_callback_remote_cmd(void *arg, const char **p)
293{
294 struct context *c = (struct context *) arg;
295 struct connection_entry *ce = &c->options.ce;
296 int ret = false;
297 if (p[1] && ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
298 {
299 int flags = 0;
300 if (!strcmp(p[1], "ACCEPT"))
301 {
302 flags = CE_MAN_QUERY_REMOTE_ACCEPT;
303 ret = true;
304 }
305 else if (!strcmp(p[1], "SKIP"))
306 {
307 flags = CE_MAN_QUERY_REMOTE_SKIP;
308 ret = true;
309 }
310 else if (!strcmp(p[1], "MOD") && p[2] && p[3])
311 {
312 if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
313 {
314 struct remote_host_store *rhs = c->options.rh_store;
315 if (!rhs)
316 {
317 ALLOC_OBJ_CLEAR_GC(rhs, struct remote_host_store, &c->options.gc);
318 c->options.rh_store = rhs;
319 }
320 strncpynt(rhs->host, p[2], RH_HOST_LEN);
321 strncpynt(rhs->port, p[3], RH_PORT_LEN);
322
323 ce->remote = rhs->host;
324 ce->remote_port = rhs->port;
325 flags = CE_MAN_QUERY_REMOTE_MOD;
326 ret = true;
327 }
328 }
329 if (ret)
330 {
331 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_REMOTE_SHIFT);
332 ce->flags |= ((flags&CE_MAN_QUERY_REMOTE_MASK)<<CE_MAN_QUERY_REMOTE_SHIFT);
333 }
334 }
335 return ret;
54561af6
JY
336}
337
338static bool
81d882d5
DS
339ce_management_query_remote(struct context *c)
340{
341 struct gc_arena gc = gc_new();
342 volatile struct connection_entry *ce = &c->options.ce;
e81f313a
DS
343 int ce_changed = true; /* presume the connection entry will be changed */
344
81d882d5
DS
345 update_time();
346 if (management)
347 {
348 struct buffer out = alloc_buf_gc(256, &gc);
e81f313a
DS
349
350 buf_printf(&out, ">REMOTE:%s,%s,%s", np(ce->remote), ce->remote_port,
351 proto2ascii(ce->proto, ce->af, false));
81d882d5 352 management_notify_generic(management, BSTR(&out));
e81f313a
DS
353
354 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMOTE_SHIFT);
355 ce->flags |= (CE_MAN_QUERY_REMOTE_QUERY << CE_MAN_QUERY_REMOTE_SHIFT);
356 while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
357 & CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
81d882d5
DS
358 {
359 management_event_loop_n_seconds(management, 1);
360 if (IS_SIG(c))
361 {
e81f313a 362 ce_changed = false; /* connection entry have not been set */
81d882d5
DS
363 break;
364 }
365 }
366 }
e81f313a
DS
367 gc_free(&gc);
368
369 if (ce_changed)
81d882d5 370 {
e81f313a
DS
371 /* If it is likely a connection entry was modified,
372 * check what changed in the flags and that it was not skipped
373 */
374 const int flags = ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
375 & CE_MAN_QUERY_REMOTE_MASK);
376 ce_changed = (flags != CE_MAN_QUERY_REMOTE_SKIP);
81d882d5 377 }
e81f313a 378 return ce_changed;
54561af6 379}
cf93f0e0 380#endif /* ENABLE_MANAGEMENT */
54561af6 381
4e9a51d7
JY
382/*
383 * Initialize and possibly randomize connection list.
384 */
385static void
81d882d5 386init_connection_list(struct context *c)
4e9a51d7 387{
81d882d5 388 struct connection_list *l = c->options.connection_list;
23d61c56 389
81d882d5
DS
390 l->current = -1;
391 if (c->options.remote_random)
6fbf66fa 392 {
81d882d5
DS
393 int i;
394 for (i = 0; i < l->len; ++i)
23d61c56 395 {
81d882d5
DS
396 const int j = get_random() % l->len;
397 if (i != j)
23d61c56 398 {
81d882d5
DS
399 struct connection_entry *tmp;
400 tmp = l->array[i];
401 l->array[i] = l->array[j];
402 l->array[j] = tmp;
23d61c56
AS
403 }
404 }
6fbf66fa 405 }
4e9a51d7
JY
406}
407
23d61c56
AS
408/*
409 * Clear the remote address list
410 */
81d882d5
DS
411static void
412clear_remote_addrlist(struct link_socket_addr *lsa, bool free)
23d61c56 413{
e719a053 414 if (lsa->remote_list && free)
81d882d5
DS
415 {
416 freeaddrinfo(lsa->remote_list);
417 }
23d61c56
AS
418 lsa->remote_list = NULL;
419 lsa->current_remote = NULL;
420}
421
4e9a51d7
JY
422/*
423 * Increment to next connection entry
424 */
425static void
81d882d5
DS
426next_connection_entry(struct context *c)
427{
428 struct connection_list *l = c->options.connection_list;
429 bool ce_defined;
430 struct connection_entry *ce;
431 int n_cycles = 0;
432
4cd4899e
SK
433 do
434 {
81d882d5
DS
435 ce_defined = true;
436 if (c->options.no_advance && l->current >= 0)
437 {
438 c->options.no_advance = false;
439 }
23d61c56 440 else
81d882d5
DS
441 {
442 /* Check if there is another resolved address to try for
443 * the current connection */
444 if (c->c1.link_socket_addr.current_remote
445 && c->c1.link_socket_addr.current_remote->ai_next)
446 {
23d61c56 447 c->c1.link_socket_addr.current_remote =
81d882d5
DS
448 c->c1.link_socket_addr.current_remote->ai_next;
449 }
450 else
451 {
452 /* FIXME (schwabe) fix the persist-remote-ip option for real,
453 * this is broken probably ever since connection lists and multiple
454 * remote existed
455 */
456 if (!c->options.persist_remote_ip)
457 {
458 /* close_instance should have cleared the addrinfo objects */
459 ASSERT(c->c1.link_socket_addr.current_remote == NULL);
460 ASSERT(c->c1.link_socket_addr.remote_list == NULL);
461 }
462 else
463 {
464 c->c1.link_socket_addr.current_remote =
465 c->c1.link_socket_addr.remote_list;
466 }
467
468 /*
469 * Increase the number of connection attempts
470 * If this is connect-retry-max * size(l)
471 * OpenVPN will quit
472 */
473
474 c->options.unsuccessful_attempts++;
475
476 if (++l->current >= l->len)
477 {
478
479 l->current = 0;
480 if (++n_cycles >= 2)
481 {
482 msg(M_FATAL, "No usable connection profiles are present");
483 }
484 }
485 }
486 }
3cf6c932 487
81d882d5 488 ce = l->array[l->current];
3cf6c932 489
81d882d5
DS
490 if (ce->flags & CE_DISABLED)
491 {
492 ce_defined = false;
493 }
3cf6c932 494
81d882d5 495 c->options.ce = *ce;
cf93f0e0 496#ifdef ENABLE_MANAGEMENT
81d882d5
DS
497 if (ce_defined && management && management_query_remote_enabled(management))
498 {
499 /* allow management interface to override connection entry details */
500 ce_defined = ce_management_query_remote(c);
501 if (IS_SIG(c))
502 {
503 break;
504 }
505 }
7b02cc2a 506 else if (ce_defined && management && management_query_proxy_enabled(management))
23d61c56 507 {
81d882d5
DS
508 ce_defined = ce_management_query_proxy(c);
509 if (IS_SIG(c))
510 {
511 break;
512 }
23d61c56 513 }
3cf6c932 514#endif
81d882d5 515 } while (!ce_defined);
23d61c56 516
81d882d5
DS
517 /* Check if this connection attempt would bring us over the limit */
518 if (c->options.connect_retry_max > 0
519 && c->options.unsuccessful_attempts > (l->len * c->options.connect_retry_max))
520 {
521 msg(M_FATAL, "All connections have been connect-retry-max (%d) times unsuccessful, exiting",
522 c->options.connect_retry_max);
523 }
524 update_options_ce_post(&c->options);
6fbf66fa
JY
525}
526
92bbb061
JY
527/*
528 * Query for private key and auth-user-pass username/passwords
529 */
315f6fbc 530void
81d882d5 531init_query_passwords(const struct context *c)
92bbb061 532{
81d882d5
DS
533 /* Certificate password input */
534 if (c->options.key_pass_file)
535 {
536 pem_password_setup(c->options.key_pass_file);
537 }
81d882d5 538
92bbb061 539#if P2MP
81d882d5
DS
540 /* Auth user/pass input */
541 if (c->options.auth_user_pass_file)
eab3e22f
JY
542 {
543#ifdef ENABLE_CLIENT_CR
81d882d5 544 auth_user_pass_setup(c->options.auth_user_pass_file, &c->options.sc_info);
eab3e22f 545#else
81d882d5 546 auth_user_pass_setup(c->options.auth_user_pass_file, NULL);
eab3e22f
JY
547#endif
548 }
92bbb061
JY
549#endif
550}
551
4e9a51d7
JY
552/*
553 * Initialize/Uninitialize HTTP or SOCKS proxy
554 */
555
4e9a51d7 556static void
81d882d5 557uninit_proxy_dowork(struct context *c)
4e9a51d7 558{
81d882d5 559 if (c->c1.http_proxy_owned && c->c1.http_proxy)
4e9a51d7 560 {
81d882d5
DS
561 http_proxy_close(c->c1.http_proxy);
562 c->c1.http_proxy = NULL;
563 c->c1.http_proxy_owned = false;
4e9a51d7 564 }
81d882d5 565 if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
4e9a51d7 566 {
81d882d5
DS
567 socks_proxy_close(c->c1.socks_proxy);
568 c->c1.socks_proxy = NULL;
569 c->c1.socks_proxy_owned = false;
4e9a51d7 570 }
4e9a51d7
JY
571}
572
573static void
81d882d5 574init_proxy_dowork(struct context *c)
6fbf66fa 575{
81d882d5 576 bool did_http = false;
f214bb21 577
81d882d5 578 uninit_proxy_dowork(c);
4e9a51d7 579
81d882d5 580 if (c->options.ce.http_proxy_options)
4e9a51d7 581 {
81d882d5
DS
582 /* Possible HTTP proxy user/pass input */
583 c->c1.http_proxy = http_proxy_new(c->options.ce.http_proxy_options);
584 if (c->c1.http_proxy)
585 {
586 did_http = true;
587 c->c1.http_proxy_owned = true;
588 }
4e9a51d7 589 }
4e9a51d7 590
a4b8f653 591 if (!did_http && c->options.ce.socks_proxy_server)
4e9a51d7 592 {
81d882d5
DS
593 c->c1.socks_proxy = socks_proxy_new(c->options.ce.socks_proxy_server,
594 c->options.ce.socks_proxy_port,
595 c->options.ce.socks_proxy_authfile);
596 if (c->c1.socks_proxy)
597 {
598 c->c1.socks_proxy_owned = true;
599 }
4e9a51d7 600 }
4e9a51d7
JY
601}
602
603static void
81d882d5 604init_proxy(struct context *c)
4e9a51d7 605{
81d882d5 606 init_proxy_dowork(c);
4e9a51d7
JY
607}
608
609static void
81d882d5 610uninit_proxy(struct context *c)
4e9a51d7 611{
81d882d5 612 uninit_proxy_dowork(c);
4e9a51d7
JY
613}
614
5fa25eeb 615/*
39326238
LS
616 * Saves the initial state of NCP-regotiable
617 * options into a storage which persists over SIGUSR1.
5fa25eeb
LS
618 */
619static void
39326238 620save_ncp_options(struct context *c)
5fa25eeb
LS
621{
622 c->c1.ciphername = c->options.ciphername;
623 c->c1.authname = c->options.authname;
624 c->c1.keysize = c->options.keysize;
625}
626
39326238 627/* Restores NCP-negotiable options to original values */
5fa25eeb 628static void
39326238 629restore_ncp_options(struct context *c)
5fa25eeb
LS
630{
631 c->options.ciphername = c->c1.ciphername;
632 c->options.authname = c->c1.authname;
633 c->options.keysize = c->c1.keysize;
634}
635
4e9a51d7 636void
81d882d5 637context_init_1(struct context *c)
4e9a51d7 638{
81d882d5 639 context_clear_1(c);
6fbf66fa 640
81d882d5 641 packet_id_persist_init(&c->c1.pid_persist);
4e9a51d7 642
81d882d5 643 init_connection_list(c);
6fbf66fa 644
39326238 645 save_ncp_options(c);
5fa25eeb 646
ce98fd24 647#if defined(ENABLE_PKCS11)
81d882d5
DS
648 if (c->first_time)
649 {
650 int i;
651 pkcs11_initialize(true, c->options.pkcs11_pin_cache_period);
652 for (i = 0; i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL; i++)
4cd4899e 653 {
81d882d5
DS
654 pkcs11_addProvider(c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
655 c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
4cd4899e 656 }
81d882d5 657 }
ce98fd24 658#endif
984cf003 659
c67d59cd 660#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
81d882d5
DS
661 {
662 /*
663 * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
664 */
665 struct user_pass up;
666 CLEAR(up);
667 strcpy(up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
668 get_user_pass(&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
669 msg(M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
670 * 'needok' command, usually 'ok' or 'cancel'. */
671 }
dd1047f5
JY
672#endif
673
e83a8684
DS
674#ifdef ENABLE_SYSTEMD
675 /* We can report the PID via getpid() to systemd here as OpenVPN will not
676 * do any fork due to daemon() a future call.
677 * See possibly_become_daemon() [init.c] for more details.
678 */
b13bc6c9 679 sd_notifyf(0, "READY=1\nSTATUS=Pre-connection initialization successful\nMAINPID=%lu",
e83a8684
DS
680 (unsigned long) getpid());
681#endif
682
6fbf66fa
JY
683}
684
685void
81d882d5 686context_gc_free(struct context *c)
6fbf66fa 687{
81d882d5
DS
688 gc_free(&c->c2.gc);
689 gc_free(&c->options.gc);
690 gc_free(&c->gc);
6fbf66fa
JY
691}
692
6add6b2f
JY
693#if PORT_SHARE
694
695static void
81d882d5 696close_port_share(void)
6add6b2f 697{
81d882d5 698 if (port_share)
6add6b2f 699 {
81d882d5
DS
700 port_share_close(port_share);
701 port_share = NULL;
6add6b2f
JY
702 }
703}
704
705static void
81d882d5 706init_port_share(struct context *c)
6add6b2f 707{
81d882d5 708 if (!port_share && (c->options.port_share_host && c->options.port_share_port))
6add6b2f 709 {
81d882d5
DS
710 port_share = port_share_open(c->options.port_share_host,
711 c->options.port_share_port,
712 MAX_RW_SIZE_LINK(&c->c2.frame),
713 c->options.port_share_journal_dir);
714 if (port_share == NULL)
715 {
716 msg(M_FATAL, "Fatal error: Port sharing failed");
717 }
6add6b2f
JY
718 }
719}
720
81d882d5 721#endif /* if PORT_SHARE */
6add6b2f 722
e74e3a4d 723
6fbf66fa 724bool
81d882d5 725init_static(void)
6fbf66fa 726{
81d882d5 727 /* configure_path (); */
c67d59cd 728
c7ca9133 729#if defined(DMALLOC)
81d882d5 730 crypto_init_dmalloc();
6fbf66fa
JY
731#endif
732
e74e3a4d
DS
733
734 /*
735 * Initialize random number seed. random() is only used
736 * when "weak" random numbers are acceptable.
737 * SSL library routines are always used when cryptographically
738 * strong random numbers are required.
739 */
740 struct timeval tv;
741 if (!gettimeofday(&tv, NULL))
742 {
743 const unsigned int seed = (unsigned int) tv.tv_sec ^ tv.tv_usec;
744 srandom(seed);
745 }
746
81d882d5
DS
747 error_reset(); /* initialize error.c */
748 reset_check_status(); /* initialize status check code in socket.c */
6fbf66fa 749
445b192a 750#ifdef _WIN32
81d882d5 751 init_win32();
6fbf66fa
JY
752#endif
753
754#ifdef OPENVPN_DEBUG_COMMAND_LINE
81d882d5
DS
755 {
756 int i;
757 for (i = 0; i < argc; ++i)
4cd4899e 758 {
81d882d5 759 msg(M_INFO, "argv[%d] = '%s'", i, argv[i]);
4cd4899e 760 }
81d882d5 761 }
6fbf66fa
JY
762#endif
763
81d882d5 764 update_time();
6fbf66fa 765
81d882d5 766 init_ssl_lib();
6fbf66fa 767
81d882d5
DS
768 /* init PRNG used for IV generation */
769 /* When forking, copy this to more places in the code to avoid fork
770 * random-state predictability */
771 prng_init(NULL, 0);
6fbf66fa
JY
772
773#ifdef PID_TEST
81d882d5
DS
774 packet_id_interactive_test(); /* test the sequence number code */
775 return false;
6fbf66fa
JY
776#endif
777
778#ifdef SCHEDULE_TEST
81d882d5
DS
779 schedule_test();
780 return false;
6fbf66fa
JY
781#endif
782
783#ifdef LIST_TEST
81d882d5
DS
784 list_test();
785 return false;
6fbf66fa
JY
786#endif
787
788#ifdef IFCONFIG_POOL_TEST
81d882d5
DS
789 ifconfig_pool_test(0x0A010004, 0x0A0100FF);
790 return false;
6fbf66fa
JY
791#endif
792
793#ifdef CHARACTER_CLASS_DEBUG
81d882d5
DS
794 character_class_debug();
795 return false;
6fbf66fa
JY
796#endif
797
798#ifdef EXTRACT_X509_FIELD_TEST
81d882d5
DS
799 extract_x509_field_test();
800 return false;
6fbf66fa
JY
801#endif
802
428b8279 803#ifdef TIME_TEST
81d882d5
DS
804 time_test();
805 return false;
428b8279
JY
806#endif
807
6a8ea970 808#ifdef TEST_GET_DEFAULT_GATEWAY
81d882d5
DS
809 {
810 struct route_gateway_info rgi;
811 struct route_ipv6_gateway_info rgi6;
812 get_default_gateway(&rgi);
813 get_default_gateway_ipv6(&rgi6, NULL);
814 print_default_gateway(M_INFO, &rgi, &rgi6);
815 return false;
816 }
6a8ea970
JY
817#endif
818
6cd276ba 819#ifdef GEN_PATH_TEST
81d882d5
DS
820 {
821 struct gc_arena gc = gc_new();
822 const char *fn = gen_path("foo",
823 "bar",
824 &gc);
825 printf("%s\n", fn);
826 gc_free(&gc);
827 }
828 return false;
6cd276ba 829#endif
ddad0a8c 830
6cd276ba 831#ifdef STATUS_PRINTF_TEST
81d882d5
DS
832 {
833 struct gc_arena gc = gc_new();
b7bea782 834 const char *tmp_file = platform_create_temp_file("/tmp", "foo", &gc);
81d882d5
DS
835 struct status_output *so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
836 status_printf(so, "%s", "foo");
837 status_printf(so, "%s", "bar");
838 if (!status_close(so))
839 {
840 msg(M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
841 }
842 gc_free(&gc);
843 }
844 return false;
ddad0a8c
JY
845#endif
846
26bb4c74 847#ifdef ARGV_TEST
81d882d5
DS
848 {
849 void argv_test(void);
850
851 argv_test();
852 return false;
853 }
26bb4c74
JY
854#endif
855
03bfb228 856#ifdef PRNG_TEST
81d882d5
DS
857 {
858 struct gc_arena gc = gc_new();
859 uint8_t rndbuf[8];
860 int i;
861 prng_init("sha1", 16);
862 /*prng_init (NULL, 0);*/
863 const int factor = 1;
864 for (i = 0; i < factor * 8; ++i)
865 {
03bfb228 866#if 1
81d882d5 867 prng_bytes(rndbuf, sizeof(rndbuf));
03bfb228 868#else
81d882d5 869 ASSERT(rand_bytes(rndbuf, sizeof(rndbuf)));
03bfb228 870#endif
81d882d5
DS
871 printf("[%d] %s\n", i, format_hex(rndbuf, sizeof(rndbuf), 0, &gc));
872 }
873 gc_free(&gc);
874 prng_uninit();
875 return false;
876 }
877#endif /* ifdef PRNG_TEST */
03bfb228 878
7e1c085d 879#ifdef BUFFER_LIST_AGGREGATE_TEST
81d882d5
DS
880 /* test buffer_list_aggregate function */
881 {
882 static const char *text[] = {
883 "It was a bright cold day in April, ",
884 "and the clocks were striking ",
885 "thirteen. ",
886 "Winston Smith, ",
887 "his chin nuzzled into his breast in an ",
888 "effort to escape the vile wind, ",
889 "slipped quickly through the glass doors ",
890 "of Victory Mansions, though not quickly ",
891 "enough to prevent a swirl of gritty dust from ",
892 "entering along with him."
893 };
894
895 int iter, listcap;
896 for (listcap = 0; listcap < 12; ++listcap)
897 {
898 for (iter = 0; iter < 512; ++iter)
899 {
900 struct buffer_list *bl = buffer_list_new(listcap);
901 {
902 int i;
903 for (i = 0; i < SIZE(text); ++i)
4cd4899e 904 {
81d882d5 905 buffer_list_push(bl, (unsigned char *)text[i]);
4cd4899e 906 }
81d882d5
DS
907 }
908 printf("[cap=%d i=%d] *************************\n", listcap, iter);
909 if (!(iter & 8))
910 {
911 buffer_list_aggregate(bl, iter/2);
912 }
913 if (!(iter & 16))
914 {
915 buffer_list_push(bl, (unsigned char *)"Even more text...");
916 }
917 buffer_list_aggregate(bl, iter);
918 if (!(iter & 1))
919 {
920 buffer_list_push(bl, (unsigned char *)"More text...");
921 }
922 {
923 struct buffer *buf;
924 while ((buf = buffer_list_peek(bl)))
925 {
926 int c;
927 printf("'");
928 while ((c = buf_read_u8(buf)) >= 0)
4cd4899e 929 {
81d882d5 930 putchar(c);
4cd4899e 931 }
81d882d5
DS
932 printf("'\n");
933 buffer_list_advance(bl, 0);
934 }
935 }
936 buffer_list_free(bl);
937 }
938 }
939 return false;
940 }
941#endif /* ifdef BUFFER_LIST_AGGREGATE_TEST */
7e1c085d 942
ffea644c 943#ifdef MSTATS_TEST
81d882d5
DS
944 {
945 int i;
946 mstats_open("/dev/shm/mstats.dat");
947 for (i = 0; i < 30; ++i)
948 {
949 mmap_stats->n_clients += 1;
950 mmap_stats->link_write_bytes += 8;
951 mmap_stats->link_read_bytes += 16;
952 sleep(1);
953 }
954 mstats_close();
955 return false;
956 }
ffea644c
JY
957#endif
958
81d882d5 959 return true;
6fbf66fa
JY
960}
961
962void
81d882d5 963uninit_static(void)
6fbf66fa 964{
81d882d5 965 free_ssl_lib();
ce98fd24 966
ce98fd24 967#ifdef ENABLE_PKCS11
81d882d5 968 pkcs11_terminate();
ce98fd24 969#endif
6fbf66fa 970
6add6b2f 971#if PORT_SHARE
81d882d5 972 close_port_share();
6add6b2f
JY
973#endif
974
c7ca9133 975#if defined(MEASURE_TLS_HANDSHAKE_STATS)
81d882d5 976 show_tls_performance_stats();
6fbf66fa
JY
977#endif
978}
979
980void
81d882d5 981init_verb_mute(struct context *c, unsigned int flags)
6fbf66fa 982{
81d882d5 983 if (flags & IVM_LEVEL_1)
6fbf66fa 984 {
81d882d5
DS
985 /* set verbosity and mute levels */
986 set_check_status(D_LINK_ERRORS, D_READ_WRITE);
987 set_debug_level(c->options.verbosity, SDL_CONSTRAIN);
988 set_mute_cutoff(c->options.mute);
6fbf66fa
JY
989 }
990
81d882d5
DS
991 /* special D_LOG_RW mode */
992 if (flags & IVM_LEVEL_2)
993 {
994 c->c2.log_rw = (check_debug_level(D_LOG_RW) && !check_debug_level(D_LOG_RW + 1));
995 }
6fbf66fa
JY
996}
997
998/*
999 * Possibly set --dev based on --dev-node.
1000 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
1001 * set --dev to tun.
1002 */
1003void
81d882d5 1004init_options_dev(struct options *options)
6fbf66fa 1005{
81d882d5
DS
1006 if (!options->dev && options->dev_node)
1007 {
1008 char *dev_node = string_alloc(options->dev_node, NULL); /* POSIX basename() implementaions may modify its arguments */
1009 options->dev = basename(dev_node);
1010 }
6fbf66fa
JY
1011}
1012
1013bool
81d882d5 1014print_openssl_info(const struct options *options)
6fbf66fa 1015{
81d882d5
DS
1016 /*
1017 * OpenSSL info print mode?
1018 */
81d882d5
DS
1019 if (options->show_ciphers || options->show_digests || options->show_engines
1020 || options->show_tls_ciphers || options->show_curves)
6fbf66fa 1021 {
81d882d5
DS
1022 if (options->show_ciphers)
1023 {
1024 show_available_ciphers();
1025 }
1026 if (options->show_digests)
1027 {
1028 show_available_digests();
1029 }
1030 if (options->show_engines)
1031 {
1032 show_available_engines();
1033 }
1034 if (options->show_tls_ciphers)
1035 {
aba75874
SK
1036 show_available_tls_ciphers(options->cipher_list,
1037 options->tls_cert_profile);
81d882d5
DS
1038 }
1039 if (options->show_curves)
1040 {
1041 show_available_curves();
1042 }
1043 return true;
6fbf66fa 1044 }
81d882d5 1045 return false;
6fbf66fa
JY
1046}
1047
1048/*
1049 * Static pre-shared key generation mode?
1050 */
1051bool
81d882d5 1052do_genkey(const struct options *options)
6fbf66fa 1053{
81d882d5 1054 if (options->genkey)
6fbf66fa 1055 {
81d882d5 1056 int nbits_written;
6fbf66fa 1057
81d882d5
DS
1058 notnull(options->shared_secret_file,
1059 "shared secret output file (--secret)");
6fbf66fa 1060
81d882d5
DS
1061 if (options->mlock) /* should we disable paging? */
1062 {
1063 platform_mlockall(true);
1064 }
6fbf66fa 1065
81d882d5 1066 nbits_written = write_key_file(2, options->shared_secret_file);
a8fa1679
SK
1067 if (nbits_written < 0)
1068 {
1069 msg(M_FATAL, "Failed to write key file");
1070 }
6fbf66fa 1071
81d882d5
DS
1072 msg(D_GENKEY | M_NOPREFIX,
1073 "Randomly generated %d bit key written to %s", nbits_written,
1074 options->shared_secret_file);
1075 return true;
6fbf66fa 1076 }
81d882d5 1077 return false;
6fbf66fa
JY
1078}
1079
1080/*
1081 * Persistent TUN/TAP device management mode?
1082 */
1083bool
81d882d5 1084do_persist_tuntap(const struct options *options)
6fbf66fa 1085{
81d882d5 1086 if (options->persist_config)
6fbf66fa 1087 {
81d882d5
DS
1088 /* sanity check on options for --mktun or --rmtun */
1089 notnull(options->dev, "TUN/TAP device (--dev)");
1090 if (options->ce.remote || options->ifconfig_local
1091 || options->ifconfig_remote_netmask
81d882d5
DS
1092 || options->shared_secret_file
1093 || options->tls_server || options->tls_client
81d882d5
DS
1094 )
1095 {
1096 msg(M_FATAL|M_OPTERR,
1097 "options --mktun or --rmtun should only be used together with --dev");
1098 }
4ad2b65d 1099#ifdef ENABLE_FEATURE_TUN_PERSIST
81d882d5
DS
1100 tuncfg(options->dev, options->dev_type, options->dev_node,
1101 options->persist_mode,
1102 options->username, options->groupname, &options->tuntap_options);
1103 if (options->persist_mode && options->lladdr)
1104 {
1105 set_lladdr(options->dev, options->lladdr, NULL);
1106 }
1107 return true;
1108#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
1109 msg( M_FATAL|M_OPTERR,
1110 "options --mktun and --rmtun are not available on your operating "
1111 "system. Please check 'man tun' (or 'tap'), whether your system "
1112 "supports using 'ifconfig %s create' / 'destroy' to create/remove "
1113 "persistant tunnel interfaces.", options->dev );
6fbf66fa 1114#endif
4ad2b65d 1115 }
81d882d5 1116 return false;
6fbf66fa
JY
1117}
1118
1119/*
1120 * Should we become a daemon?
1121 * Return true if we did it.
1122 */
da9b2927 1123bool
81d882d5 1124possibly_become_daemon(const struct options *options)
6fbf66fa 1125{
81d882d5 1126 bool ret = false;
7660bba1
CH
1127
1128#ifdef ENABLE_SYSTEMD
81d882d5
DS
1129 /* return without forking if we are running from systemd */
1130 if (sd_notify(0, "READY=0") > 0)
1131 {
1132 return ret;
1133 }
7660bba1
CH
1134#endif
1135
81d882d5 1136 if (options->daemon)
6fbf66fa 1137 {
81d882d5
DS
1138 ASSERT(!options->inetd);
1139 /* Don't chdir immediately, but the end of the init sequence, if needed */
1140 if (daemon(1, options->log) < 0)
1141 {
1142 msg(M_ERR, "daemon() failed or unsupported");
1143 }
1144 restore_signal_state();
1145 if (options->log)
1146 {
1147 set_std_files_to_null(true);
1148 }
6835555e 1149
81d882d5 1150 ret = true;
6fbf66fa 1151 }
81d882d5 1152 return ret;
6fbf66fa
JY
1153}
1154
1155/*
99385447 1156 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
6fbf66fa
JY
1157 */
1158static void
81d882d5 1159do_uid_gid_chroot(struct context *c, bool no_delay)
6fbf66fa 1160{
81d882d5
DS
1161 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
1162 struct context_0 *c0 = c->c0;
6fbf66fa 1163
81d882d5 1164 if (c0 && !c0->uid_gid_chroot_set)
6fbf66fa 1165 {
81d882d5
DS
1166 /* chroot if requested */
1167 if (c->options.chroot_dir)
1168 {
1169 if (no_delay)
65140a3a 1170 {
81d882d5
DS
1171 platform_chroot(c->options.chroot_dir);
1172 }
1173 else if (c->first_time)
1174 {
1175 msg(M_INFO, "NOTE: chroot %s", why_not);
1176 }
1177 }
1178
1179 /* set user and/or group if we want to setuid/setgid */
1180 if (c0->uid_gid_specified)
1181 {
1182 if (no_delay)
1183 {
1184 platform_group_set(&c0->platform_state_group);
1185 platform_user_set(&c0->platform_state_user);
1186 }
1187 else if (c->first_time)
1188 {
1189 msg(M_INFO, "NOTE: UID/GID downgrade %s", why_not);
65140a3a 1190 }
81d882d5 1191 }
99385447 1192
ffea644c 1193#ifdef ENABLE_MEMSTATS
81d882d5
DS
1194 if (c->first_time && c->options.memstats_fn)
1195 {
1196 mstats_open(c->options.memstats_fn);
1197 }
ffea644c
JY
1198#endif
1199
cd5990e0 1200#ifdef ENABLE_SELINUX
81d882d5
DS
1201 /* Apply a SELinux context in order to restrict what OpenVPN can do
1202 * to _only_ what it is supposed to do after initialization is complete
1203 * (basically just network I/O operations). Doing it after chroot
1204 * requires /proc to be mounted in the chroot (which is annoying indeed
1205 * but doing it before requires more complex SELinux policies.
1206 */
1207 if (c->options.selinux_context)
1208 {
1209 if (no_delay)
1210 {
1211 if (-1 == setcon(c->options.selinux_context))
1212 {
1213 msg(M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
1214 }
1215 else
1216 {
1217 msg(M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
1218 }
1219 }
1220 else if (c->first_time)
1221 {
1222 msg(M_INFO, "NOTE: setcon %s", why_not);
1223 }
1224 }
1225#endif
1226
1227 /* Privileges are going to be dropped by now (if requested), be sure
1228 * to prevent any future privilege dropping attempts from now on.
1229 */
1230 if (no_delay)
1231 {
1232 c0->uid_gid_chroot_set = true;
1233 }
6fbf66fa
JY
1234 }
1235}
1236
1237/*
1238 * Return common name in a way that is formatted for
1239 * prepending to msg() output.
1240 */
1241const char *
81d882d5 1242format_common_name(struct context *c, struct gc_arena *gc)
6fbf66fa 1243{
81d882d5 1244 struct buffer out = alloc_buf_gc(256, gc);
81d882d5 1245 if (c->c2.tls_multi)
6fbf66fa 1246 {
81d882d5 1247 buf_printf(&out, "[%s] ", tls_common_name(c->c2.tls_multi, false));
6fbf66fa 1248 }
81d882d5 1249 return BSTR(&out);
6fbf66fa
JY
1250}
1251
1252void
81d882d5 1253pre_setup(const struct options *options)
6fbf66fa 1254{
445b192a 1255#ifdef _WIN32
81d882d5 1256 if (options->exit_event_name)
6fbf66fa 1257 {
81d882d5
DS
1258 win32_signal_open(&win32_signal,
1259 WSO_FORCE_SERVICE,
1260 options->exit_event_name,
1261 options->exit_event_initial_state);
6fbf66fa 1262 }
81d882d5 1263 else
6fbf66fa 1264 {
81d882d5
DS
1265 win32_signal_open(&win32_signal,
1266 WSO_FORCE_CONSOLE,
1267 NULL,
1268 false);
6fbf66fa 1269
81d882d5
DS
1270 /* put a title on the top window bar */
1271 if (win32_signal.mode == WSO_MODE_CONSOLE)
1272 {
1273 window_title_save(&window_title);
1274 window_title_generate(options->config);
1275 }
6fbf66fa 1276 }
81d882d5 1277#endif /* ifdef _WIN32 */
6fbf66fa
JY
1278}
1279
1280void
81d882d5 1281reset_coarse_timers(struct context *c)
6fbf66fa 1282{
81d882d5 1283 c->c2.coarse_timer_wakeup = 0;
6fbf66fa
JY
1284}
1285
f2134b7b
AS
1286/*
1287 * Initialise the server poll timeout timer
1288 * This timer is used in the http/socks proxy setup so it needs to be setup
1289 * before
1290 */
1291static void
81d882d5 1292do_init_server_poll_timeout(struct context *c)
f2134b7b 1293{
81d882d5 1294 update_time();
f2134b7b 1295 if (c->options.ce.connect_timeout)
81d882d5
DS
1296 {
1297 event_timeout_init(&c->c2.server_poll_interval, c->options.ce.connect_timeout, now);
1298 }
f2134b7b
AS
1299}
1300
6fbf66fa
JY
1301/*
1302 * Initialize timers
1303 */
1304static void
81d882d5 1305do_init_timers(struct context *c, bool deferred)
6fbf66fa 1306{
81d882d5
DS
1307 update_time();
1308 reset_coarse_timers(c);
6fbf66fa 1309
81d882d5
DS
1310 /* initialize inactivity timeout */
1311 if (c->options.inactivity_timeout)
1312 {
1313 event_timeout_init(&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
1314 }
6fbf66fa 1315
81d882d5 1316 /* initialize pings */
6fbf66fa 1317
81d882d5
DS
1318 if (c->options.ping_send_timeout)
1319 {
1320 event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
1321 }
6fbf66fa 1322
81d882d5
DS
1323 if (c->options.ping_rec_timeout)
1324 {
1325 event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
1326 }
6fbf66fa 1327
81d882d5 1328 if (!deferred)
6fbf66fa 1329 {
81d882d5
DS
1330 /* initialize connection establishment timer */
1331 event_timeout_init(&c->c2.wait_for_connect, 1, now);
6fbf66fa
JY
1332
1333#ifdef ENABLE_OCC
81d882d5 1334 /* initialize occ timers */
6fbf66fa 1335
81d882d5
DS
1336 if (c->options.occ
1337 && !TLS_MODE(c)
1338 && c->c2.options_string_local && c->c2.options_string_remote)
1339 {
1340 event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
1341 }
6fbf66fa 1342
81d882d5
DS
1343 if (c->options.mtu_test)
1344 {
1345 event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
1346 }
6fbf66fa
JY
1347#endif
1348
81d882d5 1349 /* initialize packet_id persistence timer */
81d882d5
DS
1350 if (c->options.packet_id_file)
1351 {
1352 event_timeout_init(&c->c2.packet_id_persist_interval, 60, now);
1353 }
6fbf66fa 1354
81d882d5
DS
1355 /* initialize tmp_int optimization that limits the number of times we call
1356 * tls_multi_process in the main event loop */
1357 interval_init(&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
6fbf66fa
JY
1358 }
1359}
1360
1361/*
1362 * Initialize traffic shaper.
1363 */
1364static void
81d882d5 1365do_init_traffic_shaper(struct context *c)
6fbf66fa 1366{
3d163bc5 1367#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
1368 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
1369 if (c->options.shaper)
6fbf66fa 1370 {
81d882d5
DS
1371 shaper_init(&c->c2.shaper, c->options.shaper);
1372 shaper_msg(&c->c2.shaper);
6fbf66fa
JY
1373 }
1374#endif
1375}
1376
1377/*
eb95f367
GD
1378 * Allocate route list structures for IPv4 and IPv6
1379 * (we do this for IPv4 even if no --route option has been seen, as other
1380 * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
6fbf66fa
JY
1381 */
1382static void
81d882d5 1383do_alloc_route_list(struct context *c)
6fbf66fa 1384{
81d882d5
DS
1385 if (!c->c1.route_list)
1386 {
1387 ALLOC_OBJ_CLEAR_GC(c->c1.route_list, struct route_list, &c->gc);
1388 }
1389 if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
1390 {
1391 ALLOC_OBJ_CLEAR_GC(c->c1.route_ipv6_list, struct route_ipv6_list, &c->gc);
1392 }
6fbf66fa
JY
1393}
1394
1395
1396/*
1397 * Initialize the route list, resolving any DNS names in route
1398 * options and saving routes in the environment.
1399 */
1400static void
81d882d5
DS
1401do_init_route_list(const struct options *options,
1402 struct route_list *route_list,
1403 const struct link_socket_info *link_socket_info,
1404 struct env_set *es)
6fbf66fa 1405{
81d882d5
DS
1406 const char *gw = NULL;
1407 int dev = dev_type_enum(options->dev, options->dev_type);
1408 int metric = 0;
6fbf66fa 1409
81d882d5
DS
1410 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
1411 {
1412 gw = options->ifconfig_remote_netmask;
1413 }
1414 if (options->route_default_gateway)
1415 {
1416 gw = options->route_default_gateway;
1417 }
1418 if (options->route_default_metric)
1419 {
1420 metric = options->route_default_metric;
1421 }
6fbf66fa 1422
81d882d5
DS
1423 if (init_route_list(route_list,
1424 options->routes,
1425 gw,
1426 metric,
1427 link_socket_current_remote(link_socket_info),
1428 es))
6fbf66fa 1429 {
81d882d5
DS
1430 /* copy routes to environment */
1431 setenv_routes(es, route_list);
6fbf66fa
JY
1432 }
1433}
1434
512cda46 1435static void
81d882d5
DS
1436do_init_route_ipv6_list(const struct options *options,
1437 struct route_ipv6_list *route_ipv6_list,
1438 const struct link_socket_info *link_socket_info,
1439 struct env_set *es)
512cda46 1440{
81d882d5
DS
1441 const char *gw = NULL;
1442 int metric = -1; /* no metric set */
512cda46 1443
81d882d5
DS
1444 gw = options->ifconfig_ipv6_remote; /* default GW = remote end */
1445#if 0 /* not yet done for IPv6 - TODO!*/
1446 if (options->route_ipv6_default_gateway) /* override? */
1447 {
1448 gw = options->route_ipv6_default_gateway;
1449 }
512cda46
GD
1450#endif
1451
81d882d5
DS
1452 if (options->route_default_metric)
1453 {
1454 metric = options->route_default_metric;
1455 }
512cda46 1456
81d882d5
DS
1457 /* redirect (IPv6) gateway to VPN? if yes, add a few more specifics
1458 */
1459 if (options->routes_ipv6->flags & RG_REROUTE_GW)
d227929b 1460 {
81d882d5
DS
1461 char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
1462 int i;
d227929b 1463
81d882d5
DS
1464 for (i = 0; opt_list[i]; i++)
1465 {
1466 add_route_ipv6_to_option_list( options->routes_ipv6,
1467 string_alloc(opt_list[i], options->routes_ipv6->gc),
1468 NULL, NULL );
1469 }
d227929b
GD
1470 }
1471
81d882d5
DS
1472 if (init_route_ipv6_list(route_ipv6_list,
1473 options->routes_ipv6,
1474 gw,
1475 metric,
1476 link_socket_current_remote_ipv6(link_socket_info),
1477 es))
512cda46 1478 {
81d882d5
DS
1479 /* copy routes to environment */
1480 setenv_routes_ipv6(es, route_ipv6_list);
512cda46
GD
1481 }
1482}
1483
1484
6fbf66fa
JY
1485/*
1486 * Called after all initialization has been completed.
1487 */
1488void
81d882d5 1489initialization_sequence_completed(struct context *c, const unsigned int flags)
6fbf66fa 1490{
81d882d5 1491 static const char message[] = "Initialization Sequence Completed";
6fbf66fa 1492
81d882d5
DS
1493 /* Reset the unsuccessful connection counter on complete initialisation */
1494 c->options.unsuccessful_attempts = 0;
23d61c56 1495
81d882d5
DS
1496 /* If we delayed UID/GID downgrade or chroot, do it now */
1497 do_uid_gid_chroot(c, true);
6fbf66fa 1498
5bde5b6d 1499
57116536
AQ
1500 /*
1501 * In some cases (i.e. when receiving auth-token via
1502 * push-reply) the auth-nocache option configured on the
1503 * client is overridden; for this reason we have to wait
1504 * for the push-reply message before attempting to wipe
1505 * the user/pass entered by the user
1506 */
1507 if (c->options.mode == MODE_POINT_TO_POINT)
1508 {
1509 delayed_auth_pass_purge();
1510 }
1511
81d882d5
DS
1512 /* Test if errors */
1513 if (flags & ISC_ERRORS)
a9c802b2 1514 {
445b192a 1515#ifdef _WIN32
81d882d5
DS
1516 show_routes(M_INFO|M_NOPREFIX);
1517 show_adapters(M_INFO|M_NOPREFIX);
1518 msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
6fbf66fa 1519#else
c5931897 1520#ifdef ENABLE_SYSTEMD
81d882d5 1521 sd_notifyf(0, "STATUS=Failed to start up: %s With Errors\nERRNO=1", message);
c5931897 1522#endif /* HAVE_SYSTEMD_SD_DAEMON_H */
81d882d5 1523 msg(M_INFO, "%s With Errors", message);
6fbf66fa 1524#endif
a9c802b2 1525 }
81d882d5 1526 else
c5931897
CH
1527 {
1528#ifdef ENABLE_SYSTEMD
e83a8684 1529 sd_notifyf(0, "STATUS=%s", message);
c5931897 1530#endif
81d882d5 1531 msg(M_INFO, "%s", message);
c5931897 1532 }
6fbf66fa 1533
81d882d5
DS
1534 /* Flag that we initialized */
1535 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
1536 {
1537 c->options.no_advance = true;
1538 }
6fbf66fa 1539
445b192a 1540#ifdef _WIN32
81d882d5 1541 fork_register_dns_action(c->c1.tuntap);
b90c6f17
JY
1542#endif
1543
6fbf66fa 1544#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1545 /* Tell management interface that we initialized */
1546 if (management)
1547 {
1548 in_addr_t *tun_local = NULL;
1549 struct in6_addr *tun_local6 = NULL;
1550 struct openvpn_sockaddr local, remote;
1551 struct link_socket_actual *actual;
1552 socklen_t sa_len = sizeof(local);
1553 const char *detail = "SUCCESS";
1554 if (flags & ISC_ERRORS)
1555 {
1556 detail = "ERROR";
1557 }
1558
1559 CLEAR(local);
1560 actual = &get_link_socket_info(c)->lsa->actual;
1561 remote = actual->dest;
1562 getsockname(c->c2.link_socket->sd, &local.addr.sa, &sa_len);
2191c471 1563#if ENABLE_IP_PKTINFO
81d882d5 1564 if (!addr_defined(&local))
2191c471 1565 {
81d882d5 1566 switch (local.addr.sa.sa_family)
2191c471 1567 {
81d882d5 1568 case AF_INET:
7efa60d9 1569#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
81d882d5 1570 local.addr.in4.sin_addr = actual->pi.in4.ipi_spec_dst;
4a82a9ac 1571#else
81d882d5 1572 local.addr.in4.sin_addr = actual->pi.in4;
4a82a9ac 1573#endif
81d882d5
DS
1574 break;
1575
1576 case AF_INET6:
1577 local.addr.in6.sin6_addr = actual->pi.in6.ipi6_addr;
1578 break;
2191c471
HH
1579 }
1580 }
1581#endif
1582
81d882d5 1583 if (c->c1.tuntap)
2191c471 1584 {
81d882d5
DS
1585 tun_local = &c->c1.tuntap->local;
1586 tun_local6 = &c->c1.tuntap->local_ipv6;
1587 }
1588 management_set_state(management,
1589 OPENVPN_STATE_CONNECTED,
1590 detail,
1591 tun_local,
1592 tun_local6,
1593 &local,
1594 &remote);
1595 if (tun_local)
1596 {
1597 management_post_tunnel_open(management, *tun_local);
2191c471 1598 }
6fbf66fa 1599 }
81d882d5 1600#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
1601}
1602
1603/*
1604 * Possibly add routes and/or call route-up script
1605 * based on options.
1606 */
1607void
81d882d5
DS
1608do_route(const struct options *options,
1609 struct route_list *route_list,
1610 struct route_ipv6_list *route_ipv6_list,
1611 const struct tuntap *tt,
1612 const struct plugin_list *plugins,
1613 struct env_set *es)
6fbf66fa 1614{
81d882d5 1615 if (!options->route_noexec && ( route_list || route_ipv6_list ) )
15be3202 1616 {
81d882d5
DS
1617 add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options), es);
1618 setenv_int(es, "redirect_gateway", route_did_redirect_default_gateway(route_list));
15be3202
JY
1619 }
1620#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1621 if (management)
1622 {
1623 management_up_down(management, "UP", es);
1624 }
15be3202 1625#endif
6fbf66fa 1626
81d882d5 1627 if (plugin_defined(plugins, OPENVPN_PLUGIN_ROUTE_UP))
6fbf66fa 1628 {
81d882d5
DS
1629 if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1630 {
1631 msg(M_WARN, "WARNING: route-up plugin call failed");
1632 }
6fbf66fa
JY
1633 }
1634
81d882d5 1635 if (options->route_script)
6fbf66fa 1636 {
81d882d5
DS
1637 struct argv argv = argv_new();
1638 setenv_str(es, "script_type", "route-up");
1639 argv_parse_cmd(&argv, options->route_script);
1640 openvpn_run_script(&argv, es, 0, "--route-up");
1641 argv_reset(&argv);
6fbf66fa
JY
1642 }
1643
445b192a 1644#ifdef _WIN32
81d882d5 1645 if (options->show_net_up)
6fbf66fa 1646 {
81d882d5
DS
1647 show_routes(M_INFO|M_NOPREFIX);
1648 show_adapters(M_INFO|M_NOPREFIX);
6fbf66fa 1649 }
81d882d5 1650 else if (check_debug_level(D_SHOW_NET))
6fbf66fa 1651 {
81d882d5
DS
1652 show_routes(D_SHOW_NET|M_NOPREFIX);
1653 show_adapters(D_SHOW_NET|M_NOPREFIX);
6fbf66fa
JY
1654 }
1655#endif
1656}
1657
6fbf66fa
JY
1658/*
1659 * initialize tun/tap device object
1660 */
1661static void
81d882d5 1662do_init_tun(struct context *c)
6fbf66fa 1663{
81d882d5
DS
1664 c->c1.tuntap = init_tun(c->options.dev,
1665 c->options.dev_type,
1666 c->options.topology,
1667 c->options.ifconfig_local,
1668 c->options.ifconfig_remote_netmask,
1669 c->options.ifconfig_ipv6_local,
1670 c->options.ifconfig_ipv6_netbits,
1671 c->options.ifconfig_ipv6_remote,
1672 c->c1.link_socket_addr.bind_local,
1673 c->c1.link_socket_addr.remote_list,
1674 !c->options.ifconfig_nowarn,
1675 c->c2.es);
1676
1677 init_tun_post(c->c1.tuntap,
1678 &c->c2.frame,
1679 &c->options.tuntap_options);
1680
1681 c->c1.tuntap_owned = true;
6fbf66fa
JY
1682}
1683
1684/*
1685 * Open tun/tap device, ifconfig, call up script, etc.
1686 */
1687
1688static bool
81d882d5 1689do_open_tun(struct context *c)
6fbf66fa 1690{
81d882d5
DS
1691 struct gc_arena gc = gc_new();
1692 bool ret = false;
6fbf66fa 1693
bd14d55d 1694#ifndef TARGET_ANDROID
81d882d5 1695 if (!c->c1.tuntap)
6fbf66fa 1696 {
bd14d55d
AS
1697#endif
1698
1699#ifdef TARGET_ANDROID
81d882d5
DS
1700 /* If we emulate persist-tun on android we still have to open a new tun and
1701 * then close the old */
1702 int oldtunfd = -1;
1703 if (c->c1.tuntap)
1704 {
1705 oldtunfd = c->c1.tuntap->fd;
da3f583f
AS
1706 free(c->c1.tuntap);
1707 c->c1.tuntap = NULL;
1708 c->c1.tuntap_owned = false;
81d882d5 1709 }
bd14d55d
AS
1710#endif
1711
81d882d5
DS
1712 /* initialize (but do not open) tun/tap object */
1713 do_init_tun(c);
6fbf66fa 1714
445b192a 1715#ifdef _WIN32
81d882d5
DS
1716 /* store (hide) interactive service handle in tuntap_options */
1717 c->c1.tuntap->options.msg_channel = c->options.msg_channel;
1718 msg(D_ROUTE, "interactive service msg_channel=%u", (unsigned int) c->options.msg_channel);
1719#endif
1720
1721 /* allocate route list structure */
1722 do_alloc_route_list(c);
1723
1724 /* parse and resolve the route option list */
1725 ASSERT(c->c2.link_socket);
1726 if (c->options.routes && c->c1.route_list)
1727 {
1728 do_init_route_list(&c->options, c->c1.route_list,
1729 &c->c2.link_socket->info, c->c2.es);
1730 }
1731 if (c->options.routes_ipv6 && c->c1.route_ipv6_list)
1732 {
1733 do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list,
1734 &c->c2.link_socket->info, c->c2.es);
1735 }
1736
1737 /* do ifconfig */
1738 if (!c->options.ifconfig_noexec
1739 && ifconfig_order() == IFCONFIG_BEFORE_TUN_OPEN)
1740 {
1741 /* guess actual tun/tap unit number that will be returned
1742 * by open_tun */
1743 const char *guess = guess_tuntap_dev(c->options.dev,
1744 c->options.dev_type,
1745 c->options.dev_node,
1746 &gc);
1747 do_ifconfig(c->c1.tuntap, guess, TUN_MTU_SIZE(&c->c2.frame), c->c2.es);
1748 }
1749
1750 /* possibly add routes */
1751 if (route_order() == ROUTE_BEFORE_TUN)
1752 {
94e6a2da 1753 /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
81d882d5
DS
1754 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
1755 c->c1.tuntap, c->plugins, c->c2.es);
1756 }
c058cbff 1757#ifdef TARGET_ANDROID
81d882d5
DS
1758 /* Store the old fd inside the fd so open_tun can use it */
1759 c->c1.tuntap->fd = oldtunfd;
1760#endif
1761 /* open the tun device */
1762 open_tun(c->options.dev, c->options.dev_type, c->options.dev_node,
1763 c->c1.tuntap);
1764
1765 /* set the hardware address */
1766 if (c->options.lladdr)
1767 {
1768 set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
1769 }
1770
1771 /* do ifconfig */
1772 if (!c->options.ifconfig_noexec
1773 && ifconfig_order() == IFCONFIG_AFTER_TUN_OPEN)
1774 {
1775 do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE(&c->c2.frame), c->c2.es);
1776 }
1777
1778 /* run the up script */
1779 run_up_down(c->options.up_script,
1780 c->plugins,
1781 OPENVPN_PLUGIN_UP,
1782 c->c1.tuntap->actual_name,
445b192a 1783#ifdef _WIN32
81d882d5
DS
1784 c->c1.tuntap->adapter_index,
1785#endif
1786 dev_type_string(c->options.dev, c->options.dev_type),
1787 TUN_MTU_SIZE(&c->c2.frame),
1788 EXPANDED_SIZE(&c->c2.frame),
1789 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1790 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1791 "init",
1792 NULL,
1793 "up",
1794 c->c2.es);
6fbf66fa 1795
445b192a 1796#if defined(_WIN32)
81d882d5
DS
1797 if (c->options.block_outside_dns)
1798 {
1799 dmsg(D_LOW, "Blocking outside DNS");
2282b1be 1800 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
81d882d5
DS
1801 {
1802 msg(M_FATAL, "Blocking DNS failed!");
1803 }
1804 }
38c85658
V
1805#endif
1806
81d882d5
DS
1807 /* possibly add routes */
1808 if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined))
1809 {
1810 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
1811 c->c1.tuntap, c->plugins, c->c2.es);
1812 }
6fbf66fa 1813
81d882d5
DS
1814 /*
1815 * Did tun/tap driver give us an MTU?
1816 */
1817 if (c->c1.tuntap->post_open_mtu)
1818 {
1819 frame_set_mtu_dynamic(&c->c2.frame,
1820 c->c1.tuntap->post_open_mtu,
1821 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
1822 }
6fbf66fa 1823
81d882d5
DS
1824 ret = true;
1825 static_context = c;
bd14d55d 1826#ifndef TARGET_ANDROID
81d882d5
DS
1827}
1828else
1829{
1830 msg(M_INFO, "Preserving previous TUN/TAP instance: %s",
1831 c->c1.tuntap->actual_name);
6fbf66fa 1832
81d882d5
DS
1833 /* explicitly set the ifconfig_* env vars */
1834 do_ifconfig_setenv(c->c1.tuntap, c->c2.es);
db950be8 1835
81d882d5
DS
1836 /* run the up script if user specified --up-restart */
1837 if (c->options.up_restart)
1838 {
1839 run_up_down(c->options.up_script,
1840 c->plugins,
1841 OPENVPN_PLUGIN_UP,
1842 c->c1.tuntap->actual_name,
445b192a 1843#ifdef _WIN32
81d882d5
DS
1844 c->c1.tuntap->adapter_index,
1845#endif
1846 dev_type_string(c->options.dev, c->options.dev_type),
1847 TUN_MTU_SIZE(&c->c2.frame),
1848 EXPANDED_SIZE(&c->c2.frame),
1849 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1850 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1851 "restart",
1852 NULL,
1853 "up",
1854 c->c2.es);
1855 }
445b192a 1856#if defined(_WIN32)
81d882d5
DS
1857 if (c->options.block_outside_dns)
1858 {
1859 dmsg(D_LOW, "Blocking outside DNS");
1860 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
451d2177 1861 {
81d882d5 1862 msg(M_FATAL, "Blocking DNS failed!");
451d2177 1863 }
6fbf66fa 1864 }
bd14d55d 1865#endif
81d882d5
DS
1866
1867}
1868#endif /* ifndef TARGET_ANDROID */
1869 gc_free(&gc);
1870 return ret;
6fbf66fa
JY
1871}
1872
1873/*
1874 * Close TUN/TAP device
1875 */
1876
1877static void
81d882d5 1878do_close_tun_simple(struct context *c)
6fbf66fa 1879{
81d882d5 1880 msg(D_CLOSE, "Closing TUN/TAP interface");
0bea472c
AQ
1881 if (c->c1.tuntap)
1882 {
1883 close_tun(c->c1.tuntap);
1884 c->c1.tuntap = NULL;
1885 }
81d882d5 1886 c->c1.tuntap_owned = false;
6fbf66fa 1887#if P2MP
81d882d5 1888 CLEAR(c->c1.pulled_options_digest_save);
6fbf66fa
JY
1889#endif
1890}
1891
1892static void
81d882d5 1893do_close_tun(struct context *c, bool force)
6fbf66fa 1894{
81d882d5
DS
1895 struct gc_arena gc = gc_new();
1896 if (c->c1.tuntap && c->c1.tuntap_owned)
6fbf66fa 1897 {
81d882d5 1898 const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc);
445b192a 1899#ifdef _WIN32
81d882d5 1900 DWORD adapter_index = c->c1.tuntap->adapter_index;
9dff2c1f 1901#endif
81d882d5
DS
1902 const in_addr_t local = c->c1.tuntap->local;
1903 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
6fbf66fa 1904
81d882d5
DS
1905 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
1906 {
1907 static_context = NULL;
0c9eb1d3 1908
6fbf66fa 1909#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1910 /* tell management layer we are about to close the TUN/TAP device */
1911 if (management)
1912 {
1913 management_pre_tunnel_close(management);
1914 management_up_down(management, "DOWN", c->c2.es);
1915 }
1916#endif
1917
1918 /* delete any routes we added */
1919 if (c->c1.route_list || c->c1.route_ipv6_list)
1920 {
1921 run_up_down(c->options.route_predown_script,
1922 c->plugins,
1923 OPENVPN_PLUGIN_ROUTE_PREDOWN,
1924 tuntap_actual,
445b192a 1925#ifdef _WIN32
81d882d5
DS
1926 adapter_index,
1927#endif
1928 NULL,
1929 TUN_MTU_SIZE(&c->c2.frame),
1930 EXPANDED_SIZE(&c->c2.frame),
1931 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1932 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1933 "init",
1934 signal_description(c->sig->signal_received,
415421c2 1935 c->sig->signal_text),
81d882d5
DS
1936 "route-pre-down",
1937 c->c2.es);
415421c2 1938
81d882d5
DS
1939 delete_routes(c->c1.route_list, c->c1.route_ipv6_list,
1940 c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options), c->c2.es);
415421c2 1941 }
6fbf66fa 1942
81d882d5
DS
1943 /* actually close tun/tap device based on --down-pre flag */
1944 if (!c->options.down_pre)
1945 {
1946 do_close_tun_simple(c);
1947 }
6fbf66fa 1948
81d882d5
DS
1949 /* Run the down script -- note that it will run at reduced
1950 * privilege if, for example, "--user nobody" was used. */
1951 run_up_down(c->options.down_script,
1952 c->plugins,
1953 OPENVPN_PLUGIN_DOWN,
1954 tuntap_actual,
445b192a 1955#ifdef _WIN32
81d882d5
DS
1956 adapter_index,
1957#endif
1958 NULL,
1959 TUN_MTU_SIZE(&c->c2.frame),
1960 EXPANDED_SIZE(&c->c2.frame),
1961 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1962 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1963 "init",
1964 signal_description(c->sig->signal_received,
1965 c->sig->signal_text),
1966 "down",
1967 c->c2.es);
6fbf66fa 1968
445b192a 1969#if defined(_WIN32)
38c85658
V
1970 if (c->options.block_outside_dns)
1971 {
27aa8728 1972 if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
81d882d5
DS
1973 {
1974 msg(M_FATAL, "Uninitialising WFP failed!");
1975 }
38c85658
V
1976 }
1977#endif
1978
81d882d5
DS
1979 /* actually close tun/tap device based on --down-pre flag */
1980 if (c->options.down_pre)
1981 {
1982 do_close_tun_simple(c);
1983 }
1984 }
1985 else
1986 {
1987 /* run the down script on this restart if --up-restart was specified */
1988 if (c->options.up_restart)
1989 {
1990 run_up_down(c->options.down_script,
1991 c->plugins,
1992 OPENVPN_PLUGIN_DOWN,
1993 tuntap_actual,
445b192a 1994#ifdef _WIN32
81d882d5
DS
1995 adapter_index,
1996#endif
1997 NULL,
1998 TUN_MTU_SIZE(&c->c2.frame),
1999 EXPANDED_SIZE(&c->c2.frame),
2000 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2001 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2002 "restart",
2003 signal_description(c->sig->signal_received,
2004 c->sig->signal_text),
2005 "down",
2006 c->c2.es);
2007 }
451d2177 2008
445b192a 2009#if defined(_WIN32)
81d882d5 2010 if (c->options.block_outside_dns)
451d2177 2011 {
27aa8728 2012 if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
81d882d5
DS
2013 {
2014 msg(M_FATAL, "Uninitialising WFP failed!");
2015 }
451d2177
SN
2016 }
2017#endif
2018
81d882d5 2019 }
6fbf66fa 2020 }
81d882d5 2021 gc_free(&gc);
6fbf66fa
JY
2022}
2023
0c9eb1d3 2024void
e2a0cad4 2025tun_abort(void)
0c9eb1d3 2026{
81d882d5
DS
2027 struct context *c = static_context;
2028 if (c)
0c9eb1d3 2029 {
81d882d5
DS
2030 static_context = NULL;
2031 do_close_tun(c, true);
0c9eb1d3
JY
2032 }
2033}
2034
6fbf66fa
JY
2035/*
2036 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
2037 */
2038
827de237
SK
2039#if P2MP
2040/**
2041 * Helper for do_up(). Take two option hashes and return true if they are not
2042 * equal, or either one is all-zeroes.
2043 */
2044static bool
5b48e8c9
SK
2045options_hash_changed_or_zero(const struct sha256_digest *a,
2046 const struct sha256_digest *b)
827de237 2047{
5b48e8c9
SK
2048 const struct sha256_digest zero = {{0}};
2049 return memcmp(a, b, sizeof(struct sha256_digest))
2050 || !memcmp(a, &zero, sizeof(struct sha256_digest));
827de237
SK
2051}
2052#endif /* P2MP */
2053
d728ebed 2054bool
81d882d5 2055do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
6fbf66fa 2056{
81d882d5 2057 if (!c->c2.do_up_ran)
6fbf66fa 2058 {
81d882d5 2059 reset_coarse_timers(c);
6fbf66fa 2060
bd230079 2061 if (pulled_options)
81d882d5
DS
2062 {
2063 if (!do_deferred_options(c, option_types_found))
2064 {
2065 msg(D_PUSH_ERRORS, "ERROR: Failed to apply push options");
2066 return false;
2067 }
2068 }
6fbf66fa 2069
81d882d5
DS
2070 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
2071 if (c->options.up_delay || PULL_DEFINED(&c->options))
2072 {
2073 c->c2.did_open_tun = do_open_tun(c);
2074 update_time();
6fbf66fa
JY
2075
2076#if P2MP
81d882d5
DS
2077 /*
2078 * Was tun interface object persisted from previous restart iteration,
2079 * and if so did pulled options string change from previous iteration?
2080 */
2081 if (!c->c2.did_open_tun
2082 && PULL_DEFINED(&c->options)
2083 && c->c1.tuntap
2084 && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save,
2085 &c->c2.pulled_options_digest))
2086 {
2087 /* if so, close tun, delete routes, then reinitialize tun and add routes */
2088 msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
2089 do_close_tun(c, true);
45b2af9c 2090 management_sleep(1);
81d882d5
DS
2091 c->c2.did_open_tun = do_open_tun(c);
2092 update_time();
2093 }
2094#endif
2095 }
2096
2097 if (c->c2.did_open_tun)
2098 {
6fbf66fa 2099#if P2MP
81d882d5
DS
2100 c->c1.pulled_options_digest_save = c->c2.pulled_options_digest;
2101#endif
2102
2103 /* if --route-delay was specified, start timer */
2104 if ((route_order() == ROUTE_AFTER_TUN) && c->options.route_delay_defined)
2105 {
2106 event_timeout_init(&c->c2.route_wakeup, c->options.route_delay, now);
2107 event_timeout_init(&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
2108 if (c->c1.tuntap)
2109 {
2110 tun_standby_init(c->c1.tuntap);
2111 }
2112 }
2113 else
2114 {
2115 initialization_sequence_completed(c, 0); /* client/p2p --route-delay undefined */
2116 }
2117 }
2118 else if (c->options.mode == MODE_POINT_TO_POINT)
2119 {
2120 initialization_sequence_completed(c, 0); /* client/p2p restart with --persist-tun */
2121 }
2122
2123 c->c2.do_up_ran = true;
2124 }
2125 return true;
6fbf66fa
JY
2126}
2127
2128/*
2129 * These are the option categories which will be accepted by pull.
2130 */
2131unsigned int
81d882d5
DS
2132pull_permission_mask(const struct context *c)
2133{
2134 unsigned int flags =
2135 OPT_P_UP
2136 | OPT_P_ROUTE_EXTRAS
2137 | OPT_P_SOCKBUF
2138 | OPT_P_SOCKFLAGS
2139 | OPT_P_SETENV
2140 | OPT_P_SHAPER
2141 | OPT_P_TIMER
2142 | OPT_P_COMP
2143 | OPT_P_PERSIST
2144 | OPT_P_MESSAGES
2145 | OPT_P_EXPLICIT_NOTIFY
2146 | OPT_P_ECHO
2147 | OPT_P_PULL_MODE
2148 | OPT_P_PEER_ID;
2149
2150 if (!c->options.route_nopull)
2151 {
2152 flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);
2153 }
3c7f2f55 2154
81d882d5
DS
2155 if (c->options.ncp_enabled)
2156 {
2157 flags |= OPT_P_NCP;
2158 }
d728ebed 2159
81d882d5 2160 return flags;
6fbf66fa
JY
2161}
2162
2163/*
2164 * Handle non-tun-related pulled options.
2165 */
d728ebed 2166bool
81d882d5 2167do_deferred_options(struct context *c, const unsigned int found)
6fbf66fa 2168{
81d882d5 2169 if (found & OPT_P_MESSAGES)
6fbf66fa 2170 {
81d882d5
DS
2171 init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_2);
2172 msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
6fbf66fa 2173 }
81d882d5 2174 if (found & OPT_P_TIMER)
6fbf66fa 2175 {
81d882d5
DS
2176 do_init_timers(c, true);
2177 msg(D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
6fbf66fa
JY
2178 }
2179
2180#ifdef ENABLE_OCC
81d882d5 2181 if (found & OPT_P_EXPLICIT_NOTIFY)
6fbf66fa 2182 {
81d882d5
DS
2183 if (!proto_is_udp(c->options.ce.proto) && c->options.ce.explicit_exit_notification)
2184 {
2185 msg(D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
2186 c->options.ce.explicit_exit_notification = 0;
2187 }
2188 else
2189 {
2190 msg(D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
2191 }
6fbf66fa
JY
2192 }
2193#endif
2194
38d96bd7 2195#ifdef USE_COMP
81d882d5 2196 if (found & OPT_P_COMP)
537073fd 2197 {
81d882d5
DS
2198 msg(D_PUSH, "OPTIONS IMPORT: compression parms modified");
2199 comp_uninit(c->c2.comp_context);
2200 c->c2.comp_context = comp_init(&c->options.comp);
537073fd
JY
2201 }
2202#endif
2203
81d882d5 2204 if (found & OPT_P_SHAPER)
6fbf66fa 2205 {
81d882d5
DS
2206 msg(D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
2207 do_init_traffic_shaper(c);
6fbf66fa
JY
2208 }
2209
81d882d5 2210 if (found & OPT_P_SOCKBUF)
00d39170 2211 {
81d882d5
DS
2212 msg(D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
2213 link_socket_update_buffer_sizes(c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
00d39170
JY
2214 }
2215
81d882d5 2216 if (found & OPT_P_SOCKFLAGS)
00d39170 2217 {
81d882d5
DS
2218 msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
2219 link_socket_update_flags(c->c2.link_socket, c->options.sockflags);
00d39170
JY
2220 }
2221
81d882d5
DS
2222 if (found & OPT_P_PERSIST)
2223 {
2224 msg(D_PUSH, "OPTIONS IMPORT: --persist options modified");
2225 }
2226 if (found & OPT_P_UP)
2227 {
2228 msg(D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
2229 }
2230 if (found & OPT_P_ROUTE)
2231 {
2232 msg(D_PUSH, "OPTIONS IMPORT: route options modified");
2233 }
2234 if (found & OPT_P_ROUTE_EXTRAS)
2235 {
2236 msg(D_PUSH, "OPTIONS IMPORT: route-related options modified");
2237 }
2238 if (found & OPT_P_IPWIN32)
2239 {
2240 msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
2241 }
2242 if (found & OPT_P_SETENV)
2243 {
2244 msg(D_PUSH, "OPTIONS IMPORT: environment modified");
2245 }
65eedc35 2246
81d882d5
DS
2247 if (found & OPT_P_PEER_ID)
2248 {
2249 msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
2250 c->c2.tls_multi->use_peer_id = true;
2251 c->c2.tls_multi->peer_id = c->options.peer_id;
2252 frame_add_to_extra_frame(&c->c2.frame, +3); /* peer-id overhead */
2253 if (!c->options.ce.link_mtu_defined)
2254 {
2255 frame_add_to_link_mtu(&c->c2.frame, +3);
2256 msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
2257 EXPANDED_SIZE(&c->c2.frame));
2258 }
2259 else
2260 {
2261 msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
2262 " fixed by config - reducing tun-mtu to %d, expect"
2263 " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
2264 }
2265 }
2266
2267 /* process (potentially pushed) crypto options */
2268 if (c->options.pull)
2269 {
2270 struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2271 if (found & OPT_P_NCP)
2272 {
2273 msg(D_PUSH, "OPTIONS IMPORT: data channel crypto options modified");
2274 }
2275 else if (c->options.ncp_enabled)
2276 {
2277 tls_poor_mans_ncp(&c->options, c->c2.tls_multi->remote_ciphername);
2278 }
2279 /* Do not regenerate keys if server sends an extra push reply */
2280 if (!session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized
2281 && !tls_session_update_crypto_params(session, &c->options, &c->c2.frame))
2282 {
2283 msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options");
2284 return false;
2285 }
2286 }
c7ca9133 2287
81d882d5 2288 return true;
6fbf66fa
JY
2289}
2290
2291/*
396d30c2
AS
2292 * Possible hold on initialization, holdtime is the
2293 * time OpenVPN would wait without management
6fbf66fa
JY
2294 */
2295static bool
81d882d5 2296do_hold(int holdtime)
6fbf66fa
JY
2297{
2298#ifdef ENABLE_MANAGEMENT
81d882d5 2299 if (management)
6fbf66fa 2300 {
81d882d5
DS
2301 /* block until management hold is released */
2302 if (management_hold(management, holdtime))
2303 {
2304 return true;
2305 }
6fbf66fa
JY
2306 }
2307#endif
81d882d5 2308 return false;
6fbf66fa
JY
2309}
2310
2311/*
2312 * Sleep before restart.
2313 */
2314static void
81d882d5 2315socket_restart_pause(struct context *c)
6fbf66fa 2316{
81d882d5
DS
2317 int sec = 2;
2318 int backoff = 0;
6fbf66fa 2319
81d882d5 2320 switch (c->options.ce.proto)
6fbf66fa 2321 {
81d882d5
DS
2322 case PROTO_TCP_SERVER:
2323 sec = 1;
2324 break;
2325
2326 case PROTO_UDP:
2327 case PROTO_TCP_CLIENT:
2328 sec = c->options.ce.connect_retry_seconds;
2329 break;
6fbf66fa
JY
2330 }
2331
2332#ifdef ENABLE_DEBUG
81d882d5
DS
2333 if (GREMLIN_CONNECTION_FLOOD_LEVEL(c->options.gremlin))
2334 {
2335 sec = 0;
2336 }
6fbf66fa
JY
2337#endif
2338
2339#if P2MP
81d882d5
DS
2340 if (auth_retry_get() == AR_NOINTERACT)
2341 {
2342 sec = 10;
2343 }
6fbf66fa
JY
2344#endif
2345
81d882d5
DS
2346 /* Slow down reconnection after 5 retries per remote -- for tcp only in client mode */
2347 if (c->options.ce.proto != PROTO_TCP_SERVER)
5d429efd 2348 {
81d882d5
DS
2349 backoff = (c->options.unsuccessful_attempts / c->options.connection_list->len) - 4;
2350 if (backoff > 0)
5d429efd 2351 {
81d882d5
DS
2352 /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */
2353 sec = max_int(sec, 1) << min_int(backoff, 15);
5d429efd
SN
2354 }
2355
81d882d5
DS
2356 if (sec > c->options.ce.connect_retry_seconds_max)
2357 {
2358 sec = c->options.ce.connect_retry_seconds_max;
2359 }
5d429efd
SN
2360 }
2361
81d882d5
DS
2362 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
2363 {
2364 sec = c->persist.restart_sleep_seconds;
2365 }
2366 else if (c->persist.restart_sleep_seconds == -1)
2367 {
2368 sec = 0;
2369 }
2370 c->persist.restart_sleep_seconds = 0;
a9c802b2 2371
81d882d5
DS
2372 /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
2373 if (do_hold(sec))
2374 {
2375 sec = 0;
2376 }
6fbf66fa 2377
81d882d5 2378 if (sec)
6fbf66fa 2379 {
81d882d5 2380 msg(D_RESTART, "Restart pause, %d second(s)", sec);
45b2af9c 2381 management_sleep(sec);
6fbf66fa
JY
2382 }
2383}
2384
2385/*
2386 * Do a possible pause on context_2 initialization.
2387 */
2388static void
81d882d5 2389do_startup_pause(struct context *c)
6fbf66fa 2390{
81d882d5
DS
2391 if (!c->first_time)
2392 {
2393 socket_restart_pause(c);
2394 }
2395 else
2396 {
2397 do_hold(0); /* do management hold on first context initialization */
2398 }
6fbf66fa
JY
2399}
2400
2401/*
2402 * Finalize MTU parameters based on command line or config file options.
2403 */
2404static void
81d882d5 2405frame_finalize_options(struct context *c, const struct options *o)
6fbf66fa 2406{
81d882d5
DS
2407 if (!o)
2408 {
2409 o = &c->options;
2410 }
6fbf66fa 2411
81d882d5
DS
2412 /*
2413 * Set adjustment factor for buffer alignment when no
2414 * cipher is used.
2415 */
2416 if (!CIPHER_ENABLED(c))
6fbf66fa 2417 {
81d882d5
DS
2418 frame_align_to_extra_frame(&c->c2.frame);
2419 frame_or_align_flags(&c->c2.frame,
2420 FRAME_HEADROOM_MARKER_FRAGMENT
2421 |FRAME_HEADROOM_MARKER_READ_LINK
2422 |FRAME_HEADROOM_MARKER_READ_STREAM);
6fbf66fa 2423 }
81d882d5
DS
2424
2425 frame_add_to_extra_buffer(&c->c2.frame, PAYLOAD_ALIGN);
2426 frame_finalize(&c->c2.frame,
2427 o->ce.link_mtu_defined,
2428 o->ce.link_mtu,
2429 o->ce.tun_mtu_defined,
2430 o->ce.tun_mtu);
6fbf66fa
JY
2431}
2432
2433/*
2434 * Free a key schedule, including OpenSSL components.
2435 */
2436static void
81d882d5 2437key_schedule_free(struct key_schedule *ks, bool free_ssl_ctx)
6fbf66fa 2438{
81d882d5
DS
2439 free_key_ctx_bi(&ks->static_key);
2440 if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
6fbf66fa 2441 {
81d882d5 2442 tls_ctx_free(&ks->ssl_ctx);
6fbf66fa 2443 }
81d882d5 2444 CLEAR(*ks);
6fbf66fa
JY
2445}
2446
6fbf66fa 2447static void
81d882d5 2448init_crypto_pre(struct context *c, const unsigned int flags)
6fbf66fa 2449{
81d882d5
DS
2450 if (c->options.engine)
2451 {
2452 crypto_init_lib_engine(c->options.engine);
2453 }
6fbf66fa 2454
81d882d5 2455 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
6fbf66fa 2456 {
81d882d5
DS
2457 /* load a persisted packet-id for cross-session replay-protection */
2458 if (c->options.packet_id_file)
2459 {
2460 packet_id_persist_load(&c->c1.pid_persist, c->options.packet_id_file);
2461 }
6fbf66fa
JY
2462 }
2463
0f25d296 2464#ifdef ENABLE_PREDICTION_RESISTANCE
81d882d5
DS
2465 if (c->options.use_prediction_resistance)
2466 {
2467 rand_ctx_enable_prediction_resistance();
2468 }
0f25d296
AJ
2469#endif
2470
6fbf66fa
JY
2471}
2472
2473/*
2474 * Static Key Mode (using a pre-shared key)
2475 */
2476static void
81d882d5 2477do_init_crypto_static(struct context *c, const unsigned int flags)
6fbf66fa 2478{
81d882d5
DS
2479 const struct options *options = &c->options;
2480 ASSERT(options->shared_secret_file);
6fbf66fa 2481
81d882d5 2482 init_crypto_pre(c, flags);
2d9c6d20 2483
81d882d5 2484 /* Initialize flags */
81d882d5 2485 if (c->options.mute_replay_warnings)
6fbf66fa 2486 {
81d882d5 2487 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
6fbf66fa
JY
2488 }
2489
81d882d5
DS
2490 /* Initialize packet ID tracking */
2491 if (options->replay)
6fbf66fa 2492 {
81d882d5
DS
2493 packet_id_init(&c->c2.crypto_options.packet_id,
2494 options->replay_window,
2495 options->replay_time,
2496 "STATIC", 0);
2497 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
2498 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
2499 packet_id_persist_load_obj(&c->c1.pid_persist,
2500 &c->c2.crypto_options.packet_id);
2501 }
6fbf66fa 2502
81d882d5
DS
2503 if (!key_ctx_bi_defined(&c->c1.ks.static_key))
2504 {
2505 /* Get cipher & hash algorithms */
2506 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2507 options->keysize, options->test_crypto, true);
2508
2509 /* Read cipher and hmac keys from shared secret file */
2510 crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key,
2511 options->shared_secret_file,
2512 options->shared_secret_file_inline,
2513 options->key_direction, "Static Key Encryption",
2514 "secret");
6fbf66fa 2515 }
81d882d5 2516 else
6fbf66fa 2517 {
81d882d5 2518 msg(M_INFO, "Re-using pre-shared static key");
6fbf66fa
JY
2519 }
2520
81d882d5
DS
2521 /* Get key schedule */
2522 c->c2.crypto_options.key_ctx_bi = c->c1.ks.static_key;
6fbf66fa 2523
81d882d5 2524 /* Compute MTU parameters */
ef910e3e
SK
2525 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
2526 options->replay, true);
6fbf66fa 2527
ef910e3e
SK
2528 /* Sanity check on sequence number, and cipher mode options */
2529 check_replay_consistency(&c->c1.ks.key_type, options->replay);
6fbf66fa
JY
2530}
2531
5817b49b
AQ
2532/*
2533 * Initialize the tls-auth/crypt key context
2534 */
2535static void
2536do_init_tls_wrap_key(struct context *c)
2537{
2538 const struct options *options = &c->options;
2539
2540 /* TLS handshake authentication (--tls-auth) */
57d6f103 2541 if (options->ce.tls_auth_file)
5817b49b
AQ
2542 {
2543 /* Initialize key_type for tls-auth with auth only */
2544 CLEAR(c->c1.ks.tls_auth_key_type);
2545 if (!streq(options->authname, "none"))
2546 {
2547 c->c1.ks.tls_auth_key_type.digest = md_kt_get(options->authname);
2548 c->c1.ks.tls_auth_key_type.hmac_length =
2549 md_kt_size(c->c1.ks.tls_auth_key_type.digest);
2550 }
2551 else
2552 {
2553 msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth "
2554 "algorithm specified ('%s')", options->authname);
2555 }
2556
2557 crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type,
2558 &c->c1.ks.tls_wrap_key,
57d6f103
AQ
2559 options->ce.tls_auth_file,
2560 options->ce.tls_auth_file_inline,
2561 options->ce.key_direction,
5817b49b
AQ
2562 "Control Channel Authentication", "tls-auth");
2563 }
2564
2565 /* TLS handshake encryption+authentication (--tls-crypt) */
57d6f103 2566 if (options->ce.tls_crypt_file)
5817b49b
AQ
2567 {
2568 tls_crypt_init_key(&c->c1.ks.tls_wrap_key,
57d6f103
AQ
2569 options->ce.tls_crypt_file,
2570 options->ce.tls_crypt_inline, options->tls_server);
5817b49b
AQ
2571 }
2572}
2573
6fbf66fa
JY
2574/*
2575 * Initialize the persistent component of OpenVPN's TLS mode,
2576 * which is preserved across SIGUSR1 resets.
2577 */
2578static void
81d882d5 2579do_init_crypto_tls_c1(struct context *c)
6fbf66fa 2580{
81d882d5 2581 const struct options *options = &c->options;
6fbf66fa 2582
81d882d5 2583 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
6fbf66fa 2584 {
81d882d5
DS
2585 /*
2586 * Initialize the OpenSSL library's global
2587 * SSL context.
2588 */
2589 init_ssl(options, &(c->c1.ks.ssl_ctx));
2590 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
2591 {
6fbf66fa 2592#if P2MP
81d882d5
DS
2593 switch (auth_retry_get())
2594 {
2595 case AR_NONE:
2596 msg(M_FATAL, "Error: private key password verification failed");
2597 break;
2598
2599 case AR_INTERACT:
2600 ssl_purge_auth(false);
2601
2602 case AR_NOINTERACT:
2603 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
2604 break;
2605
2606 default:
2607 ASSERT(0);
2608 }
2609 c->sig->signal_text = "private-key-password-failure";
2610 return;
2611#else /* if P2MP */
2612 msg(M_FATAL, "Error: private key password verification failed");
2613#endif
2614 }
2615
2616 /* Get cipher & hash algorithms */
2617 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2618 options->keysize, true, true);
2619
2620 /* Initialize PRNG with config-specified digest */
2621 prng_init(options->prng_hash, options->prng_nonce_secret_len);
2622
5817b49b
AQ
2623 /* initialize tls-auth/crypt key */
2624 do_init_tls_wrap_key(c);
81d882d5 2625
1f4309ae 2626#if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
81d882d5
DS
2627 if (options->priv_key_file_inline)
2628 {
2629 string_clear(c->options.priv_key_file_inline);
2630 c->options.priv_key_file_inline = NULL;
2631 }
d40f2b20 2632#endif
6fbf66fa 2633 }
81d882d5 2634 else
6fbf66fa 2635 {
81d882d5 2636 msg(D_INIT_MEDIUM, "Re-using SSL/TLS context");
129d2924 2637
5817b49b
AQ
2638 /*
2639 * tls-auth/crypt key can be configured per connection block, therefore
2640 * we must reload it as it may have changed
2641 */
2642 do_init_tls_wrap_key(c);
6fbf66fa
JY
2643 }
2644}
2645
2646static void
81d882d5 2647do_init_crypto_tls(struct context *c, const unsigned int flags)
6fbf66fa 2648{
81d882d5
DS
2649 const struct options *options = &c->options;
2650 struct tls_options to;
2651 bool packet_id_long_form;
6fbf66fa 2652
81d882d5
DS
2653 ASSERT(options->tls_server || options->tls_client);
2654 ASSERT(!options->test_crypto);
6fbf66fa 2655
81d882d5 2656 init_crypto_pre(c, flags);
6fbf66fa 2657
81d882d5
DS
2658 /* Make sure we are either a TLS client or server but not both */
2659 ASSERT(options->tls_server == !options->tls_client);
6fbf66fa 2660
81d882d5
DS
2661 /* initialize persistent component */
2662 do_init_crypto_tls_c1(c);
2663 if (IS_SIG(c))
2664 {
2665 return;
2666 }
2667
ef910e3e
SK
2668 /* Sanity check on sequence number, and cipher mode options */
2669 check_replay_consistency(&c->c1.ks.key_type, options->replay);
81d882d5
DS
2670
2671 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
2672 packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher);
2673
2674 /* Compute MTU parameters (postpone if we push/pull options) */
2675 if (c->options.pull || c->options.mode == MODE_SERVER)
2676 {
2677 /* Account for worst-case crypto overhead before allocating buffers */
2678 frame_add_to_extra_frame(&c->c2.frame, crypto_max_overhead());
2679 }
2680 else
2681 {
2682 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
ef910e3e 2683 options->replay, packet_id_long_form);
81d882d5
DS
2684 }
2685 tls_adjust_frame_parameters(&c->c2.frame);
6fbf66fa 2686
81d882d5
DS
2687 /* Set all command-line TLS-related options */
2688 CLEAR(to);
2689
81d882d5
DS
2690 if (options->mute_replay_warnings)
2691 {
2692 to.crypto_flags |= CO_MUTE_REPLAY_WARNINGS;
2693 }
2694
2695 to.crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
2696 if (packet_id_long_form)
2697 {
2698 to.crypto_flags |= CO_PACKET_ID_LONG_FORM;
2699 }
2700
2701 to.ssl_ctx = c->c1.ks.ssl_ctx;
2702 to.key_type = c->c1.ks.key_type;
2703 to.server = options->tls_server;
2704 to.key_method = options->key_method;
2705 to.replay = options->replay;
2706 to.replay_window = options->replay_window;
2707 to.replay_time = options->replay_time;
2708 to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto);
2709 to.config_ciphername = c->c1.ciphername;
2710 to.config_authname = c->c1.authname;
2711 to.ncp_enabled = options->ncp_enabled;
2712 to.transition_window = options->transition_window;
2713 to.handshake_window = options->handshake_window;
2714 to.packet_timeout = options->tls_timeout;
2715 to.renegotiate_bytes = options->renegotiate_bytes;
2716 to.renegotiate_packets = options->renegotiate_packets;
dd996463
SM
2717 if (options->renegotiate_seconds_min < 0)
2718 {
2719 /* Add 10% jitter to reneg-sec by default (server side only) */
2720 int auto_jitter = options->mode != MODE_SERVER ? 0 :
2721 get_random() % max_int(options->renegotiate_seconds / 10, 1);
2722 to.renegotiate_seconds = options->renegotiate_seconds - auto_jitter;
2723 }
2724 else
2725 {
2726 /* Add user-specified jitter to reneg-sec */
2727 to.renegotiate_seconds = options->renegotiate_seconds -
2728 (get_random() % max_int(options->renegotiate_seconds
2729 - options->renegotiate_seconds_min, 1));
2730 }
81d882d5
DS
2731 to.single_session = options->single_session;
2732 to.mode = options->mode;
2733 to.pull = options->pull;
81d882d5
DS
2734 if (options->push_peer_info) /* all there is */
2735 {
2736 to.push_peer_info_detail = 2;
2737 }
2738 else if (options->pull) /* pull clients send some details */
2739 {
2740 to.push_peer_info_detail = 1;
2741 }
2742 else /* default: no peer-info at all */
2743 {
2744 to.push_peer_info_detail = 0;
2745 }
6fbf66fa 2746
81d882d5
DS
2747 /* should we not xmit any packets until we get an initial
2748 * response from client? */
2749 if (to.server && options->ce.proto == PROTO_TCP_SERVER)
2750 {
2751 to.xmit_hold = true;
2752 }
6add6b2f 2753
6fbf66fa 2754#ifdef ENABLE_OCC
81d882d5
DS
2755 to.disable_occ = !options->occ;
2756#endif
2757
2758 to.verify_command = options->tls_verify;
2759 to.verify_export_cert = options->tls_export_cert;
2760 to.verify_x509_type = (options->verify_x509_type & 0xff);
2761 to.verify_x509_name = options->verify_x509_name;
2762 to.crl_file = options->crl_file;
2763 to.crl_file_inline = options->crl_file_inline;
2764 to.ssl_flags = options->ssl_flags;
2765 to.ns_cert_type = options->ns_cert_type;
2766 memmove(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku));
2767 to.remote_cert_eku = options->remote_cert_eku;
2768 to.verify_hash = options->verify_hash;
2193d7c0 2769 to.verify_hash_algo = options->verify_hash_algo;
19dd3ef1 2770#ifdef ENABLE_X509ALTUSERNAME
81d882d5 2771 to.x509_username_field = (char *) options->x509_username_field;
19dd3ef1 2772#else
81d882d5 2773 to.x509_username_field = X509_USERNAME_FIELD_DEFAULT;
19dd3ef1 2774#endif
81d882d5 2775 to.es = c->c2.es;
6fbf66fa
JY
2776
2777#ifdef ENABLE_DEBUG
81d882d5 2778 to.gremlin = c->options.gremlin;
6fbf66fa
JY
2779#endif
2780
81d882d5 2781 to.plugins = c->plugins;
6fbf66fa 2782
90efcacb 2783#ifdef MANAGEMENT_DEF_AUTH
81d882d5 2784 to.mda_context = &c->c2.mda_context;
90efcacb
JY
2785#endif
2786
6fbf66fa 2787#if P2MP_SERVER
81d882d5
DS
2788 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
2789 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
2790 to.tmp_dir = options->tmp_dir;
2791 if (options->ccd_exclusive)
2792 {
2793 to.client_config_dir_exclusive = options->client_config_dir;
2794 }
2795 to.auth_user_pass_file = options->auth_user_pass_file;
2796 to.auth_token_generate = options->auth_token_generate;
2797 to.auth_token_lifetime = options->auth_token_lifetime;
6fbf66fa
JY
2798#endif
2799
81d882d5 2800 to.x509_track = options->x509_track;
9356bae8 2801
16d909e2 2802#if P2MP
eab3e22f 2803#ifdef ENABLE_CLIENT_CR
81d882d5 2804 to.sci = &options->sc_info;
16d909e2 2805#endif
eab3e22f
JY
2806#endif
2807
38d96bd7 2808#ifdef USE_COMP
81d882d5 2809 to.comp_options = options->comp;
38d96bd7
JY
2810#endif
2811
685e486e 2812#if defined(ENABLE_CRYPTO_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10001000
81d882d5 2813 if (options->keying_material_exporter_label)
685e486e 2814 {
81d882d5
DS
2815 to.ekm_size = options->keying_material_exporter_length;
2816 if (to.ekm_size < 16 || to.ekm_size > 4095)
2817 {
2818 to.ekm_size = 0;
2819 }
685e486e 2820
81d882d5
DS
2821 to.ekm_label = options->keying_material_exporter_label;
2822 to.ekm_label_size = strlen(to.ekm_label);
685e486e 2823 }
81d882d5 2824 else
685e486e 2825 {
81d882d5 2826 to.ekm_size = 0;
685e486e
DK
2827 }
2828#endif
2829
81d882d5 2830 /* TLS handshake authentication (--tls-auth) */
57d6f103 2831 if (options->ce.tls_auth_file)
6fbf66fa 2832 {
81d882d5
DS
2833 to.tls_wrap.mode = TLS_WRAP_AUTH;
2834 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2835 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2836 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
ef910e3e
SK
2837 crypto_adjust_frame_parameters(&to.frame, &c->c1.ks.tls_auth_key_type,
2838 true, true);
6fbf66fa
JY
2839 }
2840
81d882d5 2841 /* TLS handshake encryption (--tls-crypt) */
57d6f103 2842 if (options->ce.tls_crypt_file)
c6e24fa3 2843 {
81d882d5
DS
2844 to.tls_wrap.mode = TLS_WRAP_CRYPT;
2845 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2846 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2847 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
2848 tls_crypt_adjust_frame_parameters(&to.frame);
c6e24fa3
SK
2849 }
2850
81d882d5
DS
2851 /* If we are running over TCP, allow for
2852 * length prefix */
2853 socket_adjust_frame_parameters(&to.frame, options->ce.proto);
6fbf66fa 2854
81d882d5
DS
2855 /*
2856 * Initialize OpenVPN's master TLS-mode object.
2857 */
2858 if (flags & CF_INIT_TLS_MULTI)
2859 {
2860 c->c2.tls_multi = tls_multi_init(&to);
2861 }
6fbf66fa 2862
81d882d5
DS
2863 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
2864 {
2865 c->c2.tls_auth_standalone = tls_auth_standalone_init(&to, &c->c2.gc);
2866 }
6fbf66fa
JY
2867}
2868
2869static void
81d882d5 2870do_init_finalize_tls_frame(struct context *c)
6fbf66fa 2871{
81d882d5 2872 if (c->c2.tls_multi)
6fbf66fa 2873 {
81d882d5
DS
2874 tls_multi_init_finalize(c->c2.tls_multi, &c->c2.frame);
2875 ASSERT(EXPANDED_SIZE(&c->c2.tls_multi->opt.frame) <=
2876 EXPANDED_SIZE(&c->c2.frame));
2877 frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO,
2878 "Control Channel MTU parms");
6fbf66fa 2879 }
81d882d5 2880 if (c->c2.tls_auth_standalone)
6fbf66fa 2881 {
81d882d5
DS
2882 tls_auth_standalone_finalize(c->c2.tls_auth_standalone, &c->c2.frame);
2883 frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
2884 "TLS-Auth MTU parms");
6fbf66fa
JY
2885 }
2886}
2887
6fbf66fa
JY
2888/*
2889 * No encryption or authentication.
2890 */
2891static void
81d882d5 2892do_init_crypto_none(const struct context *c)
6fbf66fa 2893{
81d882d5
DS
2894 ASSERT(!c->options.test_crypto);
2895 msg(M_WARN,
7a1b6a0d
DS
2896 "******* WARNING *******: All encryption and authentication features "
2897 "disabled -- All data will be tunnelled as clear text and will not be "
2898 "protected against man-in-the-middle changes. "
2899 "PLEASE DO RECONSIDER THIS CONFIGURATION!");
6fbf66fa 2900}
6fbf66fa
JY
2901
2902static void
81d882d5 2903do_init_crypto(struct context *c, const unsigned int flags)
6fbf66fa 2904{
81d882d5
DS
2905 if (c->options.shared_secret_file)
2906 {
2907 do_init_crypto_static(c, flags);
2908 }
2909 else if (c->options.tls_server || c->options.tls_client)
2910 {
2911 do_init_crypto_tls(c, flags);
2912 }
2913 else /* no encryption or authentication. */
2914 {
2915 do_init_crypto_none(c);
2916 }
6fbf66fa
JY
2917}
2918
2919static void
81d882d5 2920do_init_frame(struct context *c)
6fbf66fa 2921{
38d96bd7 2922#ifdef USE_COMP
81d882d5
DS
2923 /*
2924 * modify frame parameters if compression is enabled
2925 */
2926 if (comp_enabled(&c->options.comp))
6fbf66fa 2927 {
81d882d5 2928 comp_add_to_extra_frame(&c->c2.frame);
6fbf66fa 2929
9403e3f4 2930#if !defined(ENABLE_LZ4)
81d882d5
DS
2931 /*
2932 * Compression usage affects buffer alignment when non-swapped algs
2933 * such as LZO is used.
2934 * Newer algs like LZ4 and comp-stub with COMP_F_SWAP don't need
2935 * any special alignment because of the control-byte swap approach.
2936 * LZO alignment (on the other hand) is problematic because
2937 * the presence of the control byte means that either the output of
2938 * decryption must be written to an unaligned buffer, or the input
2939 * to compression (or packet dispatch if packet is uncompressed)
2940 * must be read from an unaligned buffer.
2941 * This code tries to align the input to compression (or packet
2942 * dispatch if packet is uncompressed) at the cost of requiring
2943 * decryption output to be written to an unaligned buffer, so
2944 * it's more of a tradeoff than an optimal solution and we don't
2945 * include it when we are doing a modern build with LZ4.
2946 * Strictly speaking, on the server it would be better to execute
2947 * this code for every connection after we decide the compression
2948 * method, but currently the frame code doesn't appear to be
2949 * flexible enough for this, since the frame is already established
2950 * before it is known which compression options will be pushed.
2951 */
2952 if (comp_unswapped_prefix(&c->options.comp) && CIPHER_ENABLED(c))
2953 {
2954 frame_add_to_align_adjust(&c->c2.frame, COMP_PREFIX_LEN);
2955 frame_or_align_flags(&c->c2.frame,
2956 FRAME_HEADROOM_MARKER_FRAGMENT
2957 |FRAME_HEADROOM_MARKER_DECRYPT);
2958 }
38d96bd7 2959#endif
6fbf66fa
JY
2960
2961#ifdef ENABLE_FRAGMENT
81d882d5 2962 comp_add_to_extra_frame(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
6fbf66fa
JY
2963#endif
2964 }
38d96bd7 2965#endif /* USE_COMP */
6fbf66fa 2966
81d882d5
DS
2967 /*
2968 * Adjust frame size for UDP Socks support.
2969 */
2970 if (c->options.ce.socks_proxy_server)
2971 {
2972 socks_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
2973 }
2974
2975 /*
2976 * Adjust frame size based on the --tun-mtu-extra parameter.
2977 */
2978 if (c->options.ce.tun_mtu_extra_defined)
2979 {
2980 tun_adjust_frame_parameters(&c->c2.frame, c->options.ce.tun_mtu_extra);
2981 }
2982
2983 /*
2984 * Adjust frame size based on link socket parameters.
2985 * (Since TCP is a stream protocol, we need to insert
2986 * a packet length uint16_t in the buffer.)
2987 */
2988 socket_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
2989
2990 /*
2991 * Fill in the blanks in the frame parameters structure,
2992 * make sure values are rational, etc.
2993 */
2994 frame_finalize_options(c, NULL);
6fbf66fa 2995
38d96bd7 2996#ifdef USE_COMP
81d882d5
DS
2997 /*
2998 * Modify frame parameters if compression is compiled in.
2999 * Should be called after frame_finalize_options.
3000 */
3001 comp_add_to_extra_buffer(&c->c2.frame);
38d96bd7 3002#ifdef ENABLE_FRAGMENT
81d882d5 3003 comp_add_to_extra_buffer(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
38d96bd7
JY
3004#endif
3005#endif /* USE_COMP */
3006
81d882d5
DS
3007 /* packets with peer-id (P_DATA_V2) need 3 extra bytes in frame (on client)
3008 * and need link_mtu+3 bytes on socket reception (on server).
3009 *
3010 * accomodate receive path in f->extra_link, which has the side effect of
3011 * also increasing send buffers (BUF_SIZE() macro), which need to be
3012 * allocated big enough before receiving peer-id option from server.
3013 *
3014 * f->extra_frame is adjusted when peer-id option is push-received
3015 */
3016 frame_add_to_extra_link(&c->c2.frame, 3);
9e0963c1 3017
6fbf66fa 3018#ifdef ENABLE_FRAGMENT
81d882d5
DS
3019 /*
3020 * Set frame parameter for fragment code. This is necessary because
3021 * the fragmentation code deals with payloads which have already been
3022 * passed through the compression code.
3023 */
3024 c->c2.frame_fragment = c->c2.frame;
3025 frame_subtract_extra(&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
6fbf66fa
JY
3026#endif
3027
3028#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
81d882d5
DS
3029 /*
3030 * MTU advisories
3031 */
3032 if (c->options.ce.fragment && c->options.mtu_test)
3033 {
3034 msg(M_WARN,
3035 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
3036 }
6fbf66fa
JY
3037#endif
3038
3039#ifdef ENABLE_FRAGMENT
81d882d5
DS
3040 if ((c->options.ce.mssfix || c->options.ce.fragment)
3041 && TUN_MTU_SIZE(&c->c2.frame_fragment) != ETHERNET_MTU)
3042 {
3043 msg(M_WARN,
3044 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
3045 ETHERNET_MTU, TUN_MTU_SIZE(&c->c2.frame_fragment));
3046 }
6fbf66fa
JY
3047#endif
3048}
3049
3050static void
81d882d5 3051do_option_warnings(struct context *c)
6fbf66fa 3052{
81d882d5 3053 const struct options *o = &c->options;
6fbf66fa 3054
81d882d5
DS
3055 if (o->ping_send_timeout && !o->ping_rec_timeout)
3056 {
3057 msg(M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
3058 }
6fbf66fa 3059
81d882d5 3060 if (o->username || o->groupname || o->chroot_dir
cd5990e0 3061#ifdef ENABLE_SELINUX
81d882d5 3062 || o->selinux_context
99385447 3063#endif
81d882d5
DS
3064 )
3065 {
3066 if (!o->persist_tun)
3067 {
3068 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
3069 }
3070 if (!o->persist_key
51b1d4c2 3071#ifdef ENABLE_PKCS11
81d882d5 3072 && !o->pkcs11_id
51b1d4c2 3073#endif
81d882d5
DS
3074 )
3075 {
3076 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
3077 }
3078 }
6fbf66fa 3079
81d882d5
DS
3080 if (o->chroot_dir && !(o->username && o->groupname))
3081 {
3082 msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
3083 }
31f90e64 3084
6fbf66fa 3085#if P2MP
81d882d5
DS
3086 if (o->pull && o->ifconfig_local && c->first_time)
3087 {
3088 msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
3089 }
6fbf66fa
JY
3090
3091#if P2MP_SERVER
81d882d5
DS
3092 if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
3093 {
3094 msg(M_WARN, "NOTE: when bridging your LAN adapter with the TAP adapter, note that the new bridge adapter will often take on its own IP address that is different from what the LAN adapter was previously set to");
3095 }
f77c60d3 3096
81d882d5 3097 if (o->mode == MODE_SERVER)
6fbf66fa 3098 {
81d882d5
DS
3099 if (o->duplicate_cn && o->client_config_dir)
3100 {
3101 msg(M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
3102 }
3103 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
3104 {
3105 msg(M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
3106 }
3107 if (!o->keepalive_ping || !o->keepalive_timeout)
3108 {
3109 msg(M_WARN, "WARNING: --keepalive option is missing from server config");
3110 }
6fbf66fa 3111 }
81d882d5
DS
3112#endif /* if P2MP_SERVER */
3113#endif /* if P2MP */
6fbf66fa 3114
81d882d5
DS
3115 if (!o->replay)
3116 {
3117 msg(M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
3118 }
81d882d5
DS
3119
3120 if (o->tls_server)
3121 {
3122 warn_on_use_of_common_subnets();
3123 }
3124 if (o->tls_client
3125 && !o->tls_verify
3126 && o->verify_x509_type == VERIFY_X509_NONE
3127 && !(o->ns_cert_type & NS_CERT_CHECK_SERVER)
3128 && !o->remote_cert_eku)
3129 {
3130 msg(M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
3131 }
2dc33226
SK
3132 if (o->ns_cert_type)
3133 {
3134 msg(M_WARN, "WARNING: --ns-cert-type is DEPRECATED. Use --remote-cert-tls instead.");
3135 }
81d882d5
DS
3136
3137 /* If a script is used, print appropiate warnings */
3138 if (o->user_script_used)
3139 {
bf97c00f 3140 if (script_security() >= SSEC_SCRIPTS)
81d882d5
DS
3141 {
3142 msg(M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
3143 }
bf97c00f 3144 else if (script_security() >= SSEC_PW_ENV)
81d882d5
DS
3145 {
3146 msg(M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
3147 }
3148 else
3149 {
3150 msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
3151 }
3152 }
6fbf66fa
JY
3153}
3154
3155static void
81d882d5 3156do_init_frame_tls(struct context *c)
6fbf66fa 3157{
81d882d5 3158 do_init_finalize_tls_frame(c);
6fbf66fa
JY
3159}
3160
3161struct context_buffers *
81d882d5 3162init_context_buffers(const struct frame *frame)
6fbf66fa 3163{
81d882d5 3164 struct context_buffers *b;
6fbf66fa 3165
81d882d5 3166 ALLOC_OBJ_CLEAR(b, struct context_buffers);
6fbf66fa 3167
81d882d5
DS
3168 b->read_link_buf = alloc_buf(BUF_SIZE(frame));
3169 b->read_tun_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3170
81d882d5 3171 b->aux_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3172
81d882d5
DS
3173 b->encrypt_buf = alloc_buf(BUF_SIZE(frame));
3174 b->decrypt_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3175
38d96bd7 3176#ifdef USE_COMP
81d882d5
DS
3177 b->compress_buf = alloc_buf(BUF_SIZE(frame));
3178 b->decompress_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa
JY
3179#endif
3180
81d882d5 3181 return b;
6fbf66fa
JY
3182}
3183
3184void
81d882d5 3185free_context_buffers(struct context_buffers *b)
6fbf66fa 3186{
81d882d5 3187 if (b)
6fbf66fa 3188 {
81d882d5
DS
3189 free_buf(&b->read_link_buf);
3190 free_buf(&b->read_tun_buf);
3191 free_buf(&b->aux_buf);
6fbf66fa 3192
38d96bd7 3193#ifdef USE_COMP
81d882d5
DS
3194 free_buf(&b->compress_buf);
3195 free_buf(&b->decompress_buf);
6fbf66fa
JY
3196#endif
3197
81d882d5
DS
3198 free_buf(&b->encrypt_buf);
3199 free_buf(&b->decrypt_buf);
6fbf66fa 3200
81d882d5 3201 free(b);
6fbf66fa
JY
3202 }
3203}
3204
3205/*
3206 * Now that we know all frame parameters, initialize
3207 * our buffers.
3208 */
3209static void
81d882d5 3210do_init_buffers(struct context *c)
6fbf66fa 3211{
81d882d5
DS
3212 c->c2.buffers = init_context_buffers(&c->c2.frame);
3213 c->c2.buffers_owned = true;
6fbf66fa
JY
3214}
3215
3216#ifdef ENABLE_FRAGMENT
3217/*
3218 * Fragmenting code has buffers to initialize
3219 * once frame parameters are known.
3220 */
3221static void
81d882d5 3222do_init_fragment(struct context *c)
6fbf66fa 3223{
81d882d5
DS
3224 ASSERT(c->options.ce.fragment);
3225 frame_set_mtu_dynamic(&c->c2.frame_fragment,
3226 c->options.ce.fragment, SET_MTU_UPPER_BOUND);
3227 fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment);
6fbf66fa
JY
3228}
3229#endif
3230
6fbf66fa
JY
3231/*
3232 * Allocate our socket object.
3233 */
3234static void
81d882d5 3235do_link_socket_new(struct context *c)
6fbf66fa 3236{
81d882d5
DS
3237 ASSERT(!c->c2.link_socket);
3238 c->c2.link_socket = link_socket_new();
3239 c->c2.link_socket_owned = true;
6fbf66fa
JY
3240}
3241
3242/*
3243 * bind the TCP/UDP socket
3244 */
3245static void
81d882d5 3246do_init_socket_1(struct context *c, const int mode)
6fbf66fa 3247{
81d882d5 3248 unsigned int sockflags = c->options.sockflags;
dc46c067
JY
3249
3250#if PORT_SHARE
81d882d5
DS
3251 if (c->options.port_share_host && c->options.port_share_port)
3252 {
3253 sockflags |= SF_PORT_SHARE;
3254 }
3255#endif
3256
3257 link_socket_init_phase1(c->c2.link_socket,
3258 c->options.ce.local,
3259 c->options.ce.local_port,
3260 c->options.ce.remote,
3261 c->options.ce.remote_port,
3262 c->c1.dns_cache,
3263 c->options.ce.proto,
3264 c->options.ce.af,
3265 c->options.ce.bind_ipv6_only,
3266 mode,
3267 c->c2.accept_from,
3268 c->c1.http_proxy,
3269 c->c1.socks_proxy,
6fbf66fa 3270#ifdef ENABLE_DEBUG
81d882d5
DS
3271 c->options.gremlin,
3272#endif
3273 c->options.ce.bind_local,
3274 c->options.ce.remote_float,
3275 c->options.inetd,
3276 &c->c1.link_socket_addr,
3277 c->options.ipchange,
3278 c->plugins,
3279 c->options.resolve_retry_seconds,
3280 c->options.ce.mtu_discover_type,
3281 c->options.rcvbuf,
3282 c->options.sndbuf,
3283 c->options.mark,
3284 &c->c2.server_poll_interval,
3285 sockflags);
6fbf66fa
JY
3286}
3287
3288/*
3289 * finalize the TCP/UDP socket
3290 */
3291static void
81d882d5 3292do_init_socket_2(struct context *c)
6fbf66fa 3293{
81d882d5
DS
3294 link_socket_init_phase2(c->c2.link_socket, &c->c2.frame,
3295 c->sig);
6fbf66fa
JY
3296}
3297
3298/*
3299 * Print MTU INFO
3300 */
3301static void
81d882d5 3302do_print_data_channel_mtu_parms(struct context *c)
6fbf66fa 3303{
81d882d5 3304 frame_print(&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
6fbf66fa 3305#ifdef ENABLE_FRAGMENT
81d882d5
DS
3306 if (c->c2.fragment)
3307 {
3308 frame_print(&c->c2.frame_fragment, D_MTU_INFO,
3309 "Fragmentation MTU parms");
3310 }
6fbf66fa
JY
3311#endif
3312}
3313
3314#ifdef ENABLE_OCC
3315/*
3316 * Get local and remote options compatibility strings.
3317 */
3318static void
81d882d5 3319do_compute_occ_strings(struct context *c)
6fbf66fa 3320{
81d882d5 3321 struct gc_arena gc = gc_new();
6fbf66fa 3322
81d882d5
DS
3323 c->c2.options_string_local =
3324 options_string(&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
3325 c->c2.options_string_remote =
3326 options_string(&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
6fbf66fa 3327
81d882d5
DS
3328 msg(D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
3329 options_string_version(c->c2.options_string_local, &gc),
3330 c->c2.options_string_local);
3331 msg(D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
3332 options_string_version(c->c2.options_string_remote, &gc),
3333 c->c2.options_string_remote);
6fbf66fa 3334
81d882d5
DS
3335 if (c->c2.tls_multi)
3336 {
3337 tls_multi_init_set_options(c->c2.tls_multi,
3338 c->c2.options_string_local,
3339 c->c2.options_string_remote);
3340 }
6fbf66fa 3341
81d882d5 3342 gc_free(&gc);
6fbf66fa 3343}
81d882d5 3344#endif /* ifdef ENABLE_OCC */
6fbf66fa
JY
3345
3346/*
3347 * These things can only be executed once per program instantiation.
3348 * Set up for possible UID/GID downgrade, but don't do it yet.
3349 * Daemonize if requested.
3350 */
3351static void
81d882d5 3352do_init_first_time(struct context *c)
6fbf66fa 3353{
81d882d5 3354 if (c->first_time && !c->c0)
6fbf66fa 3355 {
81d882d5 3356 struct context_0 *c0;
92bbb061 3357
81d882d5
DS
3358 ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc);
3359 c0 = c->c0;
6fbf66fa 3360
81d882d5
DS
3361 /* get user and/or group that we want to setuid/setgid to */
3362 c0->uid_gid_specified =
3363 platform_group_get(c->options.groupname, &c0->platform_state_group)
3364 |platform_user_get(c->options.username, &c0->platform_state_user);
6fbf66fa 3365
81d882d5
DS
3366 /* perform postponed chdir if --daemon */
3367 if (c->did_we_daemonize && c->options.cd_dir == NULL)
3368 {
3369 platform_chdir("/");
3370 }
3371
3372 /* should we change scheduling priority? */
3373 platform_nice(c->options.nice);
6fbf66fa
JY
3374 }
3375}
3376
3377/*
3378 * If xinetd/inetd mode, don't allow restart.
3379 */
3380static void
81d882d5 3381do_close_check_if_restart_permitted(struct context *c)
6fbf66fa 3382{
81d882d5
DS
3383 if (c->options.inetd
3384 && (c->sig->signal_received == SIGHUP
3385 || c->sig->signal_received == SIGUSR1))
6fbf66fa 3386 {
81d882d5
DS
3387 c->sig->signal_received = SIGTERM;
3388 msg(M_INFO,
3389 PACKAGE_NAME
3390 " started by inetd/xinetd cannot restart... Exiting.");
6fbf66fa
JY
3391 }
3392}
3393
3394/*
3395 * free buffers
3396 */
3397static void
81d882d5 3398do_close_free_buf(struct context *c)
6fbf66fa 3399{
81d882d5 3400 if (c->c2.buffers_owned)
6fbf66fa 3401 {
81d882d5
DS
3402 free_context_buffers(c->c2.buffers);
3403 c->c2.buffers = NULL;
3404 c->c2.buffers_owned = false;
6fbf66fa
JY
3405 }
3406}
3407
3408/*
3409 * close TLS
3410 */
3411static void
81d882d5 3412do_close_tls(struct context *c)
6fbf66fa 3413{
81d882d5 3414 if (c->c2.tls_multi)
6fbf66fa 3415 {
81d882d5
DS
3416 tls_multi_free(c->c2.tls_multi, true);
3417 c->c2.tls_multi = NULL;
6fbf66fa
JY
3418 }
3419
3420#ifdef ENABLE_OCC
81d882d5
DS
3421 /* free options compatibility strings */
3422 if (c->c2.options_string_local)
3423 {
3424 free(c->c2.options_string_local);
3425 }
3426 if (c->c2.options_string_remote)
3427 {
3428 free(c->c2.options_string_remote);
3429 }
3430 c->c2.options_string_local = c->c2.options_string_remote = NULL;
6fbf66fa 3431#endif
07036fd3
SK
3432
3433 if (c->c2.pulled_options_state)
3434 {
3435 md_ctx_cleanup(c->c2.pulled_options_state);
3436 md_ctx_free(c->c2.pulled_options_state);
3437 }
6fbf66fa
JY
3438}
3439
3440/*
3441 * Free key schedules
3442 */
3443static void
81d882d5 3444do_close_free_key_schedule(struct context *c, bool free_ssl_ctx)
6fbf66fa 3445{
5817b49b
AQ
3446 /*
3447 * always free the tls_auth/crypt key. If persist_key is true, the key will
3448 * be reloaded from memory (pre-cached)
3449 */
3450 free_key_ctx_bi(&c->c1.ks.tls_wrap_key);
3451 CLEAR(c->c1.ks.tls_wrap_key);
3452
81d882d5
DS
3453 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
3454 {
3455 key_schedule_free(&c->c1.ks, free_ssl_ctx);
3456 }
6fbf66fa
JY
3457}
3458
3459/*
3460 * Close TCP/UDP connection
3461 */
3462static void
81d882d5 3463do_close_link_socket(struct context *c)
6fbf66fa 3464{
81d882d5 3465 if (c->c2.link_socket && c->c2.link_socket_owned)
6fbf66fa 3466 {
81d882d5
DS
3467 link_socket_close(c->c2.link_socket);
3468 c->c2.link_socket = NULL;
6fbf66fa
JY
3469 }
3470
81d882d5
DS
3471
3472 /* Preserve the resolved list of remote if the user request to or if we want
3473 * reconnect to the same host again or there are still addresses that need
3474 * to be tried */
3475 if (!(c->sig->signal_received == SIGUSR1
3476 && ( (c->options.persist_remote_ip)
3477 ||
3478 ( c->sig->source != SIG_SOURCE_HARD
3479 && ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
3480 || c->options.no_advance))
3481 )))
23d61c56 3482 {
81d882d5 3483 clear_remote_addrlist(&c->c1.link_socket_addr, !c->options.resolve_in_advance);
23d61c56
AS
3484 }
3485
3486 /* Clear the remote actual address when persist_remote_ip is not in use */
3487 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
81d882d5
DS
3488 {
3489 CLEAR(c->c1.link_socket_addr.actual);
3490 }
6fbf66fa 3491
81d882d5
DS
3492 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
3493 {
3494 if (c->c1.link_socket_addr.bind_local && !c->options.resolve_in_advance)
3495 {
3496 freeaddrinfo(c->c1.link_socket_addr.bind_local);
3497 }
e719a053 3498
81d882d5
DS
3499 c->c1.link_socket_addr.bind_local = NULL;
3500 }
6fbf66fa
JY
3501}
3502
3503/*
3504 * Close packet-id persistance file
3505 */
3506static void
81d882d5 3507do_close_packet_id(struct context *c)
6fbf66fa 3508{
81d882d5
DS
3509 packet_id_free(&c->c2.crypto_options.packet_id);
3510 packet_id_persist_save(&c->c1.pid_persist);
3511 if (!(c->sig->signal_received == SIGUSR1))
3512 {
3513 packet_id_persist_close(&c->c1.pid_persist);
3514 }
6fbf66fa
JY
3515}
3516
3517#ifdef ENABLE_FRAGMENT
3518/*
3519 * Close fragmentation handler.
3520 */
3521static void
81d882d5 3522do_close_fragment(struct context *c)
6fbf66fa 3523{
81d882d5 3524 if (c->c2.fragment)
6fbf66fa 3525 {
81d882d5
DS
3526 fragment_free(c->c2.fragment);
3527 c->c2.fragment = NULL;
6fbf66fa
JY
3528 }
3529}
3530#endif
3531
3532/*
3533 * Open and close our event objects.
3534 */
3535
3536static void
81d882d5
DS
3537do_event_set_init(struct context *c,
3538 bool need_us_timeout)
6fbf66fa 3539{
81d882d5 3540 unsigned int flags = 0;
6fbf66fa 3541
81d882d5 3542 c->c2.event_set_max = BASE_N_EVENTS;
6fbf66fa 3543
81d882d5 3544 flags |= EVENT_METHOD_FAST;
6fbf66fa 3545
81d882d5
DS
3546 if (need_us_timeout)
3547 {
3548 flags |= EVENT_METHOD_US_TIMEOUT;
3549 }
6fbf66fa 3550
81d882d5
DS
3551 c->c2.event_set = event_set_init(&c->c2.event_set_max, flags);
3552 c->c2.event_set_owned = true;
6fbf66fa
JY
3553}
3554
3555static void
81d882d5 3556do_close_event_set(struct context *c)
6fbf66fa 3557{
81d882d5 3558 if (c->c2.event_set && c->c2.event_set_owned)
6fbf66fa 3559 {
81d882d5
DS
3560 event_free(c->c2.event_set);
3561 c->c2.event_set = NULL;
3562 c->c2.event_set_owned = false;
6fbf66fa
JY
3563 }
3564}
3565
3566/*
3567 * Open and close --status file
3568 */
3569
3570static void
81d882d5 3571do_open_status_output(struct context *c)
6fbf66fa 3572{
81d882d5 3573 if (!c->c1.status_output)
6fbf66fa 3574 {
81d882d5
DS
3575 c->c1.status_output = status_open(c->options.status_file,
3576 c->options.status_file_update_freq,
3577 -1,
3578 NULL,
3579 STATUS_OUTPUT_WRITE);
3580 c->c1.status_output_owned = true;
6fbf66fa
JY
3581 }
3582}
3583
3584static void
81d882d5 3585do_close_status_output(struct context *c)
6fbf66fa 3586{
81d882d5 3587 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3588 {
81d882d5
DS
3589 if (c->c1.status_output_owned && c->c1.status_output)
3590 {
3591 status_close(c->c1.status_output);
3592 c->c1.status_output = NULL;
3593 c->c1.status_output_owned = false;
3594 }
6fbf66fa
JY
3595 }
3596}
3597
3598/*
3599 * Handle ifconfig-pool persistance object.
3600 */
3601static void
81d882d5 3602do_open_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3603{
3604#if P2MP_SERVER
81d882d5 3605 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
6fbf66fa 3606 {
81d882d5
DS
3607 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init(c->options.ifconfig_pool_persist_filename,
3608 c->options.ifconfig_pool_persist_refresh_freq);
3609 c->c1.ifconfig_pool_persist_owned = true;
6fbf66fa
JY
3610 }
3611#endif
3612}
3613
3614static void
81d882d5 3615do_close_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3616{
3617#if P2MP_SERVER
81d882d5 3618 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3619 {
81d882d5
DS
3620 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
3621 {
3622 ifconfig_pool_persist_close(c->c1.ifconfig_pool_persist);
3623 c->c1.ifconfig_pool_persist = NULL;
3624 c->c1.ifconfig_pool_persist_owned = false;
3625 }
6fbf66fa
JY
3626 }
3627#endif
3628}
3629
3630/*
3631 * Inherit environmental variables
3632 */
3633
3634static void
81d882d5 3635do_inherit_env(struct context *c, const struct env_set *src)
6fbf66fa 3636{
81d882d5
DS
3637 c->c2.es = env_set_create(NULL);
3638 c->c2.es_owned = true;
3639 env_set_inherit(c->c2.es, src);
6fbf66fa
JY
3640}
3641
2a64816b 3642static void
81d882d5 3643do_env_set_destroy(struct context *c)
2a64816b 3644{
81d882d5 3645 if (c->c2.es && c->c2.es_owned)
2a64816b 3646 {
81d882d5
DS
3647 env_set_destroy(c->c2.es);
3648 c->c2.es = NULL;
3649 c->c2.es_owned = false;
2a64816b
JY
3650 }
3651}
3652
6fbf66fa
JY
3653/*
3654 * Fast I/O setup. Fast I/O is an optimization which only works
3655 * if all of the following are true:
3656 *
3657 * (1) The platform is not Windows
3658 * (2) --proto udp is enabled
3659 * (3) --shaper is disabled
3660 */
3661static void
81d882d5 3662do_setup_fast_io(struct context *c)
6fbf66fa 3663{
81d882d5 3664 if (c->options.fast_io)
6fbf66fa 3665 {
445b192a 3666#ifdef _WIN32
81d882d5 3667 msg(M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
6fbf66fa 3668#else
81d882d5
DS
3669 if (!proto_is_udp(c->options.ce.proto))
3670 {
3671 msg(M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
3672 }
3673 else
3674 {
3d163bc5 3675#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
3676 if (c->options.shaper)
3677 {
3678 msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
3679 }
3680 else
0475d17e 3681#endif
81d882d5
DS
3682 {
3683 c->c2.fast_io = true;
3684 }
3685 }
6fbf66fa
JY
3686#endif
3687 }
3688}
3689
3690static void
81d882d5 3691do_signal_on_tls_errors(struct context *c)
6fbf66fa 3692{
81d882d5
DS
3693 if (c->options.tls_exit)
3694 {
3695 c->c2.tls_exit_signal = SIGTERM;
3696 }
3697 else
3698 {
3699 c->c2.tls_exit_signal = SIGUSR1;
3700 }
6fbf66fa
JY
3701}
3702
3c7f2f55 3703#ifdef ENABLE_PLUGIN
6fbf66fa 3704
3c7f2f55 3705void
81d882d5 3706init_plugins(struct context *c)
6fbf66fa 3707{
81d882d5 3708 if (c->options.plugin_list && !c->plugins)
e1791bb1 3709 {
81d882d5
DS
3710 c->plugins = plugin_list_init(c->options.plugin_list);
3711 c->plugins_owned = true;
e1791bb1
JY
3712 }
3713}
3714
3715void
81d882d5
DS
3716open_plugins(struct context *c, const bool import_options, int init_point)
3717{
3718 if (c->plugins && c->plugins_owned)
3719 {
3720 if (import_options)
3721 {
3722 struct plugin_return pr, config;
3723 plugin_return_init(&pr);
3724 plugin_list_open(c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
3725 plugin_return_get_column(&pr, &config, "config");
3726 if (plugin_return_defined(&config))
3727 {
3728 int i;
3729 for (i = 0; i < config.n; ++i)
3730 {
3731 unsigned int option_types_found = 0;
3732 if (config.list[i] && config.list[i]->value)
3733 {
3734 options_string_import(&c->options,
3735 config.list[i]->value,
3736 D_IMPORT_ERRORS|M_OPTERR,
3737 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
3738 &option_types_found,
3739 c->es);
3740 }
3741 }
3742 }
3743 plugin_return_free(&pr);
3744 }
3745 else
3746 {
3747 plugin_list_open(c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
3748 }
6fbf66fa 3749 }
6fbf66fa
JY
3750}
3751
3752static void
81d882d5 3753do_close_plugins(struct context *c)
6fbf66fa 3754{
81d882d5 3755 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 3756 {
81d882d5
DS
3757 plugin_list_close(c->plugins);
3758 c->plugins = NULL;
3759 c->plugins_owned = false;
6fbf66fa 3760 }
6fbf66fa
JY
3761}
3762
3c7f2f55 3763static void
81d882d5 3764do_inherit_plugins(struct context *c, const struct context *src)
3c7f2f55 3765{
81d882d5 3766 if (!c->plugins && src->plugins)
3c7f2f55 3767 {
81d882d5
DS
3768 c->plugins = plugin_list_inherit(src->plugins);
3769 c->plugins_owned = true;
3c7f2f55
JY
3770 }
3771}
3772
81d882d5 3773#endif /* ifdef ENABLE_PLUGIN */
3c7f2f55 3774
6fbf66fa
JY
3775#ifdef ENABLE_MANAGEMENT
3776
3777static void
81d882d5 3778management_callback_status_p2p(void *arg, const int version, struct status_output *so)
6fbf66fa 3779{
81d882d5
DS
3780 struct context *c = (struct context *) arg;
3781 print_status(c, so);
6fbf66fa
JY
3782}
3783
3784void
81d882d5 3785management_show_net_callback(void *arg, const int msglevel)
6fbf66fa 3786{
445b192a 3787#ifdef _WIN32
81d882d5
DS
3788 show_routes(msglevel);
3789 show_adapters(msglevel);
3790 msg(msglevel, "END");
6fbf66fa 3791#else
81d882d5 3792 msg(msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
6fbf66fa
JY
3793#endif
3794}
3795
30003978
AS
3796#ifdef TARGET_ANDROID
3797int
81d882d5 3798management_callback_network_change(void *arg, bool samenetwork)
30003978
AS
3799{
3800 /* Check if the client should translate the network change to a SIGUSR1 to
81d882d5
DS
3801 * reestablish the connection or just reprotect the socket
3802 *
3803 * At the moment just assume that, for all settings that use pull (not
3804 * --static) and are not using peer-id reestablishing the connection is
3805 * required (unless the network is the same)
3806 *
3807 * The function returns -1 on invalid fd and -2 if the socket cannot be
3808 * reused. On the -2 return value the man_network_change function triggers
3809 * a SIGUSR1 to force a reconnect.
3810 */
3811
3812 int socketfd = -1;
3813 struct context *c = (struct context *) arg;
3814 if (!c->c2.link_socket)
3815 {
3816 return -1;
3817 }
3818 if (c->c2.link_socket->sd == SOCKET_UNDEFINED)
3819 {
3820 return -1;
3821 }
30003978 3822
81d882d5
DS
3823 socketfd = c->c2.link_socket->sd;
3824 if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
3825 {
3826 return socketfd;
3827 }
3828 else
3829 {
3830 return -2;
3831 }
30003978 3832}
81d882d5 3833#endif /* ifdef TARGET_ANDROID */
30003978 3834
81d882d5 3835#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
3836
3837void
81d882d5 3838init_management_callback_p2p(struct context *c)
6fbf66fa
JY
3839{
3840#ifdef ENABLE_MANAGEMENT
81d882d5
DS
3841 if (management)
3842 {
3843 struct management_callback cb;
3844 CLEAR(cb);
3845 cb.arg = c;
3846 cb.status = management_callback_status_p2p;
3847 cb.show_net = management_show_net_callback;
3848 cb.proxy_cmd = management_callback_proxy_cmd;
3849 cb.remote_cmd = management_callback_remote_cmd;
30003978 3850#ifdef TARGET_ANDROID
81d882d5 3851 cb.network_change = management_callback_network_change;
30003978 3852#endif
81d882d5 3853 management_set_callback(management, &cb);
6fbf66fa
JY
3854 }
3855#endif
3856}
3857
3858#ifdef ENABLE_MANAGEMENT
3859
3860void
81d882d5 3861init_management(struct context *c)
6fbf66fa 3862{
81d882d5
DS
3863 if (!management)
3864 {
3865 management = management_init();
3866 }
6fbf66fa
JY
3867}
3868
3869bool
81d882d5
DS
3870open_management(struct context *c)
3871{
3872 /* initialize management layer */
3873 if (management)
3874 {
3875 if (c->options.management_addr)
3876 {
3877 unsigned int flags = c->options.management_flags;
3878 if (c->options.mode == MODE_SERVER)
3879 {
3880 flags |= MF_SERVER;
3881 }
3882 if (management_open(management,
3883 c->options.management_addr,
3884 c->options.management_port,
3885 c->options.management_user_pass,
3886 c->options.management_client_user,
3887 c->options.management_client_group,
3888 c->options.management_log_history_cache,
3889 c->options.management_echo_buffer_size,
3890 c->options.management_state_buffer_size,
3891 c->options.management_write_peer_info_file,
3892 c->options.remap_sigusr1,
3893 flags))
3894 {
3895 management_set_state(management,
3896 OPENVPN_STATE_CONNECTING,
3897 NULL,
3898 NULL,
3899 NULL,
3900 NULL,
3901 NULL);
3902 }
3903
3904 /* initial management hold, called early, before first context initialization */
3905 do_hold(0);
3906 if (IS_SIG(c))
3907 {
3908 msg(M_WARN, "Signal received from management interface, exiting");
3909 return false;
3910 }
3911 }
3912 else
3913 {
3914 close_management();
3915 }
3916 }
3917 return true;
6fbf66fa
JY
3918}
3919
3920void
81d882d5 3921close_management(void)
6fbf66fa 3922{
81d882d5 3923 if (management)
6fbf66fa 3924 {
81d882d5
DS
3925 management_close(management);
3926 management = NULL;
6fbf66fa
JY
3927 }
3928}
3929
81d882d5 3930#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
3931
3932
3933void
81d882d5 3934uninit_management_callback(void)
6fbf66fa
JY
3935{
3936#ifdef ENABLE_MANAGEMENT
81d882d5 3937 if (management)
6fbf66fa 3938 {
81d882d5 3939 management_clear_callback(management);
6fbf66fa
JY
3940 }
3941#endif
3942}
3943
3944/*
3945 * Initialize a tunnel instance, handle pre and post-init
3946 * signal settings.
3947 */
3948void
81d882d5 3949init_instance_handle_signals(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 3950{
81d882d5
DS
3951 pre_init_signal_catch();
3952 init_instance(c, env, flags);
3953 post_init_signal_catch();
3954
3955 /*
3956 * This is done so that signals thrown during
3957 * initialization can bring us back to
3958 * a management hold.
3959 */
3960 if (IS_SIG(c))
d5badcf1 3961 {
81d882d5
DS
3962 remap_signal(c);
3963 uninit_management_callback();
d5badcf1 3964 }
6fbf66fa
JY
3965}
3966
3967/*
3968 * Initialize a tunnel instance.
3969 */
3970void
81d882d5 3971init_instance(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 3972{
81d882d5
DS
3973 const struct options *options = &c->options;
3974 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
3975 int link_socket_mode = LS_MODE_DEFAULT;
6fbf66fa 3976
81d882d5
DS
3977 /* init garbage collection level */
3978 gc_init(&c->c2.gc);
6fbf66fa 3979
81d882d5
DS
3980 /* inherit environmental variables */
3981 if (env)
3982 {
3983 do_inherit_env(c, env);
3984 }
ac1c2f25 3985
81d882d5
DS
3986 /* signals caught here will abort */
3987 c->sig->signal_received = 0;
3988 c->sig->signal_text = NULL;
3989 c->sig->source = SIG_SOURCE_SOFT;
6fbf66fa 3990
81d882d5
DS
3991 if (c->mode == CM_P2P)
3992 {
3993 init_management_callback_p2p(c);
3994 }
3cf6c932 3995
81d882d5
DS
3996 /* possible sleep or management hold if restart */
3997 if (c->mode == CM_P2P || c->mode == CM_TOP)
3cf6c932 3998 {
81d882d5
DS
3999 do_startup_pause(c);
4000 if (IS_SIG(c))
4001 {
4002 goto sig;
4003 }
3cf6c932
JY
4004 }
4005
81d882d5 4006 if (c->options.resolve_in_advance)
e719a053 4007 {
81d882d5
DS
4008 do_preresolve(c);
4009 if (IS_SIG(c))
4010 {
4011 goto sig;
4012 }
e719a053
AS
4013 }
4014
81d882d5
DS
4015 /* map in current connection entry */
4016 next_connection_entry(c);
4e9a51d7 4017
81d882d5
DS
4018 /* link_socket_mode allows CM_CHILD_TCP
4019 * instances to inherit acceptable fds
4020 * from a top-level parent */
4021 if (c->options.ce.proto == PROTO_TCP_SERVER)
6fbf66fa 4022 {
81d882d5
DS
4023 if (c->mode == CM_TOP)
4024 {
4025 link_socket_mode = LS_MODE_TCP_LISTEN;
4026 }
4027 else if (c->mode == CM_CHILD_TCP)
4028 {
4029 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
4030 }
6fbf66fa
JY
4031 }
4032
81d882d5
DS
4033 /* should we disable paging? */
4034 if (c->first_time && options->mlock)
4035 {
4036 platform_mlockall(true);
4037 }
6fbf66fa 4038
92bbb061 4039#if P2MP
81d882d5
DS
4040 /* get passwords if undefined */
4041 if (auth_retry_get() == AR_INTERACT)
4042 {
4043 init_query_passwords(c);
4044 }
92bbb061
JY
4045#endif
4046
81d882d5
DS
4047 /* initialize context level 2 --verb/--mute parms */
4048 init_verb_mute(c, IVM_LEVEL_2);
4049
4050 /* set error message delay for non-server modes */
4051 if (c->mode == CM_P2P)
4052 {
4053 set_check_status_error_delay(P2P_ERROR_DELAY_MS);
4054 }
6fbf66fa 4055
81d882d5
DS
4056 /* warn about inconsistent options */
4057 if (c->mode == CM_P2P || c->mode == CM_TOP)
4058 {
4059 do_option_warnings(c);
4060 }
6fbf66fa 4061
3c7f2f55 4062#ifdef ENABLE_PLUGIN
81d882d5
DS
4063 /* initialize plugins */
4064 if (c->mode == CM_P2P || c->mode == CM_TOP)
4065 {
4066 open_plugins(c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
4067 }
3c7f2f55 4068#endif
6fbf66fa 4069
81d882d5
DS
4070 /* should we enable fast I/O? */
4071 if (c->mode == CM_P2P || c->mode == CM_TOP)
4072 {
4073 do_setup_fast_io(c);
4074 }
6fbf66fa 4075
81d882d5
DS
4076 /* should we throw a signal on TLS errors? */
4077 do_signal_on_tls_errors(c);
6fbf66fa 4078
81d882d5
DS
4079 /* open --status file */
4080 if (c->mode == CM_P2P || c->mode == CM_TOP)
4081 {
4082 do_open_status_output(c);
4083 }
6fbf66fa 4084
81d882d5
DS
4085 /* open --ifconfig-pool-persist file */
4086 if (c->mode == CM_TOP)
4087 {
4088 do_open_ifconfig_pool_persist(c);
4089 }
6fbf66fa
JY
4090
4091#ifdef ENABLE_OCC
81d882d5
DS
4092 /* reset OCC state */
4093 if (c->mode == CM_P2P || child)
4094 {
4095 c->c2.occ_op = occ_reset_op();
4096 }
6fbf66fa
JY
4097#endif
4098
81d882d5
DS
4099 /* our wait-for-i/o objects, different for posix vs. win32 */
4100 if (c->mode == CM_P2P)
4101 {
4102 do_event_set_init(c, SHAPER_DEFINED(&c->options));
4103 }
4104 else if (c->mode == CM_CHILD_TCP)
4105 {
4106 do_event_set_init(c, false);
4107 }
6fbf66fa 4108
81d882d5
DS
4109 /* initialize HTTP or SOCKS proxy object at scope level 2 */
4110 init_proxy(c);
4e9a51d7 4111
81d882d5
DS
4112 /* allocate our socket object */
4113 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4114 {
4115 do_link_socket_new(c);
4116 }
6fbf66fa
JY
4117
4118#ifdef ENABLE_FRAGMENT
81d882d5
DS
4119 /* initialize internal fragmentation object */
4120 if (options->ce.fragment && (c->mode == CM_P2P || child))
4121 {
4122 c->c2.fragment = fragment_init(&c->c2.frame);
4123 }
6fbf66fa
JY
4124#endif
4125
81d882d5
DS
4126 /* init crypto layer */
4127 {
4128 unsigned int crypto_flags = 0;
4129 if (c->mode == CM_TOP)
4130 {
4131 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
4132 }
4133 else if (c->mode == CM_P2P)
4134 {
4135 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
4136 }
4137 else if (child)
4138 {
4139 crypto_flags = CF_INIT_TLS_MULTI;
4140 }
4141 do_init_crypto(c, crypto_flags);
4142 if (IS_SIG(c) && !child)
4143 {
4144 goto sig;
4145 }
4146 }
6fbf66fa 4147
38d96bd7 4148#ifdef USE_COMP
81d882d5
DS
4149 /* initialize compression library. */
4150 if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
4151 {
4152 c->c2.comp_context = comp_init(&options->comp);
4153 }
6fbf66fa
JY
4154#endif
4155
81d882d5
DS
4156 /* initialize MTU variables */
4157 do_init_frame(c);
6fbf66fa 4158
81d882d5
DS
4159 /* initialize TLS MTU variables */
4160 do_init_frame_tls(c);
6fbf66fa 4161
81d882d5
DS
4162 /* init workspace buffers whose size is derived from frame size */
4163 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
4164 {
4165 do_init_buffers(c);
4166 }
6fbf66fa
JY
4167
4168#ifdef ENABLE_FRAGMENT
81d882d5
DS
4169 /* initialize internal fragmentation capability with known frame size */
4170 if (options->ce.fragment && (c->mode == CM_P2P || child))
4171 {
4172 do_init_fragment(c);
4173 }
6fbf66fa
JY
4174#endif
4175
81d882d5
DS
4176 /* initialize dynamic MTU variable */
4177 frame_init_mssfix(&c->c2.frame, &c->options);
6fbf66fa 4178
81d882d5
DS
4179 /* bind the TCP/UDP socket */
4180 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4181 {
4182 do_init_socket_1(c, link_socket_mode);
4183 }
6fbf66fa 4184
81d882d5
DS
4185 /* initialize tun/tap device object,
4186 * open tun/tap device, ifconfig, run up script, etc. */
4187 if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
4188 {
4189 c->c2.did_open_tun = do_open_tun(c);
4190 }
6fbf66fa 4191
9900e023
SK
4192 c->c2.frame_initial = c->c2.frame;
4193
81d882d5
DS
4194 /* print MTU info */
4195 do_print_data_channel_mtu_parms(c);
6fbf66fa
JY
4196
4197#ifdef ENABLE_OCC
81d882d5
DS
4198 /* get local and remote options compatibility strings */
4199 if (c->mode == CM_P2P || child)
4200 {
4201 do_compute_occ_strings(c);
4202 }
6fbf66fa
JY
4203#endif
4204
81d882d5
DS
4205 /* initialize output speed limiter */
4206 if (c->mode == CM_P2P)
4207 {
4208 do_init_traffic_shaper(c);
4209 }
6fbf66fa 4210
81d882d5
DS
4211 /* do one-time inits, and possibily become a daemon here */
4212 do_init_first_time(c);
6fbf66fa 4213
e1791bb1 4214#ifdef ENABLE_PLUGIN
81d882d5
DS
4215 /* initialize plugins */
4216 if (c->mode == CM_P2P || c->mode == CM_TOP)
4217 {
4218 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
4219 }
e1791bb1
JY
4220#endif
4221
81d882d5
DS
4222 /* initialise connect timeout timer */
4223 do_init_server_poll_timeout(c);
4db06290 4224
81d882d5
DS
4225 /* finalize the TCP/UDP socket */
4226 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4227 {
4228 do_init_socket_2(c);
4229 }
b3e97582 4230
81d882d5
DS
4231 /*
4232 * Actually do UID/GID downgrade, and chroot, if requested.
4233 * May be delayed by --client, --pull, or --up-delay.
4234 */
4235 do_uid_gid_chroot(c, c->c2.did_open_tun);
6fbf66fa 4236
81d882d5
DS
4237 /* initialize timers */
4238 if (c->mode == CM_P2P || child)
4239 {
4240 do_init_timers(c, false);
4241 }
6fbf66fa 4242
e1791bb1 4243#ifdef ENABLE_PLUGIN
81d882d5
DS
4244 /* initialize plugins */
4245 if (c->mode == CM_P2P || c->mode == CM_TOP)
4246 {
4247 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
4248 }
e1791bb1
JY
4249#endif
4250
6add6b2f 4251#if PORT_SHARE
81d882d5
DS
4252 /* share OpenVPN port with foreign (such as HTTPS) server */
4253 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
4254 {
4255 init_port_share(c);
4256 }
6add6b2f 4257#endif
81d882d5 4258
47ae8457 4259#ifdef ENABLE_PF
81d882d5
DS
4260 if (child)
4261 {
4262 pf_init_context(c);
4263 }
47ae8457
JY
4264#endif
4265
81d882d5
DS
4266 /* Check for signals */
4267 if (IS_SIG(c))
4268 {
4269 goto sig;
4270 }
6fbf66fa 4271
81d882d5 4272 return;
6fbf66fa 4273
81d882d5
DS
4274sig:
4275 if (!c->sig->signal_text)
4276 {
4277 c->sig->signal_text = "init_instance";
4278 }
4279 close_context(c, -1, flags);
4280 return;
6fbf66fa
JY
4281}
4282
4283/*
4284 * Close a tunnel instance.
4285 */
4286void
81d882d5 4287close_instance(struct context *c)
6fbf66fa 4288{
81d882d5
DS
4289 /* close event objects */
4290 do_close_event_set(c);
6fbf66fa
JY
4291
4292 if (c->mode == CM_P2P
81d882d5
DS
4293 || c->mode == CM_CHILD_TCP
4294 || c->mode == CM_CHILD_UDP
4295 || c->mode == CM_TOP)
4296 {
4297 /* if xinetd/inetd mode, don't allow restart */
4298 do_close_check_if_restart_permitted(c);
6fbf66fa 4299
38d96bd7 4300#ifdef USE_COMP
81d882d5
DS
4301 if (c->c2.comp_context)
4302 {
4303 comp_uninit(c->c2.comp_context);
4304 c->c2.comp_context = NULL;
4305 }
6fbf66fa
JY
4306#endif
4307
81d882d5
DS
4308 /* free buffers */
4309 do_close_free_buf(c);
6fbf66fa 4310
81d882d5
DS
4311 /* close TLS */
4312 do_close_tls(c);
6fbf66fa 4313
81d882d5
DS
4314 /* free key schedules */
4315 do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP));
6fbf66fa 4316
39326238 4317 restore_ncp_options(c);
5fa25eeb 4318
81d882d5
DS
4319 /* close TCP/UDP connection */
4320 do_close_link_socket(c);
6fbf66fa 4321
81d882d5
DS
4322 /* close TUN/TAP device */
4323 do_close_tun(c, false);
6fbf66fa 4324
90efcacb 4325#ifdef MANAGEMENT_DEF_AUTH
81d882d5
DS
4326 if (management)
4327 {
4328 management_notify_client_close(management, &c->c2.mda_context, NULL);
4329 }
90efcacb
JY
4330#endif
4331
47ae8457 4332#ifdef ENABLE_PF
81d882d5 4333 pf_destroy_context(&c->c2.pf);
47ae8457
JY
4334#endif
4335
3c7f2f55 4336#ifdef ENABLE_PLUGIN
81d882d5
DS
4337 /* call plugin close functions and unload */
4338 do_close_plugins(c);
3c7f2f55 4339#endif
6fbf66fa 4340
81d882d5
DS
4341 /* close packet-id persistance file */
4342 do_close_packet_id(c);
6fbf66fa 4343
81d882d5
DS
4344 /* close --status file */
4345 do_close_status_output(c);
6fbf66fa
JY
4346
4347#ifdef ENABLE_FRAGMENT
81d882d5
DS
4348 /* close fragmentation handler */
4349 do_close_fragment(c);
6fbf66fa
JY
4350#endif
4351
81d882d5
DS
4352 /* close --ifconfig-pool-persist obj */
4353 do_close_ifconfig_pool_persist(c);
6fbf66fa 4354
81d882d5
DS
4355 /* free up environmental variable store */
4356 do_env_set_destroy(c);
2a64816b 4357
81d882d5
DS
4358 /* close HTTP or SOCKS proxy */
4359 uninit_proxy(c);
4e9a51d7 4360
81d882d5
DS
4361 /* garbage collect */
4362 gc_free(&c->c2.gc);
4363 }
6fbf66fa
JY
4364}
4365
4366void
81d882d5
DS
4367inherit_context_child(struct context *dest,
4368 const struct context *src)
6fbf66fa 4369{
81d882d5 4370 CLEAR(*dest);
6fbf66fa 4371
81d882d5
DS
4372 /* proto_is_dgram will ASSERT(0) if proto is invalid */
4373 dest->mode = proto_is_dgram(src->options.ce.proto) ? CM_CHILD_UDP : CM_CHILD_TCP;
6fbf66fa 4374
81d882d5 4375 dest->gc = gc_new();
6fbf66fa 4376
81d882d5 4377 ALLOC_OBJ_CLEAR_GC(dest->sig, struct signal_info, &dest->gc);
6fbf66fa 4378
81d882d5
DS
4379 /* c1 init */
4380 packet_id_persist_init(&dest->c1.pid_persist);
6fbf66fa 4381
81d882d5
DS
4382 dest->c1.ks.key_type = src->c1.ks.key_type;
4383 /* inherit SSL context */
4384 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
4385 dest->c1.ks.tls_wrap_key = src->c1.ks.tls_wrap_key;
4386 dest->c1.ks.tls_auth_key_type = src->c1.ks.tls_auth_key_type;
4387 /* inherit pre-NCP ciphers */
4388 dest->c1.ciphername = src->c1.ciphername;
4389 dest->c1.authname = src->c1.authname;
4390 dest->c1.keysize = src->c1.keysize;
81d882d5
DS
4391
4392 /* options */
4393 dest->options = src->options;
4394 options_detach(&dest->options);
4395
4396 if (dest->mode == CM_CHILD_TCP)
6fbf66fa 4397 {
81d882d5
DS
4398 /*
4399 * The CM_TOP context does the socket listen(),
4400 * and the CM_CHILD_TCP context does the accept().
4401 */
4402 dest->c2.accept_from = src->c2.link_socket;
6fbf66fa
JY
4403 }
4404
3c7f2f55 4405#ifdef ENABLE_PLUGIN
81d882d5
DS
4406 /* inherit plugins */
4407 do_inherit_plugins(dest, src);
3c7f2f55 4408#endif
6fbf66fa 4409
81d882d5
DS
4410 /* context init */
4411 init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
4412 if (IS_SIG(dest))
4413 {
4414 return;
4415 }
6fbf66fa 4416
81d882d5
DS
4417 /* inherit tun/tap interface object */
4418 dest->c1.tuntap = src->c1.tuntap;
6fbf66fa 4419
81d882d5
DS
4420 /* UDP inherits some extra things which TCP does not */
4421 if (dest->mode == CM_CHILD_UDP)
6fbf66fa 4422 {
81d882d5
DS
4423 /* inherit buffers */
4424 dest->c2.buffers = src->c2.buffers;
6fbf66fa 4425
81d882d5
DS
4426 /* inherit parent link_socket and tuntap */
4427 dest->c2.link_socket = src->c2.link_socket;
6fbf66fa 4428
81d882d5
DS
4429 ALLOC_OBJ_GC(dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
4430 *dest->c2.link_socket_info = src->c2.link_socket->info;
6fbf66fa 4431
81d882d5
DS
4432 /* locally override some link_socket_info fields */
4433 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
4434 dest->c2.link_socket_info->connection_established = false;
6fbf66fa
JY
4435 }
4436}
4437
4438void
81d882d5
DS
4439inherit_context_top(struct context *dest,
4440 const struct context *src)
6fbf66fa 4441{
81d882d5
DS
4442 /* copy parent */
4443 *dest = *src;
6fbf66fa 4444
81d882d5
DS
4445 /*
4446 * CM_TOP_CLONE will prevent close_instance from freeing or closing
4447 * resources owned by the parent.
4448 *
4449 * Also note that CM_TOP_CLONE context objects are
4450 * closed by multi_top_free in multi.c.
4451 */
4452 dest->mode = CM_TOP_CLONE;
6fbf66fa 4453
81d882d5
DS
4454 dest->first_time = false;
4455 dest->c0 = NULL;
6fbf66fa 4456
81d882d5
DS
4457 options_detach(&dest->options);
4458 gc_detach(&dest->gc);
4459 gc_detach(&dest->c2.gc);
6fbf66fa 4460
81d882d5
DS
4461 /* detach plugins */
4462 dest->plugins_owned = false;
3c7f2f55 4463
81d882d5 4464 dest->c2.tls_multi = NULL;
6fbf66fa 4465
81d882d5
DS
4466 /* detach c1 ownership */
4467 dest->c1.tuntap_owned = false;
4468 dest->c1.status_output_owned = false;
6fbf66fa 4469#if P2MP_SERVER
81d882d5 4470 dest->c1.ifconfig_pool_persist_owned = false;
6fbf66fa 4471#endif
3c7f2f55 4472
81d882d5
DS
4473 /* detach c2 ownership */
4474 dest->c2.event_set_owned = false;
4475 dest->c2.link_socket_owned = false;
4476 dest->c2.buffers_owned = false;
4477 dest->c2.es_owned = false;
6fbf66fa 4478
81d882d5
DS
4479 dest->c2.event_set = NULL;
4480 if (proto_is_dgram(src->options.ce.proto))
4481 {
4482 do_event_set_init(dest, false);
4483 }
38d96bd7
JY
4484
4485#ifdef USE_COMP
81d882d5 4486 dest->c2.comp_context = NULL;
38d96bd7 4487#endif
6fbf66fa
JY
4488}
4489
4490void
81d882d5 4491close_context(struct context *c, int sig, unsigned int flags)
6fbf66fa 4492{
81d882d5
DS
4493 ASSERT(c);
4494 ASSERT(c->sig);
79df31c8 4495
81d882d5
DS
4496 if (sig >= 0)
4497 {
4498 c->sig->signal_received = sig;
4499 }
6fbf66fa 4500
81d882d5 4501 if (c->sig->signal_received == SIGUSR1)
6fbf66fa 4502 {
81d882d5
DS
4503 if ((flags & CC_USR1_TO_HUP)
4504 || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
c058cbff 4505 {
81d882d5
DS
4506 c->sig->signal_received = SIGHUP;
4507 c->sig->signal_text = "close_context usr1 to hup";
c058cbff 4508 }
6fbf66fa
JY
4509 }
4510
81d882d5
DS
4511 if (!(flags & CC_NO_CLOSE))
4512 {
4513 close_instance(c);
4514 }
6fbf66fa 4515
81d882d5
DS
4516 if (flags & CC_GC_FREE)
4517 {
4518 context_gc_free(c);
4519 }
6fbf66fa
JY
4520}
4521
6fbf66fa
JY
4522/*
4523 * Do a loopback test
4524 * on the crypto subsystem.
4525 */
4526static void *
81d882d5 4527test_crypto_thread(void *arg)
6fbf66fa 4528{
81d882d5
DS
4529 struct context *c = (struct context *) arg;
4530 const struct options *options = &c->options;
6fbf66fa 4531
81d882d5
DS
4532 ASSERT(options->test_crypto);
4533 init_verb_mute(c, IVM_LEVEL_1);
4534 context_init_1(c);
4535 next_connection_entry(c);
4536 do_init_crypto_static(c, 0);
6fbf66fa 4537
81d882d5 4538 frame_finalize_options(c, options);
6fbf66fa 4539
81d882d5 4540 test_crypto(&c->c2.crypto_options, &c->c2.frame);
6fbf66fa 4541
81d882d5
DS
4542 key_schedule_free(&c->c1.ks, true);
4543 packet_id_free(&c->c2.crypto_options.packet_id);
6fbf66fa 4544
81d882d5
DS
4545 context_gc_free(c);
4546 return NULL;
6fbf66fa
JY
4547}
4548
6fbf66fa 4549bool
81d882d5 4550do_test_crypto(const struct options *o)
6fbf66fa 4551{
81d882d5 4552 if (o->test_crypto)
6fbf66fa 4553 {
81d882d5 4554 struct context c;
6fbf66fa 4555
81d882d5
DS
4556 /* print version number */
4557 msg(M_INFO, "%s", title_string);
6fbf66fa 4558
81d882d5
DS
4559 context_clear(&c);
4560 c.options = *o;
4561 options_detach(&c.options);
4562 c.first_time = true;
4563 test_crypto_thread((void *) &c);
4564 return true;
6fbf66fa 4565 }
81d882d5 4566 return false;
6fbf66fa 4567}