/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

* network-hooks.d/bridge: Use "/usr/sbin/brctl" explicitly.
* plugins.d/mandos-client.c (run_network_hooks): Raise priviliges in
                                                 child process.
  (main): Do not use getuid() to check if running setuid root.  Do not
          raise privileges for run_network_hooks.

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-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   strtoimax() */
 
64
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
76
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_state, struct argp,
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
90
90
#include <grp.h>                /* setgroups() */
91
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
92
 
                                   argz_delete(), argz_append(),
93
 
                                   argz_stringify(), argz_add(),
94
 
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
91
 
98
92
#ifdef __linux__
99
93
#include <sys/klog.h>           /* klogctl() */
141
135
static const char sys_class_net[] = "/sys/class/net";
142
136
char *connect_to = NULL;
143
137
const char *hookdir = HOOKDIR;
144
 
uid_t uid = 65534;
145
 
gid_t gid = 65534;
146
138
 
147
139
/* Doubly linked list that need to be circularly linked when used */
148
140
typedef struct server{
149
141
  const char *ip;
150
 
  in_port_t port;
 
142
  uint16_t port;
151
143
  AvahiIfIndex if_index;
152
144
  int af;
153
145
  struct timespec last_seen;
157
149
 
158
150
/* Used for passing in values through the Avahi callback functions */
159
151
typedef struct {
 
152
  AvahiSimplePoll *simple_poll;
160
153
  AvahiServer *server;
161
154
  gnutls_certificate_credentials_t cred;
162
155
  unsigned int dh_bits;
164
157
  const char *priority;
165
158
  gpgme_ctx_t ctx;
166
159
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
160
} mandos_context;
170
161
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
162
/* global context so signal handler can reach it*/
 
163
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
164
                      .dh_bits = 1024, .priority = "SECURE256"
 
165
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
166
                      .current_server = NULL };
173
167
 
174
168
sig_atomic_t quit_now = 0;
175
169
int signal_received = 0;
176
170
 
177
171
/* Function to use when printing errors */
178
172
void perror_plus(const char *print_text){
179
 
  int e = errno;
180
173
  fprintf(stderr, "Mandos plugin %s: ",
181
174
          program_invocation_short_name);
182
 
  errno = e;
183
175
  perror(print_text);
184
176
}
185
177
 
186
 
__attribute__((format (gnu_printf, 2, 3)))
187
178
int fprintf_plus(FILE *stream, const char *format, ...){
188
179
  va_list ap;
189
180
  va_start (ap, format);
190
181
  
191
182
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
183
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
184
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
185
}
195
186
 
196
187
/*
201
192
size_t incbuffer(char **buffer, size_t buffer_length,
202
193
                 size_t buffer_capacity){
203
194
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
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;
 
195
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
196
    if(buffer == NULL){
210
197
      return 0;
211
198
    }
212
 
    *buffer = new_buf;
213
199
    buffer_capacity += BUFFER_SIZE;
214
200
  }
215
201
  return buffer_capacity;
216
202
}
217
203
 
218
204
/* Add server to set of servers to retry periodically */
219
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
220
 
                int af, server **current_server){
 
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
206
               int af){
221
207
  int ret;
222
208
  server *new_server = malloc(sizeof(server));
223
209
  if(new_server == NULL){
224
210
    perror_plus("malloc");
225
 
    return false;
 
211
    return -1;
226
212
  }
227
213
  *new_server = (server){ .ip = strdup(ip),
228
214
                          .port = port,
230
216
                          .af = af };
231
217
  if(new_server->ip == NULL){
232
218
    perror_plus("strdup");
233
 
    return false;
 
219
    return -1;
234
220
  }
235
221
  /* Special case of first server */
236
 
  if(*current_server == NULL){
 
222
  if (mc.current_server == NULL){
237
223
    new_server->next = new_server;
238
224
    new_server->prev = new_server;
239
 
    *current_server = new_server;
 
225
    mc.current_server = new_server;
240
226
  /* Place the new server last in the list */
241
227
  } else {
242
 
    new_server->next = *current_server;
243
 
    new_server->prev = (*current_server)->prev;
 
228
    new_server->next = mc.current_server;
 
229
    new_server->prev = mc.current_server->prev;
244
230
    new_server->prev->next = new_server;
245
 
    (*current_server)->prev = new_server;
 
231
    mc.current_server->prev = new_server;
246
232
  }
247
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
 
233
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
248
234
  if(ret == -1){
249
235
    perror_plus("clock_gettime");
250
 
    return false;
 
236
    return -1;
251
237
  }
252
 
  return true;
 
238
  return 0;
253
239
}
254
240
 
255
241
/* 
256
242
 * Initialize GPGME.
257
243
 */
258
244
static bool init_gpgme(const char *seckey, const char *pubkey,
259
 
                       const char *tempdir, mandos_context *mc){
 
245
                       const char *tempdir){
260
246
  gpgme_error_t rc;
261
247
  gpgme_engine_info_t engine_info;
262
248
  
 
249
  
263
250
  /*
264
251
   * Helper function to insert pub and seckey to the engine keyring.
265
252
   */
281
268
      return false;
282
269
    }
283
270
    
284
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
271
    rc = gpgme_op_import(mc.ctx, pgp_data);
285
272
    if(rc != GPG_ERR_NO_ERROR){
286
273
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
287
274
                   gpgme_strsource(rc), gpgme_strerror(rc));
331
318
  }
332
319
  
333
320
  /* Create new GPGME "context" */
334
 
  rc = gpgme_new(&(mc->ctx));
 
321
  rc = gpgme_new(&(mc.ctx));
