/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-03-10 07:04:09 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 311.
  • Revision ID: teddy@recompile.se-20140310070409-ho6p1wrnpopi2ny1
White space fix: change "if (" to "if(" in C code.

* plugins.d/askpass-fifo.c (error_plus): White space fix.
* plugins.d/password-prompt.c (error_plus, conflict_detection,
                               main): - '' -
* plugins.d/plymouth.c (error_plus, exec_and_wait, get_pid): - '' -
* plugins.d/splashy.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

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-2013 Teddy Hogeborn
 
13
 * Copyright © 2008-2013 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
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
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() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
59
60
#include <fcntl.h>              /* open() */
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() */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
76
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_state, struct argp,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
 
91
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
92
                                   argz_delete(), argz_append(),
 
93
                                   argz_stringify(), argz_add(),
 
94
                                   argz_count() */
 
95
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
96
                                   EAI_SYSTEM, gai_strerror() */
90
97
 
91
98
#ifdef __linux__
92
99
#include <sys/klog.h>           /* klogctl() */
134
141
static const char sys_class_net[] = "/sys/class/net";
135
142
char *connect_to = NULL;
136
143
const char *hookdir = HOOKDIR;
 
144
uid_t uid = 65534;
 
145
gid_t gid = 65534;
137
146
 
138
147
/* Doubly linked list that need to be circularly linked when used */
139
148
typedef struct server{
140
149
  const char *ip;
141
 
  uint16_t port;
 
150
  in_port_t port;
142
151
  AvahiIfIndex if_index;
143
152
  int af;
144
153
  struct timespec last_seen;
148
157
 
149
158
/* Used for passing in values through the Avahi callback functions */
150
159
typedef struct {
151
 
  AvahiSimplePoll *simple_poll;
152
160
  AvahiServer *server;
153
161
  gnutls_certificate_credentials_t cred;
154
162
  unsigned int dh_bits;
156
164
  const char *priority;
157
165
  gpgme_ctx_t ctx;
158
166
  server *current_server;
 
167
  char *interfaces;
 
168
  size_t interfaces_size;
159
169
} mandos_context;
160
170
 
161
 
/* global context so signal handler can reach it*/
162
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
 
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
171
/* global so signal handler can reach it*/
 
172
AvahiSimplePoll *simple_poll;
166
173
 
167
174
sig_atomic_t quit_now = 0;
168
175
int signal_received = 0;
169
176
 
170
177
/* Function to use when printing errors */
171
178
void perror_plus(const char *print_text){
 
179
  int e = errno;
172
180
  fprintf(stderr, "Mandos plugin %s: ",
173
181
          program_invocation_short_name);
 
182
  errno = e;
174
183
  perror(print_text);
175
184
}
176
185
 
 
186
__attribute__((format (gnu_printf, 2, 3)))
177
187
int fprintf_plus(FILE *stream, const char *format, ...){
178
188
  va_list ap;
179
189
  va_start (ap, format);
180
190
  
181
191
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
182
192
                             program_invocation_short_name));
183
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
193
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
184
194
}
185
195
 
186
196
/*
191
201
size_t incbuffer(char **buffer, size_t buffer_length,
192
202
                 size_t buffer_capacity){
193
203
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
194
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
195
 
    if(buffer == NULL){
 
204
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
205
    if(new_buf == NULL){
 
206
      int old_errno = errno;
 
207
      free(*buffer);
 
208
      errno = old_errno;
 
209
      *buffer = NULL;
196
210
      return 0;
197
211
    }
 
212
    *buffer = new_buf;
198
213
    buffer_capacity += BUFFER_SIZE;
199
214
  }
200
215
  return buffer_capacity;
201
216
}
202
217
 
203
218
/* Add server to set of servers to retry periodically */
204
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
205
 
               int af){
 
219
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
220
                int af, server **current_server){
206
221
  int ret;
207
222
  server *new_server = malloc(sizeof(server));
208
223
  if(new_server == NULL){
209
224
    perror_plus("malloc");
210
 
    return -1;
 
225
    return false;
211
226
  }
212
227
  *new_server = (server){ .ip = strdup(ip),
213
228
                          .port = port,
215
230
                          .af = af };
216
231
  if(new_server->ip == NULL){
217
232
    perror_plus("strdup");
218
 
    return -1;
 
233
    return false;
 
234
  }
 
235
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
236
  if(ret == -1){
 
237
    perror_plus("clock_gettime");
 
238
    return false;
219
239
  }
220
240
  /* Special case of first server */
221
 
  if (mc.current_server == NULL){
 
241
  if(*current_server == NULL){
222
242
    new_server->next = new_server;
223
243
    new_server->prev = new_server;
224
 
    mc.current_server = new_server;
 
244
    *current_server = new_server;
225
245
  /* Place the new server last in the list */
226
246
  } else {
227
 
    new_server->next = mc.current_server;
228
 
    new_server->prev = mc.current_server->prev;
 
247
    new_server->next = *current_server;
 
248
    new_server->prev = (*current_server)->prev;
229
249
    new_server->prev->next = new_server;
230
 
    mc.current_server->prev = new_server;
231
 
  }
232
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
233
 
  if(ret == -1){
234
 
    perror_plus("clock_gettime");
235
 
    return -1;
236
 
  }
237
 
  return 0;
 
250
    (*current_server)->prev = new_server;
 
251
  }
 
252
  return true;
238
253
}
239
254
 
240
255
/* 
241
256
 * Initialize GPGME.
242
257
 */
243
258
static bool init_gpgme(const char *seckey, const char *pubkey,
244
 
                       const char *tempdir){
 
259
                       const char *tempdir, mandos_context *mc){
245
260
  gpgme_error_t rc;
246
261
  gpgme_engine_info_t engine_info;
247
262
  
248
 
  
249
263
  /*
250
264
   * Helper function to insert pub and seckey to the engine keyring.
251
265
   */
267
281
      return false;
268
282
    }
269
283
    
270
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
284
    rc = gpgme_op_import(mc->ctx, pgp_data);
271
285
    if(rc != GPG_ERR_NO_ERROR){
272
286
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
273
287
                   gpgme_strsource(rc), gpgme_strerror(rc));
317
331
  }
318
332
  
319
333
  /* Create new GPGME "context" */
320
 
  rc = gpgme_new(&(mc.ctx));
 
334
  rc = gpgme_new(&(mc->ctx));
