/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: 2012-06-01 21:48:12 UTC
  • Revision ID: teddy@recompile.se-20120601214812-g7685v5oeiuhi2qw
* debian/copyright (Copyright): Join the two lines to one line.
* debian/mandos-client.README.Debian: Refer to new location of example
  network hooks.
* debian/mandos-client.docs (network-hooks.d): Removed.
* debian/mandos-client.examples: New; contains "network-hooks.d".
* debian/rules (binary-common): Added "dh_installexamples".
  (binary-common/dh_fixperms): Changed to exclude new location of
  "network-hooks.d".
* init.d-mandos (status): Support new "status" action.

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-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 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
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   strtoimax() */
 
64
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
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() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
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,
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
90
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() */
97
91
 
98
92
#ifdef __linux__
99
93
#include <sys/klog.h>           /* klogctl() */
141
135
static const char sys_class_net[] = "/sys/class/net";
142
136
char *connect_to = NULL;
143
137
const char *hookdir = HOOKDIR;
144
 
uid_t uid = 65534;
145
 
gid_t gid = 65534;
146
138
 
147
139
/* Doubly linked list that need to be circularly linked when used */
148
140
typedef struct server{
149
141
  const char *ip;
150
 
  in_port_t port;
 
142
  uint16_t port;
151
143
  AvahiIfIndex if_index;
152
144
  int af;
153
145
  struct timespec last_seen;
157
149
 
158
150
/* Used for passing in values through the Avahi callback functions */
159
151
typedef struct {
 
152
  AvahiSimplePoll *simple_poll;
160
153
  AvahiServer *server;
161
154
  gnutls_certificate_credentials_t cred;
162
155
  unsigned int dh_bits;
164
157
  const char *priority;
165
158
  gpgme_ctx_t ctx;
166
159
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
160
} mandos_context;
170
161
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
162
/* global context so signal handler can reach it*/
 
163
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
164
                      .dh_bits = 1024, .priority = "SECURE256"
 
165
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
166
                      .current_server = NULL };
173
167
 
174
168
sig_atomic_t quit_now = 0;
175
169
int signal_received = 0;
183
177
  perror(print_text);
184
178
}
185
179
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
180
__attribute__((format (gnu_printf, 2, 3)))
187
181
int fprintf_plus(FILE *stream, const char *format, ...){
188
182
  va_list ap;
189
183
  va_start (ap, format);
190
184
  
191
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
186
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
188
}
195
189
 
196
190
/*
198
192
 * bytes. "buffer_capacity" is how much is currently allocated,
199
193
 * "buffer_length" is how much is already used.
200
194
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
195
size_t incbuffer(char **buffer, size_t buffer_length,
203
196
                 size_t buffer_capacity){
204
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
205
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
206
 
    if(new_buf == NULL){
207
 
      int old_errno = errno;
208
 
      free(*buffer);
209
 
      errno = old_errno;
210
 
      *buffer = NULL;
 
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
199
    if(buffer == NULL){
211
200
      return 0;
212
201
    }
213
 
    *buffer = new_buf;
214
202
    buffer_capacity += BUFFER_SIZE;
215
203
  }
216
204
  return buffer_capacity;
217
205
}
218
206
 
219
207
/* Add server to set of servers to retry periodically */
220
 
