/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: 2015-07-06 20:09:47 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150706200947-w21u4eq74efgl6r5
Fix minor bugs and typos and add some more debug output.

* Makefile (install-client-nokey): Create plugin-helpers directory and
                                   the mandos-client-iprouteadddel
                                   helper program.
* initramfs-tools-hook (PLUGINHELPERDIR): Fix typo.
* plugins.d/mandos-client.c: Change terminology; routes are "deleted",
                             not "removed".  All occurences changed.
  (add_remove_local_route): Renamed to "add_delete_local_route".  All
                            callers changed.  Also pass "--debug" flag
                            to helper if in debug mode.
  (add_local_route): Add debugging output.
  (remove_local_route): Renamed to "delete_local_route".  All callers
                        changed.  Also pass "--debug" flag to helper
                        if in debug mode.
  (start_mandos_communication): Add debug output when adding route.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 Björn Påhlsson
 
12
 * Copyright © 2008-2015 Teddy Hogeborn
 
13
 * Copyright © 2008-2015 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(),
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect(),
59
59
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open() */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
61
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
62
                                 */
63
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause(), _exit(),
 
77
                                   unlinkat() */
77
78
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
79
#include <iso646.h>             /* not, or, and */
79
80
#include <argp.h>               /* struct argp_option, error_t, struct
141
142
static const char sys_class_net[] = "/sys/class/net";
142
143
char *connect_to = NULL;
143
144
const char *hookdir = HOOKDIR;
 
145
int hookdir_fd = -1;
144
146
uid_t uid = 65534;
145
147
gid_t gid = 65534;
146
148
 
183
185
  perror(print_text);
184
186
}
185
187
 
186
 
__attribute__((format (gnu_printf, 2, 3)))
 
188
__attribute__((format (gnu_printf, 2, 3), nonnull))
187
189
int fprintf_plus(FILE *stream, const char *format, ...){
188
190
  va_list ap;
189
191
  va_start (ap, format);
198
200
 * bytes. "buffer_capacity" is how much is currently allocated,
199
201
 * "buffer_length" is how much is already used.
200
202
 */
 
203
__attribute__((nonnull, warn_unused_result))
201
204
size_t incbuffer(char **buffer, size_t buffer_length,
202
205
                 size_t buffer_capacity){
203
206
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
216
219
}
217
220
 
218
221
/* Add server to set of servers to retry periodically */
 
222
__attribute__((nonnull, warn_unused_result))
219
223
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
220
224
                int af, server **current_server){
221
225
  int ret;
230
234
                          .af = af };
231
235
  if(new_server->ip == NULL){
232
236
    perror_plus("strdup");
 
237
    free(new_server);
233
238
    return false;
234
239
  }
235
240
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
236
241
  if(ret == -1){
237
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);
238
252
    return false;
239
253
  }
240
254
  /* Special case of first server */
242
256
    new_server->next = new_server;
243
257
    new_server->prev = new_server;
244
258
    *current_server = new_server;
245
 
  /* Place the new server last in the list */
