/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-13 22:06:57 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120613220657-qvq7c7nrndl3t413
* plugins.d/mandos-client.c (get_flags): Don't clobber errno.
  (up_interface): Removed; replaced with "interface_is_up".
  (interface_is_up, interface_is_running,
   lower_privileges_permanently, take_down_interface): New.
  (bring_up_interface): Return "error_t".  Use new functions
                        "interface_is_up", "get_flags", and
                        "interface_is_running".
  (main): Save all interfaces either autodetected or specified with
          --interface in argz vector "interfaces".  Save interfaces to
          take down on exit in argz vector "interfaces_to_take_down".
          Save interface names for DEVICE variable to network hooks as
          argz_vector "interfaces_hooks".  Bug fix: Be privileged
          while stopping network hooks.
* plugins.d/mandos-client.xml (SYNOPSIS): Changed --interface synopsis.
  (DESCRIPTION): Updated to document use of all interfaces.
  (OPTIONS): Updated description of "--interface".
* network-hooks.d/bridge: Parse comma-separated DEVICE environment
                          variable.
* network-hooks.d/openvpn: - '' -
* network-hooks.d/wireless: - '' -

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
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
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   strtoimax() */
 
64
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
76
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_state, struct argp,
92
92
                                   argz_delete(), argz_append(),
93
93
                                   argz_stringify(), argz_add(),
94
94
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
95
 
98
96
#ifdef __linux__
99
97
#include <sys/klog.h>           /* klogctl() */
147
145
/* Doubly linked list that need to be circularly linked when used */
148
146
typedef struct server{
149
147
  const char *ip;
150
 
  in_port_t port;
 
148
  uint16_t port;
151
149
  AvahiIfIndex if_index;
152
150
  int af;
153
151
  struct timespec last_seen;
157
155
 
158
156
/* Used for passing in values through the Avahi callback functions */
159
157
typedef struct {
 
158
  AvahiSimplePoll *simple_poll;
160
159
  AvahiServer *server;
161
160
  gnutls_certificate_credentials_t cred;
162
161
  unsigned int dh_bits;
164
163
  const char *priority;
165
164
  gpgme_ctx_t ctx;
166
165
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
166
} mandos_context;
170
167
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
168
/* global context so signal handler can reach it*/
 
169
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
170
                      .dh_bits = 1024, .priority = "SECURE256"
 
171
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
172
                      .current_server = NULL };
173
173
 
174
174
sig_atomic_t quit_now = 0;
175
175
int signal_received = 0;
183
183
  perror(print_text);
184
184
}
185
185
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
186
__attribute__((format (gnu_printf, 2, 3)))
187
187
int fprintf_plus(FILE *stream, const char *format, ...){
188
188
  va_list ap;
189
189
  va_start (ap, format);
190
190
  
191
191
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
192
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
193
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
194
}
195
195
 
196
196
/*
198
198
 * bytes. "buffer_capacity" is how much is currently allocated,
199
199
 * "buffer_length" is how much is already used.
200
200
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
201
size_t incbuffer(char **buffer, size_t buffer_length,
203
202
                 size_t buffer_capacity){
204
203
  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;
 
204
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
205
    if(buffer == NULL){
211
206
      return 0;
212
207
    }
213
 
    *buffer = new_buf;
214
208
    buffer_capacity += BUFFER_SIZE;
215
209
  }
216
210
  return buffer_capacity;
217
211
}
218
212
 
219
213
/* Add server to set of servers to retry periodically */
220
 