__attribute__((nonnull, warn_unused_result))
221
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
222
 
                int af, server **current_server){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
223
210
  int ret;
224
211
  server *new_server = malloc(sizeof(server));
225
212
  if(new_server == NULL){
234
221
    perror_plus("strdup");
235
222
    return false;
236
223
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
224
  /* Special case of first server */
243
 
  if(*current_server == NULL){
 
225
  if (mc.current_server == NULL){
244
226
    new_server->next = new_server;
245
227
    new_server->prev = new_server;
246
 
    *current_server = new_server;
 
228
    mc.current_server = new_server;
 
229
  /* Place the new server last in the list */
247
230
  } else {
248
 
    /* Place the new server last in the list */
249
 
    new_server->next = *current_server;
250
 
    new_server->prev = (*current_server)->prev;
 
231
    new_server->next = mc.current_server;
 
232
    new_server->prev = mc.current_server->prev;
251
233
    new_server->prev->next = new_server;
252
 
    (*current_server)->prev = new_server;
 
234
    mc.current_server->prev = new_server;
 
235
  }
 
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
237
  if(ret == -1){
 
238
    perror_plus("clock_gettime");
 
239
    return false;
253
240
  }
254
241
  return true;
255
242
}
257
244
/* 
258
245
 * Initialize GPGME.
259
246
 */
260
 
__attribute__((nonnull, warn_unused_result))
261
 
static bool init_gpgme(const char * const seckey,
262
 
                       const char * const pubkey,
263
 
                       const char * const tempdir,
264
 
                       mandos_context *mc){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
265
249
  gpgme_error_t rc;
266
250
  gpgme_engine_info_t engine_info;
267
251
  
 
252
  
268
253
  /*
269
254
   * Helper function to insert pub and seckey to the engine keyring.
270
255
   */
271
 
  bool import_key(const char * const filename){
 
256
  bool import_key(const char *filename){
272
257
    int ret;
273
258
    int fd;
274
259
    gpgme_data_t pgp_data;
286
271
      return false;
287
272
    }
288
273
    
289
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
290
275
    if(rc != GPG_ERR_NO_ERROR){
291
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
292
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
336
321
  }
337
322
  
338
323
  /* Create new GPGME "context" */
339
 
  rc = gpgme_new(&(mc->ctx));
 
324
  rc = gpgme_new(&(mc.ctx));
340
325
  if(rc != GPG_ERR_NO_ERROR){
341
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
342
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
355
340
 * Decrypt OpenPGP data.
356
341
 * Returns -1 on error
357
342
 */
358
 
__attribute__((nonnull, warn_unused_result))
359
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
360
344
                                  size_t crypto_size,
361
 
                                  char **plaintext,
362
 
                                  mandos_context *mc){
 
345
                                  char **plaintext){
363
346
  gpgme_data_t dh_crypto, dh_plain;
364
347
  gpgme_error_t rc;
365
348
  ssize_t ret;
391
374
  
392
375
  /* Decrypt data from the cryptotext data buffer to the plaintext
393
376
     data buffer */
394
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
395
378
  if(rc != GPG_ERR_NO_ERROR){
396
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
397
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
398
381
    plaintext_length = -1;
399
382
    if(debug){
400
383
      gpgme_decrypt_result_t result;
401
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
384
      result = gpgme_op_decrypt_result(mc.ctx);
402
385
      if(result == NULL){
403
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
404
387
      } else {
481
464
  return plaintext_length;
482
465
}
483
466
 
484
 
__attribute__((warn_unused_result))
485
 
static const char *safer_gnutls_strerror(int value){
486
 
  const char *ret = gnutls_strerror(value);
 
467
static const char * safer_gnutls_strerror(int value){
 
468
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
469
                                               -Wunreachable-code */
487
470
  if(ret == NULL)
488
471
    ret = "(unknown)";
489
472
  return ret;
490
473
}
491
474
 
492
475
/* GnuTLS log function callback */
493
 
__attribute__((nonnull))
494
476
static void debuggnutls(__attribute__((unused)) int level,
495
477
                        const char* string){
496
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
479
}
498
480
 
499
 
__attribute__((nonnull, warn_unused_result))
500
481
static int init_gnutls_global(const char *pubkeyfilename,
501
 
                              const char *seckeyfilename,
502
 
                              mandos_context *mc){
 
482
                              const char *seckeyfilename){
503
483
  int ret;
504
484
  
505
485
  if(debug){
522
502
  }
523
503
  
524
504
  /* OpenPGP credentials */
525
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
526
506
  if(ret != GNUTLS_E_SUCCESS){
527
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
528
508
                 safer_gnutls_strerror(ret));
538
518
  }
539
519
  
540
520
  ret = gnutls_certificate_set_openpgp_key_file
541
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
521
    (mc.cred, pubkeyfilename, seckeyfilename,
542
522
     GNUTLS_OPENPGP_FMT_BASE64);
543
523
  if(ret != GNUTLS_E_SUCCESS){
544
524
    fprintf_plus(stderr,
550
530
  }
551
531
  
552
532
  /* GnuTLS server initialization */
553
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
533
  ret = gnutls_dh_params_init(&mc.dh_params);
554
534
  if(ret != GNUTLS_E_SUCCESS){
555
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
556
536
                 " initialization: %s\n",
557
537
                 safer_gnutls_strerror(ret));
558
538
    goto globalfail;
559
539
  }
560
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
561
541
  if(ret != GNUTLS_E_SUCCESS){
562
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
563
543
                 safer_gnutls_strerror(ret));
564
544
    goto globalfail;
565
545
  }
566
546
  
567
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
547
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
568
548
  
569
549
  return 0;
570
550
  
571
551
 globalfail:
572
552
  
573
 
  gnutls_certificate_free_credentials(mc->cred);
 
553
  gnutls_certificate_free_credentials(mc.cred);
574
554
  gnutls_global_deinit();
575
 
  gnutls_dh_params_deinit(mc->dh_params);
 
555
  gnutls_dh_params_deinit(mc.dh_params);
576
556
  return -1;
577
557
}
578
558
 
579
 
__attribute__((nonnull, warn_unused_result))
580
 
static int init_gnutls_session(gnutls_session_t *session,
581
 
                               mandos_context *mc){
 
559
static int init_gnutls_session(gnutls_session_t *session){
582
560
  int ret;
583
561
  /* GnuTLS session creation */
584
562
  do {
596
574
  {
597
575
    const char *err;
598
576
    do {
599
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
577
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
600
578
      if(quit_now){
601
579
        gnutls_deinit(*session);
602
580
        return -1;
613
591
  
614
592
  do {
615
593
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
616
 
                                 mc->cred);
 
594
                                 mc.cred);
617
595
    if(quit_now){
618
596
      gnutls_deinit(*session);
619
597
      return -1;
629
607
  /* ignore client certificate if any. */
630
608
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
631
609
  
632
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
610
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
633
611
  
634
612
  return 0;
635
613
}
639
617
                      __attribute__((unused)) const char *txt){}
640
618
 
641
619
/* Called when a Mandos server is found */
642
 
__attribute__((nonnull, warn_unused_result))
643
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
620
static int start_mandos_communication(const char *ip, uint16_t port,
644
621
                                      AvahiIfIndex if_index,
645
 
                                      int af, mandos_context *mc){
 
622
                                      int af){
646
623
  int ret, tcp_sd = -1;
647
624
  ssize_t sret;
648
 
  struct sockaddr_storage to;
 
625
  union {
 
626
    struct sockaddr_in in;
 
627
    struct sockaddr_in6 in6;
 
628
  } to;
649
629
  char *buffer = NULL;
650
630
  char *decrypted_buffer = NULL;
651
631
  size_t buffer_length = 0;
675
655
    return -1;
676
656
  }
677
657
  
678
 
  /* If the interface is specified and we have a list of interfaces */
679
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
680
 
    /* Check if the interface is one of the interfaces we are using */
681
 
    bool match = false;
682
 
    {
683
 
      char *interface = NULL;
684
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
685
 
                                 interface))){
686
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
687
 
          match = true;
688
 
          break;
689
 
        }
690
 
      }
691
 
    }
692
 
    if(not match){
693
 
      /* This interface does not match any in the list, so we don't
694
 
         connect to the server */
695
 
      if(debug){
696
 
        char interface[IF_NAMESIZE];
697
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
698
 
          perror_plus("if_indextoname");
699
 
        } else {
700
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
701
 
                       " \"%s\"\n",
702
 
                       if_indextoname((unsigned int)if_index,
703
 
                                      interface));
704
 
        }
705
 
      }
706
 
      return -1;
707
 
    }
708
 
  }
709
 
  
710
 
  ret = init_gnutls_session(&session, mc);
 
658
  ret = init_gnutls_session(&session);
711
659
  if(ret != 0){
712
660
    return -1;
713
661
  }
714
662
  
715
663
  if(debug){
716
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
717
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
665
                 PRIu16 "\n", ip, port);
718
666
  }
719
667
  
720
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
732
680
  
733
681
  memset(&to, 0, sizeof(to));
734
682
  if(af == AF_INET6){
735
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
736
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
683
    to.in6.sin6_family = (sa_family_t)af;
 
684
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
737
685
  } else {                      /* IPv4 */
738
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
739
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
686
    to.in.sin_family = (sa_family_t)af;
 
687
    ret = inet_pton(af, ip, &to.in.sin_addr);
740
688
  }
741
689
  if(ret < 0 ){
742
690
    int e = errno;
751
699
    goto mandos_end;
752
700
  }
753
701
  if(af == AF_INET6){
754
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
755
 
    if(IN6_IS_ADDR_LINKLOCAL
756
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
702
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
703
                                       -Wconversion and
 
704
                                       -Wunreachable-code */
 
705
    
 
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
708
                                -Wunreachable-code*/
757
709
      if(if_index == AVAHI_IF_UNSPEC){
758
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
759
711
                     " incomplete without a network interface\n");
761
713
        goto mandos_end;
762
714
      }
763
715
      /* Set the network interface number as scope */
764
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
716
      to.in6.sin6_scope_id = (uint32_t)if_index;
765
717
    }
766
718
  } else {
767
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
719
    to.in.sin_port = htons(port); /* Spurious warnings from
 
720
                                     -Wconversion and
 
721
                                     -Wunreachable-code */
768
722
  }
769
723
  
770
724
  if(quit_now){
778
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
779
733
        perror_plus("if_indextoname");
780
734
      } else {
781
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
782
 
                     "\n", ip, interface, (uintmax_t)port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
783
737
      }
784
738
    } else {
785
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
786
 
                   ip, (uintmax_t)port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
787
741
    }
788
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
789
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
744
    const char *pcret;
790
745
    if(af == AF_INET6){
791
 
      ret = getnameinfo((struct sockaddr *)&to,
792
 
                        sizeof(struct sockaddr_in6),
793
 
                        addrstr, sizeof(addrstr), NULL, 0,
794
 
                        NI_NUMERICHOST);
 
746
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
747
                        sizeof(addrstr));
795
748
    } else {
796
 
      ret = getnameinfo((struct sockaddr *)&to,
797
 
                        sizeof(struct sockaddr_in),
798
 
                        addrstr, sizeof(addrstr), NULL, 0,
799
 
                        NI_NUMERICHOST);
 
749
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
750
                        sizeof(addrstr));
800
751
    }
801
 
    if(ret == EAI_SYSTEM){
802
 
      perror_plus("getnameinfo");
803
 
    } else if(ret != 0) {
804
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
805
 
    } else if(strcmp(addrstr, ip) != 0){
806
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
752
    if(pcret == NULL){
 
753
      perror_plus("inet_ntop");
 
754
    } else {
 
755
      if(strcmp(addrstr, ip) != 0){
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
757
      }
807
758
    }
808
759
  }
809
760
  
813
764
  }
814
765
  
815
766
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
 
767
    ret = connect(tcp_sd, &to.in6, sizeof(to));
818
768
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
 
769
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
821
770
  }
822
771
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
772
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
773
      int e = errno;
825
774
      perror_plus("connect");
826
775
      errno = e;