246
259
  } else {
 
260
    /* Place the new server last in the list */
247
261
    new_server->next = *current_server;
248
262
    new_server->prev = (*current_server)->prev;
249
263
    new_server->prev->next = new_server;
255
269
/* 
256
270
 * Initialize GPGME.
257
271
 */
258
 
static bool init_gpgme(const char *seckey, const char *pubkey,
259
 
                       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){
260
277
  gpgme_error_t rc;
261
278
  gpgme_engine_info_t engine_info;
262
279
  
263
280
  /*
264
281
   * Helper function to insert pub and seckey to the engine keyring.
265
282
   */
266
 
  bool import_key(const char *filename){
 
283
  bool import_key(const char * const filename){
267
284
    int ret;
268
285
    int fd;
269
286
    gpgme_data_t pgp_data;
350
367
 * Decrypt OpenPGP data.
351
368
 * Returns -1 on error
352
369
 */
 
370
__attribute__((nonnull, warn_unused_result))
353
371
static ssize_t pgp_packet_decrypt(const char *cryptotext,
354
372
                                  size_t crypto_size,
355
373
                                  char **plaintext,
475
493
  return plaintext_length;
476
494
}
477
495
 
478
 
static const char * safer_gnutls_strerror(int value){
 
496
__attribute__((warn_unused_result))
 
497
static const char *safer_gnutls_strerror(int value){
479
498
  const char *ret = gnutls_strerror(value);
480
499
  if(ret == NULL)
481
500
    ret = "(unknown)";
483
502
}
484
503
 
485
504
/* GnuTLS log function callback */
 
505
__attribute__((nonnull))
486
506
static void debuggnutls(__attribute__((unused)) int level,
487
507
                        const char* string){
488
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
489
509
}
490
510
 
 
511
__attribute__((nonnull, warn_unused_result))
491
512
static int init_gnutls_global(const char *pubkeyfilename,
492
513
                              const char *seckeyfilename,
493
514
                              mandos_context *mc){
567
588
  return -1;
568
589
}
569
590
 
 
591
__attribute__((nonnull, warn_unused_result))
570
592
static int init_gnutls_session(gnutls_session_t *session,
571
593
                               mandos_context *mc){
572
594
  int ret;
628
650
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
629
651
                      __attribute__((unused)) const char *txt){}
630
652
 
 
653
/* Set effective uid to 0, return errno */
 
654
__attribute__((warn_unused_result))
 
655
error_t raise_privileges(void){
 
656
  error_t old_errno = errno;
 
657
  error_t ret_errno = 0;
 
658
  if(seteuid(0) == -1){
 
659
    ret_errno = errno;
 
660
  }
 
661
  errno = old_errno;
 
662
  return ret_errno;
 
663
}
 
664
 
 
665
/* Set effective and real user ID to 0.  Return errno. */
 
666
__attribute__((warn_unused_result))
 
667
error_t raise_privileges_permanently(void){
 
668
  error_t old_errno = errno;
 
669
  error_t ret_errno = raise_privileges();
 
670
  if(ret_errno != 0){
 
671
    errno = old_errno;
 
672
    return ret_errno;
 
673
  }
 
674
  if(setuid(0) == -1){
 
675
    ret_errno = errno;
 
676
  }
 
677
  errno = old_errno;
 
678
  return ret_errno;
 
679
}
 
680
 
 
681
/* Set effective user ID to unprivileged saved user ID */
 
682
__attribute__((warn_unused_result))
 
683
error_t lower_privileges(void){
 
684
  error_t old_errno = errno;
 
685
  error_t ret_errno = 0;
 
686
  if(seteuid(uid) == -1){
 
687
    ret_errno = errno;
 
688
  }
 
689
  errno = old_errno;
 
690
  return ret_errno;
 
691
}
 
692
 
 
693
/* Lower privileges permanently */
 
694
__attribute__((warn_unused_result))
 
695
error_t lower_privileges_permanently(void){
 
696
  error_t old_errno = errno;
 
697
  error_t ret_errno = 0;
 
698
  if(setuid(uid) == -1){
 
699
    ret_errno = errno;
 
700
  }
 
701
  errno = old_errno;
 
702
  return ret_errno;
 
703
}
 
704
 
 
705
/* Helper function to add_local_route() and delete_local_route() */
 
706
__attribute__((nonnull, warn_unused_result))
 
707
static bool add_delete_local_route(const bool add,
 
708
                                   const char *address,
 
709
                                   AvahiIfIndex if_index){
 
710
  int ret;
 
711
  char helper[] = "mandos-client-iprouteadddel";
 
712
  char add_arg[] = "add";
 
713
  char delete_arg[] = "delete";
 
714
  char debug_flag[] = "--debug";
 
715
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
716
  if(pluginhelperdir == NULL){
 
717
    if(debug){
 
718
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
719
                   " variable not set; cannot run helper\n");
 
720
    }
 
721
    return false;
 
722
  }
 
723
  
 
724
  char interface[IF_NAMESIZE];
 
725
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
726
    perror_plus("if_indextoname");
 
727
    return false;
 
728
  }
 
729
  
 
730
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
731
  if(devnull == -1){
 
732
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
733
    return false;
 
734
  }
 
735
  pid_t pid = fork();
 
736
  if(pid == 0){
 
737
    /* Child */
 
738
    /* Raise privileges */
 
739
    errno = raise_privileges_permanently();
 
740
    if(errno != 0){
 
741
      perror_plus("Failed to raise privileges");
 
742
      /* _exit(EX_NOPERM); */
 
743
    } else {
 
744
      /* Set group */
 
745
      errno = 0;
 
746
      ret = setgid(0);
 
747
      if(ret == -1){
 
748
        perror_plus("setgid");
 
749
        _exit(EX_NOPERM);
 
750
      }
 
751
      /* Reset supplementary groups */
 
752
      errno = 0;
 
753
      ret = setgroups(0, NULL);
 
754
      if(ret == -1){
 
755
        perror_plus("setgroups");
 
756
        _exit(EX_NOPERM);
 
757
      }
 
758
    }
 
759
    ret = dup2(devnull, STDIN_FILENO);
 
760
    if(ret == -1){
 
761
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
762
      _exit(EX_OSERR);
 
763
    }
 
764
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
765
    if(ret == -1){
 
766
      perror_plus("close");
 
767
      _exit(EX_OSERR);
 
768
    }
 
769
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
770
    if(ret == -1){
 
771
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
772
      _exit(EX_OSERR);
 
773
    }
 
774
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
775
                                                    O_RDONLY
 
776
                                                    | O_DIRECTORY
 
777
                                                    | O_PATH
 
778
                                                    | O_CLOEXEC));
 
779
    if(helperdir_fd == -1){
 
780
      perror_plus("open");
 
781
      _exit(EX_UNAVAILABLE);
 
782
    }
 
783
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
784
                                                   helper, O_RDONLY));
 
785
    if(helper_fd == -1){
 
786
      perror_plus("openat");
 
787
      _exit(EX_UNAVAILABLE);
 
788
    }
 
789
    TEMP_FAILURE_RETRY(close(helperdir_fd));
 
790
#ifdef __GNUC__
 
791
#pragma GCC diagnostic push
 
792
#pragma GCC diagnostic ignored "-Wcast-qual"
 
793
#endif
 
794
    if(fexecve(helper_fd, (char *const [])
 
795
               { helper, add ? add_arg : delete_arg, (char *)address,
 
796
                   interface, debug ? debug_flag : NULL, NULL },
 
797
               environ) == -1){
 
798
#ifdef __GNUC__
 
799
#pragma GCC diagnostic pop
 
800
#endif
 
801
      perror_plus("fexecve");
 
802
      _exit(EXIT_FAILURE);
 
803
    }
 
804
  }
 
805
  if(pid == -1){
 
806
    perror_plus("fork");
 
807
    return false;
 
808
  }
 
809
  int status;
 
810
  pid_t pret = -1;
 
811
  errno = 0;
 
812
  do {
 
813
    pret = waitpid(pid, &status, 0);
 
814
    if(pret == -1 and errno == EINTR and quit_now){
 
815
      int errno_raising = 0;
 
816
      if((errno = raise_privileges()) != 0){
 
817
        errno_raising = errno;
 
818
        perror_plus("Failed to raise privileges in order to"
 
819
                    " kill helper program");
 
820
      }
 
821
      if(kill(pid, SIGTERM) == -1){
 
822
        perror_plus("kill");
 
823
      }
 
824
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
825
        perror_plus("Failed to lower privileges after killing"
 
826
                    " helper program");
 
827
      }
 
828
      return false;
 
829
    }
 
830
  } while(pret == -1 and errno == EINTR);
 
831
  if(pret == -1){
 
832
    perror_plus("waitpid");
 
833
    return false;
 
834
  }
 
835
  if(WIFEXITED(status)){
 
836
    if(WEXITSTATUS(status) != 0){
 
837
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
838
                   " with status %d\n", WEXITSTATUS(status));
 
839
      return false;
 
840
    }
 
841
    return true;
 
842
  }
 
843
  if(WIFSIGNALED(status)){
 
844
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
845
                 " signal %d\n", WTERMSIG(status));
 
846
    return false;
 
847
  }
 
848
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
849
  return false;
 
850
}
 
851
 
 
852
__attribute__((nonnull, warn_unused_result))
 
853
static bool add_local_route(const char *address,
 
854
                            AvahiIfIndex if_index){
 
855
  if(debug){
 
856
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
857
  }
 
858
  return add_delete_local_route(true, address, if_index);
 
859
}
 
860
 
 
861
__attribute__((nonnull, warn_unused_result))
 
862
static bool delete_local_route(const char *address,
 
863
                               AvahiIfIndex if_index){
 
864
  if(debug){
 
865
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
866
  }
 
867
  return add_delete_local_route(false, address, if_index);
 
868
}
 
869
 
631
870
/* Called when a Mandos server is found */
 
871
__attribute__((nonnull, warn_unused_result))
632
872
static int start_mandos_communication(const char *ip, in_port_t port,
633
873
                                      AvahiIfIndex if_index,
634
874
                                      int af, mandos_context *mc){
643
883
  int retval = -1;
644
884
  gnutls_session_t session;
645
885
  int pf;                       /* Protocol family */
 
886
  bool route_added = false;
646
887
  
647
888
  errno = 0;
648
889
  
706
947
                 PRIuMAX "\n", ip, (uintmax_t)port);
707
948
  }
708
949
  
