]> git.ipfire.org Git - thirdparty/openvpn.git/blame - src/openvpn/init.c
Fix new doxygen warnings about using @return in void functions
[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 *
022f0a43 8 * Copyright (C) 2002-2025 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"
c110b289
ABL
26#endif
27
6fbf66fa
JY
28#include "syshead.h"
29
c5931897
CH
30#ifdef ENABLE_SYSTEMD
31#include <systemd/sd-daemon.h>
32#endif
33
6fbf66fa
JY
34#include "win32.h"
35#include "init.h"
bf97c00f 36#include "run_command.h"
6fbf66fa
JY
37#include "sig.h"
38#include "occ.h"
39#include "list.h"
40#include "otime.h"
41#include "pool.h"
42#include "gremlin.h"
a54f37d8 43#include "occ.h"
ce98fd24 44#include "pkcs11.h"
6add6b2f 45#include "ps.h"
e12fe286 46#include "lladdr.h"
e7a65dfb 47#include "ping.h"
ffea644c 48#include "mstats.h"
63dc03d0 49#include "ssl_verify.h"
1828f9c1 50#include "ssl_ncp.h"
c6e24fa3 51#include "tls_crypt.h"
a54f37d8 52#include "forward.h"
1b9a88a2 53#include "auth_token.h"
d4458eed 54#include "mss.h"
b3647114 55#include "mudp.h"
a2d851d4 56#include "dco.h"
d0a93625 57#include "tun_afunix.h"
6fbf66fa
JY
58
59#include "memdbg.h"
60
6fbf66fa 61
0c9eb1d3 62static struct context *static_context; /* GLOBAL */
008ec688 63static const char *saved_pid_file_name; /* GLOBAL */
0c9eb1d3 64
6fbf66fa
JY
65/*
66 * Crypto initialization flags
67 */
68#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
69#define CF_INIT_TLS_MULTI (1<<1)
70#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
71
81d882d5 72static void do_init_first_time(struct context *c);
7d48d31b 73
8c72d798 74static bool do_deferred_p2p_ncp(struct context *c);
6fbf66fa
JY
75
76void
81d882d5 77context_clear(struct context *c)
6fbf66fa 78{
81d882d5 79 CLEAR(*c);
6fbf66fa
JY
80}
81
82void
81d882d5 83context_clear_1(struct context *c)
6fbf66fa 84{
81d882d5 85 CLEAR(c->c1);
6fbf66fa
JY
86}
87
88void
81d882d5 89context_clear_2(struct context *c)
6fbf66fa 90{
81d882d5 91 CLEAR(c->c2);
6fbf66fa
JY
92}
93
94void
81d882d5 95context_clear_all_except_first_time(struct context *c)
6fbf66fa 96{
81d882d5
DS
97 const bool first_time_save = c->first_time;
98 const struct context_persist cpsave = c->persist;
99 context_clear(c);
100 c->first_time = first_time_save;
101 c->persist = cpsave;
6fbf66fa
JY
102}
103
4a9d1d70
SK
104/*
105 * Pass tunnel endpoint and MTU parms to a user-supplied script.
106 * Used to execute the up/down script/plugins.
107 */
108static void
109run_up_down(const char *command,
110 const struct plugin_list *plugins,
111 int plugin_type,
112 const char *arg,
113#ifdef _WIN32
114 DWORD adapter_index,
115#endif
116 const char *dev_type,
117 int tun_mtu,
4a9d1d70
SK
118 const char *ifconfig_local,
119 const char *ifconfig_remote,
120 const char *context,
121 const char *signal_text,
122 const char *script_type,
123 struct env_set *es)
124{
125 struct gc_arena gc = gc_new();
126
127 if (signal_text)
128 {
129 setenv_str(es, "signal", signal_text);
130 }
131 setenv_str(es, "script_context", context);
132 setenv_int(es, "tun_mtu", tun_mtu);
4a9d1d70
SK
133 setenv_str(es, "dev", arg);
134 if (dev_type)
135 {
136 setenv_str(es, "dev_type", dev_type);
137 }
138#ifdef _WIN32
139 setenv_int(es, "dev_idx", adapter_index);
140#endif
141
142 if (!ifconfig_local)
143 {
144 ifconfig_local = "";
145 }
146 if (!ifconfig_remote)
147 {
148 ifconfig_remote = "";
149 }
150 if (!context)
151 {
152 context = "";
153 }
154
155 if (plugin_defined(plugins, plugin_type))
156 {
157 struct argv argv = argv_new();
158 ASSERT(arg);
159 argv_printf(&argv,
3780ce0e
AS
160 "%s %d 0 %s %s %s",
161 arg, tun_mtu, ifconfig_local, ifconfig_remote, context);
4a9d1d70
SK
162
163 if (plugin_call(plugins, plugin_type, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
164 {
165 msg(M_FATAL, "ERROR: up/down plugin call failed");
166 }
167
870e2405 168 argv_free(&argv);
4a9d1d70
SK
169 }
170
171 if (command)
172 {
173 struct argv argv = argv_new();
174 ASSERT(arg);
175 setenv_str(es, "script_type", script_type);
176 argv_parse_cmd(&argv, command);
3780ce0e 177 argv_printf_cat(&argv, "%s %d 0 %s %s %s", arg, tun_mtu,
4a9d1d70
SK
178 ifconfig_local, ifconfig_remote, context);
179 argv_msg(M_INFO, &argv);
180 openvpn_run_script(&argv, es, S_FATAL, "--up/--down");
870e2405 181 argv_free(&argv);
4a9d1d70
SK
182 }
183
184 gc_free(&gc);
185}
186
6fbf66fa 187/*
4e9a51d7
JY
188 * Should be called after options->ce is modified at the top
189 * of a SIGUSR1 restart.
6fbf66fa
JY
190 */
191static void
81d882d5 192update_options_ce_post(struct options *options)
6fbf66fa 193{
81d882d5
DS
194 /*
195 * In pull mode, we usually import --ping/--ping-restart parameters from
196 * the server. However we should also set an initial default --ping-restart
197 * for the period of time before we pull the --ping-restart parameter
198 * from the server.
199 */
200 if (options->pull
201 && options->ping_rec_timeout_action == PING_UNDEF
202 && proto_is_dgram(options->ce.proto))
4e9a51d7 203 {
81d882d5
DS
204 options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
205 options->ping_rec_timeout_action = PING_RESTART;
4e9a51d7 206 }
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));
93ba6ccd 273 management->persist.special_state_msg = BSTR(&out);
81d882d5
DS
274 }
275 ce->flags |= CE_MAN_QUERY_PROXY;
276 while (ce->flags & CE_MAN_QUERY_PROXY)
277 {
278 management_event_loop_n_seconds(management, 1);
279 if (IS_SIG(c))
af1bf85a 280 {
81d882d5
DS
281 ret = false;
282 break;
af1bf85a
HH
283 }
284 }
93ba6ccd 285 management->persist.special_state_msg = NULL;
81d882d5 286 gc_free(&gc);
3cf6c932 287 }
af1bf85a 288
81d882d5 289 return ret;
3cf6c932
JY
290}
291
adb9bb91
AS
292/**
293 * This method sends a custom control channel message
294 *
295 * This will write the control message
296 *
ccdffc08
FL
297 * command parm1,parm2,...
298 *
adb9bb91
AS
299 * to the control channel.
300 *
301 * @param arg The context struct
302 * @param command The command being sent
303 * @param parameters the parameters to the command
304 * @return if sending was successful
305 */
306static bool
307management_callback_send_cc_message(void *arg,
308 const char *command,
309 const char *parameters)
310{
311 struct context *c = (struct context *) arg;
62560e2a 312 size_t len = strlen(command) + 1 + strlen(parameters) + 1;
adb9bb91
AS
313 if (len > PUSH_BUNDLE_SIZE)
314 {
315 return false;
316 }
317
318 struct gc_arena gc = gc_new();
319 struct buffer buf = alloc_buf_gc(len, &gc);
320 ASSERT(buf_printf(&buf, "%s", command));
321 if (parameters)
322 {
323 ASSERT(buf_printf(&buf, ",%s", parameters));
324 }
325 bool status = send_control_channel_string(c, BSTR(&buf), D_PUSH);
326
327 gc_free(&gc);
328 return status;
329}
3cf6c932 330
12526380
SN
331static unsigned int
332management_callback_remote_entry_count(void *arg)
333{
334 assert(arg);
335 struct context *c = (struct context *) arg;
336 struct connection_list *l = c->options.connection_list;
337
338 return l->len;
339}
340
341static bool
342management_callback_remote_entry_get(void *arg, unsigned int index, char **remote)
343{
344 assert(arg);
345 assert(remote);
346
347 struct context *c = (struct context *) arg;
348 struct connection_list *l = c->options.connection_list;
349 bool ret = true;
350
351 if (index < l->len)
352 {
353 struct connection_entry *ce = l->array[index];
354 const char *proto = proto2ascii(ce->proto, ce->af, false);
eafbedc5 355 const char *status = (ce->flags & CE_DISABLED) ? "disabled" : "enabled";
12526380 356
eafbedc5
SN
357 /* space for output including 3 commas and a nul */
358 int len = strlen(ce->remote) + strlen(ce->remote_port) + strlen(proto)
359 + strlen(status) + 3 + 1;
12526380
SN
360 char *out = malloc(len);
361 check_malloc_return(out);
362
130548fe 363 snprintf(out, len, "%s,%s,%s,%s", ce->remote, ce->remote_port, proto, status);
12526380
SN
364 *remote = out;
365 }
366 else
367 {
368 ret = false;
369 msg(M_WARN, "Out of bounds index in management query for remote entry: index = %u", index);
370 }
371
372 return ret;
373}
374
54561af6 375static bool
81d882d5
DS
376management_callback_remote_cmd(void *arg, const char **p)
377{
378 struct context *c = (struct context *) arg;
379 struct connection_entry *ce = &c->options.ce;
380 int ret = false;
381 if (p[1] && ((ce->flags>>CE_MAN_QUERY_REMOTE_SHIFT)&CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
382 {
383 int flags = 0;
384 if (!strcmp(p[1], "ACCEPT"))
385 {
386 flags = CE_MAN_QUERY_REMOTE_ACCEPT;
387 ret = true;
388 }
389 else if (!strcmp(p[1], "SKIP"))
390 {
391 flags = CE_MAN_QUERY_REMOTE_SKIP;
392 ret = true;
ec5ffe35 393 c->options.ce_advance_count = (p[2]) ? atoi(p[2]) : 1;
81d882d5
DS
394 }
395 else if (!strcmp(p[1], "MOD") && p[2] && p[3])
396 {
397 if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
398 {
399 struct remote_host_store *rhs = c->options.rh_store;
400 if (!rhs)
401 {
402 ALLOC_OBJ_CLEAR_GC(rhs, struct remote_host_store, &c->options.gc);
403 c->options.rh_store = rhs;
404 }
405 strncpynt(rhs->host, p[2], RH_HOST_LEN);
406 strncpynt(rhs->port, p[3], RH_PORT_LEN);
407
408 ce->remote = rhs->host;
409 ce->remote_port = rhs->port;
410 flags = CE_MAN_QUERY_REMOTE_MOD;
411 ret = true;
412 }
413 }
414 if (ret)
415 {
416 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK<<CE_MAN_QUERY_REMOTE_SHIFT);
417 ce->flags |= ((flags&CE_MAN_QUERY_REMOTE_MASK)<<CE_MAN_QUERY_REMOTE_SHIFT);
418 }
419 }
420 return ret;
54561af6
JY
421}
422
423static bool
81d882d5
DS
424ce_management_query_remote(struct context *c)
425{
426 struct gc_arena gc = gc_new();
427 volatile struct connection_entry *ce = &c->options.ce;
e81f313a
DS
428 int ce_changed = true; /* presume the connection entry will be changed */
429
81d882d5
DS
430 update_time();
431 if (management)
432 {
433 struct buffer out = alloc_buf_gc(256, &gc);
e81f313a
DS
434
435 buf_printf(&out, ">REMOTE:%s,%s,%s", np(ce->remote), ce->remote_port,
436 proto2ascii(ce->proto, ce->af, false));
81d882d5 437 management_notify_generic(management, BSTR(&out));
93ba6ccd 438 management->persist.special_state_msg = BSTR(&out);
e81f313a
DS
439
440 ce->flags &= ~(CE_MAN_QUERY_REMOTE_MASK << CE_MAN_QUERY_REMOTE_SHIFT);
441 ce->flags |= (CE_MAN_QUERY_REMOTE_QUERY << CE_MAN_QUERY_REMOTE_SHIFT);
442 while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
443 & CE_MAN_QUERY_REMOTE_MASK) == CE_MAN_QUERY_REMOTE_QUERY)
81d882d5
DS
444 {
445 management_event_loop_n_seconds(management, 1);
446 if (IS_SIG(c))
447 {
e81f313a 448 ce_changed = false; /* connection entry have not been set */
81d882d5
DS
449 break;
450 }
451 }
93ba6ccd 452 management->persist.special_state_msg = NULL;
81d882d5 453 }
e81f313a
DS
454 gc_free(&gc);
455
456 if (ce_changed)
81d882d5 457 {
e81f313a
DS
458 /* If it is likely a connection entry was modified,
459 * check what changed in the flags and that it was not skipped
460 */
461 const int flags = ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
462 & CE_MAN_QUERY_REMOTE_MASK);
463 ce_changed = (flags != CE_MAN_QUERY_REMOTE_SKIP);
81d882d5 464 }
e81f313a 465 return ce_changed;
54561af6 466}
cf93f0e0 467#endif /* ENABLE_MANAGEMENT */
54561af6 468
4e9a51d7 469/*
9502e525
SF
470 * Initialize and possibly randomize the connection list.
471 *
472 * Applies the Fisher-Yates shuffle algorithm to ensure all permutations
473 * are equally probable, thereby eliminating shuffling bias.
474 *
475 * The algorithm randomly selects an element from the unshuffled portion
476 * and places it at position i. There's only one way to obtain each
477 * permutation through these swaps. This guarantees that each permutation
478 * occurs with equal probability in theory.
4e9a51d7
JY
479 */
480static void
81d882d5 481init_connection_list(struct context *c)
4e9a51d7 482{
81d882d5 483 struct connection_list *l = c->options.connection_list;
23d61c56 484
81d882d5
DS
485 l->current = -1;
486 if (c->options.remote_random)
6fbf66fa 487 {
81d882d5 488 int i;
9502e525 489 for (i = l->len - 1; i > 0; --i)
23d61c56 490 {
9502e525 491 const int j = get_random() % (i + 1);
81d882d5 492 if (i != j)
23d61c56 493 {
81d882d5
DS
494 struct connection_entry *tmp;
495 tmp = l->array[i];
496 l->array[i] = l->array[j];
497 l->array[j] = tmp;
23d61c56
AS
498 }
499 }
6fbf66fa 500 }
4e9a51d7
JY
501}
502
23d61c56
AS
503/*
504 * Clear the remote address list
505 */
81d882d5
DS
506static void
507clear_remote_addrlist(struct link_socket_addr *lsa, bool free)
23d61c56 508{
e719a053 509 if (lsa->remote_list && free)
81d882d5
DS
510 {
511 freeaddrinfo(lsa->remote_list);
512 }
23d61c56
AS
513 lsa->remote_list = NULL;
514 lsa->current_remote = NULL;
515}
516
4e9a51d7
JY
517/*
518 * Increment to next connection entry
519 */
520static void
81d882d5
DS
521next_connection_entry(struct context *c)
522{
523 struct connection_list *l = c->options.connection_list;
524 bool ce_defined;
525 struct connection_entry *ce;
526 int n_cycles = 0;
527
4cd4899e
SK
528 do
529 {
81d882d5
DS
530 ce_defined = true;
531 if (c->options.no_advance && l->current >= 0)
532 {
533 c->options.no_advance = false;
534 }
23d61c56 535 else
81d882d5
DS
536 {
537 /* Check if there is another resolved address to try for
538 * the current connection */
94b391d7
AQ
539 if (c->c1.link_socket_addrs[0].current_remote
540 && c->c1.link_socket_addrs[0].current_remote->ai_next
c9474fa3 541 && !c->options.advance_next_remote)
81d882d5 542 {
94b391d7
AQ
543 c->c1.link_socket_addrs[0].current_remote =
544 c->c1.link_socket_addrs[0].current_remote->ai_next;
81d882d5
DS
545 }
546 else
547 {
c9474fa3 548 c->options.advance_next_remote = false;
81d882d5
DS
549 /* FIXME (schwabe) fix the persist-remote-ip option for real,
550 * this is broken probably ever since connection lists and multiple
551 * remote existed
552 */
553 if (!c->options.persist_remote_ip)
554 {
3ad86c25
VG
555 /* Connection entry addrinfo objects might have been
556 * resolved earlier but the entry itself might have been
557 * skipped by management on the previous loop.
558 * If so, clear the addrinfo objects as close_instance does
559 */
94b391d7 560 if (c->c1.link_socket_addrs[0].remote_list)
3ad86c25 561 {
94b391d7 562 clear_remote_addrlist(&c->c1.link_socket_addrs[0],
3ad86c25
VG
563 !c->options.resolve_in_advance);
564 }
565
81d882d5 566 /* close_instance should have cleared the addrinfo objects */
94b391d7
AQ
567 ASSERT(c->c1.link_socket_addrs[0].current_remote == NULL);
568 ASSERT(c->c1.link_socket_addrs[0].remote_list == NULL);
81d882d5
DS
569 }
570 else
571 {
94b391d7
AQ
572 c->c1.link_socket_addrs[0].current_remote =
573 c->c1.link_socket_addrs[0].remote_list;
81d882d5
DS
574 }
575
ec5ffe35
SN
576 int advance_count = 1;
577
578 /* If previous connection entry was skipped by management client
579 * with a count to advance by, apply it.
580 */
581 if (c->options.ce_advance_count > 0)
582 {
583 advance_count = c->options.ce_advance_count;
584 }
585
81d882d5
DS
586 /*
587 * Increase the number of connection attempts
588 * If this is connect-retry-max * size(l)
589 * OpenVPN will quit
590 */
591
ec5ffe35
SN
592 c->options.unsuccessful_attempts += advance_count;
593 l->current += advance_count;
81d882d5 594
ec5ffe35 595 if (l->current >= l->len)
81d882d5 596 {
ec5ffe35 597 l->current %= l->len;
81d882d5
DS
598 if (++n_cycles >= 2)
599 {
600 msg(M_FATAL, "No usable connection profiles are present");
601 }
602 }
603 }
604 }
3cf6c932 605
ec5ffe35 606 c->options.ce_advance_count = 1;
81d882d5 607 ce = l->array[l->current];
3cf6c932 608
81d882d5
DS
609 if (ce->flags & CE_DISABLED)
610 {
611 ce_defined = false;
612 }
3cf6c932 613
81d882d5 614 c->options.ce = *ce;
619c3e9a 615
cf93f0e0 616#ifdef ENABLE_MANAGEMENT
81d882d5
DS
617 if (ce_defined && management && management_query_remote_enabled(management))
618 {
619 /* allow management interface to override connection entry details */
620 ce_defined = ce_management_query_remote(c);
621 if (IS_SIG(c))
622 {
623 break;
624 }
625 }
7b02cc2a 626 else if (ce_defined && management && management_query_proxy_enabled(management))
23d61c56 627 {
81d882d5
DS
628 ce_defined = ce_management_query_proxy(c);
629 if (IS_SIG(c))
630 {
631 break;
632 }
23d61c56 633 }
3cf6c932 634#endif
81d882d5 635 } while (!ce_defined);
23d61c56 636
81d882d5
DS
637 /* Check if this connection attempt would bring us over the limit */
638 if (c->options.connect_retry_max > 0
639 && c->options.unsuccessful_attempts > (l->len * c->options.connect_retry_max))
640 {
641 msg(M_FATAL, "All connections have been connect-retry-max (%d) times unsuccessful, exiting",
642 c->options.connect_retry_max);
643 }
644 update_options_ce_post(&c->options);
6fbf66fa
JY
645}
646
92bbb061
JY
647/*
648 * Query for private key and auth-user-pass username/passwords
649 */
315f6fbc 650void
81d882d5 651init_query_passwords(const struct context *c)
92bbb061 652{
81d882d5
DS
653 /* Certificate password input */
654 if (c->options.key_pass_file)
655 {
656 pem_password_setup(c->options.key_pass_file);
657 }
81d882d5 658
81d882d5
DS
659 /* Auth user/pass input */
660 if (c->options.auth_user_pass_file)
eab3e22f 661 {
7d291e10 662 enable_auth_user_pass();
66b9409b 663#ifdef ENABLE_MANAGEMENT
7d48d31b
AQ
664 auth_user_pass_setup(c->options.auth_user_pass_file,
665 c->options.auth_user_pass_file_inline,
666 &c->options.sc_info);
eab3e22f 667#else
7d48d31b
AQ
668 auth_user_pass_setup(c->options.auth_user_pass_file,
669 c->options.auth_user_pass_file_inline, NULL);
eab3e22f
JY
670#endif
671 }
92bbb061
JY
672}
673
4e9a51d7
JY
674/*
675 * Initialize/Uninitialize HTTP or SOCKS proxy
676 */
677
4e9a51d7 678static void
81d882d5 679uninit_proxy_dowork(struct context *c)
4e9a51d7 680{
81d882d5 681 if (c->c1.http_proxy_owned && c->c1.http_proxy)
4e9a51d7 682 {
81d882d5
DS
683 http_proxy_close(c->c1.http_proxy);
684 c->c1.http_proxy = NULL;
685 c->c1.http_proxy_owned = false;
4e9a51d7 686 }
81d882d5 687 if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
4e9a51d7 688 {
81d882d5
DS
689 socks_proxy_close(c->c1.socks_proxy);
690 c->c1.socks_proxy = NULL;
691 c->c1.socks_proxy_owned = false;
4e9a51d7 692 }
4e9a51d7
JY
693}
694
695static void
81d882d5 696init_proxy_dowork(struct context *c)
6fbf66fa 697{
81d882d5 698 bool did_http = false;
f214bb21 699
81d882d5 700 uninit_proxy_dowork(c);
4e9a51d7 701
81d882d5 702 if (c->options.ce.http_proxy_options)
4e9a51d7 703 {
3cfd6f96
GDG
704 c->options.ce.http_proxy_options->first_time = c->first_time;
705
81d882d5
DS
706 /* Possible HTTP proxy user/pass input */
707 c->c1.http_proxy = http_proxy_new(c->options.ce.http_proxy_options);
708 if (c->c1.http_proxy)
709 {
710 did_http = true;
711 c->c1.http_proxy_owned = true;
712 }
4e9a51d7 713 }
4e9a51d7 714
a4b8f653 715 if (!did_http && c->options.ce.socks_proxy_server)
4e9a51d7 716 {
81d882d5
DS
717 c->c1.socks_proxy = socks_proxy_new(c->options.ce.socks_proxy_server,
718 c->options.ce.socks_proxy_port,
719 c->options.ce.socks_proxy_authfile);
720 if (c->c1.socks_proxy)
721 {
722 c->c1.socks_proxy_owned = true;
723 }
4e9a51d7 724 }
4e9a51d7
JY
725}
726
727static void
81d882d5 728init_proxy(struct context *c)
4e9a51d7 729{
81d882d5 730 init_proxy_dowork(c);
4e9a51d7
JY
731}
732
733static void
81d882d5 734uninit_proxy(struct context *c)
4e9a51d7 735{
81d882d5 736 uninit_proxy_dowork(c);
4e9a51d7
JY
737}
738
94b391d7
AQ
739static void
740do_link_socket_addr_new(struct context *c)
741{
742 ALLOC_ARRAY_CLEAR_GC(c->c1.link_socket_addrs, struct link_socket_addr,
743 c->c1.link_sockets_num, &c->gc);
744}
745
4e9a51d7 746void
81d882d5 747context_init_1(struct context *c)
4e9a51d7 748{
81d882d5 749 context_clear_1(c);
6fbf66fa 750
81d882d5 751 packet_id_persist_init(&c->c1.pid_persist);
4e9a51d7 752
81d882d5 753 init_connection_list(c);
6fbf66fa 754
8466c2ca 755 c->c1.link_sockets_num = c->options.ce.local_list->len;
94b391d7
AQ
756
757 do_link_socket_addr_new(c);
758
ce98fd24 759#if defined(ENABLE_PKCS11)
81d882d5
DS
760 if (c->first_time)
761 {
762 int i;
763 pkcs11_initialize(true, c->options.pkcs11_pin_cache_period);
764 for (i = 0; i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL; i++)
4cd4899e 765 {
81d882d5
DS
766 pkcs11_addProvider(c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
767 c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
4cd4899e 768 }
81d882d5 769 }
ce98fd24 770#endif
984cf003 771
c67d59cd 772#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
81d882d5
DS
773 {
774 /*
775 * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
776 */
777 struct user_pass up;
778 CLEAR(up);
779 strcpy(up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
780 get_user_pass(&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
781 msg(M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
782 * 'needok' command, usually 'ok' or 'cancel'. */
783 }
dd1047f5
JY
784#endif
785
e83a8684
DS
786#ifdef ENABLE_SYSTEMD
787 /* We can report the PID via getpid() to systemd here as OpenVPN will not
788 * do any fork due to daemon() a future call.
789 * See possibly_become_daemon() [init.c] for more details.
790 */
b13bc6c9 791 sd_notifyf(0, "READY=1\nSTATUS=Pre-connection initialization successful\nMAINPID=%lu",
e83a8684
DS
792 (unsigned long) getpid());
793#endif
794
6fbf66fa
JY
795}
796
797void
81d882d5 798context_gc_free(struct context *c)
6fbf66fa 799{
81d882d5
DS
800 gc_free(&c->c2.gc);
801 gc_free(&c->options.gc);
802 gc_free(&c->gc);
6fbf66fa
JY
803}
804
6add6b2f
JY
805#if PORT_SHARE
806
807static void
81d882d5 808close_port_share(void)
6add6b2f 809{
81d882d5 810 if (port_share)
6add6b2f 811 {
81d882d5
DS
812 port_share_close(port_share);
813 port_share = NULL;
6add6b2f
JY
814 }
815}
816
817static void
81d882d5 818init_port_share(struct context *c)
6add6b2f 819{
81d882d5 820 if (!port_share && (c->options.port_share_host && c->options.port_share_port))
6add6b2f 821 {
81d882d5
DS
822 port_share = port_share_open(c->options.port_share_host,
823 c->options.port_share_port,
65a21eb1 824 c->c2.frame.buf.payload_size,
81d882d5
DS
825 c->options.port_share_journal_dir);
826 if (port_share == NULL)
827 {
828 msg(M_FATAL, "Fatal error: Port sharing failed");
829 }
6add6b2f
JY
830 }
831}
832
81d882d5 833#endif /* if PORT_SHARE */
6add6b2f 834
e74e3a4d 835
6fbf66fa 836bool
81d882d5 837init_static(void)
6fbf66fa 838{
c7ca9133 839#if defined(DMALLOC)
81d882d5 840 crypto_init_dmalloc();
6fbf66fa
JY
841#endif
842
e74e3a4d
DS
843
844 /*
845 * Initialize random number seed. random() is only used
846 * when "weak" random numbers are acceptable.
847 * SSL library routines are always used when cryptographically
848 * strong random numbers are required.
849 */
850 struct timeval tv;
851 if (!gettimeofday(&tv, NULL))
852 {
853 const unsigned int seed = (unsigned int) tv.tv_sec ^ tv.tv_usec;
854 srandom(seed);
855 }
856
81d882d5
DS
857 error_reset(); /* initialize error.c */
858 reset_check_status(); /* initialize status check code in socket.c */
6fbf66fa 859
445b192a 860#ifdef _WIN32
81d882d5 861 init_win32();
6fbf66fa
JY
862#endif
863
864#ifdef OPENVPN_DEBUG_COMMAND_LINE
81d882d5
DS
865 {
866 int i;
867 for (i = 0; i < argc; ++i)
4cd4899e 868 {
81d882d5 869 msg(M_INFO, "argv[%d] = '%s'", i, argv[i]);
4cd4899e 870 }
81d882d5 871 }
6fbf66fa
JY
872#endif
873
81d882d5 874 update_time();
6fbf66fa 875
81d882d5 876 init_ssl_lib();
6fbf66fa 877
6fbf66fa 878#ifdef SCHEDULE_TEST
81d882d5
DS
879 schedule_test();
880 return false;
6fbf66fa
JY
881#endif
882
6fbf66fa 883#ifdef IFCONFIG_POOL_TEST
81d882d5
DS
884 ifconfig_pool_test(0x0A010004, 0x0A0100FF);
885 return false;
6fbf66fa
JY
886#endif
887
428b8279 888#ifdef TIME_TEST
81d882d5
DS
889 time_test();
890 return false;
428b8279
JY
891#endif
892
6cd276ba 893#ifdef GEN_PATH_TEST
81d882d5
DS
894 {
895 struct gc_arena gc = gc_new();
896 const char *fn = gen_path("foo",
897 "bar",
898 &gc);
899 printf("%s\n", fn);
900 gc_free(&gc);
901 }
902 return false;
6cd276ba 903#endif
ddad0a8c 904
6cd276ba 905#ifdef STATUS_PRINTF_TEST
81d882d5
DS
906 {
907 struct gc_arena gc = gc_new();
b7bea782 908 const char *tmp_file = platform_create_temp_file("/tmp", "foo", &gc);
81d882d5
DS
909 struct status_output *so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
910 status_printf(so, "%s", "foo");
911 status_printf(so, "%s", "bar");
912 if (!status_close(so))
913 {
914 msg(M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
915 }
916 gc_free(&gc);
917 }
918 return false;
ddad0a8c
JY
919#endif
920
ffea644c 921#ifdef MSTATS_TEST
81d882d5
DS
922 {
923 int i;
924 mstats_open("/dev/shm/mstats.dat");
925 for (i = 0; i < 30; ++i)
926 {
927 mmap_stats->n_clients += 1;
928 mmap_stats->link_write_bytes += 8;
929 mmap_stats->link_read_bytes += 16;
930 sleep(1);
931 }
932 mstats_close();
933 return false;
934 }
ffea644c
JY
935#endif
936
81d882d5 937 return true;
6fbf66fa
JY
938}
939
940void
81d882d5 941uninit_static(void)
6fbf66fa 942{
81d882d5 943 free_ssl_lib();
ce98fd24 944
ce98fd24 945#ifdef ENABLE_PKCS11
81d882d5 946 pkcs11_terminate();
ce98fd24 947#endif
6fbf66fa 948
6add6b2f 949#if PORT_SHARE
81d882d5 950 close_port_share();
6add6b2f
JY
951#endif
952
c7ca9133 953#if defined(MEASURE_TLS_HANDSHAKE_STATS)
81d882d5 954 show_tls_performance_stats();
6fbf66fa
JY
955#endif
956}
957
958void
81d882d5 959init_verb_mute(struct context *c, unsigned int flags)
6fbf66fa 960{
81d882d5 961 if (flags & IVM_LEVEL_1)
6fbf66fa 962 {
81d882d5
DS
963 /* set verbosity and mute levels */
964 set_check_status(D_LINK_ERRORS, D_READ_WRITE);
965 set_debug_level(c->options.verbosity, SDL_CONSTRAIN);
966 set_mute_cutoff(c->options.mute);
6fbf66fa
JY
967 }
968
81d882d5
DS
969 /* special D_LOG_RW mode */
970 if (flags & IVM_LEVEL_2)
971 {
972 c->c2.log_rw = (check_debug_level(D_LOG_RW) && !check_debug_level(D_LOG_RW + 1));
973 }
6fbf66fa
JY
974}
975
976/*
977 * Possibly set --dev based on --dev-node.
978 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
979 * set --dev to tun.
980 */
981void
81d882d5 982init_options_dev(struct options *options)
6fbf66fa 983{
81d882d5
DS
984 if (!options->dev && options->dev_node)
985 {
eef30e6e
FL
986 /* POSIX basename() implementations may modify its arguments */
987 char *dev_node = string_alloc(options->dev_node, NULL);
81d882d5
DS
988 options->dev = basename(dev_node);
989 }
6fbf66fa
JY
990}
991
992bool
81d882d5 993print_openssl_info(const struct options *options)
6fbf66fa 994{
81d882d5
DS
995 /*
996 * OpenSSL info print mode?
997 */
81d882d5
DS
998 if (options->show_ciphers || options->show_digests || options->show_engines
999 || options->show_tls_ciphers || options->show_curves)
6fbf66fa 1000 {
81d882d5
DS
1001 if (options->show_ciphers)
1002 {
1003 show_available_ciphers();
1004 }
1005 if (options->show_digests)
1006 {
1007 show_available_digests();
1008 }
1009 if (options->show_engines)
1010 {
1011 show_available_engines();
1012 }
1013 if (options->show_tls_ciphers)
1014 {
aba75874 1015 show_available_tls_ciphers(options->cipher_list,
7aeabadd 1016 options->cipher_list_tls13,
aba75874 1017 options->tls_cert_profile);
81d882d5
DS
1018 }
1019 if (options->show_curves)
1020 {
1021 show_available_curves();
1022 }
1023 return true;
6fbf66fa 1024 }
81d882d5 1025 return false;
6fbf66fa
JY
1026}
1027
1028/*
1029 * Static pre-shared key generation mode?
1030 */
1031bool
81d882d5 1032do_genkey(const struct options *options)
6fbf66fa 1033{
9d59029a 1034 /* should we disable paging? */
0d80b562 1035 if (options->mlock && (options->genkey))
9d59029a
SK
1036 {
1037 platform_mlockall(true);
1038 }
0d80b562
AS
1039
1040 /*
1041 * We do not want user to use --genkey with --secret. In the transistion
1042 * phase we for secret.
1043 */
1044 if (options->genkey && options->genkey_type != GENKEY_SECRET
1045 && options->shared_secret_file)
1046 {
1047 msg(M_USAGE, "Using --genkey type with --secret filename is "
1048 "not supported. Use --genkey type filename instead.");
1049 }
1050 if (options->genkey && options->genkey_type == GENKEY_SECRET)
6fbf66fa 1051 {
81d882d5 1052 int nbits_written;
0d80b562
AS
1053 const char *genkey_filename = options->genkey_filename;
1054 if (options->shared_secret_file && options->genkey_filename)
1055 {
1056 msg(M_USAGE, "You must provide a filename to either --genkey "
1057 "or --secret, not both");
1058 }
6fbf66fa 1059
0d80b562
AS
1060 /*
1061 * Copy filename from shared_secret_file to genkey_filename to support
1062 * the old --genkey --secret foo.file syntax.
1063 */
1064 if (options->shared_secret_file)
1065 {
1066 msg(M_WARN, "WARNING: Using --genkey --secret filename is "
1067 "DEPRECATED. Use --genkey secret filename instead.");
1068 genkey_filename = options->shared_secret_file;
1069 }
6fbf66fa 1070
0d80b562 1071 nbits_written = write_key_file(2, genkey_filename);
a8fa1679
SK
1072 if (nbits_written < 0)
1073 {
1074 msg(M_FATAL, "Failed to write key file");
1075 }
6fbf66fa 1076
81d882d5
DS
1077 msg(D_GENKEY | M_NOPREFIX,
1078 "Randomly generated %d bit key written to %s", nbits_written,
1079 options->shared_secret_file);
1080 return true;
6fbf66fa 1081 }
0d80b562 1082 else if (options->genkey && options->genkey_type == GENKEY_TLS_CRYPTV2_SERVER)
9d59029a 1083 {
0d80b562
AS
1084 tls_crypt_v2_write_server_key_file(options->genkey_filename);
1085 return true;
1086 }
1087 else if (options->genkey && options->genkey_type == GENKEY_TLS_CRYPTV2_CLIENT)
1088 {
1089 if (!options->tls_crypt_v2_file)
9d59029a 1090 {
0d80b562
AS
1091 msg(M_USAGE,
1092 "--genkey tls-crypt-v2-client requires a server key to be set via --tls-crypt-v2 to create a client key");
9d59029a
SK
1093 }
1094
0d80b562
AS
1095 tls_crypt_v2_write_client_key_file(options->genkey_filename,
1096 options->genkey_extra_data, options->tls_crypt_v2_file,
cb2e9218 1097 options->tls_crypt_v2_file_inline);
0d80b562
AS
1098 return true;
1099 }
1b9a88a2
AS
1100 else if (options->genkey && options->genkey_type == GENKEY_AUTH_TOKEN)
1101 {
1102 auth_token_write_server_key_file(options->genkey_filename);
1103 return true;
1104 }
0d80b562
AS
1105 else
1106 {
1107 return false;
9d59029a 1108 }
6fbf66fa
JY
1109}
1110
1111/*
1112 * Persistent TUN/TAP device management mode?
1113 */
1114bool
6a2fe47a 1115do_persist_tuntap(struct options *options, openvpn_net_ctx_t *ctx)
6fbf66fa 1116{
84099782 1117 if (!options->persist_config)
6fbf66fa 1118 {
84099782
LS
1119 return false;
1120 }
1121
1122 /* sanity check on options for --mktun or --rmtun */
1123 notnull(options->dev, "TUN/TAP device (--dev)");
1124 if (options->ce.remote || options->ifconfig_local
1125 || options->ifconfig_remote_netmask
1126 || options->shared_secret_file
1127 || options->tls_server || options->tls_client
1128 )
1129 {
1130 msg(M_FATAL|M_OPTERR,
1131 "options --mktun or --rmtun should only be used together with --dev");
1132 }
6a2fe47a
AQ
1133
1134#if defined(ENABLE_DCO)
84099782
LS
1135 if (dco_enabled(options))
1136 {
1137 /* creating a DCO interface via --mktun is not supported as it does not
1138 * make much sense. Since DCO is enabled by default, people may run into
1139 * this without knowing, therefore this case should be properly handled.
1140 *
1141 * Disable DCO if --mktun was provided and print a message to let
1142 * user know.
1143 */
1144 if (dev_type_enum(options->dev, options->dev_type) == DEV_TYPE_TUN)
6a2fe47a 1145 {
84099782 1146 msg(M_WARN, "Note: --mktun does not support DCO. Creating TUN interface.");
6a2fe47a 1147 }
84099782 1148
d8490738 1149 options->disable_dco = true;
84099782 1150 }
6a2fe47a
AQ
1151#endif
1152
4ad2b65d 1153#ifdef ENABLE_FEATURE_TUN_PERSIST
84099782
LS
1154 tuncfg(options->dev, options->dev_type, options->dev_node,
1155 options->persist_mode,
1156 options->username, options->groupname, &options->tuntap_options,
1157 ctx);
1158 if (options->persist_mode && options->lladdr)
1159 {
1160 set_lladdr(ctx, options->dev, options->lladdr, NULL);
1161 }
1162 return true;
81d882d5 1163#else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
84099782
LS
1164 msg(M_FATAL|M_OPTERR,
1165 "options --mktun and --rmtun are not available on your operating "
1166 "system. Please check 'man tun' (or 'tap'), whether your system "
1167 "supports using 'ifconfig %s create' / 'destroy' to create/remove "
1168 "persistent tunnel interfaces.", options->dev );
6fbf66fa 1169#endif
81d882d5 1170 return false;
6fbf66fa
JY
1171}
1172
1173/*
1174 * Should we become a daemon?
1175 * Return true if we did it.
1176 */
da9b2927 1177bool
81d882d5 1178possibly_become_daemon(const struct options *options)
6fbf66fa 1179{
81d882d5 1180 bool ret = false;
7660bba1
CH
1181
1182#ifdef ENABLE_SYSTEMD
81d882d5
DS
1183 /* return without forking if we are running from systemd */
1184 if (sd_notify(0, "READY=0") > 0)
1185 {
1186 return ret;
1187 }
7660bba1
CH
1188#endif
1189
81d882d5 1190 if (options->daemon)
6fbf66fa 1191 {
81d882d5 1192 /* Don't chdir immediately, but the end of the init sequence, if needed */
a480eaae
AS
1193
1194#if defined(__APPLE__) && defined(__clang__)
1195#pragma clang diagnostic push
1196#pragma clang diagnostic ignored "-Wdeprecated-declarations"
1197#endif
81d882d5
DS
1198 if (daemon(1, options->log) < 0)
1199 {
1200 msg(M_ERR, "daemon() failed or unsupported");
1201 }
a480eaae
AS
1202#if defined(__APPLE__) && defined(__clang__)
1203#pragma clang diagnostic pop
1204#endif
81d882d5
DS
1205 restore_signal_state();
1206 if (options->log)
1207 {
1208 set_std_files_to_null(true);
1209 }
6835555e 1210
81d882d5 1211 ret = true;
6fbf66fa 1212 }
81d882d5 1213 return ret;
6fbf66fa
JY
1214}
1215
1216/*
99385447 1217 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
6fbf66fa
JY
1218 */
1219static void
81d882d5 1220do_uid_gid_chroot(struct context *c, bool no_delay)
6fbf66fa 1221{
81d882d5
DS
1222 static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
1223 struct context_0 *c0 = c->c0;
6fbf66fa 1224
81d882d5 1225 if (c0 && !c0->uid_gid_chroot_set)
6fbf66fa 1226 {
81d882d5
DS
1227 /* chroot if requested */
1228 if (c->options.chroot_dir)
1229 {
1230 if (no_delay)
65140a3a 1231 {
81d882d5
DS
1232 platform_chroot(c->options.chroot_dir);
1233 }
1234 else if (c->first_time)
1235 {
1236 msg(M_INFO, "NOTE: chroot %s", why_not);
1237 }
1238 }
1239
1240 /* set user and/or group if we want to setuid/setgid */
1241 if (c0->uid_gid_specified)
1242 {
1243 if (no_delay)
1244 {
2e359a08
TR
1245 platform_user_group_set(&c0->platform_state_user,
1246 &c0->platform_state_group,
1247 c);
81d882d5
DS
1248 }
1249 else if (c->first_time)
1250 {
1251 msg(M_INFO, "NOTE: UID/GID downgrade %s", why_not);
65140a3a 1252 }
81d882d5 1253 }
99385447 1254
ffea644c 1255#ifdef ENABLE_MEMSTATS
81d882d5
DS
1256 if (c->first_time && c->options.memstats_fn)
1257 {
1258 mstats_open(c->options.memstats_fn);
1259 }
ffea644c
JY
1260#endif
1261
cd5990e0 1262#ifdef ENABLE_SELINUX
81d882d5
DS
1263 /* Apply a SELinux context in order to restrict what OpenVPN can do
1264 * to _only_ what it is supposed to do after initialization is complete
1265 * (basically just network I/O operations). Doing it after chroot
1266 * requires /proc to be mounted in the chroot (which is annoying indeed
1267 * but doing it before requires more complex SELinux policies.
1268 */
1269 if (c->options.selinux_context)
1270 {
1271 if (no_delay)
1272 {
1273 if (-1 == setcon(c->options.selinux_context))
1274 {
1275 msg(M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
1276 }
1277 else
1278 {
1279 msg(M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
1280 }
1281 }
1282 else if (c->first_time)
1283 {
1284 msg(M_INFO, "NOTE: setcon %s", why_not);
1285 }
1286 }
1287#endif
1288
1289 /* Privileges are going to be dropped by now (if requested), be sure
1290 * to prevent any future privilege dropping attempts from now on.
1291 */
1292 if (no_delay)
1293 {
1294 c0->uid_gid_chroot_set = true;
1295 }
6fbf66fa
JY
1296 }
1297}
1298
1299/*
1300 * Return common name in a way that is formatted for
1301 * prepending to msg() output.
1302 */
1303const char *
81d882d5 1304format_common_name(struct context *c, struct gc_arena *gc)
6fbf66fa 1305{
81d882d5 1306 struct buffer out = alloc_buf_gc(256, gc);
81d882d5 1307 if (c->c2.tls_multi)
6fbf66fa 1308 {
81d882d5 1309 buf_printf(&out, "[%s] ", tls_common_name(c->c2.tls_multi, false));
6fbf66fa 1310 }
81d882d5 1311 return BSTR(&out);
6fbf66fa
JY
1312}
1313
1314void
81d882d5 1315pre_setup(const struct options *options)
6fbf66fa 1316{
445b192a 1317#ifdef _WIN32
81d882d5 1318 if (options->exit_event_name)
6fbf66fa 1319 {
81d882d5
DS
1320 win32_signal_open(&win32_signal,
1321 WSO_FORCE_SERVICE,
1322 options->exit_event_name,
1323 options->exit_event_initial_state);
6fbf66fa 1324 }
81d882d5 1325 else
6fbf66fa 1326 {
81d882d5
DS
1327 win32_signal_open(&win32_signal,
1328 WSO_FORCE_CONSOLE,
1329 NULL,
1330 false);
6fbf66fa 1331
81d882d5
DS
1332 /* put a title on the top window bar */
1333 if (win32_signal.mode == WSO_MODE_CONSOLE)
1334 {
1335 window_title_save(&window_title);
1336 window_title_generate(options->config);
1337 }
6fbf66fa 1338 }
81d882d5 1339#endif /* ifdef _WIN32 */
6fbf66fa
JY
1340}
1341
1342void
81d882d5 1343reset_coarse_timers(struct context *c)
6fbf66fa 1344{
81d882d5 1345 c->c2.coarse_timer_wakeup = 0;
6fbf66fa
JY
1346}
1347
f2134b7b
AS
1348/*
1349 * Initialise the server poll timeout timer
1350 * This timer is used in the http/socks proxy setup so it needs to be setup
1351 * before
1352 */
1353static void
81d882d5 1354do_init_server_poll_timeout(struct context *c)
f2134b7b 1355{
81d882d5 1356 update_time();
f2134b7b 1357 if (c->options.ce.connect_timeout)
81d882d5
DS
1358 {
1359 event_timeout_init(&c->c2.server_poll_interval, c->options.ce.connect_timeout, now);
1360 }
f2134b7b
AS
1361}
1362
6fbf66fa
JY
1363/*
1364 * Initialize timers
1365 */
1366static void
81d882d5 1367do_init_timers(struct context *c, bool deferred)
6fbf66fa 1368{
81d882d5
DS
1369 update_time();
1370 reset_coarse_timers(c);
6fbf66fa 1371
81d882d5
DS
1372 /* initialize inactivity timeout */
1373 if (c->options.inactivity_timeout)
1374 {
1375 event_timeout_init(&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
1376 }
6fbf66fa 1377
f96290ff
DZ
1378 /* initialize inactivity timeout */
1379 if (c->options.session_timeout)
1380 {
1381 event_timeout_init(&c->c2.session_interval, c->options.session_timeout,
1382 now);
1383 }
1384
81d882d5 1385 /* initialize pings */
a2d851d4 1386 if (dco_enabled(&c->options))
81d882d5 1387 {
a2d851d4
AQ
1388 /* The DCO kernel module will send the pings instead of user space */
1389 event_timeout_clear(&c->c2.ping_rec_interval);
1390 event_timeout_clear(&c->c2.ping_send_interval);
81d882d5 1391 }
a2d851d4 1392 else
81d882d5 1393 {
a2d851d4
AQ
1394 if (c->options.ping_send_timeout)
1395 {
1396 event_timeout_init(&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
1397 }
1398
1399 if (c->options.ping_rec_timeout)
1400 {
1401 event_timeout_init(&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
1402 }
81d882d5 1403 }
6fbf66fa 1404
9a516170
AS
1405 /* If the auth-token renewal interval is shorter than reneg-sec, arm
1406 * "auth-token renewal" timer to send additional auth-token to update the
1407 * token on the client more often. If not, this happens automatically
1408 * at renegotiation time, without needing an extra event.
1409 */
1410 if (c->options.auth_token_generate
1411 && c->options.auth_token_renewal < c->options.renegotiate_seconds)
1412 {
1413 event_timeout_init(&c->c2.auth_token_renewal_interval,
1414 c->options.auth_token_renewal, now);
1415 }
1416
81d882d5 1417 if (!deferred)
6fbf66fa 1418 {
81d882d5
DS
1419 /* initialize connection establishment timer */
1420 event_timeout_init(&c->c2.wait_for_connect, 1, now);
6fbf66fa 1421
81d882d5 1422 /* initialize occ timers */
6fbf66fa 1423
81d882d5
DS
1424 if (c->options.occ
1425 && !TLS_MODE(c)
1426 && c->c2.options_string_local && c->c2.options_string_remote)
1427 {
1428 event_timeout_init(&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
1429 }
6fbf66fa 1430
81d882d5
DS
1431 if (c->options.mtu_test)
1432 {
1433 event_timeout_init(&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
1434 }
6fbf66fa 1435
81d882d5 1436 /* initialize packet_id persistence timer */
81d882d5
DS
1437 if (c->options.packet_id_file)
1438 {
1439 event_timeout_init(&c->c2.packet_id_persist_interval, 60, now);
1440 }
6fbf66fa 1441
81d882d5
DS
1442 /* initialize tmp_int optimization that limits the number of times we call
1443 * tls_multi_process in the main event loop */
1444 interval_init(&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
6fbf66fa
JY
1445 }
1446}
1447
1448/*
1449 * Initialize traffic shaper.
1450 */
1451static void
81d882d5 1452do_init_traffic_shaper(struct context *c)
6fbf66fa 1453{
81d882d5
DS
1454 /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
1455 if (c->options.shaper)
6fbf66fa 1456 {
81d882d5
DS
1457 shaper_init(&c->c2.shaper, c->options.shaper);
1458 shaper_msg(&c->c2.shaper);
6fbf66fa 1459 }
6fbf66fa
JY
1460}
1461
1462/*
eb95f367
GD
1463 * Allocate route list structures for IPv4 and IPv6
1464 * (we do this for IPv4 even if no --route option has been seen, as other
1465 * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
6fbf66fa
JY
1466 */
1467static void
81d882d5 1468do_alloc_route_list(struct context *c)
6fbf66fa 1469{
81d882d5
DS
1470 if (!c->c1.route_list)
1471 {
1472 ALLOC_OBJ_CLEAR_GC(c->c1.route_list, struct route_list, &c->gc);
1473 }
1474 if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
1475 {
1476 ALLOC_OBJ_CLEAR_GC(c->c1.route_ipv6_list, struct route_ipv6_list, &c->gc);
1477 }
6fbf66fa
JY
1478}
1479
1480
1481/*
1482 * Initialize the route list, resolving any DNS names in route
1483 * options and saving routes in the environment.
1484 */
1485static void
81d882d5
DS
1486do_init_route_list(const struct options *options,
1487 struct route_list *route_list,
1488 const struct link_socket_info *link_socket_info,
aec4a3d1
AQ
1489 struct env_set *es,
1490 openvpn_net_ctx_t *ctx)
6fbf66fa 1491{
81d882d5
DS
1492 const char *gw = NULL;
1493 int dev = dev_type_enum(options->dev, options->dev_type);
1494 int metric = 0;
6fbf66fa 1495
90d9c38b
AQ
1496 /* if DCO is enabled we have both regular routes and iroutes in the system
1497 * routing table, and normal routes must have a higher metric for that to
1498 * work so that iroutes are always matched first
1499 */
1500 if (dco_enabled(options))
1501 {
1502 metric = DCO_DEFAULT_METRIC;
1503 }
1504
81d882d5
DS
1505 if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
1506 {
1507 gw = options->ifconfig_remote_netmask;
1508 }
1509 if (options->route_default_gateway)
1510 {
1511 gw = options->route_default_gateway;
1512 }
1513 if (options->route_default_metric)
1514 {
1515 metric = options->route_default_metric;
1516 }
6fbf66fa 1517
81d882d5
DS
1518 if (init_route_list(route_list,
1519 options->routes,
1520 gw,
1521 metric,
1522 link_socket_current_remote(link_socket_info),
aec4a3d1
AQ
1523 es,
1524 ctx))
6fbf66fa 1525 {
81d882d5
DS
1526 /* copy routes to environment */
1527 setenv_routes(es, route_list);
6fbf66fa
JY
1528 }
1529}
1530
512cda46 1531static void
81d882d5
DS
1532do_init_route_ipv6_list(const struct options *options,
1533 struct route_ipv6_list *route_ipv6_list,
1534 const struct link_socket_info *link_socket_info,
c454b21e
AQ
1535 struct env_set *es,
1536 openvpn_net_ctx_t *ctx)
512cda46 1537{
81d882d5
DS
1538 const char *gw = NULL;
1539 int metric = -1; /* no metric set */
512cda46 1540
90d9c38b
AQ
1541 /* see explanation in do_init_route_list() */
1542 if (dco_enabled(options))
1543 {
1544 metric = DCO_DEFAULT_METRIC;
1545 }
1546
81d882d5 1547 gw = options->ifconfig_ipv6_remote; /* default GW = remote end */
d24e1b17 1548 if (options->route_ipv6_default_gateway)
81d882d5
DS
1549 {
1550 gw = options->route_ipv6_default_gateway;
1551 }
512cda46 1552
81d882d5
DS
1553 if (options->route_default_metric)
1554 {
1555 metric = options->route_default_metric;
1556 }
512cda46 1557
81d882d5
DS
1558 /* redirect (IPv6) gateway to VPN? if yes, add a few more specifics
1559 */
1560 if (options->routes_ipv6->flags & RG_REROUTE_GW)
d227929b 1561 {
81d882d5
DS
1562 char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
1563 int i;
d227929b 1564
81d882d5
DS
1565 for (i = 0; opt_list[i]; i++)
1566 {
1567 add_route_ipv6_to_option_list( options->routes_ipv6,
1568 string_alloc(opt_list[i], options->routes_ipv6->gc),
f93fc813 1569 NULL, NULL, options->route_default_table_id);
81d882d5 1570 }
d227929b
GD
1571 }
1572
81d882d5
DS
1573 if (init_route_ipv6_list(route_ipv6_list,
1574 options->routes_ipv6,
1575 gw,
1576 metric,
1577 link_socket_current_remote_ipv6(link_socket_info),
c454b21e
AQ
1578 es,
1579 ctx))
512cda46 1580 {
81d882d5
DS
1581 /* copy routes to environment */
1582 setenv_routes_ipv6(es, route_ipv6_list);
512cda46
GD
1583 }
1584}
1585
1586
6fbf66fa
JY
1587/*
1588 * Called after all initialization has been completed.
1589 */
1590void
81d882d5 1591initialization_sequence_completed(struct context *c, const unsigned int flags)
6fbf66fa 1592{
81d882d5 1593 static const char message[] = "Initialization Sequence Completed";
6fbf66fa 1594
81d882d5
DS
1595 /* Reset the unsuccessful connection counter on complete initialisation */
1596 c->options.unsuccessful_attempts = 0;
23d61c56 1597
81d882d5
DS
1598 /* If we delayed UID/GID downgrade or chroot, do it now */
1599 do_uid_gid_chroot(c, true);
6fbf66fa 1600
81d882d5
DS
1601 /* Test if errors */
1602 if (flags & ISC_ERRORS)
a9c802b2 1603 {
445b192a 1604#ifdef _WIN32
81d882d5
DS
1605 show_routes(M_INFO|M_NOPREFIX);
1606 show_adapters(M_INFO|M_NOPREFIX);
1607 msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
6fbf66fa 1608#else
c5931897 1609#ifdef ENABLE_SYSTEMD
81d882d5 1610 sd_notifyf(0, "STATUS=Failed to start up: %s With Errors\nERRNO=1", message);
c5931897 1611#endif /* HAVE_SYSTEMD_SD_DAEMON_H */
81d882d5 1612 msg(M_INFO, "%s With Errors", message);
6fbf66fa 1613#endif
a9c802b2 1614 }
81d882d5 1615 else
c5931897
CH
1616 {
1617#ifdef ENABLE_SYSTEMD
e83a8684 1618 sd_notifyf(0, "STATUS=%s", message);
c5931897 1619#endif
81d882d5 1620 msg(M_INFO, "%s", message);
c5931897 1621 }
6fbf66fa 1622
81d882d5
DS
1623 /* Flag that we initialized */
1624 if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
1625 {
1626 c->options.no_advance = true;
1627 }
6fbf66fa 1628
445b192a 1629#ifdef _WIN32
81d882d5 1630 fork_register_dns_action(c->c1.tuntap);
b90c6f17
JY
1631#endif
1632
6fbf66fa 1633#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1634 /* Tell management interface that we initialized */
1635 if (management)
1636 {
1637 in_addr_t *tun_local = NULL;
1638 struct in6_addr *tun_local6 = NULL;
1639 struct openvpn_sockaddr local, remote;
1640 struct link_socket_actual *actual;
1641 socklen_t sa_len = sizeof(local);
1642 const char *detail = "SUCCESS";
1643 if (flags & ISC_ERRORS)
1644 {
1645 detail = "ERROR";
1646 }
e04c2536
SN
1647 /* Flag route error only on platforms where trivial "already exists" errors
1648 * are filtered out. Currently this is the case on Windows or if usng netlink.
1649 */
1650#if defined(_WIN32) || defined(ENABLE_SITNL)
1651 else if (flags & ISC_ROUTE_ERRORS)
1652 {
1653 detail = "ROUTE_ERROR";
1654 }
1655#endif
81d882d5
DS
1656
1657 CLEAR(local);
1658 actual = &get_link_socket_info(c)->lsa->actual;
1659 remote = actual->dest;
94b391d7 1660 getsockname(c->c2.link_sockets[0]->sd, &local.addr.sa, &sa_len);
2191c471 1661#if ENABLE_IP_PKTINFO
81d882d5 1662 if (!addr_defined(&local))
2191c471 1663 {
81d882d5 1664 switch (local.addr.sa.sa_family)
2191c471 1665 {
81d882d5 1666 case AF_INET:
7efa60d9 1667#if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
81d882d5 1668 local.addr.in4.sin_addr = actual->pi.in4.ipi_spec_dst;
4a82a9ac 1669#else
81d882d5 1670 local.addr.in4.sin_addr = actual->pi.in4;
4a82a9ac 1671#endif
81d882d5
DS
1672 break;
1673
1674 case AF_INET6:
1675 local.addr.in6.sin6_addr = actual->pi.in6.ipi6_addr;
1676 break;
2191c471
HH
1677 }
1678 }
1679#endif
1680
81d882d5 1681 if (c->c1.tuntap)
2191c471 1682 {
81d882d5
DS
1683 tun_local = &c->c1.tuntap->local;
1684 tun_local6 = &c->c1.tuntap->local_ipv6;
1685 }
1686 management_set_state(management,
1687 OPENVPN_STATE_CONNECTED,
1688 detail,
1689 tun_local,
1690 tun_local6,
1691 &local,
1692 &remote);
1693 if (tun_local)
1694 {
1695 management_post_tunnel_open(management, *tun_local);
2191c471 1696 }
6fbf66fa 1697 }
81d882d5 1698#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
1699}
1700
5c4a0b71
AS
1701/**
1702 * Determine if external route commands should be executed based on
1703 * configured options and backend driver
1704 */
1705static bool
1706route_noexec_enabled(const struct options *o, const struct tuntap *tt)
1707{
1708 return o->route_noexec
1709 || (tt && tt->backend_driver == DRIVER_AFUNIX)
1710 || (tt && tt->backend_driver == DRIVER_NULL);
1711}
1712
6fbf66fa
JY
1713/*
1714 * Possibly add routes and/or call route-up script
1715 * based on options.
1716 */
e04c2536 1717bool
81d882d5
DS
1718do_route(const struct options *options,
1719 struct route_list *route_list,
1720 struct route_ipv6_list *route_ipv6_list,
1721 const struct tuntap *tt,
1722 const struct plugin_list *plugins,
aec4a3d1
AQ
1723 struct env_set *es,
1724 openvpn_net_ctx_t *ctx)
6fbf66fa 1725{
e04c2536 1726 bool ret = true;
5c4a0b71 1727 if (!route_noexec_enabled(options, tt) && ( route_list || route_ipv6_list ) )
15be3202 1728 {
e04c2536
SN
1729 ret = add_routes(route_list, route_ipv6_list, tt, ROUTE_OPTION_FLAGS(options),
1730 es, ctx);
81d882d5 1731 setenv_int(es, "redirect_gateway", route_did_redirect_default_gateway(route_list));
15be3202
JY
1732 }
1733#ifdef ENABLE_MANAGEMENT
81d882d5
DS
1734 if (management)
1735 {
1736 management_up_down(management, "UP", es);
1737 }
15be3202 1738#endif
6fbf66fa 1739
81d882d5 1740 if (plugin_defined(plugins, OPENVPN_PLUGIN_ROUTE_UP))
6fbf66fa 1741 {
81d882d5
DS
1742 if (plugin_call(plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
1743 {
1744 msg(M_WARN, "WARNING: route-up plugin call failed");
1745 }
6fbf66fa
JY
1746 }
1747
81d882d5 1748 if (options->route_script)
6fbf66fa 1749 {
81d882d5
DS
1750 struct argv argv = argv_new();
1751 setenv_str(es, "script_type", "route-up");
1752 argv_parse_cmd(&argv, options->route_script);
1753 openvpn_run_script(&argv, es, 0, "--route-up");
870e2405 1754 argv_free(&argv);
6fbf66fa
JY
1755 }
1756
445b192a 1757#ifdef _WIN32
81d882d5 1758 if (options->show_net_up)
6fbf66fa 1759 {
81d882d5
DS
1760 show_routes(M_INFO|M_NOPREFIX);
1761 show_adapters(M_INFO|M_NOPREFIX);
6fbf66fa 1762 }
81d882d5 1763 else if (check_debug_level(D_SHOW_NET))
6fbf66fa 1764 {
81d882d5
DS
1765 show_routes(D_SHOW_NET|M_NOPREFIX);
1766 show_adapters(D_SHOW_NET|M_NOPREFIX);
6fbf66fa
JY
1767 }
1768#endif
e04c2536 1769 return ret;
6fbf66fa
JY
1770}
1771
6fbf66fa
JY
1772/*
1773 * initialize tun/tap device object
1774 */
1775static void
81d882d5 1776do_init_tun(struct context *c)
6fbf66fa 1777{
81d882d5
DS
1778 c->c1.tuntap = init_tun(c->options.dev,
1779 c->options.dev_type,
1780 c->options.topology,
1781 c->options.ifconfig_local,
1782 c->options.ifconfig_remote_netmask,
1783 c->options.ifconfig_ipv6_local,
1784 c->options.ifconfig_ipv6_netbits,
1785 c->options.ifconfig_ipv6_remote,
94b391d7
AQ
1786 c->c1.link_socket_addrs[0].bind_local,
1787 c->c1.link_socket_addrs[0].remote_list,
81d882d5 1788 !c->options.ifconfig_nowarn,
dc7fcd71 1789 c->c2.es,
3adbc5c6
AQ
1790 &c->net_ctx,
1791 c->c1.tuntap);
81d882d5 1792
d0a93625
AS
1793 if (is_tun_afunix(c->options.dev_node))
1794 {
1795 /* Using AF_UNIX trumps using DCO */
1796 c->c1.tuntap->backend_driver = DRIVER_AFUNIX;
1797 }
8fe14fea
AS
1798 else if (is_dev_type(c->options.dev, c->options.dev_type, "null"))
1799 {
1800 c->c1.tuntap->backend_driver = DRIVER_NULL;
1801 }
c0658271 1802#ifdef _WIN32
d0a93625
AS
1803 else
1804 {
1805 c->c1.tuntap->backend_driver = c->options.windows_driver;
1806 }
d8490738 1807#else
d0a93625 1808 else if (dco_enabled(&c->options))
d8490738
AS
1809 {
1810 c->c1.tuntap->backend_driver = DRIVER_DCO;
1811 }
1812 else
1813 {
1814 c->c1.tuntap->backend_driver = DRIVER_GENERIC_TUNTAP;
1815 }
c0658271
LS
1816#endif
1817
81d882d5
DS
1818 init_tun_post(c->c1.tuntap,
1819 &c->c2.frame,
1820 &c->options.tuntap_options);
1821
1822 c->c1.tuntap_owned = true;
6fbf66fa
JY
1823}
1824
1825/*
1826 * Open tun/tap device, ifconfig, call up script, etc.
1827 */
1828
bd139689
AQ
1829
1830static bool
1831can_preserve_tun(struct tuntap *tt)
1832{
d0a93625
AS
1833 if (tt && tt->backend_driver == DRIVER_AFUNIX)
1834 {
1835 return false;
1836 }
bd139689
AQ
1837#ifdef TARGET_ANDROID
1838 return false;
1839#else
3adbc5c6 1840 return is_tun_type_set(tt);
bd139689
AQ
1841#endif
1842}
1843
bf887c95
HH
1844/**
1845 * Add WFP filters to block traffic to local networks.
1846 * Depending on the configuration all or just DNS is filtered.
1847 * This functionality is only available on Windows on all other
1848 * systems this function is a noop.
1849 *
1850 * @param c pointer to the connection context
1851 */
1852static void
1853add_wfp_block(struct context *c)
1854{
1855#if defined(_WIN32)
1856 /* Fortify 'redirect-gateway block-local' with firewall rules? */
1857 bool block_local = block_local_needed(c->c1.route_list);
1858
1859 if (c->options.block_outside_dns || block_local)
1860 {
1861 BOOL dns_only = !block_local;
1862 if (!win_wfp_block(c->c1.tuntap->adapter_index, c->options.msg_channel, dns_only))
1863 {
1864 msg(M_FATAL, "WFP: initialization failed");
1865 }
1866 }
1867#endif
1868}
1869
1870/**
1871 * Remove any WFP block filters previously added.
1872 * This functionality is only available on Windows on all other
1873 * systems the function is a noop.
1874 *
1875 * @param c pointer to the connection context
1876 * @param adapter_index the VPN adapter index
1877 */
1878static void
1879del_wfp_block(struct context *c, unsigned long adapter_index)
1880{
1881#if defined(_WIN32)
1882 if (c->options.block_outside_dns || block_local_needed(c->c1.route_list))
1883 {
1884 if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
1885 {
1886 msg(M_FATAL, "WFP: deinitialization failed");
1887 }
1888 }
1889#endif
1890}
1891
5c4a0b71
AS
1892/**
1893 * Determines if ifconfig execution should be disabled because of a
1894 * @param c
1895 * @return
1896 */
1897static bool
1898ifconfig_noexec_enabled(const struct context *c)
1899{
1900 return c->options.ifconfig_noexec
1901 || (c->c1.tuntap && c->c1.tuntap->backend_driver == DRIVER_AFUNIX)
1902 || (c->c1.tuntap && c->c1.tuntap->backend_driver == DRIVER_NULL);
1903}
1904
d0a93625
AS
1905static void
1906open_tun_backend(struct context *c)
1907{
1908 struct tuntap *tt = c->c1.tuntap;
8fe14fea
AS
1909
1910 if (tt->backend_driver == DRIVER_NULL)
1911 {
1912 open_tun_null(c->c1.tuntap);
1913 }
1914 else if (tt->backend_driver == DRIVER_AFUNIX)
d0a93625
AS
1915 {
1916 open_tun_afunix(&c->options, c->c2.frame.tun_mtu, tt, c->c2.es);
1917 }
1918 else
1919 {
1920 open_tun(c->options.dev, c->options.dev_type, c->options.dev_node,
1921 tt, &c->net_ctx);
1922 }
193b4f9d 1923 msg(M_INFO, "%s device [%s] opened", print_tun_backend_driver(tt->backend_driver), tt->actual_name);
d0a93625
AS
1924}
1925
1926
6fbf66fa 1927static bool
e04c2536 1928do_open_tun(struct context *c, int *error_flags)
6fbf66fa 1929{
81d882d5
DS
1930 struct gc_arena gc = gc_new();
1931 bool ret = false;
e04c2536 1932 *error_flags = 0;
6fbf66fa 1933
bd139689 1934 if (!can_preserve_tun(c->c1.tuntap))
6fbf66fa 1935 {
bd14d55d 1936#ifdef TARGET_ANDROID
bd139689
AQ
1937 /* If we emulate persist-tun on android we still have to open a new tun and
1938 * then close the old */
1939 int oldtunfd = -1;
1940 if (c->c1.tuntap)
1941 {
1942 oldtunfd = c->c1.tuntap->fd;
1943 free(c->c1.tuntap);
1944 c->c1.tuntap = NULL;
1945 c->c1.tuntap_owned = false;
1946 }
bd14d55d
AS
1947#endif
1948
d0a93625
AS
1949 /* initialize (but do not open) tun/tap object, this also sets
1950 * the backend driver type */
bd139689 1951 do_init_tun(c);
6fbf66fa 1952
bd139689
AQ
1953 /* inherit the dco context from the tuntap object */
1954 if (c->c2.tls_multi)
1955 {
1956 c->c2.tls_multi->dco = &c->c1.tuntap->dco;
1957 }
a2d851d4 1958
445b192a 1959#ifdef _WIN32
bd139689
AQ
1960 /* store (hide) interactive service handle in tuntap_options */
1961 c->c1.tuntap->options.msg_channel = c->options.msg_channel;
9c52e0c6
AS
1962 msg(D_ROUTE, "interactive service msg_channel=%" PRIuPTR,
1963 (intptr_t) c->options.msg_channel);
81d882d5
DS
1964#endif
1965
bd139689
AQ
1966 /* allocate route list structure */
1967 do_alloc_route_list(c);
81d882d5 1968
bd139689 1969 /* parse and resolve the route option list */
94b391d7 1970 ASSERT(c->c2.link_sockets[0]);
bd139689
AQ
1971 if (c->options.routes && c->c1.route_list)
1972 {
1973 do_init_route_list(&c->options, c->c1.route_list,
94b391d7 1974 &c->c2.link_sockets[0]->info, c->c2.es, &c->net_ctx);
bd139689
AQ
1975 }
1976 if (c->options.routes_ipv6 && c->c1.route_ipv6_list)
1977 {
1978 do_init_route_ipv6_list(&c->options, c->c1.route_ipv6_list,
94b391d7 1979 &c->c2.link_sockets[0]->info, c->c2.es, &c->net_ctx);
bd139689 1980 }
81d882d5 1981
bd139689 1982 /* do ifconfig */
5c4a0b71 1983 if (!ifconfig_noexec_enabled(c)
d0a93625 1984 && ifconfig_order(c->c1.tuntap) == IFCONFIG_BEFORE_TUN_OPEN)
bd139689
AQ
1985 {
1986 /* guess actual tun/tap unit number that will be returned
1987 * by open_tun */
1988 const char *guess = guess_tuntap_dev(c->options.dev,
1989 c->options.dev_type,
1990 c->options.dev_node,
1991 &gc);
94b391d7 1992 do_ifconfig(c->c1.tuntap, guess, c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx);
bd139689 1993 }
81d882d5 1994
bd139689 1995 /* possibly add routes */
d0a93625 1996 if (route_order(c->c1.tuntap) == ROUTE_BEFORE_TUN)
bd139689
AQ
1997 {
1998 /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
e04c2536
SN
1999 bool status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
2000 c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
2001 *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS);
bd139689 2002 }
c058cbff 2003#ifdef TARGET_ANDROID
bd139689
AQ
2004 /* Store the old fd inside the fd so open_tun can use it */
2005 c->c1.tuntap->fd = oldtunfd;
81d882d5 2006#endif
94b391d7 2007
bd139689 2008 if (dco_enabled(&c->options))
81d882d5 2009 {
1625d927 2010 ovpn_dco_init(c->mode, &c->c1.tuntap->dco, c->options.dev_node);
81d882d5 2011 }
38c85658 2012
bd139689 2013 /* open the tun device */
d0a93625 2014 open_tun_backend(c);
6fbf66fa 2015
bd139689
AQ
2016 /* set the hardware address */
2017 if (c->options.lladdr)
2018 {
94b391d7 2019 set_lladdr(&c->net_ctx, c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
bd139689 2020 }
6fbf66fa 2021
bd139689 2022 /* do ifconfig */
5c4a0b71 2023 if (!ifconfig_noexec_enabled(c)
d0a93625 2024 && ifconfig_order(c->c1.tuntap) == IFCONFIG_AFTER_TUN_OPEN)
bd139689
AQ
2025 {
2026 do_ifconfig(c->c1.tuntap, c->c1.tuntap->actual_name,
2027 c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx);
2028 }
db950be8 2029
1dfe8729 2030 run_dns_up_down(true, &c->options, c->c1.tuntap, &c->persist.duri);
0f3b7d17 2031
bd139689 2032 /* run the up script */
81d882d5
DS
2033 run_up_down(c->options.up_script,
2034 c->plugins,
2035 OPENVPN_PLUGIN_UP,
2036 c->c1.tuntap->actual_name,
445b192a 2037#ifdef _WIN32
81d882d5
DS
2038 c->c1.tuntap->adapter_index,
2039#endif
2040 dev_type_string(c->options.dev, c->options.dev_type),
364b7b4f 2041 c->c2.frame.tun_mtu,
81d882d5
DS
2042 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
2043 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
bd139689 2044 "init",
81d882d5
DS
2045 NULL,
2046 "up",
2047 c->c2.es);
bd139689 2048
bf887c95 2049 add_wfp_block(c);
bd139689
AQ
2050
2051 /* possibly add routes */
d0a93625 2052 if ((route_order(c->c1.tuntap) == ROUTE_AFTER_TUN) && (!c->options.route_delay_defined))
bd139689 2053 {
e04c2536
SN
2054 int status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
2055 c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
2056 *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS);
451d2177 2057 }
bd139689
AQ
2058
2059 ret = true;
2060 static_context = c;
6fbf66fa 2061 }
bd139689
AQ
2062 else
2063 {
2064 msg(M_INFO, "Preserving previous TUN/TAP instance: %s",
2065 c->c1.tuntap->actual_name);
2066
2067 /* explicitly set the ifconfig_* env vars */
2068 do_ifconfig_setenv(c->c1.tuntap, c->c2.es);
2069
1dfe8729 2070 run_dns_up_down(true, &c->options, c->c1.tuntap, &c->persist.duri);
0f3b7d17 2071
bd139689
AQ
2072 /* run the up script if user specified --up-restart */
2073 if (c->options.up_restart)
2074 {
2075 run_up_down(c->options.up_script,
2076 c->plugins,
2077 OPENVPN_PLUGIN_UP,
2078 c->c1.tuntap->actual_name,
2079#ifdef _WIN32
2080 c->c1.tuntap->adapter_index,
2081#endif
2082 dev_type_string(c->options.dev, c->options.dev_type),
2083 c->c2.frame.tun_mtu,
2084 print_in_addr_t(c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
2085 print_in_addr_t(c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2086 "restart",
2087 NULL,
2088 "up",
2089 c->c2.es);
2090 }
81d882d5 2091
bf887c95 2092 add_wfp_block(c);
bd139689 2093 }
81d882d5
DS
2094 gc_free(&gc);
2095 return ret;
6fbf66fa
JY
2096}
2097
2098/*
2099 * Close TUN/TAP device
2100 */
2101
2102static void
81d882d5 2103do_close_tun_simple(struct context *c)
6fbf66fa 2104{
77829be2 2105 msg(D_CLOSE, "Closing %s interface",
193b4f9d 2106 print_tun_backend_driver(c->c1.tuntap->backend_driver));
77829be2 2107
0bea472c
AQ
2108 if (c->c1.tuntap)
2109 {
5c4a0b71 2110 if (!ifconfig_noexec_enabled(c))
0c4d40cb
MF
2111 {
2112 undo_ifconfig(c->c1.tuntap, &c->net_ctx);
2113 }
d0a93625
AS
2114 if (c->c1.tuntap->backend_driver == DRIVER_AFUNIX)
2115 {
2116 close_tun_afunix(c->c1.tuntap);
2117 }
8fe14fea
AS
2118 else if (c->c1.tuntap->backend_driver == DRIVER_NULL)
2119 {
2120 free(c->c1.tuntap->actual_name);
2121 free(c->c1.tuntap);
2122 }
d0a93625
AS
2123 else
2124 {
2125 close_tun(c->c1.tuntap, &c->net_ctx);
2126 }
0bea472c
AQ
2127 c->c1.tuntap = NULL;
2128 }
81d882d5 2129 c->c1.tuntap_owned = false;
81d882d5 2130 CLEAR(c->c1.pulled_options_digest_save);
6fbf66fa
JY
2131}
2132
2133static void
81d882d5 2134do_close_tun(struct context *c, bool force)
6fbf66fa 2135{
3adbc5c6
AQ
2136 /* With dco-win we open tun handle in the very beginning.
2137 * In case when tun wasn't opened - like we haven't connected,
2138 * we still need to close tun handle
2139 */
2140 if (tuntap_is_dco_win(c->c1.tuntap) && !is_tun_type_set(c->c1.tuntap))
2141 {
2142 do_close_tun_simple(c);
2143 return;
2144 }
2145
c05a0502 2146 if (!c->c1.tuntap || !c->c1.tuntap_owned)
6fbf66fa 2147 {
c05a0502
AQ
2148 return;
2149 }
2150
2151 struct gc_arena gc = gc_new();
2152 const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc);
c05a0502
AQ
2153 const in_addr_t local = c->c1.tuntap->local;
2154 const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
bf887c95
HH
2155 unsigned long adapter_index = 0;
2156#ifdef _WIN32
2157 adapter_index = c->c1.tuntap->adapter_index;
2158#endif
6fbf66fa 2159
1dfe8729 2160 run_dns_up_down(false, &c->options, c->c1.tuntap, &c->persist.duri);
0f3b7d17 2161
c05a0502
AQ
2162 if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
2163 {
2164 static_context = NULL;
0c9eb1d3 2165
6fbf66fa 2166#ifdef ENABLE_MANAGEMENT
c05a0502
AQ
2167 /* tell management layer we are about to close the TUN/TAP device */
2168 if (management)
2169 {
2170 management_pre_tunnel_close(management);
2171 management_up_down(management, "DOWN", c->c2.es);
2172 }
81d882d5 2173#endif
6fbf66fa 2174
c05a0502
AQ
2175 /* delete any routes we added */
2176 if (c->c1.route_list || c->c1.route_ipv6_list)
2177 {
2178 run_up_down(c->options.route_predown_script,
81d882d5 2179 c->plugins,
c05a0502 2180 OPENVPN_PLUGIN_ROUTE_PREDOWN,
81d882d5 2181 tuntap_actual,
445b192a 2182#ifdef _WIN32
81d882d5
DS
2183 adapter_index,
2184#endif
2185 NULL,
364b7b4f 2186 c->c2.frame.tun_mtu,
81d882d5
DS
2187 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2188 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2189 "init",
2190 signal_description(c->sig->signal_received,
2191 c->sig->signal_text),
c05a0502 2192 "route-pre-down",
81d882d5 2193 c->c2.es);
6fbf66fa 2194
c05a0502
AQ
2195 delete_routes(c->c1.route_list, c->c1.route_ipv6_list,
2196 c->c1.tuntap, ROUTE_OPTION_FLAGS(&c->options),
2197 c->c2.es, &c->net_ctx);
2198 }
2199
2200 /* actually close tun/tap device based on --down-pre flag */
2201 if (!c->options.down_pre)
2202 {
2203 do_close_tun_simple(c);
2204 }
2205
2206 /* Run the down script -- note that it will run at reduced
a6664825 2207 * privilege if, for example, "--user" was used. */
c05a0502
AQ
2208 run_up_down(c->options.down_script,
2209 c->plugins,
2210 OPENVPN_PLUGIN_DOWN,
2211 tuntap_actual,
2212#ifdef _WIN32
2213 adapter_index,
2214#endif
2215 NULL,
2216 c->c2.frame.tun_mtu,
2217 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2218 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2219 "init",
2220 signal_description(c->sig->signal_received,
2221 c->sig->signal_text),
2222 "down",
2223 c->c2.es);
2224
bf887c95 2225 del_wfp_block(c, adapter_index);
38c85658 2226
c05a0502
AQ
2227 /* actually close tun/tap device based on --down-pre flag */
2228 if (c->options.down_pre)
2229 {
2230 do_close_tun_simple(c);
81d882d5 2231 }
c05a0502
AQ
2232 }
2233 else
2234 {
2235 /* run the down script on this restart if --up-restart was specified */
2236 if (c->options.up_restart)
81d882d5 2237 {
c05a0502
AQ
2238 run_up_down(c->options.down_script,
2239 c->plugins,
2240 OPENVPN_PLUGIN_DOWN,
2241 tuntap_actual,
445b192a 2242#ifdef _WIN32
c05a0502 2243 adapter_index,
81d882d5 2244#endif
c05a0502
AQ
2245 NULL,
2246 c->c2.frame.tun_mtu,
2247 print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2248 print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2249 "restart",
2250 signal_description(c->sig->signal_received,
2251 c->sig->signal_text),
2252 "down",
2253 c->c2.es);
2254 }
451d2177 2255
bf887c95 2256 del_wfp_block(c, adapter_index);
6fbf66fa 2257 }
81d882d5 2258 gc_free(&gc);
6fbf66fa
JY
2259}
2260
0c9eb1d3 2261void
e2a0cad4 2262tun_abort(void)
0c9eb1d3 2263{
81d882d5
DS
2264 struct context *c = static_context;
2265 if (c)
0c9eb1d3 2266 {
81d882d5
DS
2267 static_context = NULL;
2268 do_close_tun(c, true);
0c9eb1d3
JY
2269 }
2270}
2271
6fbf66fa
JY
2272/*
2273 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
2274 */
2275
827de237
SK
2276/**
2277 * Helper for do_up(). Take two option hashes and return true if they are not
2278 * equal, or either one is all-zeroes.
2279 */
2280static bool
5b48e8c9
SK
2281options_hash_changed_or_zero(const struct sha256_digest *a,
2282 const struct sha256_digest *b)
827de237 2283{
5b48e8c9
SK
2284 const struct sha256_digest zero = {{0}};
2285 return memcmp(a, b, sizeof(struct sha256_digest))
2286 || !memcmp(a, &zero, sizeof(struct sha256_digest));
827de237 2287}
827de237 2288
c333a0c0
AS
2289/**
2290 * Helper function for tls_print_deferred_options_results
2291 * Adds the ", " delimitor if there already some data in the
2292 * buffer.
2293 */
2294static void
2295add_delim_if_non_empty(struct buffer *buf, const char *header)
2296{
2297 if (buf_len(buf) > strlen(header))
2298 {
2299 buf_printf(buf, ", ");
2300 }
2301}
2302
2303
2304/**
2305 * Prints the results of options imported for the data channel
ccdffc08 2306 * @param c
c333a0c0
AS
2307 */
2308static void
2309tls_print_deferred_options_results(struct context *c)
2310{
2311 struct options *o = &c->options;
2312
2313 struct buffer out;
2314 uint8_t line[1024] = { 0 };
2315 buf_set_write(&out, line, sizeof(line));
2316
2317
2318 if (cipher_kt_mode_aead(o->ciphername))
2319 {
2320 buf_printf(&out, "Data Channel: cipher '%s'",
2321 cipher_kt_name(o->ciphername));
2322 }
2323 else
2324 {
2325 buf_printf(&out, "Data Channel: cipher '%s', auth '%s'",
2326 cipher_kt_name(o->ciphername), md_kt_name(o->authname));
2327 }
2328
2329 if (o->use_peer_id)
2330 {
2331 buf_printf(&out, ", peer-id: %d", o->peer_id);
2332 }
2333
2334#ifdef USE_COMP
2335 if (c->c2.comp_context)
2336 {
2337 buf_printf(&out, ", compression: '%s'", c->c2.comp_context->alg.name);
2338 }
2339#endif
2340
2341 msg(D_HANDSHAKE, "%s", BSTR(&out));
2342
2343 buf_clear(&out);
2344
2345 const char *header = "Timers: ";
2346
2347 buf_printf(&out, "%s", header);
2348
2349 if (o->ping_send_timeout)
2350 {
2351 buf_printf(&out, "ping %d", o->ping_send_timeout);
2352 }
2353
2354 if (o->ping_rec_timeout_action != PING_UNDEF)
2355 {
2356 /* yes unidirectional ping is possible .... */
2357 add_delim_if_non_empty(&out, header);
2358
2359 if (o->ping_rec_timeout_action == PING_EXIT)
2360 {
2361 buf_printf(&out, "ping-exit %d", o->ping_rec_timeout);
2362 }
2363 else
2364 {
2365 buf_printf(&out, "ping-restart %d", o->ping_rec_timeout);
2366 }
2367 }
2368
2369 if (o->inactivity_timeout)
2370 {
2371 add_delim_if_non_empty(&out, header);
2372
2373 buf_printf(&out, "inactive %d", o->inactivity_timeout);
2374 if (o->inactivity_minimum_bytes)
2375 {
2376 buf_printf(&out, " %" PRIu64, o->inactivity_minimum_bytes);
2377 }
2378 }
2379
2380 if (o->session_timeout)
2381 {
2382 add_delim_if_non_empty(&out, header);
2383 buf_printf(&out, "session-timeout %d", o->session_timeout);
2384 }
2385
2386 if (buf_len(&out) > strlen(header))
2387 {
2388 msg(D_HANDSHAKE, "%s", BSTR(&out));
2389 }
2390
2391 buf_clear(&out);
2392 header = "Protocol options: ";
2393 buf_printf(&out, "%s", header);
2394
2395 if (c->options.ce.explicit_exit_notification)
2396 {
2397 buf_printf(&out, "explicit-exit-notify %d",
2398 c->options.ce.explicit_exit_notification);
2399 }
2400 if (c->options.imported_protocol_flags)
2401 {
2402 add_delim_if_non_empty(&out, header);
2403
2404 buf_printf(&out, "protocol-flags");
2405
2406 if (o->imported_protocol_flags & CO_USE_CC_EXIT_NOTIFY)
2407 {
2408 buf_printf(&out, " cc-exit");
2409 }
2410 if (o->imported_protocol_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT)
2411 {
2412 buf_printf(&out, " tls-ekm");
2413 }
6a05768a
AS
2414 if (o->imported_protocol_flags & CO_USE_DYNAMIC_TLS_CRYPT)
2415 {
2416 buf_printf(&out, " dyn-tls-crypt");
2417 }
0671a4d0 2418 if (o->imported_protocol_flags & CO_EPOCH_DATA_KEY_FORMAT)
233e10ae 2419 {
0671a4d0 2420 buf_printf(&out, " aead-epoch");
233e10ae 2421 }
c333a0c0
AS
2422 }
2423
2424 if (buf_len(&out) > strlen(header))
2425 {
2426 msg(D_HANDSHAKE, "%s", BSTR(&out));
2427 }
2428}
2429
2430
6b9f4d71
AQ
2431/**
2432 * This function is expected to be invoked after open_tun() was performed.
2433 *
2434 * This kind of behaviour is required by DCO, because the following operations
2435 * can be done only after the DCO device was created and the new peer was
2436 * properly added.
2437 */
2438static bool
2439do_deferred_options_part2(struct context *c)
2440{
2441 struct frame *frame_fragment = NULL;
2442#ifdef ENABLE_FRAGMENT
2443 if (c->options.ce.fragment)
2444 {
2445 frame_fragment = &c->c2.frame_fragment;
2446 }
2447#endif
2448
2449 struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2450 if (!tls_session_update_crypto_params(c->c2.tls_multi, session,
2451 &c->options, &c->c2.frame,
2452 frame_fragment,
32e748bd
GDG
2453 get_link_socket_info(c),
2454 &c->c1.tuntap->dco))
6b9f4d71
AQ
2455 {
2456 msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options");
2457 return false;
2458 }
2459
2460 return true;
2461}
2462
d728ebed 2463bool
81d882d5 2464do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
6fbf66fa 2465{
e04c2536 2466 int error_flags = 0;
81d882d5 2467 if (!c->c2.do_up_ran)
6fbf66fa 2468 {
81d882d5 2469 reset_coarse_timers(c);
6fbf66fa 2470
bd230079 2471 if (pulled_options)
81d882d5
DS
2472 {
2473 if (!do_deferred_options(c, option_types_found))
2474 {
2475 msg(D_PUSH_ERRORS, "ERROR: Failed to apply push options");
2476 return false;
2477 }
2478 }
6fbf66fa 2479
81d882d5
DS
2480 /* if --up-delay specified, open tun, do ifconfig, and run up script now */
2481 if (c->options.up_delay || PULL_DEFINED(&c->options))
2482 {
e04c2536 2483 c->c2.did_open_tun = do_open_tun(c, &error_flags);
81d882d5 2484 update_time();
6fbf66fa 2485
81d882d5
DS
2486 /*
2487 * Was tun interface object persisted from previous restart iteration,
2488 * and if so did pulled options string change from previous iteration?
2489 */
2490 if (!c->c2.did_open_tun
2491 && PULL_DEFINED(&c->options)
2492 && c->c1.tuntap
2493 && options_hash_changed_or_zero(&c->c1.pulled_options_digest_save,
2494 &c->c2.pulled_options_digest))
2495 {
2496 /* if so, close tun, delete routes, then reinitialize tun and add routes */
2497 msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
cac18de7
LS
2498
2499 bool tt_dco_win = tuntap_is_dco_win(c->c1.tuntap);
81d882d5 2500 do_close_tun(c, true);
cac18de7
LS
2501
2502 if (tt_dco_win)
2503 {
2504 msg(M_NONFATAL, "dco-win doesn't yet support reopening TUN device");
2505 /* prevent link_socket_close() from closing handle with WinSock API */
94b391d7 2506 c->c2.link_sockets[0]->sd = SOCKET_UNDEFINED;
cac18de7
LS
2507 return false;
2508 }
2509 else
2510 {
2511 management_sleep(1);
e04c2536 2512 c->c2.did_open_tun = do_open_tun(c, &error_flags);
cac18de7
LS
2513 update_time();
2514 }
81d882d5 2515 }
81d882d5 2516 }
cde3edb1 2517 }
81d882d5 2518
cde3edb1
AS
2519 /* This part needs to be run in p2p mode (without pull) when the client
2520 * reconnects to setup various things (like DCO and NCP cipher) that
2521 * might have changed from the previous connection.
2522 */
2523 if (!c->c2.do_up_ran || (c->c2.tls_multi && c->c2.tls_multi->multi_state == CAS_RECONNECT_PENDING))
2524 {
b6f7b285
AQ
2525 if (c->mode == MODE_POINT_TO_POINT)
2526 {
2527 /* ovpn-dco requires adding the peer now, before any option can be set,
2528 * but *after* having parsed the pushed peer-id in do_deferred_options()
2529 */
2530 int ret = dco_p2p_add_new_peer(c);
2531 if (ret < 0)
2532 {
2533 msg(D_DCO, "Cannot add peer to DCO: %s (%d)", strerror(-ret), ret);
2534 return false;
2535 }
2536 }
2537
6b9f4d71
AQ
2538 /* do_deferred_options_part2() and do_deferred_p2p_ncp() *must* be
2539 * invoked after open_tun().
2540 * This is required by DCO because we must have created the interface
2541 * and added the peer before we can fiddle with the keys or any other
2542 * data channel per-peer setting.
2543 */
2544 if (pulled_options)
2545 {
2546 if (!do_deferred_options_part2(c))
2547 {
2548 return false;
2549 }
2550 }
2551 else
2552 {
2553 if (c->mode == MODE_POINT_TO_POINT)
2554 {
2555 if (!do_deferred_p2p_ncp(c))
2556 {
2557 msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
2558 return false;
2559 }
2560 }
2561 }
2562
81d882d5
DS
2563 if (c->c2.did_open_tun)
2564 {
81d882d5 2565 c->c1.pulled_options_digest_save = c->c2.pulled_options_digest;
81d882d5
DS
2566
2567 /* if --route-delay was specified, start timer */
d0a93625 2568 if ((route_order(c->c1.tuntap) == ROUTE_AFTER_TUN) && c->options.route_delay_defined)
81d882d5
DS
2569 {
2570 event_timeout_init(&c->c2.route_wakeup, c->options.route_delay, now);
2571 event_timeout_init(&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
a8cc97f9 2572 tun_standby_init(c->c1.tuntap);
81d882d5
DS
2573 }
2574 else
2575 {
eef30e6e
FL
2576 /* client/p2p --route-delay undefined */
2577 initialization_sequence_completed(c, error_flags);
81d882d5
DS
2578 }
2579 }
2580 else if (c->options.mode == MODE_POINT_TO_POINT)
2581 {
eef30e6e
FL
2582 /* client/p2p restart with --persist-tun */
2583 initialization_sequence_completed(c, error_flags);
81d882d5
DS
2584 }
2585
c333a0c0
AS
2586 tls_print_deferred_options_results(c);
2587
81d882d5 2588 c->c2.do_up_ran = true;
34b42549
AS
2589 if (c->c2.tls_multi)
2590 {
2591 c->c2.tls_multi->multi_state = CAS_CONNECT_DONE;
2592 }
81d882d5
DS
2593 }
2594 return true;
6fbf66fa
JY
2595}
2596
2597/*
2598 * These are the option categories which will be accepted by pull.
2599 */
2600unsigned int
81d882d5
DS
2601pull_permission_mask(const struct context *c)
2602{
2603 unsigned int flags =
2604 OPT_P_UP
2605 | OPT_P_ROUTE_EXTRAS
2606 | OPT_P_SOCKBUF
2607 | OPT_P_SOCKFLAGS
2608 | OPT_P_SETENV
2609 | OPT_P_SHAPER
2610 | OPT_P_TIMER
2611 | OPT_P_COMP
2612 | OPT_P_PERSIST
2613 | OPT_P_MESSAGES
2614 | OPT_P_EXPLICIT_NOTIFY
2615 | OPT_P_ECHO
2616 | OPT_P_PULL_MODE
caacd629 2617 | OPT_P_PEER_ID
01aed6a5
AS
2618 | OPT_P_NCP
2619 | OPT_P_PUSH_MTU;
81d882d5
DS
2620
2621 if (!c->options.route_nopull)
2622 {
8a7d0005 2623 flags |= (OPT_P_ROUTE | OPT_P_DHCPDNS);
81d882d5 2624 }
3c7f2f55 2625
81d882d5 2626 return flags;
6fbf66fa
JY
2627}
2628
8c72d798
AS
2629static bool
2630do_deferred_p2p_ncp(struct context *c)
2631{
2632 if (!c->c2.tls_multi)
2633 {
2634 return true;
2635 }
2636
0d46c496
LS
2637 c->options.use_peer_id = c->c2.tls_multi->use_peer_id;
2638
8c72d798
AS
2639 struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2640
2641 const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,
2642 &c->options.gc);
2643
2644 if (ncp_cipher)
2645 {
2646 c->options.ciphername = ncp_cipher;
2647 }
2648 else if (!c->options.enable_ncp_fallback)
2649 {
2650 msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
abe49856
DS
2651 "--data-ciphers-fallback not enabled. No usable "
2652 "data channel cipher");
8c72d798
AS
2653 return false;
2654 }
2655
2656 struct frame *frame_fragment = NULL;
2657#ifdef ENABLE_FRAGMENT
2658 if (c->options.ce.fragment)
2659 {
2660 frame_fragment = &c->c2.frame_fragment;
2661 }
2662#endif
2663
6a5612fe
AQ
2664 if (!tls_session_update_crypto_params(c->c2.tls_multi, session, &c->options,
2665 &c->c2.frame, frame_fragment,
32e748bd
GDG
2666 get_link_socket_info(c),
2667 &c->c1.tuntap->dco))
8c72d798
AS
2668 {
2669 msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
2670 return false;
2671 }
2672 return true;
2673}
2674
6fbf66fa
JY
2675/*
2676 * Handle non-tun-related pulled options.
2677 */
d728ebed 2678bool
81d882d5 2679do_deferred_options(struct context *c, const unsigned int found)
6fbf66fa 2680{
81d882d5 2681 if (found & OPT_P_MESSAGES)
6fbf66fa 2682 {
81d882d5
DS
2683 init_verb_mute(c, IVM_LEVEL_1|IVM_LEVEL_2);
2684 msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
6fbf66fa 2685 }
81d882d5 2686 if (found & OPT_P_TIMER)
6fbf66fa 2687 {
81d882d5 2688 do_init_timers(c, true);
c333a0c0 2689 msg(D_PUSH_DEBUG, "OPTIONS IMPORT: timers and/or timeouts modified");
6fbf66fa
JY
2690 }
2691
81d882d5 2692 if (found & OPT_P_EXPLICIT_NOTIFY)
6fbf66fa 2693 {
619c3e9a
GDG
2694 /* Client side, so just check the first link_socket */
2695 if (!proto_is_udp(c->c2.link_sockets[0]->info.proto)
2696 && c->options.ce.explicit_exit_notification)
81d882d5
DS
2697 {
2698 msg(D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
2699 c->options.ce.explicit_exit_notification = 0;
2700 }
2701 else
2702 {
c333a0c0 2703 msg(D_PUSH_DEBUG, "OPTIONS IMPORT: explicit notify parm(s) modified");
81d882d5 2704 }
6fbf66fa 2705 }
6fbf66fa 2706
81d882d5 2707 if (found & OPT_P_COMP)
537073fd 2708 {
e86bc8b2
AS
2709 if (!check_compression_settings_valid(&c->options.comp, D_PUSH_ERRORS))
2710 {
2711 msg(D_PUSH_ERRORS, "OPTIONS ERROR: server pushed compression "
2712 "settings that are not allowed and will result "
2713 "in a non-working connection. "
2714 "See also allow-compression in the manual.");
2715 return false;
2716 }
a8170dd0 2717#ifdef USE_COMP
c333a0c0 2718 msg(D_PUSH_DEBUG, "OPTIONS IMPORT: compression parms modified");
81d882d5
DS
2719 comp_uninit(c->c2.comp_context);
2720 c->c2.comp_context = comp_init(&c->options.comp);
537073fd 2721#endif
a8170dd0 2722 }
537073fd 2723
81d882d5 2724 if (found & OPT_P_SHAPER)
6fbf66fa 2725 {
81d882d5
DS
2726 msg(D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
2727 do_init_traffic_shaper(c);
6fbf66fa
JY
2728 }
2729
81d882d5 2730 if (found & OPT_P_SOCKBUF)
00d39170 2731 {
81d882d5 2732 msg(D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
94b391d7
AQ
2733
2734 for (int i = 0; i < c->c1.link_sockets_num; i++)
2735 {
2736 link_socket_update_buffer_sizes(c->c2.link_sockets[i],
2737 c->options.rcvbuf,
2738 c->options.sndbuf);
2739 }
00d39170
JY
2740 }
2741
81d882d5 2742 if (found & OPT_P_SOCKFLAGS)
00d39170 2743 {
81d882d5 2744 msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
94b391d7
AQ
2745 for (int i = 0; i < c->c1.link_sockets_num; i++)
2746 {
2747 link_socket_update_flags(c->c2.link_sockets[i],
2748 c->options.sockflags);
2749 }
00d39170
JY
2750 }
2751
81d882d5
DS
2752 if (found & OPT_P_PERSIST)
2753 {
2754 msg(D_PUSH, "OPTIONS IMPORT: --persist options modified");
2755 }
2756 if (found & OPT_P_UP)
2757 {
2758 msg(D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
2759 }
2760 if (found & OPT_P_ROUTE)
2761 {
2762 msg(D_PUSH, "OPTIONS IMPORT: route options modified");
2763 }
2764 if (found & OPT_P_ROUTE_EXTRAS)
2765 {
2766 msg(D_PUSH, "OPTIONS IMPORT: route-related options modified");
2767 }
8a7d0005 2768 if (found & OPT_P_DHCPDNS)
81d882d5
DS
2769 {
2770 msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
2771 }
2772 if (found & OPT_P_SETENV)
2773 {
2774 msg(D_PUSH, "OPTIONS IMPORT: environment modified");
2775 }
65eedc35 2776
81d882d5
DS
2777 if (found & OPT_P_PEER_ID)
2778 {
c333a0c0 2779 msg(D_PUSH_DEBUG, "OPTIONS IMPORT: peer-id set");
81d882d5
DS
2780 c->c2.tls_multi->use_peer_id = true;
2781 c->c2.tls_multi->peer_id = c->options.peer_id;
81d882d5
DS
2782 }
2783
f9ef554a 2784 /* process (potentially) pushed options */
81d882d5
DS
2785 if (c->options.pull)
2786 {
2c1d8c33 2787 if (!check_pull_client_ncp(c, found))
81d882d5 2788 {
2c1d8c33 2789 return false;
81d882d5 2790 }
c7ca9133 2791
f9ef554a
AQ
2792 /* Check if pushed options are compatible with DCO, if enabled */
2793 if (dco_enabled(&c->options)
2794 && !dco_check_pull_options(D_PUSH_ERRORS, &c->options))
2795 {
2796 msg(D_PUSH_ERRORS, "OPTIONS ERROR: pushed options are incompatible "
2797 "with data channel offload. Use --disable-dco to connect to "
2798 "this server");
2799 return false;
2800 }
46f6a7e8
AQ
2801 }
2802
9f4670fc
AS
2803 /* Ensure that for epoch data format is only enabled if also data v2
2804 * is enabled */
2805 bool epoch_data = (c->options.imported_protocol_flags & CO_EPOCH_DATA_KEY_FORMAT);
2806 bool datav2_enabled = (c->options.peer_id >= 0 && c->options.peer_id < MAX_PEER_ID);
2807
2808 if (epoch_data && !datav2_enabled)
2809 {
2810 msg(D_PUSH_ERRORS, "OPTIONS ERROR: Epoch key data format tag requires "
2811 "data v2 (peer-id) to be enabled.");
2812 return false;
2813 }
2814
2815
01aed6a5
AS
2816 if (found & OPT_P_PUSH_MTU)
2817 {
2818 /* MTU has changed, check that the pushed MTU is small enough to
2819 * be able to change it */
2820 msg(D_PUSH, "OPTIONS IMPORT: tun-mtu set to %d", c->options.ce.tun_mtu);
2821
2822 struct frame *frame = &c->c2.frame;
2823
2824 if (c->options.ce.tun_mtu > frame->tun_max_mtu)
2825 {
2826 msg(D_PUSH_ERRORS, "Server-pushed tun-mtu is too large, please add "
2827 "tun-mtu-max %d in the client configuration",
2828 c->options.ce.tun_mtu);
2829 }
2830 frame->tun_mtu = min_int(frame->tun_max_mtu, c->options.ce.tun_mtu);
2831 }
2832
81d882d5 2833 return true;
6fbf66fa
JY
2834}
2835
2836/*
396d30c2
AS
2837 * Possible hold on initialization, holdtime is the
2838 * time OpenVPN would wait without management
6fbf66fa
JY
2839 */
2840static bool
81d882d5 2841do_hold(int holdtime)
6fbf66fa
JY
2842{
2843#ifdef ENABLE_MANAGEMENT
81d882d5 2844 if (management)
6fbf66fa 2845 {
81d882d5
DS
2846 /* block until management hold is released */
2847 if (management_hold(management, holdtime))
2848 {
2849 return true;
2850 }
6fbf66fa
JY
2851 }
2852#endif
81d882d5 2853 return false;
6fbf66fa
JY
2854}
2855
2856/*
2857 * Sleep before restart.
2858 */
2859static void
81d882d5 2860socket_restart_pause(struct context *c)
6fbf66fa 2861{
81d882d5
DS
2862 int sec = 2;
2863 int backoff = 0;
6fbf66fa 2864
619c3e9a 2865 switch (c->mode)
6fbf66fa 2866 {
619c3e9a 2867 case CM_TOP:
81d882d5
DS
2868 sec = 1;
2869 break;
2870
619c3e9a
GDG
2871 case CM_CHILD_UDP:
2872 case CM_CHILD_TCP:
81d882d5
DS
2873 sec = c->options.ce.connect_retry_seconds;
2874 break;
6fbf66fa
JY
2875 }
2876
2877#ifdef ENABLE_DEBUG
81d882d5
DS
2878 if (GREMLIN_CONNECTION_FLOOD_LEVEL(c->options.gremlin))
2879 {
2880 sec = 0;
2881 }
6fbf66fa
JY
2882#endif
2883
81d882d5
DS
2884 if (auth_retry_get() == AR_NOINTERACT)
2885 {
2886 sec = 10;
2887 }
6fbf66fa 2888
063d55af 2889 /* Slow down reconnection after 5 retries per remote -- for TCP client or UDP tls-client only */
619c3e9a 2890 if (c->mode == CM_CHILD_TCP
063d55af 2891 || (c->options.ce.proto == PROTO_UDP && c->options.tls_client))
5d429efd 2892 {
81d882d5
DS
2893 backoff = (c->options.unsuccessful_attempts / c->options.connection_list->len) - 4;
2894 if (backoff > 0)
5d429efd 2895 {
81d882d5
DS
2896 /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */
2897 sec = max_int(sec, 1) << min_int(backoff, 15);
5d429efd 2898 }
c9474fa3
AS
2899 if (c->options.server_backoff_time)
2900 {
2901 sec = max_int(sec, c->options.server_backoff_time);
2902 c->options.server_backoff_time = 0;
2903 }
5d429efd 2904
81d882d5
DS
2905 if (sec > c->options.ce.connect_retry_seconds_max)
2906 {
2907 sec = c->options.ce.connect_retry_seconds_max;
2908 }
5d429efd
SN
2909 }
2910
81d882d5
DS
2911 if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
2912 {
2913 sec = c->persist.restart_sleep_seconds;
2914 }
2915 else if (c->persist.restart_sleep_seconds == -1)
2916 {
2917 sec = 0;
2918 }
2919 c->persist.restart_sleep_seconds = 0;
a9c802b2 2920
ccb636c7 2921 /* do management hold on context restart, i.e. second, third, fourth, etc. initialization */
81d882d5
DS
2922 if (do_hold(sec))
2923 {
2924 sec = 0;
2925 }
6fbf66fa 2926
81d882d5 2927 if (sec)
6fbf66fa 2928 {
81d882d5 2929 msg(D_RESTART, "Restart pause, %d second(s)", sec);
45b2af9c 2930 management_sleep(sec);
6fbf66fa
JY
2931 }
2932}
2933
2934/*
2935 * Do a possible pause on context_2 initialization.
2936 */
2937static void
81d882d5 2938do_startup_pause(struct context *c)
6fbf66fa 2939{
81d882d5
DS
2940 if (!c->first_time)
2941 {
2942 socket_restart_pause(c);
2943 }
2944 else
2945 {
2946 do_hold(0); /* do management hold on first context initialization */
2947 }
6fbf66fa
JY
2948}
2949
65a21eb1
AS
2950static size_t
2951get_frame_mtu(struct context *c, const struct options *o)
2952{
2953 size_t mtu;
2954
2955 if (o->ce.link_mtu_defined)
2956 {
2957 ASSERT(o->ce.link_mtu_defined);
2958 /* if we have a link mtu defined we calculate what the old code
2959 * would have come up with as tun-mtu */
2960 size_t overhead = frame_calculate_protocol_header_size(&c->c1.ks.key_type,
2961 o, true);
2962 mtu = o->ce.link_mtu - overhead;
2963
2964 }
2965 else
2966 {
2967 ASSERT(o->ce.tun_mtu_defined);
2968 mtu = o->ce.tun_mtu;
2969 }
2970
2971 if (mtu < TUN_MTU_MIN)
2972 {
6e375353 2973 msg(M_WARN, "TUN MTU value (%zu) must be at least %d", mtu, TUN_MTU_MIN);
65a21eb1
AS
2974 frame_print(&c->c2.frame, M_FATAL, "MTU is too small");
2975 }
2976 return mtu;
2977}
2978
6fbf66fa
JY
2979/*
2980 * Finalize MTU parameters based on command line or config file options.
2981 */
2982static void
81d882d5 2983frame_finalize_options(struct context *c, const struct options *o)
6fbf66fa 2984{
81d882d5
DS
2985 if (!o)
2986 {
2987 o = &c->options;
2988 }
6fbf66fa 2989
65a21eb1
AS
2990 struct frame *frame = &c->c2.frame;
2991
2992 frame->tun_mtu = get_frame_mtu(c, o);
01aed6a5
AS
2993 frame->tun_max_mtu = o->ce.tun_mtu_max;
2994
2995 /* max mtu needs to be at least as large as the tun mtu */
2996 frame->tun_max_mtu = max_int(frame->tun_mtu, frame->tun_max_mtu);
65a21eb1 2997
01aed6a5
AS
2998 /* We always allow at least 1600 MTU packets to be received in our buffer
2999 * space to allow server to push "baby giant" MTU sizes */
3000 frame->tun_max_mtu = max_int(1600, frame->tun_max_mtu);
3001
3002 size_t payload_size = frame->tun_max_mtu;
65a21eb1 3003
5f6ea597
AS
3004 /* we need to be also large enough to hold larger control channel packets
3005 * if configured */
3006 payload_size = max_int(payload_size, o->ce.tls_mtu);
3007
65a21eb1
AS
3008 /* The extra tun needs to be added to the payload size */
3009 if (o->ce.tun_mtu_defined)
3010 {
3011 payload_size += o->ce.tun_mtu_extra;
3012 }
3013
01aed6a5
AS
3014 /* Add 32 byte of extra space in the buffer to account for small errors
3015 * in the calculation */
3016 payload_size += 32;
65a21eb1
AS
3017
3018
3019 /* the space that is reserved before the payload to add extra headers to it
abe49856 3020 * we always reserve the space for the worst case */
65a21eb1
AS
3021 size_t headroom = 0;
3022
3023 /* includes IV and packet ID */
3024 headroom += crypto_max_overhead();
3025
3026 /* peer id + opcode */
3027 headroom += 4;
3028
3029 /* socks proxy header */
3030 headroom += 10;
3031
3032 /* compression header and fragment header (part of the encrypted payload) */
3033 headroom += 1 + 1;
3034
3035 /* Round up headroom to the next multiple of 4 to ensure alignment */
3036 headroom = (headroom + 3) & ~3;
3037
3038 /* Add the headroom to the payloadsize as a received (IP) packet can have
3039 * all the extra headers in it */
3040 payload_size += headroom;
3041
3042 /* the space after the payload, this needs some extra buffer space for
3043 * encryption so headroom is probably too much but we do not really care
3044 * the few extra bytes */
3045 size_t tailroom = headroom;
3046
3047#ifdef USE_COMP
8c815699 3048 msg(D_MTU_DEBUG, "MTU: adding %zu buffer tailroom for compression for %zu "
abe49856
DS
3049 "bytes of payload",
3050 COMP_EXTRA_BUFFER(payload_size), payload_size);
65a21eb1
AS
3051 tailroom += COMP_EXTRA_BUFFER(payload_size);
3052#endif
3053
3054 frame->buf.payload_size = payload_size;
3055 frame->buf.headroom = headroom;
3056 frame->buf.tailroom = tailroom;
6fbf66fa
JY
3057}
3058
3059/*
3060 * Free a key schedule, including OpenSSL components.
3061 */
3062static void
81d882d5 3063key_schedule_free(struct key_schedule *ks, bool free_ssl_ctx)
6fbf66fa 3064{
81d882d5
DS
3065 free_key_ctx_bi(&ks->static_key);
3066 if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
6fbf66fa 3067 {
81d882d5 3068 tls_ctx_free(&ks->ssl_ctx);
fe39156a 3069 free_key_ctx(&ks->auth_token_key);
6fbf66fa 3070 }
81d882d5 3071 CLEAR(*ks);
6fbf66fa
JY
3072}
3073
6fbf66fa 3074static void
81d882d5 3075init_crypto_pre(struct context *c, const unsigned int flags)
6fbf66fa 3076{
81d882d5
DS
3077 if (c->options.engine)
3078 {
3079 crypto_init_lib_engine(c->options.engine);
3080 }
6fbf66fa 3081
81d882d5 3082 if (flags & CF_LOAD_PERSISTED_PACKET_ID)
6fbf66fa 3083 {
81d882d5
DS
3084 /* load a persisted packet-id for cross-session replay-protection */
3085 if (c->options.packet_id_file)
3086 {
3087 packet_id_persist_load(&c->c1.pid_persist, c->options.packet_id_file);
3088 }
6fbf66fa
JY
3089 }
3090
0f25d296 3091#ifdef ENABLE_PREDICTION_RESISTANCE
81d882d5
DS
3092 if (c->options.use_prediction_resistance)
3093 {
3094 rand_ctx_enable_prediction_resistance();
3095 }
0f25d296 3096#endif
6fbf66fa
JY
3097}
3098
3099/*
3100 * Static Key Mode (using a pre-shared key)
3101 */
3102static void
81d882d5 3103do_init_crypto_static(struct context *c, const unsigned int flags)
6fbf66fa 3104{
81d882d5
DS
3105 const struct options *options = &c->options;
3106 ASSERT(options->shared_secret_file);
6fbf66fa 3107
81d882d5 3108 init_crypto_pre(c, flags);
2d9c6d20 3109
81d882d5 3110 /* Initialize flags */
81d882d5 3111 if (c->options.mute_replay_warnings)
6fbf66fa 3112 {
81d882d5 3113 c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
6fbf66fa
JY
3114 }
3115
81d882d5 3116 /* Initialize packet ID tracking */
6d76218d
FL
3117 packet_id_init(&c->c2.crypto_options.packet_id,
3118 options->replay_window,
3119 options->replay_time,
3120 "STATIC", 0);
3121 c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
3122 c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
3123 packet_id_persist_load_obj(&c->c1.pid_persist,
3124 &c->c2.crypto_options.packet_id);
6fbf66fa 3125
81d882d5
DS
3126 if (!key_ctx_bi_defined(&c->c1.ks.static_key))
3127 {
3128 /* Get cipher & hash algorithms */
3129 init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
6ea62d50 3130 options->test_crypto, true);
81d882d5
DS
3131
3132 /* Read cipher and hmac keys from shared secret file */
3133 crypto_read_openvpn_key(&c->c1.ks.key_type, &c->c1.ks.static_key,
3134 options->shared_secret_file,
3135 options->shared_secret_file_inline,
3136 options->key_direction, "Static Key Encryption",
6a05768a 3137 "secret", NULL);
6fbf66fa 3138 }
81d882d5 3139 else
6fbf66fa 3140 {
81d882d5 3141 msg(M_INFO, "Re-using pre-shared static key");
6fbf66fa
JY
3142 }
3143
81d882d5
DS
3144 /* Get key schedule */
3145 c->c2.crypto_options.key_ctx_bi = c->c1.ks.static_key;
6fbf66fa
JY
3146}
3147
5817b49b
AQ
3148/*
3149 * Initialize the tls-auth/crypt key context
3150 */
3151static void
3152do_init_tls_wrap_key(struct context *c)
3153{
3154 const struct options *options = &c->options;
3155
3156 /* TLS handshake authentication (--tls-auth) */
57d6f103 3157 if (options->ce.tls_auth_file)
5817b49b
AQ
3158 {
3159 /* Initialize key_type for tls-auth with auth only */
3160 CLEAR(c->c1.ks.tls_auth_key_type);
b39725cf
AS
3161 c->c1.ks.tls_auth_key_type.cipher = "none";
3162 c->c1.ks.tls_auth_key_type.digest = options->authname;
3163 if (!md_valid(options->authname))
5817b49b
AQ
3164 {
3165 msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth "
3166 "algorithm specified ('%s')", options->authname);
3167 }
3168
3169 crypto_read_openvpn_key(&c->c1.ks.tls_auth_key_type,
3170 &c->c1.ks.tls_wrap_key,
57d6f103
AQ
3171 options->ce.tls_auth_file,
3172 options->ce.tls_auth_file_inline,
3173 options->ce.key_direction,
6a05768a
AS
3174 "Control Channel Authentication", "tls-auth",
3175 &c->c1.ks.original_wrap_keydata);
5817b49b
AQ
3176 }
3177
3178 /* TLS handshake encryption+authentication (--tls-crypt) */
57d6f103 3179 if (options->ce.tls_crypt_file)
5817b49b
AQ
3180 {
3181 tls_crypt_init_key(&c->c1.ks.tls_wrap_key,
6a05768a 3182 &c->c1.ks.original_wrap_keydata,
57d6f103 3183 options->ce.tls_crypt_file,
cb2e9218
AQ
3184 options->ce.tls_crypt_file_inline,
3185 options->tls_server);
5817b49b 3186 }
19d6d9c3
SK
3187
3188 /* tls-crypt with client-specific keys (--tls-crypt-v2) */
3189 if (options->ce.tls_crypt_v2_file)
3190 {
3191 if (options->tls_server)
3192 {
3193 tls_crypt_v2_init_server_key(&c->c1.ks.tls_crypt_v2_server_key,
3194 true, options->ce.tls_crypt_v2_file,
cb2e9218 3195 options->ce.tls_crypt_v2_file_inline);
19d6d9c3
SK
3196 }
3197 else
3198 {
3199 tls_crypt_v2_init_client_key(&c->c1.ks.tls_wrap_key,
6a05768a 3200 &c->c1.ks.original_wrap_keydata,
19d6d9c3
SK
3201 &c->c1.ks.tls_crypt_v2_wkc,
3202 options->ce.tls_crypt_v2_file,
cb2e9218 3203 options->ce.tls_crypt_v2_file_inline);
19d6d9c3 3204 }
5f6ea597
AS
3205 /* We have to ensure that the loaded tls-crypt key is small enough
3206 * to fit into the initial hard reset v3 packet */
3207 int wkc_len = buf_len(&c->c1.ks.tls_crypt_v2_wkc);
3208
3209 /* empty ACK/message id, tls-crypt, Opcode, UDP, ipv6 */
3210 int required_size = 5 + wkc_len + tls_crypt_buf_overhead() + 1 + 8 + 40;
3211
3212 if (required_size > c->options.ce.tls_mtu)
3213 {
3214 msg(M_WARN, "ERROR: tls-crypt-v2 client key too large to work with "
3215 "requested --max-packet-size %d, requires at least "
3216 "--max-packet-size %d. Packets will ignore requested "
3217 "maximum packet size", c->options.ce.tls_mtu,
3218 required_size);
3219 }
19d6d9c3
SK
3220 }
3221
3222
5817b49b
AQ
3223}
3224
6fbf66fa
JY
3225/*
3226 * Initialize the persistent component of OpenVPN's TLS mode,
3227 * which is preserved across SIGUSR1 resets.
3228 */
3229static void
81d882d5 3230do_init_crypto_tls_c1(struct context *c)
6fbf66fa 3231{
81d882d5 3232 const struct options *options = &c->options;
6fbf66fa 3233
81d882d5 3234 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
6fbf66fa 3235 {
81d882d5
DS
3236 /*
3237 * Initialize the OpenSSL library's global
3238 * SSL context.
3239 */
21a0b249 3240 init_ssl(options, &(c->c1.ks.ssl_ctx), c->c0 && c->c0->uid_gid_chroot_set);
81d882d5
DS
3241 if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
3242 {
81d882d5
DS
3243 switch (auth_retry_get())
3244 {
3245 case AR_NONE:
3246 msg(M_FATAL, "Error: private key password verification failed");
3247 break;
3248
3249 case AR_INTERACT:
3250 ssl_purge_auth(false);
f2454ec6 3251 /* Intentional [[fallthrough]]; */
81d882d5
DS
3252
3253 case AR_NOINTERACT:
05715485
SN
3254 /* SOFT-SIGUSR1 -- Password failure error */
3255 register_signal(c->sig, SIGUSR1, "private-key-password-failure");
81d882d5
DS
3256 break;
3257
3258 default:
3259 ASSERT(0);
3260 }
81d882d5 3261 return;
81d882d5
DS
3262 }
3263
abe49856
DS
3264 /*
3265 * BF-CBC is allowed to be used only when explicitly configured
3266 * as NCP-fallback or when NCP has been disabled or explicitly
3267 * allowed in the in ncp_ciphers list.
3268 * In all other cases do not attempt to initialize BF-CBC as it
3269 * may not even be supported by the underlying SSL library.
3270 *
3271 * Therefore, the key structure has to be initialized when:
3272 * - any non-BF-CBC cipher was selected; or
3273 * - BF-CBC is selected, NCP is enabled and fallback is enabled
3274 * (BF-CBC will be the fallback).
3275 * - BF-CBC is in data-ciphers and we negotiate to use BF-CBC:
3276 * If the negotiated cipher and options->ciphername are the
3277 * same we do not reinit the cipher
3278 *
3279 * Note that BF-CBC will still be part of the OCC string to retain
3280 * backwards compatibility with older clients.
3281 */
3282 const char *ciphername = options->ciphername;
ce2954a0
AS
3283 if (streq(options->ciphername, "BF-CBC")
3284 && !tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers)
3285 && !options->enable_ncp_fallback)
79ff3f79 3286 {
ce2954a0 3287 ciphername = "none";
79ff3f79 3288 }
81d882d5 3289
ce2954a0
AS
3290 /* Do not warn if the cipher is used only in OCC */
3291 bool warn = options->enable_ncp_fallback;
3292 init_key_type(&c->c1.ks.key_type, ciphername, options->authname,
3293 true, warn);
3294
19d6d9c3 3295 /* initialize tls-auth/crypt/crypt-v2 key */
5817b49b 3296 do_init_tls_wrap_key(c);
81d882d5 3297
1b9a88a2 3298 /* initialise auth-token crypto support */
6cf4fa5a
AS
3299 if (c->options.auth_token_generate)
3300 {
3301 auth_token_init_secret(&c->c1.ks.auth_token_key,
3302 c->options.auth_token_secret_file,
3303 c->options.auth_token_secret_file_inline);
3304 }
1b9a88a2 3305
1f4309ae 3306#if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
81d882d5
DS
3307 if (options->priv_key_file_inline)
3308 {
3309 string_clear(c->options.priv_key_file_inline);
3310 c->options.priv_key_file_inline = NULL;
3311 }
d40f2b20 3312#endif
6fbf66fa 3313 }
81d882d5 3314 else
6fbf66fa 3315 {
81d882d5 3316 msg(D_INIT_MEDIUM, "Re-using SSL/TLS context");
129d2924 3317
5817b49b
AQ
3318 /*
3319 * tls-auth/crypt key can be configured per connection block, therefore
3320 * we must reload it as it may have changed
3321 */
3322 do_init_tls_wrap_key(c);
6fbf66fa
JY
3323 }
3324}
3325
3326static void
81d882d5 3327do_init_crypto_tls(struct context *c, const unsigned int flags)
6fbf66fa 3328{
81d882d5
DS
3329 const struct options *options = &c->options;
3330 struct tls_options to;
3331 bool packet_id_long_form;
6fbf66fa 3332
81d882d5
DS
3333 ASSERT(options->tls_server || options->tls_client);
3334 ASSERT(!options->test_crypto);
6fbf66fa 3335
81d882d5 3336 init_crypto_pre(c, flags);
6fbf66fa 3337
81d882d5
DS
3338 /* Make sure we are either a TLS client or server but not both */
3339 ASSERT(options->tls_server == !options->tls_client);
6fbf66fa 3340
81d882d5
DS
3341 /* initialize persistent component */
3342 do_init_crypto_tls_c1(c);
3343 if (IS_SIG(c))
3344 {
3345 return;
3346 }
3347
81d882d5
DS
3348 /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
3349 packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher);
3350
81d882d5
DS
3351 /* Set all command-line TLS-related options */
3352 CLEAR(to);
3353
81d882d5
DS
3354 if (options->mute_replay_warnings)
3355 {
3356 to.crypto_flags |= CO_MUTE_REPLAY_WARNINGS;
3357 }
3358
3359 to.crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
3360 if (packet_id_long_form)
3361 {
3362 to.crypto_flags |= CO_PACKET_ID_LONG_FORM;
3363 }
3364
3365 to.ssl_ctx = c->c1.ks.ssl_ctx;
3366 to.key_type = c->c1.ks.key_type;
3367 to.server = options->tls_server;
81d882d5
DS
3368 to.replay_window = options->replay_window;
3369 to.replay_time = options->replay_time;
7064ccb9
AS
3370 to.config_ciphername = c->options.ciphername;
3371 to.config_ncp_ciphers = c->options.ncp_ciphers;
81d882d5
DS
3372 to.transition_window = options->transition_window;
3373 to.handshake_window = options->handshake_window;
3374 to.packet_timeout = options->tls_timeout;
3375 to.renegotiate_bytes = options->renegotiate_bytes;
3376 to.renegotiate_packets = options->renegotiate_packets;
dd996463
SM
3377 if (options->renegotiate_seconds_min < 0)
3378 {
3379 /* Add 10% jitter to reneg-sec by default (server side only) */
3380 int auto_jitter = options->mode != MODE_SERVER ? 0 :
f57431cd 3381 get_random() % max_int(options->renegotiate_seconds / 10, 1);
dd996463
SM
3382 to.renegotiate_seconds = options->renegotiate_seconds - auto_jitter;
3383 }
3384 else
3385 {
3386 /* Add user-specified jitter to reneg-sec */
f57431cd
GD
3387 to.renegotiate_seconds = options->renegotiate_seconds
3388 -(get_random() % max_int(options->renegotiate_seconds
3389 - options->renegotiate_seconds_min, 1));
dd996463 3390 }
81d882d5
DS
3391 to.single_session = options->single_session;
3392 to.mode = options->mode;
3393 to.pull = options->pull;
81d882d5
DS
3394 if (options->push_peer_info) /* all there is */
3395 {
8c72d798 3396 to.push_peer_info_detail = 3;
81d882d5
DS
3397 }
3398 else if (options->pull) /* pull clients send some details */
3399 {
8c72d798 3400 to.push_peer_info_detail = 2;
81d882d5 3401 }
8c72d798 3402 else if (options->mode == MODE_SERVER) /* server: no peer info at all */
81d882d5
DS
3403 {
3404 to.push_peer_info_detail = 0;
3405 }
8c72d798
AS
3406 else /* default: minimal info to allow NCP in P2P mode */
3407 {
3408 to.push_peer_info_detail = 1;
3409 }
3410
9f4670fc
AS
3411 /* Check if the DCO drivers support the epoch data format */
3412 if (dco_enabled(options))
3413 {
3414 to.data_epoch_supported = dco_supports_epoch_data(c);
3415 }
3416 else
3417 {
3418 to.data_epoch_supported = true;
3419 }
6fbf66fa 3420
81d882d5
DS
3421 /* should we not xmit any packets until we get an initial
3422 * response from client? */
619c3e9a 3423 if (to.server && c->mode == CM_CHILD_TCP)
81d882d5
DS
3424 {
3425 to.xmit_hold = true;
3426 }
6add6b2f 3427
81d882d5 3428 to.verify_command = options->tls_verify;
81d882d5
DS
3429 to.verify_x509_type = (options->verify_x509_type & 0xff);
3430 to.verify_x509_name = options->verify_x509_name;
3431 to.crl_file = options->crl_file;
3432 to.crl_file_inline = options->crl_file_inline;
3433 to.ssl_flags = options->ssl_flags;
3434 to.ns_cert_type = options->ns_cert_type;
3b04c34d 3435 memcpy(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku));
81d882d5
DS
3436 to.remote_cert_eku = options->remote_cert_eku;
3437 to.verify_hash = options->verify_hash;
2193d7c0 3438 to.verify_hash_algo = options->verify_hash_algo;
c3a7065d 3439 to.verify_hash_depth = options->verify_hash_depth;
c3746da7 3440 to.verify_hash_no_ca = options->verify_hash_no_ca;
19dd3ef1 3441#ifdef ENABLE_X509ALTUSERNAME
3b04c34d 3442 memcpy(to.x509_username_field, options->x509_username_field, sizeof(to.x509_username_field));
19dd3ef1 3443#else
3b04c34d 3444 to.x509_username_field[0] = X509_USERNAME_FIELD_DEFAULT;
19dd3ef1 3445#endif
81d882d5 3446 to.es = c->c2.es;
aec4a3d1 3447 to.net_ctx = &c->net_ctx;
6fbf66fa
JY
3448
3449#ifdef ENABLE_DEBUG
81d882d5 3450 to.gremlin = c->options.gremlin;
6fbf66fa
JY
3451#endif
3452
81d882d5 3453 to.plugins = c->plugins;
6fbf66fa 3454
99d217b2 3455#ifdef ENABLE_MANAGEMENT
81d882d5 3456 to.mda_context = &c->c2.mda_context;
90efcacb
JY
3457#endif
3458
81d882d5
DS
3459 to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
3460 to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
23eec2d2 3461 to.client_crresponse_script = options->client_crresponse_script;
81d882d5 3462 to.tmp_dir = options->tmp_dir;
c58c7c3c 3463 to.export_peer_cert_dir = options->tls_export_peer_cert_dir;
81d882d5
DS
3464 if (options->ccd_exclusive)
3465 {
3466 to.client_config_dir_exclusive = options->client_config_dir;
3467 }
3468 to.auth_user_pass_file = options->auth_user_pass_file;
7d48d31b 3469 to.auth_user_pass_file_inline = options->auth_user_pass_file_inline;
81d882d5
DS
3470 to.auth_token_generate = options->auth_token_generate;
3471 to.auth_token_lifetime = options->auth_token_lifetime;
9a516170 3472 to.auth_token_renewal = options->auth_token_renewal;
c8723aa7 3473 to.auth_token_call_auth = options->auth_token_call_auth;
1b9a88a2 3474 to.auth_token_key = c->c1.ks.auth_token_key;
6fbf66fa 3475
81d882d5 3476 to.x509_track = options->x509_track;
9356bae8 3477
66b9409b 3478#ifdef ENABLE_MANAGEMENT
81d882d5 3479 to.sci = &options->sc_info;
16d909e2 3480#endif
eab3e22f 3481
38d96bd7 3482#ifdef USE_COMP
81d882d5 3483 to.comp_options = options->comp;
38d96bd7
JY
3484#endif
3485
81d882d5 3486 if (options->keying_material_exporter_label)
685e486e 3487 {
81d882d5
DS
3488 to.ekm_size = options->keying_material_exporter_length;
3489 if (to.ekm_size < 16 || to.ekm_size > 4095)
3490 {
3491 to.ekm_size = 0;
3492 }
685e486e 3493
81d882d5
DS
3494 to.ekm_label = options->keying_material_exporter_label;
3495 to.ekm_label_size = strlen(to.ekm_label);
685e486e 3496 }
81d882d5 3497 else
685e486e 3498 {
81d882d5 3499 to.ekm_size = 0;
685e486e 3500 }
685e486e 3501
81d882d5 3502 /* TLS handshake authentication (--tls-auth) */
57d6f103 3503 if (options->ce.tls_auth_file)
6fbf66fa 3504 {
81d882d5 3505 to.tls_wrap.mode = TLS_WRAP_AUTH;
6fbf66fa
JY
3506 }
3507
81d882d5 3508 /* TLS handshake encryption (--tls-crypt) */
19dffdbd
SK
3509 if (options->ce.tls_crypt_file
3510 || (options->ce.tls_crypt_v2_file && options->tls_client))
c6e24fa3 3511 {
81d882d5 3512 to.tls_wrap.mode = TLS_WRAP_CRYPT;
6a05768a
AS
3513 }
3514
3515 if (to.tls_wrap.mode == TLS_WRAP_AUTH || to.tls_wrap.mode == TLS_WRAP_CRYPT)
3516 {
81d882d5
DS
3517 to.tls_wrap.opt.key_ctx_bi = c->c1.ks.tls_wrap_key;
3518 to.tls_wrap.opt.pid_persist = &c->c1.pid_persist;
3519 to.tls_wrap.opt.flags |= CO_PACKET_ID_LONG_FORM;
6a05768a 3520 to.tls_wrap.original_wrap_keydata = c->c1.ks.original_wrap_keydata;
19dffdbd
SK
3521 }
3522
19d6d9c3 3523 if (options->ce.tls_crypt_v2_file)
19dffdbd
SK
3524 {
3525 to.tls_crypt_v2 = true;
6a05768a
AS
3526 to.tls_wrap.tls_crypt_v2_wkc = &c->c1.ks.tls_crypt_v2_wkc;
3527
19dffdbd
SK
3528 if (options->tls_server)
3529 {
3530 to.tls_wrap.tls_crypt_v2_server_key = c->c1.ks.tls_crypt_v2_server_key;
ff931c5e 3531 to.tls_crypt_v2_verify_script = c->options.tls_crypt_v2_verify_script;
e7d8c4a7
AS
3532 if (options->ce.tls_crypt_v2_force_cookie)
3533 {
3534 to.tls_wrap.opt.flags |= CO_FORCE_TLSCRYPTV2_COOKIE;
3535 }
19dffdbd 3536 }
c6e24fa3
SK
3537 }
3538
a2d851d4
AQ
3539 /* let the TLS engine know if keys have to be installed in DCO or not */
3540 to.dco_enabled = dco_enabled(options);
3541
81d882d5
DS
3542 /*
3543 * Initialize OpenVPN's master TLS-mode object.
3544 */
3545 if (flags & CF_INIT_TLS_MULTI)
3546 {
3547 c->c2.tls_multi = tls_multi_init(&to);
a2d851d4
AQ
3548 /* inherit the dco context from the tuntap object */
3549 if (c->c1.tuntap)
3550 {
3551 c->c2.tls_multi->dco = &c->c1.tuntap->dco;
3552 }
81d882d5 3553 }
6fbf66fa 3554
81d882d5
DS
3555 if (flags & CF_INIT_TLS_AUTH_STANDALONE)
3556 {
3557 c->c2.tls_auth_standalone = tls_auth_standalone_init(&to, &c->c2.gc);
b3647114 3558 c->c2.session_id_hmac = session_id_hmac_init();
81d882d5 3559 }
6fbf66fa
JY
3560}
3561
3562static void
2b6fcdc0 3563do_init_frame_tls(struct context *c)
6fbf66fa 3564{
81d882d5 3565 if (c->c2.tls_multi)
6fbf66fa 3566 {
5f6ea597 3567 tls_multi_init_finalize(c->c2.tls_multi, c->options.ce.tls_mtu);
986559bf
AS
3568 ASSERT(c->c2.tls_multi->opt.frame.buf.payload_size <=
3569 c->c2.frame.buf.payload_size);
81d882d5
DS
3570 frame_print(&c->c2.tls_multi->opt.frame, D_MTU_INFO,
3571 "Control Channel MTU parms");
01aed6a5
AS
3572
3573 /* Keep the max mtu also in the frame of tls multi so it can access
3574 * it in push_peer_info */
3575 c->c2.tls_multi->opt.frame.tun_max_mtu = c->c2.frame.tun_max_mtu;
6fbf66fa 3576 }
81d882d5 3577 if (c->c2.tls_auth_standalone)
6fbf66fa 3578 {
5f6ea597 3579 tls_init_control_channel_frame_parameters(&c->c2.tls_auth_standalone->frame, c->options.ce.tls_mtu);
81d882d5
DS
3580 frame_print(&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
3581 "TLS-Auth MTU parms");
b3647114 3582 c->c2.tls_auth_standalone->tls_wrap.work = alloc_buf_gc(BUF_SIZE(&c->c2.frame), &c->c2.gc);
e8ecaadd 3583 c->c2.tls_auth_standalone->workbuf = alloc_buf_gc(BUF_SIZE(&c->c2.frame), &c->c2.gc);
6fbf66fa
JY
3584 }
3585}
3586
6fbf66fa
JY
3587/*
3588 * No encryption or authentication.
3589 */
3590static void
02d8f792 3591do_init_crypto_none(struct context *c)
6fbf66fa 3592{
81d882d5 3593 ASSERT(!c->options.test_crypto);
02d8f792
AS
3594
3595 /* Initialise key_type with auth/cipher "none", so the key_type struct is
3596 * valid */
3597 init_key_type(&c->c1.ks.key_type, "none", "none",
3598 c->options.test_crypto, true);
3599
81d882d5 3600 msg(M_WARN,
7a1b6a0d
DS
3601 "******* WARNING *******: All encryption and authentication features "
3602 "disabled -- All data will be tunnelled as clear text and will not be "
3603 "protected against man-in-the-middle changes. "
3604 "PLEASE DO RECONSIDER THIS CONFIGURATION!");
6fbf66fa 3605}
6fbf66fa
JY
3606
3607static void
81d882d5 3608do_init_crypto(struct context *c, const unsigned int flags)
6fbf66fa 3609{
81d882d5
DS
3610 if (c->options.shared_secret_file)
3611 {
3612 do_init_crypto_static(c, flags);
3613 }
3614 else if (c->options.tls_server || c->options.tls_client)
3615 {
3616 do_init_crypto_tls(c, flags);
3617 }
3618 else /* no encryption or authentication. */
3619 {
3620 do_init_crypto_none(c);
3621 }
6fbf66fa
JY
3622}
3623
3624static void
81d882d5 3625do_init_frame(struct context *c)
6fbf66fa 3626{
81d882d5
DS
3627 /*
3628 * Adjust frame size based on the --tun-mtu-extra parameter.
3629 */
3630 if (c->options.ce.tun_mtu_extra_defined)
3631 {
65c63086 3632 c->c2.frame.extra_tun += c->options.ce.tun_mtu_extra;
81d882d5
DS
3633 }
3634
81d882d5
DS
3635 /*
3636 * Fill in the blanks in the frame parameters structure,
3637 * make sure values are rational, etc.
3638 */
3639 frame_finalize_options(c, NULL);
6fbf66fa 3640
6fbf66fa 3641
ba66faad 3642#if defined(ENABLE_FRAGMENT)
81d882d5
DS
3643 /*
3644 * MTU advisories
3645 */
3646 if (c->options.ce.fragment && c->options.mtu_test)
3647 {
3648 msg(M_WARN,
3649 "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
3650 }
6fbf66fa
JY
3651#endif
3652
3653#ifdef ENABLE_FRAGMENT
f1e06301 3654 if (c->options.ce.fragment > 0 && c->options.ce.mssfix > c->options.ce.fragment)
81d882d5 3655 {
f1e06301 3656 msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should "
abe49856
DS
3657 "set --fragment (%d) larger or equal than --mssfix (%d)",
3658 c->options.ce.fragment, c->options.ce.mssfix);
f1e06301
AS
3659 }
3660 if (c->options.ce.fragment > 0 && c->options.ce.mssfix > 0
3661 && c->options.ce.fragment_encap != c->options.ce.mssfix_encap)
3662 {
3663 msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should "
abe49856 3664 "use the \"mtu\" flag for both or none of of them.");
81d882d5 3665 }
6fbf66fa
JY
3666#endif
3667}
3668
3669static void
81d882d5 3670do_option_warnings(struct context *c)
6fbf66fa 3671{
81d882d5 3672 const struct options *o = &c->options;
6fbf66fa 3673
81d882d5
DS
3674 if (o->ping_send_timeout && !o->ping_rec_timeout)
3675 {
3676 msg(M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
3677 }
6fbf66fa 3678
81d882d5 3679 if (o->username || o->groupname || o->chroot_dir
cd5990e0 3680#ifdef ENABLE_SELINUX
81d882d5 3681 || o->selinux_context
99385447 3682#endif
81d882d5
DS
3683 )
3684 {
3685 if (!o->persist_tun)
3686 {
3687 msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
3688 }
81d882d5 3689 }
6fbf66fa 3690
81d882d5
DS
3691 if (o->chroot_dir && !(o->username && o->groupname))
3692 {
3693 msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
3694 }
31f90e64 3695
81d882d5
DS
3696 if (o->pull && o->ifconfig_local && c->first_time)
3697 {
3698 msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
3699 }
6fbf66fa 3700
9d92221e 3701 if (o->server_bridge_defined || o->server_bridge_proxy_dhcp)
81d882d5
DS
3702 {
3703 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");
3704 }
f77c60d3 3705
81d882d5 3706 if (o->mode == MODE_SERVER)
6fbf66fa 3707 {
81d882d5
DS
3708 if (o->duplicate_cn && o->client_config_dir)
3709 {
3710 msg(M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
3711 }
3712 if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
3713 {
3714 msg(M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
3715 }
3716 if (!o->keepalive_ping || !o->keepalive_timeout)
3717 {
3718 msg(M_WARN, "WARNING: --keepalive option is missing from server config");
3719 }
6fbf66fa 3720 }
6fbf66fa 3721
81d882d5
DS
3722 if (o->tls_server)
3723 {
aec4a3d1 3724 warn_on_use_of_common_subnets(&c->net_ctx);
81d882d5
DS
3725 }
3726 if (o->tls_client
3727 && !o->tls_verify
3728 && o->verify_x509_type == VERIFY_X509_NONE
3729 && !(o->ns_cert_type & NS_CERT_CHECK_SERVER)
4b956565
AS
3730 && !o->remote_cert_eku
3731 && !(o->verify_hash_depth == 0 && o->verify_hash))
81d882d5
DS
3732 {
3733 msg(M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
3734 }
2dc33226
SK
3735 if (o->ns_cert_type)
3736 {
3737 msg(M_WARN, "WARNING: --ns-cert-type is DEPRECATED. Use --remote-cert-tls instead.");
3738 }
81d882d5 3739
ccb636c7 3740 /* If a script is used, print appropriate warnings */
81d882d5
DS
3741 if (o->user_script_used)
3742 {
bf97c00f 3743 if (script_security() >= SSEC_SCRIPTS)
81d882d5
DS
3744 {
3745 msg(M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
3746 }
bf97c00f 3747 else if (script_security() >= SSEC_PW_ENV)
81d882d5
DS
3748 {
3749 msg(M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
3750 }
3751 else
3752 {
3753 msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
3754 }
3755 }
6fbf66fa
JY
3756}
3757
6fbf66fa 3758struct context_buffers *
81d882d5 3759init_context_buffers(const struct frame *frame)
6fbf66fa 3760{
81d882d5 3761 struct context_buffers *b;
6fbf66fa 3762
81d882d5 3763 ALLOC_OBJ_CLEAR(b, struct context_buffers);
6fbf66fa 3764
65a21eb1
AS
3765 size_t buf_size = BUF_SIZE(frame);
3766
3767 b->read_link_buf = alloc_buf(buf_size);
3768 b->read_tun_buf = alloc_buf(buf_size);
6fbf66fa 3769
65a21eb1 3770 b->aux_buf = alloc_buf(buf_size);
6fbf66fa 3771
65a21eb1
AS
3772 b->encrypt_buf = alloc_buf(buf_size);
3773 b->decrypt_buf = alloc_buf(buf_size);
6fbf66fa 3774
38d96bd7 3775#ifdef USE_COMP
65a21eb1
AS
3776 b->compress_buf = alloc_buf(buf_size);
3777 b->decompress_buf = alloc_buf(buf_size);
6fbf66fa
JY
3778#endif
3779
81d882d5 3780 return b;
6fbf66fa
JY
3781}
3782
3783void
81d882d5 3784free_context_buffers(struct context_buffers *b)
6fbf66fa 3785{
81d882d5 3786 if (b)
6fbf66fa 3787 {
81d882d5
DS
3788 free_buf(&b->read_link_buf);
3789 free_buf(&b->read_tun_buf);
3790 free_buf(&b->aux_buf);
6fbf66fa 3791
38d96bd7 3792#ifdef USE_COMP
81d882d5
DS
3793 free_buf(&b->compress_buf);
3794 free_buf(&b->decompress_buf);
6fbf66fa
JY
3795#endif
3796
81d882d5
DS
3797 free_buf(&b->encrypt_buf);
3798 free_buf(&b->decrypt_buf);
6fbf66fa 3799
81d882d5 3800 free(b);
6fbf66fa
JY
3801 }
3802}
3803
3804/*
3805 * Now that we know all frame parameters, initialize
3806 * our buffers.
3807 */
3808static void
81d882d5 3809do_init_buffers(struct context *c)
6fbf66fa 3810{
81d882d5
DS
3811 c->c2.buffers = init_context_buffers(&c->c2.frame);
3812 c->c2.buffers_owned = true;
6fbf66fa
JY
3813}
3814
3815#ifdef ENABLE_FRAGMENT
3816/*
3817 * Fragmenting code has buffers to initialize
3818 * once frame parameters are known.
3819 */
3820static void
81d882d5 3821do_init_fragment(struct context *c)
6fbf66fa 3822{
81d882d5 3823 ASSERT(c->options.ce.fragment);
a3419142
AS
3824
3825 /*
3826 * Set frame parameter for fragment code. This is necessary because
3827 * the fragmentation code deals with payloads which have already been
3828 * passed through the compression code.
3829 */
3830 c->c2.frame_fragment = c->c2.frame;
3831
0d969976
AS
3832 frame_calculate_dynamic(&c->c2.frame_fragment, &c->c1.ks.key_type,
3833 &c->options, get_link_socket_info(c));
81d882d5 3834 fragment_frame_init(c->c2.fragment, &c->c2.frame_fragment);
6fbf66fa
JY
3835}
3836#endif
3837
6fbf66fa
JY
3838/*
3839 * Allocate our socket object.
3840 */
3841static void
81d882d5 3842do_link_socket_new(struct context *c)
6fbf66fa 3843{
94b391d7
AQ
3844 ASSERT(!c->c2.link_sockets);
3845
3846 ALLOC_ARRAY_GC(c->c2.link_sockets, struct link_socket *,
3847 c->c1.link_sockets_num, &c->c2.gc);
3848
3849 for (int i = 0; i < c->c1.link_sockets_num; i++)
3850 {
3851 c->c2.link_sockets[i] = link_socket_new();
3852 }
81d882d5 3853 c->c2.link_socket_owned = true;
6fbf66fa
JY
3854}
3855
94b391d7
AQ
3856/*
3857 * bind TCP/UDP sockets
3858 */
3859static void
3860do_init_socket_phase1(struct context *c)
3861{
3862 for (int i = 0; i < c->c1.link_sockets_num; i++)
3863 {
3864 int mode = LS_MODE_DEFAULT;
3865
3866 /* mode allows CM_CHILD_TCP
3867 * instances to inherit acceptable fds
3868 * from a top-level parent */
3869 if (c->options.mode == MODE_SERVER)
3870 {
3871 /* initializing listening socket */
3872 if (c->mode == CM_TOP)
3873 {
3874 mode = LS_MODE_TCP_LISTEN;
3875 }
3876 /* initializing socket to client */
3877 else if (c->mode == CM_CHILD_TCP)
3878 {
3879 mode = LS_MODE_TCP_ACCEPT_FROM;
3880 }
3881 }
3882
3883 /* init each socket with its specific args */
3884 link_socket_init_phase1(c, i, mode);
3885 }
3886}
3887
3888/*
3889 * finalize TCP/UDP sockets
3890 */
3891static void
3892do_init_socket_phase2(struct context *c)
3893{
3894 for (int i = 0; i < c->c1.link_sockets_num; i++)
3895 {
3896 link_socket_init_phase2(c, c->c2.link_sockets[i]);
3897 }
3898}
3899
6fbf66fa
JY
3900/*
3901 * Print MTU INFO
3902 */
3903static void
81d882d5 3904do_print_data_channel_mtu_parms(struct context *c)
6fbf66fa 3905{
81d882d5 3906 frame_print(&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
6fbf66fa 3907#ifdef ENABLE_FRAGMENT
81d882d5
DS
3908 if (c->c2.fragment)
3909 {
3910 frame_print(&c->c2.frame_fragment, D_MTU_INFO,
3911 "Fragmentation MTU parms");
3912 }
6fbf66fa
JY
3913#endif
3914}
3915
6fbf66fa
JY
3916/*
3917 * Get local and remote options compatibility strings.
3918 */
3919static void
81d882d5 3920do_compute_occ_strings(struct context *c)
6fbf66fa 3921{
81d882d5 3922 struct gc_arena gc = gc_new();
6fbf66fa 3923
81d882d5 3924 c->c2.options_string_local =
dc7fcd71
AQ
3925 options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3926 false, &gc);
81d882d5 3927 c->c2.options_string_remote =
dc7fcd71
AQ
3928 options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3929 true, &gc);
6fbf66fa 3930
81d882d5
DS
3931 msg(D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
3932 options_string_version(c->c2.options_string_local, &gc),
3933 c->c2.options_string_local);
3934 msg(D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
3935 options_string_version(c->c2.options_string_remote, &gc),
3936 c->c2.options_string_remote);
6fbf66fa 3937
81d882d5
DS
3938 if (c->c2.tls_multi)
3939 {
3940 tls_multi_init_set_options(c->c2.tls_multi,
3941 c->c2.options_string_local,
3942 c->c2.options_string_remote);
3943 }
6fbf66fa 3944
81d882d5 3945 gc_free(&gc);
6fbf66fa 3946}
6fbf66fa
JY
3947
3948/*
3949 * These things can only be executed once per program instantiation.
3950 * Set up for possible UID/GID downgrade, but don't do it yet.
3951 * Daemonize if requested.
3952 */
3953static void
81d882d5 3954do_init_first_time(struct context *c)
6fbf66fa 3955{
81d882d5 3956 if (c->first_time && !c->c0)
6fbf66fa 3957 {
81d882d5 3958 struct context_0 *c0;
92bbb061 3959
81d882d5
DS
3960 ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc);
3961 c0 = c->c0;
6fbf66fa 3962
66f6a3b7
AS
3963 /* get user and/or group that we want to setuid/setgid to,
3964 * sets also platform_x_state */
3965 bool group_defined = platform_group_get(c->options.groupname,
3966 &c0->platform_state_group);
3967 bool user_defined = platform_user_get(c->options.username,
3968 &c0->platform_state_user);
3969
3970 c0->uid_gid_specified = user_defined || group_defined;
6fbf66fa 3971
1dfe8729
HH
3972 /* fork the dns script runner to preserve root? */
3973 c->persist.duri.required = user_defined;
3974
81d882d5
DS
3975 /* perform postponed chdir if --daemon */
3976 if (c->did_we_daemonize && c->options.cd_dir == NULL)
3977 {
3978 platform_chdir("/");
3979 }
3980
3981 /* should we change scheduling priority? */
3982 platform_nice(c->options.nice);
6fbf66fa
JY
3983 }
3984}
3985
6fbf66fa
JY
3986/*
3987 * free buffers
3988 */
3989static void
81d882d5 3990do_close_free_buf(struct context *c)
6fbf66fa 3991{
81d882d5 3992 if (c->c2.buffers_owned)
6fbf66fa 3993 {
81d882d5
DS
3994 free_context_buffers(c->c2.buffers);
3995 c->c2.buffers = NULL;
3996 c->c2.buffers_owned = false;
6fbf66fa
JY
3997 }
3998}
3999
4000/*
4001 * close TLS
4002 */
4003static void
81d882d5 4004do_close_tls(struct context *c)
6fbf66fa 4005{
81d882d5 4006 if (c->c2.tls_multi)
6fbf66fa 4007 {
81d882d5
DS
4008 tls_multi_free(c->c2.tls_multi, true);
4009 c->c2.tls_multi = NULL;
6fbf66fa
JY
4010 }
4011
81d882d5 4012 /* free options compatibility strings */
cb70cf51
AS
4013 free(c->c2.options_string_local);
4014 free(c->c2.options_string_remote);
4015
81d882d5 4016 c->c2.options_string_local = c->c2.options_string_remote = NULL;
07036fd3
SK
4017
4018 if (c->c2.pulled_options_state)
4019 {
4020 md_ctx_cleanup(c->c2.pulled_options_state);
4021 md_ctx_free(c->c2.pulled_options_state);
4022 }
e8ecaadd
AS
4023
4024 tls_auth_standalone_free(c->c2.tls_auth_standalone);
6fbf66fa
JY
4025}
4026
4027/*
4028 * Free key schedules
4029 */
4030static void
81d882d5 4031do_close_free_key_schedule(struct context *c, bool free_ssl_ctx)
6fbf66fa 4032{
5817b49b 4033 /*
802fcce5 4034 * always free the tls_auth/crypt key. The key will
5817b49b
AQ
4035 * be reloaded from memory (pre-cached)
4036 */
fb169c3b 4037 free_key_ctx(&c->c1.ks.tls_crypt_v2_server_key);
5817b49b
AQ
4038 free_key_ctx_bi(&c->c1.ks.tls_wrap_key);
4039 CLEAR(c->c1.ks.tls_wrap_key);
19dffdbd
SK
4040 buf_clear(&c->c1.ks.tls_crypt_v2_wkc);
4041 free_buf(&c->c1.ks.tls_crypt_v2_wkc);
5817b49b 4042
802fcce5 4043 if (!(c->sig->signal_received == SIGUSR1))
81d882d5
DS
4044 {
4045 key_schedule_free(&c->c1.ks, free_ssl_ctx);
4046 }
6fbf66fa
JY
4047}
4048
4049/*
4050 * Close TCP/UDP connection
4051 */
4052static void
81d882d5 4053do_close_link_socket(struct context *c)
6fbf66fa 4054{
94b391d7 4055 if (c->c2.link_sockets && c->c2.link_socket_owned)
6fbf66fa 4056 {
94b391d7
AQ
4057 for (int i = 0; i < c->c1.link_sockets_num; i++)
4058 {
1452625b
LS
4059 /* in dco-win case, link socket is a tun handle which is
4060 * closed in do_close_tun(). Set it to UNDEFINED so
4061 * we won't use WinSock API to close it. */
4062 if (tuntap_is_dco_win(c->c1.tuntap))
4063 {
4064 c->c2.link_sockets[i]->sd = SOCKET_UNDEFINED;
4065 }
4066
94b391d7
AQ
4067 link_socket_close(c->c2.link_sockets[i]);
4068 }
4069 c->c2.link_sockets = NULL;
6fbf66fa
JY
4070 }
4071
81d882d5
DS
4072
4073 /* Preserve the resolved list of remote if the user request to or if we want
4074 * reconnect to the same host again or there are still addresses that need
4075 * to be tried */
4076 if (!(c->sig->signal_received == SIGUSR1
4077 && ( (c->options.persist_remote_ip)
4078 ||
4079 ( c->sig->source != SIG_SOURCE_HARD
94b391d7
AQ
4080 && ((c->c1.link_socket_addrs[0].current_remote
4081 && c->c1.link_socket_addrs[0].current_remote->ai_next)
81d882d5
DS
4082 || c->options.no_advance))
4083 )))
23d61c56 4084 {
94b391d7
AQ
4085 clear_remote_addrlist(&c->c1.link_socket_addrs[0],
4086 !c->options.resolve_in_advance);
23d61c56
AS
4087 }
4088
4089 /* Clear the remote actual address when persist_remote_ip is not in use */
4090 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
81d882d5 4091 {
94b391d7
AQ
4092 for (int i = 0; i < c->c1.link_sockets_num; i++)
4093 {
4094 CLEAR(c->c1.link_socket_addrs[i].actual);
4095 }
81d882d5 4096 }
6fbf66fa 4097
81d882d5
DS
4098 if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
4099 {
94b391d7 4100 for (int i = 0; i < c->c1.link_sockets_num; i++)
81d882d5 4101 {
94b391d7
AQ
4102 if (c->c1.link_socket_addrs[i].bind_local
4103 && !c->options.resolve_in_advance)
4104 {
4105 freeaddrinfo(c->c1.link_socket_addrs[i].bind_local);
4106 }
e719a053 4107
94b391d7
AQ
4108 c->c1.link_socket_addrs[i].bind_local = NULL;
4109 }
81d882d5 4110 }
6fbf66fa
JY
4111}
4112
4113/*
ccb636c7 4114 * Close packet-id persistence file
6fbf66fa
JY
4115 */
4116static void
81d882d5 4117do_close_packet_id(struct context *c)
6fbf66fa 4118{
81d882d5
DS
4119 packet_id_free(&c->c2.crypto_options.packet_id);
4120 packet_id_persist_save(&c->c1.pid_persist);
4121 if (!(c->sig->signal_received == SIGUSR1))
4122 {
4123 packet_id_persist_close(&c->c1.pid_persist);
4124 }
6fbf66fa
JY
4125}
4126
4127#ifdef ENABLE_FRAGMENT
4128/*
4129 * Close fragmentation handler.
4130 */
4131static void
81d882d5 4132do_close_fragment(struct context *c)
6fbf66fa 4133{
81d882d5 4134 if (c->c2.fragment)
6fbf66fa 4135 {
81d882d5
DS
4136 fragment_free(c->c2.fragment);
4137 c->c2.fragment = NULL;
6fbf66fa
JY
4138 }
4139}
4140#endif
4141
4142/*
4143 * Open and close our event objects.
4144 */
4145
4146static void
81d882d5
DS
4147do_event_set_init(struct context *c,
4148 bool need_us_timeout)
6fbf66fa 4149{
81d882d5 4150 unsigned int flags = 0;
6fbf66fa 4151
81d882d5 4152 c->c2.event_set_max = BASE_N_EVENTS;
6fbf66fa 4153
81d882d5 4154 flags |= EVENT_METHOD_FAST;
6fbf66fa 4155
81d882d5
DS
4156 if (need_us_timeout)
4157 {
4158 flags |= EVENT_METHOD_US_TIMEOUT;
4159 }
6fbf66fa 4160
81d882d5
DS
4161 c->c2.event_set = event_set_init(&c->c2.event_set_max, flags);
4162 c->c2.event_set_owned = true;
6fbf66fa
JY
4163}
4164
4165static void
81d882d5 4166do_close_event_set(struct context *c)
6fbf66fa 4167{
81d882d5 4168 if (c->c2.event_set && c->c2.event_set_owned)
6fbf66fa 4169 {
81d882d5
DS
4170 event_free(c->c2.event_set);
4171 c->c2.event_set = NULL;
4172 c->c2.event_set_owned = false;
6fbf66fa
JY
4173 }
4174}
4175
4176/*
4177 * Open and close --status file
4178 */
4179
4180static void
81d882d5 4181do_open_status_output(struct context *c)
6fbf66fa 4182{
81d882d5 4183 if (!c->c1.status_output)
6fbf66fa 4184 {
81d882d5
DS
4185 c->c1.status_output = status_open(c->options.status_file,
4186 c->options.status_file_update_freq,
4187 -1,
4188 NULL,
4189 STATUS_OUTPUT_WRITE);
4190 c->c1.status_output_owned = true;
6fbf66fa
JY
4191 }
4192}
4193
4194static void
81d882d5 4195do_close_status_output(struct context *c)
6fbf66fa 4196{
81d882d5 4197 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 4198 {
81d882d5
DS
4199 if (c->c1.status_output_owned && c->c1.status_output)
4200 {
4201 status_close(c->c1.status_output);
4202 c->c1.status_output = NULL;
4203 c->c1.status_output_owned = false;
4204 }
6fbf66fa
JY
4205 }
4206}
4207
4208/*
ccb636c7 4209 * Handle ifconfig-pool persistence object.
6fbf66fa
JY
4210 */
4211static void
81d882d5 4212do_open_ifconfig_pool_persist(struct context *c)
6fbf66fa 4213{
81d882d5 4214 if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
6fbf66fa 4215 {
81d882d5
DS
4216 c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init(c->options.ifconfig_pool_persist_filename,
4217 c->options.ifconfig_pool_persist_refresh_freq);
4218 c->c1.ifconfig_pool_persist_owned = true;
6fbf66fa 4219 }
6fbf66fa
JY
4220}
4221
4222static void
81d882d5 4223do_close_ifconfig_pool_persist(struct context *c)
6fbf66fa 4224{
81d882d5 4225 if (!(c->sig->signal_received == SIGUSR1))
6fbf66fa 4226 {
81d882d5
DS
4227 if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
4228 {
4229 ifconfig_pool_persist_close(c->c1.ifconfig_pool_persist);
4230 c->c1.ifconfig_pool_persist = NULL;
4231 c->c1.ifconfig_pool_persist_owned = false;
4232 }
6fbf66fa 4233 }
6fbf66fa
JY
4234}
4235
4236/*
4237 * Inherit environmental variables
4238 */
4239
4240static void
81d882d5 4241do_inherit_env(struct context *c, const struct env_set *src)
6fbf66fa 4242{
81d882d5
DS
4243 c->c2.es = env_set_create(NULL);
4244 c->c2.es_owned = true;
4245 env_set_inherit(c->c2.es, src);
6fbf66fa
JY
4246}
4247
2a64816b 4248static void
81d882d5 4249do_env_set_destroy(struct context *c)
2a64816b 4250{
81d882d5 4251 if (c->c2.es && c->c2.es_owned)
2a64816b 4252 {
81d882d5
DS
4253 env_set_destroy(c->c2.es);
4254 c->c2.es = NULL;
4255 c->c2.es_owned = false;
2a64816b
JY
4256 }
4257}
4258
6fbf66fa
JY
4259/*
4260 * Fast I/O setup. Fast I/O is an optimization which only works
4261 * if all of the following are true:
4262 *
4263 * (1) The platform is not Windows
4264 * (2) --proto udp is enabled
4265 * (3) --shaper is disabled
4266 */
4267static void
81d882d5 4268do_setup_fast_io(struct context *c)
6fbf66fa 4269{
81d882d5 4270 if (c->options.fast_io)
6fbf66fa 4271 {
445b192a 4272#ifdef _WIN32
81d882d5 4273 msg(M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
6fbf66fa 4274#else
619c3e9a 4275 if (c->options.shaper)
81d882d5 4276 {
619c3e9a 4277 msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
81d882d5
DS
4278 }
4279 else
4280 {
619c3e9a 4281 c->c2.fast_io = true;
81d882d5 4282 }
6fbf66fa
JY
4283#endif
4284 }
4285}
4286
4287static void
81d882d5 4288do_signal_on_tls_errors(struct context *c)
6fbf66fa 4289{
81d882d5
DS
4290 if (c->options.tls_exit)
4291 {
4292 c->c2.tls_exit_signal = SIGTERM;
4293 }
4294 else
4295 {
4296 c->c2.tls_exit_signal = SIGUSR1;
4297 }
6fbf66fa
JY
4298}
4299
3c7f2f55 4300#ifdef ENABLE_PLUGIN
6fbf66fa 4301
3c7f2f55 4302void
81d882d5 4303init_plugins(struct context *c)
6fbf66fa 4304{
81d882d5 4305 if (c->options.plugin_list && !c->plugins)
e1791bb1 4306 {
81d882d5
DS
4307 c->plugins = plugin_list_init(c->options.plugin_list);
4308 c->plugins_owned = true;
e1791bb1
JY
4309 }
4310}
4311
4312void
81d882d5
DS
4313open_plugins(struct context *c, const bool import_options, int init_point)
4314{
4315 if (c->plugins && c->plugins_owned)
4316 {
4317 if (import_options)
4318 {
4319 struct plugin_return pr, config;
4320 plugin_return_init(&pr);
4321 plugin_list_open(c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
4322 plugin_return_get_column(&pr, &config, "config");
4323 if (plugin_return_defined(&config))
4324 {
4325 int i;
4326 for (i = 0; i < config.n; ++i)
4327 {
4328 unsigned int option_types_found = 0;
4329 if (config.list[i] && config.list[i]->value)
4330 {
4331 options_string_import(&c->options,
4332 config.list[i]->value,
4333 D_IMPORT_ERRORS|M_OPTERR,
4334 OPT_P_DEFAULT & ~OPT_P_PLUGIN,
4335 &option_types_found,
4336 c->es);
4337 }
4338 }
4339 }
4340 plugin_return_free(&pr);
4341 }
4342 else
4343 {
4344 plugin_list_open(c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
4345 }
6fbf66fa 4346 }
6fbf66fa
JY
4347}
4348
4349static void
81d882d5 4350do_close_plugins(struct context *c)
6fbf66fa 4351{
81d882d5 4352 if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
6fbf66fa 4353 {
81d882d5
DS
4354 plugin_list_close(c->plugins);
4355 c->plugins = NULL;
4356 c->plugins_owned = false;
6fbf66fa 4357 }
6fbf66fa
JY
4358}
4359
3c7f2f55 4360static void
81d882d5 4361do_inherit_plugins(struct context *c, const struct context *src)
3c7f2f55 4362{
81d882d5 4363 if (!c->plugins && src->plugins)
3c7f2f55 4364 {
81d882d5
DS
4365 c->plugins = plugin_list_inherit(src->plugins);
4366 c->plugins_owned = true;
3c7f2f55
JY
4367 }
4368}
4369
81d882d5 4370#endif /* ifdef ENABLE_PLUGIN */
3c7f2f55 4371
6fbf66fa
JY
4372#ifdef ENABLE_MANAGEMENT
4373
4374static void
81d882d5 4375management_callback_status_p2p(void *arg, const int version, struct status_output *so)
6fbf66fa 4376{
81d882d5
DS
4377 struct context *c = (struct context *) arg;
4378 print_status(c, so);
6fbf66fa
JY
4379}
4380
4381void
81d882d5 4382management_show_net_callback(void *arg, const int msglevel)
6fbf66fa 4383{
445b192a 4384#ifdef _WIN32
81d882d5
DS
4385 show_routes(msglevel);
4386 show_adapters(msglevel);
4387 msg(msglevel, "END");
6fbf66fa 4388#else
81d882d5 4389 msg(msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
6fbf66fa
JY
4390#endif
4391}
4392
30003978
AS
4393#ifdef TARGET_ANDROID
4394int
81d882d5 4395management_callback_network_change(void *arg, bool samenetwork)
30003978
AS
4396{
4397 /* Check if the client should translate the network change to a SIGUSR1 to
81d882d5
DS
4398 * reestablish the connection or just reprotect the socket
4399 *
4400 * At the moment just assume that, for all settings that use pull (not
4401 * --static) and are not using peer-id reestablishing the connection is
4402 * required (unless the network is the same)
4403 *
4404 * The function returns -1 on invalid fd and -2 if the socket cannot be
4405 * reused. On the -2 return value the man_network_change function triggers
4406 * a SIGUSR1 to force a reconnect.
4407 */
4408
4409 int socketfd = -1;
4410 struct context *c = (struct context *) arg;
3ddfe26e 4411 if (!c->c2.link_sockets || !c->c2.link_sockets[0])
81d882d5
DS
4412 {
4413 return -1;
4414 }
3ddfe26e 4415 if (c->c2.link_sockets[0]->sd == SOCKET_UNDEFINED)
81d882d5
DS
4416 {
4417 return -1;
4418 }
30003978 4419
43abb412
AS
4420 /* On some newer Android handsets, changing to a different network
4421 * often does not trigger a TCP reset but continue using the old
4422 * connection (e.g. using mobile connection when WiFi becomes available */
4423 struct link_socket_info *lsi = get_link_socket_info(c);
4424 if (lsi && proto_is_tcp(lsi->proto) && !samenetwork)
4425 {
4426 return -2;
4427 }
4428
3ddfe26e 4429 socketfd = c->c2.link_sockets[0]->sd;
81d882d5
DS
4430 if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
4431 {
4432 return socketfd;
4433 }
4434 else
4435 {
4436 return -2;
4437 }
30003978 4438}
81d882d5 4439#endif /* ifdef TARGET_ANDROID */
30003978 4440
81d882d5 4441#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
4442
4443void
81d882d5 4444init_management_callback_p2p(struct context *c)
6fbf66fa
JY
4445{
4446#ifdef ENABLE_MANAGEMENT
81d882d5
DS
4447 if (management)
4448 {
4449 struct management_callback cb;
4450 CLEAR(cb);
4451 cb.arg = c;
4452 cb.status = management_callback_status_p2p;
4453 cb.show_net = management_show_net_callback;
4454 cb.proxy_cmd = management_callback_proxy_cmd;
4455 cb.remote_cmd = management_callback_remote_cmd;
adb9bb91 4456 cb.send_cc_message = management_callback_send_cc_message;
30003978 4457#ifdef TARGET_ANDROID
81d882d5 4458 cb.network_change = management_callback_network_change;
30003978 4459#endif
12526380
SN
4460 cb.remote_entry_count = management_callback_remote_entry_count;
4461 cb.remote_entry_get = management_callback_remote_entry_get;
81d882d5 4462 management_set_callback(management, &cb);
6fbf66fa
JY
4463 }
4464#endif
4465}
4466
4467#ifdef ENABLE_MANAGEMENT
4468
4469void
91ba1add 4470init_management(void)
6fbf66fa 4471{
81d882d5
DS
4472 if (!management)
4473 {
4474 management = management_init();
4475 }
6fbf66fa
JY
4476}
4477
4478bool
81d882d5
DS
4479open_management(struct context *c)
4480{
4481 /* initialize management layer */
4482 if (management)
4483 {
4484 if (c->options.management_addr)
4485 {
4486 unsigned int flags = c->options.management_flags;
4487 if (c->options.mode == MODE_SERVER)
4488 {
4489 flags |= MF_SERVER;
4490 }
4491 if (management_open(management,
4492 c->options.management_addr,
4493 c->options.management_port,
4494 c->options.management_user_pass,
4495 c->options.management_client_user,
4496 c->options.management_client_group,
4497 c->options.management_log_history_cache,
4498 c->options.management_echo_buffer_size,
4499 c->options.management_state_buffer_size,
81d882d5
DS
4500 c->options.remap_sigusr1,
4501 flags))
4502 {
4503 management_set_state(management,
4504 OPENVPN_STATE_CONNECTING,
4505 NULL,
4506 NULL,
4507 NULL,
4508 NULL,
4509 NULL);
4510 }
4511
4512 /* initial management hold, called early, before first context initialization */
4513 do_hold(0);
4514 if (IS_SIG(c))
4515 {
4516 msg(M_WARN, "Signal received from management interface, exiting");
4517 return false;
4518 }
4519 }
4520 else
4521 {
4522 close_management();
4523 }
4524 }
4525 return true;
6fbf66fa
JY
4526}
4527
4528void
81d882d5 4529close_management(void)
6fbf66fa 4530{
81d882d5 4531 if (management)
6fbf66fa 4532 {
81d882d5
DS
4533 management_close(management);
4534 management = NULL;
6fbf66fa
JY
4535 }
4536}
4537
81d882d5 4538#endif /* ifdef ENABLE_MANAGEMENT */
6fbf66fa
JY
4539
4540
4541void
81d882d5 4542uninit_management_callback(void)
6fbf66fa
JY
4543{
4544#ifdef ENABLE_MANAGEMENT
81d882d5 4545 if (management)
6fbf66fa 4546 {
81d882d5 4547 management_clear_callback(management);
6fbf66fa
JY
4548 }
4549#endif
4550}
4551
0fdbb288
SN
4552void
4553persist_client_stats(struct context *c)
4554{
4555#ifdef ENABLE_MANAGEMENT
4556 if (management)
4557 {
4558 man_persist_client_stats(management, c);
4559 }
4560#endif
4561}
4562
6fbf66fa
JY
4563/*
4564 * Initialize a tunnel instance, handle pre and post-init
4565 * signal settings.
4566 */
4567void
81d882d5 4568init_instance_handle_signals(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 4569{
81d882d5
DS
4570 pre_init_signal_catch();
4571 init_instance(c, env, flags);
4572 post_init_signal_catch();
4573
4574 /*
4575 * This is done so that signals thrown during
4576 * initialization can bring us back to
4577 * a management hold.
4578 */
4579 if (IS_SIG(c))
d5badcf1 4580 {
81d882d5
DS
4581 remap_signal(c);
4582 uninit_management_callback();
d5badcf1 4583 }
6fbf66fa
JY
4584}
4585
4586/*
4587 * Initialize a tunnel instance.
4588 */
4589void
81d882d5 4590init_instance(struct context *c, const struct env_set *env, const unsigned int flags)
6fbf66fa 4591{
81d882d5
DS
4592 const struct options *options = &c->options;
4593 const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
6fbf66fa 4594
81d882d5
DS
4595 /* init garbage collection level */
4596 gc_init(&c->c2.gc);
6fbf66fa 4597
81d882d5
DS
4598 /* inherit environmental variables */
4599 if (env)
4600 {
4601 do_inherit_env(c, env);
4602 }
ac1c2f25 4603
81d882d5
DS
4604 if (c->mode == CM_P2P)
4605 {
4606 init_management_callback_p2p(c);
4607 }
3cf6c932 4608
81d882d5
DS
4609 /* possible sleep or management hold if restart */
4610 if (c->mode == CM_P2P || c->mode == CM_TOP)
3cf6c932 4611 {
81d882d5
DS
4612 do_startup_pause(c);
4613 if (IS_SIG(c))
4614 {
4615 goto sig;
4616 }
3cf6c932
JY
4617 }
4618
81d882d5 4619 if (c->options.resolve_in_advance)
e719a053 4620 {
81d882d5
DS
4621 do_preresolve(c);
4622 if (IS_SIG(c))
4623 {
4624 goto sig;
4625 }
e719a053
AS
4626 }
4627
c1150e5b
AS
4628 /* Resets all values to the initial values from the config where needed */
4629 pre_connect_restore(&c->options, &c->c2.gc);
528a78fb 4630
81d882d5
DS
4631 /* map in current connection entry */
4632 next_connection_entry(c);
4e9a51d7 4633
81d882d5
DS
4634 /* should we disable paging? */
4635 if (c->first_time && options->mlock)
4636 {
4637 platform_mlockall(true);
4638 }
6fbf66fa 4639
81d882d5
DS
4640 /* get passwords if undefined */
4641 if (auth_retry_get() == AR_INTERACT)
4642 {
4643 init_query_passwords(c);
4644 }
92bbb061 4645
81d882d5
DS
4646 /* initialize context level 2 --verb/--mute parms */
4647 init_verb_mute(c, IVM_LEVEL_2);
4648
4649 /* set error message delay for non-server modes */
4650 if (c->mode == CM_P2P)
4651 {
4652 set_check_status_error_delay(P2P_ERROR_DELAY_MS);
4653 }
6fbf66fa 4654
81d882d5
DS
4655 /* warn about inconsistent options */
4656 if (c->mode == CM_P2P || c->mode == CM_TOP)
4657 {
4658 do_option_warnings(c);
4659 }
6fbf66fa 4660
3c7f2f55 4661#ifdef ENABLE_PLUGIN
81d882d5
DS
4662 /* initialize plugins */
4663 if (c->mode == CM_P2P || c->mode == CM_TOP)
4664 {
4665 open_plugins(c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
4666 }
3c7f2f55 4667#endif
6fbf66fa 4668
81d882d5
DS
4669 /* should we enable fast I/O? */
4670 if (c->mode == CM_P2P || c->mode == CM_TOP)
4671 {
4672 do_setup_fast_io(c);
4673 }
6fbf66fa 4674
81d882d5
DS
4675 /* should we throw a signal on TLS errors? */
4676 do_signal_on_tls_errors(c);
6fbf66fa 4677
81d882d5
DS
4678 /* open --status file */
4679 if (c->mode == CM_P2P || c->mode == CM_TOP)
4680 {
4681 do_open_status_output(c);
4682 }
6fbf66fa 4683
81d882d5
DS
4684 /* open --ifconfig-pool-persist file */
4685 if (c->mode == CM_TOP)
4686 {
4687 do_open_ifconfig_pool_persist(c);
4688 }
6fbf66fa 4689
81d882d5
DS
4690 /* reset OCC state */
4691 if (c->mode == CM_P2P || child)
4692 {
4693 c->c2.occ_op = occ_reset_op();
4694 }
6fbf66fa 4695
81d882d5 4696 /* our wait-for-i/o objects, different for posix vs. win32 */
619c3e9a 4697 if (c->mode == CM_P2P || c->mode == CM_TOP)
81d882d5
DS
4698 {
4699 do_event_set_init(c, SHAPER_DEFINED(&c->options));
4700 }
4701 else if (c->mode == CM_CHILD_TCP)
4702 {
4703 do_event_set_init(c, false);
4704 }
6fbf66fa 4705
81d882d5
DS
4706 /* initialize HTTP or SOCKS proxy object at scope level 2 */
4707 init_proxy(c);
4e9a51d7 4708
81d882d5
DS
4709 /* allocate our socket object */
4710 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4711 {
4712 do_link_socket_new(c);
4713 }
6fbf66fa
JY
4714
4715#ifdef ENABLE_FRAGMENT
81d882d5
DS
4716 /* initialize internal fragmentation object */
4717 if (options->ce.fragment && (c->mode == CM_P2P || child))
4718 {
4719 c->c2.fragment = fragment_init(&c->c2.frame);
4720 }
6fbf66fa
JY
4721#endif
4722
81d882d5
DS
4723 /* init crypto layer */
4724 {
4725 unsigned int crypto_flags = 0;
4726 if (c->mode == CM_TOP)
4727 {
4728 crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
4729 }
4730 else if (c->mode == CM_P2P)
4731 {
4732 crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
4733 }
4734 else if (child)
4735 {
4736 crypto_flags = CF_INIT_TLS_MULTI;
4737 }
4738 do_init_crypto(c, crypto_flags);
4739 if (IS_SIG(c) && !child)
4740 {
4741 goto sig;
4742 }
4743 }
6fbf66fa 4744
38d96bd7 4745#ifdef USE_COMP
81d882d5
DS
4746 /* initialize compression library. */
4747 if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
4748 {
4749 c->c2.comp_context = comp_init(&options->comp);
4750 }
6fbf66fa
JY
4751#endif
4752
81d882d5
DS
4753 /* initialize MTU variables */
4754 do_init_frame(c);
6fbf66fa 4755
81d882d5
DS
4756 /* initialize TLS MTU variables */
4757 do_init_frame_tls(c);
6fbf66fa 4758
81d882d5
DS
4759 /* init workspace buffers whose size is derived from frame size */
4760 if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
4761 {
4762 do_init_buffers(c);
4763 }
6fbf66fa
JY
4764
4765#ifdef ENABLE_FRAGMENT
81d882d5
DS
4766 /* initialize internal fragmentation capability with known frame size */
4767 if (options->ce.fragment && (c->mode == CM_P2P || child))
4768 {
4769 do_init_fragment(c);
4770 }
6fbf66fa
JY
4771#endif
4772
81d882d5
DS
4773 /* bind the TCP/UDP socket */
4774 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4775 {
94b391d7 4776 do_init_socket_phase1(c);
81d882d5 4777 }
6fbf66fa 4778
81d882d5
DS
4779 /* initialize tun/tap device object,
4780 * open tun/tap device, ifconfig, run up script, etc. */
4781 if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
4782 {
e04c2536
SN
4783 int error_flags = 0;
4784 c->c2.did_open_tun = do_open_tun(c, &error_flags);
81d882d5 4785 }
6fbf66fa 4786
81d882d5
DS
4787 /* print MTU info */
4788 do_print_data_channel_mtu_parms(c);
6fbf66fa 4789
81d882d5
DS
4790 /* get local and remote options compatibility strings */
4791 if (c->mode == CM_P2P || child)
4792 {
4793 do_compute_occ_strings(c);
4794 }
6fbf66fa 4795
81d882d5
DS
4796 /* initialize output speed limiter */
4797 if (c->mode == CM_P2P)
4798 {
4799 do_init_traffic_shaper(c);
4800 }
6fbf66fa 4801
ccb636c7 4802 /* do one-time inits, and possibly become a daemon here */
81d882d5 4803 do_init_first_time(c);
6fbf66fa 4804
e1791bb1 4805#ifdef ENABLE_PLUGIN
81d882d5
DS
4806 /* initialize plugins */
4807 if (c->mode == CM_P2P || c->mode == CM_TOP)
4808 {
4809 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
4810 }
e1791bb1
JY
4811#endif
4812
81d882d5
DS
4813 /* initialise connect timeout timer */
4814 do_init_server_poll_timeout(c);
4db06290 4815
81d882d5
DS
4816 /* finalize the TCP/UDP socket */
4817 if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4818 {
94b391d7 4819 do_init_socket_phase2(c);
b3e97582 4820
2d17869f
AS
4821
4822 /* Update dynamic frame calculation as exact transport socket information
4823 * (IP vs IPv6) may be only available after socket phase2 has finished.
4824 * This is only needed for --static or no crypto, NCP will recalculate this
4825 * in tls_session_update_crypto_params (P2MP) */
94b391d7
AQ
4826 for (int i = 0; i < c->c1.link_sockets_num; i++)
4827 {
4828 frame_calculate_dynamic(&c->c2.frame, &c->c1.ks.key_type, &c->options,
4829 &c->c2.link_sockets[i]->info);
4830 }
2d17869f 4831 }
0d969976 4832
81d882d5
DS
4833 /*
4834 * Actually do UID/GID downgrade, and chroot, if requested.
4835 * May be delayed by --client, --pull, or --up-delay.
4836 */
4837 do_uid_gid_chroot(c, c->c2.did_open_tun);
6fbf66fa 4838
81d882d5
DS
4839 /* initialize timers */
4840 if (c->mode == CM_P2P || child)
4841 {
4842 do_init_timers(c, false);
4843 }
6fbf66fa 4844
e1791bb1 4845#ifdef ENABLE_PLUGIN
81d882d5
DS
4846 /* initialize plugins */
4847 if (c->mode == CM_P2P || c->mode == CM_TOP)
4848 {
4849 open_plugins(c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
4850 }
e1791bb1
JY
4851#endif
4852
6add6b2f 4853#if PORT_SHARE
81d882d5
DS
4854 /* share OpenVPN port with foreign (such as HTTPS) server */
4855 if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
4856 {
4857 init_port_share(c);
4858 }
6add6b2f 4859#endif
81d882d5 4860
81d882d5
DS
4861 /* Check for signals */
4862 if (IS_SIG(c))
4863 {
4864 goto sig;
4865 }
6fbf66fa 4866
81d882d5 4867 return;
6fbf66fa 4868
81d882d5
DS
4869sig:
4870 if (!c->sig->signal_text)
4871 {
4872 c->sig->signal_text = "init_instance";
4873 }
4874 close_context(c, -1, flags);
4875 return;
6fbf66fa
JY
4876}
4877
4878/*
4879 * Close a tunnel instance.
4880 */
4881void
81d882d5 4882close_instance(struct context *c)
6fbf66fa 4883{
81d882d5
DS
4884 /* close event objects */
4885 do_close_event_set(c);
6fbf66fa
JY
4886
4887 if (c->mode == CM_P2P
81d882d5
DS
4888 || c->mode == CM_CHILD_TCP
4889 || c->mode == CM_CHILD_UDP
4890 || c->mode == CM_TOP)
4891 {
38d96bd7 4892#ifdef USE_COMP
81d882d5
DS
4893 if (c->c2.comp_context)
4894 {
4895 comp_uninit(c->c2.comp_context);
4896 c->c2.comp_context = NULL;
4897 }
6fbf66fa
JY
4898#endif
4899
81d882d5
DS
4900 /* free buffers */
4901 do_close_free_buf(c);
6fbf66fa 4902
b6f7b285
AQ
4903 /* close peer for DCO if enabled, needs peer-id so must be done before
4904 * closing TLS contexts */
4905 dco_remove_peer(c);
4906
81d882d5
DS
4907 /* close TLS */
4908 do_close_tls(c);
6fbf66fa 4909
81d882d5
DS
4910 /* free key schedules */
4911 do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP));
6fbf66fa 4912
81d882d5
DS
4913 /* close TCP/UDP connection */
4914 do_close_link_socket(c);
6fbf66fa 4915
81d882d5
DS
4916 /* close TUN/TAP device */
4917 do_close_tun(c, false);
6fbf66fa 4918
99d217b2 4919#ifdef ENABLE_MANAGEMENT
81d882d5
DS
4920 if (management)
4921 {
4922 management_notify_client_close(management, &c->c2.mda_context, NULL);
4923 }
90efcacb
JY
4924#endif
4925
3c7f2f55 4926#ifdef ENABLE_PLUGIN
81d882d5
DS
4927 /* call plugin close functions and unload */
4928 do_close_plugins(c);
3c7f2f55 4929#endif
6fbf66fa 4930
ccb636c7 4931 /* close packet-id persistence file */
81d882d5 4932 do_close_packet_id(c);
6fbf66fa 4933
81d882d5
DS
4934 /* close --status file */
4935 do_close_status_output(c);
6fbf66fa
JY
4936
4937#ifdef ENABLE_FRAGMENT
81d882d5
DS
4938 /* close fragmentation handler */
4939 do_close_fragment(c);
6fbf66fa
JY
4940#endif
4941
81d882d5
DS
4942 /* close --ifconfig-pool-persist obj */
4943 do_close_ifconfig_pool_persist(c);
6fbf66fa 4944
81d882d5
DS
4945 /* free up environmental variable store */
4946 do_env_set_destroy(c);
2a64816b 4947
81d882d5
DS
4948 /* close HTTP or SOCKS proxy */
4949 uninit_proxy(c);
4e9a51d7 4950
81d882d5
DS
4951 /* garbage collect */
4952 gc_free(&c->c2.gc);
4953 }
6fbf66fa
JY
4954}
4955
4956void
81d882d5 4957inherit_context_child(struct context *dest,
94b391d7 4958 const struct context *src,
7e553528 4959 struct link_socket *sock)
6fbf66fa 4960{
81d882d5 4961 CLEAR(*dest);
6fbf66fa 4962
81d882d5 4963 /* proto_is_dgram will ASSERT(0) if proto is invalid */
7e553528 4964 dest->mode = proto_is_dgram(sock->info.proto) ? CM_CHILD_UDP : CM_CHILD_TCP;
6fbf66fa 4965
81d882d5 4966 dest->gc = gc_new();
6fbf66fa 4967
81d882d5 4968 ALLOC_OBJ_CLEAR_GC(dest->sig, struct signal_info, &dest->gc);
6fbf66fa 4969
81d882d5
DS
4970 /* c1 init */
4971 packet_id_persist_init(&dest->c1.pid_persist);
94b391d7
AQ
4972 dest->c1.link_sockets_num = 1;
4973 do_link_socket_addr_new(dest);
6fbf66fa 4974
81d882d5
DS
4975 dest->c1.ks.key_type = src->c1.ks.key_type;
4976 /* inherit SSL context */
4977 dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
4978 dest->c1.ks.tls_wrap_key = src->c1.ks.tls_wrap_key;
4979 dest->c1.ks.tls_auth_key_type = src->c1.ks.tls_auth_key_type;
19dffdbd 4980 dest->c1.ks.tls_crypt_v2_server_key = src->c1.ks.tls_crypt_v2_server_key;
81d882d5 4981 /* inherit pre-NCP ciphers */
7064ccb9
AS
4982 dest->options.ciphername = src->options.ciphername;
4983 dest->options.authname = src->options.authname;
81d882d5 4984
1b9a88a2
AS
4985 /* inherit auth-token */
4986 dest->c1.ks.auth_token_key = src->c1.ks.auth_token_key;
4987
81d882d5
DS
4988 /* options */
4989 dest->options = src->options;
7e553528 4990 dest->options.ce.proto = sock->info.proto;
81d882d5
DS
4991 options_detach(&dest->options);
4992
619c3e9a
GDG
4993 dest->c2.event_set = src->c2.event_set;
4994
81d882d5 4995 if (dest->mode == CM_CHILD_TCP)
6fbf66fa 4996 {
81d882d5
DS
4997 /*
4998 * The CM_TOP context does the socket listen(),
4999 * and the CM_CHILD_TCP context does the accept().
5000 */
7e553528 5001 dest->c2.accept_from = sock;
6fbf66fa
JY
5002 }
5003
3c7f2f55 5004#ifdef ENABLE_PLUGIN
81d882d5
DS
5005 /* inherit plugins */
5006 do_inherit_plugins(dest, src);
3c7f2f55 5007#endif
6fbf66fa 5008
81d882d5 5009 /* context init */
a2d851d4
AQ
5010
5011 /* inherit tun/tap interface object now as it may be required
5012 * to initialize the DCO context in init_instance()
5013 */
5014 dest->c1.tuntap = src->c1.tuntap;
5015
81d882d5
DS
5016 /* UDP inherits some extra things which TCP does not */
5017 if (dest->mode == CM_CHILD_UDP)
6fbf66fa 5018 {
94b391d7 5019 ASSERT(!dest->c2.link_sockets);
8466c2ca 5020 ASSERT(dest->options.ce.local_list);
94b391d7 5021
81d882d5
DS
5022 /* inherit buffers */
5023 dest->c2.buffers = src->c2.buffers;
6fbf66fa 5024
94b391d7
AQ
5025 ALLOC_ARRAY_GC(dest->c2.link_sockets, struct link_socket *, 1, &dest->gc);
5026
81d882d5 5027 /* inherit parent link_socket and tuntap */
7e553528 5028 dest->c2.link_sockets[0] = sock;
6fbf66fa 5029
94b391d7
AQ
5030 ALLOC_ARRAY_GC(dest->c2.link_socket_infos, struct link_socket_info *, 1, &dest->gc);
5031 ALLOC_OBJ_GC(dest->c2.link_socket_infos[0], struct link_socket_info, &dest->gc);
7e553528 5032 *dest->c2.link_socket_infos[0] = sock->info;
6fbf66fa 5033
81d882d5 5034 /* locally override some link_socket_info fields */
94b391d7
AQ
5035 dest->c2.link_socket_infos[0]->lsa = &dest->c1.link_socket_addrs[0];
5036 dest->c2.link_socket_infos[0]->connection_established = false;
5037 }
5038
5039 init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
5040 if (IS_SIG(dest))
5041 {
5042 return;
6fbf66fa
JY
5043 }
5044}
5045
5046void
81d882d5
DS
5047inherit_context_top(struct context *dest,
5048 const struct context *src)
6fbf66fa 5049{
81d882d5
DS
5050 /* copy parent */
5051 *dest = *src;
6fbf66fa 5052
81d882d5
DS
5053 /*
5054 * CM_TOP_CLONE will prevent close_instance from freeing or closing
5055 * resources owned by the parent.
5056 *
5057 * Also note that CM_TOP_CLONE context objects are
5058 * closed by multi_top_free in multi.c.
5059 */
5060 dest->mode = CM_TOP_CLONE;
6fbf66fa 5061
81d882d5
DS
5062 dest->first_time = false;
5063 dest->c0 = NULL;
6fbf66fa 5064
81d882d5
DS
5065 options_detach(&dest->options);
5066 gc_detach(&dest->gc);
5067 gc_detach(&dest->c2.gc);
6fbf66fa 5068
81d882d5
DS
5069 /* detach plugins */
5070 dest->plugins_owned = false;
3c7f2f55 5071
81d882d5 5072 dest->c2.tls_multi = NULL;
6fbf66fa 5073
81d882d5
DS
5074 /* detach c1 ownership */
5075 dest->c1.tuntap_owned = false;
5076 dest->c1.status_output_owned = false;
81d882d5 5077 dest->c1.ifconfig_pool_persist_owned = false;
3c7f2f55 5078
81d882d5
DS
5079 /* detach c2 ownership */
5080 dest->c2.event_set_owned = false;
5081 dest->c2.link_socket_owned = false;
5082 dest->c2.buffers_owned = false;
5083 dest->c2.es_owned = false;
6fbf66fa 5084
81d882d5 5085 dest->c2.event_set = NULL;
619c3e9a 5086 do_event_set_init(dest, false);
38d96bd7
JY
5087
5088#ifdef USE_COMP
81d882d5 5089 dest->c2.comp_context = NULL;
38d96bd7 5090#endif
6fbf66fa
JY
5091}
5092
5093void
81d882d5 5094close_context(struct context *c, int sig, unsigned int flags)
6fbf66fa 5095{
81d882d5
DS
5096 ASSERT(c);
5097 ASSERT(c->sig);
79df31c8 5098
81d882d5
DS
5099 if (sig >= 0)
5100 {
05715485 5101 register_signal(c->sig, sig, "close_context");
81d882d5 5102 }
6fbf66fa 5103
81d882d5 5104 if (c->sig->signal_received == SIGUSR1)
6fbf66fa 5105 {
81d882d5
DS
5106 if ((flags & CC_USR1_TO_HUP)
5107 || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
c058cbff 5108 {
05715485 5109 register_signal(c->sig, SIGHUP, "close_context usr1 to hup");
c058cbff 5110 }
6fbf66fa
JY
5111 }
5112
81d882d5
DS
5113 if (!(flags & CC_NO_CLOSE))
5114 {
5115 close_instance(c);
5116 }
6fbf66fa 5117
81d882d5
DS
5118 if (flags & CC_GC_FREE)
5119 {
5120 context_gc_free(c);
5121 }
6fbf66fa
JY
5122}
5123
008ec688
GD
5124/* Write our PID to a file */
5125void
5126write_pid_file(const char *filename, const char *chroot_dir)
5127{
5128 if (filename)
5129 {
5130 unsigned int pid = 0;
5131 FILE *fp = platform_fopen(filename, "w");
5132 if (!fp)
5133 {
5134 msg(M_ERR, "Open error on pid file %s", filename);
5135 return;
5136 }
5137
5138 pid = platform_getpid();
5139 fprintf(fp, "%u\n", pid);
5140 if (fclose(fp))
5141 {
5142 msg(M_ERR, "Close error on pid file %s", filename);
5143 }
5144
5145 /* remember file name so it can be deleted "out of context" later */
5146 /* (the chroot case is more complex and not handled today) */
5147 if (!chroot_dir)
5148 {
5149 saved_pid_file_name = strdup(filename);
b7c6920e
IS
5150 if (!saved_pid_file_name)
5151 {
5152 msg(M_FATAL, "Failed allocate memory saved_pid_file_name");
5153 }
008ec688
GD
5154 }
5155 }
5156}
5157
5158/* remove PID file on exit, called from openvpn_exit() */
5159void
5160remove_pid_file(void)
5161{
5162 if (saved_pid_file_name)
5163 {
5164 platform_unlink(saved_pid_file_name);
5165 }
5166}
5167
5168
6fbf66fa
JY
5169/*
5170 * Do a loopback test
5171 * on the crypto subsystem.
5172 */
5173static void *
81d882d5 5174test_crypto_thread(void *arg)
6fbf66fa 5175{
81d882d5
DS
5176 struct context *c = (struct context *) arg;
5177 const struct options *options = &c->options;
6fbf66fa 5178
81d882d5
DS
5179 ASSERT(options->test_crypto);
5180 init_verb_mute(c, IVM_LEVEL_1);
5181 context_init_1(c);
5182 next_connection_entry(c);
5183 do_init_crypto_static(c, 0);
6fbf66fa 5184
81d882d5 5185 frame_finalize_options(c, options);
6fbf66fa 5186
81d882d5 5187 test_crypto(&c->c2.crypto_options, &c->c2.frame);
6fbf66fa 5188
81d882d5
DS
5189 key_schedule_free(&c->c1.ks, true);
5190 packet_id_free(&c->c2.crypto_options.packet_id);
6fbf66fa 5191
81d882d5
DS
5192 context_gc_free(c);
5193 return NULL;
6fbf66fa
JY
5194}
5195
6fbf66fa 5196bool
81d882d5 5197do_test_crypto(const struct options *o)
6fbf66fa 5198{
81d882d5 5199 if (o->test_crypto)
6fbf66fa 5200 {
81d882d5 5201 struct context c;
6fbf66fa 5202
81d882d5
DS
5203 /* print version number */
5204 msg(M_INFO, "%s", title_string);
6fbf66fa 5205
81d882d5
DS
5206 context_clear(&c);
5207 c.options = *o;
5208 options_detach(&c.options);
5209 c.first_time = true;
5210 test_crypto_thread((void *) &c);
5211 return true;
6fbf66fa 5212 }
81d882d5 5213 return false;
6fbf66fa 5214}