/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-01 16:07:20 UTC
  • mfrom: (237.7.140 trunk)
  • mto: This revision was merged to the branch mainline in revision 301.
  • Revision ID: teddy@recompile.se-20120601160720-vsivlnue8qqkcsla
Merge from trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif  /* not _LARGEFILE_SOURCE */
 
35
#endif
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror() */
 
43
                                   stdout, ferror(), remove() */
44
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(),
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() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
58
                                   inet_pton(), connect() */
 
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() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit(),
77
 
                                   unlinkat() */
78
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
76
                                   setgid(), pause(), _exit() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
79
78
#include <iso646.h>             /* not, or, and */
80
79
#include <argp.h>               /* struct argp_option, error_t, struct
81
80
                                   argp_state, struct argp,
89
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
90
89
                                   WEXITSTATUS(), WTERMSIG() */
91
90
#include <grp.h>                /* setgroups() */
92
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
93
 
                                   argz_delete(), argz_append(),
94
 
                                   argz_stringify(), argz_add(),
95
 
                                   argz_count() */
96
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
97
 
                                   EAI_SYSTEM, gai_strerror() */
98
91
 
99
92
#ifdef __linux__
100
93
#include <sys/klog.h>           /* klogctl() */
142
135
static const char sys_class_net[] = "/sys/class/net";
143
136
char *connect_to = NULL;
144
137
const char *hookdir = HOOKDIR;
145
 
int hookdir_fd = -1;
146
 
uid_t uid = 65534;
147
 
gid_t gid = 65534;
148
138
 
149
139
/* Doubly linked list that need to be circularly linked when used */
150
140
typedef struct server{
151
141
  const char *ip;
152
 
  in_port_t port;
 
142
  uint16_t port;
153
143
  AvahiIfIndex if_index;
154
144
  int af;
155
145
  struct timespec last_seen;
159
149
 
160
150
/* Used for passing in values through the Avahi callback functions */
161
151
typedef struct {
 
152
  AvahiSimplePoll *simple_poll;
162
153
  AvahiServer *server;
163
154
  gnutls_certificate_credentials_t cred;
164
155
  unsigned int dh_bits;
166
157
  const char *priority;
167
158
  gpgme_ctx_t ctx;
168
159
  server *current_server;
169
 
  char *interfaces;
170
 
  size_t interfaces_size;
171
160
} mandos_context;
172
161
 
173
 
/* global so signal handler can reach it*/
174
 
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 };
175
167
 
176
168
sig_atomic_t quit_now = 0;
177
169
int signal_received = 0;
185
177
  perror(print_text);
186
178
}
187
179
 
188
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
180
__attribute__((format (gnu_printf, 2, 3)))
189
181
int fprintf_plus(FILE *stream, const char *format, ...){
190
182
  va_list ap;
191
183
  va_start (ap, format);
192
184
  
193
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
194
186
                             program_invocation_short_name));
195
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
196
188
}
197
189
 
198
190
/*
200
192
 * bytes. "buffer_capacity" is how much is currently allocated,
201
193
 * "buffer_length" is how much is already used.
202
194
 */
203
 
__attribute__((nonnull, warn_unused_result))
204
195
size_t incbuffer(char **buffer, size_t buffer_length,
205
196
                 size_t buffer_capacity){
206
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
207
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
208
 
    if(new_buf == NULL){
209
 
      int old_errno = errno;
210
 
      free(*buffer);
211
 
      errno = old_errno;
212
 
      *buffer = NULL;
 
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
199
    if(buffer == NULL){
213
200
      return 0;
214
201
    }
215
 
    *buffer = new_buf;
216
202
    buffer_capacity += BUFFER_SIZE;
217
203
  }
218
204
  return buffer_capacity;
219
205
}
220
206
 
221
207
/* Add server to set of servers to retry periodically */
222
 
__attribute__((nonnull, warn_unused_result))
223
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
224
 
                int af, server **current_server){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
225
210
  int ret;
226
211
  server *new_server = malloc(sizeof(server));
227
212
  if(new_server == NULL){
234
219
                          .af = af };
235
220
  if(new_server->ip == NULL){
236
221
    perror_plus("strdup");
237
 
    free(new_server);
238
 
    return false;
239
 
  }
240
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
 
  if(ret == -1){
242
 
    perror_plus("clock_gettime");
243
 
#ifdef __GNUC__
244
 
#pragma GCC diagnostic push
245
 
#pragma GCC diagnostic ignored "-Wcast-qual"
246
 
#endif
247
 
    free((char *)(new_server->ip));
248
 
#ifdef __GNUC__
249
 
#pragma GCC diagnostic pop
250
 
#endif
251
 
    free(new_server);
252
222
    return false;
253
223
  }
254
224
  /* Special case of first server */
255
 
  if(*current_server == NULL){
 
225
  if (mc.current_server == NULL){
256
226
    new_server->next = new_server;
257
227
    new_server->prev = new_server;
258
 
    *current_server = new_server;
 
228
    mc.current_server = new_server;
 
229
  /* Place the new server last in the list */
259
230
  } else {
260
 
    /* Place the new server last in the list */
261
 
    new_server->next = *current_server;
262
 
    new_server->prev = (*current_server)->prev;
 
231
    new_server->next = mc.current_server;
 
232
    new_server->prev = mc.current_server->prev;
263
233
    new_server->prev->next = new_server;
264
 
    (*current_server)->prev = new_server;
 
234
    mc.current_server->prev = new_server;
 
235
  }
 
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
237
  if(ret == -1){
 
238
    perror_plus("clock_gettime");
 
239
    return false;
265
240
  }
266
241
  return true;
267
242
}
269
244
/* 
270
245
 * Initialize GPGME.
271
246
 */
272
 
__attribute__((nonnull, warn_unused_result))
273
 
static bool init_gpgme(const char * const seckey,
274
 
                       const char * const pubkey,
275
 
                       const char * const tempdir,
276
 
                       mandos_context *mc){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
277
249
  gpgme_error_t rc;
278
250
  gpgme_engine_info_t engine_info;
279
251
  
 
252
  
280
253
  /*
281
254
   * Helper function to insert pub and seckey to the engine keyring.
282
255
   */
283
 
  bool import_key(const char * const filename){
 
256
  bool import_key(const char *filename){
284
257
    int ret;
285
258
    int fd;
286
259
    gpgme_data_t pgp_data;
298
271
      return false;
299
272
    }
300
273
    
301
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
302
275
    if(rc != GPG_ERR_NO_ERROR){
303
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
304
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
348
321
  }
349
322
  
350
323
  /* Create new GPGME "context" */
351
 
  rc = gpgme_new(&(mc->ctx));
 
324
  rc = gpgme_new(&(mc.ctx));
352
325
  if(rc != GPG_ERR_NO_ERROR){
353
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
354
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
367
340
 * Decrypt OpenPGP data.
368
341
 * Returns -1 on error
369
342
 */
370
 
__attribute__((nonnull, warn_unused_result))
371
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
372
344
                                  size_t crypto_size,
373
 
                                  char **plaintext,
374
 
                                  mandos_context *mc){
 
345
                                  char **plaintext){
375
346
  gpgme_data_t dh_crypto, dh_plain;
376
347
  gpgme_error_t rc;
377
348
  ssize_t ret;
403
374
  
404
375
  /* Decrypt data from the cryptotext data buffer to the plaintext
405
376
     data buffer */
406
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
407
378
  if(rc != GPG_ERR_NO_ERROR){
408
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
409
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
410
381
    plaintext_length = -1;
411
382
    if(debug){
412
383
      gpgme_decrypt_result_t result;
413
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
384
      result = gpgme_op_decrypt_result(mc.ctx);
414
385
      if(result == NULL){
415
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
416
387
      } else {
493
464
  return plaintext_length;
494
465
}
495
466
 
496
 
__attribute__((warn_unused_result))
497
 
static const char *safer_gnutls_strerror(int value){
498
 
  const char *ret = gnutls_strerror(value);
 
467
static const char * safer_gnutls_strerror(int value){
 
468
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
469
                                               -Wunreachable-code */
499
470
  if(ret == NULL)
500
471
    ret = "(unknown)";
501
472
  return ret;
502
473
}
503
474
 
504
475
/* GnuTLS log function callback */
505
 
__attribute__((nonnull))
506
476
static void debuggnutls(__attribute__((unused)) int level,
507
477
                        const char* string){
508
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
509
479
}
510
480
 
511
 
__attribute__((nonnull, warn_unused_result))
512
481
static int init_gnutls_global(const char *pubkeyfilename,
513
 
                              const char *seckeyfilename,
514
 
                              mandos_context *mc){
 
482
                              const char *seckeyfilename){
515
483
  int ret;
516
484
  
517
485
  if(debug){
534
502
  }
535
503
  
536
504
  /* OpenPGP credentials */
537
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
538
506
  if(ret != GNUTLS_E_SUCCESS){
539
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
508
                 safer_gnutls_strerror(ret));
550
518
  }
551
519
  
552
520
  ret = gnutls_certificate_set_openpgp_key_file
553
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
521
    (mc.cred, pubkeyfilename, seckeyfilename,
554
522
     GNUTLS_OPENPGP_FMT_BASE64);
555
523
  if(ret != GNUTLS_E_SUCCESS){
556
524
    fprintf_plus(stderr,
562
530
  }
563
531
  
564
532
  /* GnuTLS server initialization */
565
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
533
  ret = gnutls_dh_params_init(&mc.dh_params);
566
534
  if(ret != GNUTLS_E_SUCCESS){
567
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
568
536
                 " initialization: %s\n",
569
537
                 safer_gnutls_strerror(ret));
570
538
    goto globalfail;
571
539
  }
572
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
573
541
  if(ret != GNUTLS_E_SUCCESS){
574
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
575
543
                 safer_gnutls_strerror(ret));
576
544
    goto globalfail;
577
545
  }
578
546
  
579
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
547
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
580
548
  
581
549
  return 0;
582
550
  
583
551
 globalfail:
584
552
  
585
 
  gnutls_certificate_free_credentials(mc->cred);
 
553
  gnutls_certificate_free_credentials(mc.cred);
586
554
  gnutls_global_deinit();
587
 
  gnutls_dh_params_deinit(mc->dh_params);
 
555
  gnutls_dh_params_deinit(mc.dh_params);
588
556
  return -1;
589
557
}
590
558
 
591
 
__attribute__((nonnull, warn_unused_result))
592
 
static int init_gnutls_session(gnutls_session_t *session,
593
 
                               mandos_context *mc){
 
559
static int init_gnutls_session(gnutls_session_t *session){
594
560
  int ret;
595
561
  /* GnuTLS session creation */
596
562
  do {
608
574
  {
609
575
    const char *err;
610
576
    do {
611
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
577
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
612
578
      if(quit_now){
613
579
        gnutls_deinit(*session);
614
580
        return -1;
625
591
  
626
592
  do {
627
593
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
628
 
                                 mc->cred);
 
594
                                 mc.cred);
629
595
    if(quit_now){
630
596
      gnutls_deinit(*session);
631
597
      return -1;
641
607
  /* ignore client certificate if any. */
642
608
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
643
609
  
644
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
610
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
645
611
  
646
612
  return 0;
647
613
}
651
617
                      __attribute__((unused)) const char *txt){}
652
618
 
653
619
/* Called when a Mandos server is found */
654
 
__attribute__((nonnull, warn_unused_result))
655
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
620
static int start_mandos_communication(const char *ip, uint16_t port,
656
621
                                      AvahiIfIndex if_index,
657
 
                                      int af, mandos_context *mc){
 
622
                                      int af){
658
623
  int ret, tcp_sd = -1;
659
624
  ssize_t sret;
660
 
  struct sockaddr_storage to;
 
625
  union {
 
626
    struct sockaddr_in in;
 
627
    struct sockaddr_in6 in6;
 
628
  } to;
661
629
  char *buffer = NULL;
662
630
  char *decrypted_buffer = NULL;
663
631
  size_t buffer_length = 0;
687
655
    return -1;
688
656
  }
689
657
  
690
 
  /* If the interface is specified and we have a list of interfaces */
691
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
692
 
    /* Check if the interface is one of the interfaces we are using */
693
 
    bool match = false;
694
 
    {
695
 
      char *interface = NULL;
696
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
697
 
                                 interface))){
698
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
699
 
          match = true;
700
 
          break;
701
 
        }
702
 
      }
703
 
    }
704
 
    if(not match){
705
 
      /* This interface does not match any in the list, so we don't
706
 
         connect to the server */
707
 
      if(debug){
708
 
        char interface[IF_NAMESIZE];
709
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
 
          perror_plus("if_indextoname");
711
 
        } else {
712
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
713
 
                       " \"%s\"\n",
714
 
                       if_indextoname((unsigned int)if_index,
715
 
                                      interface));
716
 
        }
717
 
      }
718
 
      return -1;
719
 
    }
720
 
  }
721
 
  
722
 
  ret = init_gnutls_session(&session, mc);
 
658
  ret = init_gnutls_session(&session);
723
659
  if(ret != 0){
724
660
    return -1;
725
661
  }
726
662
  
727
663
  if(debug){
728
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
729
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
665
                 PRIu16 "\n", ip, port);
730
666
  }
731
667
  
732
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
744
680
  
745
681
  memset(&to, 0, sizeof(to));
746
682
  if(af == AF_INET6){
747
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
748
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
683
    to.in6.sin6_family = (sa_family_t)af;
 
684
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
749
685
  } else {                      /* IPv4 */
750
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
751
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
686
    to.in.sin_family = (sa_family_t)af;
 
687
    ret = inet_pton(af, ip, &to.in.sin_addr);
752
688
  }
753
689
  if(ret < 0 ){
754
690
    int e = errno;
763
699
    goto mandos_end;
764
700
  }
765
701
  if(af == AF_INET6){
766
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
767
 
    if(IN6_IS_ADDR_LINKLOCAL
768
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
702
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
703
                                       -Wconversion and
 
704
                                       -Wunreachable-code */
 
705
    
 
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
708
                                -Wunreachable-code*/
769
709
      if(if_index == AVAHI_IF_UNSPEC){
770
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
771
711
                     " incomplete without a network interface\n");
773
713
        goto mandos_end;
774
714
      }
775
715
      /* Set the network interface number as scope */
776
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
716
      to.in6.sin6_scope_id = (uint32_t)if_index;
777
717
    }
778
718
  } else {
779
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
719
    to.in.sin_port = htons(port); /* Spurious warnings from
 
720
                                     -Wconversion and
 
721
                                     -Wunreachable-code */
780
722
  }