__attribute__((nonnull, warn_unused_result))
221
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
222
 
                int af, server **current_server){
 
214
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
215
                int af){
223
216
  int ret;
224
217
  server *new_server = malloc(sizeof(server));
225
218
  if(new_server == NULL){
234
227
    perror_plus("strdup");
235
228
    return false;
236
229
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
230
  /* Special case of first server */
243
 
  if(*current_server == NULL){
 
231
  if (mc.current_server == NULL){
244
232
    new_server->next = new_server;
245
233
    new_server->prev = new_server;
246
 
    *current_server = new_server;
 
234
    mc.current_server = new_server;
 
235
  /* Place the new server last in the list */
247
236
  } else {
248
 
    /* Place the new server last in the list */
249
 
    new_server->next = *current_server;
250
 
    new_server->prev = (*current_server)->prev;
 
237
    new_server->next = mc.current_server;
 
238
    new_server->prev = mc.current_server->prev;
251
239
    new_server->prev->next = new_server;
252
 
    (*current_server)->prev = new_server;
 
240
    mc.current_server->prev = new_server;
 
241
  }
 
242
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
243
  if(ret == -1){
 
244
    perror_plus("clock_gettime");
 
245
    return false;
253
246
  }
254
247
  return true;
255
248
}
257
250
/* 
258
251
 * Initialize GPGME.
259
252
 */
260
 
__attribute__((nonnull, warn_unused_result))
261
 
static bool init_gpgme(const char * const seckey,
262
 
                       const char * const pubkey,
263
 
                       const char * const tempdir,
264
 
                       mandos_context *mc){
 
253
static bool init_gpgme(const char *seckey, const char *pubkey,
 
254
                       const char *tempdir){
265
255
  gpgme_error_t rc;
266
256
  gpgme_engine_info_t engine_info;
267
257
  
 
258
  
268
259
  /*
269
260
   * Helper function to insert pub and seckey to the engine keyring.
270
261
   */
271
 
  bool import_key(const char * const filename){
 
262
  bool import_key(const char *filename){
272
263
    int ret;
273
264
    int fd;
274
265
    gpgme_data_t pgp_data;
286
277
      return false;
287
278
    }
288
279
    
289
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
280
    rc = gpgme_op_import(mc.ctx, pgp_data);
290
281
    if(rc != GPG_ERR_NO_ERROR){
291
282
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
292
283
                   gpgme_strsource(rc), gpgme_strerror(rc));
336
327
  }
337
328
  
338
329
  /* Create new GPGME "context" */
339
 
  rc = gpgme_new(&(mc->ctx));
 
330
  rc = gpgme_new(&(mc.ctx));
340
331
  if(rc != GPG_ERR_NO_ERROR){
341
332
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
342
333
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
355
346
 * Decrypt OpenPGP data.
356
347
 * Returns -1 on error
357
348
 */
358
 
__attribute__((nonnull, warn_unused_result))
359
349
static ssize_t pgp_packet_decrypt(const char *cryptotext,
360
350
                                  size_t crypto_size,
361
 
                                  char **plaintext,
362
 
                                  mandos_context *mc){
 
351
                                  char **plaintext){
363
352
  gpgme_data_t dh_crypto, dh_plain;
364
353
  gpgme_error_t rc;
365
354
  ssize_t ret;
391
380
  
392
381
  /* Decrypt data from the cryptotext data buffer to the plaintext
393
382
     data buffer */
394
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
383
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
395
384
  if(rc != GPG_ERR_NO_ERROR){
396
385
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
397
386
                 gpgme_strsource(rc), gpgme_strerror(rc));
398
387
    plaintext_length = -1;
399
388
    if(debug){
400
389
      gpgme_decrypt_result_t result;
401
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
390
      result = gpgme_op_decrypt_result(mc.ctx);
402
391
      if(result == NULL){
403
392
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
404
393
      } else {
481
470
  return plaintext_length;
482
471
}
483
472
 
484
 
__attribute__((warn_unused_result))
485
 
static const char *safer_gnutls_strerror(int value){
486
 
  const char *ret = gnutls_strerror(value);
 
473
static const char * safer_gnutls_strerror(int value){
 
474
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
475
                                               -Wunreachable-code */
487
476
  if(ret == NULL)
488
477
    ret = "(unknown)";
489
478
  return ret;
490
479
}
491
480
 
492
481
/* GnuTLS log function callback */
493
 
__attribute__((nonnull))
494
482
static void debuggnutls(__attribute__((unused)) int level,
495
483
                        const char* string){
496
484
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
485
}
498
486
 
499
 
__attribute__((nonnull, warn_unused_result))
500
487
static int init_gnutls_global(const char *pubkeyfilename,
501
 
                              const char *seckeyfilename,
502
 
                              mandos_context *mc){
 
488
                              const char *seckeyfilename){
503
489
  int ret;
504
490
  
505
491
  if(debug){
522
508
  }
523
509
  
524
510
  /* OpenPGP credentials */
525
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
511
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
526
512
  if(ret != GNUTLS_E_SUCCESS){
527
513
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
528
514
                 safer_gnutls_strerror(ret));
538
524
  }
539
525
  
540
526
  ret = gnutls_certificate_set_openpgp_key_file
541
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
527
    (mc.cred, pubkeyfilename, seckeyfilename,
542
528
     GNUTLS_OPENPGP_FMT_BASE64);
543
529
  if(ret != GNUTLS_E_SUCCESS){
544
530
    fprintf_plus(stderr,
550
536
  }
551
537
  
552
538
  /* GnuTLS server initialization */
553
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
539
  ret = gnutls_dh_params_init(&mc.dh_params);
554
540
  if(ret != GNUTLS_E_SUCCESS){
555
541
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
556
542
                 " initialization: %s\n",
557
543
                 safer_gnutls_strerror(ret));
558
544
    goto globalfail;
559
545
  }
560
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
546
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
561
547
  if(ret != GNUTLS_E_SUCCESS){
562
548
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
563
549
                 safer_gnutls_strerror(ret));
564
550
    goto globalfail;
565
551
  }
566
552
  
567
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
553
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
568
554
  
569
555
  return 0;
570
556
  
571
557
 globalfail:
572
558
  
573
 
  gnutls_certificate_free_credentials(mc->cred);
 
559
  gnutls_certificate_free_credentials(mc.cred);
574
560
  gnutls_global_deinit();
575
 
  gnutls_dh_params_deinit(mc->dh_params);
 
561
  gnutls_dh_params_deinit(mc.dh_params);
576
562
  return -1;
577
563
}
578
564
 
579
 
__attribute__((nonnull, warn_unused_result))
580
 
static int init_gnutls_session(gnutls_session_t *session,
581
 
                               mandos_context *mc){
 
565
static int init_gnutls_session(gnutls_session_t *session){
582
566
  int ret;
583
567
  /* GnuTLS session creation */
584
568
  do {
596
580
  {
597
581
    const char *err;
598
582
    do {
599
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
583
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
600
584
      if(quit_now){
601
585
        gnutls_deinit(*session);
602
586
        return -1;
613
597
  
614
598
  do {
615
599
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
616
 
                                 mc->cred);
 
600
                                 mc.cred);
617
601
    if(quit_now){
618
602
      gnutls_deinit(*session);
619
603
      return -1;
629
613
  /* ignore client certificate if any. */
630
614
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
631
615
  
632
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
616
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
633
617
  
634
618
  return 0;
635
619
}
639
623
                      __attribute__((unused)) const char *txt){}
640
624
 
641
625
/* Called when a Mandos server is found */
642
 
__attribute__((nonnull, warn_unused_result))
643
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
626
static int start_mandos_communication(const char *ip, uint16_t port,
644
627
                                      AvahiIfIndex if_index,
645
 
                                      int af, mandos_context *mc){
 
628
                                      int af){
646
629
  int ret, tcp_sd = -1;
647
630
  ssize_t sret;
648
 
  struct sockaddr_storage to;
 
631
  union {
 
632
    struct sockaddr_in in;
 
633
    struct sockaddr_in6 in6;
 
634
  } to;
649
635
  char *buffer = NULL;
650
636
  char *decrypted_buffer = NULL;
651
637
  size_t buffer_length = 0;
675
661
    return -1;
676
662
  }
677
663
  
678
 
  /* If the interface is specified and we have a list of interfaces */
679
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
680
 
    /* Check if the interface is one of the interfaces we are using */
681
 
    bool match = false;
682
 
    {
683
 
      char *interface = NULL;
684
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
685
 
                                 interface))){
686
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
687
 
          match = true;
688
 
          break;
689
 
        }
690
 
      }
691
 
    }
692
 
    if(not match){
693
 
      /* This interface does not match any in the list, so we don't
694
 
         connect to the server */
695
 
      if(debug){
696
 
        char interface[IF_NAMESIZE];
697
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
698
 
          perror_plus("if_indextoname");
699
 
        } else {
700
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
701
 
                       " \"%s\"\n",
702
 
                       if_indextoname((unsigned int)if_index,
703
 
                                      interface));
704
 
        }
705
 
      }
706
 
      return -1;
707
 
    }
708
 
  }
709
 
  
710
 
  ret = init_gnutls_session(&session, mc);
 
664
  ret = init_gnutls_session(&session);
711
665
  if(ret != 0){
712
666
    return -1;
713
667
  }
714
668
  
715
669
  if(debug){
716
670
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
717
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
671
                 PRIu16 "\n", ip, port);
718
672
  }
719
673
  
720
674
  tcp_sd = socket(pf, SOCK_STREAM, 0);
732
686
  
733
687
  memset(&to, 0, sizeof(to));
734
688
  if(af == AF_INET6){
735
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
736
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
689
    to.in6.sin6_family = (sa_family_t)af;
 
690
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
737
691
  } else {                      /* IPv4 */
738
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
739
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
692
    to.in.sin_family = (sa_family_t)af;
 
693
    ret = inet_pton(af, ip, &to.in.sin_addr);
740
694
  }
741
695
  if(ret < 0 ){
742
696
    int e = errno;
751
705
    goto mandos_end;
752
706
  }
753
707
  if(af == AF_INET6){
754
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
755
 
    if(IN6_IS_ADDR_LINKLOCAL
756
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
708
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
709
                                       -Wconversion and
 
710
                                       -Wunreachable-code */
 
711
    
 
712
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
713
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
714
                                -Wunreachable-code*/
757
715
      if(if_index == AVAHI_IF_UNSPEC){
758
716
        fprintf_plus(stderr, "An IPv6 link-local address is"
759
717
                     " incomplete without a network interface\n");
761
719
        goto mandos_end;
762
720
      }
763
721
      /* Set the network interface number as scope */
764
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
722
      to.in6.sin6_scope_id = (uint32_t)if_index;
765
723
    }
766
724
  } else {
767
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
725
    to.in.sin_port = htons(port); /* Spurious warnings from
 
726
                                     -Wconversion and
 
727
                                     -Wunreachable-code */
768
728
  }
769
729
  
770
730
  if(quit_now){
778
738
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
779
739
        perror_plus("if_indextoname");
780
740
      } else {
781
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
782
 
                     "\n", ip, interface, (uintmax_t)port);
 
741
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
742
                     "\n", ip, interface, port);
783
743
      }
