~ubuntu-branches/ubuntu/trusty/openvpn/trusty-security

« back to all changes in this revision

Viewing changes to .pc/debian_openssl_vulnkeys.patch/init.c

  • Committer: Bazaar Package Importer
  • Author(s): Chuck Short
  • Date: 2010-05-05 03:06:19 UTC
  • mfrom: (10.2.6 sid)
  • Revision ID: james.westby@ubuntu.com-20100505030619-cwre0snhgx1mql53
Tags: 2.1.0-2ubuntu1
* Merge from debian unstable.  Remaining changes:
  + debian/openvpn.init.d:
    - Do not use start-stop-daemon and use </dev/null to avoid blocking boot
    - Show per-VPN result messages
    - Add "--script-security 2" by default for backwards compatablitiy
   + debian/control: Add lsb-base >= 3.2-14 to allow status_of_proc() 

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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-2009 OpenVPN Technologies, 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
 
20
 *  along with this program (see the file COPYING included with this
 
21
 *  distribution); if not, write to the Free Software Foundation, Inc.,
 
22
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
23
 */
 
24
 
 
25
#include "syshead.h"
 
26
 
 
27
#include "win32.h"
 
28
#include "init.h"
 
29
#include "sig.h"
 
30
#include "occ.h"
 
31
#include "list.h"
 
32
#include "otime.h"
 
33
#include "pool.h"
 
34
#include "gremlin.h"
 
35
#include "pkcs11.h"
 
36
#include "ps.h"
 
37
#include "lladdr.h"
 
38
#include "ping.h"
 
39
 
 
40
#include "memdbg.h"
 
41
 
 
42
#include "occ-inline.h"
 
43
 
 
44
/*
 
45
 * Crypto initialization flags
 
46
 */
 
47
#define CF_LOAD_PERSISTED_PACKET_ID (1<<0)
 
48
#define CF_INIT_TLS_MULTI           (1<<1)
 
49
#define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
 
50
 
 
51
static void do_init_first_time (struct context *c);
 
52
 
 
53
void
 
54
context_clear (struct context *c)
 
55
{
 
56
  CLEAR (*c);
 
57
}
 
58
 
 
59
void
 
60
context_clear_1 (struct context *c)
 
61
{
 
62
  CLEAR (c->c1);
 
63
}
 
64
 
 
65
void
 
66
context_clear_2 (struct context *c)
 
67
{
 
68
  CLEAR (c->c2);
 
69
}
 
70
 
 
71
void
 
72
context_clear_all_except_first_time (struct context *c)
 
73
{
 
74
  const bool first_time_save = c->first_time;
 
75
  const struct context_persist cpsave = c->persist;
 
76
  context_clear (c);
 
77
  c->first_time = first_time_save;
 
78
  c->persist = cpsave;
 
79
}
 
80
 
 
81
/*
 
82
 * Should be called after options->ce is modified at the top
 
83
 * of a SIGUSR1 restart.
 
84
 */
 
85
static void
 
86
update_options_ce_post (struct options *options)
 
87
{
 
88
#if P2MP
 
89
  /*
 
90
   * In pull mode, we usually import --ping/--ping-restart parameters from
 
91
   * the server.  However we should also set an initial default --ping-restart
 
92
   * for the period of time before we pull the --ping-restart parameter
 
93
   * from the server.
 
94
   */
 
95
  if (options->pull
 
96
      && options->ping_rec_timeout_action == PING_UNDEF
 
97
      && options->ce.proto == PROTO_UDPv4)
 
98
    {
 
99
      options->ping_rec_timeout = PRE_PULL_INITIAL_PING_RESTART;
 
100
      options->ping_rec_timeout_action = PING_RESTART;
 
101
    }
 
102
#endif
 
103
#ifdef USE_CRYPTO
 
104
  /* 
 
105
   * Don't use replay window for TCP mode (i.e. require that packets be strictly in sequence).
 
106
   */
 
107
  if (link_socket_proto_connection_oriented (options->ce.proto))
 
108
    options->replay_window = options->replay_time = 0;
 
109
#endif
 
110
}
 
111
 
 
112
/*
 
113
 * Initialize and possibly randomize connection list.
 
114
 */
 
115
static void
 
116
init_connection_list (struct context *c)
 
117
{
 
118
#ifdef ENABLE_CONNECTION
 
119
  struct connection_list *l = c->options.connection_list;
 
120
  if (l)
 
121
    {
 
122
      l->current = -1;
 
123
      if (c->options.remote_random)
 
124
        {
 
125
          int i;
 
126
          for (i = 0; i < l->len; ++i)
 
127
            {
 
128
              const int j = get_random () % l->len;
 
129
              if (i != j)
 
130
                {
 
131
                  struct connection_entry *tmp;
 
132
                  tmp = l->array[i];
 
133
                  l->array[i] = l->array[j];
 
134
                  l->array[j] = tmp;
 
135
                }
 
136
            }
 
137
        }
 
138
    }
 
139
#endif
 
140
}
 
141
 
 
142
/*
 
143
 * Increment to next connection entry
 
144
 */
 
145
static void
 
146
next_connection_entry (struct context *c)
 
147
{
 
148
#ifdef ENABLE_CONNECTION
 
149
  struct connection_list *l = c->options.connection_list;
 
150
  if (l)
 
151
    {
 
152
      if (l->no_advance && l->current >= 0)
 
153
        {
 
154
          l->no_advance = false;
 
155
        }
 
156
      else
 
157
        {
 
158
          int i;
 
159
          if (++l->current >= l->len)
 
160
            l->current = 0;
 
161
 
 
162
          dmsg (D_CONNECTION_LIST, "CONNECTION_LIST len=%d current=%d",
 
163
                l->len, l->current);
 
164
          for (i = 0; i < l->len; ++i)
 
165
            {
 
166
              dmsg (D_CONNECTION_LIST, "[%d] %s:%d",
 
167
                    i,
 
168
                    l->array[i]->remote,
 
169
                    l->array[i]->remote_port);
 
170
            }
 
171
        }
 
172
      c->options.ce = *l->array[l->current];
 
173
    }
 
174
#endif
 
175
  update_options_ce_post (&c->options);
 
176
}
 
177
 
 
178
/*
 
179
 * Query for private key and auth-user-pass username/passwords
 
180
 */
 
181
static void
 
182
init_query_passwords (struct context *c)
 
183
{
 
184
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
185
  /* Certificate password input */
 
186
  if (c->options.key_pass_file)
 
187
    pem_password_setup (c->options.key_pass_file);
 
188
#endif
 
189
  
 
190
#if P2MP
 
191
  /* Auth user/pass input */
 
192
  if (c->options.auth_user_pass_file)
 
193
    auth_user_pass_setup (c->options.auth_user_pass_file);
 
194
#endif
 
195
}
 
196
 
 
197
/*
 
198
 * Initialize/Uninitialize HTTP or SOCKS proxy
 
199
 */
 
200
 
 
201
#ifdef GENERAL_PROXY_SUPPORT
 
202
 
 
203
static int
 
204
proxy_scope (struct context *c)
 
205
{
 
206
  return connection_list_defined (&c->options) ? 2 : 1;
 
207
}
 
208
 
 
209
static void
 
210
uninit_proxy_dowork (struct context *c)
 
211
{
 
212
#ifdef ENABLE_HTTP_PROXY
 
213
  if (c->c1.http_proxy_owned && c->c1.http_proxy)
 
214
    {
 
215
      http_proxy_close (c->c1.http_proxy);
 
216
      c->c1.http_proxy = NULL;
 
217
      c->c1.http_proxy_owned = false;
 
218
    }
 
219
#endif
 
220
#ifdef ENABLE_SOCKS
 
221
  if (c->c1.socks_proxy_owned && c->c1.socks_proxy)
 
222
    {
 
223
      socks_proxy_close (c->c1.socks_proxy);
 
224
      c->c1.socks_proxy = NULL;
 
225
      c->c1.socks_proxy_owned = false;
 
226
    }
 
227
#endif
 
228
}
 
229
 
 
230
static void
 
231
init_proxy_dowork (struct context *c)
 
232
{
 
233
#ifdef ENABLE_HTTP_PROXY
 
234
  bool did_http = false;
 
235
#else
 
236
  const bool did_http = false;
 
237
#endif
 
238
 
 
239
  uninit_proxy_dowork (c);
 
240
 
 
241
#ifdef ENABLE_HTTP_PROXY
 
242
  if (c->options.ce.http_proxy_options || c->options.auto_proxy_info)
 
243
    {
 
244
      /* Possible HTTP proxy user/pass input */
 
245
      c->c1.http_proxy = http_proxy_new (c->options.ce.http_proxy_options,
 
246
                                         c->options.auto_proxy_info);
 
247
      if (c->c1.http_proxy)
 
248
        {
 
249
          did_http = true;
 
250
          c->c1.http_proxy_owned = true;
 
251
        }
 
252
    }
 
253
#endif
 
254
 
 
255
#ifdef ENABLE_SOCKS
 
256
  if (!did_http && (c->options.ce.socks_proxy_server || c->options.auto_proxy_info))
 
257
    {
 
258
      c->c1.socks_proxy = socks_proxy_new (c->options.ce.socks_proxy_server,
 
259
                                           c->options.ce.socks_proxy_port,
 
260
                                           c->options.ce.socks_proxy_retry,
 
261
                                           c->options.auto_proxy_info);
 
262
      if (c->c1.socks_proxy)
 
263
        {
 
264
          c->c1.socks_proxy_owned = true;
 
265
        }
 
266
    }
 
267
#endif
 
268
}
 
269
 
 
270
static void
 
271
init_proxy (struct context *c, const int scope)
 
272
{
 
273
  if (scope == proxy_scope (c))
 
274
    init_proxy_dowork (c);
 
275
}
 
276
 
 
277
static void
 
278
uninit_proxy (struct context *c)
 
279
{
 
280
  if (c->sig->signal_received != SIGUSR1 || proxy_scope (c) == 2)
 
281
    uninit_proxy_dowork (c);
 
282
}
 
283
 
 
284
#else
 
285
 
 
286
static inline void
 
287
init_proxy (struct context *c, const int scope)
 
288
{
 
289
}
 
290
 
 
291
static inline void
 
292
uninit_proxy (struct context *c)
 
293
{
 
294
}
 
295
 
 
296
#endif
 
297
 
 
298
void
 
299
context_init_1 (struct context *c)
 
300
{
 
301
  context_clear_1 (c);
 
302
 
 
303
  packet_id_persist_init (&c->c1.pid_persist);
 
304
 
 
305
  init_connection_list (c);
 
306
 
 
307
  init_query_passwords (c);
 
308
 
 
309
#if defined(ENABLE_PKCS11)
 
310
  if (c->first_time) {
 
311
    int i;
 
312
    pkcs11_initialize (true, c->options.pkcs11_pin_cache_period);
 
313
    for (i=0;i<MAX_PARMS && c->options.pkcs11_providers[i] != NULL;i++)
 
314
     pkcs11_addProvider (c->options.pkcs11_providers[i], c->options.pkcs11_protected_authentication[i],
 
315
       c->options.pkcs11_private_mode[i], c->options.pkcs11_cert_private[i]);
 
316
  }
 
317
#endif
 
318
 
 
319
#if 0 /* test get_user_pass with GET_USER_PASS_NEED_OK flag */
 
320
 {
 
321
   /*
 
322
    * In the management interface, you can okay the request by entering "needok token-insertion-request ok"
 
323
    */
 
324
   struct user_pass up;
 
325
   CLEAR (up);
 
326
   strcpy (up.username, "Please insert your cryptographic token"); /* put the high-level message in up.username */
 
327
   get_user_pass (&up, NULL, "token-insertion-request", GET_USER_PASS_MANAGEMENT|GET_USER_PASS_NEED_OK);
 
328
   msg (M_INFO, "RET:%s", up.password); /* will return the third argument to management interface
 
329
                                           'needok' command, usually 'ok' or 'cancel'. */
 
330
 }
 
331
#endif
 
332
 
 
333
  /* initialize HTTP or SOCKS proxy object at scope level 1 */
 
334
  init_proxy (c, 1);
 
335
}
 
336
 
 
337
void
 
338
context_gc_free (struct context *c)
 
339
{
 
340
  gc_free (&c->c2.gc);
 
341
  gc_free (&c->options.gc);
 
342
  gc_free (&c->gc);
 
343
}
 
344
 
 
345
#if PORT_SHARE
 
346
 
 
347
static void
 
348
close_port_share (void)
 
349
{
 
350
  if (port_share)
 
351
    {
 
352
      port_share_close (port_share);
 
353
      port_share = NULL;
 
354
    }
 
355
}
 
356
 
 
357
static void
 
358
init_port_share (struct context *c)
 
359
{
 
360
  if (!port_share && (c->options.port_share_host && c->options.port_share_port))
 
361
    {
 
362
      port_share = port_share_open (c->options.port_share_host,
 
363
                                    c->options.port_share_port);
 
364
      if (port_share == NULL)
 
365
        msg (M_FATAL, "Fatal error: Port sharing failed");
 
366
    }
 
367
}
 
368
 
 
369
#endif
 
370
 
 
371
bool
 
372
init_static (void)
 
373
{
 
374
  /* configure_path (); */
 
375
 
 
376
#if defined(USE_CRYPTO) && defined(DMALLOC)
 
377
  openssl_dmalloc_init ();
 
378
#endif
 
379
 
 
380
  init_random_seed ();          /* init random() function, only used as
 
381
                                   source for weak random numbers */
 
382
  error_reset ();               /* initialize error.c */
 
383
  reset_check_status ();        /* initialize status check code in socket.c */
 
384
 
 
385
#ifdef WIN32
 
386
  init_win32 ();
 
387
#endif
 
388
 
 
389
#ifdef OPENVPN_DEBUG_COMMAND_LINE
 
390
  {
 
391
    int i;
 
392
    for (i = 0; i < argc; ++i)
 
393
      msg (M_INFO, "argv[%d] = '%s'", i, argv[i]);
 
394
  }
 
395
#endif
 
396
 
 
397
  update_time ();
 
398
 
 
399
#ifdef USE_CRYPTO
 
400
  init_ssl_lib ();
 
401
 
 
402
  /* init PRNG used for IV generation */
 
403
  /* When forking, copy this to more places in the code to avoid fork
 
404
     random-state predictability */
 
405
  prng_init (NULL, 0);
 
406
#endif
 
407
 
 
408
#ifdef PID_TEST
 
409
  packet_id_interactive_test ();        /* test the sequence number code */
 
410
  return false;
 
411
#endif
 
412
 
 
413
#ifdef SCHEDULE_TEST
 
414
  schedule_test ();
 
415
  return false;
 
416
#endif
 
417
 
 
418
#ifdef LIST_TEST
 
419
  list_test ();
 
420
  return false;
 
421
#endif
 
422
 
 
423
#ifdef IFCONFIG_POOL_TEST
 
424
  ifconfig_pool_test (0x0A010004, 0x0A0100FF);
 
425
  return false;
 
426
#endif
 
427
 
 
428
#ifdef CHARACTER_CLASS_DEBUG
 
429
  character_class_debug ();
 
430
  return false;
 
431
#endif
 
432
 
 
433
#ifdef EXTRACT_X509_FIELD_TEST
 
434
  extract_x509_field_test ();
 
435
  return false;
 
436
#endif
 
437
 
 
438
#ifdef TIME_TEST
 
439
  time_test ();
 
440
  return false;
 
441
#endif
 
442
 
 
443
#ifdef GEN_PATH_TEST
 
444
  {
 
445
    struct gc_arena gc = gc_new ();
 
446
    const char *fn = gen_path ("foo",
 
447
                               "bar",
 
448
                               &gc);
 
449
    printf ("%s\n", fn);
 
450
    gc_free (&gc);
 
451
  }
 
452
  return false;
 
453
#endif
 
454
 
 
455
#ifdef STATUS_PRINTF_TEST
 
456
  {
 
457
    struct gc_arena gc = gc_new ();
 
458
    const char *tmp_file = create_temp_filename ("/tmp", "foo", &gc);
 
459
    struct status_output *so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
 
460
    status_printf (so, "%s", "foo");
 
461
    status_printf (so, "%s", "bar");
 
462
    if (!status_close (so))
 
463
      msg (M_WARN, "STATUS_PRINTF_TEST: %s: write error", tmp_file);
 
464
    gc_free (&gc);
 
465
  }
 
466
  return false;
 
467
#endif
 
468
 
 
469
#ifdef ARGV_TEST
 
470
  {
 
471
    void argv_test (void);
 
472
    argv_test ();
 
473
    return false;
 
474
  }
 
475
#endif
 
476
 
 
477
#ifdef PRNG_TEST
 
478
  {
 
479
    struct gc_arena gc = gc_new ();
 
480
    uint8_t rndbuf[8];
 
481
    int i;
 
482
    prng_init ("sha1", 16);
 
483
    //prng_init (NULL, 0);
 
484
    const int factor = 1;
 
485
    for (i = 0; i < factor * 8; ++i)
 
486
      {
 
487
#if 1
 
488
        prng_bytes (rndbuf, sizeof (rndbuf));
 
489
#else
 
490
        ASSERT(RAND_bytes (rndbuf, sizeof (rndbuf)));
 
491
#endif
 
492
        printf ("[%d] %s\n", i, format_hex (rndbuf, sizeof (rndbuf), 0, &gc));
 
493
      }
 
494
    gc_free (&gc);
 
495
    prng_uninit ();
 
496
    return false;
 
497
  }
 
498
#endif
 
499
 
 
500
  return true;
 
501
}
 