335
322
  if(rc != GPG_ERR_NO_ERROR){
336
323
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
337
324
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
352
339
 */
353
340
static ssize_t pgp_packet_decrypt(const char *cryptotext,
354
341
                                  size_t crypto_size,
355
 
                                  char **plaintext,
356
 
                                  mandos_context *mc){
 
342
                                  char **plaintext){
357
343
  gpgme_data_t dh_crypto, dh_plain;
358
344
  gpgme_error_t rc;
359
345
  ssize_t ret;
385
371
  
386
372
  /* Decrypt data from the cryptotext data buffer to the plaintext
387
373
     data buffer */
388
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
374
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
389
375
  if(rc != GPG_ERR_NO_ERROR){
390
376
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
391
377
                 gpgme_strsource(rc), gpgme_strerror(rc));
392
378
    plaintext_length = -1;
393
379
    if(debug){
394
380
      gpgme_decrypt_result_t result;
395
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
381
      result = gpgme_op_decrypt_result(mc.ctx);
396
382
      if(result == NULL){
397
383
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
398
384
      } else {
476
462
}
477
463
 
478
464
static const char * safer_gnutls_strerror(int value){
479
 
  const char *ret = gnutls_strerror(value);
 
465
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
466
                                               -Wunreachable-code */
480
467
  if(ret == NULL)
481
468
    ret = "(unknown)";
482
469
  return ret;
489
476
}
490
477
 
491
478
static int init_gnutls_global(const char *pubkeyfilename,
492
 
                              const char *seckeyfilename,
493
 
                              mandos_context *mc){
 
479
                              const char *seckeyfilename){
494
480
  int ret;
495
481
  
496
482
  if(debug){
513
499
  }
514
500
  
515
501
  /* OpenPGP credentials */
516
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
502
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
517
503
  if(ret != GNUTLS_E_SUCCESS){
518
504
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
519
505
                 safer_gnutls_strerror(ret));
529
515
  }
530
516
  
531
517
  ret = gnutls_certificate_set_openpgp_key_file
532
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
518
    (mc.cred, pubkeyfilename, seckeyfilename,
533
519
     GNUTLS_OPENPGP_FMT_BASE64);
534
520
  if(ret != GNUTLS_E_SUCCESS){
535
521
    fprintf_plus(stderr,
541
527
  }
542
528
  
543
529
  /* GnuTLS server initialization */
544
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
530
  ret = gnutls_dh_params_init(&mc.dh_params);
545
531
  if(ret != GNUTLS_E_SUCCESS){
546
532
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
547
533
                 " initialization: %s\n",
548
534
                 safer_gnutls_strerror(ret));
549
535
    goto globalfail;
550
536
  }
551
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
537
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
552
538
  if(ret != GNUTLS_E_SUCCESS){
553
539
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
554
540
                 safer_gnutls_strerror(ret));
555
541
    goto globalfail;
556
542
  }
557
543
  
558
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
544
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
559
545
  
560
546
  return 0;
561
547
  
562
548
 globalfail:
563
549
  
564
 
  gnutls_certificate_free_credentials(mc->cred);
 
550
  gnutls_certificate_free_credentials(mc.cred);
565
551
  gnutls_global_deinit();
566
 
  gnutls_dh_params_deinit(mc->dh_params);
 
552
  gnutls_dh_params_deinit(mc.dh_params);
567
553
  return -1;
568
554
}
569
555
 
570
 
static int init_gnutls_session(gnutls_session_t *session,
571
 
                               mandos_context *mc){
 
556
static int init_gnutls_session(gnutls_session_t *session){
572
557
  int ret;
573
558
  /* GnuTLS session creation */
574
559
  do {
586
571
  {
587
572
    const char *err;
588
573
    do {
589
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
574
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
590
575
      if(quit_now){
591
576
        gnutls_deinit(*session);
592
577
        return -1;
603
588
  
604
589
  do {
605
590
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
606
 
                                 mc->cred);
 
591
                                 mc.cred);
607
592
    if(quit_now){
608
593
      gnutls_deinit(*session);
609
594
      return -1;
619
604
  /* ignore client certificate if any. */
620
605
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
621
606
  
622
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
607
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
623
608
  
624
609
  return 0;
625
610
}
629
614
                      __attribute__((unused)) const char *txt){}
630
615
 
631
616
/* Called when a Mandos server is found */
632
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
617
static int start_mandos_communication(const char *ip, uint16_t port,
633
618
                                      AvahiIfIndex if_index,
634
 
                                      int af, mandos_context *mc){
 
619
                                      int af){
635
620
  int ret, tcp_sd = -1;
636
621
  ssize_t sret;
637
622
  union {
667
652
    return -1;
668
653
  }
669
654
  
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);
 
655
  ret = init_gnutls_session(&session);
703
656
  if(ret != 0){
704
657
    return -1;
705
658
  }
706
659
  
707
660
  if(debug){
708
661
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
709
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
662
                 PRIu16 "\n", ip, port);
710
663
  }
711
664
  
712
665
  tcp_sd = socket(pf, SOCK_STREAM, 0);
743
696
    goto mandos_end;
744
697
  }
745
698
  if(af == AF_INET6){
746
 
    to.in6.sin6_port = htons(port);    
747
 
#ifdef __GNUC__
748
 
#pragma GCC diagnostic push
749
 
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
750
 
#endif
 
699
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
700
                                       -Wconversion and
 
701
                                       -Wunreachable-code */
 
702
    
751
703
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
752
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
753
 
#ifdef __GNUC__
754
 
#pragma GCC diagnostic pop
755
 
#endif
 
704
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
705
                                -Wunreachable-code*/
756
706
      if(if_index == AVAHI_IF_UNSPEC){
757
707
        fprintf_plus(stderr, "An IPv6 link-local address is"
758
708
                     " incomplete without a network interface\n");
763
713
      to.in6.sin6_scope_id = (uint32_t)if_index;
764
714
    }
765
715
  } else {
766
 
    to.in.sin_port = htons(port);
 
716
    to.in.sin_port = htons(port); /* Spurious warnings from
 
717
                                     -Wconversion and
 
718
                                     -Wunreachable-code */
767
719
  }
768
720
  
769
721
  if(quit_now){
777
729
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
778
730
        perror_plus("if_indextoname");
779
731
      } else {
780
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
781
 
                     "\n", ip, interface, (uintmax_t)port);
 
732
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
733
                     "\n", ip, interface, port);
782
734
      }
783
735
    } else {
784
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
785
 
                   ip, (uintmax_t)port);
 