781
723
  
782
724
  if(quit_now){
790
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
791
733
        perror_plus("if_indextoname");
792
734
      } else {
793
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
794
 
                     "\n", ip, interface, (uintmax_t)port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
795
737
      }
796
738
    } else {
797
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
798
 
                   ip, (uintmax_t)port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
799
741
    }
800
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
801
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
744
    const char *pcret;
802
745
    if(af == AF_INET6){
803
 
      ret = getnameinfo((struct sockaddr *)&to,
804
 
                        sizeof(struct sockaddr_in6),
805
 
                        addrstr, sizeof(addrstr), NULL, 0,
806
 
                        NI_NUMERICHOST);
 
746
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
747
                        sizeof(addrstr));
807
748
    } else {
808
 
      ret = getnameinfo((struct sockaddr *)&to,
809
 
                        sizeof(struct sockaddr_in),
810
 
                        addrstr, sizeof(addrstr), NULL, 0,
811
 
                        NI_NUMERICHOST);
 
749
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
750
                        sizeof(addrstr));
812
751
    }
813
 
    if(ret == EAI_SYSTEM){
814
 
      perror_plus("getnameinfo");
815
 
    } else if(ret != 0) {
816
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
817
 
    } else if(strcmp(addrstr, ip) != 0){
818
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
752
    if(pcret == NULL){
 
753
      perror_plus("inet_ntop");
 
754
    } else {
 
755
      if(strcmp(addrstr, ip) != 0){
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
757
      }
819
758
    }
820
759
  }
821
760
  
825
764
  }
826
765
  
827
766
  if(af == AF_INET6){
828
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
829
 
                  sizeof(struct sockaddr_in6));
 
767
    ret = connect(tcp_sd, &to.in6, sizeof(to));
830
768
  } else {
831
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
832
 
                  sizeof(struct sockaddr_in));
 
769
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
833
770
  }
834
771
  if(ret < 0){
835
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
772
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
836
773
      int e = errno;
837
774
      perror_plus("connect");
838
775
      errno = e;
999
936
  if(buffer_length > 0){
1000
937
    ssize_t decrypted_buffer_size;
1001
938
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
1002
 
                                               &decrypted_buffer, mc);
 
939
                                               &decrypted_buffer);
1003
940
    if(decrypted_buffer_size >= 0){
1004
941
      
1005
942
      written = 0;
1053
990
  return retval;
1054
991
}
1055
992
 
1056
 
__attribute__((nonnull))
1057
993
static void resolve_callback(AvahiSServiceResolver *r,
1058
994
                             AvahiIfIndex interface,
1059
995
                             AvahiProtocol proto,
1067
1003
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1068
1004
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1069
1005
                             flags,
1070
 
                             void *mc){
1071
 
  if(r == NULL){
1072
 
    return;
1073
 
  }
 
1006
                             AVAHI_GCC_UNUSED void* userdata){
 
1007
  assert(r);
1074
1008
  
1075
1009
  /* Called whenever a service has been resolved successfully or
1076
1010
     timed out */
1077
1011
  
1078
1012
  if(quit_now){
1079
 
    avahi_s_service_resolver_free(r);
1080
1013
    return;
1081
1014
  }
1082
1015
  
1086
1019
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1087
1020
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1088
1021
                 domain,
1089
 
                 avahi_strerror(avahi_server_errno
1090
 
                                (((mandos_context*)mc)->server)));
 
1022
                 avahi_strerror(avahi_server_errno(mc.server)));
1091
1023
    break;
1092
1024
    
1093
1025
  case AVAHI_RESOLVER_FOUND:
1099
1031
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1100
1032
                     host_name, ip, (intmax_t)interface, port);
1101
1033
      }
1102
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1103
 
                                           interface,
1104
 
                                           avahi_proto_to_af(proto),
1105
 
                                           mc);
 
1034
      int ret = start_mandos_communication(ip, port, interface,
 
1035
                                           avahi_proto_to_af(proto));
