/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2011-12-21 17:18:18 UTC
  • mfrom: (505.1.24 teddy)
  • Revision ID: teddy@recompile.se-20111221171818-eclh6voe7j5bc6be
Merge some small changes.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2016 Teddy Hogeborn
13
 
 * Copyright © 2008-2016 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif  /* not _LARGEFILE_SOURCE */
 
35
#endif
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
43
                                   stdout, ferror(), remove() */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
50
 
                                   asprintf(), strncpy() */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
58
                                   inet_pton(), connect() */
 
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   strtoimax() */
 
64
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit(),
77
 
                                   unlinkat() */
78
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
76
                                   setgid(), pause(), _exit() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
79
78
#include <iso646.h>             /* not, or, and */
80
79
#include <argp.h>               /* struct argp_option, error_t, struct
81
80
                                   argp_state, struct argp,
89
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
90
89
                                   WEXITSTATUS(), WTERMSIG() */
91
90
#include <grp.h>                /* setgroups() */
92
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
93
 
                                   argz_delete(), argz_append(),
94
 
                                   argz_stringify(), argz_add(),
95
 
                                   argz_count() */
96
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
97
 
                                   EAI_SYSTEM, gai_strerror() */
98
91
 
99
92
#ifdef __linux__
100
93
#include <sys/klog.h>           /* klogctl() */
142
135
static const char sys_class_net[] = "/sys/class/net";
143
136
char *connect_to = NULL;
144
137
const char *hookdir = HOOKDIR;
145
 
int hookdir_fd = -1;
146
 
uid_t uid = 65534;
147
 
gid_t gid = 65534;
148
138
 
149
139
/* Doubly linked list that need to be circularly linked when used */
150
140
typedef struct server{
151
141
  const char *ip;
152
 
  in_port_t port;
 
142
  uint16_t port;
153
143
  AvahiIfIndex if_index;
154
144
  int af;
155
145
  struct timespec last_seen;
159
149
 
160
150
/* Used for passing in values through the Avahi callback functions */
161
151
typedef struct {
 
152
  AvahiSimplePoll *simple_poll;
162
153
  AvahiServer *server;
163
154
  gnutls_certificate_credentials_t cred;
164
155
  unsigned int dh_bits;
166
157
  const char *priority;
167
158
  gpgme_ctx_t ctx;
168
159
  server *current_server;
169
 
  char *interfaces;
170
 
  size_t interfaces_size;
171
160
} mandos_context;
172
161
 
173
 
/* global so signal handler can reach it*/
174
 
AvahiSimplePoll *simple_poll;
 
162
/* global context so signal handler can reach it*/
 
163
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
164
                      .dh_bits = 1024, .priority = "SECURE256"
 
165
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
166
                      .current_server = NULL };
175
167
 
176
168
sig_atomic_t quit_now = 0;
177
169
int signal_received = 0;
178
170
 
179
171
/* Function to use when printing errors */
180
172
void perror_plus(const char *print_text){
181
 
  int e = errno;
182
173
  fprintf(stderr, "Mandos plugin %s: ",
183
174
          program_invocation_short_name);
184
 
  errno = e;
185
175
  perror(print_text);
186
176
}
187
177
 
188
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
189
178
int fprintf_plus(FILE *stream, const char *format, ...){
190
179
  va_list ap;
191
180
  va_start (ap, format);
192
181
  
193
182
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
194
183
                             program_invocation_short_name));
195
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
184
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
196
185
}
197
186
 
198
187
/*
200
189
 * bytes. "buffer_capacity" is how much is currently allocated,
201
190
 * "buffer_length" is how much is already used.
202
191
 */
203
 
__attribute__((nonnull, warn_unused_result))
204
192
size_t incbuffer(char **buffer, size_t buffer_length,
205
193
                 size_t buffer_capacity){
206
194
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
207
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
208
 
    if(new_buf == NULL){
209
 
      int old_errno = errno;
210
 
      free(*buffer);
211
 
      errno = old_errno;
212
 
      *buffer = NULL;
 
195
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
196
    if(buffer == NULL){
213
197
      return 0;
214
198
    }
215
 
    *buffer = new_buf;
216
199
    buffer_capacity += BUFFER_SIZE;
217
200
  }
218
201
  return buffer_capacity;
219
202
}
220
203
 
221
204
/* Add server to set of servers to retry periodically */
222
 
__attribute__((nonnull, warn_unused_result))
223
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
224
 
                int af, server **current_server){
 
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
206
               int af){
225
207
  int ret;
226
208
  server *new_server = malloc(sizeof(server));
227
209
  if(new_server == NULL){
228
210
    perror_plus("malloc");
229
 
    return false;
 
211
    return -1;
230
212
  }
231
213
  *new_server = (server){ .ip = strdup(ip),
232
214
                          .port = port,
234
216
                          .af = af };
235
217
  if(new_server->ip == NULL){
236
218
    perror_plus("strdup");
237
 
    free(new_server);
238
 
    return false;
239
 
  }
240
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
 
  if(ret == -1){
242
 
    perror_plus("clock_gettime");
243
 
#ifdef __GNUC__
244
 
#pragma GCC diagnostic push
245
 
#pragma GCC diagnostic ignored "-Wcast-qual"
246
 
#endif
247
 
    free((char *)(new_server->ip));
248
 
#ifdef __GNUC__
249
 
#pragma GCC diagnostic pop
250
 
#endif
251
 
    free(new_server);
252
 
    return false;
 
219
    return -1;
253
220
  }
254
221
  /* Special case of first server */
255
 
  if(*current_server == NULL){
 
222
  if (mc.current_server == NULL){
256
223
    new_server->next = new_server;
257
224
    new_server->prev = new_server;
258
 
    *current_server = new_server;
 
225
    mc.current_server = new_server;
 
226
  /* Place the new server last in the list */
259
227
  } else {
260
 
    /* Place the new server last in the list */
261
 
    new_server->next = *current_server;
262
 
    new_server->prev = (*current_server)->prev;
 
228
    new_server->next = mc.current_server;
 
229
    new_server->prev = mc.current_server->prev;
263
230
    new_server->prev->next = new_server;
264
 
    (*current_server)->prev = new_server;
265
 
  }
266
 
  return true;
 
231
    mc.current_server->prev = new_server;
 
232
  }
 
233
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
234
  if(ret == -1){
 
235
    perror_plus("clock_gettime");
 
236
    return -1;
 
237
  }
 
238
  return 0;
267
239
}
268
240
 
269
241
/* 
270
242
 * Initialize GPGME.
271
243
 */
272
 
__attribute__((nonnull, warn_unused_result))
273
 
static bool init_gpgme(const char * const seckey,
274
 
                       const char * const pubkey,
275
 
                       const char * const tempdir,
276
 
                       mandos_context *mc){
 
244
static bool init_gpgme(const char *seckey, const char *pubkey,
 
245
                       const char *tempdir){
277
246
  gpgme_error_t rc;
278
247
  gpgme_engine_info_t engine_info;
279
248
  
 
249
  
280
250
  /*
281
251
   * Helper function to insert pub and seckey to the engine keyring.
282
252
   */
283
 
  bool import_key(const char * const filename){
 
253
  bool import_key(const char *filename){
284
254
    int ret;
285
255
    int fd;
286
256
    gpgme_data_t pgp_data;
298
268
      return false;
299
269
    }
300
270
    
301
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
271
    rc = gpgme_op_import(mc.ctx, pgp_data);
302
272
    if(rc != GPG_ERR_NO_ERROR){
303
273
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
304
274
                   gpgme_strsource(rc), gpgme_strerror(rc));
305
275
      return false;
306
276
    }
307
277
    
308
 
    ret = close(fd);
 
278
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
309
279
    if(ret == -1){
310
280
      perror_plus("close");
311
281
    }
348
318
  }
349
319
  
350
320
  /* Create new GPGME "context" */
351
 
  rc = gpgme_new(&(mc->ctx));
 
321
  rc = gpgme_new(&(mc.ctx));
352
322
  if(rc != GPG_ERR_NO_ERROR){
353
323
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
354
324
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
367
337
 * Decrypt OpenPGP data.
368
338
 * Returns -1 on error
369
339
 */
370
 
__attribute__((nonnull, warn_unused_result))
371
340
static ssize_t pgp_packet_decrypt(const char *cryptotext,
372
341
                                  size_t crypto_size,
373
 
                                  char **plaintext,
374
 
                                  mandos_context *mc){
 
342
                                  char **plaintext){
375
343
  gpgme_data_t dh_crypto, dh_plain;
376
344
  gpgme_error_t rc;
377
345
  ssize_t ret;
403
371
  
404
372
  /* Decrypt data from the cryptotext data buffer to the plaintext
405
373
     data buffer */
406
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
374
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
407
375
  if(rc != GPG_ERR_NO_ERROR){
408
376
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
409
377
                 gpgme_strsource(rc), gpgme_strerror(rc));
410
378
    plaintext_length = -1;
411
379
    if(debug){
412
380
      gpgme_decrypt_result_t result;
413
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
381
      result = gpgme_op_decrypt_result(mc.ctx);
414
382
      if(result == NULL){
415
383
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
416
384
      } else {
493
461
  return plaintext_length;
494
462
}
495
463
 
496
 
__attribute__((warn_unused_result, const))
497
 
static const char *safe_string(const char *str){
498
 
  if(str == NULL)
499
 
    return "(unknown)";
500
 
  return str;
501
 
}
502
 
 
503
 
__attribute__((warn_unused_result))
504
 
static const char *safer_gnutls_strerror(int value){
505
 
  const char *ret = gnutls_strerror(value);
506
 
  return safe_string(ret);
 
464
static const char * safer_gnutls_strerror(int value){
 
465
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
466
                                               -Wunreachable-code */
 
467
  if(ret == NULL)
 
468
    ret = "(unknown)";
 
469
  return ret;
507
470
}
508
471
 
509
472
/* GnuTLS log function callback */
510
 
__attribute__((nonnull))
511
473
static void debuggnutls(__attribute__((unused)) int level,
512
474
                        const char* string){
513
475
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
476
}
515
477
 
516
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
517
478
static int init_gnutls_global(const char *pubkeyfilename,
518
 
                              const char *seckeyfilename,
519
 
                              const char *dhparamsfilename,
520
 
                              mandos_context *mc){
 
479
                              const char *seckeyfilename){
521
480
  int ret;
522
 
  unsigned int uret;
523
481
  
524
482
  if(debug){
525
483
    fprintf_plus(stderr, "Initializing GnuTLS\n");
526
484
  }
527
485
  
 
486
  ret = gnutls_global_init();
 
487
  if(ret != GNUTLS_E_SUCCESS){
 
488
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
489
                 safer_gnutls_strerror(ret));
 
490
    return -1;
 
491
  }
 
492
  
528
493
  if(debug){
529
494
    /* "Use a log level over 10 to enable all debugging options."
530
495
     * - GnuTLS manual
534
499
  }
535
500
  
536
501
  /* OpenPGP credentials */
537
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
502
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
538
503
  if(ret != GNUTLS_E_SUCCESS){
539
504
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
505
                 safer_gnutls_strerror(ret));
 
506
    gnutls_global_deinit();
541
507
    return -1;
542
508
  }
543
509
  
549
515
  }
550
516
  
551
517
  ret = gnutls_certificate_set_openpgp_key_file
552
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
518
    (mc.cred, pubkeyfilename, seckeyfilename,
553
519
     GNUTLS_OPENPGP_FMT_BASE64);
554
520
  if(ret != GNUTLS_E_SUCCESS){
555
521
    fprintf_plus(stderr,
561
527
  }
562
528
  
563
529
  /* GnuTLS server initialization */
564
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
530
  ret = gnutls_dh_params_init(&mc.dh_params);
565
531
  if(ret != GNUTLS_E_SUCCESS){
566
532
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
567
533
                 " initialization: %s\n",
568
534
                 safer_gnutls_strerror(ret));
569
535
    goto globalfail;
570
536
  }
571
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
572
 
  if(dhparamsfilename != NULL){
573
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
574
 
    do {
575
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
576
 
      if(dhpfile == -1){
577
 
        perror_plus("open");
578
 
        dhparamsfilename = NULL;
579
 
        break;
580
 
      }
581
 
      size_t params_capacity = 0;
582
 
      while(true){
583
 
        params_capacity = incbuffer((char **)&params.data,
584
 
                                    (size_t)params.size,
585
 
                                    (size_t)params_capacity);
586
 
        if(params_capacity == 0){
587
 
          perror_plus("incbuffer");
588
 
          free(params.data);
589
 
          params.data = NULL;
590
 
          dhparamsfilename = NULL;
591
 
          break;
592
 
        }
593
 
        ssize_t bytes_read = read(dhpfile,
594
 
                                  params.data + params.size,
595
 
                                  BUFFER_SIZE);
596
 
        /* EOF */
597
 
        if(bytes_read == 0){
598
 
          break;
599
 
        }
600
 
        /* check bytes_read for failure */
601
 
        if(bytes_read < 0){
602
 
          perror_plus("read");
603
 
          free(params.data);
604
 
          params.data = NULL;
605
 
          dhparamsfilename = NULL;
606
 
          break;
607
 
        }
608
 
        params.size += (unsigned int)bytes_read;
609
 
      }
610
 
      if(params.data == NULL){
611
 
        dhparamsfilename = NULL;
612
 
      }
613
 
      if(dhparamsfilename == NULL){
614
 
        break;
615
 
      }
616
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
617
 
                                          GNUTLS_X509_FMT_PEM);
618
 
      if(ret != GNUTLS_E_SUCCESS){
619
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
620
 
                     " \"%s\": %s\n", dhparamsfilename,
621
 
                     safer_gnutls_strerror(ret));
622
 
        dhparamsfilename = NULL;
623
 
      }
624
 
    } while(false);
625
 
  }
626
 
  if(dhparamsfilename == NULL){
627
 
    if(mc->dh_bits == 0){
628
 
      /* Find out the optimal number of DH bits */
629
 
      /* Try to read the private key file */
630
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
631
 
      do {
632
 
        int secfile = open(seckeyfilename, O_RDONLY);
633
 
        if(secfile == -1){
634
 
          perror_plus("open");
635
 
          break;
636
 
        }
637
 
        size_t buffer_capacity = 0;
638
 
        while(true){
639
 
          buffer_capacity = incbuffer((char **)&buffer.data,
640
 
                                      (size_t)buffer.size,
641
 
                                      (size_t)buffer_capacity);
642
 
          if(buffer_capacity == 0){
643
 
            perror_plus("incbuffer");
644
 
            free(buffer.data);
645
 
            buffer.data = NULL;
646
 
            break;
647
 
          }
648
 
          ssize_t bytes_read = read(secfile,
649
 
                                    buffer.data + buffer.size,
650
 
                                    BUFFER_SIZE);
651
 
          /* EOF */
652
 
          if(bytes_read == 0){
653
 
            break;
654
 
          }
655
 
          /* check bytes_read for failure */
656
 
          if(bytes_read < 0){
657
 
            perror_plus("read");
658
 
            free(buffer.data);
659
 
            buffer.data = NULL;
660
 
            break;
661
 
          }
662
 
          buffer.size += (unsigned int)bytes_read;
663
 
        }
664
 
        close(secfile);
665
 
      } while(false);
666
 
      /* If successful, use buffer to parse private key */
667
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
668
 
      if(buffer.data != NULL){
669
 
        {
670
 
          gnutls_openpgp_privkey_t privkey = NULL;
671
 
          ret = gnutls_openpgp_privkey_init(&privkey);
672
 
          if(ret != GNUTLS_E_SUCCESS){
673
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
674
 
                         " structure: %s",
675
 
                         safer_gnutls_strerror(ret));
676
 
            free(buffer.data);
677
 
            buffer.data = NULL;
678
 
          } else {
679
 
            ret = gnutls_openpgp_privkey_import
680
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
681
 
            if(ret != GNUTLS_E_SUCCESS){
682
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
683
 
                           safer_gnutls_strerror(ret));
684
 
              privkey = NULL;
685
 
            }
686
 
            free(buffer.data);
687
 
            buffer.data = NULL;
688
 
            if(privkey != NULL){
689
 
              /* Use private key to suggest an appropriate
690
 
                 sec_param */
691
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
692
 
              gnutls_openpgp_privkey_deinit(privkey);
693
 
              if(debug){
694
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
695
 
                             " a GnuTLS security parameter \"%s\".\n",
696
 
                             safe_string(gnutls_sec_param_get_name
697
 
                                         (sec_param)));
698
 
              }
699
 
            }
700
 
          }
701
 
        }
702
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
703
 
          /* Err on the side of caution */
704
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
705
 
          if(debug){
706
 
            fprintf_plus(stderr, "Falling back to security parameter"
707
 
                         " \"%s\"\n",
708
 
                         safe_string(gnutls_sec_param_get_name
709
 
                                     (sec_param)));
710
 
          }
711
 
        }
712
 
      }