987
936
  if(buffer_length > 0){
988
937
    ssize_t decrypted_buffer_size;
989
938
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
990
 
                                               &decrypted_buffer, mc);
 
939
                                               &decrypted_buffer);
991
940
    if(decrypted_buffer_size >= 0){
992
941
      
993
942
      written = 0;
1041
990
  return retval;
1042
991
}
1043
992
 
1044
 
__attribute__((nonnull))
1045
993
static void resolve_callback(AvahiSServiceResolver *r,
1046
994
                             AvahiIfIndex interface,
1047
995
                             AvahiProtocol proto,
1055
1003
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1056
1004
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1057
1005
                             flags,
1058
 
                             void *mc){
1059
 
  if(r == NULL){
1060
 
    return;
1061
 
  }
 
1006
                             AVAHI_GCC_UNUSED void* userdata){
 
1007
  assert(r);
1062
1008
  
1063
1009
  /* Called whenever a service has been resolved successfully or
1064
1010
     timed out */
1073
1019
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1074
1020
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1075
1021
                 domain,
1076
 
                 avahi_strerror(avahi_server_errno
1077
 
                                (((mandos_context*)mc)->server)));
 
1022
                 avahi_strerror(avahi_server_errno(mc.server)));
1078
1023
    break;
1079
1024
    
1080
1025
  case AVAHI_RESOLVER_FOUND:
1086
1031
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1087
1032
                     host_name, ip, (intmax_t)interface, port);
1088
1033
      }
1089
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1090
 
                                           interface,
1091
 
                                           avahi_proto_to_af(proto),
1092
 
                                           mc);
 
1034
      int ret = start_mandos_communication(ip, port, interface,
 
1035
                                           avahi_proto_to_af(proto));
1093
1036
      if(ret == 0){
1094
 
        avahi_simple_poll_quit(simple_poll);
 
1037
        avahi_simple_poll_quit(mc.simple_poll);
1095
1038
      } else {
1096
 
        if(not add_server(ip, (in_port_t)port, interface,
1097
 
                          avahi_proto_to_af(proto),
1098
 
                          &((mandos_context*)mc)->current_server)){
 
1039
        if(not add_server(ip, port, interface,
 
1040
                          avahi_proto_to_af(proto))){
1099
1041
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1100
1042
                       " list\n", name);
1101
1043
        }
1114
1056
                            const char *domain,
1115
1057
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1116
1058
                            flags,
1117
 
                            void *mc){
1118
 
  if(b == NULL){
1119
 
    return;
1120
 
  }
 
1059
                            AVAHI_GCC_UNUSED void* userdata){
 
1060
  assert(b);
1121
1061
  
1122
1062
  /* Called whenever a new services becomes available on the LAN or
1123
1063
     is removed from the LAN */
1131
1071
  case AVAHI_BROWSER_FAILURE:
1132
1072
    
1133
1073
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1134
 
                 avahi_strerror(avahi_server_errno
1135
 
                                (((mandos_context*)mc)->server)));
1136
 
    avahi_simple_poll_quit(simple_poll);
 
1074
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1075
    avahi_simple_poll_quit(mc.simple_poll);
1137
1076
    return;
1138
1077
    
1139
1078
  case AVAHI_BROWSER_NEW:
1142
1081
       the callback function is called the Avahi server will free the
1143
1082
       resolver for us. */
1144
1083
    
1145
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1146
 
                                    interface, protocol, name, type,
1147
 
                                    domain, protocol, 0,
1148
 
                                    resolve_callback, mc) == NULL)
 
1084
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1085
                                    name, type, domain, protocol, 0,
 
1086
                                    resolve_callback, NULL) == NULL)
1149
1087
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1150
1088
                   " %s\n", name,
1151
 
                   avahi_strerror(avahi_server_errno
1152
 
                                  (((mandos_context*)mc)->server)));
 
1089
                   avahi_strerror(avahi_server_errno(mc.server)));
1153
1090
    break;
1154
1091
    
1155
1092
  case AVAHI_BROWSER_REMOVE:
1174
1111
  signal_received = sig;
1175
1112
  int old_errno = errno;
1176
1113
  /* set main loop to exit */
1177
 
  if(simple_poll != NULL){
1178
 
    avahi_simple_poll_quit(simple_poll);
 
1114
  if(mc.simple_poll != NULL){
 
1115
    avahi_simple_poll_quit(mc.simple_poll);
1179
1116
  }
1180
1117
  errno = old_errno;
1181
1118
}
1182
1119
 
1183
 
__attribute__((nonnull, warn_unused_result))
1184
1120
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1121
  int ret;
1186
 
  error_t ret_errno;
1187
1122
  
1188
1123
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1189
1124
  if(s < 0){
1190
 
    ret_errno = errno;
1191
1125
    perror_plus("socket");
1192
 
    errno = ret_errno;
1193
1126
    return false;
1194
1127
  }
1195
1128
  strcpy(ifr->ifr_name, ifname);
1196
1129
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1197
1130
  if(ret == -1){
1198
1131
    if(debug){
1199
 
      ret_errno = errno;
1200
1132
      perror_plus("ioctl SIOCGIFFLAGS");
1201
 
      errno = ret_errno;
1202
1133
    }
1203
1134
    return false;
1204
1135
  }
1205
1136
  return true;
1206
1137
}
1207
1138
 
1208
 
__attribute__((nonnull, warn_unused_result))
1209
1139
bool good_flags(const char *ifname, const struct ifreq *ifr){
1210
1140
  
1211
1141
  /* Reject the loopback device */
1253
1183
 * corresponds to an acceptable network device.
1254
1184
 * (This function is passed to scandir(3) as a filter function.)
1255
1185
 */
1256
 
__attribute__((nonnull, warn_unused_result))
1257
1186
int good_interface(const struct dirent *if_entry){
1258
1187
  if(if_entry->d_name[0] == '.'){
1259
1188
    return 0;
1275
1204
}
1276
1205
 
1277
1206
/* 
1278
 
 * This function determines if a network interface is up.
1279
 
 */
1280
 
__attribute__((nonnull, warn_unused_result))
1281
 
bool interface_is_up(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_UP);
1292
 
}
1293
 
 
1294
 
/* 
1295
 
 * This function determines if a network interface is running
1296
 
 */
1297
 
__attribute__((nonnull, warn_unused_result))
1298
 
bool interface_is_running(const char *interface){
1299
 
  struct ifreq ifr;
1300
 
  if(not get_flags(interface, &ifr)){
1301
 
    if(debug){
1302
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1303
 
                   "\"%s\"\n", interface);
1304
 
    }
1305
 
    return false;
1306
 
  }
1307
 
  
1308
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1309
 
}
1310
 
 
1311
 
__attribute__((nonnull, pure, warn_unused_result))
 
1207
 * This function determines if a directory entry in /sys/class/net
 
1208
 * corresponds to an acceptable network device which is up.
 
1209
 * (This function is passed to scandir(3) as a filter function.)
 
1210
 */
 
1211
int up_interface(const struct dirent *if_entry){
 
1212
  if(if_entry->d_name[0] == '.'){
 
1213
    return 0;
 
1214
  }
 
1215
  
 
1216
  struct ifreq ifr;
 
1217
  if(not get_flags(if_entry->d_name, &ifr)){
 
1218
    if(debug){
 
1219
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1220
                   "\"%s\"\n", if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  /* Reject down interfaces */
 
1226
  if(not (ifr.ifr_flags & IFF_UP)){
 
1227
    if(debug){
 
1228
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1229
                   if_entry->d_name);
 
1230
    }
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  /* Reject non-running interfaces */
 
1235
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1236
    if(debug){
 
1237
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1238
                   if_entry->d_name);
 
1239
    }
 
1240
    return 0;
 
1241
  }
 
1242
  
 
1243
  if(not good_flags(if_entry->d_name, &ifr)){
 
1244
    return 0;
 
1245
  }
 
1246
  return 1;
 
1247
}
 
