/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: 2016-03-02 17:35:23 UTC
  • Revision ID: teddy@recompile.se-20160302173523-rdhzeatfxr582i2c
Use "nogroup" as a fallback group, not "nobody".

* Makefile (GROUP): Use "nogroup" as a fallback group, not "nobody".
* mandos (main): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 Björn Påhlsson
 
12
 * Copyright © 2008-2016 Teddy Hogeborn
 
13
 * Copyright © 2008-2016 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
 
                                   stdout, ferror(), remove() */
 
43
                                   stdout, ferror() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
 
49
#include <string.h>             /* strcmp(), strlen(), strerror(),
 
50
                                   asprintf(), strncpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
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
 
#include <fcntl.h>              /* open() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
 
60
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
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 <errno.h>              /* perror(), errno,
 
65
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
 
66
                                   EAI_SYSTEM, ENETUNREACH,
 
67
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
 
68
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
 
69
                                   ENOTEMPTY,
65
70
                                   program_invocation_short_name */
66
71
#include <time.h>               /* nanosleep(), time(), sleep() */
67
72
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
72
77
                                */
73
78
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
79
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause(), _exit() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
80
                                   setgid(), pause(), _exit(),
 
81
                                   unlinkat() */
 
82
#include <arpa/inet.h>          /* inet_pton(), htons() */
77
83
#include <iso646.h>             /* not, or, and */
78
84
#include <argp.h>               /* struct argp_option, error_t, struct
79
85
                                   argp_state, struct argp,
91
97
                                   argz_delete(), argz_append(),
92
98
                                   argz_stringify(), argz_add(),
93
99
                                   argz_count() */
 
100
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
101
                                   EAI_SYSTEM, gai_strerror() */
94
102
 
95
103
#ifdef __linux__
96
104
#include <sys/klog.h>           /* klogctl() */
138
146
static const char sys_class_net[] = "/sys/class/net";
139
147
char *connect_to = NULL;
140
148
const char *hookdir = HOOKDIR;
 
149
int hookdir_fd = -1;
141
150
uid_t uid = 65534;
142
151
gid_t gid = 65534;
143
152
 
180
189
  perror(print_text);
181
190
}
182
191
 
183
 
__attribute__((format (gnu_printf, 2, 3)))
 
192
__attribute__((format (gnu_printf, 2, 3), nonnull))
184
193
int fprintf_plus(FILE *stream, const char *format, ...){
185
194
  va_list ap;
186
195
  va_start (ap, format);
195
204
 * bytes. "buffer_capacity" is how much is currently allocated,
196
205
 * "buffer_length" is how much is already used.
197
206
 */
 
207
__attribute__((nonnull, warn_unused_result))
198
208
size_t incbuffer(char **buffer, size_t buffer_length,
199
209
                 size_t buffer_capacity){
200
210
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
201
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
202
 
    if(buffer == NULL){
 
211
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
212
    if(new_buf == NULL){
 
213
      int old_errno = errno;
 
214
      free(*buffer);
 
215
      errno = old_errno;
 
216
      *buffer = NULL;
203
217
      return 0;
204
218
    }
 
219
    *buffer = new_buf;
205
220
    buffer_capacity += BUFFER_SIZE;
206
221
  }
207
222
  return buffer_capacity;
208
223
}
209
224
 
210
225
/* Add server to set of servers to retry periodically */
 
226
__attribute__((nonnull, warn_unused_result))
211
227
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
212
228
                int af, server **current_server){
213
229
  int ret;
222
238
                          .af = af };
223
239
  if(new_server->ip == NULL){
224
240
    perror_plus("strdup");
 
241
    free(new_server);
 
242
    return false;
 
243
  }
 
244
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
245
  if(ret == -1){
 
246
    perror_plus("clock_gettime");
 
247
#ifdef __GNUC__
 
248
#pragma GCC diagnostic push
 
249
#pragma GCC diagnostic ignored "-Wcast-qual"
 
250
#endif
 
251
    free((char *)(new_server->ip));
 
252
#ifdef __GNUC__
 
253
#pragma GCC diagnostic pop
 
254
#endif
 
255
    free(new_server);
225
256
    return false;
226
257
  }
227
258
  /* Special case of first server */
229
260
    new_server->next = new_server;
230
261
    new_server->prev = new_server;
231
262
    *current_server = new_server;
232
 
  /* Place the new server last in the list */
233
263
  } else {
 
264
    /* Place the new server last in the list */
234
265
    new_server->next = *current_server;
235
266
    new_server->prev = (*current_server)->prev;
236
267
    new_server->prev->next = new_server;
237
268
    (*current_server)->prev = new_server;
238
269
  }
239
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
240
 
  if(ret == -1){
241
 
    perror_plus("clock_gettime");
242
 
    return false;
243
 
  }
244
270
  return true;
245
271
}
246
272
 
247
273
/* 
248
274
 * Initialize GPGME.
249
275
 */
250
 
