~ubuntu-branches/ubuntu/saucy/openvpn/saucy

« back to all changes in this revision

Viewing changes to .pc/jjo-ipv6-support.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
  /* CVE-2008-0166 (Debian weak key checks) */
 
1568
  /* Only check if we can actually read the key file. Unless the file does not
 
1569
   * exist in the first place, this should never happen (since static keys do
 
1570
   * not work with multi-client mode), but we test it anyway to be on the safe
 
1571
   * side and avoid wrong -vulnkey alerts. */
 
1572
  if (access (options->shared_secret_file, R_OK) == 0)
 
1573
    {
 
1574
      struct argv argv = argv_new ();
 
1575
      int ret;
 
1576
      argv_printf (&argv, "/usr/sbin/openvpn-vulnkey -q %s", options->shared_secret_file);
 
1577
      argv_msg (M_INFO, &argv);
 
1578
      ret = openvpn_execve (&argv, c->c2.es, 0);
 
1579
      if (WEXITSTATUS (ret) == 1)
 
1580
        {
 
1581
          msg (M_WARN, "******* WARNING *******: '%s' is a known vulnerable key. See 'man openvpn-vulnkey' for details.", options->shared_secret_file);
 
1582
        }
 
1583
      else if (WEXITSTATUS (ret) != 0)
 
1584
        {
 
1585
          msg (M_WARN, "******* WARNING *******: '%s' cannot be verified as a non-vulnerable key. See 'man openvpn-vulnkey' for details.", options->shared_secret_file);
 
1586
        }
 
1587
      argv_reset (&argv);
 
1588
    }
 
1589
 
 
1590
  init_crypto_pre (c, flags);
 
1591
 
 
1592
  /* Initialize packet ID tracking */
 
1593
  if (options->replay)
 
1594
    {
 
1595
      packet_id_init (&c->c2.packet_id, options->replay_window,
 
1596
                      options->replay_time);
 
1597
      c->c2.crypto_options.packet_id = &c->c2.packet_id;
 
1598
      c->c2.crypto_options.pid_persist = &c->c1.pid_persist;
 
1599
      c->c2.crypto_options.flags |= CO_PACKET_ID_LONG_FORM;
 
1600
      packet_id_persist_load_obj (&c->c1.pid_persist,
 
1601
                                  c->c2.crypto_options.packet_id);
 
1602
    }
 
1603
 
 
1604
  if (!key_ctx_bi_defined (&c->c1.ks.static_key))
 
1605
    {
 
1606
      struct key2 key2;
 
1607
      struct key_direction_state kds;
 
1608
 
 
1609
      /* Get cipher & hash algorithms */
 
1610
      init_key_type (&c->c1.ks.key_type, options->ciphername,
 
1611
                     options->ciphername_defined, options->authname,
 
1612
                     options->authname_defined, options->keysize,
 
1613
                     options->test_crypto, true);
 
1614
 
 
1615
      /* Read cipher and hmac keys from shared secret file */
 
1616
      {
 
1617
        unsigned int rkf_flags = RKF_MUST_SUCCEED;
 
1618
        const char *rkf_file = options->shared_secret_file;
 
1619
 
 
1620
#if ENABLE_INLINE_FILES
 
1621
        if (options->shared_secret_file_inline)
 
1622
          {
 
1623
            rkf_file = options->shared_secret_file_inline;
 
1624
            rkf_flags |= RKF_INLINE;
 
1625
          }
 
1626
#endif
 
1627
        read_key_file (&key2, rkf_file, rkf_flags);
 
1628
      }
 
1629
 
 
1630
      /* Check for and fix highly unlikely key problems */
 
1631
      verify_fix_key2 (&key2, &c->c1.ks.key_type,
 
1632
                       options->shared_secret_file);
 
1633
 
 
1634
      /* Initialize OpenSSL key objects */
 
1635
      key_direction_state_init (&kds, options->key_direction);
 
1636
      must_have_n_keys (options->shared_secret_file, "secret", &key2,
 
1637
                        kds.need_keys);
 
1638
      init_key_ctx (&c->c1.ks.static_key.encrypt, &key2.keys[kds.out_key],
 
1639
                    &c->c1.ks.key_type, DO_ENCRYPT, "Static Encrypt");
 
1640
      init_key_ctx (&c->c1.ks.static_key.decrypt, &key2.keys[kds.in_key],
 
1641
                    &c->c1.ks.key_type, DO_DECRYPT, "Static Decrypt");
 
1642
 
 
1643
      /* Erase the temporary copy of key */
 
1644
      CLEAR (key2);
 
1645
    }
 
1646
  else
 
1647
    {
 
1648
      msg (M_INFO, "Re-using pre-shared static key");
 
1649
    }
 
1650
 
 
1651
  /* Get key schedule */
 
1652
  c->c2.crypto_options.key_ctx_bi = &c->c1.ks.static_key;
 
1653
 
 
1654
  /* Compute MTU parameters */
 
1655
  crypto_adjust_frame_parameters (&c->c2.frame,
 
1656
                                  &c->c1.ks.key_type,
 
1657
                                  options->ciphername_defined,
 
1658
                                  options->use_iv, options->replay, true);
 
1659
 
 
1660
  /* Sanity check on IV, sequence number, and cipher mode options */
 
1661
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
 
1662
                               options->use_iv);
 
1663
}
 
1664
 
 
1665
#ifdef USE_SSL
 
1666
 
 
1667
/*
 
1668
 * Initialize the persistent component of OpenVPN's TLS mode,
 
1669
 * which is preserved across SIGUSR1 resets.
 
1670
 */
 
1671
static void
 
1672
do_init_crypto_tls_c1 (struct context *c)
 
1673
{
 
1674
  const struct options *options = &c->options;
 
1675
  SSL *ssl;
 
1676
 
 
1677
  if (!c->c1.ks.ssl_ctx)
 
1678
    {
 
1679
      /*
 
1680
       * Initialize the OpenSSL library's global
 
1681
       * SSL context.
 
1682
       */
 
1683
      c->c1.ks.ssl_ctx = init_ssl (options);
 
1684
      if (!c->c1.ks.ssl_ctx)
 
1685
        {
 
1686
#if P2MP
 
1687
          switch (auth_retry_get ())
 
1688
            {
 
1689
            case AR_NONE:
 
1690
              msg (M_FATAL, "Error: private key password verification failed");
 
1691
              break;
 
1692
            case AR_INTERACT:
 
1693
              ssl_purge_auth ();
 
1694
            case AR_NOINTERACT:
 
1695
              c->sig->signal_received = SIGUSR1; /* SOFT-SIGUSR1 -- Password failure error */
 
1696
              break;
 
1697
            default:
 
1698
              ASSERT (0);
 
1699
            }
 
1700
          c->sig->signal_text = "private-key-password-failure";
 
1701
          return;
 
1702
#else
 
1703
          msg (M_FATAL, "Error: private key password verification failed");
 
1704
#endif
 
1705
        }
 
1706
 
 
1707
      /* Get cipher & hash algorithms */
 
1708
      init_key_type (&c->c1.ks.key_type, options->ciphername,
 
1709
                     options->ciphername_defined, options->authname,
 
1710
                     options->authname_defined, options->keysize, true, true);
 
1711
 
 
1712
      /* Initialize PRNG with config-specified digest */
 
1713
      prng_init (options->prng_hash, options->prng_nonce_secret_len);
 
1714
 
 
1715
      /* CVE-2008-0166 (Debian weak key checks)
 
1716
       * Obtain the modulus and bits from the certificate that was initialized,
 
1717
       * and send that to openssl-vulnkey.
 
1718
       */
 
1719
      ssl = SSL_new(c->c1.ks.ssl_ctx);
 
1720
      if (ssl != NULL)
 
1721
        {
 
1722
          X509* cert = NULL;
 
1723
          char *bn;
 
1724
          int bits;
 
1725
 
 
1726
          cert = SSL_get_certificate(ssl);
 
1727
          if (cert != NULL)
 
1728
            {
 
1729
              EVP_PKEY *pkey = X509_get_pubkey (cert);
 
1730
              if (pkey != NULL)
 
1731
                {
 
1732
                  if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
 
1733
                      && pkey->pkey.rsa->n != NULL)
 
1734
                    {
 
1735
                      bits = BN_num_bits(pkey->pkey.rsa->n);
 
1736
                      bn = BN_bn2hex(pkey->pkey.rsa->n);
 
1737
                    }
 
1738
                  else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
 
1739
                           && pkey->pkey.dsa->p != NULL)
 
1740
                    {
 
1741
                      bits = BN_num_bits(pkey->pkey.dsa->p);
 
1742
                      bn = BN_bn2hex(pkey->pkey.dsa->p);
 
1743
                    }
 
1744
                  if (bn != NULL)
 
1745
                    {
 
1746
                      int ret;
 
1747
                      struct argv argv = argv_new ();
 
1748
                      argv_printf (&argv, "/usr/bin/openssl-vulnkey -q -b %d -m %s", bits, bn);
 
1749
                      OPENSSL_free(bn);
 
1750
                      msg (M_INFO, "/usr/bin/openssl-vulnkey -q -b %d -m <modulus omitted>", bits);
 
1751
                      ret = openvpn_execve (&argv, NULL, 0);
 
1752
                      if (WEXITSTATUS (ret) == 1)
 
1753
                        {
 
1754
                          msg (M_WARN, "******* WARNING *******: '%s' is a known vulnerable key. See 'man openssl-vulnkey' for details.", options->priv_key_file);
 
1755
                        }
 
1756
                      else if (WEXITSTATUS (ret) != 0)
 
1757
                        {
 
1758
                          msg (M_WARN, "******* WARNING *******: '%s' cannot be verified as a non-vulnerable key. See 'man openssl-vulnkey' for details.", options->priv_key_file);
 
1759
                        }
 
1760
                      argv_reset (&argv);
 
1761
                    }
 
1762
                  EVP_PKEY_free (pkey);
 
1763
               }
 
1764
            }
 
1765
            SSL_free(ssl);
 
1766
         }
 
