/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-03-10 06:34:36 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 311.
  • Revision ID: teddy@recompile.se-20140310063436-zksdghqvv6k1pbyg
Do not add a new server to server list if clock_gettime() fails

* plugins.d/mandos-client.c (add_server): Set server.last_seen before
                                          adding new server, in case
                                          clock_gettime() fails.

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() */
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;
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
/*
197
201
size_t incbuffer(char **buffer, size_t buffer_length,
198
202
                 size_t buffer_capacity){
199
203
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
200
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
201
 
    if(buffer == NULL){
 
204
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
205
    if(new_buf == NULL){
 
206
      int old_errno = errno;
 
207
      free(*buffer);
 
208
      errno = old_errno;
 
209
      *buffer = NULL;
202
210
      return 0;
203
211
    }
 
212
    *buffer = new_buf;
204
213
    buffer_capacity += BUFFER_SIZE;
205
214
  }
206
215
  return buffer_capacity;
207
216
}
208
217
 
209
218
/* 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){
 
219
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
220
                int af, server **current_server){
212
221
  int ret;
213
222
  server *new_server = malloc(sizeof(server));
214
223
  if(new_server == NULL){
223
232
    perror_plus("strdup");
224
233
    return false;
225
234
  }
 
235
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
236
  if(ret == -1){
 
237
    perror_plus("clock_gettime");
 
238
    return false;
 
239
  }
226
240
  /* Special case of first server */
227
 
  if (mc.current_server == NULL){
 
241
  if(*current_server == NULL){
228
242
    new_server->next = new_server;
229
243
    new_server->prev = new_server;
230
 
    mc.current_server = new_server;
 
244
    *current_server = new_server;
231
245
  /* Place the new server last in the list */
232
246
  } else {
233
 
    new_server->next = mc.current_server;
234
 
    new_server->prev = mc.current_server->prev;
 
247
    new_server->next = *current_server;
 
248
    new_server->prev = (*current_server)->prev;
235
249
    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;
 
250
    (*current_server)->prev = new_server;
242
251
  }
243
252
  return true;
244
253
}
247
256
 * Initialize GPGME.
248
257
 */
249
258
static bool init_gpgme(const char *seckey, const char *pubkey,
250
 
                       const char *tempdir){
 
259
                       const char *tempdir, mandos_context *mc){
251
260
  gpgme_error_t rc;
252
261
  gpgme_engine_info_t engine_info;
253
262
  
254
 
  
255
263
  /*
256
264
   * Helper function to insert pub and seckey to the engine keyring.
257
265
   */
273
281
      return false;
274
282
    }
275
283
    
276
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
284
    rc = gpgme_op_import(mc->ctx, pgp_data);
277
285
    if(rc != GPG_ERR_NO_ERROR){
278
286
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
279
287
                   gpgme_strsource(rc), gpgme_strerror(rc));
323
331
  }
324
332
  
325
333
  /* Create new GPGME "context" */
326
 
  rc = gpgme_new(&(mc.ctx));
 
334
  rc = gpgme_new(&(mc->ctx));