321
335
  if(rc != GPG_ERR_NO_ERROR){
322
336
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
323
337
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
338
352
 */
339
353
static ssize_t pgp_packet_decrypt(const char *cryptotext,
340
354
                                  size_t crypto_size,
341
 
                                  char **plaintext){
 
355
                                  char **plaintext,
 
356
                                  mandos_context *mc){
342
357
  gpgme_data_t dh_crypto, dh_plain;
343
358
  gpgme_error_t rc;
344
359
  ssize_t ret;
370
385
  
371
386
  /* Decrypt data from the cryptotext data buffer to the plaintext
372
387
     data buffer */
373
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
388
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
374
389
  if(rc != GPG_ERR_NO_ERROR){
375
390
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
376
391
                 gpgme_strsource(rc), gpgme_strerror(rc));
377
392
    plaintext_length = -1;
378
393
    if(debug){
379
394
      gpgme_decrypt_result_t result;
380
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
395
      result = gpgme_op_decrypt_result(mc->ctx);
381
396
      if(result == NULL){
382
397
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
383
398
      } else {
461
476
}
462
477
 
463
478
static const char * safer_gnutls_strerror(int value){
464
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
465
 
                                               -Wunreachable-code */
 
479
  const char *ret = gnutls_strerror(value);
466
480
  if(ret == NULL)
467
481
    ret = "(unknown)";
468
482
  return ret;
475
489
}
476
490
 
477
491
static int init_gnutls_global(const char *pubkeyfilename,
478
 
                              const char *seckeyfilename){
 
492
                              const char *seckeyfilename,
 
493
                              mandos_context *mc){
479
494
  int ret;
480
495
  
481
496
  if(debug){
498
513
  }
499
514
  
500
515
  /* OpenPGP credentials */
501
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
516
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
502
517
  if(ret != GNUTLS_E_SUCCESS){
503
518
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
504
519
                 safer_gnutls_strerror(ret));
514
529
  }
515
530
  
516
531
  ret = gnutls_certificate_set_openpgp_key_file
517
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
532
    (mc->cred, pubkeyfilename, seckeyfilename,
518
533
     GNUTLS_OPENPGP_FMT_BASE64);
519
534
  if(ret != GNUTLS_E_SUCCESS){
520
535
    fprintf_plus(stderr,
526
541
  }
527
542
  
528
543
  /* GnuTLS server initialization */
529
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
544
  ret = gnutls_dh_params_init(&mc->dh_params);
530
545
  if(ret != GNUTLS_E_SUCCESS){
531
546
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
532
547
                 " initialization: %s\n",
533
548
                 safer_gnutls_strerror(ret));
534
549
    goto globalfail;
535
550
  }
536
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
551
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
537
552
  if(ret != GNUTLS_E_SUCCESS){
538
553
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
539
554
                 safer_gnutls_strerror(ret));
540
555
    goto globalfail;
541
556
  }
542
557
  
543
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
558
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
544
559
  
545
560
  return 0;
546
561
  
547
562
 globalfail:
548
563
  
549
 
  gnutls_certificate_free_credentials(mc.cred);
 
564
  gnutls_certificate_free_credentials(mc->cred);
550
565
  gnutls_global_deinit();
551
 
  gnutls_dh_params_deinit(mc.dh_params);
 
566
  gnutls_dh_params_deinit(mc->dh_params);
552
567
  return -1;
553
568
}
554
569
 
555
 
static int init_gnutls_session(gnutls_session_t *session){
 
570
static int init_gnutls_session(gnutls_session_t *session,
 
571
                               mandos_context *mc){
556
572
  int ret;
557
573
  /* GnuTLS session creation */
558
574
  do {
570
586
  {
571
587
    const char *err;
572
588
    do {
573
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
589
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
574
590
      if(quit_now){
575
591
        gnutls_deinit(*session);
576
592
        return -1;
587
603
  
588
604
  do {
589
605
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
590
 
                                 mc.cred);
 
606
                                 mc->cred);
591
607
    if(quit_now){
592
608
      gnutls_deinit(*session);
593
609
      return -1;
603
619
  /* ignore client certificate if any. */
604
620
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
605
621
  
606
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
622
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
607
623
  
608
624
  return 0;
609
625
}
613
629
                      __attribute__((unused)) const char *txt){}
614
630
 
615
631
/* Called when a Mandos server is found */
616
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
632
static int start_mandos_communication(const char *ip, in_port_t port,
617
633
                                      AvahiIfIndex if_index,
618
 
                                      int af){
 
634
                                      int af, mandos_context *mc){
619
635
  int ret, tcp_sd = -1;
620
636
  ssize_t sret;
621
 
  union {
622
 
    struct sockaddr_in in;
623
 
    struct sockaddr_in6 in6;
624
 
  } to;
 
637
  struct sockaddr_storage to;
625
638
  char *buffer = NULL;
626
639
  char *decrypted_buffer = NULL;
627
640
  size_t buffer_length = 0;
651
664
    return -1;
652
665
  }
653
666
  
654
 
  ret = init_gnutls_session(&session);
 
667
  /* If the interface is specified and we have a list of interfaces */
 
668
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
669
    /* Check if the interface is one of the interfaces we are using */
 
670
    bool match = false;
 
671
    {
 
672
      char *interface = NULL;
 
673
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
674
                                 interface))){
 
675
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
676
          match = true;
 
677
          break;
 
678
        }
 
679
      }
 
680
    }
 
681
    if(not match){
 
682
      /* This interface does not match any in the list, so we don't
 
683
         connect to the server */
 
684
      if(debug){
 
685
        char interface[IF_NAMESIZE];
 
686
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
687
          perror_plus("if_indextoname");
 
688
        } else {
 
689
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
690
                       " \"%s\"\n",
 
691
                       if_indextoname((unsigned int)if_index,
 
692
                                      interface));
 
693
        }
 
694
      }
 
695
      return -1;
 
696
    }
 
697
  }
 
698
  
 
699
  ret = init_gnutls_session(&session, mc);
655
700
  if(ret != 0){
656
701
    return -1;
657
702
  }
658
703
  
659
704
  if(debug){
660
705
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
661
 
                 PRIu16 "\n", ip, port);
 
706
                 PRIuMAX "\n", ip, (uintmax_t)port);
662
707
  }
663
708
  
664
709
  tcp_sd = socket(pf, SOCK_STREAM, 0);
676
721
  
677
722
  memset(&to, 0, sizeof(to));
678
723
  if(af == AF_INET6){
679
 
    to.in6.sin6_family = (sa_family_t)af;
680
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
724
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
725
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
681
726
  } else {                      /* IPv4 */
682
 
    to.in.sin_family = (sa_family_t)af;
683
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
727
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
728
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
684
729
  }
685
730
  if(ret < 0 ){
686
731
    int e = errno;
695
740
    goto mandos_end;
696
741
  }
697
742
  if(af == AF_INET6){
698
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
699
 
                                       -Wconversion and
700
 
                                       -Wunreachable-code */
701
 
    
702
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
703
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
704
 
                                -Wunreachable-code*/
 
743
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);    
 
744
    if(IN6_IS_ADDR_LINKLOCAL
 
745
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
705
746
      if(if_index == AVAHI_IF_UNSPEC){
706
747
        fprintf_plus(stderr, "An IPv6 link-local address is"
707
748
                     " incomplete without a network interface\n");
709
750
        goto mandos_end;
710
751
      }
711
752
      /* Set the network interface number as scope */
712
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
753
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
713
754
    }
714
755
  } else {
715
 
    to.in.sin_port = htons(port); /* Spurious warnings from
716
 
                                     -Wconversion and
717
 
                                     -Wunreachable-code */
 
756
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
718
757
  }
719
758
  
720
759
  if(quit_now){
728
767
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
729
768
        perror_plus("if_indextoname");
730
769
      } else {
731
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
732
 
                     "\n", ip, interface, port);
 
770
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
771
                     "\n", ip, interface, (uintmax_t)port);
733
772
      }
734
773
    } else {
735
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
736
 
                   ip, port);
 
774
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
775
                   ip, (uintmax_t)port);
737
776
    }
738
777
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
739
778
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
740
 
    const char *pcret;
741
779
    if(af == AF_INET6){
742
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
743
 
                        sizeof(addrstr));
 
780
      ret = getnameinfo((struct sockaddr *)&to,
 
781
                        sizeof(struct sockaddr_in6),
 
782
                        addrstr, sizeof(addrstr), NULL, 0,
 
783
                        NI_NUMERICHOST);
744
784
    } else {
745
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
746
 
                        sizeof(addrstr));
 
785
      ret = getnameinfo((struct sockaddr *)&to,
 
786
                        sizeof(struct sockaddr_in),
 
787
                        addrstr, sizeof(addrstr), NULL, 0,
 
788
                        NI_NUMERICHOST);
747
789
    }
