/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: 2015-07-01 20:01:26 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150701200126-qb3f6c3jcas2f4og
mandos-client: Try to start a plugin to add and remove a local route.

* debian/mandos-client.README.Debian: Add setting of environment
                                      variable MANDOSPLUGINHELPERDIR
                                      to command line testing
                                      mandos-client.
* mandos-client.c (raise_privileges): Moved to top of file.
                  (raise_privileges_permanently): - '' -
                  (lower_privileges): - '' -
                  (lower_privileges_permanently): - '' -
  (add_remove_local_route, add_local_route, remove_local_route): New.
  (start_mandos_communication): Set SOCK_CLOEXEC flag on socket.  Run
                                the above functions to add (and
                                remove) local route, if the conditions
                                indicates it could help.
  (run_network_hooks): Use O_DIRECTORY, O_PATH, and O_CLOEXEC flags
                       when opening network hook directory. Do
                       TEMP_FAILURE_RETRY around opening of /dev/null
                       and network hook executables.  Move redirecting
                       of stdout and stderr to as late as possible
                       before fexecve().
  (main): Use O_DIRECTORY and O_PATH when opening temporary directory.
* plugins.d/mandos-client.xml (ENVIRONMENT): Document usage of the
                                             MANDOSPLUGINHELPERDIR
                                             environment variable.

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2015 Teddy Hogeborn
 
13
 * Copyright © 2008-2015 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
 
35
#endif  /* not _LARGEFILE_SOURCE */
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
38
#endif  /* not _FILE_OFFSET_BITS */
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
43
                                   stdout, ferror() */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
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
 
#include <fcntl.h>              /* open() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
60
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
62
                                 */
62
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
64
                                   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
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
                                   setgid(), pause(), _exit(),
 
77
                                   unlinkat() */
 
78
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
79
#include <iso646.h>             /* not, or, and */
79
80
#include <argp.h>               /* struct argp_option, error_t, struct
80
81
                                   argp_state, struct argp,
88
89
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
90
                                   WEXITSTATUS(), WTERMSIG() */
90
91
#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() */
91
98
 
92
99
#ifdef __linux__
93
100
#include <sys/klog.h>           /* klogctl() */
135
142
static const char sys_class_net[] = "/sys/class/net";
136
143
char *connect_to = NULL;
137
144
const char *hookdir = HOOKDIR;
 
145
int hookdir_fd = -1;
 
146
uid_t uid = 65534;
 
147
gid_t gid = 65534;
138
148
 
139
149
/* Doubly linked list that need to be circularly linked when used */
140
150
typedef struct server{
141
151
  const char *ip;
142
 
  uint16_t port;
 
152
  in_port_t port;
143
153
  AvahiIfIndex if_index;
144
154
  int af;
145
155
  struct timespec last_seen;
149
159
 
150
160
/* Used for passing in values through the Avahi callback functions */
151
161
typedef struct {
152
 
  AvahiSimplePoll *simple_poll;
153
162
  AvahiServer *server;
154
163
  gnutls_certificate_credentials_t cred;
155
164
  unsigned int dh_bits;
157
166
  const char *priority;
158
167
  gpgme_ctx_t ctx;
159
168
  server *current_server;
 
169
  char *interfaces;
 
170
  size_t interfaces_size;
160
171
} mandos_context;
161
172
 
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 };
 
173
/* global so signal handler can reach it*/
 
174
AvahiSimplePoll *simple_poll;
167
175
 
168
176
sig_atomic_t quit_now = 0;
169
177
int signal_received = 0;
170
178
 
171
179
/* Function to use when printing errors */
172
180
void perror_plus(const char *print_text){
 
181
  int e = errno;
173
182
  fprintf(stderr, "Mandos plugin %s: ",
174
183
          program_invocation_short_name);
 
184
  errno = e;
175
185
  perror(print_text);
176
186
}
177
187
 
178
 
__attribute__((format (gnu_printf, 2, 3)))
 
188
__attribute__((format (gnu_printf, 2, 3), nonnull))
179
189
int fprintf_plus(FILE *stream, const char *format, ...){
180
190
  va_list ap;
181
191
  va_start (ap, format);
182
192
  
183
193
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
184
194
                             program_invocation_short_name));
185
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
195
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
186
196
}
187
197
 
188
198
/*
190
200
 * bytes. "buffer_capacity" is how much is currently allocated,
191
201
 * "buffer_length" is how much is already used.
192
202
 */
 
203
__attribute__((nonnull, warn_unused_result))
193
204
size_t incbuffer(char **buffer, size_t buffer_length,
194
205
                 size_t buffer_capacity){
195
206
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
196
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
197
 
    if(buffer == NULL){
 
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;
198
213
      return 0;
199
214
    }
 
215
    *buffer = new_buf;
200
216
    buffer_capacity += BUFFER_SIZE;
201
217
  }
202
218
  return buffer_capacity;
203
219
}
204
220
 
205
221
/* Add server to set of servers to retry periodically */
206
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
207
 
                int af){
 
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){
208
225
  int ret;
209
226
  server *new_server = malloc(sizeof(server));
210
227
  if(new_server == NULL){
217
234
                          .af = af };
218
235
  if(new_server->ip == NULL){
219
236
    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);
220
252
    return false;
221
253
  }
222
254
  /* Special case of first server */
223
 
  if (mc.current_server == NULL){
 
255
  if(*current_server == NULL){
224
256
    new_server->next = new_server;
225
257
    new_server->prev = new_server;
226
 
    mc.current_server = new_server;
227
 
  /* Place the new server last in the list */
 
258
    *current_server = new_server;
228
259
  } else {
229
 
    new_server->next = mc.current_server;
230
 
    new_server->prev = mc.current_server->prev;
 
260
    /* Place the new server last in the list */
 
261
    new_server->next = *current_server;
 
262
    new_server->prev = (*current_server)->prev;
231
263
    new_server->prev->next = new_server;
232
 
    mc.current_server->prev = new_server;
233
 
  }
234
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
235
 
  if(ret == -1){
236
 
    perror_plus("clock_gettime");
237
 
    return false;
 
264
    (*current_server)->prev = new_server;
238
265
  }
239
266
  return true;
240
267
}
242
269
/* 
243
270
 * Initialize GPGME.
244
271
 */
245
 
