/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-17 02:30:59 UTC
  • Revision ID: teddy@recompile.se-20120617023059-em4nfnxg1tsn64xj
* plugins.d/mandos-client (start_mandos_communication): Bug fix; skip
                                                        non-specified
                                                        interfaces.
  (main): Use lower_privileges() consistently.  Bug fix: Don't remove
          "none" from list of interfaces.  Make --interface=none work
          again by not bringing up interfaces specified after "none".
* plugins.d/mandos-client.xml (OPTIONS): Document new meaning of
                                         specifying --interface=none
                                         together with other
                                         interface names,

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
61
61
                                 */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
64
#include <errno.h>              /* perror(), errno,
66
65
                                   program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
88
87
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
88
                                   WEXITSTATUS(), WTERMSIG() */
90
89
#include <grp.h>                /* setgroups() */
 
90
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
91
                                   argz_delete(), argz_append(),
 
92
                                   argz_stringify(), argz_add(),
 
93
                                   argz_count() */
91
94
 
92
95
#ifdef __linux__
93
96
#include <sys/klog.h>           /* klogctl() */
135
138
static const char sys_class_net[] = "/sys/class/net";
136
139
char *connect_to = NULL;
137
140
const char *hookdir = HOOKDIR;
 
141
uid_t uid = 65534;
 
142
gid_t gid = 65534;
138
143
 
139
144
/* Doubly linked list that need to be circularly linked when used */
140
145
typedef struct server{
141
146
  const char *ip;
142
 
  uint16_t port;
 
147
  in_port_t port;
143
148
  AvahiIfIndex if_index;
144
149
  int af;
145
150
  struct timespec last_seen;
149
154
 
150
155
/* Used for passing in values through the Avahi callback functions */
151
156
typedef struct {
152
 
  AvahiSimplePoll *simple_poll;
153
157
  AvahiServer *server;
154
158
  gnutls_certificate_credentials_t cred;
155
159
  unsigned int dh_bits;
157
161
  const char *priority;
158
162
  gpgme_ctx_t ctx;
159
163
  server *current_server;
 
164
  char *interfaces;
 
165
  size_t interfaces_size;
160
166
} mandos_context;
161
167
 
162
 
/* global context so signal handler can reach it*/
163
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
164
 
                      .dh_bits = 1024, .priority = "SECURE256"
165
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
166
 
                      .current_server = NULL };
 
168
/* global so signal handler can reach it*/
 
169
AvahiSimplePoll *simple_poll;
167
170
 
168
171
sig_atomic_t quit_now = 0;
169
172
int signal_received = 0;
205
208
}
206
209
 