327
335
  if(rc != GPG_ERR_NO_ERROR){
328
336
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
329
337
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
344
352
 */
345
353
static ssize_t pgp_packet_decrypt(const char *cryptotext,
346
354
                                  size_t crypto_size,
347
 
                                  char **plaintext){
 
355
                                  char **plaintext,
 
356
                                  mandos_context *mc){
348
357
  gpgme_data_t dh_crypto, dh_plain;
349
358
  gpgme_error_t rc;
350
359
  ssize_t ret;
376
385
  
377
386
  /* Decrypt data from the cryptotext data buffer to the plaintext
378
387
     data buffer */
379
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
388
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
380
389
  if(rc != GPG_ERR_NO_ERROR){
381
390
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
382
391
                 gpgme_strsource(rc), gpgme_strerror(rc));
383
392
    plaintext_length = -1;
384
393
    if(debug){
385
394
      gpgme_decrypt_result_t result;
386
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
395
      result = gpgme_op_decrypt_result(mc->ctx);
387
396
      if(result == NULL){
388
397
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
389
398
      } else {
467
476
}
468
477
 
469
478
static const char * safer_gnutls_strerror(int value){
470
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
471
 
                                               -Wunreachable-code */
 
479
  const char *ret = gnutls_strerror(value);
472
480
  if(ret == NULL)
473
481
    ret = "(unknown)";
474
482
  return ret;
481
489
}
482
490
 
483
491
static int init_gnutls_global(const char *pubkeyfilename,
484
 
                              const char *seckeyfilename){
 
492
                              const char *seckeyfilename,
 
493
                              mandos_context *mc){
485
494
  int ret;
486
495
  
487
496
  if(debug){
504
513
  }
505
514
  
506
515
  /* OpenPGP credentials */
507
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
516
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
508
517
  if(ret != GNUTLS_E_SUCCESS){
509
518
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
519
                 safer_gnutls_strerror(ret));
520
529
  }
521
530
  
522
531
  ret = gnutls_certificate_set_openpgp_key_file
523
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
532
    (mc->cred, pubkeyfilename, seckeyfilename,
524
533
     GNUTLS_OPENPGP_FMT_BASE64);
525
534
  if(ret != GNUTLS_E_SUCCESS){
526
535
    fprintf_plus(stderr,
532
541
  }
533
542
  
534
543
  /* GnuTLS server initialization */
535
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
544
  ret = gnutls_dh_params_init(&mc->dh_params);
536
545
  if(ret != GNUTLS_E_SUCCESS){
537
546
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
547
                 " initialization: %s\n",
539
548
                 safer_gnutls_strerror(ret));
540
549
    goto globalfail;
541
550
  }
542
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
551
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
543
552
  if(ret != GNUTLS_E_SUCCESS){
544
553
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
554
                 safer_gnutls_strerror(ret));
546
555
    goto globalfail;
547
556
  }
548
557
  
549
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
558
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
550
559
  
551
560
  return 0;
552
561
  
553
562
 globalfail:
554
563
  
555
 
  gnutls_certificate_free_credentials(mc.cred);
 
564
  gnutls_certificate_free_credentials(mc->cred);
556
565
  gnutls_global_deinit();
557
 
  gnutls_dh_params_deinit(mc.dh_params);
 
566
  gnutls_dh_params_deinit(mc->dh_params);
558
567
  return -1;
559
568
}
560
569
 
561
 
static int init_gnutls_session(gnutls_session_t *session){
 
570
static int init_gnutls_session(gnutls_session_t *session,
 
571
                               mandos_context *mc){
562
572
  int ret;
563
573
  /* GnuTLS session creation */
564
574
  do {
576
586
  {
577
587
    const char *err;
578
588
    do {
579
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
589
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
580
590
      if(quit_now){
581
591
        gnutls_deinit(*session);
582
592
        return -1;
593
603
  
594
604
  do {
595
605
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
596
 
                                 mc.cred);
 
606
                                 mc->cred);
597
607
    if(quit_now){
598
608
      gnutls_deinit(*session);
599
609
      return -1;
609
619
  /* ignore client certificate if any. */
610
620
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
611
621
  
612
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
622
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
613
623
  
614
624
  return 0;
615
625
}
619
629
                      __attribute__((unused)) const char *txt){}
620
630
 
621
631
/* Called when a Mandos server is found */
622
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
632
static int start_mandos_communication(const char *ip, in_port_t port,
623
633
                                      AvahiIfIndex if_index,
624
 
                                      int af){
 
634
                                      int af, mandos_context *mc){
625
635
  int ret, tcp_sd = -1;
626
636
  ssize_t sret;
627
637
  union {
657
667
    return -1;
658
668
  }
659
669
  
660
 
  ret = init_gnutls_session(&session);
 
670
  /* If the interface is specified and we have a list of interfaces */
 
671
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
672
    /* Check if the interface is one of the interfaces we are using */
 
673
    bool match = false;
 
674
    {
 
675
      char *interface = NULL;
 
676
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
677
                                 interface))){
 
678
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
679
          match = true;
 
680
          break;
 
681
        }
 
682
      }
 
683
    }
 
684
    if(not match){
 
685
      /* This interface does not match any in the list, so we don't
 
686
         connect to the server */
 
687
      if(debug){
 
688
        char interface[IF_NAMESIZE];
 
689
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
690
          perror_plus("if_indextoname");
 
691
        } else {
 
692
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
693
                       " \"%s\"\n",
 
694
                       if_indextoname((unsigned int)if_index,
 
695
                                      interface));
 
696
        }
 
697
      }
 
698
      return -1;
 
699
    }
 
700
  }
 
701
  
 
702
  ret = init_gnutls_session(&session, mc);
661
703
  if(ret != 0){
662
704
    return -1;
663
705
  }
664
706
  
665
707
  if(debug){
666
708
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
 
                 PRIu16 "\n", ip, port);
 
709
                 PRIuMAX "\n", ip, (uintmax_t)port);
668
710
  }
669
711
  
670
712
  tcp_sd = socket(pf, SOCK_STREAM, 0);
701
743
    goto mandos_end;
702
744
  }
703
745
  if(af == AF_INET6){
704
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
705
 
                                       -Wconversion and
706
 
                                       -Wunreachable-code */
707
 
    
 
746
    to.in6.sin6_port = htons(port);    
 
747
#ifdef __GNUC__
 
748
#pragma GCC diagnostic push
 
749
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
750
#endif
708
751
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
709
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
710
 
                                -Wunreachable-code*/
 
752
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
753
#ifdef __GNUC__
 
754
#pragma GCC diagnostic pop
 
755
#endif
711
756
      if(if_index == AVAHI_IF_UNSPEC){
712
757
        fprintf_plus(stderr, "An IPv6 link-local address is"
713
758
                     " incomplete without a network interface\n");
718
763
      to.in6.sin6_scope_id = (uint32_t)if_index;
719
764
    }
720
765
  } else {
721
 
    to.in.sin_port = htons(port); /* Spurious warnings from
722
 
                                     -Wconversion and
723
 
                                     -Wunreachable-code */
 
766
    to.in.sin_port = htons(port);
724
767
  }
725
768
  
726
769
  if(quit_now){
734
777
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
735
778
        perror_plus("if_indextoname");
736
779
      } else {
737
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
738
 
                     "\n", ip, interface, port);
 
780
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
781
                     "\n", ip, interface, (uintmax_t)port);
739
782
      }
