/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-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 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
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() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
43
                                   stdout, ferror(), remove() */
 
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() */
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;
178
170
 
179
171
/* Function to use when printing errors */
180
172
void perror_plus(const char *print_text){
181
 
  int e = errno;
182
173
  fprintf(stderr, "Mandos plugin %s: ",
183
174
          program_invocation_short_name);
184
 
  errno = e;
185
175
  perror(print_text);
186
176
}
187
177
 
188
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
189
178
int fprintf_plus(FILE *stream, const char *format, ...){
190
179
  va_list ap;
191
180
  va_start (ap, format);
192
181
  
193
182
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
194
183
                             program_invocation_short_name));
195
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
184
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
196
185
}
197
186
 
198
187
/*
200
189
 * bytes. "buffer_capacity" is how much is currently allocated,
201
190
 * "buffer_length" is how much is already used.
202
191
 */
203
 
__attribute__((nonnull, warn_unused_result))
204
192
size_t incbuffer(char **buffer, size_t buffer_length,
205
193
                 size_t buffer_capacity){
206
194
  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;
 
195
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
196
    if(buffer == NULL){
213
197
      return 0;
214
198
    }
215
 
    *buffer = new_buf;
216
199
    buffer_capacity += BUFFER_SIZE;
217
200
  }
218
201
  return buffer_capacity;
219
202
}
220
203
 
221
204
/* 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){
 
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
206
               int af){
225
207
  int ret;
226
208
  server *new_server = malloc(sizeof(server));
227
209
  if(new_server == NULL){
228
210
    perror_plus("malloc");
229
 
    return false;
 
211
    return -1;
230
212
  }
231
213
  *new_server = (server){ .ip = strdup(ip),
232
214
                          .port = port,
234
216
                          .af = af };
235
217
  if(new_server->ip == NULL){
236
218
    perror_plus("strdup");
237
 
    return false;
238
 
  }
239
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
240
 
  if(ret == -1){
241
 
    perror_plus("clock_gettime");
242
 
    return false;
 
219
    return -1;
243
220
  }
244
221
  /* Special case of first server */
245
 
  if(*current_server == NULL){
 
222
  if (mc.current_server == NULL){
246
223
    new_server->next = new_server;
247
224
    new_server->prev = new_server;
248
 
    *current_server = new_server;
 
225
    mc.current_server = new_server;
 
226
  /* Place the new server last in the list */
249
227
  } else {
250
 
    /* Place the new server last in the list */
251
 
    new_server->next = *current_server;
252
 
    new_server->prev = (*current_server)->prev;
 
228
    new_server->next = mc.current_server;
 
229
    new_server->prev = mc.current_server->prev;
253
230
    new_server->prev->next = new_server;
254
 
    (*current_server)->prev = new_server;
255
 
  }
256
 
  return true;
 
231
    mc.current_server->prev = new_server;
 
232
  }
 
233
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
234
  if(ret == -1){
 
235
    perror_plus("clock_gettime");
 
236
    return -1;
 
237
  }
 
238
  return 0;
257
239
}
258
240
 
259
241
/* 
260
242
 * Initialize GPGME.
261
243
 */
262
 
__attribute__((nonnull, warn_unused_result))
263
 
static bool init_gpgme(const char * const seckey,
264
 
                       const char * const pubkey,
265
 
                       const char * const tempdir,
266
 
                       mandos_context *mc){
 
244
static bool init_gpgme(const char *seckey, const char *pubkey,
 
245
                       const char *tempdir){
267
246
  gpgme_error_t rc;
268
247
  gpgme_engine_info_t engine_info;
269
248
  
 
249
  
270
250
  /*
271
251
   * Helper function to insert pub and seckey to the engine keyring.
272
252
   */
273
 
  bool import_key(const char * const filename){
 
253
  bool import_key(const char *filename){
274
254
    int ret;
275
255
    int fd;
276
256
    gpgme_data_t pgp_data;
288
268
      return false;
289
269
    }
290
270
    
291
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
271
    rc = gpgme_op_import(mc.ctx, pgp_data);
292
272
    if(rc != GPG_ERR_NO_ERROR){
293
273
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
294
274
                   gpgme_strsource(rc), gpgme_strerror(rc));
338
318
  }
339
319
  
340
320
  /* Create new GPGME "context" */
341
 
  rc = gpgme_new(&(mc->ctx));
 
321
  rc = gpgme_new(&(mc.ctx));
342
322
  if(rc != GPG_ERR_NO_ERROR){
343
323
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
344
324
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
357
337
 * Decrypt OpenPGP data.
358
338
 * Returns -1 on error
359
339
 */
360
 
__attribute__((nonnull, warn_unused_result))
361
340
static ssize_t pgp_packet_decrypt(const char *cryptotext,
362
341
                                  size_t crypto_size,
363
 
                                  char **plaintext,
364
 
                                  mandos_context *mc){
 
342
                                  char **plaintext){
365
343
  gpgme_data_t dh_crypto, dh_plain;
366
344
  gpgme_error_t rc;
367
345
  ssize_t ret;
393
371
  
394
372
  /* Decrypt data from the cryptotext data buffer to the plaintext
395
373
     data buffer */
396
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
374
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
397
375
  if(rc != GPG_ERR_NO_ERROR){
398
376
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
399
377
                 gpgme_strsource(rc), gpgme_strerror(rc));
400
378
    plaintext_length = -1;
401
379
    if(debug){
402
380
      gpgme_decrypt_result_t result;
403
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
381
      result = gpgme_op_decrypt_result(mc.ctx);
404
382
      if(result == NULL){
405
383
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
406
384
      } else {
483
461
  return plaintext_length;
484
462
}
485
463
 
486
 
__attribute__((warn_unused_result))
487
 
static const char *safer_gnutls_strerror(int value){
488
 
  const char *ret = gnutls_strerror(value);
 
464
static const char * safer_gnutls_strerror(int value){
 
465
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
466
                                               -Wunreachable-code */
489
467
  if(ret == NULL)
490
468
    ret = "(unknown)";
491
469
  return ret;
492
470
}
493
471
 
494
472
/* GnuTLS log function callback */
495
 
__attribute__((nonnull))
496
473
static void debuggnutls(__attribute__((unused)) int level,
497
474
                        const char* string){
498
475
  fprintf_plus(stderr, "GnuTLS: %s", string);
499
476
}
500
477
 
501
 
__attribute__((nonnull, warn_unused_result))
502
478
static int init_gnutls_global(const char *pubkeyfilename,
503
 
                              const char *seckeyfilename,
504
 
                              mandos_context *mc){
 
479
                              const char *seckeyfilename){
505
480
  int ret;
506
481
  
507
482
  if(debug){
524
499
  }
525
500
  
526
501
  /* OpenPGP credentials */
527
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
502
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
528
503
  if(ret != GNUTLS_E_SUCCESS){
529
504
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
530
505
                 safer_gnutls_strerror(ret));
540
515
  }
541
516
  
542
517
  ret = gnutls_certificate_set_openpgp_key_file
543
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
518
    (mc.cred, pubkeyfilename, seckeyfilename,
544
519
     GNUTLS_OPENPGP_FMT_BASE64);
545
520
  if(ret != GNUTLS_E_SUCCESS){
546
521
    fprintf_plus(stderr,
552
527
  }
553
528
  
554
529
  /* GnuTLS server initialization */
555
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
530
  ret = gnutls_dh_params_init(&mc.dh_params);
556
531
  if(ret != GNUTLS_E_SUCCESS){
557
532
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
558
533
                 " initialization: %s\n",
559
534
                 safer_gnutls_strerror(ret));
560
535
    goto globalfail;
561
536
  }
562
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
537
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
563
538
  if(ret != GNUTLS_E_SUCCESS){
564
539
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
565
540
                 safer_gnutls_strerror(ret));
566
541
    goto globalfail;
567
542
  }
568
543
  
569
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
544
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
570
545
  
571
546
  return 0;
572
547
  
573
548
 globalfail:
574
549
  
575
 
  gnutls_certificate_free_credentials(mc->cred);
 
550
  gnutls_certificate_free_credentials(mc.cred);
576
551
  gnutls_global_deinit();
577
 
  gnutls_dh_params_deinit(mc->dh_params);
 
552
  gnutls_dh_params_deinit(mc.dh_params);
578
553
  return -1;
579
554
}
580
555
 
581
 
__attribute__((nonnull, warn_unused_result))
582
 
static int init_gnutls_session(gnutls_session_t *session,
583
 
                               mandos_context *mc){
 
556
static int init_gnutls_session(gnutls_session_t *session){
584
557
  int ret;
585
558
  /* GnuTLS session creation */
586
559
  do {
598
571
  {
599
572
    const char *err;
600
573
    do {
601
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
574
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
602
575
      if(quit_now){
603
576
        gnutls_deinit(*session);
604
577
        return -1;
615
588
  
616
589
  do {
617
590
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
618
 
                                 mc->cred);
 
591
                                 mc.cred);
619
592
    if(quit_now){
620
593
      gnutls_deinit(*session);
621
594
      return -1;
631
604
  /* ignore client certificate if any. */
632
605
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
633
606
  
634
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
607
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
635
608
  
636
609
  return 0;
637
610
}
641
614
                      __attribute__((unused)) const char *txt){}
642
615
 
643
616
/* Called when a Mandos server is found */
644
 
__attribute__((nonnull, warn_unused_result))
645
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
617
static int start_mandos_communication(const char *ip, uint16_t port,
646
618
                                      AvahiIfIndex if_index,
647
 
                                      int af, mandos_context *mc){
 
619
                                      int af){
648
620
  int ret, tcp_sd = -1;
649
621
  ssize_t sret;
650
 
  struct sockaddr_storage to;
 
622
  union {
 
623
    struct sockaddr_in in;
 
624
    struct sockaddr_in6 in6;
 
625
  } to;
651
626
  char *buffer = NULL;
652
627
  char *decrypted_buffer = NULL;
653
628
  size_t buffer_length = 0;
677
652
    return -1;
678
653
  }
679
654
  
680
 
  /* If the interface is specified and we have a list of interfaces */
681
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
682
 
    /* Check if the interface is one of the interfaces we are using */
683
 
    bool match = false;
684
 
    {
685
 
      char *interface = NULL;
686
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
687
 
                                 interface))){
688
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
689
 
          match = true;
690
 
          break;
691
 
        }
692
 
      }
693
 
    }
694
 
    if(not match){
695
 
      /* This interface does not match any in the list, so we don't
696
 
         connect to the server */
697
 
      if(debug){
698
 
        char interface[IF_NAMESIZE];
699
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
700
 
          perror_plus("if_indextoname");
701
 
        } else {
702
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
703
 
                       " \"%s\"\n",
704
 
                       if_indextoname((unsigned int)if_index,
705
 
                                      interface));
706
 
        }
707
 
      }
708
 
      return -1;
709
 
    }
710
 
  }
711
 
  
712
 
  ret = init_gnutls_session(&session, mc);
 
655
  ret = init_gnutls_session(&session);
713
656
  if(ret != 0){
714
657
    return -1;
715
658
  }
716
659
  
717
660
  if(debug){
718
661
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
719
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
662
                 PRIu16 "\n", ip, port);
720
663
  }