1106
1036
      if(ret == 0){
1107
 
        avahi_simple_poll_quit(simple_poll);
 
1037
        avahi_simple_poll_quit(mc.simple_poll);
1108
1038
      } else {
1109
 
        if(not add_server(ip, (in_port_t)port, interface,
1110
 
                          avahi_proto_to_af(proto),
1111
 
                          &((mandos_context*)mc)->current_server)){
 
1039
        if(not add_server(ip, port, interface,
 
1040
                          avahi_proto_to_af(proto))){
1112
1041
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1113
1042
                       " list\n", name);
1114
1043
        }
1127
1056
                            const char *domain,
1128
1057
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1129
1058
                            flags,
1130
 
                            void *mc){
1131
 
  if(b == NULL){
1132
 
    return;
1133
 
  }
 
1059
                            AVAHI_GCC_UNUSED void* userdata){
 
1060
  assert(b);
1134
1061
  
1135
1062
  /* Called whenever a new services becomes available on the LAN or
1136
1063
     is removed from the LAN */
1144
1071
  case AVAHI_BROWSER_FAILURE:
1145
1072
    
1146
1073
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1147
 
                 avahi_strerror(avahi_server_errno
1148
 
                                (((mandos_context*)mc)->server)));
1149
 
    avahi_simple_poll_quit(simple_poll);
 
1074
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1075
    avahi_simple_poll_quit(mc.simple_poll);
1150
1076
    return;
1151
1077
    
1152
1078
  case AVAHI_BROWSER_NEW:
1155
1081
       the callback function is called the Avahi server will free the
1156
1082
       resolver for us. */
1157
1083
    
1158
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1159
 
                                    interface, protocol, name, type,
1160
 
                                    domain, protocol, 0,
1161
 
                                    resolve_callback, mc) == NULL)
 
1084
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1085
                                    name, type, domain, protocol, 0,
 
1086
                                    resolve_callback, NULL) == NULL)
1162
1087
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1163
1088
                   " %s\n", name,
1164
 
                   avahi_strerror(avahi_server_errno
1165
 
                                  (((mandos_context*)mc)->server)));
 
1089
                   avahi_strerror(avahi_server_errno(mc.server)));
1166
1090
    break;
1167
1091
    
1168
1092
  case AVAHI_BROWSER_REMOVE:
1187
1111
  signal_received = sig;
1188
1112
  int old_errno = errno;
1189
1113
  /* set main loop to exit */
1190
 
  if(simple_poll != NULL){
1191
 
    avahi_simple_poll_quit(simple_poll);
 
1114
  if(mc.simple_poll != NULL){
 
1115
    avahi_simple_poll_quit(mc.simple_poll);
1192
1116
  }
1193
1117
  errno = old_errno;
1194
1118
}
1195
1119
 
1196
 
__attribute__((nonnull, warn_unused_result))
1197
1120
bool get_flags(const char *ifname, struct ifreq *ifr){
1198
1121
  int ret;
1199
 
  error_t ret_errno;
1200
1122
  
1201
1123
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1202
1124
  if(s < 0){
1203
 
    ret_errno = errno;
1204
1125
    perror_plus("socket");
1205
 
    errno = ret_errno;
1206
1126
    return false;
1207
1127
  }
1208
1128
  strcpy(ifr->ifr_name, ifname);
1209
1129
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1210
1130
  if(ret == -1){
1211
1131
    if(debug){
1212
 
      ret_errno = errno;
1213
1132
      perror_plus("ioctl SIOCGIFFLAGS");
1214
 
      errno = ret_errno;
1215
1133
    }
1216
1134
    return false;
1217
1135
  }
1218
1136
  return true;
1219
1137
}
1220
1138
 
1221
 
__attribute__((nonnull, warn_unused_result))
1222
1139
bool good_flags(const char *ifname, const struct ifreq *ifr){
1223
1140
  
1224
1141
  /* Reject the loopback device */
1266
1183
 * corresponds to an acceptable network device.
1267
1184
 * (This function is passed to scandir(3) as a filter function.)
1268
1185
 */
1269
 
__attribute__((nonnull, warn_unused_result))
1270
1186
int good_interface(const struct dirent *if_entry){
1271
1187
  if(if_entry->d_name[0] == '.'){
1272
1188
    return 0;
1288
1204
}
1289
1205
 
1290
1206
/* 
1291
 
 * This function determines if a network interface is up.
1292
 
 */
1293
 
__attribute__((nonnull, warn_unused_result))
1294
 
bool interface_is_up(const char *interface){
1295
 
  struct ifreq ifr;
1296
 
  if(not get_flags(interface, &ifr)){
1297
 
    if(debug){
1298
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1299
 
                   "\"%s\"\n", interface);
1300
 
    }
1301
 
    return false;
1302
 
  }
1303
 
  
1304
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1305
 
}
1306
 
 
1307
 
/* 
1308
 
 * This function determines if a network interface is running
1309
 
 */
1310
 
__attribute__((nonnull, warn_unused_result))
1311
 
bool interface_is_running(const char *interface){
1312
 
  struct ifreq ifr;
1313
 
  if(not get_flags(interface, &ifr)){
1314
 
    if(debug){
1315
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1316
 
                   "\"%s\"\n", interface);
1317
 
    }
1318
 
    return false;
1319
 
  }
1320
 
  
1321
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1322
 
}
1323
 
 
1324
 
__attribute__((nonnull, pure, warn_unused_result))
 
1207
 * This function determines if a directory entry in /sys/class/net
 
1208
 * corresponds to an acceptable network device which is up.
 
1209
 * (This function is passed to scandir(3) as a filter function.)
 
1210
 */
 
1211
int up_interface(const struct dirent *if_entry){
 
1212
  if(if_entry->d_name[0] == '.'){
 
1213
    return 0;
 
1214
  }
 
1215
  
 
1216
  struct ifreq ifr;
 
1217
  if(not get_flags(if_entry->d_name, &ifr)){
 
1218
    if(debug){
 
1219
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1220
                   "\"%s\"\n", if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  /* Reject down interfaces */
 
1226
  if(not (ifr.ifr_flags & IFF_UP)){
 
1227
    if(debug){
 
1228
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1229
                   if_entry->d_name);
 
1230
    }
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  /* Reject non-running interfaces */
 
1235
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1236
    if(debug){
 
1237
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1238
                   if_entry->d_name);
 
1239
    }
 
1240
    return 0;
 
1241
  }
 
1242
  
 
1243
  if(not good_flags(if_entry->d_name, &ifr)){
 
1244
    return 0;
 
1245
  }
 
1246
  return 1;
 
1247
}
 
1248
 
1325
1249
int notdotentries(const struct dirent *direntry){
1326
1250
  /* Skip "." and ".." */
1327
1251
  if(direntry->d_name[0] == '.'
1334
1258
}
1335
1259
 
1336
1260
/* Is this directory entry a runnable program? */
1337
 
__attribute__((nonnull, warn_unused_result))
1338
1261
int runnable_hook(const struct dirent *direntry){
1339
1262
  int ret;
1340
1263
  size_t sret;
1348
1271
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1349
1272
                "abcdefghijklmnopqrstuvwxyz"
1350
1273
                "0123456789"
1351
 
                "_.-");
 
1274
                "_-");