502
 
 
503
void
 
504
uninit_static (void)
 
505
{
 
506
  openvpn_thread_cleanup ();
 
507
 
 
508
#ifdef USE_CRYPTO
 
509
  free_ssl_lib ();
 
510
#endif
 
511
 
 
512
#ifdef ENABLE_PKCS11
 
513
  pkcs11_terminate ();
 
514
#endif
 
515
 
 
516
#if PORT_SHARE
 
517
  close_port_share ();
 
518
#endif
 
519
 
 
520
#if defined(MEASURE_TLS_HANDSHAKE_STATS) && defined(USE_CRYPTO) && defined(USE_SSL)
 
521
  show_tls_performance_stats ();
 
522
#endif
 
523
}
 
524
 
 
525
void
 
526
init_verb_mute (struct context *c, unsigned int flags)
 
527
{
 
528
  if (flags & IVM_LEVEL_1)
 
529
    {
 
530
      /* set verbosity and mute levels */
 
531
      set_check_status (D_LINK_ERRORS, D_READ_WRITE);
 
532
      set_debug_level (c->options.verbosity, SDL_CONSTRAIN);
 
533
      set_mute_cutoff (c->options.mute);
 
534
    }
 
535
 
 
536
  /* special D_LOG_RW mode */
 
537
  if (flags & IVM_LEVEL_2)
 
538
    c->c2.log_rw = (check_debug_level (D_LOG_RW) && !check_debug_level (D_LOG_RW + 1));
 
539
}
 
540
 
 
541
/*
 
542
 * Possibly set --dev based on --dev-node.
 
543
 * For example, if --dev-node /tmp/foo/tun, and --dev undefined,
 
544
 * set --dev to tun.
 
545
 */
 
546
void
 
547
init_options_dev (struct options *options)
 
548
{
 
549
  if (!options->dev)
 
550
    options->dev = openvpn_basename (options->dev_node);
 
551
}
 
552
 
 
553
bool
 
554
print_openssl_info (const struct options *options)
 
555
{
 
556
  /*
 
557
   * OpenSSL info print mode?
 
558
   */
 
559
#ifdef USE_CRYPTO
 
560
  if (options->show_ciphers || options->show_digests || options->show_engines
 
561
#ifdef USE_SSL
 
562
      || options->show_tls_ciphers
 
563
#endif
 
564
    )
 
565
    {
 
566
      if (options->show_ciphers)
 
567
        show_available_ciphers ();
 
568
      if (options->show_digests)
 
569
        show_available_digests ();
 
570
      if (options->show_engines)
 
571
        show_available_engines ();
 
572
#ifdef USE_SSL
 
573
      if (options->show_tls_ciphers)
 
574
        show_available_tls_ciphers ();
 
575
#endif
 
576
      return true;
 
577
    }
 
578
#endif
 
579
  return false;
 
580
}
 
581
 
 
582
/*
 
583
 * Static pre-shared key generation mode?
 
584
 */
 
585
bool
 
586
do_genkey (const struct options * options)
 
587
{
 
588
#ifdef USE_CRYPTO
 
589
  if (options->genkey)
 
590
    {
 
591
      int nbits_written;
 
592
 
 
593
      notnull (options->shared_secret_file,
 
594
               "shared secret output file (--secret)");
 
595
 
 
596
      if (options->mlock)       /* should we disable paging? */
 
597
        do_mlockall (true);
 
598
 
 
599
      nbits_written = write_key_file (2, options->shared_secret_file);
 
600
 
 
601
      msg (D_GENKEY | M_NOPREFIX,
 
602
           "Randomly generated %d bit key written to %s", nbits_written,
 
603
           options->shared_secret_file);
 
604
      return true;
 
605
    }
 
606
#endif
 
607
  return false;
 
608
}
 
609
 
 
610
/*
 
611
 * Persistent TUN/TAP device management mode?
 
612
 */
 
613
bool
 
614
do_persist_tuntap (const struct options *options)
 
615
{
 
616
#ifdef TUNSETPERSIST
 
617
  if (options->persist_config)
 
618
    {
 
619
      /* sanity check on options for --mktun or --rmtun */
 
620
      notnull (options->dev, "TUN/TAP device (--dev)");
 
621
      if (options->ce.remote || options->ifconfig_local
 
622
          || options->ifconfig_remote_netmask
 
623
#ifdef USE_CRYPTO
 
624
          || options->shared_secret_file
 
625
#ifdef USE_SSL
 
626
          || options->tls_server || options->tls_client
 
627
#endif
 
628
#endif
 
629
        )
 
630
        msg (M_FATAL|M_OPTERR,
 
631
             "options --mktun or --rmtun should only be used together with --dev");
 
632
      tuncfg (options->dev, options->dev_type, options->dev_node,
 
633
              options->tun_ipv6, options->persist_mode,
 
634
              options->username, options->groupname, &options->tuntap_options);
 
635
      if (options->persist_mode && options->lladdr)
 
636
        set_lladdr(options->dev, options->lladdr, NULL);
 
637
      return true;
 
638
    }
 
639
#endif
 
640
  return false;
 
641
}
 
642
 
 
643
/*
 
644
 * Should we become a daemon?
 
645
 * Return true if we did it.
 
646
 */
 
647
static bool
 
648
possibly_become_daemon (const struct options *options, const bool first_time)
 
649
{
 
650
  bool ret = false;
 
651
  if (first_time && options->daemon)
 
652
    {
 
653
      ASSERT (!options->inetd);
 
654
      if (daemon (options->cd_dir != NULL, options->log) < 0)
 
655
        msg (M_ERR, "daemon() failed");
 
656
      restore_signal_state ();
 
657
      if (options->log)
 
658
        set_std_files_to_null (true);
 
659
 
 
660
#if defined(ENABLE_PKCS11)
 
661
      pkcs11_forkFixup ();
 
662
#endif
 
663
 
 
664
      ret = true;
 
665
    }
 
666
  return ret;
 
667
}
 
668
 
 
669
/*
 
670
 * Actually do UID/GID downgrade, chroot and SELinux context switching, if requested.
 
671
 */
 
672
static void
 
673
do_uid_gid_chroot (struct context *c, bool no_delay)
 
674
{
 
675
  static const char why_not[] = "will be delayed because of --client, --pull, or --up-delay";
 
676
  struct context_0 *c0 = c->c0;
 
677
 
 
678
  if (c->first_time && c0 && !c0->uid_gid_set)
 
679
    {
 
680
      /* chroot if requested */
 
681
      if (c->options.chroot_dir)
 
682
        {
 
683
          if (no_delay)
 
684
            do_chroot (c->options.chroot_dir);
 
685
          else
 
686
            msg (M_INFO, "NOTE: chroot %s", why_not);
 
687
        }
 
688
 
 
689
      /* set user and/or group that we want to setuid/setgid to */
 
690
      if (no_delay)
 
691
        {
 
692
          set_group (&c0->group_state);
 
693
          set_user (&c0->user_state);
 
694
          c0->uid_gid_set = true;
 
695
        }
 
696
      else if (c0->uid_gid_specified)
 
697
        {
 
698
          msg (M_INFO, "NOTE: UID/GID downgrade %s", why_not);
 
699
        }
 
700
 
 
701
#ifdef HAVE_SETCON
 
702
      /* Apply a SELinux context in order to restrict what OpenVPN can do
 
703
       * to _only_ what it is supposed to do after initialization is complete
 
704
       * (basically just network I/O operations). Doing it after chroot
 
705
       * requires /proc to be mounted in the chroot (which is annoying indeed
 
706
       * but doing it before requires more complex SELinux policies.
 
707
       */
 
708
      if (c->options.selinux_context)
 
709
        {
 
710
          if (no_delay) {
 
711
            if (-1 == setcon (c->options.selinux_context))
 
712
              msg (M_ERR, "setcon to '%s' failed; is /proc accessible?", c->options.selinux_context);
 
713
            else
 
714
              msg (M_INFO, "setcon to '%s' succeeded", c->options.selinux_context);
 
715
          }
 
716
          else
 
717
            msg (M_INFO, "NOTE: setcon %s", why_not);
 
718
        }
 
719
#endif
 
720
    }
 
721
}
 
722
 
 
723
/*
 
724
 * Return common name in a way that is formatted for
 
725
 * prepending to msg() output.
 
726
 */
 
727
const char *
 
728
format_common_name (struct context *c, struct gc_arena *gc)
 
729
{
 
730
  struct buffer out = alloc_buf_gc (256, gc);
 
731
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
732
  if (c->c2.tls_multi)
 
733
    {
 
734
      buf_printf (&out, "[%s] ", tls_common_name (c->c2.tls_multi, false));
 
735
    }
 
736
#endif
 
737
  return BSTR (&out);
 
738
}
 
739
 
 
740
void
 
741
pre_setup (const struct options *options)
 
742
{
 
743
#ifdef WIN32
 
744
  if (options->exit_event_name)
 
745
    {
 
746
      win32_signal_open (&win32_signal,
 
747
                         WSO_FORCE_SERVICE,
 
748
                         options->exit_event_name,
 
749
                         options->exit_event_initial_state);
 
750
    }
 
751
  else
 
752
    {
 
753
      win32_signal_open (&win32_signal,
 
754
                         WSO_FORCE_CONSOLE,
 
755
                         NULL,
 
756
                         false);
 
757
 
 
758
      /* put a title on the top window bar */
 
759
      if (win32_signal.mode == WSO_MODE_CONSOLE)
 
760
        {
 
761
          window_title_save (&window_title); 
 
762
          window_title_generate (options->config);
 
763
        }
 
764
    }
 
765
#endif
 
766
}
 
767
 
 
768
void
 
769
reset_coarse_timers (struct context *c)
 
770
{
 
771
  c->c2.coarse_timer_wakeup = 0;
 
772
}
 
773
 
 
774
/*
 
775
 * Initialize timers
 
776
 */
 
777
static void
 
778
do_init_timers (struct context *c, bool deferred)
 
779
{
 
780
  update_time ();
 
781
  reset_coarse_timers (c);
 
782
 
 
783
  /* initialize inactivity timeout */
 
784
  if (c->options.inactivity_timeout)
 
785
    event_timeout_init (&c->c2.inactivity_interval, c->options.inactivity_timeout, now);
 
786
 
 
787
  /* initialize pings */
 
788
 
 
789
  if (c->options.ping_send_timeout)
 
790
    event_timeout_init (&c->c2.ping_send_interval, c->options.ping_send_timeout, 0);
 
791
 
 
792
  if (c->options.ping_rec_timeout)
 
793
    event_timeout_init (&c->c2.ping_rec_interval, c->options.ping_rec_timeout, now);
 
794
 
 
795
#if P2MP
 
796
  if (c->options.server_poll_timeout)
 
797
    event_timeout_init (&c->c2.server_poll_interval, c->options.server_poll_timeout, now);
 
798
#endif
 
799
 
 
800
  if (!deferred)
 
801
    {
 
802
      /* initialize connection establishment timer */
 
803
      event_timeout_init (&c->c2.wait_for_connect, 1, now);
 
804
 
 
805
#ifdef ENABLE_OCC
 
806
      /* initialize occ timers */
 
807
 
 
808
      if (c->options.occ
 
809
          && !TLS_MODE (c)
 
810
          && c->c2.options_string_local && c->c2.options_string_remote)
 
811
        event_timeout_init (&c->c2.occ_interval, OCC_INTERVAL_SECONDS, now);
 
812
 
 
813
      if (c->options.mtu_test)
 
814
        event_timeout_init (&c->c2.occ_mtu_load_test_interval, OCC_MTU_LOAD_INTERVAL_SECONDS, now);
 
815
#endif
 
816
 
 
817
      /* initialize packet_id persistence timer */
 
818
#ifdef USE_CRYPTO
 
819
      if (c->options.packet_id_file)
 
820
        event_timeout_init (&c->c2.packet_id_persist_interval, 60, now);
 
821
#endif
 
822
 
 
823
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
824
      /* initialize tmp_int optimization that limits the number of times we call
 
825
         tls_multi_process in the main event loop */
 
826
      interval_init (&c->c2.tmp_int, TLS_MULTI_HORIZON, TLS_MULTI_REFRESH);
 
827
#endif
 
828
    }
 
829
}
 
830
 
 
831
/*
 
832
 * Initialize traffic shaper.
 
833
 */
 
834
static void
 
835
do_init_traffic_shaper (struct context *c)
 
836
{
 
837
#ifdef HAVE_GETTIMEOFDAY
 
838
  /* initialize traffic shaper (i.e. transmit bandwidth limiter) */
 
839
  if (c->options.shaper)
 
840
    {
 
841
      shaper_init (&c->c2.shaper, c->options.shaper);
 
842
      shaper_msg (&c->c2.shaper);
 
843
    }
 
844
#endif
 
845
}
 
846
 
 
847
/*
 
848
 * Allocate a route list structure if at least one
 
849
 * --route option was specified.
 
850
 */
 
851
static void
 
852
do_alloc_route_list (struct context *c)
 
853
{
 
854
  if (c->options.routes && !c->c1.route_list)
 
855
    c->c1.route_list = new_route_list (c->options.max_routes, &c->gc);
 
856
}
 
857
 
 
858
 
 
859
/*
 
860
 * Initialize the route list, resolving any DNS names in route
 
861
 * options and saving routes in the environment.
 
862
 */
 
863
static void
 
864
do_init_route_list (const struct options *options,
 
865
                    struct route_list *route_list,
 
866
                    const struct link_socket_info *link_socket_info,
 
867
                    bool fatal,
 
868
                    struct env_set *es)
 
869
{
 
870
  const char *gw = NULL;
 
871
  int dev = dev_type_enum (options->dev, options->dev_type);
 
872
  int metric = 0;
 
873
 
 
874
  if (dev == DEV_TYPE_TUN && (options->topology == TOP_NET30 || options->topology == TOP_P2P))
 
875
    gw = options->ifconfig_remote_netmask;
 
876
  if (options->route_default_gateway)
 
877
    gw = options->route_default_gateway;
 
878
  if (options->route_default_metric)
 
879
    metric = options->route_default_metric;
 
880
 
 
881
  if (!init_route_list (route_list,
 
882
                        options->routes,
 
883
                        gw,
 
884
                        metric,
 
885
                        link_socket_current_remote (link_socket_info),
 
886
                        es))
 
887
    {
 
888
      if (fatal)
 
889
        openvpn_exit (OPENVPN_EXIT_STATUS_ERROR);       /* exit point */
 
890
    }
 
891
  else
 
892
    {
 
893
      /* copy routes to environment */
 
894
      setenv_routes (es, route_list);
 
895
    }
 
896
}
 
