/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-03-10 06:34:36 UTC
  • Revision ID: teddy@recompile.se-20140310063436-zksdghqvv6k1pbyg
Do not add a new server to server list if clock_gettime() fails

* plugins.d/mandos-client.c (add_server): Set server.last_seen before
                                          adding new server, in case
                                          clock_gettime() fails.

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-2018 Teddy Hogeborn
13
 
 * Copyright © 2008-2018 Björn Påhlsson
14
 
 * 
15
 
 * This file is part of Mandos.
16
 
 * 
17
 
 * Mandos is free software: you can redistribute it and/or modify it
18
 
 * under the terms of the GNU General Public License as published by
19
 
 * the Free Software Foundation, either version 3 of the License, or
20
 
 * (at your option) any later version.
21
 
 * 
22
 
 * Mandos is distributed in the hope that it will be useful, but
 
12
 * Copyright © 2008-2013 Teddy Hogeborn
 
13
 * Copyright © 2008-2013 Björn Påhlsson
 
14
 * 
 
15
 * This program is free software: you can redistribute it and/or
 
16
 * modify it under the terms of the GNU General Public License as
 
17
 * published by the Free Software Foundation, either version 3 of the
 
18
 * License, or (at your option) any later version.
 
19
 * 
 
20
 * This program is distributed in the hope that it will be useful, but
23
21
 * WITHOUT ANY WARRANTY; without even the implied warranty of
24
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
23
 * General Public License for more details.
26
24
 * 
27
25
 * You should have received a copy of the GNU General Public License
28
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
26
 * along with this program.  If not, see
 
27
 * <http://www.gnu.org/licenses/>.
29
28
 * 
30
29
 * Contact the authors at <mandos@recompile.se>.
31
30
 */
33
32
/* Needed by GPGME, specifically gpgme_data_seek() */
34
33
#ifndef _LARGEFILE_SOURCE
35
34
#define _LARGEFILE_SOURCE
36
 
#endif  /* not _LARGEFILE_SOURCE */
 
35
#endif
37
36
#ifndef _FILE_OFFSET_BITS
38
37
#define _FILE_OFFSET_BITS 64
39
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
40
39
 
41
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
42
41
 
43
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
44
 
                                   stdout, ferror() */
 
43
                                   stdout, ferror(), remove() */
45
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
46
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
47
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
48
47
                                   strtof(), abort() */
49
48
#include <stdbool.h>            /* bool, false, true */
50
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
51
 
                                   asprintf(), strncpy(), strsignal()
52
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
53
51
#include <sys/ioctl.h>          /* ioctl */
54
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
55
53
                                   sockaddr_in6, PF_INET6,
59
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
60
58
                                   inet_pton(), connect(),
61
59
                                   getnameinfo() */
62
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open() */
63
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
64
62
                                 */
65
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
66
64
                                   strtoimax() */
67
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
68
 
                                   EAI_SYSTEM, ENETUNREACH,
69
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
70
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
71
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
72
66
                                   program_invocation_short_name */
73
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
79
73
                                */
80
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
81
75
                                   getuid(), getgid(), seteuid(),
82
 
                                   setgid(), pause(), _exit(),
83
 
                                   unlinkat() */
 
76
                                   setgid(), pause(), _exit() */
84
77
#include <arpa/inet.h>          /* inet_pton(), htons() */
85
78
#include <iso646.h>             /* not, or, and */
86
79
#include <argp.h>               /* struct argp_option, error_t, struct
148
141
static const char sys_class_net[] = "/sys/class/net";
149
142
char *connect_to = NULL;
150
143
const char *hookdir = HOOKDIR;
151
 
int hookdir_fd = -1;
152
144
uid_t uid = 65534;
153
145
gid_t gid = 65534;
154
146
 
191
183
  perror(print_text);
192
184
}
193
185
 
194
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
186
__attribute__((format (gnu_printf, 2, 3)))
195
187
int fprintf_plus(FILE *stream, const char *format, ...){
196
188
  va_list ap;
197
189
  va_start (ap, format);
206
198
 * bytes. "buffer_capacity" is how much is currently allocated,
207
199
 * "buffer_length" is how much is already used.
208
200
 */
209
 
__attribute__((nonnull, warn_unused_result))
210
201
size_t incbuffer(char **buffer, size_t buffer_length,
211
202
                 size_t buffer_capacity){
212
203
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
225
216
}
226
217
 
227
218
/* Add server to set of servers to retry periodically */
228
 
__attribute__((nonnull, warn_unused_result))
229
219
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
230
220
                int af, server **current_server){
231
221
  int ret;
240
230
                          .af = af };
241
231
  if(new_server->ip == NULL){
242
232
    perror_plus("strdup");
243
 
    free(new_server);
244
233
    return false;
245
234
  }
246
235
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
247
236
  if(ret == -1){
248
237
    perror_plus("clock_gettime");
249
 
#ifdef __GNUC__
250
 
#pragma GCC diagnostic push
251
 
#pragma GCC diagnostic ignored "-Wcast-qual"
252
 
#endif
253
 
    free((char *)(new_server->ip));
254
 
#ifdef __GNUC__
255
 
#pragma GCC diagnostic pop
256
 
#endif
257
 
    free(new_server);
258
238
    return false;
259
239
  }
260
240
  /* Special case of first server */
262
242
    new_server->next = new_server;
263
243
    new_server->prev = new_server;
264
244
    *current_server = new_server;
 
245
  /* Place the new server last in the list */