1352
1275
  if((direntry->d_name)[sret] != '\0'){
1353
1276
    /* Contains non-allowed characters */
1354
1277
    if(debug){
1358
1281
    return 0;
1359
1282
  }
1360
1283
  
1361
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1284
  char *fullname = NULL;
 
1285
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1286
  if(ret < 0){
 
1287
    perror_plus("asprintf");
 
1288
    return 0;
 
1289
  }
 
1290
  
 
1291
  ret = stat(fullname, &st);
1362
1292
  if(ret == -1){
1363
1293
    if(debug){
1364
1294
      perror_plus("Could not stat hook");
1388
1318
  return 1;
1389
1319
}
1390
1320
 
1391
 
__attribute__((nonnull, warn_unused_result))
1392
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1393
 
                            mandos_context *mc){
 
1321
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1394
1322
  int ret;
1395
1323
  struct timespec now;
1396
1324
  struct timespec waited_time;
1397
1325
  intmax_t block_time;
1398
1326
  
1399
1327
  while(true){
1400
 
    if(mc->current_server == NULL){
1401
 
      if(debug){
 
1328
    if(mc.current_server == NULL){
 
1329
      if (debug){
1402
1330
        fprintf_plus(stderr, "Wait until first server is found."
1403
1331
                     " No timeout!\n");
1404
1332
      }
1405
1333
      ret = avahi_simple_poll_iterate(s, -1);
1406
1334
    } else {
1407
 
      if(debug){
 
1335
      if (debug){
1408
1336
        fprintf_plus(stderr, "Check current_server if we should run"
1409
1337
                     " it, or wait\n");
1410
1338
      }
1417
1345
      /* Calculating in ms how long time between now and server
1418
1346
         who we visted longest time ago. Now - last seen.  */
1419
1347
      waited_time.tv_sec = (now.tv_sec
1420
 
                            - mc->current_server->last_seen.tv_sec);
 
1348
                            - mc.current_server->last_seen.tv_sec);
1421
1349
      waited_time.tv_nsec = (now.tv_nsec
1422
 
                             - mc->current_server->last_seen.tv_nsec);
 
1350
                             - mc.current_server->last_seen.tv_nsec);
1423
1351
      /* total time is 10s/10,000ms.
1424
1352
         Converting to s from ms by dividing by 1,000,
1425
1353
         and ns to ms by dividing by 1,000,000. */
1427
1355
                     - ((intmax_t)waited_time.tv_sec * 1000))
1428
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1429
1357
      
1430
 
      if(debug){
 
1358
      if (debug){
1431
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1432
1360
                     block_time);
1433
1361
      }
1434
1362
      
1435
1363
      if(block_time <= 0){
1436
 
        ret = start_mandos_communication(mc->current_server->ip,
1437
 
                                         mc->current_server->port,
1438
 
                                         mc->current_server->if_index,
1439
 
                                         mc->current_server->af, mc);
 
1364
        ret = start_mandos_communication(mc.current_server->ip,
 
1365
                                         mc.current_server->port,
 
1366
                                         mc.current_server->if_index,
 
1367
                                         mc.current_server->af);
1440
1368
        if(ret == 0){
1441
 
          avahi_simple_poll_quit(s);
 
1369
          avahi_simple_poll_quit(mc.simple_poll);
1442
1370
          return 0;
1443
1371
        }
1444
1372
        ret = clock_gettime(CLOCK_MONOTONIC,
1445
 
                            &mc->current_server->last_seen);
 
1373
                            &mc.current_server->last_seen);
1446
1374
        if(ret == -1){
1447
1375
          perror_plus("clock_gettime");
1448
1376
          return -1;
1449
1377
        }
1450
 
        mc->current_server = mc->current_server->next;
 
1378
        mc.current_server = mc.current_server->next;
1451
1379
        block_time = 0;         /* Call avahi to find new Mandos
1452
1380
                                   servers, but don't block */
1453
1381
      }
1455
1383
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1456
1384
    }
1457
1385
    if(ret != 0){
1458
 
      if(ret > 0 or errno != EINTR){
 
1386
      if (ret > 0 or errno != EINTR){
1459
1387
        return (ret != 1) ? ret : 0;
1460
1388
      }
1461
1389
    }
1462
1390
  }
1463
1391
}
1464
1392
 
1465
 
/* Set effective uid to 0, return errno */
1466
 
__attribute__((warn_unused_result))
1467
 
error_t raise_privileges(void){
1468
 
  error_t old_errno = errno;
1469
 
  error_t ret_errno = 0;
1470
 
  if(seteuid(0) == -1){
1471
 
    ret_errno = errno;
1472
 
  }
1473
 
  errno = old_errno;
1474
 
  return ret_errno;
1475
 
}
1476
 
 
1477
 
/* Set effective and real user ID to 0.  Return errno. */
1478
 
__attribute__((warn_unused_result))
1479
 
error_t raise_privileges_permanently(void){
1480
 
  error_t old_errno = errno;
1481
 
  error_t ret_errno = raise_privileges();
1482
 
  if(ret_errno != 0){
1483
 
    errno = old_errno;
1484
 
    return ret_errno;
1485
 
  }
1486
 
  if(setuid(0) == -1){
1487
 
    ret_errno = errno;
1488
 
  }
1489
 
  errno = old_errno;
1490
 
  return ret_errno;
1491
 
}
1492
 
 
1493
 
/* Set effective user ID to unprivileged saved user ID */
1494
 
__attribute__((warn_unused_result))
1495
 
error_t lower_privileges(void){
1496
 
  error_t old_errno = errno;
1497
 
  error_t ret_errno = 0;
1498
 
  if(seteuid(uid) == -1){
1499
 
    ret_errno = errno;
1500
 
  }
1501
 
  errno = old_errno;
1502
 
  return ret_errno;
1503
 
}
1504
 
 
1505
 
/* Lower privileges permanently */
1506
 
__attribute__((warn_unused_result))
1507
 
error_t lower_privileges_permanently(void){
1508
 
  error_t old_errno = errno;
1509
 
  error_t ret_errno = 0;
1510
 
  if(setuid(uid) == -1){
1511
 
    ret_errno = errno;
1512
 
  }
1513
 
  errno = old_errno;
1514
 
  return ret_errno;
1515
 
}
1516
 
 
1517
 
__attribute__((nonnull))
1518
 
void run_network_hooks(const char *mode, const char *interface,
 
1393
bool run_network_hooks(const char *mode, const char *interface,
1519
1394
                       const float delay){
1520
 
  struct dirent **direntries = NULL;
1521
 
  if(hookdir_fd == -1){
1522
 
    hookdir_fd = open(hookdir, O_RDONLY);
1523
 
    if(hookdir_fd == -1){
1524
 
      if(errno == ENOENT){
1525
 
        if(debug){
1526
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1527
 
                       " found\n", hookdir);
1528
 
        }
1529
 
      } else {
1530
 
        perror_plus("open");
1531
 
      }
1532
 
      return;
1533
 
    }
1534
 
  }
1535
 
#ifdef __GLIBC__
1536
 
#if __GLIBC_PREREQ(2, 15)
1537
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1538
 
                           runnable_hook, alphasort);
1539
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1540
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1541
 
                         alphasort);
1542
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1543
 
#else   /* not __GLIBC__ */
1544
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1545
 
                         alphasort);
1546
 
#endif  /* not __GLIBC__ */
 
1395
  struct dirent **direntries;
 
1396
  struct dirent *direntry;
 
1397
  int ret;
 
1398
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1399
                         alphasort);
1547
1400
  if(numhooks == -1){
1548
1401
    perror_plus("scandir");
1549
 
    return;
1550
 
  }
1551
 
  struct dirent *direntry;
1552
 
  int ret;
1553
 
  int devnull = open("/dev/null", O_RDONLY);
1554
 
  for(int i = 0; i < numhooks; i++){
1555
 
    direntry = direntries[i];
1556
 
    if(debug){
1557
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1558
 
                   direntry->d_name);
1559
 
    }
1560
 
    pid_t hook_pid = fork();
1561
 
    if(hook_pid == 0){
1562
 
      /* Child */
1563
 
      /* Raise privileges */
1564
 
      errno = raise_privileges_permanently();
1565
 
      if(errno != 0){
1566
 
        perror_plus("Failed to raise privileges");
1567
 
        _exit(EX_NOPERM);
1568
 
      }
1569
 
      /* Set group */
1570
 
      errno = 0;
1571
 
      ret = setgid(0);
1572
 
      if(ret == -1){
1573
 
        perror_plus("setgid");
1574
 
        _exit(EX_NOPERM);
1575
 
      }
1576
 
      /* Reset supplementary groups */
1577
 
      errno = 0;
1578
 
      ret = setgroups(0, NULL);
1579
 
      if(ret == -1){
1580
 
        perror_plus("setgroups");
1581
 
        _exit(EX_NOPERM);
1582
 
      }
1583
 
      ret = dup2(devnull, STDIN_FILENO);
1584
 
      if(ret == -1){
1585
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1586
 
        _exit(EX_OSERR);
1587
 
      }
1588
 
      ret = close(devnull);
1589
 
      if(ret == -1){
1590
 
        perror_plus("close");
1591
 
        _exit(EX_OSERR);
1592
 
      }
1593
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1594
 
      if(ret == -1){
1595
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1596
 
        _exit(EX_OSERR);
1597
 
      }
1598
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1599
 
      if(ret == -1){
1600
 
        perror_plus("setenv");
1601
 
        _exit(EX_OSERR);
1602
 
      }
1603
 
      ret = setenv("DEVICE", interface, 1);
1604
 
      if(ret == -1){
1605
 
        perror_plus("setenv");
1606
 
        _exit(EX_OSERR);
1607
 
      }
1608
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1609
 
      if(ret == -1){
1610
 
        perror_plus("setenv");
1611
 
        _exit(EX_OSERR);
1612
 
      }
1613
 
      ret = setenv("MODE", mode, 1);
1614
 
      if(ret == -1){
1615
 
        perror_plus("setenv");
1616
 
        _exit(EX_OSERR);
1617
 
      }
1618
 
      char *delaystring;
1619
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1620
 
      if(ret == -1){
 
1402
  } else {
 
1403
    int devnull = open("/dev/null", O_RDONLY);
 
1404
    for(int i = 0; i < numhooks; i++){
 
1405
      direntry = direntries[i];
 
1406
      char *fullname = NULL;
 
1407
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1408
      if(ret < 0){
1621
1409
        perror_plus("asprintf");
1622
 
        _exit(EX_OSERR);
1623
 
      }
1624
 
      ret = setenv("DELAY", delaystring, 1);
1625
 
      if(ret == -1){
 
1410
        continue;
 
1411
      }
 
1412
      if(debug){
 
1413
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1414
                     direntry->d_name);
 
1415
      }
 
1416
      pid_t hook_pid = fork();
 
1417
      if(hook_pid == 0){
 
1418
        /* Child */
 
1419
        /* Raise privileges */
 
1420
        errno = 0;
 
1421
        ret = seteuid(0);
 
1422
        if(ret == -1){
 
1423
          perror_plus("seteuid");
 
1424
        }
 
1425
        /* Raise privileges even more */
 
1426
        errno = 0;
 
1427
        ret = setuid(0);
 
1428
        if(ret == -1){
 
1429
          perror_plus("setuid");
 
1430
        }
 
1431
        /* Set group */
 
1432
        errno = 0;
 
1433
        ret = setgid(0);
 
1434
        if(ret == -1){
 
1435
          perror_plus("setgid");
 
1436
        }
 
1437
        /* Reset supplementary groups */
 
1438
        errno = 0;
 
1439
        ret = setgroups(0, NULL);
 
1440
        if(ret == -1){
 
1441
          perror_plus("setgroups");
 
1442
        }
 
1443
        dup2(devnull, STDIN_FILENO);
 
1444
        close(devnull);
 
1445
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1446
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1447
        if(ret == -1){
 
1448
          perror_plus("setenv");
 
1449
          _exit(EX_OSERR);
 
1450
        }
 
1451
        ret = setenv("DEVICE", interface, 1);
 
1452
        if(ret == -1){
 
1453
          perror_plus("setenv");
 
1454
          _exit(EX_OSERR);
 
1455
        }
 
1456
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1457
        if(ret == -1){
 
1458
          perror_plus("setenv");
 
1459
          _exit(EX_OSERR);
 
1460
        }
 
1461
        ret = setenv("MODE", mode, 1);
 
1462
        if(ret == -1){
 
1463
          perror_plus("setenv");
 
1464
          _exit(EX_OSERR);
 
1465
        }
 
1466
        char *delaystring;
 
1467
        ret = asprintf(&delaystring, "%f", delay);
 
1468
        if(ret == -1){
 
1469
          perror_plus("asprintf");
 
1470
          _exit(EX_OSERR);
 
1471
        }
 
1472
        ret = setenv("DELAY", delaystring, 1);
 
1473
        if(ret == -1){
 
1474
          free(delaystring);
 
1475
          perror_plus("setenv");
 
1476
          _exit(EX_OSERR);
 
1477
        }
1626
1478
        free(delaystring);
1627
 
        perror_plus("setenv");
1628
 
        _exit(EX_OSERR);
1629
 
      }
1630
 
      free(delaystring);
1631
 
      if(connect_to != NULL){
1632
 
        ret = setenv("CONNECT", connect_to, 1);
1633
 
        if(ret == -1){
1634
 
          perror_plus("setenv");
1635
 
          _exit(EX_OSERR);
1636
 
        }
1637
 
      }
1638
 
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
1639
 
      if(hook_fd == -1){
1640
 
        perror_plus("openat");
1641
 
        _exit(EXIT_FAILURE);
1642
 
      }
1643
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1644
 
        perror_plus("close");
1645
 
        _exit(EXIT_FAILURE);
1646
 
      }
1647
 
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1648
 
                 environ) == -1){
1649
 
        perror_plus("fexecve");
1650
 
        _exit(EXIT_FAILURE);
1651
 
      }
