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