207
210
/* Add server to set of servers to retry periodically */
208
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
209
 
                int af){
 
211
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
212
                int af, server **current_server){
210
213
  int ret;
211
214
  server *new_server = malloc(sizeof(server));
212
215
  if(new_server == NULL){
222
225
    return false;
223
226
  }
224
227
  /* Special case of first server */
225
 
  if (mc.current_server == NULL){
 
228
  if(*current_server == NULL){
226
229
    new_server->next = new_server;
227
230
    new_server->prev = new_server;
228
 
    mc.current_server = new_server;
 
231
    *current_server = new_server;
229
232
  /* Place the new server last in the list */
230
233
  } else {
231
 
    new_server->next = mc.current_server;
232
 
    new_server->prev = mc.current_server->prev;
 
234
    new_server->next = *current_server;
 
235
    new_server->prev = (*current_server)->prev;
233
236
    new_server->prev->next = new_server;
234
 
    mc.current_server->prev = new_server;
 
237
    (*current_server)->prev = new_server;
235
238
  }
236
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
237
240
  if(ret == -1){
238
241
    perror_plus("clock_gettime");
239
242
    return false;
245
248
 * Initialize GPGME.
246
249
 */
247
250
static bool init_gpgme(const char *seckey, const char *pubkey,
248
 
                       const char *tempdir){
 
251
                       const char *tempdir, mandos_context *mc){
249
252
  gpgme_error_t rc;
250
253
  gpgme_engine_info_t engine_info;
251
254
  
252
 
  
253
255
  /*
254
256
   * Helper function to insert pub and seckey to the engine keyring.
255
257
   */
271
273
      return false;
272
274
    }
273
275
    
274
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
276
    rc = gpgme_op_import(mc->ctx, pgp_data);
275
277
    if(rc != GPG_ERR_NO_ERROR){
276
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
277
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
321
323
  }
322
324
  
323
325
  /* Create new GPGME "context" */
324
 
  rc = gpgme_new(&(mc.ctx));
 
326
  rc = gpgme_new(&(mc->ctx));
325
327
  if(rc != GPG_ERR_NO_ERROR){
326
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
327
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
342
344
 */
343
345
static ssize_t pgp_packet_decrypt(const char *cryptotext,
344
346
                                  size_t crypto_size,
345
 
                                  char **plaintext){
 
347
                                  char **plaintext,
 
348
                                  mandos_context *mc){
346
349
  gpgme_data_t dh_crypto, dh_plain;
347
350
  gpgme_error_t rc;
348
351
  ssize_t ret;
374
377
  
375
378
  /* Decrypt data from the cryptotext data buffer to the plaintext
376
379
     data buffer */
377
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
380
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
378
381
  if(rc != GPG_ERR_NO_ERROR){
379
382
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
380
383
                 gpgme_strsource(rc), gpgme_strerror(rc));
381
384
    plaintext_length = -1;
382
385
    if(debug){
383
386
      gpgme_decrypt_result_t result;
384
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
387
      result = gpgme_op_decrypt_result(mc->ctx);
385
388
      if(result == NULL){
386
389
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
387
390
      } else {
465
468
}
466
469
 
467
470
static const char * safer_gnutls_strerror(int value){
468
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
469
 
                                               -Wunreachable-code */
 
471
  const char *ret = gnutls_strerror(value);
470
472
  if(ret == NULL)
471
473
    ret = "(unknown)";
472
474
  return ret;
479
481
}
480
482
 
481
483
static int init_gnutls_global(const char *pubkeyfilename,
482
 
                              const char *seckeyfilename){
 
484
                              const char *seckeyfilename,
 
485
                              mandos_context *mc){
483
486
  int ret;
484
487
  
485
488
  if(debug){
502
505
  }
503
506
  
504
507
  /* OpenPGP credentials */
505
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
508
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
506
509
  if(ret != GNUTLS_E_SUCCESS){
507
510
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
508
511
                 safer_gnutls_strerror(ret));
518
521
  }
519
522
  
520
523
  ret = gnutls_certificate_set_openpgp_key_file
521
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
524
    (mc->cred, pubkeyfilename, seckeyfilename,
522
525
     GNUTLS_OPENPGP_FMT_BASE64);
523
526
  if(ret != GNUTLS_E_SUCCESS){
524
527
    fprintf_plus(stderr,
530
533
  }
531
534
  
532
535
  /* GnuTLS server initialization */
533
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
536
  ret = gnutls_dh_params_init(&mc->dh_params);
534
537
  if(ret != GNUTLS_E_SUCCESS){
535
538
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
536
539
                 " initialization: %s\n",
537
540
                 safer_gnutls_strerror(ret));
538
541
    goto globalfail;
539
542
  }
540
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
543
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
541
544
  if(ret != GNUTLS_E_SUCCESS){
542
545
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
543
546
                 safer_gnutls_strerror(ret));
544
547
    goto globalfail;
545
548
  }
546
549
  
547
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
550
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
548
551
  
549
552
  return 0;
550
553
  
551
554
 globalfail:
552
555
  
553
 
  gnutls_certificate_free_credentials(mc.cred);
 
556
  gnutls_certificate_free_credentials(mc->cred);
554
557
  gnutls_global_deinit();
555
 
  gnutls_dh_params_deinit(mc.dh_params);
 
558
  gnutls_dh_params_deinit(mc->dh_params);
556
559
  return -1;
557
560
}
558
561
 
559
 
static int init_gnutls_session(gnutls_session_t *session){
 
562
static int init_gnutls_session(gnutls_session_t *session,
 
563
                               mandos_context *mc){
560
564
  int ret;
561
565
  /* GnuTLS session creation */
562
566
  do {
574
578
  {
575
579
    const char *err;
576
580
    do {
577
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
581
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
578
582
      if(quit_now){
579
583
        gnutls_deinit(*session);
580
584
        return -1;
591
595
  
592
596
  do {
593
597
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
594
 
                                 mc.cred);
 
598
                                 mc->cred);
595
599
    if(quit_now){
596
600
      gnutls_deinit(*session);
597
601
      return -1;
607
611
  /* ignore client certificate if any. */
608
612
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
609
613
  
610
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
614
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
611
615
  
612
616
  return 0;
613
617
}
617
621
                      __attribute__((unused)) const char *txt){}
618
622
 
619
623
/* Called when a Mandos server is found */
620
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
624
static int start_mandos_communication(const char *ip, in_port_t port,
621
625
                                      AvahiIfIndex if_index,
622
 
                                      int af){
 
626
                                      int af, mandos_context *mc){
623
627
  int ret, tcp_sd = -1;
624
628
  ssize_t sret;
625
629
  union {
655
659
    return -1;
656
660
  }
657
661
  
658
 
  ret = init_gnutls_session(&session);
 
662
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
663
    /* Check if the interface is one of the interfaces we are using */
 
664
    bool match = false;
 
665
    {
 
666
      char *interface = NULL;
 
667
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
668
                                 interface))){
 
669
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
670
          match = true;
 
671
          break;
 
672
        }
 
673
      }
 
674
    }
 
675
    if(not match){
 
676
      if(debug){
 
677
        char interface[IF_NAMESIZE];
 
678
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
679
          perror_plus("if_indextoname");
 
680
        } else {
 
681
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
682
                       " \"%s\"\n",
 
683
                       if_indextoname((unsigned int)if_index,
 
684
                                      interface));
 
685
        }
 
686
      }
 
687
      return -1;
 
688
    }
 
689
  }
 
690
  
 
691
  ret = init_gnutls_session(&session, mc);
659
692
  if(ret != 0){
660
693
    return -1;
661
694
  }
662
695
  
663
696
  if(debug){
664
697
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
665
 
                 PRIu16 "\n", ip, port);
 
698
                 PRIuMAX "\n", ip, (uintmax_t)port);
666
699
  }
667
700
  
668
701
  tcp_sd = socket(pf, SOCK_STREAM, 0);
699
732
    goto mandos_end;
700
733
  }
701
734
  if(af == AF_INET6){
702
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
703
 
                                       -Wconversion and
704
 
                                       -Wunreachable-code */
705
 
    
 
735
    to.in6.sin6_port = htons(port);    
706
736
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
707
737
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
738
                                -Wunreachable-code*/
732
762
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
733
763
        perror_plus("if_indextoname");
734
764
      } else {
735
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
736
 
                     "\n", ip, interface, port);
 
765
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
766
                     "\n", ip, interface, (uintmax_t)port);
737
767
      }
738
768
    } else {
739
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
740
 
                   ip, port);
 
769
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
770
                   ip, (uintmax_t)port);
741
771
    }
742
772
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
743
773
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
821
851
    goto mandos_end;
822
852
  }
823
853
  
824
 
  /* Spurious warning from -Wint-to-pointer-cast */
825
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
854
  /* This casting via intptr_t is to eliminate warning about casting
 
855
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
856
     function "set-session-transport-fd!" does it. */
 
857
  gnutls_transport_set_ptr(session,
 
858
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
826
859
  
827
860
  if(quit_now){
828
861
    errno = EINTR;
933
966
  if(buffer_length > 0){
934
967
    ssize_t decrypted_buffer_size;
935
968
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
936
 
                                               &decrypted_buffer);
 
969
                                               &decrypted_buffer, mc);
937
970
    if(decrypted_buffer_size >= 0){
938
971
      
939
972
      written = 0;
1000
1033
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1001
1034
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1002
1035
                             flags,
1003
 
                             AVAHI_GCC_UNUSED void* userdata){
1004
 
  assert(r);
 
1036
                             void* mc){
 
1037
  if(r == NULL){
 
1038
    return;
 
1039
  }
1005
1040
  
1006
1041
  /* Called whenever a service has been resolved successfully or
1007
1042
     timed out */
1016
1051
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1017
1052
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1018
1053
                 domain,
1019
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1054
                 avahi_strerror(avahi_server_errno
 
1055
                                (((mandos_context*)mc)->server)));
1020
1056
    break;
1021
1057
    
1022
1058
  case AVAHI_RESOLVER_FOUND:
1028
1064
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1029
1065
                     host_name, ip, (intmax_t)interface, port);
1030
1066
      }