1652
 
    } else {
1653
 
      int status;
1654
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1655
 
        perror_plus("waitpid");
1656
 
        free(direntry);
1657
 
        continue;
1658
 
      }
1659
 
      if(WIFEXITED(status)){
1660
 
        if(WEXITSTATUS(status) != 0){
1661
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1662
 
                       " with status %d\n", direntry->d_name,
1663
 
                       WEXITSTATUS(status));
1664
 
          free(direntry);
1665
 
          continue;
1666
 
        }
1667
 
      } else if(WIFSIGNALED(status)){
1668
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1669
 
                     " signal %d\n", direntry->d_name,
1670
 
                     WTERMSIG(status));
1671
 
        free(direntry);
1672
 
        continue;
1673
 
      } else {
1674
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1675
 
                     " crashed\n", direntry->d_name);
1676
 
        free(direntry);
1677
 
        continue;
1678
 
      }
1679
 
    }
1680
 
    if(debug){
1681
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1682
 
                   direntry->d_name);
1683
 
    }
1684
 
    free(direntry);
1685
 
  }
1686
 
  free(direntries);
1687
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1688
 
    perror_plus("close");
1689
 
  } else {
1690
 
    hookdir_fd = -1;
1691
 
  }
1692
 
  close(devnull);
1693
 
}
1694
 
 
1695
 
__attribute__((nonnull, warn_unused_result))
1696
 
error_t bring_up_interface(const char *const interface,
1697
 
                           const float delay){
1698
 
  error_t old_errno = errno;
1699
 
  int ret;
1700
 
  struct ifreq network;
1701
 
  unsigned int if_index = if_nametoindex(interface);
1702
 
  if(if_index == 0){
1703
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1704
 
    errno = old_errno;
1705
 
    return ENXIO;
1706
 
  }
1707
 
  
1708
 
  if(quit_now){
1709
 
    errno = old_errno;
1710
 
    return EINTR;
1711
 
  }
1712
 
  
1713
 
  if(not interface_is_up(interface)){
1714
 
    error_t ret_errno = 0, ioctl_errno = 0;
1715
 
    if(not get_flags(interface, &network)){
1716
 
      ret_errno = errno;
1717
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1718
 
                   "\"%s\"\n", interface);
1719
 
      errno = old_errno;
1720
 
      return ret_errno;
1721
 
    }
1722
 
    network.ifr_flags |= IFF_UP; /* set flag */
1723
 
    
1724
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1725
 
    if(sd == -1){
1726
 
      ret_errno = errno;
1727
 
      perror_plus("socket");
1728
 
      errno = old_errno;
1729
 
      return ret_errno;
1730
 
    }
1731
 
    
1732
 
    if(quit_now){
1733
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1734
 
      if(ret == -1){
1735
 
        perror_plus("close");
1736
 
      }
1737
 
      errno = old_errno;
1738
 
      return EINTR;
1739
 
    }
1740
 
    
1741
 
    if(debug){
1742
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1743
 
                   interface);
1744
 
    }
1745
 
    
1746
 
    /* Raise privileges */
1747
 
    ret_errno = raise_privileges();
1748
 
    if(ret_errno != 0){
1749
 
      errno = ret_errno;
1750
 
      perror_plus("Failed to raise privileges");
1751
 
    }
1752
 
    
1753
 
#ifdef __linux__
1754
 
    int ret_linux;
1755
 
    bool restore_loglevel = false;
1756
 
    if(ret_errno == 0){
1757
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1758
 
         messages about the network interface to mess up the prompt */
1759
 
      ret_linux = klogctl(8, NULL, 5);
1760
 
      if(ret_linux == -1){
1761
 
        perror_plus("klogctl");
1762
 
      } else {
1763
 
        restore_loglevel = true;
1764
 
      }
1765
 
    }
1766
 
#endif  /* __linux__ */
1767
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1768
 
    ioctl_errno = errno;
1769
 
#ifdef __linux__
1770
 
    if(restore_loglevel){
1771
 
      ret_linux = klogctl(7, NULL, 0);
1772
 
      if(ret_linux == -1){
1773
 
        perror_plus("klogctl");
1774
 
      }
1775
 
    }
1776
 
#endif  /* __linux__ */
1777
 
    
1778
 
    /* If raise_privileges() succeeded above */
1779
 
    if(ret_errno == 0){
1780
 
      /* Lower privileges */
1781
 
      ret_errno = lower_privileges();
1782
 
      if(ret_errno != 0){
1783
 
        errno = ret_errno;
1784
 
        perror_plus("Failed to lower privileges");
1785
 
      }
1786
 
    }
1787
 
    
1788
 
    /* Close the socket */
1789
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1790
 
    if(ret == -1){
1791
 
      perror_plus("close");
1792
 
    }
1793
 
    
1794
 
    if(ret_setflags == -1){
1795
 
      errno = ioctl_errno;
1796
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1797
 
      errno = old_errno;
1798
 
      return ioctl_errno;
1799
 
    }
1800
 
  } else if(debug){
1801
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1802
 
                 interface);
1803
 
  }
1804
 
  
1805
 
  /* Sleep checking until interface is running.
1806
 
     Check every 0.25s, up to total time of delay */
1807
 
  for(int i=0; i < delay * 4; i++){
1808
 
    if(interface_is_running(interface)){
1809
 
      break;
1810
 
    }
1811
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1812
 
    ret = nanosleep(&sleeptime, NULL);
1813
 
    if(ret == -1 and errno != EINTR){
1814
 
      perror_plus("nanosleep");
1815
 
    }
1816
 
  }
1817
 
  
1818
 
  errno = old_errno;
1819
 
  return 0;
1820
 
}
1821
 
 
1822
 
__attribute__((nonnull, warn_unused_result))
1823
 
error_t take_down_interface(const char *const interface){
1824
 
  error_t old_errno = errno;
1825
 
  struct ifreq network;
1826
 
  unsigned int if_index = if_nametoindex(interface);
1827
 
  if(if_index == 0){
1828
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1829
 
    errno = old_errno;
1830
 
    return ENXIO;
1831
 
  }
1832
 
  if(interface_is_up(interface)){
1833
 
    error_t ret_errno = 0, ioctl_errno = 0;
1834
 
    if(not get_flags(interface, &network) and debug){
1835
 
      ret_errno = errno;
1836
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1837
 
                   "\"%s\"\n", interface);
1838
 
      errno = old_errno;
1839
 
      return ret_errno;
1840
 
    }
1841
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1842
 
    
1843
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1844
 
    if(sd == -1){
1845
 
      ret_errno = errno;
1846
 
      perror_plus("socket");
1847
 
      errno = old_errno;
1848
 
      return ret_errno;
1849
 
    }
1850
 
    
1851
 
    if(debug){
1852
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1853
 
                   interface);
1854
 
    }
1855
 
    
1856
 
    /* Raise privileges */
1857
 
    ret_errno = raise_privileges();