static bool init_gpgme(const char *seckey, const char *pubkey,
246
 
                       const char *tempdir){
 
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){
247
277
  gpgme_error_t rc;
248
278
  gpgme_engine_info_t engine_info;
249
279
  
250
 
  
251
280
  /*
252
281
   * Helper function to insert pub and seckey to the engine keyring.
253
282
   */
254
 
  bool import_key(const char *filename){
 
283
  bool import_key(const char * const filename){
255
284
    int ret;
256
285
    int fd;
257
286
    gpgme_data_t pgp_data;
269
298
      return false;
270
299
    }
271
300
    
272
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
301
    rc = gpgme_op_import(mc->ctx, pgp_data);
273
302
    if(rc != GPG_ERR_NO_ERROR){
274
303
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
275
304
                   gpgme_strsource(rc), gpgme_strerror(rc));
319
348
  }
320
349
  
321
350
  /* Create new GPGME "context" */
322
 
  rc = gpgme_new(&(mc.ctx));
 
351
  rc = gpgme_new(&(mc->ctx));
323
352
  if(rc != GPG_ERR_NO_ERROR){
324
353
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
325
354
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
338
367
 * Decrypt OpenPGP data.
339
368
 * Returns -1 on error
340
369
 */
 
370
__attribute__((nonnull, warn_unused_result))
341
371
static ssize_t pgp_packet_decrypt(const char *cryptotext,
342
372
                                  size_t crypto_size,
343
 
                                  char **plaintext){
 
373
                                  char **plaintext,
 
374
                                  mandos_context *mc){
344
375
  gpgme_data_t dh_crypto, dh_plain;
345
376
  gpgme_error_t rc;
346
377
  ssize_t ret;
372
403
  
373
404
  /* Decrypt data from the cryptotext data buffer to the plaintext
374
405
     data buffer */
375
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
406
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
376
407
  if(rc != GPG_ERR_NO_ERROR){
377
408
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
378
409
                 gpgme_strsource(rc), gpgme_strerror(rc));
379
410
    plaintext_length = -1;
380
411
    if(debug){
381
412
      gpgme_decrypt_result_t result;
382
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
413
      result = gpgme_op_decrypt_result(mc->ctx);
383
414
      if(result == NULL){
384
415
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
385
416
      } else {
462
493
  return plaintext_length;
463
494
}
464
495
 
465
 
static const char * safer_gnutls_strerror(int value){
466
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
467
 
                                               -Wunreachable-code */
 
496
__attribute__((warn_unused_result))
 
497
static const char *safer_gnutls_strerror(int value){
 
498
  const char *ret = gnutls_strerror(value);
468
499
  if(ret == NULL)
469
500
    ret = "(unknown)";
470
501
  return ret;
471
502
}
472
503
 
473
504
/* GnuTLS log function callback */
 
505
__attribute__((nonnull))
474
506
static void debuggnutls(__attribute__((unused)) int level,
475
507
                        const char* string){
476
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
477
509
}
478
510
 
 
511
__attribute__((nonnull, warn_unused_result))
479
512
static int init_gnutls_global(const char *pubkeyfilename,
480
 
                              const char *seckeyfilename){
 
513
                              const char *seckeyfilename,
 
514
                              mandos_context *mc){
481
515
  int ret;
482
516
  
483
517
  if(debug){
500
534
  }
501
535
  
502
536
  /* OpenPGP credentials */
503
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
537
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
504
538
  if(ret != GNUTLS_E_SUCCESS){
505
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
506
540
                 safer_gnutls_strerror(ret));
516
550
  }
517
551
  
518
552
  ret = gnutls_certificate_set_openpgp_key_file
519
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
553
    (mc->cred, pubkeyfilename, seckeyfilename,
520
554
     GNUTLS_OPENPGP_FMT_BASE64);
521
555
  if(ret != GNUTLS_E_SUCCESS){
522
556
    fprintf_plus(stderr,
528
562
  }
529
563
  
530
564
  /* GnuTLS server initialization */
531
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
565
  ret = gnutls_dh_params_init(&mc->dh_params);
532
566
  if(ret != GNUTLS_E_SUCCESS){
533
567
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
534
568
                 " initialization: %s\n",
535
569
                 safer_gnutls_strerror(ret));
536
570
    goto globalfail;
537
571
  }
538
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
572
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
539
573
  if(ret != GNUTLS_E_SUCCESS){
540
574
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
541
575
                 safer_gnutls_strerror(ret));
542
576
    goto globalfail;
543
577
  }
544
578
  
545
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
546
580
  
547
581
  return 0;
548
582
  
549
583
 globalfail:
550
584
  
551
 
  gnutls_certificate_free_credentials(mc.cred);
 
585
  gnutls_certificate_free_credentials(mc->cred);
552
586
  gnutls_global_deinit();
553
 
  gnutls_dh_params_deinit(mc.dh_params);
 
587
  gnutls_dh_params_deinit(mc->dh_params);
554
588
  return -1;
555
589
}
556
590
 
557
 
static int init_gnutls_session(gnutls_session_t *session){
 
591
__attribute__((nonnull, warn_unused_result))
 
592
static int init_gnutls_session(gnutls_session_t *session,
 
593
                               mandos_context *mc){
558
594
  int ret;
559
595
  /* GnuTLS session creation */
560
596
  do {
572
608
  {
573
609
    const char *err;
574
610
    do {
575
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
611
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
576
612
      if(quit_now){
577
613
        gnutls_deinit(*session);
578
614
        return -1;
589
625
  
590
626
  do {
591
627
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
592
 
                                 mc.cred);
 
628
                                 mc->cred);
593
629
    if(quit_now){
594
630
      gnutls_deinit(*session);
595
631
      return -1;
605
641
  /* ignore client certificate if any. */
606
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
607
643
  
608
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
609
645
  
610
646
  return 0;
611
647
}
614
650
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
615
651
                      __attribute__((unused)) const char *txt){}
616
652
 
 
653
/* Set effective uid to 0, return errno */
 
654
__attribute__((warn_unused_result))
 
655
error_t raise_privileges(void){
 
656
  error_t old_errno = errno;
 
657
  error_t ret_errno = 0;
 
658
  if(seteuid(0) == -1){
 
659
    ret_errno = errno;
 
660
  }
 
661
  errno = old_errno;
 
662
  return ret_errno;
 
663
}
 
664
 
 
665
/* Set effective and real user ID to 0.  Return errno. */
 
666
__attribute__((warn_unused_result))
 
667
error_t raise_privileges_permanently(void){
 
668
  error_t old_errno = errno;
 
669
  error_t ret_errno = raise_privileges();
 
670
  if(ret_errno != 0){
 
671
    errno = old_errno;
 
672
    return ret_errno;
 
673
  }
 
674
  if(setuid(0) == -1){
 
675
    ret_errno = errno;
 
676
  }
 
677
  errno = old_errno;
 
678
  return ret_errno;
 
679
}
 
680
 
 
681
/* Set effective user ID to unprivileged saved user ID */
 
682
__attribute__((warn_unused_result))
 
683
error_t lower_privileges(void){
 
684
  error_t old_errno = errno;
 
685
  error_t ret_errno = 0;
 
686
  if(seteuid(uid) == -1){
 
687
    ret_errno = errno;
 
688
  }
 
689
  errno = old_errno;
 
690
  return ret_errno;
 
691
}
 
692
 
 
693
/* Lower privileges permanently */
 
694
__attribute__((warn_unused_result))
 
695
error_t lower_privileges_permanently(void){
 
696
  error_t old_errno = errno;
 
697
  error_t ret_errno = 0;
 
698
  if(setuid(uid) == -1){
 
699
    ret_errno = errno;
 
700
  }
 
701
  errno = old_errno;
 
702
  return ret_errno;
 
703
}
 
704
 
 
705
/* Helper function to add_local_route() and remove_local_route() */
 
706
__attribute__((nonnull, warn_unused_result))
 
707
static bool add_remove_local_route(const bool add,
 
708
                                   const char *address,
 
709
                                   AvahiIfIndex if_index){
 
710
  int ret;
 
711
  char helper[] = "mandos-client-iprouteadddel";
 
712
  char add_arg[] = "add";
 
713
  char remove_arg[] = "remove";
 
714
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
715
  if(pluginhelperdir == NULL){
 
716
    if(debug){
 
717
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
718
                   " variable not set; cannot run helper\n");
 
719
    }
 
720
    return false;
 
721
  }
 
722
  
 
723
  char interface[IF_NAMESIZE];
 
724
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
725
    perror_plus("if_indextoname");
 
726
    return false;
 
727
  }
 
728
  
 
729
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
730
  if(devnull == -1){
 
731
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
732
    return false;
 
733
  }
 
734
  pid_t pid = fork();
 
735
  if(pid == 0){
 
736
    /* Child */
 
737
    /* Raise privileges */
 
738
    errno = raise_privileges_permanently();
 
739
    if(errno != 0){
 
740
      perror_plus("Failed to raise privileges");
 
741
      /* _exit(EX_NOPERM); */
 
742
    } else {
 
743
      /* Set group */
 
744
      errno = 0;
 
745
      ret = setgid(0);
 
746
      if(ret == -1){
 
747
        perror_plus("setgid");
 
748
        _exit(EX_NOPERM);
 
749
      }
 
750
      /* Reset supplementary groups */
 
751
      errno = 0;
 
752
      ret = setgroups(0, NULL);
 
753
      if(ret == -1){
 
754
        perror_plus("setgroups");
 
755
        _exit(EX_NOPERM);
 
756
      }
 
757
    }
 
758
    ret = dup2(devnull, STDIN_FILENO);
 
759
    if(ret == -1){
 
760
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
761
      _exit(EX_OSERR);
 
762
    }
 
763
    ret = close(devnull);
 
764
    if(ret == -1){
 
765
      perror_plus("close");
 
766
      _exit(EX_OSERR);
 
767
    }
 
768
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
769
    if(ret == -1){
 
770
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
771
      _exit(EX_OSERR);
 
772
    }
 
773
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
774
                                                    O_RDONLY
 
775
                                                    | O_DIRECTORY
 
776
                                                    | O_PATH
 
777
                                                    | O_CLOEXEC));
 
778
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
779
                                                   helper, O_RDONLY));
 
780
    TEMP_FAILURE_RETRY(close(helperdir_fd));
 
781
#ifdef __GNUC__
 
782
#pragma GCC diagnostic push
 
783
#pragma GCC diagnostic ignored "-Wcast-qual"
 
784
#endif
 
785
    if(fexecve(helper_fd, (char *const [])
 
786
               { helper, add ? add_arg : remove_arg, (char *)address,
 
787
                   interface, NULL }, environ) == -1){
 
788
#ifdef __GNUC__
 
789
#pragma GCC diagnostic pop
 
790
#endif
 
791
      perror_plus("fexecve");
 
792
      _exit(EXIT_FAILURE);
 
793
    }
 
794
  }
 
795
  if(pid == -1){
 
796
    perror_plus("fork");
 
797
    return false;
 
798
  }
 
799
  int status;
 
800
  pid_t pret = -1;
 
801
  errno = 0;
 
802
  do {
 
803
    pret = waitpid(pid, &status, 0);
 
804
    if(pret == -1 and errno == EINTR and quit_now){
 
805
      int errno_raising = 0;
 
806
      if((errno = raise_privileges()) != 0){
 
807
        errno_raising = errno;
 
808
        perror_plus("Failed to raise privileges in order to"
 
809
                    " kill helper program");
 
810
      }
 
811
      if(kill(pid, SIGTERM) == -1){
 
812
        perror_plus("kill");
 
813
      }
 
814
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
815
        perror_plus("Failed to lower privileges after killing"
 
816
                    " helper program");
 
817
      }
 
818
      return false;
 
819
    }
 
820
  } while(pret == -1 and errno == EINTR);
 
821
  if(pret == -1){
 
822
    perror_plus("waitpid");
 
823
    return false;
 
824
  }
 
825
  if(WIFEXITED(status)){
 
826
    if(WEXITSTATUS(status) != 0){
 
827
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
828
                   " with status %d\n", WEXITSTATUS(status));
 
829
      return false;
 
830
    }
 
831
    return true;
 
832
  }
 
833
  if(WIFSIGNALED(status)){
 
834
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
835
                 " signal %d\n", WTERMSIG(status));
 
836
    return false;
 
837
  }
 
838
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
839
  return false;
 
840
}
 
841
 
 
842
__attribute__((nonnull, warn_unused_result))
 
843
static bool add_local_route(const char *address,
 
844
                            AvahiIfIndex if_index){
 
845
  return add_remove_local_route(true, address, if_index);
 
846
}
 
847
 
 
848
__attribute__((nonnull, warn_unused_result))
 
849
static bool remove_local_route(const char *address,
 
850
                               AvahiIfIndex if_index){
 
851
  return add_remove_local_route(false, address, if_index);
 
852
}
 
853
 
617
854
/* Called when a Mandos server is found */
618
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
855
__attribute__((nonnull, warn_unused_result))
 
856
static int start_mandos_communication(const char *ip, in_port_t port,
619
857
                                      AvahiIfIndex if_index,
620
 
                                      int af){
 
858
                                      int af, mandos_context *mc){
621
859
  int ret, tcp_sd = -1;
622
860
  ssize_t sret;
623
 
  union {
624
 
    struct sockaddr_in in;
625
 
    struct sockaddr_in6 in6;
626
 
  } to;
 
861
  struct sockaddr_storage to;
627
862
  char *buffer = NULL;
628
863
  char *decrypted_buffer = NULL;
629
864
  size_t buffer_length = 0;
632
867
  int retval = -1;
633
868
  gnutls_session_t session;
634
869
  int pf;                       /* Protocol family */
 
870
  bool route_added = false;
635
871
  
636
872
  errno = 0;
637
873
  
653
889
    return -1;
654
890
  }
655
891
  
656
 
  ret = init_gnutls_session(&session);
 
892
  /* If the interface is specified and we have a list of interfaces */
 
893
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
894
    /* Check if the interface is one of the interfaces we are using */
 
895
    bool match = false;
 
896
    {
 
897
      char *interface = NULL;
 
898
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
899
                                 interface))){
 
900
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
901
          match = true;
 
902
          break;
 
903
        }
 
904
      }
 
905
    }
 
906
    if(not match){
 
907
      /* This interface does not match any in the list, so we don't
 
908
         connect to the server */
 
909
      if(debug){
 
910
        char interface[IF_NAMESIZE];
 
911
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
912
          perror_plus("if_indextoname");
 
913
        } else {
 
914
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
915
                       " \"%s\"\n",
 
916
                       if_indextoname((unsigned int)if_index,
 
917
                                      interface));
 
918
        }
 
919
      }
 
920
      return -1;
 
921
    }
 
922
  }
 
923
  
 
924
  ret = init_gnutls_session(&session, mc);
657
925
  if(ret != 0){
658
926
    return -1;
659
927
  }
660
928
  