721
664
  
722
665
  tcp_sd = socket(pf, SOCK_STREAM, 0);
734
677
  
735
678
  memset(&to, 0, sizeof(to));
736
679
  if(af == AF_INET6){
737
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
738
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
680
    to.in6.sin6_family = (sa_family_t)af;
 
681
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
739
682
  } else {                      /* IPv4 */
740
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
741
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
683
    to.in.sin_family = (sa_family_t)af;
 
684
    ret = inet_pton(af, ip, &to.in.sin_addr);
742
685
  }
743
686
  if(ret < 0 ){
744
687
    int e = errno;
753
696
    goto mandos_end;
754
697
  }
755
698
  if(af == AF_INET6){
756
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
757
 
    if(IN6_IS_ADDR_LINKLOCAL
758
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
699
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
700
                                       -Wconversion and
 
701
                                       -Wunreachable-code */
 
702
    
 
703
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
704
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
705
                                -Wunreachable-code*/
759
706
      if(if_index == AVAHI_IF_UNSPEC){
760
707
        fprintf_plus(stderr, "An IPv6 link-local address is"
761
708
                     " incomplete without a network interface\n");
763
710
        goto mandos_end;
764
711
      }
765
712
      /* Set the network interface number as scope */
766
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
713
      to.in6.sin6_scope_id = (uint32_t)if_index;
767
714
    }
768
715
  } else {
769
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
716
    to.in.sin_port = htons(port); /* Spurious warnings from
 
717
                                     -Wconversion and
 
718
                                     -Wunreachable-code */
770
719
  }
771
720
  
772
721
  if(quit_now){
780
729
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
781
730
        perror_plus("if_indextoname");
782
731
      } else {
783
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
784
 
                     "\n", ip, interface, (uintmax_t)port);
 
732
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
733
                     "\n", ip, interface, port);
785
734
      }
786
735
    } else {
787
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
788
 
                   ip, (uintmax_t)port);
 
736
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
737
                   ip, port);
789
738
    }
790
739
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
791
740
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
741
    const char *pcret;
792
742
    if(af == AF_INET6){
793
 
      ret = getnameinfo((struct sockaddr *)&to,
794
 
                        sizeof(struct sockaddr_in6),
795
 
                        addrstr, sizeof(addrstr), NULL, 0,
796
 
                        NI_NUMERICHOST);
 
743
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
744
                        sizeof(addrstr));
797
745
    } else {
798
 
      ret = getnameinfo((struct sockaddr *)&to,
799
 
                        sizeof(struct sockaddr_in),
800
 
                        addrstr, sizeof(addrstr), NULL, 0,
801
 
                        NI_NUMERICHOST);
 
746
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
747
                        sizeof(addrstr));
802
748
    }
803
 
    if(ret == EAI_SYSTEM){
804
 
      perror_plus("getnameinfo");
805
 
    } else if(ret != 0) {
806
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
807
 
    } else if(strcmp(addrstr, ip) != 0){
808
 
      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
      }
809
755
    }
810
756
  }
811
757
  
815
761
  }
816
762
  
817
763
  if(af == AF_INET6){
818
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
819
 
                  sizeof(struct sockaddr_in6));
 
764
    ret = connect(tcp_sd, &to.in6, sizeof(to));
820
765
  } else {
821
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
822
 
                  sizeof(struct sockaddr_in));
 
766
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
823
767
  }
824
768
  if(ret < 0){
825
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
769
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
826
770
      int e = errno;
827
771
      perror_plus("connect");
828
772
      errno = e;
874
818
    goto mandos_end;
875
819
  }
876
820
  
877
 
  /* This casting via intptr_t is to eliminate warning about casting
878
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
879
 
     function "set-session-transport-fd!" does it. */
880
 
  gnutls_transport_set_ptr(session,
881
 
                           (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);
882
823
  
883
824
  if(quit_now){
884
825
    errno = EINTR;
989
930
  if(buffer_length > 0){
990
931
    ssize_t decrypted_buffer_size;
991
932
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
992
 
                                               &decrypted_buffer, mc);
 
933
                                               &decrypted_buffer);
993
934
    if(decrypted_buffer_size >= 0){
994
935
      
995
936
      written = 0;
1043
984
  return retval;
1044
985
}
1045
986
 
1046
 
__attribute__((nonnull))
1047
987
static void resolve_callback(AvahiSServiceResolver *r,
1048
988
                             AvahiIfIndex interface,
1049
989
                             AvahiProtocol proto,
1057
997
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1058
998
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1059
999
                             flags,
1060
 
                             void *mc){
1061
 
  if(r == NULL){
1062
 
    return;
1063
 
  }
 
1000
                             AVAHI_GCC_UNUSED void* userdata){
 
1001
  assert(r);
1064
1002
  
1065
1003
  /* Called whenever a service has been resolved successfully or
1066
1004
     timed out */
1075
1013
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1076
1014
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1077
1015
                 domain,
1078
 
                 avahi_strerror(avahi_server_errno
1079
 
                                (((mandos_context*)mc)->server)));
 
1016
                 avahi_strerror(avahi_server_errno(mc.server)));