1248
 
1312
1249
int notdotentries(const struct dirent *direntry){
1313
1250
  /* Skip "." and ".." */
1314
1251
  if(direntry->d_name[0] == '.'
1321
1258
}
1322
1259
 
1323
1260
/* Is this directory entry a runnable program? */
1324
 
__attribute__((nonnull, warn_unused_result))
1325
1261
int runnable_hook(const struct dirent *direntry){
1326
1262
  int ret;
1327
1263
  size_t sret;
1382
1318
  return 1;
1383
1319
}
1384
1320
 
1385
 
__attribute__((nonnull, warn_unused_result))
1386
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1387
 
                            mandos_context *mc){
 
1321
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1388
1322
  int ret;
1389
1323
  struct timespec now;
1390
1324
  struct timespec waited_time;
1391
1325
  intmax_t block_time;
1392
1326
  
1393
1327
  while(true){
1394
 
    if(mc->current_server == NULL){
1395
 
      if(debug){
 
1328
    if(mc.current_server == NULL){
 
1329
      if (debug){
1396
1330
        fprintf_plus(stderr, "Wait until first server is found."
1397
1331
                     " No timeout!\n");
1398
1332
      }
1399
1333
      ret = avahi_simple_poll_iterate(s, -1);
1400
1334
    } else {
1401
 
      if(debug){
 
1335
      if (debug){
1402
1336
        fprintf_plus(stderr, "Check current_server if we should run"
1403
1337
                     " it, or wait\n");
1404
1338
      }
1411
1345
      /* Calculating in ms how long time between now and server
1412
1346
         who we visted longest time ago. Now - last seen.  */
1413
1347
      waited_time.tv_sec = (now.tv_sec
1414
 
                            - mc->current_server->last_seen.tv_sec);
 
1348
                            - mc.current_server->last_seen.tv_sec);
1415
1349
      waited_time.tv_nsec = (now.tv_nsec
1416
 
                             - mc->current_server->last_seen.tv_nsec);
 
1350
                             - mc.current_server->last_seen.tv_nsec);
1417
1351
      /* total time is 10s/10,000ms.
1418
1352
         Converting to s from ms by dividing by 1,000,
1419
1353
         and ns to ms by dividing by 1,000,000. */
1421
1355
                     - ((intmax_t)waited_time.tv_sec * 1000))
1422
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1423
1357
      
1424
 
      if(debug){
 
1358
      if (debug){
1425
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1426
1360
                     block_time);
1427
1361
      }
1428
1362
      
1429
1363
      if(block_time <= 0){
1430
 
        ret = start_mandos_communication(mc->current_server->ip,
1431
 
                                         mc->current_server->port,
1432
 
                                         mc->current_server->if_index,
1433
 
                                         mc->current_server->af, mc);
 
1364
        ret = start_mandos_communication(mc.current_server->ip,
 
1365
                                         mc.current_server->port,
 
1366
                                         mc.current_server->if_index,
 
1367
                                         mc.current_server->af);
1434
1368
        if(ret == 0){
1435
 
          avahi_simple_poll_quit(s);
 
1369
          avahi_simple_poll_quit(mc.simple_poll);
1436
1370
          return 0;
1437
1371
        }
1438
1372
        ret = clock_gettime(CLOCK_MONOTONIC,
1439
 
                            &mc->current_server->last_seen);
 
1373
                            &mc.current_server->last_seen);
1440
1374
        if(ret == -1){
1441
1375
          perror_plus("clock_gettime");
1442
1376
          return -1;
1443
1377
        }
1444
 
        mc->current_server = mc->current_server->next;
 
1378
        mc.current_server = mc.current_server->next;
1445
1379
        block_time = 0;         /* Call avahi to find new Mandos
1446
1380
                                   servers, but don't block */
1447
1381
      }
1449
1383
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1450
1384
    }
1451
1385
    if(ret != 0){
1452
 
      if(ret > 0 or errno != EINTR){
 
1386
      if (ret > 0 or errno != EINTR){
1453
1387
        return (ret != 1) ? ret : 0;
1454
1388
      }
1455
1389
    }
1456
1390
  }
1457
1391
}
1458
1392
 
1459
 
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
 
error_t raise_privileges(void){
1462
 
  error_t old_errno = errno;
1463
 
  error_t ret_errno = 0;
1464
 
  if(seteuid(0) == -1){
1465
 
    ret_errno = errno;
1466
 
    perror_plus("seteuid");
1467
 
  }
1468
 
  errno = old_errno;
1469
 
  return ret_errno;
1470
 
}
1471
 
 
1472
 
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
 
error_t raise_privileges_permanently(void){
1475
 
  error_t old_errno = errno;
1476
 
  error_t ret_errno = raise_privileges();
1477
 
  if(ret_errno != 0){
1478
 
    errno = old_errno;
1479
 
    return ret_errno;
1480
 
  }
1481
 
  if(setuid(0) == -1){
1482
 
    ret_errno = errno;
1483
 
    perror_plus("seteuid");
1484
 
  }
1485
 
  errno = old_errno;
1486
 
  return ret_errno;
1487
 
}
1488
 
 
1489
 
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
 
error_t lower_privileges(void){
1492
 
  error_t old_errno = errno;
1493
 
  error_t ret_errno = 0;
1494
 
  if(seteuid(uid) == -1){
1495
 
    ret_errno = errno;
1496
 
    perror_plus("seteuid");
1497
 
  }
1498
 
  errno = old_errno;
1499
 
  return ret_errno;
1500
 
}
1501
 
 
1502
 
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
 
error_t lower_privileges_permanently(void){
1505
 
  error_t old_errno = errno;
1506
 
  error_t ret_errno = 0;
1507
 
  if(setuid(uid) == -1){
1508
 
    ret_errno = errno;
1509
 
    perror_plus("setuid");
1510
 
  }
1511
 
  errno = old_errno;
1512
 
  return ret_errno;
1513
 
}
1514
 
 
1515
 
__attribute__((nonnull))
1516
 
void run_network_hooks(const char *mode, const char *interface,
 
1393
bool run_network_hooks(const char *mode, const char *interface,
1517
1394
                       const float delay){
1518
1395
  struct dirent **direntries;
 
1396
  struct dirent *direntry;
 
1397
  int ret;
1519
1398
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
1399
                         alphasort);
1521
1400
  if(numhooks == -1){
1522
 
    if(errno == ENOENT){
1523
 
      if(debug){
1524
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1525
 
                     " found\n", hookdir);
1526
 
      }
1527
 
    } else {
1528
 
      perror_plus("scandir");
1529
 
    }
 
1401
    perror_plus("scandir");
1530
1402
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
1403
    int devnull = open("/dev/null", O_RDONLY);
1534
1404
    for(int i = 0; i < numhooks; i++){
1535
1405
      direntry = direntries[i];
1547
1417
      if(hook_pid == 0){
1548
1418
        /* Child */
1549
1419
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
 
1420
        errno = 0;
 
1421
        ret = seteuid(0);
 
1422
        if(ret == -1){
 
1423
          perror_plus("seteuid");
 
1424
        }
 
1425
        /* Raise privileges even more */
 
1426
        errno = 0;
 
1427
        ret = setuid(0);
 
1428
        if(ret == -1){
 
1429
          perror_plus("setuid");
1553
1430
        }
1554
1431
        /* Set group */
1555
1432
        errno = 0;
1556
1433
        ret = setgid(0);
1557
1434
        if(ret == -1){
1558
1435
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
1436
        }
1561
1437
        /* Reset supplementary groups */
1562
1438
        errno = 0;
1563
1439
        ret = setgroups(0, NULL);
1564
1440
        if(ret == -1){
1565
1441
          perror_plus("setgroups");
1566
 
          _exit(EX_NOPERM);
1567
 
        }
1568
 
        ret = dup2(devnull, STDIN_FILENO);
1569
 
        if(ret == -1){
1570
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1571
 
          _exit(EX_OSERR);
1572
 
        }
1573
 
        ret = close(devnull);
1574
 
        if(ret == -1){
1575
 
          perror_plus("close");
1576
 
          _exit(EX_OSERR);
1577
 
        }
1578
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1579
 
        if(ret == -1){
1580
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1581
 
          _exit(EX_OSERR);
1582
 
        }
 
1442
        }
 
1443
        dup2(devnull, STDIN_FILENO);
 
1444
        close(devnull);
 
1445
        dup2(STDERR_FILENO, STDOUT_FILENO);
1583
1446
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
1447
        if(ret == -1){
1585
1448
          perror_plus("setenv");
1601
1464
          _exit(EX_OSERR);
1602
1465
        }
1603
1466
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1467
        ret = asprintf(&delaystring, "%f", delay);
1605
1468
        if(ret == -1){
1606
1469
          perror_plus("asprintf");
1607
1470
          _exit(EX_OSERR);
1660
1523
    }
1661
1524
    close(devnull);
1662
1525
  }
1663
 
}
1664
 
 
1665
 
