]> git.ipfire.org Git - thirdparty/openvpn.git/blame - src/openvpn/init.c
Remove -no-cpp-precomp flag from Darwin builds
[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"
a54f37d8 45#include "occ.h"
ce98fd24 46#include "pkcs11.h"
6add6b2f 47#include "ps.h"
e12fe286 48#include "lladdr.h"
e7a65dfb 49#include "ping.h"
ffea644c 50#include "mstats.h"
63dc03d0 51#include "ssl_verify.h"
c6e24fa3 52#include "tls_crypt.h"
a54f37d8 53#include "forward.h"
6fbf66fa
JY
54
55#include "memdbg.h"
56
6fbf66fa 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 542 {
66b9409b 543#ifdef ENABLE_MANAGEMENT
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 {
ccb636c7 1008 char *dev_node = string_alloc(options->dev_node, NULL); /* POSIX basename() implementations may modify its arguments */
81d882d5
DS
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 1036 show_available_tls_ciphers(options->cipher_list,
7aeabadd 1037 options->cipher_list_tls13,
aba75874 1038 options->tls_cert_profile);
81d882d5
DS
1039 }
1040 if (options->show_curves)
1041 {
1042 show_available_curves();
1043 }
1044 return true;
6fbf66fa 1045 }
81d882d5 1046 return false;
6fbf66fa
JY
1047}
1048
1049/*
1050 * Static pre-shared key generation mode?
1051 */
1052bool
81d882d5 1053do_genkey(const struct options *options)
6fbf66fa 1054{
9d59029a 1055 /* should we disable paging? */
0d80b562 1056 if (options->mlock && (options->genkey))
9d59029a
SK
1057 {
1058 platform_mlockall(true);
1059 }
0d80b562
AS
1060
1061 /*
1062 * We do not want user to use --genkey with --secret. In the transistion
1063 * phase we for secret.
1064 */
1065 if (options->genkey && options->genkey_type != GENKEY_SECRET
1066 && options->shared_secret_file)
1067 {
1068 msg(M_USAGE, "Using --genkey type with --secret filename is "
1069 "not supported. Use --genkey type filename instead.");
1070 }
1071 if (options->genkey && options->genkey_type == GENKEY_SECRET)
6fbf66fa 1072 {
81d882d5 1073 int nbits_written;
0d80b562
AS
1074 const char *genkey_filename = options->genkey_filename;
1075 if (options->shared_secret_file && options->genkey_filename)
1076 {
1077 msg(M_USAGE, "You must provide a filename to either --genkey "
1078 "or --secret, not both");
1079 }
6fbf66fa 1080
0d80b562
AS
1081 /*
1082 * Copy filename from shared_secret_file to genkey_filename to support
1083 * the old --genkey --secret foo.file syntax.
1084 */
1085 if (options->shared_secret_file)
1086 {
1087 msg(M_WARN, "WARNING: Using --genkey --secret filename is "
1088 "DEPRECATED. Use --genkey secret filename instead.");
1089 genkey_filename = options->shared_secret_file;
1090 }
6fbf66fa 1091
0d80b562 1092 nbits_written = write_key_file(2, genkey_filename);
a8fa1679
SK
1093 if (nbits_written < 0)
1094 {
1095 msg(M_FATAL, "Failed to write key file");
1096 }
6fbf66fa 1097
81d882d5
DS
1098 msg(D_GENKEY | M_NOPREFIX,
1099 "Randomly generated %d bit key written to %s", nbits_written,
1100 options->shared_secret_file);
1101 return true;
6fbf66fa 1102 }
0d80b562 1103 else if (options->genkey && options->genkey_type == GENKEY_TLS_CRYPTV2_SERVER)
9d59029a 1104 {
0d80b562
AS
1105 tls_crypt_v2_write_server_key_file(options->genkey_filename);
1106 return true;
1107 }
1108 else if (options->genkey && options->genkey_type == GENKEY_TLS_CRYPTV2_CLIENT)
1109 {
1110 if (!options->tls_crypt_v2_file)
9d59029a 1111 {
0d80b562
AS
1112 msg(M_USAGE,
1113 "--genkey tls-crypt-v2-client requires a server key to be set via --tls-crypt-v2 to create a client key");
9d59029a
SK
1114 }
1115
0d80b562
AS
1116 tls_crypt_v2_write_client_key_file(options->genkey_filename,
1117 options->genkey_extra_data, options->tls_crypt_v2_file,
1118 options->tls_crypt_v2_inline);
1119 return true;
1120 }
1121 else
1122 {
1123 return false;
9d59029a 1124 }
6fbf66fa
JY
1125}
1126
1127/*
1128 * Persistent TUN/TAP device management mode?
1129 */
1130bool
dc7fcd71 1131do_persist_tuntap(const struct options *options, openvpn_net_ctx_t *ctx)
6fbf66fa 1132{
81d882d5 1133 if (options->persist_config)
6fbf66fa 1134 {
81d882d5
DS
1135 /* sanity check on options for --mktun or --rmtun */
1136 notnull(options->dev, "TUN/TAP device (--dev)");
1137 if (options->ce.remote || options->ifconfig_local
1138 || options->ifconfig_remote_netmask
81d882d5
DS
1139 || options->shared_secret_file
1140 || options->tls_server || options->tls_client
81d882d5
DS
1141 )
1142 {
1143 msg(M_FATAL|M_OPTERR,
1144 "options --mktun or --rmtun should only be used together with --dev");
1145 }
4ad2b65d 1146#ifdef ENABLE_FEATURE_TUN_PERSIST
81d882d5
DS
1147 tuncfg(options->dev, options->dev_type, options->dev_node,
1148 options->persist_mode,
dc7fcd71
AQ
1149 options->username, options->groupname, &options->tuntap_options,
1150 ctx);
81d882d5
DS
1151 if (options->persist_mode && options->lladdr)
1152 {
1153 set_lladdr(options->dev, options->lladdr, NULL);
1154 }
1155 return true;
1156#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
1157 msg( M_FATAL|M_OPTERR,
1158 "options --mktun and --rmtun are not available on your operating "
1159 "system. Please check 'man tun' (or 'tap'), whether your system "
1160 "supports using 'ifconfig %s create' / 'destroy' to create/remove "
ccb636c7 1161 "persistent tunnel interfaces.", options->dev );
6fbf66fa 1162#endif
4ad2b65d 1163 }
81d882d5 1164 return false;
6fbf66fa
JY
1165}
1166
1167/*
1168 * Should we become a daemon?
1169 * Return true if we did it.
1170 */
da9b2927 1171bool
81d882d5 1172possibly_become_daemon(const struct options *options)
6fbf66fa 1173{
81d882d5 1174 bool ret = false;
7660bba1
CH
1175
1176#ifdef ENABLE_SYSTEMD
81d882d5
DS
1177 /* return without forking if we are running from systemd */
1178 if (sd_notify(0, "READY=0") > 0)
1179 {
1180 return ret;
1181 }
7660bba1
CH
1182#endif
1183
81d882d5 1184 if (options->daemon)
6fbf66fa 1185 {
81d882d5
DS
1186 ASSERT(!options->inetd);
1187 /* Don't chdir immediately, but the end of the init sequence, if needed */
1188 if (daemon(1, options->log) < 0)
1189 {
1190 msg(M_ERR, "daemon() failed or unsupported");
1191 }
1192 restore_signal_state();
1193 if (options->log)
1194 {
1195 set_std_files_to_null(true);
1196 }
6835555e 1197
81d882d5 1198 ret = true;
6fbf66fa 1199 }
81d882d5 1200 return ret;
6fbf66fa
JY
1201}
1202
1203/*
99385447 1204 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
6fbf66fa
JY
1205 */
1206static void
81d882d5 1207do_uid_gid_chroot(struct context *c, bool no_delay)
6fbf66fa 1208{
81d882d5
DS
1209 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
1210 struct context_0 *c0 = c->c0;
6fbf66fa 1211
81d882d5 1212 if (c0 && !c0->uid_gid_chroot_set)
6fbf66fa 1213 {
81d882d5
DS
1214 /* chroot if requested */
1215 if (c->options.chroot_dir)
1216 {
1217 if (no_delay)
65140a3a 1218 {
81d882d5
DS
1219 platform_chroot(c->options.chroot_dir);
1220 }
1221 else if (c->first_time)
1222 {
1223 msg(M_INFO, "NOTE: chroot %s", why_not);
1224 }
1225 }
1226
1227 /* set user and/or group if we want to setuid/setgid */
1228 if (c0->uid_gid_specified)
1229 {
1230 if (no_delay)
1231 {
1232 platform_group_set(&c0->platform_state_group);
1233 platform_user_set(&c0->platform_state_user);
1234 }
1235 else if (c->first_time)
1236 {
1237 msg(M_INFO, "NOTE: UID/GID downgrade %s", why_not);
65140a3a 1238 }
81d882d5 1239 }
99385447 1240
ffea644c 1241#ifdef ENABLE_MEMSTATS
81d882d5
DS
1242 if (c->first_time && c->options.memstats_fn)
1243 {
1244 mstats_open(c->options.memstats_fn);
1245 }
ffea644c
JY
1246#endif
1247
cd5990e0 1248#ifdef ENABLE_SELINUX
81d882d5
DS
1249 /* Apply a SELinux context in order to restrict what OpenVPN can do
1250 * to _only_ what it is supposed to do after initialization is complete
1251 * (basically just network I/O operations). Doing it after chroot
1252 * requires /proc to be mounted in the chroot (which is annoying indeed
1253 * but doing it before requires more complex SELinux policies.
1254 */
1255 if (c->options.selinux_context)
1256 {
1257 if (no_delay)
1258 {
1259 if (-1 == setcon(c->options.selinux_context))
1260 {
1261 msg(M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
1262 }
1263 else
1264 {
1265 msg(M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
1266 }
1267 }
1268 else if (c->first_time)
1269 {
1270 msg(M_INFO, "NOTE: setcon %s", why_not);
1271 }
1272 }
1273#endif
1274
1275 /* Privileges are going to be dropped by now (if requested), be sure
1276 * to prevent any future privilege dropping attempts from now on.
1277 */
1278 if (no_delay)
1279 {
1280 c0->uid_gid_chroot_set = true;
1281 }
6fbf66fa
JY
1282 }
1283}
1284
1285/*
1286 * Return common name in a way that is formatted for
1287 * prepending to msg() output.
1288 */
1289const char *
81d882d5 1290format_common_name(struct context *c, struct gc_arena *gc)
6fbf66fa 1291{
81d882d5 1292 struct buffer out = alloc_buf_gc(256, gc);
81d882d5 1293 if (c->c2.tls_multi)
6fbf66fa 1294 {
81d882d5 1295 buf_printf(&out, "[%s] ", tls_common_name(c->c2.tls_multi, false));
6fbf66fa 1296 }
81d882d5 1297 return BSTR(&out);
6fbf66fa
JY
1298}
1299
1300void
81d882d5 1301pre_setup(const struct options *options)
6fbf66fa 1302{
445b192a 1303#ifdef _WIN32
81d882d5 1304 if (options->exit_event_name)
6fbf66fa 1305 {
81d882d5
DS
1306 win32_signal_open(&win32_signal,
1307 WSO_FORCE_SERVICE,
1308 options->exit_event_name,
1309 options->exit_event_initial_state);
6fbf66fa 1310 }
81d882d5 1311 else
6fbf66fa 1312 {
81d882d5
DS
1313 win32_signal_open(&win32_signal,
1314 WSO_FORCE_CONSOLE,
1315 NULL,
1316 false);
6fbf66fa 1317
81d882d5
DS
1318 /* put a title on the top window bar */
1319 if (win32_signal.mode == WSO_MODE_CONSOLE)
1320 {
1321 window_title_save(&window_title);
1322 window_title_generate(options->config);
1323 }
6fbf66fa 1324 }
81d882d5 1325#endif /* ifdef _WIN32 */
6fbf66fa
JY
1326}
1327
1328void
81d882d5 1329reset_coarse_timers(struct context *c)
6fbf66fa 1330{
81d882d5 1331 c->c2.coarse_timer_wakeup = 0;
6fbf66fa
JY
1332}
1333
f2134b7b
AS
1334/*
1335 * Initialise the server poll timeout timer
1336 * This timer is used in the http/socks proxy setup so it needs to be setup
1337 * before
1338 */
1339static void
81d882d5 1340do_init_server_poll_timeout(struct context *c)
f2134b7b 1341{
81d882d5 1342 update_time();
f2134b7b 1343 if (c->options.ce.connect_timeout)
81d882d5
DS
1344 {
1345 event_timeout_init(&c->c2.server_poll_interval, c->options.ce.connect_timeout, now);
1346 }
f2134b7b
AS
1347}
1348
6fbf66fa
JY
1349/*
1350 * Initialize timers
1351 */
1352static void
81d882d5 1353do_init_timers(struct context *c, bool deferred)
6fbf66fa 1354{
81d882d5
DS
1355 update_time();
1356 reset_coarse_timers(c);
6fbf66fa 1357
81d882d5
DS
1358 /* initialize inactivity timeout */
1359 if (c->options.inactivity_timeout)
1360 {
1361 event_timeout_init(&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
1362 }
6fbf66fa 1363
81d882d5 1364 /* initialize pings */
6fbf66fa 1365
81d882d5
DS
1366 if (c->options.ping_send_timeout)
1367 {
1368 event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
1369 }
6fbf66fa 1370
81d882d5
DS
1371 if (c->options.ping_rec_timeout)
1372 {
1373 event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
1374 }
6fbf66fa 1375
81d882d5 1376 if (!deferred)
6fbf66fa 1377 {
81d882d5
DS
1378 /* initialize connection establishment timer */
1379 event_timeout_init(&c->c2.wait_for_connect, 1, now);
6fbf66fa
JY
1380
1381#ifdef ENABLE_OCC
81d882d5 1382 /* initialize occ timers */
6fbf66fa 1383
81d882d5
DS
1384 if (c->options.occ
1385 && !TLS_MODE(c)
1386 && c->c2.options_string_local && c->c2.options_string_remote)
1387 {
1388 event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
1389 }
6fbf66fa 1390
81d882d5
DS
1391 if (c->options.mtu_test)
1392 {
1393 event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
1394 }
6fbf66fa
JY
1395#endif
1396
81d882d5 1397 /* initialize packet_id persistence timer */
81d882d5
DS
1398 if (c->options.packet_id_file)
1399 {
1400 event_timeout_init(&c->c2.packet_id_persist_interval, 60, now);
1401 }
6fbf66fa 1402
81d882d5
DS
1403 /* initialize tmp_int optimization that limits the number of times we call
1404 * tls_multi_process in the main event loop */
1405 interval_init(&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
6fbf66fa
JY
1406 }
1407}
1408
1409/*
1410 * Initialize traffic shaper.
1411 */
1412static void
81d882d5 1413do_init_traffic_shaper(struct context *c)
6fbf66fa 1414{
3d163bc5 1415#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
1416 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
1417 if (c->options.shaper)
6fbf66fa 1418 {
81d882d5
DS
1419 shaper_init(&c->c2.shaper, c->options.shaper);
1420 shaper_msg(&c->c2.shaper);
6fbf66fa
JY
1421 }
1422#endif
1423}
1424
1425/*
eb95f367
GD
1426 * Allocate route list structures for IPv4 and IPv6
1427 * (we do this for IPv4 even if no --route option has been seen, as other
1428 * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
6fbf66fa
JY
1429 */
1430static void
81d882d5 1431do_alloc_route_list(struct context *c)
6fbf66fa 1432{
81d882d5
DS
1433 if (!c->c1.route_list)
1434 {
1435 ALLOC_OBJ_CLEAR_GC(c->c1.route_list, struct route_list, &c->gc);
1436 }
1437 if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
1438 {
1439 ALLOC_OBJ_CLEAR_GC(c->c1.route_ipv6_list, struct route_ipv6_list, &c->gc);
1440 }
6fbf66fa
JY
1441}
1442
1443
1444/*
1445 * Initialize the route list, resolving any DNS names in route
1446 * options and saving routes in the environment.
1447 */
1448static void
81d882d5
DS
1449do_init_route_list(const struct options *options,
1450 struct route_list *route_list,
1451 const struct link_socket_info *link_socket_info,
aec4a3d1
AQ
1452 struct env_set *es,
1453 openvpn_net_ctx_t *ctx)
6fbf66fa 1454{
81d882d5
DS
1455 const char *gw = NULL;
1456 int dev = dev_type_enum(options->dev, options->dev_type);
1457 int metric = 0;
6fbf66fa 1458
81d882d5
DS
1459 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
1460 {
1461 gw = options->ifconfig_remote_netmask;
1462 }
1463 if (options->route_default_gateway)
1464 {
1465 gw = options->route_default_gateway;
1466 }
1467 if (options->route_default_metric)
1468 {
1469 metric = options->route_default_metric;
1470 }
6fbf66fa 1471
81d882d5
DS
1472 if (init_route_list(route_list,
1473 options->routes,
1474 gw,
1475 metric,
1476 link_socket_current_remote(link_socket_info),
aec4a3d1
AQ
1477 es,
1478 ctx))
6fbf66fa 1479 {
81d882d5
DS
1480 /* copy routes to environment */
1481 setenv_routes(es, route_list);
6fbf66fa
JY
1482 }
1483}
1484
512cda46 1485static void
81d882d5
DS
1486do_init_route_ipv6_list(const struct options *options,
1487 struct route_ipv6_list *route_ipv6_list,
1488 const struct link_socket_info *link_socket_info,
1489 struct env_set *es)
512cda46 1490{
81d882d5
DS
1491 const char *gw = NULL;
1492 int metric = -1; /* no metric set */
512cda46 1493
81d882d5 1494 gw = options->ifconfig_ipv6_remote; /* default GW = remote end */
d24e1b17 1495 if (options->route_ipv6_default_gateway)
81d882d5
DS
1496 {
1497 gw = options->route_ipv6_default_gateway;
1498 }
512cda46 1499
81d882d5
DS
1500 if (options->route_default_metric)
1501 {
1502 metric = options->route_default_metric;
1503 }
512cda46 1504
81d882d5
DS
1505 /* redirect (IPv6) gateway to VPN? if yes, add a few more specifics
1506 */
1507 if (options->routes_ipv6->flags & RG_REROUTE_GW)
d227929b 1508 {
81d882d5
DS
1509 char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
1510 int i;
d227929b 1511
81d882d5
DS
1512 for (i = 0; opt_list[i]; i++)
1513 {
1514 add_route_ipv6_to_option_list( options->routes_ipv6,
1515 string_alloc(opt_list[i], options->routes_ipv6->gc),
1516 NULL, NULL );
1517 }
d227929b
GD
1518 }
1519
81d882d5
DS
1520 if (init_route_ipv6_list(route_ipv6_list,
1521 options->routes_ipv6,
1522 gw,
1523 metric,
1524 link_socket_current_remote_ipv6(link_socket_info),
1525 es))
512cda46 1526 {
81d882d5
DS
1527 /* copy routes to environment */
1528 setenv_routes_ipv6(es, route_ipv6_list);
512cda46
GD
1529 }
1530}
1531
1532
6fbf66fa
JY
1533/*
1534 * Called after all initialization has been completed.
1535 */
1536void
81d882d5 1537initialization_sequence_completed(struct context *c, const unsigned int flags)
6fbf66fa 1538{
81d882d5 1539 static const char message[] = "Initialization Sequence Completed";
6fbf66fa 1540
81d882d5
DS
1541 /* Reset the unsuccessful connection counter on complete initialisation */
1542 c->options.unsuccessful_attempts = 0;
23d61c56 1543
81d882d5
DS
1544 /* If we delayed UID/GID downgrade or chroot, do it now */
1545 do_uid_gid_chroot(c, true);
6fbf66fa 1546
5bde5b6d 1547
57116536
AQ
1548 /*
1549 * In some cases (i.e. when receiving auth-token via
1550 * push-reply) the auth-nocache option configured on the
1551 * client is overridden; for this reason we have to wait
1552 * for the push-reply message before attempting to wipe
1553 * the user/pass entered by the user
1554 */
1555 if (c->options.mode == MODE_POINT_TO_POINT)
1556 {
1557 delayed_auth_pass_purge();
1558 }
1559
81d882d5
DS
1560 /* Test if errors */
1561 if (flags & ISC_ERRORS)
a9c802b2 1562 {
445b192a 1563#ifdef _WIN32
81d882d5
DS
1564 show_routes(M_INFO|M_NOPREFIX);
1565 show_adapters(M_INFO|M_NOPREFIX);
1566 msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
6fbf66fa 1567#else
c5931897 1568#ifdef ENABLE_SYSTEMD
81d882d5 1569 sd_notifyf(0, "STATUS=Failed to start up: %s With Errors\nERRNO=1", message);
c5931897 1570#endif /* HAVE_SYSTEMD_SD_DAEMON_H */
81d882d5 1571 msg(M_INFO, "%s With Errors", message);
6fbf66fa 1572#endif
a9c802b2 1573 }
81d882d5 1574 else
c5931897
CH
1575 {
1576#ifdef ENABLE_SYSTEMD
e83a8684 1577 sd_notifyf(0, "STATUS=%s", message);
c5931897 1578#endif
81d882d5 1579 msg(M_INFO, "%s", message);
c5931897 1580 }
6fbf66fa 1581
81d882d5
DS
1582 /* Flag that we initialized */
1583 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
1584 {
1585 c->options.no_advance = true;
1586 }
6fbf66fa 1587
445b192a 1588#ifdef _WIN32
81d882d5 1589 fork_register_dns_action(c->c1.tuntap);
b90c6f17
JY
1590#endif
1591
6fbf66fa 1592#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1593 /* Tell management interface that we initialized */
1594 if (management)
1595 {
1596 in_addr_t *tun_local = NULL;
1597 struct in6_addr *tun_local6 = NULL;
1598 struct openvpn_sockaddr local, remote;
1599 struct link_socket_actual *actual;
1600 socklen_t sa_len = sizeof(local);
1601 const char *detail = "SUCCESS";
1602 if (flags & ISC_ERRORS)
1603 {
1604 detail = "ERROR";
1605 }
1606
1607 CLEAR(local);
1608 actual = &get_link_socket_info(c)->lsa->actual;
1609 remote = actual->dest;
1610 getsockname(c->c2.link_socket->sd, &local.addr.sa, &sa_len);
2191c471 1611#if ENABLE_IP_PKTINFO
81d882d5 1612 if (!addr_defined(&local))
2191c471 1613 {
81d882d5 1614 switch (local.addr.sa.sa_family)
2191c471 1615 {
81d882d5 1616 case AF_INET:
7efa60d9 1617#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
81d882d5 1618 local.addr.in4.sin_addr = actual->pi.in4.ipi_spec_dst;
4a82a9ac 1619#else
81d882d5 1620 local.addr.in4.sin_addr = actual->pi.in4;
4a82a9ac 1621#endif
81d882d5
DS
1622 break;
1623
1624 case AF_INET6:
1625 local.addr.in6.sin6_addr = actual->pi.in6.ipi6_addr;
1626 break;
2191c471
HH
1627 }
1628 }
1629#endif
1630
81d882d5 1631 if (c->c1.tuntap)
2191c471 1632 {
81d882d5
DS
1633 tun_local = &c->c1.tuntap->local;
1634 tun_local6 = &c->c1.tuntap->local_ipv6;
1635 }
1636 management_set_state(management,
1637 OPENVPN_STATE_CONNECTED,
1638 detail,
1639 tun_local,
1640 tun_local6,
1641 &local,
1642 &remote);
1643 if (tun_local)
1644 {
1645 management_post_tunnel_open(management, *tun_local);
2191c471 1646 }
6fbf66fa 1647 }
81d882d5 1648#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
1649}
1650
1651/*
1652 * Possibly add routes and/or call route-up script
1653 * based on options.
1654 */
1655void
81d882d5
DS
1656do_route(const struct options *options,
1657 struct route_list *route_list,
1658 struct route_ipv6_list *route_ipv6_list,
1659 const struct tuntap *tt,
1660 const struct plugin_list *plugins,
aec4a3d1
AQ
1661 struct env_set *es,
1662 openvpn_net_ctx_t *ctx)
6fbf66fa 1663{
81d882d5 1664 if (!options->route_noexec && ( route_list || route_ipv6_list ) )
15be3202 1665 {
aec4a3d1
AQ
1666 add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options),
1667 es, ctx);
81d882d5 1668 setenv_int(es, "redirect_gateway", route_did_redirect_default_gateway(route_list));
15be3202
JY
1669 }
1670#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1671 if (management)
1672 {
1673 management_up_down(management, "UP", es);
1674 }
15be3202 1675#endif
6fbf66fa 1676
81d882d5 1677 if (plugin_defined(plugins, OPENVPN_PLUGIN_ROUTE_UP))
6fbf66fa 1678 {
81d882d5
DS
1679 if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1680 {
1681 msg(M_WARN, "WARNING: route-up plugin call failed");
1682 }
6fbf66fa
JY
1683 }
1684
81d882d5 1685 if (options->route_script)
6fbf66fa 1686 {
81d882d5
DS
1687 struct argv argv = argv_new();
1688 setenv_str(es, "script_type", "route-up");
1689 argv_parse_cmd(&argv, options->route_script);
1690 openvpn_run_script(&argv, es, 0, "--route-up");
1691 argv_reset(&argv);
6fbf66fa
JY
1692 }
1693
445b192a 1694#ifdef _WIN32
81d882d5 1695 if (options->show_net_up)
6fbf66fa 1696 {
81d882d5
DS
1697 show_routes(M_INFO|M_NOPREFIX);
1698 show_adapters(M_INFO|M_NOPREFIX);
6fbf66fa 1699 }
81d882d5 1700 else if (check_debug_level(D_SHOW_NET))
6fbf66fa 1701 {
81d882d5
DS
1702 show_routes(D_SHOW_NET|M_NOPREFIX);
1703 show_adapters(D_SHOW_NET|M_NOPREFIX);
6fbf66fa
JY
1704 }
1705#endif
1706}
1707
6fbf66fa
JY
1708/*
1709 * initialize tun/tap device object
1710 */
1711static void
81d882d5 1712do_init_tun(struct context *c)
6fbf66fa 1713{
81d882d5
DS
1714 c->c1.tuntap = init_tun(c->options.dev,
1715 c->options.dev_type,
1716 c->options.topology,
1717 c->options.ifconfig_local,
1718 c->options.ifconfig_remote_netmask,
1719 c->options.ifconfig_ipv6_local,
1720 c->options.ifconfig_ipv6_netbits,
1721 c->options.ifconfig_ipv6_remote,
1722 c->c1.link_socket_addr.bind_local,
1723 c->c1.link_socket_addr.remote_list,
1724 !c->options.ifconfig_nowarn,
dc7fcd71
AQ
1725 c->c2.es,
1726 &c->net_ctx);
81d882d5
DS
1727
1728 init_tun_post(c->c1.tuntap,
1729 &c->c2.frame,
1730 &c->options.tuntap_options);
1731
1732 c->c1.tuntap_owned = true;
6fbf66fa
JY
1733}
1734
1735/*
1736 * Open tun/tap device, ifconfig, call up script, etc.
1737 */
1738
1739static bool
81d882d5 1740do_open_tun(struct context *c)
6fbf66fa 1741{
81d882d5
DS
1742 struct gc_arena gc = gc_new();
1743 bool ret = false;
6fbf66fa 1744
bd14d55d 1745#ifndef TARGET_ANDROID
81d882d5 1746 if (!c->c1.tuntap)
6fbf66fa 1747 {
bd14d55d
AS
1748#endif
1749
1750#ifdef TARGET_ANDROID
81d882d5
DS
1751 /* If we emulate persist-tun on android we still have to open a new tun and
1752 * then close the old */
1753 int oldtunfd = -1;
1754 if (c->c1.tuntap)
1755 {
1756 oldtunfd = c->c1.tuntap->fd;
da3f583f
AS
1757 free(c->c1.tuntap);
1758 c->c1.tuntap = NULL;
1759 c->c1.tuntap_owned = false;
81d882d5 1760 }
bd14d55d
AS
1761#endif
1762
81d882d5
DS
1763 /* initialize (but do not open) tun/tap object */
1764 do_init_tun(c);
6fbf66fa 1765
445b192a 1766#ifdef _WIN32
81d882d5
DS
1767 /* store (hide) interactive service handle in tuntap_options */
1768 c->c1.tuntap->options.msg_channel = c->options.msg_channel;
1769 msg(D_ROUTE, "interactive service msg_channel=%u", (unsigned int) c->options.msg_channel);
1770#endif
1771
1772 /* allocate route list structure */
1773 do_alloc_route_list(c);
1774
1775 /* parse and resolve the route option list */
1776 ASSERT(c->c2.link_socket);
1777 if (c->options.routes && c->c1.route_list)
1778 {
1779 do_init_route_list(&c->options, c->c1.route_list,
aec4a3d1 1780 &c->c2.link_socket->info, c->c2.es, &c->net_ctx);
81d882d5
DS
1781 }
1782 if (c->options.routes_ipv6 && c->c1.route_ipv6_list)
1783 {
1784 do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list,
1785 &c->c2.link_socket->info, c->c2.es);
1786 }
1787
1788 /* do ifconfig */
1789 if (!c->options.ifconfig_noexec
1790 && ifconfig_order() == IFCONFIG_BEFORE_TUN_OPEN)
1791 {
1792 /* guess actual tun/tap unit number that will be returned
1793 * by open_tun */
1794 const char *guess = guess_tuntap_dev(c->options.dev,
1795 c->options.dev_type,
1796 c->options.dev_node,
1797 &gc);
dc7fcd71
AQ
1798 do_ifconfig(c->c1.tuntap, guess, TUN_MTU_SIZE(&c->c2.frame), c->c2.es,
1799 &c->net_ctx);
81d882d5
DS
1800 }
1801
1802 /* possibly add routes */
1803 if (route_order() == ROUTE_BEFORE_TUN)
1804 {
94e6a2da 1805 /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
81d882d5 1806 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
aec4a3d1 1807 c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
81d882d5 1808 }
c058cbff 1809#ifdef TARGET_ANDROID
81d882d5
DS
1810 /* Store the old fd inside the fd so open_tun can use it */
1811 c->c1.tuntap->fd = oldtunfd;
1812#endif
1813 /* open the tun device */
1814 open_tun(c->options.dev, c->options.dev_type, c->options.dev_node,
1815 c->c1.tuntap);
1816
1817 /* set the hardware address */
1818 if (c->options.lladdr)
1819 {
1820 set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
1821 }
1822
1823 /* do ifconfig */
1824 if (!c->options.ifconfig_noexec
1825 && ifconfig_order() == IFCONFIG_AFTER_TUN_OPEN)
1826 {
dc7fcd71
AQ
1827 do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name,
1828 TUN_MTU_SIZE(&c->c2.frame), c->c2.es, &c->net_ctx);
81d882d5
DS
1829 }
1830
1831 /* run the up script */
1832 run_up_down(c->options.up_script,
1833 c->plugins,
1834 OPENVPN_PLUGIN_UP,
1835 c->c1.tuntap->actual_name,
445b192a 1836#ifdef _WIN32
81d882d5
DS
1837 c->c1.tuntap->adapter_index,
1838#endif
1839 dev_type_string(c->options.dev, c->options.dev_type),
1840 TUN_MTU_SIZE(&c->c2.frame),
1841 EXPANDED_SIZE(&c->c2.frame),
1842 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1843 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1844 "init",
1845 NULL,
1846 "up",
1847 c->c2.es);
6fbf66fa 1848
445b192a 1849#if defined(_WIN32)
81d882d5
DS
1850 if (c->options.block_outside_dns)
1851 {
1852 dmsg(D_LOW, "Blocking outside DNS");
2282b1be 1853 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
81d882d5
DS
1854 {
1855 msg(M_FATAL, "Blocking DNS failed!");
1856 }
1857 }
38c85658
V
1858#endif
1859
81d882d5
DS
1860 /* possibly add routes */
1861 if ((route_order() == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined))
1862 {
1863 do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
aec4a3d1 1864 c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
81d882d5 1865 }
6fbf66fa 1866
81d882d5
DS
1867 /*
1868 * Did tun/tap driver give us an MTU?
1869 */
1870 if (c->c1.tuntap->post_open_mtu)
1871 {
1872 frame_set_mtu_dynamic(&c->c2.frame,
1873 c->c1.tuntap->post_open_mtu,
1874 SET_MTU_TUN | SET_MTU_UPPER_BOUND);
1875 }
6fbf66fa 1876
81d882d5
DS
1877 ret = true;
1878 static_context = c;
bd14d55d 1879#ifndef TARGET_ANDROID
81d882d5
DS
1880}
1881else
1882{
1883 msg(M_INFO, "Preserving previous TUN/TAP instance: %s",
1884 c->c1.tuntap->actual_name);
6fbf66fa 1885
81d882d5
DS
1886 /* explicitly set the ifconfig_* env vars */
1887 do_ifconfig_setenv(c->c1.tuntap, c->c2.es);
db950be8 1888
81d882d5
DS
1889 /* run the up script if user specified --up-restart */
1890 if (c->options.up_restart)
1891 {
1892 run_up_down(c->options.up_script,
1893 c->plugins,
1894 OPENVPN_PLUGIN_UP,
1895 c->c1.tuntap->actual_name,
445b192a 1896#ifdef _WIN32
81d882d5
DS
1897 c->c1.tuntap->adapter_index,
1898#endif
1899 dev_type_string(c->options.dev, c->options.dev_type),
1900 TUN_MTU_SIZE(&c->c2.frame),
1901 EXPANDED_SIZE(&c->c2.frame),
1902 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
1903 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1904 "restart",
1905 NULL,
1906 "up",
1907 c->c2.es);
1908 }
445b192a 1909#if defined(_WIN32)
81d882d5
DS
1910 if (c->options.block_outside_dns)
1911 {
1912 dmsg(D_LOW, "Blocking outside DNS");
1913 if (!win_wfp_block_dns(c->c1.tuntap->adapter_index, c->options.msg_channel))
451d2177 1914 {
81d882d5 1915 msg(M_FATAL, "Blocking DNS failed!");
451d2177 1916 }
6fbf66fa 1917 }
bd14d55d 1918#endif
81d882d5
DS
1919
1920}
1921#endif /* ifndef TARGET_ANDROID */
1922 gc_free(&gc);
1923 return ret;
6fbf66fa
JY
1924}
1925
1926/*
1927 * Close TUN/TAP device
1928 */
1929
1930static void
81d882d5 1931do_close_tun_simple(struct context *c)
6fbf66fa 1932{
81d882d5 1933 msg(D_CLOSE, "Closing TUN/TAP interface");
0bea472c
AQ
1934 if (c->c1.tuntap)
1935 {
dc7fcd71 1936 close_tun(c->c1.tuntap, &c->net_ctx);
0bea472c
AQ
1937 c->c1.tuntap = NULL;
1938 }
81d882d5 1939 c->c1.tuntap_owned = false;
6fbf66fa 1940#if P2MP
81d882d5 1941 CLEAR(c->c1.pulled_options_digest_save);
6fbf66fa
JY
1942#endif
1943}
1944
1945static void
81d882d5 1946do_close_tun(struct context *c, bool force)
6fbf66fa 1947{
81d882d5
DS
1948 struct gc_arena gc = gc_new();
1949 if (c->c1.tuntap && c->c1.tuntap_owned)
6fbf66fa 1950 {
81d882d5 1951 const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc);
445b192a 1952#ifdef _WIN32
81d882d5 1953 DWORD adapter_index = c->c1.tuntap->adapter_index;
9dff2c1f 1954#endif
81d882d5
DS
1955 const in_addr_t local = c->c1.tuntap->local;
1956 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
6fbf66fa 1957
81d882d5
DS
1958 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
1959 {
1960 static_context = NULL;
0c9eb1d3 1961
6fbf66fa 1962#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1963 /* tell management layer we are about to close the TUN/TAP device */
1964 if (management)
1965 {
1966 management_pre_tunnel_close(management);
1967 management_up_down(management, "DOWN", c->c2.es);
1968 }
1969#endif
1970
1971 /* delete any routes we added */
1972 if (c->c1.route_list || c->c1.route_ipv6_list)
1973 {
1974 run_up_down(c->options.route_predown_script,
1975 c->plugins,
1976 OPENVPN_PLUGIN_ROUTE_PREDOWN,
1977 tuntap_actual,
445b192a 1978#ifdef _WIN32
81d882d5
DS
1979 adapter_index,
1980#endif
1981 NULL,
1982 TUN_MTU_SIZE(&c->c2.frame),
1983 EXPANDED_SIZE(&c->c2.frame),
1984 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
1985 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
1986 "init",
1987 signal_description(c->sig->signal_received,
415421c2 1988 c->sig->signal_text),
81d882d5
DS
1989 "route-pre-down",
1990 c->c2.es);
415421c2 1991
81d882d5 1992 delete_routes(c->c1.route_list, c->c1.route_ipv6_list,
aec4a3d1
AQ
1993 c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options),
1994 c->c2.es, &c->net_ctx);
415421c2 1995 }
6fbf66fa 1996
81d882d5
DS
1997 /* actually close tun/tap device based on --down-pre flag */
1998 if (!c->options.down_pre)
1999 {
2000 do_close_tun_simple(c);
2001 }
6fbf66fa 2002
81d882d5
DS
2003 /* Run the down script -- note that it will run at reduced
2004 * privilege if, for example, "--user nobody" was used. */
2005 run_up_down(c->options.down_script,
2006 c->plugins,
2007 OPENVPN_PLUGIN_DOWN,
2008 tuntap_actual,
445b192a 2009#ifdef _WIN32
81d882d5
DS
2010 adapter_index,
2011#endif
2012 NULL,
2013 TUN_MTU_SIZE(&c->c2.frame),
2014 EXPANDED_SIZE(&c->c2.frame),
2015 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2016 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2017 "init",
2018 signal_description(c->sig->signal_received,
2019 c->sig->signal_text),
2020 "down",
2021 c->c2.es);
6fbf66fa 2022
445b192a 2023#if defined(_WIN32)
38c85658
V
2024 if (c->options.block_outside_dns)
2025 {
27aa8728 2026 if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
81d882d5
DS
2027 {
2028 msg(M_FATAL, "Uninitialising WFP failed!");
2029 }
38c85658
V
2030 }
2031#endif
2032
81d882d5
DS
2033 /* actually close tun/tap device based on --down-pre flag */
2034 if (c->options.down_pre)
2035 {
2036 do_close_tun_simple(c);
2037 }
2038 }
2039 else
2040 {
2041 /* run the down script on this restart if --up-restart was specified */
2042 if (c->options.up_restart)
2043 {
2044 run_up_down(c->options.down_script,
2045 c->plugins,
2046 OPENVPN_PLUGIN_DOWN,
2047 tuntap_actual,
445b192a 2048#ifdef _WIN32
81d882d5
DS
2049 adapter_index,
2050#endif
2051 NULL,
2052 TUN_MTU_SIZE(&c->c2.frame),
2053 EXPANDED_SIZE(&c->c2.frame),
2054 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2055 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2056 "restart",
2057 signal_description(c->sig->signal_received,
2058 c->sig->signal_text),
2059 "down",
2060 c->c2.es);
2061 }
451d2177 2062
445b192a 2063#if defined(_WIN32)
81d882d5 2064 if (c->options.block_outside_dns)
451d2177 2065 {
27aa8728 2066 if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
81d882d5
DS
2067 {
2068 msg(M_FATAL, "Uninitialising WFP failed!");
2069 }
451d2177
SN
2070 }
2071#endif
2072
81d882d5 2073 }
6fbf66fa 2074 }
81d882d5 2075 gc_free(&gc);
6fbf66fa
JY
2076}
2077
0c9eb1d3 2078void
e2a0cad4 2079tun_abort(void)
0c9eb1d3 2080{
81d882d5
DS
2081 struct context *c = static_context;
2082 if (c)
0c9eb1d3 2083 {
81d882d5
DS
2084 static_context = NULL;
2085 do_close_tun(c, true);
0c9eb1d3
JY
2086 }
2087}
2088
6fbf66fa
JY
2089/*
2090 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
2091 */
2092
827de237
SK
2093#if P2MP
2094/**
2095 * Helper for do_up(). Take two option hashes and return true if they are not
2096 * equal, or either one is all-zeroes.
2097 */
2098static bool
5b48e8c9
SK
2099options_hash_changed_or_zero(const struct sha256_digest *a,
2100 const struct sha256_digest *b)
827de237 2101{
5b48e8c9
SK
2102 const struct sha256_digest zero = {{0}};
2103 return memcmp(a, b, sizeof(struct sha256_digest))
2104 || !memcmp(a, &zero, sizeof(struct sha256_digest));
827de237
SK
2105}
2106#endif /* P2MP */
2107
d728ebed 2108bool
81d882d5 2109do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
6fbf66fa 2110{
81d882d5 2111 if (!c->c2.do_up_ran)
6fbf66fa 2112 {
81d882d5 2113 reset_coarse_timers(c);
6fbf66fa 2114
bd230079 2115 if (pulled_options)
81d882d5
DS
2116 {
2117 if (!do_deferred_options(c, option_types_found))
2118 {
2119 msg(D_PUSH_ERRORS, "ERROR: Failed to apply push options");
2120 return false;
2121 }
2122 }
6fbf66fa 2123
81d882d5
DS
2124 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
2125 if (c->options.up_delay || PULL_DEFINED(&c->options))
2126 {
2127 c->c2.did_open_tun = do_open_tun(c);
2128 update_time();
6fbf66fa
JY
2129
2130#if P2MP
81d882d5
DS
2131 /*
2132 * Was tun interface object persisted from previous restart iteration,
2133 * and if so did pulled options string change from previous iteration?
2134 */
2135 if (!c->c2.did_open_tun
2136 && PULL_DEFINED(&c->options)
2137 && c->c1.tuntap
2138 && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save,
2139 &c->c2.pulled_options_digest))
2140 {
2141 /* if so, close tun, delete routes, then reinitialize tun and add routes */
2142 msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
2143 do_close_tun(c, true);
45b2af9c 2144 management_sleep(1);
81d882d5
DS
2145 c->c2.did_open_tun = do_open_tun(c);
2146 update_time();
2147 }
2148#endif
2149 }
2150
2151 if (c->c2.did_open_tun)
2152 {
6fbf66fa 2153#if P2MP
81d882d5
DS
2154 c->c1.pulled_options_digest_save = c->c2.pulled_options_digest;
2155#endif
2156
2157 /* if --route-delay was specified, start timer */
2158 if ((route_order() == ROUTE_AFTER_TUN) && c->options.route_delay_defined)
2159 {
2160 event_timeout_init(&c->c2.route_wakeup, c->options.route_delay, now);
2161 event_timeout_init(&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
2162 if (c->c1.tuntap)
2163 {
2164 tun_standby_init(c->c1.tuntap);
2165 }
2166 }
2167 else
2168 {
2169 initialization_sequence_completed(c, 0); /* client/p2p --route-delay undefined */
2170 }
2171 }
2172 else if (c->options.mode == MODE_POINT_TO_POINT)
2173 {
2174 initialization_sequence_completed(c, 0); /* client/p2p restart with --persist-tun */
2175 }
2176
2177 c->c2.do_up_ran = true;
2178 }
2179 return true;
6fbf66fa
JY
2180}
2181
2182/*
2183 * These are the option categories which will be accepted by pull.
2184 */
2185unsigned int
81d882d5
DS
2186pull_permission_mask(const struct context *c)
2187{
2188 unsigned int flags =
2189 OPT_P_UP
2190 | OPT_P_ROUTE_EXTRAS
2191 | OPT_P_SOCKBUF
2192 | OPT_P_SOCKFLAGS
2193 | OPT_P_SETENV
2194 | OPT_P_SHAPER
2195 | OPT_P_TIMER
2196 | OPT_P_COMP
2197 | OPT_P_PERSIST
2198 | OPT_P_MESSAGES
2199 | OPT_P_EXPLICIT_NOTIFY
2200 | OPT_P_ECHO
2201 | OPT_P_PULL_MODE
2202 | OPT_P_PEER_ID;
2203
2204 if (!c->options.route_nopull)
2205 {
2206 flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);
2207 }
3c7f2f55 2208
81d882d5
DS
2209 if (c->options.ncp_enabled)
2210 {
2211 flags |= OPT_P_NCP;
2212 }
d728ebed 2213
81d882d5 2214 return flags;
6fbf66fa
JY
2215}
2216
2217/*
2218 * Handle non-tun-related pulled options.
2219 */
d728ebed 2220bool
81d882d5 2221do_deferred_options(struct context *c, const unsigned int found)
6fbf66fa 2222{
81d882d5 2223 if (found & OPT_P_MESSAGES)
6fbf66fa 2224 {
81d882d5
DS
2225 init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_2);
2226 msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
6fbf66fa 2227 }
81d882d5 2228 if (found & OPT_P_TIMER)
6fbf66fa 2229 {
81d882d5
DS
2230 do_init_timers(c, true);
2231 msg(D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
6fbf66fa
JY
2232 }
2233
2234#ifdef ENABLE_OCC
81d882d5 2235 if (found & OPT_P_EXPLICIT_NOTIFY)
6fbf66fa 2236 {
81d882d5
DS
2237 if (!proto_is_udp(c->options.ce.proto) && c->options.ce.explicit_exit_notification)
2238 {
2239 msg(D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
2240 c->options.ce.explicit_exit_notification = 0;
2241 }
2242 else
2243 {
2244 msg(D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
2245 }
6fbf66fa
JY
2246 }
2247#endif
2248
38d96bd7 2249#ifdef USE_COMP
81d882d5 2250 if (found & OPT_P_COMP)
537073fd 2251 {
81d882d5
DS
2252 msg(D_PUSH, "OPTIONS IMPORT: compression parms modified");
2253 comp_uninit(c->c2.comp_context);
2254 c->c2.comp_context = comp_init(&c->options.comp);
537073fd
JY
2255 }
2256#endif
2257
81d882d5 2258 if (found & OPT_P_SHAPER)
6fbf66fa 2259 {
81d882d5
DS
2260 msg(D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
2261 do_init_traffic_shaper(c);
6fbf66fa
JY
2262 }
2263
81d882d5 2264 if (found & OPT_P_SOCKBUF)
00d39170 2265 {
81d882d5
DS
2266 msg(D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
2267 link_socket_update_buffer_sizes(c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
00d39170
JY
2268 }
2269
81d882d5 2270 if (found & OPT_P_SOCKFLAGS)
00d39170 2271 {
81d882d5
DS
2272 msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
2273 link_socket_update_flags(c->c2.link_socket, c->options.sockflags);
00d39170
JY
2274 }
2275
81d882d5
DS
2276 if (found & OPT_P_PERSIST)
2277 {
2278 msg(D_PUSH, "OPTIONS IMPORT: --persist options modified");
2279 }
2280 if (found & OPT_P_UP)
2281 {
2282 msg(D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
2283 }
2284 if (found & OPT_P_ROUTE)
2285 {
2286 msg(D_PUSH, "OPTIONS IMPORT: route options modified");
2287 }
2288 if (found & OPT_P_ROUTE_EXTRAS)
2289 {
2290 msg(D_PUSH, "OPTIONS IMPORT: route-related options modified");
2291 }
2292 if (found & OPT_P_IPWIN32)
2293 {
2294 msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
2295 }
2296 if (found & OPT_P_SETENV)
2297 {
2298 msg(D_PUSH, "OPTIONS IMPORT: environment modified");
2299 }
65eedc35 2300
81d882d5
DS
2301 if (found & OPT_P_PEER_ID)
2302 {
2303 msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
2304 c->c2.tls_multi->use_peer_id = true;
2305 c->c2.tls_multi->peer_id = c->options.peer_id;
2306 frame_add_to_extra_frame(&c->c2.frame, +3); /* peer-id overhead */
2307 if (!c->options.ce.link_mtu_defined)
2308 {
2309 frame_add_to_link_mtu(&c->c2.frame, +3);
2310 msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
2311 EXPANDED_SIZE(&c->c2.frame));
2312 }
2313 else
2314 {
2315 msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
2316 " fixed by config - reducing tun-mtu to %d, expect"
2317 " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
2318 }
2319 }
2320
2321 /* process (potentially pushed) crypto options */
2322 if (c->options.pull)
2323 {
2324 struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2325 if (found & OPT_P_NCP)
2326 {
2327 msg(D_PUSH, "OPTIONS IMPORT: data channel crypto options modified");
2328 }
2329 else if (c->options.ncp_enabled)
2330 {
2331 tls_poor_mans_ncp(&c->options, c->c2.tls_multi->remote_ciphername);
2332 }
2333 /* Do not regenerate keys if server sends an extra push reply */
2334 if (!session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized
2335 && !tls_session_update_crypto_params(session, &c->options, &c->c2.frame))
2336 {
2337 msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options");
2338 return false;
2339 }
2340 }
c7ca9133 2341
81d882d5 2342 return true;
6fbf66fa
JY
2343}
2344
2345/*
396d30c2
AS
2346 * Possible hold on initialization, holdtime is the
2347 * time OpenVPN would wait without management
6fbf66fa
JY
2348 */
2349static bool
81d882d5 2350do_hold(int holdtime)
6fbf66fa
JY
2351{
2352#ifdef ENABLE_MANAGEMENT
81d882d5 2353 if (management)
6fbf66fa 2354 {
81d882d5
DS
2355 /* block until management hold is released */
2356 if (management_hold(management, holdtime))
2357 {
2358 return true;
2359 }
6fbf66fa
JY
2360 }
2361#endif
81d882d5 2362 return false;
6fbf66fa
JY
2363}
2364
2365/*
2366 * Sleep before restart.
2367 */
2368static void
81d882d5 2369socket_restart_pause(struct context *c)
6fbf66fa 2370{
81d882d5
DS
2371 int sec = 2;
2372 int backoff = 0;
6fbf66fa 2373
81d882d5 2374 switch (c->options.ce.proto)
6fbf66fa 2375 {
81d882d5
DS
2376 case PROTO_TCP_SERVER:
2377 sec = 1;
2378 break;
2379
2380 case PROTO_UDP:
2381 case PROTO_TCP_CLIENT:
2382 sec = c->options.ce.connect_retry_seconds;
2383 break;
6fbf66fa
JY
2384 }
2385
2386#ifdef ENABLE_DEBUG
81d882d5
DS
2387 if (GREMLIN_CONNECTION_FLOOD_LEVEL(c->options.gremlin))
2388 {
2389 sec = 0;
2390 }
6fbf66fa
JY
2391#endif
2392
2393#if P2MP
81d882d5
DS
2394 if (auth_retry_get() == AR_NOINTERACT)
2395 {
2396 sec = 10;
2397 }
6fbf66fa
JY
2398#endif
2399
81d882d5
DS
2400 /* Slow down reconnection after 5 retries per remote -- for tcp only in client mode */
2401 if (c->options.ce.proto != PROTO_TCP_SERVER)
5d429efd 2402 {
81d882d5
DS
2403 backoff = (c->options.unsuccessful_attempts / c->options.connection_list->len) - 4;
2404 if (backoff > 0)
5d429efd 2405 {
81d882d5
DS
2406 /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */
2407 sec = max_int(sec, 1) << min_int(backoff, 15);
5d429efd
SN
2408 }
2409
81d882d5
DS
2410 if (sec > c->options.ce.connect_retry_seconds_max)
2411 {
2412 sec = c->options.ce.connect_retry_seconds_max;
2413 }
5d429efd
SN
2414 }
2415
81d882d5
DS
2416 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
2417 {
2418 sec = c->persist.restart_sleep_seconds;
2419 }
2420 else if (c->persist.restart_sleep_seconds == -1)
2421 {
2422 sec = 0;
2423 }
2424 c->persist.restart_sleep_seconds = 0;
a9c802b2 2425
ccb636c7 2426 /* do management hold on context restart, i.e. second, third, fourth, etc. initialization */
81d882d5
DS
2427 if (do_hold(sec))
2428 {
2429 sec = 0;
2430 }
6fbf66fa 2431
81d882d5 2432 if (sec)
6fbf66fa 2433 {
81d882d5 2434 msg(D_RESTART, "Restart pause, %d second(s)", sec);
45b2af9c 2435 management_sleep(sec);
6fbf66fa
JY
2436 }
2437}
2438
2439/*
2440 * Do a possible pause on context_2 initialization.
2441 */
2442static void
81d882d5 2443do_startup_pause(struct context *c)
6fbf66fa 2444{
81d882d5
DS
2445 if (!c->first_time)
2446 {
2447 socket_restart_pause(c);
2448 }
2449 else
2450 {
2451 do_hold(0); /* do management hold on first context initialization */
2452 }
6fbf66fa
JY
2453}
2454
2455/*
2456 * Finalize MTU parameters based on command line or config file options.
2457 */
2458static void
81d882d5 2459frame_finalize_options(struct context *c, const struct options *o)
6fbf66fa 2460{
81d882d5
DS
2461 if (!o)
2462 {
2463 o = &c->options;
2464 }
6fbf66fa 2465
81d882d5
DS
2466 /*
2467 * Set adjustment factor for buffer alignment when no
2468 * cipher is used.
2469 */
2470 if (!CIPHER_ENABLED(c))
6fbf66fa 2471 {
81d882d5
DS
2472 frame_align_to_extra_frame(&c->c2.frame);
2473 frame_or_align_flags(&c->c2.frame,
2474 FRAME_HEADROOM_MARKER_FRAGMENT
2475 |FRAME_HEADROOM_MARKER_READ_LINK
2476 |FRAME_HEADROOM_MARKER_READ_STREAM);
6fbf66fa 2477 }
81d882d5
DS
2478
2479 frame_add_to_extra_buffer(&c->c2.frame, PAYLOAD_ALIGN);
2480 frame_finalize(&c->c2.frame,
2481 o->ce.link_mtu_defined,
2482 o->ce.link_mtu,
2483 o->ce.tun_mtu_defined,
2484 o->ce.tun_mtu);
6fbf66fa
JY
2485}
2486
2487/*
2488 * Free a key schedule, including OpenSSL components.
2489 */
2490static void
81d882d5 2491key_schedule_free(struct key_schedule *ks, bool free_ssl_ctx)
6fbf66fa 2492{
81d882d5
DS
2493 free_key_ctx_bi(&ks->static_key);
2494 if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
6fbf66fa 2495 {
81d882d5 2496 tls_ctx_free(&ks->ssl_ctx);
19dffdbd 2497 free_key_ctx(&ks->tls_crypt_v2_server_key);
6fbf66fa 2498 }
81d882d5 2499 CLEAR(*ks);
6fbf66fa
JY
2500}
2501
6fbf66fa 2502static void
81d882d5 2503init_crypto_pre(struct context *c, const unsigned int flags)
6fbf66fa 2504{
81d882d5
DS
2505 if (c->options.engine)
2506 {
2507 crypto_init_lib_engine(c->options.engine);
2508 }
6fbf66fa 2509
81d882d5 2510 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
6fbf66fa 2511 {
81d882d5
DS
2512 /* load a persisted packet-id for cross-session replay-protection */
2513 if (c->options.packet_id_file)
2514 {
2515 packet_id_persist_load(&c->c1.pid_persist, c->options.packet_id_file);
2516 }
6fbf66fa
JY
2517 }
2518
0f25d296 2519#ifdef ENABLE_PREDICTION_RESISTANCE
81d882d5
DS
2520 if (c->options.use_prediction_resistance)
2521 {
2522 rand_ctx_enable_prediction_resistance();
2523 }
0f25d296
AJ
2524#endif
2525
6fbf66fa
JY
2526}
2527
2528/*
2529 * Static Key Mode (using a pre-shared key)
2530 */
2531static void
81d882d5 2532do_init_crypto_static(struct context *c, const unsigned int flags)
6fbf66fa 2533{
81d882d5
DS
2534 const struct options *options = &c->options;
2535 ASSERT(options->shared_secret_file);
6fbf66fa 2536
81d882d5 2537 init_crypto_pre(c, flags);
2d9c6d20 2538
81d882d5 2539 /* Initialize flags */
81d882d5 2540 if (c->options.mute_replay_warnings)
6fbf66fa 2541 {
81d882d5 2542 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
6fbf66fa
JY
2543 }
2544
81d882d5
DS
2545 /* Initialize packet ID tracking */
2546 if (options->replay)
6fbf66fa 2547 {
81d882d5
DS
2548 packet_id_init(&c->c2.crypto_options.packet_id,
2549 options->replay_window,
2550 options->replay_time,
2551 "STATIC", 0);
2552 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
2553 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
2554 packet_id_persist_load_obj(&c->c1.pid_persist,
2555 &c->c2.crypto_options.packet_id);
2556 }
6fbf66fa 2557
81d882d5
DS
2558 if (!key_ctx_bi_defined(&c->c1.ks.static_key))
2559 {
2560 /* Get cipher & hash algorithms */
2561 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2562 options->keysize, options->test_crypto, true);
2563
2564 /* Read cipher and hmac keys from shared secret file */
2565 crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key,
2566 options->shared_secret_file,
2567 options->shared_secret_file_inline,
2568 options->key_direction, "Static Key Encryption",
2569 "secret");
6fbf66fa 2570 }
81d882d5 2571 else
6fbf66fa 2572 {
81d882d5 2573 msg(M_INFO, "Re-using pre-shared static key");
6fbf66fa
JY
2574 }
2575
81d882d5
DS
2576 /* Get key schedule */
2577 c->c2.crypto_options.key_ctx_bi = c->c1.ks.static_key;
6fbf66fa 2578
81d882d5 2579 /* Compute MTU parameters */
ef910e3e
SK
2580 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
2581 options->replay, true);
6fbf66fa 2582
ef910e3e
SK
2583 /* Sanity check on sequence number, and cipher mode options */
2584 check_replay_consistency(&c->c1.ks.key_type, options->replay);
6fbf66fa
JY
2585}
2586
5817b49b
AQ
2587/*
2588 * Initialize the tls-auth/crypt key context
2589 */
2590static void
2591do_init_tls_wrap_key(struct context *c)
2592{
2593 const struct options *options = &c->options;
2594
2595 /* TLS handshake authentication (--tls-auth) */
57d6f103 2596 if (options->ce.tls_auth_file)
5817b49b
AQ
2597 {
2598 /* Initialize key_type for tls-auth with auth only */
2599 CLEAR(c->c1.ks.tls_auth_key_type);
2600 if (!streq(options->authname, "none"))
2601 {
2602 c->c1.ks.tls_auth_key_type.digest = md_kt_get(options->authname);
f57431cd
GD
2603 c->c1.ks.tls_auth_key_type.hmac_length =
2604 md_kt_size(c->c1.ks.tls_auth_key_type.digest);
5817b49b
AQ
2605 }
2606 else
2607 {
2608 msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth "
2609 "algorithm specified ('%s')", options->authname);
2610 }
2611
2612 crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type,
2613 &c->c1.ks.tls_wrap_key,
57d6f103
AQ
2614 options->ce.tls_auth_file,
2615 options->ce.tls_auth_file_inline,
2616 options->ce.key_direction,
5817b49b
AQ
2617 "Control Channel Authentication", "tls-auth");
2618 }
2619
2620 /* TLS handshake encryption+authentication (--tls-crypt) */
57d6f103 2621 if (options->ce.tls_crypt_file)
5817b49b
AQ
2622 {
2623 tls_crypt_init_key(&c->c1.ks.tls_wrap_key,
57d6f103
AQ
2624 options->ce.tls_crypt_file,
2625 options->ce.tls_crypt_inline, options->tls_server);
5817b49b 2626 }
19d6d9c3
SK
2627
2628 /* tls-crypt with client-specific keys (--tls-crypt-v2) */
2629 if (options->ce.tls_crypt_v2_file)
2630 {
2631 if (options->tls_server)
2632 {
2633 tls_crypt_v2_init_server_key(&c->c1.ks.tls_crypt_v2_server_key,
2634 true, options->ce.tls_crypt_v2_file,
2635 options->ce.tls_crypt_v2_inline);
2636 }
2637 else
2638 {
2639 tls_crypt_v2_init_client_key(&c->c1.ks.tls_wrap_key,
2640 &c->c1.ks.tls_crypt_v2_wkc,
2641 options->ce.tls_crypt_v2_file,
2642 options->ce.tls_crypt_v2_inline);
2643 }
2644 }
2645
2646
5817b49b
AQ
2647}
2648
6fbf66fa
JY
2649/*
2650 * Initialize the persistent component of OpenVPN's TLS mode,
2651 * which is preserved across SIGUSR1 resets.
2652 */
2653static void
81d882d5 2654do_init_crypto_tls_c1(struct context *c)
6fbf66fa 2655{
81d882d5 2656 const struct options *options = &c->options;
6fbf66fa 2657
81d882d5 2658 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
6fbf66fa 2659 {
81d882d5
DS
2660 /*
2661 * Initialize the OpenSSL library's global
2662 * SSL context.
2663 */
2664 init_ssl(options, &(c->c1.ks.ssl_ctx));
2665 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
2666 {
6fbf66fa 2667#if P2MP
81d882d5
DS
2668 switch (auth_retry_get())
2669 {
2670 case AR_NONE:
2671 msg(M_FATAL, "Error: private key password verification failed");
2672 break;
2673
2674 case AR_INTERACT:
2675 ssl_purge_auth(false);
2676
2677 case AR_NOINTERACT:
2678 c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
2679 break;
2680
2681 default:
2682 ASSERT(0);
2683 }
2684 c->sig->signal_text = "private-key-password-failure";
2685 return;
2686#else /* if P2MP */
2687 msg(M_FATAL, "Error: private key password verification failed");
f57431cd 2688#endif /* if P2MP */
81d882d5
DS
2689 }
2690
2691 /* Get cipher & hash algorithms */
2692 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
2693 options->keysize, true, true);
2694
2695 /* Initialize PRNG with config-specified digest */
2696 prng_init(options->prng_hash, options->prng_nonce_secret_len);
2697
19d6d9c3 2698 /* initialize tls-auth/crypt/crypt-v2 key */
5817b49b 2699 do_init_tls_wrap_key(c);
81d882d5 2700
1f4309ae 2701#if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
81d882d5
DS
2702 if (options->priv_key_file_inline)
2703 {
2704 string_clear(c->options.priv_key_file_inline);
2705 c->options.priv_key_file_inline = NULL;
2706 }
d40f2b20 2707#endif
6fbf66fa 2708 }
81d882d5 2709 else
6fbf66fa 2710 {
81d882d5 2711 msg(D_INIT_MEDIUM, "Re-using SSL/TLS context");
129d2924 2712
5817b49b
AQ
2713 /*
2714 * tls-auth/crypt key can be configured per connection block, therefore
2715 * we must reload it as it may have changed
2716 */
2717 do_init_tls_wrap_key(c);
6fbf66fa
JY
2718 }
2719}
2720
2721static void
81d882d5 2722do_init_crypto_tls(struct context *c, const unsigned int flags)
6fbf66fa 2723{
81d882d5
DS
2724 const struct options *options = &c->options;
2725 struct tls_options to;
2726 bool packet_id_long_form;
6fbf66fa 2727
81d882d5
DS
2728 ASSERT(options->tls_server || options->tls_client);
2729 ASSERT(!options->test_crypto);
6fbf66fa 2730
81d882d5 2731 init_crypto_pre(c, flags);
6fbf66fa 2732
81d882d5
DS
2733 /* Make sure we are either a TLS client or server but not both */
2734 ASSERT(options->tls_server == !options->tls_client);
6fbf66fa 2735
81d882d5
DS
2736 /* initialize persistent component */
2737 do_init_crypto_tls_c1(c);
2738 if (IS_SIG(c))
2739 {
2740 return;
2741 }
2742
ef910e3e
SK
2743 /* Sanity check on sequence number, and cipher mode options */
2744 check_replay_consistency(&c->c1.ks.key_type, options->replay);
81d882d5
DS
2745
2746 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
2747 packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher);
2748
2749 /* Compute MTU parameters (postpone if we push/pull options) */
2750 if (c->options.pull || c->options.mode == MODE_SERVER)
2751 {
2752 /* Account for worst-case crypto overhead before allocating buffers */
2753 frame_add_to_extra_frame(&c->c2.frame, crypto_max_overhead());
2754 }
2755 else
2756 {
2757 crypto_adjust_frame_parameters(&c->c2.frame, &c->c1.ks.key_type,
ef910e3e 2758 options->replay, packet_id_long_form);
81d882d5
DS
2759 }
2760 tls_adjust_frame_parameters(&c->c2.frame);
6fbf66fa 2761
81d882d5
DS
2762 /* Set all command-line TLS-related options */
2763 CLEAR(to);
2764
81d882d5
DS
2765 if (options->mute_replay_warnings)
2766 {
2767 to.crypto_flags |= CO_MUTE_REPLAY_WARNINGS;
2768 }
2769
2770 to.crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
2771 if (packet_id_long_form)
2772 {
2773 to.crypto_flags |= CO_PACKET_ID_LONG_FORM;
2774 }
2775
2776 to.ssl_ctx = c->c1.ks.ssl_ctx;
2777 to.key_type = c->c1.ks.key_type;
2778 to.server = options->tls_server;
2779 to.key_method = options->key_method;
2780 to.replay = options->replay;
2781 to.replay_window = options->replay_window;
2782 to.replay_time = options->replay_time;
2783 to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto);
2784 to.config_ciphername = c->c1.ciphername;
2785 to.config_authname = c->c1.authname;
2786 to.ncp_enabled = options->ncp_enabled;
2787 to.transition_window = options->transition_window;
2788 to.handshake_window = options->handshake_window;
2789 to.packet_timeout = options->tls_timeout;
2790 to.renegotiate_bytes = options->renegotiate_bytes;
2791 to.renegotiate_packets = options->renegotiate_packets;
dd996463
SM
2792 if (options->renegotiate_seconds_min < 0)
2793 {
2794 /* Add 10% jitter to reneg-sec by default (server side only) */
2795 int auto_jitter = options->mode != MODE_SERVER ? 0 :
f57431cd 2796 get_random() % max_int(options->renegotiate_seconds / 10, 1);
dd996463
SM
2797 to.renegotiate_seconds = options->renegotiate_seconds - auto_jitter;
2798 }
2799 else
2800 {
2801 /* Add user-specified jitter to reneg-sec */
f57431cd
GD
2802 to.renegotiate_seconds = options->renegotiate_seconds
2803 -(get_random() % max_int(options->renegotiate_seconds
2804 - options->renegotiate_seconds_min, 1));
dd996463 2805 }
81d882d5
DS
2806 to.single_session = options->single_session;
2807 to.mode = options->mode;
2808 to.pull = options->pull;
81d882d5
DS
2809 if (options->push_peer_info) /* all there is */
2810 {
2811 to.push_peer_info_detail = 2;
2812 }
2813 else if (options->pull) /* pull clients send some details */
2814 {
2815 to.push_peer_info_detail = 1;
2816 }
2817 else /* default: no peer-info at all */
2818 {
2819 to.push_peer_info_detail = 0;
2820 }
6fbf66fa 2821
81d882d5
DS
2822 /* should we not xmit any packets until we get an initial
2823 * response from client? */
2824 if (to.server && options->ce.proto == PROTO_TCP_SERVER)
2825 {
2826 to.xmit_hold = true;
2827 }
6add6b2f 2828
6fbf66fa 2829#ifdef ENABLE_OCC
81d882d5
DS
2830 to.disable_occ = !options->occ;
2831#endif
2832
2833 to.verify_command = options->tls_verify;
2834 to.verify_export_cert = options->tls_export_cert;
2835 to.verify_x509_type = (options->verify_x509_type & 0xff);
2836 to.verify_x509_name = options->verify_x509_name;
2837 to.crl_file = options->crl_file;
2838 to.crl_file_inline = options->crl_file_inline;
2839 to.ssl_flags = options->ssl_flags;
2840 to.ns_cert_type = options->ns_cert_type;
2841 memmove(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku));
2842 to.remote_cert_eku = options->remote_cert_eku;
2843 to.verify_hash = options->verify_hash;
2193d7c0 2844 to.verify_hash_algo = options->verify_hash_algo;
19dd3ef1 2845#ifdef ENABLE_X509ALTUSERNAME
81d882d5 2846 to.x509_username_field = (char *) options->x509_username_field;
19dd3ef1 2847#else
81d882d5 2848 to.x509_username_field = X509_USERNAME_FIELD_DEFAULT;
19dd3ef1 2849#endif
81d882d5 2850 to.es = c->c2.es;
aec4a3d1 2851 to.net_ctx = &c->net_ctx;
6fbf66fa
JY
2852
2853#ifdef ENABLE_DEBUG
81d882d5 2854 to.gremlin = c->options.gremlin;
6fbf66fa
JY
2855#endif
2856
81d882d5 2857 to.plugins = c->plugins;
6fbf66fa 2858
90efcacb 2859#ifdef MANAGEMENT_DEF_AUTH
81d882d5 2860 to.mda_context = &c->c2.mda_context;
90efcacb
JY
2861#endif
2862
6fbf66fa 2863#if P2MP_SERVER
81d882d5
DS
2864 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
2865 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
2866 to.tmp_dir = options->tmp_dir;
2867 if (options->ccd_exclusive)
2868 {
2869 to.client_config_dir_exclusive = options->client_config_dir;
2870 }
2871 to.auth_user_pass_file = options->auth_user_pass_file;
2872 to.auth_token_generate = options->auth_token_generate;
2873 to.auth_token_lifetime = options->auth_token_lifetime;
6fbf66fa
JY
2874#endif
2875
81d882d5 2876 to.x509_track = options->x509_track;
9356bae8 2877
16d909e2 2878#if P2MP
66b9409b 2879#ifdef ENABLE_MANAGEMENT
81d882d5 2880 to.sci = &options->sc_info;
16d909e2 2881#endif
eab3e22f
JY
2882#endif
2883
38d96bd7 2884#ifdef USE_COMP
81d882d5 2885 to.comp_options = options->comp;
38d96bd7
JY
2886#endif
2887
685e486e 2888#if defined(ENABLE_CRYPTO_OPENSSL) && OPENSSL_VERSION_NUMBER >= 0x10001000
81d882d5 2889 if (options->keying_material_exporter_label)
685e486e 2890 {
81d882d5
DS
2891 to.ekm_size = options->keying_material_exporter_length;
2892 if (to.ekm_size < 16 || to.ekm_size > 4095)
2893 {
2894 to.ekm_size = 0;
2895 }
685e486e 2896
81d882d5
DS
2897 to.ekm_label = options->keying_material_exporter_label;
2898 to.ekm_label_size = strlen(to.ekm_label);
685e486e 2899 }
81d882d5 2900 else
685e486e 2901 {
81d882d5 2902 to.ekm_size = 0;
685e486e
DK
2903 }
2904#endif
2905
81d882d5 2906 /* TLS handshake authentication (--tls-auth) */
57d6f103 2907 if (options->ce.tls_auth_file)
6fbf66fa 2908 {
81d882d5
DS
2909 to.tls_wrap.mode = TLS_WRAP_AUTH;
2910 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2911 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2912 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
ef910e3e
SK
2913 crypto_adjust_frame_parameters(&to.frame, &c->c1.ks.tls_auth_key_type,
2914 true, true);
6fbf66fa
JY
2915 }
2916
81d882d5 2917 /* TLS handshake encryption (--tls-crypt) */
19dffdbd
SK
2918 if (options->ce.tls_crypt_file
2919 || (options->ce.tls_crypt_v2_file && options->tls_client))
c6e24fa3 2920 {
81d882d5
DS
2921 to.tls_wrap.mode = TLS_WRAP_CRYPT;
2922 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
2923 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
2924 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
2925 tls_crypt_adjust_frame_parameters(&to.frame);
19dffdbd 2926
19d6d9c3 2927 if (options->ce.tls_crypt_v2_file)
19dffdbd
SK
2928 {
2929 to.tls_wrap.tls_crypt_v2_wkc = &c->c1.ks.tls_crypt_v2_wkc;
2930 }
2931 }
2932
19d6d9c3 2933 if (options->ce.tls_crypt_v2_file)
19dffdbd
SK
2934 {
2935 to.tls_crypt_v2 = true;
2936 if (options->tls_server)
2937 {
2938 to.tls_wrap.tls_crypt_v2_server_key = c->c1.ks.tls_crypt_v2_server_key;
ff931c5e 2939 to.tls_crypt_v2_verify_script = c->options.tls_crypt_v2_verify_script;
19dffdbd 2940 }
c6e24fa3
SK
2941 }
2942
81d882d5
DS
2943 /* If we are running over TCP, allow for
2944 * length prefix */
2945 socket_adjust_frame_parameters(&to.frame, options->ce.proto);
6fbf66fa 2946
81d882d5
DS
2947 /*
2948 * Initialize OpenVPN's master TLS-mode object.
2949 */
2950 if (flags & CF_INIT_TLS_MULTI)
2951 {
2952 c->c2.tls_multi = tls_multi_init(&to);
2953 }
6fbf66fa 2954
81d882d5
DS
2955 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
2956 {
2957 c->c2.tls_auth_standalone = tls_auth_standalone_init(&to, &c->c2.gc);
2958 }
6fbf66fa
JY
2959}
2960
2961static void
81d882d5 2962do_init_finalize_tls_frame(struct context *c)
6fbf66fa 2963{
81d882d5 2964 if (c->c2.tls_multi)
6fbf66fa 2965 {
81d882d5
DS
2966 tls_multi_init_finalize(c->c2.tls_multi, &c->c2.frame);
2967 ASSERT(EXPANDED_SIZE(&c->c2.tls_multi->opt.frame) <=
2968 EXPANDED_SIZE(&c->c2.frame));
2969 frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO,
2970 "Control Channel MTU parms");
6fbf66fa 2971 }
81d882d5 2972 if (c->c2.tls_auth_standalone)
6fbf66fa 2973 {
81d882d5
DS
2974 tls_auth_standalone_finalize(c->c2.tls_auth_standalone, &c->c2.frame);
2975 frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
2976 "TLS-Auth MTU parms");
6fbf66fa
JY
2977 }
2978}
2979
6fbf66fa
JY
2980/*
2981 * No encryption or authentication.
2982 */
2983static void
81d882d5 2984do_init_crypto_none(const struct context *c)
6fbf66fa 2985{
81d882d5
DS
2986 ASSERT(!c->options.test_crypto);
2987 msg(M_WARN,
7a1b6a0d
DS
2988 "******* WARNING *******: All encryption and authentication features "
2989 "disabled -- All data will be tunnelled as clear text and will not be "
2990 "protected against man-in-the-middle changes. "
2991 "PLEASE DO RECONSIDER THIS CONFIGURATION!");
6fbf66fa 2992}
6fbf66fa
JY
2993
2994static void
81d882d5 2995do_init_crypto(struct context *c, const unsigned int flags)
6fbf66fa 2996{
81d882d5
DS
2997 if (c->options.shared_secret_file)
2998 {
2999 do_init_crypto_static(c, flags);
3000 }
3001 else if (c->options.tls_server || c->options.tls_client)
3002 {
3003 do_init_crypto_tls(c, flags);
3004 }
3005 else /* no encryption or authentication. */
3006 {
3007 do_init_crypto_none(c);
3008 }
6fbf66fa
JY
3009}
3010
3011static void
81d882d5 3012do_init_frame(struct context *c)
6fbf66fa 3013{
38d96bd7 3014#ifdef USE_COMP
81d882d5
DS
3015 /*
3016 * modify frame parameters if compression is enabled
3017 */
3018 if (comp_enabled(&c->options.comp))
6fbf66fa 3019 {
81d882d5 3020 comp_add_to_extra_frame(&c->c2.frame);
6fbf66fa 3021
9403e3f4 3022#if !defined(ENABLE_LZ4)
81d882d5
DS
3023 /*
3024 * Compression usage affects buffer alignment when non-swapped algs
3025 * such as LZO is used.
3026 * Newer algs like LZ4 and comp-stub with COMP_F_SWAP don't need
3027 * any special alignment because of the control-byte swap approach.
3028 * LZO alignment (on the other hand) is problematic because
3029 * the presence of the control byte means that either the output of
3030 * decryption must be written to an unaligned buffer, or the input
3031 * to compression (or packet dispatch if packet is uncompressed)
3032 * must be read from an unaligned buffer.
3033 * This code tries to align the input to compression (or packet
3034 * dispatch if packet is uncompressed) at the cost of requiring
3035 * decryption output to be written to an unaligned buffer, so
3036 * it's more of a tradeoff than an optimal solution and we don't
3037 * include it when we are doing a modern build with LZ4.
3038 * Strictly speaking, on the server it would be better to execute
3039 * this code for every connection after we decide the compression
3040 * method, but currently the frame code doesn't appear to be
3041 * flexible enough for this, since the frame is already established
3042 * before it is known which compression options will be pushed.
3043 */
3044 if (comp_unswapped_prefix(&c->options.comp) && CIPHER_ENABLED(c))
3045 {
3046 frame_add_to_align_adjust(&c->c2.frame, COMP_PREFIX_LEN);
3047 frame_or_align_flags(&c->c2.frame,
3048 FRAME_HEADROOM_MARKER_FRAGMENT
3049 |FRAME_HEADROOM_MARKER_DECRYPT);
3050 }
38d96bd7 3051#endif
6fbf66fa
JY
3052
3053#ifdef ENABLE_FRAGMENT
81d882d5 3054 comp_add_to_extra_frame(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
6fbf66fa
JY
3055#endif
3056 }
38d96bd7 3057#endif /* USE_COMP */
6fbf66fa 3058
81d882d5
DS
3059 /*
3060 * Adjust frame size for UDP Socks support.
3061 */
3062 if (c->options.ce.socks_proxy_server)
3063 {
3064 socks_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
3065 }
3066
3067 /*
3068 * Adjust frame size based on the --tun-mtu-extra parameter.
3069 */
3070 if (c->options.ce.tun_mtu_extra_defined)
3071 {
3072 tun_adjust_frame_parameters(&c->c2.frame, c->options.ce.tun_mtu_extra);
3073 }
3074
3075 /*
3076 * Adjust frame size based on link socket parameters.
3077 * (Since TCP is a stream protocol, we need to insert
3078 * a packet length uint16_t in the buffer.)
3079 */
3080 socket_adjust_frame_parameters(&c->c2.frame, c->options.ce.proto);
3081
3082 /*
3083 * Fill in the blanks in the frame parameters structure,
3084 * make sure values are rational, etc.
3085 */
3086 frame_finalize_options(c, NULL);
6fbf66fa 3087
38d96bd7 3088#ifdef USE_COMP
81d882d5
DS
3089 /*
3090 * Modify frame parameters if compression is compiled in.
3091 * Should be called after frame_finalize_options.
3092 */
3093 comp_add_to_extra_buffer(&c->c2.frame);
38d96bd7 3094#ifdef ENABLE_FRAGMENT
81d882d5 3095 comp_add_to_extra_buffer(&c->c2.frame_fragment_omit); /* omit compression frame delta from final frame_fragment */
38d96bd7
JY
3096#endif
3097#endif /* USE_COMP */
3098
81d882d5
DS
3099 /* packets with peer-id (P_DATA_V2) need 3 extra bytes in frame (on client)
3100 * and need link_mtu+3 bytes on socket reception (on server).
3101 *
ccb636c7 3102 * accommodate receive path in f->extra_link, which has the side effect of
81d882d5
DS
3103 * also increasing send buffers (BUF_SIZE() macro), which need to be
3104 * allocated big enough before receiving peer-id option from server.
3105 *
3106 * f->extra_frame is adjusted when peer-id option is push-received
3107 */
3108 frame_add_to_extra_link(&c->c2.frame, 3);
9e0963c1 3109
6fbf66fa 3110#ifdef ENABLE_FRAGMENT
81d882d5
DS
3111 /*
3112 * Set frame parameter for fragment code. This is necessary because
3113 * the fragmentation code deals with payloads which have already been
3114 * passed through the compression code.
3115 */
3116 c->c2.frame_fragment = c->c2.frame;
3117 frame_subtract_extra(&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
6fbf66fa
JY
3118#endif
3119
3120#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
81d882d5
DS
3121 /*
3122 * MTU advisories
3123 */
3124 if (c->options.ce.fragment && c->options.mtu_test)
3125 {
3126 msg(M_WARN,
3127 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
3128 }
6fbf66fa
JY
3129#endif
3130
3131#ifdef ENABLE_FRAGMENT
81d882d5
DS
3132 if ((c->options.ce.mssfix || c->options.ce.fragment)
3133 && TUN_MTU_SIZE(&c->c2.frame_fragment) != ETHERNET_MTU)
3134 {
3135 msg(M_WARN,
3136 "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
3137 ETHERNET_MTU, TUN_MTU_SIZE(&c->c2.frame_fragment));
3138 }
6fbf66fa
JY
3139#endif
3140}
3141
3142static void
81d882d5 3143do_option_warnings(struct context *c)
6fbf66fa 3144{
81d882d5 3145 const struct options *o = &c->options;
6fbf66fa 3146
81d882d5
DS
3147 if (o->ping_send_timeout && !o->ping_rec_timeout)
3148 {
3149 msg(M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
3150 }
6fbf66fa 3151
81d882d5 3152 if (o->username || o->groupname || o->chroot_dir
cd5990e0 3153#ifdef ENABLE_SELINUX
81d882d5 3154 || o->selinux_context
99385447 3155#endif
81d882d5
DS
3156 )
3157 {
3158 if (!o->persist_tun)
3159 {
3160 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
3161 }
3162 if (!o->persist_key
51b1d4c2 3163#ifdef ENABLE_PKCS11
81d882d5 3164 && !o->pkcs11_id
51b1d4c2 3165#endif
81d882d5
DS
3166 )
3167 {
3168 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
3169 }
3170 }
6fbf66fa 3171
81d882d5
DS
3172 if (o->chroot_dir && !(o->username && o->groupname))
3173 {
3174 msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
3175 }
31f90e64 3176
6fbf66fa 3177#if P2MP
81d882d5
DS
3178 if (o->pull && o->ifconfig_local && c->first_time)
3179 {
3180 msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
3181 }
6fbf66fa
JY
3182
3183#if P2MP_SERVER
81d882d5
DS
3184 if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
3185 {
3186 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");
3187 }
f77c60d3 3188
81d882d5 3189 if (o->mode == MODE_SERVER)
6fbf66fa 3190 {
81d882d5
DS
3191 if (o->duplicate_cn && o->client_config_dir)
3192 {
3193 msg(M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
3194 }
3195 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
3196 {
3197 msg(M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
3198 }
3199 if (!o->keepalive_ping || !o->keepalive_timeout)
3200 {
3201 msg(M_WARN, "WARNING: --keepalive option is missing from server config");
3202 }
6fbf66fa 3203 }
81d882d5
DS
3204#endif /* if P2MP_SERVER */
3205#endif /* if P2MP */
6fbf66fa 3206
81d882d5
DS
3207 if (!o->replay)
3208 {
3209 msg(M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
3210 }
81d882d5
DS
3211
3212 if (o->tls_server)
3213 {
aec4a3d1 3214 warn_on_use_of_common_subnets(&c->net_ctx);
81d882d5
DS
3215 }
3216 if (o->tls_client
3217 && !o->tls_verify
3218 && o->verify_x509_type == VERIFY_X509_NONE
3219 && !(o->ns_cert_type & NS_CERT_CHECK_SERVER)
3220 && !o->remote_cert_eku)
3221 {
3222 msg(M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
3223 }
2dc33226
SK
3224 if (o->ns_cert_type)
3225 {
3226 msg(M_WARN, "WARNING: --ns-cert-type is DEPRECATED. Use --remote-cert-tls instead.");
3227 }
81d882d5 3228
ccb636c7 3229 /* If a script is used, print appropriate warnings */
81d882d5
DS
3230 if (o->user_script_used)
3231 {
bf97c00f 3232 if (script_security() >= SSEC_SCRIPTS)
81d882d5
DS
3233 {
3234 msg(M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
3235 }
bf97c00f 3236 else if (script_security() >= SSEC_PW_ENV)
81d882d5
DS
3237 {
3238 msg(M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
3239 }
3240 else
3241 {
3242 msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
3243 }
3244 }
6fbf66fa
JY
3245}
3246
3247static void
81d882d5 3248do_init_frame_tls(struct context *c)
6fbf66fa 3249{
81d882d5 3250 do_init_finalize_tls_frame(c);
6fbf66fa
JY
3251}
3252
3253struct context_buffers *
81d882d5 3254init_context_buffers(const struct frame *frame)
6fbf66fa 3255{
81d882d5 3256 struct context_buffers *b;
6fbf66fa 3257
81d882d5 3258 ALLOC_OBJ_CLEAR(b, struct context_buffers);
6fbf66fa 3259
81d882d5
DS
3260 b->read_link_buf = alloc_buf(BUF_SIZE(frame));
3261 b->read_tun_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3262
81d882d5 3263 b->aux_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3264
81d882d5
DS
3265 b->encrypt_buf = alloc_buf(BUF_SIZE(frame));
3266 b->decrypt_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa 3267
38d96bd7 3268#ifdef USE_COMP
81d882d5
DS
3269 b->compress_buf = alloc_buf(BUF_SIZE(frame));
3270 b->decompress_buf = alloc_buf(BUF_SIZE(frame));
6fbf66fa
JY
3271#endif
3272
81d882d5 3273 return b;
6fbf66fa
JY
3274}
3275
3276void
81d882d5 3277free_context_buffers(struct context_buffers *b)
6fbf66fa 3278{
81d882d5 3279 if (b)
6fbf66fa 3280 {
81d882d5
DS
3281 free_buf(&b->read_link_buf);
3282 free_buf(&b->read_tun_buf);
3283 free_buf(&b->aux_buf);
6fbf66fa 3284
38d96bd7 3285#ifdef USE_COMP
81d882d5
DS
3286 free_buf(&b->compress_buf);
3287 free_buf(&b->decompress_buf);
6fbf66fa
JY
3288#endif
3289
81d882d5
DS
3290 free_buf(&b->encrypt_buf);
3291 free_buf(&b->decrypt_buf);
6fbf66fa 3292
81d882d5 3293 free(b);
6fbf66fa
JY
3294 }
3295}
3296
3297/*
3298 * Now that we know all frame parameters, initialize
3299 * our buffers.
3300 */
3301static void
81d882d5 3302do_init_buffers(struct context *c)
6fbf66fa 3303{
81d882d5
DS
3304 c->c2.buffers = init_context_buffers(&c->c2.frame);
3305 c->c2.buffers_owned = true;
6fbf66fa
JY
3306}
3307
3308#ifdef ENABLE_FRAGMENT
3309/*
3310 * Fragmenting code has buffers to initialize
3311 * once frame parameters are known.
3312 */
3313static void
81d882d5 3314do_init_fragment(struct context *c)
6fbf66fa 3315{
81d882d5
DS
3316 ASSERT(c->options.ce.fragment);
3317 frame_set_mtu_dynamic(&c->c2.frame_fragment,
3318 c->options.ce.fragment, SET_MTU_UPPER_BOUND);
3319 fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment);
6fbf66fa
JY
3320}
3321#endif
3322
6fbf66fa
JY
3323/*
3324 * Allocate our socket object.
3325 */
3326static void
81d882d5 3327do_link_socket_new(struct context *c)
6fbf66fa 3328{
81d882d5
DS
3329 ASSERT(!c->c2.link_socket);
3330 c->c2.link_socket = link_socket_new();
3331 c->c2.link_socket_owned = true;
6fbf66fa
JY
3332}
3333
3334/*
3335 * bind the TCP/UDP socket
3336 */
3337static void
81d882d5 3338do_init_socket_1(struct context *c, const int mode)
6fbf66fa 3339{
81d882d5 3340 unsigned int sockflags = c->options.sockflags;
dc46c067
JY
3341
3342#if PORT_SHARE
81d882d5
DS
3343 if (c->options.port_share_host && c->options.port_share_port)
3344 {
3345 sockflags |= SF_PORT_SHARE;
3346 }
3347#endif
3348
3349 link_socket_init_phase1(c->c2.link_socket,
3350 c->options.ce.local,
3351 c->options.ce.local_port,
3352 c->options.ce.remote,
3353 c->options.ce.remote_port,
3354 c->c1.dns_cache,
3355 c->options.ce.proto,
3356 c->options.ce.af,
3357 c->options.ce.bind_ipv6_only,
3358 mode,
3359 c->c2.accept_from,
3360 c->c1.http_proxy,
3361 c->c1.socks_proxy,
6fbf66fa 3362#ifdef ENABLE_DEBUG
81d882d5
DS
3363 c->options.gremlin,
3364#endif
3365 c->options.ce.bind_local,
3366 c->options.ce.remote_float,
3367 c->options.inetd,
3368 &c->c1.link_socket_addr,
3369 c->options.ipchange,
3370 c->plugins,
3371 c->options.resolve_retry_seconds,
3372 c->options.ce.mtu_discover_type,
3373 c->options.rcvbuf,
3374 c->options.sndbuf,
3375 c->options.mark,
3376 &c->c2.server_poll_interval,
3377 sockflags);
6fbf66fa
JY
3378}
3379
3380/*
3381 * finalize the TCP/UDP socket
3382 */
3383static void
81d882d5 3384do_init_socket_2(struct context *c)
6fbf66fa 3385{
81d882d5
DS
3386 link_socket_init_phase2(c->c2.link_socket, &c->c2.frame,
3387 c->sig);
6fbf66fa
JY
3388}
3389
3390/*
3391 * Print MTU INFO
3392 */
3393static void
81d882d5 3394do_print_data_channel_mtu_parms(struct context *c)
6fbf66fa 3395{
81d882d5 3396 frame_print(&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
6fbf66fa 3397#ifdef ENABLE_FRAGMENT
81d882d5
DS
3398 if (c->c2.fragment)
3399 {
3400 frame_print(&c->c2.frame_fragment, D_MTU_INFO,
3401 "Fragmentation MTU parms");
3402 }
6fbf66fa
JY
3403#endif
3404}
3405
3406#ifdef ENABLE_OCC
3407/*
3408 * Get local and remote options compatibility strings.
3409 */
3410static void
81d882d5 3411do_compute_occ_strings(struct context *c)
6fbf66fa 3412{
81d882d5 3413 struct gc_arena gc = gc_new();
6fbf66fa 3414
81d882d5 3415 c->c2.options_string_local =
dc7fcd71
AQ
3416 options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3417 false, &gc);
81d882d5 3418 c->c2.options_string_remote =
dc7fcd71
AQ
3419 options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3420 true, &gc);
6fbf66fa 3421
81d882d5
DS
3422 msg(D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
3423 options_string_version(c->c2.options_string_local, &gc),
3424 c->c2.options_string_local);
3425 msg(D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
3426 options_string_version(c->c2.options_string_remote, &gc),
3427 c->c2.options_string_remote);
6fbf66fa 3428
81d882d5
DS
3429 if (c->c2.tls_multi)
3430 {
3431 tls_multi_init_set_options(c->c2.tls_multi,
3432 c->c2.options_string_local,
3433 c->c2.options_string_remote);
3434 }
6fbf66fa 3435
81d882d5 3436 gc_free(&gc);
6fbf66fa 3437}
81d882d5 3438#endif /* ifdef ENABLE_OCC */
6fbf66fa
JY
3439
3440/*
3441 * These things can only be executed once per program instantiation.
3442 * Set up for possible UID/GID downgrade, but don't do it yet.
3443 * Daemonize if requested.
3444 */
3445static void
81d882d5 3446do_init_first_time(struct context *c)
6fbf66fa 3447{
81d882d5 3448 if (c->first_time && !c->c0)
6fbf66fa 3449 {
81d882d5 3450 struct context_0 *c0;
92bbb061 3451
81d882d5
DS
3452 ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc);
3453 c0 = c->c0;
6fbf66fa 3454
81d882d5
DS
3455 /* get user and/or group that we want to setuid/setgid to */
3456 c0->uid_gid_specified =
3457 platform_group_get(c->options.groupname, &c0->platform_state_group)
3458 |platform_user_get(c->options.username, &c0->platform_state_user);
6fbf66fa 3459
81d882d5
DS
3460 /* perform postponed chdir if --daemon */
3461 if (c->did_we_daemonize && c->options.cd_dir == NULL)
3462 {
3463 platform_chdir("/");
3464 }
3465
3466 /* should we change scheduling priority? */
3467 platform_nice(c->options.nice);
6fbf66fa
JY
3468 }
3469}
3470
3471/*
3472 * If xinetd/inetd mode, don't allow restart.
3473 */
3474static void
81d882d5 3475do_close_check_if_restart_permitted(struct context *c)
6fbf66fa 3476{
81d882d5
DS
3477 if (c->options.inetd
3478 && (c->sig->signal_received == SIGHUP
3479 || c->sig->signal_received == SIGUSR1))
6fbf66fa 3480 {
81d882d5
DS
3481 c->sig->signal_received = SIGTERM;
3482 msg(M_INFO,
3483 PACKAGE_NAME
3484 " started by inetd/xinetd cannot restart... Exiting.");
6fbf66fa
JY
3485 }
3486}
3487
3488/*
3489 * free buffers
3490 */
3491static void
81d882d5 3492do_close_free_buf(struct context *c)
6fbf66fa 3493{
81d882d5 3494 if (c->c2.buffers_owned)
6fbf66fa 3495 {
81d882d5
DS
3496 free_context_buffers(c->c2.buffers);
3497 c->c2.buffers = NULL;
3498 c->c2.buffers_owned = false;
6fbf66fa
JY
3499 }
3500}
3501
3502/*
3503 * close TLS
3504 */
3505static void
81d882d5 3506do_close_tls(struct context *c)
6fbf66fa 3507{
81d882d5 3508 if (c->c2.tls_multi)
6fbf66fa 3509 {
81d882d5
DS
3510 tls_multi_free(c->c2.tls_multi, true);
3511 c->c2.tls_multi = NULL;
6fbf66fa
JY
3512 }
3513
3514#ifdef ENABLE_OCC
81d882d5
DS
3515 /* free options compatibility strings */
3516 if (c->c2.options_string_local)
3517 {
3518 free(c->c2.options_string_local);
3519 }
3520 if (c->c2.options_string_remote)
3521 {
3522 free(c->c2.options_string_remote);
3523 }
3524 c->c2.options_string_local = c->c2.options_string_remote = NULL;
6fbf66fa 3525#endif
07036fd3
SK
3526
3527 if (c->c2.pulled_options_state)
3528 {
3529 md_ctx_cleanup(c->c2.pulled_options_state);
3530 md_ctx_free(c->c2.pulled_options_state);
3531 }
6fbf66fa
JY
3532}
3533
3534/*
3535 * Free key schedules
3536 */
3537static void
81d882d5 3538do_close_free_key_schedule(struct context *c, bool free_ssl_ctx)
6fbf66fa 3539{
5817b49b
AQ
3540 /*
3541 * always free the tls_auth/crypt key. If persist_key is true, the key will
3542 * be reloaded from memory (pre-cached)
3543 */
3544 free_key_ctx_bi(&c->c1.ks.tls_wrap_key);
3545 CLEAR(c->c1.ks.tls_wrap_key);
19dffdbd
SK
3546 buf_clear(&c->c1.ks.tls_crypt_v2_wkc);
3547 free_buf(&c->c1.ks.tls_crypt_v2_wkc);
5817b49b 3548
81d882d5
DS
3549 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
3550 {
3551 key_schedule_free(&c->c1.ks, free_ssl_ctx);
3552 }
6fbf66fa
JY
3553}
3554
3555/*
3556 * Close TCP/UDP connection
3557 */
3558static void
81d882d5 3559do_close_link_socket(struct context *c)
6fbf66fa 3560{
81d882d5 3561 if (c->c2.link_socket && c->c2.link_socket_owned)
6fbf66fa 3562 {
81d882d5
DS
3563 link_socket_close(c->c2.link_socket);
3564 c->c2.link_socket = NULL;
6fbf66fa
JY
3565 }
3566
81d882d5
DS
3567
3568 /* Preserve the resolved list of remote if the user request to or if we want
3569 * reconnect to the same host again or there are still addresses that need
3570 * to be tried */
3571 if (!(c->sig->signal_received == SIGUSR1
3572 && ( (c->options.persist_remote_ip)
3573 ||
3574 ( c->sig->source != SIG_SOURCE_HARD
3575 && ((c->c1.link_socket_addr.current_remote && c->c1.link_socket_addr.current_remote->ai_next)
3576 || c->options.no_advance))
3577 )))
23d61c56 3578 {
81d882d5 3579 clear_remote_addrlist(&c->c1.link_socket_addr, !c->options.resolve_in_advance);
23d61c56
AS
3580 }
3581
3582 /* Clear the remote actual address when persist_remote_ip is not in use */
3583 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
81d882d5
DS
3584 {
3585 CLEAR(c->c1.link_socket_addr.actual);
3586 }
6fbf66fa 3587
81d882d5
DS
3588 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
3589 {
3590 if (c->c1.link_socket_addr.bind_local && !c->options.resolve_in_advance)
3591 {
3592 freeaddrinfo(c->c1.link_socket_addr.bind_local);
3593 }
e719a053 3594
81d882d5
DS
3595 c->c1.link_socket_addr.bind_local = NULL;
3596 }
6fbf66fa
JY
3597}
3598
3599/*
ccb636c7 3600 * Close packet-id persistence file
6fbf66fa
JY
3601 */
3602static void
81d882d5 3603do_close_packet_id(struct context *c)
6fbf66fa 3604{
81d882d5
DS
3605 packet_id_free(&c->c2.crypto_options.packet_id);
3606 packet_id_persist_save(&c->c1.pid_persist);
3607 if (!(c->sig->signal_received == SIGUSR1))
3608 {
3609 packet_id_persist_close(&c->c1.pid_persist);
3610 }
6fbf66fa
JY
3611}
3612
3613#ifdef ENABLE_FRAGMENT
3614/*
3615 * Close fragmentation handler.
3616 */
3617static void
81d882d5 3618do_close_fragment(struct context *c)
6fbf66fa 3619{
81d882d5 3620 if (c->c2.fragment)
6fbf66fa 3621 {
81d882d5
DS
3622 fragment_free(c->c2.fragment);
3623 c->c2.fragment = NULL;
6fbf66fa
JY
3624 }
3625}
3626#endif
3627
3628/*
3629 * Open and close our event objects.
3630 */
3631
3632static void
81d882d5
DS
3633do_event_set_init(struct context *c,
3634 bool need_us_timeout)
6fbf66fa 3635{
81d882d5 3636 unsigned int flags = 0;
6fbf66fa 3637
81d882d5 3638 c->c2.event_set_max = BASE_N_EVENTS;
6fbf66fa 3639
81d882d5 3640 flags |= EVENT_METHOD_FAST;
6fbf66fa 3641
81d882d5
DS
3642 if (need_us_timeout)
3643 {
3644 flags |= EVENT_METHOD_US_TIMEOUT;
3645 }
6fbf66fa 3646
81d882d5
DS
3647 c->c2.event_set = event_set_init(&c->c2.event_set_max, flags);
3648 c->c2.event_set_owned = true;
6fbf66fa
JY
3649}
3650
3651static void
81d882d5 3652do_close_event_set(struct context *c)
6fbf66fa 3653{
81d882d5 3654 if (c->c2.event_set && c->c2.event_set_owned)
6fbf66fa 3655 {
81d882d5
DS
3656 event_free(c->c2.event_set);
3657 c->c2.event_set = NULL;
3658 c->c2.event_set_owned = false;
6fbf66fa
JY
3659 }
3660}
3661
3662/*
3663 * Open and close --status file
3664 */
3665
3666static void
81d882d5 3667do_open_status_output(struct context *c)
6fbf66fa 3668{
81d882d5 3669 if (!c->c1.status_output)
6fbf66fa 3670 {
81d882d5
DS
3671 c->c1.status_output = status_open(c->options.status_file,
3672 c->options.status_file_update_freq,
3673 -1,
3674 NULL,
3675 STATUS_OUTPUT_WRITE);
3676 c->c1.status_output_owned = true;
6fbf66fa
JY
3677 }
3678}
3679
3680static void
81d882d5 3681do_close_status_output(struct context *c)
6fbf66fa 3682{
81d882d5 3683 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3684 {
81d882d5
DS
3685 if (c->c1.status_output_owned && c->c1.status_output)
3686 {
3687 status_close(c->c1.status_output);
3688 c->c1.status_output = NULL;
3689 c->c1.status_output_owned = false;
3690 }
6fbf66fa
JY
3691 }
3692}
3693
3694/*
ccb636c7 3695 * Handle ifconfig-pool persistence object.
6fbf66fa
JY
3696 */
3697static void
81d882d5 3698do_open_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3699{
3700#if P2MP_SERVER
81d882d5 3701 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
6fbf66fa 3702 {
81d882d5
DS
3703 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init(c->options.ifconfig_pool_persist_filename,
3704 c->options.ifconfig_pool_persist_refresh_freq);
3705 c->c1.ifconfig_pool_persist_owned = true;
6fbf66fa
JY
3706 }
3707#endif
3708}
3709
3710static void
81d882d5 3711do_close_ifconfig_pool_persist(struct context *c)
6fbf66fa
JY
3712{
3713#if P2MP_SERVER
81d882d5 3714 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 3715 {
81d882d5
DS
3716 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
3717 {
3718 ifconfig_pool_persist_close(c->c1.ifconfig_pool_persist);
3719 c->c1.ifconfig_pool_persist = NULL;
3720 c->c1.ifconfig_pool_persist_owned = false;
3721 }
6fbf66fa
JY
3722 }
3723#endif
3724}
3725
3726/*
3727 * Inherit environmental variables
3728 */
3729
3730static void
81d882d5 3731do_inherit_env(struct context *c, const struct env_set *src)
6fbf66fa 3732{
81d882d5
DS
3733 c->c2.es = env_set_create(NULL);
3734 c->c2.es_owned = true;
3735 env_set_inherit(c->c2.es, src);
6fbf66fa
JY
3736}
3737
2a64816b 3738static void
81d882d5 3739do_env_set_destroy(struct context *c)
2a64816b 3740{
81d882d5 3741 if (c->c2.es && c->c2.es_owned)
2a64816b 3742 {
81d882d5
DS
3743 env_set_destroy(c->c2.es);
3744 c->c2.es = NULL;
3745 c->c2.es_owned = false;
2a64816b
JY
3746 }
3747}
3748
6fbf66fa
JY
3749/*
3750 * Fast I/O setup. Fast I/O is an optimization which only works
3751 * if all of the following are true:
3752 *
3753 * (1) The platform is not Windows
3754 * (2) --proto udp is enabled
3755 * (3) --shaper is disabled
3756 */
3757static void
81d882d5 3758do_setup_fast_io(struct context *c)
6fbf66fa 3759{
81d882d5 3760 if (c->options.fast_io)
6fbf66fa 3761 {
445b192a 3762#ifdef _WIN32
81d882d5 3763 msg(M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
6fbf66fa 3764#else
81d882d5
DS
3765 if (!proto_is_udp(c->options.ce.proto))
3766 {
3767 msg(M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
3768 }
3769 else
3770 {
3d163bc5 3771#ifdef ENABLE_FEATURE_SHAPER
81d882d5
DS
3772 if (c->options.shaper)
3773 {
3774 msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
3775 }
3776 else
0475d17e 3777#endif
81d882d5
DS
3778 {
3779 c->c2.fast_io = true;
3780 }
3781 }
6fbf66fa
JY
3782#endif
3783 }
3784}
3785
3786static void
81d882d5 3787do_signal_on_tls_errors(struct context *c)
6fbf66fa 3788{
81d882d5
DS
3789 if (c->options.tls_exit)
3790 {
3791 c->c2.tls_exit_signal = SIGTERM;
3792 }
3793 else
3794 {
3795 c->c2.tls_exit_signal = SIGUSR1;
3796 }
6fbf66fa
JY
3797}
3798
3c7f2f55 3799#ifdef ENABLE_PLUGIN
6fbf66fa 3800
3c7f2f55 3801void
81d882d5 3802init_plugins(struct context *c)
6fbf66fa 3803{
81d882d5 3804 if (c->options.plugin_list && !c->plugins)
e1791bb1 3805 {
81d882d5
DS
3806 c->plugins = plugin_list_init(c->options.plugin_list);
3807 c->plugins_owned = true;
e1791bb1
JY
3808 }
3809}
3810
3811void
81d882d5
DS
3812open_plugins(struct context *c, const bool import_options, int init_point)
3813{
3814 if (c->plugins && c->plugins_owned)
3815 {
3816 if (import_options)
3817 {
3818 struct plugin_return pr, config;
3819 plugin_return_init(&pr);
3820 plugin_list_open(c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
3821 plugin_return_get_column(&pr, &config, "config");
3822 if (plugin_return_defined(&config))
3823 {
3824 int i;
3825 for (i = 0; i < config.n; ++i)
3826 {
3827 unsigned int option_types_found = 0;
3828 if (config.list[i] && config.list[i]->value)
3829 {
3830 options_string_import(&c->options,
3831 config.list[i]->value,
3832 D_IMPORT_ERRORS|M_OPTERR,
3833 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
3834 &option_types_found,
3835 c->es);
3836 }
3837 }
3838 }
3839 plugin_return_free(&pr);
3840 }
3841 else
3842 {
3843 plugin_list_open(c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
3844 }
6fbf66fa 3845 }
6fbf66fa
JY
3846}
3847
3848static void
81d882d5 3849do_close_plugins(struct context *c)
6fbf66fa 3850{
81d882d5 3851 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 3852 {
81d882d5
DS
3853 plugin_list_close(c->plugins);
3854 c->plugins = NULL;
3855 c->plugins_owned = false;
6fbf66fa 3856 }
6fbf66fa
JY
3857}
3858
3c7f2f55 3859static void
81d882d5 3860do_inherit_plugins(struct context *c, const struct context *src)
3c7f2f55 3861{
81d882d5 3862 if (!c->plugins && src->plugins)
3c7f2f55 3863 {
81d882d5
DS
3864 c->plugins = plugin_list_inherit(src->plugins);
3865 c->plugins_owned = true;
3c7f2f55
JY
3866 }
3867}
3868
81d882d5 3869#endif /* ifdef ENABLE_PLUGIN */
3c7f2f55 3870
6fbf66fa
JY
3871#ifdef ENABLE_MANAGEMENT
3872
3873static void
81d882d5 3874management_callback_status_p2p(void *arg, const int version, struct status_output *so)
6fbf66fa 3875{
81d882d5
DS
3876 struct context *c = (struct context *) arg;
3877 print_status(c, so);
6fbf66fa
JY
3878}
3879
3880void
81d882d5 3881management_show_net_callback(void *arg, const int msglevel)
6fbf66fa 3882{
445b192a 3883#ifdef _WIN32
81d882d5
DS
3884 show_routes(msglevel);
3885 show_adapters(msglevel);
3886 msg(msglevel, "END");
6fbf66fa 3887#else
81d882d5 3888 msg(msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
6fbf66fa
JY
3889#endif
3890}
3891
30003978
AS
3892#ifdef TARGET_ANDROID
3893int
81d882d5 3894management_callback_network_change(void *arg, bool samenetwork)
30003978
AS
3895{
3896 /* Check if the client should translate the network change to a SIGUSR1 to
81d882d5
DS
3897 * reestablish the connection or just reprotect the socket
3898 *
3899 * At the moment just assume that, for all settings that use pull (not
3900 * --static) and are not using peer-id reestablishing the connection is
3901 * required (unless the network is the same)
3902 *
3903 * The function returns -1 on invalid fd and -2 if the socket cannot be
3904 * reused. On the -2 return value the man_network_change function triggers
3905 * a SIGUSR1 to force a reconnect.
3906 */
3907
3908 int socketfd = -1;
3909 struct context *c = (struct context *) arg;
3910 if (!c->c2.link_socket)
3911 {
3912 return -1;
3913 }
3914 if (c->c2.link_socket->sd == SOCKET_UNDEFINED)
3915 {
3916 return -1;
3917 }
30003978 3918
81d882d5
DS
3919 socketfd = c->c2.link_socket->sd;
3920 if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
3921 {
3922 return socketfd;
3923 }
3924 else
3925 {
3926 return -2;
3927 }
30003978 3928}
81d882d5 3929#endif /* ifdef TARGET_ANDROID */
30003978 3930
81d882d5 3931#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
3932
3933void
81d882d5 3934init_management_callback_p2p(struct context *c)
6fbf66fa
JY
3935{
3936#ifdef ENABLE_MANAGEMENT
81d882d5
DS
3937 if (management)
3938 {
3939 struct management_callback cb;
3940 CLEAR(cb);
3941 cb.arg = c;
3942 cb.status = management_callback_status_p2p;
3943 cb.show_net = management_show_net_callback;
3944 cb.proxy_cmd = management_callback_proxy_cmd;
3945 cb.remote_cmd = management_callback_remote_cmd;
30003978 3946#ifdef TARGET_ANDROID
81d882d5 3947 cb.network_change = management_callback_network_change;
30003978 3948#endif
81d882d5 3949 management_set_callback(management, &cb);
6fbf66fa
JY
3950 }
3951#endif
3952}
3953
3954#ifdef ENABLE_MANAGEMENT
3955
3956void
91ba1add 3957init_management(void)
6fbf66fa 3958{
81d882d5
DS
3959 if (!management)
3960 {
3961 management = management_init();
3962 }
6fbf66fa
JY
3963}
3964
3965bool
81d882d5
DS
3966open_management(struct context *c)
3967{
3968 /* initialize management layer */
3969 if (management)
3970 {
3971 if (c->options.management_addr)
3972 {
3973 unsigned int flags = c->options.management_flags;
3974 if (c->options.mode == MODE_SERVER)
3975 {
3976 flags |= MF_SERVER;
3977 }
3978 if (management_open(management,
3979 c->options.management_addr,
3980 c->options.management_port,
3981 c->options.management_user_pass,
3982 c->options.management_client_user,
3983 c->options.management_client_group,
3984 c->options.management_log_history_cache,
3985 c->options.management_echo_buffer_size,
3986 c->options.management_state_buffer_size,
3987 c->options.management_write_peer_info_file,
3988 c->options.remap_sigusr1,
3989 flags))
3990 {
3991 management_set_state(management,
3992 OPENVPN_STATE_CONNECTING,
3993 NULL,
3994 NULL,
3995 NULL,
3996 NULL,
3997 NULL);
3998 }
3999
4000 /* initial management hold, called early, before first context initialization */
4001 do_hold(0);
4002 if (IS_SIG(c))
4003 {
4004 msg(M_WARN, "Signal received from management interface, exiting");
4005 return false;
4006 }
4007 }
4008 else
4009 {
4010 close_management();
4011 }
4012 }
4013 return true;
6fbf66fa
JY
4014}
4015
4016void
81d882d5 4017close_management(void)
6fbf66fa 4018{
81d882d5 4019 if (management)
6fbf66fa 4020 {
81d882d5
DS
4021 management_close(management);
4022 management = NULL;
6fbf66fa
JY
4023 }
4024}
4025
81d882d5 4026#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
4027
4028
4029void
81d882d5 4030uninit_management_callback(void)
6fbf66fa
JY
4031{
4032#ifdef ENABLE_MANAGEMENT
81d882d5 4033 if (management)
6fbf66fa 4034 {
81d882d5 4035 management_clear_callback(management);
6fbf66fa
JY
4036 }
4037#endif
4038}
4039
4040/*
4041 * Initialize a tunnel instance, handle pre and post-init
4042 * signal settings.
4043 */
4044void
81d882d5 4045init_instance_handle_signals(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 4046{
81d882d5
DS
4047 pre_init_signal_catch();
4048 init_instance(c, env, flags);
4049 post_init_signal_catch();
4050
4051 /*
4052 * This is done so that signals thrown during
4053 * initialization can bring us back to
4054 * a management hold.
4055 */
4056 if (IS_SIG(c))
d5badcf1 4057 {
81d882d5
DS
4058 remap_signal(c);
4059 uninit_management_callback();
d5badcf1 4060 }
6fbf66fa
JY
4061}
4062
4063/*
4064 * Initialize a tunnel instance.
4065 */
4066void
81d882d5 4067init_instance(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 4068{
81d882d5
DS
4069 const struct options *options = &c->options;
4070 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
4071 int link_socket_mode = LS_MODE_DEFAULT;
6fbf66fa 4072
81d882d5
DS
4073 /* init garbage collection level */
4074 gc_init(&c->c2.gc);
6fbf66fa 4075
81d882d5
DS
4076 /* inherit environmental variables */
4077 if (env)
4078 {
4079 do_inherit_env(c, env);
4080 }
ac1c2f25 4081
81d882d5
DS
4082 /* signals caught here will abort */
4083 c->sig->signal_received = 0;
4084 c->sig->signal_text = NULL;
4085 c->sig->source = SIG_SOURCE_SOFT;
6fbf66fa 4086
81d882d5
DS
4087 if (c->mode == CM_P2P)
4088 {
4089 init_management_callback_p2p(c);
4090 }
3cf6c932 4091
81d882d5
DS
4092 /* possible sleep or management hold if restart */
4093 if (c->mode == CM_P2P || c->mode == CM_TOP)
3cf6c932 4094 {
81d882d5
DS
4095 do_startup_pause(c);
4096 if (IS_SIG(c))
4097 {
4098 goto sig;
4099 }
3cf6c932
JY
4100 }
4101
81d882d5 4102 if (c->options.resolve_in_advance)
e719a053 4103 {
81d882d5
DS
4104 do_preresolve(c);
4105 if (IS_SIG(c))
4106 {
4107 goto sig;
4108 }
e719a053
AS
4109 }
4110
81d882d5
DS
4111 /* map in current connection entry */
4112 next_connection_entry(c);
4e9a51d7 4113
81d882d5
DS
4114 /* link_socket_mode allows CM_CHILD_TCP
4115 * instances to inherit acceptable fds
4116 * from a top-level parent */
4117 if (c->options.ce.proto == PROTO_TCP_SERVER)
6fbf66fa 4118 {
81d882d5
DS
4119 if (c->mode == CM_TOP)
4120 {
4121 link_socket_mode = LS_MODE_TCP_LISTEN;
4122 }
4123 else if (c->mode == CM_CHILD_TCP)
4124 {
4125 link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
4126 }
6fbf66fa
JY
4127 }
4128
81d882d5
DS
4129 /* should we disable paging? */
4130 if (c->first_time && options->mlock)
4131 {
4132 platform_mlockall(true);
4133 }
6fbf66fa 4134
92bbb061 4135#if P2MP
81d882d5
DS
4136 /* get passwords if undefined */
4137 if (auth_retry_get() == AR_INTERACT)
4138 {
4139 init_query_passwords(c);
4140 }
92bbb061
JY
4141#endif
4142
81d882d5
DS
4143 /* initialize context level 2 --verb/--mute parms */
4144 init_verb_mute(c, IVM_LEVEL_2);
4145
4146 /* set error message delay for non-server modes */
4147 if (c->mode == CM_P2P)
4148 {
4149 set_check_status_error_delay(P2P_ERROR_DELAY_MS);
4150 }
6fbf66fa 4151
81d882d5
DS
4152 /* warn about inconsistent options */
4153 if (c->mode == CM_P2P || c->mode == CM_TOP)
4154 {
4155 do_option_warnings(c);
4156 }
6fbf66fa 4157
3c7f2f55 4158#ifdef ENABLE_PLUGIN
81d882d5
DS
4159 /* initialize plugins */
4160 if (c->mode == CM_P2P || c->mode == CM_TOP)
4161 {
4162 open_plugins(c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
4163 }
3c7f2f55 4164#endif
6fbf66fa 4165
81d882d5
DS
4166 /* should we enable fast I/O? */
4167 if (c->mode == CM_P2P || c->mode == CM_TOP)
4168 {
4169 do_setup_fast_io(c);
4170 }
6fbf66fa 4171
81d882d5
DS
4172 /* should we throw a signal on TLS errors? */
4173 do_signal_on_tls_errors(c);
6fbf66fa 4174
81d882d5
DS
4175 /* open --status file */
4176 if (c->mode == CM_P2P || c->mode == CM_TOP)
4177 {
4178 do_open_status_output(c);
4179 }
6fbf66fa 4180
81d882d5
DS
4181 /* open --ifconfig-pool-persist file */
4182 if (c->mode == CM_TOP)
4183 {
4184 do_open_ifconfig_pool_persist(c);
4185 }
6fbf66fa
JY
4186
4187#ifdef ENABLE_OCC
81d882d5
DS
4188 /* reset OCC state */
4189 if (c->mode == CM_P2P || child)
4190 {
4191 c->c2.occ_op = occ_reset_op();
4192 }
6fbf66fa
JY
4193#endif
4194
81d882d5
DS
4195 /* our wait-for-i/o objects, different for posix vs. win32 */
4196 if (c->mode == CM_P2P)
4197 {
4198 do_event_set_init(c, SHAPER_DEFINED(&c->options));
4199 }
4200 else if (c->mode == CM_CHILD_TCP)
4201 {
4202 do_event_set_init(c, false);
4203 }
6fbf66fa 4204
81d882d5
DS
4205 /* initialize HTTP or SOCKS proxy object at scope level 2 */
4206 init_proxy(c);
4e9a51d7 4207
81d882d5
DS
4208 /* allocate our socket object */
4209 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4210 {
4211 do_link_socket_new(c);
4212 }
6fbf66fa
JY
4213
4214#ifdef ENABLE_FRAGMENT
81d882d5
DS
4215 /* initialize internal fragmentation object */
4216 if (options->ce.fragment && (c->mode == CM_P2P || child))
4217 {
4218 c->c2.fragment = fragment_init(&c->c2.frame);
4219 }
6fbf66fa
JY
4220#endif
4221
81d882d5
DS
4222 /* init crypto layer */
4223 {
4224 unsigned int crypto_flags = 0;
4225 if (c->mode == CM_TOP)
4226 {
4227 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
4228 }
4229 else if (c->mode == CM_P2P)
4230 {
4231 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
4232 }
4233 else if (child)
4234 {
4235 crypto_flags = CF_INIT_TLS_MULTI;
4236 }
4237 do_init_crypto(c, crypto_flags);
4238 if (IS_SIG(c) && !child)
4239 {
4240 goto sig;
4241 }
4242 }
6fbf66fa 4243
38d96bd7 4244#ifdef USE_COMP
81d882d5
DS
4245 /* initialize compression library. */
4246 if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
4247 {
4248 c->c2.comp_context = comp_init(&options->comp);
4249 }
6fbf66fa
JY
4250#endif
4251
81d882d5
DS
4252 /* initialize MTU variables */
4253 do_init_frame(c);
6fbf66fa 4254
81d882d5
DS
4255 /* initialize TLS MTU variables */
4256 do_init_frame_tls(c);
6fbf66fa 4257
81d882d5
DS
4258 /* init workspace buffers whose size is derived from frame size */
4259 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
4260 {
4261 do_init_buffers(c);
4262 }
6fbf66fa
JY
4263
4264#ifdef ENABLE_FRAGMENT
81d882d5
DS
4265 /* initialize internal fragmentation capability with known frame size */
4266 if (options->ce.fragment && (c->mode == CM_P2P || child))
4267 {
4268 do_init_fragment(c);
4269 }
6fbf66fa
JY
4270#endif
4271
81d882d5
DS
4272 /* initialize dynamic MTU variable */
4273 frame_init_mssfix(&c->c2.frame, &c->options);
6fbf66fa 4274
81d882d5
DS
4275 /* bind the TCP/UDP socket */
4276 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4277 {
4278 do_init_socket_1(c, link_socket_mode);
4279 }
6fbf66fa 4280
81d882d5
DS
4281 /* initialize tun/tap device object,
4282 * open tun/tap device, ifconfig, run up script, etc. */
4283 if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
4284 {
4285 c->c2.did_open_tun = do_open_tun(c);
4286 }
6fbf66fa 4287
9900e023
SK
4288 c->c2.frame_initial = c->c2.frame;
4289
81d882d5
DS
4290 /* print MTU info */
4291 do_print_data_channel_mtu_parms(c);
6fbf66fa
JY
4292
4293#ifdef ENABLE_OCC
81d882d5
DS
4294 /* get local and remote options compatibility strings */
4295 if (c->mode == CM_P2P || child)
4296 {
4297 do_compute_occ_strings(c);
4298 }
6fbf66fa
JY
4299#endif
4300
81d882d5
DS
4301 /* initialize output speed limiter */
4302 if (c->mode == CM_P2P)
4303 {
4304 do_init_traffic_shaper(c);
4305 }
6fbf66fa 4306
ccb636c7 4307 /* do one-time inits, and possibly become a daemon here */
81d882d5 4308 do_init_first_time(c);
6fbf66fa 4309
e1791bb1 4310#ifdef ENABLE_PLUGIN
81d882d5
DS
4311 /* initialize plugins */
4312 if (c->mode == CM_P2P || c->mode == CM_TOP)
4313 {
4314 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
4315 }
e1791bb1
JY
4316#endif
4317
81d882d5
DS
4318 /* initialise connect timeout timer */
4319 do_init_server_poll_timeout(c);
4db06290 4320
81d882d5
DS
4321 /* finalize the TCP/UDP socket */
4322 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4323 {
4324 do_init_socket_2(c);
4325 }
b3e97582 4326
81d882d5
DS
4327 /*
4328 * Actually do UID/GID downgrade, and chroot, if requested.
4329 * May be delayed by --client, --pull, or --up-delay.
4330 */
4331 do_uid_gid_chroot(c, c->c2.did_open_tun);
6fbf66fa 4332
81d882d5
DS
4333 /* initialize timers */
4334 if (c->mode == CM_P2P || child)
4335 {
4336 do_init_timers(c, false);
4337 }
6fbf66fa 4338
e1791bb1 4339#ifdef ENABLE_PLUGIN
81d882d5
DS
4340 /* initialize plugins */
4341 if (c->mode == CM_P2P || c->mode == CM_TOP)
4342 {
4343 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
4344 }
e1791bb1
JY
4345#endif
4346
6add6b2f 4347#if PORT_SHARE
81d882d5
DS
4348 /* share OpenVPN port with foreign (such as HTTPS) server */
4349 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
4350 {
4351 init_port_share(c);
4352 }
6add6b2f 4353#endif
81d882d5 4354
47ae8457 4355#ifdef ENABLE_PF
81d882d5
DS
4356 if (child)
4357 {
4358 pf_init_context(c);
4359 }
47ae8457
JY
4360#endif
4361
81d882d5
DS
4362 /* Check for signals */
4363 if (IS_SIG(c))
4364 {
4365 goto sig;
4366 }
6fbf66fa 4367
81d882d5 4368 return;
6fbf66fa 4369
81d882d5
DS
4370sig:
4371 if (!c->sig->signal_text)
4372 {
4373 c->sig->signal_text = "init_instance";
4374 }
4375 close_context(c, -1, flags);
4376 return;
6fbf66fa
JY
4377}
4378
4379/*
4380 * Close a tunnel instance.
4381 */
4382void
81d882d5 4383close_instance(struct context *c)
6fbf66fa 4384{
81d882d5
DS
4385 /* close event objects */
4386 do_close_event_set(c);
6fbf66fa
JY
4387
4388 if (c->mode == CM_P2P
81d882d5
DS
4389 || c->mode == CM_CHILD_TCP
4390 || c->mode == CM_CHILD_UDP
4391 || c->mode == CM_TOP)
4392 {
4393 /* if xinetd/inetd mode, don't allow restart */
4394 do_close_check_if_restart_permitted(c);
6fbf66fa 4395
38d96bd7 4396#ifdef USE_COMP
81d882d5
DS
4397 if (c->c2.comp_context)
4398 {
4399 comp_uninit(c->c2.comp_context);
4400 c->c2.comp_context = NULL;
4401 }
6fbf66fa
JY
4402#endif
4403
81d882d5
DS
4404 /* free buffers */
4405 do_close_free_buf(c);
6fbf66fa 4406
81d882d5
DS
4407 /* close TLS */
4408 do_close_tls(c);
6fbf66fa 4409
81d882d5
DS
4410 /* free key schedules */
4411 do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP));
6fbf66fa 4412
39326238 4413 restore_ncp_options(c);
5fa25eeb 4414
81d882d5
DS
4415 /* close TCP/UDP connection */
4416 do_close_link_socket(c);
6fbf66fa 4417
81d882d5
DS
4418 /* close TUN/TAP device */
4419 do_close_tun(c, false);
6fbf66fa 4420
90efcacb 4421#ifdef MANAGEMENT_DEF_AUTH
81d882d5
DS
4422 if (management)
4423 {
4424 management_notify_client_close(management, &c->c2.mda_context, NULL);
4425 }
90efcacb
JY
4426#endif
4427
47ae8457 4428#ifdef ENABLE_PF
81d882d5 4429 pf_destroy_context(&c->c2.pf);
47ae8457
JY
4430#endif
4431
3c7f2f55 4432#ifdef ENABLE_PLUGIN
81d882d5
DS
4433 /* call plugin close functions and unload */
4434 do_close_plugins(c);
3c7f2f55 4435#endif
6fbf66fa 4436
ccb636c7 4437 /* close packet-id persistence file */
81d882d5 4438 do_close_packet_id(c);
6fbf66fa 4439
81d882d5
DS
4440 /* close --status file */
4441 do_close_status_output(c);
6fbf66fa
JY
4442
4443#ifdef ENABLE_FRAGMENT
81d882d5
DS
4444 /* close fragmentation handler */
4445 do_close_fragment(c);
6fbf66fa
JY
4446#endif
4447
81d882d5
DS
4448 /* close --ifconfig-pool-persist obj */
4449 do_close_ifconfig_pool_persist(c);
6fbf66fa 4450
81d882d5
DS
4451 /* free up environmental variable store */
4452 do_env_set_destroy(c);
2a64816b 4453
81d882d5
DS
4454 /* close HTTP or SOCKS proxy */
4455 uninit_proxy(c);
4e9a51d7 4456
81d882d5
DS
4457 /* garbage collect */
4458 gc_free(&c->c2.gc);
4459 }
6fbf66fa
JY
4460}
4461
4462void
81d882d5
DS
4463inherit_context_child(struct context *dest,
4464 const struct context *src)
6fbf66fa 4465{
81d882d5 4466 CLEAR(*dest);
6fbf66fa 4467
81d882d5
DS
4468 /* proto_is_dgram will ASSERT(0) if proto is invalid */
4469 dest->mode = proto_is_dgram(src->options.ce.proto) ? CM_CHILD_UDP : CM_CHILD_TCP;
6fbf66fa 4470
81d882d5 4471 dest->gc = gc_new();
6fbf66fa 4472
81d882d5 4473 ALLOC_OBJ_CLEAR_GC(dest->sig, struct signal_info, &dest->gc);
6fbf66fa 4474
81d882d5
DS
4475 /* c1 init */
4476 packet_id_persist_init(&dest->c1.pid_persist);
6fbf66fa 4477
81d882d5
DS
4478 dest->c1.ks.key_type = src->c1.ks.key_type;
4479 /* inherit SSL context */
4480 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
4481 dest->c1.ks.tls_wrap_key = src->c1.ks.tls_wrap_key;
4482 dest->c1.ks.tls_auth_key_type = src->c1.ks.tls_auth_key_type;
19dffdbd 4483 dest->c1.ks.tls_crypt_v2_server_key = src->c1.ks.tls_crypt_v2_server_key;
81d882d5
DS
4484 /* inherit pre-NCP ciphers */
4485 dest->c1.ciphername = src->c1.ciphername;
4486 dest->c1.authname = src->c1.authname;
4487 dest->c1.keysize = src->c1.keysize;
81d882d5
DS
4488
4489 /* options */
4490 dest->options = src->options;
4491 options_detach(&dest->options);
4492
4493 if (dest->mode == CM_CHILD_TCP)
6fbf66fa 4494 {
81d882d5
DS
4495 /*
4496 * The CM_TOP context does the socket listen(),
4497 * and the CM_CHILD_TCP context does the accept().
4498 */
4499 dest->c2.accept_from = src->c2.link_socket;
6fbf66fa
JY
4500 }
4501
3c7f2f55 4502#ifdef ENABLE_PLUGIN
81d882d5
DS
4503 /* inherit plugins */
4504 do_inherit_plugins(dest, src);
3c7f2f55 4505#endif
6fbf66fa 4506
81d882d5
DS
4507 /* context init */
4508 init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
4509 if (IS_SIG(dest))
4510 {
4511 return;
4512 }
6fbf66fa 4513
81d882d5
DS
4514 /* inherit tun/tap interface object */
4515 dest->c1.tuntap = src->c1.tuntap;
6fbf66fa 4516
81d882d5
DS
4517 /* UDP inherits some extra things which TCP does not */
4518 if (dest->mode == CM_CHILD_UDP)
6fbf66fa 4519 {
81d882d5
DS
4520 /* inherit buffers */
4521 dest->c2.buffers = src->c2.buffers;
6fbf66fa 4522
81d882d5
DS
4523 /* inherit parent link_socket and tuntap */
4524 dest->c2.link_socket = src->c2.link_socket;
6fbf66fa 4525
81d882d5
DS
4526 ALLOC_OBJ_GC(dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
4527 *dest->c2.link_socket_info = src->c2.link_socket->info;
6fbf66fa 4528
81d882d5
DS
4529 /* locally override some link_socket_info fields */
4530 dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
4531 dest->c2.link_socket_info->connection_established = false;
6fbf66fa
JY
4532 }
4533}
4534
4535void
81d882d5
DS
4536inherit_context_top(struct context *dest,
4537 const struct context *src)
6fbf66fa 4538{
81d882d5
DS
4539 /* copy parent */
4540 *dest = *src;
6fbf66fa 4541
81d882d5
DS
4542 /*
4543 * CM_TOP_CLONE will prevent close_instance from freeing or closing
4544 * resources owned by the parent.
4545 *
4546 * Also note that CM_TOP_CLONE context objects are
4547 * closed by multi_top_free in multi.c.
4548 */
4549 dest->mode = CM_TOP_CLONE;
6fbf66fa 4550
81d882d5
DS
4551 dest->first_time = false;
4552 dest->c0 = NULL;
6fbf66fa 4553
81d882d5
DS
4554 options_detach(&dest->options);
4555 gc_detach(&dest->gc);
4556 gc_detach(&dest->c2.gc);
6fbf66fa 4557
81d882d5
DS
4558 /* detach plugins */
4559 dest->plugins_owned = false;
3c7f2f55 4560
81d882d5 4561 dest->c2.tls_multi = NULL;
6fbf66fa 4562
81d882d5
DS
4563 /* detach c1 ownership */
4564 dest->c1.tuntap_owned = false;
4565 dest->c1.status_output_owned = false;
6fbf66fa 4566#if P2MP_SERVER
81d882d5 4567 dest->c1.ifconfig_pool_persist_owned = false;
6fbf66fa 4568#endif
3c7f2f55 4569
81d882d5
DS
4570 /* detach c2 ownership */
4571 dest->c2.event_set_owned = false;
4572 dest->c2.link_socket_owned = false;
4573 dest->c2.buffers_owned = false;
4574 dest->c2.es_owned = false;
6fbf66fa 4575
81d882d5
DS
4576 dest->c2.event_set = NULL;
4577 if (proto_is_dgram(src->options.ce.proto))
4578 {
4579 do_event_set_init(dest, false);
4580 }
38d96bd7
JY
4581
4582#ifdef USE_COMP
81d882d5 4583 dest->c2.comp_context = NULL;
38d96bd7 4584#endif
6fbf66fa
JY
4585}
4586
4587void
81d882d5 4588close_context(struct context *c, int sig, unsigned int flags)
6fbf66fa 4589{
81d882d5
DS
4590 ASSERT(c);
4591 ASSERT(c->sig);
79df31c8 4592
81d882d5
DS
4593 if (sig >= 0)
4594 {
4595 c->sig->signal_received = sig;
4596 }
6fbf66fa 4597
81d882d5 4598 if (c->sig->signal_received == SIGUSR1)
6fbf66fa 4599 {
81d882d5
DS
4600 if ((flags & CC_USR1_TO_HUP)
4601 || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
c058cbff 4602 {
81d882d5
DS
4603 c->sig->signal_received = SIGHUP;
4604 c->sig->signal_text = "close_context usr1 to hup";
c058cbff 4605 }
6fbf66fa
JY
4606 }
4607
81d882d5
DS
4608 if (!(flags & CC_NO_CLOSE))
4609 {
4610 close_instance(c);
4611 }
6fbf66fa 4612
81d882d5
DS
4613 if (flags & CC_GC_FREE)
4614 {
4615 context_gc_free(c);
4616 }
6fbf66fa
JY
4617}
4618
6fbf66fa
JY
4619/*
4620 * Do a loopback test
4621 * on the crypto subsystem.
4622 */
4623static void *
81d882d5 4624test_crypto_thread(void *arg)
6fbf66fa 4625{
81d882d5
DS
4626 struct context *c = (struct context *) arg;
4627 const struct options *options = &c->options;
6fbf66fa 4628
81d882d5
DS
4629 ASSERT(options->test_crypto);
4630 init_verb_mute(c, IVM_LEVEL_1);
4631 context_init_1(c);
4632 next_connection_entry(c);
4633 do_init_crypto_static(c, 0);
6fbf66fa 4634
81d882d5 4635 frame_finalize_options(c, options);
6fbf66fa 4636
81d882d5 4637 test_crypto(&c->c2.crypto_options, &c->c2.frame);
6fbf66fa 4638
81d882d5
DS
4639 key_schedule_free(&c->c1.ks, true);
4640 packet_id_free(&c->c2.crypto_options.packet_id);
6fbf66fa 4641
81d882d5
DS
4642 context_gc_free(c);
4643 return NULL;
6fbf66fa
JY
4644}
4645
6fbf66fa 4646bool
81d882d5 4647do_test_crypto(const struct options *o)
6fbf66fa 4648{
81d882d5 4649 if (o->test_crypto)
6fbf66fa 4650 {
81d882d5 4651 struct context c;
6fbf66fa 4652
81d882d5
DS
4653 /* print version number */
4654 msg(M_INFO, "%s", title_string);
6fbf66fa 4655
81d882d5
DS
4656 context_clear(&c);
4657 c.options = *o;
4658 options_detach(&c.options);
4659 c.first_time = true;
4660 test_crypto_thread((void *) &c);
4661 return true;
6fbf66fa 4662 }
81d882d5 4663 return false;
6fbf66fa 4664}