1767
 
 
1768
      /* TLS handshake authentication (--tls-auth) */
 
1769
      if (options->tls_auth_file)
 
1770
        {
 
1771
          unsigned int flags = 0;
 
1772
          const char *file = options->tls_auth_file;
 
1773
 
 
1774
#if ENABLE_INLINE_FILES
 
1775
          if (options->tls_auth_file_inline)
 
1776
            {
 
1777
              flags |= GHK_INLINE;
 
1778
              file = options->tls_auth_file_inline;
 
1779
            }
 
1780
#endif
 
1781
          get_tls_handshake_key (&c->c1.ks.key_type,
 
1782
                                 &c->c1.ks.tls_auth_key,
 
1783
                                 file,
 
1784
                                 options->key_direction,
 
1785
                                 flags);
 
1786
        }
 
1787
 
 
1788
#if 0 /* was: #if ENABLE_INLINE_FILES --  Note that enabling this code will break restarts */
 
1789
      if (options->priv_key_file_inline)
 
1790
        {
 
1791
          string_clear (c->options.priv_key_file_inline);
 
1792
          c->options.priv_key_file_inline = NULL;
 
1793
        }
 
1794
#endif
 
1795
    }
 
1796
  else
 
1797
    {
 
1798
      msg (M_INFO, "Re-using SSL/TLS context");
 
1799
    }
 
1800
}
 
1801
 
 
1802
static void
 
1803
do_init_crypto_tls (struct context *c, const unsigned int flags)
 
1804
{
 
1805
  const struct options *options = &c->options;
 
1806
  struct tls_options to;
 
1807
  bool packet_id_long_form;
 
1808
 
 
1809
  ASSERT (options->tls_server || options->tls_client);
 
1810
  ASSERT (!options->test_crypto);
 
1811
 
 
1812
  init_crypto_pre (c, flags);
 
1813
 
 
1814
  /* Make sure we are either a TLS client or server but not both */
 
1815
  ASSERT (options->tls_server == !options->tls_client);
 
1816
 
 
1817
  /* initialize persistent component */
 
1818
  do_init_crypto_tls_c1 (c);
 
1819
  if (IS_SIG (c))
 
1820
    return;
 
1821
 
 
1822
  /* Sanity check on IV, sequence number, and cipher mode options */
 
1823
  check_replay_iv_consistency (&c->c1.ks.key_type, options->replay,
 
1824
                               options->use_iv);
 
1825
 
 
1826
  /* In short form, unique datagram identifier is 32 bits, in long form 64 bits */
 
1827
  packet_id_long_form = cfb_ofb_mode (&c->c1.ks.key_type);
 
1828
 
 
1829
  /* Compute MTU parameters */
 
1830
  crypto_adjust_frame_parameters (&c->c2.frame,
 
1831
                                  &c->c1.ks.key_type,
 
1832
                                  options->ciphername_defined,
 
1833
                                  options->use_iv,
 
1834
                                  options->replay, packet_id_long_form);
 
1835
  tls_adjust_frame_parameters (&c->c2.frame);
 
1836
 
 
1837
  /* Set all command-line TLS-related options */
 
1838
  CLEAR (to);
 
1839
 
 
1840
  to.crypto_flags_and = ~(CO_PACKET_ID_LONG_FORM);
 
1841
  if (packet_id_long_form)
 
1842
    to.crypto_flags_or = CO_PACKET_ID_LONG_FORM;
 
1843
 
 
1844
  to.ssl_ctx = c->c1.ks.ssl_ctx;
 
1845
  to.key_type = c->c1.ks.key_type;
 
1846
  to.server = options->tls_server;
 
1847
  to.key_method = options->key_method;
 
1848
  to.replay = options->replay;
 
1849
  to.replay_window = options->replay_window;
 
1850
  to.replay_time = options->replay_time;
 
1851
  to.transition_window = options->transition_window;
 
1852
  to.handshake_window = options->handshake_window;
 
1853
  to.packet_timeout = options->tls_timeout;
 
1854
  to.renegotiate_bytes = options->renegotiate_bytes;
 
1855
  to.renegotiate_packets = options->renegotiate_packets;
 
1856
  to.renegotiate_seconds = options->renegotiate_seconds;
 
1857
  to.single_session = options->single_session;
 
1858
 
 
1859
  /* should we not xmit any packets until we get an initial
 
1860
     response from client? */
 
1861
  if (to.server && options->ce.proto == PROTO_TCPv4_SERVER)
 
1862
    to.xmit_hold = true;
 
1863
 
 
1864
#ifdef ENABLE_OCC
 
1865
  to.disable_occ = !options->occ;
 
1866
#endif
 
1867
 
 
1868
  to.verify_command = options->tls_verify;
 
1869
  to.verify_x509name = options->tls_remote;
 
1870
  to.crl_file = options->crl_file;
 
1871
  to.ns_cert_type = options->ns_cert_type;
 
1872
  memmove (to.remote_cert_ku, options->remote_cert_ku, sizeof (to.remote_cert_ku));
 
1873
  to.remote_cert_eku = options->remote_cert_eku;
 
1874
  to.es = c->c2.es;
 
1875
 
 
1876
#ifdef ENABLE_DEBUG
 
1877
  to.gremlin = c->options.gremlin;
 
1878
#endif
 
1879
 
 
1880
  to.plugins = c->plugins;
 
1881
 
 
1882
#ifdef MANAGEMENT_DEF_AUTH
 
1883
  to.mda_context = &c->c2.mda_context;
 
1884
#endif
 
1885
 
 
1886
#if P2MP_SERVER
 
1887
  to.auth_user_pass_verify_script = options->auth_user_pass_verify_script;
 
1888
  to.auth_user_pass_verify_script_via_file = options->auth_user_pass_verify_script_via_file;
 
1889
  to.tmp_dir = options->tmp_dir;
 
1890
  to.ssl_flags = options->ssl_flags;
 
1891
  if (options->ccd_exclusive)
 
1892
    to.client_config_dir_exclusive = options->client_config_dir;
 
1893
#endif
 
1894
 
 
1895
  /* TLS handshake authentication (--tls-auth) */
 
1896
  if (options->tls_auth_file)
 
1897
    {
 
1898
      to.tls_auth_key = c->c1.ks.tls_auth_key;
 
1899
      to.tls_auth.pid_persist = &c->c1.pid_persist;
 
1900
      to.tls_auth.flags |= CO_PACKET_ID_LONG_FORM;
 
1901
      crypto_adjust_frame_parameters (&to.frame,
 
1902
                                      &c->c1.ks.key_type,
 
1903
                                      false, false, true, true);
 
1904
    }
 
1905
 
 
1906
  /* If we are running over TCP, allow for
 
1907
     length prefix */
 
1908
  socket_adjust_frame_parameters (&to.frame, options->ce.proto);
 
1909
 
 
1910
  /*
 
1911
   * Initialize OpenVPN's master TLS-mode object.
 
1912
   */
 
1913
  if (flags & CF_INIT_TLS_MULTI)
 
1914
    c->c2.tls_multi = tls_multi_init (&to);
 
1915
 
 
1916
  if (flags & CF_INIT_TLS_AUTH_STANDALONE)
 
1917
    c->c2.tls_auth_standalone = tls_auth_standalone_init (&to, &c->c2.gc);
 
1918
}
 
1919
 
 
1920
static void
 
1921
do_init_finalize_tls_frame (struct context *c)
 
1922
{
 
1923
  if (c->c2.tls_multi)
 
1924
    {
 
1925
      tls_multi_init_finalize (c->c2.tls_multi, &c->c2.frame);
 
1926
      ASSERT (EXPANDED_SIZE (&c->c2.tls_multi->opt.frame) <=
 
1927
              EXPANDED_SIZE (&c->c2.frame));
 
1928
      frame_print (&c->c2.tls_multi->opt.frame, D_MTU_INFO,
 
1929
                   "Control Channel MTU parms");
 
1930
    }
 
1931
  if (c->c2.tls_auth_standalone)
 
1932
    {
 
1933
      tls_auth_standalone_finalize (c->c2.tls_auth_standalone, &c->c2.frame);
 
1934
      frame_print (&c->c2.tls_auth_standalone->frame, D_MTU_INFO,
 
1935
                   "TLS-Auth MTU parms");
 
1936
    }
 
1937
}
 
1938
 
 
1939
#endif /* USE_SSL */
 
1940
#endif /* USE_CRYPTO */
 
1941
 
 
1942
#ifdef USE_CRYPTO
 
1943
/*
 
1944
 * No encryption or authentication.
 
1945
 */
 
1946
static void
 
1947
do_init_crypto_none (const struct context *c)
 
1948
{
 
1949
  ASSERT (!c->options.test_crypto);
 
1950
  msg (M_WARN,
 
1951
       "******* WARNING *******: all encryption and authentication features disabled -- all data will be tunnelled as cleartext");
 
1952
}
 
1953
#endif
 
1954
 
 
1955
static void
 
1956
do_init_crypto (struct context *c, const unsigned int flags)
 
1957
{
 
1958
#ifdef USE_CRYPTO
 
1959
  if (c->options.shared_secret_file)
 
1960
    do_init_crypto_static (c, flags);
 
1961
#ifdef USE_SSL
 
1962
  else if (c->options.tls_server || c->options.tls_client)
 
1963
    do_init_crypto_tls (c, flags);
 
1964
#endif
 
1965
  else                          /* no encryption or authentication. */
 
1966
    do_init_crypto_none (c);
 
1967
#else /* USE_CRYPTO */
 
1968
  msg (M_WARN,
 
1969
       "******* WARNING *******: " PACKAGE_NAME
 
1970
       " built without OpenSSL -- encryption and authentication features disabled -- all data will be tunnelled as cleartext");
 
1971
#endif /* USE_CRYPTO */
 
1972
}
 
1973
 
 
1974
static void
 