713
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
714
 
      if(uret != 0){
715
 
        mc->dh_bits = uret;
716
 
        if(debug){
717
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
718
 
                       " implies %u DH bits; using that.\n",
719
 
                       safe_string(gnutls_sec_param_get_name
720
 
                                   (sec_param)),
721
 
                       mc->dh_bits);
722
 
        }
723
 
      } else {
724
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
725
 
                     " bits for security parameter \"%s\"): %s\n",
726
 
                     safe_string(gnutls_sec_param_get_name
727
 
                                 (sec_param)),
728
 
                     safer_gnutls_strerror(ret));
729
 
        goto globalfail;
730
 
      }
731
 
    } else if(debug){
732
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
733
 
                   mc->dh_bits);
734
 
    }
735
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
736
 
    if(ret != GNUTLS_E_SUCCESS){
737
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
738
 
                   " bits): %s\n", mc->dh_bits,
739
 
                   safer_gnutls_strerror(ret));
740
 
      goto globalfail;
741
 
    }
742
 
  }
743
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
537
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
538
  if(ret != GNUTLS_E_SUCCESS){
 
539
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
540
                 safer_gnutls_strerror(ret));
 
541
    goto globalfail;
 
542
  }
 
543
  
 
544
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
744
545
  
745
546
  return 0;
746
547
  
747
548
 globalfail:
748
549
  
749
 
  gnutls_certificate_free_credentials(mc->cred);
750
 
  gnutls_dh_params_deinit(mc->dh_params);
 
550
  gnutls_certificate_free_credentials(mc.cred);
 
551
  gnutls_global_deinit();
 
552
  gnutls_dh_params_deinit(mc.dh_params);
751
553
  return -1;
752
554
}
753
555
 
754
 
__attribute__((nonnull, warn_unused_result))
755
 
static int init_gnutls_session(gnutls_session_t *session,
756
 
                               mandos_context *mc){
 
556
static int init_gnutls_session(gnutls_session_t *session){
757
557
  int ret;
758
558
  /* GnuTLS session creation */
759
559
  do {
771
571
  {
772
572
    const char *err;
773
573
    do {
774
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
574
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
775
575
      if(quit_now){
776
576
        gnutls_deinit(*session);
777
577
        return -1;
788
588
  
789
589
  do {
790
590
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
791
 
                                 mc->cred);
 
591
                                 mc.cred);
792
592
    if(quit_now){
793
593
      gnutls_deinit(*session);
794
594
      return -1;
804
604
  /* ignore client certificate if any. */
805
605
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
806
606
  
 
607
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
608
  
807
609
  return 0;
808
610
}
809
611
 
811
613
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
812
614
                      __attribute__((unused)) const char *txt){}
813
615
 
814
 
/* Set effective uid to 0, return errno */
815
 
__attribute__((warn_unused_result))
816
 
error_t raise_privileges(void){
817
 
  error_t old_errno = errno;
818
 
  error_t ret_errno = 0;
819
 
  if(seteuid(0) == -1){
820
 
    ret_errno = errno;
821
 
  }
822
 
  errno = old_errno;
823
 
  return ret_errno;
824
 
}
825
 
 
826
 
/* Set effective and real user ID to 0.  Return errno. */
827
 
__attribute__((warn_unused_result))
828
 
error_t raise_privileges_permanently(void){
829
 
  error_t old_errno = errno;
830
 
  error_t ret_errno = raise_privileges();
831
 
  if(ret_errno != 0){
832
 
    errno = old_errno;
833
 
    return ret_errno;
834
 
  }
835
 
  if(setuid(0) == -1){
836
 
    ret_errno = errno;
837
 
  }
838
 
  errno = old_errno;
839
 
  return ret_errno;
840
 
}
841
 
 
842
 
/* Set effective user ID to unprivileged saved user ID */
843
 
__attribute__((warn_unused_result))
844
 
error_t lower_privileges(void){
845
 
  error_t old_errno = errno;
846
 
  error_t ret_errno = 0;
847
 
  if(seteuid(uid) == -1){
848
 
    ret_errno = errno;
849
 
  }
850
 
  errno = old_errno;
851
 
  return ret_errno;
852
 
}
853
 
 
854
 
/* Lower privileges permanently */
855
 
__attribute__((warn_unused_result))
856
 
error_t lower_privileges_permanently(void){
857
 
  error_t old_errno = errno;
858
 
  error_t ret_errno = 0;
859
 
  if(setuid(uid) == -1){
860
 
    ret_errno = errno;
861
 
  }
862
 
  errno = old_errno;
863
 
  return ret_errno;
864
 
}
865
 
 
866
 
/* Helper function to add_local_route() and delete_local_route() */
867
 
__attribute__((nonnull, warn_unused_result))
868
 
static bool add_delete_local_route(const bool add,
869
 
                                   const char *address,
870
 
                                   AvahiIfIndex if_index){
871
 
  int ret;
872
 
  char helper[] = "mandos-client-iprouteadddel";
873
 
  char add_arg[] = "add";
874
 
  char delete_arg[] = "delete";
875
 
  char debug_flag[] = "--debug";
876
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
877
 
  if(pluginhelperdir == NULL){
878
 
    if(debug){
879
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
880
 
                   " variable not set; cannot run helper\n");
881
 
    }
882
 
    return false;
883
 
  }
884
 
  
885
 
  char interface[IF_NAMESIZE];
886
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
887
 
    perror_plus("if_indextoname");
888
 
    return false;
889
 
  }
890
 
  
891
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
892
 
  if(devnull == -1){
893
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
894
 
    return false;
895
 
  }
896
 
  pid_t pid = fork();
897
 
  if(pid == 0){
898
 
    /* Child */
899
 
    /* Raise privileges */
900
 
    errno = raise_privileges_permanently();
901
 
    if(errno != 0){
902
 
      perror_plus("Failed to raise privileges");
903
 
      /* _exit(EX_NOPERM); */
904
 
    } else {
905
 
      /* Set group */
906
 
      errno = 0;
907
 
      ret = setgid(0);
908
 
      if(ret == -1){
909
 
        perror_plus("setgid");
910
 
        _exit(EX_NOPERM);
911
 
      }
912
 
      /* Reset supplementary groups */
913
 
      errno = 0;
914
 
      ret = setgroups(0, NULL);
915
 
      if(ret == -1){
916
 
        perror_plus("setgroups");
917
 
        _exit(EX_NOPERM);
918
 
      }
919
 
    }
920
 
    ret = dup2(devnull, STDIN_FILENO);
921
 
    if(ret == -1){
922
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
923
 
      _exit(EX_OSERR);
924
 
    }
925
 
    ret = close(devnull);
926
 
    if(ret == -1){
927
 
      perror_plus("close");
928
 
      _exit(EX_OSERR);
929
 
    }
930
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
931
 
    if(ret == -1){
932
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
933
 
      _exit(EX_OSERR);
934
 
    }
935
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
936
 
                                                    O_RDONLY
937
 
                                                    | O_DIRECTORY
938
 
                                                    | O_PATH
939
 
                                                    | O_CLOEXEC));
940
 
    if(helperdir_fd == -1){
941
 
      perror_plus("open");
942
 
      _exit(EX_UNAVAILABLE);
943
 
    }
944
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
945
 
                                                   helper, O_RDONLY));