748
 
    if(pcret == NULL){
749
 
      perror_plus("inet_ntop");
750
 
    } else {
751
 
      if(strcmp(addrstr, ip) != 0){
752
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
753
 
      }
 
790
    if(ret == EAI_SYSTEM){
 
791
      perror_plus("getnameinfo");
 
792
    } else if(ret != 0) {
 
793
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
794
    } else if(strcmp(addrstr, ip) != 0){
 
795
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
754
796
    }
755
797
  }
756
798
  
760
802
  }
761
803
  
762
804
  if(af == AF_INET6){
763
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
805
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
806
                  sizeof(struct sockaddr_in6));
764
807
  } else {
765
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
808
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
809
                  sizeof(struct sockaddr_in));
766
810
  }
767
811
  if(ret < 0){
768
812
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
817
861
    goto mandos_end;
818
862
  }
819
863
  
820
 
  /* Spurious warning from -Wint-to-pointer-cast */
821
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
864
  /* This casting via intptr_t is to eliminate warning about casting
 
865
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
866
     function "set-session-transport-fd!" does it. */
 
867
  gnutls_transport_set_ptr(session,
 
868
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
822
869
  
823
870
  if(quit_now){
824
871
    errno = EINTR;
929
976
  if(buffer_length > 0){
930
977
    ssize_t decrypted_buffer_size;
931
978
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
932
 
                                               &decrypted_buffer);
 
979
                                               &decrypted_buffer, mc);
933
980
    if(decrypted_buffer_size >= 0){
934
981
      
935
982
      written = 0;
996
1043
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
997
1044
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
998
1045
                             flags,
999
 
                             AVAHI_GCC_UNUSED void* userdata){
1000
 
  assert(r);
 
1046
                             void* mc){
 
1047
  if(r == NULL){
 
1048
    return;
 
1049
  }
1001
1050
  
1002
1051
  /* Called whenever a service has been resolved successfully or
1003
1052
     timed out */
1012
1061
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1013
1062
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1014
1063
                 domain,
1015
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1064
                 avahi_strerror(avahi_server_errno
 
1065
                                (((mandos_context*)mc)->server)));
1016
1066
    break;
1017
1067
    
1018
1068
  case AVAHI_RESOLVER_FOUND:
1024
1074
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1025
1075
                     host_name, ip, (intmax_t)interface, port);
1026
1076
      }
1027
 
      int ret = start_mandos_communication(ip, port, interface,
1028
 
                                           avahi_proto_to_af(proto));
 
1077
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1078
                                           interface,
 
1079
                                           avahi_proto_to_af(proto),
 
1080
                                           mc);
1029
1081
      if(ret == 0){
1030
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1082
        avahi_simple_poll_quit(simple_poll);
1031
1083
      } else {
1032
 
        ret = add_server(ip, port, interface,
1033
 
                         avahi_proto_to_af(proto));
 
1084
        if(not add_server(ip, (in_port_t)port, interface,
 
1085
                          avahi_proto_to_af(proto),
 
1086
                          &((mandos_context*)mc)->current_server)){
 
1087
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1088
                       " list\n", name);
 
1089
        }
1034
1090
      }
1035
1091
    }
1036
1092
  }
1046
1102
                            const char *domain,
1047
1103
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1048
1104
                            flags,
1049
 
                            AVAHI_GCC_UNUSED void* userdata){
1050
 
  assert(b);
 
1105
                            void* mc){
 
1106
  if(b == NULL){
 
1107
    return;
 
1108
  }
1051
1109
  
1052
1110
  /* Called whenever a new services becomes available on the LAN or
1053
1111
     is removed from the LAN */
1061
1119
  case AVAHI_BROWSER_FAILURE:
1062
1120
    
1063
1121
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1064
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1065
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1122
                 avahi_strerror(avahi_server_errno
 
1123
                                (((mandos_context*)mc)->server)));
 
1124
    avahi_simple_poll_quit(simple_poll);
1066
1125
    return;
1067
1126
    
1068
1127
  case AVAHI_BROWSER_NEW:
1071
1130
       the callback function is called the Avahi server will free the
1072
1131
       resolver for us. */
1073
1132
    
1074
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1075
 
                                    name, type, domain, protocol, 0,
1076
 
                                    resolve_callback, NULL) == NULL)
 
1133
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1134
                                    interface, protocol, name, type,
 
1135
                                    domain, protocol, 0,
 
1136
                                    resolve_callback, mc) == NULL)
1077
1137
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1078
1138
                   " %s\n", name,
1079
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1139
                   avahi_strerror(avahi_server_errno
 
1140
                                  (((mandos_context*)mc)->server)));
1080
1141
    break;
1081
1142
    
1082
1143
  case AVAHI_BROWSER_REMOVE:
1101
1162
  signal_received = sig;
1102
1163
  int old_errno = errno;
1103
1164
  /* set main loop to exit */
1104
 
  if(mc.simple_poll != NULL){
1105
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1165
  if(simple_poll != NULL){
 
1166
    avahi_simple_poll_quit(simple_poll);
1106
1167
  }
1107
1168
  errno = old_errno;
1108
1169
}
1109
1170
 
1110
1171
bool get_flags(const char *ifname, struct ifreq *ifr){
1111
1172
  int ret;
 
1173
  error_t ret_errno;
1112
1174
  
1113
1175
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1114
1176
  if(s < 0){
 
1177
    ret_errno = errno;
1115
1178
    perror_plus("socket");
 
1179
    errno = ret_errno;
1116
1180
    return false;
1117
1181
  }
1118
1182
  strcpy(ifr->ifr_name, ifname);
1119
1183
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1120
1184
  if(ret == -1){
1121
1185
    if(debug){
 
1186
      ret_errno = errno;
1122
1187
      perror_plus("ioctl SIOCGIFFLAGS");
 
1188
      errno = ret_errno;
1123
1189
    }
1124
1190
    return false;
1125
1191
  }
1194
1260
}
1195
1261
 
1196
1262
/* 
1197
 
 * This function determines if a directory entry in /sys/class/net
1198
 
 * corresponds to an acceptable network device which is up.
1199
 
 * (This function is passed to scandir(3) as a filter function.)
1200
 
 */
1201
 
int up_interface(const struct dirent *if_entry){
1202
 
  if(if_entry->d_name[0] == '.'){
1203
 
    return 0;
1204
 
  }
1205
 
  
1206
 
  struct ifreq ifr;
1207
 
  if(not get_flags(if_entry->d_name, &ifr)){
1208
 
    if(debug){
1209
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1210
 
                   "\"%s\"\n", if_entry->d_name);
1211
 
    }
1212
 
    return 0;
1213
 
  }
1214
 
  
1215
 
  /* Reject down interfaces */
1216
 
  if(not (ifr.ifr_flags & IFF_UP)){
1217
 
    if(debug){
1218
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1219
 
                   if_entry->d_name);
1220
 
    }
1221
 
    return 0;
1222
 
  }
1223
 
  
1224
 
  /* Reject non-running interfaces */
1225
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1226
 
    if(debug){
1227
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1228
 
                   if_entry->d_name);
1229
 
    }
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  if(not good_flags(if_entry->d_name, &ifr)){
1234
 
    return 0;
1235
 
  }
1236
 
  return 1;
 
1263
 * This function determines if a network interface is up.
 
1264
 */
 
1265
bool interface_is_up(const char *interface){
 
1266
  struct ifreq ifr;
 
1267
  if(not get_flags(interface, &ifr)){
 
1268
    if(debug){
 
1269
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1270
                   "\"%s\"\n", interface);
 
1271
    }
 
1272
    return false;
 
1273
  }
 
