/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: 2012-06-16 23:25:46 UTC
  • Revision ID: teddy@recompile.se-20120616232546-dcrkmnhd4yhq6mvd
* plugins.d/mandos-client (mandos_context): Moved to inside "main()".
                                            All users changed.
  (add_server): Take new "current_server" argument; all callers
                changed.
  (init_gpgme, pgp_packet_decrypt, init_gnutls_global,
  init_gnutls_session, start_mandos_communication,
  avahi_loop_with_timeout): Take new "mc" argument"; all callers
                            changed.
  (resolve_callback, browse_callback): Handle void pointer userdata as
                                       "mc", a pointer to
                                       mandos_context.  All callers
                                       changed.
  (main): New "mc" variable.

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-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 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  /* not _LARGEFILE_SOURCE */
 
35
#endif
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror() */
 
43
                                   stdout, ferror(), remove() */
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(),
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
58
                                   inet_pton(), connect() */
 
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit(),
77
 
                                   unlinkat() */
78
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
75
                                   setgid(), pause(), _exit() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
79
77
#include <iso646.h>             /* not, or, and */
80
78
#include <argp.h>               /* struct argp_option, error_t, struct
81
79
                                   argp_state, struct argp,
93
91
                                   argz_delete(), argz_append(),
94
92
                                   argz_stringify(), argz_add(),
95
93
                                   argz_count() */
96
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
97
 
                                   EAI_SYSTEM, gai_strerror() */
98
94
 
99
95
#ifdef __linux__
100
96
#include <sys/klog.h>           /* klogctl() */
142
138
static const char sys_class_net[] = "/sys/class/net";
143
139
char *connect_to = NULL;
144
140
const char *hookdir = HOOKDIR;
145
 
int hookdir_fd = -1;
146
141
uid_t uid = 65534;
147
142
gid_t gid = 65534;
148
143
 
166
161
  const char *priority;
167
162
  gpgme_ctx_t ctx;
168
163
  server *current_server;
169
 
  char *interfaces;
170
 
  size_t interfaces_size;
171
164
} mandos_context;
172
165
 
173
166
/* global so signal handler can reach it*/
185
178
  perror(print_text);
186
179
}
187
180
 
188
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
181
__attribute__((format (gnu_printf, 2, 3)))
189
182
int fprintf_plus(FILE *stream, const char *format, ...){
190
183
  va_list ap;
191
184
  va_start (ap, format);
192
185
  
193
186
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
194
187
                             program_invocation_short_name));
195
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
188
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
196
189
}
197
190
 
198
191
/*
200
193
 * bytes. "buffer_capacity" is how much is currently allocated,
201
194
 * "buffer_length" is how much is already used.
202
195
 */
203
 
__attribute__((nonnull, warn_unused_result))
204
196
size_t incbuffer(char **buffer, size_t buffer_length,
205
197
                 size_t buffer_capacity){
206
198
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
207
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
208
 
    if(new_buf == NULL){
209
 
      int old_errno = errno;
210
 
      free(*buffer);
211
 
      errno = old_errno;
212
 
      *buffer = NULL;
 
199
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
200
    if(buffer == NULL){
213
201
      return 0;
214
202
    }
215
 
    *buffer = new_buf;
216
203
    buffer_capacity += BUFFER_SIZE;
217
204
  }
218
205
  return buffer_capacity;
219
206
}
220
207
 
221
208
/* Add server to set of servers to retry periodically */
222
 
__attribute__((nonnull, warn_unused_result))
223
209
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
224
210
                int af, server **current_server){
225
211
  int ret;
234
220
                          .af = af };
235
221
  if(new_server->ip == NULL){
236
222
    perror_plus("strdup");
237
 
    free(new_server);
238
 
    return false;
239
 
  }
240
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
 
  if(ret == -1){
242
 
    perror_plus("clock_gettime");
243
 
#ifdef __GNUC__
244
 
#pragma GCC diagnostic push
245
 
#pragma GCC diagnostic ignored "-Wcast-qual"
246
 
#endif
247
 
    free((char *)(new_server->ip));
248
 
#ifdef __GNUC__
249
 
#pragma GCC diagnostic pop
250
 
#endif
251
 
    free(new_server);
252
223
    return false;
253
224
  }
254
225
  /* Special case of first server */
256
227
    new_server->next = new_server;
257
228
    new_server->prev = new_server;
258
229
    *current_server = new_server;
 
230
  /* Place the new server last in the list */
259
231
  } else {
260
 
    /* Place the new server last in the list */
261
232
    new_server->next = *current_server;
262
233
    new_server->prev = (*current_server)->prev;
263
234
    new_server->prev->next = new_server;
264
235
    (*current_server)->prev = new_server;
265
236
  }
 
237
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
 
238
  if(ret == -1){
 
239
    perror_plus("clock_gettime");
 
240
    return false;
 
241
  }
266
242
  return true;
267
243
}
268
244
 