946
 
    if(helper_fd == -1){
947
 
      perror_plus("openat");
948
 
      close(helperdir_fd);
949
 
      _exit(EX_UNAVAILABLE);
950
 
    }
951
 
    close(helperdir_fd);
952
 
#ifdef __GNUC__
953
 
#pragma GCC diagnostic push
954
 
#pragma GCC diagnostic ignored "-Wcast-qual"
955
 
#endif
956
 
    if(fexecve(helper_fd, (char *const [])
957
 
               { helper, add ? add_arg : delete_arg, (char *)address,
958
 
                   interface, debug ? debug_flag : NULL, NULL },
959
 
               environ) == -1){
960
 
#ifdef __GNUC__
961
 
#pragma GCC diagnostic pop
962
 
#endif
963
 
      perror_plus("fexecve");
964
 
      _exit(EXIT_FAILURE);
965
 
    }
966
 
  }
967
 
  if(pid == -1){
968
 
    perror_plus("fork");
969
 
    return false;
970
 
  }
971
 
  int status;
972
 
  pid_t pret = -1;
973
 
  errno = 0;
974
 
  do {
975
 
    pret = waitpid(pid, &status, 0);
976
 
    if(pret == -1 and errno == EINTR and quit_now){
977
 
      int errno_raising = 0;
978
 
      if((errno = raise_privileges()) != 0){
979
 
        errno_raising = errno;
980
 
        perror_plus("Failed to raise privileges in order to"
981
 
                    " kill helper program");
982
 
      }
983
 
      if(kill(pid, SIGTERM) == -1){
984
 
        perror_plus("kill");
985
 
      }
986
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
987
 
        perror_plus("Failed to lower privileges after killing"
988
 
                    " helper program");
989
 
      }
990
 
      return false;
991
 
    }
992
 
  } while(pret == -1 and errno == EINTR);
993
 
  if(pret == -1){
994
 
    perror_plus("waitpid");
995
 
    return false;
996
 
  }
997
 
  if(WIFEXITED(status)){
998
 
    if(WEXITSTATUS(status) != 0){
999
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1000
 
                   " with status %d\n", WEXITSTATUS(status));
1001
 
      return false;
1002
 
    }
1003
 
    return true;
1004
 
  }
1005
 
  if(WIFSIGNALED(status)){
1006
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1007
 
                 " signal %d\n", WTERMSIG(status));
1008
 
    return false;
1009
 
  }
1010
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1011
 
  return false;
1012
 
}
1013
 
 
1014
 
__attribute__((nonnull, warn_unused_result))
1015
 
static bool add_local_route(const char *address,
1016
 
                            AvahiIfIndex if_index){
1017
 
  if(debug){
1018
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1019
 
  }
1020
 
  return add_delete_local_route(true, address, if_index);
1021
 
}
1022
 
 
1023
 
__attribute__((nonnull, warn_unused_result))
1024
 
static bool delete_local_route(const char *address,
1025
 
                               AvahiIfIndex if_index){
1026
 
  if(debug){
1027
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1028
 
  }
1029
 
  return add_delete_local_route(false, address, if_index);
1030
 
}
1031
 
 
1032
616
/* Called when a Mandos server is found */
1033
 
__attribute__((nonnull, warn_unused_result))
1034
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
617
static int start_mandos_communication(const char *ip, uint16_t port,
1035
618
                                      AvahiIfIndex if_index,
1036
 
                                      int af, mandos_context *mc){
 
619
                                      int af){
1037
620
  int ret, tcp_sd = -1;
1038
621
  ssize_t sret;
1039
 
  struct sockaddr_storage to;
 
622
  union {
 
623
    struct sockaddr_in in;
 
624
    struct sockaddr_in6 in6;
 
625
  } to;
1040
626
  char *buffer = NULL;
1041
627
  char *decrypted_buffer = NULL;
1042
628
  size_t buffer_length = 0;
1045
631
  int retval = -1;
1046
632
  gnutls_session_t session;
1047
633
  int pf;                       /* Protocol family */
1048
 
  bool route_added = false;
1049
634
  
1050
635
  errno = 0;
1051
636
  
1067
652
    return -1;
1068
653
  }
1069
654
  
1070
 
  /* If the interface is specified and we have a list of interfaces */
1071
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
1072
 
    /* Check if the interface is one of the interfaces we are using */
1073
 
    bool match = false;
1074
 
    {
1075
 
      char *interface = NULL;
1076
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1077
 
                                 interface))){
1078
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
1079
 
          match = true;
1080
 
          break;
1081
 
        }
1082
 
      }
1083
 
    }
1084
 
    if(not match){
1085
 
      /* This interface does not match any in the list, so we don't
1086
 
         connect to the server */
1087
 
      if(debug){
1088
 
        char interface[IF_NAMESIZE];
1089
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
1090
 
          perror_plus("if_indextoname");
1091
 
        } else {
1092
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
1093
 
                       " \"%s\"\n",
1094
 
                       if_indextoname((unsigned int)if_index,
1095
 
                                      interface));
1096
 
        }
1097
 
      }
1098
 
      return -1;
1099
 
    }
1100
 
  }
1101
 
  
1102
 
  ret = init_gnutls_session(&session, mc);
 
655
  ret = init_gnutls_session(&session);
1103
656
  if(ret != 0){
1104
657
    return -1;
1105
658
  }
1106
659
  
1107
660
  if(debug){
1108
661
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
1109
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
662
                 PRIu16 "\n", ip, port);
1110
663
  }
1111
664
  
1112
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
665
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1113
666
  if(tcp_sd < 0){
1114
667
    int e = errno;
1115
668
    perror_plus("socket");
1122
675
    goto mandos_end;
1123
676
  }
1124
677
  
 
678
  memset(&to, 0, sizeof(to));
1125
679
  if(af == AF_INET6){
1126
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1127
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1128
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
680
    to.in6.sin6_family = (sa_family_t)af;
 
681
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
1129
682
  } else {                      /* IPv4 */
1130
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1131
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1132
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
683
    to.in.sin_family = (sa_family_t)af;
 
684
    ret = inet_pton(af, ip, &to.in.sin_addr);
1133
685
  }
1134
686
  if(ret < 0 ){
1135
687
    int e = errno;
1144
696
    goto mandos_end;
1145
697
  }
1146
698
  if(af == AF_INET6){
1147
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1148
 
    if(IN6_IS_ADDR_LINKLOCAL
1149
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
699
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
700
                                       -Wconversion and
 
701
                                       -Wunreachable-code */
 
702
    
 
703
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
704
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
705
                                -Wunreachable-code*/
1150
706
      if(if_index == AVAHI_IF_UNSPEC){
1151
707
        fprintf_plus(stderr, "An IPv6 link-local address is"
1152
708
                     " incomplete without a network interface\n");
1154
710
        goto mandos_end;
1155
711
      }
1156
712
      /* Set the network interface number as scope */
1157
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
713
      to.in6.sin6_scope_id = (uint32_t)if_index;
1158
714
    }
1159
715
  } else {
1160
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
716
    to.in.sin_port = htons(port); /* Spurious warnings from
 
717
                                     -Wconversion and
 
718
                                     -Wunreachable-code */
1161
719
  }
1162
720
  
1163
721
  if(quit_now){
1171
729
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
1172
730
        perror_plus("if_indextoname");
1173
731
      } else {
1174
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
1175
 
                     "\n", ip, interface, (uintmax_t)port);
 
732
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
733
                     "\n", ip, interface, port);
1176
734
      }
1177
735
    } else {
1178
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
1179
 
                   ip, (uintmax_t)port);
 
736
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
737
                   ip, port);
1180
738
    }
1181
739
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1182
740
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1183
 
    if(af == AF_INET6){
1184
 
      ret = getnameinfo((struct sockaddr *)&to,
1185
 
                        sizeof(struct sockaddr_in6),
1186
 
                        addrstr, sizeof(addrstr), NULL, 0,
1187
 
                        NI_NUMERICHOST);
1188
 
    } else {
1189
 
      ret = getnameinfo((struct sockaddr *)&to,
1190
 
                        sizeof(struct sockaddr_in),
1191
 
                        addrstr, sizeof(addrstr), NULL, 0,
1192
 
                        NI_NUMERICHOST);
1193
 
    }
1194
 
    if(ret == EAI_SYSTEM){
1195
 
      perror_plus("getnameinfo");
1196
 
    } else if(ret != 0) {
1197
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
1198
 
    } else if(strcmp(addrstr, ip) != 0){
1199
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
1200
 
    }
1201
 
  }
1202
 
  
1203
 
  if(quit_now){
1204
 
    errno = EINTR;
1205
 
    goto mandos_end;
1206
 
  }
1207
 
  
1208
 
  while(true){
1209
 
    if(af == AF_INET6){
1210
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1211
 
                    sizeof(struct sockaddr_in6));
1212
 
    } else {
1213
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1214
 
                    sizeof(struct sockaddr_in));
1215
 
    }
1216
 
    if(ret < 0){
1217
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1218
 
         and if_index != AVAHI_IF_UNSPEC
1219
 
         and connect_to == NULL
1220
 
         and not route_added and
1221
 
         ((af == AF_INET6 and not
1222
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1223
 
                                    &to)->sin6_addr)))
1224
 
          or (af == AF_INET and
1225
 
              /* Not a a IPv4LL address */
1226
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1227
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1228
 
        /* Work around Avahi bug - Avahi does not announce link-local
1229
 
           addresses if it has a global address, so local hosts with
1230
 
           *only* a link-local address (e.g. Mandos clients) cannot
1231
 
           connect to a Mandos server announced by Avahi on a server
1232
 
           host with a global address.  Work around this by retrying
1233
 
           with an explicit route added with the server's address.
1234
 
           
1235
 
           Avahi bug reference:
1236
 
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1237
 
           https://bugs.debian.org/587961
1238
 
        */
1239
 
        if(debug){
1240
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1241
 
                       " direct route\n");
1242
 
        }
1243
 
        int e = errno;
1244
 
        route_added = add_local_route(ip, if_index);
1245
 
        if(route_added){
1246
 
          continue;
1247
 
        }
1248
 
        errno = e;
1249
 
      }
1250
 
      if(errno != ECONNREFUSED or debug){
1251
 
        int e = errno;
1252
 
        perror_plus("connect");
1253
 
        errno = e;
1254
 
      }
1255
 
      goto mandos_end;
1256
 
    }
1257
 
    
1258
 
    if(quit_now){
1259
 
      errno = EINTR;
1260
 
      goto mandos_end;
1261
 
    }
1262
 
    break;
 
741
    const char *pcret;
 
742
    if(af == AF_INET6){
 
743
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
744
                        sizeof(addrstr));
 
745
    } else {
 
746
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
747
                        sizeof(addrstr));
 
748
    }
 
749
    if(pcret == NULL){
 
750
      perror_plus("inet_ntop");
 
751
    } else {
 
752
      if(strcmp(addrstr, ip) != 0){
 
753
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
754
      }
 
755
    }
 
756
  }
 
757
  
 
758
  if(quit_now){
 
759
    errno = EINTR;
 
760
    goto mandos_end;
 
761
  }
 
762
  
 
763
  if(af == AF_INET6){
 
764
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
765
  } else {
 
766
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
767
  }
 
768
  if(ret < 0){
 
769
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
770
      int e = errno;
 
771
      perror_plus("connect");
 
772
      errno = e;
 
773
    }
 
774
    goto mandos_end;
 
775
  }
 
776
  
 
777
  if(quit_now){
 
778
    errno = EINTR;
 
779
    goto mandos_end;
1263
780
  }
1264
781
  