1031
 
      int ret = start_mandos_communication(ip, port, interface,
1032
 
                                           avahi_proto_to_af(proto));
 
1067
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1068
                                           interface,
 
1069
                                           avahi_proto_to_af(proto),
 
1070
                                           mc);
1033
1071
      if(ret == 0){
1034
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1072
        avahi_simple_poll_quit(simple_poll);
1035
1073
      } else {
1036
 
        if(not add_server(ip, port, interface,
1037
 
                          avahi_proto_to_af(proto))){
 
1074
        if(not add_server(ip, (in_port_t)port, interface,
 
1075
                          avahi_proto_to_af(proto),
 
1076
                          &((mandos_context*)mc)->current_server)){
1038
1077
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1039
1078
                       " list\n", name);
1040
1079
        }
1053
1092
                            const char *domain,
1054
1093
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1055
1094
                            flags,
1056
 
                            AVAHI_GCC_UNUSED void* userdata){
1057
 
  assert(b);
 
1095
                            void* mc){
 
1096
  if(b == NULL){
 
1097
    return;
 
1098
  }
1058
1099
  
1059
1100
  /* Called whenever a new services becomes available on the LAN or
1060
1101
     is removed from the LAN */
1068
1109
  case AVAHI_BROWSER_FAILURE:
1069
1110
    
1070
1111
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1071
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1072
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1112
                 avahi_strerror(avahi_server_errno
 
1113
                                (((mandos_context*)mc)->server)));
 
1114
    avahi_simple_poll_quit(simple_poll);
1073
1115
    return;
1074
1116
    
1075
1117
  case AVAHI_BROWSER_NEW:
1078
1120
       the callback function is called the Avahi server will free the
1079
1121
       resolver for us. */
1080
1122
    
1081
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1082
 
                                    name, type, domain, protocol, 0,
1083
 
                                    resolve_callback, NULL) == NULL)
 
1123
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1124
                                    interface, protocol, name, type,
 
1125
                                    domain, protocol, 0,
 
1126
                                    resolve_callback, mc) == NULL)
1084
1127
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1085
1128
                   " %s\n", name,
1086
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1129
                   avahi_strerror(avahi_server_errno
 
1130
                                  (((mandos_context*)mc)->server)));
1087
1131
    break;
1088
1132
    
1089
1133
  case AVAHI_BROWSER_REMOVE:
1108
1152
  signal_received = sig;
1109
1153
  int old_errno = errno;
1110
1154
  /* set main loop to exit */
1111
 
  if(mc.simple_poll != NULL){
1112
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1155
  if(simple_poll != NULL){
 
1156
    avahi_simple_poll_quit(simple_poll);
1113
1157
  }
1114
1158
  errno = old_errno;
1115
1159
}
1116
1160
 
1117
1161
bool get_flags(const char *ifname, struct ifreq *ifr){
1118
1162
  int ret;
 
1163
  error_t ret_errno;
1119
1164
  
1120
1165
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1121
1166
  if(s < 0){
 
1167
    ret_errno = errno;
1122
1168
    perror_plus("socket");
 
1169
    errno = ret_errno;
1123
1170
    return false;
1124
1171
  }
1125
1172
  strcpy(ifr->ifr_name, ifname);
1126
1173
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1127
1174
  if(ret == -1){
1128
1175
    if(debug){
 
1176
      ret_errno = errno;
1129
1177
      perror_plus("ioctl SIOCGIFFLAGS");
 
1178
      errno = ret_errno;
1130
1179
    }
1131
1180
    return false;
1132
1181
  }
1201
1250
}
1202
1251
 
1203
1252
/* 
1204
 
 * This function determines if a directory entry in /sys/class/net
1205
 
 * corresponds to an acceptable network device which is up.
1206
 
 * (This function is passed to scandir(3) as a filter function.)
1207
 
 */
1208
 
int up_interface(const struct dirent *if_entry){
1209
 
  if(if_entry->d_name[0] == '.'){
1210
 
    return 0;
1211
 
  }
1212
 
  
1213
 
  struct ifreq ifr;
1214
 
  if(not get_flags(if_entry->d_name, &ifr)){
1215
 
    if(debug){
1216
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1217
 
                   "\"%s\"\n", if_entry->d_name);
1218
 
    }
1219
 
    return 0;
1220
 
  }
1221
 
  
1222
 
  /* Reject down interfaces */
1223
 
  if(not (ifr.ifr_flags & IFF_UP)){
1224
 
    if(debug){
1225
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1226
 
                   if_entry->d_name);
1227
 
    }
1228
 
    return 0;
1229
 
  }
1230
 
  
1231
 
  /* Reject non-running interfaces */
1232
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1233
 
    if(debug){
1234
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1235
 
                   if_entry->d_name);
1236
 
    }
1237
 
    return 0;
1238
 
  }
1239
 
  
1240
 
  if(not good_flags(if_entry->d_name, &ifr)){
1241
 
    return 0;
1242
 
  }
1243
 
  return 1;
 
1253
 * This function determines if a network interface is up.
 
1254
 */
 
1255
bool interface_is_up(const char *interface){
 
1256
  struct ifreq ifr;
 
1257
  if(not get_flags(interface, &ifr)){
 
1258
    if(debug){
 
1259
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1260
                   "\"%s\"\n", interface);
 
1261
    }
 
1262
    return false;
 
1263
  }
 
1264
  
 
1265
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1266
}
 
1267
 
 
1268
/* 
 
1269
 * This function determines if a network interface is running
 
1270
 */
 
1271
bool interface_is_running(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_RUNNING);
1244
1282
}
1245
1283
 
1246
1284
int notdotentries(const struct dirent *direntry){
1315
1353
  return 1;
1316
1354
}
1317
1355
 