1274
  
 
1275
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1276
}
 
1277
 
 
1278
/* 
 
1279
 * This function determines if a network interface is running
 
1280
 */
 
1281
bool interface_is_running(const char *interface){
 
1282
  struct ifreq ifr;
 
1283
  if(not get_flags(interface, &ifr)){
 
1284
    if(debug){
 
1285
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1286
                   "\"%s\"\n", interface);
 
1287
    }
 
1288
    return false;
 
1289
  }
 
1290
  
 
1291
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1237
1292
}
1238
1293
 
1239
1294
int notdotentries(const struct dirent *direntry){
1308
1363
  return 1;
1309
1364
}
1310
1365
 
1311
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1366
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1367
                            mandos_context *mc){
1312
1368
  int ret;
1313
1369
  struct timespec now;
1314
1370
  struct timespec waited_time;
1315
1371
  intmax_t block_time;
1316
1372
  
1317
1373
  while(true){
1318
 
    if(mc.current_server == NULL){
 
1374
    if(mc->current_server == NULL){
1319
1375
      if (debug){
1320
1376
        fprintf_plus(stderr, "Wait until first server is found."
1321
1377
                     " No timeout!\n");
1335
1391
      /* Calculating in ms how long time between now and server
1336
1392
         who we visted longest time ago. Now - last seen.  */
1337
1393
      waited_time.tv_sec = (now.tv_sec
1338
 
                            - mc.current_server->last_seen.tv_sec);
 
1394
                            - mc->current_server->last_seen.tv_sec);
1339
1395
      waited_time.tv_nsec = (now.tv_nsec
1340
 
                             - mc.current_server->last_seen.tv_nsec);
 
1396
                             - mc->current_server->last_seen.tv_nsec);
1341
1397
      /* total time is 10s/10,000ms.
1342
1398
         Converting to s from ms by dividing by 1,000,
1343
1399
         and ns to ms by dividing by 1,000,000. */
1351
1407
      }
1352
1408
      
1353
1409
      if(block_time <= 0){
1354
 
        ret = start_mandos_communication(mc.current_server->ip,
1355
 
                                         mc.current_server->port,
1356
 
                                         mc.current_server->if_index,
1357
 
                                         mc.current_server->af);
 
1410
        ret = start_mandos_communication(mc->current_server->ip,
 
1411
                                         mc->current_server->port,
 
1412
                                         mc->current_server->if_index,
 
1413
                                         mc->current_server->af, mc);
1358
1414
        if(ret == 0){
1359
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1415
          avahi_simple_poll_quit(s);
1360
1416
          return 0;
1361
1417
        }
1362
1418
        ret = clock_gettime(CLOCK_MONOTONIC,
1363
 
                            &mc.current_server->last_seen);
 
1419
                            &mc->current_server->last_seen);
1364
1420
        if(ret == -1){
1365
1421
          perror_plus("clock_gettime");
1366
1422
          return -1;
1367
1423
        }
1368
 
        mc.current_server = mc.current_server->next;
 
1424
        mc->current_server = mc->current_server->next;
1369
1425
        block_time = 0;         /* Call avahi to find new Mandos
1370
1426
                                   servers, but don't block */
1371
1427
      }
1380
1436
  }
1381
1437
}
1382
1438
 
 
1439
/* Set effective uid to 0, return errno */
 
1440
error_t raise_privileges(void){
 
1441
  error_t old_errno = errno;
 
1442
  error_t ret_errno = 0;
 
1443
  if(seteuid(0) == -1){
 
1444
    ret_errno = errno;
 
1445
    perror_plus("seteuid");
 
1446
  }
 
1447
  errno = old_errno;
 
1448
  return ret_errno;
 
1449
}
 
1450
 
 
1451
/* Set effective and real user ID to 0.  Return errno. */
 
1452
error_t raise_privileges_permanently(void){
 
1453
  error_t old_errno = errno;
 
1454
  error_t ret_errno = raise_privileges();
 
1455
  if(ret_errno != 0){
 
1456
    errno = old_errno;
 
1457
    return ret_errno;
 
1458
  }
 
1459
  if(setuid(0) == -1){
 
1460
    ret_errno = errno;
 
1461
    perror_plus("seteuid");
 
1462
  }
 
1463
  errno = old_errno;
 
1464
  return ret_errno;
 
1465
}
 
1466
 
 
1467
/* Set effective user ID to unprivileged saved user ID */
 
1468
error_t lower_privileges(void){
 
1469
  error_t old_errno = errno;
 
1470
  error_t ret_errno = 0;
 
1471
  if(seteuid(uid) == -1){
 
1472
    ret_errno = errno;
 
1473
    perror_plus("seteuid");
 
1474
  }
 
1475
  errno = old_errno;
 
1476
  return ret_errno;
 
1477
}
 
1478
 
 
1479
/* Lower privileges permanently */
 
1480
error_t lower_privileges_permanently(void){
 
1481
  error_t old_errno = errno;
 
1482
  error_t ret_errno = 0;
 
1483
  if(setuid(uid) == -1){
 
1484
    ret_errno = errno;
 
1485
    perror_plus("setuid");
 
1486
  }
 
1487
  errno = old_errno;
 
1488
  return ret_errno;
 
1489
}
 
1490
 
1383
1491
bool run_network_hooks(const char *mode, const char *interface,
1384
1492
                       const float delay){
1385
1493
  struct dirent **direntries;
1386
 
  struct dirent *direntry;
1387
 
  int ret;
1388
1494
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1389
1495
                         alphasort);
1390
1496
  if(numhooks == -1){
1391
 
    perror_plus("scandir");
 
1497
    if(errno == ENOENT){
 
1498
      if(debug){
 
1499
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1500
                     " found\n", hookdir);
 
1501
      }
 
1502
    } else {
 
1503
      perror_plus("scandir");
 
1504
    }