709
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
950
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
710
951
  if(tcp_sd < 0){
711
952
    int e = errno;
712
953
    perror_plus("socket");
740
981
    goto mandos_end;
741
982
  }
742
983
  if(af == AF_INET6){
743
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);    
 
984
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
744
985
    if(IN6_IS_ADDR_LINKLOCAL
745
986
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
746
987
      if(if_index == AVAHI_IF_UNSPEC){
801
1042
    goto mandos_end;
802
1043
  }
803
1044
  
804
 
  if(af == AF_INET6){
805
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
806
 
                  sizeof(struct sockaddr_in6));
807
 
  } else {
808
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
809
 
                  sizeof(struct sockaddr_in));
810
 
  }
811
 
  if(ret < 0){
812
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
813
 
      int e = errno;
814
 
      perror_plus("connect");
815
 
      errno = e;
816
 
    }
817
 
    goto mandos_end;
818
 
  }
819
 
  
820
 
  if(quit_now){
821
 
    errno = EINTR;
822
 
    goto mandos_end;
 
1045
  while(true){
 
1046
    if(af == AF_INET6){
 
1047
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1048
                    sizeof(struct sockaddr_in6));
 
1049
    } else {
 
1050
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1051
                    sizeof(struct sockaddr_in));
 
1052
    }
 
1053
    if(ret < 0){
 
1054
      if(errno == ENETUNREACH
 
1055
         and if_index != AVAHI_IF_UNSPEC
 
1056
         and connect_to == NULL
 
1057
         and not route_added and
 
1058
         ((af == AF_INET6 and not
 
1059
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1060
                                    &to)->sin6_addr)))
 
1061
          or (af == AF_INET and
 
1062
              /* Not a a IPv4LL address */
 
1063
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1064
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1065
        /* Work around Avahi bug - Avahi does not announce link-local
 
1066
           addresses if it has a global address, so local hosts with
 
1067
           *only* a link-local address (e.g. Mandos clients) cannot
 
1068
           connect to a Mandos server announced by Avahi on a server
 
1069
           host with a global address.  Work around this by retrying
 
1070
           with an explicit route added with the server's address.
 
1071
           
 
1072
           Avahi bug reference:
 
1073
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1074
           https://bugs.debian.org/587961
 
1075
        */
 
1076
        if(debug){
 
1077
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1078
                       " direct route\n");
 
1079
        }
 
1080
        int e = errno;
 
1081
        route_added = add_local_route(ip, if_index);
 
1082
        if(route_added){
 
1083
          continue;
 
1084
        }
 
1085
        errno = e;
 
1086
      }
 
1087
      if(errno != ECONNREFUSED or debug){
 
1088
        int e = errno;
 
1089
        perror_plus("connect");
 
1090
        errno = e;
 
1091
      }
 
1092
      goto mandos_end;
 
1093
    }
 
1094
    
 
1095
    if(quit_now){
 
1096
      errno = EINTR;
 
1097
      goto mandos_end;
 
1098
    }
 
1099
    break;
823
1100
  }
824
1101
  
825
1102
  const char *out = mandos_protocol_version;
1008
1285
  
1009
1286
 mandos_end:
1010
1287
  {
 
1288
    if(route_added){
 
1289
      if(not delete_local_route(ip, if_index)){
 
1290
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1291
                     " interface %d", ip, if_index);
 
1292
      }
 
1293
    }
1011
1294
    int e = errno;
1012
1295
    free(decrypted_buffer);
1013
1296
    free(buffer);
1030
1313
  return retval;