1080
1017
    break;
1081
1018
    
1082
1019
  case AVAHI_RESOLVER_FOUND:
1088
1025
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1089
1026
                     host_name, ip, (intmax_t)interface, port);
1090
1027
      }
1091
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1092
 
                                           interface,
1093
 
                                           avahi_proto_to_af(proto),
1094
 
                                           mc);
 
1028
      int ret = start_mandos_communication(ip, port, interface,
 
1029
                                           avahi_proto_to_af(proto));
1095
1030
      if(ret == 0){
1096
 
        avahi_simple_poll_quit(simple_poll);
 
1031
        avahi_simple_poll_quit(mc.simple_poll);
1097
1032
      } else {
1098
 
        if(not add_server(ip, (in_port_t)port, interface,
1099
 
                          avahi_proto_to_af(proto),
1100
 
                          &((mandos_context*)mc)->current_server)){
1101
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1102
 
                       " list\n", name);
1103
 
        }
 
1033
        ret = add_server(ip, port, interface,
 
1034
                         avahi_proto_to_af(proto));
1104
1035
      }
1105
1036
    }
1106
1037
  }
1116
1047
                            const char *domain,
1117
1048
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1118
1049
                            flags,
1119
 
                            void *mc){
1120
 
  if(b == NULL){
1121
 
    return;
1122
 
  }
 
1050
                            AVAHI_GCC_UNUSED void* userdata){
 
1051
  assert(b);
1123
1052
  
1124
1053
  /* Called whenever a new services becomes available on the LAN or
1125
1054
     is removed from the LAN */
1133
1062
  case AVAHI_BROWSER_FAILURE:
1134
1063
    
1135
1064
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1136
 
                 avahi_strerror(avahi_server_errno
1137
 
                                (((mandos_context*)mc)->server)));
1138
 
    avahi_simple_poll_quit(simple_poll);
 
1065
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1066
    avahi_simple_poll_quit(mc.simple_poll);
1139
1067
    return;
1140
1068
    
1141
1069
  case AVAHI_BROWSER_NEW:
1144
1072
       the callback function is called the Avahi server will free the
1145
1073
       resolver for us. */
1146
1074
    
1147
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1148
 
                                    interface, protocol, name, type,
1149
 
                                    domain, protocol, 0,
1150
 
                                    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)
1151
1078
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1152
1079
                   " %s\n", name,
1153
 
                   avahi_strerror(avahi_server_errno
1154
 
                                  (((mandos_context*)mc)->server)));
 
1080
                   avahi_strerror(avahi_server_errno(mc.server)));
1155
1081
    break;
1156
1082
    
1157
1083
  case AVAHI_BROWSER_REMOVE:
1176
1102
  signal_received = sig;
1177
1103
  int old_errno = errno;
1178
1104
  /* set main loop to exit */
1179
 
  if(simple_poll != NULL){
1180
 
    avahi_simple_poll_quit(simple_poll);
 
1105
  if(mc.simple_poll != NULL){
 
1106
    avahi_simple_poll_quit(mc.simple_poll);
1181
1107
  }
1182
1108
  errno = old_errno;
1183
1109
}
1184
1110
 
1185
 
__attribute__((nonnull, warn_unused_result))
1186
1111
bool get_flags(const char *ifname, struct ifreq *ifr){
1187
1112
  int ret;
1188
 
  error_t ret_errno;
1189
1113
  
1190
1114
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1191
1115
  if(s < 0){
1192
 
    ret_errno = errno;
1193
1116
    perror_plus("socket");
1194
 
    errno = ret_errno;
1195
1117
    return false;
1196
1118
  }
1197
1119
  strcpy(ifr->ifr_name, ifname);
1198
1120
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1199
1121
  if(ret == -1){
1200
1122
    if(debug){
1201
 
      ret_errno = errno;
1202
1123
      perror_plus("ioctl SIOCGIFFLAGS");
1203
 
      errno = ret_errno;
1204
1124
    }
1205
1125
    return false;
1206
1126
  }
1207
1127
  return true;
1208
1128
}
1209
1129
 
1210
 
__attribute__((nonnull, warn_unused_result))
1211
1130
bool good_flags(const char *ifname, const struct ifreq *ifr){
1212
1131
  
1213
1132
  /* Reject the loopback device */
1255
1174
 * corresponds to an acceptable network device.
1256
1175
 * (This function is passed to scandir(3) as a filter function.)
1257
1176
 */
1258
 
__attribute__((nonnull, warn_unused_result))
1259
1177
int good_interface(const struct dirent *if_entry){
1260
1178
  if(if_entry->d_name[0] == '.'){
1261
1179
    return 0;
1277
1195
}
1278
1196
 
1279
1197
/* 
1280
 
 * This function determines if a network interface is up.
1281
 
 */
1282
 
__attribute__((nonnull, warn_unused_result))
1283
 
bool interface_is_up(const char *interface){
1284
 
  struct ifreq ifr;
1285
 
  if(not get_flags(interface, &ifr)){
1286
 
    if(debug){
1287
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1288
 
                   "\"%s\"\n", interface);
1289
 
    }
1290
 
    return false;
1291
 
  }
1292
 
  
1293
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1294
 
}
1295
 
 
1296
 
/* 
1297
 
 * This function determines if a network interface is running
1298
 
 */
1299
 
__attribute__((nonnull, warn_unused_result))
1300
 
bool interface_is_running(const char *interface){
1301
 
  struct ifreq ifr;
1302
 
  if(not get_flags(interface, &ifr)){
1303
 
    if(debug){
1304
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1305
 
                   "\"%s\"\n", interface);
1306
 
    }
1307
 
    return false;
1308
 
  }
1309
 
  
1310
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1311
 
}
1312
 
 
1313
 
__attribute__((nonnull, pure, warn_unused_result))
 
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;
 
1238
}
 
1239
 
1314
1240
int notdotentries(const struct dirent *direntry){
1315
1241
  /* Skip "." and ".." */
1316
1242
  if(direntry->d_name[0] == '.'
1323
1249
}
1324
1250
 
1325
1251
/* Is this directory entry a runnable program? */
1326
 
__attribute__((nonnull, warn_unused_result))
1327
1252
int runnable_hook(const struct dirent *direntry){
1328
1253
  int ret;
1329
1254
  size_t sret;
1337
1262
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1338
1263
                "abcdefghijklmnopqrstuvwxyz"
1339
1264
                "0123456789"
1340
 
                "_.-");
 
1265
                "_-");