269
245
/* 
270
246
 * Initialize GPGME.
271
247
 */
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){
 
248
static bool init_gpgme(const char *seckey, const char *pubkey,
 
249
                       const char *tempdir, mandos_context *mc){
277
250
  gpgme_error_t rc;
278
251
  gpgme_engine_info_t engine_info;
279
252
  
280
253
  /*
281
254
   * Helper function to insert pub and seckey to the engine keyring.
282
255
   */
283
 
  bool import_key(const char * const filename){
 
256
  bool import_key(const char *filename){
284
257
    int ret;
285
258
    int fd;
286
259
    gpgme_data_t pgp_data;
367
340
 * Decrypt OpenPGP data.
368
341
 * Returns -1 on error
369
342
 */
370
 
__attribute__((nonnull, warn_unused_result))
371
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
372
344
                                  size_t crypto_size,
373
345
                                  char **plaintext,
493
465
  return plaintext_length;
494
466
}
495
467
 
496
 
__attribute__((warn_unused_result, const))
497
 
static const char *safe_string(const char *str){
498
 
  if(str == NULL)
499
 
    return "(unknown)";
500
 
  return str;
501
 
}
502
 
 
503
 
__attribute__((warn_unused_result))
504
 
static const char *safer_gnutls_strerror(int value){
 
468
static const char * safer_gnutls_strerror(int value){
505
469
  const char *ret = gnutls_strerror(value);
506
 
  return safe_string(ret);
 
470
  if(ret == NULL)
 
471
    ret = "(unknown)";
 
472
  return ret;
507
473
}
508
474
 
509
475
/* GnuTLS log function callback */
510
 
__attribute__((nonnull))
511
476
static void debuggnutls(__attribute__((unused)) int level,
512
477
                        const char* string){
513
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
479
}
515
480
 
516
 
__attribute__((nonnull, warn_unused_result))
517
481
static int init_gnutls_global(const char *pubkeyfilename,
518
482
                              const char *seckeyfilename,
519
483
                              mandos_context *mc){
520
484
  int ret;
521
 
  unsigned int uret;
522
485
  
523
486
  if(debug){
524
487
    fprintf_plus(stderr, "Initializing GnuTLS\n");
575
538
                 safer_gnutls_strerror(ret));
576
539
    goto globalfail;
577
540
  }
578
 
  if(mc->dh_bits == 0){
579
 
    /* Find out the optimal number of DH bits */
580
 
    /* Try to read the private key file */
581
 
    gnutls_datum_t buffer = { .data = NULL, .size = 0 };
582
 
    {
583
 
      int secfile = open(seckeyfilename, O_RDONLY);
584
 
      size_t buffer_capacity = 0;
585
 
      while(true){
586
 
        buffer_capacity = incbuffer((char **)&buffer.data,
587
 
                                    (size_t)buffer.size,
588
 
                                    (size_t)buffer_capacity);
589
 
        if(buffer_capacity == 0){
590
 
          perror_plus("incbuffer");
591
 
          free(buffer.data);
592
 
          buffer.data = NULL;
593
 
          break;
594
 
        }
595
 
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
596
 
                                  BUFFER_SIZE);
597
 
        /* EOF */
598
 
        if(bytes_read == 0){
599
 
          break;
600
 
        }
601
 
        /* check bytes_read for failure */
602
 
        if(bytes_read < 0){
603
 
          perror_plus("read");
604
 
          free(buffer.data);
605
 
          buffer.data = NULL;
606
 
          break;
607
 
        }
608
 
        buffer.size += (unsigned int)bytes_read;
609
 
      }
610
 
      close(secfile);
611
 
    }
612
 
    /* If successful, use buffer to parse private key */
613
 
    gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
614
 
    if(buffer.data != NULL){
615
 
      {
616
 
        gnutls_openpgp_privkey_t privkey = NULL;
617
 
        ret = gnutls_openpgp_privkey_init(&privkey);
618
 
        if(ret != GNUTLS_E_SUCCESS){
619
 
          fprintf_plus(stderr, "Error initializing OpenPGP key"
620
 
                       " structure: %s", safer_gnutls_strerror(ret));
621
 
          free(buffer.data);
622
 
          buffer.data = NULL;
623
 
        } else {
624
 
          ret = gnutls_openpgp_privkey_import(privkey, &buffer,
625
 
                                            GNUTLS_OPENPGP_FMT_BASE64,
626
 
                                              "", 0);
627
 
          if(ret != GNUTLS_E_SUCCESS){
628
 
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
629
 
                         safer_gnutls_strerror(ret));
630
 
            privkey = NULL;
631
 
          }
632
 
          free(buffer.data);
633
 
          buffer.data = NULL;
634
 
          if(privkey != NULL){
635
 
            /* Use private key to suggest an appropriate sec_param */
636
 
            sec_param = gnutls_openpgp_privkey_sec_param(privkey);
637
 
            gnutls_openpgp_privkey_deinit(privkey);
638
 
            if(debug){
639
 
              fprintf_plus(stderr, "This OpenPGP key implies using a"
640
 
                           " GnuTLS security parameter \"%s\".\n",
641
 
                           safe_string(gnutls_sec_param_get_name
642
 
                                       (sec_param)));
643
 
            }
644
 
          }
645
 
        }
646
 
      }
647
 
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
648
 
        /* Err on the side of caution */
649
 
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
650
 
        if(debug){
651
 
          fprintf_plus(stderr, "Falling back to security parameter"
652
 
                       " \"%s\"\n",
653
 
                       safe_string(gnutls_sec_param_get_name
654
 
                                   (sec_param)));
655
 
        }
656
 
      }
657
 
    }
658
 
    uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
659
 
    if(uret != 0){
660
 
      mc->dh_bits = uret;
661
 
      if(debug){
662
 
        fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
663
 
                     " implies %u DH bits; using that.\n",
664
 
                     safe_string(gnutls_sec_param_get_name
665
 
                                 (sec_param)),
666
 
                     mc->dh_bits);
667
 
      }
668
 
    } else {
669
 
      fprintf_plus(stderr, "Failed to get implied number of DH"
670
 
                   " bits for security parameter \"%s\"): %s\n",
671
 
                   safe_string(gnutls_sec_param_get_name(sec_param)),
672
 
                   safer_gnutls_strerror(ret));
673
 
      goto globalfail;
674
 
    }
675
 
  } else if(debug){
676
 
    fprintf_plus(stderr, "DH bits explicitly set to %u\n",
677
 
                 mc->dh_bits);
678
 
  }
679
541
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
680
542
  if(ret != GNUTLS_E_SUCCESS){
681
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation (%u bits):"
682
 
                 " %s\n", mc->dh_bits, safer_gnutls_strerror(ret));
 
543
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
544
                 safer_gnutls_strerror(ret));
683
545
    goto globalfail;
684
546
  }
685
547
  
695
557
  return -1;
696
558
}
697
559
 
698
 
__attribute__((nonnull, warn_unused_result))
699
560
static int init_gnutls_session(gnutls_session_t *session,
700
561
                               mandos_context *mc){
701
562
  int ret;
758
619
                      __attribute__((unused)) const char *txt){}
759
620
 
760
621
/* Called when a Mandos server is found */
761
 
__attribute__((nonnull, warn_unused_result))
762
622
static int start_mandos_communication(const char *ip, in_port_t port,
763
623
                                      AvahiIfIndex if_index,
764
624
                                      int af, mandos_context *mc){
765
625
  int ret, tcp_sd = -1;
766
626
  ssize_t sret;
767
 
  struct sockaddr_storage to;
 
627
  union {
 
628
    struct sockaddr_in in;
 
629
    struct sockaddr_in6 in6;
 
630
  } to;
768
631
  char *buffer = NULL;
769
632
  char *decrypted_buffer = NULL;
770
633
  size_t buffer_length = 0;
794
657
    return -1;
795
658
  }
796
659
  
797
 
  /* If the interface is specified and we have a list of interfaces */
798
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
799
 
    /* Check if the interface is one of the interfaces we are using */
800
 
    bool match = false;
801
 
    {
802
 
      char *interface = NULL;
803
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
804
 
                                 interface))){
805
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
806
 
          match = true;
807
 
          break;
808
 
        }
809
 
      }
810
 
    }
811
 
    if(not match){
812
 
      /* This interface does not match any in the list, so we don't
813
 
         connect to the server */
814
 
      if(debug){
815
 
        char interface[IF_NAMESIZE];
816
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
817
 
          perror_plus("if_indextoname");
818
 
        } else {
819
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
820
 
                       " \"%s\"\n",
821
 
                       if_indextoname((unsigned int)if_index,
822
 
                                      interface));
823
 
        }
824
 
      }
825
 
      return -1;
826
 
    }
827
 
  }
828
 
  
829
660
  ret = init_gnutls_session(&session, mc);