__attribute__((nonnull, warn_unused_result))
1666
 
error_t bring_up_interface(const char *const interface,
1667
 
                           const float delay){
1668
 
  error_t old_errno = errno;
1669
 
  int ret;
1670
 
  struct ifreq network;
1671
 
  unsigned int if_index = if_nametoindex(interface);
1672
 
  if(if_index == 0){
1673
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1674
 
    errno = old_errno;
1675
 
    return ENXIO;
1676
 
  }
1677
 
  
1678
 
  if(quit_now){
1679
 
    errno = old_errno;
1680
 
    return EINTR;
1681
 
  }
1682
 
  
1683
 
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
1685
 
    if(not get_flags(interface, &network)){
1686
 
      ret_errno = errno;
1687
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1688
 
                   "\"%s\"\n", interface);
1689
 
      errno = old_errno;
1690
 
      return ret_errno;
1691
 
    }
1692
 
    network.ifr_flags |= IFF_UP; /* set flag */
1693
 
    
1694
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1695
 
    if(sd == -1){
1696
 
      ret_errno = errno;
1697
 
      perror_plus("socket");
1698
 
      errno = old_errno;
1699
 
      return ret_errno;
1700
 
    }
1701
 
    
1702
 
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1704
 
      if(ret == -1){
1705
 
        perror_plus("close");
1706
 
      }
1707
 
      errno = old_errno;
1708
 
      return EINTR;
1709
 
    }
1710
 
    
1711
 
    if(debug){
1712
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1713
 
                   interface);
1714
 
    }
1715
 
    
1716
 
    /* Raise privileges */
1717
 
    ret_errno = raise_privileges();
1718
 
    if(ret_errno != 0){
1719
 
      perror_plus("Failed to raise privileges");
1720
 
    }
1721
 
    
1722
 
#ifdef __linux__
1723
 
    int ret_linux;
1724
 
    bool restore_loglevel = false;
1725
 
    if(ret_errno == 0){
1726
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1727
 
         messages about the network interface to mess up the prompt */
1728
 
      ret_linux = klogctl(8, NULL, 5);
1729
 
      if(ret_linux == -1){
1730
 
        perror_plus("klogctl");
1731
 
      } else {
1732
 
        restore_loglevel = true;
1733
 
      }
1734
 
    }
1735
 
#endif  /* __linux__ */
1736
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1737
 
    ioctl_errno = errno;
1738
 
#ifdef __linux__
1739
 
    if(restore_loglevel){
1740
 
      ret_linux = klogctl(7, NULL, 0);
1741
 
      if(ret_linux == -1){
1742
 
        perror_plus("klogctl");
1743
 
      }
1744
 
    }
1745
 
#endif  /* __linux__ */
1746
 
    
1747
 
    /* If raise_privileges() succeeded above */
1748
 
    if(ret_errno == 0){
1749
 
      /* Lower privileges */
1750
 
      ret_errno = lower_privileges();
1751
 
      if(ret_errno != 0){
1752
 
        errno = ret_errno;
1753
 
        perror_plus("Failed to lower privileges");
1754
 
      }
1755
 
    }
1756
 
    
1757
 
    /* Close the socket */
1758
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1759
 
    if(ret == -1){
1760
 
      perror_plus("close");
1761
 
    }
1762
 
    
1763
 
    if(ret_setflags == -1){
1764
 
      errno = ioctl_errno;
1765
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1766
 
      errno = old_errno;
1767
 
      return ioctl_errno;
1768
 
    }
1769
 
  } else if(debug){
1770
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1771
 
                 interface);
1772
 
  }
1773
 
  
1774
 
  /* Sleep checking until interface is running.
1775
 
     Check every 0.25s, up to total time of delay */
1776
 
  for(int i=0; i < delay * 4; i++){
1777
 
    if(interface_is_running(interface)){
1778
 
      break;
1779
 
    }
1780
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1781
 
    ret = nanosleep(&sleeptime, NULL);
1782
 
    if(ret == -1 and errno != EINTR){
1783
 
      perror_plus("nanosleep");
1784
 
    }
1785
 
  }
1786
 
  
1787
 
  errno = old_errno;
1788
 
  return 0;
1789
 
}
1790
 
 
1791
 
__attribute__((nonnull, warn_unused_result))
1792
 
error_t take_down_interface(const char *const interface){
1793
 
  error_t old_errno = errno;
1794
 
  struct ifreq network;
1795
 
  unsigned int if_index = if_nametoindex(interface);
1796
 
  if(if_index == 0){
1797
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1798
 
    errno = old_errno;
1799
 
    return ENXIO;
1800
 
  }
1801
 
  if(interface_is_up(interface)){
1802
 
    error_t ret_errno = 0, ioctl_errno = 0;
1803
 
    if(not get_flags(interface, &network) and debug){
1804
 
      ret_errno = errno;
1805
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1806
 
                   "\"%s\"\n", interface);
1807
 
      errno = old_errno;
1808
 
      return ret_errno;
1809
 
    }
1810
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1811
 
    
1812
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1813
 
    if(sd == -1){
1814
 
      ret_errno = errno;
1815
 
      perror_plus("socket");
1816
 
      errno = old_errno;
1817
 
      return ret_errno;
1818
 
    }
1819
 
    
1820
 
    if(debug){
1821
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1822
 
                   interface);
1823
 
    }
1824
 
    
1825
 
    /* Raise privileges */
1826
 
    ret_errno = raise_privileges();
1827
 
    if(ret_errno != 0){
1828
 
      perror_plus("Failed to raise privileges");
1829
 
    }
1830
 
    
1831
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1832
 
    ioctl_errno = errno;
1833
 
    
1834
 
    /* If raise_privileges() succeeded above */
1835
 
    if(ret_errno == 0){
1836
 
      /* Lower privileges */
1837
 
      ret_errno = lower_privileges();
1838
 
      if(ret_errno != 0){
1839
 
        errno = ret_errno;
1840
 
        perror_plus("Failed to lower privileges");
1841
 
      }
1842
 
    }
1843
 
    
1844
 
    /* Close the socket */
1845
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1846
 
    if(ret == -1){
1847
 
      perror_plus("close");
1848
 
    }
1849
 
    
1850
 
    if(ret_setflags == -1){
1851
 
      errno = ioctl_errno;
1852
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1853
 
      errno = old_errno;
1854
 
      return ioctl_errno;
1855
 
    }
