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