1318
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1356
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1357
                            mandos_context *mc){
1319
1358
  int ret;
1320
1359
  struct timespec now;
1321
1360
  struct timespec waited_time;
1322
1361
  intmax_t block_time;
1323
1362
  
1324
1363
  while(true){
1325
 
    if(mc.current_server == NULL){
 
1364
    if(mc->current_server == NULL){
1326
1365
      if (debug){
1327
1366
        fprintf_plus(stderr, "Wait until first server is found."
1328
1367
                     " No timeout!\n");
1342
1381
      /* Calculating in ms how long time between now and server
1343
1382
         who we visted longest time ago. Now - last seen.  */
1344
1383
      waited_time.tv_sec = (now.tv_sec
1345
 
                            - mc.current_server->last_seen.tv_sec);
 
1384
                            - mc->current_server->last_seen.tv_sec);
1346
1385
      waited_time.tv_nsec = (now.tv_nsec
1347
 
                             - mc.current_server->last_seen.tv_nsec);
 
1386
                             - mc->current_server->last_seen.tv_nsec);
1348
1387
      /* total time is 10s/10,000ms.
1349
1388
         Converting to s from ms by dividing by 1,000,
1350
1389
         and ns to ms by dividing by 1,000,000. */
1358
1397
      }
1359
1398
      
1360
1399
      if(block_time <= 0){
1361
 
        ret = start_mandos_communication(mc.current_server->ip,
1362
 
                                         mc.current_server->port,
1363
 
                                         mc.current_server->if_index,
1364
 
                                         mc.current_server->af);
 
1400
        ret = start_mandos_communication(mc->current_server->ip,
 
1401
                                         mc->current_server->port,
 
1402
                                         mc->current_server->if_index,
 
1403
                                         mc->current_server->af, mc);
1365
1404
        if(ret == 0){
1366
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1405
          avahi_simple_poll_quit(s);
1367
1406
          return 0;
1368
1407
        }
1369
1408
        ret = clock_gettime(CLOCK_MONOTONIC,
1370
 
                            &mc.current_server->last_seen);
 
1409
                            &mc->current_server->last_seen);
1371
1410
        if(ret == -1){
1372
1411
          perror_plus("clock_gettime");
1373
1412
          return -1;
1374
1413
        }
1375
 
        mc.current_server = mc.current_server->next;
 
1414
        mc->current_server = mc->current_server->next;
1376
1415
        block_time = 0;         /* Call avahi to find new Mandos
1377
1416
                                   servers, but don't block */
1378
1417
      }
1387
1426
  }
1388
1427
}
1389
1428
 
 
1429
/* Set effective uid to 0, return errno */
 
1430
error_t raise_privileges(void){
 
1431
  error_t old_errno = errno;
 
1432
  error_t ret_errno = 0;
 
1433
  if(seteuid(0) == -1){
 
1434
    ret_errno = errno;
 
1435
    perror_plus("seteuid");
 
1436
  }
 
1437
  errno = old_errno;
 
1438
  return ret_errno;
 
1439
}
 
1440
 
 
1441
/* Set effective and real user ID to 0.  Return errno. */
 
1442
error_t raise_privileges_permanently(void){
 
1443
  error_t old_errno = errno;
 
1444
  error_t ret_errno = raise_privileges();
 
1445
  if(ret_errno != 0){
 
1446
    errno = old_errno;
 
1447
    return ret_errno;
 
1448
  }
 
1449
  if(setuid(0) == -1){
 
1450
    ret_errno = errno;
 
1451
    perror_plus("seteuid");
 
1452
  }
 
1453
  errno = old_errno;
 
1454
  return ret_errno;
 
1455
}
 
1456
 
 
1457
/* Set effective user ID to unprivileged saved user ID */
 
1458
error_t lower_privileges(void){
 
1459
  error_t old_errno = errno;
 
1460
  error_t ret_errno = 0;
 
1461
  if(seteuid(uid) == -1){
 
1462
    ret_errno = errno;
 
1463
    perror_plus("seteuid");
 
1464
  }
 
1465
  errno = old_errno;
 
1466
  return ret_errno;
 
1467
}
 
1468
 
 
1469
/* Lower privileges permanently */
 
1470
error_t lower_privileges_permanently(void){
 
1471
  error_t old_errno = errno;
 
1472
  error_t ret_errno = 0;
 
1473
  if(setuid(uid) == -1){
 
1474
    ret_errno = errno;
 
1475
    perror_plus("setuid");
 
1476
  }
 
1477
  errno = old_errno;
 
1478
  return ret_errno;
 
1479
}
 
1480
 
1390
1481
bool run_network_hooks(const char *mode, const char *interface,
1391
1482
                       const float delay){
1392
1483
  struct dirent **direntries;
1395
1486
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1396
1487
                         alphasort);
1397
1488
  if(numhooks == -1){
1398
 
    perror_plus("scandir");
 
1489
    if(errno == ENOENT){
 
1490
      if(debug){
 
1491
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1492
                     " found\n", hookdir);
 
1493
      }
 
1494
    } else {
 
1495
      perror_plus("scandir");
 
1496
    }