static bool init_gpgme(const char *seckey, const char *pubkey,
251
 
                       const char *tempdir, mandos_context *mc){
 
276
__attribute__((nonnull, warn_unused_result))
 
277
static bool init_gpgme(const char * const seckey,
 
278
                       const char * const pubkey,
 
279
                       const char * const tempdir,
 
280
                       mandos_context *mc){
252
281
  gpgme_error_t rc;
253
282
  gpgme_engine_info_t engine_info;
254
283
  
255
284
  /*
256
285
   * Helper function to insert pub and seckey to the engine keyring.
257
286
   */
258
 
  bool import_key(const char *filename){
 
287
  bool import_key(const char * const filename){
259
288
    int ret;
260
289
    int fd;
261
290
    gpgme_data_t pgp_data;
280
309
      return false;
281
310
    }
282
311
    
283
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
312
    ret = close(fd);
284
313
    if(ret == -1){
285
314
      perror_plus("close");
286
315
    }
342
371
 * Decrypt OpenPGP data.
343
372
 * Returns -1 on error
344
373
 */
 
374
__attribute__((nonnull, warn_unused_result))
345
375
static ssize_t pgp_packet_decrypt(const char *cryptotext,
346
376
                                  size_t crypto_size,
347
377
                                  char **plaintext,
467
497
  return plaintext_length;
468
498
}
469
499
 
470
 
static const char * safer_gnutls_strerror(int value){
 
500
__attribute__((warn_unused_result, const))
 
501
static const char *safe_string(const char *str){
 
502
  if(str == NULL)
 
503
    return "(unknown)";
 
504
  return str;
 
505
}
 
506
 
 
507
__attribute__((warn_unused_result))
 
508
static const char *safer_gnutls_strerror(int value){
471
509
  const char *ret = gnutls_strerror(value);
472
 
  if(ret == NULL)
473
 
    ret = "(unknown)";
474
 
  return ret;
 
510
  return safe_string(ret);
475
511
}
476
512
 
477
513
/* GnuTLS log function callback */
 
514
__attribute__((nonnull))
478
515
static void debuggnutls(__attribute__((unused)) int level,
479
516
                        const char* string){
480
517
  fprintf_plus(stderr, "GnuTLS: %s", string);
481
518
}
482
519
 
 
520
__attribute__((nonnull(1, 2, 4), warn_unused_result))
483
521
static int init_gnutls_global(const char *pubkeyfilename,
484
522
                              const char *seckeyfilename,
 
523
                              const char *dhparamsfilename,
485
524
                              mandos_context *mc){
486
525
  int ret;
 
526
  unsigned int uret;
487
527
  
488
528
  if(debug){
489
529
    fprintf_plus(stderr, "Initializing GnuTLS\n");
490
530
  }
491
531
  
492
 
  ret = gnutls_global_init();
493
 
  if(ret != GNUTLS_E_SUCCESS){
494
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
495
 
                 safer_gnutls_strerror(ret));
496
 
    return -1;
497
 
  }
498
 
  
499
532
  if(debug){
500
533
    /* "Use a log level over 10 to enable all debugging options."
501
534
     * - GnuTLS manual
509
542
  if(ret != GNUTLS_E_SUCCESS){
510
543
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
511
544
                 safer_gnutls_strerror(ret));
512
 
    gnutls_global_deinit();
513
545
    return -1;
514
546
  }
515
547
  
540
572
                 safer_gnutls_strerror(ret));
541
573
    goto globalfail;
542
574
  }
543
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
544
 
  if(ret != GNUTLS_E_SUCCESS){
545
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
546
 
                 safer_gnutls_strerror(ret));
547
 
    goto globalfail;
548
 
  }
549
 
  
 
575
  /* If a Diffie-Hellman parameters file was given, try to use it */
 
576
  if(dhparamsfilename != NULL){
 
577
    gnutls_datum_t params = { .data = NULL, .size = 0 };
 
578
    do {
 
579
      int dhpfile = open(dhparamsfilename, O_RDONLY);
 
580
      if(dhpfile == -1){
 
581
        perror_plus("open");
 
582
        dhparamsfilename = NULL;
 
583
        break;
 
584
      }
 
585
      size_t params_capacity = 0;
 
586
      while(true){
 
587
        params_capacity = incbuffer((char **)&params.data,
 
588
                                    (size_t)params.size,
 
589
                                    (size_t)params_capacity);
 
590
        if(params_capacity == 0){
 
591
          perror_plus("incbuffer");
 
592
          free(params.data);
 
593
          params.data = NULL;
 
594
          dhparamsfilename = NULL;
 
595
          break;
 
596
        }
 
597
        ssize_t bytes_read = read(dhpfile,
 
598
                                  params.data + params.size,
 
599
                                  BUFFER_SIZE);
 
600
        /* EOF */
 
601
        if(bytes_read == 0){
 
602
          break;
 
603
        }
 
604
        /* check bytes_read for failure */
 
605
        if(bytes_read < 0){
 
606
          perror_plus("read");
 
607
          free(params.data);
 
608
          params.data = NULL;
 
609
          dhparamsfilename = NULL;
 
610
          break;
 
611
        }
 
612
        params.size += (unsigned int)bytes_read;
 
613
      }
 
614
      if(params.data == NULL){
 
615
        dhparamsfilename = NULL;
 
616
      }
 
617
      if(dhparamsfilename == NULL){
 
618
        break;
 
619
      }
 
620
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
 
621
                                          GNUTLS_X509_FMT_PEM);
 
622
      if(ret != GNUTLS_E_SUCCESS){
 
623
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
 
624
                     " \"%s\": %s\n", dhparamsfilename,
 
625
                     safer_gnutls_strerror(ret));
 
626
        dhparamsfilename = NULL;
 
627
      }
 
628
    } while(false);
 
629
  }
 
630
  if(dhparamsfilename == NULL){
 
631
    if(mc->dh_bits == 0){
 
632
      /* Find out the optimal number of DH bits */
 
633
      /* Try to read the private key file */
 
634
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
635
      do {
 
636
        int secfile = open(seckeyfilename, O_RDONLY);
 
637
        if(secfile == -1){
 
638
          perror_plus("open");
 
639
          break;
 
640
        }
 
641
        size_t buffer_capacity = 0;
 
642
        while(true){
 
643
          buffer_capacity = incbuffer((char **)&buffer.data,
 
644
                                      (size_t)buffer.size,
 
645
                                      (size_t)buffer_capacity);
 
646
          if(buffer_capacity == 0){
 
647
            perror_plus("incbuffer");
 
648
            free(buffer.data);
 
649
            buffer.data = NULL;
 
650
            break;
 
651
          }
 
652
          ssize_t bytes_read = read(secfile,
 
653
                                    buffer.data + buffer.size,
 
654
                                    BUFFER_SIZE);
 
655
          /* EOF */
 
656
          if(bytes_read == 0){
 
657
            break;
 
658
          }
 
659
          /* check bytes_read for failure */
 
660
          if(bytes_read < 0){
 
661
            perror_plus("read");
 
662
            free(buffer.data);
 
663
            buffer.data = NULL;
 
664
            break;
 
665
          }
 
666
          buffer.size += (unsigned int)bytes_read;
 
667
        }
 
668
        close(secfile);
 
669
      } while(false);
 
670
      /* If successful, use buffer to parse private key */
 
671
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
672
      if(buffer.data != NULL){
 
673
        {
 
674
          gnutls_openpgp_privkey_t privkey = NULL;
 
675
          ret = gnutls_openpgp_privkey_init(&privkey);
 
676
          if(ret != GNUTLS_E_SUCCESS){
 
677
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
678
                         " structure: %s",
 
679
                         safer_gnutls_strerror(ret));
 
680
            free(buffer.data);
 
681
            buffer.data = NULL;
 
682
          } else {
 
683
            ret = gnutls_openpgp_privkey_import
 
684
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
685
            if(ret != GNUTLS_E_SUCCESS){
 
686
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
687
                           safer_gnutls_strerror(ret));
 
688
              privkey = NULL;
 
689
            }
 
690
            free(buffer.data);
 
691
            buffer.data = NULL;
 
692
            if(privkey != NULL){
 
693
              /* Use private key to suggest an appropriate
 
694
                 sec_param */
 
695
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
696
              gnutls_openpgp_privkey_deinit(privkey);
 
697
              if(debug){
 
698
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
699
                             " a GnuTLS security parameter \"%s\".\n",
 
700
                             safe_string(gnutls_sec_param_get_name
 
701
                                         (sec_param)));
 
702
              }
 
703
            }
 
704
          }
 
705
        }
 
706
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
707
          /* Err on the side of caution */
 
708
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
709
          if(debug){
 
710
            fprintf_plus(stderr, "Falling back to security parameter"
 
711
                         " \"%s\"\n",
 
712
                         safe_string(gnutls_sec_param_get_name
 
713
                                     (sec_param)));
 
714
          }
 
715
        }
 
716
      }
 
717
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
718
      if(uret != 0){
 
719
        mc->dh_bits = uret;
 
720
        if(debug){
 
721
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
722
                       " implies %u DH bits; using that.\n",
 
723
                       safe_string(gnutls_sec_param_get_name
 
724
                                   (sec_param)),
 
725
                       mc->dh_bits);
 
726
        }
 
727
      } else {
 
728
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
729
                     " bits for security parameter \"%s\"): %s\n",
 
730
                     safe_string(gnutls_sec_param_get_name
 
731
                                 (sec_param)),
 
732
                     safer_gnutls_strerror(ret));
 
733
        goto globalfail;
 
734
      }
 
735
    } else if(debug){
 
736
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
737
                   mc->dh_bits);
 
738
    }
 
739
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
740
    if(ret != GNUTLS_E_SUCCESS){
 
741
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
742
                   " bits): %s\n", mc->dh_bits,
 
743
                   safer_gnutls_strerror(ret));
 
744
      goto globalfail;
 
745
    }
 
746
  }
550
747
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
551
748
  
552
749
  return 0;
554
751
 globalfail:
555
752
  
556
753
  gnutls_certificate_free_credentials(mc->cred);
557
 
  gnutls_global_deinit();
558
754
  gnutls_dh_params_deinit(mc->dh_params);
559
755
  return -1;
560
756
}
561
757
 
 
758
__attribute__((nonnull, warn_unused_result))
562
759
static int init_gnutls_session(gnutls_session_t *session,
563
760
                               mandos_context *mc){
564
761
  int ret;
611
808
  /* ignore client certificate if any. */
612
809
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
613
810
  
614
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
615
 
  
616
811
  return 0;
617
812
}
618
813
 
620
815
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
621
816
                      __attribute__((unused)) const char *txt){}
622
817
 
 
818
/* Set effective uid to 0, return errno */
 
819
__attribute__((warn_unused_result))
 
820
error_t raise_privileges(void){
 
821
  error_t old_errno = errno;
 
822
  error_t ret_errno = 0;
 
823
  if(seteuid(0) == -1){
 
824
    ret_errno = errno;
 
825
  }
 
826
  errno = old_errno;
 
827
  return ret_errno;
 
828
}
 
829
 
 
830
/* Set effective and real user ID to 0.  Return errno. */
 
831
__attribute__((warn_unused_result))
 
832
error_t raise_privileges_permanently(void){
 
833
  error_t old_errno = errno;
 
834
  error_t ret_errno = raise_privileges();
 
835
  if(ret_errno != 0){
 
836
    errno = old_errno;
 
837
    return ret_errno;
 
838
  }
 
839
  if(setuid(0) == -1){
 
840
    ret_errno = errno;
 
841
  }
 
842
  errno = old_errno;
 
843
  return ret_errno;
 
844
}
 
845
 
 
846
/* Set effective user ID to unprivileged saved user ID */
 
847
__attribute__((warn_unused_result))
 
848
error_t lower_privileges(void){
 
849
  error_t old_errno = errno;
 
850
  error_t ret_errno = 0;
 
851
  if(seteuid(uid) == -1){
 
852
    ret_errno = errno;
 
853
  }
 
854
  errno = old_errno;
 
855
  return ret_errno;
 
856
}
 
857
 
 
858
/* Lower privileges permanently */
 
859
__attribute__((warn_unused_result))
 
860
error_t lower_privileges_permanently(void){
 
861
  error_t old_errno = errno;
 
862
  error_t ret_errno = 0;
 
863
  if(setuid(uid) == -1){
 
864
    ret_errno = errno;
 
865
  }
 
866
  errno = old_errno;
 
867
  return ret_errno;
 
868
}
 
869
 
 
870
/* Helper function to add_local_route() and delete_local_route() */
 
871
__attribute__((nonnull, warn_unused_result))
 
872
static bool add_delete_local_route(const bool add,
 
873
                                   const char *address,
 
874
                                   AvahiIfIndex if_index){
 
875
  int ret;
 
876
  char helper[] = "mandos-client-iprouteadddel";
 
877
  char add_arg[] = "add";
 
878
  char delete_arg[] = "delete";
 
879
  char debug_flag[] = "--debug";
 
880
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
881
  if(pluginhelperdir == NULL){
 
882
    if(debug){
 
883
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
884
                   " variable not set; cannot run helper\n");
 
885
    }
 
886
    return false;
 
887
  }
 