1341
1266
  if((direntry->d_name)[sret] != '\0'){
1342
1267
    /* Contains non-allowed characters */
1343
1268
    if(debug){
1347
1272
    return 0;
1348
1273
  }
1349
1274
  
1350
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1275
  char *fullname = NULL;
 
1276
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1277
  if(ret < 0){
 
1278
    perror_plus("asprintf");
 
1279
    return 0;
 
1280
  }
 
1281
  
 
1282
  ret = stat(fullname, &st);
1351
1283
  if(ret == -1){
1352
1284
    if(debug){
1353
1285
      perror_plus("Could not stat hook");
1377
1309
  return 1;
1378
1310
}
1379
1311
 
1380
 
__attribute__((nonnull, warn_unused_result))
1381
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1382
 
                            mandos_context *mc){
 
1312
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1383
1313
  int ret;
1384
1314
  struct timespec now;
1385
1315
  struct timespec waited_time;
1386
1316
  intmax_t block_time;
1387
1317
  
1388
1318
  while(true){
1389
 
    if(mc->current_server == NULL){
1390
 
      if(debug){
 
1319
    if(mc.current_server == NULL){
 
1320
      if (debug){
1391
1321
        fprintf_plus(stderr, "Wait until first server is found."
1392
1322
                     " No timeout!\n");
1393
1323
      }
1394
1324
      ret = avahi_simple_poll_iterate(s, -1);
1395
1325
    } else {
1396
 
      if(debug){
 
1326
      if (debug){
1397
1327
        fprintf_plus(stderr, "Check current_server if we should run"
1398
1328
                     " it, or wait\n");
1399
1329
      }
1406
1336
      /* Calculating in ms how long time between now and server
1407
1337
         who we visted longest time ago. Now - last seen.  */
1408
1338
      waited_time.tv_sec = (now.tv_sec
1409
 
                            - mc->current_server->last_seen.tv_sec);
 
1339
                            - mc.current_server->last_seen.tv_sec);
1410
1340
      waited_time.tv_nsec = (now.tv_nsec
1411
 
                             - mc->current_server->last_seen.tv_nsec);
 
1341
                             - mc.current_server->last_seen.tv_nsec);
1412
1342
      /* total time is 10s/10,000ms.
1413
1343
         Converting to s from ms by dividing by 1,000,
1414
1344
         and ns to ms by dividing by 1,000,000. */
1416
1346
                     - ((intmax_t)waited_time.tv_sec * 1000))
1417
1347
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1418
1348
      
1419
 
      if(debug){
 
1349
      if (debug){
1420
1350
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1421
1351
                     block_time);
1422
1352
      }
1423
1353
      
1424
1354
      if(block_time <= 0){
1425
 
        ret = start_mandos_communication(mc->current_server->ip,
1426
 
                                         mc->current_server->port,
1427
 
                                         mc->current_server->if_index,
1428
 
                                         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);
1429
1359
        if(ret == 0){
1430
 
          avahi_simple_poll_quit(s);
 
1360
          avahi_simple_poll_quit(mc.simple_poll);
1431
1361
          return 0;
1432
1362
        }
1433
1363
        ret = clock_gettime(CLOCK_MONOTONIC,
1434
 
                            &mc->current_server->last_seen);
 
1364
                            &mc.current_server->last_seen);
1435
1365
        if(ret == -1){
1436
1366
          perror_plus("clock_gettime");
1437
1367
          return -1;
1438
1368
        }
1439
 
        mc->current_server = mc->current_server->next;
 
1369
        mc.current_server = mc.current_server->next;
1440
1370
        block_time = 0;         /* Call avahi to find new Mandos
1441
1371
                                   servers, but don't block */
1442
1372
      }
1444
1374
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1445
1375
    }
1446
1376
    if(ret != 0){
1447
 
      if(ret > 0 or errno != EINTR){
 
1377
      if (ret > 0 or errno != EINTR){
1448
1378
        return (ret != 1) ? ret : 0;
1449
1379
      }
1450
1380
    }
1451
1381
  }
1452
1382
}
1453
1383
 
1454
 
/* Set effective uid to 0, return errno */
1455
 
__attribute__((warn_unused_result))
1456
 
error_t raise_privileges(void){
1457
 
  error_t old_errno = errno;
1458
 
  error_t ret_errno = 0;
1459
 
  if(seteuid(0) == -1){
1460
 
    ret_errno = errno;
1461
 
    perror_plus("seteuid");
1462
 
  }
1463
 
  errno = old_errno;
1464
 
  return ret_errno;
1465
 
}
1466
 
 
1467
 
/* Set effective and real user ID to 0.  Return errno. */
1468
 
__attribute__((warn_unused_result))
1469
 
error_t raise_privileges_permanently(void){
1470
 
  error_t old_errno = errno;
1471
 
  error_t ret_errno = raise_privileges();
1472
 
  if(ret_errno != 0){
1473
 
    errno = old_errno;
1474
 
    return ret_errno;
1475
 
  }
1476
 
  if(setuid(0) == -1){
1477
 
    ret_errno = errno;
1478
 
    perror_plus("seteuid");
1479
 
  }
1480
 
  errno = old_errno;
1481
 
  return ret_errno;
1482
 
}
1483
 
 
1484
 
/* Set effective user ID to unprivileged saved user ID */
1485
 
__attribute__((warn_unused_result))
1486
 
error_t lower_privileges(void){
1487
 
  error_t old_errno = errno;
1488
 
  error_t ret_errno = 0;
1489
 
  if(seteuid(uid) == -1){
1490
 
    ret_errno = errno;
1491
 
    perror_plus("seteuid");
1492
 
  }
1493
 
  errno = old_errno;
1494
 
  return ret_errno;
1495
 
}
1496
 
 
1497
 
/* Lower privileges permanently */
1498
 
__attribute__((warn_unused_result))
1499
 
error_t lower_privileges_permanently(void){
1500
 
  error_t old_errno = errno;
1501
 
  error_t ret_errno = 0;
1502
 
  if(setuid(uid) == -1){
1503
 
    ret_errno = errno;
1504
 
    perror_plus("setuid");
1505
 
  }
1506
 
  errno = old_errno;
1507
 
  return ret_errno;
1508
 
}
1509
 
 
1510
 
#ifndef O_CLOEXEC
1511
 
/*
1512
 
 * Based on the example in the GNU LibC manual chapter 13.13 "File
1513
 
 * Descriptor Flags".
1514
 
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
1515
 
 */
1516
 
__attribute__((warn_unused_result))
1517
 
static int set_cloexec_flag(int fd){
1518
 
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
1519
 
  /* If reading the flags failed, return error indication now. */
1520
 
  if(ret < 0){
1521
 
    return ret;
1522
 
  }
1523
 
  /* Store modified flag word in the descriptor. */
1524
 
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
1525
 
                                       ret | FD_CLOEXEC));
1526
 
}
1527
 
#endif  /* not O_CLOEXEC */
1528
 
 
1529
 
__attribute__((nonnull))
1530
 
void run_network_hooks(const char *mode, const char *interface,
 
1384
bool run_network_hooks(const char *mode, const char *interface,
1531
1385
                       const float delay){
1532
1386
  struct dirent **direntries;
1533
 
  if(hookdir_fd == -1){
1534
 
    hookdir_fd = open(hookdir, O_RDONLY |
1535
 
#ifdef O_CLOEXEC
1536
 
                      O_CLOEXEC
1537
 
#else  /* not O_CLOEXEC */
1538
 
                      0
1539
 
#endif  /* not O_CLOEXEC */
1540
 
                      );
1541
 
    if(hookdir_fd == -1){
1542
 
      if(errno == ENOENT){
1543
 
        if(debug){
1544
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1545
 
                       " found\n", hookdir);
1546
 
        }
1547
 
      } else {
1548
 
        perror_plus("open");
1549
 
      }
1550
 
      return;
1551
 
    }
1552
 
#ifndef O_CLOEXEC
1553
 
    if(set_cloexec_flag(hookdir_fd) < 0){
1554
 
      perror_plus("set_cloexec_flag");
1555
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1556
 
        perror_plus("close");
1557
 
      } else {
1558
 
        hookdir_fd = -1;
1559
 
      }
1560
 
      return;
1561
 
    }
1562
 
#endif  /* not O_CLOEXEC */
1563
 
  }
1564
 
#ifdef __GLIBC__
1565
 
#if __GLIBC_PREREQ(2, 15)
1566
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1567
 
                           runnable_hook, alphasort);
1568
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1569
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1570
 
                         alphasort);
1571
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1572
 
#else   /* not __GLIBC__ */
1573
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1574
 
                         alphasort);
1575
 
#endif  /* not __GLIBC__ */
 
1387
  struct dirent *direntry;
 
1388
  int ret;
 
1389
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1390
                         alphasort);
1576
1391
  if(numhooks == -1){
1577
1392
    perror_plus("scandir");
1578
 
    return;
1579
 
  }
1580
 
  struct dirent *direntry;
1581
 
  int ret;
1582
 
  int devnull = open("/dev/null", O_RDONLY);
1583
 
  for(int i = 0; i < numhooks; i++){
1584
 
    direntry = direntries[i];
1585
 
    if(debug){
1586
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1587
 
                   direntry->d_name);
1588
 
    }
1589
 
    pid_t hook_pid = fork();
