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