888
  
 
889
  char interface[IF_NAMESIZE];
 
890
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
891
    perror_plus("if_indextoname");
 
892
    return false;
 
893
  }
 
894
  
 
895
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
896
  if(devnull == -1){
 
897
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
898
    return false;
 
899
  }
 
900
  pid_t pid = fork();
 
901
  if(pid == 0){
 
902
    /* Child */
 
903
    /* Raise privileges */
 
904
    errno = raise_privileges_permanently();
 
905
    if(errno != 0){
 
906
      perror_plus("Failed to raise privileges");
 
907
      /* _exit(EX_NOPERM); */
 
908
    } else {
 
909
      /* Set group */
 
910
      errno = 0;
 
911
      ret = setgid(0);
 
912
      if(ret == -1){
 
913
        perror_plus("setgid");
 
914
        _exit(EX_NOPERM);
 
915
      }
 
916
      /* Reset supplementary groups */
 
917
      errno = 0;
 
918
      ret = setgroups(0, NULL);
 
919
      if(ret == -1){
 
920
        perror_plus("setgroups");
 
921
        _exit(EX_NOPERM);
 
922
      }
 
923
    }
 
924
    ret = dup2(devnull, STDIN_FILENO);
 
925
    if(ret == -1){
 
926
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
927
      _exit(EX_OSERR);
 
928
    }
 
929
    ret = close(devnull);
 
930
    if(ret == -1){
 
931
      perror_plus("close");
 
932
      _exit(EX_OSERR);
 
933
    }
 
934
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
935
    if(ret == -1){
 
936
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
937
      _exit(EX_OSERR);
 
938
    }
 
939
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
940
                                                    O_RDONLY
 
941
                                                    | O_DIRECTORY
 
942
                                                    | O_PATH
 
943
                                                    | O_CLOEXEC));
 
944
    if(helperdir_fd == -1){
 
945
      perror_plus("open");
 
946
      _exit(EX_UNAVAILABLE);
 
947
    }
 
948
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
949
                                                   helper, O_RDONLY));
 
950
    if(helper_fd == -1){
 
951
      perror_plus("openat");
 
952
      close(helperdir_fd);
 
953
      _exit(EX_UNAVAILABLE);
 
954
    }
 
955
    close(helperdir_fd);
 
956
#ifdef __GNUC__
 
957
#pragma GCC diagnostic push
 
958
#pragma GCC diagnostic ignored "-Wcast-qual"
 
959
#endif
 
960
    if(fexecve(helper_fd, (char *const [])
 
961
               { helper, add ? add_arg : delete_arg, (char *)address,
 
962
                   interface, debug ? debug_flag : NULL, NULL },
 
963
               environ) == -1){
 
964
#ifdef __GNUC__
 
965
#pragma GCC diagnostic pop
 
966
#endif
 
967
      perror_plus("fexecve");
 
968
      _exit(EXIT_FAILURE);
 
969
    }
 
970
  }
 
971
  if(pid == -1){
 
972
    perror_plus("fork");
 
973
    return false;
 
974
  }
 
975
  int status;
 
976
  pid_t pret = -1;
 
977
  errno = 0;
 
978
  do {
 
979
    pret = waitpid(pid, &status, 0);
 
980
    if(pret == -1 and errno == EINTR and quit_now){
 
981
      int errno_raising = 0;
 
982
      if((errno = raise_privileges()) != 0){
 
983
        errno_raising = errno;
 
984
        perror_plus("Failed to raise privileges in order to"
 
985
                    " kill helper program");
 
986
      }
 
987
      if(kill(pid, SIGTERM) == -1){
 
988
        perror_plus("kill");
 
989
      }
 
990
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
991
        perror_plus("Failed to lower privileges after killing"
 
992
                    " helper program");
 
993
      }
 
994
      return false;
 
995
    }
 
996
  } while(pret == -1 and errno == EINTR);
 
997
  if(pret == -1){
 
998
    perror_plus("waitpid");
 
999
    return false;
 
1000
  }
 
1001
  if(WIFEXITED(status)){
 
1002
    if(WEXITSTATUS(status) != 0){
 
1003
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
1004
                   " with status %d\n", WEXITSTATUS(status));
 
1005
      return false;
 
1006
    }
 
1007
    return true;
 
1008
  }
 
1009
  if(WIFSIGNALED(status)){
 
1010
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
1011
                 " signal %d\n", WTERMSIG(status));
 
1012
    return false;
 
1013
  }
 
1014
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
1015
  return false;
 
1016
}
 
1017
 
 
1018
__attribute__((nonnull, warn_unused_result))
 
1019
static bool add_local_route(const char *address,
 
1020
                            AvahiIfIndex if_index){
 
1021
  if(debug){
 
1022
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
1023
  }
 
1024
  return add_delete_local_route(true, address, if_index);
 
1025
}
 
1026
 
 
1027
__attribute__((nonnull, warn_unused_result))
 
1028
static bool delete_local_route(const char *address,
 
1029
                               AvahiIfIndex if_index){
 
1030
  if(debug){
 
1031
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
1032
  }
 
1033
  return add_delete_local_route(false, address, if_index);
 
1034
}
 
1035
 
623
1036
/* Called when a Mandos server is found */
 
1037
__attribute__((nonnull, warn_unused_result))
624
1038
static int start_mandos_communication(const char *ip, in_port_t port,
625
1039
                                      AvahiIfIndex if_index,
626
1040
                                      int af, mandos_context *mc){
627
1041
  int ret, tcp_sd = -1;
628
1042
  ssize_t sret;
629
 
  union {
630
 
    struct sockaddr_in in;
631
 
    struct sockaddr_in6 in6;
632
 
  } to;
 
1043
  struct sockaddr_storage to;
633
1044
  char *buffer = NULL;
634
1045
  char *decrypted_buffer = NULL;
635
1046
  size_t buffer_length = 0;
638
1049
  int retval = -1;
639
1050
  gnutls_session_t session;
640
1051
  int pf;                       /* Protocol family */
 
1052
  bool route_added = false;
641
1053
  
642
1054
  errno = 0;
643
1055
  
701
1113
                 PRIuMAX "\n", ip, (uintmax_t)port);
702
1114
  }
703
1115
  
704
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1116
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
705
1117
  if(tcp_sd < 0){
706
1118
    int e = errno;
707
1119
    perror_plus("socket");
714
1126
    goto mandos_end;
715
1127
  }
716
1128
  
717
 
  memset(&to, 0, sizeof(to));
718
1129
  if(af == AF_INET6){
719
 
    to.in6.sin6_family = (sa_family_t)af;
720
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
1130
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1131
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1132
    ret = inet_pton(af, ip, &to6->sin6_addr);
721
1133
  } else {                      /* IPv4 */
722
 
    to.in.sin_family = (sa_family_t)af;
723
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
1134
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1135
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1136
    ret = inet_pton(af, ip, &to4->sin_addr);
724
1137
  }
725
1138
  if(ret < 0 ){
726
1139
    int e = errno;
735
1148
    goto mandos_end;
736
1149
  }
737
1150
  if(af == AF_INET6){
738
 
    to.in6.sin6_port = htons(port);    
739
 
#ifdef __GNUC__
740
 
#pragma GCC diagnostic push
741
 
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
742
 
#endif
743
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
744
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
745
 
#ifdef __GNUC__
746
 
#pragma GCC diagnostic pop
747
 
#endif
 
1151
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
1152
    if(IN6_IS_ADDR_LINKLOCAL
 
1153
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
748
1154
      if(if_index == AVAHI_IF_UNSPEC){
749
1155
        fprintf_plus(stderr, "An IPv6 link-local address is"
750
1156
                     " incomplete without a network interface\n");
752
1158
        goto mandos_end;
753
1159
      }
754
1160
      /* Set the network interface number as scope */
755
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
1161
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
756
1162
    }
757
1163
  } else {
758
 
    to.in.sin_port = htons(port);
 
1164
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
759
1165
  }
760
1166
  
761
1167
  if(quit_now){
778
1184
    }
779
1185
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
780
1186
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
781
 
    const char *pcret;
782
 
    if(af == AF_INET6){
783
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
784
 
                        sizeof(addrstr));
785
 
    } else {
786
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
787
 
                        sizeof(addrstr));
788
 
    }
789
 
    if(pcret == NULL){
790
 
      perror_plus("inet_ntop");
791
 
    } else {
792
 
      if(strcmp(addrstr, ip) != 0){
793
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
794
 
      }
795
 
    }
796
 
  }
797
 
  
798
 
  if(quit_now){
799
 
    errno = EINTR;
800
 
    goto mandos_end;
801
 
  }
802
 
  
803
 
  if(af == AF_INET6){
804
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
805
 
  } else {
806
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
807
 
  }
808
 
  if(ret < 0){
809
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
810
 
      int e = errno;
811
 
      perror_plus("connect");
812
 
      errno = e;
813
 
    }