1856
 
  } else if(debug){
1857
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1858
 
                 interface);
1859
 
  }
1860
 
  
1861
 
  errno = old_errno;
1862
 
  return 0;
 
1526
  return true;
1863
1527
}
1864
1528
 
1865
1529
int main(int argc, char *argv[]){
1866
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1867
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1868
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1869
 
                        .interfaces = NULL, .interfaces_size = 0 };
1870
1530
  AvahiSServiceBrowser *sb = NULL;
1871
 
  error_t ret_errno;
 
1531
  int error;
1872
1532
  int ret;
1873
1533
  intmax_t tmpmax;
1874
1534
  char *tmp;
1875
1535
  int exitcode = EXIT_SUCCESS;
1876
 
  char *interfaces_to_take_down = NULL;
1877
 
  size_t interfaces_to_take_down_size = 0;
1878
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1879
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1880
 
  char *tempdir = NULL;
 
1536
  const char *interface = "";
 
1537
  struct ifreq network;
 
1538
  int sd = -1;
 
1539
  bool take_down_interface = false;
 
1540
  uid_t uid;
 
1541
  gid_t gid;
 
1542
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1543
  bool tempdir_created = false;
1881
1544
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1882
1545
  const char *seckey = PATHDIR "/" SECKEY;
1883
1546
  const char *pubkey = PATHDIR "/" PUBKEY;
1884
 
  char *interfaces_hooks = NULL;
1885
1547
  
1886
1548
  bool gnutls_initialized = false;
1887
1549
  bool gpgme_initialized = false;
1978
1640
        connect_to = arg;
1979
1641
        break;
1980
1642
      case 'i':                 /* --interface */
1981
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1982
 
                                 arg, (int)',');
1983
 
        if(ret_errno != 0){
1984
 
          argp_error(state, "%s", strerror(ret_errno));
1985
 
        }
 
1643
        interface = arg;
1986
1644
        break;
1987
1645
      case 's':                 /* --seckey */
1988
1646
        seckey = arg;
2065
1723
    /* Work around Debian bug #633582:
2066
1724
       <http://bugs.debian.org/633582> */
2067
1725
    
2068
 
    /* Re-raise privileges */
2069
 
    ret_errno = raise_privileges();
2070
 
    if(ret_errno != 0){
2071
 
      errno = ret_errno;
2072
 
      perror_plus("Failed to raise privileges");
 
1726
    /* Re-raise priviliges */
 
1727
    errno = 0;
 
1728
    ret = seteuid(0);
 
1729
    if(ret == -1){
 
1730
      perror_plus("seteuid");
2073
1731
    } else {
2074
1732
      struct stat st;
2075
1733
      
2116
1774
      }
2117
1775
    
2118
1776
      /* Lower privileges */
2119
 
      ret_errno = lower_privileges();
2120
 
      if(ret_errno != 0){
2121
 
        errno = ret_errno;
2122
 
        perror_plus("Failed to lower privileges");
2123
 
      }
2124
 
    }
2125
 
  }
2126
 
  
2127
 
  /* Remove invalid interface names (except "none") */
2128
 
  {
2129
 
    char *interface = NULL;
2130
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2131
 
                                 interface))){
2132
 
      if(strcmp(interface, "none") != 0
2133
 
         and if_nametoindex(interface) == 0){
2134
 
        if(interface[0] != '\0'){
2135
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2136
 
                       " \"%s\"\n", interface);
2137
 
        }
2138
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2139
 
        interface = NULL;
 
1777
      errno = 0;
 
1778
      ret = seteuid(uid);
 
1779
      if(ret == -1){
 
1780
        perror_plus("seteuid");
2140
1781
      }
2141
1782
    }
2142
1783
  }
2143
1784
  
2144
1785
  /* Run network hooks */
2145
 
  {
2146
 
    if(mc.interfaces != NULL){
2147
 
      interfaces_hooks = malloc(mc.interfaces_size);
2148
 
      if(interfaces_hooks == NULL){
2149
 
        perror_plus("malloc");
2150
 
        goto end;
2151
 
      }
2152
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2153
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2154
 
    }
2155
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2156
 
                      interfaces_hooks : "", delay);
 
1786
  if(not run_network_hooks("start", interface, delay)){
 
1787
    goto end;
2157
1788
  }
2158
1789
  
2159
1790
  if(not debug){
2160
1791
    avahi_set_log_function(empty_log);
2161
1792
  }
2162
1793
  
 
1794
  if(interface[0] == '\0'){
 
1795
    struct dirent **direntries;
 
1796
    /* First look for interfaces that are up */
 
1797
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1798
                  alphasort);
 
1799
    if(ret == 0){
 
1800
      /* No up interfaces, look for any good interfaces */
 
1801
      free(direntries);
 
1802
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1803
                    alphasort);
 
1804
    }
 
1805
    if(ret >= 1){
 
1806
      /* Pick the first interface returned */
 
1807
      interface = strdup(direntries[0]->d_name);
 
1808
      if(debug){
 
1809
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1810
      }
 
1811
      if(interface == NULL){
 
1812
        perror_plus("malloc");
 
1813
        free(direntries);
 
1814
        exitcode = EXIT_FAILURE;
 
1815
        goto end;
 
1816
      }
 
1817
      free(direntries);
 
1818
    } else {
 
1819
      free(direntries);
 
1820
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1821
      exitcode = EXIT_FAILURE;
 
1822
      goto end;
 
1823
    }
 
1824
  }
 
1825
  
2163
1826
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2164
1827
     from the signal handler */
2165
1828
  /* Initialize the pseudo-RNG for Avahi */
2166
1829
  srand((unsigned int) time(NULL));
2167
 
  simple_poll = avahi_simple_poll_new();
2168
 
  if(simple_poll == NULL){
 
1830
  mc.simple_poll = avahi_simple_poll_new();
 
1831
  if(mc.simple_poll == NULL){
2169
1832
    fprintf_plus(stderr,
2170
1833
                 "Avahi: Failed to create simple poll object.\n");
2171
1834
    exitcode = EX_UNAVAILABLE;
2235
1898
    }
2236
1899
  }
2237
1900
  
2238
 
  /* If no interfaces were specified, make a list */
2239
 
  if(mc.interfaces == NULL){
2240
 
    struct dirent **direntries;
2241
 
    /* Look for any good interfaces */
2242
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2243
 
                  alphasort);
2244
 
    if(ret >= 1){
2245
 
      /* Add all found interfaces to interfaces list */
2246
 
      for(int i = 0; i < ret; ++i){
2247
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2248
 
                             direntries[i]->d_name);
2249
 
        if(ret_errno != 0){
2250
 
          errno = ret_errno;
2251
 
          perror_plus("argz_add");
2252
 
          continue;
2253
 
        }
2254
 
        if(debug){
2255
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2256
 
                       direntries[i]->d_name);
2257
 
        }
2258
 
      }
2259
 
      free(direntries);
2260
 
    } else {
2261
 
      free(direntries);
2262
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2263
 
      exitcode = EXIT_FAILURE;
2264
 
      goto end;
2265
 
    }
2266
 
  }
2267
 
  
2268
 
  /* Bring up interfaces which are down, and remove any "none"s */