1975
do_init_frame (struct context *c)
 
1976
{
 
1977
#ifdef USE_LZO
 
1978
  /*
 
1979
   * Initialize LZO compression library.
 
1980
   */
 
1981
  if (c->options.lzo & LZO_SELECTED)
 
1982
    {
 
1983
      lzo_adjust_frame_parameters (&c->c2.frame);
 
1984
 
 
1985
      /*
 
1986
       * LZO usage affects buffer alignment.
 
1987
       */
 
1988
      if (CIPHER_ENABLED (c))
 
1989
        {
 
1990
          frame_add_to_align_adjust (&c->c2.frame, LZO_PREFIX_LEN);
 
1991
          frame_or_align_flags (&c->c2.frame,
 
1992
                                FRAME_HEADROOM_MARKER_FRAGMENT
 
1993
                                |FRAME_HEADROOM_MARKER_DECRYPT);
 
1994
        }
 
1995
 
 
1996
#ifdef ENABLE_FRAGMENT
 
1997
      lzo_adjust_frame_parameters (&c->c2.frame_fragment_omit); /* omit LZO frame delta from final frame_fragment */
 
1998
#endif
 
1999
    }
 
2000
#endif /* USE_LZO */
 
2001
 
 
2002
#ifdef ENABLE_SOCKS
 
2003
  /*
 
2004
   * Adjust frame size for UDP Socks support.
 
2005
   */
 
2006
  if (c->options.ce.socks_proxy_server)
 
2007
    socks_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
 
2008
#endif
 
2009
 
 
2010
  /*
 
2011
   * Adjust frame size based on the --tun-mtu-extra parameter.
 
2012
   */
 
2013
  if (c->options.tun_mtu_extra_defined)
 
2014
    tun_adjust_frame_parameters (&c->c2.frame, c->options.tun_mtu_extra);
 
2015
 
 
2016
  /*
 
2017
   * Adjust frame size based on link socket parameters.
 
2018
   * (Since TCP is a stream protocol, we need to insert
 
2019
   * a packet length uint16_t in the buffer.)
 
2020
   */
 
2021
  socket_adjust_frame_parameters (&c->c2.frame, c->options.ce.proto);
 
2022
 
 
2023
  /*
 
2024
   * Fill in the blanks in the frame parameters structure,
 
2025
   * make sure values are rational, etc.
 
2026
   */
 
2027
  frame_finalize_options (c, NULL);
 
2028
 
 
2029
#ifdef ENABLE_FRAGMENT
 
2030
  /*
 
2031
   * Set frame parameter for fragment code.  This is necessary because
 
2032
   * the fragmentation code deals with payloads which have already been
 
2033
   * passed through the compression code.
 
2034
   */
 
2035
  c->c2.frame_fragment = c->c2.frame;
 
2036
  frame_subtract_extra (&c->c2.frame_fragment, &c->c2.frame_fragment_omit);
 
2037
#endif
 
2038
 
 
2039
#if defined(ENABLE_FRAGMENT) && defined(ENABLE_OCC)
 
2040
  /*
 
2041
   * MTU advisories
 
2042
   */
 
2043
  if (c->options.fragment && c->options.mtu_test)
 
2044
    msg (M_WARN,
 
2045
         "WARNING: using --fragment and --mtu-test together may produce an inaccurate MTU test result");
 
2046
#endif
 
2047
 
 
2048
#ifdef ENABLE_FRAGMENT
 
2049
  if ((c->options.mssfix || c->options.fragment)
 
2050
      && TUN_MTU_SIZE (&c->c2.frame_fragment) != ETHERNET_MTU)
 
2051
    msg (M_WARN,
 
2052
         "WARNING: normally if you use --mssfix and/or --fragment, you should also set --tun-mtu %d (currently it is %d)",
 
2053
         ETHERNET_MTU, TUN_MTU_SIZE (&c->c2.frame_fragment));
 
2054
#endif
 
2055
}
 
2056
 
 
2057
static void
 
2058
do_option_warnings (struct context *c)
 
2059
{
 
2060
  const struct options *o = &c->options;
 
2061
 
 
2062
#if 1 /* JYFIXME -- port warning */
 
2063
  if (!o->ce.port_option_used && (o->ce.local_port == OPENVPN_PORT && o->ce.remote_port == OPENVPN_PORT))
 
2064
    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.",
 
2065
         OPENVPN_PORT);
 
2066
#endif
 
2067
 
 
2068
  if (o->ping_send_timeout && !o->ping_rec_timeout)
 
2069
    msg (M_WARN, "WARNING: --ping should normally be used with --ping-restart or --ping-exit");
 
2070
 
 
2071
  if (o->username || o->groupname || o->chroot_dir
 
2072
#ifdef HAVE_SETCON
 
2073
      || o->selinux_context
 
2074
#endif
 
2075
      )
 
2076
   {
 
2077
    if (!o->persist_tun)
 
2078
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-tun -- this may cause restarts to fail");
 
2079
    if (!o->persist_key
 
2080
#ifdef ENABLE_PKCS11
 
2081
        && !o->pkcs11_id
 
2082
#endif
 
2083
        )
 
2084
     msg (M_WARN, "WARNING: you are using user/group/chroot/setcon without persist-key -- this may cause restarts to fail");
 
2085
   }
 
2086
 
 
2087
  if (o->chroot_dir && !(o->username && o->groupname))
 
2088
    msg (M_WARN, "WARNING: you are using chroot without specifying user and group -- this may cause the chroot jail to be insecure");
 
2089
 
 
2090
#if P2MP
 
2091
  if (o->pull && o->ifconfig_local && c->first_time)
 
2092
    msg (M_WARN, "WARNING: using --pull/--client and --ifconfig together is probably not what you want");
 
2093
 
 
2094
#if P2MP_SERVER
 
2095
  if (o->server_bridge_defined | o->server_bridge_proxy_dhcp)
 
2096
    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");
 
2097
 
 
2098
  if (o->mode == MODE_SERVER)
 
2099
    {
 
2100
      if (o->duplicate_cn && o->client_config_dir)
 
2101
        msg (M_WARN, "WARNING: using --duplicate-cn and --client-config-dir together is probably not what you want");
 
2102
      if (o->duplicate_cn && o->ifconfig_pool_persist_filename)
 
2103
        msg (M_WARN, "WARNING: --ifconfig-pool-persist will not work with --duplicate-cn");
 
2104
      if (!o->keepalive_ping || !o->keepalive_timeout)
 
2105
        msg (M_WARN, "WARNING: --keepalive option is missing from server config");
 
2106
    }
 
2107
#endif
 
2108
#endif
 
2109
 
 
2110
#ifdef USE_CRYPTO
 
2111
  if (!o->replay)
 
2112
    msg (M_WARN, "WARNING: You have disabled Replay Protection (--no-replay) which may make " PACKAGE_NAME " less secure");
 
2113
  if (!o->use_iv)
 
2114
    msg (M_WARN, "WARNING: You have disabled Crypto IVs (--no-iv) which may make " PACKAGE_NAME " less secure");
 
2115
 
 
2116
#ifdef USE_SSL
 
2117
  if (o->tls_server)
 
2118
    warn_on_use_of_common_subnets ();
 
2119
  if (o->tls_client
 
2120
      && !o->tls_verify
 
2121
      && !o->tls_remote
 
2122
      && !(o->ns_cert_type & NS_SSL_SERVER)
 
2123
      && !o->remote_cert_eku)
 
2124
    msg (M_WARN, "WARNING: No server certificate verification method has been enabled.  See http://openvpn.net/howto.html#mitm for more info.");
 
2125
  if (o->tls_remote)
 
2126
    msg (M_WARN, "WARNING: Make sure you understand the semantics of --tls-remote before using it (see the man page).");
 
2127
#endif
 
2128
#endif
 
2129
 
 
2130
#ifndef CONNECT_NONBLOCK
 
2131
  if (o->ce.connect_timeout_defined)
 
2132
    msg (M_WARN, "NOTE: --connect-timeout option is not supported on this OS");
 
2133
#endif
 
2134
 
 
2135
  if (script_security >= SSEC_SCRIPTS)
 
2136
    msg (M_WARN, "NOTE: the current --script-security setting may allow this configuration to call user-defined scripts");
 
2137
  else if (script_security >= SSEC_PW_ENV)
 
2138
    msg (M_WARN, "WARNING: the current --script-security setting may allow passwords to be passed to scripts via environmental variables");
 
2139
  else
 
2140
    msg (M_WARN, "NOTE: " PACKAGE_NAME " 2.1 requires '--script-security 2' or higher to call user-defined scripts or executables");
 
2141
 
 
2142
  if (script_method == SM_SYSTEM)
 
2143
    msg (M_WARN, "NOTE: --script-security method='system' is deprecated due to the fact that passed parameters will be subject to shell expansion");
 
2144
}
 
2145
 
 
2146
static void
 
2147
do_init_frame_tls (struct context *c)
 
2148
{
 
2149
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2150
  do_init_finalize_tls_frame (c);
 
2151
#endif
 
2152
}
 
2153
 
 
2154
struct context_buffers *
 
2155
init_context_buffers (const struct frame *frame)
 
2156
{
 
2157
  struct context_buffers *b;
 
2158
 
 
2159
  ALLOC_OBJ_CLEAR (b, struct context_buffers);
 
2160
 
 
2161
  b->read_link_buf = alloc_buf (BUF_SIZE (frame));
 
2162
  b->read_tun_buf = alloc_buf (BUF_SIZE (frame));
 
2163
 
 
2164
  b->aux_buf = alloc_buf (BUF_SIZE (frame));
 
2165
 
 
2166
#ifdef USE_CRYPTO
 
2167
  b->encrypt_buf = alloc_buf (BUF_SIZE (frame));
 
2168
  b->decrypt_buf = alloc_buf (BUF_SIZE (frame));
 
2169
#endif
 
2170
 
 
2171
#ifdef USE_LZO
 
2172
  b->lzo_compress_buf = alloc_buf (BUF_SIZE (frame));
 
2173
  b->lzo_decompress_buf = alloc_buf (BUF_SIZE (frame));
 
2174
#endif
 
2175
 
 
2176
  return b;
 
2177
}
 