736
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
737
                   ip, port);
786
738
    }
787
739
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
788
740
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
741
    const char *pcret;
789
742
    if(af == AF_INET6){
790
 
      ret = getnameinfo((struct sockaddr *)&(to.in6), sizeof(to.in6),
791
 
                        addrstr, sizeof(addrstr), NULL, 0,
792
 
                        NI_NUMERICHOST);
 
743
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
744
                        sizeof(addrstr));
793
745
    } else {
794
 
      ret = getnameinfo((struct sockaddr *)&(to.in), sizeof(to.in),
795
 
                        addrstr, sizeof(addrstr), NULL, 0,
796
 
                        NI_NUMERICHOST);
 
746
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
747
                        sizeof(addrstr));
797
748
    }
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);
 
749
    if(pcret == NULL){
 
750
      perror_plus("inet_ntop");
 
751
    } else {
 
752
      if(strcmp(addrstr, ip) != 0){
 
753
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
754
      }
804
755
    }
805
756
  }
806
757
  
867
818
    goto mandos_end;
868
819
  }
869
820
  
870
 
  /* This casting via intptr_t is to eliminate warning about casting
871
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
872
 
     function "set-session-transport-fd!" does it. */
873
 
  gnutls_transport_set_ptr(session,
874
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
821
  /* Spurious warning from -Wint-to-pointer-cast */
 
822
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
875
823
  
876
824
  if(quit_now){
877
825
    errno = EINTR;
982
930
  if(buffer_length > 0){
983
931
    ssize_t decrypted_buffer_size;
984
932
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
985
 
                                               &decrypted_buffer, mc);
 
933
                                               &decrypted_buffer);
986
934
    if(decrypted_buffer_size >= 0){
987
935
      
988
936
      written = 0;
1049
997
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1050
998
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1051
999
                             flags,
1052
 
                             void* mc){
1053
 
  if(r == NULL){
1054
 
    return;
1055
 
  }
 
1000
                             AVAHI_GCC_UNUSED void* userdata){
 
1001
  assert(r);
1056
1002
  
1057
1003
  /* Called whenever a service has been resolved successfully or
1058
1004
     timed out */
1067
1013
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1068
1014
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1069
1015
                 domain,
1070
 
                 avahi_strerror(avahi_server_errno
1071
 
                                (((mandos_context*)mc)->server)));
 
1016
                 avahi_strerror(avahi_server_errno(mc.server)));
1072
1017
    break;
1073
1018
    
1074
1019
  case AVAHI_RESOLVER_FOUND:
1080
1025
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1081
1026
                     host_name, ip, (intmax_t)interface, port);
1082
1027
      }
1083
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1084
 
                                           interface,
1085
 
                                           avahi_proto_to_af(proto),
1086
 
                                           mc);
 
1028
      int ret = start_mandos_communication(ip, port, interface,
 
1029
                                           avahi_proto_to_af(proto));
1087
1030
      if(ret == 0){
1088
 
        avahi_simple_poll_quit(simple_poll);
 
1031
        avahi_simple_poll_quit(mc.simple_poll);
1089
1032
      } else {
1090
 
        if(not add_server(ip, (in_port_t)port, interface,
1091
 
                          avahi_proto_to_af(proto),
1092
 
                          &((mandos_context*)mc)->current_server)){
1093
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1094
 
                       " list\n", name);
1095
 
        }
 
1033
        ret = add_server(ip, port, interface,
 
1034
                         avahi_proto_to_af(proto));
1096
1035
      }
1097
1036
    }
1098
1037
  }
1108
1047
                            const char *domain,
1109
1048
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1110
1049
                            flags,
1111
 
                            void* mc){
1112
 
  if(b == NULL){
1113
 
    return;
1114
 
  }
 
1050
                            AVAHI_GCC_UNUSED void* userdata){
 
1051
  assert(b);
1115
1052
  
1116
1053
  /* Called whenever a new services becomes available on the LAN or
1117
1054
     is removed from the LAN */
1125
1062
  case AVAHI_BROWSER_FAILURE:
1126
1063
    
1127
1064
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1128
 
                 avahi_strerror(avahi_server_errno
1129
 
                                (((mandos_context*)mc)->server)));
1130
 
    avahi_simple_poll_quit(simple_poll);
 
1065
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1066
    avahi_simple_poll_quit(mc.simple_poll);
1131
1067
    return;
1132
1068
    
1133
1069
  case AVAHI_BROWSER_NEW:
1136
1072
       the callback function is called the Avahi server will free the
1137
1073
       resolver for us. */
1138
1074
    
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)
 
1075
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1076
                                    name, type, domain, protocol, 0,
 
1077
                                    resolve_callback, NULL) == NULL)
1143
1078
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1144
1079
                   " %s\n", name,
1145
 
                   avahi_strerror(avahi_server_errno
1146
 
                                  (((mandos_context*)mc)->server)));
 