830
661
  if(ret != 0){
831
662
    return -1;
851
682
  
852
683
  memset(&to, 0, sizeof(to));
853
684
  if(af == AF_INET6){
854
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
855
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
685
    to.in6.sin6_family = (sa_family_t)af;
 
686
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
856
687
  } else {                      /* IPv4 */
857
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
858
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
688
    to.in.sin_family = (sa_family_t)af;
 
689
    ret = inet_pton(af, ip, &to.in.sin_addr);
859
690
  }
860
691
  if(ret < 0 ){
861
692
    int e = errno;
870
701
    goto mandos_end;
871
702
  }
872
703
  if(af == AF_INET6){
873
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
874
 
    if(IN6_IS_ADDR_LINKLOCAL
875
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
704
    to.in6.sin6_port = htons(port);    
 
705
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
706
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
707
                                -Wunreachable-code*/
876
708
      if(if_index == AVAHI_IF_UNSPEC){
877
709
        fprintf_plus(stderr, "An IPv6 link-local address is"
878
710
                     " incomplete without a network interface\n");
880
712
        goto mandos_end;
881
713
      }
882
714
      /* Set the network interface number as scope */
883
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
715
      to.in6.sin6_scope_id = (uint32_t)if_index;
884
716
    }
885
717
  } else {
886
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
718
    to.in.sin_port = htons(port); /* Spurious warnings from
 
719
                                     -Wconversion and
 
720
                                     -Wunreachable-code */
887
721
  }
888
722
  
889
723
  if(quit_now){
906
740
    }
907
741
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
908
742
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
743
    const char *pcret;
909
744
    if(af == AF_INET6){
910
 
      ret = getnameinfo((struct sockaddr *)&to,
911
 
                        sizeof(struct sockaddr_in6),
912
 
                        addrstr, sizeof(addrstr), NULL, 0,
913
 
                        NI_NUMERICHOST);
 
745
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
746
                        sizeof(addrstr));
914
747
    } else {
915
 
      ret = getnameinfo((struct sockaddr *)&to,
916
 
                        sizeof(struct sockaddr_in),
917
 
                        addrstr, sizeof(addrstr), NULL, 0,
918
 
                        NI_NUMERICHOST);
 
748
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
749
                        sizeof(addrstr));
919
750
    }
920
 
    if(ret == EAI_SYSTEM){
921
 
      perror_plus("getnameinfo");
922
 
    } else if(ret != 0) {
923
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
924
 
    } else if(strcmp(addrstr, ip) != 0){
925
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
751
    if(pcret == NULL){
 
752
      perror_plus("inet_ntop");
 
753
    } else {
 
754
      if(strcmp(addrstr, ip) != 0){
 
755
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
756
      }
926
757
    }
927
758
  }
928
759
  
932
763
  }
933
764
  
934
765
  if(af == AF_INET6){
935
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
936
 
                  sizeof(struct sockaddr_in6));
 
766
    ret = connect(tcp_sd, &to.in6, sizeof(to));
937
767
  } else {
938
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
939
 
                  sizeof(struct sockaddr_in));
 
768
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
940
769
  }
941
770
  if(ret < 0){
942
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
771
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
943
772
      int e = errno;
944
773
      perror_plus("connect");
945
774
      errno = e;
1160
989
  return retval;
1161
990
}
1162
991
 
1163
 
__attribute__((nonnull))
1164
992
static void resolve_callback(AvahiSServiceResolver *r,
1165
993
                             AvahiIfIndex interface,
1166
994
                             AvahiProtocol proto,
1174
1002
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1175
1003
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1176
1004
                             flags,
1177
 
                             void *mc){
 
1005
                             void* mc){
1178
1006
  if(r == NULL){
1179
1007
    return;
1180
1008
  }
1183
1011
     timed out */
1184
1012
  
1185
1013
  if(quit_now){
1186
 
    avahi_s_service_resolver_free(r);
1187
1014
    return;
1188
1015
  }
1189
1016
  
1234
1061
                            const char *domain,
1235
1062
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1236
1063
                            flags,
1237
 
                            void *mc){
 
1064
                            void* mc){
1238
1065
  if(b == NULL){
1239
1066
    return;
1240
1067
  }
1300
1127
  errno = old_errno;
1301
1128
}
1302
1129
 
1303
 
__attribute__((nonnull, warn_unused_result))
1304
1130
bool get_flags(const char *ifname, struct ifreq *ifr){
1305
1131
  int ret;
1306
1132
  error_t ret_errno;
1325
1151
  return true;
1326
1152
}
1327
1153
 
1328
 
__attribute__((nonnull, warn_unused_result))
1329
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
1330
1155
  
1331
1156
  /* Reject the loopback device */
1373
1198
 * corresponds to an acceptable network device.
1374
1199
 * (This function is passed to scandir(3) as a filter function.)
1375
1200
 */
1376
 
