/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 19:30:08 UTC
  • Revision ID: teddy@recompile.se-20120616193008-2erbfaw5a5y3yay1
* debian/mandos-client.README.Debian: Update documentation for using
                                      multiple interfaces.

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-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
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() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
92
91
                                   argz_delete(), argz_append(),
93
92
                                   argz_stringify(), argz_add(),
94
93
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
94
 
98
95
#ifdef __linux__
99
96
#include <sys/klog.h>           /* klogctl() */
157
154
 
158
155
/* Used for passing in values through the Avahi callback functions */
159
156
typedef struct {
 
157
  AvahiSimplePoll *simple_poll;
160
158
  AvahiServer *server;
161
159
  gnutls_certificate_credentials_t cred;
162
160
  unsigned int dh_bits;
164
162
  const char *priority;
165
163
  gpgme_ctx_t ctx;
166
164
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
165
} mandos_context;
170
166
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
167
/* global context so signal handler can reach it*/
 
168
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
169
                      .dh_bits = 1024, .priority = "SECURE256"
 
170
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
171
                      .current_server = NULL };
173
172
 
174
173
sig_atomic_t quit_now = 0;
175
174
int signal_received = 0;
183
182
  perror(print_text);
184
183
}
185
184
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
185
__attribute__((format (gnu_printf, 2, 3)))
187
186
int fprintf_plus(FILE *stream, const char *format, ...){
188
187
  va_list ap;
189
188
  va_start (ap, format);
190
189
  
191
190
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
191
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
192
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
193
}
195
194
 
196
195
/*
198
197
 * bytes. "buffer_capacity" is how much is currently allocated,
199
198
 * "buffer_length" is how much is already used.
200
199
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
200
size_t incbuffer(char **buffer, size_t buffer_length,
203
201
                 size_t buffer_capacity){
204
202
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
205
 
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
206
 
    if(new_buf == NULL){
207
 
      int old_errno = errno;
208
 
      free(*buffer);
209
 
      errno = old_errno;
210
 
      *buffer = NULL;
 
203
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
204
    if(buffer == NULL){
211
205
      return 0;
212
206
    }
213
 
    *buffer = new_buf;
214
207
    buffer_capacity += BUFFER_SIZE;
215
208
  }
216
209
  return buffer_capacity;
217
210
}
218
211
 
219
212
/* Add server to set of servers to retry periodically */
220
 