1080
                   avahi_strerror(avahi_server_errno(mc.server)));
1147
1081
    break;
1148
1082
    
1149
1083
  case AVAHI_BROWSER_REMOVE:
1168
1102
  signal_received = sig;
1169
1103
  int old_errno = errno;
1170
1104
  /* set main loop to exit */
1171
 
  if(simple_poll != NULL){
1172
 
    avahi_simple_poll_quit(simple_poll);
 
1105
  if(mc.simple_poll != NULL){
 
1106
    avahi_simple_poll_quit(mc.simple_poll);
1173
1107
  }
1174
1108
  errno = old_errno;
1175
1109
}
1176
1110
 
1177
1111
bool get_flags(const char *ifname, struct ifreq *ifr){
1178
1112
  int ret;
1179
 
  error_t ret_errno;
1180
1113
  
1181
1114
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1182
1115
  if(s < 0){
1183
 
    ret_errno = errno;
1184
1116
    perror_plus("socket");
1185
 
    errno = ret_errno;
1186
1117
    return false;
1187
1118
  }
1188
1119
  strcpy(ifr->ifr_name, ifname);
1189
1120
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1190
1121
  if(ret == -1){
1191
1122
    if(debug){
1192
 
      ret_errno = errno;
1193
1123
      perror_plus("ioctl SIOCGIFFLAGS");
1194
 
      errno = ret_errno;
1195
1124
    }
1196
1125
    return false;
1197
1126
  }
1266
1195
}
1267
1196
 
1268
1197
/* 
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);
 
1198
 * This function determines if a directory entry in /sys/class/net
 
1199
 * corresponds to an acceptable network device which is up.
 
1200
 * (This function is passed to scandir(3) as a filter function.)
 
1201
 */
 
1202
int up_interface(const struct dirent *if_entry){
 
1203
  if(if_entry->d_name[0] == '.'){
 
1204
    return 0;
 
1205
  }
 
1206
  
 
1207
  struct ifreq ifr;
 
1208
  if(not get_flags(if_entry->d_name, &ifr)){
 
1209
    if(debug){
 
1210
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1211
                   "\"%s\"\n", if_entry->d_name);
 
1212
    }
 
1213
    return 0;
 
1214
  }
 
1215
  
 
1216
  /* Reject down interfaces */
 
1217
  if(not (ifr.ifr_flags & IFF_UP)){
 
1218
    if(debug){
 
1219
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1220
                   if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  /* Reject non-running interfaces */
 
1226
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1227
    if(debug){
 
1228
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1229
                   if_entry->d_name);
 
1230
    }
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  if(not good_flags(if_entry->d_name, &ifr)){
 
1235
    return 0;
 
1236
  }
 
1237
  return 1;
1298
1238
}
1299
1239
 
1300
1240
int notdotentries(const struct dirent *direntry){
1369
1309
  return 1;
1370
1310
}
1371
1311
 
1372
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1373
 
                            mandos_context *mc){
 
1312
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1374
1313
  int ret;
1375
1314
  struct timespec now;
1376
1315
  struct timespec waited_time;
1377
1316
  intmax_t block_time;
1378
1317
  
1379
1318
  while(true){
1380
 
    if(mc->current_server == NULL){
 
1319
    if(mc.current_server == NULL){
1381
1320
      if (debug){
1382
1321
        fprintf_plus(stderr, "Wait until first server is found."
1383
1322
                     " No timeout!\n");
1397
1336
      /* Calculating in ms how long time between now and server
1398
1337
         who we visted longest time ago. Now - last seen.  */
1399
1338
      waited_time.tv_sec = (now.tv_sec
1400
 
                            - mc->current_server->last_seen.tv_sec);
 
1339
                            - mc.current_server->last_seen.tv_sec);
1401
1340
      waited_time.tv_nsec = (now.tv_nsec
1402
 
                             - mc->current_server->last_seen.tv_nsec);
 
1341
                             - mc.current_server->last_seen.tv_nsec);
1403
1342
      /* total time is 10s/10,000ms.
1404
1343
         Converting to s from ms by dividing by 1,000,
1405
1344
         and ns to ms by dividing by 1,000,000. */
1413
1352
      }
1414
1353
      
1415
1354
      if(block_time <= 0){
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);
 
1355
        ret = start_mandos_communication(mc.current_server->ip,
 
1356
                                         mc.current_server->port,
 
1357
                                         mc.current_server->if_index,
 
1358
                                         mc.current_server->af);
1420
1359
        if(ret == 0){
1421
 
          avahi_simple_poll_quit(s);
 
1360
          avahi_simple_poll_quit(mc.simple_poll);
1422
1361
          return 0;
1423
1362
        }
1424
1363
        ret = clock_gettime(CLOCK_MONOTONIC,
1425
 
                            &mc->current_server->last_seen);
 
1364
                            &mc.current_server->last_seen);
1426
1365
        if(ret == -1){
1427
1366
          perror_plus("clock_gettime");
1428
1367
          return -1;
1429
1368
        }
1430
 
        mc->current_server = mc->current_server->next;
 
1369
        mc.current_server = mc.current_server->next;
1431
1370
        block_time = 0;         /* Call avahi to find new Mandos
1432
1371
                                   servers, but don't block */
1433
1372
      }
1442
1381
  }
1443
1382
}
1444
1383
 
1445
 
/* Set effective uid to 0, return errno */
1446
 
error_t raise_privileges(void){
1447
 
  error_t old_errno = errno;
1448
 
  error_t ret_errno = 0;
1449
 
  if(seteuid(0) == -1){
1450
 
    ret_errno = errno;
1451
 
    perror_plus("seteuid");
1452
 
  }
1453
 
  errno = old_errno;
1454
 
  return ret_errno;
1455
 
}
1456
 
 
1457
 