2178
 
 
2179
void
 
2180
free_context_buffers (struct context_buffers *b)
 
2181
{
 
2182
  if (b)
 
2183
    {
 
2184
      free_buf (&b->read_link_buf);
 
2185
      free_buf (&b->read_tun_buf);
 
2186
      free_buf (&b->aux_buf);
 
2187
 
 
2188
#ifdef USE_LZO
 
2189
      free_buf (&b->lzo_compress_buf);
 
2190
      free_buf (&b->lzo_decompress_buf);
 
2191
#endif
 
2192
 
 
2193
#ifdef USE_CRYPTO
 
2194
      free_buf (&b->encrypt_buf);
 
2195
      free_buf (&b->decrypt_buf);
 
2196
#endif
 
2197
 
 
2198
      free (b);
 
2199
    }
 
2200
}
 
2201
 
 
2202
/*
 
2203
 * Now that we know all frame parameters, initialize
 
2204
 * our buffers.
 
2205
 */
 
2206
static void
 
2207
do_init_buffers (struct context *c)
 
2208
{
 
2209
  c->c2.buffers = init_context_buffers (&c->c2.frame);
 
2210
  c->c2.buffers_owned = true;
 
2211
}
 
2212
 
 
2213
#ifdef ENABLE_FRAGMENT
 
2214
/*
 
2215
 * Fragmenting code has buffers to initialize
 
2216
 * once frame parameters are known.
 
2217
 */
 
2218
static void
 
2219
do_init_fragment (struct context *c)
 
2220
{
 
2221
  ASSERT (c->options.fragment);
 
2222
  frame_set_mtu_dynamic (&c->c2.frame_fragment,
 
2223
                         c->options.fragment, SET_MTU_UPPER_BOUND);
 
2224
  fragment_frame_init (c->c2.fragment, &c->c2.frame_fragment);
 
2225
}
 
2226
#endif
 
2227
 
 
2228
/*
 
2229
 * Set the --mssfix option.
 
2230
 */
 
2231
static void
 
2232
do_init_mssfix (struct context *c)
 
2233
{
 
2234
  if (c->options.mssfix)
 
2235
    {
 
2236
      frame_set_mtu_dynamic (&c->c2.frame,
 
2237
                             c->options.mssfix, SET_MTU_UPPER_BOUND);
 
2238
    }
 
2239
}
 
2240
 
 
2241
/*
 
2242
 * Allocate our socket object.
 
2243
 */
 
2244
static void
 
2245
do_link_socket_new (struct context *c)
 
2246
{
 
2247
  ASSERT (!c->c2.link_socket);
 
2248
  c->c2.link_socket = link_socket_new ();
 
2249
  c->c2.link_socket_owned = true;
 
2250
}
 
2251
 
 
2252
/*
 
2253
 * bind the TCP/UDP socket
 
2254
 */
 
2255
static void
 
2256
do_init_socket_1 (struct context *c, const int mode)
 
2257
{
 
2258
  unsigned int sockflags = c->options.sockflags;
 
2259
 
 
2260
#if PORT_SHARE
 
2261
  if (c->options.port_share_host && c->options.port_share_port)
 
2262
    sockflags |= SF_PORT_SHARE;
 
2263
#endif
 
2264
 
 
2265
  link_socket_init_phase1 (c->c2.link_socket,
 
2266
                           connection_list_defined (&c->options),
 
2267
                           c->options.ce.local,
 
2268
                           c->options.ce.local_port,
 
2269
                           c->options.ce.remote,
 
2270
                           c->options.ce.remote_port,
 
2271
                           c->options.ce.proto,
 
2272
                           mode,
 
2273
                           c->c2.accept_from,
 
2274
#ifdef ENABLE_HTTP_PROXY
 
2275
                           c->c1.http_proxy,
 
2276
#endif
 
2277
#ifdef ENABLE_SOCKS
 
2278
                           c->c1.socks_proxy,
 
2279
#endif
 
2280
#ifdef ENABLE_DEBUG
 
2281
                           c->options.gremlin,
 
2282
#endif
 
2283
                           c->options.ce.bind_local,
 
2284
                           c->options.ce.remote_float,
 
2285
                           c->options.inetd,
 
2286
                           &c->c1.link_socket_addr,
 
2287
                           c->options.ipchange,
 
2288
                           c->plugins,
 
2289
                           c->options.resolve_retry_seconds,
 
2290
                           c->options.ce.connect_retry_seconds,
 
2291
                           c->options.ce.connect_timeout,
 
2292
                           c->options.ce.connect_retry_max,
 
2293
                           c->options.mtu_discover_type,
 
2294
                           c->options.rcvbuf,
 
2295
                           c->options.sndbuf,
 
2296
                           sockflags);
 
2297
}
 
2298
 
 
2299
/*
 
2300
 * finalize the TCP/UDP socket
 
2301
 */
 
2302
static void
 
2303
do_init_socket_2 (struct context *c)
 
2304
{
 
2305
  link_socket_init_phase2 (c->c2.link_socket, &c->c2.frame,
 
2306
                           &c->sig->signal_received);
 
2307
}
 
2308
 
 
2309
/*
 
2310
 * Print MTU INFO
 
2311
 */
 
2312
static void
 
2313
do_print_data_channel_mtu_parms (struct context *c)
 
2314
{
 
2315
  frame_print (&c->c2.frame, D_MTU_INFO, "Data Channel MTU parms");
 
2316
#ifdef ENABLE_FRAGMENT
 
2317
  if (c->c2.fragment)
 
2318
    frame_print (&c->c2.frame_fragment, D_MTU_INFO,
 
2319
                 "Fragmentation MTU parms");
 
2320
#endif
 
2321
}
 
2322
 
 
2323
#ifdef ENABLE_OCC
 
2324
/*
 
2325
 * Get local and remote options compatibility strings.
 
2326
 */
 
2327
static void
 
2328
do_compute_occ_strings (struct context *c)
 
2329
{
 
2330
  struct gc_arena gc = gc_new ();
 
2331
 
 
2332
  c->c2.options_string_local =
 
2333
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, false, &gc);
 
2334
  c->c2.options_string_remote =
 
2335
    options_string (&c->options, &c->c2.frame, c->c1.tuntap, true, &gc);
 
2336
 
 
2337
  msg (D_SHOW_OCC, "Local Options String: '%s'", c->c2.options_string_local);
 
2338
  msg (D_SHOW_OCC, "Expected Remote Options String: '%s'",
 
2339
       c->c2.options_string_remote);
 
2340
 
 
2341
#ifdef USE_CRYPTO
 
2342
  msg (D_SHOW_OCC_HASH, "Local Options hash (VER=%s): '%s'",
 
2343
       options_string_version (c->c2.options_string_local, &gc),
 
2344
       md5sum ((uint8_t*)c->c2.options_string_local,
 
2345
               strlen (c->c2.options_string_local), 9, &gc));
 
2346
  msg (D_SHOW_OCC_HASH, "Expected Remote Options hash (VER=%s): '%s'",
 
2347
       options_string_version (c->c2.options_string_remote, &gc),
 
2348
       md5sum ((uint8_t*)c->c2.options_string_remote,
 
2349
               strlen (c->c2.options_string_remote), 9, &gc));
 
2350
#endif
 
2351
 
 
2352
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2353
  if (c->c2.tls_multi)
 
2354
    tls_multi_init_set_options (c->c2.tls_multi,
 
2355
                                c->c2.options_string_local,
 
2356
                                c->c2.options_string_remote);
 
2357
#endif
 
2358
 
 
2359
  gc_free (&gc);
 
2360
}
 
2361
#endif
 
2362
 
 
2363
/*
 
2364
 * These things can only be executed once per program instantiation.
 
2365
 * Set up for possible UID/GID downgrade, but don't do it yet.
 
2366
 * Daemonize if requested.
 
2367
 */
 
2368
static void
 
2369
do_init_first_time (struct context *c)
 
2370
{
 
2371
  if (c->first_time && !c->did_we_daemonize && !c->c0)
 
2372
    {
 
2373
      struct context_0 *c0;
 
2374
 
 
2375
      ALLOC_OBJ_CLEAR_GC (c->c0, struct context_0, &c->gc);
 
2376
      c0 = c->c0;
 
2377
      
 
2378
      /* get user and/or group that we want to setuid/setgid to */
 
2379
      c0->uid_gid_specified =
 
2380
        get_group (c->options.groupname, &c0->group_state) |
 
2381
        get_user (c->options.username, &c0->user_state);
 
2382
 
 
2383
      /* get --writepid file descriptor */
 
2384
      get_pid_file (c->options.writepid, &c0->pid_state);
 
2385
 
 
2386
      /* become a daemon if --daemon */
 
2387
      c->did_we_daemonize = possibly_become_daemon (&c->options, c->first_time);
 
2388
 
 
2389
      /* should we disable paging? */
 
2390
      if (c->options.mlock && c->did_we_daemonize)
 
2391
        do_mlockall (true);     /* call again in case we daemonized */
 
2392
 
 
2393
      /* save process ID in a file */
 
2394
      write_pid (&c0->pid_state);
 
2395
 
 
2396
      /* should we change scheduling priority? */
 
2397
      set_nice (c->options.nice);
 
2398
    }
 
2399
}
 
2400
 
 
2401
/*
 
2402
 * If xinetd/inetd mode, don't allow restart.
 
2403
 */
 
2404
static void
 
2405
do_close_check_if_restart_permitted (struct context *c)
 
2406
{
 
2407
  if (c->options.inetd
 
2408
      && (c->sig->signal_received == SIGHUP
 
2409
          || c->sig->signal_received == SIGUSR1))
 
2410
    {
 
2411
      c->sig->signal_received = SIGTERM;
 
2412
      msg (M_INFO,
 
2413
           PACKAGE_NAME
 
2414
           " started by inetd/xinetd cannot restart... Exiting.");
 
2415
    }
 
2416
}
 