__attribute__((nonnull, warn_unused_result))
221
213
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
222
 
                int af, server **current_server){
 
214
                int af){
223
215
  int ret;
224
216
  server *new_server = malloc(sizeof(server));
225
217
  if(new_server == NULL){
234
226
    perror_plus("strdup");
235
227
    return false;
236
228
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
229
  /* Special case of first server */
243
 
  if(*current_server == NULL){
 
230
  if (mc.current_server == NULL){
244
231
    new_server->next = new_server;
245
232
    new_server->prev = new_server;
246
 
    *current_server = new_server;
 
233
    mc.current_server = new_server;
 
234
  /* Place the new server last in the list */
247
235
  } else {
248
 
    /* Place the new server last in the list */
249
 
    new_server->next = *current_server;
250
 
    new_server->prev = (*current_server)->prev;
 
236
    new_server->next = mc.current_server;
 
237
    new_server->prev = mc.current_server->prev;
251
238
    new_server->prev->next = new_server;
252
 
    (*current_server)->prev = new_server;
 
239
    mc.current_server->prev = new_server;
 
240
  }
 
241
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
242
  if(ret == -1){
 
243
    perror_plus("clock_gettime");
 
244
    return false;
253
245
  }
254
246
  return true;
255
247
}
257
249
/* 
258
250
 * Initialize GPGME.
259
251
 */
260
 
__attribute__((nonnull, warn_unused_result))
261
252
static bool init_gpgme(const char *seckey, const char *pubkey,
262
 
                       const char *tempdir, mandos_context *mc){
 
253
                       const char *tempdir){
263
254
  gpgme_error_t rc;
264
255
  gpgme_engine_info_t engine_info;
265
256
  
 
257
  
266
258
  /*
267
259
   * Helper function to insert pub and seckey to the engine keyring.
268
260
   */
284
276
      return false;
285
277
    }
286
278
    
287
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
279
    rc = gpgme_op_import(mc.ctx, pgp_data);
288
280
    if(rc != GPG_ERR_NO_ERROR){
289
281
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
290
282
                   gpgme_strsource(rc), gpgme_strerror(rc));
334
326
  }
335
327
  
336
328
  /* Create new GPGME "context" */
337
 
  rc = gpgme_new(&(mc->ctx));
 
329
  rc = gpgme_new(&(mc.ctx));
338
330
  if(rc != GPG_ERR_NO_ERROR){
339
331
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
340
332
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
353
345
 * Decrypt OpenPGP data.
354
346
 * Returns -1 on error
355
347
 */
356
 
__attribute__((nonnull, warn_unused_result))
357
348
static ssize_t pgp_packet_decrypt(const char *cryptotext,
358
349
                                  size_t crypto_size,
359
 
                                  char **plaintext,
360
 
                                  mandos_context *mc){
 
350
                                  char **plaintext){
361
351
  gpgme_data_t dh_crypto, dh_plain;
362
352
  gpgme_error_t rc;
363
353
  ssize_t ret;
389
379
  
390
380
  /* Decrypt data from the cryptotext data buffer to the plaintext
391
381
     data buffer */
392
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
382
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
393
383
  if(rc != GPG_ERR_NO_ERROR){
394
384
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
395
385
                 gpgme_strsource(rc), gpgme_strerror(rc));
396
386
    plaintext_length = -1;
397
387
    if(debug){
398
388
      gpgme_decrypt_result_t result;
399
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
389
      result = gpgme_op_decrypt_result(mc.ctx);
400
390
      if(result == NULL){
401
391
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
402
392
      } else {
479
469
  return plaintext_length;
480
470
}
481
471
 
482
 
__attribute__((warn_unused_result))
483
 
static const char *safer_gnutls_strerror(int value){
 
472
static const char * safer_gnutls_strerror(int value){
484
473
  const char *ret = gnutls_strerror(value);
485
474
  if(ret == NULL)
486
475
    ret = "(unknown)";
488
477
}
489
478
 
490
479
/* GnuTLS log function callback */
491
 
__attribute__((nonnull))
492
480
static void debuggnutls(__attribute__((unused)) int level,
493
481
                        const char* string){
494
482
  fprintf_plus(stderr, "GnuTLS: %s", string);
495
483
}
496
484
 
497
 
__attribute__((nonnull, warn_unused_result))
498
485
static int init_gnutls_global(const char *pubkeyfilename,
499
 
                              const char *seckeyfilename,
500
 
                              mandos_context *mc){
 
486
                              const char *seckeyfilename){
501
487
  int ret;
502
488
  
503
489
  if(debug){
520
506
  }
521
507
  
522
508
  /* OpenPGP credentials */
523
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
524
510
  if(ret != GNUTLS_E_SUCCESS){
525
511
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
526
512
                 safer_gnutls_strerror(ret));
536
522
  }
537
523
  
538
524
  ret = gnutls_certificate_set_openpgp_key_file
539
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
525
    (mc.cred, pubkeyfilename, seckeyfilename,
540
526
     GNUTLS_OPENPGP_FMT_BASE64);
541
527
  if(ret != GNUTLS_E_SUCCESS){
542
528
    fprintf_plus(stderr,
548
534
  }
549
535
  
550
536
  /* GnuTLS server initialization */
551
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
537
  ret = gnutls_dh_params_init(&mc.dh_params);
552
538
  if(ret != GNUTLS_E_SUCCESS){
553
539
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
554
540
                 " initialization: %s\n",
555
541
                 safer_gnutls_strerror(ret));
556
542
    goto globalfail;
557
543
  }
558
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
544
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
559
545
  if(ret != GNUTLS_E_SUCCESS){
560
546
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
561
547
                 safer_gnutls_strerror(ret));
562
548
    goto globalfail;
563
549
  }
564
550
  
565
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
551
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
566
552
  
567
553
  return 0;
568
554
  
569
555
 globalfail:
570
556
  
571
 
  gnutls_certificate_free_credentials(mc->cred);
 
557
  gnutls_certificate_free_credentials(mc.cred);
572
558
  gnutls_global_deinit();
573
 
  gnutls_dh_params_deinit(mc->dh_params);
 
559
  gnutls_dh_params_deinit(mc.dh_params);
574
560
  return -1;
575
561
}
576
562
 
577
 
__attribute__((nonnull, warn_unused_result))
578
 
static int init_gnutls_session(gnutls_session_t *session,
579
 
                               mandos_context *mc){
 
563
static int init_gnutls_session(gnutls_session_t *session){
580
564
  int ret;
581
565
  /* GnuTLS session creation */
582
566
  do {
594
578
  {
595
579
    const char *err;
596
580
    do {
597
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
581
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
598
582
      if(quit_now){
599
583
        gnutls_deinit(*session);
600
584
        return -1;
611
595
  
612
596
  do {
613
597
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
614
 
                                 mc->cred);
 
598
                                 mc.cred);
615
599
    if(quit_now){
616
600
      gnutls_deinit(*session);
617
601
      return -1;
627
611
  /* ignore client certificate if any. */
628
612
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
629
613
  
630
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
614
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
631
615
  
632
616
  return 0;
633
617
}
637
621
                      __attribute__((unused)) const char *txt){}
638
622
 
639
623
/* Called when a Mandos server is found */
640
 
__attribute__((nonnull, warn_unused_result))
641
624
static int start_mandos_communication(const char *ip, in_port_t port,
642
625
                                      AvahiIfIndex if_index,
643
 
                                      int af, mandos_context *mc){
 
626
                                      int af){
644
627
  int ret, tcp_sd = -1;
645
628
  ssize_t sret;
646
 
  struct sockaddr_storage to;
 
629
  union {
 
630
    struct sockaddr_in in;
 
631
    struct sockaddr_in6 in6;
 
632
  } to;
647
633
  char *buffer = NULL;
648
634
  char *decrypted_buffer = NULL;
649
635
  size_t buffer_length = 0;
673
659
    return -1;
674
660
  }
675
661
  
676
 
  /* If the interface is specified and we have a list of interfaces */
677
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
678
 
    /* Check if the interface is one of the interfaces we are using */
679
 
    bool match = false;
680
 
    {
681
 
      char *interface = NULL;
682
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
683
 
                                 interface))){
684
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
685
 
          match = true;
686
 
          break;
687
 
        }
688
 
      }
689
 
    }
690
 
    if(not match){
691
 
      /* This interface does not match any in the list, so we don't
692
 
         connect to the server */
693
 
      if(debug){
694
 
        char interface[IF_NAMESIZE];
695
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
696
 
          perror_plus("if_indextoname");
697
 
        } else {
698
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
699
 
                       " \"%s\"\n",
700
 
                       if_indextoname((unsigned int)if_index,
701
 
                                      interface));
702
 
        }
703
 
      }
704
 
      return -1;
705
 
    }
706
 
  }
707
 
  
708
 
  ret = init_gnutls_session(&session, mc);
 
662
  ret = init_gnutls_session(&session);
709
663
  if(ret != 0){
710
664
    return -1;
711
665
  }
730
684
  
731
685
  memset(&to, 0, sizeof(to));
732
686
  if(af == AF_INET6){
733
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
734
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
687
    to.in6.sin6_family = (sa_family_t)af;
 
688
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
735
689
  } else {                      /* IPv4 */
736
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
737
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
690
    to.in.sin_family = (sa_family_t)af;
 
691
    ret = inet_pton(af, ip, &to.in.sin_addr);
738
692
  }
739
693
  if(ret < 0 ){
740
694
    int e = errno;
749
703
    goto mandos_end;
750
704
  }
751
705
  if(af == AF_INET6){
752
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
753
 
    if(IN6_IS_ADDR_LINKLOCAL
754
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
706
    to.in6.sin6_port = htons(port);    
 
707
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
708
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
709
                                -Wunreachable-code*/
755
710
      if(if_index == AVAHI_IF_UNSPEC){
756
711
        fprintf_plus(stderr, "An IPv6 link-local address is"
757
712
                     " incomplete without a network interface\n");
759
714
        goto mandos_end;
760
715
      }
761
716
      /* Set the network interface number as scope */
762
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
717
      to.in6.sin6_scope_id = (uint32_t)if_index;
763
718
    }
764
719
  } else {
765
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
720
    to.in.sin_port = htons(port); /* Spurious warnings from
 
721
                                     -Wconversion and
 
722
                                     -Wunreachable-code */
766
723
  }