661
929
  if(debug){
662
930
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
663
 
                 PRIu16 "\n", ip, port);
 
931
                 PRIuMAX "\n", ip, (uintmax_t)port);
664
932
  }
665
933
  
666
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
934
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
667
935
  if(tcp_sd < 0){
668
936
    int e = errno;
669
937
    perror_plus("socket");
678
946
  
679
947
  memset(&to, 0, sizeof(to));
680
948
  if(af == AF_INET6){
681
 
    to.in6.sin6_family = (sa_family_t)af;
682
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
949
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
950
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
683
951
  } else {                      /* IPv4 */
684
 
    to.in.sin_family = (sa_family_t)af;
685
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
952
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
953
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
686
954
  }
687
955
  if(ret < 0 ){
688
956
    int e = errno;
697
965
    goto mandos_end;
698
966
  }
699
967
  if(af == AF_INET6){
700
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
701
 
                                       -Wconversion and
702
 
                                       -Wunreachable-code */
703
 
    
704
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
705
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
706
 
                                -Wunreachable-code*/
 
968
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
969
    if(IN6_IS_ADDR_LINKLOCAL
 
970
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
707
971
      if(if_index == AVAHI_IF_UNSPEC){
708
972
        fprintf_plus(stderr, "An IPv6 link-local address is"
709
973
                     " incomplete without a network interface\n");
711
975
        goto mandos_end;
712
976
      }
713
977
      /* Set the network interface number as scope */
714
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
978
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
715
979
    }
716
980
  } else {
717
 
    to.in.sin_port = htons(port); /* Spurious warnings from
718
 
                                     -Wconversion and
719
 
                                     -Wunreachable-code */
 
981
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
720
982
  }
721
983
  
722
984
  if(quit_now){
730
992
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
731
993
        perror_plus("if_indextoname");
732
994
      } else {
733
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
734
 
                     "\n", ip, interface, port);
 
995
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
996
                     "\n", ip, interface, (uintmax_t)port);
735
997
      }
736
998
    } else {
737
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
738
 
                   ip, port);
 
999
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
1000
                   ip, (uintmax_t)port);
739
1001
    }
740
1002
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
741
1003
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
742
 
    const char *pcret;
743
 
    if(af == AF_INET6){
744
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
745
 
                        sizeof(addrstr));
746
 
    } else {
747
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
748
 
                        sizeof(addrstr));
749
 
    }
750
 
    if(pcret == NULL){
751
 
      perror_plus("inet_ntop");
752
 
    } else {
753
 
      if(strcmp(addrstr, ip) != 0){
754
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
755
 
      }
756
 
    }
757
 
  }
758
 
  
759
 
  if(quit_now){
760
 
    errno = EINTR;
761
 
    goto mandos_end;
762
 
  }
763
 
  
764
 
  if(af == AF_INET6){
765
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
766
 
  } else {
767
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
768
 
  }
769
 
  if(ret < 0){
770
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
771
 
      int e = errno;
772
 
      perror_plus("connect");
773
 
      errno = e;
774
 
    }
775
 
    goto mandos_end;
776
 
  }
777
 
  
778
 
  if(quit_now){
779
 
    errno = EINTR;
780
 
    goto mandos_end;
 
1004
    if(af == AF_INET6){
 
1005
      ret = getnameinfo((struct sockaddr *)&to,
 
1006
                        sizeof(struct sockaddr_in6),
 
1007
                        addrstr, sizeof(addrstr), NULL, 0,
 
1008
                        NI_NUMERICHOST);
 
1009
    } else {
 
1010
      ret = getnameinfo((struct sockaddr *)&to,
 
1011
                        sizeof(struct sockaddr_in),
 
1012
                        addrstr, sizeof(addrstr), NULL, 0,
 
1013
                        NI_NUMERICHOST);
 
1014
    }
 
1015
    if(ret == EAI_SYSTEM){
 
1016
      perror_plus("getnameinfo");
 
1017
    } else if(ret != 0) {
 
1018
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
1019
    } else if(strcmp(addrstr, ip) != 0){
 
1020
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
1021
    }
 
1022
  }
 
1023
  
 
1024
  if(quit_now){
 
1025
    errno = EINTR;
 
1026
    goto mandos_end;
 
1027
  }
 
1028
  
 
1029
  while(true){
 
1030
    if(af == AF_INET6){
 
1031
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1032
                    sizeof(struct sockaddr_in6));
 
1033
    } else {
 
1034
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1035
                    sizeof(struct sockaddr_in));
 
1036
    }
 
1037
    if(ret < 0){
 
1038
      if(errno == ENETUNREACH
 
1039
         and if_index != AVAHI_IF_UNSPEC
 
1040
         and connect_to == NULL
 
1041
         and not route_added and
 
1042
         ((af == AF_INET6 and not
 
1043
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1044
                                    &to)->sin6_addr)))
 
1045
          or (af == AF_INET and
 
1046
              /* Not a a IPv4LL address */
 
1047
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1048
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1049
        /* Work around Avahi bug - Avahi does not announce link-local
 
1050
           addresses if it has a global address, so local hosts with
 
1051
           *only* a link-local address (e.g. Mandos clients) cannot
 
1052
           connect to a Mandos server announced by Avahi on a server
 
1053
           host with a global address.  Work around this by retrying
 
1054
           with an explicit route added with the server's address.
 
1055
           
 
1056
           Avahi bug reference:
 
1057
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1058
           https://bugs.debian.org/587961
 
1059
        */
 
1060
        int e = errno;
 
1061
        route_added = add_local_route(ip, if_index);
 
1062
        if(route_added){
 
1063
          continue;
 
1064
        }
 
1065
        errno = e;
 
1066
      }
 
1067
      if(errno != ECONNREFUSED or debug){
 
1068
        int e = errno;
 
1069
        perror_plus("connect");
 
1070
        errno = e;
 
1071
      }
 
1072
      goto mandos_end;
 
1073
    }
 
1074
    
 
1075
    if(quit_now){
 
1076
      errno = EINTR;
 
1077
      goto mandos_end;
 
1078
    }
 
1079
    break;
781
1080
  }
782
1081
  
783
1082
  const char *out = mandos_protocol_version;
819
1118
    goto mandos_end;
820
1119
  }
821
1120
  
822
 
  /* Spurious warning from -Wint-to-pointer-cast */
823
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
1121
  /* This casting via intptr_t is to eliminate warning about casting
 
1122
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
1123
     function "set-session-transport-fd!" does it. */
 
1124
  gnutls_transport_set_ptr(session,
 
1125
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
824
1126
  
825
1127
  if(quit_now){
826
1128
    errno = EINTR;
931
1233
  if(buffer_length > 0){
932
1234
    ssize_t decrypted_buffer_size;
933
1235
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
934
 
                                               &decrypted_buffer);
 
1236
                                               &decrypted_buffer, mc);
935
1237
    if(decrypted_buffer_size >= 0){
936
1238
      
937
1239
      written = 0;
963
1265
  
964
1266
 mandos_end:
965
1267
  {
 
1268
    if(route_added){
 
1269
      if(not remove_local_route(ip, if_index)){
 
1270
        fprintf_plus(stderr, "Failed to remove local route to %s on"
 
1271
                     " interface %d", ip, if_index);
 
1272
      }
 
1273
    }
966
1274
    int e = errno;
967
1275
    free(decrypted_buffer);
968
1276
    free(buffer);
985
1293
  return retval;
986
1294
}
987
1295
 
 
1296
__attribute__((nonnull))
988
1297
static void resolve_callback(AvahiSServiceResolver *r,
989
1298
                             AvahiIfIndex interface,
990
1299
                             AvahiProtocol proto,
998
1307
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
999
1308
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1000
1309
                             flags,
1001
 
                             AVAHI_GCC_UNUSED void* userdata){
1002
 
  assert(r);
 
1310
                             void *mc){
 
1311
  if(r == NULL){
 
1312
    return;
 
1313
  }
1003
1314
  
1004
1315
  /* Called whenever a service has been resolved successfully or
1005
1316
     timed out */
1006
1317
  
1007
1318
  if(quit_now){
 
1319
    avahi_s_service_resolver_free(r);
1008
1320
    return;
1009
1321
  }
1010
1322
  
1014
1326
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1015
1327
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1016
1328
                 domain,
1017
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1329
                 avahi_strerror(avahi_server_errno
 
1330
                                (((mandos_context*)mc)->server)));
1018
1331
    break;
1019
1332
    
1020
1333
  case AVAHI_RESOLVER_FOUND:
1026
1339
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1027
1340
                     host_name, ip, (intmax_t)interface, port);
1028
1341
      }
1029
 
      int ret = start_mandos_communication(ip, port, interface,
1030
 
                                           avahi_proto_to_af(proto));
 
1342
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1343
                                           interface,
 
1344
                                           avahi_proto_to_af(proto),
 
1345
                                           mc);
1031
1346
      if(ret == 0){
1032
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1347
        avahi_simple_poll_quit(simple_poll);
1033
1348
      } else {
1034
 
        if(not add_server(ip, port, interface,
1035
 
                          avahi_proto_to_af(proto))){
 
1349
        if(not add_server(ip, (in_port_t)port, interface,
 
1350
                          avahi_proto_to_af(proto),
 
1351
                          &((mandos_context*)mc)->current_server)){
1036
1352
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1037
1353
                       " list\n", name);
1038
1354
        }
1051
1367
                            const char *domain,
1052
1368
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1053
1369
                            flags,
1054
 
                            AVAHI_GCC_UNUSED void* userdata){
1055
 
  assert(b);
 
1370
                            void *mc){
 
1371
  if(b == NULL){
 
1372
    return;
 
1373
  }
1056
1374
  
1057
1375
  /* Called whenever a new services becomes available on the LAN or
1058
1376
     is removed from the LAN */
1066
1384
  case AVAHI_BROWSER_FAILURE:
1067
1385
    
1068
1386
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1069
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1070
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1387
                 avahi_strerror(avahi_server_errno
 
1388
                                (((mandos_context*)mc)->server)));
 
1389
    avahi_simple_poll_quit(simple_poll);
1071
1390
    return;
1072
1391
    
1073
1392
  case AVAHI_BROWSER_NEW:
1076
1395
       the callback function is called the Avahi server will free the
1077
1396
       resolver for us. */
1078
1397
    
1079
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1080
 
                                    name, type, domain, protocol, 0,
1081
 
                                    resolve_callback, NULL) == NULL)
 
1398
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1399
                                    interface, protocol, name, type,
 
1400
                                    domain, protocol, 0,
 
1401
                                    resolve_callback, mc) == NULL)
1082
1402
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1083
1403
                   " %s\n", name,