1265
782
  const char *out = mandos_protocol_version;
1301
818
    goto mandos_end;
1302
819
  }
1303
820
  
1304
 
  /* This casting via intptr_t is to eliminate warning about casting
1305
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
1306
 
     function "set-session-transport-fd!" does it. */
1307
 
  gnutls_transport_set_ptr(session,
1308
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
821
  /* Spurious warning from -Wint-to-pointer-cast */
 
822
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
1309
823
  
1310
824
  if(quit_now){
1311
825
    errno = EINTR;
1416
930
  if(buffer_length > 0){
1417
931
    ssize_t decrypted_buffer_size;
1418
932
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
1419
 
                                               &decrypted_buffer, mc);
 
933
                                               &decrypted_buffer);
1420
934
    if(decrypted_buffer_size >= 0){
1421
935
      
1422
936
      written = 0;
1448
962
  
1449
963
 mandos_end:
1450
964
  {
1451
 
    if(route_added){
1452
 
      if(not delete_local_route(ip, if_index)){
1453
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1454
 
                     " interface %d", ip, if_index);
1455
 
      }
1456
 
    }
1457
965
    int e = errno;
1458
966
    free(decrypted_buffer);
1459
967
    free(buffer);
1460
968
    if(tcp_sd >= 0){
1461
 
      ret = close(tcp_sd);
 
969
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1462
970
    }
1463
971
    if(ret == -1){
1464
972
      if(e == 0){
1476
984
  return retval;
1477
985
}
1478
986
 
1479
 
__attribute__((nonnull))
1480
987
static void resolve_callback(AvahiSServiceResolver *r,
1481
988
                             AvahiIfIndex interface,
1482
989
                             AvahiProtocol proto,
1490
997
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1491
998
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1492
999
                             flags,
1493
 
                             void *mc){
1494
 
  if(r == NULL){
1495
 
    return;
1496
 
  }
 
1000
                             AVAHI_GCC_UNUSED void* userdata){
 
1001
  assert(r);
1497
1002
  
1498
1003
  /* Called whenever a service has been resolved successfully or
1499
1004
     timed out */
1500
1005
  
1501
1006
  if(quit_now){
1502
 
    avahi_s_service_resolver_free(r);
1503
1007
    return;
1504
1008
  }
1505
1009
  
1509
1013
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1510
1014
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1511
1015
                 domain,
1512
 
                 avahi_strerror(avahi_server_errno
1513
 
                                (((mandos_context*)mc)->server)));
 
1016
                 avahi_strerror(avahi_server_errno(mc.server)));
1514
1017
    break;
1515
1018
    
1516
1019
  case AVAHI_RESOLVER_FOUND:
1522
1025
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1523
1026
                     host_name, ip, (intmax_t)interface, port);
1524
1027
      }
1525
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1526
 
                                           interface,
1527
 
                                           avahi_proto_to_af(proto),
1528
 
                                           mc);
 
1028
      int ret = start_mandos_communication(ip, port, interface,
 
1029
                                           avahi_proto_to_af(proto));
1529
1030
      if(ret == 0){
1530
 
        avahi_simple_poll_quit(simple_poll);
 
1031
        avahi_simple_poll_quit(mc.simple_poll);
1531
1032
      } else {
1532
 
        if(not add_server(ip, (in_port_t)port, interface,
1533
 
                          avahi_proto_to_af(proto),
1534
 
                          &((mandos_context*)mc)->current_server)){
1535
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1536
 
                       " list\n", name);
1537
 
        }
 
1033
        ret = add_server(ip, port, interface,
 
1034
                         avahi_proto_to_af(proto));
1538
1035
      }
1539
1036
    }
1540
1037
  }
1550
1047
                            const char *domain,
1551
1048
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1552
1049
                            flags,
1553
 
                            void *mc){
1554
 
  if(b == NULL){
1555
 
    return;
1556
 
  }
 
1050
                            AVAHI_GCC_UNUSED void* userdata){
 
1051
  assert(b);
1557
1052
  
1558
1053
  /* Called whenever a new services becomes available on the LAN or
1559
1054
     is removed from the LAN */
1567
1062
  case AVAHI_BROWSER_FAILURE:
1568
1063
    
1569
1064
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1570
 
                 avahi_strerror(avahi_server_errno
1571
 
                                (((mandos_context*)mc)->server)));
1572
 
    avahi_simple_poll_quit(simple_poll);
 
1065
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1066
    avahi_simple_poll_quit(mc.simple_poll);
1573
1067
    return;
1574
1068
    
1575
1069
  case AVAHI_BROWSER_NEW:
1578
1072
       the callback function is called the Avahi server will free the
1579
1073
       resolver for us. */
1580
1074
    
1581
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1582
 
                                    interface, protocol, name, type,
1583
 
                                    domain, protocol, 0,
1584
 
                                    resolve_callback, mc) == NULL)
 
1075
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1076
                                    name, type, domain, protocol, 0,
 
1077
                                    resolve_callback, NULL) == NULL)
1585
1078
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1586
1079
                   " %s\n", name,
1587
 
                   avahi_strerror(avahi_server_errno
1588
 
                                  (((mandos_context*)mc)->server)));
 
1080
                   avahi_strerror(avahi_server_errno(mc.server)));
1589
1081
    break;
1590
1082
    
1591
1083
  case AVAHI_BROWSER_REMOVE:
1610
1102
  signal_received = sig;
1611
1103
  int old_errno = errno;
1612
1104
  /* set main loop to exit */
1613
 
  if(simple_poll != NULL){
1614
 
    avahi_simple_poll_quit(simple_poll);
 
1105
  if(mc.simple_poll != NULL){
 
1106
    avahi_simple_poll_quit(mc.simple_poll);
1615
1107
  }
1616
1108
  errno = old_errno;
1617
1109
}
1618
1110
 
1619
 
__attribute__((nonnull, warn_unused_result))
1620
1111
bool get_flags(const char *ifname, struct ifreq *ifr){
1621
1112
  int ret;
1622
 
  error_t ret_errno;
1623
1113
  
1624
1114
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1625
1115
  if(s < 0){
1626
 
    ret_errno = errno;
1627
1116
    perror_plus("socket");
1628
 
    errno = ret_errno;
1629
1117
    return false;
1630
1118
  }
1631
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1632
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1119
  strcpy(ifr->ifr_name, ifname);
1633
1120
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1634
1121
  if(ret == -1){
1635
1122
    if(debug){
1636
 
      ret_errno = errno;
1637
1123
      perror_plus("ioctl SIOCGIFFLAGS");
1638
 
      errno = ret_errno;
1639
1124
    }
1640
1125
    return false;
1641
1126
  }
1642
1127
  return true;
1643
1128
}
1644
1129
 
1645
 
__attribute__((nonnull, warn_unused_result))
1646
1130
bool good_flags(const char *ifname, const struct ifreq *ifr){
1647
1131
  
1648
1132
  /* Reject the loopback device */
1690
1174
 * corresponds to an acceptable network device.
1691
1175
 * (This function is passed to scandir(3) as a filter function.)
1692
1176
 */
1693
 
__attribute__((nonnull, warn_unused_result))
1694
1177
int good_interface(const struct dirent *if_entry){
1695
1178
  if(if_entry->d_name[0] == '.'){
1696
1179
    return 0;
1712
1195
}
1713
1196
 
1714
1197
/* 
1715
 
 * This function determines if a network interface is up.
1716
 
 */
1717
 
__attribute__((nonnull, warn_unused_result))
1718
 
bool interface_is_up(const char *interface){
1719
 
  struct ifreq ifr;
1720
 
  if(not get_flags(interface, &ifr)){
1721
 
    if(debug){
1722
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1723
 
                   "\"%s\"\n", interface);
1724
 
    }
1725
 
    return false;
1726
 
  }
1727
 
  
1728
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1729
 
}
1730
 
 
1731
 
/* 
1732
 
 * This function determines if a network interface is running
1733
 
 */
1734
 
__attribute__((nonnull, warn_unused_result))
1735
 
bool interface_is_running(const char *interface){
1736
 
  struct ifreq ifr;
1737
 
  if(not get_flags(interface, &ifr)){
1738
 
    if(debug){
1739
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1740
 
                   "\"%s\"\n", interface);
1741
 
    }
1742
 
    return false;
1743
 
  }
1744
 
  
1745
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1746
 
}
1747
 
 
1748
 
__attribute__((nonnull, pure, warn_unused_result))
 
1198
 * This function determines if a directory entry in /sys/class/net
 
1199
 * corresponds to an acceptable network device which is up.
 
1200
 * (This function is passed to scandir(3) as a filter function.)
 
1201
 */
 
1202
int up_interface(const struct dirent *if_entry){
 
1203
  if(if_entry->d_name[0] == '.'){
 
1204
    return 0;
 
1205
  }
 
1206
  
 
1207
  struct ifreq ifr;
 
1208
  if(not get_flags(if_entry->d_name, &ifr)){
 
1209
    if(debug){
 
1210
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1211
                   "\"%s\"\n", if_entry->d_name);
 
1212
    }
 
1213
    return 0;
 
1214
  }
 
1215
  
 
1216
  /* Reject down interfaces */
 
1217
  if(not (ifr.ifr_flags & IFF_UP)){
 
1218
    if(debug){
 
1219
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1220
                   if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  /* Reject non-running interfaces */
 
1226
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1227
    if(debug){
 
1228
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1229
                   if_entry->d_name);
 
1230
    }
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  if(not good_flags(if_entry->d_name, &ifr)){
 
1235
    return 0;
 
1236
  }
 
1237
  return 1;
 
1238
}
 
1239
 
1749
1240
int notdotentries(const struct dirent *direntry){
1750
1241
  /* Skip "." and ".." */
1751
1242
  if(direntry->d_name[0] == '.'
1758
1249
}
1759
1250
 
1760
1251
/* Is this directory entry a runnable program? */
1761
 
__attribute__((nonnull, warn_unused_result))
1762
1252
int runnable_hook(const struct dirent *direntry){
1763
1253
  int ret;
1764
1254
  size_t sret;
1772
1262
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1773
1263
                "abcdefghijklmnopqrstuvwxyz"
1774
1264
                "0123456789"
1775
 
                "_.-");
 
1265
                "_-");