1858
 
    if(ret_errno != 0){
1859
 
      errno = ret_errno;
1860
 
      perror_plus("Failed to raise privileges");
1861
 
    }
1862
 
    
1863
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1864
 
    ioctl_errno = errno;
1865
 
    
1866
 
    /* If raise_privileges() succeeded above */
1867
 
    if(ret_errno == 0){
1868
 
      /* Lower privileges */
1869
 
      ret_errno = lower_privileges();
1870
 
      if(ret_errno != 0){
1871
 
        errno = ret_errno;
1872
 
        perror_plus("Failed to lower privileges");
1873
 
      }
1874
 
    }
1875
 
    
1876
 
    /* Close the socket */
1877
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1878
 
    if(ret == -1){
1879
 
      perror_plus("close");
1880
 
    }
1881
 
    
1882
 
    if(ret_setflags == -1){
1883
 
      errno = ioctl_errno;
1884
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1885
 
      errno = old_errno;
1886
 
      return ioctl_errno;
1887
 
    }
1888
 
  } else if(debug){
1889
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1890
 
                 interface);
1891
 
  }
1892
 
  
1893
 
  errno = old_errno;
1894
 
  return 0;
 
1479
        if(connect_to != NULL){
 
1480
          ret = setenv("CONNECT", connect_to, 1);
 
1481
          if(ret == -1){
 
1482
            perror_plus("setenv");
 
1483
            _exit(EX_OSERR);
 
1484
          }
 
1485
        }
 
1486
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1487
          perror_plus("execl");
 
1488
          _exit(EXIT_FAILURE);
 
1489
        }
 
1490
      } else {
 
1491
        int status;
 
1492
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1493
          perror_plus("waitpid");
 
1494
          free(fullname);
 
1495
          continue;
 
1496
        }
 
1497
        if(WIFEXITED(status)){
 
1498
          if(WEXITSTATUS(status) != 0){
 
1499
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1500
                         " with status %d\n", direntry->d_name,
 
1501
                         WEXITSTATUS(status));
 
1502
            free(fullname);
 
1503
            continue;
 
1504
          }
 
1505
        } else if(WIFSIGNALED(status)){
 
1506
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1507
                       " signal %d\n", direntry->d_name,
 
1508
                       WTERMSIG(status));
 
1509
          free(fullname);
 
1510
          continue;
 
1511
        } else {
 
1512
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1513
                       " crashed\n", direntry->d_name);
 
1514
          free(fullname);
 
1515
          continue;
 
1516
        }
 
1517
      }
 
1518
      free(fullname);
 
1519
      if(debug){
 
1520
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1521
                     direntry->d_name);
 
1522
      }
 
1523
    }
 
1524
    close(devnull);
 
1525
  }
 
1526
  return true;
1895
1527
}
1896
1528
 
1897
1529
int main(int argc, char *argv[]){
1898
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1899
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1900
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1901
 
                        .interfaces = NULL, .interfaces_size = 0 };
1902
1530
  AvahiSServiceBrowser *sb = NULL;
1903
 
  error_t ret_errno;
 
1531
  int error;
1904
1532
  int ret;
1905
1533
  intmax_t tmpmax;
1906
1534
  char *tmp;
1907
1535
  int exitcode = EXIT_SUCCESS;
1908
 
  char *interfaces_to_take_down = NULL;
1909
 
  size_t interfaces_to_take_down_size = 0;
1910
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1911
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1912
 
  char *tempdir = NULL;
 
1536
  const char *interface = "";
 
1537
  struct ifreq network;
 
1538
  int sd = -1;
 
1539
  bool take_down_interface = false;
 
1540
  uid_t uid;
 
1541
  gid_t gid;
 
1542
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1543
  bool tempdir_created = false;
1913
1544
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1914
1545
  const char *seckey = PATHDIR "/" SECKEY;
1915
1546
  const char *pubkey = PATHDIR "/" PUBKEY;
1916
 
  char *interfaces_hooks = NULL;
1917
1547
  
1918
1548
  bool gnutls_initialized = false;
1919
1549
  bool gpgme_initialized = false;
2010
1640
        connect_to = arg;
2011
1641
        break;
2012
1642
      case 'i':                 /* --interface */
2013
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2014
 
                                 arg, (int)',');
2015
 
        if(ret_errno != 0){
2016
 
          argp_error(state, "%s", strerror(ret_errno));
2017
 
        }
 
1643
        interface = arg;
2018
1644
        break;
2019
1645
      case 's':                 /* --seckey */
2020
1646
        seckey = arg;
2097
1723
    /* Work around Debian bug #633582:
2098
1724
       <http://bugs.debian.org/633582> */
2099
1725
    
2100
 
    /* Re-raise privileges */
2101
 
    ret_errno = raise_privileges();
2102
 
    if(ret_errno != 0){
2103
 
      errno = ret_errno;
2104
 
      perror_plus("Failed to raise privileges");
 
1726
    /* Re-raise priviliges */
 
1727
    errno = 0;
 
1728
    ret = seteuid(0);
 
1729
    if(ret == -1){
 
1730
      perror_plus("seteuid");
2105
1731
    } else {
2106
1732
      struct stat st;
2107
1733
      
2148
1774
      }
2149
1775
    
2150
1776
      /* Lower privileges */
2151
 
      ret_errno = lower_privileges();
2152
 
      if(ret_errno != 0){
2153
 
        errno = ret_errno;
2154
 
        perror_plus("Failed to lower privileges");
2155
 
      }
2156
 
    }
2157
 
  }
2158
 
  
2159
 
  /* Remove invalid interface names (except "none") */
2160
 
  {
2161
 
    char *interface = NULL;
2162
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2163
 
                                 interface))){
2164
 
      if(strcmp(interface, "none") != 0
2165
 
         and if_nametoindex(interface) == 0){
2166
 
        if(interface[0] != '\0'){
2167
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2168
 
                       " \"%s\"\n", interface);
2169
 
        }
2170
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2171
 
        interface = NULL;
 
1777
      errno = 0;
 
1778
      ret = seteuid(uid);
 
1779
      if(ret == -1){
 
1780
        perror_plus("seteuid");
2172
1781
      }
2173
1782
    }
2174
1783
  }
2175
1784
  
2176
1785
  /* Run network hooks */
2177
 
  {
2178
 
    if(mc.interfaces != NULL){
2179
 
      interfaces_hooks = malloc(mc.interfaces_size);
2180
 
      if(interfaces_hooks == NULL){
2181
 
        perror_plus("malloc");
2182
 
        goto end;
2183
 
      }
2184
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2185
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2186
 
    }
2187
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2188
 
                      interfaces_hooks : "", delay);
 
1786
  if(not run_network_hooks("start", interface, delay)){
 
1787
    goto end;
2189
1788
  }
2190
1789
  
2191
1790
  if(not debug){
2192
1791
    avahi_set_log_function(empty_log);
2193
1792
  }
2194
1793
  
 
1794
  if(interface[0] == '\0'){
 
1795
    struct dirent **direntries;
 
1796
    /* First look for interfaces that are up */
 
1797
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1798
                  alphasort);
 
1799
    if(ret == 0){
 
1800
      /* No up interfaces, look for any good interfaces */
 
1801
      free(direntries);
 
1802
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1803
                    alphasort);
 
1804
    }
 
1805
    if(ret >= 1){
 
1806
      /* Pick the first interface returned */
 
1807
      interface = strdup(direntries[0]->d_name);
 
1808
      if(debug){
 
1809
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1810
      }
 
1811
      if(interface == NULL){
 
1812
        perror_plus("malloc");
 
1813
        free(direntries);
 
1814
        exitcode = EXIT_FAILURE;
 
1815
        goto end;
 
1816
      }
 
1817
      free(direntries);
 
1818
    } else {
 
1819
      free(direntries);
 
1820
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1821
      exitcode = EXIT_FAILURE;
 
1822
      goto end;
 
1823
    }
 
1824
  }
 
1825
  
2195
1826
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2196
1827
     from the signal handler */
2197
1828
  /* Initialize the pseudo-RNG for Avahi */
2198
1829
  srand((unsigned int) time(NULL));
2199
 
  simple_poll = avahi_simple_poll_new();
2200
 
  if(simple_poll == NULL){
 
1830
  mc.simple_poll = avahi_simple_poll_new();
 
1831
  if(mc.simple_poll == NULL){
2201
1832
    fprintf_plus(stderr,
2202
1833
                 "Avahi: Failed to create simple poll object.\n");
2203
1834
    exitcode = EX_UNAVAILABLE;
2267
1898
    }
2268
1899
  }
2269
1900
  
2270
 
  /* If no interfaces were specified, make a list */
2271
 
  if(mc.interfaces == NULL){
2272
 
    struct dirent **direntries = NULL;
2273
 
    /* Look for any good interfaces */
2274
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2275
 
                  alphasort);
2276
 
    if(ret >= 1){
2277
 
      /* Add all found interfaces to interfaces list */
2278
 
      for(int i = 0; i < ret; ++i){
2279
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2280
 
                             direntries[i]->d_name);
2281
 
        if(ret_errno != 0){
2282
 
          errno = ret_errno;
2283
 
          perror_plus("argz_add");
2284
 
          free(direntries[i]);
2285
 
          continue;
2286
 
        }
2287
 
        if(debug){
2288
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2289
 
                       direntries[i]->d_name);
2290
 
        }