__attribute__((nonnull, warn_unused_result))
1377
1201
int good_interface(const struct dirent *if_entry){
1378
1202
  if(if_entry->d_name[0] == '.'){
1379
1203
    return 0;
1397
1221
/* 
1398
1222
 * This function determines if a network interface is up.
1399
1223
 */
1400
 
__attribute__((nonnull, warn_unused_result))
1401
1224
bool interface_is_up(const char *interface){
1402
1225
  struct ifreq ifr;
1403
1226
  if(not get_flags(interface, &ifr)){
1414
1237
/* 
1415
1238
 * This function determines if a network interface is running
1416
1239
 */
1417
 
__attribute__((nonnull, warn_unused_result))
1418
1240
bool interface_is_running(const char *interface){
1419
1241
  struct ifreq ifr;
1420
1242
  if(not get_flags(interface, &ifr)){
1428
1250
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1429
1251
}
1430
1252
 
1431
 
__attribute__((nonnull, pure, warn_unused_result))
1432
1253
int notdotentries(const struct dirent *direntry){
1433
1254
  /* Skip "." and ".." */
1434
1255
  if(direntry->d_name[0] == '.'
1441
1262
}
1442
1263
 
1443
1264
/* Is this directory entry a runnable program? */
1444
 
__attribute__((nonnull, warn_unused_result))
1445
1265
int runnable_hook(const struct dirent *direntry){
1446
1266
  int ret;
1447
1267
  size_t sret;
1455
1275
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1456
1276
                "abcdefghijklmnopqrstuvwxyz"
1457
1277
                "0123456789"
1458
 
                "_.-");
 
1278
                "_-");
1459
1279
  if((direntry->d_name)[sret] != '\0'){
1460
1280
    /* Contains non-allowed characters */
1461
1281
    if(debug){
1465
1285
    return 0;
1466
1286
  }
1467
1287
  
1468
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1288
  char *fullname = NULL;
 
1289
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1290
  if(ret < 0){
 
1291
    perror_plus("asprintf");
 
1292
    return 0;
 
1293
  }
 
1294
  
 
1295
  ret = stat(fullname, &st);
1469
1296
  if(ret == -1){
1470
1297
    if(debug){
1471
1298
      perror_plus("Could not stat hook");
1495
1322
  return 1;
1496
1323
}
1497
1324
 
1498
 
__attribute__((nonnull, warn_unused_result))
1499
1325
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1500
1326
                            mandos_context *mc){
1501
1327
  int ret;
1505
1331
  
1506
1332
  while(true){
1507
1333
    if(mc->current_server == NULL){
1508
 
      if(debug){
 
1334
      if (debug){
1509
1335
        fprintf_plus(stderr, "Wait until first server is found."
1510
1336
                     " No timeout!\n");
1511
1337
      }
1512
1338
      ret = avahi_simple_poll_iterate(s, -1);
1513
1339
    } else {
1514
 
      if(debug){
 
1340
      if (debug){
1515
1341
        fprintf_plus(stderr, "Check current_server if we should run"
1516
1342
                     " it, or wait\n");
1517
1343
      }
1534
1360
                     - ((intmax_t)waited_time.tv_sec * 1000))
1535
1361
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1536
1362
      
1537
 
      if(debug){
 
1363
      if (debug){
1538
1364
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1539
1365
                     block_time);
1540
1366
      }
1562
1388
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1563
1389
    }
1564
1390
    if(ret != 0){
1565
 
      if(ret > 0 or errno != EINTR){
 
1391
      if (ret > 0 or errno != EINTR){
1566
1392
        return (ret != 1) ? ret : 0;
1567
1393
      }
1568
1394
    }
1570
1396
}
1571
1397
 
1572
1398
/* Set effective uid to 0, return errno */
1573
 
__attribute__((warn_unused_result))
1574
1399
error_t raise_privileges(void){
1575
1400
  error_t old_errno = errno;
1576
1401
  error_t ret_errno = 0;
1577
1402
  if(seteuid(0) == -1){
1578
1403
    ret_errno = errno;
 
1404
    perror_plus("seteuid");
1579
1405
  }
1580
1406
  errno = old_errno;
1581
1407
  return ret_errno;
1582
1408
}
1583
1409
 
1584
1410
/* Set effective and real user ID to 0.  Return errno. */
1585
 
__attribute__((warn_unused_result))
1586
1411
error_t raise_privileges_permanently(void){
1587
1412
  error_t old_errno = errno;
1588
1413
  error_t ret_errno = raise_privileges();
1592
1417
  }
1593
1418
  if(setuid(0) == -1){
1594
1419
    ret_errno = errno;
 
1420
    perror_plus("seteuid");
1595
1421
  }
1596
1422
  errno = old_errno;
1597
1423
  return ret_errno;
1598
1424
}
1599
1425
 
1600
1426
/* Set effective user ID to unprivileged saved user ID */
1601
 
__attribute__((warn_unused_result))
1602
1427
error_t lower_privileges(void){
1603
1428
  error_t old_errno = errno;
1604
1429
  error_t ret_errno = 0;
1605
1430
  if(seteuid(uid) == -1){
1606
1431
    ret_errno = errno;
 
1432
    perror_plus("seteuid");
1607
1433
  }
1608
1434
  errno = old_errno;
1609
1435
  return ret_errno;
1610
1436
}
1611
1437
 
1612
1438
/* Lower privileges permanently */
1613
 
__attribute__((warn_unused_result))
1614
1439
error_t lower_privileges_permanently(void){
1615
1440
  error_t old_errno = errno;
1616
1441
  error_t ret_errno = 0;
1617
1442
  if(setuid(uid) == -1){
1618
1443
    ret_errno = errno;
 
1444
    perror_plus("setuid");
1619
1445
  }
1620
1446
  errno = old_errno;
1621
1447
  return ret_errno;
1622
1448
}
1623
1449
 
1624
 
__attribute__((nonnull))
1625
 
void run_network_hooks(const char *mode, const char *interface,
 
1450
bool run_network_hooks(const char *mode, const char *interface,
1626
1451
                       const float delay){
1627
 
  struct dirent **direntries = NULL;
1628
 
  if(hookdir_fd == -1){
1629
 
    hookdir_fd = open(hookdir, O_RDONLY);
1630
 
    if(hookdir_fd == -1){
1631
 
      if(errno == ENOENT){
1632
 
        if(debug){
1633
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1634
 
                       " found\n", hookdir);
1635
 
        }
1636
 
      } else {
1637
 
        perror_plus("open");
1638
 
      }
1639
 
      return;
1640
 
    }
1641
 
  }
1642
 
#ifdef __GLIBC__
1643
 
#if __GLIBC_PREREQ(2, 15)
1644
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1645
 
                           runnable_hook, alphasort);
1646
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1647
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1648
 
                         alphasort);
1649
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1650
 
#else   /* not __GLIBC__ */
1651
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1652
 
                         alphasort);
1653
 
#endif  /* not __GLIBC__ */
 
1452
  struct dirent **direntries;
 
1453
  struct dirent *direntry;
 
1454
  int ret;
 
1455
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1456
                         alphasort);
1654
1457
  if(numhooks == -1){
1655
 
    perror_plus("scandir");
1656
 
    return;
1657
 
  }
1658
 
  struct dirent *direntry;
1659
 
  int ret;
1660
 
  int devnull = open("/dev/null", O_RDONLY);
1661
 
  for(int i = 0; i < numhooks; i++){
1662
 
    direntry = direntries[i];
1663
 
    if(debug){
1664
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1665
 
                   direntry->d_name);
 
1458
    if(errno == ENOENT){
 
1459
      if(debug){
 
1460
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1461
                     " found\n", hookdir);
 
1462
      }
 
1463
    } else {
 
1464
      perror_plus("scandir");
1666
1465
    }
1667
 
    pid_t hook_pid = fork();
1668
 
    if(hook_pid == 0){
1669
 
      /* Child */
1670
 
      /* Raise privileges */
1671
 
      errno = raise_privileges_permanently();
1672
 
      if(errno != 0){
1673
 
        perror_plus("Failed to raise privileges");
1674
 
        _exit(EX_NOPERM);
1675
 
      }
1676
 
      /* Set group */
1677
 
      errno = 0;
1678
 
      ret = setgid(0);
1679
 
      if(ret == -1){
1680
 
        perror_plus("setgid");
1681
 
        _exit(EX_NOPERM);
1682
 
      }
1683
 
      /* Reset supplementary groups */
1684
 
      errno = 0;
1685
 
      ret = setgroups(0, NULL);
1686
 
      if(ret == -1){
1687
 
        perror_plus("setgroups");
1688
 
        _exit(EX_NOPERM);
1689
 
      }
1690
 
      ret = dup2(devnull, STDIN_FILENO);
1691
 
      if(ret == -1){
1692
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1693
 
        _exit(EX_OSERR);
1694
 
      }
1695
 
      ret = close(devnull);
1696
 
      if(ret == -1){
1697
 
        perror_plus("close");
1698
 
        _exit(EX_OSERR);
1699
 
      }
1700
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1701
 
      if(ret == -1){
1702
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1703
 
        _exit(EX_OSERR);
1704
 
      }
1705
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1706
 
      if(ret == -1){
1707
 
        perror_plus("setenv");
1708
 
        _exit(EX_OSERR);
1709
 
      }
1710
 
      ret = setenv("DEVICE", interface, 1);
1711
 
      if(ret == -1){
1712
 
        perror_plus("setenv");
1713
 
        _exit(EX_OSERR);
1714
 
      }
1715
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1716
 
      if(ret == -1){
1717
 
        perror_plus("setenv");
1718
 
        _exit(EX_OSERR);
1719
 
      }
1720
 
      ret = setenv("MODE", mode, 1);
1721
 
      if(ret == -1){
1722
 
        perror_plus("setenv");
1723
 
        _exit(EX_OSERR);
1724
 
      }
1725
 
      char *delaystring;
1726
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1727
 
      if(ret == -1){
 
1466
  } else {
 
1467
    int devnull = open("/dev/null", O_RDONLY);
 
1468
    for(int i = 0; i < numhooks; i++){
 
1469
      direntry = direntries[i];
 
1470
      char *fullname = NULL;
 
1471
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1472
      if(ret < 0){
1728
1473
        perror_plus("asprintf");
1729
 
        _exit(EX_OSERR);
1730
 
      }
1731
 
      ret = setenv("DELAY", delaystring, 1);
1732
 
      if(ret == -1){
 
1474
        continue;
 
1475
      }
 
1476
      if(debug){
 
1477
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1478
                     direntry->d_name);
 
1479
      }
 
1480
      pid_t hook_pid = fork();
 
1481
      if(hook_pid == 0){
 
1482
        /* Child */
 
1483
        /* Raise privileges */
 
1484
        raise_privileges_permanently();
 
1485
        /* Set group */
 
1486
        errno = 0;
 
1487
        ret = setgid(0);
 
1488
        if(ret == -1){
 
1489
          perror_plus("setgid");
 
1490
        }
 
1491
        /* Reset supplementary groups */
 
1492
        errno = 0;
 
1493
        ret = setgroups(0, NULL);
 
1494
        if(ret == -1){
 
1495
          perror_plus("setgroups");
 
1496
        }
 
1497
        dup2(devnull, STDIN_FILENO);
 
1498
        close(devnull);
 
1499
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1500
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1501
        if(ret == -1){
 
1502
          perror_plus("setenv");
 
1503
          _exit(EX_OSERR);
 
1504
        }
 
1505
        ret = setenv("DEVICE", interface, 1);
 
1506
        if(ret == -1){
 
1507
          perror_plus("setenv");
 
1508
          _exit(EX_OSERR);
 
1509
        }
 
1510
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1511
        if(ret == -1){
 
1512
          perror_plus("setenv");
 
1513
          _exit(EX_OSERR);
 
1514
        }
 
1515
        ret = setenv("MODE", mode, 1);
 
1516
        if(ret == -1){
 
1517
          perror_plus("setenv");
 
1518
          _exit(EX_OSERR);
 
1519
        }
 
1520
        char *delaystring;
 
1521
        ret = asprintf(&delaystring, "%f", delay);
 
1522
        if(ret == -1){
 
1523
          perror_plus("asprintf");
 
1524
          _exit(EX_OSERR);
 
1525
        }
 
1526
        ret = setenv("DELAY", delaystring, 1);
 
1527
        if(ret == -1){
 
1528
          free(delaystring);
 
1529
          perror_plus("setenv");
 
1530
          _exit(EX_OSERR);
 
1531
        }
1733
1532
        free(delaystring);
1734
 
        perror_plus("setenv");
1735
 
        _exit(EX_OSERR);
1736
 
      }
1737
 
      free(delaystring);
1738
 
      if(connect_to != NULL){
1739
 
        ret = setenv("CONNECT", connect_to, 1);
1740
 
        if(ret == -1){
1741
 
          perror_plus("setenv");
1742
 
          _exit(EX_OSERR);
1743
 
        }
1744
 
      }
1745
 
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
1746
 
      if(hook_fd == -1){
1747
 
        perror_plus("openat");
1748
 
        _exit(EXIT_FAILURE);
1749
 
      }
1750
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1751
 
        perror_plus("close");
1752
 
        _exit(EXIT_FAILURE);
1753
 
      }
1754
 
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1755
 
                 environ) == -1){
1756
 
        perror_plus("fexecve");
1757
 
        _exit(EXIT_FAILURE);
1758
 
      }
1759
 
    } else {
1760
 
      if(hook_pid == -1){
1761
 
        perror_plus("fork");
1762
 
        free(direntry);
1763
 
        continue;
1764
 
      }
1765
 
      int status;
1766
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1767
 
        perror_plus("waitpid");
1768
 
        free(direntry);
1769
 
        continue;
1770
 
      }
1771
 
      if(WIFEXITED(status)){
1772
 
        if(WEXITSTATUS(status) != 0){
1773
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1774
 
                       " with status %d\n", direntry->d_name,
1775
 
                       WEXITSTATUS(status));
1776
 
          free(direntry);
1777
 
          continue;
1778
 
        }
1779
 
      } else if(WIFSIGNALED(status)){
1780
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1781
 
                     " signal %d\n", direntry->d_name,
1782
 
                     WTERMSIG(status));
1783
 
        free(direntry);
1784
 
        continue;
 
1533
        if(connect_to != NULL){
 
1534
          ret = setenv("CONNECT", connect_to, 1);
 
1535
          if(ret == -1){
 
1536
            perror_plus("setenv");
 
1537
            _exit(EX_OSERR);
 
1538
          }
 
1539
        }
 
1540
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1541
          perror_plus("execl");
 
1542
          _exit(EXIT_FAILURE);
 
1543
        }
1785
1544
      } else {
1786
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1787
 
                     " crashed\n", direntry->d_name);