1776
1266
  if((direntry->d_name)[sret] != '\0'){
1777
1267
    /* Contains non-allowed characters */
1778
1268
    if(debug){
1782
1272
    return 0;
1783
1273
  }
1784
1274
  
1785
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1275
  char *fullname = NULL;
 
1276
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1277
  if(ret < 0){
 
1278
    perror_plus("asprintf");
 
1279
    return 0;
 
1280
  }
 
1281
  
 
1282
  ret = stat(fullname, &st);
1786
1283
  if(ret == -1){
1787
1284
    if(debug){
1788
1285
      perror_plus("Could not stat hook");
1812
1309
  return 1;
1813
1310
}
1814
1311
 
1815
 
__attribute__((nonnull, warn_unused_result))
1816
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1817
 
                            mandos_context *mc){
 
1312
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1818
1313
  int ret;
1819
1314
  struct timespec now;
1820
1315
  struct timespec waited_time;
1821
1316
  intmax_t block_time;
1822
1317
  
1823
1318
  while(true){
1824
 
    if(mc->current_server == NULL){
1825
 
      if(debug){
 
1319
    if(mc.current_server == NULL){
 
1320
      if (debug){
1826
1321
        fprintf_plus(stderr, "Wait until first server is found."
1827
1322
                     " No timeout!\n");
1828
1323
      }
1829
1324
      ret = avahi_simple_poll_iterate(s, -1);
1830
1325
    } else {
1831
 
      if(debug){
 
1326
      if (debug){
1832
1327
        fprintf_plus(stderr, "Check current_server if we should run"
1833
1328
                     " it, or wait\n");
1834
1329
      }
1841
1336
      /* Calculating in ms how long time between now and server
1842
1337
         who we visted longest time ago. Now - last seen.  */
1843
1338
      waited_time.tv_sec = (now.tv_sec
1844
 
                            - mc->current_server->last_seen.tv_sec);
 
1339
                            - mc.current_server->last_seen.tv_sec);
1845
1340
      waited_time.tv_nsec = (now.tv_nsec
1846
 
                             - mc->current_server->last_seen.tv_nsec);
 
1341
                             - mc.current_server->last_seen.tv_nsec);
1847
1342
      /* total time is 10s/10,000ms.
1848
1343
         Converting to s from ms by dividing by 1,000,
1849
1344
         and ns to ms by dividing by 1,000,000. */
1851
1346
                     - ((intmax_t)waited_time.tv_sec * 1000))
1852
1347
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1853
1348
      
1854
 
      if(debug){
 
1349
      if (debug){
1855
1350
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1856
1351
                     block_time);
1857
1352
      }
1858
1353
      
1859
1354
      if(block_time <= 0){
1860
 
        ret = start_mandos_communication(mc->current_server->ip,
1861
 
                                         mc->current_server->port,
1862
 
                                         mc->current_server->if_index,
1863
 
                                         mc->current_server->af, mc);
 
1355
        ret = start_mandos_communication(mc.current_server->ip,
 
1356
                                         mc.current_server->port,
 
1357
                                         mc.current_server->if_index,
 
1358
                                         mc.current_server->af);
1864
1359
        if(ret == 0){
1865
 
          avahi_simple_poll_quit(s);
 
1360
          avahi_simple_poll_quit(mc.simple_poll);
1866
1361
          return 0;
1867
1362
        }
1868
1363
        ret = clock_gettime(CLOCK_MONOTONIC,
1869
 
                            &mc->current_server->last_seen);
 
1364
                            &mc.current_server->last_seen);
1870
1365
        if(ret == -1){
1871
1366
          perror_plus("clock_gettime");
1872
1367
          return -1;
1873
1368
        }
1874
 
        mc->current_server = mc->current_server->next;
 
1369
        mc.current_server = mc.current_server->next;
1875
1370
        block_time = 0;         /* Call avahi to find new Mandos
1876
1371
                                   servers, but don't block */
1877
1372
      }
1879
1374
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1880
1375
    }
1881
1376
    if(ret != 0){
1882
 
      if(ret > 0 or errno != EINTR){
 
1377
      if (ret > 0 or errno != EINTR){
1883
1378
        return (ret != 1) ? ret : 0;
1884
1379
      }
1885
1380
    }
1886
1381
  }
1887
1382
}
1888
1383
 
1889
 
__attribute__((nonnull))
1890
 
void run_network_hooks(const char *mode, const char *interface,
 
1384
bool run_network_hooks(const char *mode, const char *interface,
1891
1385
                       const float delay){
1892
 
  struct dirent **direntries = NULL;
1893
 
  if(hookdir_fd == -1){
1894
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1895
 
                      | O_CLOEXEC);
1896
 
    if(hookdir_fd == -1){
1897
 
      if(errno == ENOENT){
1898
 
        if(debug){
1899
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1900
 
                       " found\n", hookdir);
1901
 
        }
1902
 
      } else {
1903
 
        perror_plus("open");
1904
 
      }
1905
 
      return;
1906
 
    }
1907
 
  }
1908
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1909
 
                           runnable_hook, alphasort);
 
1386
  struct dirent **direntries;
 
1387
  struct dirent *direntry;
 
1388
  int ret;
 
1389
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1390
                         alphasort);
1910
1391
  if(numhooks == -1){
1911
1392
    perror_plus("scandir");
1912
 
    return;
1913
 
  }
1914
 
  struct dirent *direntry;
1915
 
  int ret;
1916
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1917
 
  if(devnull == -1){
1918
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1919
 
    return;
1920
 
  }
1921
 
  for(int i = 0; i < numhooks; i++){
1922
 
    direntry = direntries[i];
1923
 
    if(debug){
1924
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1925
 
                   direntry->d_name);
1926
 
    }
1927
 
    pid_t hook_pid = fork();
1928
 
    if(hook_pid == 0){
1929
 
      /* Child */
1930
 
      /* Raise privileges */
1931
 
      errno = raise_privileges_permanently();
1932
 
      if(errno != 0){
1933
 
        perror_plus("Failed to raise privileges");
1934
 
        _exit(EX_NOPERM);
1935
 
      }
1936
 
      /* Set group */
1937
 
      errno = 0;
1938
 
      ret = setgid(0);
1939
 
      if(ret == -1){
1940
 
        perror_plus("setgid");
1941
 
        _exit(EX_NOPERM);
1942
 
      }
1943
 
      /* Reset supplementary groups */
1944
 
      errno = 0;
1945
 
      ret = setgroups(0, NULL);
1946
 
      if(ret == -1){
1947
 
        perror_plus("setgroups");
1948
 
        _exit(EX_NOPERM);
1949
 
      }
1950
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1951
 
      if(ret == -1){
1952
 
        perror_plus("setenv");
1953
 
        _exit(EX_OSERR);
1954
 
      }
1955
 
      ret = setenv("DEVICE", interface, 1);
1956
 
      if(ret == -1){
1957
 
        perror_plus("setenv");
1958
 
        _exit(EX_OSERR);
1959
 
      }
1960
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1961
 
      if(ret == -1){
1962
 
        perror_plus("setenv");
1963
 
        _exit(EX_OSERR);
1964
 
      }
1965
 
      ret = setenv("MODE", mode, 1);
1966
 
      if(ret == -1){
1967
 
        perror_plus("setenv");
1968
 
        _exit(EX_OSERR);
1969
 
      }
1970
 
      char *delaystring;
1971
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1972
 
      if(ret == -1){
 
1393
  } else {
 
1394
    int devnull = open("/dev/null", O_RDONLY);
 
1395
    for(int i = 0; i < numhooks; i++){
 
1396
      direntry = direntries[i];
 
1397
      char *fullname = NULL;
 
1398
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1399
      if(ret < 0){
1973
1400
        perror_plus("asprintf");
1974
 
        _exit(EX_OSERR);
1975
 
      }
1976
 
      ret = setenv("DELAY", delaystring, 1);
1977
 
      if(ret == -1){
 
1401
        continue;
 
1402
      }
 
1403
      if(debug){
 
1404
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1405
                     direntry->d_name);
 
1406
      }
 
1407
      pid_t hook_pid = fork();
 
1408
      if(hook_pid == 0){
 
1409
        /* Child */
 
1410
        /* Raise privileges */
 
1411
        errno = 0;
 
1412
        ret = seteuid(0);
 
1413
        if(ret == -1){
 
1414
          perror_plus("seteuid");
 
1415
        }
 
1416
        /* Raise privileges even more */
 
1417
        errno = 0;
 
1418
        ret = setuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("setuid");
 
1421
        }
 
1422
        /* Set group */
 
1423
        errno = 0;
 
1424
        ret = setgid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setgid");
 
1427
        }
 
1428
        /* Reset supplementary groups */
 
1429
        errno = 0;
 
1430
        ret = setgroups(0, NULL);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgroups");
 
1433
        }
 
1434
        dup2(devnull, STDIN_FILENO);
 
1435
        close(devnull);
 
1436
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1437
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1438
        if(ret == -1){
 
1439
          perror_plus("setenv");
 
1440
          _exit(EX_OSERR);
 
1441
        }
 
1442
        ret = setenv("DEVICE", interface, 1);
 
1443
        if(ret == -1){
 
1444
          perror_plus("setenv");
 
1445
          _exit(EX_OSERR);
 
1446
        }
 
1447
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1448
        if(ret == -1){
 
1449
          perror_plus("setenv");
 
1450
          _exit(EX_OSERR);
 
1451
        }
 
1452
        ret = setenv("MODE", mode, 1);
 
1453
        if(ret == -1){
 
1454
          perror_plus("setenv");
 
1455
          _exit(EX_OSERR);
 
1456
        }
 
1457
        char *delaystring;
 
1458
        ret = asprintf(&delaystring, "%f", delay);
 
1459
        if(ret == -1){
 
1460
          perror_plus("asprintf");
 
1461
          _exit(EX_OSERR);
 
1462
        }
 
1463
        ret = setenv("DELAY", delaystring, 1);
 
1464
        if(ret == -1){
 
1465
          free(delaystring);
 
1466
          perror_plus("setenv");
 
1467
          _exit(EX_OSERR);
 
1468
        }
1978
1469
        free(delaystring);
1979
 
        perror_plus("setenv");
1980
 
        _exit(EX_OSERR);
1981
 
      }
1982
 
      free(delaystring);
1983
 
      if(connect_to != NULL){
1984
 
        ret = setenv("CONNECT", connect_to, 1);
1985
 
        if(ret == -1){
1986
 
          perror_plus("setenv");
1987
 
          _exit(EX_OSERR);
1988
 
        }
1989
 
      }
1990
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
1991
 
                                                   direntry->d_name,
1992
 
                                                   O_RDONLY));
1993
 
      if(hook_fd == -1){
1994
 
        perror_plus("openat");
1995
 
        _exit(EXIT_FAILURE);
1996
 
      }
1997
 
      if(close(hookdir_fd) == -1){
1998
 
        perror_plus("close");
1999
 
        _exit(EXIT_FAILURE);
2000
 
      }
2001
 
      ret = dup2(devnull, STDIN_FILENO);
2002
 
      if(ret == -1){
2003
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2004
 
        _exit(EX_OSERR);
2005
 
      }
2006
 
      ret = close(devnull);
2007
 
      if(ret == -1){
2008
 
        perror_plus("close");
2009
 
        _exit(EX_OSERR);
2010
 
      }
2011
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2012
 
      if(ret == -1){
2013
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2014
 
        _exit(EX_OSERR);
2015
 
      }
2016
 
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2017
 
                 environ) == -1){
2018
 
        perror_plus("fexecve");
2019
 
        _exit(EXIT_FAILURE);
2020
 
      }
2021
 
    } else {
2022
 
      if(hook_pid == -1){
2023
 
        perror_plus("fork");
2024
 
        free(direntry);
2025
 
        continue;
2026
 
      }
2027
 
      int status;
2028
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2029
 
        perror_plus("waitpid");
2030
 
        free(direntry);
2031
 
        continue;
2032
 
      }
2033
 
      if(WIFEXITED(status)){
2034
 
        if(WEXITSTATUS(status) != 0){
2035
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2036
 
                       " with status %d\n", direntry->d_name,
2037
 
                       WEXITSTATUS(status));
2038
 
          free(direntry);
2039
 
          continue;
2040
 
        }
2041
 
      } else if(WIFSIGNALED(status)){
2042
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2043
 
                     " signal %d\n", direntry->d_name,
2044
 
                     WTERMSIG(status));
2045
 
        free(direntry);
2046
 
        continue;
2047
 
      } else {
2048
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2049
 
                     " crashed\n", direntry->d_name);
2050
 
        free(direntry);
2051
 
        continue;
2052
 
      }
2053
 
    }
2054
 
    if(debug){
2055
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2056
 
                   direntry->d_name);
2057
 
    }
2058
 
    free(direntry);
2059
 
  }
2060
 
  free(direntries);
2061
 
  if(close(hookdir_fd) == -1){
2062
 
    perror_plus("close");
2063
 
  } else {
2064
 
    hookdir_fd = -1;
2065
 
  }
2066
 
  close(devnull);
2067
 
}
2068
 
 
2069
 
__attribute__((nonnull, warn_unused_result))
2070
 