2417
 
 
2418
/*
 
2419
 * free buffers
 
2420
 */
 
2421
static void
 
2422
do_close_free_buf (struct context *c)
 
2423
{
 
2424
  if (c->c2.buffers_owned)
 
2425
    {
 
2426
      free_context_buffers (c->c2.buffers);
 
2427
      c->c2.buffers = NULL;
 
2428
      c->c2.buffers_owned = false;
 
2429
    }
 
2430
}
 
2431
 
 
2432
/*
 
2433
 * close TLS
 
2434
 */
 
2435
static void
 
2436
do_close_tls (struct context *c)
 
2437
{
 
2438
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2439
  if (c->c2.tls_multi)
 
2440
    {
 
2441
      tls_multi_free (c->c2.tls_multi, true);
 
2442
      c->c2.tls_multi = NULL;
 
2443
    }
 
2444
 
 
2445
#ifdef ENABLE_OCC
 
2446
  /* free options compatibility strings */
 
2447
  if (c->c2.options_string_local)
 
2448
    free (c->c2.options_string_local);
 
2449
  if (c->c2.options_string_remote)
 
2450
    free (c->c2.options_string_remote);
 
2451
  c->c2.options_string_local = c->c2.options_string_remote = NULL;
 
2452
#endif
 
2453
#endif
 
2454
}
 
2455
 
 
2456
/*
 
2457
 * Free key schedules
 
2458
 */
 
2459
static void
 
2460
do_close_free_key_schedule (struct context *c, bool free_ssl_ctx)
 
2461
{
 
2462
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_key))
 
2463
    key_schedule_free (&c->c1.ks, free_ssl_ctx);
 
2464
}
 
2465
 
 
2466
/*
 
2467
 * Close TCP/UDP connection
 
2468
 */
 
2469
static void
 
2470
do_close_link_socket (struct context *c)
 
2471
{
 
2472
  if (c->c2.link_socket && c->c2.link_socket_owned)
 
2473
    {
 
2474
      link_socket_close (c->c2.link_socket);
 
2475
      c->c2.link_socket = NULL;
 
2476
    }
 
2477
 
 
2478
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_remote_ip))
 
2479
    {
 
2480
      CLEAR (c->c1.link_socket_addr.remote);
 
2481
      CLEAR (c->c1.link_socket_addr.actual);
 
2482
    }
 
2483
 
 
2484
  if (!(c->sig->signal_received == SIGUSR1 && c->options.persist_local_ip))
 
2485
    CLEAR (c->c1.link_socket_addr.local);
 
2486
}
 
2487
 
 
2488
/*
 
2489
 * Close packet-id persistance file
 
2490
 */
 
2491
static void
 
2492
do_close_packet_id (struct context *c)
 
2493
{
 
2494
#ifdef USE_CRYPTO
 
2495
  packet_id_free (&c->c2.packet_id);
 
2496
  packet_id_persist_save (&c->c1.pid_persist);
 
2497
  if (!(c->sig->signal_received == SIGUSR1))
 
2498
    packet_id_persist_close (&c->c1.pid_persist);
 
2499
#endif
 
2500
}
 
2501
 
 
2502
#ifdef ENABLE_FRAGMENT
 
2503
/*
 
2504
 * Close fragmentation handler.
 
2505
 */
 
2506
static void
 
2507
do_close_fragment (struct context *c)
 
2508
{
 
2509
  if (c->c2.fragment)
 
2510
    {
 
2511
      fragment_free (c->c2.fragment);
 
2512
      c->c2.fragment = NULL;
 
2513
    }
 
2514
}
 
2515
#endif
 
2516
 
 
2517
/*
 
2518
 * Open and close our event objects.
 
2519
 */
 
2520
 
 
2521
static void
 
2522
do_event_set_init (struct context *c,
 
2523
                   bool need_us_timeout)
 
2524
{
 
2525
  unsigned int flags = 0;
 
2526
 
 
2527
  c->c2.event_set_max = BASE_N_EVENTS;
 
2528
 
 
2529
  flags |= EVENT_METHOD_FAST;
 
2530
 
 
2531
  if (need_us_timeout)
 
2532
    flags |= EVENT_METHOD_US_TIMEOUT;
 
2533
 
 
2534
  c->c2.event_set = event_set_init (&c->c2.event_set_max, flags);
 
2535
  c->c2.event_set_owned = true;
 
2536
}
 
2537
 
 
2538
static void
 
2539
do_close_event_set (struct context *c)
 
2540
{
 
2541
  if (c->c2.event_set && c->c2.event_set_owned)
 
2542
    {
 
2543
      event_free (c->c2.event_set);
 
2544
      c->c2.event_set = NULL;
 
2545
      c->c2.event_set_owned = false;
 
2546
    }
 
2547
}
 
2548
 
 
2549
/*
 
2550
 * Open and close --status file
 
2551
 */
 
2552
 
 
2553
static void
 
2554
do_open_status_output (struct context *c)
 
2555
{
 
2556
  if (!c->c1.status_output)
 
2557
    {
 
2558
      c->c1.status_output = status_open (c->options.status_file,
 
2559
                                         c->options.status_file_update_freq,
 
2560
                                         -1,
 
2561
                                         NULL,
 
2562
                                         STATUS_OUTPUT_WRITE);
 
2563
      c->c1.status_output_owned = true;
 
2564
    }
 
2565
}
 
2566
 
 
2567
static void
 
2568
do_close_status_output (struct context *c)
 
2569
{
 
2570
  if (!(c->sig->signal_received == SIGUSR1))
 
2571
    {
 
2572
      if (c->c1.status_output_owned && c->c1.status_output)
 
2573
        {
 
2574
          status_close (c->c1.status_output);
 
2575
          c->c1.status_output = NULL;
 
2576
          c->c1.status_output_owned = false;
 
2577
        }
 
2578
    }
 
2579
}
 
2580
 
 
2581
/*
 
2582
 * Handle ifconfig-pool persistance object.
 
2583
 */
 
2584
static void
 
2585
do_open_ifconfig_pool_persist (struct context *c)
 
2586
{
 
2587
#if P2MP_SERVER
 
2588
  if (!c->c1.ifconfig_pool_persist && c->options.ifconfig_pool_persist_filename)
 
2589
    {
 
2590
      c->c1.ifconfig_pool_persist = ifconfig_pool_persist_init (c->options.ifconfig_pool_persist_filename,
 
2591
                                                                c->options.ifconfig_pool_persist_refresh_freq);
 
2592
      c->c1.ifconfig_pool_persist_owned = true;
 
2593
    }
 
2594
#endif
 
2595
}
 
2596
 
 
2597
static void
 
2598
do_close_ifconfig_pool_persist (struct context *c)
 
2599
{
 
2600
#if P2MP_SERVER
 
2601
  if (!(c->sig->signal_received == SIGUSR1))
 
2602
    {
 
2603
      if (c->c1.ifconfig_pool_persist && c->c1.ifconfig_pool_persist_owned)
 
2604
        {
 
2605
          ifconfig_pool_persist_close (c->c1.ifconfig_pool_persist);
 
2606
          c->c1.ifconfig_pool_persist = NULL;
 
2607
          c->c1.ifconfig_pool_persist_owned = false;
 
2608
        }
 
2609
    }
 
2610
#endif
 
2611
}
 
2612
 
 
2613
/*
 
2614
 * Inherit environmental variables
 
2615
 */
 
2616
 
 
2617
static void
 
2618
do_inherit_env (struct context *c, const struct env_set *src)
 
2619
{
 
2620
  c->c2.es = env_set_create (NULL);
 
2621
  c->c2.es_owned = true;
 
2622
  env_set_inherit (c->c2.es, src);
 
2623
}
 
2624
 
 
2625
static void
 
2626
do_env_set_destroy (struct context *c)
 
2627
{
 
2628
  if (c->c2.es && c->c2.es_owned)
 
2629
    {
 
2630
      env_set_destroy (c->c2.es);
 
2631
      c->c2.es = NULL;
 
2632
      c->c2.es_owned = false;
 
2633
    }
 
2634
}
 
2635
 
 
2636
/*
 
2637
 * Fast I/O setup.  Fast I/O is an optimization which only works
 
2638
 * if all of the following are true:
 
2639
 *
 
2640
 * (1) The platform is not Windows
 
2641
 * (2) --proto udp is enabled
 
2642
 * (3) --shaper is disabled
 
2643
 */
 
2644
static void
 
2645
do_setup_fast_io (struct context *c)
 
2646
{
 
2647
  if (c->options.fast_io)
 
2648
    {
 
2649
#ifdef WIN32
 
2650
      msg (M_INFO, "NOTE: --fast-io is disabled since we are running on Windows");
 
2651
#else
 
2652
      if (c->options.ce.proto != PROTO_UDPv4)
 
2653
        msg (M_INFO, "NOTE: --fast-io is disabled since we are not using UDP");
 
2654
      else
 
2655
        {
 
2656
#ifdef HAVE_GETTIMEOFDAY
 
2657
          if (c->options.shaper)
 
2658
            msg (M_INFO, "NOTE: --fast-io is disabled since we are using --shaper");
 
2659
          else
 
2660
#endif
 
2661
            {
 
2662
              c->c2.fast_io = true;
 
2663
            }
 
2664
        }
 
2665
#endif
 
2666
    }
 
2667
}
 
2668
 
 
2669
static void
 
2670
do_signal_on_tls_errors (struct context *c)
 
2671
{
 
2672
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
2673
  if (c->options.tls_exit)
 
2674
    c->c2.tls_exit_signal = SIGTERM;
 
2675
  else
 
2676
    c->c2.tls_exit_signal = SIGUSR1;    
 
2677
#endif
 
2678
}
 
2679
 
 
2680
#ifdef ENABLE_PLUGIN
 