767
724
  
768
725
  if(quit_now){
785
742
    }
786
743
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
787
744
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
745
    const char *pcret;
788
746
    if(af == AF_INET6){
789
 
      ret = getnameinfo((struct sockaddr *)&to,
790
 
                        sizeof(struct sockaddr_in6),
791
 
                        addrstr, sizeof(addrstr), NULL, 0,
792
 
                        NI_NUMERICHOST);
 
747
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
748
                        sizeof(addrstr));
793
749
    } else {
794
 
      ret = getnameinfo((struct sockaddr *)&to,
795
 
                        sizeof(struct sockaddr_in),
796
 
                        addrstr, sizeof(addrstr), NULL, 0,
797
 
                        NI_NUMERICHOST);
 
750
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
751
                        sizeof(addrstr));
798
752
    }
799
 
    if(ret == EAI_SYSTEM){
800
 
      perror_plus("getnameinfo");
801
 
    } else if(ret != 0) {
802
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
803
 
    } else if(strcmp(addrstr, ip) != 0){
804
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
753
    if(pcret == NULL){
 
754
      perror_plus("inet_ntop");
 
755
    } else {
 
756
      if(strcmp(addrstr, ip) != 0){
 
757
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
758
      }
805
759
    }
806
760
  }
807
761
  
811
765
  }
812
766
  
813
767
  if(af == AF_INET6){
814
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
815
 
                  sizeof(struct sockaddr_in6));
 
768
    ret = connect(tcp_sd, &to.in6, sizeof(to));
816
769
  } else {
817
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
818
 
                  sizeof(struct sockaddr_in));
 
770
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
819
771
  }
820
772
  if(ret < 0){
821
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
773
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
822
774
      int e = errno;
823
775
      perror_plus("connect");
824
776
      errno = e;
985
937
  if(buffer_length > 0){
986
938
    ssize_t decrypted_buffer_size;
987
939
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
988
 
                                               &decrypted_buffer, mc);
 
940
                                               &decrypted_buffer);
989
941
    if(decrypted_buffer_size >= 0){
990
942
      
991
943
      written = 0;
1039
991
  return retval;
1040
992
}
1041
993
 
1042
 
__attribute__((nonnull))
1043
994
static void resolve_callback(AvahiSServiceResolver *r,
1044
995
                             AvahiIfIndex interface,
1045
996
                             AvahiProtocol proto,
1053
1004
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1054
1005
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1055
1006
                             flags,
1056
 
                             void *mc){
 
1007
                             AVAHI_GCC_UNUSED void* userdata){
1057
1008
  if(r == NULL){
1058
1009
    return;
1059
1010
  }
1071
1022
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1072
1023
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1073
1024
                 domain,
1074
 
                 avahi_strerror(avahi_server_errno
1075
 
                                (((mandos_context*)mc)->server)));
 
1025
                 avahi_strerror(avahi_server_errno(mc.server)));
1076
1026
    break;
1077
1027
    
1078
1028
  case AVAHI_RESOLVER_FOUND:
1086
1036
      }
1087
1037
      int ret = start_mandos_communication(ip, (in_port_t)port,
1088
1038
                                           interface,
1089
 
                                           avahi_proto_to_af(proto),
1090
 
                                           mc);
 
1039
                                           avahi_proto_to_af(proto));
1091
1040
      if(ret == 0){
1092
 
        avahi_simple_poll_quit(simple_poll);
 
1041
        avahi_simple_poll_quit(mc.simple_poll);
1093
1042
      } else {
1094
1043
        if(not add_server(ip, (in_port_t)port, interface,
1095
 
                          avahi_proto_to_af(proto),
1096
 
                          &((mandos_context*)mc)->current_server)){
 
1044
                          avahi_proto_to_af(proto))){
1097
1045
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1098
1046
                       " list\n", name);
1099
1047
        }
1112
1060
                            const char *domain,
1113
1061
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1114
1062
                            flags,
1115
 
                            void *mc){
 
1063
                            AVAHI_GCC_UNUSED void* userdata){
1116
1064
  if(b == NULL){
1117
1065
    return;
1118
1066
  }
1129
1077
  case AVAHI_BROWSER_FAILURE:
1130
1078
    
1131
1079
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1132
 
                 avahi_strerror(avahi_server_errno
1133
 
                                (((mandos_context*)mc)->server)));
1134
 
    avahi_simple_poll_quit(simple_poll);
 
1080
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1081
    avahi_simple_poll_quit(mc.simple_poll);
1135
1082
    return;
1136
1083
    
1137
1084
  case AVAHI_BROWSER_NEW:
1140
1087
       the callback function is called the Avahi server will free the
1141
1088
       resolver for us. */
1142
1089
    
1143
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1144
 
                                    interface, protocol, name, type,
1145
 
                                    domain, protocol, 0,
1146
 
                                    resolve_callback, mc) == NULL)
 
1090
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1091
                                    name, type, domain, protocol, 0,
 
1092
                                    resolve_callback, NULL) == NULL)
1147
1093
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1148
1094
                   " %s\n", name,
1149
 
                   avahi_strerror(avahi_server_errno
1150
 
                                  (((mandos_context*)mc)->server)));
 
1095
                   avahi_strerror(avahi_server_errno(mc.server)));
1151
1096
    break;
1152
1097
    
1153
1098
  case AVAHI_BROWSER_REMOVE:
1172
1117
  signal_received = sig;
1173
1118
  int old_errno = errno;
1174
1119
  /* set main loop to exit */
1175
 
  if(simple_poll != NULL){
1176
 
    avahi_simple_poll_quit(simple_poll);
 
1120
  if(mc.simple_poll != NULL){
 
1121
    avahi_simple_poll_quit(mc.simple_poll);
1177
1122
  }
1178
1123
  errno = old_errno;
1179
1124
}
1180
1125
 
1181
 
__attribute__((nonnull, warn_unused_result))
1182
1126
bool get_flags(const char *ifname, struct ifreq *ifr){
1183
1127
  int ret;
1184
1128
  error_t ret_errno;
1203
1147
  return true;
1204
1148
}
1205
1149
 
1206
 