1031
1314
}
1032
1315
 
 
1316
__attribute__((nonnull))
1033
1317
static void resolve_callback(AvahiSServiceResolver *r,
1034
1318
                             AvahiIfIndex interface,
1035
1319
                             AvahiProtocol proto,
1043
1327
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1044
1328
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1045
1329
                             flags,
1046
 
                             void* mc){
 
1330
                             void *mc){
1047
1331
  if(r == NULL){
1048
1332
    return;
1049
1333
  }
1052
1336
     timed out */
1053
1337
  
1054
1338
  if(quit_now){
 
1339
    avahi_s_service_resolver_free(r);
1055
1340
    return;
1056
1341
  }
1057
1342
  
1102
1387
                            const char *domain,
1103
1388
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1104
1389
                            flags,
1105
 
                            void* mc){
 
1390
                            void *mc){
1106
1391
  if(b == NULL){
1107
1392
    return;
1108
1393
  }
1168
1453
  errno = old_errno;
1169
1454
}
1170
1455
 
 
1456
__attribute__((nonnull, warn_unused_result))
1171
1457
bool get_flags(const char *ifname, struct ifreq *ifr){
1172
1458
  int ret;
1173
1459
  error_t ret_errno;
1192
1478
  return true;
1193
1479
}
1194
1480
 
 
1481
__attribute__((nonnull, warn_unused_result))
1195
1482
bool good_flags(const char *ifname, const struct ifreq *ifr){
1196
1483
  
1197
1484
  /* Reject the loopback device */
1239
1526
 * corresponds to an acceptable network device.
1240
1527
 * (This function is passed to scandir(3) as a filter function.)
1241
1528
 */
 
1529
__attribute__((nonnull, warn_unused_result))
1242
1530
int good_interface(const struct dirent *if_entry){
1243
1531
  if(if_entry->d_name[0] == '.'){
1244
1532
    return 0;
1262
1550
/* 
1263
1551
 * This function determines if a network interface is up.
1264
1552
 */
 
1553
__attribute__((nonnull, warn_unused_result))
1265
1554
bool interface_is_up(const char *interface){
1266
1555
  struct ifreq ifr;
1267
1556
  if(not get_flags(interface, &ifr)){
1278
1567
/* 
1279
1568
 * This function determines if a network interface is running
1280
1569
 */
 
1570
__attribute__((nonnull, warn_unused_result))
1281
1571
bool interface_is_running(const char *interface){
1282
1572
  struct ifreq ifr;
1283
1573
  if(not get_flags(interface, &ifr)){
1291
1581
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1292
1582
}
1293
1583
 
 
1584
__attribute__((nonnull, pure, warn_unused_result))
1294
1585
int notdotentries(const struct dirent *direntry){
1295
1586
  /* Skip "." and ".." */
1296
1587
  if(direntry->d_name[0] == '.'
1303
1594
}
1304
1595
 
1305
1596
/* Is this directory entry a runnable program? */
 
1597
__attribute__((nonnull, warn_unused_result))
1306
1598
int runnable_hook(const struct dirent *direntry){
1307
1599
  int ret;
1308
1600
  size_t sret;
1316
1608
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1317
1609
                "abcdefghijklmnopqrstuvwxyz"
1318
1610
                "0123456789"
1319
 
                "_-");
 
1611
                "_.-");
1320
1612
  if((direntry->d_name)[sret] != '\0'){
1321
1613
    /* Contains non-allowed characters */
1322
1614
    if(debug){
1326
1618
    return 0;
1327
1619
  }
1328
1620
  
1329
 
  char *fullname = NULL;
1330
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1331
 
  if(ret < 0){
1332
 
    perror_plus("asprintf");
1333
 
    return 0;
1334
 
  }
1335
 
  
1336
 
  ret = stat(fullname, &st);
 
1621
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1337
1622
  if(ret == -1){
1338
1623
    if(debug){
1339
1624
      perror_plus("Could not stat hook");
1363
1648
  return 1;
1364
1649
}
1365
1650
 
 
1651
__attribute__((nonnull, warn_unused_result))
1366
1652
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1367
1653
                            mandos_context *mc){
1368
1654
  int ret;
1372
1658
  
1373
1659
  while(true){
1374
1660
    if(mc->current_server == NULL){
1375
 
      if (debug){
 
1661
      if(debug){
1376
1662
        fprintf_plus(stderr, "Wait until first server is found."
1377
1663
                     " No timeout!\n");
1378
1664
      }
1379
1665
      ret = avahi_simple_poll_iterate(s, -1);
1380
1666
    } else {
1381
 
      if (debug){
 
1667
      if(debug){
1382
1668
        fprintf_plus(stderr, "Check current_server if we should run"
1383
1669
                     " it, or wait\n");
1384
1670
      }
1401
1687
                     - ((intmax_t)waited_time.tv_sec * 1000))
1402
1688
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1403
1689
      
1404
 
      if (debug){
 
1690
      if(debug){
1405
1691
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1406
1692
                     block_time);
1407
1693
      }
1429
1715
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1430
1716
    }
1431
1717
    if(ret != 0){
1432
 
      if (ret > 0 or errno != EINTR){
 
1718
      if(ret > 0 or errno != EINTR){
1433
1719
        return (ret != 1) ? ret : 0;
1434
1720
      }
1435
1721
    }
1436
1722
  }
1437
1723
}
1438
1724
 
1439
 
/* Set effective uid to 0, return errno */
1440
 
error_t raise_privileges(void){
1441
 
  error_t old_errno = errno;
1442
 
  error_t ret_errno = 0;
1443
 
  if(seteuid(0) == -1){
1444
 
    ret_errno = errno;
1445
 
    perror_plus("seteuid");
1446
 
  }
1447
 
  errno = old_errno;
1448
 
  return ret_errno;
1449
 
}
1450
 
 
1451
 
/* Set effective and real user ID to 0.  Return errno. */
1452
 
error_t raise_privileges_permanently(void){
1453
 
  error_t old_errno = errno;
1454
 
  error_t ret_errno = raise_privileges();
1455
 
  if(ret_errno != 0){
1456
 
    errno = old_errno;
1457
 
    return ret_errno;
1458
 
  }
1459
 
  if(setuid(0) == -1){
1460
 
    ret_errno = errno;
1461
 
    perror_plus("seteuid");
1462
 
  }
1463
 
  errno = old_errno;
1464
 
  return ret_errno;
1465
 
}
1466
 
 
1467
 
/* Set effective user ID to unprivileged saved user ID */
1468
 
error_t lower_privileges(void){
1469
 
  error_t old_errno = errno;
1470
 
  error_t ret_errno = 0;
1471
 
  if(seteuid(uid) == -1){
1472
 
    ret_errno = errno;
1473
 
    perror_plus("seteuid");
1474
 
  }
1475
 
  errno = old_errno;
1476
 
  return ret_errno;
1477
 
}
1478
 
 
1479
 
/* Lower privileges permanently */
1480
 
error_t lower_privileges_permanently(void){
1481
 
  error_t old_errno = errno;
1482
 
  error_t ret_errno = 0;
1483
 
  if(setuid(uid) == -1){
1484
 
    ret_errno = errno;
1485
 
    perror_plus("setuid");
1486
 
  }
1487
 
  errno = old_errno;
1488
 
  return ret_errno;
1489
 
}
1490
 
 
1491
 
bool run_network_hooks(const char *mode, const char *interface,
 
1725
__attribute__((nonnull))
 
1726
void run_network_hooks(const char *mode, const char *interface,
1492
1727
                       const float delay){
1493
 
  struct dirent **direntries;
1494
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1495
 
                         alphasort);
 
1728
  struct dirent **direntries = NULL;
 
1729
  if(hookdir_fd == -1){
 
1730
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1731
                      | O_CLOEXEC);
 
1732
    if(hookdir_fd == -1){
 
1733
      if(errno == ENOENT){
 
1734
        if(debug){
 
1735
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1736
                       " found\n", hookdir);
 
1737
        }
 
1738
      } else {
 
1739
        perror_plus("open");
 
1740
      }
 
1741
      return;
 
1742
    }
 
1743
  }
 
1744
#ifdef __GLIBC__
 
1745
#if __GLIBC_PREREQ(2, 15)
 
1746
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1747
                           runnable_hook, alphasort);
 
1748
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1749
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1750
                         alphasort);
 
1751
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1752
#else   /* not __GLIBC__ */
 
1753
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1754
                         alphasort);
 
1755
#endif  /* not __GLIBC__ */
1496
1756
  if(numhooks == -1){
1497
 
    if(errno == ENOENT){
1498
 
      if(debug){
1499
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1500
 
                     " found\n", hookdir);
1501
 
      }
1502
 
    } else {
1503
 
      perror_plus("scandir");
 
1757
    perror_plus("scandir");
 
1758
    return;
 
1759
  }
 
1760
  struct dirent *direntry;
 
1761
  int ret;
 
1762
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1763
  if(devnull == -1){
 
1764
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1765
    return;
 
1766
  }
 
1767
  for(int i = 0; i < numhooks; i++){
 
1768
    direntry = direntries[i];
 
1769
    if(debug){
 
1770
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1771
                   direntry->d_name);
1504
1772
    }
1505
 
  } else {
1506
 
    struct dirent *direntry;
1507
 
    int ret;
1508
 
    int devnull = open("/dev/null", O_RDONLY);
1509
 
    for(int i = 0; i < numhooks; i++){
1510
 
      direntry = direntries[i];
1511
 
      char *fullname = NULL;
1512
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1513
 
      if(ret < 0){
 
1773
    pid_t hook_pid = fork();
 
1774
    if(hook_pid == 0){
 
1775
      /* Child */
 
1776
      /* Raise privileges */
 
1777
      errno = raise_privileges_permanently();
 
1778
      if(errno != 0){
 
1779
        perror_plus("Failed to raise privileges");
 
1780
        _exit(EX_NOPERM);
 
1781
      }
 
1782
      /* Set group */
 
1783
      errno = 0;
 
1784
      ret = setgid(0);
 
1785
      if(ret == -1){
 
1786
        perror_plus("setgid");
 
1787
        _exit(EX_NOPERM);
 
1788
      }
 
1789
      /* Reset supplementary groups */
 
1790
      errno = 0;
 
1791
      ret = setgroups(0, NULL);
 
1792
      if(ret == -1){
 
1793
        perror_plus("setgroups");
 
1794
        _exit(EX_NOPERM);
 
1795
      }
 
1796
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1797
      if(ret == -1){
 
1798
        perror_plus("setenv");
 
1799
        _exit(EX_OSERR);
 
1800
      }
 
1801
      ret = setenv("DEVICE", interface, 1);
 
1802
      if(ret == -1){
 
1803
        perror_plus("setenv");
 
1804
        _exit(EX_OSERR);
 
1805
      }
 
1806
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1807
      if(ret == -1){
 
1808
        perror_plus("setenv");
 
1809
        _exit(EX_OSERR);
 
1810
      }
 
1811
      ret = setenv("MODE", mode, 1);
 
1812
      if(ret == -1){
 
1813
        perror_plus("setenv");
 
1814
        _exit(EX_OSERR);
 
1815
      }
 
1816
      char *delaystring;
 
1817
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1818
      if(ret == -1){
1514
1819
        perror_plus("asprintf");
1515
 
        continue;
1516
 
      }
1517
 
      if(debug){
1518
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1519
 
                     direntry->d_name);
1520
 
      }
1521
 
      pid_t hook_pid = fork();
1522
 
      if(hook_pid == 0){
1523
 
        /* Child */
1524
 
        /* Raise privileges */
1525
 
        raise_privileges_permanently();
1526
 
        /* Set group */
1527
 
        errno = 0;
1528
 
        ret = setgid(0);
1529
 
        if(ret == -1){
1530
 
          perror_plus("setgid");
1531
 
        }
1532
 
        /* Reset supplementary groups */
1533
 
        errno = 0;
1534
 
        ret = setgroups(0, NULL);
1535
 
        if(ret == -1){
1536
 
          perror_plus("setgroups");
1537
 
        }
1538
 
        dup2(devnull, STDIN_FILENO);
1539
 
        close(devnull);
1540
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1541
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1542
 
        if(ret == -1){
1543
 
          perror_plus("setenv");
1544
 
          _exit(EX_OSERR);
1545
 
        }
1546
 
        ret = setenv("DEVICE", interface, 1);
1547
 
        if(ret == -1){
1548
 
          perror_plus("setenv");
1549
 
          _exit(EX_OSERR);
1550
 
        }
1551
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1552
 
        if(ret == -1){
1553
 
          perror_plus("setenv");
1554
 
          _exit(EX_OSERR);
1555
 
        }
1556
 
        ret = setenv("MODE", mode, 1);
1557
 
        if(ret == -1){
1558
 
          perror_plus("setenv");
1559
 
          _exit(EX_OSERR);
1560
 
        }
1561
 
        char *delaystring;
1562
 
        ret = asprintf(&delaystring, "%f", delay);
1563
 
        if(ret == -1){
1564
 
          perror_plus("asprintf");
1565
 
          _exit(EX_OSERR);
1566
 
        }
1567
 
        ret = setenv("DELAY", delaystring, 1);
1568
 
        if(ret == -1){
1569
 
          free(delaystring);
1570
 
          perror_plus("setenv");
1571
 
          _exit(EX_OSERR);
1572
 
        }
 
1820
        _exit(EX_OSERR);
 
1821
      }
 
1822
      ret = setenv("DELAY", delaystring, 1);
 
1823
      if(ret == -1){
1573
1824
        free(delaystring);
1574
 
        if(connect_to != NULL){
1575
 
          ret = setenv("CONNECT", connect_to, 1);
1576
 
          if(ret == -1){
1577
 
            perror_plus("setenv");
1578
 
            _exit(EX_OSERR);
1579
 
          }
1580
 
        }
1581
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1582
 
          perror_plus("execl");
1583
 
          _exit(EXIT_FAILURE);
1584
 
        }
 
1825
        perror_plus("setenv");
 
1826
        _exit(EX_OSERR);
 
1827
      }
 
1828
      free(delaystring);
 
1829
      if(connect_to != NULL){
 
1830
        ret = setenv("CONNECT", connect_to, 1);
 
1831
        if(ret == -1){
 
1832
          perror_plus("setenv");
 
1833
          _exit(EX_OSERR);
 
1834
        }
 
1835
      }
 
1836
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1837
                                                   direntry->d_name,
 
1838
                                                   O_RDONLY));
 
1839
      if(hook_fd == -1){
 
1840
        perror_plus("openat");
 
1841
        _exit(EXIT_FAILURE);
 
1842
      }
 
1843
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1844
        perror_plus("close");
 
1845
        _exit(EXIT_FAILURE);
 
1846
      }
 
1847
      ret = dup2(devnull, STDIN_FILENO);
 
1848
      if(ret == -1){
 
1849
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1850
        _exit(EX_OSERR);
 
1851
      }
 
1852
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
1853
      if(ret == -1){
 
1854
        perror_plus("close");
 
1855
        _exit(EX_OSERR);
 
1856
      }
 
1857
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1858
      if(ret == -1){
 
1859
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1860
        _exit(EX_OSERR);
 
1861
      }
 
1862
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
1863
                 environ) == -1){
 
1864
        perror_plus("fexecve");
 
1865
        _exit(EXIT_FAILURE);
 
1866
      }
 
1867
    } else {
 
1868
      if(hook_pid == -1){
 
1869
        perror_plus("fork");
 
1870
        free(direntry);
 
1871
        continue;
 
1872
      }
 
1873
      int status;
 
1874
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1875
        perror_plus("waitpid");
 
1876
        free(direntry);
 
1877
        continue;
 
1878
      }
 