/* Set effective and real user ID to 0.  Return errno. */
1458
 
error_t raise_privileges_permanently(void){
1459
 
  error_t old_errno = errno;
1460
 
  error_t ret_errno = raise_privileges();
1461
 
  if(ret_errno != 0){
1462
 
    errno = old_errno;
1463
 
    return ret_errno;
1464
 
  }
1465
 
  if(setuid(0) == -1){
1466
 
    ret_errno = errno;
1467
 
    perror_plus("seteuid");
1468
 
  }
1469
 
  errno = old_errno;
1470
 
  return ret_errno;
1471
 
}
1472
 
 
1473
 
/* Set effective user ID to unprivileged saved user ID */
1474
 
error_t lower_privileges(void){
1475
 
  error_t old_errno = errno;
1476
 
  error_t ret_errno = 0;
1477
 
  if(seteuid(uid) == -1){
1478
 
    ret_errno = errno;
1479
 
    perror_plus("seteuid");
1480
 
  }
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
 
  }
1493
 
  errno = old_errno;
1494
 
  return ret_errno;
1495
 
}
1496
 
 
1497
1384
bool run_network_hooks(const char *mode, const char *interface,
1498
1385
                       const float delay){
1499
1386
  struct dirent **direntries;
 
1387
  struct dirent *direntry;
 
1388
  int ret;
1500
1389
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1501
1390
                         alphasort);
1502
1391
  if(numhooks == -1){
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
 
    }
 
1392
    perror_plus("scandir");
1511
1393
  } else {
1512
 
    struct dirent *direntry;
1513
 
    int ret;
1514
1394
    int devnull = open("/dev/null", O_RDONLY);
1515
1395
    for(int i = 0; i < numhooks; i++){
1516
1396
      direntry = direntries[i];
1528
1408
      if(hook_pid == 0){
1529
1409
        /* Child */
1530
1410
        /* Raise privileges */
1531
 
        raise_privileges_permanently();
 
1411
        errno = 0;
 
1412
        ret = seteuid(0);
 
1413
        if(ret == -1){
 
1414
          perror_plus("seteuid");
 
1415
        }
 
1416
        /* Raise privileges even more */
 
1417
        errno = 0;
 
1418
        ret = setuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("setuid");
 
1421
        }
1532
1422
        /* Set group */
1533
1423
        errno = 0;
1534
1424
        ret = setgid(0);
1541
1431
        if(ret == -1){
1542
1432
          perror_plus("setgroups");
1543
1433
        }
 
1434
        fprintf_plus(stderr, "Child: getuid() = %d\n", getuid());
 
1435
        fprintf_plus(stderr, "Child: geteuid() = %d\n", geteuid());
1544
1436
        dup2(devnull, STDIN_FILENO);
1545
1437
        close(devnull);
1546
1438
        dup2(STDERR_FILENO, STDOUT_FILENO);
1554
1446
          perror_plus("setenv");
1555
1447
          _exit(EX_OSERR);
1556
1448
        }
1557
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1449
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1558
1450
        if(ret == -1){
1559
1451
          perror_plus("setenv");
1560
1452
          _exit(EX_OSERR);
1577
1469
          _exit(EX_OSERR);
1578
1470
        }
1579
1471
        free(delaystring);
1580
 
        if(connect_to != NULL){
1581
 
          ret = setenv("CONNECT", connect_to, 1);
1582
 
          if(ret == -1){
1583
 
            perror_plus("setenv");
1584
 
            _exit(EX_OSERR);
1585
 
          }
1586
 
        }
1587
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1588
 
          perror_plus("execl");
1589
 
          _exit(EXIT_FAILURE);
1590
 
        }
 
1472
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1473
        perror_plus("execl");
1591
1474
      } else {
1592
1475
        int status;
1593
1476
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1627
1510
  return true;
1628
1511
}
1629
1512
 
1630
 
error_t bring_up_interface(const char *const interface,
1631
 
                           const float delay){
1632
 
  int sd = -1;
1633
 
  error_t old_errno = errno;
1634
 
  error_t ret_errno = 0;
1635
 
  int ret, ret_setflags;
1636
 
  struct ifreq network;
1637
 
  unsigned int if_index = if_nametoindex(interface);
1638
 
  if(if_index == 0){
1639
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1640
 
    errno = old_errno;
1641
 
    return ENXIO;
1642
 
  }
1643
 
  
1644
 
  if(quit_now){
1645
 
    errno = old_errno;
1646
 
    return EINTR;
1647
 
  }
1648
 
  
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
 
    }
1656
 
    network.ifr_flags |= IFF_UP;
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));
1706
 
    if(ret == -1){
1707
 
      perror_plus("close");
1708
 
    }
1709
 
    
1710
 
    if(ret_setflags == -1){
1711
 
      errno = ret_errno;
1712
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1713
 
      errno = old_errno;
1714
 
      return ret_errno;
1715
 
    }
1716
 
  } else if(debug){
1717
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1718
 
                 interface);
1719
 
  }
1720
 
  
1721
 
  /* Sleep checking until interface is running.
1722
 
     Check every 0.25s, up to total time of delay */
1723
 
  for(int i=0; i < delay * 4; i++){
1724
 
    if(interface_is_running(interface)){
1725
 
      break;
1726
 
    }
1727
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1728
 
    ret = nanosleep(&sleeptime, NULL);
1729
 
    if(ret == -1 and errno != EINTR){
1730
 
      perror_plus("nanosleep");
1731
 
    }
1732
 
  }
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;
1746
 
  }
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));
1781
 
    if(ret == -1){
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);
1794
 
  }