740
783
    } else {
741
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
742
 
                   ip, port);
 
784
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
785
                   ip, (uintmax_t)port);
743
786
    }
744
787
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
745
788
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
746
 
    const char *pcret;
747
789
    if(af == AF_INET6){
748
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
749
 
                        sizeof(addrstr));
 
790
      ret = getnameinfo((struct sockaddr *)&(to.in6), sizeof(to.in6),
 
791
                        addrstr, sizeof(addrstr), NULL, 0,
 
792
                        NI_NUMERICHOST);
750
793
    } else {
751
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
752
 
                        sizeof(addrstr));
 
794
      ret = getnameinfo((struct sockaddr *)&(to.in), sizeof(to.in),
 
795
                        addrstr, sizeof(addrstr), NULL, 0,
 
796
                        NI_NUMERICHOST);
753
797
    }
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
 
      }
 
798
    if(ret == EAI_SYSTEM){
 
799
      perror_plus("getnameinfo");
 
800
    } else if(ret != 0) {
 
801
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
802
    } else if(strcmp(addrstr, ip) != 0){
 
803
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
760
804
    }
761
805
  }
762
806
  
938
982
  if(buffer_length > 0){
939
983
    ssize_t decrypted_buffer_size;
940
984
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
941
 
                                               &decrypted_buffer);
 
985
                                               &decrypted_buffer, mc);
942
986
    if(decrypted_buffer_size >= 0){
943
987
      
944
988
      written = 0;
1005
1049
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1006
1050
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1007
1051
                             flags,
1008
 
                             AVAHI_GCC_UNUSED void* userdata){
1009
 
  assert(r);
 
1052
                             void* mc){
 
1053
  if(r == NULL){
 
1054
    return;
 
1055
  }
1010
1056
  
1011
1057
  /* Called whenever a service has been resolved successfully or
1012
1058
     timed out */
1021
1067
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1022
1068
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1023
1069
                 domain,
1024
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1070
                 avahi_strerror(avahi_server_errno
 
1071
                                (((mandos_context*)mc)->server)));
1025
1072
    break;
1026
1073
    
1027
1074
  case AVAHI_RESOLVER_FOUND:
1033
1080
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1034
1081
                     host_name, ip, (intmax_t)interface, port);
1035
1082
      }
1036
 
      int ret = start_mandos_communication(ip, port, interface,
1037
 
                                           avahi_proto_to_af(proto));
 
1083
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1084
                                           interface,
 
1085
                                           avahi_proto_to_af(proto),
 
1086
                                           mc);
1038
1087
      if(ret == 0){
1039
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1088
        avahi_simple_poll_quit(simple_poll);
1040
1089
      } else {
1041
 
        if(not add_server(ip, port, interface,
1042
 
                          avahi_proto_to_af(proto))){
 
1090
        if(not add_server(ip, (in_port_t)port, interface,
 
1091
                          avahi_proto_to_af(proto),
 
1092
                          &((mandos_context*)mc)->current_server)){
1043
1093
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1044
1094
                       " list\n", name);
1045
1095
        }
1058
1108
                            const char *domain,
1059
1109
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1060
1110
                            flags,
1061
 
                            AVAHI_GCC_UNUSED void* userdata){
1062
 
  assert(b);
 
1111
                            void* mc){
 
1112
  if(b == NULL){
 
1113
    return;
 
1114
  }
1063
1115
  
1064
1116
  /* Called whenever a new services becomes available on the LAN or
1065
1117
     is removed from the LAN */
1073
1125
  case AVAHI_BROWSER_FAILURE:
1074
1126
    
1075
1127
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1076
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1077
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1128
                 avahi_strerror(avahi_server_errno
 
1129
                                (((mandos_context*)mc)->server)));
 
1130
    avahi_simple_poll_quit(simple_poll);
1078
1131
    return;
1079
1132
    
1080
1133
  case AVAHI_BROWSER_NEW:
1083
1136
       the callback function is called the Avahi server will free the
1084
1137
       resolver for us. */
1085
1138
    
1086
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1087
 
                                    name, type, domain, protocol, 0,
1088
 
                                    resolve_callback, NULL) == NULL)
 
1139
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1140
                                    interface, protocol, name, type,
 
1141
                                    domain, protocol, 0,
 
1142
                                    resolve_callback, mc) == NULL)
1089
1143
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1090
1144
                   " %s\n", name,
1091
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1145
                   avahi_strerror(avahi_server_errno
 
1146
                                  (((mandos_context*)mc)->server)));
1092
1147
    break;
1093
1148
    
1094
1149
  case AVAHI_BROWSER_REMOVE:
1113
1168
  signal_received = sig;
1114
1169
  int old_errno = errno;
1115
1170
  /* set main loop to exit */
1116
 
  if(mc.simple_poll != NULL){
1117
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1171
  if(simple_poll != NULL){
 
1172
    avahi_simple_poll_quit(simple_poll);
1118
1173
  }
1119
1174
  errno = old_errno;
1120
1175
}
1121
1176
 