1879
      if(WIFEXITED(status)){
 
1880
        if(WEXITSTATUS(status) != 0){
 
1881
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1882
                       " with status %d\n", direntry->d_name,
 
1883
                       WEXITSTATUS(status));
 
1884
          free(direntry);
 
1885
          continue;
 
1886
        }
 
1887
      } else if(WIFSIGNALED(status)){
 
1888
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1889
                     " signal %d\n", direntry->d_name,
 
1890
                     WTERMSIG(status));
 
1891
        free(direntry);
 
1892
        continue;
1585
1893
      } else {
1586
 
        int status;
1587
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1588
 
          perror_plus("waitpid");
1589
 
          free(fullname);
1590
 
          continue;
1591
 
        }
1592
 
        if(WIFEXITED(status)){
1593
 
          if(WEXITSTATUS(status) != 0){
1594
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1595
 
                         " with status %d\n", direntry->d_name,
1596
 
                         WEXITSTATUS(status));
1597
 
            free(fullname);
1598
 
            continue;
1599
 
          }
1600
 
        } else if(WIFSIGNALED(status)){
1601
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1602
 
                       " signal %d\n", direntry->d_name,
1603
 
                       WTERMSIG(status));
1604
 
          free(fullname);
1605
 
          continue;
1606
 
        } else {
1607
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1608
 
                       " crashed\n", direntry->d_name);