265
246
  } else {
266
 
    /* Place the new server last in the list */
267
247
    new_server->next = *current_server;
268
248
    new_server->prev = (*current_server)->prev;
269
249
    new_server->prev->next = new_server;
275
255
/* 
276
256
 * Initialize GPGME.
277
257
 */
278
 
__attribute__((nonnull, warn_unused_result))
279
 
static bool init_gpgme(const char * const seckey,
280
 
                       const char * const pubkey,
281
 
                       const char * const tempdir,
282
 
                       mandos_context *mc){
 
258
static bool init_gpgme(const char *seckey, const char *pubkey,
 
259
                       const char *tempdir, mandos_context *mc){
283
260
  gpgme_error_t rc;
284
261
  gpgme_engine_info_t engine_info;
285
262
  
286
263
  /*
287
264
   * Helper function to insert pub and seckey to the engine keyring.
288
265
   */
289
 
  bool import_key(const char * const filename){
 
266
  bool import_key(const char *filename){
290
267
    int ret;
291
268
    int fd;
292
269
    gpgme_data_t pgp_data;
311
288
      return false;
312
289
    }
313
290
    
314
 
    ret = close(fd);
 
291
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
315
292
    if(ret == -1){
316
293
      perror_plus("close");
317
294
    }
373
350
 * Decrypt OpenPGP data.
374
351
 * Returns -1 on error
375
352
 */
376
 
__attribute__((nonnull, warn_unused_result))
377
353
static ssize_t pgp_packet_decrypt(const char *cryptotext,
378
354
                                  size_t crypto_size,
379
355
                                  char **plaintext,
499
475
  return plaintext_length;
500
476
}
501
477
 
502
 
__attribute__((warn_unused_result, const))
503
 
static const char *safe_string(const char *str){
504
 
  if(str == NULL)
505
 
    return "(unknown)";
506
 
  return str;
507
 
}
508
 
 
509
 
__attribute__((warn_unused_result))
510
 
static const char *safer_gnutls_strerror(int value){
 
478
static const char * safer_gnutls_strerror(int value){
511
479
  const char *ret = gnutls_strerror(value);
512
 
  return safe_string(ret);
 
480
  if(ret == NULL)
 
481
    ret = "(unknown)";
 
482
  return ret;
513
483
}
514
484
 
515
485
/* GnuTLS log function callback */
516
 
__attribute__((nonnull))
517
486
static void debuggnutls(__attribute__((unused)) int level,
518
487
                        const char* string){
519
488
  fprintf_plus(stderr, "GnuTLS: %s", string);
520
489
}
521
490
 
522
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
523
491
static int init_gnutls_global(const char *pubkeyfilename,
524
492
                              const char *seckeyfilename,
525
 
                              const char *dhparamsfilename,
526
493
                              mandos_context *mc){
527
494
  int ret;
528
 
  unsigned int uret;
529
495
  
530
496
  if(debug){
531
497
    fprintf_plus(stderr, "Initializing GnuTLS\n");
532
498
  }
533
499
  
 
500
  ret = gnutls_global_init();
 
501
  if(ret != GNUTLS_E_SUCCESS){
 
502
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
503
                 safer_gnutls_strerror(ret));
 
504
    return -1;
 
505
  }
 
506
  
534
507
  if(debug){
535
508
    /* "Use a log level over 10 to enable all debugging options."
536
509
     * - GnuTLS manual
544
517
  if(ret != GNUTLS_E_SUCCESS){
545
518
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
546
519
                 safer_gnutls_strerror(ret));
 
520
    gnutls_global_deinit();
547
521
    return -1;
548
522
  }
549
523
  
574
548
                 safer_gnutls_strerror(ret));
575
549
    goto globalfail;
576
550
  }
577
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
578
 
  if(dhparamsfilename != NULL){
579
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
580
 
    do {
581
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
582
 
      if(dhpfile == -1){
583
 
        perror_plus("open");
584
 
        dhparamsfilename = NULL;
585
 
        break;
586
 
      }
587
 
      size_t params_capacity = 0;
588
 
      while(true){
589
 
        params_capacity = incbuffer((char **)&params.data,
590
 
                                    (size_t)params.size,
591
 
                                    (size_t)params_capacity);
592
 
        if(params_capacity == 0){
593
 
          perror_plus("incbuffer");
594
 
          free(params.data);
595
 
          params.data = NULL;
596
 
          dhparamsfilename = NULL;
597
 
          break;
598
 
        }
599
 
        ssize_t bytes_read = read(dhpfile,
600
 
                                  params.data + params.size,
601
 
                                  BUFFER_SIZE);
602
 
        /* EOF */
603
 
        if(bytes_read == 0){
604
 
          break;
605
 
        }
606
 
        /* check bytes_read for failure */
607
 
        if(bytes_read < 0){
608
 
          perror_plus("read");
609
 
          free(params.data);
610
 
          params.data = NULL;
611
 
          dhparamsfilename = NULL;
612
 
          break;
613
 
        }
614
 
        params.size += (unsigned int)bytes_read;
615
 
      }
616
 
      close(dhpfile);
617
 
      if(params.data == NULL){
618
 
        dhparamsfilename = NULL;
619
 
      }
620
 
      if(dhparamsfilename == NULL){
621
 
        break;
622
 
      }
623
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
624
 
                                          GNUTLS_X509_FMT_PEM);
625
 
      if(ret != GNUTLS_E_SUCCESS){
626
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
627
 
                     " \"%s\": %s\n", dhparamsfilename,
628
 
                     safer_gnutls_strerror(ret));
629
 
        dhparamsfilename = NULL;
630
 
      }
631
 
      free(params.data);
632
 
    } while(false);
633
 
  }
634
 
  if(dhparamsfilename == NULL){
635
 
    if(mc->dh_bits == 0){
636
 
      /* Find out the optimal number of DH bits */
637
 
      /* Try to read the private key file */
638
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
639
 
      do {
640
 
        int secfile = open(seckeyfilename, O_RDONLY);
641
 
        if(secfile == -1){
642
 
          perror_plus("open");
643
 
          break;
644
 
        }
645
 
        size_t buffer_capacity = 0;
646
 
        while(true){
647
 
          buffer_capacity = incbuffer((char **)&buffer.data,
648
 
                                      (size_t)buffer.size,
649
 
                                      (size_t)buffer_capacity);
650
 
          if(buffer_capacity == 0){
651
 
            perror_plus("incbuffer");
652
 
            free(buffer.data);
653
 
            buffer.data = NULL;
654
 
            break;
655
 
          }
656
 
          ssize_t bytes_read = read(secfile,
657
 
                                    buffer.data + buffer.size,
658
 
                                    BUFFER_SIZE);
659
 
          /* EOF */
660
 
          if(bytes_read == 0){
661
 
            break;
662
 
          }
663
 
          /* check bytes_read for failure */
664
 
          if(bytes_read < 0){
665
 
            perror_plus("read");
666
 
            free(buffer.data);
667
 
            buffer.data = NULL;
668
 
            break;
669
 
          }
670
 
          buffer.size += (unsigned int)bytes_read;
671
 
        }
672
 
        close(secfile);
673
 
      } while(false);
674
 
      /* If successful, use buffer to parse private key */
675
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
676
 
      if(buffer.data != NULL){
677
 
        {
678
 
          gnutls_openpgp_privkey_t privkey = NULL;
679
 
          ret = gnutls_openpgp_privkey_init(&privkey);
680
 
          if(ret != GNUTLS_E_SUCCESS){
681
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
682
 
                         " structure: %s",
683
 
                         safer_gnutls_strerror(ret));
684
 
            free(buffer.data);
685
 
            buffer.data = NULL;
686
 
          } else {
687
 
            ret = gnutls_openpgp_privkey_import
688
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
689
 
            if(ret != GNUTLS_E_SUCCESS){
690
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
691
 
                           safer_gnutls_strerror(ret));
692
 
              privkey = NULL;
693
 
            }
694
 
            free(buffer.data);
695
 
            buffer.data = NULL;
696
 
            if(privkey != NULL){
697
 
              /* Use private key to suggest an appropriate
698
 
                 sec_param */
699
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
700
 
              gnutls_openpgp_privkey_deinit(privkey);
701
 
              if(debug){
702
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
703
 
                             " a GnuTLS security parameter \"%s\".\n",
704
 
                             safe_string(gnutls_sec_param_get_name
705
 
                                         (sec_param)));
706
 
              }
707
 
            }
708
 
          }
709
 
        }
710
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
711
 
          /* Err on the side of caution */
712
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
713
 
          if(debug){
714
 
            fprintf_plus(stderr, "Falling back to security parameter"
715
 
                         " \"%s\"\n",
716
 
                         safe_string(gnutls_sec_param_get_name
717
 
                                     (sec_param)));
718
 
          }
719
 
        }
720
 
      }
721
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
722
 
      if(uret != 0){
723
 
        mc->dh_bits = uret;
724
 
        if(debug){
725
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
726
 
                       " implies %u DH bits; using that.\n",
727
 
                       safe_string(gnutls_sec_param_get_name
728
 
                                   (sec_param)),
729
 
                       mc->dh_bits);
730
 
        }
731
 
      } else {
732
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
733
 
                     " bits for security parameter \"%s\"): %s\n",
734
 
                     safe_string(gnutls_sec_param_get_name
735
 
                                 (sec_param)),
736
 
                     safer_gnutls_strerror(ret));
737
 
        goto globalfail;
738
 
      }
739
 
    } else if(debug){
740
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
741
 
                   mc->dh_bits);
742
 
    }
743
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
744
 
    if(ret != GNUTLS_E_SUCCESS){
745
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
746
 
                   " bits): %s\n", mc->dh_bits,
747
 
                   safer_gnutls_strerror(ret));
748
 
      goto globalfail;
749
 
    }
750
 
  }
 
551
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
552
  if(ret != GNUTLS_E_SUCCESS){
 
553
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
554
                 safer_gnutls_strerror(ret));
 
555
    goto globalfail;
 
556
  }
 
557
  
751
558
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
752
559
  
753
560
  return 0;
755
562
 globalfail:
756
563
  
757
564
  gnutls_certificate_free_credentials(mc->cred);
 
565
  gnutls_global_deinit();
758
566
  gnutls_dh_params_deinit(mc->dh_params);
759
567
  return -1;
760
568
}
761
569
 
762
 
__attribute__((nonnull, warn_unused_result))
763
570
static int init_gnutls_session(gnutls_session_t *session,
764
571
                               mandos_context *mc){
765
572
  int ret;
812
619
  /* ignore client certificate if any. */
813
620
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
814
621
  
 
622
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
623
  
815
624
  return 0;
816
625
}
817
626
 
819
628
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
820
629
                      __attribute__((unused)) const char *txt){}
821
630
 
822
 
/* Set effective uid to 0, return errno */
823
 
__attribute__((warn_unused_result))
824
 
int raise_privileges(void){
825
 
  int old_errno = errno;
826
 
  int ret = 0;
827
 
  if(seteuid(0) == -1){
828
 
    ret = errno;
829
 
  }
830
 
  errno = old_errno;
831
 
  return ret;
832
 
}
833
 
 
834
 
/* Set effective and real user ID to 0.  Return errno. */
835
 
__attribute__((warn_unused_result))
836
 
int raise_privileges_permanently(void){
837
 
  int old_errno = errno;
838
 
  int ret = raise_privileges();
839
 
  if(ret != 0){
840
 
    errno = old_errno;
841
 
    return ret;
842
 
  }
843
 
  if(setuid(0) == -1){
844
 
    ret = errno;
845
 
  }
846
 
  errno = old_errno;
847
 
  return ret;
848
 
}
849
 
 
850
 
/* Set effective user ID to unprivileged saved user ID */
851
 
__attribute__((warn_unused_result))
852
 
int lower_privileges(void){
853
 
  int old_errno = errno;
854
 
  int ret = 0;
855
 
  if(seteuid(uid) == -1){
856
 
    ret = errno;
857
 
  }
858
 
  errno = old_errno;
859
 
  return ret;
860
 
}
861
 
 
862
 
/* Lower privileges permanently */
863
 
__attribute__((warn_unused_result))
864
 
int lower_privileges_permanently(void){
865
 
  int old_errno = errno;
866
 
  int ret = 0;
867
 
  if(setuid(uid) == -1){
868
 
    ret = errno;
869
 
  }
870
 
  errno = old_errno;
871
 
  return ret;
872
 
}
873
 
 
874
 
/* Helper function to add_local_route() and delete_local_route() */
875
 
__attribute__((nonnull, warn_unused_result))
876
 
static bool add_delete_local_route(const bool add,
877
 
                                   const char *address,
878
 
                                   AvahiIfIndex if_index){
879
 
  int ret;
880
 
  char helper[] = "mandos-client-iprouteadddel";
881
 
  char add_arg[] = "add";
882
 
  char delete_arg[] = "delete";
883
 
  char debug_flag[] = "--debug";
884
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
885
 
  if(pluginhelperdir == NULL){
886
 
    if(debug){
887
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
888
 
                   " variable not set; cannot run helper\n");
889
 
    }
890
 
    return false;
891
 
  }
892
 
  
893
 
  char interface[IF_NAMESIZE];
894
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
895
 
    perror_plus("if_indextoname");