1392
1505
  } else {
 
1506
    struct dirent *direntry;
 
1507
    int ret;
1393
1508
    int devnull = open("/dev/null", O_RDONLY);
1394
1509
    for(int i = 0; i < numhooks; i++){
1395
1510
      direntry = direntries[i];
1406
1521
      pid_t hook_pid = fork();
1407
1522
      if(hook_pid == 0){
1408
1523
        /* Child */
 
1524
        /* Raise privileges */
 
1525
        raise_privileges_permanently();
 
1526
        /* Set group */
 
1527
        errno = 0;
 
1528
        ret = setgid(0);
 
1529
        if(ret == -1){
 
1530
          perror_plus("setgid");
 
1531
        }
 
1532
        /* Reset supplementary groups */
 
1533
        errno = 0;
 
1534
        ret = setgroups(0, NULL);
 
1535
        if(ret == -1){
 
1536
          perror_plus("setgroups");
 
1537
        }
1409
1538
        dup2(devnull, STDIN_FILENO);
1410
1539
        close(devnull);
1411
1540
        dup2(STDERR_FILENO, STDOUT_FILENO);
1419
1548
          perror_plus("setenv");
1420
1549
          _exit(EX_OSERR);
1421
1550
        }
1422
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1551
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1423
1552
        if(ret == -1){
1424
1553
          perror_plus("setenv");
1425
1554
          _exit(EX_OSERR);
1442
1571
          _exit(EX_OSERR);
1443
1572
        }
1444
1573
        free(delaystring);
1445
 
        ret = execl(fullname, direntry->d_name, mode, NULL);
1446
 
        perror_plus("execl");
 
1574
        if(connect_to != NULL){
 
1575
          ret = setenv("CONNECT", connect_to, 1);
 
1576
          if(ret == -1){
 
1577
            perror_plus("setenv");
 
1578
            _exit(EX_OSERR);
 
1579
          }
 
1580
        }
 
1581
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1582
          perror_plus("execl");
 
1583
          _exit(EXIT_FAILURE);
 
1584
        }
1447
1585
      } else {
1448
1586
        int status;
1449
1587
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1483
1621
  return true;
1484
1622
}
1485
1623
 
 
1624
error_t bring_up_interface(const char *const interface,
 
1625
                           const float delay){
 
1626
  int sd = -1;
 
1627
  error_t old_errno = errno;
 
1628
  error_t ret_errno = 0;
 
1629
  int ret, ret_setflags;
 
1630
  struct ifreq network;
 
1631
  unsigned int if_index = if_nametoindex(interface);
 
1632
  if(if_index == 0){
 
1633
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1634
    errno = old_errno;
 
1635
    return ENXIO;
 
1636
  }
 
1637
  
 
1638
  if(quit_now){
 
1639
    errno = old_errno;
 
1640
    return EINTR;
 
1641
  }
 
1642
  
 
1643
  if(not interface_is_up(interface)){
 
1644
    if(not get_flags(interface, &network) and debug){
 
1645
      ret_errno = errno;
 
1646
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1647
                   "\"%s\"\n", interface);
 
1648
      return ret_errno;
 
1649
    }
 
1650
    network.ifr_flags |= IFF_UP;
 
1651
    
 
1652
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1653
    if(sd < 0){
 
1654
      ret_errno = errno;
 
1655
      perror_plus("socket");
 
1656
      errno = old_errno;
 
1657
      return ret_errno;
 
1658
    }
 
1659
  
 
1660
    if(quit_now){
 
1661
      close(sd);
 
1662
      errno = old_errno;
 
1663
      return EINTR;
 
1664
    }
 
1665
    
 
1666
    if(debug){
 
1667
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1668
                   interface);
 
1669
    }
 
1670
    
 
1671
    /* Raise priviliges */
 
1672
    raise_privileges();
 
1673
    
 
1674
#ifdef __linux__
 
1675
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1676
       messages about the network interface to mess up the prompt */
 
1677
    int ret_linux = klogctl(8, NULL, 5);
 
1678
    bool restore_loglevel = true;
 
1679
    if(ret_linux == -1){
 
1680
      restore_loglevel = false;
 
1681
      perror_plus("klogctl");
 
1682
    }
 
1683
#endif  /* __linux__ */
 
1684
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1685
    ret_errno = errno;
 
1686
#ifdef __linux__
 
1687
    if(restore_loglevel){
 
1688
      ret_linux = klogctl(7, NULL, 0);
 
1689
      if(ret_linux == -1){
 
1690
        perror_plus("klogctl");
 
1691
      }
 
1692
    }
 
1693
#endif  /* __linux__ */
 
1694
    
 
1695
    /* Lower privileges */
 
1696
    lower_privileges();
 
1697
    
 
1698
    /* Close the socket */
 
1699
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1700
    if(ret == -1){
 
1701
      perror_plus("close");
 
1702
    }
 
1703
    
 
1704
    if(ret_setflags == -1){
 
1705
      errno = ret_errno;
 
1706
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1707
      errno = old_errno;
 
1708
      return ret_errno;
 
1709
    }
 
1710
  } else if(debug){
 
1711
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1712
                 interface);
 
1713
  }
 
1714
  
 
1715
  /* Sleep checking until interface is running.
 
1716
     Check every 0.25s, up to total time of delay */
 
1717
  for(int i=0; i < delay * 4; i++){
 
1718
    if(interface_is_running(interface)){
 
1719
      break;
 
1720
    }
 
1721
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1722
    ret = nanosleep(&sleeptime, NULL);
 
1723
    if(ret == -1 and errno != EINTR){
 
1724
      perror_plus("nanosleep");
 
1725
    }
 
1726
  }
 
1727
  
 
1728
  errno = old_errno;
 
1729
  return 0;
 
1730
}
 
1731
 
 
1732
error_t take_down_interface(const char *const interface){
 
1733
  error_t old_errno = errno;
 
1734
  struct ifreq network;
 
1735
  unsigned int if_index = if_nametoindex(interface);
 
1736
  if(if_index == 0){
 
1737
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1738
    errno = old_errno;
 
1739
    return ENXIO;
 
1740
  }
 
1741
  if(interface_is_up(interface)){
 
1742
    error_t ret_errno = 0;
 
1743
    if(not get_flags(interface, &network) and debug){
 
1744
      ret_errno = errno;
 
1745
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1746
                   "\"%s\"\n", interface);
 
1747
      return ret_errno;
 
1748
    }
 
1749
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1750
    
 
1751
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1752
    if(sd < 0){
 
1753
      ret_errno = errno;
 
1754
      perror_plus("socket");
 
1755
      errno = old_errno;
 
1756
      return ret_errno;
 
1757
    }
 
1758
    
 
1759
    if(debug){
 
1760
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1761
                   interface);
 
1762
    }
 
1763
    
 
1764
    /* Raise priviliges */
 
1765
    raise_privileges();
 
1766
    
 
1767
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1768
    ret_errno = errno;
 
1769
    
 
1770
    /* Lower privileges */
 
1771
    lower_privileges();
 
1772
    
 
1773
    /* Close the socket */
 
1774
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1775
    if(ret == -1){
 
1776
      perror_plus("close");
 
1777
    }
 
1778
    
 
1779
    if(ret_setflags == -1){
 
1780
      errno = ret_errno;
 
1781
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1782
      errno = old_errno;
 
1783
      return ret_errno;
 
1784
    }
 
1785
  } else if(debug){
 
1786
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1787
                 interface);
 
1788
  }
 
1789
  
 
1790
  errno = old_errno;
 
1791
  return 0;
 
1792
}
 
1793
 
1486
1794
int main(int argc, char *argv[]){
 
1795
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1796
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1797
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1798
                        .interfaces = NULL, .interfaces_size = 0 };
1487
1799
  AvahiSServiceBrowser *sb = NULL;
1488
 
  int error;
 
1800
  error_t ret_errno;
1489
1801
  int ret;
1490
1802
  intmax_t tmpmax;
1491
1803
  char *tmp;
1492
1804
  int exitcode = EXIT_SUCCESS;
1493
 
  const char *interface = "";
1494
 
  struct ifreq network;
1495
 
  int sd = -1;
1496
 
  bool take_down_interface = false;
1497
 
  uid_t uid;
1498
 
  gid_t gid;
 
1805
  char *interfaces_to_take_down = NULL;
 
1806
  size_t interfaces_to_take_down_size = 0;
1499
1807
  char tempdir[] = "/tmp/mandosXXXXXX";
1500
1808
  bool tempdir_created = false;
1501
1809
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1502
1810
  const char *seckey = PATHDIR "/" SECKEY;
1503
1811
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1812
  char *interfaces_hooks = NULL;
1504
1813
  
1505
1814
  bool gnutls_initialized = false;
1506
1815
  bool gpgme_initialized = false;
1568
1877
        .group = 2 },
1569
1878
      { .name = "retry", .key = 132,
1570
1879
        .arg = "SECONDS",
1571
 
        .doc = "Retry interval used when denied by the mandos server",
 
1880
        .doc = "Retry interval used when denied by the Mandos server",
1572
1881
        .group = 2 },
1573
1882
      { .name = "network-hook-dir", .key = 133,
1574
1883
        .arg = "DIR",
1597
1906
        connect_to = arg;
1598
1907
        break;
1599
1908
      case 'i':                 /* --interface */
1600
 
        interface = arg;
 
1909
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1910
                                 arg, (int)',');
 