1609
 
          free(fullname);
1610
 
          continue;
1611
 
        }
1612
 
      }
1613
 
      free(fullname);
1614
 
      if(debug){
1615
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1616
 
                     direntry->d_name);
1617
 
      }
1618
 
    }
1619
 
    close(devnull);
1620
 
  }
1621
 
  return true;
 
1894
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1895
                     " crashed\n", direntry->d_name);
 
1896
        free(direntry);
 
1897
        continue;
 
1898
      }
 
1899
    }
 
1900
    if(debug){
 
1901
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1902
                   direntry->d_name);
 
1903
    }
 
1904
    free(direntry);
 
1905
  }
 
1906
  free(direntries);
 
1907
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1908
    perror_plus("close");
 
1909
  } else {
 
1910
    hookdir_fd = -1;
 
1911
  }
 
1912
  close(devnull);
1622
1913
}
1623
1914
 
 
1915
__attribute__((nonnull, warn_unused_result))
1624
1916
error_t bring_up_interface(const char *const interface,
1625
1917
                           const float delay){
1626
 
  int sd = -1;
1627
1918
  error_t old_errno = errno;
1628
 
  error_t ret_errno = 0;
1629
 
  int ret, ret_setflags;
 
1919
  int ret;
1630
1920
  struct ifreq network;
1631
1921
  unsigned int if_index = if_nametoindex(interface);
1632
1922
  if(if_index == 0){
1641
1931
  }
1642
1932
  
1643
1933
  if(not interface_is_up(interface)){
1644
 
    if(not get_flags(interface, &network) and debug){
 
1934
    error_t ret_errno = 0, ioctl_errno = 0;
 
1935
    if(not get_flags(interface, &network)){
1645
1936
      ret_errno = errno;
1646
1937
      fprintf_plus(stderr, "Failed to get flags for interface "
1647
1938
                   "\"%s\"\n", interface);
 
1939
      errno = old_errno;
1648
1940
      return ret_errno;
1649
1941
    }
1650
 
    network.ifr_flags |= IFF_UP;
 
1942
    network.ifr_flags |= IFF_UP; /* set flag */
1651
1943
    
1652
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1653
 
    if(sd < 0){
 
1944
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1945
    if(sd == -1){
1654
1946
      ret_errno = errno;
1655
1947
      perror_plus("socket");
1656
1948
      errno = old_errno;
1657
1949
      return ret_errno;
1658
1950
    }
1659
 
  
 
1951
    
1660
1952
    if(quit_now){
1661
 
      close(sd);
 
1953
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1954
      if(ret == -1){
 
1955
        perror_plus("close");
 
1956
      }
1662
1957
      errno = old_errno;
1663
1958
      return EINTR;
1664
1959
    }
1668
1963
                   interface);
1669
1964
    }
1670
1965
    
1671
 
    /* Raise priviliges */
1672
 
    raise_privileges();
 
1966
    /* Raise privileges */
 
1967
    ret_errno = raise_privileges();
 
1968
    if(ret_errno != 0){
 
1969
      errno = ret_errno;
 
1970
      perror_plus("Failed to raise privileges");
 
1971
    }
1673
1972
    
1674
1973
#ifdef __linux__
1675
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1676
 
       messages about the network interface to mess up the prompt */
1677
 
    int ret_linux = klogctl(8, NULL, 5);
1678
 
    bool restore_loglevel = true;
1679
 
    if(ret_linux == -1){
1680
 
      restore_loglevel = false;
1681
 
      perror_plus("klogctl");
 
1974
    int ret_linux;
 
1975
    bool restore_loglevel = false;
 
1976
    if(ret_errno == 0){
 
1977
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1978
         messages about the network interface to mess up the prompt */
 
1979
      ret_linux = klogctl(8, NULL, 5);
 
1980
      if(ret_linux == -1){
 
1981
        perror_plus("klogctl");
 
1982
      } else {
 
1983
        restore_loglevel = true;
 
1984
      }
1682
1985
    }
1683
1986
#endif  /* __linux__ */
1684
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1685
 
    ret_errno = errno;
 
1987
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1988
    ioctl_errno = errno;
1686
1989
#ifdef __linux__
1687
1990
    if(restore_loglevel){
1688
1991
      ret_linux = klogctl(7, NULL, 0);
1692
1995
    }
1693
1996
#endif  /* __linux__ */
1694
1997
    
1695
 
    /* Lower privileges */
1696
 
    lower_privileges();
 
1998
    /* If raise_privileges() succeeded above */
 
1999
    if(ret_errno == 0){
 
2000
      /* Lower privileges */
 
2001
      ret_errno = lower_privileges();
 
2002
      if(ret_errno != 0){
 
2003
        errno = ret_errno;
 
2004
        perror_plus("Failed to lower privileges");
 
2005
      }
 
2006
    }
1697
2007
    
1698
2008
    /* Close the socket */
1699
2009
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1702
2012
    }
1703
2013
    
1704
2014
    if(ret_setflags == -1){
1705
 
      errno = ret_errno;
 
2015
      errno = ioctl_errno;
1706
2016
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1707
2017
      errno = old_errno;
1708
 
      return ret_errno;
 
2018
      return ioctl_errno;
1709
2019
    }
1710
2020
  } else if(debug){
1711
2021
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1729
2039
  return 0;
1730
2040
}
1731
2041
 
 
2042
__attribute__((nonnull, warn_unused_result))
1732
2043
error_t take_down_interface(const char *const interface){
1733
2044
  error_t old_errno = errno;
1734
2045
  struct ifreq network;
1739
2050
    return ENXIO;
1740
2051
  }
1741
2052
  if(interface_is_up(interface)){
1742
 
    error_t ret_errno = 0;
 
2053
    error_t ret_errno = 0, ioctl_errno = 0;
1743
2054
    if(not get_flags(interface, &network) and debug){
1744
2055
      ret_errno = errno;
1745
2056
      fprintf_plus(stderr, "Failed to get flags for interface "
1746
2057
                   "\"%s\"\n", interface);
 
2058
      errno = old_errno;
1747
2059
      return ret_errno;
1748
2060
    }
1749
2061
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1750
2062
    
1751
2063
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1752
 
    if(sd < 0){
 
2064
    if(sd == -1){
1753
2065
      ret_errno = errno;
1754
2066
      perror_plus("socket");
1755
2067
      errno = old_errno;
1761
2073
                   interface);
1762
2074
    }
1763
2075
    
1764
 
    /* Raise priviliges */
1765
 
    raise_privileges();
 
2076
    /* Raise privileges */
 
2077
    ret_errno = raise_privileges();
 
2078
    if(ret_errno != 0){
 
2079
      errno = ret_errno;
 
2080
      perror_plus("Failed to raise privileges");
 
2081
    }
1766
2082
    
1767
2083
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1768
 
    ret_errno = errno;
 
2084
    ioctl_errno = errno;
1769
2085
    
1770
 
    /* Lower privileges */
1771
 
    lower_privileges();
 
2086
    /* If raise_privileges() succeeded above */
 
2087
    if(ret_errno == 0){
 
2088
      /* Lower privileges */
 
2089
      ret_errno = lower_privileges();
 
2090
      if(ret_errno != 0){
 
2091
        errno = ret_errno;
 
2092
        perror_plus("Failed to lower privileges");
 
2093
      }
 
2094
    }
1772
2095
    
1773
2096
    /* Close the socket */
1774
2097
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1777
2100
    }
1778
2101
    
1779
2102
    if(ret_setflags == -1){
1780
 
      errno = ret_errno;
 
2103
      errno = ioctl_errno;
1781
2104
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1782
2105
      errno = old_errno;
1783
 
      return ret_errno;
 
2106
      return ioctl_errno;
1784
2107
    }
1785
2108
  } else if(debug){
1786
2109
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1794
2117
int main(int argc, char *argv[]){
1795
2118
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1796
2119
                        .priority = "SECURE256:!CTYPE-X.509:"
1797
 
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
2120
                        "+CTYPE-OPENPGP", .current_server = NULL,
1798
2121
                        .interfaces = NULL, .interfaces_size = 0 };
1799
2122
  AvahiSServiceBrowser *sb = NULL;
1800
2123
  error_t ret_errno;
1804
2127
  int exitcode = EXIT_SUCCESS;
1805
2128
  char *interfaces_to_take_down = NULL;
1806
2129
  size_t interfaces_to_take_down_size = 0;
1807
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1808
 
  bool tempdir_created = false;
 
2130
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
2131
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
2132
  char *tempdir = NULL;
1809
2133
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1810
2134
  const char *seckey = PATHDIR "/" SECKEY;
1811
2135
  const char *pubkey = PATHDIR "/" PUBKEY;
1988
2312
      goto end;
1989
2313
    }