2681
 
 
2682
void
 
2683
init_plugins (struct context *c)
 
2684
{
 
2685
  if (c->options.plugin_list && !c->plugins)
 
2686
    {
 
2687
      c->plugins = plugin_list_init (c->options.plugin_list);
 
2688
      c->plugins_owned = true;
 
2689
    }
 
2690
}
 
2691
 
 
2692
void
 
2693
open_plugins (struct context *c, const bool import_options, int init_point)
 
2694
{
 
2695
  if (c->plugins && c->plugins_owned)
 
2696
    {
 
2697
      if (import_options)
 
2698
        {
 
2699
          struct plugin_return pr, config;
 
2700
          plugin_return_init (&pr);
 
2701
          plugin_list_open (c->plugins, c->options.plugin_list, &pr, c->c2.es, init_point);
 
2702
          plugin_return_get_column (&pr, &config, "config");
 
2703
          if (plugin_return_defined (&config))
 
2704
            {
 
2705
              int i;
 
2706
              for (i = 0; i < config.n; ++i)
 
2707
                {
 
2708
                  unsigned int option_types_found = 0;
 
2709
                  if (config.list[i] && config.list[i]->value)
 
2710
                    options_string_import (&c->options,
 
2711
                                           config.list[i]->value,
 
2712
                                           D_IMPORT_ERRORS|M_OPTERR,
 
2713
                                           OPT_P_DEFAULT & ~OPT_P_PLUGIN,
 
2714
                                           &option_types_found,
 
2715
                                           c->es);
 
2716
                }
 
2717
            }
 
2718
          plugin_return_free (&pr);
 
2719
        }
 
2720
      else
 
2721
        {
 
2722
          plugin_list_open (c->plugins, c->options.plugin_list, NULL, c->c2.es, init_point);
 
2723
        }
 
2724
    }
 
2725
}
 
2726
 
 
2727
static void
 
2728
do_close_plugins (struct context *c)
 
2729
{
 
2730
  if (c->plugins && c->plugins_owned && !(c->sig->signal_received == SIGUSR1))
 
2731
    {
 
2732
      plugin_list_close (c->plugins);
 
2733
      c->plugins = NULL;
 
2734
      c->plugins_owned = false;
 
2735
    }
 
2736
}
 
2737
 
 
2738
static void
 
2739
do_inherit_plugins (struct context *c, const struct context *src)
 
2740
{
 
2741
  if (!c->plugins && src->plugins)
 
2742
    {
 
2743
      c->plugins = plugin_list_inherit (src->plugins);
 
2744
      c->plugins_owned = true;
 
2745
    }
 
2746
}
 
2747
 
 
2748
#endif
 
2749
 
 
2750
#ifdef ENABLE_MANAGEMENT
 
2751
 
 
2752
static void
 
2753
management_callback_status_p2p (void *arg, const int version, struct status_output *so)
 
2754
{
 
2755
  struct context *c = (struct context *) arg;
 
2756
  print_status (c, so);
 
2757
}
 
2758
 
 
2759
void
 
2760
management_show_net_callback (void *arg, const int msglevel)
 
2761
{
 
2762
#ifdef WIN32
 
2763
  show_routes (msglevel);
 
2764
  show_adapters (msglevel);
 
2765
  msg (msglevel, "END");
 
2766
#else
 
2767
  msg (msglevel, "ERROR: Sorry, this command is currently only implemented on Windows");
 
2768
#endif
 
2769
}
 
2770
 
 
2771
#endif
 
2772
 
 
2773
void
 
2774
init_management_callback_p2p (struct context *c)
 
2775
{
 
2776
#ifdef ENABLE_MANAGEMENT
 
2777
  if (management)
 
2778
    {
 
2779
      struct management_callback cb;
 
2780
      CLEAR (cb);
 
2781
      cb.arg = c;
 
2782
      cb.status = management_callback_status_p2p;
 
2783
      cb.show_net = management_show_net_callback;
 
2784
      management_set_callback (management, &cb);
 
2785
    }
 
2786
#endif
 
2787
}
 
2788
 
 
2789
#ifdef ENABLE_MANAGEMENT
 
2790
 
 
2791
void
 
2792
init_management (struct context *c)
 
2793
{
 
2794
  if (!management)
 
2795
    management = management_init ();
 
2796
}
 
2797
 
 
2798
bool
 
2799
open_management (struct context *c)
 
2800
{
 
2801
  /* initialize management layer */
 
2802
  if (management)
 
2803
    {
 
2804
      if (c->options.management_addr)
 
2805
        {
 
2806
          unsigned int flags = c->options.management_flags;
 
2807
          if (c->options.mode == MODE_SERVER)
 
2808
            flags |= MF_SERVER;
 
2809
          if (management_open (management,
 
2810
                               c->options.management_addr,
 
2811
                               c->options.management_port,
 
2812
                               c->options.management_user_pass,
 
2813
                               c->options.management_client_user,
 
2814
                               c->options.management_client_group,
 
2815
                               c->options.management_log_history_cache,
 
2816
                               c->options.management_echo_buffer_size,
 
2817
                               c->options.management_state_buffer_size,
 
2818
                               c->options.management_write_peer_info_file,
 
2819
                               c->options.remap_sigusr1,
 
2820
                               flags))
 
2821
            {
 
2822
              management_set_state (management,
 
2823
                                    OPENVPN_STATE_CONNECTING,
 
2824
                                    NULL,
 
2825
                                    (in_addr_t)0,
 
2826
                                    (in_addr_t)0);
 
2827
            }
 
2828
 
 
2829
          /* initial management hold, called early, before first context initialization */
 
2830
          do_hold (c);
 
2831
          if (IS_SIG (c))
 
2832
            {
 
2833
              msg (M_WARN, "Signal received from management interface, exiting");
 
2834
              return false;
 
2835
            }
 
2836
        }
 
2837
      else
 
2838
        close_management ();
 
2839
    }
 
2840
  return true;
 
2841
}
 
2842
 
 
2843
void
 
2844
close_management (void)
 
2845
{
 
2846
  if (management)
 
2847
    {
 
2848
      management_close (management);
 
2849
      management = NULL;
 
2850
    }
 
2851
}
 
2852
 
 
2853
#endif
 
2854
 
 
2855
 
 
2856
void
 
2857
uninit_management_callback (void)
 
2858
{
 
2859
#ifdef ENABLE_MANAGEMENT
 
2860
  if (management)
 
2861
    {
 
2862
      management_clear_callback (management);
 
2863
    }
 
2864
#endif
 
2865
}
 
2866
 
 
2867
/*
 
2868
 * Initialize a tunnel instance, handle pre and post-init
 
2869
 * signal settings.
 
2870
 */
 
2871
void
 
2872
init_instance_handle_signals (struct context *c, const struct env_set *env, const unsigned int flags)
 
2873
{
 
2874
  pre_init_signal_catch ();
 
2875
  init_instance (c, env, flags);
 
2876
  post_init_signal_catch ();
 
2877
 
 
2878
  /*
 
2879
   * This is done so that signals thrown during
 
2880
   * initialization can bring us back to
 
2881
   * a management hold.
 
2882
   */
 
2883
  if (IS_SIG (c))
 
2884
    {
 
2885
      remap_signal (c);
 
2886
      uninit_management_callback ();  
 
2887
    }
 
2888
}
 
2889
 
 
2890
/*
 
2891
 * Initialize a tunnel instance.
 
2892
 */
 
2893
void
 
2894
init_instance (struct context *c, const struct env_set *env, const unsigned int flags)
 
2895
{
 
2896
  const struct options *options = &c->options;
 
2897
  const bool child = (c->mode == CM_CHILD_TCP || c->mode == CM_CHILD_UDP);
 
2898
  int link_socket_mode = LS_MODE_DEFAULT;
 
2899
 
 
2900
  /* init garbage collection level */
 
2901
  gc_init (&c->c2.gc);
 
2902
 
 
2903
  /* signals caught here will abort */
 
2904
  c->sig->signal_received = 0;
 
2905
  c->sig->signal_text = NULL;
 
2906
  c->sig->hard = false;
 
2907
 
 
2908
  /* map in current connection entry */
 
2909
  next_connection_entry (c);
 
2910
 
 
2911
  /* link_socket_mode allows CM_CHILD_TCP
 
2912
     instances to inherit acceptable fds
 
2913
     from a top-level parent */
 
2914
  if (c->options.ce.proto == PROTO_TCPv4_SERVER)
 
2915
    {
 
2916
      if (c->mode == CM_TOP)
 
2917
        link_socket_mode = LS_MODE_TCP_LISTEN;
 
2918
      else if (c->mode == CM_CHILD_TCP)
 
2919
        link_socket_mode = LS_MODE_TCP_ACCEPT_FROM;
 
2920
    }
 
2921
 
 
2922
  /* should we disable paging? */
 
2923
  if (c->first_time && options->mlock)
 
2924
    do_mlockall (true);
 
2925
 
 
2926
  /* possible sleep or management hold if restart */
 
2927
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2928
    {
 
2929
      do_startup_pause (c);
 
2930
      if (IS_SIG (c))
 
2931
        goto sig;
 
2932
    }
 
2933
 
 
2934
#if P2MP
 
2935
  /* get passwords if undefined */
 
2936
  if (auth_retry_get () == AR_INTERACT)
 
2937
    init_query_passwords (c);
 
2938
#endif
 
2939
 
 
2940
  /* initialize context level 2 --verb/--mute parms */
 
2941
  init_verb_mute (c, IVM_LEVEL_2);
 
2942
 
 
2943
  /* set error message delay for non-server modes */
 
2944
  if (c->mode == CM_P2P)
 
2945
    set_check_status_error_delay (P2P_ERROR_DELAY_MS);
 
2946
    
 
2947
  /* warn about inconsistent options */
 
2948
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2949
    do_option_warnings (c);
 
2950
 
 
2951
  /* inherit environmental variables */
 
2952
  if (env)
 
2953
    do_inherit_env (c, env);
 
2954
 
 
2955
#ifdef ENABLE_PLUGIN
 
2956
  /* initialize plugins */
 
2957
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2958
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_PRE_DAEMON);
 