1795
 
  
1796
 
  errno = old_errno;
1797
 
  return 0;
1798
 
}
1799
 
 
1800
1513
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 };
1805
1514
  AvahiSServiceBrowser *sb = NULL;
1806
 
  error_t ret_errno;
 
1515
  int error;
1807
1516
  int ret;
1808
1517
  intmax_t tmpmax;
1809
1518
  char *tmp;
1810
1519
  int exitcode = EXIT_SUCCESS;
1811
 
  char *interfaces_to_take_down = NULL;
1812
 
  size_t interfaces_to_take_down_size = 0;
 
1520
  const char *interface = "";
 
1521
  struct ifreq network;
 
1522
  int sd = -1;
 
1523
  bool take_down_interface = false;
 
1524
  uid_t uid;
 
1525
  gid_t gid;
1813
1526
  char tempdir[] = "/tmp/mandosXXXXXX";
1814
1527
  bool tempdir_created = false;
1815
1528
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1816
1529
  const char *seckey = PATHDIR "/" SECKEY;
1817
1530
  const char *pubkey = PATHDIR "/" PUBKEY;
1818
 
  char *interfaces_hooks = NULL;
1819
1531
  
1820
1532
  bool gnutls_initialized = false;
1821
1533
  bool gpgme_initialized = false;
1883
1595
        .group = 2 },
1884
1596
      { .name = "retry", .key = 132,
1885
1597
        .arg = "SECONDS",
1886
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1598
        .doc = "Retry interval used when denied by the mandos server",
1887
1599
        .group = 2 },
1888
1600
      { .name = "network-hook-dir", .key = 133,
1889
1601
        .arg = "DIR",
1912
1624
        connect_to = arg;
1913
1625
        break;
1914
1626
      case 'i':                 /* --interface */
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
 
        }
 
1627
        interface = arg;
1920
1628
        break;
1921
1629
      case 's':                 /* --seckey */
1922
1630
        seckey = arg;
1965
1673
        argp_state_help(state, state->out_stream,
1966
1674
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1967
1675
      case 'V':                 /* --version */
 
1676
        fprintf_plus(state->out_stream,
 
1677
                     "Mandos plugin mandos-client: ");
1968
1678
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1969
1679
        exit(argp_err_exit_status);
1970
1680
        break;
2000
1710
       <http://bugs.debian.org/633582> */
2001
1711
    
2002
1712
    /* Re-raise priviliges */
2003
 
    if(raise_privileges() == 0){
 
1713
    errno = 0;
 
1714
    ret = seteuid(0);
 
1715
    if(ret == -1){
 
1716
      perror_plus("seteuid");
 
1717
    } else {
2004
1718
      struct stat st;
2005
1719
      
2006
1720
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2046
1760
      }
2047
1761
    
2048
1762
      /* Lower privileges */
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;
 
1763
      errno = 0;
 
1764
      ret = seteuid(uid);
 
1765
      if(ret == -1){
 
1766
        perror_plus("seteuid");
2066
1767
      }
2067
1768
    }
2068
1769
  }
2069
1770
  
2070
1771
  /* Run network hooks */
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
 
    }
 
1772
  if(not run_network_hooks("start", interface, delay)){
 
1773
    goto end;
2085
1774
  }
2086
1775
  
2087
1776
  if(not debug){
2088
1777
    avahi_set_log_function(empty_log);
2089
1778
  }
2090
1779
  
 
1780
  if(interface[0] == '\0'){
 
1781
    struct dirent **direntries;
 
1782
    /* First look for interfaces that are up */
 
1783
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1784
                  alphasort);
 
1785
    if(ret == 0){
 
1786
      /* No up interfaces, look for any good interfaces */
 
1787
      free(direntries);
 
1788
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1789
                    alphasort);
 
1790
    }
 
1791
    if(ret >= 1){
 
1792
      /* Pick the first interface returned */
 
1793
      interface = strdup(direntries[0]->d_name);
 
1794
      if(debug){
 
1795
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1796
      }
 
1797
      if(interface == NULL){
 
1798
        perror_plus("malloc");
 
1799
        free(direntries);
 
1800
        exitcode = EXIT_FAILURE;
 
1801
        goto end;
 
1802
      }
 
1803
      free(direntries);
 
1804
    } else {
 
1805
      free(direntries);
 
1806
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1807
      exitcode = EXIT_FAILURE;
 
1808
      goto end;
 
1809
    }
 
1810
  }
 
1811
  
2091
1812
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2092
1813
     from the signal handler */
2093
1814
  /* Initialize the pseudo-RNG for Avahi */
2094
1815
  srand((unsigned int) time(NULL));
2095
 
  simple_poll = avahi_simple_poll_new();
2096
 
  if(simple_poll == NULL){
 
1816
  mc.simple_poll = avahi_simple_poll_new();
 
1817
  if(mc.simple_poll == NULL){
2097
1818
    fprintf_plus(stderr,
2098
1819
                 "Avahi: Failed to create simple poll object.\n");
2099
1820
    exitcode = EX_UNAVAILABLE;
2163
1884
    }
2164
1885
  }
2165
1886
  
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;
 
1887
  /* If the interface is down, bring it up */
 