814
 
    goto mandos_end;
815
 
  }
816
 
  
817
 
  if(quit_now){
818
 
    errno = EINTR;
819
 
    goto mandos_end;
 
1187
    if(af == AF_INET6){
 
1188
      ret = getnameinfo((struct sockaddr *)&to,
 
1189
                        sizeof(struct sockaddr_in6),
 
1190
                        addrstr, sizeof(addrstr), NULL, 0,
 
1191
                        NI_NUMERICHOST);
 
1192
    } else {
 
1193
      ret = getnameinfo((struct sockaddr *)&to,
 
1194
                        sizeof(struct sockaddr_in),
 
1195
                        addrstr, sizeof(addrstr), NULL, 0,
 
1196
                        NI_NUMERICHOST);
 
1197
    }
 
1198
    if(ret == EAI_SYSTEM){
 
1199
      perror_plus("getnameinfo");
 
1200
    } else if(ret != 0) {
 
1201
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
1202
    } else if(strcmp(addrstr, ip) != 0){
 
1203
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
1204
    }
 
1205
  }
 
1206
  
 
1207
  if(quit_now){
 
1208
    errno = EINTR;
 
1209
    goto mandos_end;
 
1210
  }
 
1211
  
 
1212
  while(true){
 
1213
    if(af == AF_INET6){
 
1214
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1215
                    sizeof(struct sockaddr_in6));
 
1216
    } else {
 
1217
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1218
                    sizeof(struct sockaddr_in));
 
1219
    }
 
1220
    if(ret < 0){
 
1221
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1222
         and if_index != AVAHI_IF_UNSPEC
 
1223
         and connect_to == NULL
 
1224
         and not route_added and
 
1225
         ((af == AF_INET6 and not
 
1226
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1227
                                    &to)->sin6_addr)))
 
1228
          or (af == AF_INET and
 
1229
              /* Not a a IPv4LL address */
 
1230
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1231
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1232
        /* Work around Avahi bug - Avahi does not announce link-local
 
1233
           addresses if it has a global address, so local hosts with
 
1234
           *only* a link-local address (e.g. Mandos clients) cannot
 
1235
           connect to a Mandos server announced by Avahi on a server
 
1236
           host with a global address.  Work around this by retrying
 
1237
           with an explicit route added with the server's address.
 
1238
           
 
1239
           Avahi bug reference:
 
1240
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1241
           https://bugs.debian.org/587961
 
1242
        */
 
1243
        if(debug){
 
1244
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1245
                       " direct route\n");
 
1246
        }
 
1247
        int e = errno;
 
1248
        route_added = add_local_route(ip, if_index);
 
1249
        if(route_added){
 
1250
          continue;
 
1251
        }
 
1252
        errno = e;
 
1253
      }
 
1254
      if(errno != ECONNREFUSED or debug){
 
1255
        int e = errno;
 
1256
        perror_plus("connect");
 
1257
        errno = e;
 
1258
      }
 
1259
      goto mandos_end;
 
1260
    }
 
1261
    
 
1262
    if(quit_now){
 
1263
      errno = EINTR;
 
1264
      goto mandos_end;
 
1265
    }
 
1266
    break;
820
1267
  }
821
1268
  
822
1269
  const char *out = mandos_protocol_version;
1005
1452
  
1006
1453
 mandos_end:
1007
1454
  {
 
1455
    if(route_added){
 
1456
      if(not delete_local_route(ip, if_index)){
 
1457
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1458
                     " interface %d", ip, if_index);
 
1459
      }
 
1460
    }
1008
1461
    int e = errno;
1009
1462
    free(decrypted_buffer);
1010
1463
    free(buffer);
1011
1464
    if(tcp_sd >= 0){
1012
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1465
      ret = close(tcp_sd);
1013
1466
    }