1084
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1404
                   avahi_strerror(avahi_server_errno
 
1405
                                  (((mandos_context*)mc)->server)));
1085
1406
    break;
1086
1407
    
1087
1408
  case AVAHI_BROWSER_REMOVE:
1106
1427
  signal_received = sig;
1107
1428
  int old_errno = errno;
1108
1429
  /* set main loop to exit */
1109
 
  if(mc.simple_poll != NULL){
1110
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1430
  if(simple_poll != NULL){
 
1431
    avahi_simple_poll_quit(simple_poll);
1111
1432
  }
1112
1433
  errno = old_errno;
1113
1434
}
1114
1435
 
 
1436
__attribute__((nonnull, warn_unused_result))
1115
1437
bool get_flags(const char *ifname, struct ifreq *ifr){
1116
1438
  int ret;
 
1439
  error_t ret_errno;
1117
1440
  
1118
1441
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1119
1442
  if(s < 0){
 
1443
    ret_errno = errno;
1120
1444
    perror_plus("socket");
 
1445
    errno = ret_errno;
1121
1446
    return false;
1122
1447
  }
1123
1448
  strcpy(ifr->ifr_name, ifname);
1124
1449
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1125
1450
  if(ret == -1){
1126
1451
    if(debug){
 
1452
      ret_errno = errno;
1127
1453
      perror_plus("ioctl SIOCGIFFLAGS");
 
1454
      errno = ret_errno;
1128
1455
    }
1129
1456
    return false;
1130
1457
  }
1131
1458
  return true;
1132
1459
}
1133
1460
 
 
1461
__attribute__((nonnull, warn_unused_result))
1134
1462
bool good_flags(const char *ifname, const struct ifreq *ifr){
1135
1463
  
1136
1464
  /* Reject the loopback device */
1178
1506
 * corresponds to an acceptable network device.
1179
1507
 * (This function is passed to scandir(3) as a filter function.)
1180
1508
 */
 
1509
__attribute__((nonnull, warn_unused_result))
1181
1510
int good_interface(const struct dirent *if_entry){
1182
1511
  if(if_entry->d_name[0] == '.'){
1183
1512
    return 0;
1199
1528
}
1200
1529
 
1201
1530
/* 
1202
 
 * This function determines if a directory entry in /sys/class/net
1203
 
 * corresponds to an acceptable network device which is up.
1204
 
 * (This function is passed to scandir(3) as a filter function.)
1205
 
 */
1206
 
int up_interface(const struct dirent *if_entry){
1207
 
  if(if_entry->d_name[0] == '.'){
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  struct ifreq ifr;
1212
 
  if(not get_flags(if_entry->d_name, &ifr)){
1213
 
    if(debug){
1214
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1215
 
                   "\"%s\"\n", if_entry->d_name);
1216
 
    }
1217
 
    return 0;
1218
 
  }
1219
 
  
1220
 
  /* Reject down interfaces */
1221
 
  if(not (ifr.ifr_flags & IFF_UP)){
1222
 
    if(debug){
1223
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1224
 
                   if_entry->d_name);
1225
 
    }
1226
 
    return 0;
1227
 
  }
1228
 
  
1229
 
  /* Reject non-running interfaces */
1230
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1231
 
    if(debug){
1232
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1233
 
                   if_entry->d_name);
1234
 
    }
1235
 
    return 0;
1236
 
  }
1237
 
  
1238
 
  if(not good_flags(if_entry->d_name, &ifr)){
1239
 
    return 0;
1240
 
  }
1241
 
  return 1;
1242
 
}
1243
 
 
 
1531
 * This function determines if a network interface is up.
 
1532
 */
 
1533
__attribute__((nonnull, warn_unused_result))
 
1534
bool interface_is_up(const char *interface){
 
1535
  struct ifreq ifr;
 
1536
  if(not get_flags(interface, &ifr)){
 
1537
    if(debug){
 
1538
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1539
                   "\"%s\"\n", interface);
 
1540
    }
 
1541
    return false;
 
1542
  }
 
1543
  
 
1544
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1545
}
 
1546
 
 
1547
/* 
 
1548
 * This function determines if a network interface is running
 
1549
 */
 
1550
__attribute__((nonnull, warn_unused_result))
 
1551
bool interface_is_running(const char *interface){
 
1552
  struct ifreq ifr;
 
1553
  if(not get_flags(interface, &ifr)){
 
1554
    if(debug){
 
1555
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1556
                   "\"%s\"\n", interface);
 
1557
    }
 
1558
    return false;
 
1559
  }
 
1560
  
 
1561
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
 
1562
}
 
1563
 
 
1564
__attribute__((nonnull, pure, warn_unused_result))
1244
1565
int notdotentries(const struct dirent *direntry){
1245
1566
  /* Skip "." and ".." */
1246
1567
  if(direntry->d_name[0] == '.'
1253
1574
}
1254
1575
 
1255
1576
/* Is this directory entry a runnable program? */
 
1577
__attribute__((nonnull, warn_unused_result))
1256
1578
int runnable_hook(const struct dirent *direntry){
1257
1579
  int ret;
1258
1580
  size_t sret;
1266
1588
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1267
1589
                "abcdefghijklmnopqrstuvwxyz"
1268
1590
                "0123456789"
1269
 
                "_-");
 
1591
                "_.-");
1270
1592
  if((direntry->d_name)[sret] != '\0'){
1271
1593
    /* Contains non-allowed characters */
1272
1594
    if(debug){
1276
1598
    return 0;
1277
1599
  }
1278
1600
  
1279
 
  char *fullname = NULL;
1280
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1281
 
  if(ret < 0){
1282
 
    perror_plus("asprintf");
1283
 
    return 0;
1284
 
  }
1285
 
  
1286
 
  ret = stat(fullname, &st);
 
1601
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1287
1602
  if(ret == -1){
1288
1603
    if(debug){
1289
1604
      perror_plus("Could not stat hook");
1313
1628
  return 1;
1314
1629
}
1315
1630
 
1316
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1631
__attribute__((nonnull, warn_unused_result))
 
1632
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1633
                            mandos_context *mc){
1317
1634
  int ret;
1318
1635
  struct timespec now;
1319
1636
  struct timespec waited_time;
1320
1637
  intmax_t block_time;
1321
1638
  
1322
1639
  while(true){
1323
 
    if(mc.current_server == NULL){
1324
 
      if (debug){
 
1640
    if(mc->current_server == NULL){
 
1641
      if(debug){
1325
1642
        fprintf_plus(stderr, "Wait until first server is found."
1326
1643
                     " No timeout!\n");
1327
1644
      }
1328
1645
      ret = avahi_simple_poll_iterate(s, -1);
1329
1646
    } else {
1330
 
      if (debug){
 
1647
      if(debug){
1331
1648
        fprintf_plus(stderr, "Check current_server if we should run"
1332
1649
                     " it, or wait\n");
1333
1650
      }
1340
1657
      /* Calculating in ms how long time between now and server
1341
1658
         who we visted longest time ago. Now - last seen.  */
1342
1659
      waited_time.tv_sec = (now.tv_sec
1343
 
                            - mc.current_server->last_seen.tv_sec);
 
1660
                            - mc->current_server->last_seen.tv_sec);
1344
1661
      waited_time.tv_nsec = (now.tv_nsec
1345
 
                             - mc.current_server->last_seen.tv_nsec);
 
1662
                             - mc->current_server->last_seen.tv_nsec);
1346
1663
      /* total time is 10s/10,000ms.
1347
1664
         Converting to s from ms by dividing by 1,000,
1348
1665
         and ns to ms by dividing by 1,000,000. */
1350
1667
                     - ((intmax_t)waited_time.tv_sec * 1000))
1351
1668
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1352
1669
      
1353
 
      if (debug){
 
1670
      if(debug){
1354
1671
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1355
1672
                     block_time);
1356
1673
      }
1357
1674
      
1358
1675
      if(block_time <= 0){
1359
 
        ret = start_mandos_communication(mc.current_server->ip,
1360
 
                                         mc.current_server->port,
1361
 
                                         mc.current_server->if_index,
1362
 
                                         mc.current_server->af);
 
1676
        ret = start_mandos_communication(mc->current_server->ip,
 
1677
                                         mc->current_server->port,
 
1678
                                         mc->current_server->if_index,
 
1679
                                         mc->current_server->af, mc);
1363
1680
        if(ret == 0){
1364
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1681
          avahi_simple_poll_quit(s);
1365
1682
          return 0;
1366
1683
        }
1367
1684
        ret = clock_gettime(CLOCK_MONOTONIC,
1368
 
                            &mc.current_server->last_seen);
 
1685
                            &mc->current_server->last_seen);
1369
1686
        if(ret == -1){
1370
1687
          perror_plus("clock_gettime");
1371
1688
          return -1;
1372
1689
        }
1373
 
        mc.current_server = mc.current_server->next;
 
1690
        mc->current_server = mc->current_server->next;
1374
1691
        block_time = 0;         /* Call avahi to find new Mandos
1375
1692
                                   servers, but don't block */
1376
1693
      }
1378
1695
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1379
1696
    }
1380
1697
    if(ret != 0){
1381
 
      if (ret > 0 or errno != EINTR){
 
1698
      if(ret > 0 or errno != EINTR){
1382
1699
        return (ret != 1) ? ret : 0;
1383
1700
      }
1384
1701
    }
1385
1702
  }
1386
1703
}
1387
1704
 
1388
 
bool run_network_hooks(const char *mode, const char *interface,
 
1705
__attribute__((nonnull))
 
1706
void run_network_hooks(const char *mode, const char *interface,
1389
1707
                       const float delay){
1390
 
  struct dirent **direntries;
1391
 
  struct dirent *direntry;
1392
 
  int ret;
1393
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1394
 
                         alphasort);
 
1708
  struct dirent **direntries = NULL;
 
1709
  if(hookdir_fd == -1){
 
1710
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1711
                      | O_CLOEXEC);
 
1712
    if(hookdir_fd == -1){
 
1713
      if(errno == ENOENT){
 
1714
        if(debug){
 
1715
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1716
                       " found\n", hookdir);
 
1717
        }
 
1718
      } else {
 
1719
        perror_plus("open");
 
1720
      }
 
1721
      return;
 
1722
    }
 
1723
  }
 
1724
#ifdef __GLIBC__
 
1725
#if __GLIBC_PREREQ(2, 15)
 
1726
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1727
                           runnable_hook, alphasort);
 
1728
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1729
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1730
                         alphasort);
 
1731
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1732
#else   /* not __GLIBC__ */
 
1733
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1734
                         alphasort);
 
