/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-06-07 21:59:20 UTC
  • Revision ID: teddy@recompile.se-20140607215920-r4qkj7ktnjyqmrn5
Make mandos-client use fexecve().

* plugins.d/mandos-client.d (run_network_hooks): Use fexecve().

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