1911
        if(ret_errno != 0){
 
1912
          argp_error(state, "%s", strerror(ret_errno));
 
1913
        }
1601
1914
        break;
1602
1915
      case 's':                 /* --seckey */
1603
1916
        seckey = arg;
1646
1959
        argp_state_help(state, state->out_stream,
1647
1960
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1648
1961
      case 'V':                 /* --version */
1649
 
        fprintf_plus(state->out_stream,
1650
 
                     "Mandos plugin mandos-client: ");
1651
1962
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1652
1963
        exit(argp_err_exit_status);
1653
1964
        break;
1678
1989
    }
1679
1990
  }
1680
1991
    
1681
 
  if(getuid() == 0){
 
1992
  {
1682
1993
    /* Work around Debian bug #633582:
1683
1994
       <http://bugs.debian.org/633582> */
1684
 
    struct stat st;
1685
1995
    
1686
1996
    /* Re-raise priviliges */
1687
 
    errno = 0;
1688
 
    ret = seteuid(0);
1689
 
    if(ret == -1){
1690
 
      perror_plus("seteuid");
1691
 
    }
1692
 
    
1693
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1694
 
      int seckey_fd = open(seckey, O_RDONLY);
1695
 
      if(seckey_fd == -1){
1696
 
        perror_plus("open");
1697
 
      } else {
1698
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1699
 
        if(ret == -1){
1700
 
          perror_plus("fstat");
1701
 
        } else {
1702
 
          if(S_ISREG(st.st_mode)
1703
 
             and st.st_uid == 0 and st.st_gid == 0){
1704
 
            ret = fchown(seckey_fd, uid, gid);
1705
 
            if(ret == -1){
1706
 
              perror_plus("fchown");
1707
 
            }
1708
 
          }
1709
 
        }
1710
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1711
 
      }
1712
 
    }
1713
 
    
1714
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1715
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1716
 
      if(pubkey_fd == -1){
1717
 
        perror_plus("open");
1718
 
      } else {
1719
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1720
 
        if(ret == -1){
1721
 
          perror_plus("fstat");
1722
 
        } else {
1723
 
          if(S_ISREG(st.st_mode)
1724
 
             and st.st_uid == 0 and st.st_gid == 0){
1725
 
            ret = fchown(pubkey_fd, uid, gid);
1726
 
            if(ret == -1){
1727
 
              perror_plus("fchown");
1728
 
            }
1729
 
          }
1730
 
        }
1731
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1732
 
      }
1733
 
    }
1734
 
    
1735
 
    /* Lower privileges */
1736
 
    errno = 0;
1737
 
    ret = seteuid(uid);
1738
 
    if(ret == -1){
1739
 
      perror_plus("seteuid");
 
1997
    if(raise_privileges() == 0){
 
1998
      struct stat st;
 
1999
      
 
2000
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2001
        int seckey_fd = open(seckey, O_RDONLY);
 
2002
        if(seckey_fd == -1){
 
2003
          perror_plus("open");
 
2004
        } else {
 
2005
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2006
          if(ret == -1){
 
2007
            perror_plus("fstat");
 
2008
          } else {
 
2009
            if(S_ISREG(st.st_mode)
 
2010
               and st.st_uid == 0 and st.st_gid == 0){
 
2011
              ret = fchown(seckey_fd, uid, gid);
 
2012
              if(ret == -1){
 
2013
                perror_plus("fchown");
 
2014
              }
 
2015
            }
 
2016
          }
 
2017
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2018
        }
 
2019
      }
 
2020
    
 
2021
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2022
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2023
        if(pubkey_fd == -1){
 
2024
          perror_plus("open");
 
2025
        } else {
 
2026
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2027
          if(ret == -1){
 
2028
            perror_plus("fstat");
 
2029
          } else {
 
2030
            if(S_ISREG(st.st_mode)
 
2031
               and st.st_uid == 0 and st.st_gid == 0){
 
2032
              ret = fchown(pubkey_fd, uid, gid);
 
2033
              if(ret == -1){
 
2034
                perror_plus("fchown");
 
2035
              }
 
2036
            }
 
2037
          }
 
2038
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2039
        }
 
2040
      }
 
2041
    
 
2042
      /* Lower privileges */
 
2043
      lower_privileges();
 
2044
    }
 
2045
  }
 
2046
  
 
2047
  /* Remove invalid interface names (except "none") */
 
2048
  {
 
2049
    char *interface = NULL;
 
2050
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2051
                                 interface))){
 
2052
      if(strcmp(interface, "none") != 0
 
2053
         and if_nametoindex(interface) == 0){
 
2054
        if(interface[0] != '\0'){
 
2055
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2056
                       " \"%s\"\n", interface);
 
2057
        }
 
2058
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2059
        interface = NULL;
 
2060
      }
1740
2061
    }
1741
2062
  }
1742
2063
  
1743
2064
  /* Run network hooks */
1744
2065
  {
1745
 
    if(getuid() == 0){
1746
 
      /* Re-raise priviliges */
1747
 
      errno = 0;
1748
 
      ret = seteuid(0);
1749
 
      if(ret == -1){
1750
 
        perror_plus("seteuid");
 
2066
    if(mc.interfaces != NULL){
 
2067
      interfaces_hooks = malloc(mc.interfaces_size);
 
2068
      if(interfaces_hooks == NULL){
 
2069
        perror_plus("malloc");
 
2070
        goto end;
1751
2071
      }
 
2072
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2073
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
1752
2074
    }
1753
 
    if(not run_network_hooks("start", interface, delay)){
 
2075
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2076
                             interfaces_hooks : "", delay)){
1754
2077
      goto end;
1755
2078
    }
1756
 
    if(getuid() == 0){
1757
 
      /* Lower privileges */
1758
 
      errno = 0;
1759
 
      ret = seteuid(uid);
1760
 
      if(ret == -1){
1761
 
        perror_plus("seteuid");
1762
 
      }
1763
 
    }
1764
2079
  }
1765
2080
  
1766
2081
  if(not debug){
1767
2082
    avahi_set_log_function(empty_log);
1768
2083
  }
1769
2084
  
1770
 
  if(interface[0] == '\0'){
1771
 
    struct dirent **direntries;
1772
 
    /* First look for interfaces that are up */
1773
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1774
 
                  alphasort);
1775
 
    if(ret == 0){
1776
 
      /* No up interfaces, look for any good interfaces */
1777
 
      free(direntries);
1778
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1779
 
                    alphasort);
1780
 
    }
1781
 
    if(ret >= 1){
1782
 
      /* Pick the first interface returned */
1783
 
      interface = strdup(direntries[0]->d_name);
1784
 
      if(debug){
1785
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1786
 
      }
1787
 
      if(interface == NULL){
1788
 
        perror_plus("malloc");
1789
 
        free(direntries);
1790
 
        exitcode = EXIT_FAILURE;
1791
 
        goto end;
1792
 
      }
1793
 
      free(direntries);
1794
 
    } else {
1795
 
      free(direntries);
1796
 
      fprintf_plus(stderr, "Could not find a network interface\n");
1797
 
      exitcode = EXIT_FAILURE;
1798
 
      goto end;
1799
 
    }
1800
 
  }
1801
 
  
1802
2085
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1803
2086
     from the signal handler */
1804
2087
  /* Initialize the pseudo-RNG for Avahi */
1805
2088
  srand((unsigned int) time(NULL));
1806
 
  mc.simple_poll = avahi_simple_poll_new();