1735
#endif  /* not __GLIBC__ */
1395
1736
  if(numhooks == -1){
1396
1737
    perror_plus("scandir");
1397
 
  } else {
1398
 
    int devnull = open("/dev/null", O_RDONLY);
1399
 
    for(int i = 0; i < numhooks; i++){
1400
 
      direntry = direntries[i];
1401
 
      char *fullname = NULL;
1402
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1403
 
      if(ret < 0){
 
1738
    return;
 
1739
  }
 
1740
  struct dirent *direntry;
 
1741
  int ret;
 
1742
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1743
  if(devnull == -1){
 
1744
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1745
    return;
 
1746
  }
 
1747
  for(int i = 0; i < numhooks; i++){
 
1748
    direntry = direntries[i];
 
1749
    if(debug){
 
1750
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1751
                   direntry->d_name);
 
1752
    }
 
1753
    pid_t hook_pid = fork();
 
1754
    if(hook_pid == 0){
 
1755
      /* Child */
 
1756
      /* Raise privileges */
 
1757
      errno = raise_privileges_permanently();
 
1758
      if(errno != 0){
 
1759
        perror_plus("Failed to raise privileges");
 
1760
        _exit(EX_NOPERM);
 
1761
      }
 
1762
      /* Set group */
 
1763
      errno = 0;
 
1764
      ret = setgid(0);
 
1765
      if(ret == -1){
 
1766
        perror_plus("setgid");
 
1767
        _exit(EX_NOPERM);
 
1768
      }
 
1769
      /* Reset supplementary groups */
 
1770
      errno = 0;
 
1771
      ret = setgroups(0, NULL);
 
1772
      if(ret == -1){
 
1773
        perror_plus("setgroups");
 
1774
        _exit(EX_NOPERM);
 
1775
      }
 
1776
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1777
      if(ret == -1){
 
1778
        perror_plus("setenv");
 
1779
        _exit(EX_OSERR);
 
1780
      }
 
1781
      ret = setenv("DEVICE", interface, 1);
 
1782
      if(ret == -1){
 
1783
        perror_plus("setenv");
 
1784
        _exit(EX_OSERR);
 
1785
      }
 
1786
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1787
      if(ret == -1){
 
1788
        perror_plus("setenv");
 
1789
        _exit(EX_OSERR);
 
1790
      }
 
1791
      ret = setenv("MODE", mode, 1);
 
1792
      if(ret == -1){
 
1793
        perror_plus("setenv");
 
1794
        _exit(EX_OSERR);
 
1795
      }
 
1796
      char *delaystring;
 
1797
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1798
      if(ret == -1){
1404
1799
        perror_plus("asprintf");
1405
 
        continue;
1406
 
      }
1407
 
      if(debug){
1408
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1409
 
                     direntry->d_name);
1410
 
      }
1411
 
      pid_t hook_pid = fork();
1412
 
      if(hook_pid == 0){
1413
 
        /* Child */
1414
 
        /* Raise privileges */
1415
 
        errno = 0;
1416
 
        ret = seteuid(0);
1417
 
        if(ret == -1){
1418
 
          perror_plus("seteuid");
1419
 
        }
1420
 
        /* Raise privileges even more */
1421
 
        errno = 0;
1422
 
        ret = setuid(0);
1423
 
        if(ret == -1){
1424
 
          perror_plus("setuid");
1425
 
        }
1426
 
        /* Set group */
1427
 
        errno = 0;
1428
 
        ret = setgid(0);
1429
 
        if(ret == -1){
1430
 
          perror_plus("setgid");
1431
 
        }
1432
 
        /* Reset supplementary groups */
1433
 
        errno = 0;
1434
 
        ret = setgroups(0, NULL);
1435
 
        if(ret == -1){
1436
 
          perror_plus("setgroups");
1437
 
        }
1438
 
        dup2(devnull, STDIN_FILENO);
1439
 
        close(devnull);
1440
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1441
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1442
 
        if(ret == -1){
1443
 
          perror_plus("setenv");
1444
 
          _exit(EX_OSERR);
1445
 
        }
1446
 
        ret = setenv("DEVICE", interface, 1);
1447
 
        if(ret == -1){
1448
 
          perror_plus("setenv");
1449
 
          _exit(EX_OSERR);
1450
 
        }
1451
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1452
 
        if(ret == -1){
1453
 
          perror_plus("setenv");
1454
 
          _exit(EX_OSERR);
1455
 
        }
1456
 
        ret = setenv("MODE", mode, 1);
1457
 
        if(ret == -1){
1458
 
          perror_plus("setenv");
1459
 
          _exit(EX_OSERR);
1460
 
        }
1461
 
        char *delaystring;
1462
 
        ret = asprintf(&delaystring, "%f", delay);
1463
 
        if(ret == -1){
1464
 
          perror_plus("asprintf");
1465
 
          _exit(EX_OSERR);
1466
 
        }
1467
 
        ret = setenv("DELAY", delaystring, 1);
1468
 
        if(ret == -1){
1469
 
          free(delaystring);
1470
 
          perror_plus("setenv");
1471
 
          _exit(EX_OSERR);
1472
 
        }
 
1800
        _exit(EX_OSERR);
 
1801
      }
 
1802
      ret = setenv("DELAY", delaystring, 1);
 
1803
      if(ret == -1){
1473
1804
        free(delaystring);
1474
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1475
 
          perror_plus("execl");
1476
 
          _exit(EXIT_FAILURE);
1477
 
        }
1478
 
      } else {
1479
 
        int status;
1480
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1481
 
          perror_plus("waitpid");
1482
 
          free(fullname);
1483
 
          continue;
1484
 
        }
1485
 
        if(WIFEXITED(status)){
1486
 
          if(WEXITSTATUS(status) != 0){
1487
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1488
 
                         " with status %d\n", direntry->d_name,
1489
 
                         WEXITSTATUS(status));
1490
 
            free(fullname);
1491
 
            continue;
1492
 
          }
1493
 
        } else if(WIFSIGNALED(status)){
1494
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1495
 
                       " signal %d\n", direntry->d_name,
1496
 
                       WTERMSIG(status));
1497
 
          free(fullname);
1498
 
          continue;
1499
 
        } else {
1500
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1501
 
                       " crashed\n", direntry->d_name);
1502
 
          free(fullname);
1503
 
          continue;
1504
 
        }
1505
 
      }
1506
 
      free(fullname);
1507
 
      if(debug){
1508
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1509
 
                     direntry->d_name);
1510
 
      }
1511
 
    }
1512
 
    close(devnull);
1513
 
  }
1514
 
  return true;
 
1805
        perror_plus("setenv");
 
1806
        _exit(EX_OSERR);
 
1807
      }
 
1808
      free(delaystring);
 
1809
      if(connect_to != NULL){
 
1810
        ret = setenv("CONNECT", connect_to, 1);
 
1811
        if(ret == -1){
 
1812
          perror_plus("setenv");
 
1813
          _exit(EX_OSERR);
 
1814
        }
 
1815
      }
 
1816
      int hook_fd = TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1817
                                              direntry->d_name,
 
1818
                                              O_RDONLY));
 
1819
      if(hook_fd == -1){
 
1820
        perror_plus("openat");
 
1821
        _exit(EXIT_FAILURE);
 
1822
      }
 
1823
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1824
        perror_plus("close");
 
1825
        _exit(EXIT_FAILURE);
 
1826
      }
 
1827
      ret = dup2(devnull, STDIN_FILENO);
 
1828
      if(ret == -1){
 
1829
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1830
        _exit(EX_OSERR);
 
1831
      }
 
1832
      ret = close(devnull);
 
1833
      if(ret == -1){
 
1834
        perror_plus("close");
 
1835
        _exit(EX_OSERR);
 
1836
      }
 
1837
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1838
      if(ret == -1){
 
1839
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1840
        _exit(EX_OSERR);
 
1841
      }
 
1842
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
1843
                 environ) == -1){
 
1844
        perror_plus("fexecve");
 
1845
        _exit(EXIT_FAILURE);
 
1846
      }
 
1847
    } else {
 
1848
      if(hook_pid == -1){
 
1849
        perror_plus("fork");
 
1850
        free(direntry);
 
1851
        continue;
 
1852
      }
 
1853
      int status;
 
1854
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1855
        perror_plus("waitpid");
 
1856
        free(direntry);
 
1857
        continue;
 
1858
      }
 
1859
      if(WIFEXITED(status)){
 
1860
        if(WEXITSTATUS(status) != 0){
 
1861
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1862
                       " with status %d\n", direntry->d_name,
 
1863
                       WEXITSTATUS(status));
 
1864
          free(direntry);
 
1865
          continue;
 
1866
        }
 
1867
      } else if(WIFSIGNALED(status)){
 
1868
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1869
                     " signal %d\n", direntry->d_name,
 
1870
                     WTERMSIG(status));
 
1871
        free(direntry);
 
1872
        continue;
 
1873
      } else {
 
1874
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1875
                     " crashed\n", direntry->d_name);
 
1876
        free(direntry);
 
1877
        continue;
 
1878
      }
 
1879
    }
 
1880
    if(debug){
 
1881
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1882
                   direntry->d_name);
 
1883
    }
 
1884
    free(direntry);
 
1885
  }
 
1886
  free(direntries);
 
1887
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1888
    perror_plus("close");
 
1889
  } else {
 
1890
    hookdir_fd = -1;
 
1891
  }
 
1892
  close(devnull);
 
1893
}
 
1894
 
 
1895
__attribute__((nonnull, warn_unused_result))
 
1896
error_t bring_up_interface(const char *const interface,
 
1897
                           const float delay){
 
1898
  error_t old_errno = errno;
 
1899
  int ret;
 
1900
  struct ifreq network;
 
1901
  unsigned int if_index = if_nametoindex(interface);
 
1902
  if(if_index == 0){
 
1903
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1904
    errno = old_errno;
 
1905
    return ENXIO;
 
1906
  }
 
1907
  
 
1908
  if(quit_now){
 
1909
    errno = old_errno;
 
1910
    return EINTR;
 
1911
  }
 
1912
  
 
1913
  if(not interface_is_up(interface)){
 
1914
    error_t ret_errno = 0, ioctl_errno = 0;
 
1915
    if(not get_flags(interface, &network)){
 
1916
      ret_errno = errno;
 
1917
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1918
                   "\"%s\"\n", interface);
 
1919
      errno = old_errno;
 
1920
      return ret_errno;
 
1921
    }
 
1922
    network.ifr_flags |= IFF_UP; /* set flag */
 
1923
    
 
1924
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1925
    if(sd == -1){
 
1926
      ret_errno = errno;
 
1927
      perror_plus("socket");
 
1928
      errno = old_errno;
 
1929
      return ret_errno;
 
1930
    }
 
1931
    
 
1932
    if(quit_now){
 
1933
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1934
      if(ret == -1){
 
1935
        perror_plus("close");
 
1936
      }
 
1937
      errno = old_errno;
 
1938
      return EINTR;
 
1939
    }
 
1940
    
 
1941
    if(debug){
 
1942
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1943
                   interface);
 
1944
    }
 