1014
1467
    if(ret == -1){
1015
1468
      if(e == 0){
1027
1480
  return retval;
1028
1481
}
1029
1482
 
 
1483
__attribute__((nonnull))
1030
1484
static void resolve_callback(AvahiSServiceResolver *r,
1031
1485
                             AvahiIfIndex interface,
1032
1486
                             AvahiProtocol proto,
1040
1494
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1041
1495
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1042
1496
                             flags,
1043
 
                             void* mc){
 
1497
                             void *mc){
1044
1498
  if(r == NULL){
1045
1499
    return;
1046
1500
  }
1049
1503
     timed out */
1050
1504
  
1051
1505
  if(quit_now){
 
1506
    avahi_s_service_resolver_free(r);
1052
1507
    return;
1053
1508
  }
1054
1509
  
1099
1554
                            const char *domain,
1100
1555
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1101
1556
                            flags,
1102
 
                            void* mc){
 
1557
                            void *mc){
1103
1558
  if(b == NULL){
1104
1559
    return;
1105
1560
  }
1165
1620
  errno = old_errno;
1166
1621
}
1167
1622
 
 
1623
__attribute__((nonnull, warn_unused_result))
1168
1624
bool get_flags(const char *ifname, struct ifreq *ifr){
1169
1625
  int ret;
1170
1626
  error_t ret_errno;
1176
1632
    errno = ret_errno;
1177
1633
    return false;
1178
1634
  }
1179
 
  strcpy(ifr->ifr_name, ifname);
 
1635
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1636
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1180
1637
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1181
1638
  if(ret == -1){
1182
1639
    if(debug){
1189
1646
  return true;
1190
1647
}
1191
1648
 
 
1649
__attribute__((nonnull, warn_unused_result))
1192
1650
bool good_flags(const char *ifname, const struct ifreq *ifr){
1193
1651
  
1194
1652
  /* Reject the loopback device */
1236
1694
 * corresponds to an acceptable network device.
1237
1695
 * (This function is passed to scandir(3) as a filter function.)
1238
1696
 */
 
1697
__attribute__((nonnull, warn_unused_result))
1239
1698
int good_interface(const struct dirent *if_entry){
1240
1699
  if(if_entry->d_name[0] == '.'){
1241
1700
    return 0;
1259
1718
/* 
1260
1719
 * This function determines if a network interface is up.
1261
1720
 */
 
1721
__attribute__((nonnull, warn_unused_result))
1262
1722
bool interface_is_up(const char *interface){
1263
1723
  struct ifreq ifr;
1264
1724
  if(not get_flags(interface, &ifr)){
1275
1735
/* 
1276
1736
 * This function determines if a network interface is running
1277
1737
 */
 
1738
__attribute__((nonnull, warn_unused_result))
1278
1739
bool interface_is_running(const char *interface){
1279
1740
  struct ifreq ifr;
1280
1741
  if(not get_flags(interface, &ifr)){
1288
1749
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1289
1750
}
1290
1751
 
 
1752
__attribute__((nonnull, pure, warn_unused_result))
1291
1753
int notdotentries(const struct dirent *direntry){
1292
1754
  /* Skip "." and ".." */
1293
1755
  if(direntry->d_name[0] == '.'
1300
1762
}
1301
1763
 
1302
1764
/* Is this directory entry a runnable program? */
 
1765
__attribute__((nonnull, warn_unused_result))
1303
1766
int runnable_hook(const struct dirent *direntry){
1304
1767
  int ret;
1305
1768
  size_t sret;
1313
1776
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1314
1777
                "abcdefghijklmnopqrstuvwxyz"
1315
1778
                "0123456789"
1316
 
                "_-");
 
1779
                "_.-");
1317
1780
  if((direntry->d_name)[sret] != '\0'){
1318
1781
    /* Contains non-allowed characters */
1319
1782
    if(debug){
1323
1786
    return 0;
1324
1787
  }
1325
1788
  
1326
 
  char *fullname = NULL;
1327
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1328
 
  if(ret < 0){
1329
 
    perror_plus("asprintf");
1330
 
    return 0;
1331
 
  }
1332
 
  
1333
 
  ret = stat(fullname, &st);
 
1789
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1334
1790
  if(ret == -1){
1335
1791
    if(debug){
1336
1792
      perror_plus("Could not stat hook");
1360
1816
  return 1;
1361
1817
}
1362
1818
 
 
1819
__attribute__((nonnull, warn_unused_result))
1363
1820
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1364
1821
                            mandos_context *mc){
1365
1822
  int ret;
1369
1826
  
1370
1827
  while(true){
1371
1828
    if(mc->current_server == NULL){
1372
 
      if (debug){
 
1829
      if(debug){
1373
1830
        fprintf_plus(stderr, "Wait until first server is found."
1374
1831
                     " No timeout!\n");
1375
1832
      }
1376
1833
      ret = avahi_simple_poll_iterate(s, -1);
1377
1834
    } else {
1378
 
      if (debug){
 
1835
      if(debug){
1379
1836
        fprintf_plus(stderr, "Check current_server if we should run"
1380
1837
                     " it, or wait\n");
1381
1838
      }
1398
1855
                     - ((intmax_t)waited_time.tv_sec * 1000))
1399
1856
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1400
1857
      
1401
 
      if (debug){
 
1858
      if(debug){
1402
1859
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1403
1860
                     block_time);
1404
1861
      }
1426
1883
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1427
1884
    }
1428
1885
    if(ret != 0){
1429
 
      if (ret > 0 or errno != EINTR){
 
1886
      if(ret > 0 or errno != EINTR){
1430
1887
        return (ret != 1) ? ret : 0;
1431
1888
      }
1432
1889
    }
1433
1890
  }
1434
1891
}
1435
1892
 
1436
 
/* Set effective uid to 0, return errno */
1437
 
error_t raise_privileges(void){
1438
 
  error_t old_errno = errno;
1439
 
  error_t ret_errno = 0;
1440
 
  if(seteuid(0) == -1){
1441
 
    ret_errno = errno;
1442
 
    perror_plus("seteuid");
1443
 
  }
1444
 
  errno = old_errno;
1445
 
  return ret_errno;
1446
 
}
1447
 
 
1448
 
/* Set effective and real user ID to 0.  Return errno. */
1449
 
error_t raise_privileges_permanently(void){
1450
 
  error_t old_errno = errno;
1451
 
  error_t ret_errno = raise_privileges();
1452
 
  if(ret_errno != 0){
1453
 
    errno = old_errno;
1454
 
    return ret_errno;
1455
 
  }
1456
 
  if(setuid(0) == -1){
1457
 
    ret_errno = errno;
1458
 
    perror_plus("seteuid");
1459
 
  }
1460
 
  errno = old_errno;
1461
 
  return ret_errno;
1462
 
}
1463
 
 
1464
 
/* Set effective user ID to unprivileged saved user ID */
1465
 
error_t lower_privileges(void){
1466
 
  error_t old_errno = errno;
1467
 
  error_t ret_errno = 0;
1468
 
  if(seteuid(uid) == -1){
1469
 
    ret_errno = errno;
1470
 
    perror_plus("seteuid");
1471
 
  }
1472
 
  errno = old_errno;
1473
 
  return ret_errno;
1474
 
}
1475
 
 
1476
 
/* Lower privileges permanently */
1477
 
error_t lower_privileges_permanently(void){
1478
 
  error_t old_errno = errno;
1479
 
  error_t ret_errno = 0;
1480
 
  if(setuid(uid) == -1){
1481
 
    ret_errno = errno;
1482
 
    perror_plus("setuid");
1483
 
  }
1484
 
  errno = old_errno;
1485
 
  return ret_errno;
1486
 
}
1487
 
 
1488
 
bool run_network_hooks(const char *mode, const char *interface,
 
1893
__attribute__((nonnull))
 
1894
void run_network_hooks(const char *mode, const char *interface,
1489
1895
                       const float delay){
1490
 
  struct dirent **direntries;
 
1896
  struct dirent **direntries = NULL;
 
1897
  if(hookdir_fd == -1){
 
1898
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1899
                      | O_CLOEXEC);
 
1900
    if(hookdir_fd == -1){
 
1901
      if(errno == ENOENT){
 
1902
        if(debug){
 
1903
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1904
                       " found\n", hookdir);
 
1905
        }
 
1906
      } else {
 
1907
        perror_plus("open");
 
1908
      }
 
1909
      return;
 
1910
    }
 
1911
  }
 
1912
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1913
                           runnable_hook, alphasort);
 
1914
  if(numhooks == -1){
 
1915
    perror_plus("scandir");
 
1916
    return;
 
1917
  }
1491
1918
  struct dirent *direntry;
1492
1919
  int ret;
1493
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1494
 
                         alphasort);
1495
 
  if(numhooks == -1){
1496
 
    if(errno == ENOENT){
1497
 
      if(debug){
1498
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1499
 
                     " found\n", hookdir);
1500
 
      }
1501
 
    } else {
1502
 
      perror_plus("scandir");
 
1920
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1921
  if(devnull == -1){
 
1922
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1923
    return;
 
1924
  }
 
1925
  for(int i = 0; i < numhooks; i++){
 
1926
    direntry = direntries[i];
 
1927
    if(debug){
 
1928
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1929
                   direntry->d_name);
1503
1930
    }
1504
 
  } else {
1505
 
    int devnull = open("/dev/null", O_RDONLY);
1506
 
    for(int i = 0; i < numhooks; i++){
1507
 
      direntry = direntries[i];
1508
 
      char *fullname = NULL;
1509
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1510
 
      if(ret < 0){
 
1931
    pid_t hook_pid = fork();
 
1932
    if(hook_pid == 0){
 
1933
      /* Child */
 
1934
      /* Raise privileges */
 
1935
      errno = raise_privileges_permanently();
 
1936
      if(errno != 0){
 
1937
        perror_plus("Failed to raise privileges");
 
1938
        _exit(EX_NOPERM);
 
1939
      }
 
1940
      /* Set group */
 
1941
      errno = 0;
 
1942
      ret = setgid(0);
 
1943
      if(ret == -1){
 
1944
        perror_plus("setgid");
 
1945
        _exit(EX_NOPERM);
 
1946
      }
 
1947
      /* Reset supplementary groups */
 
1948
      errno = 0;
 
1949
      ret = setgroups(0, NULL);
 
1950
      if(ret == -1){
 
1951
        perror_plus("setgroups");
 
1952
        _exit(EX_NOPERM);
 
1953
      }
 
1954
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1955
      if(ret == -1){
 
1956
        perror_plus("setenv");
 
1957
        _exit(EX_OSERR);
 
1958
      }
 
1959
      ret = setenv("DEVICE", interface, 1);
 
1960
      if(ret == -1){
 
1961
        perror_plus("setenv");
 
1962
        _exit(EX_OSERR);
 
1963
      }
 
1964
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1965
      if(ret == -1){
 
1966
        perror_plus("setenv");
 
1967
        _exit(EX_OSERR);
 
1968
      }
 
1969
      ret = setenv("MODE", mode, 1);
 
1970
      if(ret == -1){
 
1971
        perror_plus("setenv");
 
1972
        _exit(EX_OSERR);
 
1973
      }
 
1974
      char *delaystring;
 
1975
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1976
      if(ret == -1){
1511
1977
        perror_plus("asprintf");
1512
 
        continue;
1513
 
      }
1514
 
      if(debug){
1515
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1516
 
                     direntry->d_name);
1517
 
      }
1518
 
      pid_t hook_pid = fork();
1519
 
      if(hook_pid == 0){
1520
 
        /* Child */
1521
 
        /* Raise privileges */
1522
 
        raise_privileges_permanently();
1523
 
        /* Set group */
1524
 
        errno = 0;
1525
 
        ret = setgid(0);
1526
 
        if(ret == -1){
1527
 
          perror_plus("setgid");
1528
 
        }
1529
 
        /* Reset supplementary groups */
1530
 
        errno = 0;
1531
 
        ret = setgroups(0, NULL);
1532
 
        if(ret == -1){
1533
 
          perror_plus("setgroups");
1534
 
        }
1535
 
        dup2(devnull, STDIN_FILENO);
1536
 
        close(devnull);
1537
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1538
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1539
 
        if(ret == -1){
1540
 
          perror_plus("setenv");
1541
 
          _exit(EX_OSERR);
1542
 
        }
1543
 
        ret = setenv("DEVICE", interface, 1);
1544
 
        if(ret == -1){
1545
 
          perror_plus("setenv");
1546
 
          _exit(EX_OSERR);
1547
 
        }
1548
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1549
 
        if(ret == -1){
1550
 
          perror_plus("setenv");
1551
 
          _exit(EX_OSERR);
1552
 
        }
1553
 
        ret = setenv("MODE", mode, 1);
1554
 
        if(ret == -1){
1555
 
          perror_plus("setenv");
1556
 
          _exit(EX_OSERR);
1557
 
        }
1558
 
        char *delaystring;
1559
 
        ret = asprintf(&delaystring, "%f", delay);
1560
 
        if(ret == -1){
1561
 
          perror_plus("asprintf");
1562
 
          _exit(EX_OSERR);
1563
 
        }
1564
 
        ret = setenv("DELAY", delaystring, 1);
1565
 
        if(ret == -1){
1566
 
          free(delaystring);
1567
 
          perror_plus("setenv");
1568
 
          _exit(EX_OSERR);
1569
 
        }
 
1978
        _exit(EX_OSERR);
 
1979
      }
 
1980
      ret = setenv("DELAY", delaystring, 1);
 
1981
      if(ret == -1){
1570
1982
        free(delaystring);
1571
 
        if(connect_to != NULL){
1572
 
          ret = setenv("CONNECT", connect_to, 1);
1573
 
          if(ret == -1){
1574
 
            perror_plus("setenv");
1575
 
            _exit(EX_OSERR);
1576
 
          }
1577
 
        }
1578
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1579
 
          perror_plus("execl");
1580
 
          _exit(EXIT_FAILURE);
1581
 
        }
 
1983
        perror_plus("setenv");
 
1984
        _exit(EX_OSERR);
 
1985
      }
 
1986
      free(delaystring);
 
1987
      if(connect_to != NULL){
 
1988
        ret = setenv("CONNECT", connect_to, 1);
 
1989
        if(ret == -1){
 
1990
          perror_plus("setenv");
 
1991
          _exit(EX_OSERR);
 
1992
        }
 
1993
      }
 
1994
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1995
                                                   direntry->d_name,
 
1996
                                                   O_RDONLY));
 
1997
      if(hook_fd == -1){
 
1998
        perror_plus("openat");
 
1999
        _exit(EXIT_FAILURE);
 
2000
      }
 
2001
      if(close(hookdir_fd) == -1){
 
2002
        perror_plus("close");
 
2003
        _exit(EXIT_FAILURE);
 
2004
      }
 
2005
      ret = dup2(devnull, STDIN_FILENO);
 
2006
      if(ret == -1){
 
2007
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
2008
        _exit(EX_OSERR);
 
2009
      }
 
2010
      ret = close(devnull);
 
2011
      if(ret == -1){
 
2012
        perror_plus("close");
 
2013
        _exit(EX_OSERR);
 
2014
      }
 
2015
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
2016
      if(ret == -1){
 
2017
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
2018
        _exit(EX_OSERR);
 
2019
      }
 
2020
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
2021
                 environ) == -1){
 
2022
        perror_plus("fexecve");
 
2023
        _exit(EXIT_FAILURE);
 
2024
      }
 
2025
    } else {
 
2026
      if(hook_pid == -1){
 
2027
        perror_plus("fork");
 
2028
        free(direntry);
 
2029
        continue;
 
2030
      }
 
2031
      int status;
 
2032
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
2033
        perror_plus("waitpid");
 
2034
        free(direntry);
 
2035
        continue;
 
2036
      }
 
2037
      if(WIFEXITED(status)){
 
2038
        if(WEXITSTATUS(status) != 0){
 
2039
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
2040
                       " with status %d\n", direntry->d_name,
 
2041
                       WEXITSTATUS(status));
 
2042
          free(direntry);
 
2043
          continue;
 
2044
        }
 
2045
      } else if(WIFSIGNALED(status)){
 
2046
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
2047
                     " signal %d\n", direntry->d_name,
 
2048
                     WTERMSIG(status));
 
2049
        free(direntry);
 
2050
        continue;
1582
2051
      } else {
1583
 
        int status;
1584
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1585
 
          perror_plus("waitpid");
1586
 
          free(fullname);
1587
 
          continue;
1588
 
        }
1589
 
        if(WIFEXITED(status)){
1590
 
          if(WEXITSTATUS(status) != 0){
1591
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1592
 
                         " with status %d\n", direntry->d_name,
1593
 
                         WEXITSTATUS(status));
1594
 
            free(fullname);
1595
 
            continue;
1596
 
          }
1597
 
        } else if(WIFSIGNALED(status)){
1598
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1599
 
                       " signal %d\n", direntry->d_name,
1600
 
                       WTERMSIG(status));
1601
 
          free(fullname);
1602
 
          continue;
1603
 
        } else {
1604
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1605
 
                       " crashed\n", direntry->d_name);
1606
 
          free(fullname);
1607
 
          continue;
1608
 
        }
1609
 
      }