1807
 
  if(mc.simple_poll == NULL){
 
2089
  simple_poll = avahi_simple_poll_new();
 
2090
  if(simple_poll == NULL){
1808
2091
    fprintf_plus(stderr,
1809
2092
                 "Avahi: Failed to create simple poll object.\n");
1810
2093
    exitcode = EX_UNAVAILABLE;
1874
2157
    }
1875
2158
  }
1876
2159
  
1877
 
  /* If the interface is down, bring it up */
1878
 
  if(strcmp(interface, "none") != 0){
1879
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1880
 
    if(if_index == 0){
1881
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1882
 
      exitcode = EX_UNAVAILABLE;
1883
 
      goto end;
1884
 
    }
1885
 
    
1886
 
    if(quit_now){
1887
 
      goto end;
1888
 
    }
1889
 
    
1890
 
    /* Re-raise priviliges */
1891
 
    errno = 0;
1892
 
    ret = seteuid(0);
1893
 
    if(ret == -1){
1894
 
      perror_plus("seteuid");
1895
 
    }
1896
 
    
1897
 
#ifdef __linux__
1898
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1899
 
       messages about the network interface to mess up the prompt */
1900
 
    ret = klogctl(8, NULL, 5);
1901
 
    bool restore_loglevel = true;
1902
 
    if(ret == -1){
1903
 
      restore_loglevel = false;
1904
 
      perror_plus("klogctl");
1905
 
    }
1906
 
#endif  /* __linux__ */
1907
 
    
1908
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1909
 
    if(sd < 0){
1910
 
      perror_plus("socket");
1911
 
      exitcode = EX_OSERR;
1912
 
#ifdef __linux__
1913
 
      if(restore_loglevel){
1914
 
        ret = klogctl(7, NULL, 0);
1915
 
        if(ret == -1){
1916
 
          perror_plus("klogctl");
1917
 
        }
1918
 
      }
1919
 
#endif  /* __linux__ */
1920
 
      /* Lower privileges */
1921
 
      errno = 0;
1922
 
      ret = seteuid(uid);
1923
 
      if(ret == -1){
1924
 
        perror_plus("seteuid");
1925
 
      }
1926
 
      goto end;
1927
 
    }
1928
 
    strcpy(network.ifr_name, interface);
1929
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1930
 
    if(ret == -1){
1931
 
      perror_plus("ioctl SIOCGIFFLAGS");
1932
 
#ifdef __linux__
1933
 
      if(restore_loglevel){
1934
 
        ret = klogctl(7, NULL, 0);
1935
 
        if(ret == -1){
1936
 
          perror_plus("klogctl");
1937
 
        }
1938
 
      }
1939
 
#endif  /* __linux__ */
1940
 
      exitcode = EX_OSERR;
1941
 
      /* Lower privileges */
1942
 
      errno = 0;
1943
 
      ret = seteuid(uid);
1944
 
      if(ret == -1){
1945
 
        perror_plus("seteuid");
1946
 
      }
1947
 
      goto end;
1948
 
    }
1949
 
    if((network.ifr_flags & IFF_UP) == 0){
1950
 
      network.ifr_flags |= IFF_UP;
1951
 
      take_down_interface = true;
1952
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1953
 
      if(ret == -1){
1954
 
        take_down_interface = false;
1955
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1956
 
        exitcode = EX_OSERR;
1957
 
#ifdef __linux__
1958
 
        if(restore_loglevel){
1959
 
          ret = klogctl(7, NULL, 0);
1960
 
          if(ret == -1){
1961
 
            perror_plus("klogctl");
 
2160
  /* If no interfaces were specified, make a list */
 
2161
  if(mc.interfaces == NULL){
 
2162
    struct dirent **direntries;
 
2163
    /* Look for any good interfaces */
 
2164
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2165
                  alphasort);
 
2166
    if(ret >= 1){
 
2167
      /* Add all found interfaces to interfaces list */
 
2168
      for(int i = 0; i < ret; ++i){
 
2169
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2170
                             direntries[i]->d_name);
 
2171
        if(ret_errno != 0){
 
2172
          errno = ret_errno;
 
2173
          perror_plus("argz_add");
 
2174
          continue;
 
2175
        }
 
2176
        if(debug){
 
2177
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2178
                       direntries[i]->d_name);
 
2179
        }
 
2180
      }
 
2181
      free(direntries);
 
2182
    } else {
 
2183
      free(direntries);
 
2184
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2185
      exitcode = EXIT_FAILURE;
 
2186
      goto end;
 
2187
    }
 
2188
  }
 
2189
  
 
2190
  /* Bring up interfaces which are down, and remove any "none"s */
 
2191
  {
 
2192
    char *interface = NULL;
 
2193
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2194
                                 interface))){
 
2195
      /* If interface name is "none", stop bringing up interfaces.
 
2196
         Also remove all instances of "none" from the list */
 
2197
      if(strcmp(interface, "none") == 0){
 
2198
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2199
                    interface);
 
2200
        interface = NULL;
 
2201
        while((interface = argz_next(mc.interfaces,
 
2202
                                     mc.interfaces_size, interface))){
 
2203
          if(strcmp(interface, "none") == 0){
 
2204
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2205
                        interface);
 
2206
            interface = NULL;
1962
2207
          }
1963
2208
        }
1964
 
#endif  /* __linux__ */
1965
 
        /* Lower privileges */
1966
 
        errno = 0;
1967
 
        ret = seteuid(uid);
1968
 
        if(ret == -1){
1969
 
          perror_plus("seteuid");
1970
 
        }
1971
 
        goto end;
1972
 
      }
1973
 
    }
1974
 
    /* Sleep checking until interface is running.
1975
 
       Check every 0.25s, up to total time of delay */
1976
 
    for(int i=0; i < delay * 4; i++){
1977
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1978
 
      if(ret == -1){
1979
 
        perror_plus("ioctl SIOCGIFFLAGS");
1980
 
      } else if(network.ifr_flags & IFF_RUNNING){
1981
2209
        break;
1982
2210
      }
1983
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1984
 
      ret = nanosleep(&sleeptime, NULL);
1985
 
      if(ret == -1 and errno != EINTR){
1986
 
        perror_plus("nanosleep");
1987
 
      }
1988
 
    }
1989
 
    if(not take_down_interface){
1990
 
      /* We won't need the socket anymore */
1991
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1992
 
      if(ret == -1){
1993
 
        perror_plus("close");
1994
 
      }
1995
 
    }
1996
 
#ifdef __linux__
1997
 
    if(restore_loglevel){
1998
 
      /* Restores kernel loglevel to default */
1999
 
      ret = klogctl(7, NULL, 0);
2000
 
      if(ret == -1){
2001
 
        perror_plus("klogctl");
2002
 
      }
2003
 
    }
2004
 
#endif  /* __linux__ */
2005
 
    /* Lower privileges */
2006
 
    errno = 0;
2007
 
    /* Lower privileges */
2008
 
    ret = seteuid(uid);
2009
 
    if(ret == -1){
2010
 
      perror_plus("seteuid");
2011
 
    }
 
2211
      bool interface_was_up = interface_is_up(interface);
 
2212
      ret = bring_up_interface(interface, delay);
 
2213
      if(not interface_was_up){
 
2214
        if(ret != 0){
 
2215
          errno = ret;
 
2216
          perror_plus("Failed to bring up interface");
 
2217
        } else {
 
2218
          ret_errno = argz_add(&interfaces_to_take_down,
 
2219
                               &interfaces_to_take_down_size,
 
2220
                               interface);
 
2221
          if(ret_errno != 0){
 
2222
            errno = ret_errno;
 
2223
            perror_plus("argz_add");
 
2224
          }
 
2225
        }
 
2226
      }
 