1945
    
 
1946
    /* Raise privileges */
 
1947
    ret_errno = raise_privileges();
 
1948
    if(ret_errno != 0){
 
1949
      errno = ret_errno;
 
1950
      perror_plus("Failed to raise privileges");
 
1951
    }
 
1952
    
 
1953
#ifdef __linux__
 
1954
    int ret_linux;
 
1955
    bool restore_loglevel = false;
 
1956
    if(ret_errno == 0){
 
1957
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1958
         messages about the network interface to mess up the prompt */
 
1959
      ret_linux = klogctl(8, NULL, 5);
 
1960
      if(ret_linux == -1){
 
1961
        perror_plus("klogctl");
 
1962
      } else {
 
1963
        restore_loglevel = true;
 
1964
      }
 
1965
    }
 
1966
#endif  /* __linux__ */
 
1967
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1968
    ioctl_errno = errno;
 
1969
#ifdef __linux__
 
1970
    if(restore_loglevel){
 
1971
      ret_linux = klogctl(7, NULL, 0);
 
1972
      if(ret_linux == -1){
 
1973
        perror_plus("klogctl");
 
1974
      }
 
1975
    }
 
1976
#endif  /* __linux__ */
 
1977
    
 
1978
    /* If raise_privileges() succeeded above */
 
1979
    if(ret_errno == 0){
 
1980
      /* Lower privileges */
 
1981
      ret_errno = lower_privileges();
 
1982
      if(ret_errno != 0){
 
1983
        errno = ret_errno;
 
1984
        perror_plus("Failed to lower privileges");
 
1985
      }
 
1986
    }
 
1987
    
 
1988
    /* Close the socket */
 
1989
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1990
    if(ret == -1){
 
1991
      perror_plus("close");
 
1992
    }
 
1993
    
 
1994
    if(ret_setflags == -1){
 
1995
      errno = ioctl_errno;
 
1996
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1997
      errno = old_errno;
 
1998
      return ioctl_errno;
 
1999
    }
 
2000
  } else if(debug){
 
2001
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
2002
                 interface);
 
2003
  }
 
2004
  
 
2005
  /* Sleep checking until interface is running.
 
2006
     Check every 0.25s, up to total time of delay */
 
2007
  for(int i=0; i < delay * 4; i++){
 
2008
    if(interface_is_running(interface)){
 
2009
      break;
 
2010
    }
 
2011
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
2012
    ret = nanosleep(&sleeptime, NULL);
 
2013
    if(ret == -1 and errno != EINTR){
 
2014
      perror_plus("nanosleep");
 
2015
    }
 
2016
  }
 
2017
  
 
2018
  errno = old_errno;
 
2019
  return 0;
 
2020
}
 
2021
 
 
2022
__attribute__((nonnull, warn_unused_result))
 
2023
error_t take_down_interface(const char *const interface){
 
2024
  error_t old_errno = errno;
 
2025
  struct ifreq network;
 
2026
  unsigned int if_index = if_nametoindex(interface);
 
2027
  if(if_index == 0){
 
2028
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
2029
    errno = old_errno;
 
2030
    return ENXIO;
 
2031
  }
 
2032
  if(interface_is_up(interface)){
 
2033
    error_t ret_errno = 0, ioctl_errno = 0;
 
2034
    if(not get_flags(interface, &network) and debug){
 
2035
      ret_errno = errno;
 
2036
      fprintf_plus(stderr, "Failed to get flags for interface "
 
2037
                   "\"%s\"\n", interface);
 
2038
      errno = old_errno;
 
2039
      return ret_errno;
 
2040
    }
 
2041
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2042
    
 
2043
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
2044
    if(sd == -1){
 
2045
      ret_errno = errno;
 
2046
      perror_plus("socket");
 
2047
      errno = old_errno;
 
2048
      return ret_errno;
 
2049
    }
 
2050
    
 
2051
    if(debug){
 
2052
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
2053
                   interface);
 
2054
    }
 
2055
    
 
2056
    /* Raise privileges */
 
2057
    ret_errno = raise_privileges();
 
2058
    if(ret_errno != 0){
 
2059
      errno = ret_errno;
 
2060
      perror_plus("Failed to raise privileges");
 
2061
    }
 
2062
    
 
2063
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
2064
    ioctl_errno = errno;
 
2065
    
 
2066
    /* If raise_privileges() succeeded above */
 
2067
    if(ret_errno == 0){
 
2068
      /* Lower privileges */
 
2069
      ret_errno = lower_privileges();
 
2070
      if(ret_errno != 0){
 
2071
        errno = ret_errno;
 
2072
        perror_plus("Failed to lower privileges");
 
2073
      }
 
2074
    }
 
2075
    
 
2076
    /* Close the socket */
 
2077
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2078
    if(ret == -1){
 
2079
      perror_plus("close");
 
2080
    }
 
2081
    
 
2082
    if(ret_setflags == -1){
 
2083
      errno = ioctl_errno;
 
2084
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2085
      errno = old_errno;
 
2086
      return ioctl_errno;
 
2087
    }
 
2088
  } else if(debug){
 
2089
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
2090
                 interface);
 
2091
  }
 
2092
  
 
2093
  errno = old_errno;
 
2094
  return 0;
1515
2095
}
1516
2096
 
1517
2097
int main(int argc, char *argv[]){
 
2098
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
2099
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2100
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
2101
                        .interfaces = NULL, .interfaces_size = 0 };
1518
2102
  AvahiSServiceBrowser *sb = NULL;
1519
 
  int error;
 
2103
  error_t ret_errno;
1520
2104
  int ret;
1521
2105
  intmax_t tmpmax;
1522
2106
  char *tmp;
1523
2107
  int exitcode = EXIT_SUCCESS;
1524
 
  const char *interface = "";
1525
 
  struct ifreq network;
1526
 
  int sd = -1;
1527
 
  bool take_down_interface = false;
1528
 
  uid_t uid;
1529
 
  gid_t gid;
1530
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1531
 
  bool tempdir_created = false;
 
2108
  char *interfaces_to_take_down = NULL;
 
2109
  size_t interfaces_to_take_down_size = 0;
 
2110
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
2111
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
2112
  char *tempdir = NULL;
1532
2113
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1533
2114
  const char *seckey = PATHDIR "/" SECKEY;
1534
2115
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2116
  char *interfaces_hooks = NULL;
1535
2117
  
1536
2118
  bool gnutls_initialized = false;
1537
2119
  bool gpgme_initialized = false;
1599
2181
        .group = 2 },
1600
2182
      { .name = "retry", .key = 132,
1601
2183
        .arg = "SECONDS",
1602
 
        .doc = "Retry interval used when denied by the mandos server",
 
2184
        .doc = "Retry interval used when denied by the Mandos server",
1603
2185
        .group = 2 },
1604
2186
      { .name = "network-hook-dir", .key = 133,
1605
2187
        .arg = "DIR",
1628
2210
        connect_to = arg;
1629
2211
        break;
1630
2212
      case 'i':                 /* --interface */
1631
 
        interface = arg;
 
2213
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
2214
                                 arg, (int)',');
 
2215
        if(ret_errno != 0){
 
2216
          argp_error(state, "%s", strerror(ret_errno));
 
2217
        }
1632
2218
        break;
1633
2219
      case 's':                 /* --seckey */
1634
2220
        seckey = arg;
1706
2292
      goto end;
1707
2293
    }
1708
2294
  }
1709
 
    
 
2295
  
1710
2296
  {
1711
2297
    /* Work around Debian bug #633582:
1712
2298
       <http://bugs.debian.org/633582> */
1713
2299
    
1714
 
    /* Re-raise priviliges */
1715
 
    errno = 0;
1716
 
    ret = seteuid(0);
1717
 
    if(ret == -1){
1718
 
      perror_plus("seteuid");
 
2300
    /* Re-raise privileges */
 
2301
    ret_errno = raise_privileges();
 
2302
    if(ret_errno != 0){
 
2303
      errno = ret_errno;
 
2304
      perror_plus("Failed to raise privileges");
1719
2305
    } else {
1720
2306
      struct stat st;
1721
2307
      
1739
2325
          TEMP_FAILURE_RETRY(close(seckey_fd));
1740
2326
        }
1741
2327
      }
1742
 
    
 
2328
      
1743
2329
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1744
2330
        int pubkey_fd = open(pubkey, O_RDONLY);
1745
2331
        if(pubkey_fd == -1){
1760
2346
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1761
2347
        }
1762
2348
      }
1763
 
    
 
2349
      
1764
2350
      /* Lower privileges */
1765
 
      errno = 0;
1766
 
      ret = seteuid(uid);
1767
 
      if(ret == -1){
1768
 
        perror_plus("seteuid");
 
2351
      ret_errno = lower_privileges();
 
2352
      if(ret_errno != 0){
 
2353
        errno = ret_errno;
 
2354
        perror_plus("Failed to lower privileges");
 
2355
      }
 
2356
    }
 
2357
  }
 
2358
  
 
2359
  /* Remove invalid interface names (except "none") */
 
2360
  {
 
2361
    char *interface = NULL;
 
2362
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2363
                                 interface))){
 
2364
      if(strcmp(interface, "none") != 0
 
2365
         and if_nametoindex(interface) == 0){
 
2366
        if(interface[0] != '\0'){
 
2367
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2368
                       " \"%s\"\n", interface);
 
2369
        }
 
2370
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2371
        interface = NULL;
1769
2372
      }
1770
2373
    }
1771
2374
  }
1772
2375
  
1773
2376
  /* Run network hooks */
1774
 
  if(not run_network_hooks("start", interface, delay)){
1775
 
    goto end;
 
2377
  {
 
2378
    if(mc.interfaces != NULL){
 
2379
      interfaces_hooks = malloc(mc.interfaces_size);
 
2380
      if(interfaces_hooks == NULL){
 
2381
        perror_plus("malloc");
 
2382
        goto end;
 
2383
      }
 
2384
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2385
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2386
    }
 
2387
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2388
                      interfaces_hooks : "", delay);
1776
2389
  }
1777
2390
  
1778
2391
  if(not debug){
1779
2392
    avahi_set_log_function(empty_log);
1780
2393
  }
1781
2394
  