__attribute__((nonnull, warn_unused_result))
1207
1150
bool good_flags(const char *ifname, const struct ifreq *ifr){
1208
1151
  
1209
1152
  /* Reject the loopback device */
1251
1194
 * corresponds to an acceptable network device.
1252
1195
 * (This function is passed to scandir(3) as a filter function.)
1253
1196
 */
1254
 
__attribute__((nonnull, warn_unused_result))
1255
1197
int good_interface(const struct dirent *if_entry){
1256
1198
  if(if_entry->d_name[0] == '.'){
1257
1199
    return 0;
1275
1217
/* 
1276
1218
 * This function determines if a network interface is up.
1277
1219
 */
1278
 
__attribute__((nonnull, warn_unused_result))
1279
1220
bool interface_is_up(const char *interface){
1280
1221
  struct ifreq ifr;
1281
1222
  if(not get_flags(interface, &ifr)){
1292
1233
/* 
1293
1234
 * This function determines if a network interface is running
1294
1235
 */
1295
 
__attribute__((nonnull, warn_unused_result))
1296
1236
bool interface_is_running(const char *interface){
1297
1237
  struct ifreq ifr;
1298
1238
  if(not get_flags(interface, &ifr)){
1306
1246
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1307
1247
}
1308
1248
 
1309
 
__attribute__((nonnull, pure, warn_unused_result))
1310
1249
int notdotentries(const struct dirent *direntry){
1311
1250
  /* Skip "." and ".." */
1312
1251
  if(direntry->d_name[0] == '.'
1319
1258
}
1320
1259
 
1321
1260
/* Is this directory entry a runnable program? */
1322
 
__attribute__((nonnull, warn_unused_result))
1323
1261
int runnable_hook(const struct dirent *direntry){
1324
1262
  int ret;
1325
1263
  size_t sret;
1380
1318
  return 1;
1381
1319
}
1382
1320
 
1383
 
__attribute__((nonnull, warn_unused_result))
1384
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1385
 
                            mandos_context *mc){
 
1321
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1386
1322
  int ret;
1387
1323
  struct timespec now;
1388
1324
  struct timespec waited_time;
1389
1325
  intmax_t block_time;
1390
1326
  
1391
1327
  while(true){
1392
 
    if(mc->current_server == NULL){
1393
 
      if(debug){
 
1328
    if(mc.current_server == NULL){
 
1329
      if (debug){
1394
1330
        fprintf_plus(stderr, "Wait until first server is found."
1395
1331
                     " No timeout!\n");
1396
1332
      }
1397
1333
      ret = avahi_simple_poll_iterate(s, -1);
1398
1334
    } else {
1399
 
      if(debug){
 
1335
      if (debug){
1400
1336
        fprintf_plus(stderr, "Check current_server if we should run"
1401
1337
                     " it, or wait\n");
1402
1338
      }
1409
1345
      /* Calculating in ms how long time between now and server
1410
1346
         who we visted longest time ago. Now - last seen.  */
1411
1347
      waited_time.tv_sec = (now.tv_sec
1412
 
                            - mc->current_server->last_seen.tv_sec);
 
1348
                            - mc.current_server->last_seen.tv_sec);
1413
1349
      waited_time.tv_nsec = (now.tv_nsec
1414
 
                             - mc->current_server->last_seen.tv_nsec);
 
1350
                             - mc.current_server->last_seen.tv_nsec);
1415
1351
      /* total time is 10s/10,000ms.
1416
1352
         Converting to s from ms by dividing by 1,000,
1417
1353
         and ns to ms by dividing by 1,000,000. */
1419
1355
                     - ((intmax_t)waited_time.tv_sec * 1000))
1420
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1421
1357
      
1422
 
      if(debug){
 
1358
      if (debug){
1423
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1424
1360
                     block_time);
1425
1361
      }
1426
1362
      
1427
1363
      if(block_time <= 0){
1428
 
        ret = start_mandos_communication(mc->current_server->ip,
1429
 
                                         mc->current_server->port,
1430
 
                                         mc->current_server->if_index,
1431
 
                                         mc->current_server->af, mc);
 
1364
        ret = start_mandos_communication(mc.current_server->ip,
 
1365
                                         mc.current_server->port,
 
1366
                                         mc.current_server->if_index,
 
1367
                                         mc.current_server->af);
1432
1368
        if(ret == 0){
1433
 
          avahi_simple_poll_quit(s);
 
1369
          avahi_simple_poll_quit(mc.simple_poll);
1434
1370
          return 0;
1435
1371
        }
1436
1372
        ret = clock_gettime(CLOCK_MONOTONIC,
1437
 
                            &mc->current_server->last_seen);
 
1373
                            &mc.current_server->last_seen);
1438
1374
        if(ret == -1){
1439
1375
          perror_plus("clock_gettime");
1440
1376
          return -1;
1441
1377
        }
1442
 
        mc->current_server = mc->current_server->next;
 
1378
        mc.current_server = mc.current_server->next;
1443
1379
        block_time = 0;         /* Call avahi to find new Mandos
1444
1380
                                   servers, but don't block */
1445
1381
      }
1447
1383
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1448
1384
    }
1449
1385
    if(ret != 0){
1450
 
      if(ret > 0 or errno != EINTR){
 
1386
      if (ret > 0 or errno != EINTR){
1451
1387
        return (ret != 1) ? ret : 0;
1452
1388
      }
1453
1389
    }
1455
1391
}
1456
1392
 
1457
1393
/* Set effective uid to 0, return errno */
1458
 
__attribute__((warn_unused_result))
1459
1394
error_t raise_privileges(void){
1460
1395
  error_t old_errno = errno;
1461
1396
  error_t ret_errno = 0;
1468
1403
}
1469
1404
 
1470
1405
/* Set effective and real user ID to 0.  Return errno. */
1471
 
__attribute__((warn_unused_result))
1472
1406
error_t raise_privileges_permanently(void){
1473
1407
  error_t old_errno = errno;
1474
1408
  error_t ret_errno = raise_privileges();
1485
1419
}
1486
1420
 
1487
1421
/* Set effective user ID to unprivileged saved user ID */
1488
 
__attribute__((warn_unused_result))
1489
1422
error_t lower_privileges(void){
1490
1423
  error_t old_errno = errno;
1491
1424
  error_t ret_errno = 0;
1498
1431
}
1499
1432
 
1500
1433
/* Lower privileges permanently */
1501
 
__attribute__((warn_unused_result))
1502
1434
error_t lower_privileges_permanently(void){
1503
1435
  error_t old_errno = errno;
1504
1436
  error_t ret_errno = 0;
1510
1442
  return ret_errno;
1511
1443
}
1512
1444
 
1513
 
__attribute__((nonnull))
1514
 
void run_network_hooks(const char *mode, const char *interface,
 
1445
bool run_network_hooks(const char *mode, const char *interface,
1515
1446
                       const float delay){
1516
1447
  struct dirent **direntries;
 
1448
  struct dirent *direntry;
 
1449
  int ret;
1517
1450
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1518
1451
                         alphasort);
1519
1452
  if(numhooks == -1){
1526
1459
      perror_plus("scandir");
1527
1460
    }
1528
1461
  } else {
1529
 
    struct dirent *direntry;
1530
 
    int ret;
1531
1462
    int devnull = open("/dev/null", O_RDONLY);
1532
1463
    for(int i = 0; i < numhooks; i++){
1533
1464
      direntry = direntries[i];
1545
1476
      if(hook_pid == 0){
1546
1477
        /* Child */
1547
1478
        /* Raise privileges */
1548
 
        if(raise_privileges_permanently() != 0){
1549
 
          perror_plus("Failed to raise privileges");
1550
 
          _exit(EX_NOPERM);
1551
 
        }
 
1479
        raise_privileges_permanently();
1552
1480
        /* Set group */
1553
1481
        errno = 0;
1554
1482
        ret = setgid(0);
1555
1483
        if(ret == -1){
1556
1484
          perror_plus("setgid");
1557
 
          _exit(EX_NOPERM);
1558
1485
        }
1559
1486
        /* Reset supplementary groups */
1560
1487
        errno = 0;
1561
1488
        ret = setgroups(0, NULL);
1562
1489
        if(ret == -1){
1563
1490
          perror_plus("setgroups");
1564
 
          _exit(EX_NOPERM);
1565
 
        }
1566
 
        ret = dup2(devnull, STDIN_FILENO);
1567
 
        if(ret == -1){
1568
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1569
 
          _exit(EX_OSERR);
1570
 
        }
1571
 
        ret = close(devnull);
1572
 
        if(ret == -1){
1573
 
          perror_plus("close");
1574
 
          _exit(EX_OSERR);
1575
 
        }
1576
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1577
 
        if(ret == -1){
1578
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1579
 
          _exit(EX_OSERR);
1580
 
        }
 
1491
        }
 
1492
        dup2(devnull, STDIN_FILENO);
 
1493
        close(devnull);
 
1494
        dup2(STDERR_FILENO, STDOUT_FILENO);
1581
1495
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1582
1496
        if(ret == -1){
1583
1497
          perror_plus("setenv");
1599
1513
          _exit(EX_OSERR);
1600
1514
        }
1601
1515
        char *delaystring;
1602
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1516
        ret = asprintf(&delaystring, "%f", delay);
1603
1517
        if(ret == -1){
1604
1518
          perror_plus("asprintf");
1605
1519
          _exit(EX_OSERR);
1658
1572
    }
1659
1573
    close(devnull);
1660
1574
  }
 
1575
  return true;
1661
1576
}
1662
1577
 
1663
 
__attribute__((nonnull, warn_unused_result))
1664
1578
error_t bring_up_interface(const char *const interface,
1665
1579
                           const float delay){
 
1580
  int sd = -1;
1666
1581
  error_t old_errno = errno;
1667
 
  int ret;
 
1582
  error_t ret_errno = 0;
 
1583
  int ret, ret_setflags;
1668
1584
  struct ifreq network;
1669
1585
  unsigned int if_index = if_nametoindex(interface);
1670
1586
  if(if_index == 0){
1679
1595
  }
1680
1596
  
1681
1597
  if(not interface_is_up(interface)){
1682
 
    error_t ret_errno = 0, ioctl_errno = 0;
1683
 
    if(not get_flags(interface, &network)){
 
1598
    if(not get_flags(interface, &network) and debug){
1684
1599
      ret_errno = errno;
1685
1600
      fprintf_plus(stderr, "Failed to get flags for interface "
1686
1601
                   "\"%s\"\n", interface);
1687
 
      errno = old_errno;
1688
1602
      return ret_errno;
1689
1603
    }
1690
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1604
    network.ifr_flags |= IFF_UP;
1691
1605
    
1692
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1693
 
    if(sd == -1){
 
1606
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1607
    if(sd < 0){
1694
1608
      ret_errno = errno;
1695
1609
      perror_plus("socket");
1696
1610
      errno = old_errno;
1697
1611
      return ret_errno;
1698
1612
    }
1699
 
    
 
1613
  
1700
1614
    if(quit_now){
1701
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1702
 
      if(ret == -1){
1703
 
        perror_plus("close");
1704
 
      }
 
1615
      close(sd);
1705
1616
      errno = old_errno;
1706
1617
      return EINTR;
1707
1618
    }
1711
1622
                   interface);
1712
1623
    }
1713
1624
    
1714
 
    /* Raise privileges */
1715
 
    ret_errno = raise_privileges();
1716
 
    bool restore_loglevel = false;
1717
 
    if(ret_errno != 0){
1718
 
      perror_plus("Failed to raise privileges");
1719
 
    }
 
1625
    /* Raise priviliges */
 
1626
    raise_privileges();
 
1627
    
1720
1628
#ifdef __linux__
1721
 
    int ret_linux;
1722
 
    if(ret_errno == 0){
1723
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1724
 
         messages about the network interface to mess up the prompt */
1725
 
      ret_linux = klogctl(8, NULL, 5);
1726
 
      if(ret_linux == -1){
1727
 
        perror_plus("klogctl");
1728
 
      } else {
1729
 
        restore_loglevel = true;
1730
 
      }
 
1629
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1630
       messages about the network interface to mess up the prompt */
 
1631
    int ret_linux = klogctl(8, NULL, 5);
 
1632
    bool restore_loglevel = true;
 
1633
    if(ret_linux == -1){
 
1634
      restore_loglevel = false;
 
1635
      perror_plus("klogctl");
1731
1636
    }
1732
1637
#endif  /* __linux__ */
1733
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1734
 
    ioctl_errno = errno;
 
1638
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1639
    ret_errno = errno;
1735
1640
#ifdef __linux__
1736
1641
    if(restore_loglevel){
1737
1642
      ret_linux = klogctl(7, NULL, 0);
1741
1646
    }
1742
1647
#endif  /* __linux__ */
1743
1648
    
1744
 
    /* If raise_privileges() succeeded above */
1745
 
    if(ret_errno == 0){
1746
 
      /* Lower privileges */
1747
 
      ret_errno = lower_privileges();
1748
 
      if(ret_errno != 0){
1749
 
        errno = ret_errno;
1750
 
        perror_plus("Failed to lower privileges");
1751
 
      }
1752
 
    }
 
1649
    /* Lower privileges */
 
1650
    lower_privileges();
1753
1651
    
1754
1652
    /* Close the socket */
1755
1653
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1758
1656
    }
1759
1657
    
1760
1658
    if(ret_setflags == -1){
1761
 
      errno = ioctl_errno;
 
1659
      errno = ret_errno;
1762
1660
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1763
1661
      errno = old_errno;
1764
 
      return ioctl_errno;
 
1662
      return ret_errno;
1765
1663
    }
1766
1664
  } else if(debug){
1767
1665
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1785
1683
  return 0;
1786
1684
}
1787
1685
 
1788
 
__attribute__((nonnull, warn_unused_result))
1789
1686
error_t take_down_interface(const char *const interface){
 
1687
  int sd = -1;
1790
1688
  error_t old_errno = errno;
 
1689
  error_t ret_errno = 0;
 
1690
  int ret, ret_setflags;
1791
1691
  struct ifreq network;
1792
1692
  unsigned int if_index = if_nametoindex(interface);
1793
1693
  if(if_index == 0){
1796
1696
    return ENXIO;
1797
1697
  }
1798
1698
  if(interface_is_up(interface)){
1799
 
    error_t ret_errno = 0, ioctl_errno = 0;
1800
1699
    if(not get_flags(interface, &network) and debug){
1801
1700
      ret_errno = errno;
1802
1701
      fprintf_plus(stderr, "Failed to get flags for interface "
1803
1702
                   "\"%s\"\n", interface);
1804
 
      errno = old_errno;
1805
1703
      return ret_errno;
1806
1704
    }
1807
1705
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1808
1706
    
1809
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1810
 
    if(sd == -1){
 
1707
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1708
    if(sd < 0){
1811
1709
      ret_errno = errno;
1812
1710
      perror_plus("socket");
1813
1711
      errno = old_errno;
1819
1717
                   interface);
1820
1718
    }
1821
1719
    
1822
 
    /* Raise privileges */
1823
 
    ret_errno = raise_privileges();
1824
 
    if(ret_errno != 0){
1825
 
      perror_plus("Failed to raise privileges");
1826
 
    }
1827
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1828
 
    ioctl_errno = errno;
1829
 
    
1830
 
    /* If raise_privileges() succeeded above */
1831
 
    if(ret_errno == 0){
1832
 
      /* Lower privileges */
1833
 
      ret_errno = lower_privileges();
1834
 
      if(ret_errno != 0){
1835
 
        errno = ret_errno;
1836
 
        perror_plus("Failed to lower privileges");
1837
 
      }
1838
 
    }
 
1720
    /* Raise priviliges */
 
1721
    raise_privileges();
 
1722
    
 
1723
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1724
    ret_errno = errno;
 
1725
    
 
1726
    /* Lower privileges */
 
1727
    lower_privileges();
1839
1728
    
1840
1729
    /* Close the socket */
1841
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1730
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1842
1731
    if(ret == -1){
1843
1732
      perror_plus("close");
1844
1733
    }
1845
1734
    
1846
1735
    if(ret_setflags == -1){
1847
 
      errno = ioctl_errno;
 
1736
      errno = ret_errno;
1848
1737
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1849
1738
      errno = old_errno;
1850
 
      return ioctl_errno;
 
1739
      return ret_errno;
1851
1740
    }
1852
1741
  } else if(debug){
1853
1742
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1859
1748
}
1860
1749
 
1861
1750
int main(int argc, char *argv[]){
1862
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1863
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1864
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1865
 
                        .interfaces = NULL, .interfaces_size = 0 };
1866
1751
  AvahiSServiceBrowser *sb = NULL;
1867
1752
  error_t ret_errno;
1868
1753
  int ret;
1869
1754
  intmax_t tmpmax;
1870
1755
  char *tmp;
1871
1756
  int exitcode = EXIT_SUCCESS;
 
1757
  char *interfaces = NULL;
 
1758
  size_t interfaces_size = 0;
1872
1759
  char *interfaces_to_take_down = NULL;
1873
1760
  size_t interfaces_to_take_down_size = 0;
1874
1761
  char tempdir[] = "/tmp/mandosXXXXXX";
1877
1764
  const char *seckey = PATHDIR "/" SECKEY;
1878
1765
  const char *pubkey = PATHDIR "/" PUBKEY;
1879
1766
  char *interfaces_hooks = NULL;
 
1767
  size_t interfaces_hooks_size = 0;
1880
1768
  
1881
1769
  bool gnutls_initialized = false;
1882
1770
  bool gpgme_initialized = false;
1973
1861
        connect_to = arg;
1974
1862
        break;
1975
1863
      case 'i':                 /* --interface */
1976
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1977
 
                                 arg, (int)',');
 
1864
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
 
1865
                                 (int)',');
1978
1866
        if(ret_errno != 0){
1979
1867
          argp_error(state, "%s", strerror(ret_errno));
1980
1868
        }
2060
1948
    /* Work around Debian bug #633582:
2061
1949
       <http://bugs.debian.org/633582> */
2062
1950
    
2063
 
    /* Re-raise privileges */
2064
 
    ret_errno = raise_privileges();
2065
 
    if(ret_errno != 0){
2066
 
      errno = ret_errno;
2067
 
      perror_plus("Failed to raise privileges");
2068
 
    } else {
 
1951
    /* Re-raise priviliges */
 
1952
    if(raise_privileges() == 0){
2069
1953
      struct stat st;
2070
1954
      
2071
1955
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2111
1995
      }
2112
1996
    
2113
1997
      /* Lower privileges */
2114
 
      ret_errno = lower_privileges();
2115
 
      if(ret_errno != 0){
2116
 
        errno = ret_errno;
2117
 
        perror_plus("Failed to lower privileges");
 
1998
      errno = 0;
 
1999
      ret = seteuid(uid);
 
2000
      if(ret == -1){
 
2001
        perror_plus("seteuid");
2118
2002
      }
2119
2003
    }
2120
2004
  }
2121
2005
  
2122
 
  /* Remove invalid interface names (except "none") */
 
2006
  /* Remove empty interface names */
2123
2007
  {
2124
2008
    char *interface = NULL;
2125
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2009
    while((interface = argz_next(interfaces, interfaces_size,
2126
2010
                                 interface))){
2127
 
      if(strcmp(interface, "none") != 0
2128
 
         and if_nametoindex(interface) == 0){
2129
 
        if(interface[0] != '\0'){
 
2011
      if(if_nametoindex(interface) == 0){
 
2012
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2130
2013
          fprintf_plus(stderr, "Not using nonexisting interface"
2131
2014
                       " \"%s\"\n", interface);
2132
2015
        }
2133
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2016
        argz_delete(&interfaces, &interfaces_size, interface);
2134
2017
        interface = NULL;
2135
2018
      }
2136
2019
    }
2138
2021
  
2139
2022
  /* Run network hooks */
2140
2023
  {
2141
 
    if(mc.interfaces != NULL){
2142
 
      interfaces_hooks = malloc(mc.interfaces_size);
 
2024
    
 
2025
    if(interfaces != NULL){
 
2026
      interfaces_hooks = malloc(interfaces_size);
2143
2027
      if(interfaces_hooks == NULL){
2144
2028
        perror_plus("malloc");
2145
2029
        goto end;
2146
2030
      }
2147
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2148
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2149
 
    }
2150
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2151
 
                      interfaces_hooks : "", delay);
 
2031
      memcpy(interfaces_hooks, interfaces, interfaces_size);
 
2032
      interfaces_hooks_size = interfaces_size;
 
2033
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2034
                     (int)',');
 
2035
    }
 
2036
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2037
                             interfaces_hooks : "", delay)){
 
2038
      goto end;
 
2039
    }
2152
2040
  }
2153
2041
  
2154
2042
  if(not debug){
2159
2047
     from the signal handler */
2160
2048
  /* Initialize the pseudo-RNG for Avahi */
2161
2049
  srand((unsigned int) time(NULL));
2162
 
  simple_poll = avahi_simple_poll_new();
2163
 
  if(simple_poll == NULL){
 
2050
  mc.simple_poll = avahi_simple_poll_new();
 
2051
  if(mc.simple_poll == NULL){
2164
2052
    fprintf_plus(stderr,
2165
2053
                 "Avahi: Failed to create simple poll object.\n");
2166
2054
    exitcode = EX_UNAVAILABLE;
2231
2119
  }
2232
2120
  
2233
2121
  /* If no interfaces were specified, make a list */
2234
 
  if(mc.interfaces == NULL){
 
2122
  if(interfaces == NULL){
2235
2123
    struct dirent **direntries;
2236
2124
    /* Look for any good interfaces */
2237
2125
    ret = scandir(sys_class_net, &direntries, good_interface,
2239
2127
    if(ret >= 1){
2240
2128
      /* Add all found interfaces to interfaces list */
2241
2129
      for(int i = 0; i < ret; ++i){
2242
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2130
        ret_errno = argz_add(&interfaces, &interfaces_size,
2243
2131
                             direntries[i]->d_name);
2244
2132
        if(ret_errno != 0){
2245
 
          errno = ret_errno;
2246
2133
          perror_plus("argz_add");
2247
2134
          continue;
2248
2135
        }
2260
2147
    }
2261
2148
  }
2262
2149
  
2263
 
  /* Bring up interfaces which are down, and remove any "none"s */
2264
 
  {
 
2150
  /* If we only got one interface, explicitly use only that one */
 
2151
  if(argz_count(interfaces, interfaces_size) == 1){
 
2152
    if(debug){
 
2153
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2154
                   interfaces);
 
2155
    }
 
2156
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
 
2157
  }
 
2158
  
 
2159
  /* Bring up interfaces which are down */
 
2160
  if(not (argz_count(interfaces, interfaces_size) == 1
 
2161
          and strcmp(interfaces, "none") == 0)){
2265
2162
    char *interface = NULL;
2266
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2163
    while((interface = argz_next(interfaces, interfaces_size,
2267
2164
                                 interface))){
2268
 
      /* If interface name is "none", stop bringing up interfaces.
2269
 
         Also remove all instances of "none" from the list */
2270
 
      if(strcmp(interface, "none") == 0){
2271
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2272
 
                    interface);
2273
 
        interface = NULL;
2274
 
        while((interface = argz_next(mc.interfaces,
2275
 
                                     mc.interfaces_size, interface))){
2276
 
          if(strcmp(interface, "none") == 0){
2277
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2278
 
                        interface);
2279
 
            interface = NULL;
2280
 
          }
2281
 
        }
2282
 
        break;
2283
 
      }
2284
2165
      bool interface_was_up = interface_is_up(interface);
2285
 
      errno = bring_up_interface(interface, delay);
 
2166
      ret = bring_up_interface(interface, delay);
2286
2167
      if(not interface_was_up){
2287
 
        if(errno != 0){
 
2168
        if(ret != 0){
 
2169
          errno = ret;
2288
2170
          perror_plus("Failed to bring up interface");
2289
2171
        } else {
2290
 
          errno = argz_add(&interfaces_to_take_down,
2291
 
                           &interfaces_to_take_down_size,
2292
 
                           interface);
2293
 
          if(errno != 0){
2294
 
            perror_plus("argz_add");
2295
 
          }
 
2172
          ret_errno = argz_add(&interfaces_to_take_down,
 
2173
                               &interfaces_to_take_down_size,
 
2174
                               interface);
2296
2175
        }
2297
2176
      }
2298
2177
    }
 
2178
    free(interfaces);
 
2179
    interfaces = NULL;
 
2180
    interfaces_size = 0;
2299
2181
    if(debug and (interfaces_to_take_down == NULL)){
2300
2182
      fprintf_plus(stderr, "No interfaces were brought up\n");
2301
2183
    }
2302
2184
  }
2303
2185
  
2304
 
  /* If we only got one interface, explicitly use only that one */
2305
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2306
 
    if(debug){
2307
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2308
 
                   mc.interfaces);
2309
 
    }
2310
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2311
 
  }
2312
 
  
2313
2186
  if(quit_now){
2314
2187
    goto end;
2315
2188
  }
2316
2189
  
2317
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2190
  ret = init_gnutls_global(pubkey, seckey);
2318
2191
  if(ret == -1){
2319
2192
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2320
2193
    exitcode = EX_UNAVAILABLE;
2337
2210
    goto end;
2338
2211
  }
2339
2212
  
2340
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2213
  if(not init_gpgme(pubkey, seckey, tempdir)){
2341
2214
    fprintf_plus(stderr, "init_gpgme failed\n");
2342
2215
    exitcode = EX_UNAVAILABLE;
2343
2216
    goto end;
2373
2246
      exitcode = EX_USAGE;
2374
2247
      goto end;
2375
2248
    }
2376
 
    
 
2249
  
2377
2250
    if(quit_now){
2378
2251
      goto end;
2379
2252
    }
2400
2273
    }
2401
2274
    
2402
2275
    while(not quit_now){
2403
 
      ret = start_mandos_communication(address, port, if_index, af,
2404
 
                                       &mc);
 
2276
      ret = start_mandos_communication(address, port, if_index, af);
2405
2277
      if(quit_now or ret == 0){
2406
2278
        break;
2407
2279
      }
2409
2281
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2410
2282
                     (int)retry_interval);
2411
2283
      }
2412
 
      sleep((unsigned int)retry_interval);
 
2284
      sleep((int)retry_interval);
2413
2285
    }
2414
2286
    
2415
 
    if(not quit_now){
 
2287
    if (not quit_now){
2416
2288
      exitcode = EXIT_SUCCESS;
2417
2289
    }
2418
2290
    
2433
2305
    config.publish_domain = 0;
2434
2306
    
2435
2307
    /* Allocate a new server */
2436
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2437
 
                                 &config, NULL, NULL, &ret_errno);
 
2308
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2309
                                 (mc.simple_poll), &config, NULL,
 
2310
                                 NULL, &ret_errno);
2438
2311
    
2439
2312
    /* Free the Avahi configuration data */
2440
2313
    avahi_server_config_free(&config);
2455
2328
  /* Create the Avahi service browser */
2456
2329
  sb = avahi_s_service_browser_new(mc.server, if_index,
2457
2330
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2458
 
                                   NULL, 0, browse_callback,
2459
 
                                   (void *)&mc);
 
2331
                                   NULL, 0, browse_callback, NULL);
2460
2332
  if(sb == NULL){
2461
2333
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2462
2334
                 avahi_strerror(avahi_server_errno(mc.server)));
2474
2346
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2475
2347
  }
2476
2348
 
2477
 
  ret = avahi_loop_with_timeout(simple_poll,
2478
 
                                (int)(retry_interval * 1000), &mc);
 
2349
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2350
                                (int)(retry_interval * 1000));