1610
 
      free(fullname);
1611
 
      if(debug){
1612
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1613
 
                     direntry->d_name);
1614
 
      }
1615
 
    }
1616
 
    close(devnull);
1617
 
  }
1618
 
  return true;
 
2052
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
2053
                     " crashed\n", direntry->d_name);
 
2054
        free(direntry);
 
2055
        continue;
 
2056
      }
 
2057
    }
 
2058
    if(debug){
 
2059
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
2060
                   direntry->d_name);
 
2061
    }
 
2062
    free(direntry);
 
2063
  }
 
2064
  free(direntries);
 
2065
  if(close(hookdir_fd) == -1){
 
2066
    perror_plus("close");
 
2067
  } else {
 
2068
    hookdir_fd = -1;
 
2069
  }
 
2070
  close(devnull);
1619
2071
}
1620
2072
 
 
2073
__attribute__((nonnull, warn_unused_result))
1621
2074
error_t bring_up_interface(const char *const interface,
1622
2075
                           const float delay){
1623
 
  int sd = -1;
1624
2076
  error_t old_errno = errno;
1625
 
  error_t ret_errno = 0;
1626
 
  int ret, ret_setflags;
 
2077
  int ret;
1627
2078
  struct ifreq network;
1628
2079
  unsigned int if_index = if_nametoindex(interface);
1629
2080
  if(if_index == 0){
1638
2089
  }
1639
2090
  
1640
2091
  if(not interface_is_up(interface)){
1641
 
    if(not get_flags(interface, &network) and debug){
 
2092
    error_t ret_errno = 0, ioctl_errno = 0;
 
2093
    if(not get_flags(interface, &network)){
1642
2094
      ret_errno = errno;
1643
2095
      fprintf_plus(stderr, "Failed to get flags for interface "
1644
2096
                   "\"%s\"\n", interface);
 
2097
      errno = old_errno;
1645
2098
      return ret_errno;
1646
2099
    }
1647
 
    network.ifr_flags |= IFF_UP;
 
2100
    network.ifr_flags |= IFF_UP; /* set flag */
1648
2101
    
1649
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1650
 
    if(sd < 0){
 
2102
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
2103
    if(sd == -1){
1651
2104
      ret_errno = errno;
1652
2105
      perror_plus("socket");
1653
2106
      errno = old_errno;
1654
2107
      return ret_errno;
1655
2108
    }
1656
 
  
 
2109
    
1657
2110
    if(quit_now){
1658
 
      close(sd);
 
2111
      ret = close(sd);
 
2112
      if(ret == -1){
 
2113
        perror_plus("close");
 
2114
      }
1659
2115
      errno = old_errno;
1660
2116
      return EINTR;
1661
2117
    }
1665
2121
                   interface);
1666
2122
    }
1667
2123
    
1668
 
    /* Raise priviliges */
1669
 
    raise_privileges();
 
2124
    /* Raise privileges */
 
2125
    ret_errno = raise_privileges();
 
2126
    if(ret_errno != 0){
 
2127
      errno = ret_errno;
 
2128
      perror_plus("Failed to raise privileges");
 
2129
    }
1670
2130
    
1671
2131
#ifdef __linux__
1672
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1673
 
       messages about the network interface to mess up the prompt */
1674
 
    int ret_linux = klogctl(8, NULL, 5);
1675
 
    bool restore_loglevel = true;
1676
 
    if(ret_linux == -1){
1677
 
      restore_loglevel = false;
1678
 
      perror_plus("klogctl");
 
2132
    int ret_linux;
 
2133
    bool restore_loglevel = false;
 
2134
    if(ret_errno == 0){
 
2135
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
2136
         messages about the network interface to mess up the prompt */
 
2137
      ret_linux = klogctl(8, NULL, 5);
 
2138
      if(ret_linux == -1){
 
2139
        perror_plus("klogctl");
 
2140
      } else {
 
2141
        restore_loglevel = true;
 
2142
      }
1679
2143
    }
1680
2144
#endif  /* __linux__ */
1681
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1682
 
    ret_errno = errno;
 
2145
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
2146
    ioctl_errno = errno;
1683
2147
#ifdef __linux__
1684
2148
    if(restore_loglevel){
1685
2149
      ret_linux = klogctl(7, NULL, 0);
1689
2153
    }
1690
2154
#endif  /* __linux__ */
1691
2155
    
1692
 
    /* Lower privileges */
1693
 
    lower_privileges();
 
2156
    /* If raise_privileges() succeeded above */
 
2157
    if(ret_errno == 0){
 
2158
      /* Lower privileges */
 
2159
      ret_errno = lower_privileges();
 
2160
      if(ret_errno != 0){
 
2161
        errno = ret_errno;
 
2162
        perror_plus("Failed to lower privileges");
 
2163
      }
 
2164
    }
1694
2165
    
1695
2166
    /* Close the socket */
1696
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2167
    ret = close(sd);
1697
2168
    if(ret == -1){
1698
2169
      perror_plus("close");
1699
2170
    }
1700
2171
    
1701
2172
    if(ret_setflags == -1){
1702
 
      errno = ret_errno;
 
2173
      errno = ioctl_errno;
1703
2174
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1704
2175
      errno = old_errno;
1705
 
      return ret_errno;
 
2176
      return ioctl_errno;
1706
2177
    }
1707
2178
  } else if(debug){
1708
2179
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1726
2197
  return 0;
1727
2198
}
1728
2199
 
 
2200
__attribute__((nonnull, warn_unused_result))
1729
2201
error_t take_down_interface(const char *const interface){
1730
 
  int sd = -1;
1731
2202
  error_t old_errno = errno;
1732
 
  error_t ret_errno = 0;
1733
 
  int ret, ret_setflags;
1734
2203
  struct ifreq network;
1735
2204
  unsigned int if_index = if_nametoindex(interface);
1736
2205
  if(if_index == 0){
1739
2208
    return ENXIO;
1740
2209
  }
1741
2210
  if(interface_is_up(interface)){
 
2211
    error_t ret_errno = 0, ioctl_errno = 0;
1742
2212
    if(not get_flags(interface, &network) and debug){
1743
2213
      ret_errno = errno;
1744
2214
      fprintf_plus(stderr, "Failed to get flags for interface "
1745
2215
                   "\"%s\"\n", interface);
 
2216
      errno = old_errno;
1746
2217
      return ret_errno;
1747
2218
    }
1748
2219
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1749
2220
    
1750
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1751
 
    if(sd < 0){
 
2221
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
2222
    if(sd == -1){
1752
2223
      ret_errno = errno;
1753
2224
      perror_plus("socket");
1754
2225
      errno = old_errno;
1760
2231
                   interface);
1761
2232
    }
1762
2233
    
1763
 
    /* Raise priviliges */
1764
 
    raise_privileges();
1765
 
    
1766
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1767
 
    ret_errno = errno;
1768
 
    
1769
 
    /* Lower privileges */
1770
 
    lower_privileges();
 
2234
    /* Raise privileges */
 
2235
    ret_errno = raise_privileges();
 
2236
    if(ret_errno != 0){
 
2237
      errno = ret_errno;
 
2238
      perror_plus("Failed to raise privileges");
 
2239
    }
 
2240
    
 
2241
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
2242
    ioctl_errno = errno;
 
2243
    
 
2244
    /* If raise_privileges() succeeded above */
 
2245
    if(ret_errno == 0){
 
2246
      /* Lower privileges */
 
2247
      ret_errno = lower_privileges();
 
2248
      if(ret_errno != 0){
 
2249
        errno = ret_errno;
 
2250
        perror_plus("Failed to lower privileges");
 
2251
      }
 
2252
    }
1771
2253
    
1772
2254
    /* Close the socket */
1773
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2255
    int ret = close(sd);
1774
2256
    if(ret == -1){
1775
2257
      perror_plus("close");
1776
2258
    }
1777
2259
    
1778
2260
    if(ret_setflags == -1){
1779
 
      errno = ret_errno;
 
2261
      errno = ioctl_errno;
1780
2262
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1781
2263
      errno = old_errno;
1782
 
      return ret_errno;
 
2264
      return ioctl_errno;
1783
2265
    }
1784
2266
  } else if(debug){
1785
2267
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1791
2273
}
1792
2274
 
1793
2275
int main(int argc, char *argv[]){
1794
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1795
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1796
 
                        "+CTYPE-OPENPGP", .current_server = NULL, 
1797
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2276
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
2277
                        .priority = "SECURE256:!CTYPE-X.509"
 
2278
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2279
                        .current_server = NULL, .interfaces = NULL,
 
2280
                        .interfaces_size = 0 };
1798
2281
  AvahiSServiceBrowser *sb = NULL;
1799
2282
  error_t ret_errno;
1800
2283
  int ret;
1803
2286
  int exitcode = EXIT_SUCCESS;
1804
2287
  char *interfaces_to_take_down = NULL;
1805
2288
  size_t interfaces_to_take_down_size = 0;
1806
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1807
 
  bool tempdir_created = false;
 
2289
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
2290
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
2291
  char *tempdir = NULL;
1808
2292
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1809
2293
  const char *seckey = PATHDIR "/" SECKEY;
1810
2294
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2295
  const char *dh_params_file = NULL;
1811
2296
  char *interfaces_hooks = NULL;
1812
 
  size_t interfaces_hooks_size = 0;
1813
2297
  
1814
2298
  bool gnutls_initialized = false;
1815
2299
  bool gpgme_initialized = false;
1867
2351
        .doc = "Bit length of the prime number used in the"
1868
2352
        " Diffie-Hellman key exchange",
1869
2353
        .group = 2 },
 
2354
      { .name = "dh-params", .key = 134,
 
2355
        .arg = "FILE",
 
2356
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2357
        " for the Diffie-Hellman key exchange",
 
2358
        .group = 2 },
1870
2359
      { .name = "priority", .key = 130,
1871
2360
        .arg = "STRING",
1872
2361
        .doc = "GnuTLS priority string for the TLS handshake",
1927
2416
        }
1928
2417
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1929
2418
        break;
 
2419
      case 134:                 /* --dh-params */
 
2420
        dh_params_file = arg;
 
2421
        break;
1930
2422
      case 130:                 /* --priority */
1931
2423
        mc.priority = arg;
1932
2424
        break;
1988
2480
      goto end;
1989
2481
    }
1990
2482
  }