1888
  if(strcmp(interface, "none") != 0){
 
1889
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1890
    if(if_index == 0){
 
1891
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1892
      exitcode = EX_UNAVAILABLE;
 
1893
      goto end;
 
1894
    }
 
1895
    
 
1896
    if(quit_now){
 
1897
      goto end;
 
1898
    }
 
1899
    
 
1900
    /* Re-raise priviliges */
 
1901
    errno = 0;
 
1902
    ret = seteuid(0);
 
1903
    if(ret == -1){
 
1904
      perror_plus("seteuid");
 
1905
    }
 
1906
    
 
1907
#ifdef __linux__
 
1908
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1909
       messages about the network interface to mess up the prompt */
 
1910
    ret = klogctl(8, NULL, 5);
 
1911
    bool restore_loglevel = true;
 
1912
    if(ret == -1){
 
1913
      restore_loglevel = false;
 
1914
      perror_plus("klogctl");
 
1915
    }
 
1916
#endif  /* __linux__ */
 
1917
    
 
1918
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1919
    if(sd < 0){
 
1920
      perror_plus("socket");
 
1921
      exitcode = EX_OSERR;
 
1922
#ifdef __linux__
 
1923
      if(restore_loglevel){
 
1924
        ret = klogctl(7, NULL, 0);
 
1925
        if(ret == -1){
 
1926
          perror_plus("klogctl");
 
1927
        }
 
1928
      }
 
1929
#endif  /* __linux__ */
 
1930
      /* Lower privileges */
 
1931
      errno = 0;
 
1932
      ret = seteuid(uid);
 
1933
      if(ret == -1){
 
1934
        perror_plus("seteuid");
 
1935
      }
 
1936
      goto end;
 
1937
    }
 
1938
    strcpy(network.ifr_name, interface);
 
1939
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1940
    if(ret == -1){
 
1941
      perror_plus("ioctl SIOCGIFFLAGS");
 
1942
#ifdef __linux__
 
1943
      if(restore_loglevel){
 
1944
        ret = klogctl(7, NULL, 0);
 
1945
        if(ret == -1){
 
1946
          perror_plus("klogctl");
 
1947
        }
 
1948
      }
 
1949
#endif  /* __linux__ */
 
1950
      exitcode = EX_OSERR;
 
1951
      /* Lower privileges */
 
1952
      errno = 0;
 
1953
      ret = seteuid(uid);
 
1954
      if(ret == -1){
 
1955
        perror_plus("seteuid");
 
1956
      }
 
1957
      goto end;
 
1958
    }
 
1959
    if((network.ifr_flags & IFF_UP) == 0){
 
1960
      network.ifr_flags |= IFF_UP;
 
1961
      take_down_interface = true;
 
1962
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1963
      if(ret == -1){
 
1964
        take_down_interface = false;
 
1965
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1966
        exitcode = EX_OSERR;
 
1967
#ifdef __linux__
 
1968
        if(restore_loglevel){
 
1969
          ret = klogctl(7, NULL, 0);
 
1970
          if(ret == -1){
 
1971
            perror_plus("klogctl");
2213
1972
          }
2214
1973
        }
 
1974
#endif  /* __linux__ */
 
1975
        /* Lower privileges */
 
1976
        errno = 0;
 
1977
        ret = seteuid(uid);
 
1978
        if(ret == -1){
 
1979
          perror_plus("seteuid");
 
1980
        }
 
1981
        goto end;
 
1982
      }
 
1983
    }
 
1984
    /* Sleep checking until interface is running.
 
1985
       Check every 0.25s, up to total time of delay */
 
1986
    for(int i=0; i < delay * 4; i++){
 
1987
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1988
      if(ret == -1){
 
1989
        perror_plus("ioctl SIOCGIFFLAGS");
 
1990
      } else if(network.ifr_flags & IFF_RUNNING){
2215
1991
        break;
2216
1992
      }
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);
 
1993
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1994
      ret = nanosleep(&sleeptime, NULL);
 
1995
      if(ret == -1 and errno != EINTR){
 
1996
        perror_plus("nanosleep");
 
1997
      }
 
1998
    }
 
1999
    if(not take_down_interface){
 
2000
      /* We won't need the socket anymore */
 
2001
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2002
      if(ret == -1){
 
2003
        perror_plus("close");
 
2004
      }
 
2005
    }
 
2006
#ifdef __linux__
 
2007
    if(restore_loglevel){
 
2008
      /* Restores kernel loglevel to default */
 
2009
      ret = klogctl(7, NULL, 0);
 
2010
      if(ret == -1){
 
2011
        perror_plus("klogctl");
 
2012
      }
 
2013
    }
 
2014
#endif  /* __linux__ */
 
2015
    /* Lower privileges */
 
2016
    errno = 0;
 
2017
    /* Lower privileges */
 
2018
    ret = seteuid(uid);
 
2019
    if(ret == -1){
 
2020
      perror_plus("seteuid");
 
2021
    }
2246
2022
  }
2247
2023
  
2248
2024
  if(quit_now){
2249
2025
    goto end;
2250
2026
  }
2251
2027
  
2252
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2028
  ret = init_gnutls_global(pubkey, seckey);
2253
2029
  if(ret == -1){
2254
2030
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2255
2031
    exitcode = EX_UNAVAILABLE;
2272
2048
    goto end;
2273
2049
  }
2274
2050
  
2275
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2051
  if(not init_gpgme(pubkey, seckey, tempdir)){
2276
2052
    fprintf_plus(stderr, "init_gpgme failed\n");
2277
2053
    exitcode = EX_UNAVAILABLE;
2278
2054
    goto end;
2288
2064
    /* Connect directly, do not use Zeroconf */
2289
2065
    /* (Mainly meant for debugging) */
2290
2066
    char *address = strrchr(connect_to, ':');
2291
 
    
2292
2067
    if(address == NULL){
2293
2068
      fprintf_plus(stderr, "No colon in address\n");
2294
2069
      exitcode = EX_USAGE;
2299
2074
      goto end;
2300
2075
    }
2301
2076
    
2302
 
    in_port_t port;
 
2077
    uint16_t port;
2303
2078
    errno = 0;
2304
2079
    tmpmax = strtoimax(address+1, &tmp, 10);
2305
2080
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2306
 
       or tmpmax != (in_port_t)tmpmax){
 
2081
       or tmpmax != (uint16_t)tmpmax){
2307
2082
      fprintf_plus(stderr, "Bad port number\n");
2308
2083
      exitcode = EX_USAGE;
2309
2084
      goto end;
2310
2085
    }