896
 
    return false;
897
 
  }
898
 
  
899
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
900
 
  if(devnull == -1){
901
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
902
 
    return false;
903
 
  }
904
 
  pid_t pid = fork();
905
 
  if(pid == 0){
906
 
    /* Child */
907
 
    /* Raise privileges */
908
 
    errno = raise_privileges_permanently();
909
 
    if(errno != 0){
910
 
      perror_plus("Failed to raise privileges");
911
 
      /* _exit(EX_NOPERM); */
912
 
    } else {
913
 
      /* Set group */
914
 
      errno = 0;
915
 
      ret = setgid(0);
916
 
      if(ret == -1){
917
 
        perror_plus("setgid");
918
 
        _exit(EX_NOPERM);
919
 
      }
920
 
      /* Reset supplementary groups */
921
 
      errno = 0;
922
 
      ret = setgroups(0, NULL);
923
 
      if(ret == -1){
924
 
        perror_plus("setgroups");
925
 
        _exit(EX_NOPERM);
926
 
      }
927
 
    }
928
 
    ret = dup2(devnull, STDIN_FILENO);
929
 
    if(ret == -1){
930
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
931
 
      _exit(EX_OSERR);
932
 
    }
933
 
    ret = close(devnull);
934
 
    if(ret == -1){
935
 
      perror_plus("close");
936
 
      _exit(EX_OSERR);
937
 
    }
938
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
939
 
    if(ret == -1){
940
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
941
 
      _exit(EX_OSERR);
942
 
    }
943
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
944
 
                                                    O_RDONLY
945
 
                                                    | O_DIRECTORY
946
 
                                                    | O_PATH
947
 
                                                    | O_CLOEXEC));
948
 
    if(helperdir_fd == -1){
949
 
      perror_plus("open");
950
 
      _exit(EX_UNAVAILABLE);
951
 
    }
952
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
953
 
                                                   helper, O_RDONLY));
954
 
    if(helper_fd == -1){
955
 
      perror_plus("openat");
956
 
      close(helperdir_fd);
957
 
      _exit(EX_UNAVAILABLE);
958
 
    }
959
 
    close(helperdir_fd);
960
 
#ifdef __GNUC__
961
 
#pragma GCC diagnostic push
962
 
#pragma GCC diagnostic ignored "-Wcast-qual"
963
 
#endif
964
 
    if(fexecve(helper_fd, (char *const [])
965
 
               { helper, add ? add_arg : delete_arg, (char *)address,
966
 
                   interface, debug ? debug_flag : NULL, NULL },
967
 
               environ) == -1){
968
 
#ifdef __GNUC__
969
 
#pragma GCC diagnostic pop
970
 
#endif
971
 
      perror_plus("fexecve");
972
 
      _exit(EXIT_FAILURE);
973
 
    }
974
 
  }
975
 
  if(pid == -1){
976
 
    perror_plus("fork");
977
 
    return false;
978
 
  }
979
 
  int status;
980
 
  pid_t pret = -1;
981
 
  errno = 0;
982
 
  do {
983
 
    pret = waitpid(pid, &status, 0);
984
 
    if(pret == -1 and errno == EINTR and quit_now){
985
 
      int errno_raising = 0;
986
 
      if((errno = raise_privileges()) != 0){
987
 
        errno_raising = errno;
988
 
        perror_plus("Failed to raise privileges in order to"
989
 
                    " kill helper program");
990
 
      }
991
 
      if(kill(pid, SIGTERM) == -1){
992
 
        perror_plus("kill");
993
 
      }
994
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
995
 
        perror_plus("Failed to lower privileges after killing"
996
 
                    " helper program");
997
 
      }
998
 
      return false;
999
 
    }
1000
 
  } while(pret == -1 and errno == EINTR);
1001
 
  if(pret == -1){
1002
 
    perror_plus("waitpid");
1003
 
    return false;
1004
 
  }
1005
 
  if(WIFEXITED(status)){
1006
 
    if(WEXITSTATUS(status) != 0){
1007
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1008
 
                   " with status %d\n", WEXITSTATUS(status));
1009
 
      return false;
1010
 
    }
1011
 
    return true;
1012
 
  }
1013
 
  if(WIFSIGNALED(status)){
1014
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1015
 
                 " signal %d\n", WTERMSIG(status));
1016
 
    return false;
1017
 
  }
1018
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1019
 
  return false;
1020
 
}
1021
 
 
1022
 
__attribute__((nonnull, warn_unused_result))
1023
 
static bool add_local_route(const char *address,
1024
 
                            AvahiIfIndex if_index){
1025
 
  if(debug){
1026
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1027
 
  }
1028
 
  return add_delete_local_route(true, address, if_index);
1029
 
}
1030
 
 
1031
 
__attribute__((nonnull, warn_unused_result))
1032
 
static bool delete_local_route(const char *address,
1033
 
                               AvahiIfIndex if_index){
1034
 
  if(debug){
1035
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1036
 
  }
1037
 
  return add_delete_local_route(false, address, if_index);
1038
 
}
1039
 
 
1040
631
/* Called when a Mandos server is found */
1041
 
__attribute__((nonnull, warn_unused_result))
1042
632
static int start_mandos_communication(const char *ip, in_port_t port,
1043
633
                                      AvahiIfIndex if_index,
1044
634
                                      int af, mandos_context *mc){
1045
635
  int ret, tcp_sd = -1;
1046
636
  ssize_t sret;
1047
 
  struct sockaddr_storage to;
 
637
  union {
 
638
    struct sockaddr_in in;
 
639
    struct sockaddr_in6 in6;
 
640
  } to;
1048
641
  char *buffer = NULL;
1049
642
  char *decrypted_buffer = NULL;
1050
643
  size_t buffer_length = 0;
1053
646
  int retval = -1;
1054
647
  gnutls_session_t session;
1055
648
  int pf;                       /* Protocol family */
1056
 
  bool route_added = false;
1057
649
  
1058
650
  errno = 0;
1059
651
  
1081
673
    bool match = false;
1082
674
    {
1083
675
      char *interface = NULL;
1084
 
      while((interface = argz_next(mc->interfaces,
1085
 
                                   mc->interfaces_size,
1086
 
                                   interface))){
 
676
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
677
                                 interface))){
1087
678
        if(if_nametoindex(interface) == (unsigned int)if_index){
1088
679
          match = true;
1089
680
          break;
1118
709
                 PRIuMAX "\n", ip, (uintmax_t)port);
1119
710
  }
1120
711
  
1121
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
712
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1122
713
  if(tcp_sd < 0){
1123
714
    int e = errno;
1124
715
    perror_plus("socket");
1131
722
    goto mandos_end;
1132
723
  }
1133
724
  
 
725
  memset(&to, 0, sizeof(to));
1134
726
  if(af == AF_INET6){
1135
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1136
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1137
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
727
    to.in6.sin6_family = (sa_family_t)af;
 
728
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
1138
729
  } else {                      /* IPv4 */
1139
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1140
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1141
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
730
    to.in.sin_family = (sa_family_t)af;
 
731
    ret = inet_pton(af, ip, &to.in.sin_addr);
1142
732
  }
1143
733
  if(ret < 0 ){
1144
734
    int e = errno;
1153
743
    goto mandos_end;
1154
744
  }
1155
745
  if(af == AF_INET6){
1156
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1157
 
    if(IN6_IS_ADDR_LINKLOCAL
1158
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
746
    to.in6.sin6_port = htons(port);    
 
747
#ifdef __GNUC__
 
748
#pragma GCC diagnostic push
 
749
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
750
#endif
 
751
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
752
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
753
#ifdef __GNUC__
 
754
#pragma GCC diagnostic pop
 
755
#endif
1159
756
      if(if_index == AVAHI_IF_UNSPEC){
1160
757
        fprintf_plus(stderr, "An IPv6 link-local address is"
1161
758
                     " incomplete without a network interface\n");
1163
760
        goto mandos_end;
1164
761
      }
1165
762
      /* Set the network interface number as scope */
1166
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
763
      to.in6.sin6_scope_id = (uint32_t)if_index;
1167
764
    }
1168
765
  } else {
1169
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
766
    to.in.sin_port = htons(port);
1170
767
  }
1171
768
  
1172
769
  if(quit_now){
1190
787
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1191
788
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1192
789
    if(af == AF_INET6){
1193
 
      ret = getnameinfo((struct sockaddr *)&to,
1194
 
                        sizeof(struct sockaddr_in6),
 
790
      ret = getnameinfo((struct sockaddr *)&(to.in6), sizeof(to.in6),
1195
791
                        addrstr, sizeof(addrstr), NULL, 0,
1196
792
                        NI_NUMERICHOST);
1197
793
    } else {
1198
 
      ret = getnameinfo((struct sockaddr *)&to,
1199
 
                        sizeof(struct sockaddr_in),
 
794
      ret = getnameinfo((struct sockaddr *)&(to.in), sizeof(to.in),
1200
795
                        addrstr, sizeof(addrstr), NULL, 0,
1201
796
                        NI_NUMERICHOST);
1202
797
    }
1214
809
    goto mandos_end;
1215
810
  }
1216
811
  
1217
 
  while(true){
1218
 
    if(af == AF_INET6){
1219
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1220
 
                    sizeof(struct sockaddr_in6));
1221
 
    } else {
1222
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1223
 
                    sizeof(struct sockaddr_in));
1224
 
    }
1225
 
    if(ret < 0){
1226
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1227
 
         and if_index != AVAHI_IF_UNSPEC
1228
 
         and connect_to == NULL
1229
 
         and not route_added and
1230
 
         ((af == AF_INET6 and not
1231
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1232
 
                                    &to)->sin6_addr)))