1991
 
    
 
2483
  
1992
2484
  {
1993
2485
    /* Work around Debian bug #633582:
1994
2486
       <http://bugs.debian.org/633582> */
1995
2487
    
1996
 
    /* Re-raise priviliges */
1997
 
    if(raise_privileges() == 0){
 
2488
    /* Re-raise privileges */
 
2489
    ret_errno = raise_privileges();
 
2490
    if(ret_errno != 0){
 
2491
      errno = ret_errno;
 
2492
      perror_plus("Failed to raise privileges");
 
2493
    } else {
1998
2494
      struct stat st;
1999
2495
      
2000
2496
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2014
2510
              }
2015
2511
            }
2016
2512
          }
2017
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2513
          close(seckey_fd);
2018
2514
        }
2019
2515
      }
2020
 
    
 
2516
      
2021
2517
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2022
2518
        int pubkey_fd = open(pubkey, O_RDONLY);
2023
2519
        if(pubkey_fd == -1){
2035
2531
              }
2036
2532
            }
2037
2533
          }
2038
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2039
 
        }
2040
 
      }
2041
 
    
 
2534
          close(pubkey_fd);
 
2535
        }
 
2536
      }
 
2537
      
 
2538
      if(dh_params_file != NULL
 
2539
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2540
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2541
        if(dhparams_fd == -1){
 
2542
          perror_plus("open");
 
2543
        } else {
 
2544
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2545
          if(ret == -1){
 
2546
            perror_plus("fstat");
 
2547
          } else {
 
2548
            if(S_ISREG(st.st_mode)
 
2549
               and st.st_uid == 0 and st.st_gid == 0){
 
2550
              ret = fchown(dhparams_fd, uid, gid);
 
2551
              if(ret == -1){
 
2552
                perror_plus("fchown");
 
2553
              }
 
2554
            }
 
2555
          }
 
2556
          close(dhparams_fd);
 
2557
        }
 
2558
      }
 
2559
      
2042
2560
      /* Lower privileges */
2043
 
      lower_privileges();
 
2561
      ret_errno = lower_privileges();
 
2562
      if(ret_errno != 0){
 
2563
        errno = ret_errno;
 
2564
        perror_plus("Failed to lower privileges");
 
2565
      }
2044
2566
    }
2045
2567
  }
2046
2568
  
2070
2592
        goto end;
2071
2593
      }
2072
2594
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2073
 
      interfaces_hooks_size = mc.interfaces_size;
2074
 
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
2075
 
                     (int)',');
2076
 
    }
2077
 
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
2078
 
                             interfaces_hooks : "", delay)){
2079
 
      goto end;
2080
 
    }
 
2595
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2596
    }
 
2597
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2598
                      interfaces_hooks : "", delay);
2081
2599
  }
2082
2600
  
2083
2601
  if(not debug){
2161
2679
  
2162
2680
  /* If no interfaces were specified, make a list */
2163
2681
  if(mc.interfaces == NULL){
2164
 
    struct dirent **direntries;
 
2682
    struct dirent **direntries = NULL;
2165
2683
    /* Look for any good interfaces */
2166
2684
    ret = scandir(sys_class_net, &direntries, good_interface,
2167
2685
                  alphasort);
2171
2689
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2172
2690
                             direntries[i]->d_name);
2173
2691
        if(ret_errno != 0){
 
2692
          errno = ret_errno;
2174
2693
          perror_plus("argz_add");
 
2694
          free(direntries[i]);
2175
2695
          continue;
2176
2696
        }
2177
2697
        if(debug){
2178
2698
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2179
2699
                       direntries[i]->d_name);
2180
2700
        }
 
2701
        free(direntries[i]);
2181
2702
      }
2182
2703
      free(direntries);
2183
2704
    } else {
2184
 
      free(direntries);
 
2705
      if(ret == 0){
 
2706
        free(direntries);
 
2707
      }
2185
2708
      fprintf_plus(stderr, "Could not find a network interface\n");
2186
2709
      exitcode = EXIT_FAILURE;
2187
2710
      goto end;
2210
2733
        break;
2211
2734
      }
2212
2735
      bool interface_was_up = interface_is_up(interface);
2213
 
      ret = bring_up_interface(interface, delay);
 
2736
      errno = bring_up_interface(interface, delay);