1399
1497
  } else {
1400
1498
    int devnull = open("/dev/null", O_RDONLY);
1401
1499
    for(int i = 0; i < numhooks; i++){
1414
1512
      if(hook_pid == 0){
1415
1513
        /* Child */
1416
1514
        /* Raise privileges */
1417
 
        errno = 0;
1418
 
        ret = seteuid(0);
1419
 
        if(ret == -1){
1420
 
          perror_plus("seteuid");
1421
 
        }
1422
 
        /* Raise privileges even more */
1423
 
        errno = 0;
1424
 
        ret = setuid(0);
1425
 
        if(ret == -1){
1426
 
          perror_plus("setuid");
1427
 
        }
 
1515
        raise_privileges_permanently();
1428
1516
        /* Set group */
1429
1517
        errno = 0;
1430
1518
        ret = setgid(0);
1450
1538
          perror_plus("setenv");
1451
1539
          _exit(EX_OSERR);
1452
1540
        }
1453
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1541
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1454
1542
        if(ret == -1){
1455
1543
          perror_plus("setenv");
1456
1544
          _exit(EX_OSERR);
1473
1561
          _exit(EX_OSERR);
1474
1562
        }
1475
1563
        free(delaystring);
 
1564
        if(connect_to != NULL){
 
1565
          ret = setenv("CONNECT", connect_to, 1);
 
1566
          if(ret == -1){
 
1567
            perror_plus("setenv");
 
1568
            _exit(EX_OSERR);
 
1569
          }
 
1570
        }
1476
1571
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1477
1572
          perror_plus("execl");
1478
1573
          _exit(EXIT_FAILURE);
1516
1611
  return true;
1517
1612
}
1518
1613
 
 
1614
error_t bring_up_interface(const char *const interface,
 
1615
                           const float delay){
 
1616
  int sd = -1;
 
1617
  error_t old_errno = errno;
 
1618
  error_t ret_errno = 0;
 
1619
  int ret, ret_setflags;
 
1620
  struct ifreq network;
 
1621
  unsigned int if_index = if_nametoindex(interface);
 
1622
  if(if_index == 0){
 
1623
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1624
    errno = old_errno;
 
1625
    return ENXIO;
 
1626
  }
 
1627
  
 
1628
  if(quit_now){
 
1629
    errno = old_errno;
 
1630
    return EINTR;
 
1631
  }
 
1632
  
 
1633
  if(not interface_is_up(interface)){
 
1634
    if(not get_flags(interface, &network) and debug){
 
1635
      ret_errno = errno;
 
1636
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1637
                   "\"%s\"\n", interface);
 
1638
      return ret_errno;
 
1639
    }
 
1640
    network.ifr_flags |= IFF_UP;
 
1641
    
 
1642
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1643
    if(sd < 0){
 
1644
      ret_errno = errno;
 
1645
      perror_plus("socket");
 
1646
      errno = old_errno;
 
1647
      return ret_errno;
 
1648
    }
 
1649
  
 
1650
    if(quit_now){
 
1651
      close(sd);
 
1652
      errno = old_errno;
 
1653
      return EINTR;
 
1654
    }
 
1655
    
 
1656
    if(debug){
 
1657
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1658
                   interface);
 
1659
    }
 
1660
    
 
1661
    /* Raise priviliges */
 
1662
    raise_privileges();
 
1663
    
 
1664
#ifdef __linux__
 
1665
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1666
       messages about the network interface to mess up the prompt */
 
1667
    int ret_linux = klogctl(8, NULL, 5);
 
1668
    bool restore_loglevel = true;
 
1669
    if(ret_linux == -1){
 
1670
      restore_loglevel = false;
 
1671
      perror_plus("klogctl");
 
1672
    }
 
1673
#endif  /* __linux__ */
 
1674
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1675
    ret_errno = errno;
 
1676
#ifdef __linux__
 
1677
    if(restore_loglevel){
 
1678
      ret_linux = klogctl(7, NULL, 0);
 
1679
      if(ret_linux == -1){
 
1680
        perror_plus("klogctl");
 
1681
      }
 
1682
    }
 
1683
#endif  /* __linux__ */
 
1684
    
 
1685
    /* Lower privileges */
 
1686
    lower_privileges();
 
1687
    
 
1688
    /* Close the socket */
 
1689
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1690
    if(ret == -1){
 
1691
      perror_plus("close");
 
1692
    }
 
1693
    
 
1694
    if(ret_setflags == -1){
 
1695
      errno = ret_errno;
 
1696
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1697
      errno = old_errno;
 
1698
      return ret_errno;
 
1699
    }
 
1700
  } else if(debug){
 
1701
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1702
                 interface);
 
1703
  }
 
1704
  
 
1705
  /* Sleep checking until interface is running.
 
1706
     Check every 0.25s, up to total time of delay */
 
1707
  for(int i=0; i < delay * 4; i++){
 
1708
    if(interface_is_running(interface)){
 
1709
      break;
 
1710
    }
 
1711
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1712
    ret = nanosleep(&sleeptime, NULL);
 
1713
    if(ret == -1 and errno != EINTR){
 
1714
      perror_plus("nanosleep");
 
1715
    }
 
1716
  }
 
1717
  
 
1718
  errno = old_errno;
 
1719
  return 0;
 
1720
}
 
1721
 
 
1722
error_t take_down_interface(const char *const interface){
 
1723
  int sd = -1;
 
1724
  error_t old_errno = errno;
 
1725
  error_t ret_errno = 0;
 
1726
  int ret, ret_setflags;
 
1727
  struct ifreq network;
 
1728
  unsigned int if_index = if_nametoindex(interface);
 
1729
  if(if_index == 0){
 
1730
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1731
    errno = old_errno;
 
1732
    return ENXIO;
 
1733
  }
 
1734
  if(interface_is_up(interface)){
 
1735
    if(not get_flags(interface, &network) and debug){
 
1736
      ret_errno = errno;
 
1737
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1738
                   "\"%s\"\n", interface);
 
1739
      return ret_errno;
 
1740
    }
 
1741
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1742
    
 
1743
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1744
    if(sd < 0){
 
1745
      ret_errno = errno;
 
1746
      perror_plus("socket");
 
1747
      errno = old_errno;
 
1748
      return ret_errno;
 
1749
    }
 
1750
    
 
1751
    if(debug){
 
1752
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1753
                   interface);
 
1754
    }
 
1755
    
 
1756
    /* Raise priviliges */
 
1757
    raise_privileges();
 
1758
    
 
1759
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1760
    ret_errno = errno;
 
1761
    
 
1762
    /* Lower privileges */
 
1763
    lower_privileges();
 
1764
    
 
1765
    /* Close the socket */
 
1766
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1767
    if(ret == -1){
 
1768
      perror_plus("close");
 
1769
    }
 
1770
    
 
1771
    if(ret_setflags == -1){
 
1772
      errno = ret_errno;
 
1773
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1774
      errno = old_errno;
 
1775
      return ret_errno;
 
1776
    }
 
1777
  } else if(debug){
 
1778
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1779
                 interface);
 
1780
  }
 
1781
  
 
1782
  errno = old_errno;
 
1783
  return 0;
 
1784
}
 
1785
 
1519
1786
int main(int argc, char *argv[]){
 
1787
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1788
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1789
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1790
                        .interfaces = NULL, .interfaces_size = 0 };
1520
1791
  AvahiSServiceBrowser *sb = NULL;
1521
 
  int error;
 
1792
  error_t ret_errno;
1522
1793
  int ret;
1523
1794
  intmax_t tmpmax;
1524
1795
  char *tmp;
1525
1796
  int exitcode = EXIT_SUCCESS;
1526
 
  const char *interface = "";
1527
 
  struct ifreq network;
1528
 
  int sd = -1;
1529
 
  bool take_down_interface = false;
1530
 
  uid_t uid;
1531
 
  gid_t gid;
 
1797
  char *interfaces_to_take_down = NULL;
 
1798
  size_t interfaces_to_take_down_size = 0;
1532
1799
  char tempdir[] = "/tmp/mandosXXXXXX";
1533
1800
  bool tempdir_created = false;
1534
1801
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1535
1802
  const char *seckey = PATHDIR "/" SECKEY;
1536
1803
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1804
  char *interfaces_hooks = NULL;
 
1805
  size_t interfaces_hooks_size = 0;
1537
1806
  
1538
1807
  bool gnutls_initialized = false;
1539
1808
  bool gpgme_initialized = false;
1601
1870
        .group = 2 },