1122
1177
bool get_flags(const char *ifname, struct ifreq *ifr){
1123
1178
  int ret;
 
1179
  error_t ret_errno;
1124
1180
  
1125
1181
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1126
1182
  if(s < 0){
 
1183
    ret_errno = errno;
1127
1184
    perror_plus("socket");
 
1185
    errno = ret_errno;
1128
1186
    return false;
1129
1187
  }
1130
1188
  strcpy(ifr->ifr_name, ifname);
1131
1189
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1132
1190
  if(ret == -1){
1133
1191
    if(debug){
 
1192
      ret_errno = errno;
1134
1193
      perror_plus("ioctl SIOCGIFFLAGS");
 
1194
      errno = ret_errno;
1135
1195
    }
1136
1196
    return false;
1137
1197
  }
1206
1266
}
1207
1267
 
1208
1268
/* 
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;
 
1269
 * This function determines if a network interface is up.
 
1270
 */
 
1271
bool interface_is_up(const char *interface){
 
1272
  struct ifreq ifr;
 
1273
  if(not get_flags(interface, &ifr)){
 
1274
    if(debug){
 
1275
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1276
                   "\"%s\"\n", interface);
 
1277
    }
 
1278
    return false;
 
1279
  }
 
1280
  
 
1281
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1282
}
 
1283
 
 
1284
/* 
 
1285
 * This function determines if a network interface is running
 
1286
 */
 
1287
bool interface_is_running(const char *interface){
 
1288
  struct ifreq ifr;
 
1289
  if(not get_flags(interface, &ifr)){
 
1290
    if(debug){
 
1291
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1292
                   "\"%s\"\n", interface);
 
1293
    }
 
1294
    return false;
 
1295
  }
 
1296
  
 
1297
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1249
1298
}
1250
1299
 
1251
1300
int notdotentries(const struct dirent *direntry){
1320
1369
  return 1;
1321
1370
}
1322
1371
 
1323
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1372
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1373
                            mandos_context *mc){
1324
1374
  int ret;
1325
1375
  struct timespec now;
1326
1376
  struct timespec waited_time;
1327
1377
  intmax_t block_time;
1328
1378
  
1329
1379
  while(true){
1330
 
    if(mc.current_server == NULL){
 
1380
    if(mc->current_server == NULL){
1331
1381
      if (debug){
1332
1382
        fprintf_plus(stderr, "Wait until first server is found."
1333
1383
                     " No timeout!\n");
1347
1397
      /* Calculating in ms how long time between now and server
1348
1398
         who we visted longest time ago. Now - last seen.  */
1349
1399
      waited_time.tv_sec = (now.tv_sec
1350
 
                            - mc.current_server->last_seen.tv_sec);
 
1400
                            - mc->current_server->last_seen.tv_sec);
1351
1401
      waited_time.tv_nsec = (now.tv_nsec
1352
 
                             - mc.current_server->last_seen.tv_nsec);
 
1402
                             - mc->current_server->last_seen.tv_nsec);
1353
1403
      /* total time is 10s/10,000ms.
1354
1404
         Converting to s from ms by dividing by 1,000,
1355
1405
         and ns to ms by dividing by 1,000,000. */
1363
1413
      }
1364
1414
      
1365
1415
      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);
 
1416
        ret = start_mandos_communication(mc->current_server->ip,
 
1417
                                         mc->current_server->port,
 
1418
                                         mc->current_server->if_index,
 
1419
                                         mc->current_server->af, mc);
1370
1420
        if(ret == 0){
1371
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1421
          avahi_simple_poll_quit(s);
1372
1422
          return 0;
1373
1423
        }
1374
1424
        ret = clock_gettime(CLOCK_MONOTONIC,
1375
 
                            &mc.current_server->last_seen);
 
1425
                            &mc->current_server->last_seen);
1376
1426
        if(ret == -1){
1377
1427
          perror_plus("clock_gettime");
1378
1428
          return -1;
1379
1429
        }
1380
 
        mc.current_server = mc.current_server->next;
 
1430
        mc->current_server = mc->current_server->next;
1381
1431
        block_time = 0;         /* Call avahi to find new Mandos
1382
1432
                                   servers, but don't block */
1383
1433
      }
1393
1443
}
1394
1444
 
1395
1445
/* 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;
 
1446
error_t raise_privileges(void){
 
1447
  error_t old_errno = errno;
 
1448
  error_t ret_errno = 0;
1400
1449
  if(seteuid(0) == -1){
 
1450
    ret_errno = errno;
1401
1451
    perror_plus("seteuid");
1402
1452
  }
1403
 
  ret_errno = errno;
1404
1453
  errno = old_errno;
1405
1454
  return ret_errno;
1406
1455
}
1407
1456
 
1408
1457
/* 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();
 
1458
error_t raise_privileges_permanently(void){
 
1459
  error_t old_errno = errno;
 
1460
  error_t ret_errno = raise_privileges();
1412
1461
  if(ret_errno != 0){
1413
1462
    errno = old_errno;
1414
1463
    return ret_errno;
1415
1464
  }
1416
 
  errno = 0;
1417
1465
  if(setuid(0) == -1){
 
1466
    ret_errno = errno;
1418
1467
    perror_plus("seteuid");
1419
1468
  }
1420
 
  ret_errno = errno;
1421
1469
  errno = old_errno;
1422
1470
  return ret_errno;
1423
1471
}
1424
1472
 
1425
1473
/* 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;
 
1474
error_t lower_privileges(void){
 
1475
  error_t old_errno = errno;
 
1476
  error_t ret_errno = 0;
1430
1477
  if(seteuid(uid) == -1){
 
1478
    ret_errno = errno;
1431
1479
    perror_plus("seteuid");
1432
1480
  }
1433
 
  ret_errno = errno;
 
1481
  errno = old_errno;
 
1482
  return ret_errno;
 
1483
}
 
1484
 
 
1485
/* Lower privileges permanently */
 