2214
2737
      if(not interface_was_up){
2215
 
        if(ret != 0){
2216
 
          errno = ret;
2217
 
          perror_plus("Failed to bring up interface");
 
2738
        if(errno != 0){
 
2739
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2740
                       " %s\n", interface, strerror(errno));
2218
2741
        } else {
2219
 
          ret_errno = argz_add(&interfaces_to_take_down,
2220
 
                               &interfaces_to_take_down_size,
2221
 
                               interface);
 
2742
          errno = argz_add(&interfaces_to_take_down,
 
2743
                           &interfaces_to_take_down_size,
 
2744
                           interface);
 
2745
          if(errno != 0){
 
2746
            perror_plus("argz_add");
 
2747
          }
2222
2748
        }
2223
2749
      }
2224
2750
    }
2240
2766
    goto end;
2241
2767
  }
2242
2768
  
2243
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2769
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2244
2770
  if(ret == -1){
2245
2771
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2246
2772
    exitcode = EX_UNAVAILABLE;
2253
2779
    goto end;
2254
2780
  }
2255
2781
  
2256
 
  if(mkdtemp(tempdir) == NULL){
 
2782
  /* Try /run/tmp before /tmp */
 
2783
  tempdir = mkdtemp(run_tempdir);
 
2784
  if(tempdir == NULL and errno == ENOENT){
 
2785
      if(debug){
 
2786
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2787
                     run_tempdir, old_tempdir);
 
2788
      }
 
2789
      tempdir = mkdtemp(old_tempdir);
 
2790
  }
 
2791
  if(tempdir == NULL){
2257
2792
    perror_plus("mkdtemp");
2258
2793
    goto end;
2259
2794
  }
2260
 
  tempdir_created = true;
2261
2795
  
2262
2796
  if(quit_now){
2263
2797
    goto end;
2338
2872
      sleep((unsigned int)retry_interval);
2339
2873
    }
2340
2874
    
2341
 
    if (not quit_now){
 
2875
    if(not quit_now){
2342
2876
      exitcode = EXIT_SUCCESS;
2343
2877
    }
2344
2878
    
2399
2933
  if(debug){
2400
2934
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2401
2935
  }
2402
 
 
 
2936
  
2403
2937
  ret = avahi_loop_with_timeout(simple_poll,
2404
2938
                                (int)(retry_interval * 1000), &mc);
2405
2939
  if(debug){
2427
2961
  
2428
2962
  if(gnutls_initialized){
2429
2963
    gnutls_certificate_free_credentials(mc.cred);
2430
 
    gnutls_global_deinit();
2431
2964
    gnutls_dh_params_deinit(mc.dh_params);
2432
2965
  }
2433
2966
  
2441
2974
    mc.current_server->prev->next = NULL;
2442
2975
    while(mc.current_server != NULL){
2443
2976
      server *next = mc.current_server->next;
 
2977
#ifdef __GNUC__
 
2978
#pragma GCC diagnostic push
 
2979
#pragma GCC diagnostic ignored "-Wcast-qual"
 
2980
#endif
 
2981
      free((char *)(mc.current_server->ip));
 
2982
#ifdef __GNUC__
 
2983
#pragma GCC diagnostic pop
 
2984
#endif
2444
2985
      free(mc.current_server);
2445
2986
      mc.current_server = next;
2446
2987
    }
2447
2988
  }
2448
2989
  
2449
 
  /* Re-raise priviliges */
 
2990
  /* Re-raise privileges */
2450
2991
  {
2451
 
    raise_privileges();
2452
 
    
2453
 
    /* Run network hooks */
2454
 
    run_network_hooks("stop", interfaces_hooks != NULL ?
2455
 
                      interfaces_hooks : "", delay);
2456
 
    
2457
 
    /* Take down the network interfaces which were brought up */
2458
 
    {
2459
 
      char *interface = NULL;
2460
 
      while((interface=argz_next(interfaces_to_take_down,
2461
 
                                 interfaces_to_take_down_size,
2462
 
                                 interface))){
2463
 
        ret_errno = take_down_interface(interface);
2464
 
        if(ret_errno != 0){
2465
 
          errno = ret_errno;
2466
 
          perror_plus("Failed to take down interface");
2467
 
        }
2468
 
      }
2469
 
      if(debug and (interfaces_to_take_down == NULL)){
2470
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2471
 
                     " down\n");
2472
 
      }
2473
 
    }
2474
 
    
2475
 
    lower_privileges_permanently();
 
2992
    ret_errno = raise_privileges();
 
2993
    if(ret_errno != 0){
 
2994
      errno = ret_errno;
 
2995
      perror_plus("Failed to raise privileges");
 
2996
    } else {
 
2997
      
 
2998
      /* Run network hooks */
 
2999
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
3000
                        interfaces_hooks : "", delay);
 
3001
      
 
3002
      /* Take down the network interfaces which were brought up */
 
3003
      {
 
3004
        char *interface = NULL;
 
3005
        while((interface=argz_next(interfaces_to_take_down,
 
3006
                                   interfaces_to_take_down_size,
 
3007
                                   interface))){
 
3008
          ret_errno = take_down_interface(interface);
 
3009
          if(ret_errno != 0){
 
3010
            errno = ret_errno;
 
3011
            perror_plus("Failed to take down interface");
 
3012
          }
 
3013
        }
 
3014
        if(debug and (interfaces_to_take_down == NULL)){
 
3015
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
3016
                       " down\n");
 
3017
        }
 
3018
      }
 
3019
    }
 
3020
    
 
3021
    ret_errno = lower_privileges_permanently();
 
3022
    if(ret_errno != 0){
 
3023
      errno = ret_errno;
 
3024
      perror_plus("Failed to lower privileges permanently");
 
3025
    }
2476
3026
  }
2477
3027
  
2478
3028
  free(interfaces_to_take_down);
2479
3029
  free(interfaces_hooks);
2480
3030
  
 
3031
  void clean_dir_at(int base, const char * const dirname,
 
3032
                    uintmax_t level){
 
3033
    struct dirent **direntries = NULL;
 
3034
    int dret;
 
3035
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
 
3036
                                                O_RDONLY
 
3037
                                                | O_NOFOLLOW
 
3038
                                                | O_DIRECTORY
 
3039
                                                | O_PATH));
 
3040
    if(dir_fd == -1){
 
3041
      perror_plus("open");
 
3042
    }
 
3043
    int numentries = scandirat(dir_fd, ".", &direntries,
 
3044
                               notdotentries, alphasort);
 
3045
    if(numentries >= 0){
 
3046
      for(int i = 0; i < numentries; i++){
 
3047
        if(debug){
 
3048
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
 
3049
                       dirname, direntries[i]->d_name);
 
3050
        }
 
3051
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
 
3052
        if(dret == -1){
 
3053
          if(errno == EISDIR){
 
3054
              dret = unlinkat(dir_fd, direntries[i]->d_name,
 
3055
                              AT_REMOVEDIR);
 
3056
          }         
 
3057
          if((dret == -1) and (errno == ENOTEMPTY)
 
3058
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
 
3059
                  == 0) and (level == 0)){
 
3060
            /* Recurse only in this special case */
 
3061
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
 
3062
            dret = 0;
 
3063
          }
 
3064
          if(dret == -1){
 
3065
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
 
3066
                         direntries[i]->d_name, strerror(errno));
 
3067
          }
 
3068
        }
 
3069
        free(direntries[i]);
 
3070
      }
 
3071
      
 
3072
      /* need to clean even if 0 because man page doesn't specify */
 
3073
      free(direntries);
 
3074
      if(numentries == -1){
 
3075
        perror_plus("scandirat");
 
3076
      }
 
3077
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
 
3078
      if(dret == -1 and errno != ENOENT){
 
3079
        perror_plus("rmdir");
 
3080
      }
 
3081
    } else {
 
3082
      perror_plus("scandirat");
 
3083
    }
 
3084
    close(dir_fd);
 
3085
  }
 
3086
  
2481
3087
  /* Removes the GPGME temp directory and all files inside */
2482
 
  if(tempdir_created){
2483
 
    struct dirent **direntries = NULL;
2484
 
    struct dirent *direntry = NULL;
2485
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2486
 
                             alphasort);
2487
 
    if (numentries > 0){
2488
 
      for(int i = 0; i < numentries; i++){
2489
 
        direntry = direntries[i];
2490
 
        char *fullname = NULL;
2491
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2492
 
                       direntry->d_name);
2493
 
        if(ret < 0){
2494
 
          perror_plus("asprintf");
2495
 
          continue;
2496
 
        }
2497
 
        ret = remove(fullname);
2498
 
        if(ret == -1){
2499
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2500
 
                       strerror(errno));
2501
 
        }
2502
 
        free(fullname);
2503
 
      }
2504
 
    }
2505
 
 
2506
 
    /* need to clean even if 0 because man page doesn't specify */
2507
 
    free(direntries);
2508
 
    if (numentries == -1){
2509
 
      perror_plus("scandir");
2510
 
    }
2511
 
    ret = rmdir(tempdir);
2512
 
    if(ret == -1 and errno != ENOENT){
2513
 
      perror_plus("rmdir");
2514
 
    }
 
3088
  if(tempdir != NULL){
 
3089
    clean_dir_at(-1, tempdir, 0);
2515
3090
  }
2516
3091
  
2517
3092
  if(quit_now){