error_t bring_up_interface(const char *const interface,
2071
 
                           const float delay){
2072
 
  error_t old_errno = errno;
2073
 
  int ret;
2074
 
  struct ifreq network;
2075
 
  unsigned int if_index = if_nametoindex(interface);
2076
 
  if(if_index == 0){
2077
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2078
 
    errno = old_errno;
2079
 
    return ENXIO;
2080
 
  }
2081
 
  
2082
 
  if(quit_now){
2083
 
    errno = old_errno;
2084
 
    return EINTR;
2085
 
  }
2086
 
  
2087
 
  if(not interface_is_up(interface)){
2088
 
    error_t ret_errno = 0, ioctl_errno = 0;
2089
 
    if(not get_flags(interface, &network)){
2090
 
      ret_errno = errno;
2091
 
      fprintf_plus(stderr, "Failed to get flags for interface "
2092
 
                   "\"%s\"\n", interface);
2093
 
      errno = old_errno;
2094
 
      return ret_errno;
2095
 
    }
2096
 
    network.ifr_flags |= IFF_UP; /* set flag */
2097
 
    
2098
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2099
 
    if(sd == -1){
2100
 
      ret_errno = errno;
2101
 
      perror_plus("socket");
2102
 
      errno = old_errno;
2103
 
      return ret_errno;
2104
 
    }
2105
 
    
2106
 
    if(quit_now){
2107
 
      ret = close(sd);
2108
 
      if(ret == -1){
2109
 
        perror_plus("close");
2110
 
      }
2111
 
      errno = old_errno;
2112
 
      return EINTR;
2113
 
    }
2114
 
    
2115
 
    if(debug){
2116
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
2117
 
                   interface);
2118
 
    }
2119
 
    
2120
 
    /* Raise privileges */
2121
 
    ret_errno = raise_privileges();
2122
 
    if(ret_errno != 0){
2123
 
      errno = ret_errno;
2124
 
      perror_plus("Failed to raise privileges");
2125
 
    }
2126
 
    
2127
 
#ifdef __linux__
2128
 
    int ret_linux;
2129
 
    bool restore_loglevel = false;
2130
 
    if(ret_errno == 0){
2131
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2132
 
         messages about the network interface to mess up the prompt */
2133
 
      ret_linux = klogctl(8, NULL, 5);
2134
 
      if(ret_linux == -1){
2135
 
        perror_plus("klogctl");
2136
 
      } else {
2137
 
        restore_loglevel = true;
2138
 
      }
2139
 
    }
2140
 
#endif  /* __linux__ */
2141
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2142
 
    ioctl_errno = errno;
2143
 
#ifdef __linux__
2144
 
    if(restore_loglevel){
2145
 
      ret_linux = klogctl(7, NULL, 0);
2146
 
      if(ret_linux == -1){
2147
 
        perror_plus("klogctl");
2148
 
      }
2149
 
    }
2150
 
#endif  /* __linux__ */
2151
 
    
2152
 
    /* If raise_privileges() succeeded above */
2153
 
    if(ret_errno == 0){
2154
 
      /* Lower privileges */
2155
 
      ret_errno = lower_privileges();
2156
 
      if(ret_errno != 0){
2157
 
        errno = ret_errno;
2158
 
        perror_plus("Failed to lower privileges");
2159
 
      }
2160
 
    }
2161
 
    
2162
 
    /* Close the socket */
2163
 
    ret = close(sd);
2164
 
    if(ret == -1){
2165
 
      perror_plus("close");
2166
 
    }
2167
 
    
2168
 
    if(ret_setflags == -1){
2169
 
      errno = ioctl_errno;
2170
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2171
 
      errno = old_errno;
2172
 
      return ioctl_errno;
2173
 
    }
2174
 
  } else if(debug){
2175
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2176
 
                 interface);
2177
 
  }
2178
 
  
2179
 
  /* Sleep checking until interface is running.
2180
 
     Check every 0.25s, up to total time of delay */
2181
 
  for(int i=0; i < delay * 4; i++){
2182
 
    if(interface_is_running(interface)){
2183
 
      break;
2184
 
    }
2185
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
2186
 
    ret = nanosleep(&sleeptime, NULL);
2187
 
    if(ret == -1 and errno != EINTR){
2188
 
      perror_plus("nanosleep");
2189
 
    }
2190
 
  }
2191
 
  
2192
 
  errno = old_errno;
2193
 
  return 0;
2194
 
}
2195
 
 
2196
 
__attribute__((nonnull, warn_unused_result))
2197
 
error_t take_down_interface(const char *const interface){
2198
 
  error_t old_errno = errno;
2199
 
  struct ifreq network;
2200
 
  unsigned int if_index = if_nametoindex(interface);
2201
 
  if(if_index == 0){
2202
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2203
 
    errno = old_errno;
2204
 
    return ENXIO;
2205
 
  }
2206
 
  if(interface_is_up(interface)){
2207
 
    error_t ret_errno = 0, ioctl_errno = 0;
2208
 
    if(not get_flags(interface, &network) and debug){
2209
 
      ret_errno = errno;
2210
 
      fprintf_plus(stderr, "Failed to get flags for interface "
2211
 
                   "\"%s\"\n", interface);
2212
 
      errno = old_errno;
2213
 
      return ret_errno;
2214
 
    }
2215
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2216
 
    
2217
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2218
 
    if(sd == -1){
2219
 
      ret_errno = errno;
2220
 
      perror_plus("socket");
2221
 
      errno = old_errno;
2222
 
      return ret_errno;
2223
 
    }
2224
 
    
2225
 
    if(debug){
2226
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
2227
 
                   interface);
2228
 
    }
2229
 
    
2230
 
    /* Raise privileges */
2231
 
    ret_errno = raise_privileges();
2232
 
    if(ret_errno != 0){
2233
 
      errno = ret_errno;
2234
 
      perror_plus("Failed to raise privileges");
2235
 
    }
2236
 
    
2237
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2238
 
    ioctl_errno = errno;
2239
 
    
2240
 
    /* If raise_privileges() succeeded above */
2241
 
    if(ret_errno == 0){
2242
 
      /* Lower privileges */
2243
 
      ret_errno = lower_privileges();
2244
 
      if(ret_errno != 0){
2245
 
        errno = ret_errno;
2246
 
        perror_plus("Failed to lower privileges");
2247
 
      }
2248
 
    }
2249
 
    
2250
 
    /* Close the socket */
2251
 
    int ret = close(sd);
2252
 
    if(ret == -1){
2253
 
      perror_plus("close");
2254
 
    }
2255
 
    
2256
 
    if(ret_setflags == -1){
2257
 
      errno = ioctl_errno;
2258
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2259
 
      errno = old_errno;
2260
 
      return ioctl_errno;
2261
 
    }
2262
 
  } else if(debug){
2263
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2264
 
                 interface);
2265
 
  }
2266
 
  
2267
 
  errno = old_errno;
2268
 
  return 0;
 
1470
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1471
        perror_plus("execl");
 
1472
      } else {
 
1473
        int status;
 
1474
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1475
          perror_plus("waitpid");
 
1476
          free(fullname);
 
1477
          continue;
 
1478
        }
 
1479
        if(WIFEXITED(status)){
 
1480
          if(WEXITSTATUS(status) != 0){
 
1481
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1482
                         " with status %d\n", direntry->d_name,
 
1483
                         WEXITSTATUS(status));
 
1484
            free(fullname);
 
1485
            continue;
 
1486
          }
 
1487
        } else if(WIFSIGNALED(status)){
 
1488
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1489
                       " signal %d\n", direntry->d_name,
 
1490
                       WTERMSIG(status));
 
1491
          free(fullname);
 
1492
          continue;
 
1493
        } else {
 
1494
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1495
                       " crashed\n", direntry->d_name);
 
1496
          free(fullname);
 
1497
          continue;
 
1498
        }
 
1499
      }
 
1500
      free(fullname);
 
1501
      if(debug){
 
1502
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1503
                     direntry->d_name);
 
1504
      }
 
1505
    }
 
1506
    close(devnull);
 
1507
  }
 
1508
  return true;
2269
1509
}
2270
1510
 
2271
1511
int main(int argc, char *argv[]){
2272
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2273
 
                        .priority = "SECURE256:!CTYPE-X.509"
2274
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2275
 
                        .current_server = NULL, .interfaces = NULL,
2276
 
                        .interfaces_size = 0 };
2277
1512
  AvahiSServiceBrowser *sb = NULL;
2278
 
  error_t ret_errno;
 
1513
  int error;
2279
1514
  int ret;
2280
1515
  intmax_t tmpmax;
2281
1516
  char *tmp;
2282
1517
  int exitcode = EXIT_SUCCESS;
2283
 
  char *interfaces_to_take_down = NULL;
2284
 
  size_t interfaces_to_take_down_size = 0;
2285
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2286
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
2287
 
  char *tempdir = NULL;
 
1518
  const char *interface = "";
 
1519
  struct ifreq network;
 
1520
  int sd = -1;
 
1521
  bool take_down_interface = false;
 
1522
  uid_t uid;
 
1523
  gid_t gid;
 
1524
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1525
  bool tempdir_created = false;
2288
1526
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2289
1527
  const char *seckey = PATHDIR "/" SECKEY;
2290
1528
  const char *pubkey = PATHDIR "/" PUBKEY;
2291
 
  const char *dh_params_file = NULL;
2292
 
  char *interfaces_hooks = NULL;
2293
1529
  
2294
1530
  bool gnutls_initialized = false;
2295
1531
  bool gpgme_initialized = false;
2347
1583
        .doc = "Bit length of the prime number used in the"
2348
1584
        " Diffie-Hellman key exchange",
2349
1585
        .group = 2 },
2350
 
      { .name = "dh-params", .key = 134,
2351
 
        .arg = "FILE",
2352
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2353
 
        " for the Diffie-Hellman key exchange",
2354
 
        .group = 2 },
2355
1586
      { .name = "priority", .key = 130,
2356
1587
        .arg = "STRING",
2357
1588
        .doc = "GnuTLS priority string for the TLS handshake",
2362
1593
        .group = 2 },
2363
1594
      { .name = "retry", .key = 132,
2364
1595
        .arg = "SECONDS",
2365
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1596
        .doc = "Retry interval used when denied by the mandos server",
2366
1597
        .group = 2 },
2367
1598
      { .name = "network-hook-dir", .key = 133,
2368
1599
        .arg = "DIR",
2391
1622
        connect_to = arg;
2392
1623
        break;
2393
1624
      case 'i':                 /* --interface */
2394
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2395
 
                                 arg, (int)',');
2396
 
        if(ret_errno != 0){
2397
 
          argp_error(state, "%s", strerror(ret_errno));
2398
 
        }
 
1625
        interface = arg;
2399
1626
        break;
2400
1627
      case 's':                 /* --seckey */
2401
1628
        seckey = arg;
2412
1639
        }
2413
1640
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2414
1641
        break;
2415
 
      case 134:                 /* --dh-params */
2416
 
        dh_params_file = arg;
2417
 
        break;
2418
1642
      case 130:                 /* --priority */
2419
1643
        mc.priority = arg;
2420
1644
        break;
2447
1671
        argp_state_help(state, state->out_stream,
2448
1672
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2449
1673
      case 'V':                 /* --version */
 
1674
        fprintf_plus(state->out_stream,
 
1675
                     "Mandos plugin mandos-client: ");
2450
1676
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
2451
1677
        exit(argp_err_exit_status);
2452
1678
        break;
2476
1702
      goto end;
2477
1703
    }
2478
1704
  }
2479
 
  
 
1705
    
2480
1706
  {
2481
1707
    /* Work around Debian bug #633582:
2482
1708
       <http://bugs.debian.org/633582> */
2483
1709
    
2484
 
    /* Re-raise privileges */
2485
 
    ret_errno = raise_privileges();
2486
 
    if(ret_errno != 0){
2487
 
      errno = ret_errno;
2488
 
      perror_plus("Failed to raise privileges");
 
1710
    /* Re-raise priviliges */
 
1711
    errno = 0;
 
1712
    ret = seteuid(0);
 
1713
    if(ret == -1){
 
1714
      perror_plus("seteuid");
2489
1715
    } else {
2490
1716
      struct stat st;
2491
1717
      
2506
1732
              }
2507
1733
            }
2508
1734
          }
2509
 
          close(seckey_fd);
 
1735
          TEMP_FAILURE_RETRY(close(seckey_fd));
