OpenVPN
init.c
Go to the documentation of this file.
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  *
8  * Copyright (C) 2002-2023 OpenVPN Inc <sales@openvpn.net>
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  *
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.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27 
28 #include "syshead.h"
29 
30 #ifdef ENABLE_SYSTEMD
31 #include <systemd/sd-daemon.h>
32 #endif
33 
34 #include "win32.h"
35 #include "init.h"
36 #include "run_command.h"
37 #include "sig.h"
38 #include "occ.h"
39 #include "list.h"
40 #include "otime.h"
41 #include "pool.h"
42 #include "gremlin.h"
43 #include "occ.h"
44 #include "pkcs11.h"
45 #include "ps.h"
46 #include "lladdr.h"
47 #include "ping.h"
48 #include "mstats.h"
49 #include "ssl_verify.h"
50 #include "ssl_ncp.h"
51 #include "tls_crypt.h"
52 #include "forward.h"
53 #include "auth_token.h"
54 #include "mss.h"
55 #include "mudp.h"
56 #include "dco.h"
57 
58 #include "memdbg.h"
59 
60 
61 static struct context *static_context; /* GLOBAL */
62 static const char *saved_pid_file_name; /* GLOBAL */
63 
64 /*
65  * Crypto initialization flags
66  */
67 #define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
68 #define CF_INIT_TLS_MULTI (1<<1)
69 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
70 
71 static void do_init_first_time(struct context *c);
72 
73 static bool do_deferred_p2p_ncp(struct context *c);
74 
75 void
77 {
78  CLEAR(*c);
79 }
80 
81 void
83 {
84  CLEAR(c->c1);
85 }
86 
87 void
89 {
90  CLEAR(c->c2);
91 }
92 
93 void
95 {
96  const bool first_time_save = c->first_time;
97  const struct context_persist cpsave = c->persist;
98  context_clear(c);
99  c->first_time = first_time_save;
100  c->persist = cpsave;
101 }
102 
103 /*
104  * Pass tunnel endpoint and MTU parms to a user-supplied script.
105  * Used to execute the up/down script/plugins.
106  */
107 static void
108 run_up_down(const char *command,
109  const struct plugin_list *plugins,
110  int plugin_type,
111  const char *arg,
112 #ifdef _WIN32
113  DWORD adapter_index,
114 #endif
115  const char *dev_type,
116  int tun_mtu,
117  const char *ifconfig_local,
118  const char *ifconfig_remote,
119  const char *context,
120  const char *signal_text,
121  const char *script_type,
122  struct env_set *es)
123 {
124  struct gc_arena gc = gc_new();
125 
126  if (signal_text)
127  {
128  setenv_str(es, "signal", signal_text);
129  }
130  setenv_str(es, "script_context", context);
131  setenv_int(es, "tun_mtu", tun_mtu);
132  setenv_str(es, "dev", arg);
133  if (dev_type)
134  {
135  setenv_str(es, "dev_type", dev_type);
136  }
137 #ifdef _WIN32
138  setenv_int(es, "dev_idx", adapter_index);
139 #endif
140 
141  if (!ifconfig_local)
142  {
143  ifconfig_local = "";
144  }
145  if (!ifconfig_remote)
146  {
147  ifconfig_remote = "";
148  }
149  if (!context)
150  {
151  context = "";
152  }
153 
154  if (plugin_defined(plugins, plugin_type))
155  {
156  struct argv argv = argv_new();
157  ASSERT(arg);
158  argv_printf(&argv,
159  "%s %d 0 %s %s %s",
160  arg, tun_mtu, ifconfig_local, ifconfig_remote, context);
161 
162  if (plugin_call(plugins, plugin_type, &argv, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
163  {
164  msg(M_FATAL, "ERROR: up/down plugin call failed");
165  }
166 
167  argv_free(&argv);
168  }
169 
170  if (command)
171  {
172  struct argv argv = argv_new();
173  ASSERT(arg);
174  setenv_str(es, "script_type", script_type);
175  argv_parse_cmd(&argv, command);
176  argv_printf_cat(&argv, "%s %d 0 %s %s %s", arg, tun_mtu,
177  ifconfig_local, ifconfig_remote, context);
178  argv_msg(M_INFO, &argv);
179  openvpn_run_script(&argv, es, S_FATAL, "--up/--down");
180  argv_free(&argv);
181  }
182 
183  gc_free(&gc);
184 }
185 
186 /*
187  * Should be called after options->ce is modified at the top
188  * of a SIGUSR1 restart.
189  */
190 static void
192 {
193  /*
194  * In pull mode, we usually import --ping/--ping-restart parameters from
195  * the server. However we should also set an initial default --ping-restart
196  * for the period of time before we pull the --ping-restart parameter
197  * from the server.
198  */
199  if (options->pull
202  {
205  }
206 }
207 
208 #ifdef ENABLE_MANAGEMENT
209 static bool
210 management_callback_proxy_cmd(void *arg, const char **p)
211 {
212  struct context *c = arg;
213  struct connection_entry *ce = &c->options.ce;
214  struct gc_arena *gc = &c->c2.gc;
215  bool ret = false;
216 
217  update_time();
218  if (streq(p[1], "NONE"))
219  {
220  ret = true;
221  }
222  else if (p[2] && p[3])
223  {
224  if (dco_enabled(&c->options))
225  {
226  msg(M_INFO, "Proxy set via management, disabling Data Channel Offload.");
228  }
229 
230  if (streq(p[1], "HTTP"))
231  {
232  struct http_proxy_options *ho;
233  if (ce->proto != PROTO_TCP && ce->proto != PROTO_TCP_CLIENT)
234  {
235  msg(M_WARN, "HTTP proxy support only works for TCP based connections");
236  return false;
237  }
239  ho->server = string_alloc(p[2], gc);
240  ho->port = string_alloc(p[3], gc);
241  ho->auth_retry = (p[4] && streq(p[4], "nct") ? PAR_NCT : PAR_ALL);
242  ret = true;
243  }
244  else if (streq(p[1], "SOCKS"))
245  {
246  ce->socks_proxy_server = string_alloc(p[2], gc);
247  ce->socks_proxy_port = string_alloc(p[3], gc);
248  ret = true;
249  }
250  }
251  else
252  {
253  msg(M_WARN, "Bad proxy command");
254  }
255 
256  ce->flags &= ~CE_MAN_QUERY_PROXY;
257 
258  return ret;
259 }
260 
261 static bool
263 {
264  const struct connection_list *l = c->options.connection_list;
265  struct connection_entry *ce = &c->options.ce;
266  struct gc_arena gc;
267  bool ret = true;
268 
269  update_time();
270  if (management)
271  {
272  gc = gc_new();
273  {
274  struct buffer out = alloc_buf_gc(256, &gc);
275  buf_printf(&out, ">PROXY:%u,%s,%s", (l ? l->current : 0) + 1,
276  (proto_is_udp(ce->proto) ? "UDP" : "TCP"), np(ce->remote));
279  }
280  ce->flags |= CE_MAN_QUERY_PROXY;
281  while (ce->flags & CE_MAN_QUERY_PROXY)
282  {
284  if (IS_SIG(c))
285  {
286  ret = false;
287  break;
288  }
289  }
291  gc_free(&gc);
292  }
293 
294  return ret;
295 }
296 
311 static bool
313  const char *command,
314  const char *parameters)
315 {
316  struct context *c = (struct context *) arg;
317  size_t len = strlen(command) + 1 + strlen(parameters) + 1;
318  if (len > PUSH_BUNDLE_SIZE)
319  {
320  return false;
321  }
322 
323  struct gc_arena gc = gc_new();
324  struct buffer buf = alloc_buf_gc(len, &gc);
325  ASSERT(buf_printf(&buf, "%s", command));
326  if (parameters)
327  {
328  ASSERT(buf_printf(&buf, ",%s", parameters));
329  }
330  bool status = send_control_channel_string(c, BSTR(&buf), D_PUSH);
331 
332  gc_free(&gc);
333  return status;
334 }
335 
336 static unsigned int
338 {
339  assert(arg);
340  struct context *c = (struct context *) arg;
341  struct connection_list *l = c->options.connection_list;
342 
343  return l->len;
344 }
345 
346 static bool
347 management_callback_remote_entry_get(void *arg, unsigned int index, char **remote)
348 {
349  assert(arg);
350  assert(remote);
351 
352  struct context *c = (struct context *) arg;
353  struct connection_list *l = c->options.connection_list;
354  bool ret = true;
355 
356  if (index < l->len)
357  {
358  struct connection_entry *ce = l->array[index];
359  const char *proto = proto2ascii(ce->proto, ce->af, false);
360  const char *status = (ce->flags & CE_DISABLED) ? "disabled" : "enabled";
361 
362  /* space for output including 3 commas and a nul */
363  int len = strlen(ce->remote) + strlen(ce->remote_port) + strlen(proto)
364  + strlen(status) + 3 + 1;
365  char *out = malloc(len);
366  check_malloc_return(out);
367 
368  openvpn_snprintf(out, len, "%s,%s,%s,%s", ce->remote, ce->remote_port, proto, status);
369  *remote = out;
370  }
371  else
372  {
373  ret = false;
374  msg(M_WARN, "Out of bounds index in management query for remote entry: index = %u", index);
375  }
376 
377  return ret;
378 }
379 
380 static bool
381 management_callback_remote_cmd(void *arg, const char **p)
382 {
383  struct context *c = (struct context *) arg;
384  struct connection_entry *ce = &c->options.ce;
385  int ret = false;
387  {
388  int flags = 0;
389  if (!strcmp(p[1], "ACCEPT"))
390  {
392  ret = true;
393  }
394  else if (!strcmp(p[1], "SKIP"))
395  {
397  ret = true;
398  c->options.ce_advance_count = (p[2]) ? atoi(p[2]) : 1;
399  }
400  else if (!strcmp(p[1], "MOD") && p[2] && p[3])
401  {
402  if (strlen(p[2]) < RH_HOST_LEN && strlen(p[3]) < RH_PORT_LEN)
403  {
404  struct remote_host_store *rhs = c->options.rh_store;
405  if (!rhs)
406  {
408  c->options.rh_store = rhs;
409  }
410  strncpynt(rhs->host, p[2], RH_HOST_LEN);
411  strncpynt(rhs->port, p[3], RH_PORT_LEN);
412 
413  ce->remote = rhs->host;
414  ce->remote_port = rhs->port;
415  flags = CE_MAN_QUERY_REMOTE_MOD;
416  ret = true;
417  }
418  }
419  if (ret)
420  {
423  }
424  }
425  return ret;
426 }
427 
428 static bool
430 {
431  struct gc_arena gc = gc_new();
432  volatile struct connection_entry *ce = &c->options.ce;
433  int ce_changed = true; /* presume the connection entry will be changed */
434 
435  update_time();
436  if (management)
437  {
438  struct buffer out = alloc_buf_gc(256, &gc);
439 
440  buf_printf(&out, ">REMOTE:%s,%s,%s", np(ce->remote), ce->remote_port,
441  proto2ascii(ce->proto, ce->af, false));
444 
447  while (((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
449  {
451  if (IS_SIG(c))
452  {
453  ce_changed = false; /* connection entry have not been set */
454  break;
455  }
456  }
458  }
459  gc_free(&gc);
460 
461  if (ce_changed)
462  {
463  /* If it is likely a connection entry was modified,
464  * check what changed in the flags and that it was not skipped
465  */
466  const int flags = ((ce->flags >> CE_MAN_QUERY_REMOTE_SHIFT)
468  ce_changed = (flags != CE_MAN_QUERY_REMOTE_SKIP);
469  }
470  return ce_changed;
471 }
472 #endif /* ENABLE_MANAGEMENT */
473 
474 /*
475  * Initialize and possibly randomize connection list.
476  */
477 static void
479 {
480  struct connection_list *l = c->options.connection_list;
481 
482  l->current = -1;
483  if (c->options.remote_random)
484  {
485  int i;
486  for (i = 0; i < l->len; ++i)
487  {
488  const int j = get_random() % l->len;
489  if (i != j)
490  {
491  struct connection_entry *tmp;
492  tmp = l->array[i];
493  l->array[i] = l->array[j];
494  l->array[j] = tmp;
495  }
496  }
497  }
498 }
499 
500 /*
501  * Clear the remote address list
502  */
503 static void
505 {
506  if (lsa->remote_list && free)
507  {
508  freeaddrinfo(lsa->remote_list);
509  }
510  lsa->remote_list = NULL;
511  lsa->current_remote = NULL;
512 }
513 
514 /*
515  * Increment to next connection entry
516  */
517 static void
519 {
520  struct connection_list *l = c->options.connection_list;
521  bool ce_defined;
522  struct connection_entry *ce;
523  int n_cycles = 0;
524 
525  do
526  {
527  ce_defined = true;
528  if (c->options.no_advance && l->current >= 0)
529  {
530  c->options.no_advance = false;
531  }
532  else
533  {
534  /* Check if there is another resolved address to try for
535  * the current connection */
537  && c->c1.link_socket_addr.current_remote->ai_next
539  {
541  c->c1.link_socket_addr.current_remote->ai_next;
542  }
543  else
544  {
545  c->options.advance_next_remote = false;
546  /* FIXME (schwabe) fix the persist-remote-ip option for real,
547  * this is broken probably ever since connection lists and multiple
548  * remote existed
549  */
550  if (!c->options.persist_remote_ip)
551  {
552  /* Connection entry addrinfo objects might have been
553  * resolved earlier but the entry itself might have been
554  * skipped by management on the previous loop.
555  * If so, clear the addrinfo objects as close_instance does
556  */
558  {
561  }
562 
563  /* close_instance should have cleared the addrinfo objects */
566  }
567  else
568  {
571  }
572 
573  int advance_count = 1;
574 
575  /* If previous connection entry was skipped by management client
576  * with a count to advance by, apply it.
577  */
578  if (c->options.ce_advance_count > 0)
579  {
580  advance_count = c->options.ce_advance_count;
581  }
582 
583  /*
584  * Increase the number of connection attempts
585  * If this is connect-retry-max * size(l)
586  * OpenVPN will quit
587  */
588 
589  c->options.unsuccessful_attempts += advance_count;
590  l->current += advance_count;
591 
592  if (l->current >= l->len)
593  {
594  l->current %= l->len;
595  if (++n_cycles >= 2)
596  {
597  msg(M_FATAL, "No usable connection profiles are present");
598  }
599  }
600  }
601  }
602 
603  c->options.ce_advance_count = 1;
604  ce = l->array[l->current];
605 
606  if (ce->flags & CE_DISABLED)
607  {
608  ce_defined = false;
609  }
610 
611  c->options.ce = *ce;
612 #ifdef ENABLE_MANAGEMENT
614  {
615  /* allow management interface to override connection entry details */
616  ce_defined = ce_management_query_remote(c);
617  if (IS_SIG(c))
618  {
619  break;
620  }
621  }
622  else if (ce_defined && management && management_query_proxy_enabled(management))
623  {
624  ce_defined = ce_management_query_proxy(c);
625  if (IS_SIG(c))
626  {
627  break;
628  }
629  }
630 #endif
631  } while (!ce_defined);
632 
633  /* Check if this connection attempt would bring us over the limit */
634  if (c->options.connect_retry_max > 0
636  {
637  msg(M_FATAL, "All connections have been connect-retry-max (%d) times unsuccessful, exiting",
639  }
641 }
642 
643 /*
644  * Query for private key and auth-user-pass username/passwords
645  */
646 void
648 {
649  /* Certificate password input */
650  if (c->options.key_pass_file)
651  {
653  }
654 
655  /* Auth user/pass input */
657  {
659 #ifdef ENABLE_MANAGEMENT
662  &c->options.sc_info);
663 #else
666 #endif
667  }
668 }
669 
670 /*
671  * Initialize/Uninitialize HTTP or SOCKS proxy
672  */
673 
674 static void
676 {
677  if (c->c1.http_proxy_owned && c->c1.http_proxy)
678  {
680  c->c1.http_proxy = NULL;
681  c->c1.http_proxy_owned = false;
682  }
683  if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
684  {
686  c->c1.socks_proxy = NULL;
687  c->c1.socks_proxy_owned = false;
688  }
689 }
690 
691 static void
693 {
694  bool did_http = false;
695 
697 
699  {
700  /* Possible HTTP proxy user/pass input */
702  if (c->c1.http_proxy)
703  {
704  did_http = true;
705  c->c1.http_proxy_owned = true;
706  }
707  }
708 
709  if (!did_http && c->options.ce.socks_proxy_server)
710  {
714  if (c->c1.socks_proxy)
715  {
716  c->c1.socks_proxy_owned = true;
717  }
718  }
719 }
720 
721 static void
722 init_proxy(struct context *c)
723 {
725 }
726 
727 static void
729 {
731 }
732 
733 void
735 {
736  context_clear_1(c);
737 
739 
741 
742 #if defined(ENABLE_PKCS11)
743  if (c->first_time)
744  {
745  int i;
746  pkcs11_initialize(true, c->options.pkcs11_pin_cache_period);
747  for (i = 0; i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL; i++)
748  {
749  pkcs11_addProvider(c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
750  c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
751  }
752  }
753 #endif
754 
755 #if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
756  {
757  /*
758  * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
759  */
760  struct user_pass up;
761  CLEAR(up);
762  strcpy(up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
763  get_user_pass(&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
764  msg(M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
765  * 'needok' command, usually 'ok' or 'cancel'. */
766  }
767 #endif
768 
769 #ifdef ENABLE_SYSTEMD
770  /* We can report the PID via getpid() to systemd here as OpenVPN will not
771  * do any fork due to daemon() a future call.
772  * See possibly_become_daemon() [init.c] for more details.
773  */
774  sd_notifyf(0, "READY=1\nSTATUS=Pre-connection initialization successful\nMAINPID=%lu",
775  (unsigned long) getpid());
776 #endif
777 
778 }
779 
780 void
782 {
783  gc_free(&c->c2.gc);
784  gc_free(&c->options.gc);
785  gc_free(&c->gc);
786 }
787 
788 #if PORT_SHARE
789 
790 static void
791 close_port_share(void)
792 {
793  if (port_share)
794  {
795  port_share_close(port_share);
796  port_share = NULL;
797  }
798 }
799 
800 static void
801 init_port_share(struct context *c)
802 {
803  if (!port_share && (c->options.port_share_host && c->options.port_share_port))
804  {
805  port_share = port_share_open(c->options.port_share_host,
806  c->options.port_share_port,
808  c->options.port_share_journal_dir);
809  if (port_share == NULL)
810  {
811  msg(M_FATAL, "Fatal error: Port sharing failed");
812  }
813  }
814 }
815 
816 #endif /* if PORT_SHARE */
817 
818 
819 bool
821 {
822  /* configure_path (); */
823 
824 #if defined(DMALLOC)
825  crypto_init_dmalloc();
826 #endif
827 
828 
829  /*
830  * Initialize random number seed. random() is only used
831  * when "weak" random numbers are acceptable.
832  * SSL library routines are always used when cryptographically
833  * strong random numbers are required.
834  */
835  struct timeval tv;
836  if (!gettimeofday(&tv, NULL))
837  {
838  const unsigned int seed = (unsigned int) tv.tv_sec ^ tv.tv_usec;
839  srandom(seed);
840  }
841 
842  error_reset(); /* initialize error.c */
843  reset_check_status(); /* initialize status check code in socket.c */
844 
845 #ifdef _WIN32
846  init_win32();
847 #endif
848 
849 #ifdef OPENVPN_DEBUG_COMMAND_LINE
850  {
851  int i;
852  for (i = 0; i < argc; ++i)
853  {
854  msg(M_INFO, "argv[%d] = '%s'", i, argv[i]);
855  }
856  }
857 #endif
858 
859  update_time();
860 
861  init_ssl_lib();
862 
863 #ifdef SCHEDULE_TEST
864  schedule_test();
865  return false;
866 #endif
867 
868 #ifdef LIST_TEST
869  list_test();
870  return false;
871 #endif
872 
873 #ifdef IFCONFIG_POOL_TEST
874  ifconfig_pool_test(0x0A010004, 0x0A0100FF);
875  return false;
876 #endif
877 
878 #ifdef CHARACTER_CLASS_DEBUG
879  character_class_debug();
880  return false;
881 #endif
882 
883 #ifdef EXTRACT_X509_FIELD_TEST
885  return false;
886 #endif
887 
888 #ifdef TIME_TEST
889  time_test();
890  return false;
891 #endif
892 
893 #ifdef TEST_GET_DEFAULT_GATEWAY
894  {
895  struct route_gateway_info rgi;
896  struct route_ipv6_gateway_info rgi6;
897  get_default_gateway(&rgi);
898  get_default_gateway_ipv6(&rgi6, NULL);
899  print_default_gateway(M_INFO, &rgi, &rgi6);
900  return false;
901  }
902 #endif
903 
904 #ifdef GEN_PATH_TEST
905  {
906  struct gc_arena gc = gc_new();
907  const char *fn = gen_path("foo",
908  "bar",
909  &gc);
910  printf("%s\n", fn);
911  gc_free(&gc);
912  }
913  return false;
914 #endif
915 
916 #ifdef STATUS_PRINTF_TEST
917  {
918  struct gc_arena gc = gc_new();
919  const char *tmp_file = platform_create_temp_file("/tmp", "foo", &gc);
920  struct status_output *so = status_open(tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
921  status_printf(so, "%s", "foo");
922  status_printf(so, "%s", "bar");
923  if (!status_close(so))
924  {
925  msg(M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
926  }
927  gc_free(&gc);
928  }
929  return false;
930 #endif
931 
932 #ifdef MSTATS_TEST
933  {
934  int i;
935  mstats_open("/dev/shm/mstats.dat");
936  for (i = 0; i < 30; ++i)
937  {
938  mmap_stats->n_clients += 1;
939  mmap_stats->link_write_bytes += 8;
940  mmap_stats->link_read_bytes += 16;
941  sleep(1);
942  }
943  mstats_close();
944  return false;
945  }
946 #endif
947 
948  return true;
949 }
950 
951 void
953 {
954  free_ssl_lib();
955 
956 #ifdef ENABLE_PKCS11
957  pkcs11_terminate();
958 #endif
959 
960 #if PORT_SHARE
961  close_port_share();
962 #endif
963 
964 #if defined(MEASURE_TLS_HANDSHAKE_STATS)
965  show_tls_performance_stats();
966 #endif
967 }
968 
969 void
970 init_verb_mute(struct context *c, unsigned int flags)
971 {
972  if (flags & IVM_LEVEL_1)
973  {
974  /* set verbosity and mute levels */
978  }
979 
980  /* special D_LOG_RW mode */
981  if (flags & IVM_LEVEL_2)
982  {
984  }
985 }
986 
987 /*
988  * Possibly set --dev based on --dev-node.
989  * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
990  * set --dev to tun.
991  */
992 void
994 {
995  if (!options->dev && options->dev_node)
996  {
997  char *dev_node = string_alloc(options->dev_node, NULL); /* POSIX basename() implementations may modify its arguments */
998  options->dev = basename(dev_node);
999  }
1000 }
1001 
1002 bool
1004 {
1005  /*
1006  * OpenSSL info print mode?
1007  */
1010  {
1011  if (options->show_ciphers)
1012  {
1014  }
1015  if (options->show_digests)
1016  {
1018  }
1019  if (options->show_engines)
1020  {
1022  }
1024  {
1028  }
1029  if (options->show_curves)
1030  {
1032  }
1033  return true;
1034  }
1035  return false;
1036 }
1037 
1038 /*
1039  * Static pre-shared key generation mode?
1040  */
1041 bool
1042 do_genkey(const struct options *options)
1043 {
1044  /* should we disable paging? */
1045  if (options->mlock && (options->genkey))
1046  {
1047  platform_mlockall(true);
1048  }
1049 
1050  /*
1051  * We do not want user to use --genkey with --secret. In the transistion
1052  * phase we for secret.
1053  */
1056  {
1057  msg(M_USAGE, "Using --genkey type with --secret filename is "
1058  "not supported. Use --genkey type filename instead.");
1059  }
1061  {
1062  int nbits_written;
1063  const char *genkey_filename = options->genkey_filename;
1065  {
1066  msg(M_USAGE, "You must provide a filename to either --genkey "
1067  "or --secret, not both");
1068  }
1069 
1070  /*
1071  * Copy filename from shared_secret_file to genkey_filename to support
1072  * the old --genkey --secret foo.file syntax.
1073  */
1075  {
1076  msg(M_WARN, "WARNING: Using --genkey --secret filename is "
1077  "DEPRECATED. Use --genkey secret filename instead.");
1078  genkey_filename = options->shared_secret_file;
1079  }
1080 
1081  nbits_written = write_key_file(2, genkey_filename);
1082  if (nbits_written < 0)
1083  {
1084  msg(M_FATAL, "Failed to write key file");
1085  }
1086 
1088  "Randomly generated %d bit key written to %s", nbits_written,
1090  return true;
1091  }
1093  {
1095  return true;
1096  }
1098  {
1099  if (!options->tls_crypt_v2_file)
1100  {
1101  msg(M_USAGE,
1102  "--genkey tls-crypt-v2-client requires a server key to be set via --tls-crypt-v2 to create a client key");
1103  }
1104 
1108  return true;
1109  }
1111  {
1113  return true;
1114  }
1115  else
1116  {
1117  return false;
1118  }
1119 }
1120 
1121 /*
1122  * Persistent TUN/TAP device management mode?
1123  */
1124 bool
1126 {
1127  if (!options->persist_config)
1128  {
1129  return false;
1130  }
1131 
1132  /* sanity check on options for --mktun or --rmtun */
1133  notnull(options->dev, "TUN/TAP device (--dev)");
1138  )
1139  {
1141  "options --mktun or --rmtun should only be used together with --dev");
1142  }
1143 
1144 #if defined(ENABLE_DCO)
1145  if (dco_enabled(options))
1146  {
1147  /* creating a DCO interface via --mktun is not supported as it does not
1148  * make much sense. Since DCO is enabled by default, people may run into
1149  * this without knowing, therefore this case should be properly handled.
1150  *
1151  * Disable DCO if --mktun was provided and print a message to let
1152  * user know.
1153  */
1155  {
1156  msg(M_WARN, "Note: --mktun does not support DCO. Creating TUN interface.");
1157  }
1158 
1160  }
1161 #endif
1162 
1163 #ifdef ENABLE_FEATURE_TUN_PERSIST
1167  ctx);
1169  {
1170  set_lladdr(ctx, options->dev, options->lladdr, NULL);
1171  }
1172  return true;
1173 #else /* ifdef ENABLE_FEATURE_TUN_PERSIST */
1175  "options --mktun and --rmtun are not available on your operating "
1176  "system. Please check 'man tun' (or 'tap'), whether your system "
1177  "supports using 'ifconfig %s create' / 'destroy' to create/remove "
1178  "persistent tunnel interfaces.", options->dev );
1179 #endif
1180  return false;
1181 }
1182 
1183 /*
1184  * Should we become a daemon?
1185  * Return true if we did it.
1186  */
1187 bool
1189 {
1190  bool ret = false;
1191 
1192 #ifdef ENABLE_SYSTEMD
1193  /* return without forking if we are running from systemd */
1194  if (sd_notify(0, "READY=0") > 0)
1195  {
1196  return ret;
1197  }
1198 #endif
1199 
1200  if (options->daemon)
1201  {
1202  /* Don't chdir immediately, but the end of the init sequence, if needed */
1203 
1204 #if defined(__APPLE__) && defined(__clang__)
1205 #pragma clang diagnostic push
1206 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1207 #endif
1208  if (daemon(1, options->log) < 0)
1209  {
1210  msg(M_ERR, "daemon() failed or unsupported");
1211  }
1212 #if defined(__APPLE__) && defined(__clang__)
1213 #pragma clang diagnostic pop
1214 #endif
1216  if (options->log)
1217  {
1218  set_std_files_to_null(true);
1219  }
1220 
1221  ret = true;
1222  }
1223  return ret;
1224 }
1225 
1226 /*
1227  * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
1228  */
1229 static void
1230 do_uid_gid_chroot(struct context *c, bool no_delay)
1231 {
1232  static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
1233  struct context_0 *c0 = c->c0;
1234 
1235  if (c0 && !c0->uid_gid_chroot_set)
1236  {
1237  /* chroot if requested */
1238  if (c->options.chroot_dir)
1239  {
1240  if (no_delay)
1241  {
1243  }
1244  else if (c->first_time)
1245  {
1246  msg(M_INFO, "NOTE: chroot %s", why_not);
1247  }
1248  }
1249 
1250  /* set user and/or group if we want to setuid/setgid */
1251  if (c0->uid_gid_specified)
1252  {
1253  if (no_delay)
1254  {
1256  &c0->platform_state_group,
1257  c);
1258  }
1259  else if (c->first_time)
1260  {
1261  msg(M_INFO, "NOTE: UID/GID downgrade %s", why_not);
1262  }
1263  }
1264 
1265 #ifdef ENABLE_MEMSTATS
1266  if (c->first_time && c->options.memstats_fn)
1267  {
1268  mstats_open(c->options.memstats_fn);
1269  }
1270 #endif
1271 
1272 #ifdef ENABLE_SELINUX
1273  /* Apply a SELinux context in order to restrict what OpenVPN can do
1274  * to _only_ what it is supposed to do after initialization is complete
1275  * (basically just network I/O operations). Doing it after chroot
1276  * requires /proc to be mounted in the chroot (which is annoying indeed
1277  * but doing it before requires more complex SELinux policies.
1278  */
1279  if (c->options.selinux_context)
1280  {
1281  if (no_delay)
1282  {
1283  if (-1 == setcon(c->options.selinux_context))
1284  {
1285  msg(M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
1286  }
1287  else
1288  {
1289  msg(M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
1290  }
1291  }
1292  else if (c->first_time)
1293  {
1294  msg(M_INFO, "NOTE: setcon %s", why_not);
1295  }
1296  }
1297 #endif
1298 
1299  /* Privileges are going to be dropped by now (if requested), be sure
1300  * to prevent any future privilege dropping attempts from now on.
1301  */
1302  if (no_delay)
1303  {
1304  c0->uid_gid_chroot_set = true;
1305  }
1306  }
1307 }
1308 
1309 /*
1310  * Return common name in a way that is formatted for
1311  * prepending to msg() output.
1312  */
1313 const char *
1314 format_common_name(struct context *c, struct gc_arena *gc)
1315 {
1316  struct buffer out = alloc_buf_gc(256, gc);
1317  if (c->c2.tls_multi)
1318  {
1319  buf_printf(&out, "[%s] ", tls_common_name(c->c2.tls_multi, false));
1320  }
1321  return BSTR(&out);
1322 }
1323 
1324 void
1325 pre_setup(const struct options *options)
1326 {
1327 #ifdef _WIN32
1328  if (options->exit_event_name)
1329  {
1334  }
1335  else
1336  {
1339  NULL,
1340  false);
1341 
1342  /* put a title on the top window bar */
1344  {
1347  }
1348  }
1349 #endif /* ifdef _WIN32 */
1350 }
1351 
1352 void
1354 {
1355  c->c2.coarse_timer_wakeup = 0;
1356 }
1357 
1358 /*
1359  * Initialise the server poll timeout timer
1360  * This timer is used in the http/socks proxy setup so it needs to be setup
1361  * before
1362  */
1363 static void
1365 {
1366  update_time();
1367  if (c->options.ce.connect_timeout)
1368  {
1370  }
1371 }
1372 
1373 /*
1374  * Initialize timers
1375  */
1376 static void
1377 do_init_timers(struct context *c, bool deferred)
1378 {
1379  update_time();
1381 
1382  /* initialize inactivity timeout */
1383  if (c->options.inactivity_timeout)
1384  {
1386  }
1387 
1388  /* initialize inactivity timeout */
1389  if (c->options.session_timeout)
1390  {
1392  now);
1393  }
1394 
1395  /* initialize pings */
1396  if (dco_enabled(&c->options))
1397  {
1398  /* The DCO kernel module will send the pings instead of user space */
1401  }
1402  else
1403  {
1404  if (c->options.ping_send_timeout)
1405  {
1407  }
1408 
1409  if (c->options.ping_rec_timeout)
1410  {
1412  }
1413  }
1414 
1415  /* If the auth-token renewal interval is shorter than reneg-sec, arm
1416  * "auth-token renewal" timer to send additional auth-token to update the
1417  * token on the client more often. If not, this happens automatically
1418  * at renegotiation time, without needing an extra event.
1419  */
1422  {
1425  }
1426 
1427  if (!deferred)
1428  {
1429  /* initialize connection establishment timer */
1431 
1432  /* initialize occ timers */
1433 
1434  if (c->options.occ
1435  && !TLS_MODE(c)
1437  {
1439  }
1440 
1441  if (c->options.mtu_test)
1442  {
1444  }
1445 
1446  /* initialize packet_id persistence timer */
1447  if (c->options.packet_id_file)
1448  {
1450  }
1451 
1452  /* initialize tmp_int optimization that limits the number of times we call
1453  * tls_multi_process in the main event loop */
1455  }
1456 }
1457 
1458 /*
1459  * Initialize traffic shaper.
1460  */
1461 static void
1463 {
1464  /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
1465  if (c->options.shaper)
1466  {
1467  shaper_init(&c->c2.shaper, c->options.shaper);
1468  shaper_msg(&c->c2.shaper);
1469  }
1470 }
1471 
1472 /*
1473  * Allocate route list structures for IPv4 and IPv6
1474  * (we do this for IPv4 even if no --route option has been seen, as other
1475  * parts of OpenVPN might want to fill the route-list with info, e.g. DHCP)
1476  */
1477 static void
1479 {
1480  if (!c->c1.route_list)
1481  {
1482  ALLOC_OBJ_CLEAR_GC(c->c1.route_list, struct route_list, &c->gc);
1483  }
1484  if (c->options.routes_ipv6 && !c->c1.route_ipv6_list)
1485  {
1487  }
1488 }
1489 
1490 
1491 /*
1492  * Initialize the route list, resolving any DNS names in route
1493  * options and saving routes in the environment.
1494  */
1495 static void
1497  struct route_list *route_list,
1498  const struct link_socket_info *link_socket_info,
1499  struct env_set *es,
1500  openvpn_net_ctx_t *ctx)
1501 {
1502  const char *gw = NULL;
1503  int dev = dev_type_enum(options->dev, options->dev_type);
1504  int metric = 0;
1505 
1506  /* if DCO is enabled we have both regular routes and iroutes in the system
1507  * routing table, and normal routes must have a higher metric for that to
1508  * work so that iroutes are always matched first
1509  */
1510  if (dco_enabled(options))
1511  {
1512  metric = DCO_DEFAULT_METRIC;
1513  }
1514 
1515  if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
1516  {
1518  }
1520  {
1522  }
1524  {
1525  metric = options->route_default_metric;
1526  }
1527 
1529  options->routes,
1530  gw,
1531  metric,
1533  es,
1534  ctx))
1535  {
1536  /* copy routes to environment */
1538  }
1539 }
1540 
1541 static void
1544  const struct link_socket_info *link_socket_info,
1545  struct env_set *es,
1546  openvpn_net_ctx_t *ctx)
1547 {
1548  const char *gw = NULL;
1549  int metric = -1; /* no metric set */
1550 
1551  /* see explanation in do_init_route_list() */
1552  if (dco_enabled(options))
1553  {
1554  metric = DCO_DEFAULT_METRIC;
1555  }
1556 
1557  gw = options->ifconfig_ipv6_remote; /* default GW = remote end */
1559  {
1561  }
1562 
1564  {
1565  metric = options->route_default_metric;
1566  }
1567 
1568  /* redirect (IPv6) gateway to VPN? if yes, add a few more specifics
1569  */
1571  {
1572  char *opt_list[] = { "::/3", "2000::/4", "3000::/4", "fc00::/7", NULL };
1573  int i;
1574 
1575  for (i = 0; opt_list[i]; i++)
1576  {
1578  string_alloc(opt_list[i], options->routes_ipv6->gc),
1579  NULL, NULL );
1580  }
1581  }
1582 
1585  gw,
1586  metric,
1588  es,
1589  ctx))
1590  {
1591  /* copy routes to environment */
1593  }
1594 }
1595 
1596 
1597 /*
1598  * Called after all initialization has been completed.
1599  */
1600 void
1601 initialization_sequence_completed(struct context *c, const unsigned int flags)
1602 {
1603  static const char message[] = "Initialization Sequence Completed";
1604 
1605  /* Reset the unsuccessful connection counter on complete initialisation */
1607 
1608  /* If we delayed UID/GID downgrade or chroot, do it now */
1609  do_uid_gid_chroot(c, true);
1610 
1611  /* Test if errors */
1612  if (flags & ISC_ERRORS)
1613  {
1614 #ifdef _WIN32
1617  msg(M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
1618 #else
1619 #ifdef ENABLE_SYSTEMD
1620  sd_notifyf(0, "STATUS=Failed to start up: %s With Errors\nERRNO=1", message);
1621 #endif /* HAVE_SYSTEMD_SD_DAEMON_H */
1622  msg(M_INFO, "%s With Errors", message);
1623 #endif
1624  }
1625  else
1626  {
1627 #ifdef ENABLE_SYSTEMD
1628  sd_notifyf(0, "STATUS=%s", message);
1629 #endif
1630  msg(M_INFO, "%s", message);
1631  }
1632 
1633  /* Flag that we initialized */
1634  if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0)
1635  {
1636  c->options.no_advance = true;
1637  }
1638 
1639 #ifdef _WIN32
1641 #endif
1642 
1643 #ifdef ENABLE_MANAGEMENT
1644  /* Tell management interface that we initialized */
1645  if (management)
1646  {
1647  in_addr_t *tun_local = NULL;
1648  struct in6_addr *tun_local6 = NULL;
1649  struct openvpn_sockaddr local, remote;
1650  struct link_socket_actual *actual;
1651  socklen_t sa_len = sizeof(local);
1652  const char *detail = "SUCCESS";
1653  if (flags & ISC_ERRORS)
1654  {
1655  detail = "ERROR";
1656  }
1657  /* Flag route error only on platforms where trivial "already exists" errors
1658  * are filtered out. Currently this is the case on Windows or if usng netlink.
1659  */
1660 #if defined(_WIN32) || defined(ENABLE_SITNL)
1661  else if (flags & ISC_ROUTE_ERRORS)
1662  {
1663  detail = "ROUTE_ERROR";
1664  }
1665 #endif
1666 
1667  CLEAR(local);
1668  actual = &get_link_socket_info(c)->lsa->actual;
1669  remote = actual->dest;
1670  getsockname(c->c2.link_socket->sd, &local.addr.sa, &sa_len);
1671 #if ENABLE_IP_PKTINFO
1672  if (!addr_defined(&local))
1673  {
1674  switch (local.addr.sa.sa_family)
1675  {
1676  case AF_INET:
1677 #if defined(HAVE_IN_PKTINFO) && defined(HAVE_IPI_SPEC_DST)
1678  local.addr.in4.sin_addr = actual->pi.in4.ipi_spec_dst;
1679 #else
1680  local.addr.in4.sin_addr = actual->pi.in4;
1681 #endif
1682  break;
1683 
1684  case AF_INET6:
1685  local.addr.in6.sin6_addr = actual->pi.in6.ipi6_addr;
1686  break;
1687  }
1688  }
1689 #endif
1690 
1691  if (c->c1.tuntap)
1692  {
1693  tun_local = &c->c1.tuntap->local;
1694  tun_local6 = &c->c1.tuntap->local_ipv6;
1695  }
1698  detail,
1699  tun_local,
1700  tun_local6,
1701  &local,
1702  &remote);
1703  if (tun_local)
1704  {
1706  }
1707  }
1708 #endif /* ifdef ENABLE_MANAGEMENT */
1709 }
1710 
1711 /*
1712  * Possibly add routes and/or call route-up script
1713  * based on options.
1714  */
1715 bool
1716 do_route(const struct options *options,
1717  struct route_list *route_list,
1719  const struct tuntap *tt,
1720  const struct plugin_list *plugins,
1721  struct env_set *es,
1722  openvpn_net_ctx_t *ctx)
1723 {
1724  bool ret = true;
1726  {
1728  es, ctx);
1730  }
1731 #ifdef ENABLE_MANAGEMENT
1732  if (management)
1733  {
1735  }
1736 #endif
1737 
1739  {
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  }
1744  }
1745 
1746  if (options->route_script)
1747  {
1748  struct argv argv = argv_new();
1749  setenv_str(es, "script_type", "route-up");
1751  openvpn_run_script(&argv, es, 0, "--route-up");
1752  argv_free(&argv);
1753  }
1754 
1755 #ifdef _WIN32
1756  if (options->show_net_up)
1757  {
1760  }
1761  else if (check_debug_level(D_SHOW_NET))
1762  {
1765  }
1766 #endif
1767  return ret;
1768 }
1769 
1770 /*
1771  * initialize tun/tap device object
1772  */
1773 static void
1775 {
1776  c->c1.tuntap = init_tun(c->options.dev,
1777  c->options.dev_type,
1778  c->options.topology,
1787  c->c2.es,
1788  &c->net_ctx,
1789  c->c1.tuntap);
1790 
1791 #ifdef _WIN32
1793 #endif
1794 
1795  init_tun_post(c->c1.tuntap,
1796  &c->c2.frame,
1797  &c->options.tuntap_options);
1798 
1799  c->c1.tuntap_owned = true;
1800 }
1801 
1802 /*
1803  * Open tun/tap device, ifconfig, call up script, etc.
1804  */
1805 
1806 
1807 static bool
1809 {
1810 #ifdef TARGET_ANDROID
1811  return false;
1812 #else
1813  return is_tun_type_set(tt);
1814 #endif
1815 }
1816 
1817 static bool
1818 do_open_tun(struct context *c, int *error_flags)
1819 {
1820  struct gc_arena gc = gc_new();
1821  bool ret = false;
1822  *error_flags = 0;
1823 
1824  if (!can_preserve_tun(c->c1.tuntap))
1825  {
1826 #ifdef TARGET_ANDROID
1827  /* If we emulate persist-tun on android we still have to open a new tun and
1828  * then close the old */
1829  int oldtunfd = -1;
1830  if (c->c1.tuntap)
1831  {
1832  oldtunfd = c->c1.tuntap->fd;
1833  free(c->c1.tuntap);
1834  c->c1.tuntap = NULL;
1835  c->c1.tuntap_owned = false;
1836  }
1837 #endif
1838 
1839  /* initialize (but do not open) tun/tap object */
1840  do_init_tun(c);
1841 
1842  /* inherit the dco context from the tuntap object */
1843  if (c->c2.tls_multi)
1844  {
1845  c->c2.tls_multi->dco = &c->c1.tuntap->dco;
1846  }
1847 
1848 #ifdef _WIN32
1849  /* store (hide) interactive service handle in tuntap_options */
1851  msg(D_ROUTE, "interactive service msg_channel=%" PRIuPTR,
1852  (intptr_t) c->options.msg_channel);
1853 #endif
1854 
1855  /* allocate route list structure */
1857 
1858  /* parse and resolve the route option list */
1859  ASSERT(c->c2.link_socket);
1860  if (c->options.routes && c->c1.route_list)
1861  {
1863  &c->c2.link_socket->info, c->c2.es, &c->net_ctx);
1864  }
1865  if (c->options.routes_ipv6 && c->c1.route_ipv6_list)
1866  {
1868  &c->c2.link_socket->info, c->c2.es,
1869  &c->net_ctx);
1870  }
1871 
1872  /* do ifconfig */
1873  if (!c->options.ifconfig_noexec
1875  {
1876  /* guess actual tun/tap unit number that will be returned
1877  * by open_tun */
1878  const char *guess = guess_tuntap_dev(c->options.dev,
1879  c->options.dev_type,
1880  c->options.dev_node,
1881  &gc);
1882  do_ifconfig(c->c1.tuntap, guess, c->c2.frame.tun_mtu, c->c2.es,
1883  &c->net_ctx);
1884  }
1885 
1886  /* possibly add routes */
1887  if (route_order() == ROUTE_BEFORE_TUN)
1888  {
1889  /* Ignore route_delay, would cause ROUTE_BEFORE_TUN to be ignored */
1890  bool status = do_route(&c->options, c->c1.route_list, c->c1.route_ipv6_list,
1891  c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
1892  *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS);
1893  }
1894 #ifdef TARGET_ANDROID
1895  /* Store the old fd inside the fd so open_tun can use it */
1896  c->c1.tuntap->fd = oldtunfd;
1897 #endif
1898  if (dco_enabled(&c->options))
1899  {
1900  ovpn_dco_init(c->mode, &c->c1.tuntap->dco);
1901  }
1902 
1903  /* open the tun device */
1905  c->c1.tuntap, &c->net_ctx);
1906 
1907  /* set the hardware address */
1908  if (c->options.lladdr)
1909  {
1911  c->c2.es);
1912  }
1913 
1914  /* do ifconfig */
1915  if (!c->options.ifconfig_noexec
1917  {
1919  c->c2.frame.tun_mtu, c->c2.es, &c->net_ctx);
1920  }
1921 
1922  /* run the up script */
1924  c->plugins,
1926  c->c1.tuntap->actual_name,
1927 #ifdef _WIN32
1928  c->c1.tuntap->adapter_index,
1929 #endif
1931  c->c2.frame.tun_mtu,
1934  "init",
1935  NULL,
1936  "up",
1937  c->c2.es);
1938 
1939 #if defined(_WIN32)
1940  if (c->options.block_outside_dns)
1941  {
1942  dmsg(D_LOW, "Blocking outside DNS");
1944  {
1945  msg(M_FATAL, "Blocking DNS failed!");
1946  }
1947  }
1948 #endif
1949 
1950  /* possibly add routes */
1952  {
1954  c->c1.tuntap, c->plugins, c->c2.es, &c->net_ctx);
1955  *error_flags |= (status ? 0 : ISC_ROUTE_ERRORS);
1956  }
1957 
1958  ret = true;
1959  static_context = c;
1960  }
1961  else
1962  {
1963  msg(M_INFO, "Preserving previous TUN/TAP instance: %s",
1964  c->c1.tuntap->actual_name);
1965 
1966  /* explicitly set the ifconfig_* env vars */
1967  do_ifconfig_setenv(c->c1.tuntap, c->c2.es);
1968 
1969  /* run the up script if user specified --up-restart */
1970  if (c->options.up_restart)
1971  {
1973  c->plugins,
1975  c->c1.tuntap->actual_name,
1976 #ifdef _WIN32
1977  c->c1.tuntap->adapter_index,
1978 #endif
1980  c->c2.frame.tun_mtu,
1983  "restart",
1984  NULL,
1985  "up",
1986  c->c2.es);
1987  }
1988 #if defined(_WIN32)
1989  if (c->options.block_outside_dns)
1990  {
1991  dmsg(D_LOW, "Blocking outside DNS");
1993  {
1994  msg(M_FATAL, "Blocking DNS failed!");
1995  }
1996  }
1997 #endif
1998 
1999  }
2000  gc_free(&gc);
2001  return ret;
2002 }
2003 
2004 /*
2005  * Close TUN/TAP device
2006  */
2007 
2008 static void
2010 {
2011  msg(D_CLOSE, "Closing %s interface",
2012  dco_enabled(&c->options) ? "DCO" : "TUN/TAP");
2013 
2014  if (c->c1.tuntap)
2015  {
2016  if (!c->options.ifconfig_noexec)
2017  {
2018  undo_ifconfig(c->c1.tuntap, &c->net_ctx);
2019  }
2020  close_tun(c->c1.tuntap, &c->net_ctx);
2021  c->c1.tuntap = NULL;
2022  }
2023  c->c1.tuntap_owned = false;
2025 }
2026 
2027 static void
2028 do_close_tun(struct context *c, bool force)
2029 {
2030  /* With dco-win we open tun handle in the very beginning.
2031  * In case when tun wasn't opened - like we haven't connected,
2032  * we still need to close tun handle
2033  */
2035  {
2037  return;
2038  }
2039 
2040  if (!c->c1.tuntap || !c->c1.tuntap_owned)
2041  {
2042  return;
2043  }
2044 
2045  struct gc_arena gc = gc_new();
2046  const char *tuntap_actual = string_alloc(c->c1.tuntap->actual_name, &gc);
2047 #ifdef _WIN32
2048  DWORD adapter_index = c->c1.tuntap->adapter_index;
2049 #endif
2050  const in_addr_t local = c->c1.tuntap->local;
2051  const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
2052 
2053  if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
2054  {
2055  static_context = NULL;
2056 
2057 #ifdef ENABLE_MANAGEMENT
2058  /* tell management layer we are about to close the TUN/TAP device */
2059  if (management)
2060  {
2062  management_up_down(management, "DOWN", c->c2.es);
2063  }
2064 #endif
2065 
2066  /* delete any routes we added */
2067  if (c->c1.route_list || c->c1.route_ipv6_list)
2068  {
2070  c->plugins,
2072  tuntap_actual,
2073 #ifdef _WIN32
2074  adapter_index,
2075 #endif
2076  NULL,
2077  c->c2.frame.tun_mtu,
2078  print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2079  print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2080  "init",
2082  c->sig->signal_text),
2083  "route-pre-down",
2084  c->c2.es);
2085 
2088  c->c2.es, &c->net_ctx);
2089  }
2090 
2091  /* actually close tun/tap device based on --down-pre flag */
2092  if (!c->options.down_pre)
2093  {
2095  }
2096 
2097  /* Run the down script -- note that it will run at reduced
2098  * privilege if, for example, "--user" was used. */
2100  c->plugins,
2102  tuntap_actual,
2103 #ifdef _WIN32
2104  adapter_index,
2105 #endif
2106  NULL,
2107  c->c2.frame.tun_mtu,
2108  print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2109  print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2110  "init",
2112  c->sig->signal_text),
2113  "down",
2114  c->c2.es);
2115 
2116 #if defined(_WIN32)
2117  if (c->options.block_outside_dns)
2118  {
2119  if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
2120  {
2121  msg(M_FATAL, "Uninitialising WFP failed!");
2122  }
2123  }
2124 #endif
2125 
2126  /* actually close tun/tap device based on --down-pre flag */
2127  if (c->options.down_pre)
2128  {
2130  }
2131  }
2132  else
2133  {
2134  /* run the down script on this restart if --up-restart was specified */
2135  if (c->options.up_restart)
2136  {
2138  c->plugins,
2140  tuntap_actual,
2141 #ifdef _WIN32
2142  adapter_index,
2143 #endif
2144  NULL,
2145  c->c2.frame.tun_mtu,
2146  print_in_addr_t(local, IA_EMPTY_IF_UNDEF, &gc),
2147  print_in_addr_t(remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
2148  "restart",
2150  c->sig->signal_text),
2151  "down",
2152  c->c2.es);
2153  }
2154 
2155 #if defined(_WIN32)
2156  if (c->options.block_outside_dns)
2157  {
2158  if (!win_wfp_uninit(adapter_index, c->options.msg_channel))
2159  {
2160  msg(M_FATAL, "Uninitialising WFP failed!");
2161  }
2162  }
2163 #endif
2164 
2165  }
2166  gc_free(&gc);
2167 }
2168 
2169 void
2171 {
2172  struct context *c = static_context;
2173  if (c)
2174  {
2175  static_context = NULL;
2176  do_close_tun(c, true);
2177  }
2178 }
2179 
2180 /*
2181  * Handle delayed tun/tap interface bringup due to --up-delay or --pull
2182  */
2183 
2188 static bool
2190  const struct sha256_digest *b)
2191 {
2192  const struct sha256_digest zero = {{0}};
2193  return memcmp(a, b, sizeof(struct sha256_digest))
2194  || !memcmp(a, &zero, sizeof(struct sha256_digest));
2195 }
2196 
2197 static bool
2199 {
2200  if (dco_enabled(&c->options)
2201  && (c->options.ping_send_timeout || c->c2.frame.mss_fix))
2202  {
2203  int ret = dco_set_peer(&c->c1.tuntap->dco,
2204  c->c2.tls_multi->dco_peer_id,
2207  c->c2.frame.mss_fix);
2208  if (ret < 0)
2209  {
2210  msg(D_DCO, "Cannot set parameters for DCO peer (id=%u): %s",
2211  c->c2.tls_multi->dco_peer_id, strerror(-ret));
2212  return false;
2213  }
2214  }
2215  return true;
2216 }
2217 
2223 static void
2224 add_delim_if_non_empty(struct buffer *buf, const char *header)
2225 {
2226  if (buf_len(buf) > strlen(header))
2227  {
2228  buf_printf(buf, ", ");
2229  }
2230 }
2231 
2232 
2237 static void
2239 {
2240  struct options *o = &c->options;
2241 
2242  struct buffer out;
2243  uint8_t line[1024] = { 0 };
2244  buf_set_write(&out, line, sizeof(line));
2245 
2246 
2248  {
2249  buf_printf(&out, "Data Channel: cipher '%s'",
2251  }
2252  else
2253  {
2254  buf_printf(&out, "Data Channel: cipher '%s', auth '%s'",
2256  }
2257 
2258  if (o->use_peer_id)
2259  {
2260  buf_printf(&out, ", peer-id: %d", o->peer_id);
2261  }
2262 
2263 #ifdef USE_COMP
2264  if (c->c2.comp_context)
2265  {
2266  buf_printf(&out, ", compression: '%s'", c->c2.comp_context->alg.name);
2267  }
2268 #endif
2269 
2270  msg(D_HANDSHAKE, "%s", BSTR(&out));
2271 
2272  buf_clear(&out);
2273 
2274  const char *header = "Timers: ";
2275 
2276  buf_printf(&out, "%s", header);
2277 
2278  if (o->ping_send_timeout)
2279  {
2280  buf_printf(&out, "ping %d", o->ping_send_timeout);
2281  }
2282 
2284  {
2285  /* yes unidirectional ping is possible .... */
2286  add_delim_if_non_empty(&out, header);
2287 
2289  {
2290  buf_printf(&out, "ping-exit %d", o->ping_rec_timeout);
2291  }
2292  else
2293  {
2294  buf_printf(&out, "ping-restart %d", o->ping_rec_timeout);
2295  }
2296  }
2297 
2298  if (o->inactivity_timeout)
2299  {
2300  add_delim_if_non_empty(&out, header);
2301 
2302  buf_printf(&out, "inactive %d", o->inactivity_timeout);
2303  if (o->inactivity_minimum_bytes)
2304  {
2305  buf_printf(&out, " %" PRIu64, o->inactivity_minimum_bytes);
2306  }
2307  }
2308 
2309  if (o->session_timeout)
2310  {
2311  add_delim_if_non_empty(&out, header);
2312  buf_printf(&out, "session-timeout %d", o->session_timeout);
2313  }
2314 
2315  if (buf_len(&out) > strlen(header))
2316  {
2317  msg(D_HANDSHAKE, "%s", BSTR(&out));
2318  }
2319 
2320  buf_clear(&out);
2321  header = "Protocol options: ";
2322  buf_printf(&out, "%s", header);
2323 
2325  {
2326  buf_printf(&out, "explicit-exit-notify %d",
2328  }
2330  {
2331  add_delim_if_non_empty(&out, header);
2332 
2333  buf_printf(&out, "protocol-flags");
2334 
2336  {
2337  buf_printf(&out, " cc-exit");
2338  }
2340  {
2341  buf_printf(&out, " tls-ekm");
2342  }
2344  {
2345  buf_printf(&out, " dyn-tls-crypt");
2346  }
2347  }
2348 
2349  if (buf_len(&out) > strlen(header))
2350  {
2351  msg(D_HANDSHAKE, "%s", BSTR(&out));
2352  }
2353 }
2354 
2355 
2363 static bool
2365 {
2366  struct frame *frame_fragment = NULL;
2367 #ifdef ENABLE_FRAGMENT
2368  if (c->options.ce.fragment)
2369  {
2370  frame_fragment = &c->c2.frame_fragment;
2371  }
2372 #endif
2373 
2374  struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2376  &c->options, &c->c2.frame,
2377  frame_fragment,
2379  {
2380  msg(D_TLS_ERRORS, "OPTIONS ERROR: failed to import crypto options");
2381  return false;
2382  }
2383 
2384  return true;
2385 }
2386 
2387 bool
2388 do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
2389 {
2390  int error_flags = 0;
2391  if (!c->c2.do_up_ran)
2392  {
2394 
2395  if (pulled_options)
2396  {
2397  if (!do_deferred_options(c, option_types_found))
2398  {
2399  msg(D_PUSH_ERRORS, "ERROR: Failed to apply push options");
2400  return false;
2401  }
2402  }
2403 
2404  /* if --up-delay specified, open tun, do ifconfig, and run up script now */
2405  if (c->options.up_delay || PULL_DEFINED(&c->options))
2406  {
2407  c->c2.did_open_tun = do_open_tun(c, &error_flags);
2408  update_time();
2409 
2410  /*
2411  * Was tun interface object persisted from previous restart iteration,
2412  * and if so did pulled options string change from previous iteration?
2413  */
2414  if (!c->c2.did_open_tun
2415  && PULL_DEFINED(&c->options)
2416  && c->c1.tuntap
2419  {
2420  /* if so, close tun, delete routes, then reinitialize tun and add routes */
2421  msg(M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
2422 
2423  bool tt_dco_win = tuntap_is_dco_win(c->c1.tuntap);
2424  do_close_tun(c, true);
2425 
2426  if (tt_dco_win)
2427  {
2428  msg(M_NONFATAL, "dco-win doesn't yet support reopening TUN device");
2429  /* prevent link_socket_close() from closing handle with WinSock API */
2431  return false;
2432  }
2433  else
2434  {
2435  management_sleep(1);
2436  c->c2.did_open_tun = do_open_tun(c, &error_flags);
2437  update_time();
2438  }
2439  }
2440  }
2441  }
2442 
2443  /* This part needs to be run in p2p mode (without pull) when the client
2444  * reconnects to setup various things (like DCO and NCP cipher) that
2445  * might have changed from the previous connection.
2446  */
2448  {
2449  if (c->mode == MODE_POINT_TO_POINT)
2450  {
2451  /* ovpn-dco requires adding the peer now, before any option can be set,
2452  * but *after* having parsed the pushed peer-id in do_deferred_options()
2453  */
2454  int ret = dco_p2p_add_new_peer(c);
2455  if (ret < 0)
2456  {
2457  msg(D_DCO, "Cannot add peer to DCO: %s (%d)", strerror(-ret), ret);
2458  return false;
2459  }
2460  }
2461 
2462  /* do_deferred_options_part2() and do_deferred_p2p_ncp() *must* be
2463  * invoked after open_tun().
2464  * This is required by DCO because we must have created the interface
2465  * and added the peer before we can fiddle with the keys or any other
2466  * data channel per-peer setting.
2467  */
2468  if (pulled_options)
2469  {
2470  if (!do_deferred_options_part2(c))
2471  {
2472  return false;
2473  }
2474  }
2475  else
2476  {
2477  if (c->mode == MODE_POINT_TO_POINT)
2478  {
2479  if (!do_deferred_p2p_ncp(c))
2480  {
2481  msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
2482  return false;
2483  }
2484  }
2485  }
2486 
2488  {
2489  msg(D_TLS_ERRORS, "ERROR: Failed to apply DCO keepalive or MSS fix parameters");
2490  return false;
2491  }
2492 
2493  if (c->c2.did_open_tun)
2494  {
2496 
2497  /* if --route-delay was specified, start timer */
2499  {
2502  if (c->c1.tuntap)
2503  {
2505  }
2506  }
2507  else
2508  {
2509  initialization_sequence_completed(c, error_flags); /* client/p2p --route-delay undefined */
2510  }
2511  }
2512  else if (c->options.mode == MODE_POINT_TO_POINT)
2513  {
2514  initialization_sequence_completed(c, error_flags); /* client/p2p restart with --persist-tun */
2515  }
2516 
2518 
2519  c->c2.do_up_ran = true;
2520  if (c->c2.tls_multi)
2521  {
2523  }
2524  }
2525  return true;
2526 }
2527 
2528 /*
2529  * These are the option categories which will be accepted by pull.
2530  */
2531 unsigned int
2533 {
2534  unsigned int flags =
2535  OPT_P_UP
2537  | OPT_P_SOCKBUF
2538  | OPT_P_SOCKFLAGS
2539  | OPT_P_SETENV
2540  | OPT_P_SHAPER
2541  | OPT_P_TIMER
2542  | OPT_P_COMP
2543  | OPT_P_PERSIST
2544  | OPT_P_MESSAGES
2546  | OPT_P_ECHO
2547  | OPT_P_PULL_MODE
2548  | OPT_P_PEER_ID
2549  | OPT_P_NCP
2550  | OPT_P_PUSH_MTU;
2551 
2552  if (!c->options.route_nopull)
2553  {
2554  flags |= (OPT_P_ROUTE | OPT_P_DHCPDNS);
2555  }
2556 
2557  return flags;
2558 }
2559 
2560 static bool
2562 {
2563  if (!c->c2.tls_multi)
2564  {
2565  return true;
2566  }
2567 
2569 
2570  struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
2571 
2572  const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,
2573  &c->options.gc);
2574 
2575  if (ncp_cipher)
2576  {
2577  c->options.ciphername = ncp_cipher;
2578  }
2579  else if (!c->options.enable_ncp_fallback)
2580  {
2581  msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
2582  "--data-ciphers-fallback not enabled. No usable "
2583  "data channel cipher");
2584  return false;
2585  }
2586 
2587  struct frame *frame_fragment = NULL;
2588 #ifdef ENABLE_FRAGMENT
2589  if (c->options.ce.fragment)
2590  {
2591  frame_fragment = &c->c2.frame_fragment;
2592  }
2593 #endif
2594 
2596  &c->c2.frame, frame_fragment,
2598  {
2599  msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
2600  return false;
2601  }
2602  return true;
2603 }
2604 
2605 /*
2606  * Handle non-tun-related pulled options.
2607  */
2608 bool
2609 do_deferred_options(struct context *c, const unsigned int found)
2610 {
2611  if (found & OPT_P_MESSAGES)
2612  {
2614  msg(D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
2615  }
2616  if (found & OPT_P_TIMER)
2617  {
2618  do_init_timers(c, true);
2619  msg(D_PUSH_DEBUG, "OPTIONS IMPORT: timers and/or timeouts modified");
2620  }
2621 
2622  if (found & OPT_P_EXPLICIT_NOTIFY)
2623  {
2625  {
2626  msg(D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
2628  }
2629  else
2630  {
2631  msg(D_PUSH_DEBUG, "OPTIONS IMPORT: explicit notify parm(s) modified");
2632  }
2633  }
2634 
2635  if (found & OPT_P_COMP)
2636  {
2638  {
2639  msg(D_PUSH_ERRORS, "OPTIONS ERROR: server pushed compression "
2640  "settings that are not allowed and will result "
2641  "in a non-working connection. "
2642  "See also allow-compression in the manual.");
2643  return false;
2644  }
2645 #ifdef USE_COMP
2646  msg(D_PUSH_DEBUG, "OPTIONS IMPORT: compression parms modified");
2647  comp_uninit(c->c2.comp_context);
2648  c->c2.comp_context = comp_init(&c->options.comp);
2649 #endif
2650  }
2651 
2652  if (found & OPT_P_SHAPER)
2653  {
2654  msg(D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
2656  }
2657 
2658  if (found & OPT_P_SOCKBUF)
2659  {
2660  msg(D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
2662  }
2663 
2664  if (found & OPT_P_SOCKFLAGS)
2665  {
2666  msg(D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
2668  }
2669 
2670  if (found & OPT_P_PERSIST)
2671  {
2672  msg(D_PUSH, "OPTIONS IMPORT: --persist options modified");
2673  }
2674  if (found & OPT_P_UP)
2675  {
2676  msg(D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
2677  }
2678  if (found & OPT_P_ROUTE)
2679  {
2680  msg(D_PUSH, "OPTIONS IMPORT: route options modified");
2681  }
2682  if (found & OPT_P_ROUTE_EXTRAS)
2683  {
2684  msg(D_PUSH, "OPTIONS IMPORT: route-related options modified");
2685  }
2686  if (found & OPT_P_DHCPDNS)
2687  {
2688  msg(D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
2689  }
2690  if (found & OPT_P_SETENV)
2691  {
2692  msg(D_PUSH, "OPTIONS IMPORT: environment modified");
2693  }
2694 
2695  if (found & OPT_P_PEER_ID)
2696  {
2697  msg(D_PUSH_DEBUG, "OPTIONS IMPORT: peer-id set");
2698  c->c2.tls_multi->use_peer_id = true;
2699  c->c2.tls_multi->peer_id = c->options.peer_id;
2700  }
2701 
2702  /* process (potentially) pushed options */
2703  if (c->options.pull)
2704  {
2705  if (!check_pull_client_ncp(c, found))
2706  {
2707  return false;
2708  }
2709 
2710  /* Check if pushed options are compatible with DCO, if enabled */
2711  if (dco_enabled(&c->options)
2713  {
2714  msg(D_PUSH_ERRORS, "OPTIONS ERROR: pushed options are incompatible "
2715  "with data channel offload. Use --disable-dco to connect to "
2716  "this server");
2717  return false;
2718  }
2719  }
2720 
2721  if (found & OPT_P_PUSH_MTU)
2722  {
2723  /* MTU has changed, check that the pushed MTU is small enough to
2724  * be able to change it */
2725  msg(D_PUSH, "OPTIONS IMPORT: tun-mtu set to %d", c->options.ce.tun_mtu);
2726 
2727  struct frame *frame = &c->c2.frame;
2728 
2729  if (c->options.ce.tun_mtu > frame->tun_max_mtu)
2730  {
2731  msg(D_PUSH_ERRORS, "Server-pushed tun-mtu is too large, please add "
2732  "tun-mtu-max %d in the client configuration",
2733  c->options.ce.tun_mtu);
2734  }
2736  }
2737 
2738  return true;
2739 }
2740 
2741 /*
2742  * Possible hold on initialization, holdtime is the
2743  * time OpenVPN would wait without management
2744  */
2745 static bool
2746 do_hold(int holdtime)
2747 {
2748 #ifdef ENABLE_MANAGEMENT
2749  if (management)
2750  {
2751  /* block until management hold is released */
2752  if (management_hold(management, holdtime))
2753  {
2754  return true;
2755  }
2756  }
2757 #endif
2758  return false;
2759 }
2760 
2761 /*
2762  * Sleep before restart.
2763  */
2764 static void
2766 {
2767  int sec = 2;
2768  int backoff = 0;
2769 
2770  switch (c->options.ce.proto)
2771  {
2772  case PROTO_TCP_SERVER:
2773  sec = 1;
2774  break;
2775 
2776  case PROTO_UDP:
2777  case PROTO_TCP_CLIENT:
2778  sec = c->options.ce.connect_retry_seconds;
2779  break;
2780  }
2781 
2782 #ifdef ENABLE_DEBUG
2783  if (GREMLIN_CONNECTION_FLOOD_LEVEL(c->options.gremlin))
2784  {
2785  sec = 0;
2786  }
2787 #endif
2788 
2789  if (auth_retry_get() == AR_NOINTERACT)
2790  {
2791  sec = 10;
2792  }
2793 
2794  /* Slow down reconnection after 5 retries per remote -- for TCP client or UDP tls-client only */
2795  if (c->options.ce.proto == PROTO_TCP_CLIENT
2796  || (c->options.ce.proto == PROTO_UDP && c->options.tls_client))
2797  {
2798  backoff = (c->options.unsuccessful_attempts / c->options.connection_list->len) - 4;
2799  if (backoff > 0)
2800  {
2801  /* sec is less than 2^16; we can left shift it by up to 15 bits without overflow */
2802  sec = max_int(sec, 1) << min_int(backoff, 15);
2803  }
2805  {
2806  sec = max_int(sec, c->options.server_backoff_time);
2808  }
2809 
2810  if (sec > c->options.ce.connect_retry_seconds_max)
2811  {
2813  }
2814  }
2815 
2817  {
2818  sec = c->persist.restart_sleep_seconds;
2819  }
2820  else if (c->persist.restart_sleep_seconds == -1)
2821  {
2822  sec = 0;
2823  }
2825 
2826  /* do management hold on context restart, i.e. second, third, fourth, etc. initialization */
2827  if (do_hold(sec))
2828  {
2829  sec = 0;
2830  }
2831 
2832  if (sec)
2833  {
2834  msg(D_RESTART, "Restart pause, %d second(s)", sec);
2835  management_sleep(sec);
2836  }
2837 }
2838 
2839 /*
2840  * Do a possible pause on context_2 initialization.
2841  */
2842 static void
2844 {
2845  if (!c->first_time)
2846  {
2848  }
2849  else
2850  {
2851  do_hold(0); /* do management hold on first context initialization */
2852  }
2853 }
2854 
2855 static size_t
2856 get_frame_mtu(struct context *c, const struct options *o)
2857 {
2858  size_t mtu;
2859 
2860  if (o->ce.link_mtu_defined)
2861  {
2863  /* if we have a link mtu defined we calculate what the old code
2864  * would have come up with as tun-mtu */
2865  size_t overhead = frame_calculate_protocol_header_size(&c->c1.ks.key_type,
2866  o, true);
2867  mtu = o->ce.link_mtu - overhead;
2868 
2869  }
2870  else
2871  {
2873  mtu = o->ce.tun_mtu;
2874  }
2875 
2876  if (mtu < TUN_MTU_MIN)
2877  {
2878  msg(M_WARN, "TUN MTU value (%zu) must be at least %d", mtu, TUN_MTU_MIN);
2879  frame_print(&c->c2.frame, M_FATAL, "MTU is too small");
2880  }
2881  return mtu;
2882 }
2883 
2884 /*
2885  * Finalize MTU parameters based on command line or config file options.
2886  */
2887 static void
2888 frame_finalize_options(struct context *c, const struct options *o)
2889 {
2890  if (!o)
2891  {
2892  o = &c->options;
2893  }
2894 
2895  struct frame *frame = &c->c2.frame;
2896 
2897  frame->tun_mtu = get_frame_mtu(c, o);
2899 
2900  /* max mtu needs to be at least as large as the tun mtu */
2902 
2903  /* We always allow at least 1600 MTU packets to be received in our buffer
2904  * space to allow server to push "baby giant" MTU sizes */
2906 
2907  size_t payload_size = frame->tun_max_mtu;
2908 
2909  /* we need to be also large enough to hold larger control channel packets
2910  * if configured */
2912 
2913  /* The extra tun needs to be added to the payload size */
2914  if (o->ce.tun_mtu_defined)
2915  {
2917  }
2918 
2919  /* Add 32 byte of extra space in the buffer to account for small errors
2920  * in the calculation */
2921  payload_size += 32;
2922 
2923 
2924  /* the space that is reserved before the payload to add extra headers to it
2925  * we always reserve the space for the worst case */
2926  size_t headroom = 0;
2927 
2928  /* includes IV and packet ID */
2930 
2931  /* peer id + opcode */
2932  headroom += 4;
2933 
2934  /* socks proxy header */
2935  headroom += 10;
2936 
2937  /* compression header and fragment header (part of the encrypted payload) */
2938  headroom += 1 + 1;
2939 
2940  /* Round up headroom to the next multiple of 4 to ensure alignment */
2941  headroom = (headroom + 3) & ~3;
2942 
2943  /* Add the headroom to the payloadsize as a received (IP) packet can have
2944  * all the extra headers in it */
2946 
2947  /* the space after the payload, this needs some extra buffer space for
2948  * encryption so headroom is probably too much but we do not really care
2949  * the few extra bytes */
2950  size_t tailroom = headroom;
2951 
2952 #ifdef USE_COMP
2953  msg(D_MTU_DEBUG, "MTU: adding %zu buffer tailroom for compression for %zu "
2954  "bytes of payload",
2955  COMP_EXTRA_BUFFER(payload_size), payload_size);
2956  tailroom += COMP_EXTRA_BUFFER(payload_size);
2957 #endif
2958 
2962 }
2963 
2964 /*
2965  * Free a key schedule, including OpenSSL components.
2966  */
2967 static void
2968 key_schedule_free(struct key_schedule *ks, bool free_ssl_ctx)
2969 {
2971  if (tls_ctx_initialised(&ks->ssl_ctx) && free_ssl_ctx)
2972  {
2973  tls_ctx_free(&ks->ssl_ctx);
2975  }
2976  CLEAR(*ks);
2977 }
2978 
2979 static void
2980 init_crypto_pre(struct context *c, const unsigned int flags)
2981 {
2982  if (c->options.engine)
2983  {
2985  }
2986 
2987  if (flags & CF_LOAD_PERSISTED_PACKET_ID)
2988  {
2989  /* load a persisted packet-id for cross-session replay-protection */
2990  if (c->options.packet_id_file)
2991  {
2993  }
2994  }
2995 
2996 #ifdef ENABLE_PREDICTION_RESISTANCE
2997  if (c->options.use_prediction_resistance)
2998  {
2999  rand_ctx_enable_prediction_resistance();
3000  }
3001 #endif
3002 }
3003 
3004 /*
3005  * Static Key Mode (using a pre-shared key)
3006  */
3007 static void
3008 do_init_crypto_static(struct context *c, const unsigned int flags)
3009 {
3010  const struct options *options = &c->options;
3012 
3013  init_crypto_pre(c, flags);
3014 
3015  /* Initialize flags */
3017  {
3019  }
3020 
3021  /* Initialize packet ID tracking */
3022  if (options->replay)
3023  {
3027  "STATIC", 0);
3032  }
3033 
3034  if (!key_ctx_bi_defined(&c->c1.ks.static_key))
3035  {
3036  /* Get cipher & hash algorithms */
3038  options->test_crypto, true);
3039 
3040  /* Read cipher and hmac keys from shared secret file */
3044  options->key_direction, "Static Key Encryption",
3045  "secret", NULL);
3046  }
3047  else
3048  {
3049  msg(M_INFO, "Re-using pre-shared static key");
3050  }
3051 
3052  /* Get key schedule */
3054 
3055  /* Sanity check on sequence number, and cipher mode options */
3057 }
3058 
3059 /*
3060  * Initialize the tls-auth/crypt key context
3061  */
3062 static void
3064 {
3065  const struct options *options = &c->options;
3066 
3067  /* TLS handshake authentication (--tls-auth) */
3068  if (options->ce.tls_auth_file)
3069  {
3070  /* Initialize key_type for tls-auth with auth only */
3072  c->c1.ks.tls_auth_key_type.cipher = "none";
3074  if (!md_valid(options->authname))
3075  {
3076  msg(M_FATAL, "ERROR: tls-auth enabled, but no valid --auth "
3077  "algorithm specified ('%s')", options->authname);
3078  }
3079 
3081  &c->c1.ks.tls_wrap_key,
3085  "Control Channel Authentication", "tls-auth",
3087  }
3088 
3089  /* TLS handshake encryption+authentication (--tls-crypt) */
3090  if (options->ce.tls_crypt_file)
3091  {
3096  options->tls_server);
3097  }
3098 
3099  /* tls-crypt with client-specific keys (--tls-crypt-v2) */
3101  {
3102  if (options->tls_server)
3103  {
3105  true, options->ce.tls_crypt_v2_file,
3107  }
3108  else
3109  {
3112  &c->c1.ks.tls_crypt_v2_wkc,
3115  }
3116  /* We have to ensure that the loaded tls-crypt key is small enough
3117  * to fit into the initial hard reset v3 packet */
3118  int wkc_len = buf_len(&c->c1.ks.tls_crypt_v2_wkc);
3119 
3120  /* empty ACK/message id, tls-crypt, Opcode, UDP, ipv6 */
3121  int required_size = 5 + wkc_len + tls_crypt_buf_overhead() + 1 + 8 + 40;
3122 
3123  if (required_size > c->options.ce.tls_mtu)
3124  {
3125  msg(M_WARN, "ERROR: tls-crypt-v2 client key too large to work with "
3126  "requested --max-packet-size %d, requires at least "
3127  "--max-packet-size %d. Packets will ignore requested "
3128  "maximum packet size", c->options.ce.tls_mtu,
3129  required_size);
3130  }
3131  }
3132 
3133 
3134 }
3135 
3136 /*
3137  * Initialize the persistent component of OpenVPN's TLS mode,
3138  * which is preserved across SIGUSR1 resets.
3139  */
3140 static void
3142 {
3143  const struct options *options = &c->options;
3144 
3145  if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
3146  {
3147  /*
3148  * Initialize the OpenSSL library's global
3149  * SSL context.
3150  */
3151  init_ssl(options, &(c->c1.ks.ssl_ctx), c->c0 && c->c0->uid_gid_chroot_set);
3152  if (!tls_ctx_initialised(&c->c1.ks.ssl_ctx))
3153  {
3154  switch (auth_retry_get())
3155  {
3156  case AR_NONE:
3157  msg(M_FATAL, "Error: private key password verification failed");
3158  break;
3159 
3160  case AR_INTERACT:
3161  ssl_purge_auth(false);
3162  /* Intentional [[fallthrough]]; */
3163 
3164  case AR_NOINTERACT:
3165  /* SOFT-SIGUSR1 -- Password failure error */
3166  register_signal(c->sig, SIGUSR1, "private-key-password-failure");
3167  break;
3168 
3169  default:
3170  ASSERT(0);
3171  }
3172  return;
3173  }
3174 
3175  /*
3176  * BF-CBC is allowed to be used only when explicitly configured
3177  * as NCP-fallback or when NCP has been disabled or explicitly
3178  * allowed in the in ncp_ciphers list.
3179  * In all other cases do not attempt to initialize BF-CBC as it
3180  * may not even be supported by the underlying SSL library.
3181  *
3182  * Therefore, the key structure has to be initialized when:
3183  * - any non-BF-CBC cipher was selected; or
3184  * - BF-CBC is selected, NCP is enabled and fallback is enabled
3185  * (BF-CBC will be the fallback).
3186  * - BF-CBC is in data-ciphers and we negotiate to use BF-CBC:
3187  * If the negotiated cipher and options->ciphername are the
3188  * same we do not reinit the cipher
3189  *
3190  * Note that BF-CBC will still be part of the OCC string to retain
3191  * backwards compatibility with older clients.
3192  */
3193  const char *ciphername = options->ciphername;
3194  if (streq(options->ciphername, "BF-CBC")
3197  {
3198  ciphername = "none";
3199  }
3200 
3201  /* Do not warn if the cipher is used only in OCC */
3202  bool warn = options->enable_ncp_fallback;
3204  true, warn);
3205 
3206  /* initialize tls-auth/crypt/crypt-v2 key */
3208 
3209  /* initialise auth-token crypto support */
3211  {
3215  }
3216 
3217 #if 0 /* was: #if ENABLE_INLINE_FILES -- Note that enabling this code will break restarts */
3219  {
3221  c->options.priv_key_file_inline = NULL;
3222  }
3223 #endif
3224  }
3225  else
3226  {
3227  msg(D_INIT_MEDIUM, "Re-using SSL/TLS context");
3228 
3229  /*
3230  * tls-auth/crypt key can be configured per connection block, therefore
3231  * we must reload it as it may have changed
3232  */
3234  }
3235 }
3236 
3237 static void
3238 do_init_crypto_tls(struct context *c, const unsigned int flags)
3239 {
3240  const struct options *options = &c->options;
3241  struct tls_options to;
3242  bool packet_id_long_form;
3243 
3246 
3247  init_crypto_pre(c, flags);
3248 
3249  /* Make sure we are either a TLS client or server but not both */
3251 
3252  /* initialize persistent component */
3254  if (IS_SIG(c))
3255  {
3256  return;
3257  }
3258 
3259  /* Sanity check on sequence number, and cipher mode options */
3261 
3262  /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
3263  packet_id_long_form = cipher_kt_mode_ofb_cfb(c->c1.ks.key_type.cipher);
3264 
3265  /* Set all command-line TLS-related options */
3266  CLEAR(to);
3267 
3269  {
3271  }
3272 
3274  if (packet_id_long_form)
3275  {
3277  }
3278 
3279  to.ssl_ctx = c->c1.ks.ssl_ctx;
3280  to.key_type = c->c1.ks.key_type;
3281  to.server = options->tls_server;
3282  to.replay = options->replay;
3294  {
3295  /* Add 10% jitter to reneg-sec by default (server side only) */
3296  int auto_jitter = options->mode != MODE_SERVER ? 0 :
3298  to.renegotiate_seconds = options->renegotiate_seconds - auto_jitter;
3299  }
3300  else
3301  {
3302  /* Add user-specified jitter to reneg-sec */
3306  }
3308  to.mode = options->mode;
3309  to.pull = options->pull;
3310  if (options->push_peer_info) /* all there is */
3311  {
3312  to.push_peer_info_detail = 3;
3313  }
3314  else if (options->pull) /* pull clients send some details */
3315  {
3316  to.push_peer_info_detail = 2;
3317  }
3318  else if (options->mode == MODE_SERVER) /* server: no peer info at all */
3319  {
3320  to.push_peer_info_detail = 0;
3321  }
3322  else /* default: minimal info to allow NCP in P2P mode */
3323  {
3324  to.push_peer_info_detail = 1;
3325  }
3326 
3327 
3328  /* should we not xmit any packets until we get an initial
3329  * response from client? */
3330  if (to.server && options->ce.proto == PROTO_TCP_SERVER)
3331  {
3332  to.xmit_hold = true;
3333  }
3334 
3337  to.verify_x509_type = (options->verify_x509_type & 0xff);
3339  to.crl_file = options->crl_file;
3341  to.ssl_flags = options->ssl_flags;
3343  memcpy(to.remote_cert_ku, options->remote_cert_ku, sizeof(to.remote_cert_ku));
3349 #ifdef ENABLE_X509ALTUSERNAME
3350  memcpy(to.x509_username_field, options->x509_username_field, sizeof(to.x509_username_field));
3351 #else
3353 #endif
3354  to.es = c->c2.es;
3355  to.net_ctx = &c->net_ctx;
3356 
3357 #ifdef ENABLE_DEBUG
3358  to.gremlin = c->options.gremlin;
3359 #endif
3360 
3361  to.plugins = c->plugins;
3362 
3363 #ifdef ENABLE_MANAGEMENT
3364  to.mda_context = &c->c2.mda_context;
3365 #endif
3366 
3370  to.tmp_dir = options->tmp_dir;
3371  if (options->ccd_exclusive)
3372  {
3374  }
3382 
3384 
3385 #ifdef ENABLE_MANAGEMENT
3386  to.sci = &options->sc_info;
3387 #endif
3388 
3389 #ifdef USE_COMP
3390  to.comp_options = options->comp;
3391 #endif
3392 
3393 #ifdef HAVE_EXPORT_KEYING_MATERIAL
3394  if (options->keying_material_exporter_label)
3395  {
3396  to.ekm_size = options->keying_material_exporter_length;
3397  if (to.ekm_size < 16 || to.ekm_size > 4095)
3398  {
3399  to.ekm_size = 0;
3400  }
3401 
3402  to.ekm_label = options->keying_material_exporter_label;
3403  to.ekm_label_size = strlen(to.ekm_label);
3404  }
3405  else
3406  {
3407  to.ekm_size = 0;
3408  }
3409 #endif /* HAVE_EXPORT_KEYING_MATERIAL */
3410 
3411  /* TLS handshake authentication (--tls-auth) */
3412  if (options->ce.tls_auth_file)
3413  {
3414  to.tls_wrap.mode = TLS_WRAP_AUTH;
3415  }
3416 
3417  /* TLS handshake encryption (--tls-crypt) */
3420  {
3421  to.tls_wrap.mode = TLS_WRAP_CRYPT;
3422  }
3423 
3424  if (to.tls_wrap.mode == TLS_WRAP_AUTH || to.tls_wrap.mode == TLS_WRAP_CRYPT)
3425  {
3430  }
3431 
3433  {
3434  to.tls_crypt_v2 = true;
3436 
3437  if (options->tls_server)
3438  {
3442  {
3444  }
3445  }
3446  }
3447 
3448  /* let the TLS engine know if keys have to be installed in DCO or not */
3450 
3451  /*
3452  * Initialize OpenVPN's master TLS-mode object.
3453  */
3454  if (flags & CF_INIT_TLS_MULTI)
3455  {
3456  c->c2.tls_multi = tls_multi_init(&to);
3457  /* inherit the dco context from the tuntap object */
3458  if (c->c1.tuntap)
3459  {
3460  c->c2.tls_multi->dco = &c->c1.tuntap->dco;
3461  }
3462  }
3463 
3464  if (flags & CF_INIT_TLS_AUTH_STANDALONE)
3465  {
3468  }
3469 }
3470 
3471 static void
3473 {
3474  if (c->c2.tls_multi)
3475  {
3478  c->c2.frame.buf.payload_size);
3480  "Control Channel MTU parms");
3481 
3482  /* Keep the max mtu also in the frame of tls multi so it can access
3483  * it in push_peer_info */
3485  }
3486  if (c->c2.tls_auth_standalone)
3487  {
3490  "TLS-Auth MTU parms");
3493  }
3494 }
3495 
3496 /*
3497  * No encryption or authentication.
3498  */
3499 static void
3501 {
3502  ASSERT(!c->options.test_crypto);
3503 
3504  /* Initialise key_type with auth/cipher "none", so the key_type struct is
3505  * valid */
3506  init_key_type(&c->c1.ks.key_type, "none", "none",
3507  c->options.test_crypto, true);
3508 
3509  msg(M_WARN,
3510  "******* WARNING *******: All encryption and authentication features "
3511  "disabled -- All data will be tunnelled as clear text and will not be "
3512  "protected against man-in-the-middle changes. "
3513  "PLEASE DO RECONSIDER THIS CONFIGURATION!");
3514 }
3515 
3516 static void
3517 do_init_crypto(struct context *c, const unsigned int flags)
3518 {
3519  if (c->options.shared_secret_file)
3520  {
3521  do_init_crypto_static(c, flags);
3522  }
3523  else if (c->options.tls_server || c->options.tls_client)
3524  {
3525  do_init_crypto_tls(c, flags);
3526  }
3527  else /* no encryption or authentication. */
3528  {
3530  }
3531 }
3532 
3533 static void
3535 {
3536  /*
3537  * Adjust frame size based on the --tun-mtu-extra parameter.
3538  */
3540  {
3542  }
3543 
3544  /*
3545  * Fill in the blanks in the frame parameters structure,
3546  * make sure values are rational, etc.
3547  */
3548  frame_finalize_options(c, NULL);
3549 
3550 #ifdef ENABLE_FRAGMENT
3551  /*
3552  * Set frame parameter for fragment code. This is necessary because
3553  * the fragmentation code deals with payloads which have already been
3554  * passed through the compression code.
3555  */
3556  c->c2.frame_fragment = c->c2.frame;
3558 #endif
3559 
3560 #if defined(ENABLE_FRAGMENT)
3561  /*
3562  * MTU advisories
3563  */
3564  if (c->options.ce.fragment && c->options.mtu_test)
3565  {
3566  msg(M_WARN,
3567  "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
3568  }
3569 #endif
3570 
3571 #ifdef ENABLE_FRAGMENT
3572  if (c->options.ce.fragment > 0 && c->options.ce.mssfix > c->options.ce.fragment)
3573  {
3574  msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should "
3575  "set --fragment (%d) larger or equal than --mssfix (%d)",
3576  c->options.ce.fragment, c->options.ce.mssfix);
3577  }
3578  if (c->options.ce.fragment > 0 && c->options.ce.mssfix > 0
3580  {
3581  msg(M_WARN, "WARNING: if you use --mssfix and --fragment, you should "
3582  "use the \"mtu\" flag for both or none of of them.");
3583  }
3584 #endif
3585 }
3586 
3587 static void
3589 {
3590  const struct options *o = &c->options;
3591 
3592  if (o->ping_send_timeout && !o->ping_rec_timeout)
3593  {
3594  msg(M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
3595  }
3596 
3597  if (o->username || o->groupname || o->chroot_dir
3598 #ifdef ENABLE_SELINUX
3599  || o->selinux_context
3600 #endif
3601  )
3602  {
3603  if (!o->persist_tun)
3604  {
3605  msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
3606  }
3607  if (!o->persist_key
3608 #ifdef ENABLE_PKCS11
3609  && !o->pkcs11_id
3610 #endif
3611  )
3612  {
3613  msg(M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
3614  }
3615  }
3616 
3617  if (o->chroot_dir && !(o->username && o->groupname))
3618  {
3619  msg(M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
3620  }
3621 
3622  if (o->pull && o->ifconfig_local && c->first_time)
3623  {
3624  msg(M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
3625  }
3626 
3628  {
3629  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");
3630  }
3631 
3632  if (o->mode == MODE_SERVER)
3633  {
3634  if (o->duplicate_cn && o->client_config_dir)
3635  {
3636  msg(M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
3637  }
3639  {
3640  msg(M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
3641  }
3642  if (!o->keepalive_ping || !o->keepalive_timeout)
3643  {
3644  msg(M_WARN, "WARNING: --keepalive option is missing from server config");
3645  }
3646  }
3647 
3648  if (!o->replay)
3649  {
3650  msg(M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
3651  }
3652 
3653  if (o->tls_server)
3654  {
3656  }
3657  if (o->tls_client
3658  && !o->tls_verify
3661  && !o->remote_cert_eku)
3662  {
3663  msg(M_WARN, "WARNING: No server certificate verification method has been enabled. See http://openvpn.net/howto.html#mitm for more info.");
3664  }
3665  if (o->ns_cert_type)
3666  {
3667  msg(M_WARN, "WARNING: --ns-cert-type is DEPRECATED. Use --remote-cert-tls instead.");
3668  }
3669 
3670  /* If a script is used, print appropriate warnings */
3671  if (o->user_script_used)
3672  {
3673  if (script_security() >= SSEC_SCRIPTS)
3674  {
3675  msg(M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
3676  }
3677  else if (script_security() >= SSEC_PW_ENV)
3678  {
3679  msg(M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
3680  }
3681  else
3682  {
3683  msg(M_WARN, "NOTE: starting with " PACKAGE_NAME " 2.1, '--script-security 2' or higher is required to call user-defined scripts or executables");
3684  }
3685  }
3686 }
3687 
3688 struct context_buffers *
3690 {
3691  struct context_buffers *b;
3692 
3693  ALLOC_OBJ_CLEAR(b, struct context_buffers);
3694 
3695  size_t buf_size = BUF_SIZE(frame);
3696 
3697  b->read_link_buf = alloc_buf(buf_size);
3698  b->read_tun_buf = alloc_buf(buf_size);
3699 
3700  b->aux_buf = alloc_buf(buf_size);
3701 
3702  b->encrypt_buf = alloc_buf(buf_size);
3703  b->decrypt_buf = alloc_buf(buf_size);
3704 
3705 #ifdef USE_COMP
3706  b->compress_buf = alloc_buf(buf_size);
3707  b->decompress_buf = alloc_buf(buf_size);
3708 #endif
3709 
3710  return b;
3711 }
3712 
3713 void
3715 {
3716  if (b)
3717  {
3718  free_buf(&b->read_link_buf);
3719  free_buf(&b->read_tun_buf);
3720  free_buf(&b->aux_buf);
3721 
3722 #ifdef USE_COMP
3723  free_buf(&b->compress_buf);
3724  free_buf(&b->decompress_buf);
3725 #endif
3726 
3727  free_buf(&b->encrypt_buf);
3728  free_buf(&b->decrypt_buf);
3729 
3730  free(b);
3731  }
3732 }
3733 
3734 /*
3735  * Now that we know all frame parameters, initialize
3736  * our buffers.
3737  */
3738 static void
3740 {
3742  c->c2.buffers_owned = true;
3743 }
3744 
3745 #ifdef ENABLE_FRAGMENT
3746 /*
3747  * Fragmenting code has buffers to initialize
3748  * once frame parameters are known.
3749  */
3750 static void
3752 {
3753  ASSERT(c->options.ce.fragment);
3755  &c->options, get_link_socket_info(c));
3757 }
3758 #endif
3759 
3760 /*
3761  * Allocate our socket object.
3762  */
3763 static void
3765 {
3766  ASSERT(!c->c2.link_socket);
3768  c->c2.link_socket_owned = true;
3769 }
3770 
3771 /*
3772  * Print MTU INFO
3773  */
3774 static void
3776 {
3777  frame_print(&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
3778 #ifdef ENABLE_FRAGMENT
3779  if (c->c2.fragment)
3780  {
3782  "Fragmentation MTU parms");
3783  }
3784 #endif
3785 }
3786 
3787 /*
3788  * Get local and remote options compatibility strings.
3789  */
3790 static void
3792 {
3793  struct gc_arena gc = gc_new();
3794 
3796  options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3797  false, &gc);
3799  options_string(&c->options, &c->c2.frame, c->c1.tuntap, &c->net_ctx,
3800  true, &gc);
3801 
3802  msg(D_SHOW_OCC, "Local Options String (VER=%s): '%s'",
3805  msg(D_SHOW_OCC, "Expected Remote Options String (VER=%s): '%s'",
3808 
3809  if (c->c2.tls_multi)
3810  {
3814  }
3815 
3816  gc_free(&gc);
3817 }
3818 
3819 /*
3820  * These things can only be executed once per program instantiation.
3821  * Set up for possible UID/GID downgrade, but don't do it yet.
3822  * Daemonize if requested.
3823  */
3824 static void
3826 {
3827  if (c->first_time && !c->c0)
3828  {
3829  struct context_0 *c0;
3830 
3831  ALLOC_OBJ_CLEAR_GC(c->c0, struct context_0, &c->gc);
3832  c0 = c->c0;
3833 
3834  /* get user and/or group that we want to setuid/setgid to,
3835  * sets also platform_x_state */
3836  bool group_defined = platform_group_get(c->options.groupname,
3837  &c0->platform_state_group);
3838  bool user_defined = platform_user_get(c->options.username,
3839  &c0->platform_state_user);
3840 
3841  c0->uid_gid_specified = user_defined || group_defined;
3842 
3843  /* perform postponed chdir if --daemon */
3844  if (c->did_we_daemonize && c->options.cd_dir == NULL)
3845  {
3846  platform_chdir("/");
3847  }
3848 
3849  /* should we change scheduling priority? */
3851  }
3852 }
3853 
3854 /*
3855  * free buffers
3856  */
3857 static void
3859 {
3860  if (c->c2.buffers_owned)
3861  {
3863  c->c2.buffers = NULL;
3864  c->c2.buffers_owned = false;
3865  }
3866 }
3867 
3868 /*
3869  * close TLS
3870  */
3871 static void
3873 {
3874  if (c->c2.tls_multi)
3875  {
3876  tls_multi_free(c->c2.tls_multi, true);
3877  c->c2.tls_multi = NULL;
3878  }
3879 
3880  /* free options compatibility strings */
3881  free(c->c2.options_string_local);
3882  free(c->c2.options_string_remote);
3883 
3885 
3886  if (c->c2.pulled_options_state)
3887  {
3890  }
3891 
3893 }
3894 
3895 /*
3896  * Free key schedules
3897  */
3898 static void
3899 do_close_free_key_schedule(struct context *c, bool free_ssl_ctx)
3900 {
3901  /*
3902  * always free the tls_auth/crypt key. If persist_key is true, the key will
3903  * be reloaded from memory (pre-cached)
3904  */
3907  CLEAR(c->c1.ks.tls_wrap_key);
3910 
3911  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
3912  {
3913  key_schedule_free(&c->c1.ks, free_ssl_ctx);
3914  }
3915 }
3916 
3917 /*
3918  * Close TCP/UDP connection
3919  */
3920 static void
3922 {
3923  /* in dco-win case, link socket is a tun handle which is
3924  * closed in do_close_tun(). Set it to UNDEFINED so
3925  * we won't use WinSock API to close it. */
3926  if (tuntap_is_dco_win(c->c1.tuntap) && c->c2.link_socket)
3927  {
3929  }
3930 
3931  if (c->c2.link_socket && c->c2.link_socket_owned)
3932  {
3934  c->c2.link_socket = NULL;
3935  }
3936 
3937 
3938  /* Preserve the resolved list of remote if the user request to or if we want
3939  * reconnect to the same host again or there are still addresses that need
3940  * to be tried */
3941  if (!(c->sig->signal_received == SIGUSR1
3942  && ( (c->options.persist_remote_ip)
3943  ||
3944  ( c->sig->source != SIG_SOURCE_HARD
3946  && c->c1.link_socket_addr.current_remote->ai_next)
3947  || c->options.no_advance))
3948  )))
3949  {
3951  }
3952 
3953  /* Clear the remote actual address when persist_remote_ip is not in use */
3954  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
3955  {
3957  }
3958 
3959  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
3960  {
3962  {
3963  freeaddrinfo(c->c1.link_socket_addr.bind_local);
3964  }
3965 
3966  c->c1.link_socket_addr.bind_local = NULL;
3967  }
3968 }
3969 
3970 /*
3971  * Close packet-id persistence file
3972  */
3973 static void
3975 {
3978  if (!(c->sig->signal_received == SIGUSR1))
3979  {
3981  }
3982 }
3983 
3984 #ifdef ENABLE_FRAGMENT
3985 /*
3986  * Close fragmentation handler.
3987  */
3988 static void
3990 {
3991  if (c->c2.fragment)
3992  {
3994  c->c2.fragment = NULL;
3995  }
3996 }
3997 #endif
3998 
3999 /*
4000  * Open and close our event objects.
4001  */
4002 
4003 static void
4005  bool need_us_timeout)
4006 {
4007  unsigned int flags = 0;
4008 
4010 
4011  flags |= EVENT_METHOD_FAST;
4012 
4013  if (need_us_timeout)
4014  {
4015  flags |= EVENT_METHOD_US_TIMEOUT;
4016  }
4017 
4018  c->c2.event_set = event_set_init(&c->c2.event_set_max, flags);
4019  c->c2.event_set_owned = true;
4020 }
4021 
4022 static void
4024 {
4025  if (c->c2.event_set && c->c2.event_set_owned)
4026  {
4027  event_free(c->c2.event_set);
4028  c->c2.event_set = NULL;
4029  c->c2.event_set_owned = false;
4030  }
4031 }
4032 
4033 /*
4034  * Open and close --status file
4035  */
4036 
4037 static void
4039 {
4040  if (!c->c1.status_output)
4041  {
4044  -1,
4045  NULL,
4047  c->c1.status_output_owned = true;
4048  }
4049 }
4050 
4051 static void
4053 {
4054  if (!(c->sig->signal_received == SIGUSR1))
4055  {
4056  if (c->c1.status_output_owned && c->c1.status_output)
4057  {
4059  c->c1.status_output = NULL;
4060  c->c1.status_output_owned = false;
4061  }
4062  }
4063 }
4064 
4065 /*
4066  * Handle ifconfig-pool persistence object.
4067  */
4068 static void
4070 {
4072  {
4075  c->c1.ifconfig_pool_persist_owned = true;
4076  }
4077 }
4078 
4079 static void
4081 {
4082  if (!(c->sig->signal_received == SIGUSR1))
4083  {
4085  {
4087  c->c1.ifconfig_pool_persist = NULL;
4088  c->c1.ifconfig_pool_persist_owned = false;
4089  }
4090  }
4091 }
4092 
4093 /*
4094  * Inherit environmental variables
4095  */
4096 
4097 static void
4098 do_inherit_env(struct context *c, const struct env_set *src)
4099 {
4100  c->c2.es = env_set_create(NULL);
4101  c->c2.es_owned = true;
4102  env_set_inherit(c->c2.es, src);
4103 }
4104 
4105 static void
4107 {
4108  if (c->c2.es && c->c2.es_owned)
4109  {
4110  env_set_destroy(c->c2.es);
4111  c->c2.es = NULL;
4112  c->c2.es_owned = false;
4113  }
4114 }
4115 
4116 /*
4117  * Fast I/O setup. Fast I/O is an optimization which only works
4118  * if all of the following are true:
4119  *
4120  * (1) The platform is not Windows
4121  * (2) --proto udp is enabled
4122  * (3) --shaper is disabled
4123  */
4124 static void
4126 {
4127  if (c->options.fast_io)
4128  {
4129 #ifdef _WIN32
4130  msg(M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
4131 #else
4132  if (!proto_is_udp(c->options.ce.proto))
4133  {
4134  msg(M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
4135  }
4136  else
4137  {
4138  if (c->options.shaper)
4139  {
4140  msg(M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
4141  }
4142  else
4143  {
4144  c->c2.fast_io = true;
4145  }
4146  }
4147 #endif
4148  }
4149 }
4150 
4151 static void
4153 {
4154  if (c->options.tls_exit)
4155  {
4156  c->c2.tls_exit_signal = SIGTERM;
4157  }
4158  else
4159  {
4160  c->c2.tls_exit_signal = SIGUSR1;
4161  }
4162 }
4163 
4164 #ifdef ENABLE_PLUGIN
4165 
4166 void
4168 {
4169  if (c->options.plugin_list && !c->plugins)
4170  {
4172  c->plugins_owned = true;
4173  }
4174 }
4175 
4176 void
4177 open_plugins(struct context *c, const bool import_options, int init_point)
4178 {
4179  if (c->plugins && c->plugins_owned)
4180  {
4181  if (import_options)
4182  {
4183  struct plugin_return pr, config;
4184  plugin_return_init(&pr);
4185  plugin_list_open(c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
4186  plugin_return_get_column(&pr, &config, "config");
4187  if (plugin_return_defined(&config))
4188  {
4189  int i;
4190  for (i = 0; i < config.n; ++i)
4191  {
4192  unsigned int option_types_found = 0;
4193  if (config.list[i] && config.list[i]->value)
4194  {
4196  config.list[i]->value,
4199  &option_types_found,
4200  c->es);
4201  }
4202  }
4203  }
4204  plugin_return_free(&pr);
4205  }
4206  else
4207  {
4208  plugin_list_open(c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
4209  }
4210  }
4211 }
4212 
4213 static void
4215 {
4216  if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
4217  {
4219  c->plugins = NULL;
4220  c->plugins_owned = false;
4221  }
4222 }
4223 
4224 static void
4225 do_inherit_plugins(struct context *c, const struct context *src)
4226 {
4227  if (!c->plugins && src->plugins)
4228  {
4229  c->plugins = plugin_list_inherit(src->plugins);
4230  c->plugins_owned = true;
4231  }
4232 }
4233 
4234 #endif /* ifdef ENABLE_PLUGIN */
4235 
4236 #ifdef ENABLE_MANAGEMENT
4237 
4238 static void
4239 management_callback_status_p2p(void *arg, const int version, struct status_output *so)
4240 {
4241  struct context *c = (struct context *) arg;
4242  print_status(c, so);
4243 }
4244 
4245 void
4246 management_show_net_callback(void *arg, const int msglevel)
4247 {
4248 #ifdef _WIN32
4249  show_routes(msglevel);
4250  show_adapters(msglevel);
4251  msg(msglevel, "END");
4252 #else
4253  msg(msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
4254 #endif
4255 }
4256 
4257 #ifdef TARGET_ANDROID
4258 int
4259 management_callback_network_change(void *arg, bool samenetwork)
4260 {
4261  /* Check if the client should translate the network change to a SIGUSR1 to
4262  * reestablish the connection or just reprotect the socket
4263  *
4264  * At the moment just assume that, for all settings that use pull (not
4265  * --static) and are not using peer-id reestablishing the connection is
4266  * required (unless the network is the same)
4267  *
4268  * The function returns -1 on invalid fd and -2 if the socket cannot be
4269  * reused. On the -2 return value the man_network_change function triggers
4270  * a SIGUSR1 to force a reconnect.
4271  */
4272 
4273  int socketfd = -1;
4274  struct context *c = (struct context *) arg;
4275  if (!c->c2.link_socket)
4276  {
4277  return -1;
4278  }
4279  if (c->c2.link_socket->sd == SOCKET_UNDEFINED)
4280  {
4281  return -1;
4282  }
4283 
4284  socketfd = c->c2.link_socket->sd;
4285  if (!c->options.pull || c->c2.tls_multi->use_peer_id || samenetwork)
4286  {
4287  return socketfd;
4288  }
4289  else
4290  {
4291  return -2;
4292  }
4293 }
4294 #endif /* ifdef TARGET_ANDROID */
4295 
4296 #endif /* ifdef ENABLE_MANAGEMENT */
4297 
4298 void
4300 {
4301 #ifdef ENABLE_MANAGEMENT
4302  if (management)
4303  {
4304  struct management_callback cb;
4305  CLEAR(cb);
4306  cb.arg = c;
4312 #ifdef TARGET_ANDROID
4313  cb.network_change = management_callback_network_change;
4314 #endif
4318  }
4319 #endif
4320 }
4321 
4322 #ifdef ENABLE_MANAGEMENT
4323 
4324 void
4326 {
4327  if (!management)
4328  {
4330  }
4331 }
4332 
4333 bool
4335 {
4336  /* initialize management layer */
4337  if (management)
4338  {
4339  if (c->options.management_addr)
4340  {
4341  unsigned int flags = c->options.management_flags;
4342  if (c->options.mode == MODE_SERVER)
4343  {
4344  flags |= MF_SERVER;
4345  }
4356  flags))
4357  {
4360  NULL,
4361  NULL,
4362  NULL,
4363  NULL,
4364  NULL);
4365  }
4366 
4367  /* initial management hold, called early, before first context initialization */
4368  do_hold(0);
4369  if (IS_SIG(c))
4370  {
4371  msg(M_WARN, "Signal received from management interface, exiting");
4372  return false;
4373  }
4374  }
4375  else
4376  {
4377  close_management();
4378  }
4379  }
4380  return true;
4381 }
4382 
4383 void
4385 {
4386  if (management)
4387  {
4389  management = NULL;
4390  }
4391 }
4392 
4393 #endif /* ifdef ENABLE_MANAGEMENT */
4394 
4395 
4396 void
4398 {
4399 #ifdef ENABLE_MANAGEMENT
4400  if (management)
4401  {
4403  }
4404 #endif
4405 }
4406 
4407 void
4409 {
4410 #ifdef ENABLE_MANAGEMENT
4411  if (management)
4412  {
4414  }
4415 #endif
4416 }
4417 
4418 /*
4419  * Initialize a tunnel instance, handle pre and post-init
4420  * signal settings.
4421  */
4422 void
4423 init_instance_handle_signals(struct context *c, const struct env_set *env, const unsigned int flags)
4424 {
4426  init_instance(c, env, flags);
4428 
4429  /*
4430  * This is done so that signals thrown during
4431  * initialization can bring us back to
4432  * a management hold.
4433  */
4434  if (IS_SIG(c))
4435  {
4436  remap_signal(c);
4438  }
4439 }
4440 
4441 /*
4442  * Initialize a tunnel instance.
4443  */
4444 void
4445 init_instance(struct context *c, const struct env_set *env, const unsigned int flags)
4446 {
4447  const struct options *options = &c->options;
4448  const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
4449  int link_socket_mode = LS_MODE_DEFAULT;
4450 
4451  /* init garbage collection level */
4452  gc_init(&c->c2.gc);
4453 
4454  /* inherit environmental variables */
4455  if (env)
4456  {
4457  do_inherit_env(c, env);
4458  }
4459 
4460  if (c->mode == CM_P2P)
4461  {
4463  }
4464 
4465  /* possible sleep or management hold if restart */
4466  if (c->mode == CM_P2P || c->mode == CM_TOP)
4467  {
4468  do_startup_pause(c);
4469  if (IS_SIG(c))
4470  {
4471  goto sig;
4472  }
4473  }
4474 
4475  if (c->options.resolve_in_advance)
4476  {
4477  do_preresolve(c);
4478  if (IS_SIG(c))
4479  {
4480  goto sig;
4481  }
4482  }
4483 
4484  /* Resets all values to the initial values from the config where needed */
4485  pre_connect_restore(&c->options, &c->c2.gc);
4486 
4487  /* map in current connection entry */
4489 
4490  /* link_socket_mode allows CM_CHILD_TCP
4491  * instances to inherit acceptable fds
4492  * from a top-level parent */
4493  if (c->options.ce.proto == PROTO_TCP_SERVER)
4494  {
4495  if (c->mode == CM_TOP)
4496  {
4497  link_socket_mode = LS_MODE_TCP_LISTEN;
4498  }
4499  else if (c->mode == CM_CHILD_TCP)
4500  {
4501  link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
4502  }
4503  }
4504 
4505  /* should we disable paging? */
4506  if (c->first_time && options->mlock)
4507  {
4508  platform_mlockall(true);
4509  }
4510 
4511  /* get passwords if undefined */
4512  if (auth_retry_get() == AR_INTERACT)
4513  {
4515  }
4516 
4517  /* initialize context level 2 --verb/--mute parms */
4519 
4520  /* set error message delay for non-server modes */
4521  if (c->mode == CM_P2P)
4522  {
4524  }
4525 
4526  /* warn about inconsistent options */
4527  if (c->mode == CM_P2P || c->mode == CM_TOP)
4528  {
4529  do_option_warnings(c);
4530  }
4531 
4532 #ifdef ENABLE_PLUGIN
4533  /* initialize plugins */
4534  if (c->mode == CM_P2P || c->mode == CM_TOP)
4535  {
4537  }
4538 #endif
4539 
4540  /* should we enable fast I/O? */
4541  if (c->mode == CM_P2P || c->mode == CM_TOP)
4542  {
4543  do_setup_fast_io(c);
4544  }
4545 
4546  /* should we throw a signal on TLS errors? */
4548 
4549  /* open --status file */
4550  if (c->mode == CM_P2P || c->mode == CM_TOP)
4551  {
4553  }
4554 
4555  /* open --ifconfig-pool-persist file */
4556  if (c->mode == CM_TOP)
4557  {
4559  }
4560 
4561  /* reset OCC state */
4562  if (c->mode == CM_P2P || child)
4563  {
4564  c->c2.occ_op = occ_reset_op();
4565  }
4566 
4567  /* our wait-for-i/o objects, different for posix vs. win32 */
4568  if (c->mode == CM_P2P)
4569  {
4571  }
4572  else if (c->mode == CM_CHILD_TCP)
4573  {
4574  do_event_set_init(c, false);
4575  }
4576 
4577  /* initialize HTTP or SOCKS proxy object at scope level 2 */
4578  init_proxy(c);
4579 
4580  /* allocate our socket object */
4581  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4582  {
4583  do_link_socket_new(c);
4584  }
4585 
4586 #ifdef ENABLE_FRAGMENT
4587  /* initialize internal fragmentation object */
4588  if (options->ce.fragment && (c->mode == CM_P2P || child))
4589  {
4590  c->c2.fragment = fragment_init(&c->c2.frame);
4591  }
4592 #endif
4593 
4594  /* init crypto layer */
4595  {
4596  unsigned int crypto_flags = 0;
4597  if (c->mode == CM_TOP)
4598  {
4599  crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
4600  }
4601  else if (c->mode == CM_P2P)
4602  {
4604  }
4605  else if (child)
4606  {
4607  crypto_flags = CF_INIT_TLS_MULTI;
4608  }
4609  do_init_crypto(c, crypto_flags);
4610  if (IS_SIG(c) && !child)
4611  {
4612  goto sig;
4613  }
4614  }
4615 
4616 #ifdef USE_COMP
4617  /* initialize compression library. */
4618  if (comp_enabled(&options->comp) && (c->mode == CM_P2P || child))
4619  {
4620  c->c2.comp_context = comp_init(&options->comp);
4621  }
4622 #endif
4623 
4624  /* initialize MTU variables */
4625  do_init_frame(c);
4626 
4627  /* initialize TLS MTU variables */
4628  do_init_frame_tls(c);
4629 
4630  /* init workspace buffers whose size is derived from frame size */
4631  if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
4632  {
4633  do_init_buffers(c);
4634  }
4635 
4636 #ifdef ENABLE_FRAGMENT
4637  /* initialize internal fragmentation capability with known frame size */
4638  if (options->ce.fragment && (c->mode == CM_P2P || child))
4639  {
4640  do_init_fragment(c);
4641  }
4642 #endif
4643 
4644  /* bind the TCP/UDP socket */
4645  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4646  {
4647  link_socket_init_phase1(c, link_socket_mode);
4648  }
4649 
4650  /* initialize tun/tap device object,
4651  * open tun/tap device, ifconfig, run up script, etc. */
4652  if (!(options->up_delay || PULL_DEFINED(options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
4653  {
4654  int error_flags = 0;
4655  c->c2.did_open_tun = do_open_tun(c, &error_flags);
4656  }
4657 
4658  c->c2.frame_initial = c->c2.frame;
4659 
4660  /* print MTU info */
4662 
4663  /* get local and remote options compatibility strings */
4664  if (c->mode == CM_P2P || child)
4665  {
4667  }
4668 
4669  /* initialize output speed limiter */
4670  if (c->mode == CM_P2P)
4671  {
4673  }
4674 
4675  /* do one-time inits, and possibly become a daemon here */
4676  do_init_first_time(c);
4677 
4678 #ifdef ENABLE_PLUGIN
4679  /* initialize plugins */
4680  if (c->mode == CM_P2P || c->mode == CM_TOP)
4681  {
4683  }
4684 #endif
4685 
4686  /* initialise connect timeout timer */
4688 
4689  /* finalize the TCP/UDP socket */
4690  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
4691  {
4693 
4694 
4695  /* Update dynamic frame calculation as exact transport socket information
4696  * (IP vs IPv6) may be only available after socket phase2 has finished.
4697  * This is only needed for --static or no crypto, NCP will recalculate this
4698  * in tls_session_update_crypto_params (P2MP) */
4701  }
4702 
4703  /*
4704  * Actually do UID/GID downgrade, and chroot, if requested.
4705  * May be delayed by --client, --pull, or --up-delay.
4706  */
4708 
4709  /* initialize timers */
4710  if (c->mode == CM_P2P || child)
4711  {
4712  do_init_timers(c, false);
4713  }
4714 
4715 #ifdef ENABLE_PLUGIN
4716  /* initialize plugins */
4717  if (c->mode == CM_P2P || c->mode == CM_TOP)
4718  {
4720  }
4721 #endif
4722 
4723 #if PORT_SHARE
4724  /* share OpenVPN port with foreign (such as HTTPS) server */
4725  if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
4726  {
4727  init_port_share(c);
4728  }
4729 #endif
4730 
4731  /* Check for signals */
4732  if (IS_SIG(c))
4733  {
4734  goto sig;
4735  }
4736 
4737  return;
4738 
4739 sig:
4740  if (!c->sig->signal_text)
4741  {
4742  c->sig->signal_text = "init_instance";
4743  }
4744  close_context(c, -1, flags);
4745  return;
4746 }
4747 
4748 /*
4749  * Close a tunnel instance.
4750  */
4751 void
4753 {
4754  /* close event objects */
4755  do_close_event_set(c);
4756 
4757  if (c->mode == CM_P2P
4758  || c->mode == CM_CHILD_TCP
4759  || c->mode == CM_CHILD_UDP
4760  || c->mode == CM_TOP)
4761  {
4762 #ifdef USE_COMP
4763  if (c->c2.comp_context)
4764  {
4765  comp_uninit(c->c2.comp_context);
4766  c->c2.comp_context = NULL;
4767  }
4768 #endif
4769 
4770  /* free buffers */
4771  do_close_free_buf(c);
4772 
4773  /* close peer for DCO if enabled, needs peer-id so must be done before
4774  * closing TLS contexts */
4775  dco_remove_peer(c);
4776 
4777  /* close TLS */
4778  do_close_tls(c);
4779 
4780  /* free key schedules */
4781  do_close_free_key_schedule(c, (c->mode == CM_P2P || c->mode == CM_TOP));
4782 
4783  /* close TCP/UDP connection */
4785 
4786  /* close TUN/TAP device */
4787  do_close_tun(c, false);
4788 
4789 #ifdef ENABLE_MANAGEMENT
4790  if (management)
4791  {
4793  }
4794 #endif
4795 
4796 #ifdef ENABLE_PLUGIN
4797  /* call plugin close functions and unload */
4798  do_close_plugins(c);
4799 #endif
4800 
4801  /* close packet-id persistence file */
4802  do_close_packet_id(c);
4803 
4804  /* close --status file */
4806 
4807 #ifdef ENABLE_FRAGMENT
4808  /* close fragmentation handler */
4809  do_close_fragment(c);
4810 #endif
4811 
4812  /* close --ifconfig-pool-persist obj */
4814 
4815  /* free up environmental variable store */
4816  do_env_set_destroy(c);
4817 
4818  /* close HTTP or SOCKS proxy */
4819  uninit_proxy(c);
4820 
4821  /* garbage collect */
4822  gc_free(&c->c2.gc);
4823  }
4824 }
4825 
4826 void
4828  const struct context *src)
4829 {
4830  CLEAR(*dest);
4831 
4832  /* proto_is_dgram will ASSERT(0) if proto is invalid */
4834 
4835  dest->gc = gc_new();
4836 
4837  ALLOC_OBJ_CLEAR_GC(dest->sig, struct signal_info, &dest->gc);
4838 
4839  /* c1 init */
4841 
4842  dest->c1.ks.key_type = src->c1.ks.key_type;
4843  /* inherit SSL context */
4844  dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
4845  dest->c1.ks.tls_wrap_key = src->c1.ks.tls_wrap_key;
4848  /* inherit pre-NCP ciphers */
4849  dest->options.ciphername = src->options.ciphername;
4850  dest->options.authname = src->options.authname;
4851 
4852  /* inherit auth-token */
4853  dest->c1.ks.auth_token_key = src->c1.ks.auth_token_key;
4854 
4855  /* options */
4856  dest->options = src->options;
4857  options_detach(&dest->options);
4858 
4859  if (dest->mode == CM_CHILD_TCP)
4860  {
4861  /*
4862  * The CM_TOP context does the socket listen(),
4863  * and the CM_CHILD_TCP context does the accept().
4864  */
4865  dest->c2.accept_from = src->c2.link_socket;
4866  }
4867 
4868 #ifdef ENABLE_PLUGIN
4869  /* inherit plugins */
4870  do_inherit_plugins(dest, src);
4871 #endif
4872 
4873  /* context init */
4874 
4875  /* inherit tun/tap interface object now as it may be required
4876  * to initialize the DCO context in init_instance()
4877  */
4878  dest->c1.tuntap = src->c1.tuntap;
4879 
4880  init_instance(dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
4881  if (IS_SIG(dest))
4882  {
4883  return;
4884  }
4885 
4886  /* UDP inherits some extra things which TCP does not */
4887  if (dest->mode == CM_CHILD_UDP)
4888  {
4889  /* inherit buffers */
4890  dest->c2.buffers = src->c2.buffers;
4891 
4892  /* inherit parent link_socket and tuntap */
4893  dest->c2.link_socket = src->c2.link_socket;
4894 
4895  ALLOC_OBJ_GC(dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
4896  *dest->c2.link_socket_info = src->c2.link_socket->info;
4897 
4898  /* locally override some link_socket_info fields */
4899  dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
4901  }
4902 }
4903 
4904 void
4906  const struct context *src)
4907 {
4908  /* copy parent */
4909  *dest = *src;
4910 
4911  /*
4912  * CM_TOP_CLONE will prevent close_instance from freeing or closing
4913  * resources owned by the parent.
4914  *
4915  * Also note that CM_TOP_CLONE context objects are
4916  * closed by multi_top_free in multi.c.
4917  */
4918  dest->mode = CM_TOP_CLONE;
4919 
4920  dest->first_time = false;
4921  dest->c0 = NULL;
4922 
4923  options_detach(&dest->options);
4924  gc_detach(&dest->gc);
4925  gc_detach(&dest->c2.gc);
4926 
4927  /* detach plugins */
4928  dest->plugins_owned = false;
4929 
4930  dest->c2.tls_multi = NULL;
4931 
4932  /* detach c1 ownership */
4933  dest->c1.tuntap_owned = false;
4934  dest->c1.status_output_owned = false;
4935  dest->c1.ifconfig_pool_persist_owned = false;
4936 
4937  /* detach c2 ownership */
4938  dest->c2.event_set_owned = false;
4939  dest->c2.link_socket_owned = false;
4940  dest->c2.buffers_owned = false;
4941  dest->c2.es_owned = false;
4942 
4943  dest->c2.event_set = NULL;
4944  if (proto_is_dgram(src->options.ce.proto))
4945  {
4946  do_event_set_init(dest, false);
4947  }
4948 
4949 #ifdef USE_COMP
4950  dest->c2.comp_context = NULL;
4951 #endif
4952 }
4953 
4954 void
4955 close_context(struct context *c, int sig, unsigned int flags)
4956 {
4957  ASSERT(c);
4958  ASSERT(c->sig);
4959 
4960  if (sig >= 0)
4961  {
4962  register_signal(c->sig, sig, "close_context");
4963  }
4964 
4965  if (c->sig->signal_received == SIGUSR1)
4966  {
4967  if ((flags & CC_USR1_TO_HUP)
4968  || (c->sig->source == SIG_SOURCE_HARD && (flags & CC_HARD_USR1_TO_HUP)))
4969  {
4970  register_signal(c->sig, SIGHUP, "close_context usr1 to hup");
4971  }
4972  }
4973 
4974  if (!(flags & CC_NO_CLOSE))
4975  {
4976  close_instance(c);
4977  }
4978 
4979  if (flags & CC_GC_FREE)
4980  {
4981  context_gc_free(c);
4982  }
4983 }
4984 
4985 /* Write our PID to a file */
4986 void
4987 write_pid_file(const char *filename, const char *chroot_dir)
4988 {
4989  if (filename)
4990  {
4991  unsigned int pid = 0;
4992  FILE *fp = platform_fopen(filename, "w");
4993  if (!fp)
4994  {
4995  msg(M_ERR, "Open error on pid file %s", filename);
4996  return;
4997  }
4998 
4999  pid = platform_getpid();
5000  fprintf(fp, "%u\n", pid);
5001  if (fclose(fp))
5002  {
5003  msg(M_ERR, "Close error on pid file %s", filename);
5004  }
5005 
5006  /* remember file name so it can be deleted "out of context" later */
5007  /* (the chroot case is more complex and not handled today) */
5008  if (!chroot_dir)
5009  {
5010  saved_pid_file_name = strdup(filename);
5011  }
5012  }
5013 }
5014 
5015 /* remove PID file on exit, called from openvpn_exit() */
5016 void
5018 {
5019  if (saved_pid_file_name)
5020  {
5022  }
5023 }
5024 
5025 
5026 /*
5027  * Do a loopback test
5028  * on the crypto subsystem.
5029  */
5030 static void *
5032 {
5033  struct context *c = (struct context *) arg;
5034  const struct options *options = &c->options;
5035 
5038  context_init_1(c);
5040  do_init_crypto_static(c, 0);
5041 
5043 
5044  test_crypto(&c->c2.crypto_options, &c->c2.frame);
5045 
5046  key_schedule_free(&c->c1.ks, true);
5048 
5049  context_gc_free(c);
5050  return NULL;
5051 }
5052 
5053 bool
5054 do_test_crypto(const struct options *o)
5055 {
5056  if (o->test_crypto)
5057  {
5058  struct context c;
5059 
5060  /* print version number */
5061  msg(M_INFO, "%s", title_string);
5062 
5063  context_clear(&c);
5064  c.options = *o;
5065  options_detach(&c.options);
5066  c.first_time = true;
5067  test_crypto_thread((void *) &c);
5068  return true;
5069  }
5070  return false;
5071 }
connection_entry::tls_crypt_file
const char * tls_crypt_file
Definition: options.h:160
status_open
struct status_output * status_open(const char *filename, const int refresh_freq, const int msglevel, const struct virtual_output *vout, const unsigned int flags)
Definition: status.c:61
options::keepalive_timeout
int keepalive_timeout
Definition: options.h:328
plugin_return::list
struct openvpn_plugin_string_list * list[MAX_PLUGINS]
Definition: plugin.h:104
init_tun
struct tuntap * init_tun(const char *dev, const char *dev_type, int topology, const char *ifconfig_local_parm, const char *ifconfig_remote_netmask_parm, const char *ifconfig_ipv6_local_parm, int ifconfig_ipv6_netbits_parm, const char *ifconfig_ipv6_remote_parm, struct addrinfo *local_public, struct addrinfo *remote_public, const bool strict_warn, struct env_set *es, openvpn_net_ctx_t *ctx, struct tuntap *tt)
Definition: tun.c:816
do_close_ifconfig_pool_persist
static void do_close_ifconfig_pool_persist(struct context *c)
Definition: init.c:4080
pull_permission_mask
unsigned int pull_permission_mask(const struct context *c)
Definition: init.c:2532
context_2::route_wakeup
struct event_timeout route_wakeup
Definition: openvpn.h:389
tun_standby_init
void tun_standby_init(struct tuntap *tt)
Definition: tun.c:5828
options::replay_time
int replay_time
Definition: options.h:566
GENKEY_AUTH_TOKEN
@ GENKEY_AUTH_TOKEN
Definition: options.h:224
platform_create_temp_file
const char * platform_create_temp_file(const char *directory, const char *prefix, struct gc_arena *gc)
Create a temporary file in directory, returns the filename of the created file.
Definition: platform.c:554
do_test_crypto
bool do_test_crypto(const struct options *o)
Definition: init.c:5054
context_2::tls_auth_standalone
struct tls_auth_standalone * tls_auth_standalone
TLS state structure required for the initial authentication of a client's connection attempt.
Definition: openvpn.h:332
options::genkey_type
enum genkey_type genkey_type
Definition: options.h:269
plugin_list_init
struct plugin_list * plugin_list_init(const struct plugin_option_list *list)
Definition: plugin.c:764
management_set_state
void management_set_state(struct management *man, const int state, const char *detail, const in_addr_t *tun_local_ip, const struct in6_addr *tun_local_ip6, const struct openvpn_sockaddr *local, const struct openvpn_sockaddr *remote)
Definition: manage.c:2740
options::show_engines
bool show_engines
Definition: options.h:265
do_close_plugins
static void do_close_plugins(struct context *c)
Definition: init.c:4214
write_key_file
int write_key_file(const int nkeys, const char *filename)
Write nkeys 1024-bits keys to file.
Definition: crypto.c:1361
signal_info::signal_received
volatile int signal_received
Definition: sig.h:43
options::ssl_flags
unsigned int ssl_flags
Definition: options.h:608
options::verbosity
int verbosity
Definition: options.h:382
do_ifconfig_setenv
void do_ifconfig_setenv(const struct tuntap *tt, struct env_set *es)
Definition: tun.c:772
WSO_MODE_CONSOLE
#define WSO_MODE_CONSOLE
Definition: win32.h:154
do_init_server_poll_timeout
static void do_init_server_poll_timeout(struct context *c)
Definition: init.c:1364
tls_init_control_channel_frame_parameters
void tls_init_control_channel_frame_parameters(struct frame *frame, int tls_mtu)
Definition: ssl.c:298
next_connection_entry
static void next_connection_entry(struct context *c)
Definition: init.c:518
CE_MAN_QUERY_REMOTE_MOD
#define CE_MAN_QUERY_REMOTE_MOD
Definition: options.h:148
openvpn_sockaddr::addr
union openvpn_sockaddr::@14 addr
options::verify_hash
struct verify_hash_list * verify_hash
Definition: options.h:604
OPENVPN_PLUGIN_UP
#define OPENVPN_PLUGIN_UP
Definition: openvpn-plugin.h:117
tls_crypt_v2_init_server_key
void tls_crypt_v2_init_server_key(struct key_ctx *key_ctx, bool encrypt, const char *key_file, bool key_inline)
Initialize a tls-crypt-v2 server key (used to encrypt/decrypt client keys).
Definition: tls_crypt.c:362
connection_entry::mssfix_encap
bool mssfix_encap
Definition: options.h:137
frame::mss_fix
unsigned int mss_fix
The actual MSS value that should be written to the payload packets.
Definition: mtu.h:118
get_default_gateway_ipv6
void get_default_gateway_ipv6(struct route_ipv6_gateway_info *rgi6, const struct in6_addr *dest, openvpn_net_ctx_t *ctx)
Definition: route.c:2756
tls_options::config_ncp_ciphers
const char * config_ncp_ciphers
Definition: ssl_common.h:364
platform_user_group_set
void platform_user_group_set(const struct platform_state_user *user_state, const struct platform_state_group *group_state, struct context *c)
Definition: platform.c:217
M_INFO
#define M_INFO
Definition: errlevel.h:55
connection_entry::mssfix
int mssfix
Definition: options.h:135
management_post_tunnel_open
void management_post_tunnel_open(struct management *man, const in_addr_t tun_local_ip)
Definition: manage.c:3049
options::show_digests
bool show_digests
Definition: options.h:264
do_close_tls
static void do_close_tls(struct context *c)
Definition: init.c:3872
connection_entry::link_mtu
int link_mtu
Definition: options.h:125
route_ipv6_option_list::flags
unsigned int flags
Definition: route.h:107
fragment_frame_init
void fragment_frame_init(struct fragment_master *f, const struct frame *frame)
Allocate internal packet buffers for a fragment_master structure.
Definition: fragment.c:122
options::use_peer_id
bool use_peer_id
Definition: options.h:683
notnull
void notnull(const char *arg, const char *description)
Definition: options.c:4878
M_OPTERR
#define M_OPTERR
Definition: error.h:106
tls_options::verify_x509_name
const char * verify_x509_name
Definition: ssl_common.h:340
options::sc_info
struct static_challenge_info sc_info
Definition: options.h:550
OPENVPN_PLUGIN_DOWN
#define OPENVPN_PLUGIN_DOWN
Definition: openvpn-plugin.h:118
tls_wrap_ctx::original_wrap_keydata
struct key2 original_wrap_keydata
original key data to be xored in to the key for dynamic tls-crypt.
Definition: ssl_common.h:286
context_2::accept_from
const struct link_socket * accept_from
Definition: openvpn.h:245
options::enable_ncp_fallback
bool enable_ncp_fallback
If defined fall back to ciphername if NCP fails.
Definition: options.h:557
add_route_ipv6_to_option_list
void add_route_ipv6_to_option_list(struct route_ipv6_option_list *l, const char *prefix, const char *gateway, const char *metric)
Definition: route.c:521
gc_new
static struct gc_arena gc_new(void)
Definition: buffer.h:1011
GENKEY_SECRET
@ GENKEY_SECRET
Definition: options.h:221
fragment_init
struct fragment_master * fragment_init(struct frame *frame)
Allocate and initialize a fragment_master structure.
Definition: fragment.c:89
options::nice
int nice
Definition: options.h:381
do_ifconfig
void do_ifconfig(struct tuntap *tt, const char *ifname, int tun_mtu, const struct env_set *es, openvpn_net_ctx_t *ctx)
do_ifconfig - configure the tunnel interface
Definition: tun.c:1658
run_command.h
DEV_TYPE_TUN
#define DEV_TYPE_TUN
Definition: proto.h:37
auth_token.h
tls_options::frame
struct frame frame
Definition: ssl_common.h:372
connection_entry::connect_retry_seconds
int connect_retry_seconds
Definition: options.h:110
connection_entry::explicit_exit_notification
int explicit_exit_notification
Definition: options.h:141
context_2::tls_multi
struct tls_multi * tls_multi
TLS state structure for this VPN tunnel.
Definition: openvpn.h:329
forward.h
open_management
bool open_management(struct context *c)
Definition: init.c:4334
plugin_return
Definition: plugin.h:101
ROUTE_BEFORE_TUN
#define ROUTE_BEFORE_TUN
Definition: tun.h:379
context_2::frame_initial
struct frame frame_initial
Definition: openvpn.h:252
fragment_free
void fragment_free(struct fragment_master *f)
Free a fragment_master structure and its internal packet buffers.
Definition: fragment.c:113
key_ctx_bi_defined
static bool key_ctx_bi_defined(const struct key_ctx_bi *key)
Definition: crypto.h:556
signal_info::signal_text
const char * signal_text
Definition: sig.h:45
route_list
Definition: route.h:206
gremlin.h
context_1::status_output_owned
bool status_output_owned
Definition: openvpn.h:184
PACKAGE_NAME
#define PACKAGE_NAME
Definition: config.h:492
options::up_script
const char * up_script
Definition: options.h:368
context::persist
struct context_persist persist
Persistent context.
Definition: openvpn.h:516
buffer::len
int len
Length in bytes of the actual content within the allocated memory.
Definition: buffer.h:66
restore_signal_state
void restore_signal_state(void)
Definition: sig.c:466
frame_print
void frame_print(const struct frame *frame, int level, const char *prefix)
Definition: mtu.c:202
OPT_P_DEFAULT
#define OPT_P_DEFAULT
Definition: options.h:743
OPT_P_PUSH_MTU
#define OPT_P_PUSH_MTU
Definition: options.h:741
options::keepalive_ping
int keepalive_ping
Definition: options.h:327
connection_entry::socks_proxy_server
const char * socks_proxy_server
Definition: options.h:114
set_lladdr
int set_lladdr(openvpn_net_ctx_t *ctx, const char *ifname, const char *lladdr, const struct env_set *es)
Definition: lladdr.c:17
open_tun
void open_tun(const char *dev, const char *dev_type, const char *dev_node, struct tuntap *tt, openvpn_net_ctx_t *ctx)
Definition: tun.c:6826
init_connection_list
static void init_connection_list(struct context *c)
Definition: init.c:478
packet_id_init
void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
Definition: packet_id.c:79
D_LINK_ERRORS
#define D_LINK_ERRORS
Definition: errlevel.h:57
management_hold
bool management_hold(struct management *man, int holdtime)
Definition: manage.c:3814
M_FATAL
#define M_FATAL
Definition: error.h:95
tls_item_in_cipher_list
bool tls_item_in_cipher_list(const char *item, const char *list)
Return true iff item is present in the colon-separated zero-terminated cipher list.
Definition: ssl_ncp.c:207
init_query_passwords
void init_query_passwords(const struct context *c)
Query for private key and auth-user-pass username/passwords.
Definition: init.c:647
win32.h
options::ce_advance_count
int ce_advance_count
Definition: options.h:287
env_set_destroy
void env_set_destroy(struct env_set *es)
Definition: env_set.c:166
options::auth_token_secret_file
const char * auth_token_secret_file
Definition: options.h:530
EVENT_METHOD_US_TIMEOUT
#define EVENT_METHOD_US_TIMEOUT
Definition: event.h:82
tuntap::windows_driver
enum windows_driver_type windows_driver
Definition: tun.h:213
options_string
char * options_string(const struct options *o, const struct frame *frame, struct tuntap *tt, openvpn_net_ctx_t *ctx, bool remote, struct gc_arena *gc)
Definition: options.c:4212
context_1::tuntap
struct tuntap * tuntap
Tun/tap virtual network interface.
Definition: openvpn.h:170
route_gateway_info
Definition: route.h:146
options::show_ciphers
bool show_ciphers
Definition: options.h:263
RH_PORT_LEN
#define RH_PORT_LEN
Definition: options.h:216
argv
Definition: argv.h:35
context_2::es_owned
bool es_owned
Definition: openvpn.h:427
options::duplicate_cn
bool duplicate_cn
Definition: options.h:511
connection_entry::tls_crypt_file_inline
bool tls_crypt_file_inline
Definition: options.h:161
streq
#define streq(x, y)
Definition: options.h:706
set_check_status_error_delay
static void set_check_status_error_delay(unsigned int milliseconds)
Definition: error.h:292
proto2ascii
const char * proto2ascii(int proto, sa_family_t af, bool display_form)
Definition: socket.c:3127
options::inactivity_minimum_bytes
int64_t inactivity_minimum_bytes
Definition: options.h:331
packet_id_persist_load
void packet_id_persist_load(struct packet_id_persist *p, const char *filename)
Definition: packet_id.c:431
TLS_MODE
#define TLS_MODE(c)
Definition: openvpn.h:542
M_NONFATAL
#define M_NONFATAL
Definition: error.h:96
do_close_free_buf
static void do_close_free_buf(struct context *c)
Definition: init.c:3858
tls_wrap_ctx::tls_crypt_v2_wkc
const struct buffer * tls_crypt_v2_wkc
Wrapped client key, sent to server.
Definition: ssl_common.h:273
occ_reset_op
static int occ_reset_op(void)
Definition: occ.h:101
connection_entry::remote_port
const char * remote_port
Definition: options.h:103
management_sleep
void management_sleep(const int n)
A sleep function that services the management layer for n seconds rather than doing nothing.
Definition: manage.c:4115
context_1::tuntap_owned
bool tuntap_owned
Whether the tun/tap interface should be cleaned up when this context is cleaned up.
Definition: openvpn.h:171
ROUTE_AFTER_TUN
#define ROUTE_AFTER_TUN
Definition: tun.h:380