1788
 
        free(direntry);
1789
 
        continue;
1790
 
      }
1791
 
    }
1792
 
    if(debug){
1793
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1794
 
                   direntry->d_name);
1795
 
    }
1796
 
    free(direntry);
1797
 
  }
1798
 
  free(direntries);
1799
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1800
 
    perror_plus("close");
1801
 
  } else {
1802
 
    hookdir_fd = -1;
1803
 
  }
1804
 
  close(devnull);
 
1545
        int status;
 
1546
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1547
          perror_plus("waitpid");
 
1548
          free(fullname);
 
1549
          continue;
 
1550
        }
 
1551
        if(WIFEXITED(status)){
 
1552
          if(WEXITSTATUS(status) != 0){
 
1553
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1554
                         " with status %d\n", direntry->d_name,
 
1555
                         WEXITSTATUS(status));
 
1556
            free(fullname);
 
1557
            continue;
 
1558
          }
 
1559
        } else if(WIFSIGNALED(status)){
 
1560
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1561
                       " signal %d\n", direntry->d_name,
 
1562
                       WTERMSIG(status));
 
1563
          free(fullname);
 
1564
          continue;
 
1565
        } else {
 
1566
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1567
                       " crashed\n", direntry->d_name);
 
1568
          free(fullname);
 
1569
          continue;
 
1570
        }
 
1571
      }
 
1572
      free(fullname);
 
1573
      if(debug){
 
1574
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1575
                     direntry->d_name);
 
1576
      }
 
1577
    }
 
1578
    close(devnull);
 
1579
  }
 
1580
  return true;
1805
1581
}
1806
1582
 
1807
 