2479
2351
  if(debug){
2480
2352
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2481
2353
                 (ret == 0) ? "successfully" : "with error");
2488
2360
  }
2489
2361
  
2490
2362
  /* Cleanup things */
2491
 
  free(mc.interfaces);
2492
 
  
2493
2363
  if(sb != NULL)
2494
2364
    avahi_s_service_browser_free(sb);
2495
2365
  
2496
2366
  if(mc.server != NULL)
2497
2367
    avahi_server_free(mc.server);
2498
2368
  
2499
 
  if(simple_poll != NULL)
2500
 
    avahi_simple_poll_free(simple_poll);
 
2369
  if(mc.simple_poll != NULL)
 
2370
    avahi_simple_poll_free(mc.simple_poll);
2501
2371
  
2502
2372
  if(gnutls_initialized){
2503
2373
    gnutls_certificate_free_credentials(mc.cred);
2520
2390
    }
2521
2391
  }
2522
2392
  
2523
 
  /* Re-raise privileges */
 
2393
  /* Re-raise priviliges */
2524
2394
  {
2525
 
    ret_errno = raise_privileges();
2526
 
    if(ret_errno != 0){
2527
 
      perror_plus("Failed to raise privileges");
2528
 
    } else {
2529
 
      
2530
 
      /* Run network hooks */
2531
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2532
 
                        interfaces_hooks : "", delay);
2533
 
      
2534
 
      /* Take down the network interfaces which were brought up */
2535
 
      {
2536
 
        char *interface = NULL;
2537
 
        while((interface=argz_next(interfaces_to_take_down,
2538
 
                                   interfaces_to_take_down_size,
2539
 
                                   interface))){
2540
 
          ret_errno = take_down_interface(interface);
2541
 
          if(ret_errno != 0){
2542
 
            errno = ret_errno;
2543
 
            perror_plus("Failed to take down interface");
2544
 
          }
2545
 
        }
2546
 
        if(debug and (interfaces_to_take_down == NULL)){
2547
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2548
 
                       " down\n");
2549
 
        }
2550
 
      }