1486
error_t lower_privileges_permanently(void){
 
1487
  error_t old_errno = errno;
 
1488
  error_t ret_errno = 0;
 
1489
  if(setuid(uid) == -1){
 
1490
    ret_errno = errno;
 
1491
    perror_plus("setuid");
 
1492
  }
1434
1493
  errno = old_errno;
1435
1494
  return ret_errno;
1436
1495
}
1438
1497
bool run_network_hooks(const char *mode, const char *interface,
1439
1498
                       const float delay){
1440
1499
  struct dirent **direntries;
1441
 
  struct dirent *direntry;
1442
 
  int ret;
1443
1500
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1444
1501
                         alphasort);
1445
1502
  if(numhooks == -1){
1446
 
    perror_plus("scandir");
 
1503
    if(errno == ENOENT){
 
1504
      if(debug){
 
1505
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1506
                     " found\n", hookdir);
 
1507
      }
 
1508
    } else {
 
1509
      perror_plus("scandir");
 
1510
    }
1447
1511
  } else {
 
1512
    struct dirent *direntry;
 
1513
    int ret;
1448
1514
    int devnull = open("/dev/null", O_RDONLY);
1449
1515
    for(int i = 0; i < numhooks; i++){
1450
1516
      direntry = direntries[i];
1561
1627
  return true;
1562
1628
}
1563
1629
 
1564
 
int bring_up_interface(const char * const interface, const float delay){
 
1630
error_t bring_up_interface(const char *const interface,
 
1631
                           const float delay){
1565
1632
  int sd = -1;
1566
 
  int ret;
 
1633
  error_t old_errno = errno;
 
1634
  error_t ret_errno = 0;
 
1635
  int ret, ret_setflags;
1567
1636
  struct ifreq network;
1568
 
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
 
1637
  unsigned int if_index = if_nametoindex(interface);
1569
1638
  if(if_index == 0){
1570
1639
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1571
 
    return EX_UNAVAILABLE;
 
1640
    errno = old_errno;
 
1641
    return ENXIO;
1572
1642
  }
1573
1643
  
1574
1644
  if(quit_now){
 
1645
    errno = old_errno;
1575
1646
    return EINTR;
1576
1647
  }
1577
1648
  
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){
 
1649
  if(not interface_is_up(interface)){
 
1650
    if(not get_flags(interface, &network) and debug){
 
1651
      ret_errno = errno;
 
1652
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1653
                   "\"%s\"\n", interface);
 
1654
      return ret_errno;
 
1655
    }
1625
1656
    network.ifr_flags |= IFF_UP;
1626
 
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1657
    
 
1658
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1659
    if(sd < 0){
 
1660
      ret_errno = errno;
 
1661
      perror_plus("socket");
 
1662
      errno = old_errno;
 
1663
      return ret_errno;
 
1664
    }
 
1665
  
 
1666
    if(quit_now){
 
1667
      close(sd);
 
1668
      errno = old_errno;
 
1669
      return EINTR;
 
1670
    }
 
1671
    
 
1672
    if(debug){
 
1673
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1674
                   interface);
 
1675
    }
 
1676
    
 
1677
    /* Raise priviliges */
 
1678
    raise_privileges();
 
1679
    
 
1680
#ifdef __linux__
 
1681
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1682
       messages about the network interface to mess up the prompt */
 
1683
    int ret_linux = klogctl(8, NULL, 5);
 
1684
    bool restore_loglevel = true;
 
1685
    if(ret_linux == -1){
 
1686
      restore_loglevel = false;
 
1687
      perror_plus("klogctl");
 
1688
    }
 
1689
#endif  /* __linux__ */
 
1690
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1691
    ret_errno = errno;
 
1692
#ifdef __linux__
 
1693
    if(restore_loglevel){
 
1694
      ret_linux = klogctl(7, NULL, 0);
 
1695
      if(ret_linux == -1){
 
1696
        perror_plus("klogctl");
 
1697
      }
 
1698
    }
 
1699
#endif  /* __linux__ */
 
1700
    
 
1701
    /* Lower privileges */
 
1702
    lower_privileges();
 
1703
    
 
1704
    /* Close the socket */
 
1705
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1627
1706
    if(ret == -1){
 
1707
      perror_plus("close");
 
1708
    }
 
1709
    
 
1710
    if(ret_setflags == -1){
 
1711
      errno = ret_errno;
1628
1712
      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;
 
1713
      errno = old_errno;
 
1714
      return ret_errno;
1640
1715
    }
 
1716
  } else if(debug){
 
1717
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1718
                 interface);
1641
1719
  }
 
1720
  
1642
1721
  /* Sleep checking until interface is running.
1643
1722
     Check every 0.25s, up to total time of delay */
1644
1723
  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){
 
1724
    if(interface_is_running(interface)){
1649
1725
      break;
1650
1726
    }
1651
1727
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1654
1730
      perror_plus("nanosleep");
1655
1731
    }