897
 
 
898
/*
 
899
 * Called after all initialization has been completed.
 
900
 */
 
901
void
 
902
initialization_sequence_completed (struct context *c, const unsigned int flags)
 
903
{
 
904
  static const char message[] = "Initialization Sequence Completed";
 
905
 
 
906
  /* If we delayed UID/GID downgrade or chroot, do it now */
 
907
  do_uid_gid_chroot (c, true);
 
908
 
 
909
  /* Test if errors */
 
910
  if (flags & ISC_ERRORS)
 
911
    {
 
912
#ifdef WIN32
 
913
      show_routes (M_INFO|M_NOPREFIX);
 
914
      show_adapters (M_INFO|M_NOPREFIX);
 
915
      msg (M_INFO, "%s With Errors ( see http://openvpn.net/faq.html#dhcpclientserv )", message);
 
916
#else
 
917
      msg (M_INFO, "%s With Errors", message);
 
918
#endif
 
919
    }
 
920
  else
 
921
    msg (M_INFO, "%s", message);
 
922
 
 
923
  /* Flag connection_list that we initialized */
 
924
  if ((flags & (ISC_ERRORS|ISC_SERVER)) == 0 && connection_list_defined (&c->options))
 
925
    connection_list_set_no_advance (&c->options);
 
926
 
 
927
#ifdef ENABLE_MANAGEMENT
 
928
  /* Tell management interface that we initialized */
 
929
  if (management)
 
930
    {
 
931
      in_addr_t tun_local = 0;
 
932
      in_addr_t tun_remote = 0; /* FKS */
 
933
      const char *detail = "SUCCESS";
 
934
      if (c->c1.tuntap)
 
935
        tun_local = c->c1.tuntap->local;
 
936
      tun_remote = htonl (c->c1.link_socket_addr.actual.dest.sa.sin_addr.s_addr);
 
937
      if (flags & ISC_ERRORS)
 
938
        detail = "ERROR";
 
939
      management_set_state (management,
 
940
                            OPENVPN_STATE_CONNECTED,
 
941
                            detail,
 
942
                            tun_local,
 
943
                            tun_remote);
 
944
      if (tun_local)
 
945
        management_post_tunnel_open (management, tun_local);
 
946
    }
 
947
#endif
 
948
 
 
949
}
 
950
 
 
951
/*
 
952
 * Possibly add routes and/or call route-up script
 
953
 * based on options.
 
954
 */
 
955
void
 
956
do_route (const struct options *options,
 
957
          struct route_list *route_list,
 
958
          const struct tuntap *tt,
 
959
          const struct plugin_list *plugins,
 
960
          struct env_set *es)
 
