/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2016-02-28 20:34:59 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 333.
  • Revision ID: teddy@recompile.se-20160228203459-81vtqvr96yukyrok
Client: Remove calls to gnutls_global_init and gnutls_global_deinit

* plugins.d/mandos-client.c (init_gnutls_global, main): Don't call
  gnutls_global_init or gnutls_global_deinit anymore; these are
  unnecessary in GnuTLS 3.3.

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