1233
 
          or (af == AF_INET and
1234
 
              /* Not a a IPv4LL address */
1235
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1236
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1237
 
        /* Work around Avahi bug - Avahi does not announce link-local
1238
 
           addresses if it has a global address, so local hosts with
1239
 
           *only* a link-local address (e.g. Mandos clients) cannot
1240
 
           connect to a Mandos server announced by Avahi on a server
1241
 
           host with a global address.  Work around this by retrying
1242
 
           with an explicit route added with the server's address.
1243
 
           
1244
 
           Avahi bug reference:
1245
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1246
 
           https://bugs.debian.org/587961
1247
 
        */
1248
 
        if(debug){
1249
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1250
 
                       " direct route\n");
1251
 
        }
1252
 
        int e = errno;
1253
 
        route_added = add_local_route(ip, if_index);
1254
 
        if(route_added){
1255
 
          continue;
1256
 
        }
1257
 
        errno = e;
1258
 
      }
1259
 
      if(errno != ECONNREFUSED or debug){
1260
 
        int e = errno;
1261
 
        perror_plus("connect");
1262
 
        errno = e;
1263
 
      }
1264
 
      goto mandos_end;
1265
 
    }
1266
 
    
1267
 
    if(quit_now){
1268
 
      errno = EINTR;
1269
 
      goto mandos_end;
1270
 
    }
1271
 
    break;
 
812
  if(af == AF_INET6){
 
813
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
814
  } else {
 
815
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
816
  }
 
817
  if(ret < 0){
 
818
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
819
      int e = errno;
 
820
      perror_plus("connect");
 
821
      errno = e;
 
822
    }
 
823
    goto mandos_end;
 
824
  }
 
825
  
 
826
  if(quit_now){
 
827
    errno = EINTR;
 
828
    goto mandos_end;
1272
829
  }
1273
830
  
1274
831
  const char *out = mandos_protocol_version;
1428
985
                                               &decrypted_buffer, mc);
1429
986
    if(decrypted_buffer_size >= 0){
1430
987
      
1431
 
      clearerr(stdout);
1432
988
      written = 0;
1433
989
      while(written < (size_t) decrypted_buffer_size){
1434
990
        if(quit_now){
1450
1006
        }
1451
1007
        written += (size_t)ret;
1452
1008
      }
1453
 
      ret = fflush(stdout);
1454
 
      if(ret != 0){
1455
 
        int e = errno;
1456
 
        if(debug){
1457
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1458
 
                       strerror(errno));
1459
 
        }
1460
 
        errno = e;
1461
 
        goto mandos_end;
1462
 
      }
1463
1009
      retval = 0;
1464
1010
    }
1465
1011
  }
1468
1014
  
1469
1015
 mandos_end:
1470
1016
  {
1471
 
    if(route_added){
1472
 
      if(not delete_local_route(ip, if_index)){
1473
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1474
 
                     " interface %d", ip, if_index);
1475
 
      }
1476
 
    }
1477
1017
    int e = errno;
1478
1018
    free(decrypted_buffer);
1479
1019
    free(buffer);
1480
1020
    if(tcp_sd >= 0){
1481
 
      ret = close(tcp_sd);
 
1021
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1482
1022
    }