1590
 
    if(hook_pid == 0){
1591
 
      /* Child */
1592
 
      /* Raise privileges */
1593
 
      if(raise_privileges_permanently() != 0){
1594
 
        perror_plus("Failed to raise privileges");
1595
 
        _exit(EX_NOPERM);
1596
 
      }
1597
 
      /* Set group */
1598
 
      errno = 0;
1599
 
      ret = setgid(0);
1600
 
      if(ret == -1){
1601
 
        perror_plus("setgid");
1602
 
        _exit(EX_NOPERM);
1603
 
      }
1604
 
      /* Reset supplementary groups */
1605
 
      errno = 0;
1606
 
      ret = setgroups(0, NULL);
1607
 
      if(ret == -1){
1608
 
        perror_plus("setgroups");
1609
 
        _exit(EX_NOPERM);
1610
 
      }
1611
 
      ret = dup2(devnull, STDIN_FILENO);
1612
 
      if(ret == -1){
1613
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1614
 
        _exit(EX_OSERR);
1615
 
      }
1616
 
      ret = close(devnull);
1617
 
      if(ret == -1){
1618
 
        perror_plus("close");
1619
 
        _exit(EX_OSERR);
1620
 
      }
1621
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1622
 
      if(ret == -1){
1623
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1624
 
        _exit(EX_OSERR);
1625
 
      }
1626
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1627
 
      if(ret == -1){
1628
 
        perror_plus("setenv");
1629
 
        _exit(EX_OSERR);
1630
 
      }
1631
 
      ret = setenv("DEVICE", interface, 1);
1632
 
      if(ret == -1){
1633
 
        perror_plus("setenv");
1634
 
        _exit(EX_OSERR);
1635
 
      }
1636
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1637
 
      if(ret == -1){
1638
 
        perror_plus("setenv");
1639
 
        _exit(EX_OSERR);
1640
 
      }
1641
 
      ret = setenv("MODE", mode, 1);
1642
 
      if(ret == -1){
1643
 
        perror_plus("setenv");
1644
 
        _exit(EX_OSERR);
1645
 
      }
1646
 
      char *delaystring;
1647
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1648
 
      if(ret == -1){
 
1393
  } else {
 
1394
    int devnull = open("/dev/null", O_RDONLY);
 
1395
    for(int i = 0; i < numhooks; i++){
 
1396
      direntry = direntries[i];
 
1397
      char *fullname = NULL;
 
1398
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1399
      if(ret < 0){
1649
1400
        perror_plus("asprintf");
1650
 
        _exit(EX_OSERR);
1651
 
      }
1652
 
      ret = setenv("DELAY", delaystring, 1);
1653
 
      if(ret == -1){
 
1401
        continue;
 
1402
      }
 
1403
      if(debug){
 
1404
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1405
                     direntry->d_name);
 
1406
      }
 
1407
      pid_t hook_pid = fork();
 
1408
      if(hook_pid == 0){
 
1409
        /* Child */
 
1410
        /* Raise privileges */
 
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
        }
 
1422
        /* Set group */
 
1423
        errno = 0;
 
1424
        ret = setgid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setgid");
 
1427
        }
 
1428
        /* Reset supplementary groups */
 
1429
        errno = 0;
 
1430
        ret = setgroups(0, NULL);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgroups");
 
1433
        }
 
1434
        fprintf_plus(stderr, "Child: getuid() = %d\n", getuid());
 
1435
        fprintf_plus(stderr, "Child: geteuid() = %d\n", geteuid());
 
1436
        dup2(devnull, STDIN_FILENO);
 
1437
        close(devnull);
 
1438
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1439
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1440
        if(ret == -1){
 
1441
          perror_plus("setenv");
 
1442
          _exit(EX_OSERR);
 
1443
        }
 
1444
        ret = setenv("DEVICE", interface, 1);
 
1445
        if(ret == -1){
 
1446
          perror_plus("setenv");
 
1447
          _exit(EX_OSERR);
 
1448
        }
 
1449
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1450
        if(ret == -1){
 
1451
          perror_plus("setenv");
 
1452
          _exit(EX_OSERR);
 
1453
        }
 
1454
        ret = setenv("MODE", mode, 1);
 
1455
        if(ret == -1){
 
1456
          perror_plus("setenv");
 
1457
          _exit(EX_OSERR);
 
1458
        }
 
1459
        char *delaystring;
 
1460
        ret = asprintf(&delaystring, "%f", delay);
 
1461
        if(ret == -1){
 
1462
          perror_plus("asprintf");
 
1463
          _exit(EX_OSERR);
 
1464
        }
 
1465
        ret = setenv("DELAY", delaystring, 1);
 
1466
        if(ret == -1){
 
1467
          free(delaystring);
 
1468
          perror_plus("setenv");
 
1469
          _exit(EX_OSERR);
 
1470
        }
1654
1471
        free(delaystring);
1655
 
        perror_plus("setenv");
1656
 
        _exit(EX_OSERR);
1657
 
      }
1658
 
      free(delaystring);
1659
 
      if(connect_to != NULL){
1660
 
        ret = setenv("CONNECT", connect_to, 1);
1661
 
        if(ret == -1){
1662
 
          perror_plus("setenv");
1663
 
          _exit(EX_OSERR);
1664
 
        }
1665
 
      }
1666
 
      if(fexecve(hookdir_fd, (char *const [])
1667
 
                 { direntry->d_name, NULL }, environ) == -1){
1668
 
        perror_plus("fexecve");
1669
 
        _exit(EXIT_FAILURE);
1670
 
      }
1671
 
    } else {
1672
 
      int status;
1673
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1674
 
        perror_plus("waitpid");
1675
 
        continue;
1676
 
      }
1677
 
      if(WIFEXITED(status)){
1678
 
        if(WEXITSTATUS(status) != 0){
1679
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1680
 
                       " with status %d\n", direntry->d_name,
1681
 
                       WEXITSTATUS(status));
1682
 
          continue;
1683
 
        }
1684
 
      } else if(WIFSIGNALED(status)){
1685
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1686
 
                     " signal %d\n", direntry->d_name,
1687
 
                     WTERMSIG(status));
1688
 
        continue;
1689
 
      } else {
1690
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1691
 
                     " crashed\n", direntry->d_name);
1692
 
        continue;
1693
 
      }
1694
 
    }
1695
 
    if(debug){
1696
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1697
 
                   direntry->d_name);
1698
 
    }
1699
 
  }
1700
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1701
 
    perror_plus("close");
1702
 
  } else {
1703
 
    hookdir_fd = -1;
1704
 
  }
1705
 
  close(devnull);
1706
 
}
1707
 
 
1708
 
__attribute__((nonnull, warn_unused_result))
1709
 
error_t bring_up_interface(const char *const interface,
1710
 
                           const float delay){
1711
 
  error_t old_errno = errno;
1712
 
  int ret;
1713
 
  struct ifreq network;
1714
 
  unsigned int if_index = if_nametoindex(interface);
1715
 
  if(if_index == 0){
1716
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1717
 
    errno = old_errno;
1718
 
    return ENXIO;
1719
 
  }
1720
 
  
1721
 
  if(quit_now){
1722
 
    errno = old_errno;
1723
 
    return EINTR;
1724
 
  }
1725
 
  
1726
 
  if(not interface_is_up(interface)){
1727
 
    error_t ret_errno = 0, ioctl_errno = 0;
1728
 
    if(not get_flags(interface, &network)){
1729
 
      ret_errno = errno;
1730
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1731
 
                   "\"%s\"\n", interface);
1732
 
      errno = old_errno;
1733
 
      return ret_errno;
1734
 
    }
1735
 
    network.ifr_flags |= IFF_UP; /* set flag */
1736
 
    
1737
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1738
 
    if(sd == -1){
1739
 
      ret_errno = errno;
1740
 
      perror_plus("socket");
1741
 
      errno = old_errno;
1742
 
      return ret_errno;
1743
 
    }
1744
 
    
1745
 
    if(quit_now){
1746
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1747
 
      if(ret == -1){
1748
 
        perror_plus("close");
1749
 
      }
1750
 
      errno = old_errno;
1751
 
      return EINTR;
1752
 
    }
1753
 
    
1754
 
    if(debug){
1755
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1756
 
                   interface);
1757
 
    }
1758
 
    
1759
 
    /* Raise privileges */
1760
 
    ret_errno = raise_privileges();
1761
 
    if(ret_errno != 0){
1762
 
      perror_plus("Failed to raise privileges");
1763
 
    }