2227
    }
 
2228
    if(debug and (interfaces_to_take_down == NULL)){
 
2229
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2230
    }
 
2231
  }
 
2232
  
 
2233
  /* If we only got one interface, explicitly use only that one */
 
2234
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2235
    if(debug){
 
2236
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2237
                   mc.interfaces);
 
2238
    }
 
2239
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2012
2240
  }
2013
2241
  
2014
2242
  if(quit_now){
2015
2243
    goto end;
2016
2244
  }
2017
2245
  
2018
 
  ret = init_gnutls_global(pubkey, seckey);
 
2246
  ret = init_gnutls_global(pubkey, seckey, &mc);
2019
2247
  if(ret == -1){
2020
2248
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2021
2249
    exitcode = EX_UNAVAILABLE;
2038
2266
    goto end;
2039
2267
  }
2040
2268
  
2041
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2269
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2042
2270
    fprintf_plus(stderr, "init_gpgme failed\n");
2043
2271
    exitcode = EX_UNAVAILABLE;
2044
2272
    goto end;
2054
2282
    /* Connect directly, do not use Zeroconf */
2055
2283
    /* (Mainly meant for debugging) */
2056
2284
    char *address = strrchr(connect_to, ':');
 
2285
    
2057
2286
    if(address == NULL){
2058
2287
      fprintf_plus(stderr, "No colon in address\n");
2059
2288
      exitcode = EX_USAGE;
2064
2293
      goto end;
2065
2294
    }
2066
2295
    
2067
 
    uint16_t port;
 
2296
    in_port_t port;
2068
2297
    errno = 0;
2069
2298
    tmpmax = strtoimax(address+1, &tmp, 10);
2070
2299
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2071
 
       or tmpmax != (uint16_t)tmpmax){
 
2300
       or tmpmax != (in_port_t)tmpmax){
2072
2301
      fprintf_plus(stderr, "Bad port number\n");
2073
2302
      exitcode = EX_USAGE;
2074
2303
      goto end;
2075
2304
    }
2076
 
  
 
2305
    
2077
2306
    if(quit_now){
2078
2307
      goto end;
2079
2308
    }
2080
2309
    
2081
 
    port = (uint16_t)tmpmax;
 
2310
    port = (in_port_t)tmpmax;
2082
2311
    *address = '\0';
2083
2312
    /* Colon in address indicates IPv6 */
2084
2313
    int af;
2100
2329
    }
2101
2330
    
2102
2331
    while(not quit_now){
2103
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2332
      ret = start_mandos_communication(address, port, if_index, af,
 
2333
                                       &mc);
2104
2334
      if(quit_now or ret == 0){
2105
2335
        break;
2106
2336
      }
2108
2338
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2109
2339
                     (int)retry_interval);
2110
2340
      }
2111
 
      sleep((int)retry_interval);
 
2341
      sleep((unsigned int)retry_interval);
2112
2342
    }
2113
2343
    
2114
2344
    if (not quit_now){
2132
2362
    config.publish_domain = 0;
2133
2363
    
2134
2364
    /* Allocate a new server */
2135
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2136
 
                                 (mc.simple_poll), &config, NULL,
2137
 
                                 NULL, &error);
 
2365
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2366
                                 &config, NULL, NULL, &ret_errno);
2138
2367
    
2139
2368
    /* Free the Avahi configuration data */
2140
2369
    avahi_server_config_free(&config);
2143
2372
  /* Check if creating the Avahi server object succeeded */
2144
2373
  if(mc.server == NULL){
2145
2374
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2146
 
                 avahi_strerror(error));
 
2375
                 avahi_strerror(ret_errno));
2147
2376
    exitcode = EX_UNAVAILABLE;
2148
2377
    goto end;
2149
2378
  }
2155
2384
  /* Create the Avahi service browser */
2156
2385
  sb = avahi_s_service_browser_new(mc.server, if_index,
2157
2386
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2158
 
                                   NULL, 0, browse_callback, NULL);
 
2387
                                   NULL, 0, browse_callback,
 
2388
                                   (void *)&mc);
2159
2389
  if(sb == NULL){
2160
2390
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2161
2391
                 avahi_strerror(avahi_server_errno(mc.server)));
2173
2403
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2174
2404
  }
2175
2405
 
2176
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2177
 
                                (int)(retry_interval * 1000));
 
2406
  ret = avahi_loop_with_timeout(simple_poll,
 
2407
                                (int)(retry_interval * 1000), &mc);
2178
2408
  if(debug){
2179
2409
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2180
2410
                 (ret == 0) ? "successfully" : "with error");
2187
2417
  }
2188
2418
  
2189
2419
  /* Cleanup things */
 
2420
  free(mc.interfaces);
 
2421
  
2190
2422
  if(sb != NULL)
2191
2423
    avahi_s_service_browser_free(sb);
2192
2424
  
2193
2425
  if(mc.server != NULL)
2194
2426
    avahi_server_free(mc.server);
2195
2427
  
2196
 
  if(mc.simple_poll != NULL)
2197
 
    avahi_simple_poll_free(mc.simple_poll);
 
2428
  if(simple_poll != NULL)
 
2429
    avahi_simple_poll_free(simple_poll);
2198
2430
  
2199
2431
  if(gnutls_initialized){
2200
2432
    gnutls_certificate_free_credentials(mc.cred);
2219
2451
  
2220
2452
  /* Re-raise priviliges */
2221
2453
  {
2222
 
    if(getuid() == 0){
2223
 
      errno = 0;
2224
 
      ret = seteuid(0);
2225
 
      if(ret == -1){
2226
 
        perror_plus("seteuid");
2227
 
      }
2228
 
    }
 
2454
    raise_privileges();
2229
2455
    
2230
2456
    /* Run network hooks */
2231
 
    run_network_hooks("stop", interface, delay);
 
2457
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2458
                      interfaces_hooks : "", delay);
2232
2459
    
2233
 
    /* Take down the network interface */
2234
 
    if(take_down_interface and geteuid() == 0){
2235
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2236
 
      if(ret == -1){
2237
 
        perror_plus("ioctl SIOCGIFFLAGS");
2238
 
      } else if(network.ifr_flags & IFF_UP){
2239
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2240
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2241
 
        if(ret == -1){
2242
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2460
    /* Take down the network interfaces which were brought up */
 
2461
    {
 
2462
      char *interface = NULL;
 
2463
      while((interface=argz_next(interfaces_to_take_down,
 
2464
                                 interfaces_to_take_down_size,
 
2465
                                 interface))){
 
2466
        ret_errno = take_down_interface(interface);
 
2467
        if(ret_errno != 0){
 
2468
          errno = ret_errno;
 
2469
          perror_plus("Failed to take down interface");
2243
2470
        }
2244
2471
      }
2245
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2246
 
      if(ret == -1){
2247
 
        perror_plus("close");
 
2472
      if(debug and (interfaces_to_take_down == NULL)){
 
2473
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2474
                     " down\n");
2248
2475
      }
2249
2476
    }
2250
 
  }
2251
 
  if(getuid() == 0){
2252
 
    /* Lower privileges permanently */
2253
 
    errno = 0;
2254
 
    ret = setuid(uid);
2255
 
    if(ret == -1){
2256
 
      perror_plus("setuid");
2257
 
    }
2258
 
  }
 
2477
    
 
2478
    lower_privileges_permanently();
 
2479
  }
 
2480
  
 
2481
  free(interfaces_to_take_down);
 
2482
  free(interfaces_hooks);
2259
2483
  
2260
2484
  /* Removes the GPGME temp directory and all files inside */
2261
2485
  if(tempdir_created){