1656
1732
  }
1657
 
  /* Close the socket */
1658
 
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
1659
 
  if(ret == -1){
1660
 
    perror_plus("close");
 
1733
  
 
1734
  errno = old_errno;
 
1735
  return 0;
 
1736
}
 
1737
 
 
1738
error_t take_down_interface(const char *const interface){
 
1739
  error_t old_errno = errno;
 
1740
  struct ifreq network;
 
1741
  unsigned int if_index = if_nametoindex(interface);
 
1742
  if(if_index == 0){
 
1743
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1744
    errno = old_errno;
 
1745
    return ENXIO;
1661
1746
  }
1662
 
#ifdef __linux__
1663
 
  if(restore_loglevel){
1664
 
    /* Restores kernel loglevel to default */
1665
 
    ret = klogctl(7, NULL, 0);
 
1747
  if(interface_is_up(interface)){
 
1748
    error_t ret_errno = 0;
 
1749
    if(not get_flags(interface, &network) and debug){
 
1750
      ret_errno = errno;
 
1751
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1752
                   "\"%s\"\n", interface);
 
1753
      return ret_errno;
 
1754
    }
 
1755
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1756
    
 
1757
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1758
    if(sd < 0){
 
1759
      ret_errno = errno;
 
1760
      perror_plus("socket");
 
1761
      errno = old_errno;
 
1762
      return ret_errno;
 
1763
    }
 
1764
    
 
1765
    if(debug){
 
1766
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1767
                   interface);
 
1768
    }
 
1769
    
 
1770
    /* Raise priviliges */
 
1771
    raise_privileges();
 
1772
    
 
1773
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1774
    ret_errno = errno;
 
1775
    
 
1776
    /* Lower privileges */
 
1777
    lower_privileges();
 
1778
    
 
1779
    /* Close the socket */
 
1780
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1666
1781
    if(ret == -1){
1667
 
      perror_plus("klogctl");
1668
 
    }
 
1782
      perror_plus("close");
 
1783
    }
 
1784
    
 
1785
    if(ret_setflags == -1){
 
1786
      errno = ret_errno;
 
1787
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1788
      errno = old_errno;
 
1789
      return ret_errno;
 
1790
    }
 
1791
  } else if(debug){
 
1792
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1793
                 interface);
1669
1794
  }
1670
 
#endif  /* __linux__ */
1671
 
  /* Lower privileges */
1672
 
  lower_privileges();
1673
 
  return errno;
 
1795
  
 
1796
  errno = old_errno;
 
1797
  return 0;
1674
1798
}
1675
1799
 
1676
1800
int main(int argc, char *argv[]){
 
1801
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1802
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1803
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1804
                        .interfaces = NULL, .interfaces_size = 0 };
1677
1805
  AvahiSServiceBrowser *sb = NULL;
1678
 
  int error;
 
1806
  error_t ret_errno;
1679
1807
  int ret;
1680
1808
  intmax_t tmpmax;
1681
1809
  char *tmp;
1682
1810
  int exitcode = EXIT_SUCCESS;
1683
 
  const char *interface = "";
1684
 
  struct ifreq network;
1685
 
  int sd = -1;
1686
 
  bool take_down_interface = false;
 
1811
  char *interfaces_to_take_down = NULL;
 
1812
  size_t interfaces_to_take_down_size = 0;
1687
1813
  char tempdir[] = "/tmp/mandosXXXXXX";
1688
1814
  bool tempdir_created = false;
1689
1815
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1690
1816
  const char *seckey = PATHDIR "/" SECKEY;
1691
1817
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1818
  char *interfaces_hooks = NULL;
1692
1819
  
1693
1820
  bool gnutls_initialized = false;
1694
1821
  bool gpgme_initialized = false;
1785
1912
        connect_to = arg;
1786
1913
        break;
1787
1914
      case 'i':                 /* --interface */
1788
 
        interface = arg;
 
1915
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1916
                                 arg, (int)',');
 
1917
        if(ret_errno != 0){
 
1918
          argp_error(state, "%s", strerror(ret_errno));
 
1919
        }
1789
1920
        break;
1790
1921
      case 's':                 /* --seckey */
1791
1922
        seckey = arg;
1915
2046
      }
1916
2047
    
1917
2048
      /* Lower privileges */
1918
 
      errno = 0;
1919
 
      ret = seteuid(uid);
1920
 
      if(ret == -1){
1921
 
        perror_plus("seteuid");
 
2049
      lower_privileges();
 
2050
    }
 
2051
  }
 
2052
  
 
2053
  /* Remove invalid interface names (except "none") */
 
2054
  {
 
2055
    char *interface = NULL;
 
2056
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2057
                                 interface))){
 
2058
      if(strcmp(interface, "none") != 0
 
2059
         and if_nametoindex(interface) == 0){
 
2060
        if(interface[0] != '\0'){
 
2061
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2062
                       " \"%s\"\n", interface);
 
2063
        }
 
2064
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2065
        interface = NULL;
1922
2066
      }
1923
2067
    }
1924
2068
  }
1925
2069
  
1926
2070
  /* Run network hooks */