2510
1736
        }
2511
1737
      }
2512
 
      
 
1738
    
2513
1739
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2514
1740
        int pubkey_fd = open(pubkey, O_RDONLY);
2515
1741
        if(pubkey_fd == -1){
2527
1753
              }
2528
1754
            }
2529
1755
          }
2530
 
          close(pubkey_fd);
2531
 
        }
2532
 
      }
2533
 
      
2534
 
      if(dh_params_file != NULL
2535
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2536
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2537
 
        if(dhparams_fd == -1){
2538
 
          perror_plus("open");
2539
 
        } else {
2540
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2541
 
          if(ret == -1){
2542
 
            perror_plus("fstat");
2543
 
          } else {
2544
 
            if(S_ISREG(st.st_mode)
2545
 
               and st.st_uid == 0 and st.st_gid == 0){
2546
 
              ret = fchown(dhparams_fd, uid, gid);
2547
 
              if(ret == -1){
2548
 
                perror_plus("fchown");
2549
 
              }
2550
 
            }
2551
 
          }
2552
 
          close(dhparams_fd);
2553
 
        }
2554
 
      }
2555
 
      
 
1756
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1757
        }
 
1758
      }
 
1759
    
2556
1760
      /* Lower privileges */
2557
 
      ret_errno = lower_privileges();
2558
 
      if(ret_errno != 0){
2559
 
        errno = ret_errno;
2560
 
        perror_plus("Failed to lower privileges");
2561
 
      }
2562
 
    }
2563
 
  }
2564
 
  
2565
 
  /* Remove invalid interface names (except "none") */
2566
 
  {
2567
 
    char *interface = NULL;
2568
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2569
 
                                 interface))){
2570
 
      if(strcmp(interface, "none") != 0
2571
 
         and if_nametoindex(interface) == 0){
2572
 
        if(interface[0] != '\0'){
2573
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2574
 
                       " \"%s\"\n", interface);
2575
 
        }
2576
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2577
 
        interface = NULL;
 
1761
      errno = 0;
 
1762
      ret = seteuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("seteuid");
2578
1765
      }
2579
1766
    }
2580
1767
  }
2581
1768
  
2582
1769
  /* Run network hooks */
2583
 
  {
2584
 
    if(mc.interfaces != NULL){
2585
 
      interfaces_hooks = malloc(mc.interfaces_size);
2586
 
      if(interfaces_hooks == NULL){
2587
 
        perror_plus("malloc");
2588
 
        goto end;
2589
 
      }
2590
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2591
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2592
 
    }
2593
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2594
 
                      interfaces_hooks : "", delay);
 
1770
  if(not run_network_hooks("start", interface, delay)){
 
1771
    goto end;
2595
1772
  }
2596
1773
  
2597
1774
  if(not debug){
2598
1775
    avahi_set_log_function(empty_log);
2599
1776
  }
2600
1777
  
 
1778
  if(interface[0] == '\0'){
 
1779
    struct dirent **direntries;
 
1780
    /* First look for interfaces that are up */
 
1781
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1782
                  alphasort);
 
1783
    if(ret == 0){
 
1784
      /* No up interfaces, look for any good interfaces */
 
1785
      free(direntries);
 
1786
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1787
                    alphasort);
 
1788
    }
 
1789
    if(ret >= 1){
 
1790
      /* Pick the first interface returned */
 
1791
      interface = strdup(direntries[0]->d_name);
 
1792
      if(debug){
 
1793
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1794
      }
 
1795
      if(interface == NULL){
 
1796
        perror_plus("malloc");
 
1797
        free(direntries);
 
1798
        exitcode = EXIT_FAILURE;
 
1799
        goto end;
 
1800
      }
 
1801
      free(direntries);
 
1802
    } else {
 
1803
      free(direntries);
 
1804
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1805
      exitcode = EXIT_FAILURE;
 
1806
      goto end;
 
1807
    }
 
1808
  }
 
1809
  
2601
1810
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2602
1811
     from the signal handler */
2603
1812
  /* Initialize the pseudo-RNG for Avahi */
2604
1813
  srand((unsigned int) time(NULL));
2605
 
  simple_poll = avahi_simple_poll_new();
2606
 
  if(simple_poll == NULL){
 
1814
  mc.simple_poll = avahi_simple_poll_new();
 
1815
  if(mc.simple_poll == NULL){
2607
1816
    fprintf_plus(stderr,
2608
1817
                 "Avahi: Failed to create simple poll object.\n");
2609
1818
    exitcode = EX_UNAVAILABLE;
2673
1882
    }
2674
1883
  }
2675
1884
  
2676
 
  /* If no interfaces were specified, make a list */
2677
 
  if(mc.interfaces == NULL){
2678
 
    struct dirent **direntries = NULL;
2679
 
    /* Look for any good interfaces */
2680
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2681
 
                  alphasort);
2682
 
    if(ret >= 1){
2683
 
      /* Add all found interfaces to interfaces list */
2684
 
      for(int i = 0; i < ret; ++i){
2685
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2686
 
                             direntries[i]->d_name);
2687
 
        if(ret_errno != 0){
2688
 
          errno = ret_errno;
2689
 
          perror_plus("argz_add");
2690
 
          free(direntries[i]);
2691
 
          continue;
2692
 
        }
2693
 
        if(debug){
2694
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2695
 
                       direntries[i]->d_name);
2696
 
        }
2697
 
        free(direntries[i]);
2698
 
      }
2699
 
      free(direntries);
2700
 
    } else {
2701
 
      if(ret == 0){
2702
 
        free(direntries);
2703
 
      }
2704
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2705
 
      exitcode = EXIT_FAILURE;
2706
 
      goto end;
2707
 
    }
2708
 
  }
2709
 
  
2710
 
  /* Bring up interfaces which are down, and remove any "none"s */
2711
 
  {
2712
 
    char *interface = NULL;
2713
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2714
 
                                 interface))){
2715
 
      /* If interface name is "none", stop bringing up interfaces.
2716
 
         Also remove all instances of "none" from the list */
2717
 
      if(strcmp(interface, "none") == 0){
2718
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2719
 
                    interface);
2720
 
        interface = NULL;
2721
 
        while((interface = argz_next(mc.interfaces,
2722
 
                                     mc.interfaces_size, interface))){
2723
 
          if(strcmp(interface, "none") == 0){
2724
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2725
 
                        interface);
2726
 
            interface = NULL;
 
1885
  /* If the interface is down, bring it up */
 
1886
  if(strcmp(interface, "none") != 0){
 
1887
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1888
    if(if_index == 0){
 
1889
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1890
      exitcode = EX_UNAVAILABLE;
 
1891
      goto end;
 
1892
    }
 
1893
    
 
1894
    if(quit_now){
 
1895
      goto end;
 
1896
    }
 
1897
    
 
1898
    /* Re-raise priviliges */
 
1899
    errno = 0;
 
1900
    ret = seteuid(0);
 
1901
    if(ret == -1){
 
1902
      perror_plus("seteuid");
 
1903
    }
 
1904
    
 
1905
#ifdef __linux__
 
1906
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1907
       messages about the network interface to mess up the prompt */
 
1908
    ret = klogctl(8, NULL, 5);
 
1909
    bool restore_loglevel = true;
 
1910
    if(ret == -1){
 
1911
      restore_loglevel = false;
 
1912
      perror_plus("klogctl");
 
1913
    }
 
1914
#endif  /* __linux__ */
 
1915
    
 
1916
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1917
    if(sd < 0){
 
1918
      perror_plus("socket");
 
1919
      exitcode = EX_OSERR;
 
1920
#ifdef __linux__
 
1921
      if(restore_loglevel){
 
1922
        ret = klogctl(7, NULL, 0);
 
1923
        if(ret == -1){
 
1924
          perror_plus("klogctl");
 
1925
        }
 
1926
      }
 
1927
#endif  /* __linux__ */
 
1928
      /* Lower privileges */
 
1929
      errno = 0;
 
1930
      ret = seteuid(uid);
 
1931
      if(ret == -1){
 
1932
        perror_plus("seteuid");
 
1933
      }
 
1934
      goto end;
 
1935
    }
 
1936
    strcpy(network.ifr_name, interface);
 
1937
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1938
    if(ret == -1){
 
1939
      perror_plus("ioctl SIOCGIFFLAGS");
 
1940
#ifdef __linux__
 
1941
      if(restore_loglevel){
 
1942
        ret = klogctl(7, NULL, 0);
 
1943
        if(ret == -1){
 
1944
          perror_plus("klogctl");
 
1945
        }
 
1946
      }
 
1947
#endif  /* __linux__ */
 
1948
      exitcode = EX_OSERR;
 
1949
      /* Lower privileges */
 
1950
      errno = 0;
 
1951
      ret = seteuid(uid);
 
1952
      if(ret == -1){
 
1953
        perror_plus("seteuid");
 
1954
      }
 
1955
      goto end;
 
1956
    }
 
1957
    if((network.ifr_flags & IFF_UP) == 0){
 
1958
      network.ifr_flags |= IFF_UP;
 
1959
      take_down_interface = true;
 
1960
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1961
      if(ret == -1){
 
1962
        take_down_interface = false;
 
1963
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1964
        exitcode = EX_OSERR;
 
1965
#ifdef __linux__
 
1966
        if(restore_loglevel){
 
1967
          ret = klogctl(7, NULL, 0);
 
1968
          if(ret == -1){
 
1969
            perror_plus("klogctl");
2727
1970
          }
2728
1971
        }
 
1972
#endif  /* __linux__ */
 
1973
        /* Lower privileges */
 
1974
        errno = 0;
 
1975
        ret = seteuid(uid);
 
1976
        if(ret == -1){
 
1977
          perror_plus("seteuid");
 
1978
        }
 
1979
        goto end;
 
1980
      }
 
1981
    }
 
1982
    /* Sleep checking until interface is running.
 
1983
       Check every 0.25s, up to total time of delay */
 
1984
    for(int i=0; i < delay * 4; i++){
 
1985
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1986
      if(ret == -1){
 
1987
        perror_plus("ioctl SIOCGIFFLAGS");
 
1988
      } else if(network.ifr_flags & IFF_RUNNING){
2729
1989
        break;
2730
1990
      }
2731
 
      bool interface_was_up = interface_is_up(interface);
2732
 
      errno = bring_up_interface(interface, delay);
2733
 
      if(not interface_was_up){
2734
 
        if(errno != 0){
2735
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2736
 
                       " %s\n", interface, strerror(errno));
2737
 
        } else {
2738
 
          errno = argz_add(&interfaces_to_take_down,
2739
 
                           &interfaces_to_take_down_size,
2740
 
                           interface);
2741
 
          if(errno != 0){
2742
 
            perror_plus("argz_add");
2743
 
          }
2744
 
        }
2745
 
      }
2746
 
    }
2747
 
    if(debug and (interfaces_to_take_down == NULL)){
2748
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2749
 
    }
2750
 
  }
2751
 
  
2752
 
  /* If we only got one interface, explicitly use only that one */
2753
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2754
 
    if(debug){
2755
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2756
 
                   mc.interfaces);
2757
 
    }
2758
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
1991
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1992
      ret = nanosleep(&sleeptime, NULL);
 
1993
      if(ret == -1 and errno != EINTR){
 
1994
        perror_plus("nanosleep");
 
1995
      }
 
1996
    }
 
1997
    if(not take_down_interface){
 
1998
      /* We won't need the socket anymore */
 
1999
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2000
      if(ret == -1){
 
2001
        perror_plus("close");
 
2002
      }
 
2003
    }
 
2004
#ifdef __linux__
 
2005
    if(restore_loglevel){
 
2006
      /* Restores kernel loglevel to default */
 
2007
      ret = klogctl(7, NULL, 0);
 
2008
      if(ret == -1){
 
2009
        perror_plus("klogctl");
 
2010
      }
 
2011
    }
 
2012
#endif  /* __linux__ */
 
2013
    /* Lower privileges */
 