784
744
    } else {
785
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
786
 
                   ip, (uintmax_t)port);
 
745
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
746
                   ip, port);
787
747
    }
788
748
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
789
749
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
750
    const char *pcret;
790
751
    if(af == AF_INET6){
791
 
      ret = getnameinfo((struct sockaddr *)&to,
792
 
                        sizeof(struct sockaddr_in6),
793
 
                        addrstr, sizeof(addrstr), NULL, 0,
794
 
                        NI_NUMERICHOST);
 
752
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
753
                        sizeof(addrstr));
795
754
    } else {
796
 
      ret = getnameinfo((struct sockaddr *)&to,
797
 
                        sizeof(struct sockaddr_in),
798
 
                        addrstr, sizeof(addrstr), NULL, 0,
799
 
                        NI_NUMERICHOST);
 
755
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
756
                        sizeof(addrstr));
800
757
    }
801
 
    if(ret == EAI_SYSTEM){
802
 
      perror_plus("getnameinfo");
803
 
    } else if(ret != 0) {
804
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
805
 
    } else if(strcmp(addrstr, ip) != 0){
806
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
758
    if(pcret == NULL){
 
759
      perror_plus("inet_ntop");
 
760
    } else {
 
761
      if(strcmp(addrstr, ip) != 0){
 
762
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
763
      }
807
764
    }
808
765
  }
809
766
  
813
770
  }
814
771
  
815
772
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
 
773
    ret = connect(tcp_sd, &to.in6, sizeof(to));
818
774
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
 
775
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
821
776
  }
822
777
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
778
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
779
      int e = errno;
825
780
      perror_plus("connect");
826
781
      errno = e;
987
942
  if(buffer_length > 0){
988
943
    ssize_t decrypted_buffer_size;
989
944
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
990
 
                                               &decrypted_buffer, mc);
 
945
                                               &decrypted_buffer);
991
946
    if(decrypted_buffer_size >= 0){
992
947
      
993
948
      written = 0;
1041
996
  return retval;
1042
997
}
1043
998
 
1044
 
__attribute__((nonnull))
1045
999
static void resolve_callback(AvahiSServiceResolver *r,
1046
1000
                             AvahiIfIndex interface,
1047
1001
                             AvahiProtocol proto,
1055
1009
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1056
1010
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1057
1011
                             flags,
1058
 
                             void *mc){
1059
 
  if(r == NULL){
1060
 
    return;
1061
 
  }
 
1012
                             AVAHI_GCC_UNUSED void* userdata){
 
1013
  assert(r);
1062
1014
  
1063
1015
  /* Called whenever a service has been resolved successfully or
1064
1016
     timed out */
1073
1025
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1074
1026
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1075
1027
                 domain,
1076
 
                 avahi_strerror(avahi_server_errno
1077
 
                                (((mandos_context*)mc)->server)));
 
1028
                 avahi_strerror(avahi_server_errno(mc.server)));
1078
1029
    break;
1079
1030
    
1080
1031
  case AVAHI_RESOLVER_FOUND:
1086
1037
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1087
1038
                     host_name, ip, (intmax_t)interface, port);
1088
1039
      }
1089
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1090
 
                                           interface,
1091
 
                                           avahi_proto_to_af(proto),
1092
 
                                           mc);
 
1040
      int ret = start_mandos_communication(ip, port, interface,
 
1041
                                           avahi_proto_to_af(proto));
1093
1042
      if(ret == 0){
1094
 
        avahi_simple_poll_quit(simple_poll);
 
1043
        avahi_simple_poll_quit(mc.simple_poll);
1095
1044
      } else {
1096
 
        if(not add_server(ip, (in_port_t)port, interface,
1097
 
                          avahi_proto_to_af(proto),
1098
 
                          &((mandos_context*)mc)->current_server)){
 
1045
        if(not add_server(ip, port, interface,
 
1046
                          avahi_proto_to_af(proto))){
1099
1047
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1100
1048
                       " list\n", name);
1101
1049
        }
1114
1062
                            const char *domain,
1115
1063
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1116
1064
                            flags,
1117
 
                            void *mc){
1118
 
  if(b == NULL){
1119
 
    return;
1120
 
  }
 
1065
                            AVAHI_GCC_UNUSED void* userdata){
 
1066
  assert(b);
1121
1067
  
1122
1068
  /* Called whenever a new services becomes available on the LAN or
1123
1069
     is removed from the LAN */
1131
1077
  case AVAHI_BROWSER_FAILURE:
1132
1078
    
1133
1079
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1134
 
                 avahi_strerror(avahi_server_errno
1135
 
                                (((mandos_context*)mc)->server)));
1136
 
    avahi_simple_poll_quit(simple_poll);
 
1080
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1081
    avahi_simple_poll_quit(mc.simple_poll);
1137
1082
    return;
1138
1083
    
1139
1084
  case AVAHI_BROWSER_NEW:
1142
1087
       the callback function is called the Avahi server will free the
1143
1088
       resolver for us. */
1144
1089
    
1145
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1146
 
                                    interface, protocol, name, type,
1147
 
                                    domain, protocol, 0,
1148
 
                                    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)
1149
1093
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1150
1094
                   " %s\n", name,
1151
 
                   avahi_strerror(avahi_server_errno
1152
 
                                  (((mandos_context*)mc)->server)));
 
1095
                   avahi_strerror(avahi_server_errno(mc.server)));
1153
1096
    break;
1154
1097
    
1155
1098
  case AVAHI_BROWSER_REMOVE:
1174
1117
  signal_received = sig;
1175
1118
  int old_errno = errno;
