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