2959
#endif
 
2960
 
 
2961
  /* should we enable fast I/O? */
 
2962
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2963
    do_setup_fast_io (c);
 
2964
 
 
2965
  /* should we throw a signal on TLS errors? */
 
2966
  do_signal_on_tls_errors (c);
 
2967
 
 
2968
  /* open --status file */
 
2969
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
2970
    do_open_status_output (c);
 
2971
 
 
2972
  /* open --ifconfig-pool-persist file */
 
2973
  if (c->mode == CM_TOP)
 
2974
    do_open_ifconfig_pool_persist (c);
 
2975
 
 
2976
#ifdef ENABLE_OCC
 
2977
  /* reset OCC state */
 
2978
  if (c->mode == CM_P2P || child)
 
2979
    c->c2.occ_op = occ_reset_op ();
 
2980
#endif
 
2981
 
 
2982
  /* our wait-for-i/o objects, different for posix vs. win32 */
 
2983
  if (c->mode == CM_P2P)
 
2984
    do_event_set_init (c, SHAPER_DEFINED (&c->options));
 
2985
  else if (c->mode == CM_CHILD_TCP)
 
2986
    do_event_set_init (c, false);
 
2987
 
 
2988
  /* initialize HTTP or SOCKS proxy object at scope level 2 */
 
2989
  init_proxy (c, 2);
 
2990
 
 
2991
  /* allocate our socket object */
 
2992
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
2993
    do_link_socket_new (c);
 
2994
 
 
2995
#ifdef ENABLE_FRAGMENT
 
2996
  /* initialize internal fragmentation object */
 
2997
  if (options->fragment && (c->mode == CM_P2P || child))
 
2998
    c->c2.fragment = fragment_init (&c->c2.frame);
 
2999
#endif
 
3000
 
 
3001
  /* init crypto layer */
 
3002
  {
 
3003
    unsigned int crypto_flags = 0;
 
3004
    if (c->mode == CM_TOP)
 
3005
      crypto_flags = CF_INIT_TLS_AUTH_STANDALONE;
 
3006
    else if (c->mode == CM_P2P)
 
3007
      crypto_flags = CF_LOAD_PERSISTED_PACKET_ID | CF_INIT_TLS_MULTI;
 
3008
    else if (child)
 
3009
      crypto_flags = CF_INIT_TLS_MULTI;
 
3010
    do_init_crypto (c, crypto_flags);
 
3011
    if (IS_SIG (c) && !child)
 
3012
      goto sig;
 
3013
  }
 
3014
 
 
3015
#ifdef USE_LZO
 
3016
  /* initialize LZO compression library. */
 
3017
  if ((options->lzo & LZO_SELECTED) && (c->mode == CM_P2P || child))
 
3018
    lzo_compress_init (&c->c2.lzo_compwork, options->lzo);
 
3019
#endif
 
3020
 
 
3021
  /* initialize MTU variables */
 
3022
  do_init_frame (c);
 
3023
 
 
3024
  /* initialize TLS MTU variables */
 
3025
  do_init_frame_tls (c);
 
3026
 
 
3027
  /* init workspace buffers whose size is derived from frame size */
 
3028
  if (c->mode == CM_P2P || c->mode == CM_CHILD_TCP)
 
3029
    do_init_buffers (c);
 
3030
 
 
3031
#ifdef ENABLE_FRAGMENT
 
3032
  /* initialize internal fragmentation capability with known frame size */
 
3033
  if (options->fragment && (c->mode == CM_P2P || child))
 
3034
    do_init_fragment (c);
 
3035
#endif
 
3036
 
 
3037
  /* initialize dynamic MTU variable */
 
3038
  do_init_mssfix (c);
 
3039
 
 
3040
  /* bind the TCP/UDP socket */
 
3041
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
3042
    do_init_socket_1 (c, link_socket_mode);
 
3043
 
 
3044
  /* initialize tun/tap device object,
 
3045
     open tun/tap device, ifconfig, run up script, etc. */
 
3046
  if (!(options->up_delay || PULL_DEFINED (options)) && (c->mode == CM_P2P || c->mode == CM_TOP))
 
3047
    c->c2.did_open_tun = do_open_tun (c);
 
3048
 
 
3049
  /* print MTU info */
 
3050
  do_print_data_channel_mtu_parms (c);
 
3051
 
 
3052
#ifdef ENABLE_OCC
 
3053
  /* get local and remote options compatibility strings */
 
3054
  if (c->mode == CM_P2P || child)
 
3055
    do_compute_occ_strings (c);
 
3056
#endif
 
3057
 
 
3058
  /* initialize output speed limiter */
 
3059
  if (c->mode == CM_P2P)
 
3060
    do_init_traffic_shaper (c);
 
3061
 
 
3062
  /* do one-time inits, and possibily become a daemon here */
 
3063
  do_init_first_time (c);
 
3064
 
 
3065
#ifdef ENABLE_PLUGIN
 
3066
  /* initialize plugins */
 
3067
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
3068
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_DAEMON);
 
3069
#endif
 
3070
 
 
3071
  /*
 
3072
   * Actually do UID/GID downgrade, and chroot, if requested.
 
3073
   * May be delayed by --client, --pull, or --up-delay.
 
3074
   */
 
3075
  do_uid_gid_chroot (c, c->c2.did_open_tun);
 
3076
 
 
3077
  /* finalize the TCP/UDP socket */
 
3078
  if (c->mode == CM_P2P || c->mode == CM_TOP || c->mode == CM_CHILD_TCP)
 
3079
    do_init_socket_2 (c);
 
3080
 
 
3081
  /* initialize timers */
 
3082
  if (c->mode == CM_P2P || child)
 
3083
    do_init_timers (c, false);
 
3084
 
 
3085
#ifdef ENABLE_PLUGIN
 
3086
  /* initialize plugins */
 
3087
  if (c->mode == CM_P2P || c->mode == CM_TOP)
 
3088
    open_plugins (c, false, OPENVPN_PLUGIN_INIT_POST_UID_CHANGE);
 
3089
#endif
 
3090
 
 
3091
#if PORT_SHARE
 
3092
  /* share OpenVPN port with foreign (such as HTTPS) server */
 
3093
  if (c->first_time && (c->mode == CM_P2P || c->mode == CM_TOP))
 
3094
    init_port_share (c);
 
3095
#endif
 
3096
          
 
3097
#ifdef ENABLE_PF
 
3098
  if (child)
 
3099
    pf_init_context (c);
 
3100
#endif
 
3101
 
 
3102
  /* Check for signals */
 
3103
  if (IS_SIG (c))
 
3104
    goto sig;
 
3105
 
 
3106
  return;
 
3107
 
 
3108
 sig:
 
3109
  if (!c->sig->signal_text)
 
3110
    c->sig->signal_text = "init_instance";
 
3111
  close_context (c, -1, flags);
 
3112
  return;
 
3113
}
 
3114
 
 
3115
/*
 
3116
 * Close a tunnel instance.
 
3117
 */
 
3118
void
 
3119
close_instance (struct context *c)
 
3120
{
 
3121
  /* close event objects */
 
3122
  do_close_event_set (c);
 
3123
 
 
3124
    if (c->mode == CM_P2P
 
3125
        || c->mode == CM_CHILD_TCP
 
3126
        || c->mode == CM_CHILD_UDP
 
3127
        || c->mode == CM_TOP)
 
3128
      {
 
3129
        /* if xinetd/inetd mode, don't allow restart */
 
3130
        do_close_check_if_restart_permitted (c);
 
3131
 
 
3132
#ifdef USE_LZO
 
3133
        if (lzo_defined (&c->c2.lzo_compwork))
 
3134
          lzo_compress_uninit (&c->c2.lzo_compwork);
 
3135
#endif
 
3136
 
 
3137
        /* free buffers */
 
3138
        do_close_free_buf (c);
 
3139
 
 
3140
        /* close TLS */
 
3141
        do_close_tls (c);
 
3142
 
 
3143
        /* free key schedules */
 
3144
        do_close_free_key_schedule (c, (c->mode == CM_P2P || c->mode == CM_TOP));
 
3145
 
 
3146
        /* close TCP/UDP connection */
 
3147
        do_close_link_socket (c);
 
3148
 
 
3149
        /* close TUN/TAP device */
 
3150
        do_close_tun (c, false);
 
3151
 
 
3152
#ifdef MANAGEMENT_DEF_AUTH
 
3153
        if (management)
 
3154
          management_notify_client_close (management, &c->c2.mda_context, NULL);
 
3155
#endif
 
3156
 
 
3157
#ifdef ENABLE_PF
 
3158
        pf_destroy_context (&c->c2.pf);
 
3159
#endif
 
3160
 
 
3161
#ifdef ENABLE_PLUGIN
 
3162
        /* call plugin close functions and unload */
 
3163
        do_close_plugins (c);
 
3164
#endif
 
3165
 
 
3166
        /* close packet-id persistance file */
 
3167
        do_close_packet_id (c);
 
3168
 
 
3169
        /* close --status file */
 
3170
        do_close_status_output (c);
 
3171
 
 
3172
#ifdef ENABLE_FRAGMENT
 
3173
        /* close fragmentation handler */
 
3174
        do_close_fragment (c);
 
3175
#endif
 
3176
 
 
3177
        /* close --ifconfig-pool-persist obj */
 
3178
        do_close_ifconfig_pool_persist (c);
 
3179
 
 
3180
        /* free up environmental variable store */
 
3181
        do_env_set_destroy (c);
 
3182
 
 
3183
        /* close HTTP or SOCKS proxy */
 
3184
        uninit_proxy (c);
 
3185
 
 
3186
        /* garbage collect */
 
3187
        gc_free (&c->c2.gc);
 
3188
      }
 
3189
}
 