1176
1119
  /* set main loop to exit */
1177
 
  if(simple_poll != NULL){
1178
 
    avahi_simple_poll_quit(simple_poll);
 
1120
  if(mc.simple_poll != NULL){
 
1121
    avahi_simple_poll_quit(mc.simple_poll);
1179
1122
  }
1180
1123
  errno = old_errno;
1181
1124
}
1182
1125
 
1183
 
__attribute__((nonnull, warn_unused_result))
1184
1126
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1127
  int ret;
1186
1128
  error_t ret_errno;
1205
1147
  return true;
1206
1148
}
1207
1149
 
1208
 
__attribute__((nonnull, warn_unused_result))
1209
1150
bool good_flags(const char *ifname, const struct ifreq *ifr){
1210
1151
  
1211
1152
  /* Reject the loopback device */
1253
1194
 * corresponds to an acceptable network device.
1254
1195
 * (This function is passed to scandir(3) as a filter function.)
1255
1196
 */
1256
 
__attribute__((nonnull, warn_unused_result))
1257
1197
int good_interface(const struct dirent *if_entry){
1258
1198
  if(if_entry->d_name[0] == '.'){
1259
1199
    return 0;
1277
1217
/* 
1278
1218
 * This function determines if a network interface is up.
1279
1219
 */
1280
 
__attribute__((nonnull, warn_unused_result))
1281
1220
bool interface_is_up(const char *interface){
1282
1221
  struct ifreq ifr;
1283
1222
  if(not get_flags(interface, &ifr)){
1294
1233
/* 
1295
1234
 * This function determines if a network interface is running
1296
1235
 */
1297
 
__attribute__((nonnull, warn_unused_result))
1298
1236
bool interface_is_running(const char *interface){
1299
1237
  struct ifreq ifr;
1300
1238
  if(not get_flags(interface, &ifr)){
1308
1246
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1309
1247
}
1310
1248
 
1311
 
__attribute__((nonnull, pure, warn_unused_result))
1312
1249
int notdotentries(const struct dirent *direntry){
1313
1250
  /* Skip "." and ".." */
1314
1251
  if(direntry->d_name[0] == '.'
1321
1258
}
1322
1259
 
1323
1260
/* Is this directory entry a runnable program? */
1324
 
__attribute__((nonnull, warn_unused_result))
1325
1261
int runnable_hook(const struct dirent *direntry){
1326
1262
  int ret;
1327
1263
  size_t sret;
1382
1318
  return 1;
1383
1319
}
1384
1320
 
1385
 
__attribute__((nonnull, warn_unused_result))
1386
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1387
 
                            mandos_context *mc){
 
1321
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1388
1322
  int ret;
1389
1323
  struct timespec now;
1390
1324
  struct timespec waited_time;
1391
1325
  intmax_t block_time;
1392
1326
  
1393
1327
  while(true){
1394
 
    if(mc->current_server == NULL){
1395
 
      if(debug){
 
1328
    if(mc.current_server == NULL){
 
1329
      if (debug){
1396
1330
        fprintf_plus(stderr, "Wait until first server is found."
1397
1331
                     " No timeout!\n");
1398
1332
      }
1399
1333
      ret = avahi_simple_poll_iterate(s, -1);
1400
1334
    } else {
1401
 
      if(debug){
 
1335
      if (debug){
1402
1336
        fprintf_plus(stderr, "Check current_server if we should run"
1403
1337
                     " it, or wait\n");
1404
1338
      }
1411
1345
      /* Calculating in ms how long time between now and server
1412
1346
         who we visted longest time ago. Now - last seen.  */
1413
1347
      waited_time.tv_sec = (now.tv_sec
1414
 
                            - mc->current_server->last_seen.tv_sec);
 
1348
                            - mc.current_server->last_seen.tv_sec);
1415
1349
      waited_time.tv_nsec = (now.tv_nsec
1416
 
                             - mc->current_server->last_seen.tv_nsec);
 
1350
                             - mc.current_server->last_seen.tv_nsec);
1417
1351
      /* total time is 10s/10,000ms.
1418
1352
         Converting to s from ms by dividing by 1,000,
1419
1353
         and ns to ms by dividing by 1,000,000. */
1421
1355
                     - ((intmax_t)waited_time.tv_sec * 1000))
1422
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1423
1357
      
1424
 
      if(debug){
 
1358
      if (debug){
1425
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1426
1360
                     block_time);
1427
1361
      }
1428
1362
      
1429
1363
      if(block_time <= 0){
1430
 
        ret = start_mandos_communication(mc->current_server->ip,
1431
 
                                         mc->current_server->port,
1432
 
                                         mc->current_server->if_index,
1433
 
                                         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);
1434
1368
        if(ret == 0){
1435
 
          avahi_simple_poll_quit(s);
 
1369
          avahi_simple_poll_quit(mc.simple_poll);
1436
1370
          return 0;
1437
1371
        }
1438
1372
        ret = clock_gettime(CLOCK_MONOTONIC,
1439
 
                            &mc->current_server->last_seen);
 
1373
                            &mc.current_server->last_seen);
1440
1374
        if(ret == -1){
1441
1375
          perror_plus("clock_gettime");
1442
1376
          return -1;
1443
1377
        }
1444
 
        mc->current_server = mc->current_server->next;
 
1378
        mc.current_server = mc.current_server->next;
1445
1379
        block_time = 0;         /* Call avahi to find new Mandos
1446
1380
                                   servers, but don't block */
1447
1381
      }
1449
1383
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1450
1384
    }
1451
1385
    if(ret != 0){
1452
 
      if(ret > 0 or errno != EINTR){
 
1386
      if (ret > 0 or errno != EINTR){
1453
1387
        return (ret != 1) ? ret : 0;
1454
1388
      }
1455
1389
    }
1457
1391
}
1458
1392
 
1459
1393
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
1394
error_t raise_privileges(void){
1462
1395
  error_t old_errno = errno;
1463
1396
  error_t ret_errno = 0;
1470
1403
}
1471
1404
 
1472
1405
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
1406
error_t raise_privileges_permanently(void){
1475
1407
  error_t old_errno = errno;
1476
1408
  error_t ret_errno = raise_privileges();
1487
1419
}
1488
1420
 
1489
1421
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
1422
error_t lower_privileges(void){
1492
1423
  error_t old_errno = errno;
1493
1424
  error_t ret_errno = 0;
1500
1431
}
1501
1432
 
1502
1433
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
1434
error_t lower_privileges_permanently(void){
1505
1435
  error_t old_errno = errno;
1506
1436
  error_t ret_errno = 0;
1512
1442
  return ret_errno;
1513
1443
}
1514
1444
 
1515
 
__attribute__((nonnull))
1516
 
void run_network_hooks(const char *mode, const char *interface,
 
1445
bool run_network_hooks(const char *mode, const char *interface,
1517
1446
                       const float delay){
1518
1447
  struct dirent **direntries;
 
1448
  struct dirent *direntry;
 
1449
  int ret;
1519
1450
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
1451
                         alphasort);
1521
1452
  if(numhooks == -1){
1522
 
    if(errno == ENOENT){
1523
 
      if(debug){
1524
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1525
 
                     " found\n", hookdir);
1526
 
      }
1527
 
    } else {
1528
 
      perror_plus("scandir");
1529
 
    }
 
1453
    perror_plus("scandir");
1530
1454
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
1455
    int devnull = open("/dev/null", O_RDONLY);
1534
1456
    for(int i = 0; i < numhooks; i++){
1535
1457
      direntry = direntries[i];
1547
1469
      if(hook_pid == 0){
1548
1470
        /* Child */
1549
1471
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
1553
 
        }
 
1472
        raise_privileges_permanently();
1554
1473
        /* Set group */
1555
1474
        errno = 0;
1556
1475
        ret = setgid(0);
1557
1476
        if(ret == -1){
1558
1477
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
1478
        }
1561
1479
        /* Reset supplementary groups */
1562
1480
        errno = 0;
1563
1481
        ret = setgroups(0, NULL);
1564
1482
        if(ret == -1){
1565
1483
          perror_plus("setgroups");
1566
 
          _exit(EX_NOPERM);
1567
 
        }
1568
 
        ret = dup2(devnull, STDIN_FILENO);
1569
 
        if(ret == -1){
1570
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1571
 
          _exit(EX_OSERR);
1572
 
        }
1573
 
        ret = close(devnull);
1574
 
        if(ret == -1){
1575
 
          perror_plus("close");
1576
 
          _exit(EX_OSERR);
1577
 
        }
1578
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1579
 
        if(ret == -1){
1580
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1581
 
          _exit(EX_OSERR);
1582
 
        }
 
1484
        }
 
1485
        dup2(devnull, STDIN_FILENO);
 
1486
        close(devnull);
 
1487
        dup2(STDERR_FILENO, STDOUT_FILENO);
1583
1488
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
1489
        if(ret == -1){
1585
1490
          perror_plus("setenv");
1601
1506
          _exit(EX_OSERR);
1602
1507
        }
1603
1508
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1509
        ret = asprintf(&delaystring, "%f", delay);
1605
1510
        if(ret == -1){
1606
1511
          perror_plus("asprintf");
1607
1512
          _exit(EX_OSERR);
1660
1565
    }
1661
1566
    close(devnull);
1662
1567
  }
 
1568
  return true;
1663
1569
}
1664
1570
 
1665
 
__attribute__((nonnull, warn_unused_result))
1666
1571
error_t bring_up_interface(const char *const interface,
1667
1572
                           const float delay){
 
1573
  int sd = -1;
1668
1574
  error_t old_errno = errno;
1669
 
  int ret;
 
1575
  error_t ret_errno = 0;
 
1576
  int ret, ret_setflags;
1670
1577
  struct ifreq network;
1671
1578
  unsigned int if_index = if_nametoindex(interface);
1672
1579
  if(if_index == 0){
1681
1588
  }
1682
1589
  
1683
1590
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
1685
 
    if(not get_flags(interface, &network)){
 
1591
    if(not get_flags(interface, &network) and debug){
1686
1592
      ret_errno = errno;
1687
1593
      fprintf_plus(stderr, "Failed to get flags for interface "
1688
1594
                   "\"%s\"\n", interface);
1689
 
      errno = old_errno;
1690
1595
      return ret_errno;
1691
1596
    }
1692
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1597
    network.ifr_flags |= IFF_UP;
1693
1598
    
1694
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1695
 
    if(sd == -1){
 
1599
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1600
    if(sd < 0){
1696
1601
      ret_errno = errno;
1697
1602
      perror_plus("socket");
1698
1603
      errno = old_errno;
1699
1604
      return ret_errno;
1700
1605
    }
1701
 
    
 
1606
  
1702
1607
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1704
 
      if(ret == -1){
1705
 
        perror_plus("close");
1706
 
      }
 
1608
      close(sd);
1707
1609
      errno = old_errno;
1708
1610
      return EINTR;
1709
1611
    }
1713
1615
                   interface);
1714
1616
    }
1715
1617
    
1716
 
    /* Raise privileges */
1717
 
    ret_errno = raise_privileges();
1718
 
    if(ret_errno != 0){
1719
 
      perror_plus("Failed to raise privileges");
1720
 
    }
 
1618
    /* Raise priviliges */
 
1619
    raise_privileges();
1721
1620
    
1722
1621
#ifdef __linux__
1723
 
    int ret_linux;
1724
 
    bool restore_loglevel = false;
1725
 
    if(ret_errno == 0){
1726
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1727
 
         messages about the network interface to mess up the prompt */
1728
 
      ret_linux = klogctl(8, NULL, 5);
1729
 
      if(ret_linux == -1){
1730
 
        perror_plus("klogctl");
1731
 
      } else {
1732
 
        restore_loglevel = true;
1733
 
      }
 
1622
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1623
       messages about the network interface to mess up the prompt */
 
1624
    int ret_linux = klogctl(8, NULL, 5);
 
1625
    bool restore_loglevel = true;
 
1626
    if(ret_linux == -1){
 
1627
      restore_loglevel = false;
 
1628
      perror_plus("klogctl");
1734
1629
    }
1735
1630
#endif  /* __linux__ */
1736
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1737
 
    ioctl_errno = errno;
 
1631
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1632
    ret_errno = errno;
1738
1633
#ifdef __linux__
1739
1634
    if(restore_loglevel){
1740
1635
      ret_linux = klogctl(7, NULL, 0);
1744
1639
    }
1745
1640
#endif  /* __linux__ */
1746
1641
    
1747
 
    /* If raise_privileges() succeeded above */
1748
 
    if(ret_errno == 0){
1749
 
      /* Lower privileges */
1750
 
      ret_errno = lower_privileges();
1751
 
      if(ret_errno != 0){
1752
 
        errno = ret_errno;
1753
 
        perror_plus("Failed to lower privileges");
1754
 
      }
1755
 
    }
 
1642
    /* Lower privileges */
 
1643
    lower_privileges();
1756
1644
    
1757
1645
    /* Close the socket */
1758
1646
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1761
1649
    }
1762
1650
    
1763
1651
    if(ret_setflags == -1){
1764
 
      errno = ioctl_errno;
 
1652
      errno = ret_errno;
1765
1653
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1766
1654
      errno = old_errno;
1767
 
      return ioctl_errno;
 
1655
      return ret_errno;
1768
1656
    }
1769
1657
  } else if(debug){
1770
1658
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1788
1676
  return 0;
1789
1677
}
1790
1678
 
1791
 
__attribute__((nonnull, warn_unused_result))
1792
1679
error_t take_down_interface(const char *const interface){
 
1680
  int sd = -1;
1793
1681
  error_t old_errno = errno;
 
1682
  error_t ret_errno = 0;
 
1683
  int ret, ret_setflags;
1794
1684
  struct ifreq network;
1795
1685
  unsigned int if_index = if_nametoindex(interface);
1796
1686
  if(if_index == 0){
1799
1689
    return ENXIO;
1800
1690
  }
1801
1691
  if(interface_is_up(interface)){
1802
 
    error_t ret_errno = 0, ioctl_errno = 0;
1803
1692
    if(not get_flags(interface, &network) and debug){
1804
1693
      ret_errno = errno;
1805
1694
      fprintf_plus(stderr, "Failed to get flags for interface "
1806
1695
                   "\"%s\"\n", interface);
1807
 
      errno = old_errno;
1808
1696
      return ret_errno;
1809
1697
    }
1810
1698
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1811
1699
    
1812
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1813
 
    if(sd == -1){
 
1700
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1701
    if(sd < 0){
1814
1702
      ret_errno = errno;
1815
1703
      perror_plus("socket");
1816
1704
      errno = old_errno;
1822
1710
                   interface);
1823
1711
    }
1824
1712
    
1825
 
    /* Raise privileges */
1826
 
    ret_errno = raise_privileges();
1827
 
    if(ret_errno != 0){
1828
 
      perror_plus("Failed to raise privileges");
1829
 
    }
1830
 
    
1831
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1832
 
    ioctl_errno = errno;
1833
 
    
1834
 
    /* If raise_privileges() succeeded above */
1835
 
    if(ret_errno == 0){
1836
 
      /* Lower privileges */
1837
 
      ret_errno = lower_privileges();
1838
 
      if(ret_errno != 0){
1839
 
        errno = ret_errno;
1840
 
        perror_plus("Failed to lower privileges");
1841
 
      }
1842
 
    }
 
1713
    /* Raise priviliges */
 
1714
    raise_privileges();
 
1715
    
 
1716
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1717
    ret_errno = errno;
 
1718
    
 
1719
    /* Lower privileges */
 
1720
    lower_privileges();
1843
1721
    
1844
1722
    /* Close the socket */
1845
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1723
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1846
1724
    if(ret == -1){
1847
1725
      perror_plus("close");
1848
1726
    }
1849
1727
    
1850
1728
    if(ret_setflags == -1){
1851
 
      errno = ioctl_errno;
 
1729
      errno = ret_errno;
1852
1730
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1853
1731
      errno = old_errno;
1854
 
      return ioctl_errno;
 
1732
      return ret_errno;
1855
1733
    }
1856
1734
  } else if(debug){
1857
1735
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1863
1741
}
1864
1742
 
1865
1743
int main(int argc, char *argv[]){
1866
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1867
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1868
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1869
 
                        .interfaces = NULL, .interfaces_size = 0 };
1870
1744
  AvahiSServiceBrowser *sb = NULL;
1871
1745
  error_t ret_errno;
1872
1746
  int ret;
1873
1747
  intmax_t tmpmax;
1874
1748
  char *tmp;
1875
1749
  int exitcode = EXIT_SUCCESS;
 
1750
  char *interfaces = NULL;
 
1751
  size_t interfaces_size = 0;
1876
1752
  char *interfaces_to_take_down = NULL;
1877
1753
  size_t interfaces_to_take_down_size = 0;
1878
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1879
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1880
 
  char *tempdir = NULL;
 
1754
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1755
  bool tempdir_created = false;
1881
1756
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1882
1757
  const char *seckey = PATHDIR "/" SECKEY;
1883
1758
  const char *pubkey = PATHDIR "/" PUBKEY;
1884
1759
  char *interfaces_hooks = NULL;
 
1760
  size_t interfaces_hooks_size = 0;
1885
1761
  
1886
1762
  bool gnutls_initialized = false;
1887
1763
  bool gpgme_initialized = false;
1978
1854
        connect_to = arg;
1979
1855
        break;
1980
1856
      case 'i':                 /* --interface */
1981
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1982
 
                                 arg, (int)',');
 
1857
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
 
1858
                                 (int)',');
1983
1859
        if(ret_errno != 0){
1984
1860
          argp_error(state, "%s", strerror(ret_errno));
1985
1861
        }
2065
1941
    /* Work around Debian bug #633582:
2066
1942
       <http://bugs.debian.org/633582> */
2067
1943
    
2068
 
    /* Re-raise privileges */
2069
 
    ret_errno = raise_privileges();
2070
 
    if(ret_errno != 0){
2071
 
      errno = ret_errno;
2072
 
      perror_plus("Failed to raise privileges");
2073
 
    } else {
 
1944
    /* Re-raise priviliges */
 
1945
    if(raise_privileges() == 0){
2074
1946
      struct stat st;
2075
1947
      
2076
1948
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2116
1988
      }
2117
1989
    
2118
1990
      /* Lower privileges */
2119
 
      ret_errno = lower_privileges();
2120
 
      if(ret_errno != 0){
2121
 
        errno = ret_errno;
2122
 
        perror_plus("Failed to lower privileges");
 
1991
      errno = 0;
 
1992
      ret = seteuid(uid);
 
1993
      if(ret == -1){
 
1994
        perror_plus("seteuid");
2123
1995
      }
2124
1996
    }
2125
1997
  }
2126
1998
  
2127
 
  /* Remove invalid interface names (except "none") */
 
1999
  /* Remove empty interface names */
2128
2000
  {
2129
2001
    char *interface = NULL;
2130
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2002
    while((interface = argz_next(interfaces, interfaces_size,
2131
2003
                                 interface))){
2132
 
      if(strcmp(interface, "none") != 0
2133
 
         and if_nametoindex(interface) == 0){
2134
 
        if(interface[0] != '\0'){
 
2004
      if(if_nametoindex(interface) == 0){
 
2005
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2135
2006
          fprintf_plus(stderr, "Not using nonexisting interface"
2136
2007
                       " \"%s\"\n", interface);
2137
2008
        }
2138
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2009
        argz_delete(&interfaces, &interfaces_size, interface);
2139
2010
        interface = NULL;
2140
2011
      }
2141
2012
    }
2143
2014
  
2144
2015
  /* Run network hooks */
2145
2016
  {
2146
 
    if(mc.interfaces != NULL){
2147
 
      interfaces_hooks = malloc(mc.interfaces_size);
2148
 
      if(interfaces_hooks == NULL){
2149
 
        perror_plus("malloc");
2150
 
        goto end;
2151
 
      }
2152
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2153
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2154
 
    }
2155
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2156
 
                      interfaces_hooks : "", delay);
 
2017
    ret_errno = argz_append(&interfaces_hooks, &interfaces_hooks_size,
 
2018
                            interfaces, interfaces_size);
 
2019
    if(ret_errno != 0){
 
2020
      errno = ret_errno;
 
2021
      perror_plus("argz_append");
 
2022
      goto end;
 
2023
    }
 
2024
    argz_stringify(interfaces_hooks, interfaces_hooks_size, (int)',');
 
2025
    if(not run_network_hooks("start", interfaces_hooks, delay)){
 
2026
      goto end;
 
2027
    }
2157
2028
  }
2158
2029
  
2159
2030
  if(not debug){
2164
2035
     from the signal handler */
2165
2036
  /* Initialize the pseudo-RNG for Avahi */
2166
2037
  srand((unsigned int) time(NULL));
2167
 
  simple_poll = avahi_simple_poll_new();
2168
 
  if(simple_poll == NULL){
 
2038
  mc.simple_poll = avahi_simple_poll_new();
 
2039
  if(mc.simple_poll == NULL){
2169
2040
    fprintf_plus(stderr,
2170
2041
                 "Avahi: Failed to create simple poll object.\n");
2171
2042
    exitcode = EX_UNAVAILABLE;
2236
2107
  }
2237
2108
  
2238
2109
  /* If no interfaces were specified, make a list */
2239
 
  if(mc.interfaces == NULL){
 
2110
  if(interfaces == NULL){
2240
2111
    struct dirent **direntries;
2241
2112
    /* Look for any good interfaces */
2242
2113
    ret = scandir(sys_class_net, &direntries, good_interface,
2244
2115
    if(ret >= 1){
2245
2116
      /* Add all found interfaces to interfaces list */
2246
2117
      for(int i = 0; i < ret; ++i){
2247
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2118
        ret_errno = argz_add(&interfaces, &interfaces_size,
2248
2119
                             direntries[i]->d_name);
2249
2120
        if(ret_errno != 0){
2250
 
          errno = ret_errno;
2251
2121
          perror_plus("argz_add");
2252
2122
          continue;
2253
2123
        }
2265
2135
    }
2266
2136
  }
2267
2137
  
2268
 
  /* Bring up interfaces which are down, and remove any "none"s */
2269
 
  {
 
2138
  /* If we only got one interface, explicitly use only that one */
 
2139
  if(argz_count(interfaces, interfaces_size) == 1){
 
2140
    if(debug){
 
2141
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2142
                   interfaces);
 
2143
    }
 
2144
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
 
2145
  }
 
2146
  
 
2147
  /* Bring up interfaces which are down */
 
2148
  if(not (argz_count(interfaces, interfaces_size) == 1
 
2149
          and strcmp(interfaces, "none") == 0)){
2270
2150
    char *interface = NULL;
2271
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2151
    while((interface = argz_next(interfaces, interfaces_size,
2272
2152
                                 interface))){
2273
 
      /* If interface name is "none", stop bringing up interfaces.
2274
 
         Also remove all instances of "none" from the list */
2275
 
      if(strcmp(interface, "none") == 0){
2276
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2277
 
                    interface);
2278
 
        interface = NULL;
2279
 
        while((interface = argz_next(mc.interfaces,
2280
 
                                     mc.interfaces_size, interface))){
2281
 
          if(strcmp(interface, "none") == 0){
2282
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2283
 
                        interface);
2284
 
            interface = NULL;
2285
 
          }
2286
 
        }
2287
 
        break;
2288
 
      }
2289
2153
      bool interface_was_up = interface_is_up(interface);
2290
 
      errno = bring_up_interface(interface, delay);
 
2154
      ret = bring_up_interface(interface, delay);
2291
2155
      if(not interface_was_up){
2292
 
        if(errno != 0){
 
2156
        if(ret != 0){
 
2157
          errno = ret;
2293
2158
          perror_plus("Failed to bring up interface");
2294
2159
        } else {
2295
 
          errno = argz_add(&interfaces_to_take_down,
2296
 
                           &interfaces_to_take_down_size,
2297
 
                           interface);
2298
 
          if(errno != 0){
2299
 
            perror_plus("argz_add");
2300
 
          }
 
2160
          ret_errno = argz_add(&interfaces_to_take_down,
 
2161
                               &interfaces_to_take_down_size,
 
2162
                               interface);
2301
2163
        }
2302
2164
      }
2303
2165
    }
 
2166
    free(interfaces);
 
2167
    interfaces = NULL;
 
2168
    interfaces_size = 0;
2304
2169
    if(debug and (interfaces_to_take_down == NULL)){
2305
2170
      fprintf_plus(stderr, "No interfaces were brought up\n");
2306
2171
    }
2307
2172
  }
2308
2173
  
2309
 
  /* If we only got one interface, explicitly use only that one */
2310
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2311
 
    if(debug){
2312
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2313
 
                   mc.interfaces);
2314
 
    }
2315
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2316
 
  }
2317
 
  
2318
2174
  if(quit_now){
2319
2175
    goto end;
2320
2176
  }
2321
2177
  
2322
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2178
  ret = init_gnutls_global(pubkey, seckey);
2323
2179
  if(ret == -1){
2324
2180
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2325
2181
    exitcode = EX_UNAVAILABLE;
2332
2188
    goto end;
2333
2189
  }
2334
2190
  
2335
 
  /* Try /run/tmp before /tmp */
2336
 
  tempdir = mkdtemp(run_tempdir);
2337
 
  if(tempdir == NULL and errno == ENOENT){
2338
 
      if(debug){
2339
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2340
 
                     run_tempdir, old_tempdir);
2341
 
      }
2342
 
      tempdir = mkdtemp(old_tempdir);
2343
 
  }
2344
 
  if(tempdir == NULL){
 
2191
  if(mkdtemp(tempdir) == NULL){
2345
2192
    perror_plus("mkdtemp");
2346
2193
    goto end;
2347
2194
  }
 
2195
  tempdir_created = true;
2348
2196
  
2349
2197
  if(quit_now){
2350
2198
    goto end;
2351
2199
  }
2352
2200
  
2353
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2201
  if(not init_gpgme(pubkey, seckey, tempdir)){
2354
2202
    fprintf_plus(stderr, "init_gpgme failed\n");
2355
2203
    exitcode = EX_UNAVAILABLE;
2356
2204
    goto end;
2377
2225
      goto end;
2378
2226
    }
2379
2227
    
2380
 
    in_port_t port;
 
2228
    uint16_t port;
2381
2229
    errno = 0;
2382
2230
    tmpmax = strtoimax(address+1, &tmp, 10);
2383
2231
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2384
 
       or tmpmax != (in_port_t)tmpmax){
 
2232
       or tmpmax != (uint16_t)tmpmax){
2385
2233
      fprintf_plus(stderr, "Bad port number\n");
2386
2234
      exitcode = EX_USAGE;
2387
2235
      goto end;
2388
2236
    }
2389
 
    
 
2237
  
2390
2238
    if(quit_now){
2391
2239
      goto end;
2392
2240
    }
2393
2241
    
2394
 
    port = (in_port_t)tmpmax;
 
2242
    port = (uint16_t)tmpmax;
2395
2243
    *address = '\0';
2396
2244
    /* Colon in address indicates IPv6 */
2397
2245
    int af;
2413
2261
    }
2414
2262
    
2415
2263
    while(not quit_now){
2416
 
      ret = start_mandos_communication(address, port, if_index, af,
2417
 
                                       &mc);
 
2264
      ret = start_mandos_communication(address, port, if_index, af);
2418
2265
      if(quit_now or ret == 0){
2419
2266
        break;
2420
2267
      }
2422
2269
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2423
2270
                     (int)retry_interval);
2424
2271
      }
2425
 
      sleep((unsigned int)retry_interval);
 
2272
      sleep((int)retry_interval);
2426
2273
    }
2427
2274
    
2428
 
    if(not quit_now){
 
2275
    if (not quit_now){
2429
2276
      exitcode = EXIT_SUCCESS;
2430
2277
    }
2431
2278
    
2446
2293
    config.publish_domain = 0;
2447
2294
    
2448
2295
    /* Allocate a new server */
2449
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2450
 
                                 &config, NULL, NULL, &ret_errno);
 
2296
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2297
                                 (mc.simple_poll), &config, NULL,
 
2298
                                 NULL, &ret_errno);
2451
2299
    
2452
2300
    /* Free the Avahi configuration data */
2453
2301
    avahi_server_config_free(&config);
2468
2316
  /* Create the Avahi service browser */
2469
2317
  sb = avahi_s_service_browser_new(mc.server, if_index,
2470
2318
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2471
 
                                   NULL, 0, browse_callback,
2472
 
                                   (void *)&mc);
 
2319
                                   NULL, 0, browse_callback, NULL);
2473
2320
  if(sb == NULL){
2474
2321
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2475
2322
                 avahi_strerror(avahi_server_errno(mc.server)));
2487
2334
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2488
2335
  }