961
{
 
962
  if (!options->route_noexec && route_list)
 
963
    add_routes (route_list, tt, ROUTE_OPTION_FLAGS (options), es);
 
964
 
 
965
  if (plugin_defined (plugins, OPENVPN_PLUGIN_ROUTE_UP))
 
966
    {
 
967
      if (plugin_call (plugins, OPENVPN_PLUGIN_ROUTE_UP, NULL, NULL, es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
 
968
        msg (M_WARN, "WARNING: route-up plugin call failed");
 
969
    }
 
970
 
 
971
  if (options->route_script)
 
972
    {
 
973
      struct argv argv = argv_new ();
 
974
      setenv_str (es, "script_type", "route-up");
 
975
      argv_printf (&argv, "%sc", options->route_script);
 
976
      openvpn_execve_check (&argv, es, S_SCRIPT, "Route script failed");
 
977
      argv_reset (&argv);
 
978
    }
 
979
 
 
980
#ifdef WIN32
 
981
  if (options->show_net_up)
 
982
    {
 
983
      show_routes (M_INFO|M_NOPREFIX);
 
984
      show_adapters (M_INFO|M_NOPREFIX);
 
985
    }
 
986
  else if (check_debug_level (D_SHOW_NET))
 
987
    {
 
988
      show_routes (D_SHOW_NET|M_NOPREFIX);
 
989
      show_adapters (D_SHOW_NET|M_NOPREFIX);
 
990
    }
 
991
#endif
 
992
}
 
993
 
 
994
/*
 
995
 * Save current pulled options string in the c1 context store, so we can
 
996
 * compare against it after possible future restarts.
 
997
 */
 
998
#if P2MP
 
999
static void
 
1000
save_pulled_options_digest (struct context *c, const struct md5_digest *newdigest)
 
1001
{
 
1002
  if (newdigest)
 
1003
    c->c1.pulled_options_digest_save = *newdigest;
 
1004
  else
 
1005
    md5_digest_clear (&c->c1.pulled_options_digest_save);
 
1006
}
 
1007
#endif
 
1008
 
 
1009
/*
 
1010
 * initialize tun/tap device object
 
1011
 */
 
1012
static void
 
1013
do_init_tun (struct context *c)
 
1014
{
 
1015
  c->c1.tuntap = init_tun (c->options.dev,
 
1016
                           c->options.dev_type,
 
1017
                           c->options.topology,
 
1018
                           c->options.ifconfig_local,
 
1019
                           c->options.ifconfig_remote_netmask,
 
1020
                           addr_host (&c->c1.link_socket_addr.local),
 
1021
                           addr_host (&c->c1.link_socket_addr.remote),
 
1022
                           !c->options.ifconfig_nowarn,
 
1023
                           c->c2.es);
 
1024
 
 
1025
  init_tun_post (c->c1.tuntap,
 
1026
                 &c->c2.frame,
 
1027
                 &c->options.tuntap_options);
 
1028
 
 
1029
  c->c1.tuntap_owned = true;
 
1030
}
 
1031
 
 
1032
/*
 
1033
 * Open tun/tap device, ifconfig, call up script, etc.
 
1034
 */
 
1035
 
 
1036
static bool
 
1037
do_open_tun (struct context *c)
 
1038
{
 
1039
  struct gc_arena gc = gc_new ();
 
1040
  bool ret = false;
 
1041
 
 
1042
  c->c2.ipv4_tun = (!c->options.tun_ipv6
 
1043
                    && is_dev_type (c->options.dev, c->options.dev_type, "tun"));
 
1044
 
 
1045
  if (!c->c1.tuntap)
 
1046
    {
 
1047
      /* initialize (but do not open) tun/tap object */
 
1048
      do_init_tun (c);
 
1049
 
 
1050
      /* allocate route list structure */
 
1051
      do_alloc_route_list (c);
 
1052
 
 
1053
      /* parse and resolve the route option list */
 
1054
      if (c->options.routes && c->c1.route_list && c->c2.link_socket)
 
1055
        do_init_route_list (&c->options, c->c1.route_list, &c->c2.link_socket->info, false, c->c2.es);
 
1056
 
 
1057
      /* do ifconfig */
 
1058
      if (!c->options.ifconfig_noexec
 
1059
          && ifconfig_order () == IFCONFIG_BEFORE_TUN_OPEN)
 
1060
        {
 
1061
          /* guess actual tun/tap unit number that will be returned
 
1062
             by open_tun */
 
1063
          const char *guess = guess_tuntap_dev (c->options.dev,
 
1064
                                                c->options.dev_type,
 
1065
                                                c->options.dev_node,
 
1066
                                                &gc);
 
1067
          do_ifconfig (c->c1.tuntap, guess, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
 
1068
        }
 
1069
 
 
1070
      /* open the tun device */
 
1071
      open_tun (c->options.dev, c->options.dev_type, c->options.dev_node,
 
1072
                c->options.tun_ipv6, c->c1.tuntap);
 
1073
 
 
1074
      /* set the hardware address */
 
1075
      if (c->options.lladdr)
 
1076
          set_lladdr(c->c1.tuntap->actual_name, c->options.lladdr, c->c2.es);
 
1077
 
 
1078
      /* do ifconfig */
 
1079
      if (!c->options.ifconfig_noexec
 
1080
          && ifconfig_order () == IFCONFIG_AFTER_TUN_OPEN)
 
1081
        {
 
1082
          do_ifconfig (c->c1.tuntap, c->c1.tuntap->actual_name, TUN_MTU_SIZE (&c->c2.frame), c->c2.es);
 
1083
        }
 
1084
 
 
1085
      /* run the up script */
 
1086
      run_up_down (c->options.up_script,
 
1087
                   c->plugins,
 
1088
                   OPENVPN_PLUGIN_UP,
 
1089
                   c->c1.tuntap->actual_name,
 
1090
                   TUN_MTU_SIZE (&c->c2.frame),
 
1091
                   EXPANDED_SIZE (&c->c2.frame),
 
1092
                   print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
 
1093
                   print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
 
1094
                   "init",
 
1095
                   NULL,
 
1096
                   "up",
 
1097
                   c->c2.es);
 
1098
 
 
1099
      /* possibly add routes */
 
1100
      if (!c->options.route_delay_defined)
 
1101
        do_route (&c->options, c->c1.route_list, c->c1.tuntap, c->plugins, c->c2.es);
 
1102
 
 
1103
      /*
 
1104
       * Did tun/tap driver give us an MTU?
 
1105
       */
 
1106
      if (c->c1.tuntap->post_open_mtu)
 
1107
        frame_set_mtu_dynamic (&c->c2.frame,
 
1108
                               c->c1.tuntap->post_open_mtu,
 
1109
                               SET_MTU_TUN | SET_MTU_UPPER_BOUND);
 
1110
 
 
1111
      ret = true;
 
1112
    }
 
1113
  else
 
1114
    {
 
1115
      msg (M_INFO, "Preserving previous TUN/TAP instance: %s",
 
1116
           c->c1.tuntap->actual_name);
 
1117
 
 
1118
      /* run the up script if user specified --up-restart */
 
1119
      if (c->options.up_restart)
 
1120
        run_up_down (c->options.up_script,
 
1121
                     c->plugins,
 
1122
                     OPENVPN_PLUGIN_UP,
 
1123
                     c->c1.tuntap->actual_name,
 
1124
                     TUN_MTU_SIZE (&c->c2.frame),
 
1125
                     EXPANDED_SIZE (&c->c2.frame),
 
1126
                     print_in_addr_t (c->c1.tuntap->local, IA_EMPTY_IF_UNDEF, &gc),
 
1127
                     print_in_addr_t (c->c1.tuntap->remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
 
1128
                     "restart",
 
1129
                     NULL,
 
1130
                     "up",
 
1131
                     c->c2.es);
 
1132
    }
 
1133
  gc_free (&gc);
 
1134
  return ret;
 
1135
}
 
1136
 
 
1137
/*
 
1138
 * Close TUN/TAP device
 
1139
 */
 
1140
 
 
1141
static void
 
1142
do_close_tun_simple (struct context *c)
 
1143
{
 
1144
  msg (D_CLOSE, "Closing TUN/TAP interface");
 
1145
  close_tun (c->c1.tuntap);
 
1146
  c->c1.tuntap = NULL;
 
1147
  c->c1.tuntap_owned = false;
 
1148
#if P2MP
 
1149
  save_pulled_options_digest (c, NULL); /* delete C1-saved pulled_options_digest */
 
1150
#endif
 
1151
}
 
1152
 
 
1153
static void
 
1154
do_close_tun (struct context *c, bool force)
 
1155
{
 
1156
  struct gc_arena gc = gc_new ();
 
1157
  if (c->c1.tuntap && c->c1.tuntap_owned)
 
1158
    {
 
1159
      const char *tuntap_actual = string_alloc (c->c1.tuntap->actual_name, &gc);
 
1160
      const in_addr_t local = c->c1.tuntap->local;
 
1161
      const in_addr_t remote_netmask = c->c1.tuntap->remote_netmask;
 
1162
 
 
1163
      if (force || !(c->sig->signal_received == SIGUSR1 && c->options.persist_tun))
 
1164
        {
 
1165
#ifdef ENABLE_MANAGEMENT
 
1166
          /* tell management layer we are about to close the TUN/TAP device */
 
1167
          if (management)
 
1168
            management_pre_tunnel_close (management);
 
1169
#endif
 
1170
 
 
1171
          /* delete any routes we added */
 
1172
          if (c->c1.route_list)
 
1173
            delete_routes (c->c1.route_list, c->c1.tuntap, ROUTE_OPTION_FLAGS (&c->options), c->c2.es);
 
1174
 
 
1175
          /* actually close tun/tap device based on --down-pre flag */
 
1176
          if (!c->options.down_pre)
 
1177
            do_close_tun_simple (c);
 
1178
 
 
1179
          /* Run the down script -- note that it will run at reduced
 
1180
             privilege if, for example, "--user nobody" was used. */
 
1181
          run_up_down (c->options.down_script,
 
1182
                       c->plugins,
 
1183
                       OPENVPN_PLUGIN_DOWN,
 
1184
                       tuntap_actual,
 
1185
                       TUN_MTU_SIZE (&c->c2.frame),
 
1186
                       EXPANDED_SIZE (&c->c2.frame),
 
1187
                       print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
 
1188
                       print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
 
1189
                       "init",
 
1190
                       signal_description (c->sig->signal_received,
 
1191
                                           c->sig->signal_text),
 
1192
                       "down",
 
1193
                       c->c2.es);
 
1194
 
 
1195
          /* actually close tun/tap device based on --down-pre flag */
 
1196
          if (c->options.down_pre)
 
1197
            do_close_tun_simple (c);
 
1198
        }
 
1199
      else
 
1200
        {
 
1201
          /* run the down script on this restart if --up-restart was specified */
 
1202
          if (c->options.up_restart)
 
1203
            run_up_down (c->options.down_script,
 
1204
                         c->plugins,
 
1205
                         OPENVPN_PLUGIN_DOWN,
 
1206
                         tuntap_actual,
 
1207
                         TUN_MTU_SIZE (&c->c2.frame),
 
1208
                         EXPANDED_SIZE (&c->c2.frame),
 
1209
                         print_in_addr_t (local, IA_EMPTY_IF_UNDEF, &gc),
 
1210
                         print_in_addr_t (remote_netmask, IA_EMPTY_IF_UNDEF, &gc),
 
1211
                         "restart",
 
1212
                         signal_description (c->sig->signal_received,
 
1213
                                             c->sig->signal_text),
 
1214
                         "down",
 
1215
                         c->c2.es);
 
1216
        }
 
1217
    }
 
1218
  gc_free (&gc);
 
1219
}
 
1220
 
 
1221
/*
 
1222
 * Handle delayed tun/tap interface bringup due to --up-delay or --pull
 
1223
 */
 
1224
 
 
1225
void
 
1226
do_up (struct context *c, bool pulled_options, unsigned int option_types_found)
 
1227
{
 
1228
  if (!c->c2.do_up_ran)
 
1229
    {
 
1230
      reset_coarse_timers (c);
 
1231
 
 
1232
      if (pulled_options && option_types_found)
 
1233
        do_deferred_options (c, option_types_found);
 
1234
 
 
1235
      /* if --up-delay specified, open tun, do ifconfig, and run up script now */
 
1236
      if (c->options.up_delay || PULL_DEFINED (&c->options))
 
1237
        {
 
1238
          c->c2.did_open_tun = do_open_tun (c);
 
1239
          update_time ();
 
1240
 
 
1241
#if P2MP
 
1242
          /*
 
1243
           * Was tun interface object persisted from previous restart iteration,
 
1244
           * and if so did pulled options string change from previous iteration?
 
1245
           */
 
1246
          if (!c->c2.did_open_tun
 
1247
              && PULL_DEFINED (&c->options)
 
1248
              && c->c1.tuntap
 
1249
              && (!md5_digest_defined (&c->c1.pulled_options_digest_save) || !md5_digest_defined (&c->c2.pulled_options_digest)
 
1250
                  || !md5_digest_equal (&c->c1.pulled_options_digest_save, &c->c2.pulled_options_digest)))
 
1251
            {
 
1252
              /* if so, close tun, delete routes, then reinitialize tun and add routes */
 
1253
              msg (M_INFO, "NOTE: Pulled options changed on restart, will need to close and reopen TUN/TAP device.");
 
1254
              do_close_tun (c, true);
 
1255
              openvpn_sleep (1);
 
1256
              c->c2.did_open_tun = do_open_tun (c);
 
1257
              update_time ();
 
1258
            }
 
1259
#endif
 
1260
        }
 
1261
 
 
1262
      if (c->c2.did_open_tun)
 
1263
        {
 
1264
#if P2MP
 
1265
          save_pulled_options_digest (c, &c->c2.pulled_options_digest);
 
1266
#endif
 
1267
 
 
1268
          /* if --route-delay was specified, start timer */
 
1269
          if (c->options.route_delay_defined)
 
1270
            {
 
1271
              event_timeout_init (&c->c2.route_wakeup, c->options.route_delay, now);
 
1272
              event_timeout_init (&c->c2.route_wakeup_expire, c->options.route_delay + c->options.route_delay_window, now);
 
1273
              if (c->c1.tuntap)
 
1274
                tun_standby_init (c->c1.tuntap);
 
1275
            }
 
1276
          else
 
1277
            {
 
1278
              initialization_sequence_completed (c, 0); /* client/p2p --route-delay undefined */
 
1279
            }
 
1280
        }
 
1281
      else if (c->options.mode == MODE_POINT_TO_POINT)
 
1282
        {
 
1283
          initialization_sequence_completed (c, 0); /* client/p2p restart with --persist-tun */
 
1284
        }
 
1285
        
 
1286
      c->c2.do_up_ran = true;
 
1287
    }
 
1288
}
 
1289
 
 
1290
/*
 
1291
 * These are the option categories which will be accepted by pull.
 
1292
 */
 
1293
unsigned int
 
1294
pull_permission_mask (const struct context *c)
 
1295
{
 
1296
  unsigned int flags =
 
1297
      OPT_P_UP
 
1298
    | OPT_P_ROUTE_EXTRAS
 
1299
    | OPT_P_IPWIN32
 
1300
    | OPT_P_SOCKBUF
 
1301
    | OPT_P_SOCKFLAGS
 
1302
    | OPT_P_SETENV
 
1303
    | OPT_P_SHAPER
 
1304
    | OPT_P_TIMER
 
1305
    | OPT_P_COMP
 
1306
    | OPT_P_PERSIST
 
1307
    | OPT_P_MESSAGES
 
1308
    | OPT_P_EXPLICIT_NOTIFY
 
1309
    | OPT_P_ECHO
 
1310
    | OPT_P_PULL_MODE;
 
1311
 
 
1312
  if (!c->options.route_nopull)
 
1313
    flags |= OPT_P_ROUTE;
 
1314
 
 
1315
  return flags;
 
1316
}
 
1317
 
 
1318
/*
 
1319
 * Handle non-tun-related pulled options.
 
1320
 */
 
1321
void
 
1322
do_deferred_options (struct context *c, const unsigned int found)
 
1323
{
 
1324
  if (found & OPT_P_MESSAGES)
 
1325
    {
 
1326
      init_verb_mute (c, IVM_LEVEL_1|IVM_LEVEL_2);
 
1327
      msg (D_PUSH, "OPTIONS IMPORT: --verb and/or --mute level changed");
 
1328
    }
 
1329
  if (found & OPT_P_TIMER)
 
1330
    {
 
1331
      do_init_timers (c, true);
 
1332
      msg (D_PUSH, "OPTIONS IMPORT: timers and/or timeouts modified");
 
1333
    }
 
1334
 
 
1335
#ifdef ENABLE_OCC
 
1336
  if (found & OPT_P_EXPLICIT_NOTIFY)
 
1337
    {
 
1338
      if (c->options.ce.proto != PROTO_UDPv4 && c->options.explicit_exit_notification)
 
1339
        {
 
1340
          msg (D_PUSH, "OPTIONS IMPORT: --explicit-exit-notify can only be used with --proto udp");
 
1341
          c->options.explicit_exit_notification = 0;
 
1342
        }
 
1343
      else
 
1344
        msg (D_PUSH, "OPTIONS IMPORT: explicit notify parm(s) modified");
 
1345
    }
 
1346
#endif
 
1347
 
 
1348
#ifdef USE_LZO
 
1349
  if (found & OPT_P_COMP)
 
1350
    {
 
1351
      if (lzo_defined (&c->c2.lzo_compwork))
 
1352
        {
 
1353
          msg (D_PUSH, "OPTIONS IMPORT: LZO parms modified");
 
1354
          lzo_modify_flags (&c->c2.lzo_compwork, c->options.lzo);
 
1355
        }
 
1356
    }
 
1357
#endif
 
1358
 
 
1359
  if (found & OPT_P_SHAPER)
 
1360
    {
 
1361
      msg (D_PUSH, "OPTIONS IMPORT: traffic shaper enabled");
 
1362
      do_init_traffic_shaper (c);
 
1363
    }
 
1364
 
 
1365
  if (found & OPT_P_SOCKBUF)
 
1366
    {
 
1367
      msg (D_PUSH, "OPTIONS IMPORT: --sndbuf/--rcvbuf options modified");
 
1368
      link_socket_update_buffer_sizes (c->c2.link_socket, c->options.rcvbuf, c->options.sndbuf);
 
1369
    }
 
1370
 
 
1371
  if (found & OPT_P_SOCKFLAGS)
 
1372
    {
 
1373
      msg (D_PUSH, "OPTIONS IMPORT: --socket-flags option modified");
 
1374
      link_socket_update_flags (c->c2.link_socket, c->options.sockflags);
 
1375
    }
 
1376
 
 
1377
  if (found & OPT_P_PERSIST)
 
1378
    msg (D_PUSH, "OPTIONS IMPORT: --persist options modified");
 
1379
  if (found & OPT_P_UP)
 
1380
    msg (D_PUSH, "OPTIONS IMPORT: --ifconfig/up options modified");
 
1381
  if (found & OPT_P_ROUTE)
 
1382
    msg (D_PUSH, "OPTIONS IMPORT: route options modified");
 
1383
  if (found & OPT_P_ROUTE_EXTRAS)
 
1384
    msg (D_PUSH, "OPTIONS IMPORT: route-related options modified");
 
1385
  if (found & OPT_P_IPWIN32)
 
1386
    msg (D_PUSH, "OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified");
 
1387
  if (found & OPT_P_SETENV)
 
1388
    msg (D_PUSH, "OPTIONS IMPORT: environment modified");
 
1389
}
 
1390
 
 
1391
/*
 
1392
 * Possible hold on initialization
 
1393
 */
 
1394
static bool
 
1395
do_hold (struct context *c)
 
1396
{
 
1397
#ifdef ENABLE_MANAGEMENT
 
1398
  if (management)
 
1399
    {
 
1400
      /* if c is defined, daemonize before hold */
 
1401
      if (c && c->options.daemon && management_should_daemonize (management))
 
1402
        do_init_first_time (c);
 
1403
 
 
1404
      /* block until management hold is released */
 
1405
      if (management_hold (management))
 
1406
        return true;
 
1407
    }
 
1408
#endif
 
1409
  return false;
 
1410
}
 
1411
 
 
1412
/*
 
1413
 * Sleep before restart.
 
1414
 */
 
1415
static void
 
1416
socket_restart_pause (struct context *c)
 
1417
{
 
1418
  bool proxy = false;
 
1419
  int sec = 2;
 
1420
 
 
1421
#ifdef ENABLE_HTTP_PROXY
 
1422
  if (c->options.ce.http_proxy_options)
 
1423
    proxy = true;
 
1424
#endif
 
1425
#ifdef ENABLE_SOCKS
 
1426
  if (c->options.ce.socks_proxy_server)
 
1427
    proxy = true;
 
1428
#endif
 
1429
 
 
1430
  switch (c->options.ce.proto)
 
1431
    {
 
1432
    case PROTO_UDPv4:
 
1433
      if (proxy)
 
1434
        sec = c->options.ce.connect_retry_seconds;
 
1435
      break;
 
1436
    case PROTO_TCPv4_SERVER:
 
1437
      sec = 1;
 
1438
      break;
 
1439
    case PROTO_TCPv4_CLIENT:
 
1440
      sec = c->options.ce.connect_retry_seconds;
 
1441
      break;
 
1442
    }
 
1443
 
 
1444
#ifdef ENABLE_DEBUG
 
1445
  if (GREMLIN_CONNECTION_FLOOD_LEVEL (c->options.gremlin))
 
1446
    sec = 0;
 
1447
#endif
 
1448
 
 
1449
#if P2MP
 
1450
  if (auth_retry_get () == AR_NOINTERACT)
 
1451
    sec = 10;
 
1452
 
 
1453
  if (c->options.server_poll_timeout && sec > 1)
 
1454
    sec = 1;
 
1455
#endif
 
1456
 
 
1457
  if (c->persist.restart_sleep_seconds > 0 && c->persist.restart_sleep_seconds > sec)
 
1458
    sec = c->persist.restart_sleep_seconds;
 
1459
  else if (c->persist.restart_sleep_seconds == -1)
 
1460
    sec = 0;
 
1461
  c->persist.restart_sleep_seconds = 0;
 
1462
 
 
1463
  /* do managment hold on context restart, i.e. second, third, fourth, etc. initialization */
 
1464
  if (do_hold (NULL))
 
1465
    sec = 0;
 
1466
 
 
1467
  if (sec)
 
1468
    {
 
1469
      msg (D_RESTART, "Restart pause, %d second(s)", sec);
 
1470
      openvpn_sleep (sec);
 
1471
    }
 
1472
}
 
1473
 
 
1474
/*
 
1475
 * Do a possible pause on context_2 initialization.
 
1476
 */
 
1477
static void
 
1478
do_startup_pause (struct context *c)
 
1479
{
 
1480
  if (!c->first_time)
 
1481
    socket_restart_pause (c);
 
1482
  else
 
1483
    do_hold (NULL); /* do management hold on first context initialization */
 
1484
}
 
1485
 
 
1486
/*
 
1487
 * Finalize MTU parameters based on command line or config file options.
 
1488
 */
 
1489
static void
 
1490
frame_finalize_options (struct context *c, const struct options *o)
 
1491
{
 
1492
  if (!o)
 
1493
    o = &c->options;
 
1494
 
 
1495
  /*
 
1496
   * Set adjustment factor for buffer alignment when no
 
1497
   * cipher is used.
 
1498
   */
 
1499
  if (!CIPHER_ENABLED (c))
 
1500
    {
 
1501
      frame_align_to_extra_frame (&c->c2.frame);
 
1502
      frame_or_align_flags (&c->c2.frame,
 
1503
                            FRAME_HEADROOM_MARKER_FRAGMENT
 
1504
                            |FRAME_HEADROOM_MARKER_READ_LINK
 
1505
                            |FRAME_HEADROOM_MARKER_READ_STREAM);
 
1506
    }
 
1507
  
 
1508
  frame_finalize (&c->c2.frame,
 
1509
                  o->link_mtu_defined,
 
1510
                  o->link_mtu,
 
1511
                  o->tun_mtu_defined,
 
1512
                  o->tun_mtu);
 
1513
}
 
1514
 
 
1515
/*
 
1516
 * Free a key schedule, including OpenSSL components.
 
1517
 */
 
1518
static void
 
1519
key_schedule_free (struct key_schedule *ks, bool free_ssl_ctx)
 
1520
{
 
1521
#ifdef USE_CRYPTO
 
1522
  free_key_ctx_bi (&ks->static_key);
 
1523
#ifdef USE_SSL
 
1524
  if (ks->ssl_ctx && free_ssl_ctx)
 
1525
    {
 
1526
      SSL_CTX_free (ks->ssl_ctx);
 
1527
      free_key_ctx_bi (&ks->tls_auth_key);
 
1528
    }
 
1529
#endif /* USE_SSL */
 
1530
#endif /* USE_CRYPTO */
 
1531
  CLEAR (*ks);
 
1532
}
 
1533
 
 
1534
#ifdef USE_CRYPTO
 
1535
 
 
1536
static void
 
1537
init_crypto_pre (struct context *c, const unsigned int flags)
 
1538
{
 
1539
  if (c->options.engine)
 
1540
    init_crypto_lib_engine (c->options.engine);
 
1541
 
 
1542
  if (flags & CF_LOAD_PERSISTED_PACKET_ID)
 
1543
    {
 
1544
      /* load a persisted packet-id for cross-session replay-protection */
 
1545
      if (c->options.packet_id_file)
 
1546
        packet_id_persist_load (&c->c1.pid_persist, c->options.packet_id_file);
 
1547
    }
 
1548
 
 
1549
  /* Initialize crypto options */
 
1550
 
 
1551
  if (c->options.use_iv)
 
1552
    c->c2.crypto_options.flags |= CO_USE_IV;
 
1553
 
 
1554
  if (c->options.mute_replay_warnings)
 
1555
    c->c2.crypto_options.flags |= CO_MUTE_REPLAY_WARNINGS;
 
1556
}
 
1557
 
 
1558
/*
 
1559
 * Static Key Mode (using a pre-shared key)
 
1560
 */
 
1561
static void
 
1562
do_init_crypto_static (struct context *c, const unsigned int flags)
 
1563
{
 
1564
  const struct options *options = &c->options;
 
1565
  ASSERT (options->shared_secret_file);
 
1566
 
 
1567
  init_crypto_pre (c, flags);
 
1568
 
 
1569
  /* Initialize packet ID tracking */
 
1570
  if (options->replay)
 
1571
    {
 
1572
      packet_id_init (&c->c2.packet_id, options->replay_window,
 
1573
                      options->replay_time);
 
1574
      c->c2.crypto_options.packet_id = &c->c2.packet_id;
 
1575
      c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
 
1576
      c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
 
1577
      packet_id_persist_load_obj (&c->c1.pid_persist,
 
1578
                                  c->c2.crypto_options.packet_id);
 
1579
    }
 
1580
 
 
1581
  if (!key_ctx_bi_defined (&c->c1.ks.static_key))
 
1582
    {
 
1583
      struct key2 key2;
 
1584
      struct key_direction_state kds;
 
1585
 
 
1586
      /* Get cipher & hash algorithms */
 
1587
      init_key_type (&c->c1.ks.key_type, options->ciphername,
 
1588
                     options->ciphername_defined, options->authname,
 
1589
                     options->authname_defined, options->keysize,
 
1590
                     options->test_crypto, true);
 
1591
 
 
1592
      /* Read cipher and hmac keys from shared secret file */
 
1593
      {
 
1594
        unsigned int rkf_flags = RKF_MUST_SUCCEED;
 
1595
        const char *rkf_file = options->shared_secret_file;
 
1596
 
 
1597
#if ENABLE_INLINE_FILES
 
1598
        if (options->shared_secret_file_inline)
 
1599
          {
 
1600
            rkf_file = options->shared_secret_file_inline;
 
1601
            rkf_flags |= RKF_INLINE;
 
1602
          }
 
1603
#endif
 
1604
        read_key_file (&key2, rkf_file, rkf_flags);
 
1605
      }
 
1606
 
 
1607
      /* Check for and fix highly unlikely key problems */
 
1608
      verify_fix_key2 (&key2, &c->c1.ks.key_type,
 
1609
                       options->shared_secret_file);
 
1610
 
 
1611
      /* Initialize OpenSSL key objects */
 
1612
      key_direction_state_init (&kds, options->key_direction);
 
1613
      must_have_n_keys (options->shared_secret_file, "secret", &key2,
 
1614
                        kds.need_keys);
 
1615
      init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
 
1616
                    &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
 
1617
      init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
 
1618
                    &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
 
1619
 
 
1620
      /* Erase the temporary copy of key */
 
1621
      CLEAR (key2);
 
1622
    }
 
1623
  else
 
1624
    {
 
1625
      msg (M_INFO, "Re-using pre-shared static key");
 
1626
    }
 
1627
 
 
1628
  /* Get key schedule */
 
1629
  c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
 
1630
 
 
1631
  /* Compute MTU parameters */
 
1632
  crypto_adjust_frame_parameters (&c->c2.frame,
 
1633
                                  &c->c1.ks.key_type,
 
1634
                                  options->ciphername_defined,
 
1635
                                  options->use_iv, options->replay, true);
 
1636
 
 
1637
  /* Sanity check on IV, sequence number, and cipher mode options */
 
1638
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
 
1639
                               options->use_iv);
 
1640
}
 
1641
 
 
1642
#ifdef USE_SSL
 
1643
 
 
1644
/*
 
1645
 * Initialize the persistent component of OpenVPN's TLS mode,
 
1646
 * which is preserved across SIGUSR1 resets.
 
1647
 */
 
1648
static void
 
1649
do_init_crypto_tls_c1 (struct context *c)
 
1650
{
 
1651
  const struct options *options = &c->options;
 
1652
 
 
1653
  if (!c->c1.ks.ssl_ctx)
 
1654
    {
 
1655
      /*
 
1656
       * Initialize the OpenSSL library's global
 
1657
       * SSL context.
 
1658
       */
 
1659
      c->c1.ks.ssl_ctx = init_ssl (options);
 
1660
      if (!c->c1.ks.ssl_ctx)
 
1661
        {
 
1662
#if P2MP
 
1663
          switch (auth_retry_get ())
 
1664
            {
 
1665
            case AR_NONE:
 
1666
              msg (M_FATAL, "Error: private key password verification failed");
 
1667
              break;
 
1668
            case AR_INTERACT:
 
1669
              ssl_purge_auth ();
 
1670
            case AR_NOINTERACT:
 
1671
              c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
 
1672
              break;
 
1673
            default:
 
1674
              ASSERT (0);
 
1675
            }
 
1676
          c->sig->signal_text = "private-key-password-failure";
 
1677
          return;
 
1678
#else
 
1679
          msg (M_FATAL, "Error: private key password verification failed");
 
1680
#endif
 
1681
        }
 
1682
 
 
1683
      /* Get cipher & hash algorithms */
 
1684
      init_key_type (&c->c1.ks.key_type, options->ciphername,
 
1685
                     options->ciphername_defined, options->authname,
 
1686
                     options->authname_defined, options->keysize, true, true);
 
1687
 
 
1688
      /* Initialize PRNG with config-specified digest */
 
1689
      prng_init (options->prng_hash, options->prng_nonce_secret_len);
 
1690
 
 
1691
      /* TLS handshake authentication (--tls-auth) */
 
1692
      if (options->tls_auth_file)
 
1693
        {
 
1694
          unsigned int flags = 0;
 
1695
          const char *file = options->tls_auth_file;
 
1696
 
 
1697
#if ENABLE_INLINE_FILES
 
1698
          if (options->tls_auth_file_inline)
 
1699
            {
 
1700
              flags |= GHK_INLINE;
 
1701
              file = options->tls_auth_file_inline;
 
1702
            }
 
1703
#endif
 
1704
          get_tls_handshake_key (&c->c1.ks.key_type,
 
1705
                                 &c->c1.ks.tls_auth_key,
 
1706
                                 file,
 
1707
                                 options->key_direction,
 
1708
                                 flags);
 
1709
        }
 
1710
 
 
1711
#if 0 /* was: #if ENABLE_INLINE_FILES --  Note that enabling this code will break restarts */
 
1712
      if (options->priv_key_file_inline)
 
1713
        {
 
1714
          string_clear (c->options.priv_key_file_inline);
 
1715
          c->options.priv_key_file_inline = NULL;
 
1716
        }
 
1717
#endif
 
1718
    }
 
1719
  else
 
1720
    {
 
1721
      msg (M_INFO, "Re-using SSL/TLS context");
 
1722
    }
 
1723
}
 
1724
 
 
1725
static void
 
1726
do_init_crypto_tls (struct context *c, const unsigned int flags)
 
1727
{
 
1728
  const struct options *options = &c->options;
 
1729
  struct tls_options to;
 
1730
  bool packet_id_long_form;
 
1731
 
 
1732
  ASSERT (options->tls_server || options->tls_client);
 
1733
  ASSERT (!options->test_crypto);
 
1734
 
 
1735
  init_crypto_pre (c, flags);
 
1736
 
 
1737
  /* Make sure we are either a TLS client or server but not both */
 
1738
  ASSERT (options->tls_server == !options->tls_client);
 
1739
 
 
1740
  /* initialize persistent component */
 
1741
  do_init_crypto_tls_c1 (c);
 
1742
  if (IS_SIG (c))
 
1743
    return;
 
1744
 
 
1745
  /* Sanity check on IV, sequence number, and cipher mode options */
 
1746
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
 
1747
                               options->use_iv);
 
1748
 
 
1749
  /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
 
1750
  packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
 
1751
 
 
1752
  /* Compute MTU parameters */
 
1753
  crypto_adjust_frame_parameters (&c->c2.frame,
 
1754
                                  &c->c1.ks.key_type,
 
1755
                                  options->ciphername_defined,
 
1756
                                  options->use_iv,
 
1757
                                  options->replay, packet_id_long_form);
 
1758
  tls_adjust_frame_parameters (&c->c2.frame);
 
1759
 
 
1760
  /* Set all command-line TLS-related options */
 
1761
  CLEAR (to);
 
1762
 
 
1763
  to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
 
1764
  if (packet_id_long_form)
 
1765
    to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
 
1766
 
 
1767
  to.ssl_ctx = c->c1.ks.ssl_ctx;
 
1768
  to.key_type = c->c1.ks.key_type;
 
1769
  to.server = options->tls_server;
 
1770
  to.key_method = options->key_method;
 
1771
  to.replay = options->replay;
 
1772
  to.replay_window = options->replay_window;
 
1773
  to.replay_time = options->replay_time;
 
1774
  to.transition_window = options->transition_window;
 
1775
  to.handshake_window = options->handshake_window;
 
1776
  to.packet_timeout = options->tls_timeout;
 
1777
  to.renegotiate_bytes = options->renegotiate_bytes;
 
1778
  to.renegotiate_packets = options->renegotiate_packets;
 
1779
  to.renegotiate_seconds = options->renegotiate_seconds;
 
1780
  to.single_session = options->single_session;
 
1781
 
 
1782
  /* should we not xmit any packets until we get an initial
 
1783
     response from client? */
 
1784
  if (to.server && options->ce.proto == PROTO_TCPv4_SERVER)
 
1785
    to.xmit_hold = true;
 
1786
 
 
1787
#ifdef ENABLE_OCC
 
1788
  to.disable_occ = !options->occ;
 
1789
#endif
 
1790
 
 
1791
  to.verify_command = options->tls_verify;
 
1792
  to.verify_x509name = options->tls_remote;
 
1793
  to.crl_file = options->crl_file;
 
1794
  to.ns_cert_type = options->ns_cert_type;
 
1795
  memmove (to.remote_cert_ku, options->remote_cert_ku, sizeof (to.remote_cert_ku));
 
1796
  to.remote_cert_eku = options->remote_cert_eku;
 
1797
  to.es = c->c2.es;
 
1798
 
 
1799
#ifdef ENABLE_DEBUG
 
1800
  to.gremlin = c->options.gremlin;
 
1801
#endif
 
1802
 
 
1803
  to.plugins = c->plugins;
 
1804
 
 
1805
#ifdef MANAGEMENT_DEF_AUTH
 
1806
  to.mda_context = &c->c2.mda_context;
 
1807
#endif
 
1808
 
 
1809
#if P2MP_SERVER
 
1810
  to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
 
1811
  to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
 
1812
  to.tmp_dir = options->tmp_dir;
 
1813
  to.ssl_flags = options->ssl_flags;
 
1814
  if (options->ccd_exclusive)
 
1815
    to.client_config_dir_exclusive = options->client_config_dir;
 
1816
#endif
 
1817
 
 
1818
  /* TLS handshake authentication (--tls-auth) */
 
1819
  if (options->tls_auth_file)
 
1820
    {
 
1821
      to.tls_auth_key = c->c1.ks.tls_auth_key;
 
1822
      to.tls_auth.pid_persist = &c->c1.pid_persist;
 
1823
      to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
 
1824
      crypto_adjust_frame_parameters (&to.frame,
 
1825
                                      &c->c1.ks.key_type,
 
1826
                                      false, false, true, true);
 
1827
    }
 
1828
 
 
1829
  /* If we are running over TCP, allow for
 
1830
     length prefix */
 
1831
  socket_adjust_frame_parameters (&to.frame, options->ce.proto);
 
1832
 
 
1833
  /*
 
1834
   * Initialize OpenVPN's master TLS-mode object.
 
1835
   */
 
1836
  if (flags & CF_INIT_TLS_MULTI)
 
1837
    c->c2.tls_multi = tls_multi_init (&to);
 
1838
 
 
1839
  if (flags & CF_INIT_TLS_AUTH_STANDALONE)
 
1840
    c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
 
1841
}
 
1842
 
 
1843
static void
 
1844
do_init_finalize_tls_frame (struct context *c)
 
1845
{
 
1846
  if (c->c2.tls_multi)
 
1847
    {
 
1848
      tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
 
1849
      ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
 
1850
              EXPANDED_SIZE (&c->c2.frame));
 
1851
      frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
 
1852
                   "Control Channel MTU parms");
 
1853
    }
 
1854
  if (c->c2.tls_auth_standalone)
 
1855
    {
 
1856
      tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
 
1857
      frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
 
1858
                   "TLS-Auth MTU parms");
 
1859
    }
 
