/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2011-12-24 19:43:26 UTC
  • mto: This revision was merged to the branch mainline in revision 531.
  • Revision ID: teddy@fukt.bsnet.se-20111224194326-egfeyd0140t03xmf
* plugins.d/mandos-client.c (add_server): Return bool; all callers
                                          changed.
  (resolve_callback): Check return value from add_server().
  (main/parse_opt): Bug fix; Remove extra message on --version.

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