2291
 
        free(direntries[i]);
2292
 
      }
2293
 
      free(direntries);
2294
 
    } else {
2295
 
      if(ret == 0){
2296
 
        free(direntries);
2297
 
      }
2298
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2299
 
      exitcode = EXIT_FAILURE;
2300
 
      goto end;
2301
 
    }
2302
 
  }
2303
 
  
2304
 
  /* Bring up interfaces which are down, and remove any "none"s */
2305
 
  {
2306
 
    char *interface = NULL;
2307
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2308
 
                                 interface))){
2309
 
      /* If interface name is "none", stop bringing up interfaces.
2310
 
         Also remove all instances of "none" from the list */
2311
 
      if(strcmp(interface, "none") == 0){
2312
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2313
 
                    interface);
2314
 
        interface = NULL;
2315
 
        while((interface = argz_next(mc.interfaces,
2316
 
                                     mc.interfaces_size, interface))){
2317
 
          if(strcmp(interface, "none") == 0){
2318
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2319
 
                        interface);
2320
 
            interface = NULL;
 
1901
  /* If the interface is down, bring it up */
 
1902
  if(strcmp(interface, "none") != 0){
 
1903
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1904
    if(if_index == 0){
 
1905
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1906
      exitcode = EX_UNAVAILABLE;
 
1907
      goto end;
 
1908
    }
 
1909
    
 
1910
    if(quit_now){
 
1911
      goto end;
 
1912
    }
 
1913
    
 
1914
    /* Re-raise priviliges */
 
1915
    errno = 0;
 
1916
    ret = seteuid(0);
 
1917
    if(ret == -1){
 
1918
      perror_plus("seteuid");
 
1919
    }
 
1920
    
 
1921
#ifdef __linux__
 
1922
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1923
       messages about the network interface to mess up the prompt */
 
1924
    ret = klogctl(8, NULL, 5);
 
1925
    bool restore_loglevel = true;
 
1926
    if(ret == -1){
 
1927
      restore_loglevel = false;
 
1928
      perror_plus("klogctl");
 
1929
    }
 
1930
#endif  /* __linux__ */
 
1931
    
 
1932
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1933
    if(sd < 0){
 
1934
      perror_plus("socket");
 
1935
      exitcode = EX_OSERR;
 
1936
#ifdef __linux__
 
1937
      if(restore_loglevel){
 
1938
        ret = klogctl(7, NULL, 0);
 
1939
        if(ret == -1){
 
1940
          perror_plus("klogctl");
 
1941
        }
 
1942
      }
 
1943
#endif  /* __linux__ */
 
1944
      /* Lower privileges */
 
1945
      errno = 0;
 
1946
      ret = seteuid(uid);
 
1947
      if(ret == -1){
 
1948
        perror_plus("seteuid");
 
1949
      }
 
1950
      goto end;
 
1951
    }
 
1952
    strcpy(network.ifr_name, interface);
 
1953
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1954
    if(ret == -1){
 
1955
      perror_plus("ioctl SIOCGIFFLAGS");
 
1956
#ifdef __linux__
 
1957
      if(restore_loglevel){
 
1958
        ret = klogctl(7, NULL, 0);
 
1959
        if(ret == -1){
 
1960
          perror_plus("klogctl");
 
1961
        }
 
1962
      }
 
1963
#endif  /* __linux__ */
 
1964
      exitcode = EX_OSERR;
 
1965
      /* Lower privileges */
 
1966
      errno = 0;
 
1967
      ret = seteuid(uid);
 
1968
      if(ret == -1){
 
1969
        perror_plus("seteuid");
 
1970
      }
 
1971
      goto end;
 
1972
    }
 
1973
    if((network.ifr_flags & IFF_UP) == 0){
 
1974
      network.ifr_flags |= IFF_UP;
 
1975
      take_down_interface = true;
 
1976
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1977
      if(ret == -1){
 
1978
        take_down_interface = false;
 
1979
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1980
        exitcode = EX_OSERR;
 
1981
#ifdef __linux__
 
1982
        if(restore_loglevel){
 
1983
          ret = klogctl(7, NULL, 0);
 
1984
          if(ret == -1){
 
1985
            perror_plus("klogctl");
2321
1986
          }
2322
1987
        }
 
1988
#endif  /* __linux__ */
 
1989
        /* Lower privileges */
 
1990
        errno = 0;
 
1991
        ret = seteuid(uid);
 
1992
        if(ret == -1){
 
1993
          perror_plus("seteuid");
 
1994
        }
 
1995
        goto end;
 
1996
      }
 
1997
    }
 
1998
    /* Sleep checking until interface is running.
 
1999
       Check every 0.25s, up to total time of delay */
 
2000
    for(int i=0; i < delay * 4; i++){
 
2001
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2002
      if(ret == -1){
 
2003
        perror_plus("ioctl SIOCGIFFLAGS");
 
2004
      } else if(network.ifr_flags & IFF_RUNNING){
2323
2005
        break;
2324
2006
      }
2325
 
      bool interface_was_up = interface_is_up(interface);
2326
 
      errno = bring_up_interface(interface, delay);
2327
 
      if(not interface_was_up){
2328
 
        if(errno != 0){
2329
 
          perror_plus("Failed to bring up interface");
2330
 
        } else {
2331
 
          errno = argz_add(&interfaces_to_take_down,
2332
 
                           &interfaces_to_take_down_size,
2333
 
                           interface);
2334
 
          if(errno != 0){
2335
 
            perror_plus("argz_add");
2336
 
          }
2337
 
        }
2338
 
      }
2339
 
    }
2340
 
    if(debug and (interfaces_to_take_down == NULL)){
2341
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2342
 
    }
2343
 
  }
2344
 
  
2345
 
  /* If we only got one interface, explicitly use only that one */
2346
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2347
 
    if(debug){
2348
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2349
 
                   mc.interfaces);
2350
 
    }
2351
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
2007
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
2008
      ret = nanosleep(&sleeptime, NULL);
 
2009
      if(ret == -1 and errno != EINTR){
 
2010
        perror_plus("nanosleep");
 
2011
      }
 
2012
    }
 
2013
    if(not take_down_interface){
 
2014
      /* We won't need the socket anymore */
 
2015
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2016
      if(ret == -1){
 
2017
        perror_plus("close");
 
2018
      }
 
2019
    }
 
2020
#ifdef __linux__
 
2021
    if(restore_loglevel){
 
2022
      /* Restores kernel loglevel to default */
 
2023
      ret = klogctl(7, NULL, 0);
 
2024
      if(ret == -1){
 
2025
        perror_plus("klogctl");
 
2026
      }
 
2027
    }
 
2028
#endif  /* __linux__ */
 
2029
    /* Lower privileges */
 
2030
    errno = 0;
 
2031
    /* Lower privileges */
 
2032
    ret = seteuid(uid);
 
2033
    if(ret == -1){
 
2034
      perror_plus("seteuid");
 
2035
    }
2352
2036
  }
2353
2037
  
2354
2038
  if(quit_now){
2355
2039
    goto end;
2356
2040
  }
2357
2041
  
2358
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2042
  ret = init_gnutls_global(pubkey, seckey);
2359
2043
  if(ret == -1){
2360
2044
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2361
2045
    exitcode = EX_UNAVAILABLE;
2368
2052
    goto end;
2369
2053
  }
2370
2054
  
2371
 
  /* Try /run/tmp before /tmp */
2372
 
  tempdir = mkdtemp(run_tempdir);
2373
 
  if(tempdir == NULL and errno == ENOENT){
2374
 
      if(debug){
2375
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2376
 
                     run_tempdir, old_tempdir);
2377
 
      }
2378
 
      tempdir = mkdtemp(old_tempdir);
2379
 
  }
2380
 
  if(tempdir == NULL){
 
2055
  if(mkdtemp(tempdir) == NULL){
2381
2056
    perror_plus("mkdtemp");
2382
2057
    goto end;
2383
2058
  }
 
2059
  tempdir_created = true;
2384
2060
  
2385
2061
  if(quit_now){
2386
2062
    goto end;
2387
2063
  }
2388
2064
  
2389
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2065
  if(not init_gpgme(pubkey, seckey, tempdir)){
2390
2066
    fprintf_plus(stderr, "init_gpgme failed\n");
2391
2067
    exitcode = EX_UNAVAILABLE;
2392
2068
    goto end;
2402
2078
    /* Connect directly, do not use Zeroconf */
2403
2079
    /* (Mainly meant for debugging) */
2404
2080
    char *address = strrchr(connect_to, ':');
2405
 
    
2406
2081
    if(address == NULL){
2407
2082
      fprintf_plus(stderr, "No colon in address\n");
2408
2083
      exitcode = EX_USAGE;
2413
2088
      goto end;
2414
2089
    }
2415
2090
    
2416
 
    in_port_t port;
 
2091
    uint16_t port;
2417
2092
    errno = 0;
2418
2093
    tmpmax = strtoimax(address+1, &tmp, 10);
2419
2094
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2420
 
       or tmpmax != (in_port_t)tmpmax){
 
2095
       or tmpmax != (uint16_t)tmpmax){
2421
2096
      fprintf_plus(stderr, "Bad port number\n");
2422
2097
      exitcode = EX_USAGE;
2423
2098
      goto end;
2424
2099
    }
2425
 
    
 
2100
  
2426
2101
    if(quit_now){
2427
2102
      goto end;
2428
2103
    }
2429
2104
    
2430
 
    port = (in_port_t)tmpmax;
 
2105
    port = (uint16_t)tmpmax;
2431
2106
    *address = '\0';
2432
2107
    /* Colon in address indicates IPv6 */
2433
2108
    int af;
2449
2124
    }