2269
 
  {
2270
 
    char *interface = NULL;
2271
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2272
 
                                 interface))){
2273
 
      /* If interface name is "none", stop bringing up interfaces.
2274
 
         Also remove all instances of "none" from the list */
2275
 
      if(strcmp(interface, "none") == 0){
2276
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2277
 
                    interface);
2278
 
        interface = NULL;
2279
 
        while((interface = argz_next(mc.interfaces,
2280
 
                                     mc.interfaces_size, interface))){
2281
 
          if(strcmp(interface, "none") == 0){
2282
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2283
 
                        interface);
2284
 
            interface = NULL;
 
1901
  /* If the interface is down, bring it up */
 
1902
  if(strcmp(interface, "none") != 0){
 
1903
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1904
    if(if_index == 0){
 
1905
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1906
      exitcode = EX_UNAVAILABLE;
 
1907
      goto end;
 
1908
    }
 
1909
    
 
1910
    if(quit_now){
 
1911
      goto end;
 
1912
    }
 
1913
    
 
1914
    /* Re-raise priviliges */
 
1915
    errno = 0;
 
1916
    ret = seteuid(0);
 
1917
    if(ret == -1){
 
1918
      perror_plus("seteuid");
 
1919
    }
 
1920
    
 
1921
#ifdef __linux__
 
1922
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1923
       messages about the network interface to mess up the prompt */
 
1924
    ret = klogctl(8, NULL, 5);
 
1925
    bool restore_loglevel = true;
 
1926
    if(ret == -1){
 
1927
      restore_loglevel = false;
 
1928
      perror_plus("klogctl");
 
1929
    }
 
1930
#endif  /* __linux__ */
 
1931
    
 
1932
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1933
    if(sd < 0){
 
1934
      perror_plus("socket");
 
1935
      exitcode = EX_OSERR;
 
1936
#ifdef __linux__
 
1937
      if(restore_loglevel){
 
1938
        ret = klogctl(7, NULL, 0);
 
1939
        if(ret == -1){
 
1940
          perror_plus("klogctl");
 
1941
        }
 
1942
      }
 
1943
#endif  /* __linux__ */
 
1944
      /* Lower privileges */
 
1945
      errno = 0;
 
1946
      ret = seteuid(uid);
 
1947
      if(ret == -1){
 
1948
        perror_plus("seteuid");
 
1949
      }
 
1950
      goto end;
 
1951
    }
 
1952
    strcpy(network.ifr_name, interface);
 
1953
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1954
    if(ret == -1){
 
1955
      perror_plus("ioctl SIOCGIFFLAGS");
 
1956
#ifdef __linux__
 
1957
      if(restore_loglevel){
 
1958
        ret = klogctl(7, NULL, 0);
 
1959
        if(ret == -1){
 
1960
          perror_plus("klogctl");
 
1961
        }
 
1962
      }
 
1963
#endif  /* __linux__ */
 
1964
      exitcode = EX_OSERR;
 
1965
      /* Lower privileges */
 
1966
      errno = 0;
 
1967
      ret = seteuid(uid);
 
1968
      if(ret == -1){
 
1969
        perror_plus("seteuid");
 
1970
      }
 
1971
      goto end;
 
1972
    }
 
1973
    if((network.ifr_flags & IFF_UP) == 0){
 
1974
      network.ifr_flags |= IFF_UP;
 
1975
      take_down_interface = true;
 
1976
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1977
      if(ret == -1){
 
1978
        take_down_interface = false;
 
1979
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1980
        exitcode = EX_OSERR;
 
1981
#ifdef __linux__
 
1982
        if(restore_loglevel){
 
1983
          ret = klogctl(7, NULL, 0);
 
1984
          if(ret == -1){
 
1985
            perror_plus("klogctl");
2285
1986
          }
2286
1987
        }
 
1988
#endif  /* __linux__ */
 
1989
        /* Lower privileges */
 
1990
        errno = 0;
 
1991
        ret = seteuid(uid);
 
1992
        if(ret == -1){
 
1993
          perror_plus("seteuid");
 
1994
        }
 
1995
        goto end;
 
1996
      }
 
1997
    }
 
1998
    /* Sleep checking until interface is running.
 
1999
       Check every 0.25s, up to total time of delay */
 
2000
    for(int i=0; i < delay * 4; i++){
 
2001
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2002
      if(ret == -1){
 
2003
        perror_plus("ioctl SIOCGIFFLAGS");
 
2004
      } else if(network.ifr_flags & IFF_RUNNING){
2287
2005
        break;
2288
2006
      }
2289
 
      bool interface_was_up = interface_is_up(interface);
2290
 
      errno = bring_up_interface(interface, delay);
2291
 
      if(not interface_was_up){
2292
 
        if(errno != 0){
2293
 
          perror_plus("Failed to bring up interface");
2294
 
        } else {
2295
 
          errno = argz_add(&interfaces_to_take_down,
2296
 
                           &interfaces_to_take_down_size,
2297
 
                           interface);
2298
 
          if(errno != 0){
2299
 
            perror_plus("argz_add");
2300
 
          }
2301
 
        }
2302
 
      }
2303
 
    }
2304
 
    if(debug and (interfaces_to_take_down == NULL)){
2305
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2306
 
    }
2307
 
  }
2308
 
  
2309
 
  /* If we only got one interface, explicitly use only that one */
2310
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2311
 
    if(debug){
2312
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2313
 
                   mc.interfaces);
2314
 
    }
2315
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
2007
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
2008
      ret = nanosleep(&sleeptime, NULL);
 
2009
      if(ret == -1 and errno != EINTR){
 
2010
        perror_plus("nanosleep");
 
2011
      }
 
2012
    }
 
2013
    if(not take_down_interface){
 
2014
      /* We won't need the socket anymore */
 
2015
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2016
      if(ret == -1){
 
2017
        perror_plus("close");
 
2018
      }
 
2019
    }
 
2020
#ifdef __linux__
 
2021
    if(restore_loglevel){
 
2022
      /* Restores kernel loglevel to default */
 
2023
      ret = klogctl(7, NULL, 0);
 
2024
      if(ret == -1){
 
2025
        perror_plus("klogctl");
 
2026
      }
 
2027
    }
 
2028
#endif  /* __linux__ */
 
2029
    /* Lower privileges */
 
2030
    errno = 0;
 
2031
    /* Lower privileges */
 
2032
    ret = seteuid(uid);
 
2033
    if(ret == -1){
 
2034
      perror_plus("seteuid");
 
2035
    }
2316
2036
  }
2317
2037
  
2318
2038
  if(quit_now){
2319
2039
    goto end;
2320
2040
  }
2321
2041
  
2322
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2042
  ret = init_gnutls_global(pubkey, seckey);
2323
2043
  if(ret == -1){
2324
2044
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2325
2045
    exitcode = EX_UNAVAILABLE;
2332
2052
    goto end;
2333
2053
  }
2334
2054
  
2335
 
  /* Try /run/tmp before /tmp */
2336
 
  tempdir = mkdtemp(run_tempdir);
2337
 
  if(tempdir == NULL and errno == ENOENT){
2338
 
      if(debug){
2339
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2340
 
                     run_tempdir, old_tempdir);
2341
 
      }
2342
 
      tempdir = mkdtemp(old_tempdir);
2343
 
  }