3190
 
 
3191
void
 
3192
inherit_context_child (struct context *dest,
 
3193
                       const struct context *src)
 
3194
{
 
3195
  CLEAR (*dest);
 
3196
 
 
3197
  switch (src->options.ce.proto)
 
3198
    {
 
3199
    case PROTO_UDPv4:
 
3200
      dest->mode = CM_CHILD_UDP;
 
3201
      break;
 
3202
    case PROTO_TCPv4_SERVER:
 
3203
      dest->mode = CM_CHILD_TCP;
 
3204
      break;
 
3205
    default:
 
3206
      ASSERT (0);
 
3207
    }
 
3208
 
 
3209
  dest->gc = gc_new ();
 
3210
 
 
3211
  ALLOC_OBJ_CLEAR_GC (dest->sig, struct signal_info, &dest->gc);
 
3212
 
 
3213
  /* c1 init */
 
3214
  packet_id_persist_init (&dest->c1.pid_persist);
 
3215
 
 
3216
#ifdef USE_CRYPTO
 
3217
  dest->c1.ks.key_type = src->c1.ks.key_type;
 
3218
#ifdef USE_SSL
 
3219
  /* inherit SSL context */
 
3220
  dest->c1.ks.ssl_ctx = src->c1.ks.ssl_ctx;
 
3221
  dest->c1.ks.tls_auth_key = src->c1.ks.tls_auth_key;
 
3222
#endif
 
3223
#endif
 
3224
 
 
3225
  /* options */
 
3226
  dest->options = src->options;
 
3227
  options_detach (&dest->options);
 
3228
 
 
3229
  if (dest->mode == CM_CHILD_TCP)
 
3230
    {
 
3231
      /*
 
3232
       * The CM_TOP context does the socket listen(),
 
3233
       * and the CM_CHILD_TCP context does the accept().
 
3234
       */
 
3235
      dest->c2.accept_from = src->c2.link_socket;
 
3236
    }
 
3237
 
 
3238
#ifdef ENABLE_PLUGIN
 
3239
  /* inherit plugins */
 
3240
  do_inherit_plugins (dest, src);
 
3241
#endif
 
3242
 
 
3243
  /* context init */
 
3244
  init_instance (dest, src->c2.es, CC_NO_CLOSE | CC_USR1_TO_HUP);
 
3245
  if (IS_SIG (dest))
 
3246
    return;
 
3247
 
 
3248
  /* inherit tun/tap interface object */
 
3249
  dest->c1.tuntap = src->c1.tuntap;
 
3250
 
 
3251
  /* UDP inherits some extra things which TCP does not */
 
3252
  if (dest->mode == CM_CHILD_UDP)
 
3253
    {
 
3254
      /* inherit buffers */
 
3255
      dest->c2.buffers = src->c2.buffers;
 
3256
 
 
3257
      /* inherit parent link_socket and tuntap */
 
3258
      dest->c2.link_socket = src->c2.link_socket;
 
3259
 
 
3260
      ALLOC_OBJ_GC (dest->c2.link_socket_info, struct link_socket_info, &dest->gc);
 
3261
      *dest->c2.link_socket_info = src->c2.link_socket->info;
 
3262
 
 
3263
      /* locally override some link_socket_info fields */
 
3264
      dest->c2.link_socket_info->lsa = &dest->c1.link_socket_addr;
 
3265
      dest->c2.link_socket_info->connection_established = false;
 
3266
    }
 
3267
}
 
3268
 
 
3269
void
 
3270
inherit_context_top (struct context *dest,
 
3271
                     const struct context *src)
 
3272
{
 
3273
  /* copy parent */
 
3274
  *dest = *src;
 
3275
 
 
3276
  /*
 
3277
   * CM_TOP_CLONE will prevent close_instance from freeing or closing
 
3278
   * resources owned by the parent.
 
3279
   *
 
3280
   * Also note that CM_TOP_CLONE context objects are
 
3281
   * closed by multi_top_free in multi.c.
 
3282
   */
 
3283
  dest->mode = CM_TOP_CLONE; 
 
3284
 
 
3285
  dest->first_time = false;
 
3286
  dest->c0 = NULL;
 
3287
 
 
3288
  options_detach (&dest->options);
 
3289
  gc_detach (&dest->gc);
 
3290
  gc_detach (&dest->c2.gc);
 
3291
 
 
3292
  /* detach plugins */
 
3293
  dest->plugins_owned = false;
 
3294
 
 
3295
#if defined(USE_CRYPTO) && defined(USE_SSL)
 
3296
  dest->c2.tls_multi = NULL;
 
3297
#endif
 
3298
 
 
3299
  /* detach c1 ownership */
 
3300
  dest->c1.tuntap_owned = false;
 
3301
  dest->c1.status_output_owned = false;
 
3302
#if P2MP_SERVER
 
3303
  dest->c1.ifconfig_pool_persist_owned = false;
 
3304
#endif
 
3305
 
 
3306
  /* detach c2 ownership */
 
3307
  dest->c2.event_set_owned = false;
 
3308
  dest->c2.link_socket_owned = false;
 
3309
  dest->c2.buffers_owned = false;
 
3310
  dest->c2.es_owned = false;
 
3311
 
 
3312
  dest->c2.event_set = NULL;
 
3313
  if (src->options.ce.proto == PROTO_UDPv4)
 
3314
    do_event_set_init (dest, false);
 
3315
}
 
3316
 
 
3317
void
 
3318
close_context (struct context *c, int sig, unsigned int flags)
 
3319
{
 
3320
  ASSERT (c);
 
3321
  ASSERT (c->sig);
 
3322
 
 
3323
  if (sig >= 0)
 
3324
    c->sig->signal_received = sig;
 
3325
 
 
3326
  if (c->sig->signal_received == SIGUSR1)
 
3327
    {
 
3328
      if ((flags & CC_USR1_TO_HUP)
 
3329
          || (c->sig->hard && (flags & CC_HARD_USR1_TO_HUP)))
 
3330
        c->sig->signal_received = SIGHUP;
 
3331
    }
 
3332
 
 
3333
  if (!(flags & CC_NO_CLOSE))
 
3334
    close_instance (c);
 
3335
 
 
3336
  if (flags & CC_GC_FREE)
 
3337
    context_gc_free (c);
 
3338
}
 
3339
 
 
3340
#ifdef USE_CRYPTO
 
3341
 
 
3342
static void
 
3343
test_malloc (void)
 
3344
{
 
3345
  int i, j;
 
3346
  msg (M_INFO, "Multithreaded malloc test...");
 
3347
  for (i = 0; i < 25; ++i)
 
3348
    {
 
3349
      struct gc_arena gc = gc_new ();
 
3350
      const int limit = get_random () & 0x03FF;
 
3351
      for (j = 0; j < limit; ++j)
 
3352
        {
 
3353
          gc_malloc (get_random () & 0x03FF, false, &gc);
 
3354
        }
 
3355
      gc_free (&gc);
 
3356
    }
 
3357
}
 
3358
 
 
3359
/*
 
3360
 * Do a loopback test
 
3361
 * on the crypto subsystem.
 
3362
 */
 
3363
static void *
 
3364
test_crypto_thread (void *arg)
 
3365
{
 
3366
  struct context *c = (struct context *) arg;
 
3367
  const struct options *options = &c->options;
 
3368
#if defined(USE_PTHREAD)
 
3369
  struct context *child = NULL;
 
3370
  openvpn_thread_t child_id = 0;
 
3371
#endif
 
3372
 
 
3373
  ASSERT (options->test_crypto);
 
3374
  init_verb_mute (c, IVM_LEVEL_1);
 
3375
  context_init_1 (c);
 
3376
  do_init_crypto_static (c, 0);
 
3377
 
 
3378
#if defined(USE_PTHREAD)
 
3379
  {
 
3380
    if (c->first_time && options->n_threads > 1)
 
3381
      {
 
3382
        if (options->n_threads > 2)
 
3383
          msg (M_FATAL, "ERROR: --test-crypto option only works with --threads set to 1 or 2");
 
3384
        openvpn_thread_init ();
 
3385
        ALLOC_OBJ (child, struct context);
 
3386
        context_clear (child);
 
3387
        child->options = *options;
 
3388
        options_detach (&child->options);
 
3389
        child->first_time = false;
 
3390
        child_id = openvpn_thread_create (test_crypto_thread, (void *) child);
 
3391
      }
 
3392
  }
 
3393
#endif
 
3394
  frame_finalize_options (c, options);
 
3395
 
 
3396
#if defined(USE_PTHREAD)
 
3397
  if (options->n_threads == 2)
 
3398
    test_malloc ();
 
3399
#endif
 
3400
 
 
3401
  test_crypto (&c->c2.crypto_options, &c->c2.frame);
 
3402
 
 
3403
  key_schedule_free (&c->c1.ks, true);
 
3404
  packet_id_free (&c->c2.packet_id);
 
3405
 
 
3406
#if defined(USE_PTHREAD)
 
3407
  if (c->first_time && options->n_threads > 1)
 
3408
    openvpn_thread_join (child_id);
 
3409
  if (child)
 
3410
    free (child);
 
3411
#endif
 
3412
  context_gc_free (c);
 
3413
  return NULL;
 
3414
}
 
3415
 
 
3416
#endif
 
3417
 
 
3418
bool
 
3419
do_test_crypto (const struct options *o)
 
3420
{
 
3421
#ifdef USE_CRYPTO
 
3422
  if (o->test_crypto)
 
3423
    {
 
3424
      struct context c;
 
3425
 
 
3426
      /* print version number */
 
3427
      msg (M_INFO, "%s", title_string);
 
3428
 
 
3429
      context_clear (&c);
 
3430
      c.options = *o;
 
3431
      options_detach (&c.options);
 
3432
      c.first_time = true;
 
3433
      test_crypto_thread ((void *) &c);
 
3434
      return true;
 
3435
    }
 
3436
#endif
 
3437
  return false;
 
3438
}