1927
 
  if(not run_network_hooks("start", interface, delay)){
1928
 
    goto end;
 
2071
  {
 
2072
    if(mc.interfaces != NULL){
 
2073
      interfaces_hooks = malloc(mc.interfaces_size);
 
2074
      if(interfaces_hooks == NULL){
 
2075
        perror_plus("malloc");
 
2076
        goto end;
 
2077
      }
 
2078
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2079
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2080
    }
 
2081
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2082
                             interfaces_hooks : "", delay)){
 
2083
      goto end;
 
2084
    }
1929
2085
  }
1930
2086
  
1931
2087
  if(not debug){
1932
2088
    avahi_set_log_function(empty_log);
1933
2089
  }
1934
2090
  
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
2091
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1968
2092
     from the signal handler */
1969
2093
  /* Initialize the pseudo-RNG for Avahi */
1970
2094
  srand((unsigned int) time(NULL));
1971
 
  mc.simple_poll = avahi_simple_poll_new();
1972
 
  if(mc.simple_poll == NULL){
 
2095
  simple_poll = avahi_simple_poll_new();
 
2096
  if(simple_poll == NULL){
1973
2097
    fprintf_plus(stderr,
1974
2098
                 "Avahi: Failed to create simple poll object.\n");
1975
2099
    exitcode = EX_UNAVAILABLE;
2039
2163
    }
2040
2164
  }
2041
2165
  
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
 
    }
 
2166
  /* If no interfaces were specified, make a list */
 
2167
  if(mc.interfaces == NULL){
 
2168
    struct dirent **direntries;
 
2169
    /* Look for any good interfaces */
 
2170
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2171
                  alphasort);
 
2172
    if(ret >= 1){
 
2173
      /* Add all found interfaces to interfaces list */
 
2174
      for(int i = 0; i < ret; ++i){
 
2175
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2176
                             direntries[i]->d_name);
 
2177
        if(ret_errno != 0){
 
2178
          errno = ret_errno;
 
2179
          perror_plus("argz_add");
 
2180
          continue;
 
2181
        }
 
2182
        if(debug){
 
2183
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2184
                       direntries[i]->d_name);
 
2185
        }
 
2186
      }
 
2187
      free(direntries);
 
2188
    } else {
 
2189
      free(direntries);
 
2190
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2191
      exitcode = EXIT_FAILURE;
 
2192
      goto end;
 
2193
    }
 
2194
  }
 
2195
  
 
2196
  /* Bring up interfaces which are down, and remove any "none"s */
 
2197
  {
 
2198
    char *interface = NULL;
 
2199
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2200
                                 interface))){
 
2201
      /* If interface name is "none", stop bringing up interfaces.
 
2202
         Also remove all instances of "none" from the list */
 
2203
      if(strcmp(interface, "none") == 0){
 
2204
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2205
                    interface);
 
2206
        interface = NULL;
 
2207
        while((interface = argz_next(mc.interfaces,
 
2208
                                     mc.interfaces_size, interface))){
 
2209
          if(strcmp(interface, "none") == 0){
 
2210
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2211
                        interface);
 
2212
            interface = NULL;
 
2213
          }
 
2214
        }
 
2215
        break;
 
2216
      }
 
2217
      bool interface_was_up = interface_is_up(interface);
 
2218
      ret = bring_up_interface(interface, delay);
 
2219
      if(not interface_was_up){
 
2220
        if(ret != 0){
 
2221
          errno = ret;
 
2222
          perror_plus("Failed to bring up interface");
 
2223
        } else {
 
2224
          ret_errno = argz_add(&interfaces_to_take_down,
 
2225
                               &interfaces_to_take_down_size,
 
2226
                               interface);
 
2227
          if(ret_errno != 0){
 
2228
            errno = ret_errno;
 
2229
            perror_plus("argz_add");
 
2230
          }
 
2231
        }
 
2232
      }
 
2233
    }
 
2234
    if(debug and (interfaces_to_take_down == NULL)){
 
2235
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2236
    }
 
2237
  }
 
2238
  
 
2239
  /* If we only got one interface, explicitly use only that one */
 
2240
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2241
    if(debug){
 
2242
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2243
                   mc.interfaces);
 
2244
    }
 
2245
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2049
2246
  }
2050
2247
  
2051
2248
  if(quit_now){
2052
2249
    goto end;
2053
2250
  }
2054
2251
  
2055
 
  ret = init_gnutls_global(pubkey, seckey);
 
2252
  ret = init_gnutls_global(pubkey, seckey, &mc);
2056
2253
  if(ret == -1){
2057
2254
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2058
2255
    exitcode = EX_UNAVAILABLE;
2075
2272
    goto end;
2076
2273
  }
2077
2274
  
2078
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2275
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2079
2276
    fprintf_plus(stderr, "init_gpgme failed\n");
2080
2277
    exitcode = EX_UNAVAILABLE;
2081
2278
    goto end;
2102
2299
      goto end;
2103
2300
    }
2104
2301
    
2105
 
    uint16_t port;
 
2302
    in_port_t port;
2106
2303
    errno = 0;
2107
2304
    tmpmax = strtoimax(address+1, &tmp, 10);
2108
2305
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2109
 
       or tmpmax != (uint16_t)tmpmax){
 
2306
       or tmpmax != (in_port_t)tmpmax){
2110
2307
      fprintf_plus(stderr, "Bad port number\n");
2111
2308
      exitcode = EX_USAGE;
2112
2309
      goto end;
2113
2310
    }