1602
1871
      { .name = "retry", .key = 132,
1603
1872
        .arg = "SECONDS",
1604
 
        .doc = "Retry interval used when denied by the mandos server",
 
1873
        .doc = "Retry interval used when denied by the Mandos server",
1605
1874
        .group = 2 },
1606
1875
      { .name = "network-hook-dir", .key = 133,
1607
1876
        .arg = "DIR",
1630
1899
        connect_to = arg;
1631
1900
        break;
1632
1901
      case 'i':                 /* --interface */
1633
 
        interface = arg;
 
1902
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1903
                                 arg, (int)',');
 
1904
        if(ret_errno != 0){
 
1905
          argp_error(state, "%s", strerror(ret_errno));
 
1906
        }
1634
1907
        break;
1635
1908
      case 's':                 /* --seckey */
1636
1909
        seckey = arg;
1714
1987
       <http://bugs.debian.org/633582> */
1715
1988
    
1716
1989
    /* Re-raise priviliges */
1717
 
    errno = 0;
1718
 
    ret = seteuid(0);
1719
 
    if(ret == -1){
1720
 
      perror_plus("seteuid");
1721
 
    } else {
 
1990
    if(raise_privileges() == 0){
1722
1991
      struct stat st;
1723
1992
      
1724
1993
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1764
2033
      }
1765
2034
    
1766
2035
      /* Lower privileges */
1767
 
      errno = 0;
1768
 
      ret = seteuid(uid);
1769
 
      if(ret == -1){
1770
 
        perror_plus("seteuid");
 
2036
      lower_privileges();
 
2037
    }
 
2038
  }
 
2039
  
 
2040
  /* Remove invalid interface names (except "none") */
 
2041
  {
 
2042
    char *interface = NULL;
 
2043
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2044
                                 interface))){
 
2045
      if(strcmp(interface, "none") != 0
 
2046
         and if_nametoindex(interface) == 0){
 
2047
        if(interface[0] != '\0'){
 
2048
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2049
                       " \"%s\"\n", interface);
 
2050
        }
 
2051
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2052
        interface = NULL;
1771
2053
      }
1772
2054
    }
1773
2055
  }
1774
2056
  
1775
2057
  /* Run network hooks */
1776
 
  if(not run_network_hooks("start", interface, delay)){
1777
 
    goto end;
 
2058
  {
 
2059
    if(mc.interfaces != NULL){
 
2060
      interfaces_hooks = malloc(mc.interfaces_size);
 
2061
      if(interfaces_hooks == NULL){
 
2062
        perror_plus("malloc");
 
2063
        goto end;
 
2064
      }
 
2065
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2066
      interfaces_hooks_size = mc.interfaces_size;
 
2067
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2068
                     (int)',');
 
2069
    }
 
2070
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2071
                             interfaces_hooks : "", delay)){
 
2072
      goto end;
 
2073
    }
1778
2074
  }
1779
2075
  
1780
2076
  if(not debug){
1781
2077
    avahi_set_log_function(empty_log);
1782
2078
  }
1783
2079
  
1784
 
  if(interface[0] == '\0'){
1785
 
    struct dirent **direntries;
1786
 
    /* First look for interfaces that are up */
1787
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1788
 
                  alphasort);
1789
 
    if(ret == 0){
1790
 
      /* No up interfaces, look for any good interfaces */
1791
 
      free(direntries);
1792
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1793
 
                    alphasort);
1794
 
    }
1795
 
    if(ret >= 1){
1796
 
      /* Pick the first interface returned */
1797
 
      interface = strdup(direntries[0]->d_name);
1798
 
      if(debug){
1799
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1800
 
      }
1801
 
      if(interface == NULL){
1802
 
        perror_plus("malloc");
1803
 
        free(direntries);
1804
 
        exitcode = EXIT_FAILURE;
1805
 
        goto end;
1806
 
      }
1807
 
      free(direntries);
1808
 
    } else {
1809
 
      free(direntries);
1810
 
      fprintf_plus(stderr, "Could not find a network interface\n");
1811
 
      exitcode = EXIT_FAILURE;
1812
 
      goto end;
1813
 
    }
1814
 
  }
1815
 
  
1816
2080
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1817
2081
     from the signal handler */
1818
2082
  /* Initialize the pseudo-RNG for Avahi */
1819
2083
  srand((unsigned int) time(NULL));
1820
 
  mc.simple_poll = avahi_simple_poll_new();
1821
 
  if(mc.simple_poll == NULL){
 
2084
  simple_poll = avahi_simple_poll_new();
 
2085
  if(simple_poll == NULL){
1822
2086
    fprintf_plus(stderr,
1823
2087
                 "Avahi: Failed to create simple poll object.\n");
1824
2088
    exitcode = EX_UNAVAILABLE;
1888
2152
    }
1889
2153
  }
1890
2154
  
1891
 
  /* If the interface is down, bring it up */