__attribute__((nonnull, warn_unused_result))
1808
1583
error_t bring_up_interface(const char *const interface,
1809
1584
                           const float delay){
 
1585
  int sd = -1;
1810
1586
  error_t old_errno = errno;
1811
 
  int ret;
 
1587
  error_t ret_errno = 0;
 
1588
  int ret, ret_setflags;
1812
1589
  struct ifreq network;
1813
1590
  unsigned int if_index = if_nametoindex(interface);
1814
1591
  if(if_index == 0){
1823
1600
  }
1824
1601
  
1825
1602
  if(not interface_is_up(interface)){
1826
 
    error_t ret_errno = 0, ioctl_errno = 0;
1827
 
    if(not get_flags(interface, &network)){
 
1603
    if(not get_flags(interface, &network) and debug){
1828
1604
      ret_errno = errno;
1829
1605
      fprintf_plus(stderr, "Failed to get flags for interface "
1830
1606
                   "\"%s\"\n", interface);
1831
 
      errno = old_errno;
1832
1607
      return ret_errno;
1833
1608
    }
1834
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1609
    network.ifr_flags |= IFF_UP;
1835
1610
    
1836
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1837
 
    if(sd == -1){
 
1611
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1612
    if(sd < 0){
1838
1613
      ret_errno = errno;
1839
1614
      perror_plus("socket");
1840
1615
      errno = old_errno;
1841
1616
      return ret_errno;
1842
1617
    }
1843
 
    
 
1618
  
1844
1619
    if(quit_now){
1845
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1846
 
      if(ret == -1){
1847
 
        perror_plus("close");
1848
 
      }
 
1620
      close(sd);
1849
1621
      errno = old_errno;
1850
1622
      return EINTR;
1851
1623
    }
1855
1627
                   interface);
1856
1628
    }
1857
1629
    
1858
 
    /* Raise privileges */
1859
 
    ret_errno = raise_privileges();
1860
 
    if(ret_errno != 0){
1861
 
      errno = ret_errno;
1862
 
      perror_plus("Failed to raise privileges");
1863
 
    }
 
1630
    /* Raise priviliges */
 
1631
    raise_privileges();
1864
1632
    
1865
1633
#ifdef __linux__
1866
 
    int ret_linux;
1867
 
    bool restore_loglevel = false;
1868
 
    if(ret_errno == 0){
1869
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1870
 
         messages about the network interface to mess up the prompt */
1871
 
      ret_linux = klogctl(8, NULL, 5);
1872
 
      if(ret_linux == -1){
1873
 
        perror_plus("klogctl");
1874
 
      } else {
1875
 
        restore_loglevel = true;
1876
 
      }
 
1634
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1635
       messages about the network interface to mess up the prompt */
 
1636
    int ret_linux = klogctl(8, NULL, 5);
 
1637
    bool restore_loglevel = true;
 
1638
    if(ret_linux == -1){
 
1639
      restore_loglevel = false;
 
1640
      perror_plus("klogctl");
1877
1641
    }
1878
1642
#endif  /* __linux__ */
1879
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1880
 
    ioctl_errno = errno;
 
1643
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1644
    ret_errno = errno;
1881
1645
#ifdef __linux__
1882
1646
    if(restore_loglevel){
1883
1647
      ret_linux = klogctl(7, NULL, 0);
1887
1651
    }
1888
1652
#endif  /* __linux__ */
1889
1653
    
1890
 
    /* If raise_privileges() succeeded above */
1891
 
    if(ret_errno == 0){
1892
 
      /* Lower privileges */
1893
 
      ret_errno = lower_privileges();
1894
 
      if(ret_errno != 0){
1895
 
        errno = ret_errno;
1896
 
        perror_plus("Failed to lower privileges");
1897
 
      }
1898
 
    }
 
1654
    /* Lower privileges */
 
1655
    lower_privileges();
1899
1656
    
1900
1657
    /* Close the socket */
1901
1658
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1904
1661
    }
1905
1662
    
1906
1663
    if(ret_setflags == -1){
1907
 
      errno = ioctl_errno;
 
1664
      errno = ret_errno;
1908
1665
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1909
1666
      errno = old_errno;
1910
 
      return ioctl_errno;
 
1667
      return ret_errno;
1911
1668
    }
1912
1669
  } else if(debug){
1913
1670
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1931
1688
  return 0;
1932
1689
}
1933
1690
 
1934
 
__attribute__((nonnull, warn_unused_result))
1935
1691
error_t take_down_interface(const char *const interface){
 
1692
  int sd = -1;
1936
1693
  error_t old_errno = errno;
 
1694
  error_t ret_errno = 0;
 
1695
  int ret, ret_setflags;
1937
1696
  struct ifreq network;
1938
1697
  unsigned int if_index = if_nametoindex(interface);
1939
1698
  if(if_index == 0){
1942
1701
    return ENXIO;
1943
1702
  }
1944
1703
  if(interface_is_up(interface)){
1945
 
    error_t ret_errno = 0, ioctl_errno = 0;
1946
1704
    if(not get_flags(interface, &network) and debug){
1947
1705
      ret_errno = errno;
1948
1706
      fprintf_plus(stderr, "Failed to get flags for interface "
1949
1707
                   "\"%s\"\n", interface);
1950
 
      errno = old_errno;
1951
1708
      return ret_errno;
1952
1709
    }
1953
1710
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1954
1711
    
1955
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1956
 
    if(sd == -1){
 
1712
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1713
    if(sd < 0){
1957
1714
      ret_errno = errno;
1958
1715
      perror_plus("socket");
1959
1716
      errno = old_errno;
1965
1722
                   interface);
1966
1723
    }
1967
1724
    
1968
 
    /* Raise privileges */
1969
 
    ret_errno = raise_privileges();
1970
 
    if(ret_errno != 0){
1971
 
      errno = ret_errno;
1972
 
      perror_plus("Failed to raise privileges");
1973
 
    }
1974
 
    
1975
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1976
 
    ioctl_errno = errno;
1977
 
    
1978
 
    /* If raise_privileges() succeeded above */
1979
 
    if(ret_errno == 0){
1980
 
      /* Lower privileges */
1981
 
      ret_errno = lower_privileges();
1982
 
      if(ret_errno != 0){
1983
 
        errno = ret_errno;
1984
 
        perror_plus("Failed to lower privileges");
1985
 
      }
1986
 
    }
 
1725
    /* Raise priviliges */
 
1726
    raise_privileges();
 
1727
    
 
1728
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1729
    ret_errno = errno;
 
1730
    
 
1731
    /* Lower privileges */
 
1732
    lower_privileges();
1987
1733
    
1988
1734
    /* Close the socket */
1989
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1735
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1990
1736
    if(ret == -1){
1991
1737
      perror_plus("close");
1992
1738
    }
1993
1739
    
1994
1740
    if(ret_setflags == -1){
1995
 
      errno = ioctl_errno;
 
1741
      errno = ret_errno;
1996
1742
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1997
1743
      errno = old_errno;
1998
 
      return ioctl_errno;
 
1744
      return ret_errno;
1999
1745
    }
2000
1746
  } else if(debug){
2001
1747
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2007
1753
}
2008
1754
 
2009
1755
int main(int argc, char *argv[]){
2010
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
1756
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
2011
1757
                        .priority = "SECURE256:!CTYPE-X.509:"
2012
 
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
2013
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
1758
                        "+CTYPE-OPENPGP", .current_server = NULL };
2014
1759
  AvahiSServiceBrowser *sb = NULL;
2015
1760
  error_t ret_errno;
2016
1761
  int ret;
2017
1762
  intmax_t tmpmax;
2018
1763
  char *tmp;
2019
1764
  int exitcode = EXIT_SUCCESS;
 
1765
  char *interfaces = NULL;
 
1766
  size_t interfaces_size = 0;
2020
1767
  char *interfaces_to_take_down = NULL;
2021
1768
  size_t interfaces_to_take_down_size = 0;
2022
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2023
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
2024
 
  char *tempdir = NULL;
 
1769
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1770
  bool tempdir_created = false;
2025
1771
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2026
1772
  const char *seckey = PATHDIR "/" SECKEY;
2027
1773
  const char *pubkey = PATHDIR "/" PUBKEY;
2028
1774
  char *interfaces_hooks = NULL;
 
1775
  size_t interfaces_hooks_size = 0;
2029
1776
  
2030
1777
  bool gnutls_initialized = false;
2031
1778
  bool gpgme_initialized = false;
2122
1869
        connect_to = arg;
2123
1870
        break;
2124
1871
      case 'i':                 /* --interface */
2125
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2126
 
                                 arg, (int)',');
 
1872
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
 
1873
                                 (int)',');
2127
1874
        if(ret_errno != 0){
2128
1875
          argp_error(state, "%s", strerror(ret_errno));
2129
1876
        }
2209
1956
    /* Work around Debian bug #633582:
2210
1957
       <http://bugs.debian.org/633582> */
2211
1958
    
2212
 
    /* Re-raise privileges */
2213
 
    ret_errno = raise_privileges();