2311
 
    
 
2086
  
2312
2087
    if(quit_now){
2313
2088
      goto end;
2314
2089
    }
2315
2090
    
2316
 
    port = (in_port_t)tmpmax;
 
2091
    port = (uint16_t)tmpmax;
2317
2092
    *address = '\0';
2318
2093
    /* Colon in address indicates IPv6 */
2319
2094
    int af;
2335
2110
    }
2336
2111
    
2337
2112
    while(not quit_now){
2338
 
      ret = start_mandos_communication(address, port, if_index, af,
2339
 
                                       &mc);
 
2113
      ret = start_mandos_communication(address, port, if_index, af);
2340
2114
      if(quit_now or ret == 0){
2341
2115
        break;
2342
2116
      }
2344
2118
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2345
2119
                     (int)retry_interval);
2346
2120
      }
2347
 
      sleep((unsigned int)retry_interval);
 
2121
      sleep((int)retry_interval);
2348
2122
    }
2349
2123
    
2350
2124
    if (not quit_now){
2368
2142
    config.publish_domain = 0;
2369
2143
    
2370
2144
    /* Allocate a new server */
2371
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2372
 
                                 &config, NULL, NULL, &ret_errno);
 
2145
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2146
                                 (mc.simple_poll), &config, NULL,
 
2147
                                 NULL, &error);
2373
2148
    
2374
2149
    /* Free the Avahi configuration data */
2375
2150
    avahi_server_config_free(&config);
2378
2153
  /* Check if creating the Avahi server object succeeded */
2379
2154
  if(mc.server == NULL){
2380
2155
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2381
 
                 avahi_strerror(ret_errno));
 
2156
                 avahi_strerror(error));
2382
2157
    exitcode = EX_UNAVAILABLE;
2383
2158
    goto end;
2384
2159
  }
2390
2165
  /* Create the Avahi service browser */
2391
2166
  sb = avahi_s_service_browser_new(mc.server, if_index,
2392
2167
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2393
 
                                   NULL, 0, browse_callback,
2394
 
                                   (void *)&mc);
 
2168
                                   NULL, 0, browse_callback, NULL);
2395
2169
  if(sb == NULL){
2396
2170
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2397
2171
                 avahi_strerror(avahi_server_errno(mc.server)));
2409
2183
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2410
2184
  }
2411
2185
 
2412
 
  ret = avahi_loop_with_timeout(simple_poll,
2413
 
                                (int)(retry_interval * 1000), &mc);
 
2186
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2187
                                (int)(retry_interval * 1000));
2414
2188
  if(debug){
2415
2189
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2416
2190
                 (ret == 0) ? "successfully" : "with error");
2423
2197
  }
2424
2198
  
2425
2199
  /* Cleanup things */
2426
 
  free(mc.interfaces);
2427
 
  
2428
2200
  if(sb != NULL)
2429
2201
    avahi_s_service_browser_free(sb);
2430
2202
  
2431
2203
  if(mc.server != NULL)
2432
2204
    avahi_server_free(mc.server);
2433
2205
  
2434
 
  if(simple_poll != NULL)
2435
 
    avahi_simple_poll_free(simple_poll);
 
2206
  if(mc.simple_poll != NULL)
 
2207
    avahi_simple_poll_free(mc.simple_poll);
2436
2208
  
2437
2209
  if(gnutls_initialized){
2438
2210
    gnutls_certificate_free_credentials(mc.cred);
2455
2227
    }
2456
2228
  }
2457
2229
  
 
2230
  /* Run network hooks */
 
2231
  run_network_hooks("stop", interface, delay);
 
2232
  
2458
2233
  /* Re-raise priviliges */
2459
2234
  {
2460
 
    raise_privileges();
2461
 
    
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");
 
2235
    errno = 0;
 
2236
    ret = seteuid(0);
 
2237
    if(ret == -1){
 
2238
      perror_plus("seteuid");
 
2239
    }
 
2240
    
 
2241
    /* Take down the network interface */
 
2242
    if(take_down_interface and geteuid() == 0){
 
2243
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2244
      if(ret == -1){
 
2245
        perror_plus("ioctl SIOCGIFFLAGS");
 
2246
      } else if(network.ifr_flags & IFF_UP){
 
2247
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2248
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2249
        if(ret == -1){
 
2250
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2476
2251
        }
2477
2252
      }
2478
 
      if(debug and (interfaces_to_take_down == NULL)){
2479
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2480
 
                     " down\n");
 
2253
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2254
      if(ret == -1){
 
2255
        perror_plus("close");
2481
2256
      }
2482
2257
    }
2483
 
    
2484
 
    lower_privileges_permanently();
2485
 
  }
2486
 
  
2487
 
  free(interfaces_to_take_down);
2488
 
  free(interfaces_hooks);
 
2258
  }
 
2259
  /* Lower privileges permanently */
 
2260
  errno = 0;
 
2261
  ret = setuid(uid);
 
2262
  if(ret == -1){
 
2263
    perror_plus("setuid");
 
2264
  }
2489
2265
  
2490
2266
  /* Removes the GPGME temp directory and all files inside */
2491
2267
  if(tempdir_created){