1892
 
  if(strcmp(interface, "none") != 0){
1893
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1894
 
    if(if_index == 0){
1895
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1896
 
      exitcode = EX_UNAVAILABLE;
1897
 
      goto end;
1898
 
    }
1899
 
    
1900
 
    if(quit_now){
1901
 
      goto end;
1902
 
    }
1903
 
    
1904
 
    /* Re-raise priviliges */
1905
 
    errno = 0;
1906
 
    ret = seteuid(0);
1907
 
    if(ret == -1){
1908
 
      perror_plus("seteuid");
1909
 
    }
1910
 
    
1911
 
#ifdef __linux__
1912
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1913
 
       messages about the network interface to mess up the prompt */
1914
 
    ret = klogctl(8, NULL, 5);
1915
 
    bool restore_loglevel = true;
1916
 
    if(ret == -1){
1917
 
      restore_loglevel = false;
1918
 
      perror_plus("klogctl");
1919
 
    }
1920
 
#endif  /* __linux__ */
1921
 
    
1922
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1923
 
    if(sd < 0){
1924
 
      perror_plus("socket");
1925
 
      exitcode = EX_OSERR;
1926
 
#ifdef __linux__
1927
 
      if(restore_loglevel){
1928
 
        ret = klogctl(7, NULL, 0);
1929
 
        if(ret == -1){
1930
 
          perror_plus("klogctl");
1931
 
        }
1932
 
      }
1933
 
#endif  /* __linux__ */
1934
 
      /* Lower privileges */
1935
 
      errno = 0;
1936
 
      ret = seteuid(uid);
1937
 
      if(ret == -1){
1938
 
        perror_plus("seteuid");
1939
 
      }
1940
 
      goto end;
1941
 
    }
1942
 
    strcpy(network.ifr_name, interface);
1943
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1944
 
    if(ret == -1){
1945
 
      perror_plus("ioctl SIOCGIFFLAGS");
1946
 
#ifdef __linux__
1947
 
      if(restore_loglevel){
1948
 
        ret = klogctl(7, NULL, 0);
1949
 
        if(ret == -1){
1950
 
          perror_plus("klogctl");
1951
 
        }
1952
 
      }
1953
 
#endif  /* __linux__ */
1954
 
      exitcode = EX_OSERR;
1955
 
      /* Lower privileges */
1956
 
      errno = 0;
1957
 
      ret = seteuid(uid);
1958
 
      if(ret == -1){
1959
 
        perror_plus("seteuid");
1960
 
      }
1961
 
      goto end;
1962
 
    }
1963
 
    if((network.ifr_flags & IFF_UP) == 0){
1964
 
      network.ifr_flags |= IFF_UP;
1965
 
      take_down_interface = true;
1966
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1967
 
      if(ret == -1){
1968
 
        take_down_interface = false;
1969
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1970
 
        exitcode = EX_OSERR;
1971
 
#ifdef __linux__
1972
 
        if(restore_loglevel){
1973
 
          ret = klogctl(7, NULL, 0);
1974
 
          if(ret == -1){
1975
 
            perror_plus("klogctl");
 
2155
  /* If no interfaces were specified, make a list */
 
2156
  if(mc.interfaces == NULL){
 
2157
    struct dirent **direntries;
 
2158
    /* Look for any good interfaces */
 
2159
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2160
                  alphasort);
 
2161
    if(ret >= 1){
 
2162
      /* Add all found interfaces to interfaces list */
 
2163
      for(int i = 0; i < ret; ++i){
 
2164
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2165
                             direntries[i]->d_name);
 
2166
        if(ret_errno != 0){
 
2167
          perror_plus("argz_add");
 
2168
          continue;
 
2169
        }
 
2170
        if(debug){
 
2171
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2172
                       direntries[i]->d_name);
 
2173
        }
 
2174
      }
 
2175
      free(direntries);
 
2176
    } else {
 
2177
      free(direntries);
 
2178
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2179
      exitcode = EXIT_FAILURE;
 
2180
      goto end;
 
2181
    }
 
2182
  }
 
2183
  
 
2184
  /* Bring up interfaces which are down */
 
2185
  {
 
2186
    char *interface = NULL;
 
2187
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2188
                                 interface))){
 
2189
      /* If interface name is "none", stop bringing up interfaces.
 
2190
         Also remove all instances of "none" from the list */
 
2191
      if(strcmp(interface, "none") == 0){
 
2192
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2193
                    interface);
 
2194
        interface = NULL;
 
2195
        while((interface = argz_next(mc.interfaces,
 
2196
                                     mc.interfaces_size, interface))){
 
2197
          if(strcmp(interface, "none") == 0){
 
2198
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2199
                        interface);
 
2200
            interface = NULL;
1976
2201
          }
1977
2202
        }
1978
 
#endif  /* __linux__ */
1979
 
        /* Lower privileges */
1980
 
        errno = 0;
1981
 
        ret = seteuid(uid);
1982
 
        if(ret == -1){
1983
 
          perror_plus("seteuid");
1984
 
        }
1985
 
        goto end;
1986
 
      }
1987
 
    }
1988
 
    /* Sleep checking until interface is running.
1989
 
       Check every 0.25s, up to total time of delay */
1990
 
    for(int i=0; i < delay * 4; i++){
1991
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1992
 
      if(ret == -1){
1993
 
        perror_plus("ioctl SIOCGIFFLAGS");
1994
 
      } else if(network.ifr_flags & IFF_RUNNING){
1995
2203
        break;
1996
2204
      }
1997
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1998
 
      ret = nanosleep(&sleeptime, NULL);
1999
 
      if(ret == -1 and errno != EINTR){
2000
 
        perror_plus("nanosleep");
2001
 
      }
2002
 
    }
2003
 
    if(not take_down_interface){
2004
 
      /* We won't need the socket anymore */
2005
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2006
 
      if(ret == -1){
2007
 
        perror_plus("close");
2008
 
      }
2009
 
    }
2010
 
#ifdef __linux__
2011
 
    if(restore_loglevel){
2012
 
      /* Restores kernel loglevel to default */
2013
 
      ret = klogctl(7, NULL, 0);
2014
 
      if(ret == -1){
2015
 
        perror_plus("klogctl");
2016
 
      }
2017
 
    }
2018
 
#endif  /* __linux__ */
2019
 
    /* Lower privileges */
2020
 
    errno = 0;
2021
 
    /* Lower privileges */
2022
 
    ret = seteuid(uid);
2023
 
    if(ret == -1){
2024
 
      perror_plus("seteuid");
2025
 
    }
 
2205
      bool interface_was_up = interface_is_up(interface);
 
2206
      ret = bring_up_interface(interface, delay);
 
2207
      if(not interface_was_up){
 
2208
        if(ret != 0){
 
2209
          errno = ret;
 
2210
          perror_plus("Failed to bring up interface");
 
2211
        } else {
 
2212
          ret_errno = argz_add(&interfaces_to_take_down,
 
2213
                               &interfaces_to_take_down_size,
 
2214
                               interface);
 
2215
        }
 
2216
      }
 
2217
    }
 
2218
    if(debug and (interfaces_to_take_down == NULL)){
 
2219
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2220
    }
 
2221
  }
 
2222
  
 
2223
  /* If we only got one interface, explicitly use only that one */
 
2224
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2225
    if(debug){
 
2226
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2227
                   mc.interfaces);
 
2228
    }
 
2229
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2026
2230
  }
2027
2231
  
2028
2232
  if(quit_now){
2029
2233
    goto end;
2030
2234
  }
2031
2235
  
2032
 
  ret = init_gnutls_global(pubkey, seckey);
 
2236
  ret = init_gnutls_global(pubkey, seckey, &mc);
2033
2237
  if(ret == -1){
2034
2238
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2035
2239
    exitcode = EX_UNAVAILABLE;
2052
2256
    goto end;
2053
2257
  }
2054
2258
  
2055
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2259
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2056
2260
    fprintf_plus(stderr, "init_gpgme failed\n");