1782
 
  if(interface[0] == '\0'){
1783
 
    struct dirent **direntries;
1784
 
    /* First look for interfaces that are up */
1785
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1786
 
                  alphasort);
1787
 
    if(ret == 0){
1788
 
      /* No up interfaces, look for any good interfaces */
1789
 
      free(direntries);
1790
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1791
 
                    alphasort);
1792
 
    }
1793
 
    if(ret >= 1){
1794
 
      /* Pick the first interface returned */
1795
 
      interface = strdup(direntries[0]->d_name);
1796
 
      if(debug){
1797
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1798
 
      }
1799
 
      if(interface == NULL){
1800
 
        perror_plus("malloc");
1801
 
        free(direntries);
1802
 
        exitcode = EXIT_FAILURE;
1803
 
        goto end;
1804
 
      }
1805
 
      free(direntries);
1806
 
    } else {
1807
 
      free(direntries);
1808
 
      fprintf_plus(stderr, "Could not find a network interface\n");
1809
 
      exitcode = EXIT_FAILURE;
1810
 
      goto end;
1811
 
    }
1812
 
  }
1813
 
  
1814
2395
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1815
2396
     from the signal handler */
1816
2397
  /* Initialize the pseudo-RNG for Avahi */
1817
2398
  srand((unsigned int) time(NULL));
1818
 
  mc.simple_poll = avahi_simple_poll_new();
1819
 
  if(mc.simple_poll == NULL){
 
2399
  simple_poll = avahi_simple_poll_new();
 
2400
  if(simple_poll == NULL){
1820
2401
    fprintf_plus(stderr,
1821
2402
                 "Avahi: Failed to create simple poll object.\n");
1822
2403
    exitcode = EX_UNAVAILABLE;
1886
2467
    }
1887
2468
  }
1888
2469
  
1889
 
  /* If the interface is down, bring it up */
1890
 
  if(strcmp(interface, "none") != 0){
1891
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1892
 
    if(if_index == 0){
1893
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1894
 
      exitcode = EX_UNAVAILABLE;
1895
 
      goto end;
1896
 
    }
1897
 
    
1898
 
    if(quit_now){
1899
 
      goto end;
1900
 
    }
1901
 
    
1902
 
    /* Re-raise priviliges */
1903
 
    errno = 0;
1904
 
    ret = seteuid(0);
1905
 
    if(ret == -1){
1906
 
      perror_plus("seteuid");
1907
 
    }
1908
 
    
1909
 
#ifdef __linux__
1910
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1911
 
       messages about the network interface to mess up the prompt */
1912
 
    ret = klogctl(8, NULL, 5);
1913
 
    bool restore_loglevel = true;
1914
 
    if(ret == -1){
1915
 
      restore_loglevel = false;
1916
 
      perror_plus("klogctl");
1917
 
    }
1918
 
#endif  /* __linux__ */
1919
 
    
1920
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1921
 
    if(sd < 0){
1922
 
      perror_plus("socket");
1923
 
      exitcode = EX_OSERR;
1924
 
#ifdef __linux__
1925
 
      if(restore_loglevel){
1926
 
        ret = klogctl(7, NULL, 0);
1927
 
        if(ret == -1){
1928
 
          perror_plus("klogctl");
1929
 
        }
1930
 
      }
1931
 
#endif  /* __linux__ */
1932
 
      /* Lower privileges */
1933
 
      errno = 0;
1934
 
      ret = seteuid(uid);
1935
 
      if(ret == -1){
1936
 
        perror_plus("seteuid");
1937
 
      }
1938
 
      goto end;
1939
 
    }
1940
 
    strcpy(network.ifr_name, interface);
1941
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1942
 
    if(ret == -1){
1943
 
      perror_plus("ioctl SIOCGIFFLAGS");
1944
 
#ifdef __linux__
1945
 
      if(restore_loglevel){
1946
 
        ret = klogctl(7, NULL, 0);
1947
 
        if(ret == -1){
1948
 
          perror_plus("klogctl");
1949
 
        }
1950
 
      }
1951
 
#endif  /* __linux__ */
1952
 
      exitcode = EX_OSERR;
1953
 
      /* Lower privileges */
1954
 
      errno = 0;
1955
 
      ret = seteuid(uid);
1956
 
      if(ret == -1){
1957
 
        perror_plus("seteuid");
1958
 
      }
1959
 
      goto end;
1960
 
    }
1961
 
    if((network.ifr_flags & IFF_UP) == 0){
1962
 
      network.ifr_flags |= IFF_UP;
1963
 
      take_down_interface = true;
1964
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1965
 
      if(ret == -1){
1966
 
        take_down_interface = false;
1967
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1968
 
        exitcode = EX_OSERR;
1969
 
#ifdef __linux__
1970
 
        if(restore_loglevel){
1971
 
          ret = klogctl(7, NULL, 0);
1972
 
          if(ret == -1){
1973
 
            perror_plus("klogctl");
 
2470
  /* If no interfaces were specified, make a list */
 
2471
  if(mc.interfaces == NULL){
 
2472
    struct dirent **direntries = NULL;
 
2473
    /* Look for any good interfaces */
 
2474
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2475
                  alphasort);
 
2476
    if(ret >= 1){
 
2477
      /* Add all found interfaces to interfaces list */
 
2478
      for(int i = 0; i < ret; ++i){
 
2479
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2480
                             direntries[i]->d_name);
 
2481
        if(ret_errno != 0){
 
2482
          errno = ret_errno;
 
2483
          perror_plus("argz_add");
 
2484
          free(direntries[i]);
 
2485
          continue;
 
2486
        }
 
2487
        if(debug){
 
2488
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2489
                       direntries[i]->d_name);
 
2490
        }
 
2491
        free(direntries[i]);
 
2492
      }
 
2493
      free(direntries);
 
2494
    } else {
 
2495
      if(ret == 0){
 
2496
        free(direntries);
 
2497
      }
 
2498
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2499
      exitcode = EXIT_FAILURE;
 
2500
      goto end;
 
2501
    }
 
2502
  }
 
2503
  
 
2504
  /* Bring up interfaces which are down, and remove any "none"s */
 
2505
  {
 
2506
    char *interface = NULL;
 
2507
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2508
                                 interface))){
 
2509
      /* If interface name is "none", stop bringing up interfaces.
 
2510
         Also remove all instances of "none" from the list */
 
2511
      if(strcmp(interface, "none") == 0){
 
2512
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2513
                    interface);
 
2514
        interface = NULL;
 
2515
        while((interface = argz_next(mc.interfaces,
 
2516
                                     mc.interfaces_size, interface))){
 
2517
          if(strcmp(interface, "none") == 0){
 
2518
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2519
                        interface);
 
2520
            interface = NULL;
1974
2521
          }
1975
2522
        }
1976
 
#endif  /* __linux__ */
1977
 
        /* Lower privileges */
1978
 
        errno = 0;
1979
 
        ret = seteuid(uid);
1980
 
        if(ret == -1){
1981
 
          perror_plus("seteuid");
1982
 
        }
1983
 
        goto end;
1984
 
      }
1985
 
    }
1986
 
    /* Sleep checking until interface is running.
1987
 
       Check every 0.25s, up to total time of delay */
1988
 
    for(int i=0; i < delay * 4; i++){
1989
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1990
 
      if(ret == -1){
1991
 
        perror_plus("ioctl SIOCGIFFLAGS");
1992
 
      } else if(network.ifr_flags & IFF_RUNNING){
1993
2523
        break;
1994
2524
      }
1995
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1996
 
      ret = nanosleep(&sleeptime, NULL);
1997
 
      if(ret == -1 and errno != EINTR){
1998
 
        perror_plus("nanosleep");
1999
 
      }
2000
 
    }
2001
 
    if(not take_down_interface){
2002
 
      /* We won't need the socket anymore */
2003
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2004
 
      if(ret == -1){
2005
 
        perror_plus("close");
2006
 
      }
2007
 
    }
2008
 
#ifdef __linux__
2009
 
    if(restore_loglevel){
2010
 
      /* Restores kernel loglevel to default */
2011
 
      ret = klogctl(7, NULL, 0);
2012
 
      if(ret == -1){
2013
 
        perror_plus("klogctl");
2014
 
      }
2015
 
    }
2016
 
#endif  /* __linux__ */
2017
 
    /* Lower privileges */
2018
 
    errno = 0;
2019
 
    /* Lower privileges */
2020
 
    ret = seteuid(uid);
2021
 
    if(ret == -1){
2022
 
      perror_plus("seteuid");
2023
 
    }
 
2525
      bool interface_was_up = interface_is_up(interface);
 
2526
      errno = bring_up_interface(interface, delay);
 
2527
      if(not interface_was_up){
 
2528
        if(errno != 0){
 
2529
          perror_plus("Failed to bring up interface");
 
2530
        } else {
 
2531
          errno = argz_add(&interfaces_to_take_down,
 
2532
                           &interfaces_to_take_down_size,
 
2533
                           interface);
 
2534
          if(errno != 0){
 
2535
            perror_plus("argz_add");
 
2536
          }
 
2537
        }
 
2538
      }
 
2539
    }
 
2540
    if(debug and (interfaces_to_take_down == NULL)){
 
2541
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2542
    }
 
2543
  }
 
2544
  
 
2545
  /* If we only got one interface, explicitly use only that one */
 
2546
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2547
    if(debug){
 
2548
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2549
                   mc.interfaces);
 
2550
    }
 
2551
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2024
2552
  }
2025
2553
  
2026
2554
  if(quit_now){
2027
2555
    goto end;
2028
2556
  }
2029
2557
  
2030
 
  ret = init_gnutls_global(pubkey, seckey);
 
2558
  ret = init_gnutls_global(pubkey, seckey, &mc);
2031
2559
  if(ret == -1){
2032
2560
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2033
2561
    exitcode = EX_UNAVAILABLE;
2040
2568
    goto end;
2041
2569
  }
2042
2570
  
2043
 
  if(mkdtemp(tempdir) == NULL){
 
2571
  /* Try /run/tmp before /tmp */
 
2572
  tempdir = mkdtemp(run_tempdir);
 
2573
  if(tempdir == NULL and errno == ENOENT){
 
2574
      if(debug){
 
2575
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2576
                     run_tempdir, old_tempdir);
 
2577
      }
 
2578
      tempdir = mkdtemp(old_tempdir);
 
2579
  }
 
2580
  if(tempdir == NULL){
2044
2581
    perror_plus("mkdtemp");
2045
2582
    goto end;
2046
2583
  }
2047
 
  tempdir_created = true;
2048
2584
  