2214
 
    if(ret_errno != 0){
2215
 
      errno = ret_errno;
2216
 
      perror_plus("Failed to raise privileges");
2217
 
    } else {
 
1959
    /* Re-raise priviliges */
 
1960
    if(raise_privileges() == 0){
2218
1961
      struct stat st;
2219
1962
      
2220
1963
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2260
2003
      }
2261
2004
    
2262
2005
      /* Lower privileges */
2263
 
      ret_errno = lower_privileges();
2264
 
      if(ret_errno != 0){
2265
 
        errno = ret_errno;
2266
 
        perror_plus("Failed to lower privileges");
 
2006
      errno = 0;
 
2007
      ret = seteuid(uid);
 
2008
      if(ret == -1){
 
2009
        perror_plus("seteuid");
2267
2010
      }
2268
2011
    }
2269
2012
  }
2270
2013
  
2271
 
  /* Remove invalid interface names (except "none") */
 
2014
  /* Remove empty interface names */
2272
2015
  {
2273
2016
    char *interface = NULL;
2274
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2017
    while((interface = argz_next(interfaces, interfaces_size,
2275
2018
                                 interface))){
2276
 
      if(strcmp(interface, "none") != 0
2277
 
         and if_nametoindex(interface) == 0){
2278
 
        if(interface[0] != '\0'){
 
2019
      if(if_nametoindex(interface) == 0){
 
2020
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2279
2021
          fprintf_plus(stderr, "Not using nonexisting interface"
2280
2022
                       " \"%s\"\n", interface);
2281
2023
        }
2282
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2024
        argz_delete(&interfaces, &interfaces_size, interface);
2283
2025
        interface = NULL;
2284
2026
      }
2285
2027
    }
2287
2029
  
2288
2030
  /* Run network hooks */
2289
2031
  {
2290
 
    if(mc.interfaces != NULL){
2291
 
      interfaces_hooks = malloc(mc.interfaces_size);
 
2032
    
 
2033
    if(interfaces != NULL){
 
2034
      interfaces_hooks = malloc(interfaces_size);
2292
2035
      if(interfaces_hooks == NULL){
2293
2036
        perror_plus("malloc");
2294
2037
        goto end;
2295
2038
      }
2296
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2297
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2298
 
    }
2299
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2300
 
                      interfaces_hooks : "", delay);
 
2039
      memcpy(interfaces_hooks, interfaces, interfaces_size);
 
2040
      interfaces_hooks_size = interfaces_size;
 
2041
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2042
                     (int)',');
 
2043
    }
 
2044
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2045
                             interfaces_hooks : "", delay)){
 
2046
      goto end;
 
2047
    }
2301
2048
  }
2302
2049
  
2303
2050
  if(not debug){
2380
2127
  }
2381
2128
  
2382
2129
  /* If no interfaces were specified, make a list */
2383
 
  if(mc.interfaces == NULL){
2384
 
    struct dirent **direntries = NULL;
 
2130
  if(interfaces == NULL){
 
2131
    struct dirent **direntries;
2385
2132
    /* Look for any good interfaces */
2386
2133
    ret = scandir(sys_class_net, &direntries, good_interface,
2387
2134
                  alphasort);
2388
2135
    if(ret >= 1){
2389
2136
      /* Add all found interfaces to interfaces list */
2390
2137
      for(int i = 0; i < ret; ++i){
2391
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2138
        ret_errno = argz_add(&interfaces, &interfaces_size,
2392
2139
                             direntries[i]->d_name);
2393
2140
        if(ret_errno != 0){
2394
 
          errno = ret_errno;
2395
2141
          perror_plus("argz_add");
2396
 
          free(direntries[i]);
2397
2142
          continue;
2398
2143
        }
2399
2144
        if(debug){
2400
2145
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2401
2146
                       direntries[i]->d_name);
2402
2147
        }
2403
 
        free(direntries[i]);
2404
2148
      }
2405
2149
      free(direntries);
2406
2150
    } else {
2407
 
      if(ret == 0){
2408
 
        free(direntries);
2409
 
      }
 
2151
      free(direntries);
2410
2152
      fprintf_plus(stderr, "Could not find a network interface\n");
2411
2153
      exitcode = EXIT_FAILURE;
2412
2154
      goto end;
2413
2155
    }
2414
2156
  }
2415
2157
  
2416
 
  /* Bring up interfaces which are down, and remove any "none"s */
2417
 
  {
 
2158
  /* If we only got one interface, explicitly use only that one */
 
2159
  if(argz_count(interfaces, interfaces_size) == 1){
 
2160
    if(debug){
 
2161
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2162
                   interfaces);
 
2163
    }
 
2164
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
 
2165
  }
 
2166
  
 
2167
  /* Bring up interfaces which are down */
 
2168
  if(not (argz_count(interfaces, interfaces_size) == 1
 
2169
          and strcmp(interfaces, "none") == 0)){
2418
2170
    char *interface = NULL;
2419
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2171
    while((interface = argz_next(interfaces, interfaces_size,
2420
2172
                                 interface))){
2421
 
      /* If interface name is "none", stop bringing up interfaces.
2422
 
         Also remove all instances of "none" from the list */
2423
 
      if(strcmp(interface, "none") == 0){
2424
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2425
 
                    interface);
2426
 
        interface = NULL;
2427
 
        while((interface = argz_next(mc.interfaces,
2428
 
                                     mc.interfaces_size, interface))){
2429
 
          if(strcmp(interface, "none") == 0){
2430
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2431
 
                        interface);
2432
 
            interface = NULL;
2433
 
          }
2434
 
        }
2435
 
        break;
2436
 
      }
2437
2173
      bool interface_was_up = interface_is_up(interface);
2438
 
      errno = bring_up_interface(interface, delay);
 
2174
      ret = bring_up_interface(interface, delay);
2439
2175
      if(not interface_was_up){
2440
 
        if(errno != 0){
 
2176
        if(ret != 0){
 
2177
          errno = ret;
2441
2178
          perror_plus("Failed to bring up interface");
2442
2179
        } else {
2443
 
          errno = argz_add(&interfaces_to_take_down,
2444
 
                           &interfaces_to_take_down_size,
2445
 
                           interface);
2446
 
          if(errno != 0){
2447
 
            perror_plus("argz_add");
2448
 
          }
 
2180
          ret_errno = argz_add(&interfaces_to_take_down,
 
2181
                               &interfaces_to_take_down_size,
 
2182
                               interface);
2449
2183
        }
2450
2184
      }
2451
2185
    }
 
2186
    free(interfaces);
 
2187
    interfaces = NULL;
 
2188
    interfaces_size = 0;
2452
2189
    if(debug and (interfaces_to_take_down == NULL)){
2453
2190
      fprintf_plus(stderr, "No interfaces were brought up\n");
2454
2191
    }
2455
2192
  }
2456
2193
  
2457
 
  /* If we only got one interface, explicitly use only that one */
2458
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2459
 
    if(debug){
2460
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2461
 
                   mc.interfaces);
2462
 
    }
2463
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2464
 
  }
2465
 
  
2466
2194
  if(quit_now){
2467
2195
    goto end;
2468
2196
  }
2480
2208
    goto end;
2481
2209
  }
2482
2210
  
2483
 
  /* Try /run/tmp before /tmp */
2484
 
  tempdir = mkdtemp(run_tempdir);
2485
 
  if(tempdir == NULL and errno == ENOENT){
2486
 
      if(debug){
2487
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2488
 
                     run_tempdir, old_tempdir);
2489
 
      }