2057
2261
    exitcode = EX_UNAVAILABLE;
2058
2262
    goto end;
2068
2272
    /* Connect directly, do not use Zeroconf */
2069
2273
    /* (Mainly meant for debugging) */
2070
2274
    char *address = strrchr(connect_to, ':');
 
2275
    
2071
2276
    if(address == NULL){
2072
2277
      fprintf_plus(stderr, "No colon in address\n");
2073
2278
      exitcode = EX_USAGE;
2078
2283
      goto end;
2079
2284
    }
2080
2285
    
2081
 
    uint16_t port;
 
2286
    in_port_t port;
2082
2287
    errno = 0;
2083
2288
    tmpmax = strtoimax(address+1, &tmp, 10);
2084
2289
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2085
 
       or tmpmax != (uint16_t)tmpmax){
 
2290
       or tmpmax != (in_port_t)tmpmax){
2086
2291
      fprintf_plus(stderr, "Bad port number\n");
2087
2292
      exitcode = EX_USAGE;
2088
2293
      goto end;
2089
2294
    }
2090
 
  
 
2295
    
2091
2296
    if(quit_now){
2092
2297
      goto end;
2093
2298
    }
2094
2299
    
2095
 
    port = (uint16_t)tmpmax;
 
2300
    port = (in_port_t)tmpmax;
2096
2301
    *address = '\0';
2097
2302
    /* Colon in address indicates IPv6 */
2098
2303
    int af;
2114
2319
    }
2115
2320
    
2116
2321
    while(not quit_now){
2117
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2322
      ret = start_mandos_communication(address, port, if_index, af,
 
2323
                                       &mc);
2118
2324
      if(quit_now or ret == 0){
2119
2325
        break;
2120
2326
      }
2146
2352
    config.publish_domain = 0;
2147
2353
    
2148
2354
    /* Allocate a new server */
2149
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2150
 
                                 (mc.simple_poll), &config, NULL,
2151
 
                                 NULL, &error);
 
2355
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2356
                                 &config, NULL, NULL, &ret_errno);
2152
2357
    
2153
2358
    /* Free the Avahi configuration data */
2154
2359
    avahi_server_config_free(&config);
2157
2362
  /* Check if creating the Avahi server object succeeded */
2158
2363
  if(mc.server == NULL){
2159
2364
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2160
 
                 avahi_strerror(error));
 
2365
                 avahi_strerror(ret_errno));
2161
2366
    exitcode = EX_UNAVAILABLE;
2162
2367
    goto end;
2163
2368
  }
2169
2374
  /* Create the Avahi service browser */
2170
2375
  sb = avahi_s_service_browser_new(mc.server, if_index,
2171
2376
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2172
 
                                   NULL, 0, browse_callback, NULL);
 
2377
                                   NULL, 0, browse_callback,
 
2378
                                   (void *)&mc);
2173
2379
  if(sb == NULL){
2174
2380
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2175
2381
                 avahi_strerror(avahi_server_errno(mc.server)));
2187
2393
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2188
2394
  }
2189
2395
 
2190
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2191
 
                                (int)(retry_interval * 1000));
 
2396
  ret = avahi_loop_with_timeout(simple_poll,
 
2397
                                (int)(retry_interval * 1000), &mc);
2192
2398
  if(debug){
2193
2399
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2194
2400
                 (ret == 0) ? "successfully" : "with error");
2201
2407
  }
2202
2408
  
2203
2409
  /* Cleanup things */
 
2410
  free(mc.interfaces);
 
2411
  
2204
2412
  if(sb != NULL)
2205
2413
    avahi_s_service_browser_free(sb);
2206
2414
  
2207
2415
  if(mc.server != NULL)
2208
2416
    avahi_server_free(mc.server);
2209
2417
  
2210
 
  if(mc.simple_poll != NULL)
2211
 
    avahi_simple_poll_free(mc.simple_poll);
 
2418
  if(simple_poll != NULL)
 
2419
    avahi_simple_poll_free(simple_poll);
2212
2420
  
2213
2421
  if(gnutls_initialized){
2214
2422
    gnutls_certificate_free_credentials(mc.cred);
2231
2439
    }
2232
2440
  }
2233
2441
  
2234
 
  /* Run network hooks */
2235
 
  run_network_hooks("stop", interface, delay);
2236
 
  
2237
2442
  /* Re-raise priviliges */
2238
2443
  {
2239
 
    errno = 0;
2240
 
    ret = seteuid(0);
2241
 
    if(ret == -1){
2242
 
      perror_plus("seteuid");
2243
 
    }
2244
 
    
2245
 
    /* Take down the network interface */
2246
 
    if(take_down_interface and geteuid() == 0){
2247
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2248
 
      if(ret == -1){
2249
 
        perror_plus("ioctl SIOCGIFFLAGS");
2250
 
      } else if(network.ifr_flags & IFF_UP){
2251
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2252
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2253
 
        if(ret == -1){
2254
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2444
    raise_privileges();
 
2445
    
 
2446
    /* Run network hooks */
 
2447
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2448
                      interfaces_hooks : "", delay);
 
2449
    
 
2450
    /* Take down the network interfaces which were brought up */
 
2451
    {
 
2452
      char *interface = NULL;
 
2453
      while((interface=argz_next(interfaces_to_take_down,
 
2454
                                 interfaces_to_take_down_size,
 
2455
                                 interface))){
 
2456
        ret_errno = take_down_interface(interface);
 
2457
        if(ret_errno != 0){
 
2458
          errno = ret_errno;
 
2459
          perror_plus("Failed to take down interface");
2255
2460
        }
2256
2461
      }
2257
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2258
 
      if(ret == -1){
2259
 
        perror_plus("close");
 
2462
      if(debug and (interfaces_to_take_down == NULL)){
 
2463
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2464
                     " down\n");
2260
2465
      }
2261
2466
    }
2262
 
  }
2263
 
  /* Lower privileges permanently */
2264
 
  errno = 0;
2265
 
  ret = setuid(uid);
2266
 
  if(ret == -1){
2267
 
    perror_plus("setuid");
2268
 
  }
 
2467
    
 
2468
    lower_privileges_permanently();
 
2469
  }
 
2470
  
 
2471
  free(interfaces_to_take_down);
 
2472
  free(interfaces_hooks);
2269
2473
  
2270
2474
  /* Removes the GPGME temp directory and all files inside */
2271
2475
  if(tempdir_created){