1990
2314
  }
1991
 
    
 
2315
  
1992
2316
  {
1993
2317
    /* Work around Debian bug #633582:
1994
2318
       <http://bugs.debian.org/633582> */
1995
2319
    
1996
 
    /* Re-raise priviliges */
1997
 
    if(raise_privileges() == 0){
 
2320
    /* Re-raise privileges */
 
2321
    ret_errno = raise_privileges();
 
2322
    if(ret_errno != 0){
 
2323
      errno = ret_errno;
 
2324
      perror_plus("Failed to raise privileges");
 
2325
    } else {
1998
2326
      struct stat st;
1999
2327
      
2000
2328
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2017
2345
          TEMP_FAILURE_RETRY(close(seckey_fd));
2018
2346
        }
2019
2347
      }
2020
 
    
 
2348
      
2021
2349
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2022
2350
        int pubkey_fd = open(pubkey, O_RDONLY);
2023
2351
        if(pubkey_fd == -1){
2038
2366
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2039
2367
        }
2040
2368
      }
2041
 
    
 
2369
      
2042
2370
      /* Lower privileges */
2043
 
      lower_privileges();
 
2371
      ret_errno = lower_privileges();
 
2372
      if(ret_errno != 0){
 
2373
        errno = ret_errno;
 
2374
        perror_plus("Failed to lower privileges");
 
2375
      }
2044
2376
    }
2045
2377
  }
2046
2378
  
2072
2404
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2073
2405
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2074
2406
    }
2075
 
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
2076
 
                             interfaces_hooks : "", delay)){
2077
 
      goto end;
2078
 
    }
 
2407
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2408
                      interfaces_hooks : "", delay);
2079
2409
  }
2080
2410
  
2081
2411
  if(not debug){
2159
2489
  
2160
2490
  /* If no interfaces were specified, make a list */
2161
2491
  if(mc.interfaces == NULL){
2162
 
    struct dirent **direntries;
 
2492
    struct dirent **direntries = NULL;
2163
2493
    /* Look for any good interfaces */
2164
2494
    ret = scandir(sys_class_net, &direntries, good_interface,
2165
2495
                  alphasort);
2171
2501
        if(ret_errno != 0){
2172
2502
          errno = ret_errno;
2173
2503
          perror_plus("argz_add");
 
2504
          free(direntries[i]);
2174
2505
          continue;
2175
2506
        }
2176
2507
        if(debug){
2177
2508
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2178
2509
                       direntries[i]->d_name);
2179
2510
        }
 
2511
        free(direntries[i]);
2180
2512
      }
2181
2513
      free(direntries);
2182
2514
    } else {
2183
 
      free(direntries);
 
2515
      if(ret == 0){
 
2516
        free(direntries);
 
2517
      }
2184
2518
      fprintf_plus(stderr, "Could not find a network interface\n");
2185
2519
      exitcode = EXIT_FAILURE;
2186
2520
      goto end;
2209
2543
        break;
2210
2544
      }
2211
2545
      bool interface_was_up = interface_is_up(interface);
2212
 
      ret = bring_up_interface(interface, delay);
 
2546
      errno = bring_up_interface(interface, delay);