1860
}
 
1861
 
 
1862
#endif /* USE_SSL */
 
1863
#endif /* USE_CRYPTO */
 
1864
 
 
1865
#ifdef USE_CRYPTO
 
1866
/*
 
1867
 * No encryption or authentication.
 
1868
 */
 
1869
static void
 
1870
do_init_crypto_none (const struct context *c)
 
1871
{
 
1872
  ASSERT (!c->options.test_crypto);
 
1873
  msg (M_WARN,
 
1874
       "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
 
1875
}
 
1876
#endif
 
1877
 
 
1878
static void
 
1879
do_init_crypto (struct context *c, const unsigned int flags)
 
1880
{
 
1881
#ifdef USE_CRYPTO
 
1882
  if (c->options.shared_secret_file)
 
1883
    do_init_crypto_static (c, flags);
 
1884
#ifdef USE_SSL
 
1885
  else if (c->options.tls_server || c->options.tls_client)
 
1886
    do_init_crypto_tls (c, flags);
 
1887
#endif
 
1888
  else                          /* no encryption or authentication. */
 
1889
    do_init_crypto_none (c);
 
1890
#else /* USE_CRYPTO */
 
1891
  msg (M_WARN,
 
1892
       "******* WARNING *******: " PACKAGE_NAME
 
1893
       " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
 
1894
#endif /* USE_CRYPTO */
 
1895
}
 
1896
 
 
1897
static void
 
1898
do_init_frame (struct context *c)
 
1899
{
 
1900
#ifdef USE_LZO
 
1901
  /*
 
1902
   * Initialize LZO compression library.
 
1903
   */
 
1904
  if (c->options.lzo & LZO_SELECTED)
 
1905
    {
 
1906
      lzo_adjust_frame_parameters (&c->c2.frame);
 
1907
 
 
1908
      /*
 
1909
       * LZO usage affects buffer alignment.
 
1910
       */
 
1911
      if (CIPHER_ENABLED (c))
 
1912
        {
 
1913
          frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
 
1914
          frame_or_align_flags (&c->c2.frame,
 
1915
                                FRAME_HEADROOM_MARKER_FRAGMENT
 
1916
                                |FRAME_HEADROOM_MARKER_DECRYPT);
 
1917
        }
 
1918
 
 
1919
#ifdef ENABLE_FRAGMENT
 
1920
      lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
 
1921
#endif
 
1922
    }
 
1923
#endif /* USE_LZO */
 
1924
 
 
1925
#ifdef ENABLE_SOCKS
 
1926
  /*
 
1927
   * Adjust frame size for UDP Socks support.
 
1928
   */
 
1929
  if (c->options.ce.socks_proxy_server)
 
1930
    socks_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
 
1931
#endif
 
1932
 
 
1933
  /*
 
1934
   * Adjust frame size based on the --tun-mtu-extra parameter.
 
1935
   */
 
1936
  if (c->options.tun_mtu_extra_defined)
 
1937
    tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
 
1938
 
 
1939
  /*
 
1940
   * Adjust frame size based on link socket parameters.
 
1941
   * (Since TCP is a stream protocol, we need to insert
 
1942
   * a packet length uint16_t in the buffer.)
 
1943
   */
 
1944
  socket_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
 
1945
 
 
1946
  /*
 
1947
   * Fill in the blanks in the frame parameters structure,
 
1948
   * make sure values are rational, etc.
 
1949
   */
 
1950
  frame_finalize_options (c, NULL);
 
1951
 
 
1952
#ifdef ENABLE_FRAGMENT
 
1953
  /*
 
1954
   * Set frame parameter for fragment code.  This is necessary because
 
1955
   * the fragmentation code deals with payloads which have already been
 
1956
   * passed through the compression code.
 
1957
   */
 
1958
  c->c2.frame_fragment = c->c2.frame;
 
1959
  frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
 
1960
#endif
 
1961
 
 
1962
#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
 
1963
  /*
 
1964
   * MTU advisories
 
1965
   */
 
1966
  if (c->options.fragment && c->options.mtu_test)
 
1967
    msg (M_WARN,
 
1968
         "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
 
1969
#endif
 
1970
 
 
1971
#ifdef ENABLE_FRAGMENT
 
1972
  if ((c->options.mssfix || c->options.fragment)
 
1973
      && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
 
1974
    msg (M_WARN,
 
1975
         "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
 
1976
         ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
 
1977
#endif
 
1978
}
 
1979
 
 
1980
static void
 
1981
do_option_warnings (struct context *c)
 
1982
{
 
1983
  const struct options *o = &c->options;
 
1984
 
 
1985
#if 1 /* JYFIXME -- port warning */
 
1986
  if (!o->ce.port_option_used && (o->ce.local_port == OPENVPN_PORT && o->ce.remote_port == OPENVPN_PORT))
 
1987
    msg (M_WARN, "IMPORTANT: OpenVPN's default port number is now %d, based on an official port number assignment by IANA.  OpenVPN 2.0-beta16 and earlier used 5000 as the default port.",
 
1988
         OPENVPN_PORT);
 
1989
#endif
 
1990
 
 
1991
  if (o->ping_send_timeout && !o->ping_rec_timeout)
 
1992
    msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
 
1993
 
 
1994
  if (o->username || o->groupname || o->chroot_dir
 
1995
#ifdef HAVE_SETCON
 
1996
      || o->selinux_context
 
1997
#endif
 
1998
      )
 
1999
   {
 
2000
    if (!o->persist_tun)
 
2001
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
 
2002
    if (!o->persist_key
 
2003
#ifdef ENABLE_PKCS11
 
2004
        && !o->pkcs11_id
 
2005
#endif
 
2006
        )
 
2007
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
 
2008
   }
 
2009
 
 
2010
  if (o->chroot_dir && !(o->username && o->groupname))
 
2011
    msg (M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
 
2012
 
 
2013
#if P2MP
 
2014
  if (o->pull && o->ifconfig_local && c->first_time)
 
2015
    msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
 
2016
 
 
2017
#if P2MP_SERVER
 
2018
  if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
 
2019
    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");
 
2020
 
 
2021
  if (o->mode == MODE_SERVER)
 
2022
    {
 
2023
      if (o->duplicate_cn && o->client_config_dir)
 
2024
        msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
 
2025
      if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
 
2026
        msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
 
2027
      if (!o->keepalive_ping || !o->keepalive_timeout)
 
2028
        msg (M_WARN, "WARNING: --keepalive option is missing from server config");
 
2029
    }
 
2030
#endif
 
2031
#endif
 
2032
 
 
2033
#ifdef USE_CRYPTO
 
2034
  if (!o->replay)
 
2035
    msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
 
2036
  if (!o->use_iv)
 
2037
    msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
 
2038
 
 
2039
#ifdef USE_SSL
 
2040
  if (o->tls_server)
 
2041
    warn_on_use_of_common_subnets ();
 
2042
  if (o->tls_client
 
2043
      && !o->tls_verify
 
2044
      && !o->tls_remote
 
2045
      && !(o->ns_cert_type & NS_SSL_SERVER)
 
2046
      && !o->remote_cert_eku)
 
2047
    msg (M_WARN, "WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.");
 
2048
  if (o->tls_remote)
 
2049
    msg (M_WARN, "WARNING: Make sure you understand the semantics of --tls-remote before using it (see the man page).");
 
2050
#endif
 
2051
#endif
 
2052
 
 
2053
#ifndef CONNECT_NONBLOCK
 
2054
  if (o->ce.connect_timeout_defined)
 
2055
    msg (M_WARN, "NOTE: --connect-timeout option is not supported on this OS");
 
2056
#endif
 
2057
 
 
2058
  if (script_security >= SSEC_SCRIPTS)
 
2059
    msg (M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
 
2060
  else if (script_security >= SSEC_PW_ENV)
 
2061
    msg (M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
 
2062
  else
 
2063
    msg (M_WARN, "NOTE: " PACKAGE_NAME " 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables");
 
2064
 
 
2065
  if (script_method == SM_SYSTEM)
 
2066
    msg (M_WARN, "NOTE: --script-security method='system' is deprecated due to the fact that passed parameters will be subject to shell expansion");
 
2067
}
 
2068
 
 
2069
static void
 
2070
do_init_frame_tls (struct context *c)
 
2071
{
 
2072
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2073
  do_init_finalize_tls_frame (c);
 
2074
#endif
 
2075
}
 
2076
 
 
2077
struct context_buffers *
 
2078
init_context_buffers (const struct frame *frame)
 
2079
{
 
2080
  struct context_buffers *b;
 
2081
 
 
2082
  ALLOC_OBJ_CLEAR (b, struct context_buffers);
 
2083
 
 
2084
  b->read_link_buf = alloc_buf (BUF_SIZE (frame));
 
2085
  b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
 
2086
 
 
2087
  b->aux_buf = alloc_buf (BUF_SIZE (frame));
 
2088
 
 
2089
#ifdef USE_CRYPTO
 
2090
  b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
 
2091
  b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
 
2092
#endif
 
2093
 
 
2094
#ifdef USE_LZO
 
2095
  b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
 
2096
  b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
 
2097
#endif
 
2098
 
 
2099
  return b;
 
2100
}
 
2101
 
 
2102
void
 
2103
free_context_buffers (struct context_buffers *b)
 
2104
{
 
2105
  if (b)
 
2106
    {
 
2107
      free_buf (&b->read_link_buf);
 
2108
      free_buf (&b->read_tun_buf);
 
2109
      free_buf (&b->aux_buf);
 
2110
 
 
2111
#ifdef USE_LZO
 
2112
      free_buf (&b->lzo_compress_buf);
 
2113
      free_buf (&b->lzo_decompress_buf);
 
2114
#endif
 
2115
 
 
2116
#ifdef USE_CRYPTO
 
2117
      free_buf (&b->encrypt_buf);
 
2118
      free_buf (&b->decrypt_buf);
 
2119
#endif
 
2120
 
 
2121
      free (b);
 
2122
    }
 
2123
}
 
2124
 
 
2125
/*
 
2126
 * Now that we know all frame parameters, initialize
 
2127
 * our buffers.
 
2128
 */
 
2129
static void
 
2130
do_init_buffers (struct context *c)
 
2131
{
 
2132
  c->c2.buffers = init_context_buffers (&c->c2.frame);
 
2133
  c->c2.buffers_owned = true;
 
2134
}
 
2135
 
 
2136
#ifdef ENABLE_FRAGMENT
 
2137
/*
 
2138
 * Fragmenting code has buffers to initialize
 
2139
 * once frame parameters are known.
 
2140
 */
 
2141
static void
 
2142
do_init_fragment (struct context *c)
 
2143
{
 
2144
  ASSERT (c->options.fragment);
 
2145
  frame_set_mtu_dynamic (&c->c2.frame_fragment,
 
2146
                         c->options.fragment, SET_MTU_UPPER_BOUND);
 
2147
  fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
 
2148
}
 
2149
#endif
 
2150
 
 
2151
/*
 
2152
 * Set the --mssfix option.
 
2153
 */
 
2154
static void
 
2155
do_init_mssfix (struct context *c)
 
2156
{
 
2157
  if (c->options.mssfix)
 
2158
    {
 
2159
      frame_set_mtu_dynamic (&c->c2.frame,
 
2160
                             c->options.mssfix, SET_MTU_UPPER_BOUND);
 
2161
    }
 
2162
}
 
2163
 
 
2164
/*
 
2165
 * Allocate our socket object.
 
2166
 */
 
2167
static void
 
2168
do_link_socket_new (struct context *c)
 
2169
{
 
2170
  ASSERT (!c->c2.link_socket);
 
2171
  c->c2.link_socket = link_socket_new ();
 
2172
  c->c2.link_socket_owned = true;
 
2173
}
 
2174
 
 
2175
/*
 
2176
 * bind the TCP/UDP socket
 
2177
 */
 
2178
static void
 
2179
do_init_socket_1 (struct context *c, const int mode)
 
2180
{
 
2181
  unsigned int sockflags = c->options.sockflags;
 
2182
 
 
2183
#if PORT_SHARE
 
2184
  if (c->options.port_share_host && c->options.port_share_port)
 
2185
    sockflags |= SF_PORT_SHARE;
 
2186
#endif
 
2187
 
 
2188
  link_socket_init_phase1 (c->c2.link_socket,
 
2189
                           connection_list_defined (&c->options),
 
2190
                           c->options.ce.local,
 
2191
                           c->options.ce.local_port,
 
2192
                           c->options.ce.remote,
 
2193
                           c->options.ce.remote_port,
 
2194
                           c->options.ce.proto,
 
2195
                           mode,
 
2196
                           c->c2.accept_from,
 
2197
#ifdef ENABLE_HTTP_PROXY
 
2198
                           c->c1.http_proxy,
 
2199
#endif
 
2200
#ifdef ENABLE_SOCKS
 
2201
                           c->c1.socks_proxy,
 
2202
#endif
 
2203
#ifdef ENABLE_DEBUG
 
2204
                           c->options.gremlin,
 
2205
#endif
 
2206
                           c->options.ce.bind_local,
 
2207
                           c->options.ce.remote_float,
 
2208
                           c->options.inetd,
 
2209
                           &c->c1.link_socket_addr,
 
2210
                           c->options.ipchange,
 
2211
                           c->plugins,
 
2212
                           c->options.resolve_retry_seconds,
 
2213
                           c->options.ce.connect_retry_seconds,
 
2214
                           c->options.ce.connect_timeout,
 
2215
                           c->options.ce.connect_retry_max,
 
2216
                           c->options.mtu_discover_type,
 
2217
                           c->options.rcvbuf,
 
2218
                           c->options.sndbuf,
 
2219
                           sockflags);
 
2220
}
 
2221
 
 
2222
/*
 
2223
 * finalize the TCP/UDP socket
 
2224
 */
 
2225
static void
 
2226
do_init_socket_2 (struct context *c)
 
2227
{
 
2228
  link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
 
2229
                           &c->sig->signal_received);
 
2230
}
 
2231
 
 
2232
/*
 
2233
 * Print MTU INFO
 
2234
 */
 
2235
static void
 
2236
do_print_data_channel_mtu_parms (struct context *c)
 
2237
{
 
2238
  frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
 
2239
#ifdef ENABLE_FRAGMENT
 
2240
  if (c->c2.fragment)
 
2241
    frame_print (&c->c2.frame_fragment, D_MTU_INFO,
 
2242
                 "Fragmentation MTU parms");
 
2243
#endif
 
2244
}
 
2245
 
 
2246
#ifdef ENABLE_OCC
 
2247
/*
 
2248
 * Get local and remote options compatibility strings.
 
2249
 */
 
2250
static void
 
2251
do_compute_occ_strings (struct context *c)
 
2252
{
 
2253
  struct gc_arena gc = gc_new ();
 
2254
 
 
2255
  c->c2.options_string_local =
 
2256
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
 
2257
  c->c2.options_string_remote =
 
2258
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
 
2259
 
 
2260
  msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
 
2261
  msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
 
2262
       c->c2.options_string_remote);
 
2263
 
 
2264
#ifdef USE_CRYPTO
 
2265
  msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
 
2266
       options_string_version (c->c2.options_string_local, &gc),
 
2267
       md5sum ((uint8_t*)c->c2.options_string_local,
 
2268
               strlen (c->c2.options_string_local), 9, &gc));
 
2269
  msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
 
2270
       options_string_version (c->c2.options_string_remote, &gc),
 
2271
       md5sum ((uint8_t*)c->c2.options_string_remote,
 
2272
               strlen (c->c2.options_string_remote), 9, &gc));
 
2273
#endif
 
2274
 
 
2275
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2276
  if (c->c2.tls_multi)
 
2277
    tls_multi_init_set_options (c->c2.tls_multi,
 
2278
                                c->c2.options_string_local,
 
2279
                                c->c2.options_string_remote);
 
2280
#endif
 
2281
 
 
2282
  gc_free (&gc);
 
2283
}
 
2284
#endif
 
2285
 
 
2286
/*
 
2287
 * These things can only be executed once per program instantiation.
 
2288
 * Set up for possible UID/GID downgrade, but don't do it yet.
 
2289
 * Daemonize if requested.
 
2290
 */
 
2291
static void
 
2292
do_init_first_time (struct context *c)
 
2293
{
 
2294
  if (c->first_time && !c->did_we_daemonize && !c->c0)
 
2295
    {
 
2296
      struct context_0 *c0;
 
2297
 
 
2298
      ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
 
2299
      c0 = c->c0;
 
2300
      
 
2301
      /* get user and/or group that we want to setuid/setgid to */
 
2302
      c0->uid_gid_specified =
 
2303
        get_group (c->options.groupname, &c0->group_state) |
 
2304
        get_user (c->options.username, &c0->user_state);
 
2305
 
 
2306
      /* get --writepid file descriptor */
 
2307
      get_pid_file (c->options.writepid, &c0->pid_state);
 
2308
 
 
2309
      /* become a daemon if --daemon */
 
2310
      c->did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
 
2311
 
 
2312
      /* should we disable paging? */
 
2313
      if (c->options.mlock && c->did_we_daemonize)
 
2314
        do_mlockall (true);     /* call again in case we daemonized */
 
2315
 
 
2316
      /* save process ID in a file */
 
2317
      write_pid (&c0->pid_state);
 
2318
 
 
2319
      /* should we change scheduling priority? */
 
2320
      set_nice (c->options.nice);
 
2321
    }
 
2322
}
 
2323
 
 
2324
/*
 
2325
 * If xinetd/inetd mode, don't allow restart.
 
2326
 */
 
2327
static void
 
2328
do_close_check_if_restart_permitted (struct context *c)
 
2329
{
 
2330
  if (c->options.inetd
 
2331
      && (c->sig->signal_received == SIGHUP
 
2332
          || c->sig->signal_received == SIGUSR1))
 
2333
    {
 
2334
      c->sig->signal_received = SIGTERM;
 
2335
      msg (M_INFO,
 
2336
           PACKAGE_NAME
 
2337
           " started by inetd/xinetd cannot restart... Exiting.");
 
2338
    }
 
2339
}
 
2340
 
 
2341
/*
 
2342
 * free buffers
 
2343
 */
 
2344
static void
 
2345
do_close_free_buf (struct context *c)
 
2346
{
 
2347
  if (c->c2.buffers_owned)
 
2348
    {
 
2349
      free_context_buffers (c->c2.buffers);
 
2350
      c->c2.buffers = NULL;
 
2351
      c->c2.buffers_owned = false;
 
2352
    }
 
2353
}
 
2354
 
 
2355
/*
 
2356
 * close TLS
 
2357
 */
 
2358
static void
 
2359
do_close_tls (struct context *c)
 
2360
{
 
2361
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2362
  if (c->c2.tls_multi)
 
2363
    {
 
2364
      tls_multi_free (c->c2.tls_multi, true);
 
2365
      c->c2.tls_multi = NULL;
 
2366
    }
 
2367
 
 
2368
#ifdef ENABLE_OCC
 
2369
  /* free options compatibility strings */
 
2370
  if (c->c2.options_string_local)
 
2371
    free (c->c2.options_string_local);
 
2372
  if (c->c2.options_string_remote)
 
2373
    free (c->c2.options_string_remote);
 
2374
  c->c2.options_string_local = c->c2.options_string_remote = NULL;
 
2375
#endif
 
2376
#endif
 
2377
}
 
2378
 
 
2379
/*
 
2380
 * Free key schedules
 
2381
 */
 
2382
static void
 
2383
do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
 
2384
{
 
2385
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
 
2386
    key_schedule_free (&c->c1.ks, free_ssl_ctx);
 
2387
}
 
2388
 
 
2389
/*
 
2390
 * Close TCP/UDP connection
 
2391
 */
 
2392
static void
 
2393
do_close_link_socket (struct context *c)
 
2394
{
 
2395
  if (c->c2.link_socket && c->c2.link_socket_owned)
 
2396
    {
 
2397
      link_socket_close (c->c2.link_socket);
 
2398
      c->c2.link_socket = NULL;
 
2399
    }
 
2400
 
 
2401
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
 
2402
    {
 
2403
      CLEAR (c->c1.link_socket_addr.remote);
 
2404
      CLEAR (c->c1.link_socket_addr.actual);
 
2405
    }
 
2406
 
 
2407
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
 
2408
    CLEAR (c->c1.link_socket_addr.local);
 
2409
}
 
2410
 
 
2411
/*
 
2412
 * Close packet-id persistance file
 
2413
 */
 
2414
static void
 
2415
do_close_packet_id (struct context *c)
 
2416
{
 
2417
#ifdef USE_CRYPTO
 
2418
  packet_id_free (&c->c2.packet_id);
 
2419
  packet_id_persist_save (&c->c1.pid_persist);
 
2420
  if (!(c->sig->signal_received == SIGUSR1))
 
2421
    packet_id_persist_close (&c->c1.pid_persist);
 
2422
#endif
 
2423
}
 
2424
 
 
2425
#ifdef ENABLE_FRAGMENT
 
2426
/*
 
2427
 * Close fragmentation handler.
 
2428
 */
 
2429
static void
 
2430
do_close_fragment (struct context *c)
 
2431
{
 
2432
  if (c->c2.fragment)
 
2433
    {
 
2434
      fragment_free (c->c2.fragment);
 
2435
      c->c2.fragment = NULL;
 
2436
    }
 
2437
}
 
2438
#endif
 
2439
 
 
2440
/*
 
2441
 * Open and close our event objects.
 
2442
 */
 
2443
 
 
2444
static void
 
2445
do_event_set_init (struct context *c,
 
2446
                   bool need_us_timeout)
 
2447
{
 
2448
  unsigned int flags = 0;
 
2449
 
 
2450
  c->c2.event_set_max = BASE_N_EVENTS;
 
2451
 
 
2452
  flags |= EVENT_METHOD_FAST;
 
2453
 
 
2454
  if (need_us_timeout)
 
2455
    flags |= EVENT_METHOD_US_TIMEOUT;
 
2456
 
 
2457
  c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
 
2458
  c->c2.event_set_owned = true;
 
2459
}
 
2460
 
 
2461
static void
 
2462
do_close_event_set (struct context *c)
 
2463
{
 
2464
  if (c->c2.event_set && c->c2.event_set_owned)
 
2465
    {
 
2466
      event_free (c->c2.event_set);
 
2467
      c->c2.event_set = NULL;
 
2468
      c->c2.event_set_owned = false;
 
2469
    }
 
2470
}
 
2471
 
 
2472
/*
 
2473
 * Open and close --status file
 
2474
 */
 
2475
 
 
2476
static void
 
2477
do_open_status_output (struct context *c)
 
2478
{
 
2479
  if (!c->c1.status_output)
 
2480
    {
 
2481
      c->c1.status_output = status_open (c->options.status_file,
 
2482
                                         c->options.status_file_update_freq,
 
2483
                                         -1,
 
2484
                                         NULL,
 
2485
                                         STATUS_OUTPUT_WRITE);
 
2486
      c->c1.status_output_owned = true;
 
2487
    }
 
2488
}
 
2489
 
 
2490
static void
 
2491
do_close_status_output (struct context *c)
 
2492
{
 
2493
  if (!(c->sig->signal_received == SIGUSR1))
 
2494
    {
 
2495
      if (c->c1.status_output_owned && c->c1.status_output)
 
2496
        {
 
2497
          status_close (c->c1.status_output);
 
2498
          c->c1.status_output = NULL;
 
2499
          c->c1.status_output_owned = false;
 
2500
        }
 
2501
    }
 
2502
}
 
2503
 
 
2504
/*
 
2505
 * Handle ifconfig-pool persistance object.
 
2506
 */
 
2507
static void
 
2508
do_open_ifconfig_pool_persist (struct context *c)
 
2509
{
 
2510
#if P2MP_SERVER
 
2511
  if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
 
2512
    {
 
2513
      c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
 
2514
                                                                c->options.ifconfig_pool_persist_refresh_freq);
 
2515
      c->c1.ifconfig_pool_persist_owned = true;
 
2516
    }
 
2517
#endif
 
2518
}
 
2519
 
 
2520
static void
 
2521
do_close_ifconfig_pool_persist (struct context *c)
 
2522
{
 
2523
#if P2MP_SERVER
 
2524
  if (!(c->sig->signal_received == SIGUSR1))
 
2525
    {
 
2526
      if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
 
2527
        {
 
2528
          ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
 
2529
          c->c1.ifconfig_pool_persist = NULL;
 
2530
          c->c1.ifconfig_pool_persist_owned = false;
 
2531
        }
 
2532
    }
 
2533
#endif
 
2534
}
 
2535
 
 
2536
/*
 
2537
 * Inherit environmental variables
 
2538
 */
 
2539
 
 
2540
static void
 
2541
do_inherit_env (struct context *c, const struct env_set *src)
 
2542
{
 
2543
  c->c2.es = env_set_create (NULL);
 
2544
  c->c2.es_owned = true;
 
2545
  env_set_inherit (c->c2.es, src);
 
2546
}
 
2547
 
 
2548
static void
 
2549
do_env_set_destroy (struct context *c)
 
2550
{
 
2551
  if (c->c2.es && c->c2.es_owned)
 
2552
    {
 
2553
      env_set_destroy (c->c2.es);
 
2554
      c->c2.es = NULL;
 
2555
      c->c2.es_owned = false;
 
2556
    }
 
2557
}
 
2558
 
 
2559
/*
 
2560
 * Fast I/O setup.  Fast I/O is an optimization which only works
 
2561
 * if all of the following are true:
 
2562
 *
 
2563
 * (1) The platform is not Windows
 
2564
 * (2) --proto udp is enabled
 
2565
 * (3) --shaper is disabled
 
2566
 */
 
2567
static void
 
2568
do_setup_fast_io (struct context *c)
 
2569
{
 
2570
  if (c->options.fast_io)
 
2571
    {
 
2572
#ifdef WIN32
 
2573
      msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
 
2574
#else
 
2575
      if (c->options.ce.proto != PROTO_UDPv4)
 
2576
        msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
 
2577
      else
 
2578
        {
 
2579
#ifdef HAVE_GETTIMEOFDAY
 
2580
          if (c->options.shaper)
 
2581
            msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
 
2582
          else
 
2583
#endif
 
2584
            {
 
2585
              c->c2.fast_io = true;
 
2586
            }
 
2587
        }
 
2588
#endif
 
2589
    }
 
2590
}
 
2591
 
 
2592
static void
 
2593
do_signal_on_tls_errors (struct context *c)
 
2594
{
 
2595
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2596
  if (c->options.tls_exit)
 
2597
    c->c2.tls_exit_signal = SIGTERM;
 
2598
  else
 
2599
    c->c2.tls_exit_signal = SIGUSR1;    
 
2600
#endif
 
2601
}
 
2602
 
 
2603
#ifdef ENABLE_PLUGIN
 
2604
 
 
2605
void
 
2606
init_plugins (struct context *c)
 
2607
{
 
2608
  if (c->options.plugin_list && !c->plugins)
 
2609
    {
 
2610
      c->plugins = plugin_list_init (c->options.plugin_list);
 
2611
      c->plugins_owned = true;
 
2612
    }
 
2613
}
 
2614
 
 
2615
void
 
2616
open_plugins (struct context *c, const bool import_options, int init_point)
 
2617
{
 
2618
  if (c->plugins && c->plugins_owned)
 
2619
    {
 
2620
      if (import_options)
 
2621
        {
 
2622
          struct plugin_return pr, config;
 
2623
          plugin_return_init (&pr);
 
2624
          plugin_list_open (c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
 
2625
          plugin_return_get_column (&pr, &config, "config");
 
2626
          if (plugin_return_defined (&config))
 
2627
            {
 
2628
              int i;
 
2629
              for (i = 0; i < config.n; ++i)
 
2630
                {
 
2631
                  unsigned int option_types_found = 0;
 
2632
                  if (config.list[i] && config.list[i]->value)
 
2633
                    options_string_import (&c->options,
 
2634
                                           config.list[i]->value,
 
2635
                                           D_IMPORT_ERRORS|M_OPTERR,
 
2636
                                           OPT_P_DEFAULT & ~OPT_P_PLUGIN,
 
2637
                                           &option_types_found,
 
2638
                                           c->es);
 
2639
                }
 
2640
            }
 
2641
          plugin_return_free (&pr);
 
2642
        }
 
2643
      else
 
2644
        {
 
2645
          plugin_list_open (c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
 
2646
        }
 
2647
    }
 
2648
}
 
2649
 
 
2650
static void
 
2651
do_close_plugins (struct context *c)
 
2652
{
 
2653
  if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
 
2654
    {
 
2655
      plugin_list_close (c->plugins);
 
2656
      c->plugins = NULL;
 
2657
      c->plugins_owned = false;
 
2658
    }
 
2659
}
 
2660
 
 
2661
static void
 
2662
do_inherit_plugins (struct context *c, const struct context *src)
 
2663
{
 
2664
  if (!c->plugins && src->plugins)
 
2665
    {
 
2666
      c->plugins = plugin_list_inherit (src->plugins);
 
2667
      c->plugins_owned = true;
 
2668
    }
 
2669
}
 
2670
 
 
2671
#endif
 
2672
 
 
2673
#ifdef ENABLE_MANAGEMENT
 
2674
 
 
2675
static void
 
2676
management_callback_status_p2p (void *arg, const int version, struct status_output *so)
 
2677
{
 
2678
  struct context *c = (struct context *) arg;
 
2679
  print_status (c, so);
 
2680
}
 
2681
 
 
2682
void
 
2683
management_show_net_callback (void *arg, const int msglevel)
 
2684
{
 
2685
#ifdef WIN32
 
2686
  show_routes (msglevel);
 
2687
  show_adapters (msglevel);
 
2688
  msg (msglevel, "END");
 
2689
#else
 
2690
  msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
 
2691
#endif
 
2692
}
 
2693
 
 
2694
#endif
 
2695
 
 
2696
void
 
2697
init_management_callback_p2p (struct context *c)
 
2698
{
 
2699
#ifdef ENABLE_MANAGEMENT
 
2700
  if (management)
 
2701
    {
 
2702
      struct management_callback cb;
 
2703
      CLEAR (cb);
 
2704
      cb.arg = c;
 
2705
      cb.status = management_callback_status_p2p;
 
2706
      cb.show_net = management_show_net_callback;
 
2707
      management_set_callback (management, &cb);
 
2708
    }
 
2709
#endif
 
2710
}
 
2711
 
 
2712
#ifdef ENABLE_MANAGEMENT
 
2713
 
 
2714
void
 
2715
init_management (struct context *c)
 
2716
{
 
2717
  if (!management)
 
2718
    management = management_init ();
 
2719
}
 
2720
 
 
2721
bool
 
2722
open_management (struct context *c)
 
2723
{
 
2724
  /* initialize management layer */
 
2725
  if (management)
 
2726
    {
 
2727
      if (c->options.management_addr)
 
2728
        {
 
2729
          unsigned int flags = c->options.management_flags;
 
2730
          if (c->options.mode == MODE_SERVER)
 
2731
            flags |= MF_SERVER;
 
2732
          if (management_open (management,
 
2733
                               c->options.management_addr,
 
2734
                               c->options.management_port,
 
2735
                               c->options.management_user_pass,
 
2736
                               c->options.management_client_user,
 
2737
                               c->options.management_client_group,
 
2738
                               c->options.management_log_history_cache,
 
2739
                               c->options.management_echo_buffer_size,
 
2740
                               c->options.management_state_buffer_size,
 
2741
                               c->options.management_write_peer_info_file,
 
2742
                               c->options.remap_sigusr1,
 
2743
                               flags))
 
2744
            {
 
2745
              management_set_state (management,
 
2746
                                    OPENVPN_STATE_CONNECTING,
 
2747
                                    NULL,
 
2748
                                    (in_addr_t)0,
 
2749
                                    (in_addr_t)0);
 
2750
            }
 
2751
 
 
2752
          /* initial management hold, called early, before first context initialization */
 
2753
          do_hold (c);
 
2754
          if (IS_SIG (c))
 
2755
            {
 
2756
              msg (M_WARN, "Signal received from management interface, exiting");
 
2757
              return false;
 
2758
            }
 
2759
        }
 
2760
      else
 
2761
        close_management ();
 
2762
    }
 
2763
  return true;
 
2764
}
 
2765
 
 
2766
void
 
2767
close_management (void)
 
2768
{
 
2769
  if (management)
 
2770
    {
 
2771
      management_close (management);
 
2772
      management = NULL;
 
2773
    }
 
2774
}
 
2775
 
 
2776
#endif
 
2777
 
 
2778
 
 
2779
void
 
2780
uninit_management_callback (void)
 
2781
{
 
2782
#ifdef ENABLE_MANAGEMENT
 
2783
  if (management)
 
2784
    {
 
2785
      management_clear_callback (management);
 
2786
    }
 
2787
#endif
 
2788
}
 
2789
 
 
2790
/*
 
2791
 * Initialize a tunnel instance, handle pre and post-init
 
2792
 * signal settings.
 
2793
 */
 
2794
void
 
2795
init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
 
2796
{
 
2797
  pre_init_signal_catch ();
 
2798
  init_instance (c, env, flags);
 
2799
  post_init_signal_catch ();
 
2800
 
 
2801
  /*
 
2802
   * This is done so that signals thrown during
 
2803
   * initialization can bring us back to
 
2804
   * a management hold.
 
2805
   */
 
2806
  if (IS_SIG (c))
 
2807
    {
 
2808
      remap_signal (c);
 
2809
      uninit_management_callback ();  
 
2810
    }
 
2811
}
 
2812
 
 
2813
/*
 
2814
 * Initialize a tunnel instance.
 
2815
 */
 
2816
void
 
2817
init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
 
2818
{
 
2819
  const struct options *options = &c->options;
 
2820
  const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
 
2821
  int link_socket_mode = LS_MODE_DEFAULT;
 
2822
 
 
2823
  /* init garbage collection level */
 
2824
  gc_init (&c->c2.gc);
 
2825
 
 
2826
  /* signals caught here will abort */
 
2827
  c->sig->signal_received = 0;
 
2828
  c->sig->signal_text = NULL;
 
2829
  c->sig->hard = false;
 
2830
 
 
2831
  /* map in current connection entry */
 
2832
  next_connection_entry (c);
 
2833
 
 
2834
  /* link_socket_mode allows CM_CHILD_TCP
 
2835
     instances to inherit acceptable fds
 
2836
     from a top-level parent */
 
2837
  if (c->options.ce.proto == PROTO_TCPv4_SERVER)
 
2838
    {
 
2839
      if (c->mode == CM_TOP)
 
2840
        link_socket_mode = LS_MODE_TCP_LISTEN;
 
2841
      else if (c->mode == CM_CHILD_TCP)
 
2842
        link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
 
2843
    }
 
2844
 
 
2845
  /* should we disable paging? */
 
2846
  if (c->first_time && options->mlock)
 
2847
    do_mlockall (true);
 
2848
 
 
2849
  /* possible sleep or management hold if restart */
 
2850
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2851
    {
 
2852
      do_startup_pause (c);
 
2853
      if (IS_SIG (c))
 
2854
        goto sig;
 
2855
    }
 
2856
 
 
2857
#if P2MP
 
2858
  /* get passwords if undefined */
 
2859
  if (auth_retry_get () == AR_INTERACT)
 
2860
    init_query_passwords (c);
 
2861
#endif
 
2862
 
 
2863
  /* initialize context level 2 --verb/--mute parms */
 
2864
  init_verb_mute (c, IVM_LEVEL_2);
 
2865
 
 
2866
  /* set error message delay for non-server modes */
 
2867
  if (c->mode == CM_P2P)
 
2868
    set_check_status_error_delay (P2P_ERROR_DELAY_MS);
 
2869
    
 
2870
  /* warn about inconsistent options */
 
2871
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2872
    do_option_warnings (c);
 
2873
 
 
2874
  /* inherit environmental variables */
 
2875
  if (env)
 
2876
    do_inherit_env (c, env);
 
2877
 
 
2878
#ifdef ENABLE_PLUGIN
 
2879
  /* initialize plugins */
 
2880
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2881
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
 
2882
#endif
 
2883
 
 
2884
  /* should we enable fast I/O? */
 
2885
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2886
    do_setup_fast_io (c);
 
2887
 
 
2888
  /* should we throw a signal on TLS errors? */
 
2889
  do_signal_on_tls_errors (c);
 
2890
 
 
2891
  /* open --status file */
 
2892
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2893
    do_open_status_output (c);
 
2894
 
 
2895
  /* open --ifconfig-pool-persist file */
 
2896
  if (c->mode == CM_TOP)
 
2897
    do_open_ifconfig_pool_persist (c);
 
2898
 
 
2899
#ifdef ENABLE_OCC
 
2900
  /* reset OCC state */
 
2901
  if (c->mode == CM_P2P || child)
 
2902
    c->c2.occ_op = occ_reset_op ();
 
2903
#endif
 
2904
 
 
2905
  /* our wait-for-i/o objects, different for posix vs. win32 */
 
2906
  if (c->mode == CM_P2P)
 
2907
    do_event_set_init (c, SHAPER_DEFINED (&c->options));
 
2908
  else if (c->mode == CM_CHILD_TCP)
 
2909
    do_event_set_init (c, false);
 
2910
 
 
2911
  /* initialize HTTP or SOCKS proxy object at scope level 2 */
 
2912
  init_proxy (c, 2);
 
2913
 
 
2914
  /* allocate our socket object */
 
2915
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
2916
    do_link_socket_new (c);
 
2917
 
 
2918
#ifdef ENABLE_FRAGMENT
 
2919
  /* initialize internal fragmentation object */
 
2920
  if (options->fragment && (c->mode == CM_P2P || child))
 
2921
    c->c2.fragment = fragment_init (&c->c2.frame);
 
2922
#endif
 
2923
 
 
2924
  /* init crypto layer */
 
2925
  {
 
2926
    unsigned int crypto_flags = 0;
 
2927
    if (c->mode == CM_TOP)
 
2928
      crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
 
2929
    else if (c->mode == CM_P2P)
 
2930
      crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
 
2931
    else if (child)
 
2932
      crypto_flags = CF_INIT_TLS_MULTI;
 
2933
    do_init_crypto (c, crypto_flags);
 
2934
    if (IS_SIG (c) && !child)
 
2935
      goto sig;
 
2936
  }
 
2937
 
 
2938
#ifdef USE_LZO
 
2939
  /* initialize LZO compression library. */
 
2940
  if ((options->lzo & LZO_SELECTED) && (c->mode == CM_P2P || child))
 
2941
    lzo_compress_init (&c->c2.lzo_compwork, options->lzo);
 
2942
#endif
 
2943
 
 
2944
  /* initialize MTU variables */
 
2945
  do_init_frame (c);
 
2946
 
 
2947
  /* initialize TLS MTU variables */
 
2948
  do_init_frame_tls (c);
 
2949
 
 
2950
  /* init workspace buffers whose size is derived from frame size */
 
2951
  if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
 
2952
    do_init_buffers (c);
 
2953
 
 
2954
#ifdef ENABLE_FRAGMENT
 
2955
  /* initialize internal fragmentation capability with known frame size */
 
2956
  if (options->fragment && (c->mode == CM_P2P || child))
 
2957
    do_init_fragment (c);
 
2958
#endif
 
2959
 
 
2960
  /* initialize dynamic MTU variable */
 
2961
  do_init_mssfix (c);
 
2962
 
 
2963
  /* bind the TCP/UDP socket */
 
2964
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
2965
    do_init_socket_1 (c, link_socket_mode);
 
2966
 
 
2967
  /* initialize tun/tap device object,
 
2968
     open tun/tap device, ifconfig, run up script, etc. */
 
2969
  if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
 
2970
    c->c2.did_open_tun = do_open_tun (c);
 
2971
 
 
2972
  /* print MTU info */
 
2973
  do_print_data_channel_mtu_parms (c);
 
2974
 
 
2975
#ifdef ENABLE_OCC
 
2976
  /* get local and remote options compatibility strings */
 
2977
  if (c->mode == CM_P2P || child)
 
2978
    do_compute_occ_strings (c);
 
2979
#endif
 
2980
 
 
2981
  /* initialize output speed limiter */
 
2982
  if (c->mode == CM_P2P)
 
2983
    do_init_traffic_shaper (c);
 
2984
 
 
2985
  /* do one-time inits, and possibily become a daemon here */
 
2986
  do_init_first_time (c);
 
2987
 
 
2988
#ifdef ENABLE_PLUGIN
 
2989
  /* initialize plugins */
 
2990
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2991
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
 
2992
#endif
 
2993
 
 
2994
  /*
 
2995
   * Actually do UID/GID downgrade, and chroot, if requested.
 
2996
   * May be delayed by --client, --pull, or --up-delay.
 
2997
   */
 
2998
  do_uid_gid_chroot (c, c->c2.did_open_tun);
 
2999
 
 
3000
  /* finalize the TCP/UDP socket */
 
3001
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
3002
    do_init_socket_2 (c);
 
3003
 
 
3004
  /* initialize timers */
 
3005
  if (c->mode == CM_P2P || child)
 
3006
    do_init_timers (c, false);
 
3007
 
 
3008
#ifdef ENABLE_PLUGIN
 
3009
  /* initialize plugins */
 
3010
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
3011
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
 
3012
#endif
 
3013
 
 
3014
#if PORT_SHARE
 
3015
  /* share OpenVPN port with foreign (such as HTTPS) server */
 
3016
  if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
 
3017
    init_port_share (c);
 
3018
#endif
 
3019
          
 
3020
#ifdef ENABLE_PF
 
3021
  if (child)
 
3022
    pf_init_context (c);
 
3023
#endif
 
3024
 
 
3025
  /* Check for signals */
 
3026
  if (IS_SIG (c))
 
3027
    goto sig;
 
3028
 
 
3029
  return;
 
3030
 
 
3031
 sig:
 
3032
  if (!c->sig->signal_text)
 
3033
    c->sig->signal_text = "init_instance";
 
3034
  close_context (c, -1, flags);
 
3035
  return;
 
3036
}
 
3037
 
 
3038
/*
 
3039
 * Close a tunnel instance.
 
3040
 */
 
3041
void
 
3042
close_instance (struct context *c)
 
3043
{
 
3044
  /* close event objects */
 
3045
  do_close_event_set (c);
 
3046
 
 
3047
    if (c->mode == CM_P2P
 
3048
        || c->mode == CM_CHILD_TCP
 
3049
        || c->mode == CM_CHILD_UDP
 
3050
        || c->mode == CM_TOP)
 
3051
      {
 
3052
        /* if xinetd/inetd mode, don't allow restart */
 
3053
        do_close_check_if_restart_permitted (c);
 
3054
 
 
3055
#ifdef USE_LZO
 
3056
        if (lzo_defined (&c->c2.lzo_compwork))
 
3057
          lzo_compress_uninit (&c->c2.lzo_compwork);
 
3058
#endif
 
3059
 
 
3060
        /* free buffers */
 
3061
        do_close_free_buf (c);
 
3062
 
 
3063
        /* close TLS */
 
3064
        do_close_tls (c);
 
3065
 
 
3066
        /* free key schedules */
 
3067
        do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
 
3068
 
 
3069
        /* close TCP/UDP connection */
 
3070
        do_close_link_socket (c);
 
3071
 
 
3072
        /* close TUN/TAP device */
 
3073
        do_close_tun (c, false);
 
3074
 
 
3075
#ifdef MANAGEMENT_DEF_AUTH
 
3076
        if (management)
 
3077
          management_notify_client_close (management, &c->c2.mda_context, NULL);
 
3078
#endif
 
3079
 
 
3080
#ifdef ENABLE_PF
 
3081
        pf_destroy_context (&c->c2.pf);
 
3082
#endif
 
3083
 
 
3084
#ifdef ENABLE_PLUGIN
 
3085
        /* call plugin close functions and unload */
 
3086
        do_close_plugins (c);
 
3087
#endif
 
3088
 
 
3089
        /* close packet-id persistance file */
 
3090
        do_close_packet_id (c);
 
3091
 
 
3092
        /* close --status file */
 
3093
        do_close_status_output (c);
 
3094
 
 
3095
#ifdef ENABLE_FRAGMENT
 
3096
        /* close fragmentation handler */
 
3097
        do_close_fragment (c);
 
3098
#endif
 
3099
 
 
3100
        /* close --ifconfig-pool-persist obj */
 
3101
        do_close_ifconfig_pool_persist (c);
 
3102
 
 
3103
        /* free up environmental variable store */
 
3104
        do_env_set_destroy (c);
 
3105
 
 
3106
        /* close HTTP or SOCKS proxy */
 
3107
        uninit_proxy (c);
 
3108
 
 
3109
        /* garbage collect */
 
3110
        gc_free (&c->c2.gc);
 
3111
      }
 
3112
}
 
3113
 
 
3114
void
 
3115
inherit_context_child (struct context *dest,
 
3116
                       const struct context *src)
 
3117
{
 
3118
  CLEAR (*dest);
 
3119
 
 
3120
  switch (src->options.ce.proto)
 
3121
    {
 
3122
    case PROTO_UDPv4:
 
3123
      dest->mode = CM_CHILD_UDP;
 
3124
      break;
 
3125
    case PROTO_TCPv4_SERVER:
 
3126
      dest->mode = CM_CHILD_TCP;
 
3127
      break;
 
3128
    default:
 
3129
      ASSERT (0);
 
3130
    }
 
3131
 
 
3132
  dest->gc = gc_new ();
 
3133
 
 
3134
  ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
 
3135
 
 
3136
  /* c1 init */
 
3137
  packet_id_persist_init (&dest->c1.pid_persist);
 
3138
 
 
3139
#ifdef USE_CRYPTO
 
3140
  dest->c1.ks.key_type = src->c1.ks.key_type;
 
3141
#ifdef USE_SSL
 
3142
  /* inherit SSL context */
 
3143
  dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
 
3144
  dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
 
3145
#endif
 
3146
#endif
 
3147
 
 
3148
  /* options */
 
3149
  dest->options = src->options;
 
3150
  options_detach (&dest->options);
 
3151
 
 
3152
  if (dest->mode == CM_CHILD_TCP)
 
3153
    {
 
3154
      /*
 
3155
       * The CM_TOP context does the socket listen(),
 
3156
       * and the CM_CHILD_TCP context does the accept().
 
3157
       */
 
3158
      dest->c2.accept_from = src->c2.link_socket;
 
3159
    }
 
3160
 
 
3161
#ifdef ENABLE_PLUGIN
 
3162
  /* inherit plugins */
 
3163
  do_inherit_plugins (dest, src);
 
3164
#endif
 
3165
 
 
3166
  /* context init */
 
3167
  init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
 
3168
  if (IS_SIG (dest))
 
3169
    return;
 
3170
 
 
3171
  /* inherit tun/tap interface object */
 
3172
  dest->c1.tuntap = src->c1.tuntap;
 
3173
 
 
3174
  /* UDP inherits some extra things which TCP does not */
 
3175
  if (dest->mode == CM_CHILD_UDP)
 
3176
    {
 
3177
      /* inherit buffers */
 
3178
      dest->c2.buffers = src->c2.buffers;
 
3179
 
 
3180
      /* inherit parent link_socket and tuntap */
 
3181
      dest->c2.link_socket = src->c2.link_socket;
 
3182
 
 
3183
      ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
 
3184
      *dest->c2.link_socket_info = src->c2.link_socket->info;
 
3185
 
 
3186
      /* locally override some link_socket_info fields */
 
3187
      dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
 
3188
      dest->c2.link_socket_info->connection_established = false;
 
3189
    }
 
3190
}
 
3191
 
 
3192
void
 
3193
inherit_context_top (struct context *dest,
 
3194
                     const struct context *src)
 
3195
{
 
3196
  /* copy parent */
 
3197
  *dest = *src;
 
3198
 
 
3199
  /*
 
3200
   * CM_TOP_CLONE will prevent close_instance from freeing or closing
 
3201
   * resources owned by the parent.
 
3202
   *
 
3203
   * Also note that CM_TOP_CLONE context objects are
 
3204
   * closed by multi_top_free in multi.c.
 
3205
   */
 
3206
  dest->mode = CM_TOP_CLONE; 
 
3207
 
 
3208
  dest->first_time = false;
 
3209
  dest->c0 = NULL;
 
3210
 
 
3211
  options_detach (&dest->options);
 
3212
  gc_detach (&dest->gc);
 
3213
  gc_detach (&dest->c2.gc);
 
3214
 
 
3215
  /* detach plugins */
 
3216
  dest->plugins_owned = false;
 
3217
 
 
3218
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
3219
  dest->c2.tls_multi = NULL;
 
3220
#endif
 
3221
 
 
3222
  /* detach c1 ownership */
 
3223
  dest->c1.tuntap_owned = false;
 
3224
  dest->c1.status_output_owned = false;
 
3225
#if P2MP_SERVER
 
3226
  dest->c1.ifconfig_pool_persist_owned = false;
 
3227
#endif
 
3228
 
 
3229
  /* detach c2 ownership */
 
3230
  dest->c2.event_set_owned = false;
 
3231
  dest->c2.link_socket_owned = false;
 
3232
  dest->c2.buffers_owned = false;
 
3233
  dest->c2.es_owned = false;
 
3234
 
 
3235
  dest->c2.event_set = NULL;
 
3236
  if (src->options.ce.proto == PROTO_UDPv4)
 
3237
    do_event_set_init (dest, false);
 
3238
}
 
3239
 
 
3240
void
 
3241
close_context (struct context *c, int sig, unsigned int flags)
 
3242
{
 
3243
  ASSERT (c);
 
3244
  ASSERT (c->sig);
 
3245
 
 
3246
  if (sig >= 0)
 
3247
    c->sig->signal_received = sig;
 
3248
 
 
3249
  if (c->sig->signal_received == SIGUSR1)
 
3250
    {
 
3251
      if ((flags & CC_USR1_TO_HUP)
 
3252
          || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
 
3253
        c->sig->signal_received = SIGHUP;
 
3254
    }
 
3255
 
 
3256
  if (!(flags & CC_NO_CLOSE))
 
3257
    close_instance (c);
 
3258
 
 
3259
  if (flags & CC_GC_FREE)
 
3260
    context_gc_free (c);
 
3261
}
 
3262
 
 
3263
#ifdef USE_CRYPTO
 
3264
 
 
3265
static void
 
3266
test_malloc (void)
 
3267
{
 
3268
  int i, j;
 
3269
  msg (M_INFO, "Multithreaded malloc test...");
 
3270
  for (i = 0; i < 25; ++i)
 
3271
    {
 
3272
      struct gc_arena gc = gc_new ();
 
3273
      const int limit = get_random () & 0x03FF;
 
3274
      for (j = 0; j < limit; ++j)
 
3275
        {
 
3276
          gc_malloc (get_random () & 0x03FF, false, &gc);
 
3277
        }
 
3278
      gc_free (&gc);
 
3279
    }
 
3280
}
 
3281
 
 
3282
/*
 
3283
 * Do a loopback test
 
3284
 * on the crypto subsystem.
 
3285
 */
 
3286
static void *
 
3287
test_crypto_thread (void *arg)
 
3288
{
 
3289
  struct context *c = (struct context *) arg;
 
3290
  const struct options *options = &c->options;
 
3291
#if defined(USE_PTHREAD)
 
3292
  struct context *child = NULL;
 
3293
  openvpn_thread_t child_id = 0;
 
3294
#endif
 
3295
 
 
3296
  ASSERT (options->test_crypto);
 
3297
  init_verb_mute (c, IVM_LEVEL_1);
 
3298
  context_init_1 (c);
 
3299
  do_init_crypto_static (c, 0);
 
3300
 
 
3301
#if defined(USE_PTHREAD)
 
3302
  {
 
3303
    if (c->first_time && options->n_threads > 1)
 
3304
      {
 
3305
        if (options->n_threads > 2)
 
3306
          msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
 
3307
        openvpn_thread_init ();
 
3308
        ALLOC_OBJ (child, struct context);
 
3309
        context_clear (child);
 
3310
        child->options = *options;
 
3311
        options_detach (&child->options);
 
3312
        child->first_time = false;
 
3313
        child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
 
3314
      }
 
3315
  }
 
3316
#endif
 
3317
  frame_finalize_options (c, options);
 
3318
 
 
3319
#if defined(USE_PTHREAD)
 
3320
  if (options->n_threads == 2)
 
3321
    test_malloc ();
 
3322
#endif
 
3323
 
 
3324
  test_crypto (&c->c2.crypto_options, &c->c2.frame);
 
3325
 
 
3326
  key_schedule_free (&c->c1.ks, true);
 
3327
  packet_id_free (&c->c2.packet_id);
 
3328
 
 
3329
#if defined(USE_PTHREAD)
 
3330
  if (c->first_time && options->n_threads > 1)
 
3331
    openvpn_thread_join (child_id);
 
3332
  if (child)
 
3333
    free (child);
 
3334
#endif
 
3335
  context_gc_free (c);
 
3336
  return NULL;
 
3337
}
 
3338
 
 
3339
#endif
 
3340
 
 
3341
bool
 
3342
do_test_crypto (const struct options *o)
 
3343
{
 
3344
#ifdef USE_CRYPTO
 
3345
  if (o->test_crypto)
 
3346
    {
 
3347
      struct context c;
 
3348
 
 
3349
      /* print version number */
 
3350
      msg (M_INFO, "%s", title_string);
 
3351
 
 
3352
      context_clear (&c);
 
3353
      c.options = *o;
 
3354
      options_detach (&c.options);
 
3355
      c.first_time = true;
 
3356
      test_crypto_thread ((void *) &c);
 
3357
      return true;
 
3358
    }
 
3359
#endif
 
3360
  return false;
 
3361
}