1483
1023
    if(ret == -1){
1484
1024
      if(e == 0){
1509
1049
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1510
1050
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1511
1051
                             flags,
1512
 
                             void *mc){
 
1052
                             void* mc){
1513
1053
  if(r == NULL){
1514
1054
    return;
1515
1055
  }
1518
1058
     timed out */
1519
1059
  
1520
1060
  if(quit_now){
1521
 
    avahi_s_service_resolver_free(r);
1522
1061
    return;
1523
1062
  }
1524
1063
  
1569
1108
                            const char *domain,
1570
1109
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1571
1110
                            flags,
1572
 
                            void *mc){
 
1111
                            void* mc){
1573
1112
  if(b == NULL){
1574
1113
    return;
1575
1114
  }
1635
1174
  errno = old_errno;
1636
1175
}
1637
1176
 
1638
 
__attribute__((nonnull, warn_unused_result))
1639
1177
bool get_flags(const char *ifname, struct ifreq *ifr){
1640
1178
  int ret;
1641
 
  int old_errno;
 
1179
  error_t ret_errno;
1642
1180
  
1643
1181
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1644
1182
  if(s < 0){
1645
 
    old_errno = errno;
 
1183
    ret_errno = errno;
1646
1184
    perror_plus("socket");
1647
 
    errno = old_errno;
 
1185
    errno = ret_errno;
1648
1186
    return false;
1649
1187
  }
1650
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1651
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1188
  strcpy(ifr->ifr_name, ifname);
1652
1189
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1653
1190
  if(ret == -1){
1654
1191
    if(debug){
1655
 
      old_errno = errno;
 
1192
      ret_errno = errno;
1656
1193
      perror_plus("ioctl SIOCGIFFLAGS");
1657
 
      errno = old_errno;
 
1194
      errno = ret_errno;
1658
1195
    }
1659
 
    close(s);
1660
1196
    return false;
1661
1197
  }
1662
 
  close(s);
1663
1198
  return true;
1664
1199
}
1665
1200
 
1666
 
__attribute__((nonnull, warn_unused_result))
1667
1201
bool good_flags(const char *ifname, const struct ifreq *ifr){
1668
1202
  
1669
1203
  /* Reject the loopback device */
1711
1245
 * corresponds to an acceptable network device.
1712
1246
 * (This function is passed to scandir(3) as a filter function.)
1713
1247
 */
1714
 
__attribute__((nonnull, warn_unused_result))
1715
1248
int good_interface(const struct dirent *if_entry){
1716
1249
  if(if_entry->d_name[0] == '.'){
1717
1250
    return 0;
1735
1268
/* 
1736
1269
 * This function determines if a network interface is up.
1737
1270
 */
1738
 
__attribute__((nonnull, warn_unused_result))
1739
1271
bool interface_is_up(const char *interface){
1740
1272
  struct ifreq ifr;
1741
1273
  if(not get_flags(interface, &ifr)){
1752
1284
/* 
1753
1285
 * This function determines if a network interface is running
1754
1286
 */
1755
 
__attribute__((nonnull, warn_unused_result))
1756
1287
bool interface_is_running(const char *interface){
1757
1288
  struct ifreq ifr;
1758
1289
  if(not get_flags(interface, &ifr)){
1766
1297
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1767
1298
}
1768
1299
 
1769
 
__attribute__((nonnull, pure, warn_unused_result))
1770
1300
int notdotentries(const struct dirent *direntry){
1771
1301
  /* Skip "." and ".." */
1772
1302
  if(direntry->d_name[0] == '.'
1779
1309
}
1780
1310
 
1781
1311
/* Is this directory entry a runnable program? */
1782
 
__attribute__((nonnull, warn_unused_result))
1783
1312
int runnable_hook(const struct dirent *direntry){
1784
1313
  int ret;
1785
1314
  size_t sret;
1793
1322
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1794
1323
                "abcdefghijklmnopqrstuvwxyz"
1795
1324
                "0123456789"
1796
 
                "_.-");
 
1325
                "_-");
1797
1326
  if((direntry->d_name)[sret] != '\0'){
1798
1327
    /* Contains non-allowed characters */
1799
1328
    if(debug){
1803
1332
    return 0;
1804
1333
  }
1805
1334
  
1806
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1335
  char *fullname = NULL;
 
1336
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1337
  if(ret < 0){
 
1338
    perror_plus("asprintf");
 
1339
    return 0;
 
1340
  }
 
1341
  
 
1342
  ret = stat(fullname, &st);
1807
1343
  if(ret == -1){
1808
1344
    if(debug){
1809
1345
      perror_plus("Could not stat hook");
1833
1369
  return 1;
1834
1370
}
1835
1371
 
1836
 
__attribute__((nonnull, warn_unused_result))
1837
1372
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1838
1373
                            mandos_context *mc){
1839
1374
  int ret;
1843
1378
  
1844
1379
  while(true){
1845
1380
    if(mc->current_server == NULL){
1846
 
      if(debug){
 
1381
      if (debug){
1847
1382
        fprintf_plus(stderr, "Wait until first server is found."
1848
1383
                     " No timeout!\n");
1849
1384
      }
1850
1385
      ret = avahi_simple_poll_iterate(s, -1);
1851
1386
    } else {
1852
 
      if(debug){
 
1387
      if (debug){
1853
1388
        fprintf_plus(stderr, "Check current_server if we should run"
1854
1389
                     " it, or wait\n");
1855
1390
      }
1872
1407
                     - ((intmax_t)waited_time.tv_sec * 1000))
1873
1408
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1874
1409
      
1875
 
      if(debug){
 
1410
      if (debug){
1876
1411
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1877
1412
                     block_time);
1878
1413
      }
1900
1435
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1901
1436
    }
1902
1437
    if(ret != 0){
1903
 
      if(ret > 0 or errno != EINTR){
 
1438
      if (ret > 0 or errno != EINTR){
1904
1439
        return (ret != 1) ? ret : 0;
1905
1440
      }
1906
1441
    }
1907
1442
  }
1908
1443
}
1909
1444
 
1910
 
__attribute__((nonnull))
1911
 
void run_network_hooks(const char *mode, const char *interface,
 
1445
/* Set effective uid to 0, return errno */
 
1446
error_t raise_privileges(void){
 
1447
  error_t old_errno = errno;
 
1448
  error_t ret_errno = 0;
 
1449
  if(seteuid(0) == -1){
 
1450
    ret_errno = errno;
 
1451
    perror_plus("seteuid");
 
1452
  }
 
1453
  errno = old_errno;
 
1454
  return ret_errno;
 
1455
}
 
1456
 
 
1457
/* Set effective and real user ID to 0.  Return errno. */
 
1458
error_t raise_privileges_permanently(void){
 
1459
  error_t old_errno = errno;
 
1460
  error_t ret_errno = raise_privileges();
 
1461
  if(ret_errno != 0){
 
1462
    errno = old_errno;
 
1463
    return ret_errno;
 
1464
  }
 
1465
  if(setuid(0) == -1){
 
1466
    ret_errno = errno;
 
1467
    perror_plus("seteuid");
 
1468
  }
 
1469
  errno = old_errno;
 
1470
  return ret_errno;
 
1471
}
 
1472
 
 
1473
/* Set effective user ID to unprivileged saved user ID */
 
1474
error_t lower_privileges(void){
 
1475
  error_t old_errno = errno;
 
1476
  error_t ret_errno = 0;
 
1477
  if(seteuid(uid) == -1){
 
1478
    ret_errno = errno;
 
1479
    perror_plus("seteuid");
 
1480
  }
 
1481
  errno = old_errno;
 
1482
  return ret_errno;
 
1483
}
 
1484
 
 
1485
/* Lower privileges permanently */
 
1486
error_t lower_privileges_permanently(void){
 
1487
  error_t old_errno = errno;
 
1488
  error_t ret_errno = 0;
 
1489
  if(setuid(uid) == -1){
 
1490
    ret_errno = errno;
 
1491
    perror_plus("setuid");
 
1492
  }
 
1493
  errno = old_errno;
 
1494
  return ret_errno;
 
1495
}
 
1496
 
 
1497
bool run_network_hooks(const char *mode, const char *interface,
1912
1498
                       const float delay){
1913
 
  struct dirent **direntries = NULL;
1914
 
  if(hookdir_fd == -1){
1915
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1916
 
                      | O_CLOEXEC);
1917
 
    if(hookdir_fd == -1){
1918
 
      if(errno == ENOENT){
1919
 
        if(debug){
1920
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1921
 
                       " found\n", hookdir);
1922
 
        }
1923
 
      } else {
1924
 
        perror_plus("open");
1925
 
      }
1926
 
      return;
1927
 
    }
1928
 
  }
1929
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1930
 
  if(devnull == -1){
1931
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1932
 
    return;
1933
 
  }
1934
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1935
 
                           runnable_hook, alphasort);
 
1499
  struct dirent **direntries;
 
1500
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1501
                         alphasort);
1936
1502
  if(numhooks == -1){
1937
 
    perror_plus("scandir");
1938
 
    close(devnull);
1939
 
    return;
1940
 
  }
1941
 
  struct dirent *direntry;
1942
 
  int ret;
1943
 
  for(int i = 0; i < numhooks; i++){
1944
 
    direntry = direntries[i];
1945
 
    if(debug){
1946
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1947
 
                   direntry->d_name);
 
1503
    if(errno == ENOENT){
 
1504
      if(debug){
 
1505
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1506
                     " found\n", hookdir);
 
1507
      }
 
1508
    } else {
 
1509
      perror_plus("scandir");
1948
1510
    }
1949
 
    pid_t hook_pid = fork();
1950
 
    if(hook_pid == 0){
1951
 
      /* Child */
1952
 
      /* Raise privileges */
1953
 
      errno = raise_privileges_permanently();
1954
 
      if(errno != 0){
1955
 
        perror_plus("Failed to raise privileges");
1956
 
        _exit(EX_NOPERM);
1957
 
      }
1958
 
      /* Set group */
1959
 
      errno = 0;
1960
 
      ret = setgid(0);
1961
 
      if(ret == -1){
1962
 
        perror_plus("setgid");
1963
 
        _exit(EX_NOPERM);
1964
 
      }
1965
 
      /* Reset supplementary groups */
1966
 
      errno = 0;
1967
 
      ret = setgroups(0, NULL);
1968
 
      if(ret == -1){
1969
 
        perror_plus("setgroups");
1970
 
        _exit(EX_NOPERM);
1971
 
      }
1972
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1973
 
      if(ret == -1){
1974
 
        perror_plus("setenv");
1975
 
        _exit(EX_OSERR);
1976
 
      }
1977
 
      ret = setenv("DEVICE", interface, 1);
1978
 
      if(ret == -1){
1979
 
        perror_plus("setenv");
1980
 
        _exit(EX_OSERR);
1981
 
      }
1982
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1983
 
      if(ret == -1){
1984
 
        perror_plus("setenv");
1985
 
        _exit(EX_OSERR);
1986
 
      }
1987
 
      ret = setenv("MODE", mode, 1);
1988
 
      if(ret == -1){
1989
 
        perror_plus("setenv");
1990
 
        _exit(EX_OSERR);
1991
 
      }
1992
 
      char *delaystring;
1993
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1994
 
      if(ret == -1){
 
1511
  } else {
 
1512
    struct dirent *direntry;
 
1513
    int ret;
 
1514
    int devnull = open("/dev/null", O_RDONLY);
 
1515
    for(int i = 0; i < numhooks; i++){
 
1516
      direntry = direntries[i];
 
1517
      char *fullname = NULL;
 
1518
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1519
      if(ret < 0){
1995
1520
        perror_plus("asprintf");
1996
 
        _exit(EX_OSERR);
1997
 
      }
1998
 
      ret = setenv("DELAY", delaystring, 1);
1999
 
      if(ret == -1){
 
1521
        continue;
 
1522
      }
 
1523
      if(debug){
 
1524
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1525
                     direntry->d_name);
 
1526
      }
 
1527
      pid_t hook_pid = fork();
 
1528
      if(hook_pid == 0){
 
1529
        /* Child */
 
1530
        /* Raise privileges */
 
1531
        raise_privileges_permanently();
 
1532
        /* Set group */
 
1533
        errno = 0;
 
1534
        ret = setgid(0);
 
1535
        if(ret == -1){
 
1536
          perror_plus("setgid");
 
1537
        }
 
1538
        /* Reset supplementary groups */
 
1539
        errno = 0;
 
1540
        ret = setgroups(0, NULL);
 
1541
        if(ret == -1){
 
1542
          perror_plus("setgroups");
 
1543
        }
 
1544
        dup2(devnull, STDIN_FILENO);
 
1545
        close(devnull);
 
1546
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1547
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1548
        if(ret == -1){
 
1549
          perror_plus("setenv");
 
1550
          _exit(EX_OSERR);
 
1551
        }
 
1552
        ret = setenv("DEVICE", interface, 1);
 
1553
        if(ret == -1){
 
1554
          perror_plus("setenv");
 
1555
          _exit(EX_OSERR);
 
1556
        }
 
1557
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1558
        if(ret == -1){
 
1559
          perror_plus("setenv");
 
1560
          _exit(EX_OSERR);
 
1561
        }
 
1562
        ret = setenv("MODE", mode, 1);
 
1563
        if(ret == -1){
 
1564
          perror_plus("setenv");
 
1565
          _exit(EX_OSERR);
 
1566
        }
 
1567
        char *delaystring;
 
1568
        ret = asprintf(&delaystring, "%f", delay);
 
1569
        if(ret == -1){
 
1570
          perror_plus("asprintf");
 
1571
          _exit(EX_OSERR);
 
1572
        }
 
1573
        ret = setenv("DELAY", delaystring, 1);
 
1574
        if(ret == -1){
 
1575
          free(delaystring);
 
1576
          perror_plus("setenv");
 
1577
          _exit(EX_OSERR);
 
1578
        }
2000
1579
        free(delaystring);
2001
 
        perror_plus("setenv");
2002
 
        _exit(EX_OSERR);
2003
 
      }
2004
 
      free(delaystring);
2005
 
      if(connect_to != NULL){
2006
 
        ret = setenv("CONNECT", connect_to, 1);
2007
 
        if(ret == -1){
2008
 
          perror_plus("setenv");
2009
 
          _exit(EX_OSERR);
2010
 
        }
2011
 
      }
2012
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2013
 
                                                   direntry->d_name,
2014
 
                                                   O_RDONLY));
2015
 
      if(hook_fd == -1){
2016
 
        perror_plus("openat");
2017
 
        _exit(EXIT_FAILURE);
2018
 
      }
2019
 
      if(close(hookdir_fd) == -1){
2020
 
        perror_plus("close");
2021
 
        _exit(EXIT_FAILURE);
2022
 
      }
2023
 
      ret = dup2(devnull, STDIN_FILENO);
2024
 
      if(ret == -1){
2025
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2026
 
        _exit(EX_OSERR);
2027
 
      }
2028
 
      ret = close(devnull);
2029
 
      if(ret == -1){
2030
 
        perror_plus("close");
2031
 
        _exit(EX_OSERR);
2032
 
      }
2033
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2034
 
      if(ret == -1){
2035
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2036
 
        _exit(EX_OSERR);
2037
 
      }
2038
 
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2039
 
                 environ) == -1){
2040
 
        perror_plus("fexecve");
2041
 
        _exit(EXIT_FAILURE);
2042
 
      }
2043
 
    } else {
2044
 
      if(hook_pid == -1){
2045
 
        perror_plus("fork");
2046
 
        free(direntry);
2047
 
        continue;
2048
 
      }
2049
 
      int status;
2050
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2051
 
        perror_plus("waitpid");
2052
 
        free(direntry);
2053
 
        continue;
2054
 
      }
2055
 
      if(WIFEXITED(status)){
2056
 
        if(WEXITSTATUS(status) != 0){
2057
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2058
 
                       " with status %d\n", direntry->d_name,
2059
 
                       WEXITSTATUS(status));
2060
 
          free(direntry);
2061
 
          continue;
2062
 
        }
2063
 
      } else if(WIFSIGNALED(status)){
2064
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2065
 
                     " signal %d\n", direntry->d_name,
2066
 
                     WTERMSIG(status));
2067
 
        free(direntry);
2068
 
        continue;
 
1580
        if(connect_to != NULL){
 
1581
          ret = setenv("CONNECT", connect_to, 1);
 
1582
          if(ret == -1){
 
1583
            perror_plus("setenv");
 
1584
            _exit(EX_OSERR);
 
1585
          }
 
1586
        }
 
1587
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1588
          perror_plus("execl");
 
1589
          _exit(EXIT_FAILURE);
 
1590
        }
2069
1591
      } else {
2070
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2071
 
                     " crashed\n", direntry->d_name);
2072
 
        free(direntry);
2073
 
        continue;
2074
 
      }
2075
 
    }