2490
 
      tempdir = mkdtemp(old_tempdir);
2491
 
  }
2492
 
  if(tempdir == NULL){
 
2211
  if(mkdtemp(tempdir) == NULL){
2493
2212
    perror_plus("mkdtemp");
2494
2213
    goto end;
2495
2214
  }
 
2215
  tempdir_created = true;
2496
2216
  
2497
2217
  if(quit_now){
2498
2218
    goto end;
2534
2254
      exitcode = EX_USAGE;
2535
2255
      goto end;
2536
2256
    }
2537
 
    
 
2257
  
2538
2258
    if(quit_now){
2539
2259
      goto end;
2540
2260
    }
2570
2290
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2571
2291
                     (int)retry_interval);
2572
2292
      }
2573
 
      sleep((unsigned int)retry_interval);
 
2293
      sleep((int)retry_interval);
2574
2294
    }
2575
2295
    
2576
 
    if(not quit_now){
 
2296
    if (not quit_now){
2577
2297
      exitcode = EXIT_SUCCESS;
2578
2298
    }
2579
2299
    
2634
2354
  if(debug){
2635
2355
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2636
2356
  }
2637
 
  
 
2357
 
2638
2358
  ret = avahi_loop_with_timeout(simple_poll,
2639
2359
                                (int)(retry_interval * 1000), &mc);
2640
2360
  if(debug){
2649
2369
  }
2650
2370
  
2651
2371
  /* Cleanup things */
2652
 
  free(mc.interfaces);
2653
 
  
2654
2372
  if(sb != NULL)
2655
2373
    avahi_s_service_browser_free(sb);
2656
2374
  
2676
2394
    mc.current_server->prev->next = NULL;
2677
2395
    while(mc.current_server != NULL){
2678
2396
      server *next = mc.current_server->next;
2679
 
#ifdef __GNUC__
2680
 
#pragma GCC diagnostic push
2681
 
#pragma GCC diagnostic ignored "-Wcast-qual"
2682
 
#endif
2683
 
      free((char *)(mc.current_server->ip));
2684
 
#ifdef __GNUC__
2685
 
#pragma GCC diagnostic pop
2686
 
#endif
2687
2397
      free(mc.current_server);
2688
2398
      mc.current_server = next;
2689
2399
    }
2690
2400
  }
2691
2401
  
2692
 
  /* Re-raise privileges */
 
2402
  /* Re-raise priviliges */
2693
2403
  {
2694
 
    ret_errno = raise_privileges();
2695
 
    if(ret_errno != 0){
2696
 
      errno = ret_errno;
2697
 
      perror_plus("Failed to raise privileges");
2698
 
    } else {
2699
 
      
2700
 
      /* Run network hooks */
2701
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2702
 
                        interfaces_hooks : "", delay);
2703
 
      
2704
 
      /* Take down the network interfaces which were brought up */
2705
 
      {
2706
 
        char *interface = NULL;
2707
 
        while((interface=argz_next(interfaces_to_take_down,
2708
 
                                   interfaces_to_take_down_size,
2709
 
                                   interface))){
2710
 
          ret_errno = take_down_interface(interface);
2711
 
          if(ret_errno != 0){
2712
 
            errno = ret_errno;
2713
 
            perror_plus("Failed to take down interface");
2714
 
          }
2715
 
        }
2716
 
        if(debug and (interfaces_to_take_down == NULL)){
2717
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2718
 
                       " down\n");
2719
 
        }
2720
 
      }
2721
 
    }
2722
 
    
2723
 
    ret_errno = lower_privileges_permanently();
2724
 
    if(ret_errno != 0){
2725
 
      errno = ret_errno;
2726
 
      perror_plus("Failed to lower privileges permanently");
2727
 
    }
 
2404
    raise_privileges();
 
2405
    
 
2406
    /* Run network hooks */
 
2407
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2408
                      interfaces_hooks : "", delay);
 
2409
    
 
2410
    /* Take down the network interfaces which were brought up */
 
2411
    {
 
2412
      char *interface = NULL;
 
2413
      while((interface=argz_next(interfaces_to_take_down,
 
2414
                                 interfaces_to_take_down_size,
 
2415
                                 interface))){
 
2416
        ret_errno = take_down_interface(interface);
 
2417
        if(ret_errno != 0){
 
2418
          errno = ret_errno;
 
2419
          perror_plus("Failed to take down interface");
 
2420
        }
 
2421
      }
 
2422
      if(debug and (interfaces_to_take_down == NULL)){
 
2423
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2424
                     " down\n");
 
2425
      }
 
2426
    }
 
2427
    
 
2428
    lower_privileges_permanently();
2728
2429
  }
2729
2430
  
2730
2431
  free(interfaces_to_take_down);
2731
2432
  free(interfaces_hooks);
2732
2433
  
2733
2434
  /* Removes the GPGME temp directory and all files inside */
2734
 
  if(tempdir != NULL){
 
2435
  if(tempdir_created){
2735
2436
    struct dirent **direntries = NULL;
2736
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2737
 
                                                  O_NOFOLLOW));
2738
 
    if(tempdir_fd == -1){
2739
 
      perror_plus("open");
2740
 
    } else {
2741
 
#ifdef __GLIBC__
2742
 
#if __GLIBC_PREREQ(2, 15)
2743
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2744
 
                                 notdotentries, alphasort);
2745
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2746
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2747
 
                               alphasort);
2748
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2749
 
#else   /* not __GLIBC__ */
2750
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2751
 
                               alphasort);
2752
 
#endif  /* not __GLIBC__ */
2753
 
      if(numentries >= 0){
2754
 
        for(int i = 0; i < numentries; i++){
2755
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2756
 
          if(ret == -1){
2757
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2758
 
                         " \"%s\", 0): %s\n", tempdir,
2759
 
                         direntries[i]->d_name, strerror(errno));
2760
 
          }
2761
 
          free(direntries[i]);
2762
 
        }
2763
 
        
2764
 
        /* need to clean even if 0 because man page doesn't specify */
2765
 
        free(direntries);
2766
 
        if(numentries == -1){
2767
 
          perror_plus("scandir");
2768
 
        }
2769
 
        ret = rmdir(tempdir);
2770
 
        if(ret == -1 and errno != ENOENT){
2771
 
          perror_plus("rmdir");
2772
 
        }
 
2437
    struct dirent *direntry = NULL;
 
2438
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2439
                             alphasort);
 
2440
    if (numentries > 0){
 
2441
      for(int i = 0; i < numentries; i++){
 
2442
        direntry = direntries[i];
 
2443
        char *fullname = NULL;
 
2444
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2445
                       direntry->d_name);
 
2446
        if(ret < 0){
 
2447
          perror_plus("asprintf");
 
2448
          continue;
 
2449
        }
 
2450
        ret = remove(fullname);
 
2451
        if(ret == -1){
 
2452
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2453
                       strerror(errno));
 
2454
        }
 
2455
        free(fullname);
2773
2456
      }
2774
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2457
    }
 
2458
 
 
2459
    /* need to clean even if 0 because man page doesn't specify */
 
2460
    free(direntries);
 
2461
    if (numentries == -1){
 
2462
      perror_plus("scandir");
 
2463
    }
 
2464
    ret = rmdir(tempdir);
 
2465
    if(ret == -1 and errno != ENOENT){
 
2466
      perror_plus("rmdir");
2775
2467
    }
2776
2468
  }
2777
2469