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