2076
 
    if(debug){
2077
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2078
 
                   direntry->d_name);
2079
 
    }
2080
 
    free(direntry);
2081
 
  }
2082
 
  free(direntries);
2083
 
  if(close(hookdir_fd) == -1){
2084
 
    perror_plus("close");
2085
 
  } else {
2086
 
    hookdir_fd = -1;
2087
 
  }
2088
 
  close(devnull);
 
1592
        int status;
 
1593
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1594
          perror_plus("waitpid");
 
1595
          free(fullname);
 
1596
          continue;
 
1597
        }
 
1598
        if(WIFEXITED(status)){
 
1599
          if(WEXITSTATUS(status) != 0){
 
1600
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1601
                         " with status %d\n", direntry->d_name,
 
1602
                         WEXITSTATUS(status));
 
1603
            free(fullname);
 
1604
            continue;
 
1605
          }
 
1606
        } else if(WIFSIGNALED(status)){
 
1607
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1608
                       " signal %d\n", direntry->d_name,
 
1609
                       WTERMSIG(status));
 
1610
          free(fullname);
 
1611
          continue;
 
1612
        } else {
 
1613
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1614
                       " crashed\n", direntry->d_name);
 
1615
          free(fullname);
 
1616
          continue;
 
1617
        }
 
1618
      }
 
1619
      free(fullname);
 
1620
      if(debug){
 
1621
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1622
                     direntry->d_name);
 
1623
      }
 
1624
    }
 
1625
    close(devnull);
 
1626
  }
 
1627
  return true;
2089
1628
}
2090
1629
 
2091
 
__attribute__((nonnull, warn_unused_result))
2092
 
int bring_up_interface(const char *const interface,
2093
 
                       const float delay){
2094
 
  int old_errno = errno;
2095
 
  int ret;
 
1630
error_t bring_up_interface(const char *const interface,
 
1631
                           const float delay){
 
1632
  int sd = -1;
 
1633
  error_t old_errno = errno;
 
1634
  error_t ret_errno = 0;
 
1635
  int ret, ret_setflags;
2096
1636
  struct ifreq network;
2097
1637
  unsigned int if_index = if_nametoindex(interface);
2098
1638
  if(if_index == 0){
2107
1647
  }
2108
1648
  
2109
1649
  if(not interface_is_up(interface)){
2110
 
    int ret_errno = 0;
2111
 
    int ioctl_errno = 0;
2112
 
    if(not get_flags(interface, &network)){
 
1650
    if(not get_flags(interface, &network) and debug){
2113
1651
      ret_errno = errno;
2114
1652
      fprintf_plus(stderr, "Failed to get flags for interface "
2115
1653
                   "\"%s\"\n", interface);
2116
 
      errno = old_errno;
2117
1654
      return ret_errno;
2118
1655
    }
2119
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1656
    network.ifr_flags |= IFF_UP;
2120
1657
    
2121
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2122
 
    if(sd == -1){
 
1658
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1659
    if(sd < 0){
2123
1660
      ret_errno = errno;
2124
1661
      perror_plus("socket");
2125
1662
      errno = old_errno;
2126
1663
      return ret_errno;
2127
1664
    }
2128
 
    
 
1665
  
2129
1666
    if(quit_now){
2130
 
      ret = close(sd);
2131
 
      if(ret == -1){
2132
 
        perror_plus("close");
2133
 
      }
 
1667
      close(sd);
2134
1668
      errno = old_errno;
2135
1669
      return EINTR;
2136
1670
    }
2140
1674
                   interface);
2141
1675
    }
2142
1676
    
2143
 
    /* Raise privileges */
2144
 
    ret_errno = raise_privileges();
2145
 
    if(ret_errno != 0){
2146
 
      errno = ret_errno;
2147
 
      perror_plus("Failed to raise privileges");
2148
 
    }
 
1677
    /* Raise priviliges */
 
1678
    raise_privileges();
2149
1679
    
2150
1680
#ifdef __linux__
2151
 
    int ret_linux;
2152
 
    bool restore_loglevel = false;
2153
 
    if(ret_errno == 0){
2154
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2155
 
         messages about the network interface to mess up the prompt */
2156
 
      ret_linux = klogctl(8, NULL, 5);
2157
 
      if(ret_linux == -1){
2158
 
        perror_plus("klogctl");
2159
 
      } else {
2160
 
        restore_loglevel = true;
2161
 
      }
 
1681
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1682
       messages about the network interface to mess up the prompt */
 
1683
    int ret_linux = klogctl(8, NULL, 5);
 
1684
    bool restore_loglevel = true;
 
1685
    if(ret_linux == -1){
 
1686
      restore_loglevel = false;
 
1687
      perror_plus("klogctl");
2162
1688
    }
2163
1689
#endif  /* __linux__ */
2164
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2165
 
    ioctl_errno = errno;
 
1690
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1691
    ret_errno = errno;
2166
1692
#ifdef __linux__
2167
1693
    if(restore_loglevel){
2168
1694
      ret_linux = klogctl(7, NULL, 0);
2172
1698
    }
2173
1699
#endif  /* __linux__ */
2174
1700
    
2175
 
    /* If raise_privileges() succeeded above */
2176
 
    if(ret_errno == 0){
2177
 
      /* Lower privileges */
2178
 
      ret_errno = lower_privileges();
2179
 
      if(ret_errno != 0){
2180
 
        errno = ret_errno;
2181
 
        perror_plus("Failed to lower privileges");
2182
 
      }
2183
 
    }
 
1701
    /* Lower privileges */
 
1702
    lower_privileges();
2184
1703
    
2185
1704
    /* Close the socket */
2186
 
    ret = close(sd);
 
1705
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2187
1706
    if(ret == -1){
2188
1707
      perror_plus("close");
2189
1708
    }
2190
1709
    
2191
1710
    if(ret_setflags == -1){
2192
 
      errno = ioctl_errno;
 
1711
      errno = ret_errno;
2193
1712
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2194
1713
      errno = old_errno;
2195
 
      return ioctl_errno;
 
1714
      return ret_errno;
2196
1715
    }
2197
1716
  } else if(debug){
2198
1717
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2201
1720
  
2202
1721
  /* Sleep checking until interface is running.
2203
1722
     Check every 0.25s, up to total time of delay */
2204
 
  for(int i = 0; i < delay * 4; i++){
 
1723
  for(int i=0; i < delay * 4; i++){
2205
1724
    if(interface_is_running(interface)){
2206
1725
      break;
2207
1726
    }
2216
1735
  return 0;
2217
1736
}
2218
1737
 
2219
 
__attribute__((nonnull, warn_unused_result))
2220
 
int take_down_interface(const char *const interface){
2221
 
  int old_errno = errno;
 
1738
error_t take_down_interface(const char *const interface){
 
1739
  error_t old_errno = errno;
2222
1740
  struct ifreq network;
2223
1741
  unsigned int if_index = if_nametoindex(interface);
2224
1742
  if(if_index == 0){
2227
1745
    return ENXIO;
2228
1746
  }
2229
1747
  if(interface_is_up(interface)){
2230
 
    int ret_errno = 0;
2231
 
    int ioctl_errno = 0;
 
1748
    error_t ret_errno = 0;
2232
1749
    if(not get_flags(interface, &network) and debug){
2233
1750
      ret_errno = errno;
2234
1751
      fprintf_plus(stderr, "Failed to get flags for interface "
2235
1752
                   "\"%s\"\n", interface);
2236
 
      errno = old_errno;
2237
1753
      return ret_errno;
2238
1754
    }
2239
1755
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2240
1756
    
2241
1757
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2242
 
    if(sd == -1){
 
1758
    if(sd < 0){
2243
1759
      ret_errno = errno;
2244
1760
      perror_plus("socket");
2245
1761
      errno = old_errno;
2251
1767
                   interface);
2252
1768
    }
2253
1769
    
2254
 
    /* Raise privileges */
2255
 
    ret_errno = raise_privileges();
2256
 
    if(ret_errno != 0){
2257
 
      errno = ret_errno;
2258
 
      perror_plus("Failed to raise privileges");
2259
 
    }
 
1770
    /* Raise priviliges */
 
1771
    raise_privileges();
2260
1772
    
2261
1773
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2262
 
    ioctl_errno = errno;
 
1774
    ret_errno = errno;
2263
1775
    
2264
 
    /* If raise_privileges() succeeded above */
2265
 
    if(ret_errno == 0){
2266
 
      /* Lower privileges */
2267
 
      ret_errno = lower_privileges();
2268
 
      if(ret_errno != 0){
2269
 
        errno = ret_errno;
2270
 
        perror_plus("Failed to lower privileges");
2271
 
      }
2272
 
    }
 
1776
    /* Lower privileges */
 
1777
    lower_privileges();
2273
1778
    
2274
1779
    /* Close the socket */
2275
 
    int ret = close(sd);
 
1780
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2276
1781
    if(ret == -1){
2277
1782
      perror_plus("close");
2278
1783
    }
2279
1784
    
2280
1785
    if(ret_setflags == -1){
2281
 
      errno = ioctl_errno;
 
1786
      errno = ret_errno;
2282
1787
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2283
1788
      errno = old_errno;
2284
 
      return ioctl_errno;
 
1789
      return ret_errno;
2285
1790
    }
2286
1791
  } else if(debug){
2287
1792
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2293
1798
}
2294
1799
 
2295
1800
int main(int argc, char *argv[]){
2296
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2297
 
                        .priority = "SECURE256:!CTYPE-X.509"
2298
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2299
 
                        .current_server = NULL, .interfaces = NULL,
2300
 
                        .interfaces_size = 0 };
 
1801
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1802
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1803
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1804
                        .interfaces = NULL, .interfaces_size = 0 };
2301
1805
  AvahiSServiceBrowser *sb = NULL;
2302
1806
  error_t ret_errno;
2303
1807
  int ret;
2306
1810
  int exitcode = EXIT_SUCCESS;
2307
1811
  char *interfaces_to_take_down = NULL;
2308
1812
  size_t interfaces_to_take_down_size = 0;
2309
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2310
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
2311
 
  char *tempdir = NULL;
 
1813
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1814
  bool tempdir_created = false;
2312
1815
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2313
1816
  const char *seckey = PATHDIR "/" SECKEY;
2314
1817
  const char *pubkey = PATHDIR "/" PUBKEY;
2315
 
  const char *dh_params_file = NULL;
2316
1818
  char *interfaces_hooks = NULL;
2317
1819
  
2318
1820
  bool gnutls_initialized = false;
2371
1873
        .doc = "Bit length of the prime number used in the"
2372
1874
        " Diffie-Hellman key exchange",
2373
1875
        .group = 2 },
2374
 
      { .name = "dh-params", .key = 134,
2375
 
        .arg = "FILE",
2376
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2377
 
        " for the Diffie-Hellman key exchange",
2378
 
        .group = 2 },
2379
1876
      { .name = "priority", .key = 130,
2380
1877
        .arg = "STRING",
2381
1878
        .doc = "GnuTLS priority string for the TLS handshake",
2436
1933
        }
2437
1934
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2438
1935
        break;
2439
 
      case 134:                 /* --dh-params */
2440
 
        dh_params_file = arg;
2441
 
        break;
2442
1936
      case 130:                 /* --priority */
2443
1937
        mc.priority = arg;
2444
1938
        break;
2484
1978
                         .args_doc = "",
2485
1979
                         .doc = "Mandos client -- Get and decrypt"
2486
1980
                         " passwords from a Mandos server" };
2487
 
    ret_errno = argp_parse(&argp, argc, argv,
2488
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2489
 
    switch(ret_errno){
 
1981
    ret = argp_parse(&argp, argc, argv,
 
1982
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1983
    switch(ret){
2490
1984
    case 0:
2491
1985
      break;
2492
1986
    case ENOMEM:
2493
1987
    default:
2494
 
      errno = ret_errno;
 
1988
      errno = ret;
2495
1989
      perror_plus("argp_parse");
2496
1990
      exitcode = EX_OSERR;
2497
1991
      goto end;
2500
1994
      goto end;
2501
1995
    }
2502
1996
  }
2503
 
  
 
1997
    
2504
1998
  {
2505
1999
    /* Work around Debian bug #633582:
2506
 
       <https://bugs.debian.org/633582> */
 
2000
       <http://bugs.debian.org/633582> */
2507
2001
    
2508
 
    /* Re-raise privileges */
2509
 
    ret = raise_privileges();
2510
 
    if(ret != 0){
2511
 
      errno = ret;
2512
 
      perror_plus("Failed to raise privileges");
2513
 
    } else {
 
2002
    /* Re-raise priviliges */
 
2003
    if(raise_privileges() == 0){
2514
2004
      struct stat st;
2515
2005
      
2516
2006
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2530
2020
              }
2531
2021
            }
2532
2022
          }
2533
 
          close(seckey_fd);
 
2023
          TEMP_FAILURE_RETRY(close(seckey_fd));
2534
2024
        }
2535
2025
      }
2536
 
      
 
2026
    
2537
2027
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2538
2028
        int pubkey_fd = open(pubkey, O_RDONLY);
2539
2029
        if(pubkey_fd == -1){
2551
2041
              }
2552
2042
            }
2553
2043
          }
2554
 
          close(pubkey_fd);
2555
 
        }
2556
 
      }