2049
2585
  if(quit_now){
2050
2586
    goto end;
2051
2587
  }
2052
2588
  
2053
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2589
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2054
2590
    fprintf_plus(stderr, "init_gpgme failed\n");
2055
2591
    exitcode = EX_UNAVAILABLE;
2056
2592
    goto end;
2066
2602
    /* Connect directly, do not use Zeroconf */
2067
2603
    /* (Mainly meant for debugging) */
2068
2604
    char *address = strrchr(connect_to, ':');
 
2605
    
2069
2606
    if(address == NULL){
2070
2607
      fprintf_plus(stderr, "No colon in address\n");
2071
2608
      exitcode = EX_USAGE;
2076
2613
      goto end;
2077
2614
    }
2078
2615
    
2079
 
    uint16_t port;
 
2616
    in_port_t port;
2080
2617
    errno = 0;
2081
2618
    tmpmax = strtoimax(address+1, &tmp, 10);
2082
2619
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2083
 
       or tmpmax != (uint16_t)tmpmax){
 
2620
       or tmpmax != (in_port_t)tmpmax){
2084
2621
      fprintf_plus(stderr, "Bad port number\n");
2085
2622
      exitcode = EX_USAGE;
2086
2623
      goto end;
2087
2624
    }
2088
 
  
 
2625
    
2089
2626
    if(quit_now){
2090
2627
      goto end;
2091
2628
    }
2092
2629
    
2093
 
    port = (uint16_t)tmpmax;
 
2630
    port = (in_port_t)tmpmax;
2094
2631
    *address = '\0';
2095
2632
    /* Colon in address indicates IPv6 */
2096
2633
    int af;
2112
2649
    }
2113
2650
    
2114
2651
    while(not quit_now){
2115
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2652
      ret = start_mandos_communication(address, port, if_index, af,
 
2653
                                       &mc);
2116
2654
      if(quit_now or ret == 0){
2117
2655
        break;
2118
2656
      }
2120
2658
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2121
2659
                     (int)retry_interval);
2122
2660
      }
2123
 
      sleep((int)retry_interval);
 
2661
      sleep((unsigned int)retry_interval);
2124
2662
    }
2125
2663
    
2126
 
    if (not quit_now){
 
2664
    if(not quit_now){
2127
2665
      exitcode = EXIT_SUCCESS;
2128
2666
    }
2129
2667
    
2144
2682
    config.publish_domain = 0;
2145
2683
    
2146
2684
    /* Allocate a new server */
2147
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2148
 
                                 (mc.simple_poll), &config, NULL,
2149
 
                                 NULL, &error);
 
2685
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2686
                                 &config, NULL, NULL, &ret_errno);
2150
2687
    
2151
2688
    /* Free the Avahi configuration data */
2152
2689
    avahi_server_config_free(&config);
2155
2692
  /* Check if creating the Avahi server object succeeded */
2156
2693
  if(mc.server == NULL){
2157
2694
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2158
 
                 avahi_strerror(error));
 
2695
                 avahi_strerror(ret_errno));
2159
2696
    exitcode = EX_UNAVAILABLE;
2160
2697
    goto end;
2161
2698
  }
2167
2704
  /* Create the Avahi service browser */
2168
2705
  sb = avahi_s_service_browser_new(mc.server, if_index,
2169
2706
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2170
 
                                   NULL, 0, browse_callback, NULL);
 
2707
                                   NULL, 0, browse_callback,
 
2708
                                   (void *)&mc);
2171
2709
  if(sb == NULL){
2172
2710
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2173
2711
                 avahi_strerror(avahi_server_errno(mc.server)));
2184
2722
  if(debug){
2185
2723
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2186
2724
  }
2187
 
 
2188
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2189
 
                                (int)(retry_interval * 1000));
 
2725
  
 
2726
  ret = avahi_loop_with_timeout(simple_poll,
 
2727
                                (int)(retry_interval * 1000), &mc);
2190
2728
  if(debug){
2191
2729
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2192
2730
                 (ret == 0) ? "successfully" : "with error");
2199
2737
  }
2200
2738
  
2201
2739
  /* Cleanup things */
 
2740
  free(mc.interfaces);
 
2741
  
2202
2742
  if(sb != NULL)
2203
2743
    avahi_s_service_browser_free(sb);
2204
2744
  
2205
2745
  if(mc.server != NULL)
2206
2746
    avahi_server_free(mc.server);
2207
2747
  
2208
 
  if(mc.simple_poll != NULL)
2209
 
    avahi_simple_poll_free(mc.simple_poll);
 
2748
  if(simple_poll != NULL)
 
2749
    avahi_simple_poll_free(simple_poll);
2210
2750
  
2211
2751
  if(gnutls_initialized){
2212
2752
    gnutls_certificate_free_credentials(mc.cred);
2224
2764
    mc.current_server->prev->next = NULL;
2225
2765
    while(mc.current_server != NULL){
2226
2766
      server *next = mc.current_server->next;
 
2767
#ifdef __GNUC__
 
2768
#pragma GCC diagnostic push
 
2769
#pragma GCC diagnostic ignored "-Wcast-qual"
 
2770
#endif
 
2771
      free((char *)(mc.current_server->ip));
 
2772
#ifdef __GNUC__
 
2773
#pragma GCC diagnostic pop
 
2774
#endif
2227
2775
      free(mc.current_server);
2228
2776
      mc.current_server = next;
2229
2777
    }
2230
2778
  }
2231
2779
  
2232
 
  /* Run network hooks */
2233
 
  run_network_hooks("stop", interface, delay);
2234
 
  
2235
 
  /* Re-raise priviliges */
 
2780
  /* Re-raise privileges */
2236
2781
  {
2237
 
    errno = 0;
2238
 
    ret = seteuid(0);
2239
 
    if(ret == -1){
2240
 
      perror_plus("seteuid");
 
2782
    ret_errno = raise_privileges();
 
2783
    if(ret_errno != 0){
 
2784
      errno = ret_errno;
 
2785
      perror_plus("Failed to raise privileges");
 
2786
    } else {
 
2787
      
 
2788
      /* Run network hooks */
 
2789
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2790
                        interfaces_hooks : "", delay);
 
2791
      
 
2792
      /* Take down the network interfaces which were brought up */
 
2793
      {
 
2794
        char *interface = NULL;
 
2795
        while((interface=argz_next(interfaces_to_take_down,
 
2796
                                   interfaces_to_take_down_size,
 
2797
                                   interface))){
 
2798
          ret_errno = take_down_interface(interface);
 
2799
          if(ret_errno != 0){
 
2800
            errno = ret_errno;
 
2801
            perror_plus("Failed to take down interface");
 
2802
          }
 
2803
        }
 
2804
        if(debug and (interfaces_to_take_down == NULL)){
 
2805
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2806
                       " down\n");
 
2807
        }
 
2808
      }
2241
2809
    }
2242
2810
    
2243
 
    /* Take down the network interface */
2244
 
    if(take_down_interface and geteuid() == 0){
2245
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2246
 
      if(ret == -1){
2247
 
        perror_plus("ioctl SIOCGIFFLAGS");
2248
 
      } else if(network.ifr_flags & IFF_UP){
2249
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2250
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2251
 
        if(ret == -1){
2252
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2253
 
        }
2254
 
      }
2255
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2256
 
      if(ret == -1){
2257
 
        perror_plus("close");
2258
 
      }
 
2811
    ret_errno = lower_privileges_permanently();
 
2812
    if(ret_errno != 0){
 
2813
      errno = ret_errno;
 
2814
      perror_plus("Failed to lower privileges permanently");
2259
2815
    }
2260
2816
  }
2261
 
  /* Lower privileges permanently */
2262
 
  errno = 0;
2263
 
  ret = setuid(uid);
2264
 
  if(ret == -1){
2265
 
    perror_plus("setuid");
2266
 
  }
 
2817
  
 
2818
  free(interfaces_to_take_down);
 
2819
  free(interfaces_hooks);
2267
2820
  
2268
2821
  /* Removes the GPGME temp directory and all files inside */
2269
 
  if(tempdir_created){
 
2822
  if(tempdir != NULL){
2270
2823
    struct dirent **direntries = NULL;
2271
 
    struct dirent *direntry = NULL;
2272
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2273
 
                             alphasort);
2274
 
    if (numentries > 0){
2275
 
      for(int i = 0; i < numentries; i++){
2276
 
        direntry = direntries[i];
2277
 
        char *fullname = NULL;
2278
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2279
 
                       direntry->d_name);
2280
 
        if(ret < 0){
2281
 
          perror_plus("asprintf");
2282
 
          continue;
2283
 
        }
2284
 
        ret = remove(fullname);
2285
 
        if(ret == -1){
2286
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2287
 
                       strerror(errno));
2288
 
        }
2289
 
        free(fullname);
 
2824
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
2825
                                                  | O_NOFOLLOW
 
2826
                                                  | O_DIRECTORY
 
2827
                                                  | O_PATH));
 
2828
    if(tempdir_fd == -1){
 
2829
      perror_plus("open");
 
2830
    } else {
 
2831
#ifdef __GLIBC__
 
2832
#if __GLIBC_PREREQ(2, 15)
 
2833
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2834
                                 notdotentries, alphasort);
 
2835
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2836
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2837
                               alphasort);
 
2838
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2839
#else   /* not __GLIBC__ */
 
2840
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2841
                               alphasort);
 
2842
#endif  /* not __GLIBC__ */
 
2843
      if(numentries >= 0){
 
2844
        for(int i = 0; i < numentries; i++){
 
2845
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2846
          if(ret == -1){
 
2847
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2848
                         " \"%s\", 0): %s\n", tempdir,
 
2849
                         direntries[i]->d_name, strerror(errno));
 
2850
          }
 
2851
          free(direntries[i]);
 
2852
        }
 
2853
        
 
2854
        /* need to clean even if 0 because man page doesn't specify */
 
2855
        free(direntries);
 
2856
        if(numentries == -1){
 
2857
          perror_plus("scandir");
 
2858
        }
 
2859
        ret = rmdir(tempdir);
 
2860
        if(ret == -1 and errno != ENOENT){
 
2861
          perror_plus("rmdir");
 
2862
        }
2290
2863
      }
2291
 
    }
2292
 
 
2293
 
    /* need to clean even if 0 because man page doesn't specify */
2294
 
    free(direntries);
2295
 
    if (numentries == -1){
2296
 
      perror_plus("scandir");
2297
 
    }
2298
 
    ret = rmdir(tempdir);
2299
 
    if(ret == -1 and errno != ENOENT){
2300
 
      perror_plus("rmdir");
 
2864
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2301
2865
    }
2302
2866
  }
2303
2867