2489
2336
 
2490
 
  ret = avahi_loop_with_timeout(simple_poll,
2491
 
                                (int)(retry_interval * 1000), &mc);
 
2337
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2338
                                (int)(retry_interval * 1000));
2492
2339
  if(debug){
2493
2340
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2494
2341
                 (ret == 0) ? "successfully" : "with error");
2501
2348
  }
2502
2349
  
2503
2350
  /* Cleanup things */
2504
 
  free(mc.interfaces);
2505
 
  
2506
2351
  if(sb != NULL)
2507
2352
    avahi_s_service_browser_free(sb);
2508
2353
  
2509
2354
  if(mc.server != NULL)
2510
2355
    avahi_server_free(mc.server);
2511
2356
  
2512
 
  if(simple_poll != NULL)
2513
 
    avahi_simple_poll_free(simple_poll);
 
2357
  if(mc.simple_poll != NULL)
 
2358
    avahi_simple_poll_free(mc.simple_poll);
2514
2359
  
2515
2360
  if(gnutls_initialized){
2516
2361
    gnutls_certificate_free_credentials(mc.cred);
2533
2378
    }
2534
2379
  }
2535
2380
  
2536
 
  /* Re-raise privileges */
 
2381
  /* Re-raise priviliges */
2537
2382
  {
2538
 
    ret_errno = raise_privileges();
2539
 
    if(ret_errno != 0){
2540
 
      perror_plus("Failed to raise privileges");
2541
 
    } else {
2542
 
      
2543
 
      /* Run network hooks */
2544
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2545
 
                        interfaces_hooks : "", delay);
2546
 
      
2547
 
      /* Take down the network interfaces which were brought up */
2548
 
      {
2549
 
        char *interface = NULL;
2550
 
        while((interface=argz_next(interfaces_to_take_down,
2551
 
                                   interfaces_to_take_down_size,
2552
 
                                   interface))){
2553
 
          ret_errno = take_down_interface(interface);
2554
 
          if(ret_errno != 0){
2555
 
            errno = ret_errno;
2556
 
            perror_plus("Failed to take down interface");
2557
 
          }
2558
 
        }
2559
 
        if(debug and (interfaces_to_take_down == NULL)){
2560
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2561
 
                       " down\n");
2562
 
        }
2563
 
      }