1764
 
    
1765
 
#ifdef __linux__
1766
 
    int ret_linux;
1767
 
    bool restore_loglevel = false;
1768
 
    if(ret_errno == 0){
1769
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1770
 
         messages about the network interface to mess up the prompt */
1771
 
      ret_linux = klogctl(8, NULL, 5);
1772
 
      if(ret_linux == -1){
1773
 
        perror_plus("klogctl");
1774
 
      } else {
1775
 
        restore_loglevel = true;
1776
 
      }
1777
 
    }
1778
 
#endif  /* __linux__ */
1779
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1780
 
    ioctl_errno = errno;
1781
 
#ifdef __linux__
1782
 
    if(restore_loglevel){
1783
 
      ret_linux = klogctl(7, NULL, 0);
1784
 
      if(ret_linux == -1){
1785
 
        perror_plus("klogctl");
1786
 
      }
1787
 
    }
1788
 
#endif  /* __linux__ */
1789
 
    
1790
 
    /* If raise_privileges() succeeded above */
1791
 
    if(ret_errno == 0){
1792
 
      /* Lower privileges */
1793
 
      ret_errno = lower_privileges();
1794
 
      if(ret_errno != 0){
1795
 
        errno = ret_errno;
1796
 
        perror_plus("Failed to lower privileges");
1797
 
      }
1798
 
    }
1799
 
    
1800
 
    /* Close the socket */
1801
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1802
 
    if(ret == -1){
1803
 
      perror_plus("close");
1804
 
    }
1805
 
    
1806
 
    if(ret_setflags == -1){
1807
 
      errno = ioctl_errno;
1808
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1809
 
      errno = old_errno;
1810
 
      return ioctl_errno;
1811
 
    }
1812
 
  } else if(debug){
1813
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1814
 
                 interface);
1815
 
  }
1816
 
  
1817
 
  /* Sleep checking until interface is running.
1818
 
     Check every 0.25s, up to total time of delay */
1819
 
  for(int i=0; i < delay * 4; i++){
1820
 
    if(interface_is_running(interface)){
1821
 
      break;
1822
 
    }
1823
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1824
 
    ret = nanosleep(&sleeptime, NULL);
1825
 
    if(ret == -1 and errno != EINTR){
1826
 
      perror_plus("nanosleep");
1827
 
    }
1828
 
  }
1829
 
  
1830
 
  errno = old_errno;
1831
 
  return 0;
1832
 
}
1833
 
 
1834
 
__attribute__((nonnull, warn_unused_result))
1835
 
error_t take_down_interface(const char *const interface){
1836
 
  error_t old_errno = errno;
1837
 
  struct ifreq network;
1838
 
  unsigned int if_index = if_nametoindex(interface);
1839
 
  if(if_index == 0){
1840
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1841
 
    errno = old_errno;
1842
 
    return ENXIO;
1843
 
  }
1844
 
  if(interface_is_up(interface)){
1845
 
    error_t ret_errno = 0, ioctl_errno = 0;
1846
 
    if(not get_flags(interface, &network) and debug){
1847
 
      ret_errno = errno;
1848
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1849
 
                   "\"%s\"\n", interface);
1850
 
      errno = old_errno;
1851
 
      return ret_errno;
1852
 
    }
1853
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1854
 
    
1855
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1856
 
    if(sd == -1){
1857
 
      ret_errno = errno;
1858
 
      perror_plus("socket");
1859
 
      errno = old_errno;
1860
 
      return ret_errno;
1861
 
    }
1862
 
    
1863
 
    if(debug){
1864
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1865
 
                   interface);
1866
 
    }
1867
 
    
1868
 
    /* Raise privileges */
1869
 
    ret_errno = raise_privileges();
1870
 
    if(ret_errno != 0){
1871
 
      perror_plus("Failed to raise privileges");
1872
 
    }
1873
 
    
1874
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1875
 
    ioctl_errno = errno;
1876
 
    
1877
 
    /* If raise_privileges() succeeded above */
1878
 
    if(ret_errno == 0){
1879
 
      /* Lower privileges */
1880
 
      ret_errno = lower_privileges();
1881
 
      if(ret_errno != 0){
1882
 
        errno = ret_errno;
1883
 
        perror_plus("Failed to lower privileges");
1884
 
      }
1885
 
    }
1886
 
    
1887
 
    /* Close the socket */
1888
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1889
 
    if(ret == -1){
1890
 
      perror_plus("close");
1891
 
    }
1892
 
    
1893
 
    if(ret_setflags == -1){
1894
 
      errno = ioctl_errno;
1895
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1896
 
      errno = old_errno;
1897
 
      return ioctl_errno;
1898
 
    }
1899
 
  } else if(debug){
1900
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1901
 
                 interface);
1902
 
  }
1903
 
  
1904
 
  errno = old_errno;
1905
 
  return 0;
 
1472
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1473
        perror_plus("execl");
 
1474
      } else {
 
1475
        int status;
 
1476
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1477
          perror_plus("waitpid");
 
1478
          free(fullname);
 
1479
          continue;
 
1480
        }
 
1481
        if(WIFEXITED(status)){
 
1482
          if(WEXITSTATUS(status) != 0){
 
1483
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1484
                         " with status %d\n", direntry->d_name,
 
1485
                         WEXITSTATUS(status));
 
1486
            free(fullname);
 
1487
            continue;
 
1488
          }
 
1489
        } else if(WIFSIGNALED(status)){
 
1490
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1491
                       " signal %d\n", direntry->d_name,
 
1492
                       WTERMSIG(status));
 
1493
          free(fullname);
 
1494
          continue;
 
1495
        } else {
 
1496
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1497
                       " crashed\n", direntry->d_name);
 
1498
          free(fullname);
 
1499
          continue;
 
1500
        }
 
1501
      }
 
1502
      free(fullname);
 
1503
      if(debug){
 
1504
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1505
                     direntry->d_name);
 
1506
      }
 
1507
    }
 
1508
    close(devnull);
 
1509
  }
 
1510
  return true;
1906
1511
}
1907
1512
 
1908
1513
int main(int argc, char *argv[]){
1909
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1910
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1911
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1912
 
                        .interfaces = NULL, .interfaces_size = 0 };
1913
1514
  AvahiSServiceBrowser *sb = NULL;
1914
 
  error_t ret_errno;
 
1515
  int error;
1915
1516
  int ret;
1916
1517
  intmax_t tmpmax;
1917
1518
  char *tmp;
1918
1519
  int exitcode = EXIT_SUCCESS;
1919
 
  char *interfaces_to_take_down = NULL;
1920
 
  size_t interfaces_to_take_down_size = 0;
1921
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1922
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1923
 
  char *tempdir = NULL;
 
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;
 
1526
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1527
  bool tempdir_created = false;
1924
1528
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1925
1529
  const char *seckey = PATHDIR "/" SECKEY;
1926
1530
  const char *pubkey = PATHDIR "/" PUBKEY;
1927
 
  char *interfaces_hooks = NULL;
1928
1531
  
1929
1532
  bool gnutls_initialized = false;
1930
1533
  bool gpgme_initialized = false;
1992
1595
        .group = 2 },
1993
1596
      { .name = "retry", .key = 132,
1994
1597
        .arg = "SECONDS",
1995
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1598
        .doc = "Retry interval used when denied by the mandos server",
1996
1599
        .group = 2 },
1997
1600
      { .name = "network-hook-dir", .key = 133,
1998
1601
        .arg = "DIR",
2021
1624
        connect_to = arg;
2022
1625
        break;
2023
1626
      case 'i':                 /* --interface */
2024
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2025
 
                                 arg, (int)',');
2026
 
        if(ret_errno != 0){
2027
 
          argp_error(state, "%s", strerror(ret_errno));
2028
 
        }
 
1627
        interface = arg;
2029
1628
        break;
2030
1629
      case 's':                 /* --seckey */
2031
1630
        seckey = arg;