2344
 
  if(tempdir == NULL){
 
2055
  if(mkdtemp(tempdir) == NULL){
2345
2056
    perror_plus("mkdtemp");
2346
2057
    goto end;
2347
2058
  }
 
2059
  tempdir_created = true;
2348
2060
  
2349
2061
  if(quit_now){
2350
2062
    goto end;
2351
2063
  }
2352
2064
  
2353
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2065
  if(not init_gpgme(pubkey, seckey, tempdir)){
2354
2066
    fprintf_plus(stderr, "init_gpgme failed\n");
2355
2067
    exitcode = EX_UNAVAILABLE;
2356
2068
    goto end;
2366
2078
    /* Connect directly, do not use Zeroconf */
2367
2079
    /* (Mainly meant for debugging) */
2368
2080
    char *address = strrchr(connect_to, ':');
2369
 
    
2370
2081
    if(address == NULL){
2371
2082
      fprintf_plus(stderr, "No colon in address\n");
2372
2083
      exitcode = EX_USAGE;
2377
2088
      goto end;
2378
2089
    }
2379
2090
    
2380
 
    in_port_t port;
 
2091
    uint16_t port;
2381
2092
    errno = 0;
2382
2093
    tmpmax = strtoimax(address+1, &tmp, 10);
2383
2094
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2384
 
       or tmpmax != (in_port_t)tmpmax){
 
2095
       or tmpmax != (uint16_t)tmpmax){
2385
2096
      fprintf_plus(stderr, "Bad port number\n");
2386
2097
      exitcode = EX_USAGE;
2387
2098
      goto end;
2388
2099
    }
2389
 
    
 
2100
  
2390
2101
    if(quit_now){
2391
2102
      goto end;
2392
2103
    }
2393
2104
    
2394
 
    port = (in_port_t)tmpmax;
 
2105
    port = (uint16_t)tmpmax;
2395
2106
    *address = '\0';
2396
2107
    /* Colon in address indicates IPv6 */
2397
2108
    int af;
2413
2124
    }
2414
2125
    
2415
2126
    while(not quit_now){
2416
 
      ret = start_mandos_communication(address, port, if_index, af,
2417
 
                                       &mc);
 
2127
      ret = start_mandos_communication(address, port, if_index, af);
2418
2128
      if(quit_now or ret == 0){
2419
2129
        break;
2420
2130
      }
2422
2132
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2423
2133
                     (int)retry_interval);
2424
2134
      }
2425
 
      sleep((unsigned int)retry_interval);
 
2135
      sleep((int)retry_interval);
2426
2136
    }
2427
2137
    
2428
 
    if(not quit_now){
 
2138
    if (not quit_now){
2429
2139
      exitcode = EXIT_SUCCESS;
2430
2140
    }
2431
2141
    
2446
2156
    config.publish_domain = 0;
2447
2157
    
2448
2158
    /* Allocate a new server */
2449
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2450
 
                                 &config, NULL, NULL, &ret_errno);
 
2159
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2160
                                 (mc.simple_poll), &config, NULL,
 
2161
                                 NULL, &error);
2451
2162
    
2452
2163
    /* Free the Avahi configuration data */
2453
2164
    avahi_server_config_free(&config);
2456
2167
  /* Check if creating the Avahi server object succeeded */
2457
2168
  if(mc.server == NULL){
2458
2169
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2459
 
                 avahi_strerror(ret_errno));
 
2170
                 avahi_strerror(error));
2460
2171
    exitcode = EX_UNAVAILABLE;
2461
2172
    goto end;
2462
2173
  }
2468
2179
  /* Create the Avahi service browser */
2469
2180
  sb = avahi_s_service_browser_new(mc.server, if_index,
2470
2181
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2471
 
                                   NULL, 0, browse_callback,
2472
 
                                   (void *)&mc);
 
2182
                                   NULL, 0, browse_callback, NULL);
2473
2183
  if(sb == NULL){
2474
2184
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2475
2185
                 avahi_strerror(avahi_server_errno(mc.server)));
2487
2197
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2488
2198
  }
2489
2199
 
2490
 
  ret = avahi_loop_with_timeout(simple_poll,
2491
 
                                (int)(retry_interval * 1000), &mc);
 
2200
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2201
                                (int)(retry_interval * 1000));
2492
2202
  if(debug){
2493
2203
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2494
2204
                 (ret == 0) ? "successfully" : "with error");
2501
2211
  }
2502
2212
  
2503
2213
  /* Cleanup things */
2504
 
  free(mc.interfaces);
2505
 
  
2506
2214
  if(sb != NULL)
2507
2215
    avahi_s_service_browser_free(sb);
2508
2216
  
2509
2217
  if(mc.server != NULL)
2510
2218
    avahi_server_free(mc.server);
2511
2219
  
2512
 
  if(simple_poll != NULL)
2513
 
    avahi_simple_poll_free(simple_poll);
 
2220
  if(mc.simple_poll != NULL)
 
2221
    avahi_simple_poll_free(mc.simple_poll);
2514
2222
  
2515
2223
  if(gnutls_initialized){
2516
2224
    gnutls_certificate_free_credentials(mc.cred);
2533
2241
    }
2534
2242
  }
2535
2243
  
2536
 
  /* Re-raise privileges */
 
2244
  /* Run network hooks */
 
2245
  run_network_hooks("stop", interface, delay);
 
2246
  
 
2247
  /* Re-raise priviliges */
2537
2248
  {
2538
 
    ret_errno = raise_privileges();
2539
 
    if(ret_errno != 0){
2540
 
      perror_plus("Failed to raise privileges");
2541
 
    } else {
2542
 
      
2543
 
      /* Run network hooks */
2544
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2545
 
                        interfaces_hooks : "", delay);
2546
 
      
2547
 
      /* Take down the network interfaces which were brought up */
2548
 
      {
2549
 
        char *interface = NULL;
2550
 
        while((interface=argz_next(interfaces_to_take_down,
2551
 
                                   interfaces_to_take_down_size,
2552
 
                                   interface))){
2553
 
          ret_errno = take_down_interface(interface);
2554
 
          if(ret_errno != 0){
2555
 
            errno = ret_errno;
2556
 
            perror_plus("Failed to take down interface");
2557
 
          }
2558
 
        }
2559
 
        if(debug and (interfaces_to_take_down == NULL)){
2560
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2561
 
                       " down\n");
2562
 
        }
2563
 
      }
 
2249
    errno = 0;
 
2250
    ret = seteuid(0);
 
2251
    if(ret == -1){
 
2252
      perror_plus("seteuid");
2564
2253
    }
2565
2254
    
2566
 
    ret_errno = lower_privileges_permanently();
2567
 
    if(ret_errno != 0){
2568
 
      perror_plus("Failed to lower privileges permanently");
 
2255
    /* Take down the network interface */
 
2256
    if(take_down_interface and geteuid() == 0){
 
2257
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2258
      if(ret == -1){
 
2259
        perror_plus("ioctl SIOCGIFFLAGS");
 
2260
      } else if(network.ifr_flags & IFF_UP){
 
2261
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2262
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2263
        if(ret == -1){
 
2264
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2265
        }
 
2266
      }
 
2267
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2268
      if(ret == -1){
 
2269
        perror_plus("close");
 
2270
      }
2569
2271
    }
2570
2272
  }
2571
 
  
2572
 
  free(interfaces_to_take_down);
2573
 
  free(interfaces_hooks);
 
2273
  /* Lower privileges permanently */
 
2274
  errno = 0;
 
2275
  ret = setuid(uid);
 
2276
  if(ret == -1){
 
2277
    perror_plus("setuid");
 
2278
  }
2574
2279
  
2575
2280
  /* Removes the GPGME temp directory and all files inside */
2576
 
  if(tempdir != NULL){
 
2281
  if(tempdir_created){
2577
2282
    struct dirent **direntries = NULL;
2578
2283
    struct dirent *direntry = NULL;
2579
2284
    int numentries = scandir(tempdir, &direntries, notdotentries,
2580
2285
                             alphasort);
2581
 
    if(numentries > 0){
 
2286
    if (numentries > 0){
2582
2287
      for(int i = 0; i < numentries; i++){
2583
2288
        direntry = direntries[i];
2584
2289
        char *fullname = NULL;
2599
2304
 
2600
2305
    /* need to clean even if 0 because man page doesn't specify */
2601
2306
    free(direntries);
2602
 
    if(numentries == -1){
 
2307
    if (numentries == -1){
2603
2308
      perror_plus("scandir");
2604
2309
    }
2605
2310
    ret = rmdir(tempdir);