2551
 
    }
2552
 
    ret_errno = lower_privileges_permanently();
2553
 
    if(ret_errno != 0){
2554
 
      perror_plus("Failed to lower privileges permanently");
2555
 
    }
 
2395
    raise_privileges();
 
2396
    
 
2397
    /* Run network hooks */
 
2398
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2399
                      interfaces_hooks : "", delay);
 
2400
    
 
2401
    /* Take down the network interfaces which were brought up */
 
2402
    {
 
2403
      char *interface = NULL;
 
2404
      while((interface=argz_next(interfaces_to_take_down,
 
2405
                                 interfaces_to_take_down_size,
 
2406
                                 interface))){
 
2407
        ret_errno = take_down_interface(interface);
 
2408
        if(ret_errno != 0){
 
2409
          errno = ret_errno;
 
2410
          perror_plus("Failed to take down interface");
 
2411
        }
 
2412
      }
 
2413
      if(debug and (interfaces_to_take_down == NULL)){
 
2414
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2415
                     " down\n");
 
2416
      }
 
2417
    }
 
2418
    
 
2419
    lower_privileges_permanently();
2556
2420
  }
2557
2421
  
2558
2422
  free(interfaces_to_take_down);
2564
2428
    struct dirent *direntry = NULL;
2565
2429
    int numentries = scandir(tempdir, &direntries, notdotentries,
2566
2430
                             alphasort);
2567
 
    if(numentries > 0){
 
2431
    if (numentries > 0){
2568
2432
      for(int i = 0; i < numentries; i++){
2569
2433
        direntry = direntries[i];
2570
2434
        char *fullname = NULL;
2585
2449
 
2586
2450
    /* need to clean even if 0 because man page doesn't specify */
2587
2451
    free(direntries);
2588
 
    if(numentries == -1){
 
2452
    if (numentries == -1){
2589
2453
      perror_plus("scandir");
2590
2454
    }
2591
2455
    ret = rmdir(tempdir);