2557
 
      
2558
 
      if(dh_params_file != NULL
2559
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2560
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2561
 
        if(dhparams_fd == -1){
2562
 
          perror_plus("open");
2563
 
        } else {
2564
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2565
 
          if(ret == -1){
2566
 
            perror_plus("fstat");
2567
 
          } else {
2568
 
            if(S_ISREG(st.st_mode)
2569
 
               and st.st_uid == 0 and st.st_gid == 0){
2570
 
              ret = fchown(dhparams_fd, uid, gid);
2571
 
              if(ret == -1){
2572
 
                perror_plus("fchown");
2573
 
              }
2574
 
            }
2575
 
          }
2576
 
          close(dhparams_fd);
2577
 
        }
2578
 
      }
2579
 
      
 
2044
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2045
        }
 
2046
      }
 
2047
    
2580
2048
      /* Lower privileges */
2581
 
      ret = lower_privileges();
2582
 
      if(ret != 0){
2583
 
        errno = ret;
2584
 
        perror_plus("Failed to lower privileges");
2585
 
      }
 
2049
      lower_privileges();
2586
2050
    }
2587
2051
  }
2588
2052
  
2614
2078
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2615
2079
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2616
2080
    }
2617
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2618
 
                      interfaces_hooks : "", delay);
 
2081
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2082
                             interfaces_hooks : "", delay)){
 
2083
      goto end;
 
2084
    }
2619
2085
  }
2620
2086
  
2621
2087
  if(not debug){
2699
2165
  
2700
2166
  /* If no interfaces were specified, make a list */
2701
2167
  if(mc.interfaces == NULL){
2702
 
    struct dirent **direntries = NULL;
 
2168
    struct dirent **direntries;
2703
2169
    /* Look for any good interfaces */
2704
2170
    ret = scandir(sys_class_net, &direntries, good_interface,
2705
2171
                  alphasort);
2711
2177
        if(ret_errno != 0){
2712
2178
          errno = ret_errno;
2713
2179
          perror_plus("argz_add");
2714
 
          free(direntries[i]);
2715
2180
          continue;
2716
2181
        }
2717
2182
        if(debug){
2718
2183
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2719
2184
                       direntries[i]->d_name);
2720
2185
        }
2721
 
        free(direntries[i]);
2722
2186
      }
2723
2187
      free(direntries);
2724
2188
    } else {
2725
 
      if(ret == 0){
2726
 
        free(direntries);
2727
 
      }
 
2189
      free(direntries);
2728
2190
      fprintf_plus(stderr, "Could not find a network interface\n");
2729
2191
      exitcode = EXIT_FAILURE;
2730
2192
      goto end;
2753
2215
        break;
2754
2216
      }
2755
2217
      bool interface_was_up = interface_is_up(interface);
2756
 
      errno = bring_up_interface(interface, delay);
 
2218
      ret = bring_up_interface(interface, delay);