2213
2547
      if(not interface_was_up){
2214
 
        if(ret != 0){
2215
 
          errno = ret;
 
2548
        if(errno != 0){
2216
2549
          perror_plus("Failed to bring up interface");
2217
2550
        } else {
2218
 
          ret_errno = argz_add(&interfaces_to_take_down,
2219
 
                               &interfaces_to_take_down_size,
2220
 
                               interface);
2221
 
          if(ret_errno != 0){
2222
 
            errno = ret_errno;
 
2551
          errno = argz_add(&interfaces_to_take_down,
 
2552
                           &interfaces_to_take_down_size,
 
2553
                           interface);
 
2554
          if(errno != 0){
2223
2555
            perror_plus("argz_add");
2224
2556
          }
2225
2557
        }
2256
2588
    goto end;
2257
2589
  }
2258
2590
  
2259
 
  if(mkdtemp(tempdir) == NULL){
 
2591
  /* Try /run/tmp before /tmp */
 
2592
  tempdir = mkdtemp(run_tempdir);
 
2593
  if(tempdir == NULL and errno == ENOENT){
 
2594
      if(debug){
 
2595
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2596
                     run_tempdir, old_tempdir);
 
2597
      }
 
2598
      tempdir = mkdtemp(old_tempdir);
 
2599
  }
 
2600
  if(tempdir == NULL){
2260
2601
    perror_plus("mkdtemp");
2261
2602
    goto end;
2262
2603
  }
2263
 
  tempdir_created = true;
2264
2604
  
2265
2605
  if(quit_now){
2266
2606
    goto end;
2341
2681
      sleep((unsigned int)retry_interval);
2342
2682
    }
2343
2683
    
2344
 
    if (not quit_now){
 
2684
    if(not quit_now){
2345
2685
      exitcode = EXIT_SUCCESS;
2346
2686
    }
2347
2687
    
2402
2742
  if(debug){
2403
2743
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2404
2744
  }
2405
 
 
 
2745
  
2406
2746
  ret = avahi_loop_with_timeout(simple_poll,
2407
2747
                                (int)(retry_interval * 1000), &mc);
2408
2748
  if(debug){
2444
2784
    mc.current_server->prev->next = NULL;
2445
2785
    while(mc.current_server != NULL){
2446
2786
      server *next = mc.current_server->next;
 
2787
#ifdef __GNUC__
 
2788
#pragma GCC diagnostic push
 
2789
#pragma GCC diagnostic ignored "-Wcast-qual"
 
2790
#endif
 
2791
      free((char *)(mc.current_server->ip));
 
2792
#ifdef __GNUC__
 
2793
#pragma GCC diagnostic pop
 
2794
#endif
2447
2795
      free(mc.current_server);
2448
2796
      mc.current_server = next;
2449
2797
    }
2450
2798
  }
2451
2799
  
2452
 
  /* Re-raise priviliges */
 
2800
  /* Re-raise privileges */
2453
2801
  {
2454
 
    raise_privileges();
2455
 
    
2456
 
    /* Run network hooks */
2457
 
    run_network_hooks("stop", interfaces_hooks != NULL ?
2458
 
                      interfaces_hooks : "", delay);
2459
 
    
2460
 
    /* Take down the network interfaces which were brought up */
2461
 
    {
2462
 
      char *interface = NULL;
2463
 
      while((interface=argz_next(interfaces_to_take_down,
2464
 
                                 interfaces_to_take_down_size,
2465
 
                                 interface))){
2466
 
        ret_errno = take_down_interface(interface);
2467
 
        if(ret_errno != 0){
2468
 
          errno = ret_errno;
2469
 
          perror_plus("Failed to take down interface");
2470
 
        }
2471
 
      }
2472
 
      if(debug and (interfaces_to_take_down == NULL)){
2473
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2474
 
                     " down\n");
2475
 
      }
2476
 
    }
2477
 
    
2478
 
    lower_privileges_permanently();
 
2802
    ret_errno = raise_privileges();
 
2803
    if(ret_errno != 0){
 
2804
      errno = ret_errno;
 
2805
      perror_plus("Failed to raise privileges");
 
2806
    } else {
 
2807
      
 
2808
      /* Run network hooks */
 
2809
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2810
                        interfaces_hooks : "", delay);
 
2811
      
 
2812
      /* Take down the network interfaces which were brought up */
 
2813
      {
 
2814
        char *interface = NULL;
 
2815
        while((interface=argz_next(interfaces_to_take_down,
 
2816
                                   interfaces_to_take_down_size,
 
2817
                                   interface))){
 
2818
          ret_errno = take_down_interface(interface);
 
2819
          if(ret_errno != 0){
 
2820
            errno = ret_errno;
 
2821
            perror_plus("Failed to take down interface");
 
2822
          }
 
2823
        }
 
2824
        if(debug and (interfaces_to_take_down == NULL)){
 
2825
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2826
                       " down\n");
 
2827
        }
 
2828
      }
 
2829
    }
 
2830
    
 
2831
    ret_errno = lower_privileges_permanently();
 
2832
    if(ret_errno != 0){
 
2833
      errno = ret_errno;
 
2834
      perror_plus("Failed to lower privileges permanently");
 
2835
    }
2479
2836
  }
2480
2837
  
2481
2838
  free(interfaces_to_take_down);
2482
2839
  free(interfaces_hooks);
2483
2840
  
2484
2841
  /* Removes the GPGME temp directory and all files inside */
2485
 
  if(tempdir_created){
 
2842
  if(tempdir != NULL){
2486
2843
    struct dirent **direntries = NULL;
2487
 
    struct dirent *direntry = NULL;
2488
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2489
 
                             alphasort);
2490
 
    if (numentries > 0){
2491
 
      for(int i = 0; i < numentries; i++){
2492
 
        direntry = direntries[i];
2493
 
        char *fullname = NULL;
2494
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2495
 
                       direntry->d_name);
2496
 
        if(ret < 0){
2497
 
          perror_plus("asprintf");
2498
 
          continue;
2499
 
        }
2500
 
        ret = remove(fullname);
2501
 
        if(ret == -1){
2502
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2503
 
                       strerror(errno));
2504
 
        }
2505
 
        free(fullname);
 
2844
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
2845
                                                  | O_NOFOLLOW
 
2846
                                                  | O_DIRECTORY
 
2847
                                                  | O_PATH));
 
2848
    if(tempdir_fd == -1){
 
2849
      perror_plus("open");
 
2850
    } else {
 
2851
#ifdef __GLIBC__
 
2852
#if __GLIBC_PREREQ(2, 15)
 
2853
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2854
                                 notdotentries, alphasort);
 
2855
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2856
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2857
                               alphasort);
 
2858
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2859
#else   /* not __GLIBC__ */
 
2860
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2861
                               alphasort);
 
2862
#endif  /* not __GLIBC__ */
 
2863
      if(numentries >= 0){
 
2864
        for(int i = 0; i < numentries; i++){
 
2865
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2866
          if(ret == -1){
 
2867
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2868
                         " \"%s\", 0): %s\n", tempdir,
 
2869
                         direntries[i]->d_name, strerror(errno));
 
2870
          }
 
2871
          free(direntries[i]);
 
2872
        }
 
2873
        
 
2874
        /* need to clean even if 0 because man page doesn't specify */
 
2875
        free(direntries);
 
2876
        if(numentries == -1){
 
2877
          perror_plus("scandir");
 
2878
        }
 
2879
        ret = rmdir(tempdir);
 
2880
        if(ret == -1 and errno != ENOENT){
 
2881
          perror_plus("rmdir");
 
2882
        }
2506
2883
      }
2507
 
    }
2508
 
 
2509
 
    /* need to clean even if 0 because man page doesn't specify */
2510
 
    free(direntries);
2511
 
    if (numentries == -1){
2512
 
      perror_plus("scandir");
2513
 
    }
2514
 
    ret = rmdir(tempdir);
2515
 
    if(ret == -1 and errno != ENOENT){
2516
 
      perror_plus("rmdir");
 
2884
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2517
2885
    }
2518
2886
  }
2519
2887