2564
 
    }
2565
 
    
2566
 
    ret_errno = lower_privileges_permanently();
2567
 
    if(ret_errno != 0){
2568
 
      perror_plus("Failed to lower privileges permanently");
2569
 
    }
 
2383
    raise_privileges();
 
2384
    
 
2385
    /* Run network hooks */
 
2386
    run_network_hooks("stop", interfaces_hooks, delay);
 
2387
    
 
2388
    /* Take down the network interfaces which were brought up */
 
2389
    {
 
2390
      char *interface = NULL;
 
2391
      while((interface=argz_next(interfaces_to_take_down,
 
2392
                                 interfaces_to_take_down_size,
 
2393
                                 interface))){
 
2394
        ret_errno = take_down_interface(interface);
 
2395
        if(ret_errno != 0){
 
2396
          errno = ret_errno;
 
2397
          perror_plus("Failed to take down interface");
 
2398
        }
 
2399
      }
 
2400
      if(debug and (interfaces_to_take_down == NULL)){
 
2401
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2402
                     " down\n");
 
2403
      }
 
2404
    }
 
2405
    
 
2406
    lower_privileges_permanently();
2570
2407
  }
2571
2408
  
2572
2409
  free(interfaces_to_take_down);
2573
2410
  free(interfaces_hooks);
2574
2411
  
2575
2412
  /* Removes the GPGME temp directory and all files inside */
2576
 
  if(tempdir != NULL){
 
2413
  if(tempdir_created){
2577
2414
    struct dirent **direntries = NULL;
2578
2415
    struct dirent *direntry = NULL;
2579
2416
    int numentries = scandir(tempdir, &direntries, notdotentries,
2580
2417
                             alphasort);
2581
 
    if(numentries > 0){
 
2418
    if (numentries > 0){
2582
2419
      for(int i = 0; i < numentries; i++){
2583
2420
        direntry = direntries[i];
2584
2421
        char *fullname = NULL;
2599
2436
 
2600
2437
    /* need to clean even if 0 because man page doesn't specify */
2601
2438
    free(direntries);
2602
 
    if(numentries == -1){
 
2439
    if (numentries == -1){
2603
2440
      perror_plus("scandir");
2604
2441
    }
2605
2442
    ret = rmdir(tempdir);