2074
1673
        argp_state_help(state, state->out_stream,
2075
1674
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2076
1675
      case 'V':                 /* --version */
 
1676
        fprintf_plus(state->out_stream,
 
1677
                     "Mandos plugin mandos-client: ");
2077
1678
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
2078
1679
        exit(argp_err_exit_status);
2079
1680
        break;
2108
1709
    /* Work around Debian bug #633582:
2109
1710
       <http://bugs.debian.org/633582> */
2110
1711
    
2111
 
    /* Re-raise privileges */
2112
 
    ret_errno = raise_privileges();
2113
 
    if(ret_errno != 0){
2114
 
      errno = ret_errno;
2115
 
      perror_plus("Failed to raise privileges");
 
1712
    /* Re-raise priviliges */
 
1713
    errno = 0;
 
1714
    ret = seteuid(0);
 
1715
    if(ret == -1){
 
1716
      perror_plus("seteuid");
2116
1717
    } else {
2117
1718
      struct stat st;
2118
1719
      
2159
1760
      }
2160
1761
    
2161
1762
      /* Lower privileges */
2162
 
      ret_errno = lower_privileges();
2163
 
      if(ret_errno != 0){
2164
 
        errno = ret_errno;
2165
 
        perror_plus("Failed to lower privileges");
2166
 
      }
2167
 
    }
2168
 
  }
2169
 
  
2170
 
  /* Remove invalid interface names (except "none") */
2171
 
  {
2172
 
    char *interface = NULL;
2173
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2174
 
                                 interface))){
2175
 
      if(strcmp(interface, "none") != 0
2176
 
         and if_nametoindex(interface) == 0){
2177
 
        if(interface[0] != '\0'){
2178
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2179
 
                       " \"%s\"\n", interface);
2180
 
        }
2181
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2182
 
        interface = NULL;
 
1763
      errno = 0;
 
1764
      ret = seteuid(uid);
 
1765
      if(ret == -1){
 
1766
        perror_plus("seteuid");
2183
1767
      }
2184
1768
    }
2185
1769
  }
2186
1770
  
2187
1771
  /* Run network hooks */
2188
 
  {
2189
 
    if(mc.interfaces != NULL){
2190
 
      interfaces_hooks = malloc(mc.interfaces_size);
2191
 
      if(interfaces_hooks == NULL){
2192
 
        perror_plus("malloc");
2193
 
        goto end;
2194
 
      }
2195
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2196
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2197
 
    }
2198
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2199
 
                      interfaces_hooks : "", delay);
 
1772
  if(not run_network_hooks("start", interface, delay)){
 
1773
    goto end;
2200
1774
  }
2201
1775
  
2202
1776
  if(not debug){
2203
1777
    avahi_set_log_function(empty_log);
2204
1778
  }
2205
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
  
2206
1812
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2207
1813
     from the signal handler */
2208
1814
  /* Initialize the pseudo-RNG for Avahi */
2209
1815
  srand((unsigned int) time(NULL));
2210
 
  simple_poll = avahi_simple_poll_new();
2211
 
  if(simple_poll == NULL){
 
1816
  mc.simple_poll = avahi_simple_poll_new();
 
1817
  if(mc.simple_poll == NULL){
2212
1818
    fprintf_plus(stderr,
2213
1819
                 "Avahi: Failed to create simple poll object.\n");
2214
1820
    exitcode = EX_UNAVAILABLE;
2278
1884
    }
2279
1885
  }
2280
1886
  
2281
 
  /* If no interfaces were specified, make a list */
2282
 
  if(mc.interfaces == NULL){
2283
 
    struct dirent **direntries;
2284
 
    /* Look for any good interfaces */
2285
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2286
 
                  alphasort);
2287
 
    if(ret >= 1){
2288
 
      /* Add all found interfaces to interfaces list */
2289
 
      for(int i = 0; i < ret; ++i){
2290
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2291
 
                             direntries[i]->d_name);
2292
 
        if(ret_errno != 0){
2293
 
          errno = ret_errno;
2294
 
          perror_plus("argz_add");
2295
 
          continue;
2296
 
        }
2297
 
        if(debug){
2298
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2299
 
                       direntries[i]->d_name);
2300
 
        }
2301
 
      }
2302
 
      free(direntries);
2303
 
    } else {
2304
 
      free(direntries);
2305
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2306
 
      exitcode = EXIT_FAILURE;
2307
 
      goto end;
2308
 
    }
2309
 
  }
2310
 
  
2311
 
  /* Bring up interfaces which are down, and remove any "none"s */
2312
 
  {
2313
 
    char *interface = NULL;
2314
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2315
 
                                 interface))){
2316
 
      /* If interface name is "none", stop bringing up interfaces.
2317
 
         Also remove all instances of "none" from the list */
2318
 
      if(strcmp(interface, "none") == 0){
2319
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2320
 
                    interface);
2321
 
        interface = NULL;
2322
 
        while((interface = argz_next(mc.interfaces,
2323
 
                                     mc.interfaces_size, interface))){
2324
 
          if(strcmp(interface, "none") == 0){
2325
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2326
 
                        interface);
2327
 
            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");
2328
1972
          }
2329
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){
2330
1991
        break;
2331
1992
      }
2332
 
      bool interface_was_up = interface_is_up(interface);
2333
 
      errno = bring_up_interface(interface, delay);
2334
 
      if(not interface_was_up){
2335
 
        if(errno != 0){
2336
 
          perror_plus("Failed to bring up interface");
2337
 
        } else {
2338
 
          errno = argz_add(&interfaces_to_take_down,
2339
 
                           &interfaces_to_take_down_size,
2340
 
                           interface);
2341
 
          if(errno != 0){
2342
 
            perror_plus("argz_add");
2343
 
          }
2344
 
        }
2345
 
      }
2346
 
    }
2347
 
    if(debug and (interfaces_to_take_down == NULL)){
2348
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2349
 
    }
2350
 
  }
2351
 
  
2352
 
  /* If we only got one interface, explicitly use only that one */
2353
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2354
 
    if(debug){
2355
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2356
 
                   mc.interfaces);
2357
 
    }
2358
 
    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
    }
2359
2022
  }
2360
2023
  
2361
2024
  if(quit_now){
2362
2025
    goto end;
2363
2026
  }
2364
2027
  
2365
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2028
  ret = init_gnutls_global(pubkey, seckey);
2366
2029
  if(ret == -1){
2367
2030
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2368
2031
    exitcode = EX_UNAVAILABLE;
2375
2038
    goto end;
2376
2039
  }
2377
2040
  
2378
 
  /* Try /run/tmp before /tmp */
2379
 
  tempdir = mkdtemp(run_tempdir);
2380
 
  if(tempdir == NULL and errno == ENOENT){
2381
 
      if(debug){
2382
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2383
 
                     run_tempdir, old_tempdir);
2384
 
      }
2385
 
      tempdir = mkdtemp(old_tempdir);
2386
 
  }
2387
 
  if(tempdir == NULL){
 
2041
  if(mkdtemp(tempdir) == NULL){
2388
2042
    perror_plus("mkdtemp");
2389
2043
    goto end;
2390
2044
  }
 
2045
  tempdir_created = true;
2391
2046
  
2392
2047
  if(quit_now){
2393
2048
    goto end;
2394
2049
  }
2395
2050
  
2396
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2051
  if(not init_gpgme(pubkey, seckey, tempdir)){
2397
2052
    fprintf_plus(stderr, "init_gpgme failed\n");
2398
2053
    exitcode = EX_UNAVAILABLE;
2399
2054
    goto end;
2409
2064
    /* Connect directly, do not use Zeroconf */
2410
2065
    /* (Mainly meant for debugging) */
2411
2066
    char *address = strrchr(connect_to, ':');
2412
 
    
2413
2067
    if(address == NULL){
2414
2068
      fprintf_plus(stderr, "No colon in address\n");
2415
2069
      exitcode = EX_USAGE;
2420
2074
      goto end;
2421
2075
    }
2422
2076
    
2423
 
    in_port_t port;
 
2077
    uint16_t port;
2424
2078
    errno = 0;
2425
2079
    tmpmax = strtoimax(address+1, &tmp, 10);
2426
2080
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2427
 
       or tmpmax != (in_port_t)tmpmax){
 
2081
       or tmpmax != (uint16_t)tmpmax){
2428
2082
      fprintf_plus(stderr, "Bad port number\n");
2429
2083
      exitcode = EX_USAGE;
2430
2084
      goto end;
2431
2085
    }
2432
 
    
 
2086
  
2433
2087
    if(quit_now){
2434
2088
      goto end;
2435
2089
    }
2436
2090
    
2437
 
    port = (in_port_t)tmpmax;
 
2091
    port = (uint16_t)tmpmax;
2438
2092
    *address = '\0';
2439
2093
    /* Colon in address indicates IPv6 */
2440
2094
    int af;
2456
2110
    }