2757
2219
      if(not interface_was_up){
2758
 
        if(errno != 0){
2759
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2760
 
                       " %s\n", interface, strerror(errno));
 
2220
        if(ret != 0){
 
2221
          errno = ret;
 
2222
          perror_plus("Failed to bring up interface");
2761
2223
        } else {
2762
 
          errno = argz_add(&interfaces_to_take_down,
2763
 
                           &interfaces_to_take_down_size,
2764
 
                           interface);
2765
 
          if(errno != 0){
 
2224
          ret_errno = argz_add(&interfaces_to_take_down,
 
2225
                               &interfaces_to_take_down_size,
 
2226
                               interface);
 
2227
          if(ret_errno != 0){
 
2228
            errno = ret_errno;
2766
2229
            perror_plus("argz_add");
2767
2230
          }
2768
2231
        }
2786
2249
    goto end;
2787
2250
  }
2788
2251
  
2789
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2252
  ret = init_gnutls_global(pubkey, seckey, &mc);
2790
2253
  if(ret == -1){
2791
2254
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2792
2255
    exitcode = EX_UNAVAILABLE;
2799
2262
    goto end;
2800
2263
  }
2801
2264
  
2802
 
  /* Try /run/tmp before /tmp */
2803
 
  tempdir = mkdtemp(run_tempdir);
2804
 
  if(tempdir == NULL and errno == ENOENT){
2805
 
      if(debug){
2806
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2807
 
                     run_tempdir, old_tempdir);
2808
 
      }
2809
 
      tempdir = mkdtemp(old_tempdir);
2810
 
  }
2811
 
  if(tempdir == NULL){
 
2265
  if(mkdtemp(tempdir) == NULL){
2812
2266
    perror_plus("mkdtemp");
2813
2267
    goto end;
2814
2268
  }
 
2269
  tempdir_created = true;
2815
2270
  
2816
2271
  if(quit_now){
2817
2272
    goto end;
2892
2347
      sleep((unsigned int)retry_interval);
2893
2348
    }
2894
2349
    
2895
 
    if(not quit_now){
 
2350
    if (not quit_now){
2896
2351
      exitcode = EXIT_SUCCESS;
2897
2352
    }
2898
2353
    
2914
2369
    
2915
2370
    /* Allocate a new server */
2916
2371
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2917
 
                                 &config, NULL, NULL, &ret);
 
2372
                                 &config, NULL, NULL, &ret_errno);
2918
2373
    
2919
2374
    /* Free the Avahi configuration data */
2920
2375
    avahi_server_config_free(&config);
2923
2378
  /* Check if creating the Avahi server object succeeded */
2924
2379
  if(mc.server == NULL){
2925
2380
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2926
 
                 avahi_strerror(ret));
 
2381
                 avahi_strerror(ret_errno));
2927
2382
    exitcode = EX_UNAVAILABLE;
2928
2383
    goto end;
2929
2384
  }
2953
2408
  if(debug){
2954
2409
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2955
2410
  }
2956
 
  
 
2411
 
2957
2412
  ret = avahi_loop_with_timeout(simple_poll,
2958
2413
                                (int)(retry_interval * 1000), &mc);
2959
2414
  if(debug){
2964
2419
 end:
2965
2420
  
2966
2421
  if(debug){
2967
 
    if(signal_received){
2968
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2969
 
                   argv[0], signal_received,
2970
 
                   strsignal(signal_received));
2971
 
    } else {
2972
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
2973
 
    }
 
2422
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2974
2423
  }
2975
2424
  
2976
2425
  /* Cleanup things */
2987
2436
  
2988
2437
  if(gnutls_initialized){
2989
2438
    gnutls_certificate_free_credentials(mc.cred);
 
2439
    gnutls_global_deinit();
2990
2440
    gnutls_dh_params_deinit(mc.dh_params);
2991
2441
  }
2992
2442
  
3000
2450
    mc.current_server->prev->next = NULL;
3001
2451
    while(mc.current_server != NULL){
3002
2452
      server *next = mc.current_server->next;
3003
 
#ifdef __GNUC__
3004
 
#pragma GCC diagnostic push
3005
 
#pragma GCC diagnostic ignored "-Wcast-qual"
3006
 
#endif
3007
 
      free((char *)(mc.current_server->ip));
3008
 
#ifdef __GNUC__
3009
 
#pragma GCC diagnostic pop
3010
 
#endif
3011
2453
      free(mc.current_server);
3012
2454
      mc.current_server = next;
3013
2455
    }
3014
2456
  }
3015
2457
  
3016
 
  /* Re-raise privileges */
 
2458
  /* Re-raise priviliges */
3017
2459
  {
3018
 
    ret = raise_privileges();
3019
 
    if(ret != 0){
3020
 
      errno = ret;
3021
 
      perror_plus("Failed to raise privileges");
3022
 
    } else {
3023
 
      
3024
 
      /* Run network hooks */
3025
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
3026
 
                        interfaces_hooks : "", delay);
3027
 
      
3028
 
      /* Take down the network interfaces which were brought up */
3029
 
      {
3030
 
        char *interface = NULL;
3031
 
        while((interface = argz_next(interfaces_to_take_down,
3032
 
                                     interfaces_to_take_down_size,
3033
 
                                     interface))){
3034
 
          ret = take_down_interface(interface);
3035
 
          if(ret != 0){
3036
 
            errno = ret;
3037
 
            perror_plus("Failed to take down interface");
3038
 
          }
3039
 
        }
3040
 
        if(debug and (interfaces_to_take_down == NULL)){
3041
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
3042
 
                       " down\n");
3043
 
        }
3044
 
      }
3045
 
    }
3046
 
    
3047
 
    ret = lower_privileges_permanently();
3048
 
    if(ret != 0){
3049
 
      errno = ret;
3050
 
      perror_plus("Failed to lower privileges permanently");
3051
 
    }
 
2460
    raise_privileges();
 
2461
    
 
2462
    /* Run network hooks */
 
2463
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2464
                      interfaces_hooks : "", delay);
 
2465
    
 
2466
    /* Take down the network interfaces which were brought up */
 
2467
    {
 
2468
      char *interface = NULL;
 
2469
      while((interface=argz_next(interfaces_to_take_down,
 
2470
                                 interfaces_to_take_down_size,
 
2471
                                 interface))){
 
2472
        ret_errno = take_down_interface(interface);
 
2473
        if(ret_errno != 0){
 
2474
          errno = ret_errno;
 
2475
          perror_plus("Failed to take down interface");
 
2476
        }
 
2477
      }
 
2478
      if(debug and (interfaces_to_take_down == NULL)){
 
2479
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2480
                     " down\n");
 
2481
      }
 
2482
    }
 
2483
    
 
2484
    lower_privileges_permanently();
3052
2485
  }
3053
2486
  
3054
2487
  free(interfaces_to_take_down);
3055
2488
  free(interfaces_hooks);
3056
2489
  
3057
 
  void clean_dir_at(int base, const char * const dirname,
3058
 
                    uintmax_t level){
 
2490
  /* Removes the GPGME temp directory and all files inside */
 
2491
  if(tempdir_created){
3059
2492
    struct dirent **direntries = NULL;
3060
 
    int dret;
3061
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3062
 
                                                O_RDONLY
3063
 
                                                | O_NOFOLLOW
3064
 
                                                | O_DIRECTORY
3065
 
                                                | O_PATH));
3066
 
    if(dir_fd == -1){
3067
 
      perror_plus("open");
3068
 
      return;
3069
 
    }
3070
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3071
 
                               notdotentries, alphasort);
3072
 
    if(numentries >= 0){
 
2493
    struct dirent *direntry = NULL;
 
2494
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2495
                             alphasort);
 
2496
    if (numentries > 0){
3073
2497
      for(int i = 0; i < numentries; i++){
3074
 
        if(debug){
3075
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3076
 
                       dirname, direntries[i]->d_name);
3077
 
        }
3078
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3079
 
        if(dret == -1){
3080
 
          if(errno == EISDIR){
3081
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3082
 
                              AT_REMOVEDIR);
3083
 
          }         
3084
 
          if((dret == -1) and (errno == ENOTEMPTY)
3085
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3086
 
                  == 0) and (level == 0)){
3087
 
            /* Recurse only in this special case */
3088
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3089
 
            dret = 0;
3090
 
          }
3091
 
          if((dret == -1) and (errno != ENOENT)){
3092
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3093
 
                         direntries[i]->d_name, strerror(errno));
3094
 
          }
3095
 
        }
3096
 
        free(direntries[i]);
3097
 
      }
3098
 
      
3099
 
      /* need to clean even if 0 because man page doesn't specify */
3100
 
      free(direntries);
3101
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3102
 
      if(dret == -1 and errno != ENOENT){
3103
 
        perror_plus("rmdir");
3104
 
      }
3105
 
    } else {
3106
 
      perror_plus("scandirat");
3107
 
    }
3108
 
    close(dir_fd);
3109
 
  }
3110
 
  
3111
 
  /* Removes the GPGME temp directory and all files inside */
3112
 
  if(tempdir != NULL){
3113
 
    clean_dir_at(-1, tempdir, 0);
 
2498
        direntry = direntries[i];
 
2499
        char *fullname = NULL;
 
2500
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2501
                       direntry->d_name);
 
2502
        if(ret < 0){
 
2503
          perror_plus("asprintf");
 
2504
          continue;
 
2505
        }
 
2506
        ret = remove(fullname);
 
2507
        if(ret == -1){
 
2508
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2509
                       strerror(errno));
 
2510
        }
 
2511
        free(fullname);
 
2512
      }
 
2513
    }
 
2514
 
 
2515
    /* need to clean even if 0 because man page doesn't specify */
 
2516
    free(direntries);
 
2517
    if (numentries == -1){
 
2518
      perror_plus("scandir");
 
2519
    }
 
2520
    ret = rmdir(tempdir);
 
2521
    if(ret == -1 and errno != ENOENT){
 
2522
      perror_plus("rmdir");
 
2523
    }
3114
2524
  }
3115
2525
  
3116
2526
  if(quit_now){