2014
    errno = 0;
 
2015
    /* Lower privileges */
 
2016
    ret = seteuid(uid);
 
2017
    if(ret == -1){
 
2018
      perror_plus("seteuid");
 
2019
    }
2759
2020
  }
2760
2021
  
2761
2022
  if(quit_now){
2762
2023
    goto end;
2763
2024
  }
2764
2025
  
2765
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2026
  ret = init_gnutls_global(pubkey, seckey);
2766
2027
  if(ret == -1){
2767
2028
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2768
2029
    exitcode = EX_UNAVAILABLE;
2775
2036
    goto end;
2776
2037
  }
2777
2038
  
2778
 
  /* Try /run/tmp before /tmp */
2779
 
  tempdir = mkdtemp(run_tempdir);
2780
 
  if(tempdir == NULL and errno == ENOENT){
2781
 
      if(debug){
2782
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2783
 
                     run_tempdir, old_tempdir);
2784
 
      }
2785
 
      tempdir = mkdtemp(old_tempdir);
2786
 
  }
2787
 
  if(tempdir == NULL){
 
2039
  if(mkdtemp(tempdir) == NULL){
2788
2040
    perror_plus("mkdtemp");
2789
2041
    goto end;
2790
2042
  }
 
2043
  tempdir_created = true;
2791
2044
  
2792
2045
  if(quit_now){
2793
2046
    goto end;
2794
2047
  }
2795
2048
  
2796
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2049
  if(not init_gpgme(pubkey, seckey, tempdir)){
2797
2050
    fprintf_plus(stderr, "init_gpgme failed\n");
2798
2051
    exitcode = EX_UNAVAILABLE;
2799
2052
    goto end;
2809
2062
    /* Connect directly, do not use Zeroconf */
2810
2063
    /* (Mainly meant for debugging) */
2811
2064
    char *address = strrchr(connect_to, ':');
2812
 
    
2813
2065
    if(address == NULL){
2814
2066
      fprintf_plus(stderr, "No colon in address\n");
2815
2067
      exitcode = EX_USAGE;
2820
2072
      goto end;
2821
2073
    }
2822
2074
    
2823
 
    in_port_t port;
 
2075
    uint16_t port;
2824
2076
    errno = 0;
2825
2077
    tmpmax = strtoimax(address+1, &tmp, 10);
2826
2078
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2827
 
       or tmpmax != (in_port_t)tmpmax){
 
2079
       or tmpmax != (uint16_t)tmpmax){
2828
2080
      fprintf_plus(stderr, "Bad port number\n");
2829
2081
      exitcode = EX_USAGE;
2830
2082
      goto end;
2831
2083
    }
2832
 
    
 
2084
  
2833
2085
    if(quit_now){
2834
2086
      goto end;
2835
2087
    }
2836
2088
    
2837
 
    port = (in_port_t)tmpmax;
 
2089
    port = (uint16_t)tmpmax;
2838
2090
    *address = '\0';
2839
2091
    /* Colon in address indicates IPv6 */
2840
2092
    int af;
2856
2108
    }
2857
2109
    
2858
2110
    while(not quit_now){
2859
 
      ret = start_mandos_communication(address, port, if_index, af,
2860
 
                                       &mc);
 
2111
      ret = start_mandos_communication(address, port, if_index, af);
2861
2112
      if(quit_now or ret == 0){
2862
2113
        break;
2863
2114
      }
2865
2116
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2866
2117
                     (int)retry_interval);
2867
2118
      }
2868
 
      sleep((unsigned int)retry_interval);
 
2119
      sleep((int)retry_interval);
2869
2120
    }
2870
2121
    
2871
 
    if(not quit_now){
 
2122
    if (not quit_now){
2872
2123
      exitcode = EXIT_SUCCESS;
2873
2124
    }
2874
2125
    
2889
2140
    config.publish_domain = 0;
2890
2141
    
2891
2142
    /* Allocate a new server */
2892
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2893
 
                                 &config, NULL, NULL, &ret_errno);
 
2143
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2144
                                 (mc.simple_poll), &config, NULL,
 
2145
                                 NULL, &error);
2894
2146
    
2895
2147
    /* Free the Avahi configuration data */
2896
2148
    avahi_server_config_free(&config);
2899
2151
  /* Check if creating the Avahi server object succeeded */
2900
2152
  if(mc.server == NULL){
2901
2153
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2902
 
                 avahi_strerror(ret_errno));
 
2154
                 avahi_strerror(error));
2903
2155
    exitcode = EX_UNAVAILABLE;
2904
2156
    goto end;
2905
2157
  }
2911
2163
  /* Create the Avahi service browser */
2912
2164
  sb = avahi_s_service_browser_new(mc.server, if_index,
2913
2165
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2914
 
                                   NULL, 0, browse_callback,
2915
 
                                   (void *)&mc);
 
2166
                                   NULL, 0, browse_callback, NULL);
2916
2167
  if(sb == NULL){
2917
2168
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2918
2169
                 avahi_strerror(avahi_server_errno(mc.server)));
2929
2180
  if(debug){
2930
2181
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2931
2182
  }
2932
 
  
2933
 
  ret = avahi_loop_with_timeout(simple_poll,
2934
 
                                (int)(retry_interval * 1000), &mc);
 
2183
 
 
2184
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2185
                                (int)(retry_interval * 1000));
2935
2186
  if(debug){
2936
2187
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2937
2188
                 (ret == 0) ? "successfully" : "with error");
2944
2195
  }
2945
2196
  
2946
2197
  /* Cleanup things */
2947
 
  free(mc.interfaces);
2948
 
  
2949
2198
  if(sb != NULL)
2950
2199
    avahi_s_service_browser_free(sb);
2951
2200
  
2952
2201
  if(mc.server != NULL)
2953
2202
    avahi_server_free(mc.server);
2954
2203
  
2955
 
  if(simple_poll != NULL)
2956
 
    avahi_simple_poll_free(simple_poll);
 
2204
  if(mc.simple_poll != NULL)
 
2205
    avahi_simple_poll_free(mc.simple_poll);
2957
2206
  
2958
2207
  if(gnutls_initialized){
2959
2208
    gnutls_certificate_free_credentials(mc.cred);
 
2209
    gnutls_global_deinit();
2960
2210
    gnutls_dh_params_deinit(mc.dh_params);
2961
2211
  }
2962
2212
  
2970
2220
    mc.current_server->prev->next = NULL;
2971
2221
    while(mc.current_server != NULL){
2972
2222
      server *next = mc.current_server->next;
2973
 
#ifdef __GNUC__
2974
 
#pragma GCC diagnostic push
2975
 
#pragma GCC diagnostic ignored "-Wcast-qual"
2976
 
#endif
2977
 
      free((char *)(mc.current_server->ip));
2978
 
#ifdef __GNUC__
2979
 
#pragma GCC diagnostic pop
2980
 
#endif
2981
2223
      free(mc.current_server);
2982
2224
      mc.current_server = next;
2983
2225
    }
2984
2226
  }
2985
2227
  
2986
 
  /* Re-raise privileges */
 
2228
  /* Run network hooks */
 
2229
  run_network_hooks("stop", interface, delay);
 
2230
  
 
2231
  /* Re-raise priviliges */
2987
2232
  {
2988
 
    ret_errno = raise_privileges();
2989
 
    if(ret_errno != 0){
2990
 
      errno = ret_errno;
2991
 
      perror_plus("Failed to raise privileges");
2992
 
    } else {
2993
 
      
2994
 
      /* Run network hooks */
2995
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2996
 
                        interfaces_hooks : "", delay);
2997
 
      
2998
 
      /* Take down the network interfaces which were brought up */
2999
 
      {
3000
 
        char *interface = NULL;
3001
 
        while((interface=argz_next(interfaces_to_take_down,
3002
 
                                   interfaces_to_take_down_size,
3003
 
                                   interface))){
3004
 
          ret_errno = take_down_interface(interface);
3005
 
          if(ret_errno != 0){
3006
 
            errno = ret_errno;
3007
 
            perror_plus("Failed to take down interface");
3008
 
          }
3009
 
        }
3010
 
        if(debug and (interfaces_to_take_down == NULL)){
3011
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
3012
 
                       " down\n");
3013
 
        }
3014
 
      }
 
2233
    errno = 0;
 
2234
    ret = seteuid(0);
 
2235
    if(ret == -1){
 
2236
      perror_plus("seteuid");
3015
2237
    }
3016
2238
    
3017
 
    ret_errno = lower_privileges_permanently();
3018
 
    if(ret_errno != 0){
3019
 
      errno = ret_errno;
3020
 
      perror_plus("Failed to lower privileges permanently");
 
2239
    /* Take down the network interface */
 
2240
    if(take_down_interface and geteuid() == 0){
 
2241
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2242
      if(ret == -1){
 
2243
        perror_plus("ioctl SIOCGIFFLAGS");
 
2244
      } else if(network.ifr_flags & IFF_UP){
 
2245
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2246
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2247
        if(ret == -1){
 
2248
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2249
        }
 
2250
      }
 
2251
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2252
      if(ret == -1){
 
2253
        perror_plus("close");
 
2254
      }
3021
2255
    }
3022
2256
  }
3023
 
  
3024
 
  free(interfaces_to_take_down);
3025
 
  free(interfaces_hooks);
 
2257
  /* Lower privileges permanently */
 
2258
  errno = 0;
 
2259
  ret = setuid(uid);
 
2260
  if(ret == -1){
 
2261
    perror_plus("setuid");
 
2262
  }
3026
2263
  
3027
2264
  /* Removes the GPGME temp directory and all files inside */
3028
 
  if(tempdir != NULL){
 
2265
  if(tempdir_created){
3029
2266
    struct dirent **direntries = NULL;
3030
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
3031
 
                                                  | O_NOFOLLOW
3032
 
                                                  | O_DIRECTORY
3033
 
                                                  | O_PATH));
3034
 
    if(tempdir_fd == -1){
3035
 
      perror_plus("open");
3036
 
    } else {
3037
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
3038
 
                                 notdotentries, alphasort);
3039
 
      if(numentries >= 0){
3040
 
        for(int i = 0; i < numentries; i++){
3041
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
3042
 
          if(ret == -1){
3043
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
3044
 
                         " \"%s\", 0): %s\n", tempdir,
3045
 
                         direntries[i]->d_name, strerror(errno));
3046
 
          }
3047
 
          free(direntries[i]);
3048
 
        }
3049
 
        
3050
 
        /* need to clean even if 0 because man page doesn't specify */
3051
 
        free(direntries);
3052
 
        if(numentries == -1){
3053
 
          perror_plus("scandir");
3054
 
        }
3055
 
        ret = rmdir(tempdir);
3056
 
        if(ret == -1 and errno != ENOENT){
3057
 
          perror_plus("rmdir");
3058
 
        }
 
2267
    struct dirent *direntry = NULL;
 
2268
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2269
                             alphasort);
 
2270
    if (numentries > 0){
 
2271
      for(int i = 0; i < numentries; i++){
 
2272
        direntry = direntries[i];
 
2273
        char *fullname = NULL;
 
2274
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2275
                       direntry->d_name);
 
2276
        if(ret < 0){
 
2277
          perror_plus("asprintf");
 
2278
          continue;
 
2279
        }
 
2280
        ret = remove(fullname);
 
2281
        if(ret == -1){
 
2282
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2283
                       strerror(errno));
 
2284
        }
 
2285
        free(fullname);
3059
2286
      }
3060
 
      close(tempdir_fd);
 
2287
    }
 
2288
 
 
2289
    /* need to clean even if 0 because man page doesn't specify */
 
2290
    free(direntries);
 
2291
    if (numentries == -1){
 
2292
      perror_plus("scandir");
 
2293
    }
 
2294
    ret = rmdir(tempdir);
 
2295
    if(ret == -1 and errno != ENOENT){
 
2296
      perror_plus("rmdir");
3061
2297
    }
3062
2298
  }
3063
2299