2457
2111
    
2458
2112
    while(not quit_now){
2459
 
      ret = start_mandos_communication(address, port, if_index, af,
2460
 
                                       &mc);
 
2113
      ret = start_mandos_communication(address, port, if_index, af);
2461
2114
      if(quit_now or ret == 0){
2462
2115
        break;
2463
2116
      }
2465
2118
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2466
2119
                     (int)retry_interval);
2467
2120
      }
2468
 
      sleep((unsigned int)retry_interval);
 
2121
      sleep((int)retry_interval);
2469
2122
    }
2470
2123
    
2471
 
    if(not quit_now){
 
2124
    if (not quit_now){
2472
2125
      exitcode = EXIT_SUCCESS;
2473
2126
    }
2474
2127
    
2489
2142
    config.publish_domain = 0;
2490
2143
    
2491
2144
    /* Allocate a new server */
2492
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2493
 
                                 &config, NULL, NULL, &ret_errno);
 
2145
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2146
                                 (mc.simple_poll), &config, NULL,
 
2147
                                 NULL, &error);
2494
2148
    
2495
2149
    /* Free the Avahi configuration data */
2496
2150
    avahi_server_config_free(&config);
2499
2153
  /* Check if creating the Avahi server object succeeded */
2500
2154
  if(mc.server == NULL){
2501
2155
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2502
 
                 avahi_strerror(ret_errno));
 
2156
                 avahi_strerror(error));
2503
2157
    exitcode = EX_UNAVAILABLE;
2504
2158
    goto end;
2505
2159
  }
2511
2165
  /* Create the Avahi service browser */
2512
2166
  sb = avahi_s_service_browser_new(mc.server, if_index,
2513
2167
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2514
 
                                   NULL, 0, browse_callback,
2515
 
                                   (void *)&mc);
 
2168
                                   NULL, 0, browse_callback, NULL);
2516
2169
  if(sb == NULL){
2517
2170
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2518
2171
                 avahi_strerror(avahi_server_errno(mc.server)));
2529
2182
  if(debug){
2530
2183
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2531
2184
  }
2532
 
  
2533
 
  ret = avahi_loop_with_timeout(simple_poll,
2534
 
                                (int)(retry_interval * 1000), &mc);
 
2185
 
 
2186
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2187
                                (int)(retry_interval * 1000));
2535
2188
  if(debug){
2536
2189
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2537
2190
                 (ret == 0) ? "successfully" : "with error");
2544
2197
  }
2545
2198
  
2546
2199
  /* Cleanup things */
2547
 
  free(mc.interfaces);
2548
 
  
2549
2200
  if(sb != NULL)
2550
2201
    avahi_s_service_browser_free(sb);
2551
2202
  
2552
2203
  if(mc.server != NULL)
2553
2204
    avahi_server_free(mc.server);
2554
2205
  
2555
 
  if(simple_poll != NULL)
2556
 
    avahi_simple_poll_free(simple_poll);
 
2206
  if(mc.simple_poll != NULL)
 
2207
    avahi_simple_poll_free(mc.simple_poll);
2557
2208
  
2558
2209
  if(gnutls_initialized){
2559
2210
    gnutls_certificate_free_credentials(mc.cred);
2576
2227
    }
2577
2228
  }
2578
2229
  
2579
 
  /* Re-raise privileges */
 
2230
  /* Run network hooks */
 
2231
  run_network_hooks("stop", interface, delay);
 
2232
  
 
2233
  /* Re-raise priviliges */
2580
2234
  {
2581
 
    ret_errno = raise_privileges();
2582
 
    if(ret_errno != 0){
2583
 
      perror_plus("Failed to raise privileges");
2584
 
    } else {
2585
 
      
2586
 
      /* Run network hooks */
2587
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2588
 
                        interfaces_hooks : "", delay);
2589
 
      
2590
 
      /* Take down the network interfaces which were brought up */
2591
 
      {
2592
 
        char *interface = NULL;
2593
 
        while((interface=argz_next(interfaces_to_take_down,
2594
 
                                   interfaces_to_take_down_size,
2595
 
                                   interface))){
2596
 
          ret_errno = take_down_interface(interface);
2597
 
          if(ret_errno != 0){
2598
 
            errno = ret_errno;
2599
 
            perror_plus("Failed to take down interface");
2600
 
          }
2601
 
        }
2602
 
        if(debug and (interfaces_to_take_down == NULL)){
2603
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2604
 
                       " down\n");
2605
 
        }
2606
 
      }
 
2235
    errno = 0;
 
2236
    ret = seteuid(0);
 
2237
    if(ret == -1){
 
2238
      perror_plus("seteuid");
2607
2239
    }
2608
2240
    
2609
 
    ret_errno = lower_privileges_permanently();
2610
 
    if(ret_errno != 0){
2611
 
      perror_plus("Failed to lower privileges permanently");
 
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");
 
2251
        }
 
2252
      }
 
2253
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2254
      if(ret == -1){
 
2255
        perror_plus("close");
 
2256
      }
2612
2257
    }
2613
2258
  }
2614
 
  
2615
 
  free(interfaces_to_take_down);
2616
 
  free(interfaces_hooks);
 
2259
  /* Lower privileges permanently */
 
2260
  errno = 0;
 
2261
  ret = setuid(uid);
 
2262
  if(ret == -1){
 
2263
    perror_plus("setuid");
 
2264
  }
2617
2265
  
2618
2266
  /* Removes the GPGME temp directory and all files inside */
2619
 
  if(tempdir != NULL){
 
2267
  if(tempdir_created){
2620
2268
    struct dirent **direntries = NULL;
2621
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY));
2622
 
    if(tempdir_fd == -1){
2623
 
      perror_plus("open");
2624
 
    } else {
2625
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2626
 
                               alphasort);
2627
 
      if(numentries > 0){
2628
 
        for(int i = 0; i < numentries; i++){
2629
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2630
 
          if(ret == -1){
2631
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2632
 
                         " \"%s\", 0): %s\n", tempdir,
2633
 
                         direntries[i]->d_name, strerror(errno));
2634
 
          }
2635
 
        }
2636
 
        
2637
 
        /* need to clean even if 0 because man page doesn't specify */
2638
 
        free(direntries);
2639
 
        if(numentries == -1){
2640
 
          perror_plus("scandir");
2641
 
        }
2642
 
        ret = rmdir(tempdir);
2643
 
        if(ret == -1 and errno != ENOENT){
2644
 
          perror_plus("rmdir");
2645
 
        }
 
2269
    struct dirent *direntry = NULL;
 
2270
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2271
                             alphasort);
 
2272
    if (numentries > 0){
 
2273
      for(int i = 0; i < numentries; i++){
 
2274
        direntry = direntries[i];
 
2275
        char *fullname = NULL;
 
2276
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2277
                       direntry->d_name);
 
2278
        if(ret < 0){
 
2279
          perror_plus("asprintf");
 
2280
          continue;
 
2281
        }
 
2282
        ret = remove(fullname);
 
2283
        if(ret == -1){
 
2284
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2285
                       strerror(errno));
 
2286
        }
 
2287
        free(fullname);
2646
2288
      }
2647
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2289
    }
 
2290
 
 
2291
    /* need to clean even if 0 because man page doesn't specify */
 
2292
    free(direntries);
 
2293
    if (numentries == -1){
 
2294
      perror_plus("scandir");
 
2295
    }
 
2296
    ret = rmdir(tempdir);
 
2297
    if(ret == -1 and errno != ENOENT){
 
2298
      perror_plus("rmdir");
2648
2299
    }
2649
2300
  }
2650
2301