2114
 
  
 
2311
    
2115
2312
    if(quit_now){
2116
2313
      goto end;
2117
2314
    }
2118
2315
    
2119
 
    port = (uint16_t)tmpmax;
 
2316
    port = (in_port_t)tmpmax;
2120
2317
    *address = '\0';
2121
2318
    /* Colon in address indicates IPv6 */
2122
2319
    int af;
2138
2335
    }
2139
2336
    
2140
2337
    while(not quit_now){
2141
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2338
      ret = start_mandos_communication(address, port, if_index, af,
 
2339
                                       &mc);
2142
2340
      if(quit_now or ret == 0){
2143
2341
        break;
2144
2342
      }
2146
2344
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2147
2345
                     (int)retry_interval);
2148
2346
      }
2149
 
      sleep((int)retry_interval);
 
2347
      sleep((unsigned int)retry_interval);
2150
2348
    }
2151
2349
    
2152
2350
    if (not quit_now){
2170
2368
    config.publish_domain = 0;
2171
2369
    
2172
2370
    /* Allocate a new server */
2173
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2174
 
                                 (mc.simple_poll), &config, NULL,
2175
 
                                 NULL, &error);
 
2371
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2372
                                 &config, NULL, NULL, &ret_errno);
2176
2373
    
2177
2374
    /* Free the Avahi configuration data */
2178
2375
    avahi_server_config_free(&config);
2181
2378
  /* Check if creating the Avahi server object succeeded */
2182
2379
  if(mc.server == NULL){
2183
2380
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2184
 
                 avahi_strerror(error));
 
2381
                 avahi_strerror(ret_errno));
2185
2382
    exitcode = EX_UNAVAILABLE;
2186
2383
    goto end;
2187
2384
  }
2193
2390
  /* Create the Avahi service browser */
2194
2391
  sb = avahi_s_service_browser_new(mc.server, if_index,
2195
2392
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2196
 
                                   NULL, 0, browse_callback, NULL);
 
2393
                                   NULL, 0, browse_callback,
 
2394
                                   (void *)&mc);
2197
2395
  if(sb == NULL){
2198
2396
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2199
2397
                 avahi_strerror(avahi_server_errno(mc.server)));
2211
2409
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2212
2410
  }
2213
2411
 
2214
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2215
 
                                (int)(retry_interval * 1000));
 
2412
  ret = avahi_loop_with_timeout(simple_poll,
 
2413
                                (int)(retry_interval * 1000), &mc);
2216
2414
  if(debug){
2217
2415
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2218
2416
                 (ret == 0) ? "successfully" : "with error");
2225
2423
  }
2226
2424
  
2227
2425
  /* Cleanup things */
 
2426
  free(mc.interfaces);
 
2427
  
2228
2428
  if(sb != NULL)
2229
2429
    avahi_s_service_browser_free(sb);
2230
2430
  
2231
2431
  if(mc.server != NULL)
2232
2432
    avahi_server_free(mc.server);
2233
2433
  
2234
 
  if(mc.simple_poll != NULL)
2235
 
    avahi_simple_poll_free(mc.simple_poll);
 
2434
  if(simple_poll != NULL)
 
2435
    avahi_simple_poll_free(simple_poll);
2236
2436
  
2237
2437
  if(gnutls_initialized){
2238
2438
    gnutls_certificate_free_credentials(mc.cred);
2255
2455
    }
2256
2456
  }
2257
2457
  
2258
 
  /* Run network hooks */
2259
 
  run_network_hooks("stop", interface, delay);
2260
 
  
2261
2458
  /* Re-raise priviliges */
2262
2459
  {
2263
2460
    raise_privileges();
2264
2461
    
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");
 
2462
    /* Run network hooks */
 
2463
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2464
                      interfaces_hooks : "", delay);
 
2465
    
 
2466
    /* Take down the network interfaces which were brought up */
 
2467
    {
 
2468
      char *interface = NULL;
 
2469
      while((interface=argz_next(interfaces_to_take_down,
 
2470
                                 interfaces_to_take_down_size,
 
2471
                                 interface))){
 
2472
        ret_errno = take_down_interface(interface);
 
2473
        if(ret_errno != 0){
 
2474
          errno = ret_errno;
 
2475
          perror_plus("Failed to take down interface");
2275
2476
        }
2276
2477
      }
2277
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2278
 
      if(ret == -1){
2279
 
        perror_plus("close");
 
2478
      if(debug and (interfaces_to_take_down == NULL)){
 
2479
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2480
                     " down\n");
2280
2481
      }
2281
2482
    }
2282
 
  }
2283
 
  /* Lower privileges permanently */
2284
 
  errno = 0;
2285
 
  ret = setuid(uid);
2286
 
  if(ret == -1){
2287
 
    perror_plus("setuid");
2288
 
  }
 
2483
    
 
2484
    lower_privileges_permanently();
 
2485
  }
 
2486
  
 
2487
  free(interfaces_to_take_down);
 
2488
  free(interfaces_hooks);
2289
2489
  
2290
2490
  /* Removes the GPGME temp directory and all files inside */
2291
2491
  if(tempdir_created){