2450
2125
    
2451
2126
    while(not quit_now){
2452
 
      ret = start_mandos_communication(address, port, if_index, af,
2453
 
                                       &mc);
 
2127
      ret = start_mandos_communication(address, port, if_index, af);
2454
2128
      if(quit_now or ret == 0){
2455
2129
        break;
2456
2130
      }
2458
2132
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2459
2133
                     (int)retry_interval);
2460
2134
      }
2461
 
      sleep((unsigned int)retry_interval);
 
2135
      sleep((int)retry_interval);
2462
2136
    }
2463
2137
    
2464
 
    if(not quit_now){
 
2138
    if (not quit_now){
2465
2139
      exitcode = EXIT_SUCCESS;
2466
2140
    }
2467
2141
    
2482
2156
    config.publish_domain = 0;
2483
2157
    
2484
2158
    /* Allocate a new server */
2485
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2486
 
                                 &config, NULL, NULL, &ret_errno);
 
2159
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2160
                                 (mc.simple_poll), &config, NULL,
 
2161
                                 NULL, &error);
2487
2162
    
2488
2163
    /* Free the Avahi configuration data */
2489
2164
    avahi_server_config_free(&config);
2492
2167
  /* Check if creating the Avahi server object succeeded */
2493
2168
  if(mc.server == NULL){
2494
2169
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2495
 
                 avahi_strerror(ret_errno));
 
2170
                 avahi_strerror(error));
2496
2171
    exitcode = EX_UNAVAILABLE;
2497
2172
    goto end;
2498
2173
  }
2504
2179
  /* Create the Avahi service browser */
2505
2180
  sb = avahi_s_service_browser_new(mc.server, if_index,
2506
2181
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2507
 
                                   NULL, 0, browse_callback,
2508
 
                                   (void *)&mc);
 
2182
                                   NULL, 0, browse_callback, NULL);
2509
2183
  if(sb == NULL){
2510
2184
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2511
2185
                 avahi_strerror(avahi_server_errno(mc.server)));
2522
2196
  if(debug){
2523
2197
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2524
2198
  }
2525
 
  
2526
 
  ret = avahi_loop_with_timeout(simple_poll,
2527
 
                                (int)(retry_interval * 1000), &mc);
 
2199
 
 
2200
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2201
                                (int)(retry_interval * 1000));
2528
2202
  if(debug){
2529
2203
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2530
2204
                 (ret == 0) ? "successfully" : "with error");
2537
2211
  }
2538
2212
  
2539
2213
  /* Cleanup things */
2540
 
  free(mc.interfaces);
2541
 
  
2542
2214
  if(sb != NULL)
2543
2215
    avahi_s_service_browser_free(sb);
2544
2216
  
2545
2217
  if(mc.server != NULL)
2546
2218
    avahi_server_free(mc.server);
2547
2219
  
2548
 
  if(simple_poll != NULL)
2549
 
    avahi_simple_poll_free(simple_poll);
 
2220
  if(mc.simple_poll != NULL)
 
2221
    avahi_simple_poll_free(mc.simple_poll);
2550
2222
  
2551
2223
  if(gnutls_initialized){
2552
2224
    gnutls_certificate_free_credentials(mc.cred);
2564
2236
    mc.current_server->prev->next = NULL;
2565
2237
    while(mc.current_server != NULL){
2566
2238
      server *next = mc.current_server->next;
2567
 
#ifdef __GNUC__
2568
 
#pragma GCC diagnostic push
2569
 
#pragma GCC diagnostic ignored "-Wcast-qual"
2570
 
#endif
2571
 
      free((char *)(mc.current_server->ip));
2572
 
#ifdef __GNUC__
2573
 
#pragma GCC diagnostic pop
2574
 
#endif
2575
2239
      free(mc.current_server);
2576
2240
      mc.current_server = next;
2577
2241
    }
2578
2242
  }
2579
2243
  
2580
 
  /* Re-raise privileges */
 
2244
  /* Run network hooks */
 
2245
  run_network_hooks("stop", interface, delay);
 
2246
  
 
2247
  /* Re-raise priviliges */
2581
2248
  {
2582
 
    ret_errno = raise_privileges();
2583
 
    if(ret_errno != 0){
2584
 
      errno = ret_errno;
2585
 
      perror_plus("Failed to raise privileges");
2586
 
    } else {
2587
 
      
2588
 
      /* Run network hooks */
2589
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2590
 
                        interfaces_hooks : "", delay);
2591
 
      
2592
 
      /* Take down the network interfaces which were brought up */
2593
 
      {
2594
 
        char *interface = NULL;
2595
 
        while((interface=argz_next(interfaces_to_take_down,
2596
 
                                   interfaces_to_take_down_size,
2597
 
                                   interface))){
2598
 
          ret_errno = take_down_interface(interface);
2599
 
          if(ret_errno != 0){
2600
 
            errno = ret_errno;
2601
 
            perror_plus("Failed to take down interface");
2602
 
          }
2603
 
        }
2604
 
        if(debug and (interfaces_to_take_down == NULL)){
2605
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2606
 
                       " down\n");
2607
 
        }
2608
 
      }
 
2249
    errno = 0;
 
2250
    ret = seteuid(0);
 
2251
    if(ret == -1){
 
2252
      perror_plus("seteuid");
2609
2253
    }
2610
2254
    
2611
 
    ret_errno = lower_privileges_permanently();
2612
 
    if(ret_errno != 0){
2613
 
      errno = ret_errno;
2614
 
      perror_plus("Failed to lower privileges permanently");
 
2255
    /* Take down the network interface */
 
2256
    if(take_down_interface and geteuid() == 0){
 
2257
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2258
      if(ret == -1){
 
2259
        perror_plus("ioctl SIOCGIFFLAGS");
 
2260
      } else if(network.ifr_flags & IFF_UP){
 
2261
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2262
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2263
        if(ret == -1){
 
2264
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2265
        }
 
2266
      }
 
2267
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2268
      if(ret == -1){
 
2269
        perror_plus("close");
 
2270
      }
2615
2271
    }
2616
2272
  }
2617
 
  
2618
 
  free(interfaces_to_take_down);
2619
 
  free(interfaces_hooks);
 
2273
  /* Lower privileges permanently */
 
2274
  errno = 0;
 
2275
  ret = setuid(uid);
 
2276
  if(ret == -1){
 
2277
    perror_plus("setuid");
 
2278
  }
2620
2279
  
2621
2280
  /* Removes the GPGME temp directory and all files inside */
2622
 
  if(tempdir != NULL){
 
2281
  if(tempdir_created){
2623
2282
    struct dirent **direntries = NULL;
2624
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2625
 
                                                  O_NOFOLLOW));
2626
 
    if(tempdir_fd == -1){
2627
 
      perror_plus("open");
2628
 
    } else {
2629
 
#ifdef __GLIBC__
2630
 
#if __GLIBC_PREREQ(2, 15)
2631
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2632
 
                                 notdotentries, alphasort);
2633
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2634
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2635
 
                               alphasort);
2636
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2637
 
#else   /* not __GLIBC__ */
2638
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2639
 
                               alphasort);
2640
 
#endif  /* not __GLIBC__ */
2641
 
      if(numentries >= 0){
2642
 
        for(int i = 0; i < numentries; i++){
2643
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2644
 
          if(ret == -1){
2645
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2646
 
                         " \"%s\", 0): %s\n", tempdir,
2647
 
                         direntries[i]->d_name, strerror(errno));
2648
 
          }
2649
 
          free(direntries[i]);
2650
 
        }
2651
 
        
2652
 
        /* need to clean even if 0 because man page doesn't specify */
2653
 
        free(direntries);
2654
 
        if(numentries == -1){
2655
 
          perror_plus("scandir");
2656
 
        }
2657
 
        ret = rmdir(tempdir);
2658
 
        if(ret == -1 and errno != ENOENT){
2659
 
          perror_plus("rmdir");
2660
 
        }
 
2283
    struct dirent *direntry = NULL;
 
2284
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2285
                             alphasort);
 
2286
    if (numentries > 0){
 
2287
      for(int i = 0; i < numentries; i++){
 
2288
        direntry = direntries[i];
 
2289
        char *fullname = NULL;
 
2290
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2291
                       direntry->d_name);
 
2292
        if(ret < 0){
 
2293
          perror_plus("asprintf");
 
2294
          continue;
 
2295
        }
 
2296
        ret = remove(fullname);
 
2297
        if(ret == -1){
 
2298
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2299
                       strerror(errno));
 
2300
        }
 
2301
        free(fullname);
2661
2302
      }
2662
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2303
    }
 
2304
 
 
2305
    /* need to clean even if 0 because man page doesn't specify */
 
2306
    free(direntries);
 
2307
    if (numentries == -1){
 
2308
      perror_plus("scandir");
 
2309
    }
 
2310
    ret = rmdir(tempdir);
 
2311
    if(ret == -1 and errno != ENOENT){
 
2312
      perror_plus("rmdir");
2663
2313
    }
2664
2314
  }
2665
2315