/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: 2014-03-28 22:32:21 UTC
  • Revision ID: teddy@recompile.se-20140328223221-w579qlvlex5if3dn
Fix location and format of signing key file.

* debian/upstream/signing-key.asc: Added.
* debian/upstream-signing-key.pgp: Removed.

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